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/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/fs_struct.h>
79 #include <linux/splice.h>
80 #include <linux/task_work.h>
81 #include <linux/pagemap.h>
82 #include <linux/io_uring.h>
83 #include <linux/blk-cgroup.h>
84 #include <linux/audit.h>
86 #define CREATE_TRACE_POINTS
87 #include <trace/events/io_uring.h>
89 #include <uapi/linux/io_uring.h>
94 #define IORING_MAX_ENTRIES 32768
95 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
98 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
100 #define IORING_FILE_TABLE_SHIFT 9
101 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
102 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
103 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
104 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
105 IORING_REGISTER_LAST + IORING_OP_LAST)
107 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
108 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
112 u32 head ____cacheline_aligned_in_smp;
113 u32 tail ____cacheline_aligned_in_smp;
117 * This data is shared with the application through the mmap at offsets
118 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
120 * The offsets to the member fields are published through struct
121 * io_sqring_offsets when calling io_uring_setup.
125 * Head and tail offsets into the ring; the offsets need to be
126 * masked to get valid indices.
128 * The kernel controls head of the sq ring and the tail of the cq ring,
129 * and the application controls tail of the sq ring and the head of the
132 struct io_uring sq, cq;
134 * Bitmasks to apply to head and tail offsets (constant, equals
137 u32 sq_ring_mask, cq_ring_mask;
138 /* Ring sizes (constant, power of 2) */
139 u32 sq_ring_entries, cq_ring_entries;
141 * Number of invalid entries dropped by the kernel due to
142 * invalid index stored in array
144 * Written by the kernel, shouldn't be modified by the
145 * application (i.e. get number of "new events" by comparing to
148 * After a new SQ head value was read by the application this
149 * counter includes all submissions that were dropped reaching
150 * the new SQ head (and possibly more).
156 * Written by the kernel, shouldn't be modified by the
159 * The application needs a full memory barrier before checking
160 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
166 * Written by the application, shouldn't be modified by the
171 * Number of completion events lost because the queue was full;
172 * this should be avoided by the application by making sure
173 * there are not more requests pending than there is space in
174 * the completion queue.
176 * Written by the kernel, shouldn't be modified by the
177 * application (i.e. get number of "new events" by comparing to
180 * As completion events come in out of order this counter is not
181 * ordered with any other data.
185 * Ring buffer of completion events.
187 * The kernel writes completion events fresh every time they are
188 * produced, so the application is allowed to modify pending
191 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
194 enum io_uring_cmd_flags {
195 IO_URING_F_NONBLOCK = 1,
196 IO_URING_F_COMPLETE_DEFER = 2,
199 struct io_mapped_ubuf {
202 struct bio_vec *bvec;
203 unsigned int nr_bvecs;
204 unsigned long acct_pages;
210 struct list_head list;
217 struct fixed_rsrc_table {
221 struct fixed_rsrc_ref_node {
222 struct percpu_ref refs;
223 struct list_head node;
224 struct list_head rsrc_list;
225 struct fixed_rsrc_data *rsrc_data;
226 void (*rsrc_put)(struct io_ring_ctx *ctx,
227 struct io_rsrc_put *prsrc);
228 struct llist_node llist;
232 struct fixed_rsrc_data {
233 struct fixed_rsrc_table *table;
234 struct io_ring_ctx *ctx;
236 struct fixed_rsrc_ref_node *node;
237 struct percpu_ref refs;
238 struct completion done;
243 struct list_head list;
249 struct io_restriction {
250 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
251 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
252 u8 sqe_flags_allowed;
253 u8 sqe_flags_required;
261 /* ctx's that are using this sqd */
262 struct list_head ctx_list;
263 struct list_head ctx_new_list;
264 struct mutex ctx_lock;
266 struct task_struct *thread;
267 struct wait_queue_head wait;
269 unsigned sq_thread_idle;
272 #define IO_IOPOLL_BATCH 8
273 #define IO_COMPL_BATCH 32
274 #define IO_REQ_CACHE_SIZE 32
275 #define IO_REQ_ALLOC_BATCH 8
277 struct io_comp_state {
278 struct io_kiocb *reqs[IO_COMPL_BATCH];
280 unsigned int locked_free_nr;
281 /* inline/task_work completion list, under ->uring_lock */
282 struct list_head free_list;
283 /* IRQ completion list, under ->completion_lock */
284 struct list_head locked_free_list;
287 struct io_submit_link {
288 struct io_kiocb *head;
289 struct io_kiocb *last;
292 struct io_submit_state {
293 struct blk_plug plug;
294 struct io_submit_link link;
297 * io_kiocb alloc cache
299 void *reqs[IO_REQ_CACHE_SIZE];
300 unsigned int free_reqs;
305 * Batch completion logic
307 struct io_comp_state comp;
310 * File reference cache
314 unsigned int file_refs;
315 unsigned int ios_left;
320 struct percpu_ref refs;
321 } ____cacheline_aligned_in_smp;
325 unsigned int compat: 1;
326 unsigned int limit_mem: 1;
327 unsigned int cq_overflow_flushed: 1;
328 unsigned int drain_next: 1;
329 unsigned int eventfd_async: 1;
330 unsigned int restricted: 1;
331 unsigned int sqo_dead: 1;
334 * Ring buffer of indices into array of io_uring_sqe, which is
335 * mmapped by the application using the IORING_OFF_SQES offset.
337 * This indirection could e.g. be used to assign fixed
338 * io_uring_sqe entries to operations and only submit them to
339 * the queue when needed.
341 * The kernel modifies neither the indices array nor the entries
345 unsigned cached_sq_head;
348 unsigned sq_thread_idle;
349 unsigned cached_sq_dropped;
350 unsigned cached_cq_overflow;
351 unsigned long sq_check_overflow;
353 struct list_head defer_list;
354 struct list_head timeout_list;
355 struct list_head cq_overflow_list;
357 struct io_uring_sqe *sq_sqes;
358 } ____cacheline_aligned_in_smp;
361 struct mutex uring_lock;
362 wait_queue_head_t wait;
363 } ____cacheline_aligned_in_smp;
365 struct io_submit_state submit_state;
367 struct io_rings *rings;
370 * For SQPOLL usage - we hold a reference to the parent task, so we
371 * have access to the ->files
373 struct task_struct *sqo_task;
375 /* Only used for accounting purposes */
376 struct mm_struct *mm_account;
378 #ifdef CONFIG_BLK_CGROUP
379 struct cgroup_subsys_state *sqo_blkcg_css;
382 struct io_sq_data *sq_data; /* if using sq thread polling */
384 struct wait_queue_head sqo_sq_wait;
385 struct list_head sqd_list;
388 * If used, fixed file set. Writers must ensure that ->refs is dead,
389 * readers must ensure that ->refs is alive as long as the file* is
390 * used. Only updated through io_uring_register(2).
392 struct fixed_rsrc_data *file_data;
393 unsigned nr_user_files;
395 /* if used, fixed mapped user buffers */
396 unsigned nr_user_bufs;
397 struct io_mapped_ubuf *user_bufs;
399 struct user_struct *user;
401 const struct cred *creds;
405 unsigned int sessionid;
408 struct completion ref_comp;
409 struct completion sq_thread_comp;
411 #if defined(CONFIG_UNIX)
412 struct socket *ring_sock;
415 struct idr io_buffer_idr;
417 struct idr personality_idr;
420 unsigned cached_cq_tail;
423 atomic_t cq_timeouts;
424 unsigned cq_last_tm_flush;
425 unsigned long cq_check_overflow;
426 struct wait_queue_head cq_wait;
427 struct fasync_struct *cq_fasync;
428 struct eventfd_ctx *cq_ev_fd;
429 } ____cacheline_aligned_in_smp;
432 spinlock_t completion_lock;
435 * ->iopoll_list is protected by the ctx->uring_lock for
436 * io_uring instances that don't use IORING_SETUP_SQPOLL.
437 * For SQPOLL, only the single threaded io_sq_thread() will
438 * manipulate the list, hence no extra locking is needed there.
440 struct list_head iopoll_list;
441 struct hlist_head *cancel_hash;
442 unsigned cancel_hash_bits;
443 bool poll_multi_file;
445 spinlock_t inflight_lock;
446 struct list_head inflight_list;
447 } ____cacheline_aligned_in_smp;
449 struct delayed_work rsrc_put_work;
450 struct llist_head rsrc_put_llist;
451 struct list_head rsrc_ref_list;
452 spinlock_t rsrc_ref_lock;
454 struct io_restriction restrictions;
457 struct callback_head *exit_task_work;
459 /* Keep this last, we don't need it for the fast path */
460 struct work_struct exit_work;
464 * First field must be the file pointer in all the
465 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
467 struct io_poll_iocb {
469 struct wait_queue_head *head;
473 struct wait_queue_entry wait;
476 struct io_poll_remove {
486 struct io_timeout_data {
487 struct io_kiocb *req;
488 struct hrtimer timer;
489 struct timespec64 ts;
490 enum hrtimer_mode mode;
495 struct sockaddr __user *addr;
496 int __user *addr_len;
498 unsigned long nofile;
518 struct list_head list;
519 /* head of the link, used by linked timeouts only */
520 struct io_kiocb *head;
523 struct io_timeout_rem {
528 struct timespec64 ts;
533 /* NOTE: kiocb has the file as the first member, so don't do it here */
541 struct sockaddr __user *addr;
548 struct user_msghdr __user *umsg;
554 struct io_buffer *kbuf;
560 struct filename *filename;
562 unsigned long nofile;
565 struct io_rsrc_update {
591 struct epoll_event event;
595 struct file *file_out;
596 struct file *file_in;
603 struct io_provide_buf {
617 const char __user *filename;
618 struct statx __user *buffer;
630 struct filename *oldpath;
631 struct filename *newpath;
639 struct filename *filename;
642 struct io_completion {
644 struct list_head list;
648 struct io_async_connect {
649 struct sockaddr_storage address;
652 struct io_async_msghdr {
653 struct iovec fast_iov[UIO_FASTIOV];
654 /* points to an allocated iov, if NULL we use fast_iov instead */
655 struct iovec *free_iov;
656 struct sockaddr __user *uaddr;
658 struct sockaddr_storage addr;
662 struct iovec fast_iov[UIO_FASTIOV];
663 const struct iovec *free_iovec;
664 struct iov_iter iter;
666 struct wait_page_queue wpq;
670 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
671 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
672 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
673 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
674 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
675 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
681 REQ_F_LINK_TIMEOUT_BIT,
683 REQ_F_NEED_CLEANUP_BIT,
685 REQ_F_BUFFER_SELECTED_BIT,
686 REQ_F_NO_FILE_TABLE_BIT,
687 REQ_F_WORK_INITIALIZED_BIT,
688 REQ_F_LTIMEOUT_ACTIVE_BIT,
689 REQ_F_COMPLETE_INLINE_BIT,
691 /* not a real bit, just to check we're not overflowing the space */
697 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
698 /* drain existing IO first */
699 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
701 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
702 /* doesn't sever on completion < 0 */
703 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
705 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
706 /* IOSQE_BUFFER_SELECT */
707 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
709 /* fail rest of links */
710 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
711 /* on inflight list */
712 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
713 /* read/write uses file position */
714 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
715 /* must not punt to workers */
716 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
717 /* has or had linked timeout */
718 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
720 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
722 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
723 /* already went through poll handler */
724 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
725 /* buffer already selected */
726 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
727 /* doesn't need file table for this request */
728 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
729 /* io_wq_work is initialized */
730 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_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 destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
993 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
994 struct io_ring_ctx *ctx);
995 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
997 static bool io_rw_reissue(struct io_kiocb *req);
998 static void io_cqring_fill_event(struct io_kiocb *req, long res);
999 static void io_put_req(struct io_kiocb *req);
1000 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1001 static void io_double_put_req(struct io_kiocb *req);
1002 static void io_dismantle_req(struct io_kiocb *req);
1003 static void io_put_task(struct task_struct *task, int nr);
1004 static void io_queue_next(struct io_kiocb *req);
1005 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1006 static void __io_queue_linked_timeout(struct io_kiocb *req);
1007 static void io_queue_linked_timeout(struct io_kiocb *req);
1008 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1009 struct io_uring_rsrc_update *ip,
1011 static void __io_clean_op(struct io_kiocb *req);
1012 static struct file *io_file_get(struct io_submit_state *state,
1013 struct io_kiocb *req, int fd, bool fixed);
1014 static void __io_queue_sqe(struct io_kiocb *req);
1015 static void io_rsrc_put_work(struct work_struct *work);
1017 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1018 struct iov_iter *iter, bool needs_lock);
1019 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1020 const struct iovec *fast_iov,
1021 struct iov_iter *iter, bool force);
1022 static void io_req_task_queue(struct io_kiocb *req);
1023 static void io_submit_flush_completions(struct io_comp_state *cs,
1024 struct io_ring_ctx *ctx);
1026 static struct kmem_cache *req_cachep;
1028 static const struct file_operations io_uring_fops;
1030 struct sock *io_uring_get_socket(struct file *file)
1032 #if defined(CONFIG_UNIX)
1033 if (file->f_op == &io_uring_fops) {
1034 struct io_ring_ctx *ctx = file->private_data;
1036 return ctx->ring_sock->sk;
1041 EXPORT_SYMBOL(io_uring_get_socket);
1043 #define io_for_each_link(pos, head) \
1044 for (pos = (head); pos; pos = pos->link)
1046 static inline void io_clean_op(struct io_kiocb *req)
1048 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1052 static inline void io_set_resource_node(struct io_kiocb *req)
1054 struct io_ring_ctx *ctx = req->ctx;
1056 if (!req->fixed_rsrc_refs) {
1057 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1058 percpu_ref_get(req->fixed_rsrc_refs);
1062 static bool io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1064 if (!percpu_ref_tryget(ref)) {
1065 /* already at zero, wait for ->release() */
1066 if (!try_wait_for_completion(compl))
1071 percpu_ref_resurrect(ref);
1072 reinit_completion(compl);
1073 percpu_ref_put(ref);
1077 static bool io_match_task(struct io_kiocb *head,
1078 struct task_struct *task,
1079 struct files_struct *files)
1081 struct io_kiocb *req;
1083 if (task && head->task != task) {
1084 /* in terms of cancelation, always match if req task is dead */
1085 if (head->task->flags & PF_EXITING)
1092 io_for_each_link(req, head) {
1093 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1095 if (req->file && req->file->f_op == &io_uring_fops)
1097 if (req->work.identity->files == files)
1103 static void io_sq_thread_drop_mm_files(void)
1105 struct files_struct *files = current->files;
1106 struct mm_struct *mm = current->mm;
1109 kthread_unuse_mm(mm);
1114 struct nsproxy *nsproxy = current->nsproxy;
1117 current->files = NULL;
1118 current->nsproxy = NULL;
1119 task_unlock(current);
1120 put_files_struct(files);
1121 put_nsproxy(nsproxy);
1125 static int __io_sq_thread_acquire_files(struct io_ring_ctx *ctx)
1127 if (!current->files) {
1128 struct files_struct *files;
1129 struct nsproxy *nsproxy;
1131 task_lock(ctx->sqo_task);
1132 files = ctx->sqo_task->files;
1134 task_unlock(ctx->sqo_task);
1137 atomic_inc(&files->count);
1138 get_nsproxy(ctx->sqo_task->nsproxy);
1139 nsproxy = ctx->sqo_task->nsproxy;
1140 task_unlock(ctx->sqo_task);
1143 current->files = files;
1144 current->nsproxy = nsproxy;
1145 task_unlock(current);
1150 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1152 struct mm_struct *mm;
1157 task_lock(ctx->sqo_task);
1158 mm = ctx->sqo_task->mm;
1159 if (unlikely(!mm || !mmget_not_zero(mm)))
1161 task_unlock(ctx->sqo_task);
1171 static int __io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1172 struct io_kiocb *req)
1176 ret = __io_sq_thread_acquire_mm(ctx);
1180 ret = __io_sq_thread_acquire_files(ctx);
1187 static inline int io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1188 struct io_kiocb *req)
1190 if (!(ctx->flags & IORING_SETUP_SQPOLL))
1192 return __io_sq_thread_acquire_mm_files(ctx, req);
1195 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1196 struct cgroup_subsys_state **cur_css)
1199 #ifdef CONFIG_BLK_CGROUP
1200 /* puts the old one when swapping */
1201 if (*cur_css != ctx->sqo_blkcg_css) {
1202 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1203 *cur_css = ctx->sqo_blkcg_css;
1208 static void io_sq_thread_unassociate_blkcg(void)
1210 #ifdef CONFIG_BLK_CGROUP
1211 kthread_associate_blkcg(NULL);
1215 static inline void req_set_fail_links(struct io_kiocb *req)
1217 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1218 req->flags |= REQ_F_FAIL_LINK;
1222 * None of these are dereferenced, they are simply used to check if any of
1223 * them have changed. If we're under current and check they are still the
1224 * same, we're fine to grab references to them for actual out-of-line use.
1226 static void io_init_identity(struct io_identity *id)
1228 id->files = current->files;
1229 id->mm = current->mm;
1230 #ifdef CONFIG_BLK_CGROUP
1232 id->blkcg_css = blkcg_css();
1235 id->creds = current_cred();
1236 id->nsproxy = current->nsproxy;
1237 id->fs = current->fs;
1238 id->fsize = rlimit(RLIMIT_FSIZE);
1240 id->loginuid = current->loginuid;
1241 id->sessionid = current->sessionid;
1243 refcount_set(&id->count, 1);
1246 static inline void __io_req_init_async(struct io_kiocb *req)
1248 memset(&req->work, 0, sizeof(req->work));
1249 req->flags |= REQ_F_WORK_INITIALIZED;
1253 * Note: must call io_req_init_async() for the first time you
1254 * touch any members of io_wq_work.
1256 static inline void io_req_init_async(struct io_kiocb *req)
1258 struct io_uring_task *tctx = current->io_uring;
1260 if (req->flags & REQ_F_WORK_INITIALIZED)
1263 __io_req_init_async(req);
1265 /* Grab a ref if this isn't our static identity */
1266 req->work.identity = tctx->identity;
1267 if (tctx->identity != &tctx->__identity)
1268 refcount_inc(&req->work.identity->count);
1271 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1273 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1275 complete(&ctx->ref_comp);
1278 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1280 return !req->timeout.off;
1283 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1285 struct io_ring_ctx *ctx;
1288 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1293 * Use 5 bits less than the max cq entries, that should give us around
1294 * 32 entries per hash list if totally full and uniformly spread.
1296 hash_bits = ilog2(p->cq_entries);
1300 ctx->cancel_hash_bits = hash_bits;
1301 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1303 if (!ctx->cancel_hash)
1305 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1307 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1308 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1311 ctx->flags = p->flags;
1312 init_waitqueue_head(&ctx->sqo_sq_wait);
1313 INIT_LIST_HEAD(&ctx->sqd_list);
1314 init_waitqueue_head(&ctx->cq_wait);
1315 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1316 init_completion(&ctx->ref_comp);
1317 init_completion(&ctx->sq_thread_comp);
1318 idr_init(&ctx->io_buffer_idr);
1319 idr_init(&ctx->personality_idr);
1320 mutex_init(&ctx->uring_lock);
1321 init_waitqueue_head(&ctx->wait);
1322 spin_lock_init(&ctx->completion_lock);
1323 INIT_LIST_HEAD(&ctx->iopoll_list);
1324 INIT_LIST_HEAD(&ctx->defer_list);
1325 INIT_LIST_HEAD(&ctx->timeout_list);
1326 spin_lock_init(&ctx->inflight_lock);
1327 INIT_LIST_HEAD(&ctx->inflight_list);
1328 spin_lock_init(&ctx->rsrc_ref_lock);
1329 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1330 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1331 init_llist_head(&ctx->rsrc_put_llist);
1332 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1333 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1336 kfree(ctx->cancel_hash);
1341 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1343 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1344 struct io_ring_ctx *ctx = req->ctx;
1346 return seq != ctx->cached_cq_tail
1347 + READ_ONCE(ctx->cached_cq_overflow);
1353 static void io_put_identity(struct io_uring_task *tctx, struct io_kiocb *req)
1355 if (req->work.identity == &tctx->__identity)
1357 if (refcount_dec_and_test(&req->work.identity->count))
1358 kfree(req->work.identity);
1361 static void io_req_clean_work(struct io_kiocb *req)
1363 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1366 if (req->flags & REQ_F_INFLIGHT) {
1367 struct io_ring_ctx *ctx = req->ctx;
1368 struct io_uring_task *tctx = req->task->io_uring;
1369 unsigned long flags;
1371 spin_lock_irqsave(&ctx->inflight_lock, flags);
1372 list_del(&req->inflight_entry);
1373 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1374 req->flags &= ~REQ_F_INFLIGHT;
1375 if (atomic_read(&tctx->in_idle))
1376 wake_up(&tctx->wait);
1379 req->flags &= ~REQ_F_WORK_INITIALIZED;
1380 io_put_identity(req->task->io_uring, req);
1383 static void io_req_track_inflight(struct io_kiocb *req)
1385 struct io_ring_ctx *ctx = req->ctx;
1387 if (!(req->flags & REQ_F_INFLIGHT)) {
1388 io_req_init_async(req);
1389 req->flags |= REQ_F_INFLIGHT;
1391 spin_lock_irq(&ctx->inflight_lock);
1392 list_add(&req->inflight_entry, &ctx->inflight_list);
1393 spin_unlock_irq(&ctx->inflight_lock);
1397 static void io_prep_async_work(struct io_kiocb *req)
1399 const struct io_op_def *def = &io_op_defs[req->opcode];
1400 struct io_ring_ctx *ctx = req->ctx;
1402 io_req_init_async(req);
1404 if (req->flags & REQ_F_FORCE_ASYNC)
1405 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1407 if (req->flags & REQ_F_ISREG) {
1408 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1409 io_wq_hash_work(&req->work, file_inode(req->file));
1411 if (def->unbound_nonreg_file)
1412 req->work.flags |= IO_WQ_WORK_UNBOUND;
1416 static void io_prep_async_link(struct io_kiocb *req)
1418 struct io_kiocb *cur;
1420 io_for_each_link(cur, req)
1421 io_prep_async_work(cur);
1424 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1426 struct io_ring_ctx *ctx = req->ctx;
1427 struct io_kiocb *link = io_prep_linked_timeout(req);
1428 struct io_uring_task *tctx = req->task->io_uring;
1431 BUG_ON(!tctx->io_wq);
1433 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1434 &req->work, req->flags);
1435 io_wq_enqueue(tctx->io_wq, &req->work);
1439 static void io_queue_async_work(struct io_kiocb *req)
1441 struct io_kiocb *link;
1443 /* init ->work of the whole link before punting */
1444 io_prep_async_link(req);
1445 link = __io_queue_async_work(req);
1448 io_queue_linked_timeout(link);
1451 static void io_kill_timeout(struct io_kiocb *req)
1453 struct io_timeout_data *io = req->async_data;
1456 ret = hrtimer_try_to_cancel(&io->timer);
1458 atomic_set(&req->ctx->cq_timeouts,
1459 atomic_read(&req->ctx->cq_timeouts) + 1);
1460 list_del_init(&req->timeout.list);
1461 io_cqring_fill_event(req, 0);
1462 io_put_req_deferred(req, 1);
1467 * Returns true if we found and killed one or more timeouts
1469 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1470 struct files_struct *files)
1472 struct io_kiocb *req, *tmp;
1475 spin_lock_irq(&ctx->completion_lock);
1476 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1477 if (io_match_task(req, tsk, files)) {
1478 io_kill_timeout(req);
1482 spin_unlock_irq(&ctx->completion_lock);
1483 return canceled != 0;
1486 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1489 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1490 struct io_defer_entry, list);
1492 if (req_need_defer(de->req, de->seq))
1494 list_del_init(&de->list);
1495 io_req_task_queue(de->req);
1497 } while (!list_empty(&ctx->defer_list));
1500 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1504 if (list_empty(&ctx->timeout_list))
1507 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1510 u32 events_needed, events_got;
1511 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1512 struct io_kiocb, timeout.list);
1514 if (io_is_timeout_noseq(req))
1518 * Since seq can easily wrap around over time, subtract
1519 * the last seq at which timeouts were flushed before comparing.
1520 * Assuming not more than 2^31-1 events have happened since,
1521 * these subtractions won't have wrapped, so we can check if
1522 * target is in [last_seq, current_seq] by comparing the two.
1524 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1525 events_got = seq - ctx->cq_last_tm_flush;
1526 if (events_got < events_needed)
1529 list_del_init(&req->timeout.list);
1530 io_kill_timeout(req);
1531 } while (!list_empty(&ctx->timeout_list));
1533 ctx->cq_last_tm_flush = seq;
1536 static void io_commit_cqring(struct io_ring_ctx *ctx)
1538 io_flush_timeouts(ctx);
1540 /* order cqe stores with ring update */
1541 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1543 if (unlikely(!list_empty(&ctx->defer_list)))
1544 __io_queue_deferred(ctx);
1547 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1549 struct io_rings *r = ctx->rings;
1551 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1554 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1556 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1559 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1561 struct io_rings *rings = ctx->rings;
1565 * writes to the cq entry need to come after reading head; the
1566 * control dependency is enough as we're using WRITE_ONCE to
1569 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1572 tail = ctx->cached_cq_tail++;
1573 return &rings->cqes[tail & ctx->cq_mask];
1576 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1580 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1582 if (!ctx->eventfd_async)
1584 return io_wq_current_is_worker();
1587 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1589 /* see waitqueue_active() comment */
1592 if (waitqueue_active(&ctx->wait))
1593 wake_up(&ctx->wait);
1594 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1595 wake_up(&ctx->sq_data->wait);
1596 if (io_should_trigger_evfd(ctx))
1597 eventfd_signal(ctx->cq_ev_fd, 1);
1598 if (waitqueue_active(&ctx->cq_wait)) {
1599 wake_up_interruptible(&ctx->cq_wait);
1600 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1604 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1606 /* see waitqueue_active() comment */
1609 if (ctx->flags & IORING_SETUP_SQPOLL) {
1610 if (waitqueue_active(&ctx->wait))
1611 wake_up(&ctx->wait);
1613 if (io_should_trigger_evfd(ctx))
1614 eventfd_signal(ctx->cq_ev_fd, 1);
1615 if (waitqueue_active(&ctx->cq_wait)) {
1616 wake_up_interruptible(&ctx->cq_wait);
1617 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1621 /* Returns true if there are no backlogged entries after the flush */
1622 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1623 struct task_struct *tsk,
1624 struct files_struct *files)
1626 struct io_rings *rings = ctx->rings;
1627 struct io_kiocb *req, *tmp;
1628 struct io_uring_cqe *cqe;
1629 unsigned long flags;
1630 bool all_flushed, posted;
1633 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1637 spin_lock_irqsave(&ctx->completion_lock, flags);
1638 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1639 if (!io_match_task(req, tsk, files))
1642 cqe = io_get_cqring(ctx);
1646 list_move(&req->compl.list, &list);
1648 WRITE_ONCE(cqe->user_data, req->user_data);
1649 WRITE_ONCE(cqe->res, req->result);
1650 WRITE_ONCE(cqe->flags, req->compl.cflags);
1652 ctx->cached_cq_overflow++;
1653 WRITE_ONCE(ctx->rings->cq_overflow,
1654 ctx->cached_cq_overflow);
1659 all_flushed = list_empty(&ctx->cq_overflow_list);
1661 clear_bit(0, &ctx->sq_check_overflow);
1662 clear_bit(0, &ctx->cq_check_overflow);
1663 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1667 io_commit_cqring(ctx);
1668 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1670 io_cqring_ev_posted(ctx);
1672 while (!list_empty(&list)) {
1673 req = list_first_entry(&list, struct io_kiocb, compl.list);
1674 list_del(&req->compl.list);
1681 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1682 struct task_struct *tsk,
1683 struct files_struct *files)
1685 if (test_bit(0, &ctx->cq_check_overflow)) {
1686 /* iopoll syncs against uring_lock, not completion_lock */
1687 if (ctx->flags & IORING_SETUP_IOPOLL)
1688 mutex_lock(&ctx->uring_lock);
1689 __io_cqring_overflow_flush(ctx, force, tsk, files);
1690 if (ctx->flags & IORING_SETUP_IOPOLL)
1691 mutex_unlock(&ctx->uring_lock);
1695 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1697 struct io_ring_ctx *ctx = req->ctx;
1698 struct io_uring_cqe *cqe;
1700 trace_io_uring_complete(ctx, req->user_data, res);
1703 * If we can't get a cq entry, userspace overflowed the
1704 * submission (by quite a lot). Increment the overflow count in
1707 cqe = io_get_cqring(ctx);
1709 WRITE_ONCE(cqe->user_data, req->user_data);
1710 WRITE_ONCE(cqe->res, res);
1711 WRITE_ONCE(cqe->flags, cflags);
1712 } else if (ctx->cq_overflow_flushed ||
1713 atomic_read(&req->task->io_uring->in_idle)) {
1715 * If we're in ring overflow flush mode, or in task cancel mode,
1716 * then we cannot store the request for later flushing, we need
1717 * to drop it on the floor.
1719 ctx->cached_cq_overflow++;
1720 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1722 if (list_empty(&ctx->cq_overflow_list)) {
1723 set_bit(0, &ctx->sq_check_overflow);
1724 set_bit(0, &ctx->cq_check_overflow);
1725 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1729 req->compl.cflags = cflags;
1730 refcount_inc(&req->refs);
1731 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1735 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1737 __io_cqring_fill_event(req, res, 0);
1740 static inline void io_req_complete_post(struct io_kiocb *req, long res,
1741 unsigned int cflags)
1743 struct io_ring_ctx *ctx = req->ctx;
1744 unsigned long flags;
1746 spin_lock_irqsave(&ctx->completion_lock, flags);
1747 __io_cqring_fill_event(req, res, cflags);
1748 io_commit_cqring(ctx);
1750 * If we're the last reference to this request, add to our locked
1753 if (refcount_dec_and_test(&req->refs)) {
1754 struct io_comp_state *cs = &ctx->submit_state.comp;
1756 io_dismantle_req(req);
1757 io_put_task(req->task, 1);
1758 list_add(&req->compl.list, &cs->locked_free_list);
1759 cs->locked_free_nr++;
1762 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1764 io_cqring_ev_posted(ctx);
1767 percpu_ref_put(&ctx->refs);
1771 static void io_req_complete_state(struct io_kiocb *req, long res,
1772 unsigned int cflags)
1776 req->compl.cflags = cflags;
1777 req->flags |= REQ_F_COMPLETE_INLINE;
1780 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1781 long res, unsigned cflags)
1783 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1784 io_req_complete_state(req, res, cflags);
1786 io_req_complete_post(req, res, cflags);
1789 static inline void io_req_complete(struct io_kiocb *req, long res)
1791 __io_req_complete(req, 0, res, 0);
1794 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1796 struct io_submit_state *state = &ctx->submit_state;
1797 struct io_comp_state *cs = &state->comp;
1798 struct io_kiocb *req = NULL;
1801 * If we have more than a batch's worth of requests in our IRQ side
1802 * locked cache, grab the lock and move them over to our submission
1805 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1806 spin_lock_irq(&ctx->completion_lock);
1807 list_splice_init(&cs->locked_free_list, &cs->free_list);
1808 cs->locked_free_nr = 0;
1809 spin_unlock_irq(&ctx->completion_lock);
1812 while (!list_empty(&cs->free_list)) {
1813 req = list_first_entry(&cs->free_list, struct io_kiocb,
1815 list_del(&req->compl.list);
1816 state->reqs[state->free_reqs++] = req;
1817 if (state->free_reqs == ARRAY_SIZE(state->reqs))
1824 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1826 struct io_submit_state *state = &ctx->submit_state;
1828 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1830 if (!state->free_reqs) {
1831 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1834 if (io_flush_cached_reqs(ctx))
1837 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1841 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1842 * retry single alloc to be on the safe side.
1844 if (unlikely(ret <= 0)) {
1845 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1846 if (!state->reqs[0])
1850 state->free_reqs = ret;
1854 return state->reqs[state->free_reqs];
1857 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1864 static void io_dismantle_req(struct io_kiocb *req)
1868 if (req->async_data)
1869 kfree(req->async_data);
1871 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1872 if (req->fixed_rsrc_refs)
1873 percpu_ref_put(req->fixed_rsrc_refs);
1874 io_req_clean_work(req);
1877 static inline void io_put_task(struct task_struct *task, int nr)
1879 struct io_uring_task *tctx = task->io_uring;
1881 percpu_counter_sub(&tctx->inflight, nr);
1882 if (unlikely(atomic_read(&tctx->in_idle)))
1883 wake_up(&tctx->wait);
1884 put_task_struct_many(task, nr);
1887 static void __io_free_req(struct io_kiocb *req)
1889 struct io_ring_ctx *ctx = req->ctx;
1891 io_dismantle_req(req);
1892 io_put_task(req->task, 1);
1894 kmem_cache_free(req_cachep, req);
1895 percpu_ref_put(&ctx->refs);
1898 static inline void io_remove_next_linked(struct io_kiocb *req)
1900 struct io_kiocb *nxt = req->link;
1902 req->link = nxt->link;
1906 static void io_kill_linked_timeout(struct io_kiocb *req)
1908 struct io_ring_ctx *ctx = req->ctx;
1909 struct io_kiocb *link;
1910 bool cancelled = false;
1911 unsigned long flags;
1913 spin_lock_irqsave(&ctx->completion_lock, flags);
1917 * Can happen if a linked timeout fired and link had been like
1918 * req -> link t-out -> link t-out [-> ...]
1920 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1921 struct io_timeout_data *io = link->async_data;
1924 io_remove_next_linked(req);
1925 link->timeout.head = NULL;
1926 ret = hrtimer_try_to_cancel(&io->timer);
1928 io_cqring_fill_event(link, -ECANCELED);
1929 io_commit_cqring(ctx);
1933 req->flags &= ~REQ_F_LINK_TIMEOUT;
1934 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1937 io_cqring_ev_posted(ctx);
1943 static void io_fail_links(struct io_kiocb *req)
1945 struct io_kiocb *link, *nxt;
1946 struct io_ring_ctx *ctx = req->ctx;
1947 unsigned long flags;
1949 spin_lock_irqsave(&ctx->completion_lock, flags);
1957 trace_io_uring_fail_link(req, link);
1958 io_cqring_fill_event(link, -ECANCELED);
1961 * It's ok to free under spinlock as they're not linked anymore,
1962 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
1965 if (link->flags & REQ_F_WORK_INITIALIZED)
1966 io_put_req_deferred(link, 2);
1968 io_double_put_req(link);
1971 io_commit_cqring(ctx);
1972 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1974 io_cqring_ev_posted(ctx);
1977 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1979 if (req->flags & REQ_F_LINK_TIMEOUT)
1980 io_kill_linked_timeout(req);
1983 * If LINK is set, we have dependent requests in this chain. If we
1984 * didn't fail this request, queue the first one up, moving any other
1985 * dependencies to the next request. In case of failure, fail the rest
1988 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
1989 struct io_kiocb *nxt = req->link;
1998 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2000 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2002 return __io_req_find_next(req);
2005 static bool __tctx_task_work(struct io_uring_task *tctx)
2007 struct io_ring_ctx *ctx = NULL;
2008 struct io_wq_work_list list;
2009 struct io_wq_work_node *node;
2011 if (wq_list_empty(&tctx->task_list))
2014 spin_lock_irq(&tctx->task_lock);
2015 list = tctx->task_list;
2016 INIT_WQ_LIST(&tctx->task_list);
2017 spin_unlock_irq(&tctx->task_lock);
2021 struct io_wq_work_node *next = node->next;
2022 struct io_ring_ctx *this_ctx;
2023 struct io_kiocb *req;
2025 req = container_of(node, struct io_kiocb, io_task_work.node);
2026 this_ctx = req->ctx;
2027 req->task_work.func(&req->task_work);
2032 } else if (ctx != this_ctx) {
2033 mutex_lock(&ctx->uring_lock);
2034 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
2035 mutex_unlock(&ctx->uring_lock);
2040 if (ctx && ctx->submit_state.comp.nr) {
2041 mutex_lock(&ctx->uring_lock);
2042 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
2043 mutex_unlock(&ctx->uring_lock);
2046 return list.first != NULL;
2049 static void tctx_task_work(struct callback_head *cb)
2051 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
2053 while (__tctx_task_work(tctx))
2056 clear_bit(0, &tctx->task_state);
2059 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
2060 enum task_work_notify_mode notify)
2062 struct io_uring_task *tctx = tsk->io_uring;
2063 struct io_wq_work_node *node, *prev;
2064 unsigned long flags;
2067 WARN_ON_ONCE(!tctx);
2069 spin_lock_irqsave(&tctx->task_lock, flags);
2070 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2071 spin_unlock_irqrestore(&tctx->task_lock, flags);
2073 /* task_work already pending, we're done */
2074 if (test_bit(0, &tctx->task_state) ||
2075 test_and_set_bit(0, &tctx->task_state))
2078 if (!task_work_add(tsk, &tctx->task_work, notify))
2082 * Slow path - we failed, find and delete work. if the work is not
2083 * in the list, it got run and we're fine.
2086 spin_lock_irqsave(&tctx->task_lock, flags);
2087 wq_list_for_each(node, prev, &tctx->task_list) {
2088 if (&req->io_task_work.node == node) {
2089 wq_list_del(&tctx->task_list, node, prev);
2094 spin_unlock_irqrestore(&tctx->task_lock, flags);
2095 clear_bit(0, &tctx->task_state);
2099 static int io_req_task_work_add(struct io_kiocb *req)
2101 struct task_struct *tsk = req->task;
2102 struct io_ring_ctx *ctx = req->ctx;
2103 enum task_work_notify_mode notify;
2106 if (tsk->flags & PF_EXITING)
2110 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2111 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2112 * processing task_work. There's no reliable way to tell if TWA_RESUME
2116 if (!(ctx->flags & IORING_SETUP_SQPOLL))
2117 notify = TWA_SIGNAL;
2119 ret = io_task_work_add(tsk, req, notify);
2121 wake_up_process(tsk);
2126 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2127 task_work_func_t cb)
2129 struct io_ring_ctx *ctx = req->ctx;
2130 struct callback_head *head;
2132 init_task_work(&req->task_work, cb);
2134 head = READ_ONCE(ctx->exit_task_work);
2135 req->task_work.next = head;
2136 } while (cmpxchg(&ctx->exit_task_work, head, &req->task_work) != head);
2139 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2141 struct io_ring_ctx *ctx = req->ctx;
2143 spin_lock_irq(&ctx->completion_lock);
2144 io_cqring_fill_event(req, error);
2145 io_commit_cqring(ctx);
2146 spin_unlock_irq(&ctx->completion_lock);
2148 io_cqring_ev_posted(ctx);
2149 req_set_fail_links(req);
2150 io_double_put_req(req);
2153 static void io_req_task_cancel(struct callback_head *cb)
2155 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2156 struct io_ring_ctx *ctx = req->ctx;
2158 mutex_lock(&ctx->uring_lock);
2159 __io_req_task_cancel(req, req->result);
2160 mutex_unlock(&ctx->uring_lock);
2161 percpu_ref_put(&ctx->refs);
2164 static void __io_req_task_submit(struct io_kiocb *req)
2166 struct io_ring_ctx *ctx = req->ctx;
2168 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2169 mutex_lock(&ctx->uring_lock);
2170 if (!ctx->sqo_dead && !(current->flags & PF_EXITING) &&
2171 !io_sq_thread_acquire_mm_files(ctx, req))
2172 __io_queue_sqe(req);
2174 __io_req_task_cancel(req, -EFAULT);
2175 mutex_unlock(&ctx->uring_lock);
2177 if (ctx->flags & IORING_SETUP_SQPOLL)
2178 io_sq_thread_drop_mm_files();
2181 static void io_req_task_submit(struct callback_head *cb)
2183 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2185 __io_req_task_submit(req);
2188 static void io_req_task_queue(struct io_kiocb *req)
2192 req->task_work.func = io_req_task_submit;
2193 ret = io_req_task_work_add(req);
2194 if (unlikely(ret)) {
2195 req->result = -ECANCELED;
2196 percpu_ref_get(&req->ctx->refs);
2197 io_req_task_work_add_fallback(req, io_req_task_cancel);
2201 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2203 percpu_ref_get(&req->ctx->refs);
2205 req->task_work.func = io_req_task_cancel;
2207 if (unlikely(io_req_task_work_add(req)))
2208 io_req_task_work_add_fallback(req, io_req_task_cancel);
2211 static inline void io_queue_next(struct io_kiocb *req)
2213 struct io_kiocb *nxt = io_req_find_next(req);
2216 io_req_task_queue(nxt);
2219 static void io_free_req(struct io_kiocb *req)
2226 struct task_struct *task;
2231 static inline void io_init_req_batch(struct req_batch *rb)
2238 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2239 struct req_batch *rb)
2242 io_put_task(rb->task, rb->task_refs);
2244 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2247 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2248 struct io_submit_state *state)
2252 if (req->task != rb->task) {
2254 io_put_task(rb->task, rb->task_refs);
2255 rb->task = req->task;
2261 io_dismantle_req(req);
2262 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2263 state->reqs[state->free_reqs++] = req;
2265 list_add(&req->compl.list, &state->comp.free_list);
2268 static void io_submit_flush_completions(struct io_comp_state *cs,
2269 struct io_ring_ctx *ctx)
2272 struct io_kiocb *req;
2273 struct req_batch rb;
2275 io_init_req_batch(&rb);
2276 spin_lock_irq(&ctx->completion_lock);
2277 for (i = 0; i < nr; i++) {
2279 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2281 io_commit_cqring(ctx);
2282 spin_unlock_irq(&ctx->completion_lock);
2284 io_cqring_ev_posted(ctx);
2285 for (i = 0; i < nr; i++) {
2288 /* submission and completion refs */
2289 if (refcount_sub_and_test(2, &req->refs))
2290 io_req_free_batch(&rb, req, &ctx->submit_state);
2293 io_req_free_batch_finish(ctx, &rb);
2298 * Drop reference to request, return next in chain (if there is one) if this
2299 * was the last reference to this request.
2301 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2303 struct io_kiocb *nxt = NULL;
2305 if (refcount_dec_and_test(&req->refs)) {
2306 nxt = io_req_find_next(req);
2312 static void io_put_req(struct io_kiocb *req)
2314 if (refcount_dec_and_test(&req->refs))
2318 static void io_put_req_deferred_cb(struct callback_head *cb)
2320 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2325 static void io_free_req_deferred(struct io_kiocb *req)
2329 req->task_work.func = io_put_req_deferred_cb;
2330 ret = io_req_task_work_add(req);
2332 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2335 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2337 if (refcount_sub_and_test(refs, &req->refs))
2338 io_free_req_deferred(req);
2341 static void io_double_put_req(struct io_kiocb *req)
2343 /* drop both submit and complete references */
2344 if (refcount_sub_and_test(2, &req->refs))
2348 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2350 /* See comment at the top of this file */
2352 return __io_cqring_events(ctx);
2355 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2357 struct io_rings *rings = ctx->rings;
2359 /* make sure SQ entry isn't read before tail */
2360 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2363 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2365 unsigned int cflags;
2367 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2368 cflags |= IORING_CQE_F_BUFFER;
2369 req->flags &= ~REQ_F_BUFFER_SELECTED;
2374 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2376 struct io_buffer *kbuf;
2378 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2379 return io_put_kbuf(req, kbuf);
2382 static inline bool io_run_task_work(void)
2385 * Not safe to run on exiting task, and the task_work handling will
2386 * not add work to such a task.
2388 if (unlikely(current->flags & PF_EXITING))
2390 if (current->task_works) {
2391 __set_current_state(TASK_RUNNING);
2400 * Find and free completed poll iocbs
2402 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2403 struct list_head *done)
2405 struct req_batch rb;
2406 struct io_kiocb *req;
2408 /* order with ->result store in io_complete_rw_iopoll() */
2411 io_init_req_batch(&rb);
2412 while (!list_empty(done)) {
2415 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2416 list_del(&req->inflight_entry);
2418 if (READ_ONCE(req->result) == -EAGAIN) {
2419 req->iopoll_completed = 0;
2420 if (io_rw_reissue(req))
2424 if (req->flags & REQ_F_BUFFER_SELECTED)
2425 cflags = io_put_rw_kbuf(req);
2427 __io_cqring_fill_event(req, req->result, cflags);
2430 if (refcount_dec_and_test(&req->refs))
2431 io_req_free_batch(&rb, req, &ctx->submit_state);
2434 io_commit_cqring(ctx);
2435 io_cqring_ev_posted_iopoll(ctx);
2436 io_req_free_batch_finish(ctx, &rb);
2439 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2442 struct io_kiocb *req, *tmp;
2448 * Only spin for completions if we don't have multiple devices hanging
2449 * off our complete list, and we're under the requested amount.
2451 spin = !ctx->poll_multi_file && *nr_events < min;
2454 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2455 struct kiocb *kiocb = &req->rw.kiocb;
2458 * Move completed and retryable entries to our local lists.
2459 * If we find a request that requires polling, break out
2460 * and complete those lists first, if we have entries there.
2462 if (READ_ONCE(req->iopoll_completed)) {
2463 list_move_tail(&req->inflight_entry, &done);
2466 if (!list_empty(&done))
2469 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2473 /* iopoll may have completed current req */
2474 if (READ_ONCE(req->iopoll_completed))
2475 list_move_tail(&req->inflight_entry, &done);
2482 if (!list_empty(&done))
2483 io_iopoll_complete(ctx, nr_events, &done);
2489 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2490 * non-spinning poll check - we'll still enter the driver poll loop, but only
2491 * as a non-spinning completion check.
2493 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2496 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2499 ret = io_do_iopoll(ctx, nr_events, min);
2502 if (*nr_events >= min)
2510 * We can't just wait for polled events to come to us, we have to actively
2511 * find and complete them.
2513 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2515 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2518 mutex_lock(&ctx->uring_lock);
2519 while (!list_empty(&ctx->iopoll_list)) {
2520 unsigned int nr_events = 0;
2522 io_do_iopoll(ctx, &nr_events, 0);
2524 /* let it sleep and repeat later if can't complete a request */
2528 * Ensure we allow local-to-the-cpu processing to take place,
2529 * in this case we need to ensure that we reap all events.
2530 * Also let task_work, etc. to progress by releasing the mutex
2532 if (need_resched()) {
2533 mutex_unlock(&ctx->uring_lock);
2535 mutex_lock(&ctx->uring_lock);
2538 mutex_unlock(&ctx->uring_lock);
2541 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2543 unsigned int nr_events = 0;
2544 int iters = 0, ret = 0;
2547 * We disallow the app entering submit/complete with polling, but we
2548 * still need to lock the ring to prevent racing with polled issue
2549 * that got punted to a workqueue.
2551 mutex_lock(&ctx->uring_lock);
2554 * Don't enter poll loop if we already have events pending.
2555 * If we do, we can potentially be spinning for commands that
2556 * already triggered a CQE (eg in error).
2558 if (test_bit(0, &ctx->cq_check_overflow))
2559 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2560 if (io_cqring_events(ctx))
2564 * If a submit got punted to a workqueue, we can have the
2565 * application entering polling for a command before it gets
2566 * issued. That app will hold the uring_lock for the duration
2567 * of the poll right here, so we need to take a breather every
2568 * now and then to ensure that the issue has a chance to add
2569 * the poll to the issued list. Otherwise we can spin here
2570 * forever, while the workqueue is stuck trying to acquire the
2573 if (!(++iters & 7)) {
2574 mutex_unlock(&ctx->uring_lock);
2576 mutex_lock(&ctx->uring_lock);
2579 ret = io_iopoll_getevents(ctx, &nr_events, min);
2583 } while (min && !nr_events && !need_resched());
2585 mutex_unlock(&ctx->uring_lock);
2589 static void kiocb_end_write(struct io_kiocb *req)
2592 * Tell lockdep we inherited freeze protection from submission
2595 if (req->flags & REQ_F_ISREG) {
2596 struct inode *inode = file_inode(req->file);
2598 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2600 file_end_write(req->file);
2604 static bool io_resubmit_prep(struct io_kiocb *req)
2606 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2608 struct iov_iter iter;
2610 /* already prepared */
2611 if (req->async_data)
2614 switch (req->opcode) {
2615 case IORING_OP_READV:
2616 case IORING_OP_READ_FIXED:
2617 case IORING_OP_READ:
2620 case IORING_OP_WRITEV:
2621 case IORING_OP_WRITE_FIXED:
2622 case IORING_OP_WRITE:
2626 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2631 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2634 return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2638 static bool io_rw_reissue(struct io_kiocb *req)
2641 umode_t mode = file_inode(req->file)->i_mode;
2644 if (!S_ISBLK(mode) && !S_ISREG(mode))
2646 if ((req->flags & REQ_F_NOWAIT) || io_wq_current_is_worker())
2649 lockdep_assert_held(&req->ctx->uring_lock);
2651 ret = io_sq_thread_acquire_mm_files(req->ctx, req);
2653 if (!ret && io_resubmit_prep(req)) {
2654 refcount_inc(&req->refs);
2655 io_queue_async_work(req);
2658 req_set_fail_links(req);
2663 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2664 unsigned int issue_flags)
2668 if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_reissue(req))
2670 if (res != req->result)
2671 req_set_fail_links(req);
2673 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2674 kiocb_end_write(req);
2675 if (req->flags & REQ_F_BUFFER_SELECTED)
2676 cflags = io_put_rw_kbuf(req);
2677 __io_req_complete(req, issue_flags, res, cflags);
2680 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2682 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2684 __io_complete_rw(req, res, res2, 0);
2687 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2689 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2691 if (kiocb->ki_flags & IOCB_WRITE)
2692 kiocb_end_write(req);
2694 if (res != -EAGAIN && res != req->result)
2695 req_set_fail_links(req);
2697 WRITE_ONCE(req->result, res);
2698 /* order with io_poll_complete() checking ->result */
2700 WRITE_ONCE(req->iopoll_completed, 1);
2704 * After the iocb has been issued, it's safe to be found on the poll list.
2705 * Adding the kiocb to the list AFTER submission ensures that we don't
2706 * find it from a io_iopoll_getevents() thread before the issuer is done
2707 * accessing the kiocb cookie.
2709 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2711 struct io_ring_ctx *ctx = req->ctx;
2714 * Track whether we have multiple files in our lists. This will impact
2715 * how we do polling eventually, not spinning if we're on potentially
2716 * different devices.
2718 if (list_empty(&ctx->iopoll_list)) {
2719 ctx->poll_multi_file = false;
2720 } else if (!ctx->poll_multi_file) {
2721 struct io_kiocb *list_req;
2723 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2725 if (list_req->file != req->file)
2726 ctx->poll_multi_file = true;
2730 * For fast devices, IO may have already completed. If it has, add
2731 * it to the front so we find it first.
2733 if (READ_ONCE(req->iopoll_completed))
2734 list_add(&req->inflight_entry, &ctx->iopoll_list);
2736 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2739 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2740 * task context or in io worker task context. If current task context is
2741 * sq thread, we don't need to check whether should wake up sq thread.
2743 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2744 wq_has_sleeper(&ctx->sq_data->wait))
2745 wake_up(&ctx->sq_data->wait);
2748 static inline void io_state_file_put(struct io_submit_state *state)
2750 if (state->file_refs) {
2751 fput_many(state->file, state->file_refs);
2752 state->file_refs = 0;
2757 * Get as many references to a file as we have IOs left in this submission,
2758 * assuming most submissions are for one file, or at least that each file
2759 * has more than one submission.
2761 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2766 if (state->file_refs) {
2767 if (state->fd == fd) {
2771 io_state_file_put(state);
2773 state->file = fget_many(fd, state->ios_left);
2774 if (unlikely(!state->file))
2778 state->file_refs = state->ios_left - 1;
2782 static bool io_bdev_nowait(struct block_device *bdev)
2784 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2788 * If we tracked the file through the SCM inflight mechanism, we could support
2789 * any file. For now, just ensure that anything potentially problematic is done
2792 static bool io_file_supports_async(struct file *file, int rw)
2794 umode_t mode = file_inode(file)->i_mode;
2796 if (S_ISBLK(mode)) {
2797 if (IS_ENABLED(CONFIG_BLOCK) &&
2798 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2802 if (S_ISCHR(mode) || S_ISSOCK(mode))
2804 if (S_ISREG(mode)) {
2805 if (IS_ENABLED(CONFIG_BLOCK) &&
2806 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2807 file->f_op != &io_uring_fops)
2812 /* any ->read/write should understand O_NONBLOCK */
2813 if (file->f_flags & O_NONBLOCK)
2816 if (!(file->f_mode & FMODE_NOWAIT))
2820 return file->f_op->read_iter != NULL;
2822 return file->f_op->write_iter != NULL;
2825 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2827 struct io_ring_ctx *ctx = req->ctx;
2828 struct kiocb *kiocb = &req->rw.kiocb;
2829 struct file *file = req->file;
2833 if (S_ISREG(file_inode(file)->i_mode))
2834 req->flags |= REQ_F_ISREG;
2836 kiocb->ki_pos = READ_ONCE(sqe->off);
2837 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2838 req->flags |= REQ_F_CUR_POS;
2839 kiocb->ki_pos = file->f_pos;
2841 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2842 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2843 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2847 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2848 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2849 req->flags |= REQ_F_NOWAIT;
2851 ioprio = READ_ONCE(sqe->ioprio);
2853 ret = ioprio_check_cap(ioprio);
2857 kiocb->ki_ioprio = ioprio;
2859 kiocb->ki_ioprio = get_current_ioprio();
2861 if (ctx->flags & IORING_SETUP_IOPOLL) {
2862 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2863 !kiocb->ki_filp->f_op->iopoll)
2866 kiocb->ki_flags |= IOCB_HIPRI;
2867 kiocb->ki_complete = io_complete_rw_iopoll;
2868 req->iopoll_completed = 0;
2870 if (kiocb->ki_flags & IOCB_HIPRI)
2872 kiocb->ki_complete = io_complete_rw;
2875 req->rw.addr = READ_ONCE(sqe->addr);
2876 req->rw.len = READ_ONCE(sqe->len);
2877 req->buf_index = READ_ONCE(sqe->buf_index);
2881 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2887 case -ERESTARTNOINTR:
2888 case -ERESTARTNOHAND:
2889 case -ERESTART_RESTARTBLOCK:
2891 * We can't just restart the syscall, since previously
2892 * submitted sqes may already be in progress. Just fail this
2898 kiocb->ki_complete(kiocb, ret, 0);
2902 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2903 unsigned int issue_flags)
2905 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2906 struct io_async_rw *io = req->async_data;
2908 /* add previously done IO, if any */
2909 if (io && io->bytes_done > 0) {
2911 ret = io->bytes_done;
2913 ret += io->bytes_done;
2916 if (req->flags & REQ_F_CUR_POS)
2917 req->file->f_pos = kiocb->ki_pos;
2918 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2919 __io_complete_rw(req, ret, 0, issue_flags);
2921 io_rw_done(kiocb, ret);
2924 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2926 struct io_ring_ctx *ctx = req->ctx;
2927 size_t len = req->rw.len;
2928 struct io_mapped_ubuf *imu;
2929 u16 index, buf_index = req->buf_index;
2933 if (unlikely(buf_index >= ctx->nr_user_bufs))
2935 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2936 imu = &ctx->user_bufs[index];
2937 buf_addr = req->rw.addr;
2940 if (buf_addr + len < buf_addr)
2942 /* not inside the mapped region */
2943 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2947 * May not be a start of buffer, set size appropriately
2948 * and advance us to the beginning.
2950 offset = buf_addr - imu->ubuf;
2951 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2955 * Don't use iov_iter_advance() here, as it's really slow for
2956 * using the latter parts of a big fixed buffer - it iterates
2957 * over each segment manually. We can cheat a bit here, because
2960 * 1) it's a BVEC iter, we set it up
2961 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2962 * first and last bvec
2964 * So just find our index, and adjust the iterator afterwards.
2965 * If the offset is within the first bvec (or the whole first
2966 * bvec, just use iov_iter_advance(). This makes it easier
2967 * since we can just skip the first segment, which may not
2968 * be PAGE_SIZE aligned.
2970 const struct bio_vec *bvec = imu->bvec;
2972 if (offset <= bvec->bv_len) {
2973 iov_iter_advance(iter, offset);
2975 unsigned long seg_skip;
2977 /* skip first vec */
2978 offset -= bvec->bv_len;
2979 seg_skip = 1 + (offset >> PAGE_SHIFT);
2981 iter->bvec = bvec + seg_skip;
2982 iter->nr_segs -= seg_skip;
2983 iter->count -= bvec->bv_len + offset;
2984 iter->iov_offset = offset & ~PAGE_MASK;
2991 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2994 mutex_unlock(&ctx->uring_lock);
2997 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3000 * "Normal" inline submissions always hold the uring_lock, since we
3001 * grab it from the system call. Same is true for the SQPOLL offload.
3002 * The only exception is when we've detached the request and issue it
3003 * from an async worker thread, grab the lock for that case.
3006 mutex_lock(&ctx->uring_lock);
3009 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3010 int bgid, struct io_buffer *kbuf,
3013 struct io_buffer *head;
3015 if (req->flags & REQ_F_BUFFER_SELECTED)
3018 io_ring_submit_lock(req->ctx, needs_lock);
3020 lockdep_assert_held(&req->ctx->uring_lock);
3022 head = idr_find(&req->ctx->io_buffer_idr, bgid);
3024 if (!list_empty(&head->list)) {
3025 kbuf = list_last_entry(&head->list, struct io_buffer,
3027 list_del(&kbuf->list);
3030 idr_remove(&req->ctx->io_buffer_idr, bgid);
3032 if (*len > kbuf->len)
3035 kbuf = ERR_PTR(-ENOBUFS);
3038 io_ring_submit_unlock(req->ctx, needs_lock);
3043 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3046 struct io_buffer *kbuf;
3049 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3050 bgid = req->buf_index;
3051 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3054 req->rw.addr = (u64) (unsigned long) kbuf;
3055 req->flags |= REQ_F_BUFFER_SELECTED;
3056 return u64_to_user_ptr(kbuf->addr);
3059 #ifdef CONFIG_COMPAT
3060 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3063 struct compat_iovec __user *uiov;
3064 compat_ssize_t clen;
3068 uiov = u64_to_user_ptr(req->rw.addr);
3069 if (!access_ok(uiov, sizeof(*uiov)))
3071 if (__get_user(clen, &uiov->iov_len))
3077 buf = io_rw_buffer_select(req, &len, needs_lock);
3079 return PTR_ERR(buf);
3080 iov[0].iov_base = buf;
3081 iov[0].iov_len = (compat_size_t) len;
3086 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3089 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3093 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3096 len = iov[0].iov_len;
3099 buf = io_rw_buffer_select(req, &len, needs_lock);
3101 return PTR_ERR(buf);
3102 iov[0].iov_base = buf;
3103 iov[0].iov_len = len;
3107 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3110 if (req->flags & REQ_F_BUFFER_SELECTED) {
3111 struct io_buffer *kbuf;
3113 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3114 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3115 iov[0].iov_len = kbuf->len;
3118 if (req->rw.len != 1)
3121 #ifdef CONFIG_COMPAT
3122 if (req->ctx->compat)
3123 return io_compat_import(req, iov, needs_lock);
3126 return __io_iov_buffer_select(req, iov, needs_lock);
3129 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3130 struct iov_iter *iter, bool needs_lock)
3132 void __user *buf = u64_to_user_ptr(req->rw.addr);
3133 size_t sqe_len = req->rw.len;
3134 u8 opcode = req->opcode;
3137 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3139 return io_import_fixed(req, rw, iter);
3142 /* buffer index only valid with fixed read/write, or buffer select */
3143 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3146 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3147 if (req->flags & REQ_F_BUFFER_SELECT) {
3148 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3150 return PTR_ERR(buf);
3151 req->rw.len = sqe_len;
3154 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3159 if (req->flags & REQ_F_BUFFER_SELECT) {
3160 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3162 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3167 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3171 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3173 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3177 * For files that don't have ->read_iter() and ->write_iter(), handle them
3178 * by looping over ->read() or ->write() manually.
3180 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3182 struct kiocb *kiocb = &req->rw.kiocb;
3183 struct file *file = req->file;
3187 * Don't support polled IO through this interface, and we can't
3188 * support non-blocking either. For the latter, this just causes
3189 * the kiocb to be handled from an async context.
3191 if (kiocb->ki_flags & IOCB_HIPRI)
3193 if (kiocb->ki_flags & IOCB_NOWAIT)
3196 while (iov_iter_count(iter)) {
3200 if (!iov_iter_is_bvec(iter)) {
3201 iovec = iov_iter_iovec(iter);
3203 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3204 iovec.iov_len = req->rw.len;
3208 nr = file->f_op->read(file, iovec.iov_base,
3209 iovec.iov_len, io_kiocb_ppos(kiocb));
3211 nr = file->f_op->write(file, iovec.iov_base,
3212 iovec.iov_len, io_kiocb_ppos(kiocb));
3221 if (nr != iovec.iov_len)
3225 iov_iter_advance(iter, nr);
3231 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3232 const struct iovec *fast_iov, struct iov_iter *iter)
3234 struct io_async_rw *rw = req->async_data;
3236 memcpy(&rw->iter, iter, sizeof(*iter));
3237 rw->free_iovec = iovec;
3239 /* can only be fixed buffers, no need to do anything */
3240 if (iov_iter_is_bvec(iter))
3243 unsigned iov_off = 0;
3245 rw->iter.iov = rw->fast_iov;
3246 if (iter->iov != fast_iov) {
3247 iov_off = iter->iov - fast_iov;
3248 rw->iter.iov += iov_off;
3250 if (rw->fast_iov != fast_iov)
3251 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3252 sizeof(struct iovec) * iter->nr_segs);
3254 req->flags |= REQ_F_NEED_CLEANUP;
3258 static inline int __io_alloc_async_data(struct io_kiocb *req)
3260 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3261 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3262 return req->async_data == NULL;
3265 static int io_alloc_async_data(struct io_kiocb *req)
3267 if (!io_op_defs[req->opcode].needs_async_data)
3270 return __io_alloc_async_data(req);
3273 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3274 const struct iovec *fast_iov,
3275 struct iov_iter *iter, bool force)
3277 if (!force && !io_op_defs[req->opcode].needs_async_data)
3279 if (!req->async_data) {
3280 if (__io_alloc_async_data(req)) {
3285 io_req_map_rw(req, iovec, fast_iov, iter);
3290 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3292 struct io_async_rw *iorw = req->async_data;
3293 struct iovec *iov = iorw->fast_iov;
3296 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3297 if (unlikely(ret < 0))
3300 iorw->bytes_done = 0;
3301 iorw->free_iovec = iov;
3303 req->flags |= REQ_F_NEED_CLEANUP;
3307 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3309 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3311 return io_prep_rw(req, sqe);
3315 * This is our waitqueue callback handler, registered through lock_page_async()
3316 * when we initially tried to do the IO with the iocb armed our waitqueue.
3317 * This gets called when the page is unlocked, and we generally expect that to
3318 * happen when the page IO is completed and the page is now uptodate. This will
3319 * queue a task_work based retry of the operation, attempting to copy the data
3320 * again. If the latter fails because the page was NOT uptodate, then we will
3321 * do a thread based blocking retry of the operation. That's the unexpected
3324 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3325 int sync, void *arg)
3327 struct wait_page_queue *wpq;
3328 struct io_kiocb *req = wait->private;
3329 struct wait_page_key *key = arg;
3331 wpq = container_of(wait, struct wait_page_queue, wait);
3333 if (!wake_page_match(wpq, key))
3336 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3337 list_del_init(&wait->entry);
3339 /* submit ref gets dropped, acquire a new one */
3340 refcount_inc(&req->refs);
3341 io_req_task_queue(req);
3346 * This controls whether a given IO request should be armed for async page
3347 * based retry. If we return false here, the request is handed to the async
3348 * worker threads for retry. If we're doing buffered reads on a regular file,
3349 * we prepare a private wait_page_queue entry and retry the operation. This
3350 * will either succeed because the page is now uptodate and unlocked, or it
3351 * will register a callback when the page is unlocked at IO completion. Through
3352 * that callback, io_uring uses task_work to setup a retry of the operation.
3353 * That retry will attempt the buffered read again. The retry will generally
3354 * succeed, or in rare cases where it fails, we then fall back to using the
3355 * async worker threads for a blocking retry.
3357 static bool io_rw_should_retry(struct io_kiocb *req)
3359 struct io_async_rw *rw = req->async_data;
3360 struct wait_page_queue *wait = &rw->wpq;
3361 struct kiocb *kiocb = &req->rw.kiocb;
3363 /* never retry for NOWAIT, we just complete with -EAGAIN */
3364 if (req->flags & REQ_F_NOWAIT)
3367 /* Only for buffered IO */
3368 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3372 * just use poll if we can, and don't attempt if the fs doesn't
3373 * support callback based unlocks
3375 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3378 wait->wait.func = io_async_buf_func;
3379 wait->wait.private = req;
3380 wait->wait.flags = 0;
3381 INIT_LIST_HEAD(&wait->wait.entry);
3382 kiocb->ki_flags |= IOCB_WAITQ;
3383 kiocb->ki_flags &= ~IOCB_NOWAIT;
3384 kiocb->ki_waitq = wait;
3388 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3390 if (req->file->f_op->read_iter)
3391 return call_read_iter(req->file, &req->rw.kiocb, iter);
3392 else if (req->file->f_op->read)
3393 return loop_rw_iter(READ, req, iter);
3398 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3400 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3401 struct kiocb *kiocb = &req->rw.kiocb;
3402 struct iov_iter __iter, *iter = &__iter;
3403 struct io_async_rw *rw = req->async_data;
3404 ssize_t io_size, ret, ret2;
3405 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3411 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3415 io_size = iov_iter_count(iter);
3416 req->result = io_size;
3418 /* Ensure we clear previously set non-block flag */
3419 if (!force_nonblock)
3420 kiocb->ki_flags &= ~IOCB_NOWAIT;
3422 kiocb->ki_flags |= IOCB_NOWAIT;
3424 /* If the file doesn't support async, just async punt */
3425 if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3426 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3427 return ret ?: -EAGAIN;
3430 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3431 if (unlikely(ret)) {
3436 ret = io_iter_do_read(req, iter);
3438 if (ret == -EIOCBQUEUED) {
3440 } else if (ret == -EAGAIN) {
3441 /* IOPOLL retry should happen for io-wq threads */
3442 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3444 /* no retry on NONBLOCK nor RWF_NOWAIT */
3445 if (req->flags & REQ_F_NOWAIT)
3447 /* some cases will consume bytes even on error returns */
3448 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3450 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3451 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3452 /* read all, failed, already did sync or don't want to retry */
3456 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3461 rw = req->async_data;
3462 /* now use our persistent iterator, if we aren't already */
3467 rw->bytes_done += ret;
3468 /* if we can retry, do so with the callbacks armed */
3469 if (!io_rw_should_retry(req)) {
3470 kiocb->ki_flags &= ~IOCB_WAITQ;
3475 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3476 * we get -EIOCBQUEUED, then we'll get a notification when the
3477 * desired page gets unlocked. We can also get a partial read
3478 * here, and if we do, then just retry at the new offset.
3480 ret = io_iter_do_read(req, iter);
3481 if (ret == -EIOCBQUEUED)
3483 /* we got some bytes, but not all. retry. */
3484 } while (ret > 0 && ret < io_size);
3486 kiocb_done(kiocb, ret, issue_flags);
3488 /* it's faster to check here then delegate to kfree */
3494 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3496 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3498 return io_prep_rw(req, sqe);
3501 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3503 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3504 struct kiocb *kiocb = &req->rw.kiocb;
3505 struct iov_iter __iter, *iter = &__iter;
3506 struct io_async_rw *rw = req->async_data;
3507 ssize_t ret, ret2, io_size;
3508 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3514 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3518 io_size = iov_iter_count(iter);
3519 req->result = io_size;
3521 /* Ensure we clear previously set non-block flag */
3522 if (!force_nonblock)
3523 kiocb->ki_flags &= ~IOCB_NOWAIT;
3525 kiocb->ki_flags |= IOCB_NOWAIT;
3527 /* If the file doesn't support async, just async punt */
3528 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3531 /* file path doesn't support NOWAIT for non-direct_IO */
3532 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3533 (req->flags & REQ_F_ISREG))
3536 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3541 * Open-code file_start_write here to grab freeze protection,
3542 * which will be released by another thread in
3543 * io_complete_rw(). Fool lockdep by telling it the lock got
3544 * released so that it doesn't complain about the held lock when
3545 * we return to userspace.
3547 if (req->flags & REQ_F_ISREG) {
3548 sb_start_write(file_inode(req->file)->i_sb);
3549 __sb_writers_release(file_inode(req->file)->i_sb,
3552 kiocb->ki_flags |= IOCB_WRITE;
3554 if (req->file->f_op->write_iter)
3555 ret2 = call_write_iter(req->file, kiocb, iter);
3556 else if (req->file->f_op->write)
3557 ret2 = loop_rw_iter(WRITE, req, iter);
3562 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3563 * retry them without IOCB_NOWAIT.
3565 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3567 /* no retry on NONBLOCK nor RWF_NOWAIT */
3568 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3570 if (!force_nonblock || ret2 != -EAGAIN) {
3571 /* IOPOLL retry should happen for io-wq threads */
3572 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3575 kiocb_done(kiocb, ret2, issue_flags);
3578 /* some cases will consume bytes even on error returns */
3579 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3580 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3581 return ret ?: -EAGAIN;
3584 /* it's reportedly faster than delegating the null check to kfree() */
3590 static int io_renameat_prep(struct io_kiocb *req,
3591 const struct io_uring_sqe *sqe)
3593 struct io_rename *ren = &req->rename;
3594 const char __user *oldf, *newf;
3596 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3599 ren->old_dfd = READ_ONCE(sqe->fd);
3600 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3601 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3602 ren->new_dfd = READ_ONCE(sqe->len);
3603 ren->flags = READ_ONCE(sqe->rename_flags);
3605 ren->oldpath = getname(oldf);
3606 if (IS_ERR(ren->oldpath))
3607 return PTR_ERR(ren->oldpath);
3609 ren->newpath = getname(newf);
3610 if (IS_ERR(ren->newpath)) {
3611 putname(ren->oldpath);
3612 return PTR_ERR(ren->newpath);
3615 req->flags |= REQ_F_NEED_CLEANUP;
3619 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3621 struct io_rename *ren = &req->rename;
3624 if (issue_flags & IO_URING_F_NONBLOCK)
3627 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3628 ren->newpath, ren->flags);
3630 req->flags &= ~REQ_F_NEED_CLEANUP;
3632 req_set_fail_links(req);
3633 io_req_complete(req, ret);
3637 static int io_unlinkat_prep(struct io_kiocb *req,
3638 const struct io_uring_sqe *sqe)
3640 struct io_unlink *un = &req->unlink;
3641 const char __user *fname;
3643 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3646 un->dfd = READ_ONCE(sqe->fd);
3648 un->flags = READ_ONCE(sqe->unlink_flags);
3649 if (un->flags & ~AT_REMOVEDIR)
3652 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3653 un->filename = getname(fname);
3654 if (IS_ERR(un->filename))
3655 return PTR_ERR(un->filename);
3657 req->flags |= REQ_F_NEED_CLEANUP;
3661 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3663 struct io_unlink *un = &req->unlink;
3666 if (issue_flags & IO_URING_F_NONBLOCK)
3669 if (un->flags & AT_REMOVEDIR)
3670 ret = do_rmdir(un->dfd, un->filename);
3672 ret = do_unlinkat(un->dfd, un->filename);
3674 req->flags &= ~REQ_F_NEED_CLEANUP;
3676 req_set_fail_links(req);
3677 io_req_complete(req, ret);
3681 static int io_shutdown_prep(struct io_kiocb *req,
3682 const struct io_uring_sqe *sqe)
3684 #if defined(CONFIG_NET)
3685 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3687 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3691 req->shutdown.how = READ_ONCE(sqe->len);
3698 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3700 #if defined(CONFIG_NET)
3701 struct socket *sock;
3704 if (issue_flags & IO_URING_F_NONBLOCK)
3707 sock = sock_from_file(req->file);
3708 if (unlikely(!sock))
3711 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3713 req_set_fail_links(req);
3714 io_req_complete(req, ret);
3721 static int __io_splice_prep(struct io_kiocb *req,
3722 const struct io_uring_sqe *sqe)
3724 struct io_splice* sp = &req->splice;
3725 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3727 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3731 sp->len = READ_ONCE(sqe->len);
3732 sp->flags = READ_ONCE(sqe->splice_flags);
3734 if (unlikely(sp->flags & ~valid_flags))
3737 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3738 (sp->flags & SPLICE_F_FD_IN_FIXED));
3741 req->flags |= REQ_F_NEED_CLEANUP;
3743 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3745 * Splice operation will be punted aync, and here need to
3746 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3748 io_req_init_async(req);
3749 req->work.flags |= IO_WQ_WORK_UNBOUND;
3755 static int io_tee_prep(struct io_kiocb *req,
3756 const struct io_uring_sqe *sqe)
3758 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3760 return __io_splice_prep(req, sqe);
3763 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3765 struct io_splice *sp = &req->splice;
3766 struct file *in = sp->file_in;
3767 struct file *out = sp->file_out;
3768 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3771 if (issue_flags & IO_URING_F_NONBLOCK)
3774 ret = do_tee(in, out, sp->len, flags);
3776 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3777 req->flags &= ~REQ_F_NEED_CLEANUP;
3780 req_set_fail_links(req);
3781 io_req_complete(req, ret);
3785 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3787 struct io_splice* sp = &req->splice;
3789 sp->off_in = READ_ONCE(sqe->splice_off_in);
3790 sp->off_out = READ_ONCE(sqe->off);
3791 return __io_splice_prep(req, sqe);
3794 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3796 struct io_splice *sp = &req->splice;
3797 struct file *in = sp->file_in;
3798 struct file *out = sp->file_out;
3799 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3800 loff_t *poff_in, *poff_out;
3803 if (issue_flags & IO_URING_F_NONBLOCK)
3806 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3807 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3810 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3812 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3813 req->flags &= ~REQ_F_NEED_CLEANUP;
3816 req_set_fail_links(req);
3817 io_req_complete(req, ret);
3822 * IORING_OP_NOP just posts a completion event, nothing else.
3824 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3826 struct io_ring_ctx *ctx = req->ctx;
3828 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3831 __io_req_complete(req, issue_flags, 0, 0);
3835 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3837 struct io_ring_ctx *ctx = req->ctx;
3842 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3844 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3847 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3848 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3851 req->sync.off = READ_ONCE(sqe->off);
3852 req->sync.len = READ_ONCE(sqe->len);
3856 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3858 loff_t end = req->sync.off + req->sync.len;
3861 /* fsync always requires a blocking context */
3862 if (issue_flags & IO_URING_F_NONBLOCK)
3865 ret = vfs_fsync_range(req->file, req->sync.off,
3866 end > 0 ? end : LLONG_MAX,
3867 req->sync.flags & IORING_FSYNC_DATASYNC);
3869 req_set_fail_links(req);
3870 io_req_complete(req, ret);
3874 static int io_fallocate_prep(struct io_kiocb *req,
3875 const struct io_uring_sqe *sqe)
3877 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3879 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3882 req->sync.off = READ_ONCE(sqe->off);
3883 req->sync.len = READ_ONCE(sqe->addr);
3884 req->sync.mode = READ_ONCE(sqe->len);
3888 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3892 /* fallocate always requiring blocking context */
3893 if (issue_flags & IO_URING_F_NONBLOCK)
3895 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3898 req_set_fail_links(req);
3899 io_req_complete(req, ret);
3903 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3905 const char __user *fname;
3908 if (unlikely(sqe->ioprio || sqe->buf_index))
3910 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3913 /* open.how should be already initialised */
3914 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3915 req->open.how.flags |= O_LARGEFILE;
3917 req->open.dfd = READ_ONCE(sqe->fd);
3918 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3919 req->open.filename = getname(fname);
3920 if (IS_ERR(req->open.filename)) {
3921 ret = PTR_ERR(req->open.filename);
3922 req->open.filename = NULL;
3925 req->open.nofile = rlimit(RLIMIT_NOFILE);
3926 req->flags |= REQ_F_NEED_CLEANUP;
3930 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3934 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3936 mode = READ_ONCE(sqe->len);
3937 flags = READ_ONCE(sqe->open_flags);
3938 req->open.how = build_open_how(flags, mode);
3939 return __io_openat_prep(req, sqe);
3942 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3944 struct open_how __user *how;
3948 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3950 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3951 len = READ_ONCE(sqe->len);
3952 if (len < OPEN_HOW_SIZE_VER0)
3955 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3960 return __io_openat_prep(req, sqe);
3963 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3965 struct open_flags op;
3968 bool resolve_nonblock;
3971 ret = build_open_flags(&req->open.how, &op);
3974 nonblock_set = op.open_flag & O_NONBLOCK;
3975 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3976 if (issue_flags & IO_URING_F_NONBLOCK) {
3978 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3979 * it'll always -EAGAIN
3981 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3983 op.lookup_flags |= LOOKUP_CACHED;
3984 op.open_flag |= O_NONBLOCK;
3987 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3991 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3992 /* only retry if RESOLVE_CACHED wasn't already set by application */
3993 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3994 file == ERR_PTR(-EAGAIN)) {
3996 * We could hang on to this 'fd', but seems like marginal
3997 * gain for something that is now known to be a slower path.
3998 * So just put it, and we'll get a new one when we retry.
4006 ret = PTR_ERR(file);
4008 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4009 file->f_flags &= ~O_NONBLOCK;
4010 fsnotify_open(file);
4011 fd_install(ret, file);
4014 putname(req->open.filename);
4015 req->flags &= ~REQ_F_NEED_CLEANUP;
4017 req_set_fail_links(req);
4018 io_req_complete(req, ret);
4022 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4024 return io_openat2(req, issue_flags & IO_URING_F_NONBLOCK);
4027 static int io_remove_buffers_prep(struct io_kiocb *req,
4028 const struct io_uring_sqe *sqe)
4030 struct io_provide_buf *p = &req->pbuf;
4033 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
4036 tmp = READ_ONCE(sqe->fd);
4037 if (!tmp || tmp > USHRT_MAX)
4040 memset(p, 0, sizeof(*p));
4042 p->bgid = READ_ONCE(sqe->buf_group);
4046 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4047 int bgid, unsigned nbufs)
4051 /* shouldn't happen */
4055 /* the head kbuf is the list itself */
4056 while (!list_empty(&buf->list)) {
4057 struct io_buffer *nxt;
4059 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4060 list_del(&nxt->list);
4067 idr_remove(&ctx->io_buffer_idr, bgid);
4072 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4074 struct io_provide_buf *p = &req->pbuf;
4075 struct io_ring_ctx *ctx = req->ctx;
4076 struct io_buffer *head;
4078 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4080 io_ring_submit_lock(ctx, !force_nonblock);
4082 lockdep_assert_held(&ctx->uring_lock);
4085 head = idr_find(&ctx->io_buffer_idr, p->bgid);
4087 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4089 req_set_fail_links(req);
4091 /* need to hold the lock to complete IOPOLL requests */
4092 if (ctx->flags & IORING_SETUP_IOPOLL) {
4093 __io_req_complete(req, issue_flags, ret, 0);
4094 io_ring_submit_unlock(ctx, !force_nonblock);
4096 io_ring_submit_unlock(ctx, !force_nonblock);
4097 __io_req_complete(req, issue_flags, ret, 0);
4102 static int io_provide_buffers_prep(struct io_kiocb *req,
4103 const struct io_uring_sqe *sqe)
4105 struct io_provide_buf *p = &req->pbuf;
4108 if (sqe->ioprio || sqe->rw_flags)
4111 tmp = READ_ONCE(sqe->fd);
4112 if (!tmp || tmp > USHRT_MAX)
4115 p->addr = READ_ONCE(sqe->addr);
4116 p->len = READ_ONCE(sqe->len);
4118 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
4121 p->bgid = READ_ONCE(sqe->buf_group);
4122 tmp = READ_ONCE(sqe->off);
4123 if (tmp > USHRT_MAX)
4129 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4131 struct io_buffer *buf;
4132 u64 addr = pbuf->addr;
4133 int i, bid = pbuf->bid;
4135 for (i = 0; i < pbuf->nbufs; i++) {
4136 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4141 buf->len = pbuf->len;
4146 INIT_LIST_HEAD(&buf->list);
4149 list_add_tail(&buf->list, &(*head)->list);
4153 return i ? i : -ENOMEM;
4156 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4158 struct io_provide_buf *p = &req->pbuf;
4159 struct io_ring_ctx *ctx = req->ctx;
4160 struct io_buffer *head, *list;
4162 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4164 io_ring_submit_lock(ctx, !force_nonblock);
4166 lockdep_assert_held(&ctx->uring_lock);
4168 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4170 ret = io_add_buffers(p, &head);
4175 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4178 __io_remove_buffers(ctx, head, p->bgid, -1U);
4184 req_set_fail_links(req);
4186 /* need to hold the lock to complete IOPOLL requests */
4187 if (ctx->flags & IORING_SETUP_IOPOLL) {
4188 __io_req_complete(req, issue_flags, ret, 0);
4189 io_ring_submit_unlock(ctx, !force_nonblock);
4191 io_ring_submit_unlock(ctx, !force_nonblock);
4192 __io_req_complete(req, issue_flags, ret, 0);
4197 static int io_epoll_ctl_prep(struct io_kiocb *req,
4198 const struct io_uring_sqe *sqe)
4200 #if defined(CONFIG_EPOLL)
4201 if (sqe->ioprio || sqe->buf_index)
4203 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4206 req->epoll.epfd = READ_ONCE(sqe->fd);
4207 req->epoll.op = READ_ONCE(sqe->len);
4208 req->epoll.fd = READ_ONCE(sqe->off);
4210 if (ep_op_has_event(req->epoll.op)) {
4211 struct epoll_event __user *ev;
4213 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4214 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4224 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4226 #if defined(CONFIG_EPOLL)
4227 struct io_epoll *ie = &req->epoll;
4229 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4231 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4232 if (force_nonblock && ret == -EAGAIN)
4236 req_set_fail_links(req);
4237 __io_req_complete(req, issue_flags, ret, 0);
4244 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4246 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4247 if (sqe->ioprio || sqe->buf_index || sqe->off)
4249 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4252 req->madvise.addr = READ_ONCE(sqe->addr);
4253 req->madvise.len = READ_ONCE(sqe->len);
4254 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4261 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4263 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4264 struct io_madvise *ma = &req->madvise;
4267 if (issue_flags & IO_URING_F_NONBLOCK)
4270 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4272 req_set_fail_links(req);
4273 io_req_complete(req, ret);
4280 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4282 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4284 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4287 req->fadvise.offset = READ_ONCE(sqe->off);
4288 req->fadvise.len = READ_ONCE(sqe->len);
4289 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4293 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4295 struct io_fadvise *fa = &req->fadvise;
4298 if (issue_flags & IO_URING_F_NONBLOCK) {
4299 switch (fa->advice) {
4300 case POSIX_FADV_NORMAL:
4301 case POSIX_FADV_RANDOM:
4302 case POSIX_FADV_SEQUENTIAL:
4309 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4311 req_set_fail_links(req);
4312 io_req_complete(req, ret);
4316 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4318 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4320 if (sqe->ioprio || sqe->buf_index)
4322 if (req->flags & REQ_F_FIXED_FILE)
4325 req->statx.dfd = READ_ONCE(sqe->fd);
4326 req->statx.mask = READ_ONCE(sqe->len);
4327 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4328 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4329 req->statx.flags = READ_ONCE(sqe->statx_flags);
4334 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4336 struct io_statx *ctx = &req->statx;
4339 if (issue_flags & IO_URING_F_NONBLOCK) {
4340 /* only need file table for an actual valid fd */
4341 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4342 req->flags |= REQ_F_NO_FILE_TABLE;
4346 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4350 req_set_fail_links(req);
4351 io_req_complete(req, ret);
4355 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4357 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4359 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4360 sqe->rw_flags || sqe->buf_index)
4362 if (req->flags & REQ_F_FIXED_FILE)
4365 req->close.fd = READ_ONCE(sqe->fd);
4369 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4371 struct files_struct *files = current->files;
4372 struct io_close *close = &req->close;
4373 struct fdtable *fdt;
4379 spin_lock(&files->file_lock);
4380 fdt = files_fdtable(files);
4381 if (close->fd >= fdt->max_fds) {
4382 spin_unlock(&files->file_lock);
4385 file = fdt->fd[close->fd];
4387 spin_unlock(&files->file_lock);
4391 if (file->f_op == &io_uring_fops) {
4392 spin_unlock(&files->file_lock);
4397 /* if the file has a flush method, be safe and punt to async */
4398 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4399 spin_unlock(&files->file_lock);
4403 ret = __close_fd_get_file(close->fd, &file);
4404 spin_unlock(&files->file_lock);
4411 /* No ->flush() or already async, safely close from here */
4412 ret = filp_close(file, current->files);
4415 req_set_fail_links(req);
4418 __io_req_complete(req, issue_flags, ret, 0);
4422 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4424 struct io_ring_ctx *ctx = req->ctx;
4426 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4428 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4431 req->sync.off = READ_ONCE(sqe->off);
4432 req->sync.len = READ_ONCE(sqe->len);
4433 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4437 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4441 /* sync_file_range always requires a blocking context */
4442 if (issue_flags & IO_URING_F_NONBLOCK)
4445 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4448 req_set_fail_links(req);
4449 io_req_complete(req, ret);
4453 #if defined(CONFIG_NET)
4454 static int io_setup_async_msg(struct io_kiocb *req,
4455 struct io_async_msghdr *kmsg)
4457 struct io_async_msghdr *async_msg = req->async_data;
4461 if (io_alloc_async_data(req)) {
4462 kfree(kmsg->free_iov);
4465 async_msg = req->async_data;
4466 req->flags |= REQ_F_NEED_CLEANUP;
4467 memcpy(async_msg, kmsg, sizeof(*kmsg));
4468 async_msg->msg.msg_name = &async_msg->addr;
4469 /* if were using fast_iov, set it to the new one */
4470 if (!async_msg->free_iov)
4471 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4476 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4477 struct io_async_msghdr *iomsg)
4479 iomsg->msg.msg_name = &iomsg->addr;
4480 iomsg->free_iov = iomsg->fast_iov;
4481 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4482 req->sr_msg.msg_flags, &iomsg->free_iov);
4485 static int io_sendmsg_prep_async(struct io_kiocb *req)
4489 if (!io_op_defs[req->opcode].needs_async_data)
4491 ret = io_sendmsg_copy_hdr(req, req->async_data);
4493 req->flags |= REQ_F_NEED_CLEANUP;
4497 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4499 struct io_sr_msg *sr = &req->sr_msg;
4501 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4504 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4505 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4506 sr->len = READ_ONCE(sqe->len);
4508 #ifdef CONFIG_COMPAT
4509 if (req->ctx->compat)
4510 sr->msg_flags |= MSG_CMSG_COMPAT;
4515 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4517 struct io_async_msghdr iomsg, *kmsg;
4518 struct socket *sock;
4522 sock = sock_from_file(req->file);
4523 if (unlikely(!sock))
4526 kmsg = req->async_data;
4528 ret = io_sendmsg_copy_hdr(req, &iomsg);
4534 flags = req->sr_msg.msg_flags;
4535 if (flags & MSG_DONTWAIT)
4536 req->flags |= REQ_F_NOWAIT;
4537 else if (issue_flags & IO_URING_F_NONBLOCK)
4538 flags |= MSG_DONTWAIT;
4540 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4541 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4542 return io_setup_async_msg(req, kmsg);
4543 if (ret == -ERESTARTSYS)
4546 /* fast path, check for non-NULL to avoid function call */
4548 kfree(kmsg->free_iov);
4549 req->flags &= ~REQ_F_NEED_CLEANUP;
4551 req_set_fail_links(req);
4552 __io_req_complete(req, issue_flags, ret, 0);
4556 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4558 struct io_sr_msg *sr = &req->sr_msg;
4561 struct socket *sock;
4565 sock = sock_from_file(req->file);
4566 if (unlikely(!sock))
4569 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4573 msg.msg_name = NULL;
4574 msg.msg_control = NULL;
4575 msg.msg_controllen = 0;
4576 msg.msg_namelen = 0;
4578 flags = req->sr_msg.msg_flags;
4579 if (flags & MSG_DONTWAIT)
4580 req->flags |= REQ_F_NOWAIT;
4581 else if (issue_flags & IO_URING_F_NONBLOCK)
4582 flags |= MSG_DONTWAIT;
4584 msg.msg_flags = flags;
4585 ret = sock_sendmsg(sock, &msg);
4586 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4588 if (ret == -ERESTARTSYS)
4592 req_set_fail_links(req);
4593 __io_req_complete(req, issue_flags, ret, 0);
4597 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4598 struct io_async_msghdr *iomsg)
4600 struct io_sr_msg *sr = &req->sr_msg;
4601 struct iovec __user *uiov;
4605 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4606 &iomsg->uaddr, &uiov, &iov_len);
4610 if (req->flags & REQ_F_BUFFER_SELECT) {
4613 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4615 sr->len = iomsg->fast_iov[0].iov_len;
4616 iomsg->free_iov = NULL;
4618 iomsg->free_iov = iomsg->fast_iov;
4619 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4620 &iomsg->free_iov, &iomsg->msg.msg_iter,
4629 #ifdef CONFIG_COMPAT
4630 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4631 struct io_async_msghdr *iomsg)
4633 struct compat_msghdr __user *msg_compat;
4634 struct io_sr_msg *sr = &req->sr_msg;
4635 struct compat_iovec __user *uiov;
4640 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4641 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4646 uiov = compat_ptr(ptr);
4647 if (req->flags & REQ_F_BUFFER_SELECT) {
4648 compat_ssize_t clen;
4652 if (!access_ok(uiov, sizeof(*uiov)))
4654 if (__get_user(clen, &uiov->iov_len))
4659 iomsg->free_iov = NULL;
4661 iomsg->free_iov = iomsg->fast_iov;
4662 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4663 UIO_FASTIOV, &iomsg->free_iov,
4664 &iomsg->msg.msg_iter, true);
4673 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4674 struct io_async_msghdr *iomsg)
4676 iomsg->msg.msg_name = &iomsg->addr;
4678 #ifdef CONFIG_COMPAT
4679 if (req->ctx->compat)
4680 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4683 return __io_recvmsg_copy_hdr(req, iomsg);
4686 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4689 struct io_sr_msg *sr = &req->sr_msg;
4690 struct io_buffer *kbuf;
4692 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4697 req->flags |= REQ_F_BUFFER_SELECTED;
4701 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4703 return io_put_kbuf(req, req->sr_msg.kbuf);
4706 static int io_recvmsg_prep_async(struct io_kiocb *req)
4710 if (!io_op_defs[req->opcode].needs_async_data)
4712 ret = io_recvmsg_copy_hdr(req, req->async_data);
4714 req->flags |= REQ_F_NEED_CLEANUP;
4718 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4720 struct io_sr_msg *sr = &req->sr_msg;
4722 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4725 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4726 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4727 sr->len = READ_ONCE(sqe->len);
4728 sr->bgid = READ_ONCE(sqe->buf_group);
4730 #ifdef CONFIG_COMPAT
4731 if (req->ctx->compat)
4732 sr->msg_flags |= MSG_CMSG_COMPAT;
4737 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4739 struct io_async_msghdr iomsg, *kmsg;
4740 struct socket *sock;
4741 struct io_buffer *kbuf;
4743 int ret, cflags = 0;
4744 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4746 sock = sock_from_file(req->file);
4747 if (unlikely(!sock))
4750 kmsg = req->async_data;
4752 ret = io_recvmsg_copy_hdr(req, &iomsg);
4758 if (req->flags & REQ_F_BUFFER_SELECT) {
4759 kbuf = io_recv_buffer_select(req, !force_nonblock);
4761 return PTR_ERR(kbuf);
4762 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4763 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4764 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4765 1, req->sr_msg.len);
4768 flags = req->sr_msg.msg_flags;
4769 if (flags & MSG_DONTWAIT)
4770 req->flags |= REQ_F_NOWAIT;
4771 else if (force_nonblock)
4772 flags |= MSG_DONTWAIT;
4774 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4775 kmsg->uaddr, flags);
4776 if (force_nonblock && ret == -EAGAIN)
4777 return io_setup_async_msg(req, kmsg);
4778 if (ret == -ERESTARTSYS)
4781 if (req->flags & REQ_F_BUFFER_SELECTED)
4782 cflags = io_put_recv_kbuf(req);
4783 /* fast path, check for non-NULL to avoid function call */
4785 kfree(kmsg->free_iov);
4786 req->flags &= ~REQ_F_NEED_CLEANUP;
4788 req_set_fail_links(req);
4789 __io_req_complete(req, issue_flags, ret, cflags);
4793 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4795 struct io_buffer *kbuf;
4796 struct io_sr_msg *sr = &req->sr_msg;
4798 void __user *buf = sr->buf;
4799 struct socket *sock;
4802 int ret, cflags = 0;
4803 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4805 sock = sock_from_file(req->file);
4806 if (unlikely(!sock))
4809 if (req->flags & REQ_F_BUFFER_SELECT) {
4810 kbuf = io_recv_buffer_select(req, !force_nonblock);
4812 return PTR_ERR(kbuf);
4813 buf = u64_to_user_ptr(kbuf->addr);
4816 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4820 msg.msg_name = NULL;
4821 msg.msg_control = NULL;
4822 msg.msg_controllen = 0;
4823 msg.msg_namelen = 0;
4824 msg.msg_iocb = NULL;
4827 flags = req->sr_msg.msg_flags;
4828 if (flags & MSG_DONTWAIT)
4829 req->flags |= REQ_F_NOWAIT;
4830 else if (force_nonblock)
4831 flags |= MSG_DONTWAIT;
4833 ret = sock_recvmsg(sock, &msg, flags);
4834 if (force_nonblock && ret == -EAGAIN)
4836 if (ret == -ERESTARTSYS)
4839 if (req->flags & REQ_F_BUFFER_SELECTED)
4840 cflags = io_put_recv_kbuf(req);
4842 req_set_fail_links(req);
4843 __io_req_complete(req, issue_flags, ret, cflags);
4847 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4849 struct io_accept *accept = &req->accept;
4851 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4853 if (sqe->ioprio || sqe->len || sqe->buf_index)
4856 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4857 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4858 accept->flags = READ_ONCE(sqe->accept_flags);
4859 accept->nofile = rlimit(RLIMIT_NOFILE);
4863 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4865 struct io_accept *accept = &req->accept;
4866 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4867 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4870 if (req->file->f_flags & O_NONBLOCK)
4871 req->flags |= REQ_F_NOWAIT;
4873 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4874 accept->addr_len, accept->flags,
4876 if (ret == -EAGAIN && force_nonblock)
4879 if (ret == -ERESTARTSYS)
4881 req_set_fail_links(req);
4883 __io_req_complete(req, issue_flags, ret, 0);
4887 static int io_connect_prep_async(struct io_kiocb *req)
4889 struct io_async_connect *io = req->async_data;
4890 struct io_connect *conn = &req->connect;
4892 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4895 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4897 struct io_connect *conn = &req->connect;
4899 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4901 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4904 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4905 conn->addr_len = READ_ONCE(sqe->addr2);
4909 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4911 struct io_async_connect __io, *io;
4912 unsigned file_flags;
4914 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4916 if (req->async_data) {
4917 io = req->async_data;
4919 ret = move_addr_to_kernel(req->connect.addr,
4920 req->connect.addr_len,
4927 file_flags = force_nonblock ? O_NONBLOCK : 0;
4929 ret = __sys_connect_file(req->file, &io->address,
4930 req->connect.addr_len, file_flags);
4931 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4932 if (req->async_data)
4934 if (io_alloc_async_data(req)) {
4938 io = req->async_data;
4939 memcpy(req->async_data, &__io, sizeof(__io));
4942 if (ret == -ERESTARTSYS)
4946 req_set_fail_links(req);
4947 __io_req_complete(req, issue_flags, ret, 0);
4950 #else /* !CONFIG_NET */
4951 #define IO_NETOP_FN(op) \
4952 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4954 return -EOPNOTSUPP; \
4957 #define IO_NETOP_PREP(op) \
4959 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4961 return -EOPNOTSUPP; \
4964 #define IO_NETOP_PREP_ASYNC(op) \
4966 static int io_##op##_prep_async(struct io_kiocb *req) \
4968 return -EOPNOTSUPP; \
4971 IO_NETOP_PREP_ASYNC(sendmsg);
4972 IO_NETOP_PREP_ASYNC(recvmsg);
4973 IO_NETOP_PREP_ASYNC(connect);
4974 IO_NETOP_PREP(accept);
4977 #endif /* CONFIG_NET */
4979 struct io_poll_table {
4980 struct poll_table_struct pt;
4981 struct io_kiocb *req;
4985 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4986 __poll_t mask, task_work_func_t func)
4990 /* for instances that support it check for an event match first: */
4991 if (mask && !(mask & poll->events))
4994 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4996 list_del_init(&poll->wait.entry);
4999 req->task_work.func = func;
5000 percpu_ref_get(&req->ctx->refs);
5003 * If this fails, then the task is exiting. When a task exits, the
5004 * work gets canceled, so just cancel this request as well instead
5005 * of executing it. We can't safely execute it anyway, as we may not
5006 * have the needed state needed for it anyway.
5008 ret = io_req_task_work_add(req);
5009 if (unlikely(ret)) {
5010 WRITE_ONCE(poll->canceled, true);
5011 io_req_task_work_add_fallback(req, func);
5016 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5017 __acquires(&req->ctx->completion_lock)
5019 struct io_ring_ctx *ctx = req->ctx;
5021 if (!req->result && !READ_ONCE(poll->canceled)) {
5022 struct poll_table_struct pt = { ._key = poll->events };
5024 req->result = vfs_poll(req->file, &pt) & poll->events;
5027 spin_lock_irq(&ctx->completion_lock);
5028 if (!req->result && !READ_ONCE(poll->canceled)) {
5029 add_wait_queue(poll->head, &poll->wait);
5036 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5038 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5039 if (req->opcode == IORING_OP_POLL_ADD)
5040 return req->async_data;
5041 return req->apoll->double_poll;
5044 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5046 if (req->opcode == IORING_OP_POLL_ADD)
5048 return &req->apoll->poll;
5051 static void io_poll_remove_double(struct io_kiocb *req)
5053 struct io_poll_iocb *poll = io_poll_get_double(req);
5055 lockdep_assert_held(&req->ctx->completion_lock);
5057 if (poll && poll->head) {
5058 struct wait_queue_head *head = poll->head;
5060 spin_lock(&head->lock);
5061 list_del_init(&poll->wait.entry);
5062 if (poll->wait.private)
5063 refcount_dec(&req->refs);
5065 spin_unlock(&head->lock);
5069 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
5071 struct io_ring_ctx *ctx = req->ctx;
5073 io_poll_remove_double(req);
5074 req->poll.done = true;
5075 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
5076 io_commit_cqring(ctx);
5079 static void io_poll_task_func(struct callback_head *cb)
5081 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5082 struct io_ring_ctx *ctx = req->ctx;
5083 struct io_kiocb *nxt;
5085 if (io_poll_rewait(req, &req->poll)) {
5086 spin_unlock_irq(&ctx->completion_lock);
5088 hash_del(&req->hash_node);
5089 io_poll_complete(req, req->result, 0);
5090 spin_unlock_irq(&ctx->completion_lock);
5092 nxt = io_put_req_find_next(req);
5093 io_cqring_ev_posted(ctx);
5095 __io_req_task_submit(nxt);
5098 percpu_ref_put(&ctx->refs);
5101 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5102 int sync, void *key)
5104 struct io_kiocb *req = wait->private;
5105 struct io_poll_iocb *poll = io_poll_get_single(req);
5106 __poll_t mask = key_to_poll(key);
5108 /* for instances that support it check for an event match first: */
5109 if (mask && !(mask & poll->events))
5112 list_del_init(&wait->entry);
5114 if (poll && poll->head) {
5117 spin_lock(&poll->head->lock);
5118 done = list_empty(&poll->wait.entry);
5120 list_del_init(&poll->wait.entry);
5121 /* make sure double remove sees this as being gone */
5122 wait->private = NULL;
5123 spin_unlock(&poll->head->lock);
5125 /* use wait func handler, so it matches the rq type */
5126 poll->wait.func(&poll->wait, mode, sync, key);
5129 refcount_dec(&req->refs);
5133 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5134 wait_queue_func_t wake_func)
5138 poll->canceled = false;
5139 poll->events = events;
5140 INIT_LIST_HEAD(&poll->wait.entry);
5141 init_waitqueue_func_entry(&poll->wait, wake_func);
5144 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5145 struct wait_queue_head *head,
5146 struct io_poll_iocb **poll_ptr)
5148 struct io_kiocb *req = pt->req;
5151 * If poll->head is already set, it's because the file being polled
5152 * uses multiple waitqueues for poll handling (eg one for read, one
5153 * for write). Setup a separate io_poll_iocb if this happens.
5155 if (unlikely(poll->head)) {
5156 struct io_poll_iocb *poll_one = poll;
5158 /* already have a 2nd entry, fail a third attempt */
5160 pt->error = -EINVAL;
5163 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5165 pt->error = -ENOMEM;
5168 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5169 refcount_inc(&req->refs);
5170 poll->wait.private = req;
5177 if (poll->events & EPOLLEXCLUSIVE)
5178 add_wait_queue_exclusive(head, &poll->wait);
5180 add_wait_queue(head, &poll->wait);
5183 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5184 struct poll_table_struct *p)
5186 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5187 struct async_poll *apoll = pt->req->apoll;
5189 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5192 static void io_async_task_func(struct callback_head *cb)
5194 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5195 struct async_poll *apoll = req->apoll;
5196 struct io_ring_ctx *ctx = req->ctx;
5198 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5200 if (io_poll_rewait(req, &apoll->poll)) {
5201 spin_unlock_irq(&ctx->completion_lock);
5202 percpu_ref_put(&ctx->refs);
5206 /* If req is still hashed, it cannot have been canceled. Don't check. */
5207 if (hash_hashed(&req->hash_node))
5208 hash_del(&req->hash_node);
5210 io_poll_remove_double(req);
5211 spin_unlock_irq(&ctx->completion_lock);
5213 if (!READ_ONCE(apoll->poll.canceled))
5214 __io_req_task_submit(req);
5216 __io_req_task_cancel(req, -ECANCELED);
5218 percpu_ref_put(&ctx->refs);
5219 kfree(apoll->double_poll);
5223 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5226 struct io_kiocb *req = wait->private;
5227 struct io_poll_iocb *poll = &req->apoll->poll;
5229 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5232 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5235 static void io_poll_req_insert(struct io_kiocb *req)
5237 struct io_ring_ctx *ctx = req->ctx;
5238 struct hlist_head *list;
5240 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5241 hlist_add_head(&req->hash_node, list);
5244 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5245 struct io_poll_iocb *poll,
5246 struct io_poll_table *ipt, __poll_t mask,
5247 wait_queue_func_t wake_func)
5248 __acquires(&ctx->completion_lock)
5250 struct io_ring_ctx *ctx = req->ctx;
5251 bool cancel = false;
5253 INIT_HLIST_NODE(&req->hash_node);
5254 io_init_poll_iocb(poll, mask, wake_func);
5255 poll->file = req->file;
5256 poll->wait.private = req;
5258 ipt->pt._key = mask;
5260 ipt->error = -EINVAL;
5262 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5264 spin_lock_irq(&ctx->completion_lock);
5265 if (likely(poll->head)) {
5266 spin_lock(&poll->head->lock);
5267 if (unlikely(list_empty(&poll->wait.entry))) {
5273 if (mask || ipt->error)
5274 list_del_init(&poll->wait.entry);
5276 WRITE_ONCE(poll->canceled, true);
5277 else if (!poll->done) /* actually waiting for an event */
5278 io_poll_req_insert(req);
5279 spin_unlock(&poll->head->lock);
5285 static bool io_arm_poll_handler(struct io_kiocb *req)
5287 const struct io_op_def *def = &io_op_defs[req->opcode];
5288 struct io_ring_ctx *ctx = req->ctx;
5289 struct async_poll *apoll;
5290 struct io_poll_table ipt;
5294 if (!req->file || !file_can_poll(req->file))
5296 if (req->flags & REQ_F_POLLED)
5300 else if (def->pollout)
5304 /* if we can't nonblock try, then no point in arming a poll handler */
5305 if (!io_file_supports_async(req->file, rw))
5308 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5309 if (unlikely(!apoll))
5311 apoll->double_poll = NULL;
5313 req->flags |= REQ_F_POLLED;
5318 mask |= POLLIN | POLLRDNORM;
5320 mask |= POLLOUT | POLLWRNORM;
5322 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5323 if ((req->opcode == IORING_OP_RECVMSG) &&
5324 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5327 mask |= POLLERR | POLLPRI;
5329 ipt.pt._qproc = io_async_queue_proc;
5331 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5333 if (ret || ipt.error) {
5334 io_poll_remove_double(req);
5335 spin_unlock_irq(&ctx->completion_lock);
5336 kfree(apoll->double_poll);
5340 spin_unlock_irq(&ctx->completion_lock);
5341 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5342 apoll->poll.events);
5346 static bool __io_poll_remove_one(struct io_kiocb *req,
5347 struct io_poll_iocb *poll)
5349 bool do_complete = false;
5351 spin_lock(&poll->head->lock);
5352 WRITE_ONCE(poll->canceled, true);
5353 if (!list_empty(&poll->wait.entry)) {
5354 list_del_init(&poll->wait.entry);
5357 spin_unlock(&poll->head->lock);
5358 hash_del(&req->hash_node);
5362 static bool io_poll_remove_one(struct io_kiocb *req)
5366 io_poll_remove_double(req);
5368 if (req->opcode == IORING_OP_POLL_ADD) {
5369 do_complete = __io_poll_remove_one(req, &req->poll);
5371 struct async_poll *apoll = req->apoll;
5373 /* non-poll requests have submit ref still */
5374 do_complete = __io_poll_remove_one(req, &apoll->poll);
5377 kfree(apoll->double_poll);
5383 io_cqring_fill_event(req, -ECANCELED);
5384 io_commit_cqring(req->ctx);
5385 req_set_fail_links(req);
5386 io_put_req_deferred(req, 1);
5393 * Returns true if we found and killed one or more poll requests
5395 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5396 struct files_struct *files)
5398 struct hlist_node *tmp;
5399 struct io_kiocb *req;
5402 spin_lock_irq(&ctx->completion_lock);
5403 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5404 struct hlist_head *list;
5406 list = &ctx->cancel_hash[i];
5407 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5408 if (io_match_task(req, tsk, files))
5409 posted += io_poll_remove_one(req);
5412 spin_unlock_irq(&ctx->completion_lock);
5415 io_cqring_ev_posted(ctx);
5420 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5422 struct hlist_head *list;
5423 struct io_kiocb *req;
5425 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5426 hlist_for_each_entry(req, list, hash_node) {
5427 if (sqe_addr != req->user_data)
5429 if (io_poll_remove_one(req))
5437 static int io_poll_remove_prep(struct io_kiocb *req,
5438 const struct io_uring_sqe *sqe)
5440 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5442 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5446 req->poll_remove.addr = READ_ONCE(sqe->addr);
5451 * Find a running poll command that matches one specified in sqe->addr,
5452 * and remove it if found.
5454 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5456 struct io_ring_ctx *ctx = req->ctx;
5459 spin_lock_irq(&ctx->completion_lock);
5460 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5461 spin_unlock_irq(&ctx->completion_lock);
5464 req_set_fail_links(req);
5465 io_req_complete(req, ret);
5469 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5472 struct io_kiocb *req = wait->private;
5473 struct io_poll_iocb *poll = &req->poll;
5475 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5478 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5479 struct poll_table_struct *p)
5481 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5483 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5486 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5488 struct io_poll_iocb *poll = &req->poll;
5491 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5493 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5496 events = READ_ONCE(sqe->poll32_events);
5498 events = swahw32(events);
5500 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5501 (events & EPOLLEXCLUSIVE);
5505 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5507 struct io_poll_iocb *poll = &req->poll;
5508 struct io_ring_ctx *ctx = req->ctx;
5509 struct io_poll_table ipt;
5512 ipt.pt._qproc = io_poll_queue_proc;
5514 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5517 if (mask) { /* no async, we'd stolen it */
5519 io_poll_complete(req, mask, 0);
5521 spin_unlock_irq(&ctx->completion_lock);
5524 io_cqring_ev_posted(ctx);
5530 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5532 struct io_timeout_data *data = container_of(timer,
5533 struct io_timeout_data, timer);
5534 struct io_kiocb *req = data->req;
5535 struct io_ring_ctx *ctx = req->ctx;
5536 unsigned long flags;
5538 spin_lock_irqsave(&ctx->completion_lock, flags);
5539 list_del_init(&req->timeout.list);
5540 atomic_set(&req->ctx->cq_timeouts,
5541 atomic_read(&req->ctx->cq_timeouts) + 1);
5543 io_cqring_fill_event(req, -ETIME);
5544 io_commit_cqring(ctx);
5545 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5547 io_cqring_ev_posted(ctx);
5548 req_set_fail_links(req);
5550 return HRTIMER_NORESTART;
5553 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5556 struct io_timeout_data *io;
5557 struct io_kiocb *req;
5560 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5561 if (user_data == req->user_data) {
5568 return ERR_PTR(ret);
5570 io = req->async_data;
5571 ret = hrtimer_try_to_cancel(&io->timer);
5573 return ERR_PTR(-EALREADY);
5574 list_del_init(&req->timeout.list);
5578 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5580 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5583 return PTR_ERR(req);
5585 req_set_fail_links(req);
5586 io_cqring_fill_event(req, -ECANCELED);
5587 io_put_req_deferred(req, 1);
5591 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5592 struct timespec64 *ts, enum hrtimer_mode mode)
5594 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5595 struct io_timeout_data *data;
5598 return PTR_ERR(req);
5600 req->timeout.off = 0; /* noseq */
5601 data = req->async_data;
5602 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5603 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5604 data->timer.function = io_timeout_fn;
5605 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5609 static int io_timeout_remove_prep(struct io_kiocb *req,
5610 const struct io_uring_sqe *sqe)
5612 struct io_timeout_rem *tr = &req->timeout_rem;
5614 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5616 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5618 if (sqe->ioprio || sqe->buf_index || sqe->len)
5621 tr->addr = READ_ONCE(sqe->addr);
5622 tr->flags = READ_ONCE(sqe->timeout_flags);
5623 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5624 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5626 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5628 } else if (tr->flags) {
5629 /* timeout removal doesn't support flags */
5636 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5638 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5643 * Remove or update an existing timeout command
5645 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5647 struct io_timeout_rem *tr = &req->timeout_rem;
5648 struct io_ring_ctx *ctx = req->ctx;
5651 spin_lock_irq(&ctx->completion_lock);
5652 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5653 ret = io_timeout_cancel(ctx, tr->addr);
5655 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5656 io_translate_timeout_mode(tr->flags));
5658 io_cqring_fill_event(req, ret);
5659 io_commit_cqring(ctx);
5660 spin_unlock_irq(&ctx->completion_lock);
5661 io_cqring_ev_posted(ctx);
5663 req_set_fail_links(req);
5668 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5669 bool is_timeout_link)
5671 struct io_timeout_data *data;
5673 u32 off = READ_ONCE(sqe->off);
5675 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5677 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5679 if (off && is_timeout_link)
5681 flags = READ_ONCE(sqe->timeout_flags);
5682 if (flags & ~IORING_TIMEOUT_ABS)
5685 req->timeout.off = off;
5687 if (!req->async_data && io_alloc_async_data(req))
5690 data = req->async_data;
5693 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5696 data->mode = io_translate_timeout_mode(flags);
5697 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5701 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5703 struct io_ring_ctx *ctx = req->ctx;
5704 struct io_timeout_data *data = req->async_data;
5705 struct list_head *entry;
5706 u32 tail, off = req->timeout.off;
5708 spin_lock_irq(&ctx->completion_lock);
5711 * sqe->off holds how many events that need to occur for this
5712 * timeout event to be satisfied. If it isn't set, then this is
5713 * a pure timeout request, sequence isn't used.
5715 if (io_is_timeout_noseq(req)) {
5716 entry = ctx->timeout_list.prev;
5720 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5721 req->timeout.target_seq = tail + off;
5723 /* Update the last seq here in case io_flush_timeouts() hasn't.
5724 * This is safe because ->completion_lock is held, and submissions
5725 * and completions are never mixed in the same ->completion_lock section.
5727 ctx->cq_last_tm_flush = tail;
5730 * Insertion sort, ensuring the first entry in the list is always
5731 * the one we need first.
5733 list_for_each_prev(entry, &ctx->timeout_list) {
5734 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5737 if (io_is_timeout_noseq(nxt))
5739 /* nxt.seq is behind @tail, otherwise would've been completed */
5740 if (off >= nxt->timeout.target_seq - tail)
5744 list_add(&req->timeout.list, entry);
5745 data->timer.function = io_timeout_fn;
5746 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5747 spin_unlock_irq(&ctx->completion_lock);
5751 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5753 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5755 return req->user_data == (unsigned long) data;
5758 static int io_async_cancel_one(struct io_uring_task *tctx, void *sqe_addr)
5760 enum io_wq_cancel cancel_ret;
5766 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, sqe_addr, false);
5767 switch (cancel_ret) {
5768 case IO_WQ_CANCEL_OK:
5771 case IO_WQ_CANCEL_RUNNING:
5774 case IO_WQ_CANCEL_NOTFOUND:
5782 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5783 struct io_kiocb *req, __u64 sqe_addr,
5786 unsigned long flags;
5789 ret = io_async_cancel_one(req->task->io_uring,
5790 (void *) (unsigned long) sqe_addr);
5791 if (ret != -ENOENT) {
5792 spin_lock_irqsave(&ctx->completion_lock, flags);
5796 spin_lock_irqsave(&ctx->completion_lock, flags);
5797 ret = io_timeout_cancel(ctx, sqe_addr);
5800 ret = io_poll_cancel(ctx, sqe_addr);
5804 io_cqring_fill_event(req, ret);
5805 io_commit_cqring(ctx);
5806 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5807 io_cqring_ev_posted(ctx);
5810 req_set_fail_links(req);
5814 static int io_async_cancel_prep(struct io_kiocb *req,
5815 const struct io_uring_sqe *sqe)
5817 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5819 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5821 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5824 req->cancel.addr = READ_ONCE(sqe->addr);
5828 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5830 struct io_ring_ctx *ctx = req->ctx;
5832 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5836 static int io_rsrc_update_prep(struct io_kiocb *req,
5837 const struct io_uring_sqe *sqe)
5839 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5841 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5843 if (sqe->ioprio || sqe->rw_flags)
5846 req->rsrc_update.offset = READ_ONCE(sqe->off);
5847 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5848 if (!req->rsrc_update.nr_args)
5850 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5854 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5856 struct io_ring_ctx *ctx = req->ctx;
5857 struct io_uring_rsrc_update up;
5860 if (issue_flags & IO_URING_F_NONBLOCK)
5863 up.offset = req->rsrc_update.offset;
5864 up.data = req->rsrc_update.arg;
5866 mutex_lock(&ctx->uring_lock);
5867 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5868 mutex_unlock(&ctx->uring_lock);
5871 req_set_fail_links(req);
5872 __io_req_complete(req, issue_flags, ret, 0);
5876 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5878 switch (req->opcode) {
5881 case IORING_OP_READV:
5882 case IORING_OP_READ_FIXED:
5883 case IORING_OP_READ:
5884 return io_read_prep(req, sqe);
5885 case IORING_OP_WRITEV:
5886 case IORING_OP_WRITE_FIXED:
5887 case IORING_OP_WRITE:
5888 return io_write_prep(req, sqe);
5889 case IORING_OP_POLL_ADD:
5890 return io_poll_add_prep(req, sqe);
5891 case IORING_OP_POLL_REMOVE:
5892 return io_poll_remove_prep(req, sqe);
5893 case IORING_OP_FSYNC:
5894 return io_fsync_prep(req, sqe);
5895 case IORING_OP_SYNC_FILE_RANGE:
5896 return io_sfr_prep(req, sqe);
5897 case IORING_OP_SENDMSG:
5898 case IORING_OP_SEND:
5899 return io_sendmsg_prep(req, sqe);
5900 case IORING_OP_RECVMSG:
5901 case IORING_OP_RECV:
5902 return io_recvmsg_prep(req, sqe);
5903 case IORING_OP_CONNECT:
5904 return io_connect_prep(req, sqe);
5905 case IORING_OP_TIMEOUT:
5906 return io_timeout_prep(req, sqe, false);
5907 case IORING_OP_TIMEOUT_REMOVE:
5908 return io_timeout_remove_prep(req, sqe);
5909 case IORING_OP_ASYNC_CANCEL:
5910 return io_async_cancel_prep(req, sqe);
5911 case IORING_OP_LINK_TIMEOUT:
5912 return io_timeout_prep(req, sqe, true);
5913 case IORING_OP_ACCEPT:
5914 return io_accept_prep(req, sqe);
5915 case IORING_OP_FALLOCATE:
5916 return io_fallocate_prep(req, sqe);
5917 case IORING_OP_OPENAT:
5918 return io_openat_prep(req, sqe);
5919 case IORING_OP_CLOSE:
5920 return io_close_prep(req, sqe);
5921 case IORING_OP_FILES_UPDATE:
5922 return io_rsrc_update_prep(req, sqe);
5923 case IORING_OP_STATX:
5924 return io_statx_prep(req, sqe);
5925 case IORING_OP_FADVISE:
5926 return io_fadvise_prep(req, sqe);
5927 case IORING_OP_MADVISE:
5928 return io_madvise_prep(req, sqe);
5929 case IORING_OP_OPENAT2:
5930 return io_openat2_prep(req, sqe);
5931 case IORING_OP_EPOLL_CTL:
5932 return io_epoll_ctl_prep(req, sqe);
5933 case IORING_OP_SPLICE:
5934 return io_splice_prep(req, sqe);
5935 case IORING_OP_PROVIDE_BUFFERS:
5936 return io_provide_buffers_prep(req, sqe);
5937 case IORING_OP_REMOVE_BUFFERS:
5938 return io_remove_buffers_prep(req, sqe);
5940 return io_tee_prep(req, sqe);
5941 case IORING_OP_SHUTDOWN:
5942 return io_shutdown_prep(req, sqe);
5943 case IORING_OP_RENAMEAT:
5944 return io_renameat_prep(req, sqe);
5945 case IORING_OP_UNLINKAT:
5946 return io_unlinkat_prep(req, sqe);
5949 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5954 static int io_req_prep_async(struct io_kiocb *req)
5956 switch (req->opcode) {
5957 case IORING_OP_READV:
5958 case IORING_OP_READ_FIXED:
5959 case IORING_OP_READ:
5960 return io_rw_prep_async(req, READ);
5961 case IORING_OP_WRITEV:
5962 case IORING_OP_WRITE_FIXED:
5963 case IORING_OP_WRITE:
5964 return io_rw_prep_async(req, WRITE);
5965 case IORING_OP_SENDMSG:
5966 case IORING_OP_SEND:
5967 return io_sendmsg_prep_async(req);
5968 case IORING_OP_RECVMSG:
5969 case IORING_OP_RECV:
5970 return io_recvmsg_prep_async(req);
5971 case IORING_OP_CONNECT:
5972 return io_connect_prep_async(req);
5977 static int io_req_defer_prep(struct io_kiocb *req)
5979 if (!io_op_defs[req->opcode].needs_async_data)
5981 /* some opcodes init it during the inital prep */
5982 if (req->async_data)
5984 if (__io_alloc_async_data(req))
5986 return io_req_prep_async(req);
5989 static u32 io_get_sequence(struct io_kiocb *req)
5991 struct io_kiocb *pos;
5992 struct io_ring_ctx *ctx = req->ctx;
5993 u32 total_submitted, nr_reqs = 0;
5995 io_for_each_link(pos, req)
5998 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5999 return total_submitted - nr_reqs;
6002 static int io_req_defer(struct io_kiocb *req)
6004 struct io_ring_ctx *ctx = req->ctx;
6005 struct io_defer_entry *de;
6009 /* Still need defer if there is pending req in defer list. */
6010 if (likely(list_empty_careful(&ctx->defer_list) &&
6011 !(req->flags & REQ_F_IO_DRAIN)))
6014 seq = io_get_sequence(req);
6015 /* Still a chance to pass the sequence check */
6016 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6019 ret = io_req_defer_prep(req);
6022 io_prep_async_link(req);
6023 de = kmalloc(sizeof(*de), GFP_KERNEL);
6027 spin_lock_irq(&ctx->completion_lock);
6028 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6029 spin_unlock_irq(&ctx->completion_lock);
6031 io_queue_async_work(req);
6032 return -EIOCBQUEUED;
6035 trace_io_uring_defer(ctx, req, req->user_data);
6038 list_add_tail(&de->list, &ctx->defer_list);
6039 spin_unlock_irq(&ctx->completion_lock);
6040 return -EIOCBQUEUED;
6043 static void __io_clean_op(struct io_kiocb *req)
6045 if (req->flags & REQ_F_BUFFER_SELECTED) {
6046 switch (req->opcode) {
6047 case IORING_OP_READV:
6048 case IORING_OP_READ_FIXED:
6049 case IORING_OP_READ:
6050 kfree((void *)(unsigned long)req->rw.addr);
6052 case IORING_OP_RECVMSG:
6053 case IORING_OP_RECV:
6054 kfree(req->sr_msg.kbuf);
6057 req->flags &= ~REQ_F_BUFFER_SELECTED;
6060 if (req->flags & REQ_F_NEED_CLEANUP) {
6061 switch (req->opcode) {
6062 case IORING_OP_READV:
6063 case IORING_OP_READ_FIXED:
6064 case IORING_OP_READ:
6065 case IORING_OP_WRITEV:
6066 case IORING_OP_WRITE_FIXED:
6067 case IORING_OP_WRITE: {
6068 struct io_async_rw *io = req->async_data;
6070 kfree(io->free_iovec);
6073 case IORING_OP_RECVMSG:
6074 case IORING_OP_SENDMSG: {
6075 struct io_async_msghdr *io = req->async_data;
6077 kfree(io->free_iov);
6080 case IORING_OP_SPLICE:
6082 io_put_file(req, req->splice.file_in,
6083 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
6085 case IORING_OP_OPENAT:
6086 case IORING_OP_OPENAT2:
6087 if (req->open.filename)
6088 putname(req->open.filename);
6090 case IORING_OP_RENAMEAT:
6091 putname(req->rename.oldpath);
6092 putname(req->rename.newpath);
6094 case IORING_OP_UNLINKAT:
6095 putname(req->unlink.filename);
6098 req->flags &= ~REQ_F_NEED_CLEANUP;
6102 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6104 struct io_ring_ctx *ctx = req->ctx;
6107 switch (req->opcode) {
6109 ret = io_nop(req, issue_flags);
6111 case IORING_OP_READV:
6112 case IORING_OP_READ_FIXED:
6113 case IORING_OP_READ:
6114 ret = io_read(req, issue_flags);
6116 case IORING_OP_WRITEV:
6117 case IORING_OP_WRITE_FIXED:
6118 case IORING_OP_WRITE:
6119 ret = io_write(req, issue_flags);
6121 case IORING_OP_FSYNC:
6122 ret = io_fsync(req, issue_flags);
6124 case IORING_OP_POLL_ADD:
6125 ret = io_poll_add(req, issue_flags);
6127 case IORING_OP_POLL_REMOVE:
6128 ret = io_poll_remove(req, issue_flags);
6130 case IORING_OP_SYNC_FILE_RANGE:
6131 ret = io_sync_file_range(req, issue_flags);
6133 case IORING_OP_SENDMSG:
6134 ret = io_sendmsg(req, issue_flags);
6136 case IORING_OP_SEND:
6137 ret = io_send(req, issue_flags);
6139 case IORING_OP_RECVMSG:
6140 ret = io_recvmsg(req, issue_flags);
6142 case IORING_OP_RECV:
6143 ret = io_recv(req, issue_flags);
6145 case IORING_OP_TIMEOUT:
6146 ret = io_timeout(req, issue_flags);
6148 case IORING_OP_TIMEOUT_REMOVE:
6149 ret = io_timeout_remove(req, issue_flags);
6151 case IORING_OP_ACCEPT:
6152 ret = io_accept(req, issue_flags);
6154 case IORING_OP_CONNECT:
6155 ret = io_connect(req, issue_flags);
6157 case IORING_OP_ASYNC_CANCEL:
6158 ret = io_async_cancel(req, issue_flags);
6160 case IORING_OP_FALLOCATE:
6161 ret = io_fallocate(req, issue_flags);
6163 case IORING_OP_OPENAT:
6164 ret = io_openat(req, issue_flags);
6166 case IORING_OP_CLOSE:
6167 ret = io_close(req, issue_flags);
6169 case IORING_OP_FILES_UPDATE:
6170 ret = io_files_update(req, issue_flags);
6172 case IORING_OP_STATX:
6173 ret = io_statx(req, issue_flags);
6175 case IORING_OP_FADVISE:
6176 ret = io_fadvise(req, issue_flags);
6178 case IORING_OP_MADVISE:
6179 ret = io_madvise(req, issue_flags);
6181 case IORING_OP_OPENAT2:
6182 ret = io_openat2(req, issue_flags);
6184 case IORING_OP_EPOLL_CTL:
6185 ret = io_epoll_ctl(req, issue_flags);
6187 case IORING_OP_SPLICE:
6188 ret = io_splice(req, issue_flags);
6190 case IORING_OP_PROVIDE_BUFFERS:
6191 ret = io_provide_buffers(req, issue_flags);
6193 case IORING_OP_REMOVE_BUFFERS:
6194 ret = io_remove_buffers(req, issue_flags);
6197 ret = io_tee(req, issue_flags);
6199 case IORING_OP_SHUTDOWN:
6200 ret = io_shutdown(req, issue_flags);
6202 case IORING_OP_RENAMEAT:
6203 ret = io_renameat(req, issue_flags);
6205 case IORING_OP_UNLINKAT:
6206 ret = io_unlinkat(req, issue_flags);
6216 /* If the op doesn't have a file, we're not polling for it */
6217 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6218 const bool in_async = io_wq_current_is_worker();
6220 /* workqueue context doesn't hold uring_lock, grab it now */
6222 mutex_lock(&ctx->uring_lock);
6224 io_iopoll_req_issued(req, in_async);
6227 mutex_unlock(&ctx->uring_lock);
6233 static void io_wq_submit_work(struct io_wq_work *work)
6235 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6236 struct io_kiocb *timeout;
6239 timeout = io_prep_linked_timeout(req);
6241 io_queue_linked_timeout(timeout);
6243 if (work->flags & IO_WQ_WORK_CANCEL)
6248 ret = io_issue_sqe(req, 0);
6250 * We can get EAGAIN for polled IO even though we're
6251 * forcing a sync submission from here, since we can't
6252 * wait for request slots on the block side.
6260 /* avoid locking problems by failing it from a clean context */
6262 /* io-wq is going to take one down */
6263 refcount_inc(&req->refs);
6264 io_req_task_queue_fail(req, ret);
6268 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6271 struct fixed_rsrc_table *table;
6273 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6274 return table->files[index & IORING_FILE_TABLE_MASK];
6277 static struct file *io_file_get(struct io_submit_state *state,
6278 struct io_kiocb *req, int fd, bool fixed)
6280 struct io_ring_ctx *ctx = req->ctx;
6284 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6286 fd = array_index_nospec(fd, ctx->nr_user_files);
6287 file = io_file_from_index(ctx, fd);
6288 io_set_resource_node(req);
6290 trace_io_uring_file_get(ctx, fd);
6291 file = __io_file_get(state, fd);
6294 if (file && unlikely(file->f_op == &io_uring_fops))
6295 io_req_track_inflight(req);
6299 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6301 struct io_timeout_data *data = container_of(timer,
6302 struct io_timeout_data, timer);
6303 struct io_kiocb *prev, *req = data->req;
6304 struct io_ring_ctx *ctx = req->ctx;
6305 unsigned long flags;
6307 spin_lock_irqsave(&ctx->completion_lock, flags);
6308 prev = req->timeout.head;
6309 req->timeout.head = NULL;
6312 * We don't expect the list to be empty, that will only happen if we
6313 * race with the completion of the linked work.
6315 if (prev && refcount_inc_not_zero(&prev->refs))
6316 io_remove_next_linked(prev);
6319 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6322 req_set_fail_links(prev);
6323 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6324 io_put_req_deferred(prev, 1);
6326 io_req_complete_post(req, -ETIME, 0);
6327 io_put_req_deferred(req, 1);
6329 return HRTIMER_NORESTART;
6332 static void __io_queue_linked_timeout(struct io_kiocb *req)
6335 * If the back reference is NULL, then our linked request finished
6336 * before we got a chance to setup the timer
6338 if (req->timeout.head) {
6339 struct io_timeout_data *data = req->async_data;
6341 data->timer.function = io_link_timeout_fn;
6342 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6347 static void io_queue_linked_timeout(struct io_kiocb *req)
6349 struct io_ring_ctx *ctx = req->ctx;
6351 spin_lock_irq(&ctx->completion_lock);
6352 __io_queue_linked_timeout(req);
6353 spin_unlock_irq(&ctx->completion_lock);
6355 /* drop submission reference */
6359 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6361 struct io_kiocb *nxt = req->link;
6363 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6364 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6367 nxt->timeout.head = req;
6368 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6369 req->flags |= REQ_F_LINK_TIMEOUT;
6373 static void __io_queue_sqe(struct io_kiocb *req)
6375 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6376 const struct cred *old_creds = NULL;
6379 if ((req->flags & REQ_F_WORK_INITIALIZED) &&
6380 req->work.identity->creds != current_cred())
6381 old_creds = override_creds(req->work.identity->creds);
6383 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6386 revert_creds(old_creds);
6389 * We async punt it if the file wasn't marked NOWAIT, or if the file
6390 * doesn't support non-blocking read/write attempts
6392 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6393 if (!io_arm_poll_handler(req)) {
6395 * Queued up for async execution, worker will release
6396 * submit reference when the iocb is actually submitted.
6398 io_queue_async_work(req);
6400 } else if (likely(!ret)) {
6401 /* drop submission reference */
6402 if (req->flags & REQ_F_COMPLETE_INLINE) {
6403 struct io_ring_ctx *ctx = req->ctx;
6404 struct io_comp_state *cs = &ctx->submit_state.comp;
6406 cs->reqs[cs->nr++] = req;
6407 if (cs->nr == ARRAY_SIZE(cs->reqs))
6408 io_submit_flush_completions(cs, ctx);
6413 req_set_fail_links(req);
6415 io_req_complete(req, ret);
6418 io_queue_linked_timeout(linked_timeout);
6421 static void io_queue_sqe(struct io_kiocb *req)
6425 ret = io_req_defer(req);
6427 if (ret != -EIOCBQUEUED) {
6429 req_set_fail_links(req);
6431 io_req_complete(req, ret);
6433 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6434 ret = io_req_defer_prep(req);
6437 io_queue_async_work(req);
6439 __io_queue_sqe(req);
6444 * Check SQE restrictions (opcode and flags).
6446 * Returns 'true' if SQE is allowed, 'false' otherwise.
6448 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6449 struct io_kiocb *req,
6450 unsigned int sqe_flags)
6452 if (!ctx->restricted)
6455 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6458 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6459 ctx->restrictions.sqe_flags_required)
6462 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6463 ctx->restrictions.sqe_flags_required))
6469 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6470 const struct io_uring_sqe *sqe)
6472 struct io_submit_state *state;
6473 unsigned int sqe_flags;
6476 req->opcode = READ_ONCE(sqe->opcode);
6477 /* same numerical values with corresponding REQ_F_*, safe to copy */
6478 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6479 req->user_data = READ_ONCE(sqe->user_data);
6480 req->async_data = NULL;
6484 req->fixed_rsrc_refs = NULL;
6485 /* one is dropped after submission, the other at completion */
6486 refcount_set(&req->refs, 2);
6487 req->task = current;
6490 /* enforce forwards compatibility on users */
6491 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6496 if (unlikely(req->opcode >= IORING_OP_LAST))
6499 if (unlikely(io_sq_thread_acquire_mm_files(ctx, req)))
6502 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6505 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6506 !io_op_defs[req->opcode].buffer_select)
6509 id = READ_ONCE(sqe->personality);
6511 struct io_identity *iod;
6513 iod = idr_find(&ctx->personality_idr, id);
6516 refcount_inc(&iod->count);
6518 __io_req_init_async(req);
6519 get_cred(iod->creds);
6520 req->work.identity = iod;
6523 state = &ctx->submit_state;
6526 * Plug now if we have more than 1 IO left after this, and the target
6527 * is potentially a read/write to block based storage.
6529 if (!state->plug_started && state->ios_left > 1 &&
6530 io_op_defs[req->opcode].plug) {
6531 blk_start_plug(&state->plug);
6532 state->plug_started = true;
6535 if (io_op_defs[req->opcode].needs_file) {
6536 bool fixed = req->flags & REQ_F_FIXED_FILE;
6538 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6539 if (unlikely(!req->file))
6547 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6548 const struct io_uring_sqe *sqe)
6550 struct io_submit_link *link = &ctx->submit_state.link;
6553 ret = io_init_req(ctx, req, sqe);
6554 if (unlikely(ret)) {
6557 io_req_complete(req, ret);
6559 /* fail even hard links since we don't submit */
6560 link->head->flags |= REQ_F_FAIL_LINK;
6561 io_put_req(link->head);
6562 io_req_complete(link->head, -ECANCELED);
6567 ret = io_req_prep(req, sqe);
6571 /* don't need @sqe from now on */
6572 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6573 true, ctx->flags & IORING_SETUP_SQPOLL);
6576 * If we already have a head request, queue this one for async
6577 * submittal once the head completes. If we don't have a head but
6578 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6579 * submitted sync once the chain is complete. If none of those
6580 * conditions are true (normal request), then just queue it.
6583 struct io_kiocb *head = link->head;
6586 * Taking sequential execution of a link, draining both sides
6587 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6588 * requests in the link. So, it drains the head and the
6589 * next after the link request. The last one is done via
6590 * drain_next flag to persist the effect across calls.
6592 if (req->flags & REQ_F_IO_DRAIN) {
6593 head->flags |= REQ_F_IO_DRAIN;
6594 ctx->drain_next = 1;
6596 ret = io_req_defer_prep(req);
6599 trace_io_uring_link(ctx, req, head);
6600 link->last->link = req;
6603 /* last request of a link, enqueue the link */
6604 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6609 if (unlikely(ctx->drain_next)) {
6610 req->flags |= REQ_F_IO_DRAIN;
6611 ctx->drain_next = 0;
6613 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6625 * Batched submission is done, ensure local IO is flushed out.
6627 static void io_submit_state_end(struct io_submit_state *state,
6628 struct io_ring_ctx *ctx)
6630 if (state->link.head)
6631 io_queue_sqe(state->link.head);
6633 io_submit_flush_completions(&state->comp, ctx);
6634 if (state->plug_started)
6635 blk_finish_plug(&state->plug);
6636 io_state_file_put(state);
6640 * Start submission side cache.
6642 static void io_submit_state_start(struct io_submit_state *state,
6643 unsigned int max_ios)
6645 state->plug_started = false;
6646 state->ios_left = max_ios;
6647 /* set only head, no need to init link_last in advance */
6648 state->link.head = NULL;
6651 static void io_commit_sqring(struct io_ring_ctx *ctx)
6653 struct io_rings *rings = ctx->rings;
6656 * Ensure any loads from the SQEs are done at this point,
6657 * since once we write the new head, the application could
6658 * write new data to them.
6660 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6664 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6665 * that is mapped by userspace. This means that care needs to be taken to
6666 * ensure that reads are stable, as we cannot rely on userspace always
6667 * being a good citizen. If members of the sqe are validated and then later
6668 * used, it's important that those reads are done through READ_ONCE() to
6669 * prevent a re-load down the line.
6671 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6673 u32 *sq_array = ctx->sq_array;
6677 * The cached sq head (or cq tail) serves two purposes:
6679 * 1) allows us to batch the cost of updating the user visible
6681 * 2) allows the kernel side to track the head on its own, even
6682 * though the application is the one updating it.
6684 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6685 if (likely(head < ctx->sq_entries))
6686 return &ctx->sq_sqes[head];
6688 /* drop invalid entries */
6689 ctx->cached_sq_dropped++;
6690 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6694 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6698 /* if we have a backlog and couldn't flush it all, return BUSY */
6699 if (test_bit(0, &ctx->sq_check_overflow)) {
6700 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6704 /* make sure SQ entry isn't read before tail */
6705 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6707 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6710 percpu_counter_add(¤t->io_uring->inflight, nr);
6711 refcount_add(nr, ¤t->usage);
6712 io_submit_state_start(&ctx->submit_state, nr);
6714 while (submitted < nr) {
6715 const struct io_uring_sqe *sqe;
6716 struct io_kiocb *req;
6718 req = io_alloc_req(ctx);
6719 if (unlikely(!req)) {
6721 submitted = -EAGAIN;
6724 sqe = io_get_sqe(ctx);
6725 if (unlikely(!sqe)) {
6726 kmem_cache_free(req_cachep, req);
6729 /* will complete beyond this point, count as submitted */
6731 if (io_submit_sqe(ctx, req, sqe))
6735 if (unlikely(submitted != nr)) {
6736 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6737 struct io_uring_task *tctx = current->io_uring;
6738 int unused = nr - ref_used;
6740 percpu_ref_put_many(&ctx->refs, unused);
6741 percpu_counter_sub(&tctx->inflight, unused);
6742 put_task_struct_many(current, unused);
6745 io_submit_state_end(&ctx->submit_state, ctx);
6746 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6747 io_commit_sqring(ctx);
6752 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6754 /* Tell userspace we may need a wakeup call */
6755 spin_lock_irq(&ctx->completion_lock);
6756 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6757 spin_unlock_irq(&ctx->completion_lock);
6760 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6762 spin_lock_irq(&ctx->completion_lock);
6763 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6764 spin_unlock_irq(&ctx->completion_lock);
6767 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6769 unsigned int to_submit;
6772 to_submit = io_sqring_entries(ctx);
6773 /* if we're handling multiple rings, cap submit size for fairness */
6774 if (cap_entries && to_submit > 8)
6777 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6778 unsigned nr_events = 0;
6780 mutex_lock(&ctx->uring_lock);
6781 if (!list_empty(&ctx->iopoll_list))
6782 io_do_iopoll(ctx, &nr_events, 0);
6784 if (to_submit && !ctx->sqo_dead &&
6785 likely(!percpu_ref_is_dying(&ctx->refs)))
6786 ret = io_submit_sqes(ctx, to_submit);
6787 mutex_unlock(&ctx->uring_lock);
6790 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6791 wake_up(&ctx->sqo_sq_wait);
6796 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6798 struct io_ring_ctx *ctx;
6799 unsigned sq_thread_idle = 0;
6801 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6802 if (sq_thread_idle < ctx->sq_thread_idle)
6803 sq_thread_idle = ctx->sq_thread_idle;
6806 sqd->sq_thread_idle = sq_thread_idle;
6809 static void io_sqd_init_new(struct io_sq_data *sqd)
6811 struct io_ring_ctx *ctx;
6813 while (!list_empty(&sqd->ctx_new_list)) {
6814 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6815 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6816 complete(&ctx->sq_thread_comp);
6819 io_sqd_update_thread_idle(sqd);
6822 static int io_sq_thread(void *data)
6824 struct cgroup_subsys_state *cur_css = NULL;
6825 struct files_struct *old_files = current->files;
6826 struct nsproxy *old_nsproxy = current->nsproxy;
6827 const struct cred *old_cred = NULL;
6828 struct io_sq_data *sqd = data;
6829 struct io_ring_ctx *ctx;
6830 unsigned long timeout = 0;
6834 current->files = NULL;
6835 current->nsproxy = NULL;
6836 task_unlock(current);
6838 while (!kthread_should_stop()) {
6840 bool cap_entries, sqt_spin, needs_sched;
6843 * Any changes to the sqd lists are synchronized through the
6844 * kthread parking. This synchronizes the thread vs users,
6845 * the users are synchronized on the sqd->ctx_lock.
6847 if (kthread_should_park()) {
6850 * When sq thread is unparked, in case the previous park operation
6851 * comes from io_put_sq_data(), which means that sq thread is going
6852 * to be stopped, so here needs to have a check.
6854 if (kthread_should_stop())
6858 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
6859 io_sqd_init_new(sqd);
6860 timeout = jiffies + sqd->sq_thread_idle;
6864 cap_entries = !list_is_singular(&sqd->ctx_list);
6865 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6866 if (current->cred != ctx->creds) {
6868 revert_creds(old_cred);
6869 old_cred = override_creds(ctx->creds);
6871 io_sq_thread_associate_blkcg(ctx, &cur_css);
6873 current->loginuid = ctx->loginuid;
6874 current->sessionid = ctx->sessionid;
6877 ret = __io_sq_thread(ctx, cap_entries);
6878 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6881 io_sq_thread_drop_mm_files();
6884 if (sqt_spin || !time_after(jiffies, timeout)) {
6886 io_sq_thread_drop_mm_files();
6889 timeout = jiffies + sqd->sq_thread_idle;
6894 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6895 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6896 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6897 !list_empty_careful(&ctx->iopoll_list)) {
6898 needs_sched = false;
6901 if (io_sqring_entries(ctx)) {
6902 needs_sched = false;
6907 if (needs_sched && !kthread_should_park()) {
6908 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6909 io_ring_set_wakeup_flag(ctx);
6912 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6913 io_ring_clear_wakeup_flag(ctx);
6916 finish_wait(&sqd->wait, &wait);
6917 timeout = jiffies + sqd->sq_thread_idle;
6921 io_sq_thread_drop_mm_files();
6924 io_sq_thread_unassociate_blkcg();
6926 revert_creds(old_cred);
6929 current->files = old_files;
6930 current->nsproxy = old_nsproxy;
6931 task_unlock(current);
6938 struct io_wait_queue {
6939 struct wait_queue_entry wq;
6940 struct io_ring_ctx *ctx;
6942 unsigned nr_timeouts;
6945 static inline bool io_should_wake(struct io_wait_queue *iowq)
6947 struct io_ring_ctx *ctx = iowq->ctx;
6950 * Wake up if we have enough events, or if a timeout occurred since we
6951 * started waiting. For timeouts, we always want to return to userspace,
6952 * regardless of event count.
6954 return io_cqring_events(ctx) >= iowq->to_wait ||
6955 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6958 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6959 int wake_flags, void *key)
6961 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6965 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6966 * the task, and the next invocation will do it.
6968 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6969 return autoremove_wake_function(curr, mode, wake_flags, key);
6973 static int io_run_task_work_sig(void)
6975 if (io_run_task_work())
6977 if (!signal_pending(current))
6979 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
6980 return -ERESTARTSYS;
6984 /* when returns >0, the caller should retry */
6985 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6986 struct io_wait_queue *iowq,
6987 signed long *timeout)
6991 /* make sure we run task_work before checking for signals */
6992 ret = io_run_task_work_sig();
6993 if (ret || io_should_wake(iowq))
6995 /* let the caller flush overflows, retry */
6996 if (test_bit(0, &ctx->cq_check_overflow))
6999 *timeout = schedule_timeout(*timeout);
7000 return !*timeout ? -ETIME : 1;
7004 * Wait until events become available, if we don't already have some. The
7005 * application must reap them itself, as they reside on the shared cq ring.
7007 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7008 const sigset_t __user *sig, size_t sigsz,
7009 struct __kernel_timespec __user *uts)
7011 struct io_wait_queue iowq = {
7014 .func = io_wake_function,
7015 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7018 .to_wait = min_events,
7020 struct io_rings *rings = ctx->rings;
7021 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7025 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7026 if (io_cqring_events(ctx) >= min_events)
7028 if (!io_run_task_work())
7033 #ifdef CONFIG_COMPAT
7034 if (in_compat_syscall())
7035 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7039 ret = set_user_sigmask(sig, sigsz);
7046 struct timespec64 ts;
7048 if (get_timespec64(&ts, uts))
7050 timeout = timespec64_to_jiffies(&ts);
7053 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7054 trace_io_uring_cqring_wait(ctx, min_events);
7056 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7057 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7058 TASK_INTERRUPTIBLE);
7059 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7060 finish_wait(&ctx->wait, &iowq.wq);
7063 restore_saved_sigmask_unless(ret == -EINTR);
7065 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7068 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7070 #if defined(CONFIG_UNIX)
7071 if (ctx->ring_sock) {
7072 struct sock *sock = ctx->ring_sock->sk;
7073 struct sk_buff *skb;
7075 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7081 for (i = 0; i < ctx->nr_user_files; i++) {
7084 file = io_file_from_index(ctx, i);
7091 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7093 struct fixed_rsrc_data *data;
7095 data = container_of(ref, struct fixed_rsrc_data, refs);
7096 complete(&data->done);
7099 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7101 spin_lock_bh(&ctx->rsrc_ref_lock);
7104 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7106 spin_unlock_bh(&ctx->rsrc_ref_lock);
7109 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
7110 struct fixed_rsrc_data *rsrc_data,
7111 struct fixed_rsrc_ref_node *ref_node)
7113 io_rsrc_ref_lock(ctx);
7114 rsrc_data->node = ref_node;
7115 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
7116 io_rsrc_ref_unlock(ctx);
7117 percpu_ref_get(&rsrc_data->refs);
7120 static void io_sqe_rsrc_kill_node(struct io_ring_ctx *ctx, struct fixed_rsrc_data *data)
7122 struct fixed_rsrc_ref_node *ref_node = NULL;
7124 io_rsrc_ref_lock(ctx);
7125 ref_node = data->node;
7127 io_rsrc_ref_unlock(ctx);
7129 percpu_ref_kill(&ref_node->refs);
7132 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
7133 struct io_ring_ctx *ctx,
7134 void (*rsrc_put)(struct io_ring_ctx *ctx,
7135 struct io_rsrc_put *prsrc))
7137 struct fixed_rsrc_ref_node *backup_node;
7143 data->quiesce = true;
7146 backup_node = alloc_fixed_rsrc_ref_node(ctx);
7149 backup_node->rsrc_data = data;
7150 backup_node->rsrc_put = rsrc_put;
7152 io_sqe_rsrc_kill_node(ctx, data);
7153 percpu_ref_kill(&data->refs);
7154 flush_delayed_work(&ctx->rsrc_put_work);
7156 ret = wait_for_completion_interruptible(&data->done);
7157 if (!ret || !io_refs_resurrect(&data->refs, &data->done))
7160 io_sqe_rsrc_set_node(ctx, data, backup_node);
7162 mutex_unlock(&ctx->uring_lock);
7163 ret = io_run_task_work_sig();
7164 mutex_lock(&ctx->uring_lock);
7166 data->quiesce = false;
7169 destroy_fixed_rsrc_ref_node(backup_node);
7173 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7175 struct fixed_rsrc_data *data;
7177 data = kzalloc(sizeof(*data), GFP_KERNEL);
7181 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7182 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7187 init_completion(&data->done);
7191 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7193 percpu_ref_exit(&data->refs);
7198 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7200 struct fixed_rsrc_data *data = ctx->file_data;
7201 unsigned nr_tables, i;
7205 * percpu_ref_is_dying() is to stop parallel files unregister
7206 * Since we possibly drop uring lock later in this function to
7209 if (!data || percpu_ref_is_dying(&data->refs))
7211 ret = io_rsrc_ref_quiesce(data, ctx, io_ring_file_put);
7215 __io_sqe_files_unregister(ctx);
7216 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7217 for (i = 0; i < nr_tables; i++)
7218 kfree(data->table[i].files);
7219 free_fixed_rsrc_data(data);
7220 ctx->file_data = NULL;
7221 ctx->nr_user_files = 0;
7225 static void io_put_sq_data(struct io_sq_data *sqd)
7227 if (refcount_dec_and_test(&sqd->refs)) {
7229 * The park is a bit of a work-around, without it we get
7230 * warning spews on shutdown with SQPOLL set and affinity
7231 * set to a single CPU.
7234 kthread_park(sqd->thread);
7235 kthread_stop(sqd->thread);
7242 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7244 struct io_ring_ctx *ctx_attach;
7245 struct io_sq_data *sqd;
7248 f = fdget(p->wq_fd);
7250 return ERR_PTR(-ENXIO);
7251 if (f.file->f_op != &io_uring_fops) {
7253 return ERR_PTR(-EINVAL);
7256 ctx_attach = f.file->private_data;
7257 sqd = ctx_attach->sq_data;
7260 return ERR_PTR(-EINVAL);
7263 refcount_inc(&sqd->refs);
7268 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7270 struct io_sq_data *sqd;
7272 if (p->flags & IORING_SETUP_ATTACH_WQ)
7273 return io_attach_sq_data(p);
7275 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7277 return ERR_PTR(-ENOMEM);
7279 refcount_set(&sqd->refs, 1);
7280 INIT_LIST_HEAD(&sqd->ctx_list);
7281 INIT_LIST_HEAD(&sqd->ctx_new_list);
7282 mutex_init(&sqd->ctx_lock);
7283 mutex_init(&sqd->lock);
7284 init_waitqueue_head(&sqd->wait);
7288 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7289 __releases(&sqd->lock)
7293 kthread_unpark(sqd->thread);
7294 mutex_unlock(&sqd->lock);
7297 static void io_sq_thread_park(struct io_sq_data *sqd)
7298 __acquires(&sqd->lock)
7302 mutex_lock(&sqd->lock);
7303 kthread_park(sqd->thread);
7306 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7308 struct io_sq_data *sqd = ctx->sq_data;
7313 * We may arrive here from the error branch in
7314 * io_sq_offload_create() where the kthread is created
7315 * without being waked up, thus wake it up now to make
7316 * sure the wait will complete.
7318 wake_up_process(sqd->thread);
7319 wait_for_completion(&ctx->sq_thread_comp);
7321 io_sq_thread_park(sqd);
7324 mutex_lock(&sqd->ctx_lock);
7325 list_del(&ctx->sqd_list);
7326 io_sqd_update_thread_idle(sqd);
7327 mutex_unlock(&sqd->ctx_lock);
7330 io_sq_thread_unpark(sqd);
7332 io_put_sq_data(sqd);
7333 ctx->sq_data = NULL;
7337 #if defined(CONFIG_UNIX)
7339 * Ensure the UNIX gc is aware of our file set, so we are certain that
7340 * the io_uring can be safely unregistered on process exit, even if we have
7341 * loops in the file referencing.
7343 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7345 struct sock *sk = ctx->ring_sock->sk;
7346 struct scm_fp_list *fpl;
7347 struct sk_buff *skb;
7350 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7354 skb = alloc_skb(0, GFP_KERNEL);
7363 fpl->user = get_uid(ctx->user);
7364 for (i = 0; i < nr; i++) {
7365 struct file *file = io_file_from_index(ctx, i + offset);
7369 fpl->fp[nr_files] = get_file(file);
7370 unix_inflight(fpl->user, fpl->fp[nr_files]);
7375 fpl->max = SCM_MAX_FD;
7376 fpl->count = nr_files;
7377 UNIXCB(skb).fp = fpl;
7378 skb->destructor = unix_destruct_scm;
7379 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7380 skb_queue_head(&sk->sk_receive_queue, skb);
7382 for (i = 0; i < nr_files; i++)
7393 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7394 * causes regular reference counting to break down. We rely on the UNIX
7395 * garbage collection to take care of this problem for us.
7397 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7399 unsigned left, total;
7403 left = ctx->nr_user_files;
7405 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7407 ret = __io_sqe_files_scm(ctx, this_files, total);
7411 total += this_files;
7417 while (total < ctx->nr_user_files) {
7418 struct file *file = io_file_from_index(ctx, total);
7428 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7434 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7435 unsigned nr_tables, unsigned nr_files)
7439 for (i = 0; i < nr_tables; i++) {
7440 struct fixed_rsrc_table *table = &file_data->table[i];
7441 unsigned this_files;
7443 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7444 table->files = kcalloc(this_files, sizeof(struct file *),
7448 nr_files -= this_files;
7454 for (i = 0; i < nr_tables; i++) {
7455 struct fixed_rsrc_table *table = &file_data->table[i];
7456 kfree(table->files);
7461 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7463 struct file *file = prsrc->file;
7464 #if defined(CONFIG_UNIX)
7465 struct sock *sock = ctx->ring_sock->sk;
7466 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7467 struct sk_buff *skb;
7470 __skb_queue_head_init(&list);
7473 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7474 * remove this entry and rearrange the file array.
7476 skb = skb_dequeue(head);
7478 struct scm_fp_list *fp;
7480 fp = UNIXCB(skb).fp;
7481 for (i = 0; i < fp->count; i++) {
7484 if (fp->fp[i] != file)
7487 unix_notinflight(fp->user, fp->fp[i]);
7488 left = fp->count - 1 - i;
7490 memmove(&fp->fp[i], &fp->fp[i + 1],
7491 left * sizeof(struct file *));
7498 __skb_queue_tail(&list, skb);
7508 __skb_queue_tail(&list, skb);
7510 skb = skb_dequeue(head);
7513 if (skb_peek(&list)) {
7514 spin_lock_irq(&head->lock);
7515 while ((skb = __skb_dequeue(&list)) != NULL)
7516 __skb_queue_tail(head, skb);
7517 spin_unlock_irq(&head->lock);
7524 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7526 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7527 struct io_ring_ctx *ctx = rsrc_data->ctx;
7528 struct io_rsrc_put *prsrc, *tmp;
7530 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7531 list_del(&prsrc->list);
7532 ref_node->rsrc_put(ctx, prsrc);
7536 percpu_ref_exit(&ref_node->refs);
7538 percpu_ref_put(&rsrc_data->refs);
7541 static void io_rsrc_put_work(struct work_struct *work)
7543 struct io_ring_ctx *ctx;
7544 struct llist_node *node;
7546 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7547 node = llist_del_all(&ctx->rsrc_put_llist);
7550 struct fixed_rsrc_ref_node *ref_node;
7551 struct llist_node *next = node->next;
7553 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7554 __io_rsrc_put_work(ref_node);
7559 static struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
7562 struct fixed_rsrc_table *table;
7564 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7565 return &table->files[i & IORING_FILE_TABLE_MASK];
7568 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7570 struct fixed_rsrc_ref_node *ref_node;
7571 struct fixed_rsrc_data *data;
7572 struct io_ring_ctx *ctx;
7573 bool first_add = false;
7576 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7577 data = ref_node->rsrc_data;
7580 io_rsrc_ref_lock(ctx);
7581 ref_node->done = true;
7583 while (!list_empty(&ctx->rsrc_ref_list)) {
7584 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7585 struct fixed_rsrc_ref_node, node);
7586 /* recycle ref nodes in order */
7587 if (!ref_node->done)
7589 list_del(&ref_node->node);
7590 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7592 io_rsrc_ref_unlock(ctx);
7594 if (percpu_ref_is_dying(&data->refs))
7598 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7600 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7603 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7604 struct io_ring_ctx *ctx)
7606 struct fixed_rsrc_ref_node *ref_node;
7608 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7612 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7617 INIT_LIST_HEAD(&ref_node->node);
7618 INIT_LIST_HEAD(&ref_node->rsrc_list);
7619 ref_node->done = false;
7623 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7624 struct fixed_rsrc_ref_node *ref_node)
7626 ref_node->rsrc_data = ctx->file_data;
7627 ref_node->rsrc_put = io_ring_file_put;
7630 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7632 percpu_ref_exit(&ref_node->refs);
7637 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7640 __s32 __user *fds = (__s32 __user *) arg;
7641 unsigned nr_tables, i;
7643 int fd, ret = -ENOMEM;
7644 struct fixed_rsrc_ref_node *ref_node;
7645 struct fixed_rsrc_data *file_data;
7651 if (nr_args > IORING_MAX_FIXED_FILES)
7654 file_data = alloc_fixed_rsrc_data(ctx);
7657 ctx->file_data = file_data;
7659 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7660 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7662 if (!file_data->table)
7665 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7668 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7669 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7673 /* allow sparse sets */
7683 * Don't allow io_uring instances to be registered. If UNIX
7684 * isn't enabled, then this causes a reference cycle and this
7685 * instance can never get freed. If UNIX is enabled we'll
7686 * handle it just fine, but there's still no point in allowing
7687 * a ring fd as it doesn't support regular read/write anyway.
7689 if (file->f_op == &io_uring_fops) {
7693 *io_fixed_file_slot(file_data, i) = file;
7696 ret = io_sqe_files_scm(ctx);
7698 io_sqe_files_unregister(ctx);
7702 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7704 io_sqe_files_unregister(ctx);
7707 init_fixed_file_ref_node(ctx, ref_node);
7709 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7712 for (i = 0; i < ctx->nr_user_files; i++) {
7713 file = io_file_from_index(ctx, i);
7717 for (i = 0; i < nr_tables; i++)
7718 kfree(file_data->table[i].files);
7719 ctx->nr_user_files = 0;
7721 free_fixed_rsrc_data(ctx->file_data);
7722 ctx->file_data = NULL;
7726 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7729 #if defined(CONFIG_UNIX)
7730 struct sock *sock = ctx->ring_sock->sk;
7731 struct sk_buff_head *head = &sock->sk_receive_queue;
7732 struct sk_buff *skb;
7735 * See if we can merge this file into an existing skb SCM_RIGHTS
7736 * file set. If there's no room, fall back to allocating a new skb
7737 * and filling it in.
7739 spin_lock_irq(&head->lock);
7740 skb = skb_peek(head);
7742 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7744 if (fpl->count < SCM_MAX_FD) {
7745 __skb_unlink(skb, head);
7746 spin_unlock_irq(&head->lock);
7747 fpl->fp[fpl->count] = get_file(file);
7748 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7750 spin_lock_irq(&head->lock);
7751 __skb_queue_head(head, skb);
7756 spin_unlock_irq(&head->lock);
7763 return __io_sqe_files_scm(ctx, 1, index);
7769 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7771 struct io_rsrc_put *prsrc;
7772 struct fixed_rsrc_ref_node *ref_node = data->node;
7774 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7779 list_add(&prsrc->list, &ref_node->rsrc_list);
7784 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7787 return io_queue_rsrc_removal(data, (void *)file);
7790 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7791 struct io_uring_rsrc_update *up,
7794 struct fixed_rsrc_data *data = ctx->file_data;
7795 struct fixed_rsrc_ref_node *ref_node;
7796 struct file *file, **file_slot;
7800 bool needs_switch = false;
7802 if (check_add_overflow(up->offset, nr_args, &done))
7804 if (done > ctx->nr_user_files)
7807 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7810 init_fixed_file_ref_node(ctx, ref_node);
7812 fds = u64_to_user_ptr(up->data);
7813 for (done = 0; done < nr_args; done++) {
7815 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7819 if (fd == IORING_REGISTER_FILES_SKIP)
7822 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7823 file_slot = io_fixed_file_slot(ctx->file_data, i);
7826 err = io_queue_file_removal(data, *file_slot);
7830 needs_switch = true;
7839 * Don't allow io_uring instances to be registered. If
7840 * UNIX isn't enabled, then this causes a reference
7841 * cycle and this instance can never get freed. If UNIX
7842 * is enabled we'll handle it just fine, but there's
7843 * still no point in allowing a ring fd as it doesn't
7844 * support regular read/write anyway.
7846 if (file->f_op == &io_uring_fops) {
7852 err = io_sqe_file_register(ctx, file, i);
7862 percpu_ref_kill(&data->node->refs);
7863 io_sqe_rsrc_set_node(ctx, data, ref_node);
7865 destroy_fixed_rsrc_ref_node(ref_node);
7867 return done ? done : err;
7870 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7873 struct io_uring_rsrc_update up;
7875 if (!ctx->file_data)
7879 if (copy_from_user(&up, arg, sizeof(up)))
7884 return __io_sqe_files_update(ctx, &up, nr_args);
7887 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7889 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7891 req = io_put_req_find_next(req);
7892 return req ? &req->work : NULL;
7895 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx)
7897 struct io_wq_data data;
7898 unsigned int concurrency;
7900 data.user = ctx->user;
7901 data.free_work = io_free_work;
7902 data.do_work = io_wq_submit_work;
7904 /* Do QD, or 4 * CPUS, whatever is smallest */
7905 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7907 return io_wq_create(concurrency, &data);
7910 static int io_uring_alloc_task_context(struct task_struct *task,
7911 struct io_ring_ctx *ctx)
7913 struct io_uring_task *tctx;
7916 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7917 if (unlikely(!tctx))
7920 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7921 if (unlikely(ret)) {
7926 tctx->io_wq = io_init_wq_offload(ctx);
7927 if (IS_ERR(tctx->io_wq)) {
7928 ret = PTR_ERR(tctx->io_wq);
7929 percpu_counter_destroy(&tctx->inflight);
7935 init_waitqueue_head(&tctx->wait);
7937 atomic_set(&tctx->in_idle, 0);
7938 tctx->sqpoll = false;
7939 io_init_identity(&tctx->__identity);
7940 tctx->identity = &tctx->__identity;
7941 task->io_uring = tctx;
7942 spin_lock_init(&tctx->task_lock);
7943 INIT_WQ_LIST(&tctx->task_list);
7944 tctx->task_state = 0;
7945 init_task_work(&tctx->task_work, tctx_task_work);
7949 void __io_uring_free(struct task_struct *tsk)
7951 struct io_uring_task *tctx = tsk->io_uring;
7953 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7954 WARN_ON_ONCE(refcount_read(&tctx->identity->count) != 1);
7955 if (tctx->identity != &tctx->__identity)
7956 kfree(tctx->identity);
7957 percpu_counter_destroy(&tctx->inflight);
7959 tsk->io_uring = NULL;
7962 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7963 struct io_uring_params *p)
7967 /* Retain compatibility with failing for an invalid attach attempt */
7968 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7969 IORING_SETUP_ATTACH_WQ) {
7972 f = fdget(p->wq_fd);
7975 if (f.file->f_op != &io_uring_fops) {
7981 if (ctx->flags & IORING_SETUP_SQPOLL) {
7982 struct io_sq_data *sqd;
7985 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
7988 sqd = io_get_sq_data(p);
7995 io_sq_thread_park(sqd);
7996 mutex_lock(&sqd->ctx_lock);
7997 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7998 mutex_unlock(&sqd->ctx_lock);
7999 io_sq_thread_unpark(sqd);
8001 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8002 if (!ctx->sq_thread_idle)
8003 ctx->sq_thread_idle = HZ;
8008 if (p->flags & IORING_SETUP_SQ_AFF) {
8009 int cpu = p->sq_thread_cpu;
8012 if (cpu >= nr_cpu_ids)
8014 if (!cpu_online(cpu))
8017 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
8018 cpu, "io_uring-sq");
8020 sqd->thread = kthread_create(io_sq_thread, sqd,
8023 if (IS_ERR(sqd->thread)) {
8024 ret = PTR_ERR(sqd->thread);
8028 ret = io_uring_alloc_task_context(sqd->thread, ctx);
8031 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8032 /* Can't have SQ_AFF without SQPOLL */
8039 io_sq_thread_stop(ctx);
8043 static void io_sq_offload_start(struct io_ring_ctx *ctx)
8045 struct io_sq_data *sqd = ctx->sq_data;
8047 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
8048 wake_up_process(sqd->thread);
8051 static inline void __io_unaccount_mem(struct user_struct *user,
8052 unsigned long nr_pages)
8054 atomic_long_sub(nr_pages, &user->locked_vm);
8057 static inline int __io_account_mem(struct user_struct *user,
8058 unsigned long nr_pages)
8060 unsigned long page_limit, cur_pages, new_pages;
8062 /* Don't allow more pages than we can safely lock */
8063 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8066 cur_pages = atomic_long_read(&user->locked_vm);
8067 new_pages = cur_pages + nr_pages;
8068 if (new_pages > page_limit)
8070 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8071 new_pages) != cur_pages);
8076 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8079 __io_unaccount_mem(ctx->user, nr_pages);
8081 if (ctx->mm_account)
8082 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8085 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8089 if (ctx->limit_mem) {
8090 ret = __io_account_mem(ctx->user, nr_pages);
8095 if (ctx->mm_account)
8096 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8101 static void io_mem_free(void *ptr)
8108 page = virt_to_head_page(ptr);
8109 if (put_page_testzero(page))
8110 free_compound_page(page);
8113 static void *io_mem_alloc(size_t size)
8115 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8116 __GFP_NORETRY | __GFP_ACCOUNT;
8118 return (void *) __get_free_pages(gfp_flags, get_order(size));
8121 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8124 struct io_rings *rings;
8125 size_t off, sq_array_size;
8127 off = struct_size(rings, cqes, cq_entries);
8128 if (off == SIZE_MAX)
8132 off = ALIGN(off, SMP_CACHE_BYTES);
8140 sq_array_size = array_size(sizeof(u32), sq_entries);
8141 if (sq_array_size == SIZE_MAX)
8144 if (check_add_overflow(off, sq_array_size, &off))
8150 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8154 if (!ctx->user_bufs)
8157 for (i = 0; i < ctx->nr_user_bufs; i++) {
8158 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8160 for (j = 0; j < imu->nr_bvecs; j++)
8161 unpin_user_page(imu->bvec[j].bv_page);
8163 if (imu->acct_pages)
8164 io_unaccount_mem(ctx, imu->acct_pages);
8169 kfree(ctx->user_bufs);
8170 ctx->user_bufs = NULL;
8171 ctx->nr_user_bufs = 0;
8175 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8176 void __user *arg, unsigned index)
8178 struct iovec __user *src;
8180 #ifdef CONFIG_COMPAT
8182 struct compat_iovec __user *ciovs;
8183 struct compat_iovec ciov;
8185 ciovs = (struct compat_iovec __user *) arg;
8186 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8189 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8190 dst->iov_len = ciov.iov_len;
8194 src = (struct iovec __user *) arg;
8195 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8201 * Not super efficient, but this is just a registration time. And we do cache
8202 * the last compound head, so generally we'll only do a full search if we don't
8205 * We check if the given compound head page has already been accounted, to
8206 * avoid double accounting it. This allows us to account the full size of the
8207 * page, not just the constituent pages of a huge page.
8209 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8210 int nr_pages, struct page *hpage)
8214 /* check current page array */
8215 for (i = 0; i < nr_pages; i++) {
8216 if (!PageCompound(pages[i]))
8218 if (compound_head(pages[i]) == hpage)
8222 /* check previously registered pages */
8223 for (i = 0; i < ctx->nr_user_bufs; i++) {
8224 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8226 for (j = 0; j < imu->nr_bvecs; j++) {
8227 if (!PageCompound(imu->bvec[j].bv_page))
8229 if (compound_head(imu->bvec[j].bv_page) == hpage)
8237 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8238 int nr_pages, struct io_mapped_ubuf *imu,
8239 struct page **last_hpage)
8243 for (i = 0; i < nr_pages; i++) {
8244 if (!PageCompound(pages[i])) {
8249 hpage = compound_head(pages[i]);
8250 if (hpage == *last_hpage)
8252 *last_hpage = hpage;
8253 if (headpage_already_acct(ctx, pages, i, hpage))
8255 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8259 if (!imu->acct_pages)
8262 ret = io_account_mem(ctx, imu->acct_pages);
8264 imu->acct_pages = 0;
8268 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8269 struct io_mapped_ubuf *imu,
8270 struct page **last_hpage)
8272 struct vm_area_struct **vmas = NULL;
8273 struct page **pages = NULL;
8274 unsigned long off, start, end, ubuf;
8276 int ret, pret, nr_pages, i;
8278 ubuf = (unsigned long) iov->iov_base;
8279 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8280 start = ubuf >> PAGE_SHIFT;
8281 nr_pages = end - start;
8285 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8289 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8294 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8300 mmap_read_lock(current->mm);
8301 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8303 if (pret == nr_pages) {
8304 /* don't support file backed memory */
8305 for (i = 0; i < nr_pages; i++) {
8306 struct vm_area_struct *vma = vmas[i];
8309 !is_file_hugepages(vma->vm_file)) {
8315 ret = pret < 0 ? pret : -EFAULT;
8317 mmap_read_unlock(current->mm);
8320 * if we did partial map, or found file backed vmas,
8321 * release any pages we did get
8324 unpin_user_pages(pages, pret);
8329 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8331 unpin_user_pages(pages, pret);
8336 off = ubuf & ~PAGE_MASK;
8337 size = iov->iov_len;
8338 for (i = 0; i < nr_pages; i++) {
8341 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8342 imu->bvec[i].bv_page = pages[i];
8343 imu->bvec[i].bv_len = vec_len;
8344 imu->bvec[i].bv_offset = off;
8348 /* store original address for later verification */
8350 imu->len = iov->iov_len;
8351 imu->nr_bvecs = nr_pages;
8359 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8363 if (!nr_args || nr_args > UIO_MAXIOV)
8366 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8368 if (!ctx->user_bufs)
8374 static int io_buffer_validate(struct iovec *iov)
8377 * Don't impose further limits on the size and buffer
8378 * constraints here, we'll -EINVAL later when IO is
8379 * submitted if they are wrong.
8381 if (!iov->iov_base || !iov->iov_len)
8384 /* arbitrary limit, but we need something */
8385 if (iov->iov_len > SZ_1G)
8391 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8392 unsigned int nr_args)
8396 struct page *last_hpage = NULL;
8398 ret = io_buffers_map_alloc(ctx, nr_args);
8402 for (i = 0; i < nr_args; i++) {
8403 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8405 ret = io_copy_iov(ctx, &iov, arg, i);
8409 ret = io_buffer_validate(&iov);
8413 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8417 ctx->nr_user_bufs++;
8421 io_sqe_buffers_unregister(ctx);
8426 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8428 __s32 __user *fds = arg;
8434 if (copy_from_user(&fd, fds, sizeof(*fds)))
8437 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8438 if (IS_ERR(ctx->cq_ev_fd)) {
8439 int ret = PTR_ERR(ctx->cq_ev_fd);
8440 ctx->cq_ev_fd = NULL;
8447 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8449 if (ctx->cq_ev_fd) {
8450 eventfd_ctx_put(ctx->cq_ev_fd);
8451 ctx->cq_ev_fd = NULL;
8458 static int __io_destroy_buffers(int id, void *p, void *data)
8460 struct io_ring_ctx *ctx = data;
8461 struct io_buffer *buf = p;
8463 __io_remove_buffers(ctx, buf, id, -1U);
8467 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8469 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8470 idr_destroy(&ctx->io_buffer_idr);
8473 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8475 struct io_kiocb *req, *nxt;
8477 list_for_each_entry_safe(req, nxt, list, compl.list) {
8478 if (tsk && req->task != tsk)
8480 list_del(&req->compl.list);
8481 kmem_cache_free(req_cachep, req);
8485 static void io_req_caches_free(struct io_ring_ctx *ctx, struct task_struct *tsk)
8487 struct io_submit_state *submit_state = &ctx->submit_state;
8489 mutex_lock(&ctx->uring_lock);
8491 if (submit_state->free_reqs)
8492 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8493 submit_state->reqs);
8495 io_req_cache_free(&submit_state->comp.free_list, NULL);
8497 spin_lock_irq(&ctx->completion_lock);
8498 io_req_cache_free(&submit_state->comp.locked_free_list, NULL);
8499 spin_unlock_irq(&ctx->completion_lock);
8501 mutex_unlock(&ctx->uring_lock);
8504 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8507 * Some may use context even when all refs and requests have been put,
8508 * and they are free to do so while still holding uring_lock, see
8509 * __io_req_task_submit(). Wait for them to finish.
8511 mutex_lock(&ctx->uring_lock);
8512 mutex_unlock(&ctx->uring_lock);
8514 io_sq_thread_stop(ctx);
8515 io_sqe_buffers_unregister(ctx);
8517 if (ctx->sqo_task) {
8518 put_task_struct(ctx->sqo_task);
8519 ctx->sqo_task = NULL;
8520 mmdrop(ctx->mm_account);
8521 ctx->mm_account = NULL;
8524 #ifdef CONFIG_BLK_CGROUP
8525 if (ctx->sqo_blkcg_css)
8526 css_put(ctx->sqo_blkcg_css);
8529 mutex_lock(&ctx->uring_lock);
8530 io_sqe_files_unregister(ctx);
8531 mutex_unlock(&ctx->uring_lock);
8532 io_eventfd_unregister(ctx);
8533 io_destroy_buffers(ctx);
8534 idr_destroy(&ctx->personality_idr);
8536 #if defined(CONFIG_UNIX)
8537 if (ctx->ring_sock) {
8538 ctx->ring_sock->file = NULL; /* so that iput() is called */
8539 sock_release(ctx->ring_sock);
8543 io_mem_free(ctx->rings);
8544 io_mem_free(ctx->sq_sqes);
8546 percpu_ref_exit(&ctx->refs);
8547 free_uid(ctx->user);
8548 put_cred(ctx->creds);
8549 io_req_caches_free(ctx, NULL);
8550 kfree(ctx->cancel_hash);
8554 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8556 struct io_ring_ctx *ctx = file->private_data;
8559 poll_wait(file, &ctx->cq_wait, wait);
8561 * synchronizes with barrier from wq_has_sleeper call in
8565 if (!io_sqring_full(ctx))
8566 mask |= EPOLLOUT | EPOLLWRNORM;
8569 * Don't flush cqring overflow list here, just do a simple check.
8570 * Otherwise there could possible be ABBA deadlock:
8573 * lock(&ctx->uring_lock);
8575 * lock(&ctx->uring_lock);
8578 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8579 * pushs them to do the flush.
8581 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8582 mask |= EPOLLIN | EPOLLRDNORM;
8587 static int io_uring_fasync(int fd, struct file *file, int on)
8589 struct io_ring_ctx *ctx = file->private_data;
8591 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8594 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8596 struct io_identity *iod;
8598 iod = idr_remove(&ctx->personality_idr, id);
8600 put_cred(iod->creds);
8601 if (refcount_dec_and_test(&iod->count))
8609 static int io_remove_personalities(int id, void *p, void *data)
8611 struct io_ring_ctx *ctx = data;
8613 io_unregister_personality(ctx, id);
8617 static void io_run_ctx_fallback(struct io_ring_ctx *ctx)
8619 struct callback_head *work, *head, *next;
8624 work = READ_ONCE(ctx->exit_task_work);
8625 } while (cmpxchg(&ctx->exit_task_work, work, head) != work);
8639 static void io_ring_exit_work(struct work_struct *work)
8641 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8645 * If we're doing polled IO and end up having requests being
8646 * submitted async (out-of-line), then completions can come in while
8647 * we're waiting for refs to drop. We need to reap these manually,
8648 * as nobody else will be looking for them.
8651 io_uring_try_cancel_requests(ctx, NULL, NULL);
8652 io_run_ctx_fallback(ctx);
8653 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8654 io_ring_ctx_free(ctx);
8657 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8659 mutex_lock(&ctx->uring_lock);
8660 percpu_ref_kill(&ctx->refs);
8662 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8665 /* if force is set, the ring is going away. always drop after that */
8666 ctx->cq_overflow_flushed = 1;
8668 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8669 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8670 mutex_unlock(&ctx->uring_lock);
8672 io_kill_timeouts(ctx, NULL, NULL);
8673 io_poll_remove_all(ctx, NULL, NULL);
8675 /* if we failed setting up the ctx, we might not have any rings */
8676 io_iopoll_try_reap_events(ctx);
8678 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8680 * Use system_unbound_wq to avoid spawning tons of event kworkers
8681 * if we're exiting a ton of rings at the same time. It just adds
8682 * noise and overhead, there's no discernable change in runtime
8683 * over using system_wq.
8685 queue_work(system_unbound_wq, &ctx->exit_work);
8688 static int io_uring_release(struct inode *inode, struct file *file)
8690 struct io_ring_ctx *ctx = file->private_data;
8692 file->private_data = NULL;
8693 io_ring_ctx_wait_and_kill(ctx);
8697 struct io_task_cancel {
8698 struct task_struct *task;
8699 struct files_struct *files;
8702 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8704 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8705 struct io_task_cancel *cancel = data;
8708 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8709 unsigned long flags;
8710 struct io_ring_ctx *ctx = req->ctx;
8712 /* protect against races with linked timeouts */
8713 spin_lock_irqsave(&ctx->completion_lock, flags);
8714 ret = io_match_task(req, cancel->task, cancel->files);
8715 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8717 ret = io_match_task(req, cancel->task, cancel->files);
8722 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8723 struct task_struct *task,
8724 struct files_struct *files)
8726 struct io_defer_entry *de = NULL;
8729 spin_lock_irq(&ctx->completion_lock);
8730 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8731 if (io_match_task(de->req, task, files)) {
8732 list_cut_position(&list, &ctx->defer_list, &de->list);
8736 spin_unlock_irq(&ctx->completion_lock);
8738 while (!list_empty(&list)) {
8739 de = list_first_entry(&list, struct io_defer_entry, list);
8740 list_del_init(&de->list);
8741 req_set_fail_links(de->req);
8742 io_put_req(de->req);
8743 io_req_complete(de->req, -ECANCELED);
8748 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8749 struct task_struct *task,
8750 struct files_struct *files)
8752 struct io_task_cancel cancel = { .task = task, .files = files, };
8753 struct io_uring_task *tctx = current->io_uring;
8756 enum io_wq_cancel cret;
8759 if (tctx && tctx->io_wq) {
8760 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8762 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8765 /* SQPOLL thread does its own polling */
8766 if (!(ctx->flags & IORING_SETUP_SQPOLL) && !files) {
8767 while (!list_empty_careful(&ctx->iopoll_list)) {
8768 io_iopoll_try_reap_events(ctx);
8773 ret |= io_poll_remove_all(ctx, task, files);
8774 ret |= io_kill_timeouts(ctx, task, files);
8775 ret |= io_run_task_work();
8776 io_cqring_overflow_flush(ctx, true, task, files);
8783 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8784 struct task_struct *task,
8785 struct files_struct *files)
8787 struct io_kiocb *req;
8790 spin_lock_irq(&ctx->inflight_lock);
8791 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8792 cnt += io_match_task(req, task, files);
8793 spin_unlock_irq(&ctx->inflight_lock);
8797 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8798 struct task_struct *task,
8799 struct files_struct *files)
8801 while (!list_empty_careful(&ctx->inflight_list)) {
8805 inflight = io_uring_count_inflight(ctx, task, files);
8809 io_uring_try_cancel_requests(ctx, task, files);
8812 io_sq_thread_unpark(ctx->sq_data);
8813 prepare_to_wait(&task->io_uring->wait, &wait,
8814 TASK_UNINTERRUPTIBLE);
8815 if (inflight == io_uring_count_inflight(ctx, task, files))
8817 finish_wait(&task->io_uring->wait, &wait);
8819 io_sq_thread_park(ctx->sq_data);
8823 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
8825 mutex_lock(&ctx->uring_lock);
8827 mutex_unlock(&ctx->uring_lock);
8829 /* make sure callers enter the ring to get error */
8831 io_ring_set_wakeup_flag(ctx);
8835 * We need to iteratively cancel requests, in case a request has dependent
8836 * hard links. These persist even for failure of cancelations, hence keep
8837 * looping until none are found.
8839 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8840 struct files_struct *files)
8842 struct task_struct *task = current;
8844 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8845 io_disable_sqo_submit(ctx);
8846 task = ctx->sq_data->thread;
8847 atomic_inc(&task->io_uring->in_idle);
8848 io_sq_thread_park(ctx->sq_data);
8851 io_cancel_defer_files(ctx, task, files);
8853 io_uring_cancel_files(ctx, task, files);
8855 io_uring_try_cancel_requests(ctx, task, NULL);
8857 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8858 atomic_dec(&task->io_uring->in_idle);
8859 io_sq_thread_unpark(ctx->sq_data);
8864 * Note that this task has used io_uring. We use it for cancelation purposes.
8866 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
8868 struct io_uring_task *tctx = current->io_uring;
8871 if (unlikely(!tctx)) {
8872 ret = io_uring_alloc_task_context(current, ctx);
8875 tctx = current->io_uring;
8877 if (tctx->last != file) {
8878 void *old = xa_load(&tctx->xa, (unsigned long)file);
8882 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
8889 /* one and only SQPOLL file note, held by sqo_task */
8890 WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) &&
8891 current != ctx->sqo_task);
8897 * This is race safe in that the task itself is doing this, hence it
8898 * cannot be going through the exit/cancel paths at the same time.
8899 * This cannot be modified while exit/cancel is running.
8901 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
8902 tctx->sqpoll = true;
8908 * Remove this io_uring_file -> task mapping.
8910 static void io_uring_del_task_file(struct file *file)
8912 struct io_uring_task *tctx = current->io_uring;
8914 if (tctx->last == file)
8916 file = xa_erase(&tctx->xa, (unsigned long)file);
8921 static void io_uring_remove_task_files(struct io_uring_task *tctx)
8924 unsigned long index;
8926 xa_for_each(&tctx->xa, index, file)
8927 io_uring_del_task_file(file);
8930 void __io_uring_files_cancel(struct files_struct *files)
8932 struct io_uring_task *tctx = current->io_uring;
8934 unsigned long index;
8936 /* make sure overflow events are dropped */
8937 atomic_inc(&tctx->in_idle);
8938 xa_for_each(&tctx->xa, index, file)
8939 io_uring_cancel_task_requests(file->private_data, files);
8940 atomic_dec(&tctx->in_idle);
8943 io_uring_remove_task_files(tctx);
8944 } else if (tctx->io_wq && current->flags & PF_EXITING) {
8945 io_wq_destroy(tctx->io_wq);
8950 static s64 tctx_inflight(struct io_uring_task *tctx)
8952 return percpu_counter_sum(&tctx->inflight);
8955 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
8957 struct io_uring_task *tctx;
8963 tctx = ctx->sq_data->thread->io_uring;
8964 io_disable_sqo_submit(ctx);
8966 atomic_inc(&tctx->in_idle);
8968 /* read completions before cancelations */
8969 inflight = tctx_inflight(tctx);
8972 io_uring_cancel_task_requests(ctx, NULL);
8974 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8976 * If we've seen completions, retry without waiting. This
8977 * avoids a race where a completion comes in before we did
8978 * prepare_to_wait().
8980 if (inflight == tctx_inflight(tctx))
8982 finish_wait(&tctx->wait, &wait);
8984 atomic_dec(&tctx->in_idle);
8988 * Find any io_uring fd that this task has registered or done IO on, and cancel
8991 void __io_uring_task_cancel(void)
8993 struct io_uring_task *tctx = current->io_uring;
8997 /* make sure overflow events are dropped */
8998 atomic_inc(&tctx->in_idle);
9000 /* trigger io_disable_sqo_submit() */
9003 unsigned long index;
9005 xa_for_each(&tctx->xa, index, file)
9006 io_uring_cancel_sqpoll(file->private_data);
9010 /* read completions before cancelations */
9011 inflight = tctx_inflight(tctx);
9014 __io_uring_files_cancel(NULL);
9016 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9019 * If we've seen completions, retry without waiting. This
9020 * avoids a race where a completion comes in before we did
9021 * prepare_to_wait().
9023 if (inflight == tctx_inflight(tctx))
9025 finish_wait(&tctx->wait, &wait);
9028 atomic_dec(&tctx->in_idle);
9030 io_uring_remove_task_files(tctx);
9033 static int io_uring_flush(struct file *file, void *data)
9035 struct io_uring_task *tctx = current->io_uring;
9036 struct io_ring_ctx *ctx = file->private_data;
9038 /* Ignore helper thread files exit */
9039 if (current->flags & PF_IO_WORKER)
9042 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
9043 io_uring_cancel_task_requests(ctx, NULL);
9044 io_req_caches_free(ctx, current);
9047 io_run_ctx_fallback(ctx);
9052 /* we should have cancelled and erased it before PF_EXITING */
9053 WARN_ON_ONCE((current->flags & PF_EXITING) &&
9054 xa_load(&tctx->xa, (unsigned long)file));
9057 * fput() is pending, will be 2 if the only other ref is our potential
9058 * task file note. If the task is exiting, drop regardless of count.
9060 if (atomic_long_read(&file->f_count) != 2)
9063 if (ctx->flags & IORING_SETUP_SQPOLL) {
9064 /* there is only one file note, which is owned by sqo_task */
9065 WARN_ON_ONCE(ctx->sqo_task != current &&
9066 xa_load(&tctx->xa, (unsigned long)file));
9067 /* sqo_dead check is for when this happens after cancellation */
9068 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
9069 !xa_load(&tctx->xa, (unsigned long)file));
9071 io_disable_sqo_submit(ctx);
9074 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
9075 io_uring_del_task_file(file);
9079 static void *io_uring_validate_mmap_request(struct file *file,
9080 loff_t pgoff, size_t sz)
9082 struct io_ring_ctx *ctx = file->private_data;
9083 loff_t offset = pgoff << PAGE_SHIFT;
9088 case IORING_OFF_SQ_RING:
9089 case IORING_OFF_CQ_RING:
9092 case IORING_OFF_SQES:
9096 return ERR_PTR(-EINVAL);
9099 page = virt_to_head_page(ptr);
9100 if (sz > page_size(page))
9101 return ERR_PTR(-EINVAL);
9108 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9110 size_t sz = vma->vm_end - vma->vm_start;
9114 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9116 return PTR_ERR(ptr);
9118 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9119 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9122 #else /* !CONFIG_MMU */
9124 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9126 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9129 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9131 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9134 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9135 unsigned long addr, unsigned long len,
9136 unsigned long pgoff, unsigned long flags)
9140 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9142 return PTR_ERR(ptr);
9144 return (unsigned long) ptr;
9147 #endif /* !CONFIG_MMU */
9149 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9155 if (!io_sqring_full(ctx))
9158 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9160 if (unlikely(ctx->sqo_dead)) {
9165 if (!io_sqring_full(ctx))
9169 } while (!signal_pending(current));
9171 finish_wait(&ctx->sqo_sq_wait, &wait);
9176 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9177 struct __kernel_timespec __user **ts,
9178 const sigset_t __user **sig)
9180 struct io_uring_getevents_arg arg;
9183 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9184 * is just a pointer to the sigset_t.
9186 if (!(flags & IORING_ENTER_EXT_ARG)) {
9187 *sig = (const sigset_t __user *) argp;
9193 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9194 * timespec and sigset_t pointers if good.
9196 if (*argsz != sizeof(arg))
9198 if (copy_from_user(&arg, argp, sizeof(arg)))
9200 *sig = u64_to_user_ptr(arg.sigmask);
9201 *argsz = arg.sigmask_sz;
9202 *ts = u64_to_user_ptr(arg.ts);
9206 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9207 u32, min_complete, u32, flags, const void __user *, argp,
9210 struct io_ring_ctx *ctx;
9217 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9218 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9226 if (f.file->f_op != &io_uring_fops)
9230 ctx = f.file->private_data;
9231 if (!percpu_ref_tryget(&ctx->refs))
9235 if (ctx->flags & IORING_SETUP_R_DISABLED)
9239 * For SQ polling, the thread will do all submissions and completions.
9240 * Just return the requested submit count, and wake the thread if
9244 if (ctx->flags & IORING_SETUP_SQPOLL) {
9245 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9248 if (unlikely(ctx->sqo_dead))
9250 if (flags & IORING_ENTER_SQ_WAKEUP)
9251 wake_up(&ctx->sq_data->wait);
9252 if (flags & IORING_ENTER_SQ_WAIT) {
9253 ret = io_sqpoll_wait_sq(ctx);
9257 submitted = to_submit;
9258 } else if (to_submit) {
9259 ret = io_uring_add_task_file(ctx, f.file);
9262 mutex_lock(&ctx->uring_lock);
9263 submitted = io_submit_sqes(ctx, to_submit);
9264 mutex_unlock(&ctx->uring_lock);
9266 if (submitted != to_submit)
9269 if (flags & IORING_ENTER_GETEVENTS) {
9270 const sigset_t __user *sig;
9271 struct __kernel_timespec __user *ts;
9273 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9277 min_complete = min(min_complete, ctx->cq_entries);
9280 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9281 * space applications don't need to do io completion events
9282 * polling again, they can rely on io_sq_thread to do polling
9283 * work, which can reduce cpu usage and uring_lock contention.
9285 if (ctx->flags & IORING_SETUP_IOPOLL &&
9286 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9287 ret = io_iopoll_check(ctx, min_complete);
9289 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9294 percpu_ref_put(&ctx->refs);
9297 return submitted ? submitted : ret;
9300 #ifdef CONFIG_PROC_FS
9301 static int io_uring_show_cred(int id, void *p, void *data)
9303 struct io_identity *iod = p;
9304 const struct cred *cred = iod->creds;
9305 struct seq_file *m = data;
9306 struct user_namespace *uns = seq_user_ns(m);
9307 struct group_info *gi;
9312 seq_printf(m, "%5d\n", id);
9313 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9314 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9315 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9316 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9317 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9318 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9319 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9320 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9321 seq_puts(m, "\n\tGroups:\t");
9322 gi = cred->group_info;
9323 for (g = 0; g < gi->ngroups; g++) {
9324 seq_put_decimal_ull(m, g ? " " : "",
9325 from_kgid_munged(uns, gi->gid[g]));
9327 seq_puts(m, "\n\tCapEff:\t");
9328 cap = cred->cap_effective;
9329 CAP_FOR_EACH_U32(__capi)
9330 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9335 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9337 struct io_sq_data *sq = NULL;
9342 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9343 * since fdinfo case grabs it in the opposite direction of normal use
9344 * cases. If we fail to get the lock, we just don't iterate any
9345 * structures that could be going away outside the io_uring mutex.
9347 has_lock = mutex_trylock(&ctx->uring_lock);
9349 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9352 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9353 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9354 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9355 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9356 struct file *f = *io_fixed_file_slot(ctx->file_data, i);
9359 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9361 seq_printf(m, "%5u: <none>\n", i);
9363 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9364 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9365 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9367 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9368 (unsigned int) buf->len);
9370 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9371 seq_printf(m, "Personalities:\n");
9372 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9374 seq_printf(m, "PollList:\n");
9375 spin_lock_irq(&ctx->completion_lock);
9376 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9377 struct hlist_head *list = &ctx->cancel_hash[i];
9378 struct io_kiocb *req;
9380 hlist_for_each_entry(req, list, hash_node)
9381 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9382 req->task->task_works != NULL);
9384 spin_unlock_irq(&ctx->completion_lock);
9386 mutex_unlock(&ctx->uring_lock);
9389 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9391 struct io_ring_ctx *ctx = f->private_data;
9393 if (percpu_ref_tryget(&ctx->refs)) {
9394 __io_uring_show_fdinfo(ctx, m);
9395 percpu_ref_put(&ctx->refs);
9400 static const struct file_operations io_uring_fops = {
9401 .release = io_uring_release,
9402 .flush = io_uring_flush,
9403 .mmap = io_uring_mmap,
9405 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9406 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9408 .poll = io_uring_poll,
9409 .fasync = io_uring_fasync,
9410 #ifdef CONFIG_PROC_FS
9411 .show_fdinfo = io_uring_show_fdinfo,
9415 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9416 struct io_uring_params *p)
9418 struct io_rings *rings;
9419 size_t size, sq_array_offset;
9421 /* make sure these are sane, as we already accounted them */
9422 ctx->sq_entries = p->sq_entries;
9423 ctx->cq_entries = p->cq_entries;
9425 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9426 if (size == SIZE_MAX)
9429 rings = io_mem_alloc(size);
9434 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9435 rings->sq_ring_mask = p->sq_entries - 1;
9436 rings->cq_ring_mask = p->cq_entries - 1;
9437 rings->sq_ring_entries = p->sq_entries;
9438 rings->cq_ring_entries = p->cq_entries;
9439 ctx->sq_mask = rings->sq_ring_mask;
9440 ctx->cq_mask = rings->cq_ring_mask;
9442 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9443 if (size == SIZE_MAX) {
9444 io_mem_free(ctx->rings);
9449 ctx->sq_sqes = io_mem_alloc(size);
9450 if (!ctx->sq_sqes) {
9451 io_mem_free(ctx->rings);
9459 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9463 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9467 ret = io_uring_add_task_file(ctx, file);
9472 fd_install(fd, file);
9477 * Allocate an anonymous fd, this is what constitutes the application
9478 * visible backing of an io_uring instance. The application mmaps this
9479 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9480 * we have to tie this fd to a socket for file garbage collection purposes.
9482 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9485 #if defined(CONFIG_UNIX)
9488 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9491 return ERR_PTR(ret);
9494 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9495 O_RDWR | O_CLOEXEC);
9496 #if defined(CONFIG_UNIX)
9498 sock_release(ctx->ring_sock);
9499 ctx->ring_sock = NULL;
9501 ctx->ring_sock->file = file;
9507 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9508 struct io_uring_params __user *params)
9510 struct user_struct *user = NULL;
9511 struct io_ring_ctx *ctx;
9517 if (entries > IORING_MAX_ENTRIES) {
9518 if (!(p->flags & IORING_SETUP_CLAMP))
9520 entries = IORING_MAX_ENTRIES;
9524 * Use twice as many entries for the CQ ring. It's possible for the
9525 * application to drive a higher depth than the size of the SQ ring,
9526 * since the sqes are only used at submission time. This allows for
9527 * some flexibility in overcommitting a bit. If the application has
9528 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9529 * of CQ ring entries manually.
9531 p->sq_entries = roundup_pow_of_two(entries);
9532 if (p->flags & IORING_SETUP_CQSIZE) {
9534 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9535 * to a power-of-two, if it isn't already. We do NOT impose
9536 * any cq vs sq ring sizing.
9540 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9541 if (!(p->flags & IORING_SETUP_CLAMP))
9543 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9545 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9546 if (p->cq_entries < p->sq_entries)
9549 p->cq_entries = 2 * p->sq_entries;
9552 user = get_uid(current_user());
9554 ctx = io_ring_ctx_alloc(p);
9559 ctx->compat = in_compat_syscall();
9560 ctx->limit_mem = !capable(CAP_IPC_LOCK);
9562 ctx->creds = get_current_cred();
9564 ctx->loginuid = current->loginuid;
9565 ctx->sessionid = current->sessionid;
9567 ctx->sqo_task = get_task_struct(current);
9570 * This is just grabbed for accounting purposes. When a process exits,
9571 * the mm is exited and dropped before the files, hence we need to hang
9572 * on to this mm purely for the purposes of being able to unaccount
9573 * memory (locked/pinned vm). It's not used for anything else.
9575 mmgrab(current->mm);
9576 ctx->mm_account = current->mm;
9578 #ifdef CONFIG_BLK_CGROUP
9580 * The sq thread will belong to the original cgroup it was inited in.
9581 * If the cgroup goes offline (e.g. disabling the io controller), then
9582 * issued bios will be associated with the closest cgroup later in the
9586 ctx->sqo_blkcg_css = blkcg_css();
9587 ret = css_tryget_online(ctx->sqo_blkcg_css);
9590 /* don't init against a dying cgroup, have the user try again */
9591 ctx->sqo_blkcg_css = NULL;
9596 ret = io_allocate_scq_urings(ctx, p);
9600 ret = io_sq_offload_create(ctx, p);
9604 if (!(p->flags & IORING_SETUP_R_DISABLED))
9605 io_sq_offload_start(ctx);
9607 memset(&p->sq_off, 0, sizeof(p->sq_off));
9608 p->sq_off.head = offsetof(struct io_rings, sq.head);
9609 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9610 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9611 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9612 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9613 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9614 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9616 memset(&p->cq_off, 0, sizeof(p->cq_off));
9617 p->cq_off.head = offsetof(struct io_rings, cq.head);
9618 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9619 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9620 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9621 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9622 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9623 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9625 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9626 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9627 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9628 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9629 IORING_FEAT_EXT_ARG;
9631 if (copy_to_user(params, p, sizeof(*p))) {
9636 file = io_uring_get_file(ctx);
9638 ret = PTR_ERR(file);
9643 * Install ring fd as the very last thing, so we don't risk someone
9644 * having closed it before we finish setup
9646 ret = io_uring_install_fd(ctx, file);
9648 io_disable_sqo_submit(ctx);
9649 /* fput will clean it up */
9654 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9657 io_disable_sqo_submit(ctx);
9658 io_ring_ctx_wait_and_kill(ctx);
9663 * Sets up an aio uring context, and returns the fd. Applications asks for a
9664 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9665 * params structure passed in.
9667 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9669 struct io_uring_params p;
9672 if (copy_from_user(&p, params, sizeof(p)))
9674 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9679 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9680 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9681 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9682 IORING_SETUP_R_DISABLED))
9685 return io_uring_create(entries, &p, params);
9688 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9689 struct io_uring_params __user *, params)
9691 return io_uring_setup(entries, params);
9694 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9696 struct io_uring_probe *p;
9700 size = struct_size(p, ops, nr_args);
9701 if (size == SIZE_MAX)
9703 p = kzalloc(size, GFP_KERNEL);
9708 if (copy_from_user(p, arg, size))
9711 if (memchr_inv(p, 0, size))
9714 p->last_op = IORING_OP_LAST - 1;
9715 if (nr_args > IORING_OP_LAST)
9716 nr_args = IORING_OP_LAST;
9718 for (i = 0; i < nr_args; i++) {
9720 if (!io_op_defs[i].not_supported)
9721 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9726 if (copy_to_user(arg, p, size))
9733 static int io_register_personality(struct io_ring_ctx *ctx)
9735 struct io_identity *id;
9738 id = kmalloc(sizeof(*id), GFP_KERNEL);
9742 io_init_identity(id);
9743 id->creds = get_current_cred();
9745 ret = idr_alloc_cyclic(&ctx->personality_idr, id, 1, USHRT_MAX, GFP_KERNEL);
9747 put_cred(id->creds);
9753 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9754 unsigned int nr_args)
9756 struct io_uring_restriction *res;
9760 /* Restrictions allowed only if rings started disabled */
9761 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9764 /* We allow only a single restrictions registration */
9765 if (ctx->restrictions.registered)
9768 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9771 size = array_size(nr_args, sizeof(*res));
9772 if (size == SIZE_MAX)
9775 res = memdup_user(arg, size);
9777 return PTR_ERR(res);
9781 for (i = 0; i < nr_args; i++) {
9782 switch (res[i].opcode) {
9783 case IORING_RESTRICTION_REGISTER_OP:
9784 if (res[i].register_op >= IORING_REGISTER_LAST) {
9789 __set_bit(res[i].register_op,
9790 ctx->restrictions.register_op);
9792 case IORING_RESTRICTION_SQE_OP:
9793 if (res[i].sqe_op >= IORING_OP_LAST) {
9798 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9800 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9801 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9803 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9804 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9813 /* Reset all restrictions if an error happened */
9815 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9817 ctx->restrictions.registered = true;
9823 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9825 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9828 if (ctx->restrictions.registered)
9829 ctx->restricted = 1;
9831 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9833 io_sq_offload_start(ctx);
9838 static bool io_register_op_must_quiesce(int op)
9841 case IORING_UNREGISTER_FILES:
9842 case IORING_REGISTER_FILES_UPDATE:
9843 case IORING_REGISTER_PROBE:
9844 case IORING_REGISTER_PERSONALITY:
9845 case IORING_UNREGISTER_PERSONALITY:
9852 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9853 void __user *arg, unsigned nr_args)
9854 __releases(ctx->uring_lock)
9855 __acquires(ctx->uring_lock)
9860 * We're inside the ring mutex, if the ref is already dying, then
9861 * someone else killed the ctx or is already going through
9862 * io_uring_register().
9864 if (percpu_ref_is_dying(&ctx->refs))
9867 if (io_register_op_must_quiesce(opcode)) {
9868 percpu_ref_kill(&ctx->refs);
9871 * Drop uring mutex before waiting for references to exit. If
9872 * another thread is currently inside io_uring_enter() it might
9873 * need to grab the uring_lock to make progress. If we hold it
9874 * here across the drain wait, then we can deadlock. It's safe
9875 * to drop the mutex here, since no new references will come in
9876 * after we've killed the percpu ref.
9878 mutex_unlock(&ctx->uring_lock);
9880 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9883 ret = io_run_task_work_sig();
9888 mutex_lock(&ctx->uring_lock);
9890 if (ret && io_refs_resurrect(&ctx->refs, &ctx->ref_comp))
9894 if (ctx->restricted) {
9895 if (opcode >= IORING_REGISTER_LAST) {
9900 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9907 case IORING_REGISTER_BUFFERS:
9908 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9910 case IORING_UNREGISTER_BUFFERS:
9914 ret = io_sqe_buffers_unregister(ctx);
9916 case IORING_REGISTER_FILES:
9917 ret = io_sqe_files_register(ctx, arg, nr_args);
9919 case IORING_UNREGISTER_FILES:
9923 ret = io_sqe_files_unregister(ctx);
9925 case IORING_REGISTER_FILES_UPDATE:
9926 ret = io_sqe_files_update(ctx, arg, nr_args);
9928 case IORING_REGISTER_EVENTFD:
9929 case IORING_REGISTER_EVENTFD_ASYNC:
9933 ret = io_eventfd_register(ctx, arg);
9936 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9937 ctx->eventfd_async = 1;
9939 ctx->eventfd_async = 0;
9941 case IORING_UNREGISTER_EVENTFD:
9945 ret = io_eventfd_unregister(ctx);
9947 case IORING_REGISTER_PROBE:
9949 if (!arg || nr_args > 256)
9951 ret = io_probe(ctx, arg, nr_args);
9953 case IORING_REGISTER_PERSONALITY:
9957 ret = io_register_personality(ctx);
9959 case IORING_UNREGISTER_PERSONALITY:
9963 ret = io_unregister_personality(ctx, nr_args);
9965 case IORING_REGISTER_ENABLE_RINGS:
9969 ret = io_register_enable_rings(ctx);
9971 case IORING_REGISTER_RESTRICTIONS:
9972 ret = io_register_restrictions(ctx, arg, nr_args);
9980 if (io_register_op_must_quiesce(opcode)) {
9981 /* bring the ctx back to life */
9982 percpu_ref_reinit(&ctx->refs);
9983 reinit_completion(&ctx->ref_comp);
9988 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9989 void __user *, arg, unsigned int, nr_args)
9991 struct io_ring_ctx *ctx;
10000 if (f.file->f_op != &io_uring_fops)
10003 ctx = f.file->private_data;
10005 io_run_task_work();
10007 mutex_lock(&ctx->uring_lock);
10008 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10009 mutex_unlock(&ctx->uring_lock);
10010 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10011 ctx->cq_ev_fd != NULL, ret);
10017 static int __init io_uring_init(void)
10019 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10020 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10021 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10024 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10025 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10026 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10027 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10028 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10029 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10030 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10031 BUILD_BUG_SQE_ELEM(8, __u64, off);
10032 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10033 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10034 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10035 BUILD_BUG_SQE_ELEM(24, __u32, len);
10036 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10037 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10038 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10039 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10040 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10041 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10042 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10043 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10044 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10045 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10046 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10047 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10048 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10049 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10050 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10051 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10052 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10053 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10054 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10056 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10057 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10058 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10062 __initcall(io_uring_init);