1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
85 #include <uapi/linux/io_uring.h>
90 #define IORING_MAX_ENTRIES 32768
91 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
96 #define IORING_FILE_TABLE_SHIFT 9
97 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
98 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
99 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
100 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
101 IORING_REGISTER_LAST + IORING_OP_LAST)
103 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
104 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
108 u32 head ____cacheline_aligned_in_smp;
109 u32 tail ____cacheline_aligned_in_smp;
113 * This data is shared with the application through the mmap at offsets
114 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
116 * The offsets to the member fields are published through struct
117 * io_sqring_offsets when calling io_uring_setup.
121 * Head and tail offsets into the ring; the offsets need to be
122 * masked to get valid indices.
124 * The kernel controls head of the sq ring and the tail of the cq ring,
125 * and the application controls tail of the sq ring and the head of the
128 struct io_uring sq, cq;
130 * Bitmasks to apply to head and tail offsets (constant, equals
133 u32 sq_ring_mask, cq_ring_mask;
134 /* Ring sizes (constant, power of 2) */
135 u32 sq_ring_entries, cq_ring_entries;
137 * Number of invalid entries dropped by the kernel due to
138 * invalid index stored in array
140 * Written by the kernel, shouldn't be modified by the
141 * application (i.e. get number of "new events" by comparing to
144 * After a new SQ head value was read by the application this
145 * counter includes all submissions that were dropped reaching
146 * the new SQ head (and possibly more).
152 * Written by the kernel, shouldn't be modified by the
155 * The application needs a full memory barrier before checking
156 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
162 * Written by the application, shouldn't be modified by the
167 * Number of completion events lost because the queue was full;
168 * this should be avoided by the application by making sure
169 * there are not more requests pending than there is space in
170 * the completion queue.
172 * Written by the kernel, shouldn't be modified by the
173 * application (i.e. get number of "new events" by comparing to
176 * As completion events come in out of order this counter is not
177 * ordered with any other data.
181 * Ring buffer of completion events.
183 * The kernel writes completion events fresh every time they are
184 * produced, so the application is allowed to modify pending
187 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
190 enum io_uring_cmd_flags {
191 IO_URING_F_NONBLOCK = 1,
192 IO_URING_F_COMPLETE_DEFER = 2,
195 struct io_mapped_ubuf {
198 struct bio_vec *bvec;
199 unsigned int nr_bvecs;
200 unsigned long acct_pages;
205 struct io_overflow_cqe {
206 struct io_uring_cqe cqe;
207 struct list_head list;
211 struct list_head list;
218 struct fixed_rsrc_table {
222 struct io_rsrc_node {
223 struct percpu_ref refs;
224 struct list_head node;
225 struct list_head rsrc_list;
226 struct io_rsrc_data *rsrc_data;
227 struct llist_node llist;
231 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
233 struct io_rsrc_data {
234 struct fixed_rsrc_table *table;
235 struct io_ring_ctx *ctx;
238 struct percpu_ref refs;
239 struct completion done;
244 struct list_head list;
250 struct io_restriction {
251 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
252 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
253 u8 sqe_flags_allowed;
254 u8 sqe_flags_required;
259 IO_SQ_THREAD_SHOULD_STOP = 0,
260 IO_SQ_THREAD_SHOULD_PARK,
265 atomic_t park_pending;
268 /* ctx's that are using this sqd */
269 struct list_head ctx_list;
271 struct task_struct *thread;
272 struct wait_queue_head wait;
274 unsigned sq_thread_idle;
280 struct completion exited;
281 struct callback_head *park_task_work;
284 #define IO_IOPOLL_BATCH 8
285 #define IO_COMPL_BATCH 32
286 #define IO_REQ_CACHE_SIZE 32
287 #define IO_REQ_ALLOC_BATCH 8
289 struct io_comp_state {
290 struct io_kiocb *reqs[IO_COMPL_BATCH];
292 unsigned int locked_free_nr;
293 /* inline/task_work completion list, under ->uring_lock */
294 struct list_head free_list;
295 /* IRQ completion list, under ->completion_lock */
296 struct list_head locked_free_list;
299 struct io_submit_link {
300 struct io_kiocb *head;
301 struct io_kiocb *last;
304 struct io_submit_state {
305 struct blk_plug plug;
306 struct io_submit_link link;
309 * io_kiocb alloc cache
311 void *reqs[IO_REQ_CACHE_SIZE];
312 unsigned int free_reqs;
317 * Batch completion logic
319 struct io_comp_state comp;
322 * File reference cache
326 unsigned int file_refs;
327 unsigned int ios_left;
332 struct percpu_ref refs;
333 } ____cacheline_aligned_in_smp;
337 unsigned int compat: 1;
338 unsigned int cq_overflow_flushed: 1;
339 unsigned int drain_next: 1;
340 unsigned int eventfd_async: 1;
341 unsigned int restricted: 1;
344 * Ring buffer of indices into array of io_uring_sqe, which is
345 * mmapped by the application using the IORING_OFF_SQES offset.
347 * This indirection could e.g. be used to assign fixed
348 * io_uring_sqe entries to operations and only submit them to
349 * the queue when needed.
351 * The kernel modifies neither the indices array nor the entries
355 unsigned cached_sq_head;
358 unsigned sq_thread_idle;
359 unsigned cached_sq_dropped;
360 unsigned cached_cq_overflow;
361 unsigned long sq_check_overflow;
363 /* hashed buffered write serialization */
364 struct io_wq_hash *hash_map;
366 struct list_head defer_list;
367 struct list_head timeout_list;
368 struct list_head cq_overflow_list;
370 struct io_uring_sqe *sq_sqes;
371 } ____cacheline_aligned_in_smp;
374 struct mutex uring_lock;
375 wait_queue_head_t wait;
376 } ____cacheline_aligned_in_smp;
378 struct io_submit_state submit_state;
380 struct io_rings *rings;
382 /* Only used for accounting purposes */
383 struct mm_struct *mm_account;
385 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
386 struct io_sq_data *sq_data; /* if using sq thread polling */
388 struct wait_queue_head sqo_sq_wait;
389 struct list_head sqd_list;
392 * If used, fixed file set. Writers must ensure that ->refs is dead,
393 * readers must ensure that ->refs is alive as long as the file* is
394 * used. Only updated through io_uring_register(2).
396 struct io_rsrc_data *file_data;
397 unsigned nr_user_files;
399 /* if used, fixed mapped user buffers */
400 unsigned nr_user_bufs;
401 struct io_mapped_ubuf *user_bufs;
403 struct user_struct *user;
405 struct completion ref_comp;
407 #if defined(CONFIG_UNIX)
408 struct socket *ring_sock;
411 struct xarray io_buffers;
413 struct xarray personalities;
417 unsigned cached_cq_tail;
420 atomic_t cq_timeouts;
421 unsigned cq_last_tm_flush;
422 unsigned long cq_check_overflow;
423 struct wait_queue_head cq_wait;
424 struct fasync_struct *cq_fasync;
425 struct eventfd_ctx *cq_ev_fd;
426 } ____cacheline_aligned_in_smp;
429 spinlock_t completion_lock;
432 * ->iopoll_list is protected by the ctx->uring_lock for
433 * io_uring instances that don't use IORING_SETUP_SQPOLL.
434 * For SQPOLL, only the single threaded io_sq_thread() will
435 * manipulate the list, hence no extra locking is needed there.
437 struct list_head iopoll_list;
438 struct hlist_head *cancel_hash;
439 unsigned cancel_hash_bits;
440 bool poll_multi_file;
442 spinlock_t inflight_lock;
443 struct list_head inflight_list;
444 } ____cacheline_aligned_in_smp;
446 struct delayed_work rsrc_put_work;
447 struct llist_head rsrc_put_llist;
448 struct list_head rsrc_ref_list;
449 spinlock_t rsrc_ref_lock;
450 struct io_rsrc_node *rsrc_node;
451 struct io_rsrc_node *rsrc_backup_node;
453 struct io_restriction restrictions;
456 struct callback_head *exit_task_work;
458 struct wait_queue_head hash_wait;
460 /* Keep this last, we don't need it for the fast path */
461 struct work_struct exit_work;
462 struct list_head tctx_list;
465 struct io_uring_task {
466 /* submission side */
468 struct wait_queue_head wait;
469 const struct io_ring_ctx *last;
471 struct percpu_counter inflight;
474 spinlock_t task_lock;
475 struct io_wq_work_list task_list;
476 unsigned long task_state;
477 struct callback_head task_work;
481 * First field must be the file pointer in all the
482 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
484 struct io_poll_iocb {
486 struct wait_queue_head *head;
491 bool update_user_data;
493 struct wait_queue_entry wait;
501 struct io_poll_remove {
511 struct io_timeout_data {
512 struct io_kiocb *req;
513 struct hrtimer timer;
514 struct timespec64 ts;
515 enum hrtimer_mode mode;
520 struct sockaddr __user *addr;
521 int __user *addr_len;
523 unsigned long nofile;
543 struct list_head list;
544 /* head of the link, used by linked timeouts only */
545 struct io_kiocb *head;
548 struct io_timeout_rem {
553 struct timespec64 ts;
558 /* NOTE: kiocb has the file as the first member, so don't do it here */
566 struct sockaddr __user *addr;
573 struct user_msghdr __user *umsg;
579 struct io_buffer *kbuf;
585 struct filename *filename;
587 unsigned long nofile;
590 struct io_rsrc_update {
616 struct epoll_event event;
620 struct file *file_out;
621 struct file *file_in;
628 struct io_provide_buf {
642 const char __user *filename;
643 struct statx __user *buffer;
655 struct filename *oldpath;
656 struct filename *newpath;
664 struct filename *filename;
667 struct io_completion {
669 struct list_head list;
673 struct io_async_connect {
674 struct sockaddr_storage address;
677 struct io_async_msghdr {
678 struct iovec fast_iov[UIO_FASTIOV];
679 /* points to an allocated iov, if NULL we use fast_iov instead */
680 struct iovec *free_iov;
681 struct sockaddr __user *uaddr;
683 struct sockaddr_storage addr;
687 struct iovec fast_iov[UIO_FASTIOV];
688 const struct iovec *free_iovec;
689 struct iov_iter iter;
691 struct wait_page_queue wpq;
695 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
696 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
697 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
698 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
699 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
700 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
706 REQ_F_LINK_TIMEOUT_BIT,
707 REQ_F_NEED_CLEANUP_BIT,
709 REQ_F_BUFFER_SELECTED_BIT,
710 REQ_F_LTIMEOUT_ACTIVE_BIT,
711 REQ_F_COMPLETE_INLINE_BIT,
713 REQ_F_DONT_REISSUE_BIT,
714 /* keep async read/write and isreg together and in order */
715 REQ_F_ASYNC_READ_BIT,
716 REQ_F_ASYNC_WRITE_BIT,
719 /* not a real bit, just to check we're not overflowing the space */
725 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
726 /* drain existing IO first */
727 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
729 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
730 /* doesn't sever on completion < 0 */
731 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
733 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
734 /* IOSQE_BUFFER_SELECT */
735 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
737 /* fail rest of links */
738 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
739 /* on inflight list, should be cancelled and waited on exit reliably */
740 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
741 /* read/write uses file position */
742 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
743 /* must not punt to workers */
744 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
745 /* has or had linked timeout */
746 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
748 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
749 /* already went through poll handler */
750 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
751 /* buffer already selected */
752 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
753 /* linked timeout is active, i.e. prepared by link's head */
754 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
755 /* completion is deferred through io_comp_state */
756 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
757 /* caller should reissue async */
758 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
759 /* don't attempt request reissue, see io_rw_reissue() */
760 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
761 /* supports async reads */
762 REQ_F_ASYNC_READ = BIT(REQ_F_ASYNC_READ_BIT),
763 /* supports async writes */
764 REQ_F_ASYNC_WRITE = BIT(REQ_F_ASYNC_WRITE_BIT),
766 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
770 struct io_poll_iocb poll;
771 struct io_poll_iocb *double_poll;
774 struct io_task_work {
775 struct io_wq_work_node node;
776 task_work_func_t func;
780 * NOTE! Each of the iocb union members has the file pointer
781 * as the first entry in their struct definition. So you can
782 * access the file pointer through any of the sub-structs,
783 * or directly as just 'ki_filp' in this struct.
789 struct io_poll_iocb poll;
790 struct io_poll_remove poll_remove;
791 struct io_accept accept;
793 struct io_cancel cancel;
794 struct io_timeout timeout;
795 struct io_timeout_rem timeout_rem;
796 struct io_connect connect;
797 struct io_sr_msg sr_msg;
799 struct io_close close;
800 struct io_rsrc_update rsrc_update;
801 struct io_fadvise fadvise;
802 struct io_madvise madvise;
803 struct io_epoll epoll;
804 struct io_splice splice;
805 struct io_provide_buf pbuf;
806 struct io_statx statx;
807 struct io_shutdown shutdown;
808 struct io_rename rename;
809 struct io_unlink unlink;
810 /* use only after cleaning per-op data, see io_clean_op() */
811 struct io_completion compl;
814 /* opcode allocated if it needs to store data for async defer */
817 /* polled IO has completed */
823 struct io_ring_ctx *ctx;
826 struct task_struct *task;
829 struct io_kiocb *link;
830 struct percpu_ref *fixed_rsrc_refs;
833 * 1. used with ctx->iopoll_list with reads/writes
834 * 2. to track reqs with ->files (see io_op_def::file_table)
836 struct list_head inflight_entry;
838 struct io_task_work io_task_work;
839 struct callback_head task_work;
841 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
842 struct hlist_node hash_node;
843 struct async_poll *apoll;
844 struct io_wq_work work;
847 struct io_tctx_node {
848 struct list_head ctx_node;
849 struct task_struct *task;
850 struct io_ring_ctx *ctx;
853 struct io_defer_entry {
854 struct list_head list;
855 struct io_kiocb *req;
860 /* needs req->file assigned */
861 unsigned needs_file : 1;
862 /* hash wq insertion if file is a regular file */
863 unsigned hash_reg_file : 1;
864 /* unbound wq insertion if file is a non-regular file */
865 unsigned unbound_nonreg_file : 1;
866 /* opcode is not supported by this kernel */
867 unsigned not_supported : 1;
868 /* set if opcode supports polled "wait" */
870 unsigned pollout : 1;
871 /* op supports buffer selection */
872 unsigned buffer_select : 1;
873 /* do prep async if is going to be punted */
874 unsigned needs_async_setup : 1;
875 /* should block plug */
877 /* size of async data needed, if any */
878 unsigned short async_size;
881 static const struct io_op_def io_op_defs[] = {
882 [IORING_OP_NOP] = {},
883 [IORING_OP_READV] = {
885 .unbound_nonreg_file = 1,
888 .needs_async_setup = 1,
890 .async_size = sizeof(struct io_async_rw),
892 [IORING_OP_WRITEV] = {
895 .unbound_nonreg_file = 1,
897 .needs_async_setup = 1,
899 .async_size = sizeof(struct io_async_rw),
901 [IORING_OP_FSYNC] = {
904 [IORING_OP_READ_FIXED] = {
906 .unbound_nonreg_file = 1,
909 .async_size = sizeof(struct io_async_rw),
911 [IORING_OP_WRITE_FIXED] = {
914 .unbound_nonreg_file = 1,
917 .async_size = sizeof(struct io_async_rw),
919 [IORING_OP_POLL_ADD] = {
921 .unbound_nonreg_file = 1,
923 [IORING_OP_POLL_REMOVE] = {},
924 [IORING_OP_SYNC_FILE_RANGE] = {
927 [IORING_OP_SENDMSG] = {
929 .unbound_nonreg_file = 1,
931 .needs_async_setup = 1,
932 .async_size = sizeof(struct io_async_msghdr),
934 [IORING_OP_RECVMSG] = {
936 .unbound_nonreg_file = 1,
939 .needs_async_setup = 1,
940 .async_size = sizeof(struct io_async_msghdr),
942 [IORING_OP_TIMEOUT] = {
943 .async_size = sizeof(struct io_timeout_data),
945 [IORING_OP_TIMEOUT_REMOVE] = {
946 /* used by timeout updates' prep() */
948 [IORING_OP_ACCEPT] = {
950 .unbound_nonreg_file = 1,
953 [IORING_OP_ASYNC_CANCEL] = {},
954 [IORING_OP_LINK_TIMEOUT] = {
955 .async_size = sizeof(struct io_timeout_data),
957 [IORING_OP_CONNECT] = {
959 .unbound_nonreg_file = 1,
961 .needs_async_setup = 1,
962 .async_size = sizeof(struct io_async_connect),
964 [IORING_OP_FALLOCATE] = {
967 [IORING_OP_OPENAT] = {},
968 [IORING_OP_CLOSE] = {},
969 [IORING_OP_FILES_UPDATE] = {},
970 [IORING_OP_STATX] = {},
973 .unbound_nonreg_file = 1,
977 .async_size = sizeof(struct io_async_rw),
979 [IORING_OP_WRITE] = {
981 .unbound_nonreg_file = 1,
984 .async_size = sizeof(struct io_async_rw),
986 [IORING_OP_FADVISE] = {
989 [IORING_OP_MADVISE] = {},
992 .unbound_nonreg_file = 1,
997 .unbound_nonreg_file = 1,
1001 [IORING_OP_OPENAT2] = {
1003 [IORING_OP_EPOLL_CTL] = {
1004 .unbound_nonreg_file = 1,
1006 [IORING_OP_SPLICE] = {
1009 .unbound_nonreg_file = 1,
1011 [IORING_OP_PROVIDE_BUFFERS] = {},
1012 [IORING_OP_REMOVE_BUFFERS] = {},
1016 .unbound_nonreg_file = 1,
1018 [IORING_OP_SHUTDOWN] = {
1021 [IORING_OP_RENAMEAT] = {},
1022 [IORING_OP_UNLINKAT] = {},
1025 static bool io_disarm_next(struct io_kiocb *req);
1026 static void io_uring_del_task_file(unsigned long index);
1027 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1028 struct task_struct *task,
1029 struct files_struct *files);
1030 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
1031 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
1032 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
1034 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1035 static void io_put_req(struct io_kiocb *req);
1036 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1037 static void io_dismantle_req(struct io_kiocb *req);
1038 static void io_put_task(struct task_struct *task, int nr);
1039 static void io_queue_next(struct io_kiocb *req);
1040 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1041 static void io_queue_linked_timeout(struct io_kiocb *req);
1042 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1043 struct io_uring_rsrc_update *ip,
1045 static void io_clean_op(struct io_kiocb *req);
1046 static struct file *io_file_get(struct io_submit_state *state,
1047 struct io_kiocb *req, int fd, bool fixed);
1048 static void __io_queue_sqe(struct io_kiocb *req);
1049 static void io_rsrc_put_work(struct work_struct *work);
1051 static void io_req_task_queue(struct io_kiocb *req);
1052 static void io_submit_flush_completions(struct io_comp_state *cs,
1053 struct io_ring_ctx *ctx);
1054 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1055 static int io_req_prep_async(struct io_kiocb *req);
1057 static struct kmem_cache *req_cachep;
1059 static const struct file_operations io_uring_fops;
1061 struct sock *io_uring_get_socket(struct file *file)
1063 #if defined(CONFIG_UNIX)
1064 if (file->f_op == &io_uring_fops) {
1065 struct io_ring_ctx *ctx = file->private_data;
1067 return ctx->ring_sock->sk;
1072 EXPORT_SYMBOL(io_uring_get_socket);
1074 #define io_for_each_link(pos, head) \
1075 for (pos = (head); pos; pos = pos->link)
1077 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1079 struct io_ring_ctx *ctx = req->ctx;
1081 if (!req->fixed_rsrc_refs) {
1082 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1083 percpu_ref_get(req->fixed_rsrc_refs);
1087 static bool io_match_task(struct io_kiocb *head,
1088 struct task_struct *task,
1089 struct files_struct *files)
1091 struct io_kiocb *req;
1093 if (task && head->task != task)
1098 io_for_each_link(req, head) {
1099 if (req->flags & REQ_F_INFLIGHT)
1105 static inline void req_set_fail_links(struct io_kiocb *req)
1107 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1108 req->flags |= REQ_F_FAIL_LINK;
1111 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1113 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1115 complete(&ctx->ref_comp);
1118 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1120 return !req->timeout.off;
1123 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1125 struct io_ring_ctx *ctx;
1128 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1133 * Use 5 bits less than the max cq entries, that should give us around
1134 * 32 entries per hash list if totally full and uniformly spread.
1136 hash_bits = ilog2(p->cq_entries);
1140 ctx->cancel_hash_bits = hash_bits;
1141 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1143 if (!ctx->cancel_hash)
1145 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1147 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1148 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1151 ctx->flags = p->flags;
1152 init_waitqueue_head(&ctx->sqo_sq_wait);
1153 INIT_LIST_HEAD(&ctx->sqd_list);
1154 init_waitqueue_head(&ctx->cq_wait);
1155 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1156 init_completion(&ctx->ref_comp);
1157 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1158 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1159 mutex_init(&ctx->uring_lock);
1160 init_waitqueue_head(&ctx->wait);
1161 spin_lock_init(&ctx->completion_lock);
1162 INIT_LIST_HEAD(&ctx->iopoll_list);
1163 INIT_LIST_HEAD(&ctx->defer_list);
1164 INIT_LIST_HEAD(&ctx->timeout_list);
1165 spin_lock_init(&ctx->inflight_lock);
1166 INIT_LIST_HEAD(&ctx->inflight_list);
1167 spin_lock_init(&ctx->rsrc_ref_lock);
1168 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1169 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1170 init_llist_head(&ctx->rsrc_put_llist);
1171 INIT_LIST_HEAD(&ctx->tctx_list);
1172 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1173 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1176 kfree(ctx->cancel_hash);
1181 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1183 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1184 struct io_ring_ctx *ctx = req->ctx;
1186 return seq != ctx->cached_cq_tail
1187 + READ_ONCE(ctx->cached_cq_overflow);
1193 static void io_req_track_inflight(struct io_kiocb *req)
1195 struct io_ring_ctx *ctx = req->ctx;
1197 if (!(req->flags & REQ_F_INFLIGHT)) {
1198 req->flags |= REQ_F_INFLIGHT;
1200 spin_lock_irq(&ctx->inflight_lock);
1201 list_add(&req->inflight_entry, &ctx->inflight_list);
1202 spin_unlock_irq(&ctx->inflight_lock);
1206 static void io_prep_async_work(struct io_kiocb *req)
1208 const struct io_op_def *def = &io_op_defs[req->opcode];
1209 struct io_ring_ctx *ctx = req->ctx;
1211 if (!req->work.creds)
1212 req->work.creds = get_current_cred();
1214 req->work.list.next = NULL;
1215 req->work.flags = 0;
1216 if (req->flags & REQ_F_FORCE_ASYNC)
1217 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1219 if (req->flags & REQ_F_ISREG) {
1220 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1221 io_wq_hash_work(&req->work, file_inode(req->file));
1222 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1223 if (def->unbound_nonreg_file)
1224 req->work.flags |= IO_WQ_WORK_UNBOUND;
1227 switch (req->opcode) {
1228 case IORING_OP_SPLICE:
1231 * Splice operation will be punted aync, and here need to
1232 * modify io_wq_work.flags, so initialize io_wq_work firstly.
1234 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1235 req->work.flags |= IO_WQ_WORK_UNBOUND;
1240 static void io_prep_async_link(struct io_kiocb *req)
1242 struct io_kiocb *cur;
1244 io_for_each_link(cur, req)
1245 io_prep_async_work(cur);
1248 static void io_queue_async_work(struct io_kiocb *req)
1250 struct io_ring_ctx *ctx = req->ctx;
1251 struct io_kiocb *link = io_prep_linked_timeout(req);
1252 struct io_uring_task *tctx = req->task->io_uring;
1255 BUG_ON(!tctx->io_wq);
1257 /* init ->work of the whole link before punting */
1258 io_prep_async_link(req);
1259 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1260 &req->work, req->flags);
1261 io_wq_enqueue(tctx->io_wq, &req->work);
1263 io_queue_linked_timeout(link);
1266 static void io_kill_timeout(struct io_kiocb *req, int status)
1268 struct io_timeout_data *io = req->async_data;
1271 ret = hrtimer_try_to_cancel(&io->timer);
1273 atomic_set(&req->ctx->cq_timeouts,
1274 atomic_read(&req->ctx->cq_timeouts) + 1);
1275 list_del_init(&req->timeout.list);
1276 io_cqring_fill_event(req, status);
1277 io_put_req_deferred(req, 1);
1281 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1284 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1285 struct io_defer_entry, list);
1287 if (req_need_defer(de->req, de->seq))
1289 list_del_init(&de->list);
1290 io_req_task_queue(de->req);
1292 } while (!list_empty(&ctx->defer_list));
1295 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1299 if (list_empty(&ctx->timeout_list))
1302 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1305 u32 events_needed, events_got;
1306 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1307 struct io_kiocb, timeout.list);
1309 if (io_is_timeout_noseq(req))
1313 * Since seq can easily wrap around over time, subtract
1314 * the last seq at which timeouts were flushed before comparing.
1315 * Assuming not more than 2^31-1 events have happened since,
1316 * these subtractions won't have wrapped, so we can check if
1317 * target is in [last_seq, current_seq] by comparing the two.
1319 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1320 events_got = seq - ctx->cq_last_tm_flush;
1321 if (events_got < events_needed)
1324 list_del_init(&req->timeout.list);
1325 io_kill_timeout(req, 0);
1326 } while (!list_empty(&ctx->timeout_list));
1328 ctx->cq_last_tm_flush = seq;
1331 static void io_commit_cqring(struct io_ring_ctx *ctx)
1333 io_flush_timeouts(ctx);
1335 /* order cqe stores with ring update */
1336 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1338 if (unlikely(!list_empty(&ctx->defer_list)))
1339 __io_queue_deferred(ctx);
1342 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1344 struct io_rings *r = ctx->rings;
1346 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1349 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1351 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1354 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1356 struct io_rings *rings = ctx->rings;
1360 * writes to the cq entry need to come after reading head; the
1361 * control dependency is enough as we're using WRITE_ONCE to
1364 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1367 tail = ctx->cached_cq_tail++;
1368 return &rings->cqes[tail & ctx->cq_mask];
1371 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1375 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1377 if (!ctx->eventfd_async)
1379 return io_wq_current_is_worker();
1382 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1384 /* see waitqueue_active() comment */
1387 if (waitqueue_active(&ctx->wait))
1388 wake_up(&ctx->wait);
1389 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1390 wake_up(&ctx->sq_data->wait);
1391 if (io_should_trigger_evfd(ctx))
1392 eventfd_signal(ctx->cq_ev_fd, 1);
1393 if (waitqueue_active(&ctx->cq_wait)) {
1394 wake_up_interruptible(&ctx->cq_wait);
1395 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1399 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1401 /* see waitqueue_active() comment */
1404 if (ctx->flags & IORING_SETUP_SQPOLL) {
1405 if (waitqueue_active(&ctx->wait))
1406 wake_up(&ctx->wait);
1408 if (io_should_trigger_evfd(ctx))
1409 eventfd_signal(ctx->cq_ev_fd, 1);
1410 if (waitqueue_active(&ctx->cq_wait)) {
1411 wake_up_interruptible(&ctx->cq_wait);
1412 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1416 /* Returns true if there are no backlogged entries after the flush */
1417 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1419 struct io_rings *rings = ctx->rings;
1420 unsigned long flags;
1421 bool all_flushed, posted;
1423 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1427 spin_lock_irqsave(&ctx->completion_lock, flags);
1428 while (!list_empty(&ctx->cq_overflow_list)) {
1429 struct io_uring_cqe *cqe = io_get_cqring(ctx);
1430 struct io_overflow_cqe *ocqe;
1434 ocqe = list_first_entry(&ctx->cq_overflow_list,
1435 struct io_overflow_cqe, list);
1437 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1439 WRITE_ONCE(ctx->rings->cq_overflow,
1440 ++ctx->cached_cq_overflow);
1442 list_del(&ocqe->list);
1446 all_flushed = list_empty(&ctx->cq_overflow_list);
1448 clear_bit(0, &ctx->sq_check_overflow);
1449 clear_bit(0, &ctx->cq_check_overflow);
1450 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1454 io_commit_cqring(ctx);
1455 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1457 io_cqring_ev_posted(ctx);
1461 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1465 if (test_bit(0, &ctx->cq_check_overflow)) {
1466 /* iopoll syncs against uring_lock, not completion_lock */
1467 if (ctx->flags & IORING_SETUP_IOPOLL)
1468 mutex_lock(&ctx->uring_lock);
1469 ret = __io_cqring_overflow_flush(ctx, force);
1470 if (ctx->flags & IORING_SETUP_IOPOLL)
1471 mutex_unlock(&ctx->uring_lock);
1478 * Shamelessly stolen from the mm implementation of page reference checking,
1479 * see commit f958d7b528b1 for details.
1481 #define req_ref_zero_or_close_to_overflow(req) \
1482 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1484 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1486 return atomic_inc_not_zero(&req->refs);
1489 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1491 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1492 return atomic_sub_and_test(refs, &req->refs);
1495 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1497 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1498 return atomic_dec_and_test(&req->refs);
1501 static inline void req_ref_put(struct io_kiocb *req)
1503 WARN_ON_ONCE(req_ref_put_and_test(req));
1506 static inline void req_ref_get(struct io_kiocb *req)
1508 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1509 atomic_inc(&req->refs);
1512 static bool __io_cqring_fill_event(struct io_kiocb *req, long res,
1513 unsigned int cflags)
1515 struct io_ring_ctx *ctx = req->ctx;
1516 struct io_uring_cqe *cqe;
1518 trace_io_uring_complete(ctx, req->user_data, res, cflags);
1521 * If we can't get a cq entry, userspace overflowed the
1522 * submission (by quite a lot). Increment the overflow count in
1525 cqe = io_get_cqring(ctx);
1527 WRITE_ONCE(cqe->user_data, req->user_data);
1528 WRITE_ONCE(cqe->res, res);
1529 WRITE_ONCE(cqe->flags, cflags);
1532 if (!ctx->cq_overflow_flushed &&
1533 !atomic_read(&req->task->io_uring->in_idle)) {
1534 struct io_overflow_cqe *ocqe;
1536 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1539 if (list_empty(&ctx->cq_overflow_list)) {
1540 set_bit(0, &ctx->sq_check_overflow);
1541 set_bit(0, &ctx->cq_check_overflow);
1542 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1544 ocqe->cqe.user_data = req->user_data;
1545 ocqe->cqe.res = res;
1546 ocqe->cqe.flags = cflags;
1547 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1552 * If we're in ring overflow flush mode, or in task cancel mode,
1553 * or cannot allocate an overflow entry, then we need to drop it
1556 WRITE_ONCE(ctx->rings->cq_overflow, ++ctx->cached_cq_overflow);
1560 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1562 __io_cqring_fill_event(req, res, 0);
1565 static void io_req_complete_post(struct io_kiocb *req, long res,
1566 unsigned int cflags)
1568 struct io_ring_ctx *ctx = req->ctx;
1569 unsigned long flags;
1571 spin_lock_irqsave(&ctx->completion_lock, flags);
1572 __io_cqring_fill_event(req, res, cflags);
1574 * If we're the last reference to this request, add to our locked
1577 if (req_ref_put_and_test(req)) {
1578 struct io_comp_state *cs = &ctx->submit_state.comp;
1580 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1581 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
1582 io_disarm_next(req);
1584 io_req_task_queue(req->link);
1588 io_dismantle_req(req);
1589 io_put_task(req->task, 1);
1590 list_add(&req->compl.list, &cs->locked_free_list);
1591 cs->locked_free_nr++;
1593 if (!percpu_ref_tryget(&ctx->refs))
1596 io_commit_cqring(ctx);
1597 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1600 io_cqring_ev_posted(ctx);
1601 percpu_ref_put(&ctx->refs);
1605 static void io_req_complete_state(struct io_kiocb *req, long res,
1606 unsigned int cflags)
1608 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1611 req->compl.cflags = cflags;
1612 req->flags |= REQ_F_COMPLETE_INLINE;
1615 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1616 long res, unsigned cflags)
1618 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1619 io_req_complete_state(req, res, cflags);
1621 io_req_complete_post(req, res, cflags);
1624 static inline void io_req_complete(struct io_kiocb *req, long res)
1626 __io_req_complete(req, 0, res, 0);
1629 static void io_req_complete_failed(struct io_kiocb *req, long res)
1631 req_set_fail_links(req);
1633 io_req_complete_post(req, res, 0);
1636 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1637 struct io_comp_state *cs)
1639 spin_lock_irq(&ctx->completion_lock);
1640 list_splice_init(&cs->locked_free_list, &cs->free_list);
1641 cs->locked_free_nr = 0;
1642 spin_unlock_irq(&ctx->completion_lock);
1645 /* Returns true IFF there are requests in the cache */
1646 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1648 struct io_submit_state *state = &ctx->submit_state;
1649 struct io_comp_state *cs = &state->comp;
1653 * If we have more than a batch's worth of requests in our IRQ side
1654 * locked cache, grab the lock and move them over to our submission
1657 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH)
1658 io_flush_cached_locked_reqs(ctx, cs);
1660 nr = state->free_reqs;
1661 while (!list_empty(&cs->free_list)) {
1662 struct io_kiocb *req = list_first_entry(&cs->free_list,
1663 struct io_kiocb, compl.list);
1665 list_del(&req->compl.list);
1666 state->reqs[nr++] = req;
1667 if (nr == ARRAY_SIZE(state->reqs))
1671 state->free_reqs = nr;
1675 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1677 struct io_submit_state *state = &ctx->submit_state;
1679 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1681 if (!state->free_reqs) {
1682 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1685 if (io_flush_cached_reqs(ctx))
1688 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1692 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1693 * retry single alloc to be on the safe side.
1695 if (unlikely(ret <= 0)) {
1696 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1697 if (!state->reqs[0])
1701 state->free_reqs = ret;
1705 return state->reqs[state->free_reqs];
1708 static inline void io_put_file(struct file *file)
1714 static void io_dismantle_req(struct io_kiocb *req)
1716 unsigned int flags = req->flags;
1718 if (!(flags & REQ_F_FIXED_FILE))
1719 io_put_file(req->file);
1720 if (flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED |
1724 if (req->flags & REQ_F_INFLIGHT) {
1725 struct io_ring_ctx *ctx = req->ctx;
1726 unsigned long flags;
1728 spin_lock_irqsave(&ctx->inflight_lock, flags);
1729 list_del(&req->inflight_entry);
1730 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1731 req->flags &= ~REQ_F_INFLIGHT;
1734 if (req->fixed_rsrc_refs)
1735 percpu_ref_put(req->fixed_rsrc_refs);
1736 if (req->async_data)
1737 kfree(req->async_data);
1738 if (req->work.creds) {
1739 put_cred(req->work.creds);
1740 req->work.creds = NULL;
1744 /* must to be called somewhat shortly after putting a request */
1745 static inline void io_put_task(struct task_struct *task, int nr)
1747 struct io_uring_task *tctx = task->io_uring;
1749 percpu_counter_sub(&tctx->inflight, nr);
1750 if (unlikely(atomic_read(&tctx->in_idle)))
1751 wake_up(&tctx->wait);
1752 put_task_struct_many(task, nr);
1755 static void __io_free_req(struct io_kiocb *req)
1757 struct io_ring_ctx *ctx = req->ctx;
1759 io_dismantle_req(req);
1760 io_put_task(req->task, 1);
1762 kmem_cache_free(req_cachep, req);
1763 percpu_ref_put(&ctx->refs);
1766 static inline void io_remove_next_linked(struct io_kiocb *req)
1768 struct io_kiocb *nxt = req->link;
1770 req->link = nxt->link;
1774 static bool io_kill_linked_timeout(struct io_kiocb *req)
1775 __must_hold(&req->ctx->completion_lock)
1777 struct io_kiocb *link = req->link;
1780 * Can happen if a linked timeout fired and link had been like
1781 * req -> link t-out -> link t-out [-> ...]
1783 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1784 struct io_timeout_data *io = link->async_data;
1787 io_remove_next_linked(req);
1788 link->timeout.head = NULL;
1789 ret = hrtimer_try_to_cancel(&io->timer);
1791 io_cqring_fill_event(link, -ECANCELED);
1792 io_put_req_deferred(link, 1);
1799 static void io_fail_links(struct io_kiocb *req)
1800 __must_hold(&req->ctx->completion_lock)
1802 struct io_kiocb *nxt, *link = req->link;
1809 trace_io_uring_fail_link(req, link);
1810 io_cqring_fill_event(link, -ECANCELED);
1811 io_put_req_deferred(link, 2);
1816 static bool io_disarm_next(struct io_kiocb *req)
1817 __must_hold(&req->ctx->completion_lock)
1819 bool posted = false;
1821 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1822 posted = io_kill_linked_timeout(req);
1823 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
1824 posted |= (req->link != NULL);
1830 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1832 struct io_kiocb *nxt;
1835 * If LINK is set, we have dependent requests in this chain. If we
1836 * didn't fail this request, queue the first one up, moving any other
1837 * dependencies to the next request. In case of failure, fail the rest
1840 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK)) {
1841 struct io_ring_ctx *ctx = req->ctx;
1842 unsigned long flags;
1845 spin_lock_irqsave(&ctx->completion_lock, flags);
1846 posted = io_disarm_next(req);
1848 io_commit_cqring(req->ctx);
1849 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1851 io_cqring_ev_posted(ctx);
1858 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1860 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1862 return __io_req_find_next(req);
1865 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1869 if (ctx->submit_state.comp.nr) {
1870 mutex_lock(&ctx->uring_lock);
1871 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1872 mutex_unlock(&ctx->uring_lock);
1874 percpu_ref_put(&ctx->refs);
1877 static bool __tctx_task_work(struct io_uring_task *tctx)
1879 struct io_ring_ctx *ctx = NULL;
1880 struct io_wq_work_list list;
1881 struct io_wq_work_node *node;
1883 if (wq_list_empty(&tctx->task_list))
1886 spin_lock_irq(&tctx->task_lock);
1887 list = tctx->task_list;
1888 INIT_WQ_LIST(&tctx->task_list);
1889 spin_unlock_irq(&tctx->task_lock);
1893 struct io_wq_work_node *next = node->next;
1894 struct io_kiocb *req;
1896 req = container_of(node, struct io_kiocb, io_task_work.node);
1897 if (req->ctx != ctx) {
1898 ctx_flush_and_put(ctx);
1900 percpu_ref_get(&ctx->refs);
1903 req->task_work.func(&req->task_work);
1907 ctx_flush_and_put(ctx);
1908 return list.first != NULL;
1911 static void tctx_task_work(struct callback_head *cb)
1913 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1915 clear_bit(0, &tctx->task_state);
1917 while (__tctx_task_work(tctx))
1921 static int io_req_task_work_add(struct io_kiocb *req)
1923 struct task_struct *tsk = req->task;
1924 struct io_uring_task *tctx = tsk->io_uring;
1925 enum task_work_notify_mode notify;
1926 struct io_wq_work_node *node, *prev;
1927 unsigned long flags;
1930 if (unlikely(tsk->flags & PF_EXITING))
1933 WARN_ON_ONCE(!tctx);
1935 spin_lock_irqsave(&tctx->task_lock, flags);
1936 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1937 spin_unlock_irqrestore(&tctx->task_lock, flags);
1939 /* task_work already pending, we're done */
1940 if (test_bit(0, &tctx->task_state) ||
1941 test_and_set_bit(0, &tctx->task_state))
1945 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1946 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1947 * processing task_work. There's no reliable way to tell if TWA_RESUME
1950 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
1952 if (!task_work_add(tsk, &tctx->task_work, notify)) {
1953 wake_up_process(tsk);
1958 * Slow path - we failed, find and delete work. if the work is not
1959 * in the list, it got run and we're fine.
1961 spin_lock_irqsave(&tctx->task_lock, flags);
1962 wq_list_for_each(node, prev, &tctx->task_list) {
1963 if (&req->io_task_work.node == node) {
1964 wq_list_del(&tctx->task_list, node, prev);
1969 spin_unlock_irqrestore(&tctx->task_lock, flags);
1970 clear_bit(0, &tctx->task_state);
1974 static bool io_run_task_work_head(struct callback_head **work_head)
1976 struct callback_head *work, *next;
1977 bool executed = false;
1980 work = xchg(work_head, NULL);
1996 static void io_task_work_add_head(struct callback_head **work_head,
1997 struct callback_head *task_work)
1999 struct callback_head *head;
2002 head = READ_ONCE(*work_head);
2003 task_work->next = head;
2004 } while (cmpxchg(work_head, head, task_work) != head);
2007 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2008 task_work_func_t cb)
2010 init_task_work(&req->task_work, cb);
2011 io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
2014 static void io_req_task_cancel(struct callback_head *cb)
2016 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2017 struct io_ring_ctx *ctx = req->ctx;
2019 /* ctx is guaranteed to stay alive while we hold uring_lock */
2020 mutex_lock(&ctx->uring_lock);
2021 io_req_complete_failed(req, req->result);
2022 mutex_unlock(&ctx->uring_lock);
2025 static void __io_req_task_submit(struct io_kiocb *req)
2027 struct io_ring_ctx *ctx = req->ctx;
2029 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2030 mutex_lock(&ctx->uring_lock);
2031 if (!(current->flags & PF_EXITING) && !current->in_execve)
2032 __io_queue_sqe(req);
2034 io_req_complete_failed(req, -EFAULT);
2035 mutex_unlock(&ctx->uring_lock);
2038 static void io_req_task_submit(struct callback_head *cb)
2040 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2042 __io_req_task_submit(req);
2045 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2048 req->task_work.func = io_req_task_cancel;
2050 if (unlikely(io_req_task_work_add(req)))
2051 io_req_task_work_add_fallback(req, io_req_task_cancel);
2054 static void io_req_task_queue(struct io_kiocb *req)
2056 req->task_work.func = io_req_task_submit;
2058 if (unlikely(io_req_task_work_add(req)))
2059 io_req_task_queue_fail(req, -ECANCELED);
2062 static inline void io_queue_next(struct io_kiocb *req)
2064 struct io_kiocb *nxt = io_req_find_next(req);
2067 io_req_task_queue(nxt);
2070 static void io_free_req(struct io_kiocb *req)
2077 struct task_struct *task;
2082 static inline void io_init_req_batch(struct req_batch *rb)
2089 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2090 struct req_batch *rb)
2093 io_put_task(rb->task, rb->task_refs);
2095 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2098 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2099 struct io_submit_state *state)
2102 io_dismantle_req(req);
2104 if (req->task != rb->task) {
2106 io_put_task(rb->task, rb->task_refs);
2107 rb->task = req->task;
2113 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2114 state->reqs[state->free_reqs++] = req;
2116 list_add(&req->compl.list, &state->comp.free_list);
2119 static void io_submit_flush_completions(struct io_comp_state *cs,
2120 struct io_ring_ctx *ctx)
2123 struct io_kiocb *req;
2124 struct req_batch rb;
2126 io_init_req_batch(&rb);
2127 spin_lock_irq(&ctx->completion_lock);
2128 for (i = 0; i < nr; i++) {
2130 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2132 io_commit_cqring(ctx);
2133 spin_unlock_irq(&ctx->completion_lock);
2135 io_cqring_ev_posted(ctx);
2136 for (i = 0; i < nr; i++) {
2139 /* submission and completion refs */
2140 if (req_ref_sub_and_test(req, 2))
2141 io_req_free_batch(&rb, req, &ctx->submit_state);
2144 io_req_free_batch_finish(ctx, &rb);
2149 * Drop reference to request, return next in chain (if there is one) if this
2150 * was the last reference to this request.
2152 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2154 struct io_kiocb *nxt = NULL;
2156 if (req_ref_put_and_test(req)) {
2157 nxt = io_req_find_next(req);
2163 static inline void io_put_req(struct io_kiocb *req)
2165 if (req_ref_put_and_test(req))
2169 static void io_put_req_deferred_cb(struct callback_head *cb)
2171 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2176 static void io_free_req_deferred(struct io_kiocb *req)
2178 req->task_work.func = io_put_req_deferred_cb;
2179 if (unlikely(io_req_task_work_add(req)))
2180 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2183 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2185 if (req_ref_sub_and_test(req, refs))
2186 io_free_req_deferred(req);
2189 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2191 /* See comment at the top of this file */
2193 return __io_cqring_events(ctx);
2196 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2198 struct io_rings *rings = ctx->rings;
2200 /* make sure SQ entry isn't read before tail */
2201 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2204 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2206 unsigned int cflags;
2208 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2209 cflags |= IORING_CQE_F_BUFFER;
2210 req->flags &= ~REQ_F_BUFFER_SELECTED;
2215 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2217 struct io_buffer *kbuf;
2219 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2220 return io_put_kbuf(req, kbuf);
2223 static inline bool io_run_task_work(void)
2226 * Not safe to run on exiting task, and the task_work handling will
2227 * not add work to such a task.
2229 if (unlikely(current->flags & PF_EXITING))
2231 if (current->task_works) {
2232 __set_current_state(TASK_RUNNING);
2241 * Find and free completed poll iocbs
2243 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2244 struct list_head *done)
2246 struct req_batch rb;
2247 struct io_kiocb *req;
2249 /* order with ->result store in io_complete_rw_iopoll() */
2252 io_init_req_batch(&rb);
2253 while (!list_empty(done)) {
2256 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2257 list_del(&req->inflight_entry);
2259 if (READ_ONCE(req->result) == -EAGAIN &&
2260 !(req->flags & REQ_F_DONT_REISSUE)) {
2261 req->iopoll_completed = 0;
2263 io_queue_async_work(req);
2267 if (req->flags & REQ_F_BUFFER_SELECTED)
2268 cflags = io_put_rw_kbuf(req);
2270 __io_cqring_fill_event(req, req->result, cflags);
2273 if (req_ref_put_and_test(req))
2274 io_req_free_batch(&rb, req, &ctx->submit_state);
2277 io_commit_cqring(ctx);
2278 io_cqring_ev_posted_iopoll(ctx);
2279 io_req_free_batch_finish(ctx, &rb);
2282 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2285 struct io_kiocb *req, *tmp;
2291 * Only spin for completions if we don't have multiple devices hanging
2292 * off our complete list, and we're under the requested amount.
2294 spin = !ctx->poll_multi_file && *nr_events < min;
2297 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2298 struct kiocb *kiocb = &req->rw.kiocb;
2301 * Move completed and retryable entries to our local lists.
2302 * If we find a request that requires polling, break out
2303 * and complete those lists first, if we have entries there.
2305 if (READ_ONCE(req->iopoll_completed)) {
2306 list_move_tail(&req->inflight_entry, &done);
2309 if (!list_empty(&done))
2312 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2316 /* iopoll may have completed current req */
2317 if (READ_ONCE(req->iopoll_completed))
2318 list_move_tail(&req->inflight_entry, &done);
2325 if (!list_empty(&done))
2326 io_iopoll_complete(ctx, nr_events, &done);
2332 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2333 * non-spinning poll check - we'll still enter the driver poll loop, but only
2334 * as a non-spinning completion check.
2336 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2339 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2342 ret = io_do_iopoll(ctx, nr_events, min);
2345 if (*nr_events >= min)
2353 * We can't just wait for polled events to come to us, we have to actively
2354 * find and complete them.
2356 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2358 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2361 mutex_lock(&ctx->uring_lock);
2362 while (!list_empty(&ctx->iopoll_list)) {
2363 unsigned int nr_events = 0;
2365 io_do_iopoll(ctx, &nr_events, 0);
2367 /* let it sleep and repeat later if can't complete a request */
2371 * Ensure we allow local-to-the-cpu processing to take place,
2372 * in this case we need to ensure that we reap all events.
2373 * Also let task_work, etc. to progress by releasing the mutex
2375 if (need_resched()) {
2376 mutex_unlock(&ctx->uring_lock);
2378 mutex_lock(&ctx->uring_lock);
2381 mutex_unlock(&ctx->uring_lock);
2384 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2386 unsigned int nr_events = 0;
2387 int iters = 0, ret = 0;
2390 * We disallow the app entering submit/complete with polling, but we
2391 * still need to lock the ring to prevent racing with polled issue
2392 * that got punted to a workqueue.
2394 mutex_lock(&ctx->uring_lock);
2397 * Don't enter poll loop if we already have events pending.
2398 * If we do, we can potentially be spinning for commands that
2399 * already triggered a CQE (eg in error).
2401 if (test_bit(0, &ctx->cq_check_overflow))
2402 __io_cqring_overflow_flush(ctx, false);
2403 if (io_cqring_events(ctx))
2407 * If a submit got punted to a workqueue, we can have the
2408 * application entering polling for a command before it gets
2409 * issued. That app will hold the uring_lock for the duration
2410 * of the poll right here, so we need to take a breather every
2411 * now and then to ensure that the issue has a chance to add
2412 * the poll to the issued list. Otherwise we can spin here
2413 * forever, while the workqueue is stuck trying to acquire the
2416 if (!(++iters & 7)) {
2417 mutex_unlock(&ctx->uring_lock);
2419 mutex_lock(&ctx->uring_lock);
2422 ret = io_iopoll_getevents(ctx, &nr_events, min);
2426 } while (min && !nr_events && !need_resched());
2428 mutex_unlock(&ctx->uring_lock);
2432 static void kiocb_end_write(struct io_kiocb *req)
2435 * Tell lockdep we inherited freeze protection from submission
2438 if (req->flags & REQ_F_ISREG) {
2439 struct super_block *sb = file_inode(req->file)->i_sb;
2441 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2447 static bool io_resubmit_prep(struct io_kiocb *req)
2449 struct io_async_rw *rw = req->async_data;
2452 return !io_req_prep_async(req);
2453 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2454 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2458 static bool io_rw_should_reissue(struct io_kiocb *req)
2460 umode_t mode = file_inode(req->file)->i_mode;
2461 struct io_ring_ctx *ctx = req->ctx;
2463 if (!S_ISBLK(mode) && !S_ISREG(mode))
2465 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2466 !(ctx->flags & IORING_SETUP_IOPOLL)))
2469 * If ref is dying, we might be running poll reap from the exit work.
2470 * Don't attempt to reissue from that path, just let it fail with
2473 if (percpu_ref_is_dying(&ctx->refs))
2478 static bool io_rw_should_reissue(struct io_kiocb *req)
2484 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2485 unsigned int issue_flags)
2489 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2490 kiocb_end_write(req);
2491 if (res != req->result) {
2492 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2493 io_rw_should_reissue(req)) {
2494 req->flags |= REQ_F_REISSUE;
2497 req_set_fail_links(req);
2499 if (req->flags & REQ_F_BUFFER_SELECTED)
2500 cflags = io_put_rw_kbuf(req);
2501 __io_req_complete(req, issue_flags, res, cflags);
2504 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2506 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2508 __io_complete_rw(req, res, res2, 0);
2511 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2513 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2515 if (kiocb->ki_flags & IOCB_WRITE)
2516 kiocb_end_write(req);
2517 if (unlikely(res != req->result)) {
2521 if (res == -EAGAIN && io_rw_should_reissue(req) &&
2522 io_resubmit_prep(req))
2526 req_set_fail_links(req);
2527 req->flags |= REQ_F_DONT_REISSUE;
2531 WRITE_ONCE(req->result, res);
2532 /* order with io_iopoll_complete() checking ->result */
2534 WRITE_ONCE(req->iopoll_completed, 1);
2538 * After the iocb has been issued, it's safe to be found on the poll list.
2539 * Adding the kiocb to the list AFTER submission ensures that we don't
2540 * find it from a io_iopoll_getevents() thread before the issuer is done
2541 * accessing the kiocb cookie.
2543 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2545 struct io_ring_ctx *ctx = req->ctx;
2548 * Track whether we have multiple files in our lists. This will impact
2549 * how we do polling eventually, not spinning if we're on potentially
2550 * different devices.
2552 if (list_empty(&ctx->iopoll_list)) {
2553 ctx->poll_multi_file = false;
2554 } else if (!ctx->poll_multi_file) {
2555 struct io_kiocb *list_req;
2557 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2559 if (list_req->file != req->file)
2560 ctx->poll_multi_file = true;
2564 * For fast devices, IO may have already completed. If it has, add
2565 * it to the front so we find it first.
2567 if (READ_ONCE(req->iopoll_completed))
2568 list_add(&req->inflight_entry, &ctx->iopoll_list);
2570 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2573 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2574 * task context or in io worker task context. If current task context is
2575 * sq thread, we don't need to check whether should wake up sq thread.
2577 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2578 wq_has_sleeper(&ctx->sq_data->wait))
2579 wake_up(&ctx->sq_data->wait);
2582 static inline void io_state_file_put(struct io_submit_state *state)
2584 if (state->file_refs) {
2585 fput_many(state->file, state->file_refs);
2586 state->file_refs = 0;
2591 * Get as many references to a file as we have IOs left in this submission,
2592 * assuming most submissions are for one file, or at least that each file
2593 * has more than one submission.
2595 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2600 if (state->file_refs) {
2601 if (state->fd == fd) {
2605 io_state_file_put(state);
2607 state->file = fget_many(fd, state->ios_left);
2608 if (unlikely(!state->file))
2612 state->file_refs = state->ios_left - 1;
2616 static bool io_bdev_nowait(struct block_device *bdev)
2618 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2622 * If we tracked the file through the SCM inflight mechanism, we could support
2623 * any file. For now, just ensure that anything potentially problematic is done
2626 static bool __io_file_supports_async(struct file *file, int rw)
2628 umode_t mode = file_inode(file)->i_mode;
2630 if (S_ISBLK(mode)) {
2631 if (IS_ENABLED(CONFIG_BLOCK) &&
2632 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2636 if (S_ISCHR(mode) || S_ISSOCK(mode))
2638 if (S_ISREG(mode)) {
2639 if (IS_ENABLED(CONFIG_BLOCK) &&
2640 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2641 file->f_op != &io_uring_fops)
2646 /* any ->read/write should understand O_NONBLOCK */
2647 if (file->f_flags & O_NONBLOCK)
2650 if (!(file->f_mode & FMODE_NOWAIT))
2654 return file->f_op->read_iter != NULL;
2656 return file->f_op->write_iter != NULL;
2659 static bool io_file_supports_async(struct io_kiocb *req, int rw)
2661 if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
2663 else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
2666 return __io_file_supports_async(req->file, rw);
2669 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2671 struct io_ring_ctx *ctx = req->ctx;
2672 struct kiocb *kiocb = &req->rw.kiocb;
2673 struct file *file = req->file;
2677 if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
2678 req->flags |= REQ_F_ISREG;
2680 kiocb->ki_pos = READ_ONCE(sqe->off);
2681 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2682 req->flags |= REQ_F_CUR_POS;
2683 kiocb->ki_pos = file->f_pos;
2685 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2686 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2687 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2691 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2692 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2693 req->flags |= REQ_F_NOWAIT;
2695 ioprio = READ_ONCE(sqe->ioprio);
2697 ret = ioprio_check_cap(ioprio);
2701 kiocb->ki_ioprio = ioprio;
2703 kiocb->ki_ioprio = get_current_ioprio();
2705 if (ctx->flags & IORING_SETUP_IOPOLL) {
2706 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2707 !kiocb->ki_filp->f_op->iopoll)
2710 kiocb->ki_flags |= IOCB_HIPRI;
2711 kiocb->ki_complete = io_complete_rw_iopoll;
2712 req->iopoll_completed = 0;
2714 if (kiocb->ki_flags & IOCB_HIPRI)
2716 kiocb->ki_complete = io_complete_rw;
2719 req->rw.addr = READ_ONCE(sqe->addr);
2720 req->rw.len = READ_ONCE(sqe->len);
2721 req->buf_index = READ_ONCE(sqe->buf_index);
2725 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2731 case -ERESTARTNOINTR:
2732 case -ERESTARTNOHAND:
2733 case -ERESTART_RESTARTBLOCK:
2735 * We can't just restart the syscall, since previously
2736 * submitted sqes may already be in progress. Just fail this
2742 kiocb->ki_complete(kiocb, ret, 0);
2746 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2747 unsigned int issue_flags)
2749 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2750 struct io_async_rw *io = req->async_data;
2751 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2753 /* add previously done IO, if any */
2754 if (io && io->bytes_done > 0) {
2756 ret = io->bytes_done;
2758 ret += io->bytes_done;
2761 if (req->flags & REQ_F_CUR_POS)
2762 req->file->f_pos = kiocb->ki_pos;
2763 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2764 __io_complete_rw(req, ret, 0, issue_flags);
2766 io_rw_done(kiocb, ret);
2768 if (check_reissue && req->flags & REQ_F_REISSUE) {
2769 req->flags &= ~REQ_F_REISSUE;
2770 if (!io_resubmit_prep(req)) {
2772 io_queue_async_work(req);
2776 req_set_fail_links(req);
2777 if (req->flags & REQ_F_BUFFER_SELECTED)
2778 cflags = io_put_rw_kbuf(req);
2779 __io_req_complete(req, issue_flags, ret, cflags);
2784 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2786 struct io_ring_ctx *ctx = req->ctx;
2787 size_t len = req->rw.len;
2788 struct io_mapped_ubuf *imu;
2789 u16 index, buf_index = req->buf_index;
2793 if (unlikely(buf_index >= ctx->nr_user_bufs))
2795 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2796 imu = &ctx->user_bufs[index];
2797 buf_addr = req->rw.addr;
2800 if (buf_addr + len < buf_addr)
2802 /* not inside the mapped region */
2803 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2807 * May not be a start of buffer, set size appropriately
2808 * and advance us to the beginning.
2810 offset = buf_addr - imu->ubuf;
2811 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2815 * Don't use iov_iter_advance() here, as it's really slow for
2816 * using the latter parts of a big fixed buffer - it iterates
2817 * over each segment manually. We can cheat a bit here, because
2820 * 1) it's a BVEC iter, we set it up
2821 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2822 * first and last bvec
2824 * So just find our index, and adjust the iterator afterwards.
2825 * If the offset is within the first bvec (or the whole first
2826 * bvec, just use iov_iter_advance(). This makes it easier
2827 * since we can just skip the first segment, which may not
2828 * be PAGE_SIZE aligned.
2830 const struct bio_vec *bvec = imu->bvec;
2832 if (offset <= bvec->bv_len) {
2833 iov_iter_advance(iter, offset);
2835 unsigned long seg_skip;
2837 /* skip first vec */
2838 offset -= bvec->bv_len;
2839 seg_skip = 1 + (offset >> PAGE_SHIFT);
2841 iter->bvec = bvec + seg_skip;
2842 iter->nr_segs -= seg_skip;
2843 iter->count -= bvec->bv_len + offset;
2844 iter->iov_offset = offset & ~PAGE_MASK;
2851 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2854 mutex_unlock(&ctx->uring_lock);
2857 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2860 * "Normal" inline submissions always hold the uring_lock, since we
2861 * grab it from the system call. Same is true for the SQPOLL offload.
2862 * The only exception is when we've detached the request and issue it
2863 * from an async worker thread, grab the lock for that case.
2866 mutex_lock(&ctx->uring_lock);
2869 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2870 int bgid, struct io_buffer *kbuf,
2873 struct io_buffer *head;
2875 if (req->flags & REQ_F_BUFFER_SELECTED)
2878 io_ring_submit_lock(req->ctx, needs_lock);
2880 lockdep_assert_held(&req->ctx->uring_lock);
2882 head = xa_load(&req->ctx->io_buffers, bgid);
2884 if (!list_empty(&head->list)) {
2885 kbuf = list_last_entry(&head->list, struct io_buffer,
2887 list_del(&kbuf->list);
2890 xa_erase(&req->ctx->io_buffers, bgid);
2892 if (*len > kbuf->len)
2895 kbuf = ERR_PTR(-ENOBUFS);
2898 io_ring_submit_unlock(req->ctx, needs_lock);
2903 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2906 struct io_buffer *kbuf;
2909 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2910 bgid = req->buf_index;
2911 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2914 req->rw.addr = (u64) (unsigned long) kbuf;
2915 req->flags |= REQ_F_BUFFER_SELECTED;
2916 return u64_to_user_ptr(kbuf->addr);
2919 #ifdef CONFIG_COMPAT
2920 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2923 struct compat_iovec __user *uiov;
2924 compat_ssize_t clen;
2928 uiov = u64_to_user_ptr(req->rw.addr);
2929 if (!access_ok(uiov, sizeof(*uiov)))
2931 if (__get_user(clen, &uiov->iov_len))
2937 buf = io_rw_buffer_select(req, &len, needs_lock);
2939 return PTR_ERR(buf);
2940 iov[0].iov_base = buf;
2941 iov[0].iov_len = (compat_size_t) len;
2946 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2949 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2953 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2956 len = iov[0].iov_len;
2959 buf = io_rw_buffer_select(req, &len, needs_lock);
2961 return PTR_ERR(buf);
2962 iov[0].iov_base = buf;
2963 iov[0].iov_len = len;
2967 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2970 if (req->flags & REQ_F_BUFFER_SELECTED) {
2971 struct io_buffer *kbuf;
2973 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2974 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2975 iov[0].iov_len = kbuf->len;
2978 if (req->rw.len != 1)
2981 #ifdef CONFIG_COMPAT
2982 if (req->ctx->compat)
2983 return io_compat_import(req, iov, needs_lock);
2986 return __io_iov_buffer_select(req, iov, needs_lock);
2989 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2990 struct iov_iter *iter, bool needs_lock)
2992 void __user *buf = u64_to_user_ptr(req->rw.addr);
2993 size_t sqe_len = req->rw.len;
2994 u8 opcode = req->opcode;
2997 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2999 return io_import_fixed(req, rw, iter);
3002 /* buffer index only valid with fixed read/write, or buffer select */
3003 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3006 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3007 if (req->flags & REQ_F_BUFFER_SELECT) {
3008 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3010 return PTR_ERR(buf);
3011 req->rw.len = sqe_len;
3014 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3019 if (req->flags & REQ_F_BUFFER_SELECT) {
3020 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3022 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3027 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3031 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3033 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3037 * For files that don't have ->read_iter() and ->write_iter(), handle them
3038 * by looping over ->read() or ->write() manually.
3040 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3042 struct kiocb *kiocb = &req->rw.kiocb;
3043 struct file *file = req->file;
3047 * Don't support polled IO through this interface, and we can't
3048 * support non-blocking either. For the latter, this just causes
3049 * the kiocb to be handled from an async context.
3051 if (kiocb->ki_flags & IOCB_HIPRI)
3053 if (kiocb->ki_flags & IOCB_NOWAIT)
3056 while (iov_iter_count(iter)) {
3060 if (!iov_iter_is_bvec(iter)) {
3061 iovec = iov_iter_iovec(iter);
3063 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3064 iovec.iov_len = req->rw.len;
3068 nr = file->f_op->read(file, iovec.iov_base,
3069 iovec.iov_len, io_kiocb_ppos(kiocb));
3071 nr = file->f_op->write(file, iovec.iov_base,
3072 iovec.iov_len, io_kiocb_ppos(kiocb));
3081 if (nr != iovec.iov_len)
3085 iov_iter_advance(iter, nr);
3091 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3092 const struct iovec *fast_iov, struct iov_iter *iter)
3094 struct io_async_rw *rw = req->async_data;
3096 memcpy(&rw->iter, iter, sizeof(*iter));
3097 rw->free_iovec = iovec;
3099 /* can only be fixed buffers, no need to do anything */
3100 if (iov_iter_is_bvec(iter))
3103 unsigned iov_off = 0;
3105 rw->iter.iov = rw->fast_iov;
3106 if (iter->iov != fast_iov) {
3107 iov_off = iter->iov - fast_iov;
3108 rw->iter.iov += iov_off;
3110 if (rw->fast_iov != fast_iov)
3111 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3112 sizeof(struct iovec) * iter->nr_segs);
3114 req->flags |= REQ_F_NEED_CLEANUP;
3118 static inline int io_alloc_async_data(struct io_kiocb *req)
3120 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3121 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3122 return req->async_data == NULL;
3125 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3126 const struct iovec *fast_iov,
3127 struct iov_iter *iter, bool force)
3129 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3131 if (!req->async_data) {
3132 if (io_alloc_async_data(req)) {
3137 io_req_map_rw(req, iovec, fast_iov, iter);
3142 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3144 struct io_async_rw *iorw = req->async_data;
3145 struct iovec *iov = iorw->fast_iov;
3148 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3149 if (unlikely(ret < 0))
3152 iorw->bytes_done = 0;
3153 iorw->free_iovec = iov;
3155 req->flags |= REQ_F_NEED_CLEANUP;
3159 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3161 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3163 return io_prep_rw(req, sqe);
3167 * This is our waitqueue callback handler, registered through lock_page_async()
3168 * when we initially tried to do the IO with the iocb armed our waitqueue.
3169 * This gets called when the page is unlocked, and we generally expect that to
3170 * happen when the page IO is completed and the page is now uptodate. This will
3171 * queue a task_work based retry of the operation, attempting to copy the data
3172 * again. If the latter fails because the page was NOT uptodate, then we will
3173 * do a thread based blocking retry of the operation. That's the unexpected
3176 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3177 int sync, void *arg)
3179 struct wait_page_queue *wpq;
3180 struct io_kiocb *req = wait->private;
3181 struct wait_page_key *key = arg;
3183 wpq = container_of(wait, struct wait_page_queue, wait);
3185 if (!wake_page_match(wpq, key))
3188 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3189 list_del_init(&wait->entry);
3191 /* submit ref gets dropped, acquire a new one */
3193 io_req_task_queue(req);
3198 * This controls whether a given IO request should be armed for async page
3199 * based retry. If we return false here, the request is handed to the async
3200 * worker threads for retry. If we're doing buffered reads on a regular file,
3201 * we prepare a private wait_page_queue entry and retry the operation. This
3202 * will either succeed because the page is now uptodate and unlocked, or it
3203 * will register a callback when the page is unlocked at IO completion. Through
3204 * that callback, io_uring uses task_work to setup a retry of the operation.
3205 * That retry will attempt the buffered read again. The retry will generally
3206 * succeed, or in rare cases where it fails, we then fall back to using the
3207 * async worker threads for a blocking retry.
3209 static bool io_rw_should_retry(struct io_kiocb *req)
3211 struct io_async_rw *rw = req->async_data;
3212 struct wait_page_queue *wait = &rw->wpq;
3213 struct kiocb *kiocb = &req->rw.kiocb;
3215 /* never retry for NOWAIT, we just complete with -EAGAIN */
3216 if (req->flags & REQ_F_NOWAIT)
3219 /* Only for buffered IO */
3220 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3224 * just use poll if we can, and don't attempt if the fs doesn't
3225 * support callback based unlocks
3227 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3230 wait->wait.func = io_async_buf_func;
3231 wait->wait.private = req;
3232 wait->wait.flags = 0;
3233 INIT_LIST_HEAD(&wait->wait.entry);
3234 kiocb->ki_flags |= IOCB_WAITQ;
3235 kiocb->ki_flags &= ~IOCB_NOWAIT;
3236 kiocb->ki_waitq = wait;
3240 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3242 if (req->file->f_op->read_iter)
3243 return call_read_iter(req->file, &req->rw.kiocb, iter);
3244 else if (req->file->f_op->read)
3245 return loop_rw_iter(READ, req, iter);
3250 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3252 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3253 struct kiocb *kiocb = &req->rw.kiocb;
3254 struct iov_iter __iter, *iter = &__iter;
3255 struct io_async_rw *rw = req->async_data;
3256 ssize_t io_size, ret, ret2;
3257 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3263 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3267 io_size = iov_iter_count(iter);
3268 req->result = io_size;
3270 /* Ensure we clear previously set non-block flag */
3271 if (!force_nonblock)
3272 kiocb->ki_flags &= ~IOCB_NOWAIT;
3274 kiocb->ki_flags |= IOCB_NOWAIT;
3276 /* If the file doesn't support async, just async punt */
3277 if (force_nonblock && !io_file_supports_async(req, READ)) {
3278 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3279 return ret ?: -EAGAIN;
3282 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3283 if (unlikely(ret)) {
3288 ret = io_iter_do_read(req, iter);
3290 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3291 req->flags &= ~REQ_F_REISSUE;
3292 /* IOPOLL retry should happen for io-wq threads */
3293 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3295 /* no retry on NONBLOCK nor RWF_NOWAIT */
3296 if (req->flags & REQ_F_NOWAIT)
3298 /* some cases will consume bytes even on error returns */
3299 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3301 } else if (ret == -EIOCBQUEUED) {
3303 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3304 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3305 /* read all, failed, already did sync or don't want to retry */
3309 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3314 rw = req->async_data;
3315 /* now use our persistent iterator, if we aren't already */
3320 rw->bytes_done += ret;
3321 /* if we can retry, do so with the callbacks armed */
3322 if (!io_rw_should_retry(req)) {
3323 kiocb->ki_flags &= ~IOCB_WAITQ;
3328 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3329 * we get -EIOCBQUEUED, then we'll get a notification when the
3330 * desired page gets unlocked. We can also get a partial read
3331 * here, and if we do, then just retry at the new offset.
3333 ret = io_iter_do_read(req, iter);
3334 if (ret == -EIOCBQUEUED)
3336 /* we got some bytes, but not all. retry. */
3337 kiocb->ki_flags &= ~IOCB_WAITQ;
3338 } while (ret > 0 && ret < io_size);
3340 kiocb_done(kiocb, ret, issue_flags);
3342 /* it's faster to check here then delegate to kfree */
3348 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3350 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3352 return io_prep_rw(req, sqe);
3355 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3357 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3358 struct kiocb *kiocb = &req->rw.kiocb;
3359 struct iov_iter __iter, *iter = &__iter;
3360 struct io_async_rw *rw = req->async_data;
3361 ssize_t ret, ret2, io_size;
3362 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3368 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3372 io_size = iov_iter_count(iter);
3373 req->result = io_size;
3375 /* Ensure we clear previously set non-block flag */
3376 if (!force_nonblock)
3377 kiocb->ki_flags &= ~IOCB_NOWAIT;
3379 kiocb->ki_flags |= IOCB_NOWAIT;
3381 /* If the file doesn't support async, just async punt */
3382 if (force_nonblock && !io_file_supports_async(req, WRITE))
3385 /* file path doesn't support NOWAIT for non-direct_IO */
3386 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3387 (req->flags & REQ_F_ISREG))
3390 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3395 * Open-code file_start_write here to grab freeze protection,
3396 * which will be released by another thread in
3397 * io_complete_rw(). Fool lockdep by telling it the lock got
3398 * released so that it doesn't complain about the held lock when
3399 * we return to userspace.
3401 if (req->flags & REQ_F_ISREG) {
3402 sb_start_write(file_inode(req->file)->i_sb);
3403 __sb_writers_release(file_inode(req->file)->i_sb,
3406 kiocb->ki_flags |= IOCB_WRITE;
3408 if (req->file->f_op->write_iter)
3409 ret2 = call_write_iter(req->file, kiocb, iter);
3410 else if (req->file->f_op->write)
3411 ret2 = loop_rw_iter(WRITE, req, iter);
3415 if (req->flags & REQ_F_REISSUE) {
3416 req->flags &= ~REQ_F_REISSUE;
3421 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3422 * retry them without IOCB_NOWAIT.
3424 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3426 /* no retry on NONBLOCK nor RWF_NOWAIT */
3427 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3429 if (!force_nonblock || ret2 != -EAGAIN) {
3430 /* IOPOLL retry should happen for io-wq threads */
3431 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3434 kiocb_done(kiocb, ret2, issue_flags);
3437 /* some cases will consume bytes even on error returns */
3438 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3439 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3440 return ret ?: -EAGAIN;
3443 /* it's reportedly faster than delegating the null check to kfree() */
3449 static int io_renameat_prep(struct io_kiocb *req,
3450 const struct io_uring_sqe *sqe)
3452 struct io_rename *ren = &req->rename;
3453 const char __user *oldf, *newf;
3455 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3458 ren->old_dfd = READ_ONCE(sqe->fd);
3459 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3460 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3461 ren->new_dfd = READ_ONCE(sqe->len);
3462 ren->flags = READ_ONCE(sqe->rename_flags);
3464 ren->oldpath = getname(oldf);
3465 if (IS_ERR(ren->oldpath))
3466 return PTR_ERR(ren->oldpath);
3468 ren->newpath = getname(newf);
3469 if (IS_ERR(ren->newpath)) {
3470 putname(ren->oldpath);
3471 return PTR_ERR(ren->newpath);
3474 req->flags |= REQ_F_NEED_CLEANUP;
3478 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3480 struct io_rename *ren = &req->rename;
3483 if (issue_flags & IO_URING_F_NONBLOCK)
3486 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3487 ren->newpath, ren->flags);
3489 req->flags &= ~REQ_F_NEED_CLEANUP;
3491 req_set_fail_links(req);
3492 io_req_complete(req, ret);
3496 static int io_unlinkat_prep(struct io_kiocb *req,
3497 const struct io_uring_sqe *sqe)
3499 struct io_unlink *un = &req->unlink;
3500 const char __user *fname;
3502 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3505 un->dfd = READ_ONCE(sqe->fd);
3507 un->flags = READ_ONCE(sqe->unlink_flags);
3508 if (un->flags & ~AT_REMOVEDIR)
3511 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3512 un->filename = getname(fname);
3513 if (IS_ERR(un->filename))
3514 return PTR_ERR(un->filename);
3516 req->flags |= REQ_F_NEED_CLEANUP;
3520 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3522 struct io_unlink *un = &req->unlink;
3525 if (issue_flags & IO_URING_F_NONBLOCK)
3528 if (un->flags & AT_REMOVEDIR)
3529 ret = do_rmdir(un->dfd, un->filename);
3531 ret = do_unlinkat(un->dfd, un->filename);
3533 req->flags &= ~REQ_F_NEED_CLEANUP;
3535 req_set_fail_links(req);
3536 io_req_complete(req, ret);
3540 static int io_shutdown_prep(struct io_kiocb *req,
3541 const struct io_uring_sqe *sqe)
3543 #if defined(CONFIG_NET)
3544 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3546 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3550 req->shutdown.how = READ_ONCE(sqe->len);
3557 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3559 #if defined(CONFIG_NET)
3560 struct socket *sock;
3563 if (issue_flags & IO_URING_F_NONBLOCK)
3566 sock = sock_from_file(req->file);
3567 if (unlikely(!sock))
3570 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3572 req_set_fail_links(req);
3573 io_req_complete(req, ret);
3580 static int __io_splice_prep(struct io_kiocb *req,
3581 const struct io_uring_sqe *sqe)
3583 struct io_splice* sp = &req->splice;
3584 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3586 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3590 sp->len = READ_ONCE(sqe->len);
3591 sp->flags = READ_ONCE(sqe->splice_flags);
3593 if (unlikely(sp->flags & ~valid_flags))
3596 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3597 (sp->flags & SPLICE_F_FD_IN_FIXED));
3600 req->flags |= REQ_F_NEED_CLEANUP;
3604 static int io_tee_prep(struct io_kiocb *req,
3605 const struct io_uring_sqe *sqe)
3607 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3609 return __io_splice_prep(req, sqe);
3612 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3614 struct io_splice *sp = &req->splice;
3615 struct file *in = sp->file_in;
3616 struct file *out = sp->file_out;
3617 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3620 if (issue_flags & IO_URING_F_NONBLOCK)
3623 ret = do_tee(in, out, sp->len, flags);
3625 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3627 req->flags &= ~REQ_F_NEED_CLEANUP;
3630 req_set_fail_links(req);
3631 io_req_complete(req, ret);
3635 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3637 struct io_splice* sp = &req->splice;
3639 sp->off_in = READ_ONCE(sqe->splice_off_in);
3640 sp->off_out = READ_ONCE(sqe->off);
3641 return __io_splice_prep(req, sqe);
3644 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3646 struct io_splice *sp = &req->splice;
3647 struct file *in = sp->file_in;
3648 struct file *out = sp->file_out;
3649 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3650 loff_t *poff_in, *poff_out;
3653 if (issue_flags & IO_URING_F_NONBLOCK)
3656 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3657 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3660 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3662 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3664 req->flags &= ~REQ_F_NEED_CLEANUP;
3667 req_set_fail_links(req);
3668 io_req_complete(req, ret);
3673 * IORING_OP_NOP just posts a completion event, nothing else.
3675 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3677 struct io_ring_ctx *ctx = req->ctx;
3679 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3682 __io_req_complete(req, issue_flags, 0, 0);
3686 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3688 struct io_ring_ctx *ctx = req->ctx;
3693 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3695 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3698 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3699 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3702 req->sync.off = READ_ONCE(sqe->off);
3703 req->sync.len = READ_ONCE(sqe->len);
3707 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3709 loff_t end = req->sync.off + req->sync.len;
3712 /* fsync always requires a blocking context */
3713 if (issue_flags & IO_URING_F_NONBLOCK)
3716 ret = vfs_fsync_range(req->file, req->sync.off,
3717 end > 0 ? end : LLONG_MAX,
3718 req->sync.flags & IORING_FSYNC_DATASYNC);
3720 req_set_fail_links(req);
3721 io_req_complete(req, ret);
3725 static int io_fallocate_prep(struct io_kiocb *req,
3726 const struct io_uring_sqe *sqe)
3728 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3730 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3733 req->sync.off = READ_ONCE(sqe->off);
3734 req->sync.len = READ_ONCE(sqe->addr);
3735 req->sync.mode = READ_ONCE(sqe->len);
3739 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3743 /* fallocate always requiring blocking context */
3744 if (issue_flags & IO_URING_F_NONBLOCK)
3746 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3749 req_set_fail_links(req);
3750 io_req_complete(req, ret);
3754 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3756 const char __user *fname;
3759 if (unlikely(sqe->ioprio || sqe->buf_index))
3761 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3764 /* open.how should be already initialised */
3765 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3766 req->open.how.flags |= O_LARGEFILE;
3768 req->open.dfd = READ_ONCE(sqe->fd);
3769 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3770 req->open.filename = getname(fname);
3771 if (IS_ERR(req->open.filename)) {
3772 ret = PTR_ERR(req->open.filename);
3773 req->open.filename = NULL;
3776 req->open.nofile = rlimit(RLIMIT_NOFILE);
3777 req->flags |= REQ_F_NEED_CLEANUP;
3781 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3785 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3787 mode = READ_ONCE(sqe->len);
3788 flags = READ_ONCE(sqe->open_flags);
3789 req->open.how = build_open_how(flags, mode);
3790 return __io_openat_prep(req, sqe);
3793 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3795 struct open_how __user *how;
3799 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3801 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3802 len = READ_ONCE(sqe->len);
3803 if (len < OPEN_HOW_SIZE_VER0)
3806 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3811 return __io_openat_prep(req, sqe);
3814 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3816 struct open_flags op;
3819 bool resolve_nonblock;
3822 ret = build_open_flags(&req->open.how, &op);
3825 nonblock_set = op.open_flag & O_NONBLOCK;
3826 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3827 if (issue_flags & IO_URING_F_NONBLOCK) {
3829 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3830 * it'll always -EAGAIN
3832 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3834 op.lookup_flags |= LOOKUP_CACHED;
3835 op.open_flag |= O_NONBLOCK;
3838 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3842 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3843 /* only retry if RESOLVE_CACHED wasn't already set by application */
3844 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3845 file == ERR_PTR(-EAGAIN)) {
3847 * We could hang on to this 'fd', but seems like marginal
3848 * gain for something that is now known to be a slower path.
3849 * So just put it, and we'll get a new one when we retry.
3857 ret = PTR_ERR(file);
3859 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3860 file->f_flags &= ~O_NONBLOCK;
3861 fsnotify_open(file);
3862 fd_install(ret, file);
3865 putname(req->open.filename);
3866 req->flags &= ~REQ_F_NEED_CLEANUP;
3868 req_set_fail_links(req);
3869 io_req_complete(req, ret);
3873 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3875 return io_openat2(req, issue_flags);
3878 static int io_remove_buffers_prep(struct io_kiocb *req,
3879 const struct io_uring_sqe *sqe)
3881 struct io_provide_buf *p = &req->pbuf;
3884 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3887 tmp = READ_ONCE(sqe->fd);
3888 if (!tmp || tmp > USHRT_MAX)
3891 memset(p, 0, sizeof(*p));
3893 p->bgid = READ_ONCE(sqe->buf_group);
3897 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3898 int bgid, unsigned nbufs)
3902 /* shouldn't happen */
3906 /* the head kbuf is the list itself */
3907 while (!list_empty(&buf->list)) {
3908 struct io_buffer *nxt;
3910 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3911 list_del(&nxt->list);
3918 xa_erase(&ctx->io_buffers, bgid);
3923 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3925 struct io_provide_buf *p = &req->pbuf;
3926 struct io_ring_ctx *ctx = req->ctx;
3927 struct io_buffer *head;
3929 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3931 io_ring_submit_lock(ctx, !force_nonblock);
3933 lockdep_assert_held(&ctx->uring_lock);
3936 head = xa_load(&ctx->io_buffers, p->bgid);
3938 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3940 req_set_fail_links(req);
3942 /* complete before unlock, IOPOLL may need the lock */
3943 __io_req_complete(req, issue_flags, ret, 0);
3944 io_ring_submit_unlock(ctx, !force_nonblock);
3948 static int io_provide_buffers_prep(struct io_kiocb *req,
3949 const struct io_uring_sqe *sqe)
3952 struct io_provide_buf *p = &req->pbuf;
3955 if (sqe->ioprio || sqe->rw_flags)
3958 tmp = READ_ONCE(sqe->fd);
3959 if (!tmp || tmp > USHRT_MAX)
3962 p->addr = READ_ONCE(sqe->addr);
3963 p->len = READ_ONCE(sqe->len);
3965 size = (unsigned long)p->len * p->nbufs;
3966 if (!access_ok(u64_to_user_ptr(p->addr), size))
3969 p->bgid = READ_ONCE(sqe->buf_group);
3970 tmp = READ_ONCE(sqe->off);
3971 if (tmp > USHRT_MAX)
3977 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3979 struct io_buffer *buf;
3980 u64 addr = pbuf->addr;
3981 int i, bid = pbuf->bid;
3983 for (i = 0; i < pbuf->nbufs; i++) {
3984 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3989 buf->len = pbuf->len;
3994 INIT_LIST_HEAD(&buf->list);
3997 list_add_tail(&buf->list, &(*head)->list);
4001 return i ? i : -ENOMEM;
4004 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4006 struct io_provide_buf *p = &req->pbuf;
4007 struct io_ring_ctx *ctx = req->ctx;
4008 struct io_buffer *head, *list;
4010 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4012 io_ring_submit_lock(ctx, !force_nonblock);
4014 lockdep_assert_held(&ctx->uring_lock);
4016 list = head = xa_load(&ctx->io_buffers, p->bgid);
4018 ret = io_add_buffers(p, &head);
4019 if (ret >= 0 && !list) {
4020 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4022 __io_remove_buffers(ctx, head, p->bgid, -1U);
4025 req_set_fail_links(req);
4026 /* complete before unlock, IOPOLL may need the lock */
4027 __io_req_complete(req, issue_flags, ret, 0);
4028 io_ring_submit_unlock(ctx, !force_nonblock);
4032 static int io_epoll_ctl_prep(struct io_kiocb *req,
4033 const struct io_uring_sqe *sqe)
4035 #if defined(CONFIG_EPOLL)
4036 if (sqe->ioprio || sqe->buf_index)
4038 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4041 req->epoll.epfd = READ_ONCE(sqe->fd);
4042 req->epoll.op = READ_ONCE(sqe->len);
4043 req->epoll.fd = READ_ONCE(sqe->off);
4045 if (ep_op_has_event(req->epoll.op)) {
4046 struct epoll_event __user *ev;
4048 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4049 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4059 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4061 #if defined(CONFIG_EPOLL)
4062 struct io_epoll *ie = &req->epoll;
4064 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4066 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4067 if (force_nonblock && ret == -EAGAIN)
4071 req_set_fail_links(req);
4072 __io_req_complete(req, issue_flags, ret, 0);
4079 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4081 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4082 if (sqe->ioprio || sqe->buf_index || sqe->off)
4084 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4087 req->madvise.addr = READ_ONCE(sqe->addr);
4088 req->madvise.len = READ_ONCE(sqe->len);
4089 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4096 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4098 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4099 struct io_madvise *ma = &req->madvise;
4102 if (issue_flags & IO_URING_F_NONBLOCK)
4105 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4107 req_set_fail_links(req);
4108 io_req_complete(req, ret);
4115 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4117 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4119 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4122 req->fadvise.offset = READ_ONCE(sqe->off);
4123 req->fadvise.len = READ_ONCE(sqe->len);
4124 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4128 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4130 struct io_fadvise *fa = &req->fadvise;
4133 if (issue_flags & IO_URING_F_NONBLOCK) {
4134 switch (fa->advice) {
4135 case POSIX_FADV_NORMAL:
4136 case POSIX_FADV_RANDOM:
4137 case POSIX_FADV_SEQUENTIAL:
4144 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4146 req_set_fail_links(req);
4147 io_req_complete(req, ret);
4151 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4153 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4155 if (sqe->ioprio || sqe->buf_index)
4157 if (req->flags & REQ_F_FIXED_FILE)
4160 req->statx.dfd = READ_ONCE(sqe->fd);
4161 req->statx.mask = READ_ONCE(sqe->len);
4162 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4163 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4164 req->statx.flags = READ_ONCE(sqe->statx_flags);
4169 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4171 struct io_statx *ctx = &req->statx;
4174 if (issue_flags & IO_URING_F_NONBLOCK)
4177 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4181 req_set_fail_links(req);
4182 io_req_complete(req, ret);
4186 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4188 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4190 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4191 sqe->rw_flags || sqe->buf_index)
4193 if (req->flags & REQ_F_FIXED_FILE)
4196 req->close.fd = READ_ONCE(sqe->fd);
4200 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4202 struct files_struct *files = current->files;
4203 struct io_close *close = &req->close;
4204 struct fdtable *fdt;
4210 spin_lock(&files->file_lock);
4211 fdt = files_fdtable(files);
4212 if (close->fd >= fdt->max_fds) {
4213 spin_unlock(&files->file_lock);
4216 file = fdt->fd[close->fd];
4218 spin_unlock(&files->file_lock);
4222 if (file->f_op == &io_uring_fops) {
4223 spin_unlock(&files->file_lock);
4228 /* if the file has a flush method, be safe and punt to async */
4229 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4230 spin_unlock(&files->file_lock);
4234 ret = __close_fd_get_file(close->fd, &file);
4235 spin_unlock(&files->file_lock);
4242 /* No ->flush() or already async, safely close from here */
4243 ret = filp_close(file, current->files);
4246 req_set_fail_links(req);
4249 __io_req_complete(req, issue_flags, ret, 0);
4253 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4255 struct io_ring_ctx *ctx = req->ctx;
4257 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4259 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4262 req->sync.off = READ_ONCE(sqe->off);
4263 req->sync.len = READ_ONCE(sqe->len);
4264 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4268 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4272 /* sync_file_range always requires a blocking context */
4273 if (issue_flags & IO_URING_F_NONBLOCK)
4276 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4279 req_set_fail_links(req);
4280 io_req_complete(req, ret);
4284 #if defined(CONFIG_NET)
4285 static int io_setup_async_msg(struct io_kiocb *req,
4286 struct io_async_msghdr *kmsg)
4288 struct io_async_msghdr *async_msg = req->async_data;
4292 if (io_alloc_async_data(req)) {
4293 kfree(kmsg->free_iov);
4296 async_msg = req->async_data;
4297 req->flags |= REQ_F_NEED_CLEANUP;
4298 memcpy(async_msg, kmsg, sizeof(*kmsg));
4299 async_msg->msg.msg_name = &async_msg->addr;
4300 /* if were using fast_iov, set it to the new one */
4301 if (!async_msg->free_iov)
4302 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4307 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4308 struct io_async_msghdr *iomsg)
4310 iomsg->msg.msg_name = &iomsg->addr;
4311 iomsg->free_iov = iomsg->fast_iov;
4312 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4313 req->sr_msg.msg_flags, &iomsg->free_iov);
4316 static int io_sendmsg_prep_async(struct io_kiocb *req)
4320 ret = io_sendmsg_copy_hdr(req, req->async_data);
4322 req->flags |= REQ_F_NEED_CLEANUP;
4326 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4328 struct io_sr_msg *sr = &req->sr_msg;
4330 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4333 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4334 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4335 sr->len = READ_ONCE(sqe->len);
4337 #ifdef CONFIG_COMPAT
4338 if (req->ctx->compat)
4339 sr->msg_flags |= MSG_CMSG_COMPAT;
4344 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4346 struct io_async_msghdr iomsg, *kmsg;
4347 struct socket *sock;
4352 sock = sock_from_file(req->file);
4353 if (unlikely(!sock))
4356 kmsg = req->async_data;
4358 ret = io_sendmsg_copy_hdr(req, &iomsg);
4364 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4365 if (flags & MSG_DONTWAIT)
4366 req->flags |= REQ_F_NOWAIT;
4367 else if (issue_flags & IO_URING_F_NONBLOCK)
4368 flags |= MSG_DONTWAIT;
4370 if (flags & MSG_WAITALL)
4371 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4373 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4374 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4375 return io_setup_async_msg(req, kmsg);
4376 if (ret == -ERESTARTSYS)
4379 /* fast path, check for non-NULL to avoid function call */
4381 kfree(kmsg->free_iov);
4382 req->flags &= ~REQ_F_NEED_CLEANUP;
4384 req_set_fail_links(req);
4385 __io_req_complete(req, issue_flags, ret, 0);
4389 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4391 struct io_sr_msg *sr = &req->sr_msg;
4394 struct socket *sock;
4399 sock = sock_from_file(req->file);
4400 if (unlikely(!sock))
4403 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4407 msg.msg_name = NULL;
4408 msg.msg_control = NULL;
4409 msg.msg_controllen = 0;
4410 msg.msg_namelen = 0;
4412 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4413 if (flags & MSG_DONTWAIT)
4414 req->flags |= REQ_F_NOWAIT;
4415 else if (issue_flags & IO_URING_F_NONBLOCK)
4416 flags |= MSG_DONTWAIT;
4418 if (flags & MSG_WAITALL)
4419 min_ret = iov_iter_count(&msg.msg_iter);
4421 msg.msg_flags = flags;
4422 ret = sock_sendmsg(sock, &msg);
4423 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4425 if (ret == -ERESTARTSYS)
4429 req_set_fail_links(req);
4430 __io_req_complete(req, issue_flags, ret, 0);
4434 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4435 struct io_async_msghdr *iomsg)
4437 struct io_sr_msg *sr = &req->sr_msg;
4438 struct iovec __user *uiov;
4442 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4443 &iomsg->uaddr, &uiov, &iov_len);
4447 if (req->flags & REQ_F_BUFFER_SELECT) {
4450 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4452 sr->len = iomsg->fast_iov[0].iov_len;
4453 iomsg->free_iov = NULL;
4455 iomsg->free_iov = iomsg->fast_iov;
4456 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4457 &iomsg->free_iov, &iomsg->msg.msg_iter,
4466 #ifdef CONFIG_COMPAT
4467 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4468 struct io_async_msghdr *iomsg)
4470 struct compat_msghdr __user *msg_compat;
4471 struct io_sr_msg *sr = &req->sr_msg;
4472 struct compat_iovec __user *uiov;
4477 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4478 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4483 uiov = compat_ptr(ptr);
4484 if (req->flags & REQ_F_BUFFER_SELECT) {
4485 compat_ssize_t clen;
4489 if (!access_ok(uiov, sizeof(*uiov)))
4491 if (__get_user(clen, &uiov->iov_len))
4496 iomsg->free_iov = NULL;
4498 iomsg->free_iov = iomsg->fast_iov;
4499 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4500 UIO_FASTIOV, &iomsg->free_iov,
4501 &iomsg->msg.msg_iter, true);
4510 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4511 struct io_async_msghdr *iomsg)
4513 iomsg->msg.msg_name = &iomsg->addr;
4515 #ifdef CONFIG_COMPAT
4516 if (req->ctx->compat)
4517 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4520 return __io_recvmsg_copy_hdr(req, iomsg);
4523 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4526 struct io_sr_msg *sr = &req->sr_msg;
4527 struct io_buffer *kbuf;
4529 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4534 req->flags |= REQ_F_BUFFER_SELECTED;
4538 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4540 return io_put_kbuf(req, req->sr_msg.kbuf);
4543 static int io_recvmsg_prep_async(struct io_kiocb *req)
4547 ret = io_recvmsg_copy_hdr(req, req->async_data);
4549 req->flags |= REQ_F_NEED_CLEANUP;
4553 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4555 struct io_sr_msg *sr = &req->sr_msg;
4557 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4560 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4561 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4562 sr->len = READ_ONCE(sqe->len);
4563 sr->bgid = READ_ONCE(sqe->buf_group);
4565 #ifdef CONFIG_COMPAT
4566 if (req->ctx->compat)
4567 sr->msg_flags |= MSG_CMSG_COMPAT;
4572 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4574 struct io_async_msghdr iomsg, *kmsg;
4575 struct socket *sock;
4576 struct io_buffer *kbuf;
4579 int ret, cflags = 0;
4580 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4582 sock = sock_from_file(req->file);
4583 if (unlikely(!sock))
4586 kmsg = req->async_data;
4588 ret = io_recvmsg_copy_hdr(req, &iomsg);
4594 if (req->flags & REQ_F_BUFFER_SELECT) {
4595 kbuf = io_recv_buffer_select(req, !force_nonblock);
4597 return PTR_ERR(kbuf);
4598 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4599 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4600 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4601 1, req->sr_msg.len);
4604 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4605 if (flags & MSG_DONTWAIT)
4606 req->flags |= REQ_F_NOWAIT;
4607 else if (force_nonblock)
4608 flags |= MSG_DONTWAIT;
4610 if (flags & MSG_WAITALL)
4611 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4613 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4614 kmsg->uaddr, flags);
4615 if (force_nonblock && ret == -EAGAIN)
4616 return io_setup_async_msg(req, kmsg);
4617 if (ret == -ERESTARTSYS)
4620 if (req->flags & REQ_F_BUFFER_SELECTED)
4621 cflags = io_put_recv_kbuf(req);
4622 /* fast path, check for non-NULL to avoid function call */
4624 kfree(kmsg->free_iov);
4625 req->flags &= ~REQ_F_NEED_CLEANUP;
4626 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4627 req_set_fail_links(req);
4628 __io_req_complete(req, issue_flags, ret, cflags);
4632 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4634 struct io_buffer *kbuf;
4635 struct io_sr_msg *sr = &req->sr_msg;
4637 void __user *buf = sr->buf;
4638 struct socket *sock;
4642 int ret, cflags = 0;
4643 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4645 sock = sock_from_file(req->file);
4646 if (unlikely(!sock))
4649 if (req->flags & REQ_F_BUFFER_SELECT) {
4650 kbuf = io_recv_buffer_select(req, !force_nonblock);
4652 return PTR_ERR(kbuf);
4653 buf = u64_to_user_ptr(kbuf->addr);
4656 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4660 msg.msg_name = NULL;
4661 msg.msg_control = NULL;
4662 msg.msg_controllen = 0;
4663 msg.msg_namelen = 0;
4664 msg.msg_iocb = NULL;
4667 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4668 if (flags & MSG_DONTWAIT)
4669 req->flags |= REQ_F_NOWAIT;
4670 else if (force_nonblock)
4671 flags |= MSG_DONTWAIT;
4673 if (flags & MSG_WAITALL)
4674 min_ret = iov_iter_count(&msg.msg_iter);
4676 ret = sock_recvmsg(sock, &msg, flags);
4677 if (force_nonblock && ret == -EAGAIN)
4679 if (ret == -ERESTARTSYS)
4682 if (req->flags & REQ_F_BUFFER_SELECTED)
4683 cflags = io_put_recv_kbuf(req);
4684 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4685 req_set_fail_links(req);
4686 __io_req_complete(req, issue_flags, ret, cflags);
4690 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4692 struct io_accept *accept = &req->accept;
4694 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4696 if (sqe->ioprio || sqe->len || sqe->buf_index)
4699 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4700 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4701 accept->flags = READ_ONCE(sqe->accept_flags);
4702 accept->nofile = rlimit(RLIMIT_NOFILE);
4706 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4708 struct io_accept *accept = &req->accept;
4709 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4710 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4713 if (req->file->f_flags & O_NONBLOCK)
4714 req->flags |= REQ_F_NOWAIT;
4716 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4717 accept->addr_len, accept->flags,
4719 if (ret == -EAGAIN && force_nonblock)
4722 if (ret == -ERESTARTSYS)
4724 req_set_fail_links(req);
4726 __io_req_complete(req, issue_flags, ret, 0);
4730 static int io_connect_prep_async(struct io_kiocb *req)
4732 struct io_async_connect *io = req->async_data;
4733 struct io_connect *conn = &req->connect;
4735 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4738 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4740 struct io_connect *conn = &req->connect;
4742 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4744 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4747 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4748 conn->addr_len = READ_ONCE(sqe->addr2);
4752 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4754 struct io_async_connect __io, *io;
4755 unsigned file_flags;
4757 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4759 if (req->async_data) {
4760 io = req->async_data;
4762 ret = move_addr_to_kernel(req->connect.addr,
4763 req->connect.addr_len,
4770 file_flags = force_nonblock ? O_NONBLOCK : 0;
4772 ret = __sys_connect_file(req->file, &io->address,
4773 req->connect.addr_len, file_flags);
4774 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4775 if (req->async_data)
4777 if (io_alloc_async_data(req)) {
4781 memcpy(req->async_data, &__io, sizeof(__io));
4784 if (ret == -ERESTARTSYS)
4788 req_set_fail_links(req);
4789 __io_req_complete(req, issue_flags, ret, 0);
4792 #else /* !CONFIG_NET */
4793 #define IO_NETOP_FN(op) \
4794 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4796 return -EOPNOTSUPP; \
4799 #define IO_NETOP_PREP(op) \
4801 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4803 return -EOPNOTSUPP; \
4806 #define IO_NETOP_PREP_ASYNC(op) \
4808 static int io_##op##_prep_async(struct io_kiocb *req) \
4810 return -EOPNOTSUPP; \
4813 IO_NETOP_PREP_ASYNC(sendmsg);
4814 IO_NETOP_PREP_ASYNC(recvmsg);
4815 IO_NETOP_PREP_ASYNC(connect);
4816 IO_NETOP_PREP(accept);
4819 #endif /* CONFIG_NET */
4821 struct io_poll_table {
4822 struct poll_table_struct pt;
4823 struct io_kiocb *req;
4827 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4828 __poll_t mask, task_work_func_t func)
4832 /* for instances that support it check for an event match first: */
4833 if (mask && !(mask & poll->events))
4836 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4838 list_del_init(&poll->wait.entry);
4841 req->task_work.func = func;
4844 * If this fails, then the task is exiting. When a task exits, the
4845 * work gets canceled, so just cancel this request as well instead
4846 * of executing it. We can't safely execute it anyway, as we may not
4847 * have the needed state needed for it anyway.
4849 ret = io_req_task_work_add(req);
4850 if (unlikely(ret)) {
4851 WRITE_ONCE(poll->canceled, true);
4852 io_req_task_work_add_fallback(req, func);
4857 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4858 __acquires(&req->ctx->completion_lock)
4860 struct io_ring_ctx *ctx = req->ctx;
4862 if (!req->result && !READ_ONCE(poll->canceled)) {
4863 struct poll_table_struct pt = { ._key = poll->events };
4865 req->result = vfs_poll(req->file, &pt) & poll->events;
4868 spin_lock_irq(&ctx->completion_lock);
4869 if (!req->result && !READ_ONCE(poll->canceled)) {
4870 add_wait_queue(poll->head, &poll->wait);
4877 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4879 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4880 if (req->opcode == IORING_OP_POLL_ADD)
4881 return req->async_data;
4882 return req->apoll->double_poll;
4885 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4887 if (req->opcode == IORING_OP_POLL_ADD)
4889 return &req->apoll->poll;
4892 static void io_poll_remove_double(struct io_kiocb *req)
4894 struct io_poll_iocb *poll = io_poll_get_double(req);
4896 lockdep_assert_held(&req->ctx->completion_lock);
4898 if (poll && poll->head) {
4899 struct wait_queue_head *head = poll->head;
4901 spin_lock(&head->lock);
4902 list_del_init(&poll->wait.entry);
4903 if (poll->wait.private)
4906 spin_unlock(&head->lock);
4910 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4912 struct io_ring_ctx *ctx = req->ctx;
4913 unsigned flags = IORING_CQE_F_MORE;
4915 if (!error && req->poll.canceled) {
4917 req->poll.events |= EPOLLONESHOT;
4920 error = mangle_poll(mask);
4921 if (req->poll.events & EPOLLONESHOT)
4923 if (!__io_cqring_fill_event(req, error, flags)) {
4924 io_poll_remove_waitqs(req);
4925 req->poll.done = true;
4928 io_commit_cqring(ctx);
4929 return !(flags & IORING_CQE_F_MORE);
4932 static void io_poll_task_func(struct callback_head *cb)
4934 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4935 struct io_ring_ctx *ctx = req->ctx;
4936 struct io_kiocb *nxt;
4938 if (io_poll_rewait(req, &req->poll)) {
4939 spin_unlock_irq(&ctx->completion_lock);
4943 post_ev = done = io_poll_complete(req, req->result, 0);
4945 hash_del(&req->hash_node);
4946 } else if (!(req->poll.events & EPOLLONESHOT)) {
4949 add_wait_queue(req->poll.head, &req->poll.wait);
4951 spin_unlock_irq(&ctx->completion_lock);
4954 io_cqring_ev_posted(ctx);
4956 nxt = io_put_req_find_next(req);
4958 __io_req_task_submit(nxt);
4963 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4964 int sync, void *key)
4966 struct io_kiocb *req = wait->private;
4967 struct io_poll_iocb *poll = io_poll_get_single(req);
4968 __poll_t mask = key_to_poll(key);
4970 /* for instances that support it check for an event match first: */
4971 if (mask && !(mask & poll->events))
4973 if (!(poll->events & EPOLLONESHOT))
4974 return poll->wait.func(&poll->wait, mode, sync, key);
4976 list_del_init(&wait->entry);
4978 if (poll && poll->head) {
4981 spin_lock(&poll->head->lock);
4982 done = list_empty(&poll->wait.entry);
4984 list_del_init(&poll->wait.entry);
4985 /* make sure double remove sees this as being gone */
4986 wait->private = NULL;
4987 spin_unlock(&poll->head->lock);
4989 /* use wait func handler, so it matches the rq type */
4990 poll->wait.func(&poll->wait, mode, sync, key);
4997 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4998 wait_queue_func_t wake_func)
5002 poll->canceled = false;
5003 poll->update_events = poll->update_user_data = false;
5004 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5005 /* mask in events that we always want/need */
5006 poll->events = events | IO_POLL_UNMASK;
5007 INIT_LIST_HEAD(&poll->wait.entry);
5008 init_waitqueue_func_entry(&poll->wait, wake_func);
5011 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5012 struct wait_queue_head *head,
5013 struct io_poll_iocb **poll_ptr)
5015 struct io_kiocb *req = pt->req;
5018 * If poll->head is already set, it's because the file being polled
5019 * uses multiple waitqueues for poll handling (eg one for read, one
5020 * for write). Setup a separate io_poll_iocb if this happens.
5022 if (unlikely(poll->head)) {
5023 struct io_poll_iocb *poll_one = poll;
5025 /* already have a 2nd entry, fail a third attempt */
5027 pt->error = -EINVAL;
5030 /* double add on the same waitqueue head, ignore */
5031 if (poll->head == head)
5033 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5035 pt->error = -ENOMEM;
5038 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5040 poll->wait.private = req;
5047 if (poll->events & EPOLLEXCLUSIVE)
5048 add_wait_queue_exclusive(head, &poll->wait);
5050 add_wait_queue(head, &poll->wait);
5053 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5054 struct poll_table_struct *p)
5056 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5057 struct async_poll *apoll = pt->req->apoll;
5059 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5062 static void io_async_task_func(struct callback_head *cb)
5064 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5065 struct async_poll *apoll = req->apoll;
5066 struct io_ring_ctx *ctx = req->ctx;
5068 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5070 if (io_poll_rewait(req, &apoll->poll)) {
5071 spin_unlock_irq(&ctx->completion_lock);
5075 /* If req is still hashed, it cannot have been canceled. Don't check. */
5076 if (hash_hashed(&req->hash_node))
5077 hash_del(&req->hash_node);
5079 io_poll_remove_double(req);
5080 spin_unlock_irq(&ctx->completion_lock);
5082 if (!READ_ONCE(apoll->poll.canceled))
5083 __io_req_task_submit(req);
5085 io_req_complete_failed(req, -ECANCELED);
5087 kfree(apoll->double_poll);
5091 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5094 struct io_kiocb *req = wait->private;
5095 struct io_poll_iocb *poll = &req->apoll->poll;
5097 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5100 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5103 static void io_poll_req_insert(struct io_kiocb *req)
5105 struct io_ring_ctx *ctx = req->ctx;
5106 struct hlist_head *list;
5108 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5109 hlist_add_head(&req->hash_node, list);
5112 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5113 struct io_poll_iocb *poll,
5114 struct io_poll_table *ipt, __poll_t mask,
5115 wait_queue_func_t wake_func)
5116 __acquires(&ctx->completion_lock)
5118 struct io_ring_ctx *ctx = req->ctx;
5119 bool cancel = false;
5121 INIT_HLIST_NODE(&req->hash_node);
5122 io_init_poll_iocb(poll, mask, wake_func);
5123 poll->file = req->file;
5124 poll->wait.private = req;
5126 ipt->pt._key = mask;
5128 ipt->error = -EINVAL;
5130 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5132 spin_lock_irq(&ctx->completion_lock);
5133 if (likely(poll->head)) {
5134 spin_lock(&poll->head->lock);
5135 if (unlikely(list_empty(&poll->wait.entry))) {
5141 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5142 list_del_init(&poll->wait.entry);
5144 WRITE_ONCE(poll->canceled, true);
5145 else if (!poll->done) /* actually waiting for an event */
5146 io_poll_req_insert(req);
5147 spin_unlock(&poll->head->lock);
5153 static bool io_arm_poll_handler(struct io_kiocb *req)
5155 const struct io_op_def *def = &io_op_defs[req->opcode];
5156 struct io_ring_ctx *ctx = req->ctx;
5157 struct async_poll *apoll;
5158 struct io_poll_table ipt;
5162 if (!req->file || !file_can_poll(req->file))
5164 if (req->flags & REQ_F_POLLED)
5168 else if (def->pollout)
5172 /* if we can't nonblock try, then no point in arming a poll handler */
5173 if (!io_file_supports_async(req, rw))
5176 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5177 if (unlikely(!apoll))
5179 apoll->double_poll = NULL;
5181 req->flags |= REQ_F_POLLED;
5184 mask = EPOLLONESHOT;
5186 mask |= POLLIN | POLLRDNORM;
5188 mask |= POLLOUT | POLLWRNORM;
5190 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5191 if ((req->opcode == IORING_OP_RECVMSG) &&
5192 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5195 mask |= POLLERR | POLLPRI;
5197 ipt.pt._qproc = io_async_queue_proc;
5199 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5201 if (ret || ipt.error) {
5202 io_poll_remove_double(req);
5203 spin_unlock_irq(&ctx->completion_lock);
5204 kfree(apoll->double_poll);
5208 spin_unlock_irq(&ctx->completion_lock);
5209 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5210 apoll->poll.events);
5214 static bool __io_poll_remove_one(struct io_kiocb *req,
5215 struct io_poll_iocb *poll, bool do_cancel)
5217 bool do_complete = false;
5221 spin_lock(&poll->head->lock);
5223 WRITE_ONCE(poll->canceled, true);
5224 if (!list_empty(&poll->wait.entry)) {
5225 list_del_init(&poll->wait.entry);
5228 spin_unlock(&poll->head->lock);
5229 hash_del(&req->hash_node);
5233 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5237 io_poll_remove_double(req);
5239 if (req->opcode == IORING_OP_POLL_ADD) {
5240 do_complete = __io_poll_remove_one(req, &req->poll, true);
5242 struct async_poll *apoll = req->apoll;
5244 /* non-poll requests have submit ref still */
5245 do_complete = __io_poll_remove_one(req, &apoll->poll, true);
5248 kfree(apoll->double_poll);
5256 static bool io_poll_remove_one(struct io_kiocb *req)
5260 do_complete = io_poll_remove_waitqs(req);
5262 io_cqring_fill_event(req, -ECANCELED);
5263 io_commit_cqring(req->ctx);
5264 req_set_fail_links(req);
5265 io_put_req_deferred(req, 1);
5272 * Returns true if we found and killed one or more poll requests
5274 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5275 struct files_struct *files)
5277 struct hlist_node *tmp;
5278 struct io_kiocb *req;
5281 spin_lock_irq(&ctx->completion_lock);
5282 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5283 struct hlist_head *list;
5285 list = &ctx->cancel_hash[i];
5286 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5287 if (io_match_task(req, tsk, files))
5288 posted += io_poll_remove_one(req);
5291 spin_unlock_irq(&ctx->completion_lock);
5294 io_cqring_ev_posted(ctx);
5299 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr)
5301 struct hlist_head *list;
5302 struct io_kiocb *req;
5304 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5305 hlist_for_each_entry(req, list, hash_node) {
5306 if (sqe_addr != req->user_data)
5314 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5316 struct io_kiocb *req;
5318 req = io_poll_find(ctx, sqe_addr);
5321 if (io_poll_remove_one(req))
5327 static int io_poll_remove_prep(struct io_kiocb *req,
5328 const struct io_uring_sqe *sqe)
5330 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5332 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5336 req->poll_remove.addr = READ_ONCE(sqe->addr);
5341 * Find a running poll command that matches one specified in sqe->addr,
5342 * and remove it if found.
5344 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5346 struct io_ring_ctx *ctx = req->ctx;
5349 spin_lock_irq(&ctx->completion_lock);
5350 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5351 spin_unlock_irq(&ctx->completion_lock);
5354 req_set_fail_links(req);
5355 io_req_complete(req, ret);
5359 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5362 struct io_kiocb *req = wait->private;
5363 struct io_poll_iocb *poll = &req->poll;
5365 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5368 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5369 struct poll_table_struct *p)
5371 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5373 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5376 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5378 struct io_poll_iocb *poll = &req->poll;
5381 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5383 if (sqe->ioprio || sqe->buf_index)
5385 flags = READ_ONCE(sqe->len);
5386 if (flags & ~(IORING_POLL_ADD_MULTI | IORING_POLL_UPDATE_EVENTS |
5387 IORING_POLL_UPDATE_USER_DATA))
5389 events = READ_ONCE(sqe->poll32_events);
5391 events = swahw32(events);
5393 if (!(flags & IORING_POLL_ADD_MULTI))
5394 events |= EPOLLONESHOT;
5395 poll->update_events = poll->update_user_data = false;
5396 if (flags & IORING_POLL_UPDATE_EVENTS) {
5397 poll->update_events = true;
5398 poll->old_user_data = READ_ONCE(sqe->addr);
5400 if (flags & IORING_POLL_UPDATE_USER_DATA) {
5401 poll->update_user_data = true;
5402 poll->new_user_data = READ_ONCE(sqe->off);
5404 if (!(poll->update_events || poll->update_user_data) &&
5405 (sqe->off || sqe->addr))
5407 poll->events = demangle_poll(events) |
5408 (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5412 static int __io_poll_add(struct io_kiocb *req)
5414 struct io_poll_iocb *poll = &req->poll;
5415 struct io_ring_ctx *ctx = req->ctx;
5416 struct io_poll_table ipt;
5419 ipt.pt._qproc = io_poll_queue_proc;
5421 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5424 if (mask) { /* no async, we'd stolen it */
5426 io_poll_complete(req, mask, 0);
5428 spin_unlock_irq(&ctx->completion_lock);
5431 io_cqring_ev_posted(ctx);
5432 if (poll->events & EPOLLONESHOT)
5438 static int io_poll_update(struct io_kiocb *req)
5440 struct io_ring_ctx *ctx = req->ctx;
5441 struct io_kiocb *preq;
5444 spin_lock_irq(&ctx->completion_lock);
5445 preq = io_poll_find(ctx, req->poll.old_user_data);
5449 } else if (preq->opcode != IORING_OP_POLL_ADD) {
5450 /* don't allow internal poll updates */
5454 if (!__io_poll_remove_one(preq, &preq->poll, false)) {
5455 if (preq->poll.events & EPOLLONESHOT) {
5460 /* we now have a detached poll request. reissue. */
5463 spin_unlock_irq(&ctx->completion_lock);
5465 req_set_fail_links(req);
5466 io_req_complete(req, ret);
5469 /* only mask one event flags, keep behavior flags */
5470 if (req->poll.update_events) {
5471 preq->poll.events &= ~0xffff;
5472 preq->poll.events |= req->poll.events & 0xffff;
5473 preq->poll.events |= IO_POLL_UNMASK;
5475 if (req->poll.update_user_data)
5476 preq->user_data = req->poll.new_user_data;
5478 /* complete update request, we're done with it */
5479 io_req_complete(req, ret);
5481 ret = __io_poll_add(preq);
5483 req_set_fail_links(preq);
5484 io_req_complete(preq, ret);
5489 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5491 if (!req->poll.update_events && !req->poll.update_user_data)
5492 return __io_poll_add(req);
5493 return io_poll_update(req);
5496 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5498 struct io_timeout_data *data = container_of(timer,
5499 struct io_timeout_data, timer);
5500 struct io_kiocb *req = data->req;
5501 struct io_ring_ctx *ctx = req->ctx;
5502 unsigned long flags;
5504 spin_lock_irqsave(&ctx->completion_lock, flags);
5505 list_del_init(&req->timeout.list);
5506 atomic_set(&req->ctx->cq_timeouts,
5507 atomic_read(&req->ctx->cq_timeouts) + 1);
5509 io_cqring_fill_event(req, -ETIME);
5510 io_commit_cqring(ctx);
5511 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5513 io_cqring_ev_posted(ctx);
5514 req_set_fail_links(req);
5516 return HRTIMER_NORESTART;
5519 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5522 struct io_timeout_data *io;
5523 struct io_kiocb *req;
5526 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5527 if (user_data == req->user_data) {
5534 return ERR_PTR(ret);
5536 io = req->async_data;
5537 ret = hrtimer_try_to_cancel(&io->timer);
5539 return ERR_PTR(-EALREADY);
5540 list_del_init(&req->timeout.list);
5544 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5546 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5549 return PTR_ERR(req);
5551 req_set_fail_links(req);
5552 io_cqring_fill_event(req, -ECANCELED);
5553 io_put_req_deferred(req, 1);
5557 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5558 struct timespec64 *ts, enum hrtimer_mode mode)
5560 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5561 struct io_timeout_data *data;
5564 return PTR_ERR(req);
5566 req->timeout.off = 0; /* noseq */
5567 data = req->async_data;
5568 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5569 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5570 data->timer.function = io_timeout_fn;
5571 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5575 static int io_timeout_remove_prep(struct io_kiocb *req,
5576 const struct io_uring_sqe *sqe)
5578 struct io_timeout_rem *tr = &req->timeout_rem;
5580 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5582 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5584 if (sqe->ioprio || sqe->buf_index || sqe->len)
5587 tr->addr = READ_ONCE(sqe->addr);
5588 tr->flags = READ_ONCE(sqe->timeout_flags);
5589 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5590 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5592 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5594 } else if (tr->flags) {
5595 /* timeout removal doesn't support flags */
5602 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5604 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5609 * Remove or update an existing timeout command
5611 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5613 struct io_timeout_rem *tr = &req->timeout_rem;
5614 struct io_ring_ctx *ctx = req->ctx;
5617 spin_lock_irq(&ctx->completion_lock);
5618 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5619 ret = io_timeout_cancel(ctx, tr->addr);
5621 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5622 io_translate_timeout_mode(tr->flags));
5624 io_cqring_fill_event(req, ret);
5625 io_commit_cqring(ctx);
5626 spin_unlock_irq(&ctx->completion_lock);
5627 io_cqring_ev_posted(ctx);
5629 req_set_fail_links(req);
5634 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5635 bool is_timeout_link)
5637 struct io_timeout_data *data;
5639 u32 off = READ_ONCE(sqe->off);
5641 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5643 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5645 if (off && is_timeout_link)
5647 flags = READ_ONCE(sqe->timeout_flags);
5648 if (flags & ~IORING_TIMEOUT_ABS)
5651 req->timeout.off = off;
5653 if (!req->async_data && io_alloc_async_data(req))
5656 data = req->async_data;
5659 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5662 data->mode = io_translate_timeout_mode(flags);
5663 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5664 if (is_timeout_link)
5665 io_req_track_inflight(req);
5669 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5671 struct io_ring_ctx *ctx = req->ctx;
5672 struct io_timeout_data *data = req->async_data;
5673 struct list_head *entry;
5674 u32 tail, off = req->timeout.off;
5676 spin_lock_irq(&ctx->completion_lock);
5679 * sqe->off holds how many events that need to occur for this
5680 * timeout event to be satisfied. If it isn't set, then this is
5681 * a pure timeout request, sequence isn't used.
5683 if (io_is_timeout_noseq(req)) {
5684 entry = ctx->timeout_list.prev;
5688 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5689 req->timeout.target_seq = tail + off;
5691 /* Update the last seq here in case io_flush_timeouts() hasn't.
5692 * This is safe because ->completion_lock is held, and submissions
5693 * and completions are never mixed in the same ->completion_lock section.
5695 ctx->cq_last_tm_flush = tail;
5698 * Insertion sort, ensuring the first entry in the list is always
5699 * the one we need first.
5701 list_for_each_prev(entry, &ctx->timeout_list) {
5702 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5705 if (io_is_timeout_noseq(nxt))
5707 /* nxt.seq is behind @tail, otherwise would've been completed */
5708 if (off >= nxt->timeout.target_seq - tail)
5712 list_add(&req->timeout.list, entry);
5713 data->timer.function = io_timeout_fn;
5714 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5715 spin_unlock_irq(&ctx->completion_lock);
5719 struct io_cancel_data {
5720 struct io_ring_ctx *ctx;
5724 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5726 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5727 struct io_cancel_data *cd = data;
5729 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5732 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5733 struct io_ring_ctx *ctx)
5735 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5736 enum io_wq_cancel cancel_ret;
5739 if (!tctx || !tctx->io_wq)
5742 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5743 switch (cancel_ret) {
5744 case IO_WQ_CANCEL_OK:
5747 case IO_WQ_CANCEL_RUNNING:
5750 case IO_WQ_CANCEL_NOTFOUND:
5758 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5759 struct io_kiocb *req, __u64 sqe_addr,
5762 unsigned long flags;
5765 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5766 if (ret != -ENOENT) {
5767 spin_lock_irqsave(&ctx->completion_lock, flags);
5771 spin_lock_irqsave(&ctx->completion_lock, flags);
5772 ret = io_timeout_cancel(ctx, sqe_addr);
5775 ret = io_poll_cancel(ctx, sqe_addr);
5779 io_cqring_fill_event(req, ret);
5780 io_commit_cqring(ctx);
5781 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5782 io_cqring_ev_posted(ctx);
5785 req_set_fail_links(req);
5789 static int io_async_cancel_prep(struct io_kiocb *req,
5790 const struct io_uring_sqe *sqe)
5792 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5794 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5796 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5799 req->cancel.addr = READ_ONCE(sqe->addr);
5803 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5805 struct io_ring_ctx *ctx = req->ctx;
5806 u64 sqe_addr = req->cancel.addr;
5807 struct io_tctx_node *node;
5810 /* tasks should wait for their io-wq threads, so safe w/o sync */
5811 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5812 spin_lock_irq(&ctx->completion_lock);
5815 ret = io_timeout_cancel(ctx, sqe_addr);
5818 ret = io_poll_cancel(ctx, sqe_addr);
5821 spin_unlock_irq(&ctx->completion_lock);
5823 /* slow path, try all io-wq's */
5824 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5826 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5827 struct io_uring_task *tctx = node->task->io_uring;
5829 if (!tctx || !tctx->io_wq)
5831 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5835 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5837 spin_lock_irq(&ctx->completion_lock);
5839 io_cqring_fill_event(req, ret);
5840 io_commit_cqring(ctx);
5841 spin_unlock_irq(&ctx->completion_lock);
5842 io_cqring_ev_posted(ctx);
5845 req_set_fail_links(req);
5850 static int io_rsrc_update_prep(struct io_kiocb *req,
5851 const struct io_uring_sqe *sqe)
5853 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5855 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5857 if (sqe->ioprio || sqe->rw_flags)
5860 req->rsrc_update.offset = READ_ONCE(sqe->off);
5861 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5862 if (!req->rsrc_update.nr_args)
5864 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5868 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5870 struct io_ring_ctx *ctx = req->ctx;
5871 struct io_uring_rsrc_update up;
5874 if (issue_flags & IO_URING_F_NONBLOCK)
5877 up.offset = req->rsrc_update.offset;
5878 up.data = req->rsrc_update.arg;
5880 mutex_lock(&ctx->uring_lock);
5881 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5882 mutex_unlock(&ctx->uring_lock);
5885 req_set_fail_links(req);
5886 __io_req_complete(req, issue_flags, ret, 0);
5890 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5892 switch (req->opcode) {
5895 case IORING_OP_READV:
5896 case IORING_OP_READ_FIXED:
5897 case IORING_OP_READ:
5898 return io_read_prep(req, sqe);
5899 case IORING_OP_WRITEV:
5900 case IORING_OP_WRITE_FIXED:
5901 case IORING_OP_WRITE:
5902 return io_write_prep(req, sqe);
5903 case IORING_OP_POLL_ADD:
5904 return io_poll_add_prep(req, sqe);
5905 case IORING_OP_POLL_REMOVE:
5906 return io_poll_remove_prep(req, sqe);
5907 case IORING_OP_FSYNC:
5908 return io_fsync_prep(req, sqe);
5909 case IORING_OP_SYNC_FILE_RANGE:
5910 return io_sfr_prep(req, sqe);
5911 case IORING_OP_SENDMSG:
5912 case IORING_OP_SEND:
5913 return io_sendmsg_prep(req, sqe);
5914 case IORING_OP_RECVMSG:
5915 case IORING_OP_RECV:
5916 return io_recvmsg_prep(req, sqe);
5917 case IORING_OP_CONNECT:
5918 return io_connect_prep(req, sqe);
5919 case IORING_OP_TIMEOUT:
5920 return io_timeout_prep(req, sqe, false);
5921 case IORING_OP_TIMEOUT_REMOVE:
5922 return io_timeout_remove_prep(req, sqe);
5923 case IORING_OP_ASYNC_CANCEL:
5924 return io_async_cancel_prep(req, sqe);
5925 case IORING_OP_LINK_TIMEOUT:
5926 return io_timeout_prep(req, sqe, true);
5927 case IORING_OP_ACCEPT:
5928 return io_accept_prep(req, sqe);
5929 case IORING_OP_FALLOCATE:
5930 return io_fallocate_prep(req, sqe);
5931 case IORING_OP_OPENAT:
5932 return io_openat_prep(req, sqe);
5933 case IORING_OP_CLOSE:
5934 return io_close_prep(req, sqe);
5935 case IORING_OP_FILES_UPDATE:
5936 return io_rsrc_update_prep(req, sqe);
5937 case IORING_OP_STATX:
5938 return io_statx_prep(req, sqe);
5939 case IORING_OP_FADVISE:
5940 return io_fadvise_prep(req, sqe);
5941 case IORING_OP_MADVISE:
5942 return io_madvise_prep(req, sqe);
5943 case IORING_OP_OPENAT2:
5944 return io_openat2_prep(req, sqe);
5945 case IORING_OP_EPOLL_CTL:
5946 return io_epoll_ctl_prep(req, sqe);
5947 case IORING_OP_SPLICE:
5948 return io_splice_prep(req, sqe);
5949 case IORING_OP_PROVIDE_BUFFERS:
5950 return io_provide_buffers_prep(req, sqe);
5951 case IORING_OP_REMOVE_BUFFERS:
5952 return io_remove_buffers_prep(req, sqe);
5954 return io_tee_prep(req, sqe);
5955 case IORING_OP_SHUTDOWN:
5956 return io_shutdown_prep(req, sqe);
5957 case IORING_OP_RENAMEAT:
5958 return io_renameat_prep(req, sqe);
5959 case IORING_OP_UNLINKAT:
5960 return io_unlinkat_prep(req, sqe);
5963 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5968 static int io_req_prep_async(struct io_kiocb *req)
5970 if (!io_op_defs[req->opcode].needs_async_setup)
5972 if (WARN_ON_ONCE(req->async_data))
5974 if (io_alloc_async_data(req))
5977 switch (req->opcode) {
5978 case IORING_OP_READV:
5979 return io_rw_prep_async(req, READ);
5980 case IORING_OP_WRITEV:
5981 return io_rw_prep_async(req, WRITE);
5982 case IORING_OP_SENDMSG:
5983 return io_sendmsg_prep_async(req);
5984 case IORING_OP_RECVMSG:
5985 return io_recvmsg_prep_async(req);
5986 case IORING_OP_CONNECT:
5987 return io_connect_prep_async(req);
5989 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
5994 static u32 io_get_sequence(struct io_kiocb *req)
5996 struct io_kiocb *pos;
5997 struct io_ring_ctx *ctx = req->ctx;
5998 u32 total_submitted, nr_reqs = 0;
6000 io_for_each_link(pos, req)
6003 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6004 return total_submitted - nr_reqs;
6007 static int io_req_defer(struct io_kiocb *req)
6009 struct io_ring_ctx *ctx = req->ctx;
6010 struct io_defer_entry *de;
6014 /* Still need defer if there is pending req in defer list. */
6015 if (likely(list_empty_careful(&ctx->defer_list) &&
6016 !(req->flags & REQ_F_IO_DRAIN)))
6019 seq = io_get_sequence(req);
6020 /* Still a chance to pass the sequence check */
6021 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6024 ret = io_req_prep_async(req);
6027 io_prep_async_link(req);
6028 de = kmalloc(sizeof(*de), GFP_KERNEL);
6032 spin_lock_irq(&ctx->completion_lock);
6033 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6034 spin_unlock_irq(&ctx->completion_lock);
6036 io_queue_async_work(req);
6037 return -EIOCBQUEUED;
6040 trace_io_uring_defer(ctx, req, req->user_data);
6043 list_add_tail(&de->list, &ctx->defer_list);
6044 spin_unlock_irq(&ctx->completion_lock);
6045 return -EIOCBQUEUED;
6048 static void io_clean_op(struct io_kiocb *req)
6050 if (req->flags & REQ_F_BUFFER_SELECTED) {
6051 switch (req->opcode) {
6052 case IORING_OP_READV:
6053 case IORING_OP_READ_FIXED:
6054 case IORING_OP_READ:
6055 kfree((void *)(unsigned long)req->rw.addr);
6057 case IORING_OP_RECVMSG:
6058 case IORING_OP_RECV:
6059 kfree(req->sr_msg.kbuf);
6062 req->flags &= ~REQ_F_BUFFER_SELECTED;
6065 if (req->flags & REQ_F_NEED_CLEANUP) {
6066 switch (req->opcode) {
6067 case IORING_OP_READV:
6068 case IORING_OP_READ_FIXED:
6069 case IORING_OP_READ:
6070 case IORING_OP_WRITEV:
6071 case IORING_OP_WRITE_FIXED:
6072 case IORING_OP_WRITE: {
6073 struct io_async_rw *io = req->async_data;
6075 kfree(io->free_iovec);
6078 case IORING_OP_RECVMSG:
6079 case IORING_OP_SENDMSG: {
6080 struct io_async_msghdr *io = req->async_data;
6082 kfree(io->free_iov);
6085 case IORING_OP_SPLICE:
6087 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6088 io_put_file(req->splice.file_in);
6090 case IORING_OP_OPENAT:
6091 case IORING_OP_OPENAT2:
6092 if (req->open.filename)
6093 putname(req->open.filename);
6095 case IORING_OP_RENAMEAT:
6096 putname(req->rename.oldpath);
6097 putname(req->rename.newpath);
6099 case IORING_OP_UNLINKAT:
6100 putname(req->unlink.filename);
6103 req->flags &= ~REQ_F_NEED_CLEANUP;
6107 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6109 struct io_ring_ctx *ctx = req->ctx;
6110 const struct cred *creds = NULL;
6113 if (req->work.creds && req->work.creds != current_cred())
6114 creds = override_creds(req->work.creds);
6116 switch (req->opcode) {
6118 ret = io_nop(req, issue_flags);
6120 case IORING_OP_READV:
6121 case IORING_OP_READ_FIXED:
6122 case IORING_OP_READ:
6123 ret = io_read(req, issue_flags);
6125 case IORING_OP_WRITEV:
6126 case IORING_OP_WRITE_FIXED:
6127 case IORING_OP_WRITE:
6128 ret = io_write(req, issue_flags);
6130 case IORING_OP_FSYNC:
6131 ret = io_fsync(req, issue_flags);
6133 case IORING_OP_POLL_ADD:
6134 ret = io_poll_add(req, issue_flags);
6136 case IORING_OP_POLL_REMOVE:
6137 ret = io_poll_remove(req, issue_flags);
6139 case IORING_OP_SYNC_FILE_RANGE:
6140 ret = io_sync_file_range(req, issue_flags);
6142 case IORING_OP_SENDMSG:
6143 ret = io_sendmsg(req, issue_flags);
6145 case IORING_OP_SEND:
6146 ret = io_send(req, issue_flags);
6148 case IORING_OP_RECVMSG:
6149 ret = io_recvmsg(req, issue_flags);
6151 case IORING_OP_RECV:
6152 ret = io_recv(req, issue_flags);
6154 case IORING_OP_TIMEOUT:
6155 ret = io_timeout(req, issue_flags);
6157 case IORING_OP_TIMEOUT_REMOVE:
6158 ret = io_timeout_remove(req, issue_flags);
6160 case IORING_OP_ACCEPT:
6161 ret = io_accept(req, issue_flags);
6163 case IORING_OP_CONNECT:
6164 ret = io_connect(req, issue_flags);
6166 case IORING_OP_ASYNC_CANCEL:
6167 ret = io_async_cancel(req, issue_flags);
6169 case IORING_OP_FALLOCATE:
6170 ret = io_fallocate(req, issue_flags);
6172 case IORING_OP_OPENAT:
6173 ret = io_openat(req, issue_flags);
6175 case IORING_OP_CLOSE:
6176 ret = io_close(req, issue_flags);
6178 case IORING_OP_FILES_UPDATE:
6179 ret = io_files_update(req, issue_flags);
6181 case IORING_OP_STATX:
6182 ret = io_statx(req, issue_flags);
6184 case IORING_OP_FADVISE:
6185 ret = io_fadvise(req, issue_flags);
6187 case IORING_OP_MADVISE:
6188 ret = io_madvise(req, issue_flags);
6190 case IORING_OP_OPENAT2:
6191 ret = io_openat2(req, issue_flags);
6193 case IORING_OP_EPOLL_CTL:
6194 ret = io_epoll_ctl(req, issue_flags);
6196 case IORING_OP_SPLICE:
6197 ret = io_splice(req, issue_flags);
6199 case IORING_OP_PROVIDE_BUFFERS:
6200 ret = io_provide_buffers(req, issue_flags);
6202 case IORING_OP_REMOVE_BUFFERS:
6203 ret = io_remove_buffers(req, issue_flags);
6206 ret = io_tee(req, issue_flags);
6208 case IORING_OP_SHUTDOWN:
6209 ret = io_shutdown(req, issue_flags);
6211 case IORING_OP_RENAMEAT:
6212 ret = io_renameat(req, issue_flags);
6214 case IORING_OP_UNLINKAT:
6215 ret = io_unlinkat(req, issue_flags);
6223 revert_creds(creds);
6228 /* If the op doesn't have a file, we're not polling for it */
6229 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6230 const bool in_async = io_wq_current_is_worker();
6232 /* workqueue context doesn't hold uring_lock, grab it now */
6234 mutex_lock(&ctx->uring_lock);
6236 io_iopoll_req_issued(req, in_async);
6239 mutex_unlock(&ctx->uring_lock);
6245 static void io_wq_submit_work(struct io_wq_work *work)
6247 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6248 struct io_kiocb *timeout;
6251 timeout = io_prep_linked_timeout(req);
6253 io_queue_linked_timeout(timeout);
6255 if (work->flags & IO_WQ_WORK_CANCEL)
6260 ret = io_issue_sqe(req, 0);
6262 * We can get EAGAIN for polled IO even though we're
6263 * forcing a sync submission from here, since we can't
6264 * wait for request slots on the block side.
6272 /* avoid locking problems by failing it from a clean context */
6274 /* io-wq is going to take one down */
6276 io_req_task_queue_fail(req, ret);
6280 #define FFS_ASYNC_READ 0x1UL
6281 #define FFS_ASYNC_WRITE 0x2UL
6283 #define FFS_ISREG 0x4UL
6285 #define FFS_ISREG 0x0UL
6287 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
6289 static inline struct file **io_fixed_file_slot(struct io_rsrc_data *file_data,
6292 struct fixed_rsrc_table *table;
6294 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6295 return &table->files[i & IORING_FILE_TABLE_MASK];
6298 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6301 struct file **file_slot = io_fixed_file_slot(ctx->file_data, index);
6303 return (struct file *) ((unsigned long) *file_slot & FFS_MASK);
6306 static struct file *io_file_get(struct io_submit_state *state,
6307 struct io_kiocb *req, int fd, bool fixed)
6309 struct io_ring_ctx *ctx = req->ctx;
6313 unsigned long file_ptr;
6315 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6317 fd = array_index_nospec(fd, ctx->nr_user_files);
6318 file_ptr = (unsigned long) *io_fixed_file_slot(ctx->file_data, fd);
6319 file = (struct file *) (file_ptr & FFS_MASK);
6320 file_ptr &= ~FFS_MASK;
6321 /* mask in overlapping REQ_F and FFS bits */
6322 req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
6323 io_req_set_rsrc_node(req);
6325 trace_io_uring_file_get(ctx, fd);
6326 file = __io_file_get(state, fd);
6328 /* we don't allow fixed io_uring files */
6329 if (file && unlikely(file->f_op == &io_uring_fops))
6330 io_req_track_inflight(req);
6336 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6338 struct io_timeout_data *data = container_of(timer,
6339 struct io_timeout_data, timer);
6340 struct io_kiocb *prev, *req = data->req;
6341 struct io_ring_ctx *ctx = req->ctx;
6342 unsigned long flags;
6344 spin_lock_irqsave(&ctx->completion_lock, flags);
6345 prev = req->timeout.head;
6346 req->timeout.head = NULL;
6349 * We don't expect the list to be empty, that will only happen if we
6350 * race with the completion of the linked work.
6352 if (prev && req_ref_inc_not_zero(prev))
6353 io_remove_next_linked(prev);
6356 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6359 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6360 io_put_req_deferred(prev, 1);
6362 io_req_complete_post(req, -ETIME, 0);
6363 io_put_req_deferred(req, 1);
6365 return HRTIMER_NORESTART;
6368 static void io_queue_linked_timeout(struct io_kiocb *req)
6370 struct io_ring_ctx *ctx = req->ctx;
6372 spin_lock_irq(&ctx->completion_lock);
6374 * If the back reference is NULL, then our linked request finished
6375 * before we got a chance to setup the timer
6377 if (req->timeout.head) {
6378 struct io_timeout_data *data = req->async_data;
6380 data->timer.function = io_link_timeout_fn;
6381 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6384 spin_unlock_irq(&ctx->completion_lock);
6385 /* drop submission reference */
6389 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6391 struct io_kiocb *nxt = req->link;
6393 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6394 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6397 nxt->timeout.head = req;
6398 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6399 req->flags |= REQ_F_LINK_TIMEOUT;
6403 static void __io_queue_sqe(struct io_kiocb *req)
6405 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6408 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6411 * We async punt it if the file wasn't marked NOWAIT, or if the file
6412 * doesn't support non-blocking read/write attempts
6415 /* drop submission reference */
6416 if (req->flags & REQ_F_COMPLETE_INLINE) {
6417 struct io_ring_ctx *ctx = req->ctx;
6418 struct io_comp_state *cs = &ctx->submit_state.comp;
6420 cs->reqs[cs->nr++] = req;
6421 if (cs->nr == ARRAY_SIZE(cs->reqs))
6422 io_submit_flush_completions(cs, ctx);
6426 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6427 if (!io_arm_poll_handler(req)) {
6429 * Queued up for async execution, worker will release
6430 * submit reference when the iocb is actually submitted.
6432 io_queue_async_work(req);
6435 io_req_complete_failed(req, ret);
6438 io_queue_linked_timeout(linked_timeout);
6441 static void io_queue_sqe(struct io_kiocb *req)
6445 ret = io_req_defer(req);
6447 if (ret != -EIOCBQUEUED) {
6449 io_req_complete_failed(req, ret);
6451 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6452 ret = io_req_prep_async(req);
6455 io_queue_async_work(req);
6457 __io_queue_sqe(req);
6462 * Check SQE restrictions (opcode and flags).
6464 * Returns 'true' if SQE is allowed, 'false' otherwise.
6466 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6467 struct io_kiocb *req,
6468 unsigned int sqe_flags)
6470 if (!ctx->restricted)
6473 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6476 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6477 ctx->restrictions.sqe_flags_required)
6480 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6481 ctx->restrictions.sqe_flags_required))
6487 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6488 const struct io_uring_sqe *sqe)
6490 struct io_submit_state *state;
6491 unsigned int sqe_flags;
6492 int personality, ret = 0;
6494 req->opcode = READ_ONCE(sqe->opcode);
6495 /* same numerical values with corresponding REQ_F_*, safe to copy */
6496 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6497 req->user_data = READ_ONCE(sqe->user_data);
6498 req->async_data = NULL;
6502 req->fixed_rsrc_refs = NULL;
6503 /* one is dropped after submission, the other at completion */
6504 atomic_set(&req->refs, 2);
6505 req->task = current;
6507 req->work.creds = NULL;
6509 /* enforce forwards compatibility on users */
6510 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6515 if (unlikely(req->opcode >= IORING_OP_LAST))
6518 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6521 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6522 !io_op_defs[req->opcode].buffer_select)
6525 personality = READ_ONCE(sqe->personality);
6527 req->work.creds = xa_load(&ctx->personalities, personality);
6528 if (!req->work.creds)
6530 get_cred(req->work.creds);
6532 state = &ctx->submit_state;
6535 * Plug now if we have more than 1 IO left after this, and the target
6536 * is potentially a read/write to block based storage.
6538 if (!state->plug_started && state->ios_left > 1 &&
6539 io_op_defs[req->opcode].plug) {
6540 blk_start_plug(&state->plug);
6541 state->plug_started = true;
6544 if (io_op_defs[req->opcode].needs_file) {
6545 bool fixed = req->flags & REQ_F_FIXED_FILE;
6547 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6548 if (unlikely(!req->file))
6556 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6557 const struct io_uring_sqe *sqe)
6559 struct io_submit_link *link = &ctx->submit_state.link;
6562 ret = io_init_req(ctx, req, sqe);
6563 if (unlikely(ret)) {
6566 /* fail even hard links since we don't submit */
6567 link->head->flags |= REQ_F_FAIL_LINK;
6568 io_req_complete_failed(link->head, -ECANCELED);
6571 io_req_complete_failed(req, ret);
6574 ret = io_req_prep(req, sqe);
6578 /* don't need @sqe from now on */
6579 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6580 true, ctx->flags & IORING_SETUP_SQPOLL);
6583 * If we already have a head request, queue this one for async
6584 * submittal once the head completes. If we don't have a head but
6585 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6586 * submitted sync once the chain is complete. If none of those
6587 * conditions are true (normal request), then just queue it.
6590 struct io_kiocb *head = link->head;
6593 * Taking sequential execution of a link, draining both sides
6594 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6595 * requests in the link. So, it drains the head and the
6596 * next after the link request. The last one is done via
6597 * drain_next flag to persist the effect across calls.
6599 if (req->flags & REQ_F_IO_DRAIN) {
6600 head->flags |= REQ_F_IO_DRAIN;
6601 ctx->drain_next = 1;
6603 ret = io_req_prep_async(req);
6606 trace_io_uring_link(ctx, req, head);
6607 link->last->link = req;
6610 /* last request of a link, enqueue the link */
6611 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6616 if (unlikely(ctx->drain_next)) {
6617 req->flags |= REQ_F_IO_DRAIN;
6618 ctx->drain_next = 0;
6620 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6632 * Batched submission is done, ensure local IO is flushed out.
6634 static void io_submit_state_end(struct io_submit_state *state,
6635 struct io_ring_ctx *ctx)
6637 if (state->link.head)
6638 io_queue_sqe(state->link.head);
6640 io_submit_flush_completions(&state->comp, ctx);
6641 if (state->plug_started)
6642 blk_finish_plug(&state->plug);
6643 io_state_file_put(state);
6647 * Start submission side cache.
6649 static void io_submit_state_start(struct io_submit_state *state,
6650 unsigned int max_ios)
6652 state->plug_started = false;
6653 state->ios_left = max_ios;
6654 /* set only head, no need to init link_last in advance */
6655 state->link.head = NULL;
6658 static void io_commit_sqring(struct io_ring_ctx *ctx)
6660 struct io_rings *rings = ctx->rings;
6663 * Ensure any loads from the SQEs are done at this point,
6664 * since once we write the new head, the application could
6665 * write new data to them.
6667 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6671 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6672 * that is mapped by userspace. This means that care needs to be taken to
6673 * ensure that reads are stable, as we cannot rely on userspace always
6674 * being a good citizen. If members of the sqe are validated and then later
6675 * used, it's important that those reads are done through READ_ONCE() to
6676 * prevent a re-load down the line.
6678 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6680 u32 *sq_array = ctx->sq_array;
6684 * The cached sq head (or cq tail) serves two purposes:
6686 * 1) allows us to batch the cost of updating the user visible
6688 * 2) allows the kernel side to track the head on its own, even
6689 * though the application is the one updating it.
6691 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6692 if (likely(head < ctx->sq_entries))
6693 return &ctx->sq_sqes[head];
6695 /* drop invalid entries */
6696 ctx->cached_sq_dropped++;
6697 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6701 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6705 /* if we have a backlog and couldn't flush it all, return BUSY */
6706 if (test_bit(0, &ctx->sq_check_overflow)) {
6707 if (!__io_cqring_overflow_flush(ctx, false))
6711 /* make sure SQ entry isn't read before tail */
6712 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6714 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6717 percpu_counter_add(¤t->io_uring->inflight, nr);
6718 refcount_add(nr, ¤t->usage);
6719 io_submit_state_start(&ctx->submit_state, nr);
6721 while (submitted < nr) {
6722 const struct io_uring_sqe *sqe;
6723 struct io_kiocb *req;
6725 req = io_alloc_req(ctx);
6726 if (unlikely(!req)) {
6728 submitted = -EAGAIN;
6731 sqe = io_get_sqe(ctx);
6732 if (unlikely(!sqe)) {
6733 kmem_cache_free(req_cachep, req);
6736 /* will complete beyond this point, count as submitted */
6738 if (io_submit_sqe(ctx, req, sqe))
6742 if (unlikely(submitted != nr)) {
6743 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6744 struct io_uring_task *tctx = current->io_uring;
6745 int unused = nr - ref_used;
6747 percpu_ref_put_many(&ctx->refs, unused);
6748 percpu_counter_sub(&tctx->inflight, unused);
6749 put_task_struct_many(current, unused);
6752 io_submit_state_end(&ctx->submit_state, ctx);
6753 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6754 io_commit_sqring(ctx);
6759 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6761 /* Tell userspace we may need a wakeup call */
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 inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6769 spin_lock_irq(&ctx->completion_lock);
6770 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6771 spin_unlock_irq(&ctx->completion_lock);
6774 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6776 unsigned int to_submit;
6779 to_submit = io_sqring_entries(ctx);
6780 /* if we're handling multiple rings, cap submit size for fairness */
6781 if (cap_entries && to_submit > 8)
6784 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6785 unsigned nr_events = 0;
6787 mutex_lock(&ctx->uring_lock);
6788 if (!list_empty(&ctx->iopoll_list))
6789 io_do_iopoll(ctx, &nr_events, 0);
6791 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6792 !(ctx->flags & IORING_SETUP_R_DISABLED))
6793 ret = io_submit_sqes(ctx, to_submit);
6794 mutex_unlock(&ctx->uring_lock);
6797 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6798 wake_up(&ctx->sqo_sq_wait);
6803 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6805 struct io_ring_ctx *ctx;
6806 unsigned sq_thread_idle = 0;
6808 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6809 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6810 sqd->sq_thread_idle = sq_thread_idle;
6813 static int io_sq_thread(void *data)
6815 struct io_sq_data *sqd = data;
6816 struct io_ring_ctx *ctx;
6817 unsigned long timeout = 0;
6818 char buf[TASK_COMM_LEN];
6821 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6822 set_task_comm(current, buf);
6823 current->pf_io_worker = NULL;
6825 if (sqd->sq_cpu != -1)
6826 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6828 set_cpus_allowed_ptr(current, cpu_online_mask);
6829 current->flags |= PF_NO_SETAFFINITY;
6831 mutex_lock(&sqd->lock);
6832 while (!test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state)) {
6834 bool cap_entries, sqt_spin, needs_sched;
6836 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6837 signal_pending(current)) {
6838 bool did_sig = false;
6840 mutex_unlock(&sqd->lock);
6841 if (signal_pending(current)) {
6842 struct ksignal ksig;
6844 did_sig = get_signal(&ksig);
6847 mutex_lock(&sqd->lock);
6851 io_run_task_work_head(&sqd->park_task_work);
6852 timeout = jiffies + sqd->sq_thread_idle;
6856 cap_entries = !list_is_singular(&sqd->ctx_list);
6857 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6858 const struct cred *creds = NULL;
6860 if (ctx->sq_creds != current_cred())
6861 creds = override_creds(ctx->sq_creds);
6862 ret = __io_sq_thread(ctx, cap_entries);
6864 revert_creds(creds);
6865 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6869 if (sqt_spin || !time_after(jiffies, timeout)) {
6873 timeout = jiffies + sqd->sq_thread_idle;
6878 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6879 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6880 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6881 !list_empty_careful(&ctx->iopoll_list)) {
6882 needs_sched = false;
6885 if (io_sqring_entries(ctx)) {
6886 needs_sched = false;
6891 if (needs_sched && !test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state)) {
6892 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6893 io_ring_set_wakeup_flag(ctx);
6895 mutex_unlock(&sqd->lock);
6897 mutex_lock(&sqd->lock);
6898 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6899 io_ring_clear_wakeup_flag(ctx);
6902 finish_wait(&sqd->wait, &wait);
6903 io_run_task_work_head(&sqd->park_task_work);
6904 timeout = jiffies + sqd->sq_thread_idle;
6907 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6908 io_uring_cancel_sqpoll(ctx);
6910 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6911 io_ring_set_wakeup_flag(ctx);
6912 mutex_unlock(&sqd->lock);
6915 io_run_task_work_head(&sqd->park_task_work);
6916 complete(&sqd->exited);
6920 struct io_wait_queue {
6921 struct wait_queue_entry wq;
6922 struct io_ring_ctx *ctx;
6924 unsigned nr_timeouts;
6927 static inline bool io_should_wake(struct io_wait_queue *iowq)
6929 struct io_ring_ctx *ctx = iowq->ctx;
6932 * Wake up if we have enough events, or if a timeout occurred since we
6933 * started waiting. For timeouts, we always want to return to userspace,
6934 * regardless of event count.
6936 return io_cqring_events(ctx) >= iowq->to_wait ||
6937 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6940 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6941 int wake_flags, void *key)
6943 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6947 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6948 * the task, and the next invocation will do it.
6950 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6951 return autoremove_wake_function(curr, mode, wake_flags, key);
6955 static int io_run_task_work_sig(void)
6957 if (io_run_task_work())
6959 if (!signal_pending(current))
6961 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
6962 return -ERESTARTSYS;
6966 /* when returns >0, the caller should retry */
6967 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6968 struct io_wait_queue *iowq,
6969 signed long *timeout)
6973 /* make sure we run task_work before checking for signals */
6974 ret = io_run_task_work_sig();
6975 if (ret || io_should_wake(iowq))
6977 /* let the caller flush overflows, retry */
6978 if (test_bit(0, &ctx->cq_check_overflow))
6981 *timeout = schedule_timeout(*timeout);
6982 return !*timeout ? -ETIME : 1;
6986 * Wait until events become available, if we don't already have some. The
6987 * application must reap them itself, as they reside on the shared cq ring.
6989 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6990 const sigset_t __user *sig, size_t sigsz,
6991 struct __kernel_timespec __user *uts)
6993 struct io_wait_queue iowq = {
6996 .func = io_wake_function,
6997 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7000 .to_wait = min_events,
7002 struct io_rings *rings = ctx->rings;
7003 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7007 io_cqring_overflow_flush(ctx, false);
7008 if (io_cqring_events(ctx) >= min_events)
7010 if (!io_run_task_work())
7015 #ifdef CONFIG_COMPAT
7016 if (in_compat_syscall())
7017 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7021 ret = set_user_sigmask(sig, sigsz);
7028 struct timespec64 ts;
7030 if (get_timespec64(&ts, uts))
7032 timeout = timespec64_to_jiffies(&ts);
7035 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7036 trace_io_uring_cqring_wait(ctx, min_events);
7038 /* if we can't even flush overflow, don't wait for more */
7039 if (!io_cqring_overflow_flush(ctx, false)) {
7043 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7044 TASK_INTERRUPTIBLE);
7045 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7046 finish_wait(&ctx->wait, &iowq.wq);
7050 restore_saved_sigmask_unless(ret == -EINTR);
7052 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7055 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7057 #if defined(CONFIG_UNIX)
7058 if (ctx->ring_sock) {
7059 struct sock *sock = ctx->ring_sock->sk;
7060 struct sk_buff *skb;
7062 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7068 for (i = 0; i < ctx->nr_user_files; i++) {
7071 file = io_file_from_index(ctx, i);
7078 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7080 struct io_rsrc_data *data = container_of(ref, struct io_rsrc_data, refs);
7082 complete(&data->done);
7085 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7087 spin_lock_bh(&ctx->rsrc_ref_lock);
7090 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7092 spin_unlock_bh(&ctx->rsrc_ref_lock);
7095 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7097 percpu_ref_exit(&ref_node->refs);
7101 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7102 struct io_rsrc_data *data_to_kill)
7104 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7105 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7108 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7110 rsrc_node->rsrc_data = data_to_kill;
7111 io_rsrc_ref_lock(ctx);
7112 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7113 io_rsrc_ref_unlock(ctx);
7115 percpu_ref_get(&data_to_kill->refs);
7116 percpu_ref_kill(&rsrc_node->refs);
7117 ctx->rsrc_node = NULL;
7120 if (!ctx->rsrc_node) {
7121 ctx->rsrc_node = ctx->rsrc_backup_node;
7122 ctx->rsrc_backup_node = NULL;
7126 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7128 if (ctx->rsrc_backup_node)
7130 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7131 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7134 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7141 data->quiesce = true;
7143 ret = io_rsrc_node_switch_start(ctx);
7146 io_rsrc_node_switch(ctx, data);
7148 percpu_ref_kill(&data->refs);
7149 flush_delayed_work(&ctx->rsrc_put_work);
7151 ret = wait_for_completion_interruptible(&data->done);
7155 percpu_ref_resurrect(&data->refs);
7156 reinit_completion(&data->done);
7158 mutex_unlock(&ctx->uring_lock);
7159 ret = io_run_task_work_sig();
7160 mutex_lock(&ctx->uring_lock);
7162 data->quiesce = false;
7167 static struct io_rsrc_data *io_rsrc_data_alloc(struct io_ring_ctx *ctx,
7168 rsrc_put_fn *do_put)
7170 struct io_rsrc_data *data;
7172 data = kzalloc(sizeof(*data), GFP_KERNEL);
7176 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7177 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7182 data->do_put = do_put;
7183 init_completion(&data->done);
7187 static void io_rsrc_data_free(struct io_rsrc_data *data)
7189 percpu_ref_exit(&data->refs);
7194 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7196 struct io_rsrc_data *data = ctx->file_data;
7197 unsigned nr_tables, i;
7201 * percpu_ref_is_dying() is to stop parallel files unregister
7202 * Since we possibly drop uring lock later in this function to
7205 if (!data || percpu_ref_is_dying(&data->refs))
7207 ret = io_rsrc_ref_quiesce(data, ctx);
7211 __io_sqe_files_unregister(ctx);
7212 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7213 for (i = 0; i < nr_tables; i++)
7214 kfree(data->table[i].files);
7215 io_rsrc_data_free(data);
7216 ctx->file_data = NULL;
7217 ctx->nr_user_files = 0;
7221 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7222 __releases(&sqd->lock)
7224 WARN_ON_ONCE(sqd->thread == current);
7227 * Do the dance but not conditional clear_bit() because it'd race with
7228 * other threads incrementing park_pending and setting the bit.
7230 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7231 if (atomic_dec_return(&sqd->park_pending))
7232 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7233 mutex_unlock(&sqd->lock);
7236 static void io_sq_thread_park(struct io_sq_data *sqd)
7237 __acquires(&sqd->lock)
7239 WARN_ON_ONCE(sqd->thread == current);
7241 atomic_inc(&sqd->park_pending);
7242 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7243 mutex_lock(&sqd->lock);
7245 wake_up_process(sqd->thread);
7248 static void io_sq_thread_stop(struct io_sq_data *sqd)
7250 WARN_ON_ONCE(sqd->thread == current);
7252 mutex_lock(&sqd->lock);
7253 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7255 wake_up_process(sqd->thread);
7256 mutex_unlock(&sqd->lock);
7257 wait_for_completion(&sqd->exited);
7260 static void io_put_sq_data(struct io_sq_data *sqd)
7262 if (refcount_dec_and_test(&sqd->refs)) {
7263 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7265 io_sq_thread_stop(sqd);
7270 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7272 struct io_sq_data *sqd = ctx->sq_data;
7275 io_sq_thread_park(sqd);
7276 list_del_init(&ctx->sqd_list);
7277 io_sqd_update_thread_idle(sqd);
7278 io_sq_thread_unpark(sqd);
7280 io_put_sq_data(sqd);
7281 ctx->sq_data = NULL;
7283 put_cred(ctx->sq_creds);
7287 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7289 struct io_ring_ctx *ctx_attach;
7290 struct io_sq_data *sqd;
7293 f = fdget(p->wq_fd);
7295 return ERR_PTR(-ENXIO);
7296 if (f.file->f_op != &io_uring_fops) {
7298 return ERR_PTR(-EINVAL);
7301 ctx_attach = f.file->private_data;
7302 sqd = ctx_attach->sq_data;
7305 return ERR_PTR(-EINVAL);
7307 if (sqd->task_tgid != current->tgid) {
7309 return ERR_PTR(-EPERM);
7312 refcount_inc(&sqd->refs);
7317 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7320 struct io_sq_data *sqd;
7323 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7324 sqd = io_attach_sq_data(p);
7329 /* fall through for EPERM case, setup new sqd/task */
7330 if (PTR_ERR(sqd) != -EPERM)
7334 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7336 return ERR_PTR(-ENOMEM);
7338 atomic_set(&sqd->park_pending, 0);
7339 refcount_set(&sqd->refs, 1);
7340 INIT_LIST_HEAD(&sqd->ctx_list);
7341 mutex_init(&sqd->lock);
7342 init_waitqueue_head(&sqd->wait);
7343 init_completion(&sqd->exited);
7347 #if defined(CONFIG_UNIX)
7349 * Ensure the UNIX gc is aware of our file set, so we are certain that
7350 * the io_uring can be safely unregistered on process exit, even if we have
7351 * loops in the file referencing.
7353 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7355 struct sock *sk = ctx->ring_sock->sk;
7356 struct scm_fp_list *fpl;
7357 struct sk_buff *skb;
7360 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7364 skb = alloc_skb(0, GFP_KERNEL);
7373 fpl->user = get_uid(current_user());
7374 for (i = 0; i < nr; i++) {
7375 struct file *file = io_file_from_index(ctx, i + offset);
7379 fpl->fp[nr_files] = get_file(file);
7380 unix_inflight(fpl->user, fpl->fp[nr_files]);
7385 fpl->max = SCM_MAX_FD;
7386 fpl->count = nr_files;
7387 UNIXCB(skb).fp = fpl;
7388 skb->destructor = unix_destruct_scm;
7389 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7390 skb_queue_head(&sk->sk_receive_queue, skb);
7392 for (i = 0; i < nr_files; i++)
7403 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7404 * causes regular reference counting to break down. We rely on the UNIX
7405 * garbage collection to take care of this problem for us.
7407 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7409 unsigned left, total;
7413 left = ctx->nr_user_files;
7415 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7417 ret = __io_sqe_files_scm(ctx, this_files, total);
7421 total += this_files;
7427 while (total < ctx->nr_user_files) {
7428 struct file *file = io_file_from_index(ctx, total);
7438 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7444 static int io_sqe_alloc_file_tables(struct io_rsrc_data *file_data,
7445 unsigned nr_tables, unsigned nr_files)
7449 for (i = 0; i < nr_tables; i++) {
7450 struct fixed_rsrc_table *table = &file_data->table[i];
7451 unsigned this_files;
7453 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7454 table->files = kcalloc(this_files, sizeof(struct file *),
7458 nr_files -= this_files;
7464 for (i = 0; i < nr_tables; i++) {
7465 struct fixed_rsrc_table *table = &file_data->table[i];
7466 kfree(table->files);
7471 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7473 struct file *file = prsrc->file;
7474 #if defined(CONFIG_UNIX)
7475 struct sock *sock = ctx->ring_sock->sk;
7476 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7477 struct sk_buff *skb;
7480 __skb_queue_head_init(&list);
7483 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7484 * remove this entry and rearrange the file array.
7486 skb = skb_dequeue(head);
7488 struct scm_fp_list *fp;
7490 fp = UNIXCB(skb).fp;
7491 for (i = 0; i < fp->count; i++) {
7494 if (fp->fp[i] != file)
7497 unix_notinflight(fp->user, fp->fp[i]);
7498 left = fp->count - 1 - i;
7500 memmove(&fp->fp[i], &fp->fp[i + 1],
7501 left * sizeof(struct file *));
7508 __skb_queue_tail(&list, skb);
7518 __skb_queue_tail(&list, skb);
7520 skb = skb_dequeue(head);
7523 if (skb_peek(&list)) {
7524 spin_lock_irq(&head->lock);
7525 while ((skb = __skb_dequeue(&list)) != NULL)
7526 __skb_queue_tail(head, skb);
7527 spin_unlock_irq(&head->lock);
7534 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7536 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7537 struct io_ring_ctx *ctx = rsrc_data->ctx;
7538 struct io_rsrc_put *prsrc, *tmp;
7540 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7541 list_del(&prsrc->list);
7542 rsrc_data->do_put(ctx, prsrc);
7546 io_rsrc_node_destroy(ref_node);
7547 percpu_ref_put(&rsrc_data->refs);
7550 static void io_rsrc_put_work(struct work_struct *work)
7552 struct io_ring_ctx *ctx;
7553 struct llist_node *node;
7555 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7556 node = llist_del_all(&ctx->rsrc_put_llist);
7559 struct io_rsrc_node *ref_node;
7560 struct llist_node *next = node->next;
7562 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7563 __io_rsrc_put_work(ref_node);
7568 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7570 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7571 struct io_rsrc_data *data = node->rsrc_data;
7572 struct io_ring_ctx *ctx = data->ctx;
7573 bool first_add = false;
7576 io_rsrc_ref_lock(ctx);
7579 while (!list_empty(&ctx->rsrc_ref_list)) {
7580 node = list_first_entry(&ctx->rsrc_ref_list,
7581 struct io_rsrc_node, node);
7582 /* recycle ref nodes in order */
7585 list_del(&node->node);
7586 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7588 io_rsrc_ref_unlock(ctx);
7590 delay = percpu_ref_is_dying(&data->refs) ? 0 : HZ;
7591 if (first_add || !delay)
7592 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7595 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7597 struct io_rsrc_node *ref_node;
7599 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7603 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7608 INIT_LIST_HEAD(&ref_node->node);
7609 INIT_LIST_HEAD(&ref_node->rsrc_list);
7610 ref_node->done = false;
7614 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7617 __s32 __user *fds = (__s32 __user *) arg;
7618 unsigned nr_tables, i;
7621 struct io_rsrc_data *file_data;
7627 if (nr_args > IORING_MAX_FIXED_FILES)
7629 ret = io_rsrc_node_switch_start(ctx);
7633 file_data = io_rsrc_data_alloc(ctx, io_ring_file_put);
7636 ctx->file_data = file_data;
7639 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7640 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7642 if (!file_data->table)
7645 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7648 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7649 unsigned long file_ptr;
7651 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7655 /* allow sparse sets */
7665 * Don't allow io_uring instances to be registered. If UNIX
7666 * isn't enabled, then this causes a reference cycle and this
7667 * instance can never get freed. If UNIX is enabled we'll
7668 * handle it just fine, but there's still no point in allowing
7669 * a ring fd as it doesn't support regular read/write anyway.
7671 if (file->f_op == &io_uring_fops) {
7675 file_ptr = (unsigned long) file;
7676 if (__io_file_supports_async(file, READ))
7677 file_ptr |= FFS_ASYNC_READ;
7678 if (__io_file_supports_async(file, WRITE))
7679 file_ptr |= FFS_ASYNC_WRITE;
7680 if (S_ISREG(file_inode(file)->i_mode))
7681 file_ptr |= FFS_ISREG;
7682 *io_fixed_file_slot(file_data, i) = (struct file *) file_ptr;
7685 ret = io_sqe_files_scm(ctx);
7687 io_sqe_files_unregister(ctx);
7691 io_rsrc_node_switch(ctx, NULL);
7694 for (i = 0; i < ctx->nr_user_files; i++) {
7695 file = io_file_from_index(ctx, i);
7699 for (i = 0; i < nr_tables; i++)
7700 kfree(file_data->table[i].files);
7701 ctx->nr_user_files = 0;
7703 io_rsrc_data_free(ctx->file_data);
7704 ctx->file_data = NULL;
7708 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7711 #if defined(CONFIG_UNIX)
7712 struct sock *sock = ctx->ring_sock->sk;
7713 struct sk_buff_head *head = &sock->sk_receive_queue;
7714 struct sk_buff *skb;
7717 * See if we can merge this file into an existing skb SCM_RIGHTS
7718 * file set. If there's no room, fall back to allocating a new skb
7719 * and filling it in.
7721 spin_lock_irq(&head->lock);
7722 skb = skb_peek(head);
7724 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7726 if (fpl->count < SCM_MAX_FD) {
7727 __skb_unlink(skb, head);
7728 spin_unlock_irq(&head->lock);
7729 fpl->fp[fpl->count] = get_file(file);
7730 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7732 spin_lock_irq(&head->lock);
7733 __skb_queue_head(head, skb);
7738 spin_unlock_irq(&head->lock);
7745 return __io_sqe_files_scm(ctx, 1, index);
7751 static int io_queue_rsrc_removal(struct io_rsrc_data *data,
7752 struct io_rsrc_node *node, void *rsrc)
7754 struct io_rsrc_put *prsrc;
7756 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7761 list_add(&prsrc->list, &node->rsrc_list);
7765 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7766 struct io_uring_rsrc_update *up,
7769 struct io_rsrc_data *data = ctx->file_data;
7770 struct file *file, **file_slot;
7774 bool needs_switch = false;
7776 if (check_add_overflow(up->offset, nr_args, &done))
7778 if (done > ctx->nr_user_files)
7780 err = io_rsrc_node_switch_start(ctx);
7784 fds = u64_to_user_ptr(up->data);
7785 for (done = 0; done < nr_args; done++) {
7787 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7791 if (fd == IORING_REGISTER_FILES_SKIP)
7794 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7795 file_slot = io_fixed_file_slot(ctx->file_data, i);
7798 file = (struct file *) ((unsigned long) *file_slot & FFS_MASK);
7799 err = io_queue_rsrc_removal(data, ctx->rsrc_node, file);
7803 needs_switch = true;
7812 * Don't allow io_uring instances to be registered. If
7813 * UNIX isn't enabled, then this causes a reference
7814 * cycle and this instance can never get freed. If UNIX
7815 * is enabled we'll handle it just fine, but there's
7816 * still no point in allowing a ring fd as it doesn't
7817 * support regular read/write anyway.
7819 if (file->f_op == &io_uring_fops) {
7825 err = io_sqe_file_register(ctx, file, i);
7835 io_rsrc_node_switch(ctx, data);
7836 return done ? done : err;
7839 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7842 struct io_uring_rsrc_update up;
7844 if (!ctx->file_data)
7848 if (copy_from_user(&up, arg, sizeof(up)))
7853 return __io_sqe_files_update(ctx, &up, nr_args);
7856 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7858 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7860 req = io_put_req_find_next(req);
7861 return req ? &req->work : NULL;
7864 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7865 struct task_struct *task)
7867 struct io_wq_hash *hash;
7868 struct io_wq_data data;
7869 unsigned int concurrency;
7871 hash = ctx->hash_map;
7873 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7875 return ERR_PTR(-ENOMEM);
7876 refcount_set(&hash->refs, 1);
7877 init_waitqueue_head(&hash->wait);
7878 ctx->hash_map = hash;
7883 data.free_work = io_free_work;
7884 data.do_work = io_wq_submit_work;
7886 /* Do QD, or 4 * CPUS, whatever is smallest */
7887 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7889 return io_wq_create(concurrency, &data);
7892 static int io_uring_alloc_task_context(struct task_struct *task,
7893 struct io_ring_ctx *ctx)
7895 struct io_uring_task *tctx;
7898 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7899 if (unlikely(!tctx))
7902 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7903 if (unlikely(ret)) {
7908 tctx->io_wq = io_init_wq_offload(ctx, task);
7909 if (IS_ERR(tctx->io_wq)) {
7910 ret = PTR_ERR(tctx->io_wq);
7911 percpu_counter_destroy(&tctx->inflight);
7917 init_waitqueue_head(&tctx->wait);
7919 atomic_set(&tctx->in_idle, 0);
7920 task->io_uring = tctx;
7921 spin_lock_init(&tctx->task_lock);
7922 INIT_WQ_LIST(&tctx->task_list);
7923 tctx->task_state = 0;
7924 init_task_work(&tctx->task_work, tctx_task_work);
7928 void __io_uring_free(struct task_struct *tsk)
7930 struct io_uring_task *tctx = tsk->io_uring;
7932 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7933 WARN_ON_ONCE(tctx->io_wq);
7935 percpu_counter_destroy(&tctx->inflight);
7937 tsk->io_uring = NULL;
7940 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7941 struct io_uring_params *p)
7945 /* Retain compatibility with failing for an invalid attach attempt */
7946 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7947 IORING_SETUP_ATTACH_WQ) {
7950 f = fdget(p->wq_fd);
7953 if (f.file->f_op != &io_uring_fops) {
7959 if (ctx->flags & IORING_SETUP_SQPOLL) {
7960 struct task_struct *tsk;
7961 struct io_sq_data *sqd;
7964 sqd = io_get_sq_data(p, &attached);
7970 ctx->sq_creds = get_current_cred();
7972 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7973 if (!ctx->sq_thread_idle)
7974 ctx->sq_thread_idle = HZ;
7977 io_sq_thread_park(sqd);
7978 list_add(&ctx->sqd_list, &sqd->ctx_list);
7979 io_sqd_update_thread_idle(sqd);
7980 /* don't attach to a dying SQPOLL thread, would be racy */
7981 if (attached && !sqd->thread)
7983 io_sq_thread_unpark(sqd);
7990 if (p->flags & IORING_SETUP_SQ_AFF) {
7991 int cpu = p->sq_thread_cpu;
7994 if (cpu >= nr_cpu_ids)
7996 if (!cpu_online(cpu))
8004 sqd->task_pid = current->pid;
8005 sqd->task_tgid = current->tgid;
8006 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8013 ret = io_uring_alloc_task_context(tsk, ctx);
8014 wake_up_new_task(tsk);
8017 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8018 /* Can't have SQ_AFF without SQPOLL */
8025 io_sq_thread_finish(ctx);
8028 complete(&ctx->sq_data->exited);
8032 static inline void __io_unaccount_mem(struct user_struct *user,
8033 unsigned long nr_pages)
8035 atomic_long_sub(nr_pages, &user->locked_vm);
8038 static inline int __io_account_mem(struct user_struct *user,
8039 unsigned long nr_pages)
8041 unsigned long page_limit, cur_pages, new_pages;
8043 /* Don't allow more pages than we can safely lock */
8044 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8047 cur_pages = atomic_long_read(&user->locked_vm);
8048 new_pages = cur_pages + nr_pages;
8049 if (new_pages > page_limit)
8051 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8052 new_pages) != cur_pages);
8057 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8060 __io_unaccount_mem(ctx->user, nr_pages);
8062 if (ctx->mm_account)
8063 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8066 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8071 ret = __io_account_mem(ctx->user, nr_pages);
8076 if (ctx->mm_account)
8077 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8082 static void io_mem_free(void *ptr)
8089 page = virt_to_head_page(ptr);
8090 if (put_page_testzero(page))
8091 free_compound_page(page);
8094 static void *io_mem_alloc(size_t size)
8096 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8097 __GFP_NORETRY | __GFP_ACCOUNT;
8099 return (void *) __get_free_pages(gfp_flags, get_order(size));
8102 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8105 struct io_rings *rings;
8106 size_t off, sq_array_size;
8108 off = struct_size(rings, cqes, cq_entries);
8109 if (off == SIZE_MAX)
8113 off = ALIGN(off, SMP_CACHE_BYTES);
8121 sq_array_size = array_size(sizeof(u32), sq_entries);
8122 if (sq_array_size == SIZE_MAX)
8125 if (check_add_overflow(off, sq_array_size, &off))
8131 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8135 if (!ctx->user_bufs)
8138 for (i = 0; i < ctx->nr_user_bufs; i++) {
8139 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8141 for (j = 0; j < imu->nr_bvecs; j++)
8142 unpin_user_page(imu->bvec[j].bv_page);
8144 if (imu->acct_pages)
8145 io_unaccount_mem(ctx, imu->acct_pages);
8150 kfree(ctx->user_bufs);
8151 ctx->user_bufs = NULL;
8152 ctx->nr_user_bufs = 0;
8156 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8157 void __user *arg, unsigned index)
8159 struct iovec __user *src;
8161 #ifdef CONFIG_COMPAT
8163 struct compat_iovec __user *ciovs;
8164 struct compat_iovec ciov;
8166 ciovs = (struct compat_iovec __user *) arg;
8167 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8170 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8171 dst->iov_len = ciov.iov_len;
8175 src = (struct iovec __user *) arg;
8176 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8182 * Not super efficient, but this is just a registration time. And we do cache
8183 * the last compound head, so generally we'll only do a full search if we don't
8186 * We check if the given compound head page has already been accounted, to
8187 * avoid double accounting it. This allows us to account the full size of the
8188 * page, not just the constituent pages of a huge page.
8190 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8191 int nr_pages, struct page *hpage)
8195 /* check current page array */
8196 for (i = 0; i < nr_pages; i++) {
8197 if (!PageCompound(pages[i]))
8199 if (compound_head(pages[i]) == hpage)
8203 /* check previously registered pages */
8204 for (i = 0; i < ctx->nr_user_bufs; i++) {
8205 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8207 for (j = 0; j < imu->nr_bvecs; j++) {
8208 if (!PageCompound(imu->bvec[j].bv_page))
8210 if (compound_head(imu->bvec[j].bv_page) == hpage)
8218 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8219 int nr_pages, struct io_mapped_ubuf *imu,
8220 struct page **last_hpage)
8224 for (i = 0; i < nr_pages; i++) {
8225 if (!PageCompound(pages[i])) {
8230 hpage = compound_head(pages[i]);
8231 if (hpage == *last_hpage)
8233 *last_hpage = hpage;
8234 if (headpage_already_acct(ctx, pages, i, hpage))
8236 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8240 if (!imu->acct_pages)
8243 ret = io_account_mem(ctx, imu->acct_pages);
8245 imu->acct_pages = 0;
8249 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8250 struct io_mapped_ubuf *imu,
8251 struct page **last_hpage)
8253 struct vm_area_struct **vmas = NULL;
8254 struct page **pages = NULL;
8255 unsigned long off, start, end, ubuf;
8257 int ret, pret, nr_pages, i;
8259 ubuf = (unsigned long) iov->iov_base;
8260 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8261 start = ubuf >> PAGE_SHIFT;
8262 nr_pages = end - start;
8266 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8270 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8275 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8281 mmap_read_lock(current->mm);
8282 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8284 if (pret == nr_pages) {
8285 /* don't support file backed memory */
8286 for (i = 0; i < nr_pages; i++) {
8287 struct vm_area_struct *vma = vmas[i];
8290 !is_file_hugepages(vma->vm_file)) {
8296 ret = pret < 0 ? pret : -EFAULT;
8298 mmap_read_unlock(current->mm);
8301 * if we did partial map, or found file backed vmas,
8302 * release any pages we did get
8305 unpin_user_pages(pages, pret);
8310 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8312 unpin_user_pages(pages, pret);
8317 off = ubuf & ~PAGE_MASK;
8318 size = iov->iov_len;
8319 for (i = 0; i < nr_pages; i++) {
8322 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8323 imu->bvec[i].bv_page = pages[i];
8324 imu->bvec[i].bv_len = vec_len;
8325 imu->bvec[i].bv_offset = off;
8329 /* store original address for later verification */
8331 imu->len = iov->iov_len;
8332 imu->nr_bvecs = nr_pages;
8340 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8344 if (!nr_args || nr_args > UIO_MAXIOV)
8347 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8349 if (!ctx->user_bufs)
8355 static int io_buffer_validate(struct iovec *iov)
8357 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8360 * Don't impose further limits on the size and buffer
8361 * constraints here, we'll -EINVAL later when IO is
8362 * submitted if they are wrong.
8364 if (!iov->iov_base || !iov->iov_len)
8367 /* arbitrary limit, but we need something */
8368 if (iov->iov_len > SZ_1G)
8371 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8377 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8378 unsigned int nr_args)
8382 struct page *last_hpage = NULL;
8384 ret = io_buffers_map_alloc(ctx, nr_args);
8388 for (i = 0; i < nr_args; i++) {
8389 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8391 ret = io_copy_iov(ctx, &iov, arg, i);
8395 ret = io_buffer_validate(&iov);
8399 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8403 ctx->nr_user_bufs++;
8407 io_sqe_buffers_unregister(ctx);
8412 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8414 __s32 __user *fds = arg;
8420 if (copy_from_user(&fd, fds, sizeof(*fds)))
8423 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8424 if (IS_ERR(ctx->cq_ev_fd)) {
8425 int ret = PTR_ERR(ctx->cq_ev_fd);
8426 ctx->cq_ev_fd = NULL;
8433 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8435 if (ctx->cq_ev_fd) {
8436 eventfd_ctx_put(ctx->cq_ev_fd);
8437 ctx->cq_ev_fd = NULL;
8444 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8446 struct io_buffer *buf;
8447 unsigned long index;
8449 xa_for_each(&ctx->io_buffers, index, buf)
8450 __io_remove_buffers(ctx, buf, index, -1U);
8453 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8455 struct io_kiocb *req, *nxt;
8457 list_for_each_entry_safe(req, nxt, list, compl.list) {
8458 if (tsk && req->task != tsk)
8460 list_del(&req->compl.list);
8461 kmem_cache_free(req_cachep, req);
8465 static void io_req_caches_free(struct io_ring_ctx *ctx)
8467 struct io_submit_state *submit_state = &ctx->submit_state;
8468 struct io_comp_state *cs = &ctx->submit_state.comp;
8470 mutex_lock(&ctx->uring_lock);
8472 if (submit_state->free_reqs) {
8473 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8474 submit_state->reqs);
8475 submit_state->free_reqs = 0;
8478 io_flush_cached_locked_reqs(ctx, cs);
8479 io_req_cache_free(&cs->free_list, NULL);
8480 mutex_unlock(&ctx->uring_lock);
8483 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8486 * Some may use context even when all refs and requests have been put,
8487 * and they are free to do so while still holding uring_lock or
8488 * completion_lock, see __io_req_task_submit(). Wait for them to finish.
8490 mutex_lock(&ctx->uring_lock);
8491 mutex_unlock(&ctx->uring_lock);
8492 spin_lock_irq(&ctx->completion_lock);
8493 spin_unlock_irq(&ctx->completion_lock);
8495 io_sq_thread_finish(ctx);
8496 io_sqe_buffers_unregister(ctx);
8498 if (ctx->mm_account) {
8499 mmdrop(ctx->mm_account);
8500 ctx->mm_account = NULL;
8503 mutex_lock(&ctx->uring_lock);
8504 io_sqe_files_unregister(ctx);
8505 mutex_unlock(&ctx->uring_lock);
8506 io_eventfd_unregister(ctx);
8507 io_destroy_buffers(ctx);
8509 /* there are no registered resources left, nobody uses it */
8511 io_rsrc_node_destroy(ctx->rsrc_node);
8512 if (ctx->rsrc_backup_node)
8513 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8514 flush_delayed_work(&ctx->rsrc_put_work);
8516 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8517 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8519 #if defined(CONFIG_UNIX)
8520 if (ctx->ring_sock) {
8521 ctx->ring_sock->file = NULL; /* so that iput() is called */
8522 sock_release(ctx->ring_sock);
8526 io_mem_free(ctx->rings);
8527 io_mem_free(ctx->sq_sqes);
8529 percpu_ref_exit(&ctx->refs);
8530 free_uid(ctx->user);
8531 io_req_caches_free(ctx);
8533 io_wq_put_hash(ctx->hash_map);
8534 kfree(ctx->cancel_hash);
8538 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8540 struct io_ring_ctx *ctx = file->private_data;
8543 poll_wait(file, &ctx->cq_wait, wait);
8545 * synchronizes with barrier from wq_has_sleeper call in
8549 if (!io_sqring_full(ctx))
8550 mask |= EPOLLOUT | EPOLLWRNORM;
8553 * Don't flush cqring overflow list here, just do a simple check.
8554 * Otherwise there could possible be ABBA deadlock:
8557 * lock(&ctx->uring_lock);
8559 * lock(&ctx->uring_lock);
8562 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8563 * pushs them to do the flush.
8565 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8566 mask |= EPOLLIN | EPOLLRDNORM;
8571 static int io_uring_fasync(int fd, struct file *file, int on)
8573 struct io_ring_ctx *ctx = file->private_data;
8575 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8578 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8580 const struct cred *creds;
8582 creds = xa_erase(&ctx->personalities, id);
8591 static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8593 return io_run_task_work_head(&ctx->exit_task_work);
8596 struct io_tctx_exit {
8597 struct callback_head task_work;
8598 struct completion completion;
8599 struct io_ring_ctx *ctx;
8602 static void io_tctx_exit_cb(struct callback_head *cb)
8604 struct io_uring_task *tctx = current->io_uring;
8605 struct io_tctx_exit *work;
8607 work = container_of(cb, struct io_tctx_exit, task_work);
8609 * When @in_idle, we're in cancellation and it's racy to remove the
8610 * node. It'll be removed by the end of cancellation, just ignore it.
8612 if (!atomic_read(&tctx->in_idle))
8613 io_uring_del_task_file((unsigned long)work->ctx);
8614 complete(&work->completion);
8617 static void io_ring_exit_work(struct work_struct *work)
8619 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8620 unsigned long timeout = jiffies + HZ * 60 * 5;
8621 struct io_tctx_exit exit;
8622 struct io_tctx_node *node;
8625 /* prevent SQPOLL from submitting new requests */
8627 io_sq_thread_park(ctx->sq_data);
8628 list_del_init(&ctx->sqd_list);
8629 io_sqd_update_thread_idle(ctx->sq_data);
8630 io_sq_thread_unpark(ctx->sq_data);
8634 * If we're doing polled IO and end up having requests being
8635 * submitted async (out-of-line), then completions can come in while
8636 * we're waiting for refs to drop. We need to reap these manually,
8637 * as nobody else will be looking for them.
8640 io_uring_try_cancel_requests(ctx, NULL, NULL);
8642 WARN_ON_ONCE(time_after(jiffies, timeout));
8643 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8645 mutex_lock(&ctx->uring_lock);
8646 while (!list_empty(&ctx->tctx_list)) {
8647 WARN_ON_ONCE(time_after(jiffies, timeout));
8649 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8652 init_completion(&exit.completion);
8653 init_task_work(&exit.task_work, io_tctx_exit_cb);
8654 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8655 if (WARN_ON_ONCE(ret))
8657 wake_up_process(node->task);
8659 mutex_unlock(&ctx->uring_lock);
8660 wait_for_completion(&exit.completion);
8662 mutex_lock(&ctx->uring_lock);
8664 mutex_unlock(&ctx->uring_lock);
8666 io_ring_ctx_free(ctx);
8669 /* Returns true if we found and killed one or more timeouts */
8670 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8671 struct files_struct *files)
8673 struct io_kiocb *req, *tmp;
8676 spin_lock_irq(&ctx->completion_lock);
8677 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8678 if (io_match_task(req, tsk, files)) {
8679 io_kill_timeout(req, -ECANCELED);
8684 io_commit_cqring(ctx);
8685 spin_unlock_irq(&ctx->completion_lock);
8687 io_cqring_ev_posted(ctx);
8688 return canceled != 0;
8691 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8693 unsigned long index;
8694 struct creds *creds;
8696 mutex_lock(&ctx->uring_lock);
8697 percpu_ref_kill(&ctx->refs);
8698 /* if force is set, the ring is going away. always drop after that */
8699 ctx->cq_overflow_flushed = 1;
8701 __io_cqring_overflow_flush(ctx, true);
8702 xa_for_each(&ctx->personalities, index, creds)
8703 io_unregister_personality(ctx, index);
8704 mutex_unlock(&ctx->uring_lock);
8706 io_kill_timeouts(ctx, NULL, NULL);
8707 io_poll_remove_all(ctx, NULL, NULL);
8709 /* if we failed setting up the ctx, we might not have any rings */
8710 io_iopoll_try_reap_events(ctx);
8712 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8714 * Use system_unbound_wq to avoid spawning tons of event kworkers
8715 * if we're exiting a ton of rings at the same time. It just adds
8716 * noise and overhead, there's no discernable change in runtime
8717 * over using system_wq.
8719 queue_work(system_unbound_wq, &ctx->exit_work);
8722 static int io_uring_release(struct inode *inode, struct file *file)
8724 struct io_ring_ctx *ctx = file->private_data;
8726 file->private_data = NULL;
8727 io_ring_ctx_wait_and_kill(ctx);
8731 struct io_task_cancel {
8732 struct task_struct *task;
8733 struct files_struct *files;
8736 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8738 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8739 struct io_task_cancel *cancel = data;
8742 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8743 unsigned long flags;
8744 struct io_ring_ctx *ctx = req->ctx;
8746 /* protect against races with linked timeouts */
8747 spin_lock_irqsave(&ctx->completion_lock, flags);
8748 ret = io_match_task(req, cancel->task, cancel->files);
8749 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8751 ret = io_match_task(req, cancel->task, cancel->files);
8756 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8757 struct task_struct *task,
8758 struct files_struct *files)
8760 struct io_defer_entry *de;
8763 spin_lock_irq(&ctx->completion_lock);
8764 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8765 if (io_match_task(de->req, task, files)) {
8766 list_cut_position(&list, &ctx->defer_list, &de->list);
8770 spin_unlock_irq(&ctx->completion_lock);
8771 if (list_empty(&list))
8774 while (!list_empty(&list)) {
8775 de = list_first_entry(&list, struct io_defer_entry, list);
8776 list_del_init(&de->list);
8777 io_req_complete_failed(de->req, -ECANCELED);
8783 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8785 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8787 return req->ctx == data;
8790 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8792 struct io_tctx_node *node;
8793 enum io_wq_cancel cret;
8796 mutex_lock(&ctx->uring_lock);
8797 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8798 struct io_uring_task *tctx = node->task->io_uring;
8801 * io_wq will stay alive while we hold uring_lock, because it's
8802 * killed after ctx nodes, which requires to take the lock.
8804 if (!tctx || !tctx->io_wq)
8806 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8807 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8809 mutex_unlock(&ctx->uring_lock);
8814 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8815 struct task_struct *task,
8816 struct files_struct *files)
8818 struct io_task_cancel cancel = { .task = task, .files = files, };
8819 struct io_uring_task *tctx = task ? task->io_uring : NULL;
8822 enum io_wq_cancel cret;
8826 ret |= io_uring_try_cancel_iowq(ctx);
8827 } else if (tctx && tctx->io_wq) {
8829 * Cancels requests of all rings, not only @ctx, but
8830 * it's fine as the task is in exit/exec.
8832 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8834 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8837 /* SQPOLL thread does its own polling */
8838 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && !files) ||
8839 (ctx->sq_data && ctx->sq_data->thread == current)) {
8840 while (!list_empty_careful(&ctx->iopoll_list)) {
8841 io_iopoll_try_reap_events(ctx);
8846 ret |= io_cancel_defer_files(ctx, task, files);
8847 ret |= io_poll_remove_all(ctx, task, files);
8848 ret |= io_kill_timeouts(ctx, task, files);
8849 ret |= io_run_task_work();
8850 ret |= io_run_ctx_fallback(ctx);
8857 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8858 struct task_struct *task,
8859 struct files_struct *files)
8861 struct io_kiocb *req;
8864 spin_lock_irq(&ctx->inflight_lock);
8865 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8866 cnt += io_match_task(req, task, files);
8867 spin_unlock_irq(&ctx->inflight_lock);
8871 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8872 struct task_struct *task,
8873 struct files_struct *files)
8875 while (!list_empty_careful(&ctx->inflight_list)) {
8879 inflight = io_uring_count_inflight(ctx, task, files);
8883 io_uring_try_cancel_requests(ctx, task, files);
8885 prepare_to_wait(&task->io_uring->wait, &wait,
8886 TASK_UNINTERRUPTIBLE);
8887 if (inflight == io_uring_count_inflight(ctx, task, files))
8889 finish_wait(&task->io_uring->wait, &wait);
8893 static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
8895 struct io_uring_task *tctx = current->io_uring;
8896 struct io_tctx_node *node;
8899 if (unlikely(!tctx)) {
8900 ret = io_uring_alloc_task_context(current, ctx);
8903 tctx = current->io_uring;
8905 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
8906 node = kmalloc(sizeof(*node), GFP_KERNEL);
8910 node->task = current;
8912 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
8919 mutex_lock(&ctx->uring_lock);
8920 list_add(&node->ctx_node, &ctx->tctx_list);
8921 mutex_unlock(&ctx->uring_lock);
8928 * Note that this task has used io_uring. We use it for cancelation purposes.
8930 static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
8932 struct io_uring_task *tctx = current->io_uring;
8934 if (likely(tctx && tctx->last == ctx))
8936 return __io_uring_add_task_file(ctx);
8940 * Remove this io_uring_file -> task mapping.
8942 static void io_uring_del_task_file(unsigned long index)
8944 struct io_uring_task *tctx = current->io_uring;
8945 struct io_tctx_node *node;
8949 node = xa_erase(&tctx->xa, index);
8953 WARN_ON_ONCE(current != node->task);
8954 WARN_ON_ONCE(list_empty(&node->ctx_node));
8956 mutex_lock(&node->ctx->uring_lock);
8957 list_del(&node->ctx_node);
8958 mutex_unlock(&node->ctx->uring_lock);
8960 if (tctx->last == node->ctx)
8965 static void io_uring_clean_tctx(struct io_uring_task *tctx)
8967 struct io_tctx_node *node;
8968 unsigned long index;
8970 xa_for_each(&tctx->xa, index, node)
8971 io_uring_del_task_file(index);
8973 io_wq_put_and_exit(tctx->io_wq);
8978 static s64 tctx_inflight(struct io_uring_task *tctx)
8980 return percpu_counter_sum(&tctx->inflight);
8983 static void io_sqpoll_cancel_cb(struct callback_head *cb)
8985 struct io_tctx_exit *work = container_of(cb, struct io_tctx_exit, task_work);
8986 struct io_ring_ctx *ctx = work->ctx;
8987 struct io_sq_data *sqd = ctx->sq_data;
8990 io_uring_cancel_sqpoll(ctx);
8991 complete(&work->completion);
8994 static void io_sqpoll_cancel_sync(struct io_ring_ctx *ctx)
8996 struct io_sq_data *sqd = ctx->sq_data;
8997 struct io_tctx_exit work = { .ctx = ctx, };
8998 struct task_struct *task;
9000 io_sq_thread_park(sqd);
9001 list_del_init(&ctx->sqd_list);
9002 io_sqd_update_thread_idle(sqd);
9005 init_completion(&work.completion);
9006 init_task_work(&work.task_work, io_sqpoll_cancel_cb);
9007 io_task_work_add_head(&sqd->park_task_work, &work.task_work);
9008 wake_up_process(task);
9010 io_sq_thread_unpark(sqd);
9013 wait_for_completion(&work.completion);
9016 void __io_uring_files_cancel(struct files_struct *files)
9018 struct io_uring_task *tctx = current->io_uring;
9019 struct io_tctx_node *node;
9020 unsigned long index;
9022 /* make sure overflow events are dropped */
9023 atomic_inc(&tctx->in_idle);
9024 xa_for_each(&tctx->xa, index, node) {
9025 struct io_ring_ctx *ctx = node->ctx;
9028 io_sqpoll_cancel_sync(ctx);
9031 io_uring_cancel_files(ctx, current, files);
9033 io_uring_try_cancel_requests(ctx, current, NULL);
9035 atomic_dec(&tctx->in_idle);
9038 io_uring_clean_tctx(tctx);
9041 /* should only be called by SQPOLL task */
9042 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
9044 struct io_sq_data *sqd = ctx->sq_data;
9045 struct io_uring_task *tctx = current->io_uring;
9049 WARN_ON_ONCE(!sqd || ctx->sq_data->thread != current);
9051 atomic_inc(&tctx->in_idle);
9053 /* read completions before cancelations */
9054 inflight = tctx_inflight(tctx);
9057 io_uring_try_cancel_requests(ctx, current, NULL);
9059 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9061 * If we've seen completions, retry without waiting. This
9062 * avoids a race where a completion comes in before we did
9063 * prepare_to_wait().
9065 if (inflight == tctx_inflight(tctx))
9067 finish_wait(&tctx->wait, &wait);
9069 atomic_dec(&tctx->in_idle);
9073 * Find any io_uring fd that this task has registered or done IO on, and cancel
9076 void __io_uring_task_cancel(void)
9078 struct io_uring_task *tctx = current->io_uring;
9082 /* make sure overflow events are dropped */
9083 atomic_inc(&tctx->in_idle);
9084 __io_uring_files_cancel(NULL);
9087 /* read completions before cancelations */
9088 inflight = tctx_inflight(tctx);
9091 __io_uring_files_cancel(NULL);
9093 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9096 * If we've seen completions, retry without waiting. This
9097 * avoids a race where a completion comes in before we did
9098 * prepare_to_wait().
9100 if (inflight == tctx_inflight(tctx))
9102 finish_wait(&tctx->wait, &wait);
9105 atomic_dec(&tctx->in_idle);
9107 io_uring_clean_tctx(tctx);
9108 /* all current's requests should be gone, we can kill tctx */
9109 __io_uring_free(current);
9112 static void *io_uring_validate_mmap_request(struct file *file,
9113 loff_t pgoff, size_t sz)
9115 struct io_ring_ctx *ctx = file->private_data;
9116 loff_t offset = pgoff << PAGE_SHIFT;
9121 case IORING_OFF_SQ_RING:
9122 case IORING_OFF_CQ_RING:
9125 case IORING_OFF_SQES:
9129 return ERR_PTR(-EINVAL);
9132 page = virt_to_head_page(ptr);
9133 if (sz > page_size(page))
9134 return ERR_PTR(-EINVAL);
9141 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9143 size_t sz = vma->vm_end - vma->vm_start;
9147 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9149 return PTR_ERR(ptr);
9151 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9152 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9155 #else /* !CONFIG_MMU */
9157 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9159 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9162 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9164 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9167 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9168 unsigned long addr, unsigned long len,
9169 unsigned long pgoff, unsigned long flags)
9173 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9175 return PTR_ERR(ptr);
9177 return (unsigned long) ptr;
9180 #endif /* !CONFIG_MMU */
9182 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9187 if (!io_sqring_full(ctx))
9189 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9191 if (!io_sqring_full(ctx))
9194 } while (!signal_pending(current));
9196 finish_wait(&ctx->sqo_sq_wait, &wait);
9200 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9201 struct __kernel_timespec __user **ts,
9202 const sigset_t __user **sig)
9204 struct io_uring_getevents_arg arg;
9207 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9208 * is just a pointer to the sigset_t.
9210 if (!(flags & IORING_ENTER_EXT_ARG)) {
9211 *sig = (const sigset_t __user *) argp;
9217 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9218 * timespec and sigset_t pointers if good.
9220 if (*argsz != sizeof(arg))
9222 if (copy_from_user(&arg, argp, sizeof(arg)))
9224 *sig = u64_to_user_ptr(arg.sigmask);
9225 *argsz = arg.sigmask_sz;
9226 *ts = u64_to_user_ptr(arg.ts);
9230 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9231 u32, min_complete, u32, flags, const void __user *, argp,
9234 struct io_ring_ctx *ctx;
9241 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9242 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9246 if (unlikely(!f.file))
9250 if (unlikely(f.file->f_op != &io_uring_fops))
9254 ctx = f.file->private_data;
9255 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9259 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9263 * For SQ polling, the thread will do all submissions and completions.
9264 * Just return the requested submit count, and wake the thread if
9268 if (ctx->flags & IORING_SETUP_SQPOLL) {
9269 io_cqring_overflow_flush(ctx, false);
9272 if (unlikely(ctx->sq_data->thread == NULL)) {
9275 if (flags & IORING_ENTER_SQ_WAKEUP)
9276 wake_up(&ctx->sq_data->wait);
9277 if (flags & IORING_ENTER_SQ_WAIT) {
9278 ret = io_sqpoll_wait_sq(ctx);
9282 submitted = to_submit;
9283 } else if (to_submit) {
9284 ret = io_uring_add_task_file(ctx);
9287 mutex_lock(&ctx->uring_lock);
9288 submitted = io_submit_sqes(ctx, to_submit);
9289 mutex_unlock(&ctx->uring_lock);
9291 if (submitted != to_submit)
9294 if (flags & IORING_ENTER_GETEVENTS) {
9295 const sigset_t __user *sig;
9296 struct __kernel_timespec __user *ts;
9298 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9302 min_complete = min(min_complete, ctx->cq_entries);
9305 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9306 * space applications don't need to do io completion events
9307 * polling again, they can rely on io_sq_thread to do polling
9308 * work, which can reduce cpu usage and uring_lock contention.
9310 if (ctx->flags & IORING_SETUP_IOPOLL &&
9311 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9312 ret = io_iopoll_check(ctx, min_complete);
9314 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9319 percpu_ref_put(&ctx->refs);
9322 return submitted ? submitted : ret;
9325 #ifdef CONFIG_PROC_FS
9326 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9327 const struct cred *cred)
9329 struct user_namespace *uns = seq_user_ns(m);
9330 struct group_info *gi;
9335 seq_printf(m, "%5d\n", id);
9336 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9337 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9338 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9339 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9340 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9341 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9342 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9343 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9344 seq_puts(m, "\n\tGroups:\t");
9345 gi = cred->group_info;
9346 for (g = 0; g < gi->ngroups; g++) {
9347 seq_put_decimal_ull(m, g ? " " : "",
9348 from_kgid_munged(uns, gi->gid[g]));
9350 seq_puts(m, "\n\tCapEff:\t");
9351 cap = cred->cap_effective;
9352 CAP_FOR_EACH_U32(__capi)
9353 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9358 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9360 struct io_sq_data *sq = NULL;
9365 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9366 * since fdinfo case grabs it in the opposite direction of normal use
9367 * cases. If we fail to get the lock, we just don't iterate any
9368 * structures that could be going away outside the io_uring mutex.
9370 has_lock = mutex_trylock(&ctx->uring_lock);
9372 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9378 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9379 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9380 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9381 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9382 struct file *f = io_file_from_index(ctx, i);
9385 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9387 seq_printf(m, "%5u: <none>\n", i);
9389 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9390 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9391 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9393 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9394 (unsigned int) buf->len);
9396 if (has_lock && !xa_empty(&ctx->personalities)) {
9397 unsigned long index;
9398 const struct cred *cred;
9400 seq_printf(m, "Personalities:\n");
9401 xa_for_each(&ctx->personalities, index, cred)
9402 io_uring_show_cred(m, index, cred);
9404 seq_printf(m, "PollList:\n");
9405 spin_lock_irq(&ctx->completion_lock);
9406 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9407 struct hlist_head *list = &ctx->cancel_hash[i];
9408 struct io_kiocb *req;
9410 hlist_for_each_entry(req, list, hash_node)
9411 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9412 req->task->task_works != NULL);
9414 spin_unlock_irq(&ctx->completion_lock);
9416 mutex_unlock(&ctx->uring_lock);
9419 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9421 struct io_ring_ctx *ctx = f->private_data;
9423 if (percpu_ref_tryget(&ctx->refs)) {
9424 __io_uring_show_fdinfo(ctx, m);
9425 percpu_ref_put(&ctx->refs);
9430 static const struct file_operations io_uring_fops = {
9431 .release = io_uring_release,
9432 .mmap = io_uring_mmap,
9434 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9435 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9437 .poll = io_uring_poll,
9438 .fasync = io_uring_fasync,
9439 #ifdef CONFIG_PROC_FS
9440 .show_fdinfo = io_uring_show_fdinfo,
9444 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9445 struct io_uring_params *p)
9447 struct io_rings *rings;
9448 size_t size, sq_array_offset;
9450 /* make sure these are sane, as we already accounted them */
9451 ctx->sq_entries = p->sq_entries;
9452 ctx->cq_entries = p->cq_entries;
9454 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9455 if (size == SIZE_MAX)
9458 rings = io_mem_alloc(size);
9463 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9464 rings->sq_ring_mask = p->sq_entries - 1;
9465 rings->cq_ring_mask = p->cq_entries - 1;
9466 rings->sq_ring_entries = p->sq_entries;
9467 rings->cq_ring_entries = p->cq_entries;
9468 ctx->sq_mask = rings->sq_ring_mask;
9469 ctx->cq_mask = rings->cq_ring_mask;
9471 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9472 if (size == SIZE_MAX) {
9473 io_mem_free(ctx->rings);
9478 ctx->sq_sqes = io_mem_alloc(size);
9479 if (!ctx->sq_sqes) {
9480 io_mem_free(ctx->rings);
9488 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9492 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9496 ret = io_uring_add_task_file(ctx);
9501 fd_install(fd, file);
9506 * Allocate an anonymous fd, this is what constitutes the application
9507 * visible backing of an io_uring instance. The application mmaps this
9508 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9509 * we have to tie this fd to a socket for file garbage collection purposes.
9511 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9514 #if defined(CONFIG_UNIX)
9517 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9520 return ERR_PTR(ret);
9523 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9524 O_RDWR | O_CLOEXEC);
9525 #if defined(CONFIG_UNIX)
9527 sock_release(ctx->ring_sock);
9528 ctx->ring_sock = NULL;
9530 ctx->ring_sock->file = file;
9536 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9537 struct io_uring_params __user *params)
9539 struct io_ring_ctx *ctx;
9545 if (entries > IORING_MAX_ENTRIES) {
9546 if (!(p->flags & IORING_SETUP_CLAMP))
9548 entries = IORING_MAX_ENTRIES;
9552 * Use twice as many entries for the CQ ring. It's possible for the
9553 * application to drive a higher depth than the size of the SQ ring,
9554 * since the sqes are only used at submission time. This allows for
9555 * some flexibility in overcommitting a bit. If the application has
9556 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9557 * of CQ ring entries manually.
9559 p->sq_entries = roundup_pow_of_two(entries);
9560 if (p->flags & IORING_SETUP_CQSIZE) {
9562 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9563 * to a power-of-two, if it isn't already. We do NOT impose
9564 * any cq vs sq ring sizing.
9568 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9569 if (!(p->flags & IORING_SETUP_CLAMP))
9571 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9573 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9574 if (p->cq_entries < p->sq_entries)
9577 p->cq_entries = 2 * p->sq_entries;
9580 ctx = io_ring_ctx_alloc(p);
9583 ctx->compat = in_compat_syscall();
9584 if (!capable(CAP_IPC_LOCK))
9585 ctx->user = get_uid(current_user());
9588 * This is just grabbed for accounting purposes. When a process exits,
9589 * the mm is exited and dropped before the files, hence we need to hang
9590 * on to this mm purely for the purposes of being able to unaccount
9591 * memory (locked/pinned vm). It's not used for anything else.
9593 mmgrab(current->mm);
9594 ctx->mm_account = current->mm;
9596 ret = io_allocate_scq_urings(ctx, p);
9600 ret = io_sq_offload_create(ctx, p);
9604 memset(&p->sq_off, 0, sizeof(p->sq_off));
9605 p->sq_off.head = offsetof(struct io_rings, sq.head);
9606 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9607 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9608 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9609 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9610 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9611 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9613 memset(&p->cq_off, 0, sizeof(p->cq_off));
9614 p->cq_off.head = offsetof(struct io_rings, cq.head);
9615 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9616 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9617 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9618 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9619 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9620 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9622 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9623 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9624 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9625 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9626 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9628 if (copy_to_user(params, p, sizeof(*p))) {
9633 file = io_uring_get_file(ctx);
9635 ret = PTR_ERR(file);
9640 * Install ring fd as the very last thing, so we don't risk someone
9641 * having closed it before we finish setup
9643 ret = io_uring_install_fd(ctx, file);
9645 /* fput will clean it up */
9650 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9653 io_ring_ctx_wait_and_kill(ctx);
9658 * Sets up an aio uring context, and returns the fd. Applications asks for a
9659 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9660 * params structure passed in.
9662 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9664 struct io_uring_params p;
9667 if (copy_from_user(&p, params, sizeof(p)))
9669 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9674 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9675 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9676 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9677 IORING_SETUP_R_DISABLED))
9680 return io_uring_create(entries, &p, params);
9683 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9684 struct io_uring_params __user *, params)
9686 return io_uring_setup(entries, params);
9689 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9691 struct io_uring_probe *p;
9695 size = struct_size(p, ops, nr_args);
9696 if (size == SIZE_MAX)
9698 p = kzalloc(size, GFP_KERNEL);
9703 if (copy_from_user(p, arg, size))
9706 if (memchr_inv(p, 0, size))
9709 p->last_op = IORING_OP_LAST - 1;
9710 if (nr_args > IORING_OP_LAST)
9711 nr_args = IORING_OP_LAST;
9713 for (i = 0; i < nr_args; i++) {
9715 if (!io_op_defs[i].not_supported)
9716 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9721 if (copy_to_user(arg, p, size))
9728 static int io_register_personality(struct io_ring_ctx *ctx)
9730 const struct cred *creds;
9734 creds = get_current_cred();
9736 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9737 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9744 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9745 unsigned int nr_args)
9747 struct io_uring_restriction *res;
9751 /* Restrictions allowed only if rings started disabled */
9752 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9755 /* We allow only a single restrictions registration */
9756 if (ctx->restrictions.registered)
9759 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9762 size = array_size(nr_args, sizeof(*res));
9763 if (size == SIZE_MAX)
9766 res = memdup_user(arg, size);
9768 return PTR_ERR(res);
9772 for (i = 0; i < nr_args; i++) {
9773 switch (res[i].opcode) {
9774 case IORING_RESTRICTION_REGISTER_OP:
9775 if (res[i].register_op >= IORING_REGISTER_LAST) {
9780 __set_bit(res[i].register_op,
9781 ctx->restrictions.register_op);
9783 case IORING_RESTRICTION_SQE_OP:
9784 if (res[i].sqe_op >= IORING_OP_LAST) {
9789 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9791 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9792 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9794 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9795 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9804 /* Reset all restrictions if an error happened */
9806 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9808 ctx->restrictions.registered = true;
9814 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9816 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9819 if (ctx->restrictions.registered)
9820 ctx->restricted = 1;
9822 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9823 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9824 wake_up(&ctx->sq_data->wait);
9828 static bool io_register_op_must_quiesce(int op)
9831 case IORING_UNREGISTER_FILES:
9832 case IORING_REGISTER_FILES_UPDATE:
9833 case IORING_REGISTER_PROBE:
9834 case IORING_REGISTER_PERSONALITY:
9835 case IORING_UNREGISTER_PERSONALITY:
9842 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9843 void __user *arg, unsigned nr_args)
9844 __releases(ctx->uring_lock)
9845 __acquires(ctx->uring_lock)
9850 * We're inside the ring mutex, if the ref is already dying, then
9851 * someone else killed the ctx or is already going through
9852 * io_uring_register().
9854 if (percpu_ref_is_dying(&ctx->refs))
9857 if (io_register_op_must_quiesce(opcode)) {
9858 percpu_ref_kill(&ctx->refs);
9861 * Drop uring mutex before waiting for references to exit. If
9862 * another thread is currently inside io_uring_enter() it might
9863 * need to grab the uring_lock to make progress. If we hold it
9864 * here across the drain wait, then we can deadlock. It's safe
9865 * to drop the mutex here, since no new references will come in
9866 * after we've killed the percpu ref.
9868 mutex_unlock(&ctx->uring_lock);
9870 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9873 ret = io_run_task_work_sig();
9878 mutex_lock(&ctx->uring_lock);
9881 percpu_ref_resurrect(&ctx->refs);
9886 if (ctx->restricted) {
9887 if (opcode >= IORING_REGISTER_LAST) {
9892 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9899 case IORING_REGISTER_BUFFERS:
9900 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9902 case IORING_UNREGISTER_BUFFERS:
9906 ret = io_sqe_buffers_unregister(ctx);
9908 case IORING_REGISTER_FILES:
9909 ret = io_sqe_files_register(ctx, arg, nr_args);
9911 case IORING_UNREGISTER_FILES:
9915 ret = io_sqe_files_unregister(ctx);
9917 case IORING_REGISTER_FILES_UPDATE:
9918 ret = io_sqe_files_update(ctx, arg, nr_args);
9920 case IORING_REGISTER_EVENTFD:
9921 case IORING_REGISTER_EVENTFD_ASYNC:
9925 ret = io_eventfd_register(ctx, arg);
9928 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9929 ctx->eventfd_async = 1;
9931 ctx->eventfd_async = 0;
9933 case IORING_UNREGISTER_EVENTFD:
9937 ret = io_eventfd_unregister(ctx);
9939 case IORING_REGISTER_PROBE:
9941 if (!arg || nr_args > 256)
9943 ret = io_probe(ctx, arg, nr_args);
9945 case IORING_REGISTER_PERSONALITY:
9949 ret = io_register_personality(ctx);
9951 case IORING_UNREGISTER_PERSONALITY:
9955 ret = io_unregister_personality(ctx, nr_args);
9957 case IORING_REGISTER_ENABLE_RINGS:
9961 ret = io_register_enable_rings(ctx);
9963 case IORING_REGISTER_RESTRICTIONS:
9964 ret = io_register_restrictions(ctx, arg, nr_args);
9972 if (io_register_op_must_quiesce(opcode)) {
9973 /* bring the ctx back to life */
9974 percpu_ref_reinit(&ctx->refs);
9976 reinit_completion(&ctx->ref_comp);
9981 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9982 void __user *, arg, unsigned int, nr_args)
9984 struct io_ring_ctx *ctx;
9993 if (f.file->f_op != &io_uring_fops)
9996 ctx = f.file->private_data;
10000 mutex_lock(&ctx->uring_lock);
10001 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10002 mutex_unlock(&ctx->uring_lock);
10003 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10004 ctx->cq_ev_fd != NULL, ret);
10010 static int __init io_uring_init(void)
10012 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10013 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10014 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10017 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10018 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10019 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10020 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10021 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10022 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10023 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10024 BUILD_BUG_SQE_ELEM(8, __u64, off);
10025 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10026 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10027 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10028 BUILD_BUG_SQE_ELEM(24, __u32, len);
10029 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10030 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10031 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10032 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10033 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10034 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10035 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10036 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10037 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10038 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10039 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10040 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10041 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10042 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10043 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10044 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10045 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10046 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10047 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10049 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10050 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10051 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10055 __initcall(io_uring_init);