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_cqe (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>
65 #include <linux/anon_inodes.h>
66 #include <linux/sched/mm.h>
67 #include <linux/uaccess.h>
68 #include <linux/nospec.h>
69 #include <linux/sizes.h>
70 #include <linux/hugetlb.h>
71 #include <linux/highmem.h>
72 #include <linux/namei.h>
73 #include <linux/fsnotify.h>
74 #include <linux/fadvise.h>
75 #include <linux/eventpoll.h>
76 #include <linux/splice.h>
77 #include <linux/task_work.h>
78 #include <linux/pagemap.h>
79 #include <linux/io_uring.h>
80 #include <linux/tracehook.h>
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
85 #include <uapi/linux/io_uring.h>
87 #include "../fs/internal.h"
90 #define IORING_MAX_ENTRIES 32768
91 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
92 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
95 #define IORING_MAX_FIXED_FILES (1U << 15)
96 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
97 IORING_REGISTER_LAST + IORING_OP_LAST)
99 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
100 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
101 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
103 #define IORING_MAX_REG_BUFFERS (1U << 14)
105 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
106 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
108 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
109 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS)
111 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
114 u32 head ____cacheline_aligned_in_smp;
115 u32 tail ____cacheline_aligned_in_smp;
119 * This data is shared with the application through the mmap at offsets
120 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
122 * The offsets to the member fields are published through struct
123 * io_sqring_offsets when calling io_uring_setup.
127 * Head and tail offsets into the ring; the offsets need to be
128 * masked to get valid indices.
130 * The kernel controls head of the sq ring and the tail of the cq ring,
131 * and the application controls tail of the sq ring and the head of the
134 struct io_uring sq, cq;
136 * Bitmasks to apply to head and tail offsets (constant, equals
139 u32 sq_ring_mask, cq_ring_mask;
140 /* Ring sizes (constant, power of 2) */
141 u32 sq_ring_entries, cq_ring_entries;
143 * Number of invalid entries dropped by the kernel due to
144 * invalid index stored in array
146 * Written by the kernel, shouldn't be modified by the
147 * application (i.e. get number of "new events" by comparing to
150 * After a new SQ head value was read by the application this
151 * counter includes all submissions that were dropped reaching
152 * the new SQ head (and possibly more).
158 * Written by the kernel, shouldn't be modified by the
161 * The application needs a full memory barrier before checking
162 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
168 * Written by the application, shouldn't be modified by the
173 * Number of completion events lost because the queue was full;
174 * this should be avoided by the application by making sure
175 * there are not more requests pending than there is space in
176 * the completion queue.
178 * Written by the kernel, shouldn't be modified by the
179 * application (i.e. get number of "new events" by comparing to
182 * As completion events come in out of order this counter is not
183 * ordered with any other data.
187 * Ring buffer of completion events.
189 * The kernel writes completion events fresh every time they are
190 * produced, so the application is allowed to modify pending
193 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
196 enum io_uring_cmd_flags {
197 IO_URING_F_NONBLOCK = 1,
198 IO_URING_F_COMPLETE_DEFER = 2,
201 struct io_mapped_ubuf {
204 unsigned int nr_bvecs;
205 unsigned long acct_pages;
206 struct bio_vec bvec[];
211 struct io_overflow_cqe {
212 struct io_uring_cqe cqe;
213 struct list_head list;
216 struct io_fixed_file {
217 /* file * with additional FFS_* flags */
218 unsigned long file_ptr;
222 struct list_head list;
227 struct io_mapped_ubuf *buf;
231 struct io_file_table {
232 struct io_fixed_file *files;
235 struct io_rsrc_node {
236 struct percpu_ref refs;
237 struct list_head node;
238 struct list_head rsrc_list;
239 struct io_rsrc_data *rsrc_data;
240 struct llist_node llist;
244 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
246 struct io_rsrc_data {
247 struct io_ring_ctx *ctx;
253 struct completion done;
258 struct list_head list;
264 struct io_restriction {
265 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
266 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
267 u8 sqe_flags_allowed;
268 u8 sqe_flags_required;
273 IO_SQ_THREAD_SHOULD_STOP = 0,
274 IO_SQ_THREAD_SHOULD_PARK,
279 atomic_t park_pending;
282 /* ctx's that are using this sqd */
283 struct list_head ctx_list;
285 struct task_struct *thread;
286 struct wait_queue_head wait;
288 unsigned sq_thread_idle;
294 struct completion exited;
297 #define IO_COMPL_BATCH 32
298 #define IO_REQ_CACHE_SIZE 32
299 #define IO_REQ_ALLOC_BATCH 8
301 struct io_submit_link {
302 struct io_kiocb *head;
303 struct io_kiocb *last;
306 struct io_submit_state {
307 struct blk_plug plug;
308 struct io_submit_link link;
311 * io_kiocb alloc cache
313 void *reqs[IO_REQ_CACHE_SIZE];
314 unsigned int free_reqs;
319 * Batch completion logic
321 struct io_kiocb *compl_reqs[IO_COMPL_BATCH];
322 unsigned int compl_nr;
323 /* inline/task_work completion list, under ->uring_lock */
324 struct list_head free_list;
326 unsigned int ios_left;
330 /* const or read-mostly hot data */
332 struct percpu_ref refs;
334 struct io_rings *rings;
336 unsigned int compat: 1;
337 unsigned int drain_next: 1;
338 unsigned int eventfd_async: 1;
339 unsigned int restricted: 1;
340 unsigned int off_timeout_used: 1;
341 unsigned int drain_active: 1;
342 } ____cacheline_aligned_in_smp;
344 /* submission data */
346 struct mutex uring_lock;
349 * Ring buffer of indices into array of io_uring_sqe, which is
350 * mmapped by the application using the IORING_OFF_SQES offset.
352 * This indirection could e.g. be used to assign fixed
353 * io_uring_sqe entries to operations and only submit them to
354 * the queue when needed.
356 * The kernel modifies neither the indices array nor the entries
360 struct io_uring_sqe *sq_sqes;
361 unsigned cached_sq_head;
363 struct list_head defer_list;
366 * Fixed resources fast path, should be accessed only under
367 * uring_lock, and updated through io_uring_register(2)
369 struct io_rsrc_node *rsrc_node;
370 struct io_file_table file_table;
371 unsigned nr_user_files;
372 unsigned nr_user_bufs;
373 struct io_mapped_ubuf **user_bufs;
375 struct io_submit_state submit_state;
376 struct list_head timeout_list;
377 struct list_head ltimeout_list;
378 struct list_head cq_overflow_list;
379 struct xarray io_buffers;
380 struct xarray personalities;
382 unsigned sq_thread_idle;
383 } ____cacheline_aligned_in_smp;
385 /* IRQ completion list, under ->completion_lock */
386 struct list_head locked_free_list;
387 unsigned int locked_free_nr;
389 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
390 struct io_sq_data *sq_data; /* if using sq thread polling */
392 struct wait_queue_head sqo_sq_wait;
393 struct list_head sqd_list;
395 unsigned long check_cq_overflow;
398 unsigned cached_cq_tail;
400 struct eventfd_ctx *cq_ev_fd;
401 struct wait_queue_head poll_wait;
402 struct wait_queue_head cq_wait;
404 atomic_t cq_timeouts;
405 unsigned cq_last_tm_flush;
406 } ____cacheline_aligned_in_smp;
409 spinlock_t completion_lock;
411 spinlock_t timeout_lock;
414 * ->iopoll_list is protected by the ctx->uring_lock for
415 * io_uring instances that don't use IORING_SETUP_SQPOLL.
416 * For SQPOLL, only the single threaded io_sq_thread() will
417 * manipulate the list, hence no extra locking is needed there.
419 struct list_head iopoll_list;
420 struct hlist_head *cancel_hash;
421 unsigned cancel_hash_bits;
422 bool poll_multi_queue;
423 } ____cacheline_aligned_in_smp;
425 struct io_restriction restrictions;
427 /* slow path rsrc auxilary data, used by update/register */
429 struct io_rsrc_node *rsrc_backup_node;
430 struct io_mapped_ubuf *dummy_ubuf;
431 struct io_rsrc_data *file_data;
432 struct io_rsrc_data *buf_data;
434 struct delayed_work rsrc_put_work;
435 struct llist_head rsrc_put_llist;
436 struct list_head rsrc_ref_list;
437 spinlock_t rsrc_ref_lock;
440 /* Keep this last, we don't need it for the fast path */
442 /* hashed buffered write serialization */
443 struct io_wq_hash *hash_map;
445 /* Only used for accounting purposes */
446 struct user_struct *user;
447 struct mm_struct *mm_account;
449 /* ctx exit and cancelation */
450 struct llist_head fallback_llist;
451 struct delayed_work fallback_work;
452 struct work_struct exit_work;
453 struct list_head tctx_list;
454 struct completion ref_comp;
456 bool iowq_limits_set;
460 struct io_uring_task {
461 /* submission side */
464 struct wait_queue_head wait;
465 const struct io_ring_ctx *last;
467 struct percpu_counter inflight;
468 atomic_t inflight_tracked;
471 spinlock_t task_lock;
472 struct io_wq_work_list task_list;
473 struct callback_head task_work;
478 * First field must be the file pointer in all the
479 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
481 struct io_poll_iocb {
483 struct wait_queue_head *head;
486 struct wait_queue_entry wait;
489 struct io_poll_update {
495 bool update_user_data;
504 struct io_timeout_data {
505 struct io_kiocb *req;
506 struct hrtimer timer;
507 struct timespec64 ts;
508 enum hrtimer_mode mode;
514 struct sockaddr __user *addr;
515 int __user *addr_len;
518 unsigned long nofile;
538 struct list_head list;
539 /* head of the link, used by linked timeouts only */
540 struct io_kiocb *head;
541 /* for linked completions */
542 struct io_kiocb *prev;
545 struct io_timeout_rem {
550 struct timespec64 ts;
556 /* NOTE: kiocb has the file as the first member, so don't do it here */
564 struct sockaddr __user *addr;
571 struct compat_msghdr __user *umsg_compat;
572 struct user_msghdr __user *umsg;
579 struct io_buffer *kbuf;
580 void __user *msg_control;
587 struct filename *filename;
589 unsigned long nofile;
592 struct io_rsrc_update {
618 struct epoll_event event;
622 struct file *file_out;
630 struct io_provide_buf {
644 const char __user *filename;
645 struct statx __user *buffer;
657 struct filename *oldpath;
658 struct filename *newpath;
666 struct filename *filename;
673 struct filename *filename;
679 struct filename *oldpath;
680 struct filename *newpath;
687 struct filename *oldpath;
688 struct filename *newpath;
692 struct io_completion {
697 struct io_async_connect {
698 struct sockaddr_storage address;
701 struct io_async_msghdr {
702 struct iovec fast_iov[UIO_FASTIOV];
703 /* points to an allocated iov, if NULL we use fast_iov instead */
704 struct iovec *free_iov;
705 struct sockaddr __user *uaddr;
707 struct sockaddr_storage addr;
711 struct iovec fast_iov[UIO_FASTIOV];
712 const struct iovec *free_iovec;
713 struct iov_iter iter;
714 struct iov_iter_state iter_state;
716 struct wait_page_queue wpq;
720 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
721 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
722 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
723 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
724 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
725 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
727 /* first byte is taken by user flags, shift it to not overlap */
732 REQ_F_LINK_TIMEOUT_BIT,
733 REQ_F_NEED_CLEANUP_BIT,
735 REQ_F_BUFFER_SELECTED_BIT,
736 REQ_F_COMPLETE_INLINE_BIT,
740 REQ_F_ARM_LTIMEOUT_BIT,
741 REQ_F_PARTIAL_IO_BIT,
742 /* keep async read/write and isreg together and in order */
743 REQ_F_NOWAIT_READ_BIT,
744 REQ_F_NOWAIT_WRITE_BIT,
747 /* not a real bit, just to check we're not overflowing the space */
753 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
754 /* drain existing IO first */
755 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
757 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
758 /* doesn't sever on completion < 0 */
759 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
761 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
762 /* IOSQE_BUFFER_SELECT */
763 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
765 /* fail rest of links */
766 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
767 /* on inflight list, should be cancelled and waited on exit reliably */
768 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
769 /* read/write uses file position */
770 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
771 /* must not punt to workers */
772 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
773 /* has or had linked timeout */
774 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
776 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
777 /* already went through poll handler */
778 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
779 /* buffer already selected */
780 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
781 /* completion is deferred through io_comp_state */
782 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
783 /* caller should reissue async */
784 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
785 /* supports async reads */
786 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
787 /* supports async writes */
788 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
790 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
791 /* has creds assigned */
792 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
793 /* skip refcounting if not set */
794 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
795 /* there is a linked timeout that has to be armed */
796 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
797 /* request has already done partial IO */
798 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
802 struct io_poll_iocb poll;
803 struct io_poll_iocb *double_poll;
806 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
808 struct io_task_work {
810 struct io_wq_work_node node;
811 struct llist_node fallback_node;
813 io_req_tw_func_t func;
817 IORING_RSRC_FILE = 0,
818 IORING_RSRC_BUFFER = 1,
822 * NOTE! Each of the iocb union members has the file pointer
823 * as the first entry in their struct definition. So you can
824 * access the file pointer through any of the sub-structs,
825 * or directly as just 'ki_filp' in this struct.
831 struct io_poll_iocb poll;
832 struct io_poll_update poll_update;
833 struct io_accept accept;
835 struct io_cancel cancel;
836 struct io_timeout timeout;
837 struct io_timeout_rem timeout_rem;
838 struct io_connect connect;
839 struct io_sr_msg sr_msg;
841 struct io_close close;
842 struct io_rsrc_update rsrc_update;
843 struct io_fadvise fadvise;
844 struct io_madvise madvise;
845 struct io_epoll epoll;
846 struct io_splice splice;
847 struct io_provide_buf pbuf;
848 struct io_statx statx;
849 struct io_shutdown shutdown;
850 struct io_rename rename;
851 struct io_unlink unlink;
852 struct io_mkdir mkdir;
853 struct io_symlink symlink;
854 struct io_hardlink hardlink;
855 /* use only after cleaning per-op data, see io_clean_op() */
856 struct io_completion compl;
859 /* opcode allocated if it needs to store data for async defer */
862 /* polled IO has completed */
868 struct io_ring_ctx *ctx;
871 struct task_struct *task;
874 struct io_kiocb *link;
875 struct percpu_ref *fixed_rsrc_refs;
877 /* used with ctx->iopoll_list with reads/writes */
878 struct list_head inflight_entry;
879 struct io_task_work io_task_work;
880 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
881 struct hlist_node hash_node;
882 struct async_poll *apoll;
883 struct io_wq_work work;
884 const struct cred *creds;
886 /* store used ubuf, so we can prevent reloading */
887 struct io_mapped_ubuf *imu;
888 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
889 struct io_buffer *kbuf;
893 struct io_tctx_node {
894 struct list_head ctx_node;
895 struct task_struct *task;
896 struct io_ring_ctx *ctx;
899 struct io_defer_entry {
900 struct list_head list;
901 struct io_kiocb *req;
906 /* needs req->file assigned */
907 unsigned needs_file : 1;
908 /* hash wq insertion if file is a regular file */
909 unsigned hash_reg_file : 1;
910 /* unbound wq insertion if file is a non-regular file */
911 unsigned unbound_nonreg_file : 1;
912 /* opcode is not supported by this kernel */
913 unsigned not_supported : 1;
914 /* set if opcode supports polled "wait" */
916 unsigned pollout : 1;
917 /* op supports buffer selection */
918 unsigned buffer_select : 1;
919 /* do prep async if is going to be punted */
920 unsigned needs_async_setup : 1;
921 /* should block plug */
923 /* size of async data needed, if any */
924 unsigned short async_size;
927 static const struct io_op_def io_op_defs[] = {
928 [IORING_OP_NOP] = {},
929 [IORING_OP_READV] = {
931 .unbound_nonreg_file = 1,
934 .needs_async_setup = 1,
936 .async_size = sizeof(struct io_async_rw),
938 [IORING_OP_WRITEV] = {
941 .unbound_nonreg_file = 1,
943 .needs_async_setup = 1,
945 .async_size = sizeof(struct io_async_rw),
947 [IORING_OP_FSYNC] = {
950 [IORING_OP_READ_FIXED] = {
952 .unbound_nonreg_file = 1,
955 .async_size = sizeof(struct io_async_rw),
957 [IORING_OP_WRITE_FIXED] = {
960 .unbound_nonreg_file = 1,
963 .async_size = sizeof(struct io_async_rw),
965 [IORING_OP_POLL_ADD] = {
967 .unbound_nonreg_file = 1,
969 [IORING_OP_POLL_REMOVE] = {},
970 [IORING_OP_SYNC_FILE_RANGE] = {
973 [IORING_OP_SENDMSG] = {
975 .unbound_nonreg_file = 1,
977 .needs_async_setup = 1,
978 .async_size = sizeof(struct io_async_msghdr),
980 [IORING_OP_RECVMSG] = {
982 .unbound_nonreg_file = 1,
985 .needs_async_setup = 1,
986 .async_size = sizeof(struct io_async_msghdr),
988 [IORING_OP_TIMEOUT] = {
989 .async_size = sizeof(struct io_timeout_data),
991 [IORING_OP_TIMEOUT_REMOVE] = {
992 /* used by timeout updates' prep() */
994 [IORING_OP_ACCEPT] = {
996 .unbound_nonreg_file = 1,
999 [IORING_OP_ASYNC_CANCEL] = {},
1000 [IORING_OP_LINK_TIMEOUT] = {
1001 .async_size = sizeof(struct io_timeout_data),
1003 [IORING_OP_CONNECT] = {
1005 .unbound_nonreg_file = 1,
1007 .needs_async_setup = 1,
1008 .async_size = sizeof(struct io_async_connect),
1010 [IORING_OP_FALLOCATE] = {
1013 [IORING_OP_OPENAT] = {},
1014 [IORING_OP_CLOSE] = {},
1015 [IORING_OP_FILES_UPDATE] = {},
1016 [IORING_OP_STATX] = {},
1017 [IORING_OP_READ] = {
1019 .unbound_nonreg_file = 1,
1023 .async_size = sizeof(struct io_async_rw),
1025 [IORING_OP_WRITE] = {
1028 .unbound_nonreg_file = 1,
1031 .async_size = sizeof(struct io_async_rw),
1033 [IORING_OP_FADVISE] = {
1036 [IORING_OP_MADVISE] = {},
1037 [IORING_OP_SEND] = {
1039 .unbound_nonreg_file = 1,
1042 [IORING_OP_RECV] = {
1044 .unbound_nonreg_file = 1,
1048 [IORING_OP_OPENAT2] = {
1050 [IORING_OP_EPOLL_CTL] = {
1051 .unbound_nonreg_file = 1,
1053 [IORING_OP_SPLICE] = {
1056 .unbound_nonreg_file = 1,
1058 [IORING_OP_PROVIDE_BUFFERS] = {},
1059 [IORING_OP_REMOVE_BUFFERS] = {},
1063 .unbound_nonreg_file = 1,
1065 [IORING_OP_SHUTDOWN] = {
1068 [IORING_OP_RENAMEAT] = {},
1069 [IORING_OP_UNLINKAT] = {},
1072 /* requests with any of those set should undergo io_disarm_next() */
1073 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1075 static bool io_disarm_next(struct io_kiocb *req);
1076 static void io_uring_del_tctx_node(unsigned long index);
1077 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1078 struct task_struct *task,
1080 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1082 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1084 static void io_put_req(struct io_kiocb *req);
1085 static void io_put_req_deferred(struct io_kiocb *req);
1086 static void io_dismantle_req(struct io_kiocb *req);
1087 static void io_queue_linked_timeout(struct io_kiocb *req);
1088 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1089 struct io_uring_rsrc_update2 *up,
1091 static void io_clean_op(struct io_kiocb *req);
1092 static struct file *io_file_get(struct io_ring_ctx *ctx,
1093 struct io_kiocb *req, int fd, bool fixed,
1094 unsigned int issue_flags);
1095 static void __io_queue_sqe(struct io_kiocb *req);
1096 static void io_rsrc_put_work(struct work_struct *work);
1098 static void io_req_task_queue(struct io_kiocb *req);
1099 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1100 static int io_req_prep_async(struct io_kiocb *req);
1102 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1103 unsigned int issue_flags, u32 slot_index);
1104 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1106 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1108 static struct kmem_cache *req_cachep;
1110 static const struct file_operations io_uring_fops;
1112 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1115 mutex_lock(&ctx->uring_lock);
1120 #define io_for_each_link(pos, head) \
1121 for (pos = (head); pos; pos = pos->link)
1124 * Shamelessly stolen from the mm implementation of page reference checking,
1125 * see commit f958d7b528b1 for details.
1127 #define req_ref_zero_or_close_to_overflow(req) \
1128 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1130 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1132 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1133 return atomic_inc_not_zero(&req->refs);
1136 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1138 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1141 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1142 return atomic_dec_and_test(&req->refs);
1145 static inline void req_ref_get(struct io_kiocb *req)
1147 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1148 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1149 atomic_inc(&req->refs);
1152 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1154 if (!(req->flags & REQ_F_REFCOUNT)) {
1155 req->flags |= REQ_F_REFCOUNT;
1156 atomic_set(&req->refs, nr);
1160 static inline void io_req_set_refcount(struct io_kiocb *req)
1162 __io_req_set_refcount(req, 1);
1165 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1167 struct io_ring_ctx *ctx = req->ctx;
1169 if (!req->fixed_rsrc_refs) {
1170 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1171 percpu_ref_get(req->fixed_rsrc_refs);
1175 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1177 bool got = percpu_ref_tryget(ref);
1179 /* already at zero, wait for ->release() */
1181 wait_for_completion(compl);
1182 percpu_ref_resurrect(ref);
1184 percpu_ref_put(ref);
1187 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1189 __must_hold(&req->ctx->timeout_lock)
1191 struct io_kiocb *req;
1193 if (task && head->task != task)
1198 io_for_each_link(req, head) {
1199 if (req->flags & REQ_F_INFLIGHT)
1205 static bool io_match_linked(struct io_kiocb *head)
1207 struct io_kiocb *req;
1209 io_for_each_link(req, head) {
1210 if (req->flags & REQ_F_INFLIGHT)
1217 * As io_match_task() but protected against racing with linked timeouts.
1218 * User must not hold timeout_lock.
1220 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1225 if (task && head->task != task)
1230 if (head->flags & REQ_F_LINK_TIMEOUT) {
1231 struct io_ring_ctx *ctx = head->ctx;
1233 /* protect against races with linked timeouts */
1234 spin_lock_irq(&ctx->timeout_lock);
1235 matched = io_match_linked(head);
1236 spin_unlock_irq(&ctx->timeout_lock);
1238 matched = io_match_linked(head);
1243 static inline void req_set_fail(struct io_kiocb *req)
1245 req->flags |= REQ_F_FAIL;
1248 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1254 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1256 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1258 complete(&ctx->ref_comp);
1261 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1263 return !req->timeout.off;
1266 static void io_fallback_req_func(struct work_struct *work)
1268 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1269 fallback_work.work);
1270 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1271 struct io_kiocb *req, *tmp;
1272 bool locked = false;
1274 percpu_ref_get(&ctx->refs);
1275 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1276 req->io_task_work.func(req, &locked);
1279 if (ctx->submit_state.compl_nr)
1280 io_submit_flush_completions(ctx);
1281 mutex_unlock(&ctx->uring_lock);
1283 percpu_ref_put(&ctx->refs);
1287 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1289 struct io_ring_ctx *ctx;
1292 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1297 * Use 5 bits less than the max cq entries, that should give us around
1298 * 32 entries per hash list if totally full and uniformly spread.
1300 hash_bits = ilog2(p->cq_entries);
1304 ctx->cancel_hash_bits = hash_bits;
1305 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1307 if (!ctx->cancel_hash)
1309 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1311 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1312 if (!ctx->dummy_ubuf)
1314 /* set invalid range, so io_import_fixed() fails meeting it */
1315 ctx->dummy_ubuf->ubuf = -1UL;
1317 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1318 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1321 ctx->flags = p->flags;
1322 init_waitqueue_head(&ctx->sqo_sq_wait);
1323 INIT_LIST_HEAD(&ctx->sqd_list);
1324 init_waitqueue_head(&ctx->poll_wait);
1325 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1326 init_completion(&ctx->ref_comp);
1327 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1328 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1329 mutex_init(&ctx->uring_lock);
1330 init_waitqueue_head(&ctx->cq_wait);
1331 spin_lock_init(&ctx->completion_lock);
1332 spin_lock_init(&ctx->timeout_lock);
1333 INIT_LIST_HEAD(&ctx->iopoll_list);
1334 INIT_LIST_HEAD(&ctx->defer_list);
1335 INIT_LIST_HEAD(&ctx->timeout_list);
1336 INIT_LIST_HEAD(&ctx->ltimeout_list);
1337 spin_lock_init(&ctx->rsrc_ref_lock);
1338 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1339 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1340 init_llist_head(&ctx->rsrc_put_llist);
1341 INIT_LIST_HEAD(&ctx->tctx_list);
1342 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1343 INIT_LIST_HEAD(&ctx->locked_free_list);
1344 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1347 kfree(ctx->dummy_ubuf);
1348 kfree(ctx->cancel_hash);
1353 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1355 struct io_rings *r = ctx->rings;
1357 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1361 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1363 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1364 struct io_ring_ctx *ctx = req->ctx;
1366 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1372 #define FFS_ASYNC_READ 0x1UL
1373 #define FFS_ASYNC_WRITE 0x2UL
1375 #define FFS_ISREG 0x4UL
1377 #define FFS_ISREG 0x0UL
1379 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1381 static inline bool io_req_ffs_set(struct io_kiocb *req)
1383 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1386 static void io_req_track_inflight(struct io_kiocb *req)
1388 if (!(req->flags & REQ_F_INFLIGHT)) {
1389 req->flags |= REQ_F_INFLIGHT;
1390 atomic_inc(&req->task->io_uring->inflight_tracked);
1394 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1396 if (WARN_ON_ONCE(!req->link))
1399 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1400 req->flags |= REQ_F_LINK_TIMEOUT;
1402 /* linked timeouts should have two refs once prep'ed */
1403 io_req_set_refcount(req);
1404 __io_req_set_refcount(req->link, 2);
1408 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1410 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1412 return __io_prep_linked_timeout(req);
1415 static void io_prep_async_work(struct io_kiocb *req)
1417 const struct io_op_def *def = &io_op_defs[req->opcode];
1418 struct io_ring_ctx *ctx = req->ctx;
1420 if (!(req->flags & REQ_F_CREDS)) {
1421 req->flags |= REQ_F_CREDS;
1422 req->creds = get_current_cred();
1425 req->work.list.next = NULL;
1426 req->work.flags = 0;
1427 if (req->flags & REQ_F_FORCE_ASYNC)
1428 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1430 if (req->flags & REQ_F_ISREG) {
1431 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1432 io_wq_hash_work(&req->work, file_inode(req->file));
1433 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1434 if (def->unbound_nonreg_file)
1435 req->work.flags |= IO_WQ_WORK_UNBOUND;
1439 static void io_prep_async_link(struct io_kiocb *req)
1441 struct io_kiocb *cur;
1443 if (req->flags & REQ_F_LINK_TIMEOUT) {
1444 struct io_ring_ctx *ctx = req->ctx;
1446 spin_lock_irq(&ctx->timeout_lock);
1447 io_for_each_link(cur, req)
1448 io_prep_async_work(cur);
1449 spin_unlock_irq(&ctx->timeout_lock);
1451 io_for_each_link(cur, req)
1452 io_prep_async_work(cur);
1456 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1458 struct io_ring_ctx *ctx = req->ctx;
1459 struct io_kiocb *link = io_prep_linked_timeout(req);
1460 struct io_uring_task *tctx = req->task->io_uring;
1462 /* must not take the lock, NULL it as a precaution */
1466 BUG_ON(!tctx->io_wq);
1468 /* init ->work of the whole link before punting */
1469 io_prep_async_link(req);
1472 * Not expected to happen, but if we do have a bug where this _can_
1473 * happen, catch it here and ensure the request is marked as
1474 * canceled. That will make io-wq go through the usual work cancel
1475 * procedure rather than attempt to run this request (or create a new
1478 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1479 req->work.flags |= IO_WQ_WORK_CANCEL;
1481 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1482 &req->work, req->flags);
1483 io_wq_enqueue(tctx->io_wq, &req->work);
1485 io_queue_linked_timeout(link);
1488 static void io_kill_timeout(struct io_kiocb *req, int status)
1489 __must_hold(&req->ctx->completion_lock)
1490 __must_hold(&req->ctx->timeout_lock)
1492 struct io_timeout_data *io = req->async_data;
1494 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1497 atomic_set(&req->ctx->cq_timeouts,
1498 atomic_read(&req->ctx->cq_timeouts) + 1);
1499 list_del_init(&req->timeout.list);
1500 io_fill_cqe_req(req, status, 0);
1501 io_put_req_deferred(req);
1505 static void io_queue_deferred(struct io_ring_ctx *ctx)
1507 lockdep_assert_held(&ctx->completion_lock);
1509 while (!list_empty(&ctx->defer_list)) {
1510 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1511 struct io_defer_entry, list);
1513 if (req_need_defer(de->req, de->seq))
1515 list_del_init(&de->list);
1516 io_req_task_queue(de->req);
1521 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1522 __must_hold(&ctx->completion_lock)
1524 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1525 struct io_kiocb *req, *tmp;
1527 spin_lock_irq(&ctx->timeout_lock);
1528 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1529 u32 events_needed, events_got;
1531 if (io_is_timeout_noseq(req))
1535 * Since seq can easily wrap around over time, subtract
1536 * the last seq at which timeouts were flushed before comparing.
1537 * Assuming not more than 2^31-1 events have happened since,
1538 * these subtractions won't have wrapped, so we can check if
1539 * target is in [last_seq, current_seq] by comparing the two.
1541 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1542 events_got = seq - ctx->cq_last_tm_flush;
1543 if (events_got < events_needed)
1546 io_kill_timeout(req, 0);
1548 ctx->cq_last_tm_flush = seq;
1549 spin_unlock_irq(&ctx->timeout_lock);
1552 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1554 if (ctx->off_timeout_used)
1555 io_flush_timeouts(ctx);
1556 if (ctx->drain_active)
1557 io_queue_deferred(ctx);
1560 static inline bool io_commit_needs_flush(struct io_ring_ctx *ctx)
1562 return ctx->off_timeout_used || ctx->drain_active;
1565 static inline void __io_commit_cqring(struct io_ring_ctx *ctx)
1567 /* order cqe stores with ring update */
1568 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1571 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1573 if (unlikely(io_commit_needs_flush(ctx)))
1574 __io_commit_cqring_flush(ctx);
1575 __io_commit_cqring(ctx);
1578 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1580 struct io_rings *r = ctx->rings;
1582 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1585 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1587 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1590 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1592 struct io_rings *rings = ctx->rings;
1593 unsigned tail, mask = ctx->cq_entries - 1;
1596 * writes to the cq entry need to come after reading head; the
1597 * control dependency is enough as we're using WRITE_ONCE to
1600 if (__io_cqring_events(ctx) == ctx->cq_entries)
1603 tail = ctx->cached_cq_tail++;
1604 return &rings->cqes[tail & mask];
1607 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1609 if (likely(!ctx->cq_ev_fd))
1611 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1613 return !ctx->eventfd_async || io_wq_current_is_worker();
1617 * This should only get called when at least one event has been posted.
1618 * Some applications rely on the eventfd notification count only changing
1619 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1620 * 1:1 relationship between how many times this function is called (and
1621 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1623 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1626 * wake_up_all() may seem excessive, but io_wake_function() and
1627 * io_should_wake() handle the termination of the loop and only
1628 * wake as many waiters as we need to.
1630 if (wq_has_sleeper(&ctx->cq_wait))
1631 __wake_up(&ctx->cq_wait, TASK_NORMAL, 0,
1632 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1633 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1634 wake_up(&ctx->sq_data->wait);
1635 if (io_should_trigger_evfd(ctx))
1636 eventfd_signal_mask(ctx->cq_ev_fd, 1, EPOLL_URING_WAKE);
1637 if (waitqueue_active(&ctx->poll_wait))
1638 __wake_up(&ctx->poll_wait, TASK_INTERRUPTIBLE, 0,
1639 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1642 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1644 /* see waitqueue_active() comment */
1647 if (ctx->flags & IORING_SETUP_SQPOLL) {
1648 if (waitqueue_active(&ctx->cq_wait))
1649 __wake_up(&ctx->cq_wait, TASK_NORMAL, 0,
1650 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1652 if (io_should_trigger_evfd(ctx))
1653 eventfd_signal_mask(ctx->cq_ev_fd, 1, EPOLL_URING_WAKE);
1654 if (waitqueue_active(&ctx->poll_wait))
1655 __wake_up(&ctx->poll_wait, TASK_INTERRUPTIBLE, 0,
1656 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1659 /* Returns true if there are no backlogged entries after the flush */
1660 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1662 bool all_flushed, posted;
1664 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1668 spin_lock(&ctx->completion_lock);
1669 while (!list_empty(&ctx->cq_overflow_list)) {
1670 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1671 struct io_overflow_cqe *ocqe;
1675 ocqe = list_first_entry(&ctx->cq_overflow_list,
1676 struct io_overflow_cqe, list);
1678 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1680 io_account_cq_overflow(ctx);
1683 list_del(&ocqe->list);
1687 all_flushed = list_empty(&ctx->cq_overflow_list);
1689 clear_bit(0, &ctx->check_cq_overflow);
1690 WRITE_ONCE(ctx->rings->sq_flags,
1691 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1695 io_commit_cqring(ctx);
1696 spin_unlock(&ctx->completion_lock);
1698 io_cqring_ev_posted(ctx);
1702 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1706 if (test_bit(0, &ctx->check_cq_overflow)) {
1707 /* iopoll syncs against uring_lock, not completion_lock */
1708 if (ctx->flags & IORING_SETUP_IOPOLL)
1709 mutex_lock(&ctx->uring_lock);
1710 ret = __io_cqring_overflow_flush(ctx, false);
1711 if (ctx->flags & IORING_SETUP_IOPOLL)
1712 mutex_unlock(&ctx->uring_lock);
1718 /* must to be called somewhat shortly after putting a request */
1719 static inline void io_put_task(struct task_struct *task, int nr)
1721 struct io_uring_task *tctx = task->io_uring;
1723 if (likely(task == current)) {
1724 tctx->cached_refs += nr;
1726 percpu_counter_sub(&tctx->inflight, nr);
1727 if (unlikely(atomic_read(&tctx->in_idle)))
1728 wake_up(&tctx->wait);
1729 put_task_struct_many(task, nr);
1733 static void io_task_refs_refill(struct io_uring_task *tctx)
1735 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1737 percpu_counter_add(&tctx->inflight, refill);
1738 refcount_add(refill, ¤t->usage);
1739 tctx->cached_refs += refill;
1742 static inline void io_get_task_refs(int nr)
1744 struct io_uring_task *tctx = current->io_uring;
1746 tctx->cached_refs -= nr;
1747 if (unlikely(tctx->cached_refs < 0))
1748 io_task_refs_refill(tctx);
1751 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1753 struct io_uring_task *tctx = task->io_uring;
1754 unsigned int refs = tctx->cached_refs;
1757 tctx->cached_refs = 0;
1758 percpu_counter_sub(&tctx->inflight, refs);
1759 put_task_struct_many(task, refs);
1763 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1764 s32 res, u32 cflags)
1766 struct io_overflow_cqe *ocqe;
1768 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1771 * If we're in ring overflow flush mode, or in task cancel mode,
1772 * or cannot allocate an overflow entry, then we need to drop it
1775 io_account_cq_overflow(ctx);
1778 if (list_empty(&ctx->cq_overflow_list)) {
1779 set_bit(0, &ctx->check_cq_overflow);
1780 WRITE_ONCE(ctx->rings->sq_flags,
1781 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1784 ocqe->cqe.user_data = user_data;
1785 ocqe->cqe.res = res;
1786 ocqe->cqe.flags = cflags;
1787 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1791 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
1792 s32 res, u32 cflags)
1794 struct io_uring_cqe *cqe;
1796 trace_io_uring_complete(ctx, user_data, res, cflags);
1799 * If we can't get a cq entry, userspace overflowed the
1800 * submission (by quite a lot). Increment the overflow count in
1803 cqe = io_get_cqe(ctx);
1805 WRITE_ONCE(cqe->user_data, user_data);
1806 WRITE_ONCE(cqe->res, res);
1807 WRITE_ONCE(cqe->flags, cflags);
1810 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1813 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
1815 __io_fill_cqe(req->ctx, req->user_data, res, cflags);
1818 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
1819 s32 res, u32 cflags)
1822 return __io_fill_cqe(ctx, user_data, res, cflags);
1825 static void io_req_complete_post(struct io_kiocb *req, s32 res,
1828 struct io_ring_ctx *ctx = req->ctx;
1830 spin_lock(&ctx->completion_lock);
1831 __io_fill_cqe(ctx, req->user_data, res, cflags);
1833 * If we're the last reference to this request, add to our locked
1836 if (req_ref_put_and_test(req)) {
1837 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1838 if (req->flags & IO_DISARM_MASK)
1839 io_disarm_next(req);
1841 io_req_task_queue(req->link);
1845 io_dismantle_req(req);
1846 io_put_task(req->task, 1);
1847 list_add(&req->inflight_entry, &ctx->locked_free_list);
1848 ctx->locked_free_nr++;
1850 if (!percpu_ref_tryget(&ctx->refs))
1853 io_commit_cqring(ctx);
1854 spin_unlock(&ctx->completion_lock);
1857 io_cqring_ev_posted(ctx);
1858 percpu_ref_put(&ctx->refs);
1862 static inline bool io_req_needs_clean(struct io_kiocb *req)
1864 return req->flags & IO_REQ_CLEAN_FLAGS;
1867 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
1870 if (io_req_needs_clean(req))
1873 req->compl.cflags = cflags;
1874 req->flags |= REQ_F_COMPLETE_INLINE;
1877 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1878 s32 res, u32 cflags)
1880 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1881 io_req_complete_state(req, res, cflags);
1883 io_req_complete_post(req, res, cflags);
1886 static inline void io_req_complete(struct io_kiocb *req, s32 res)
1888 __io_req_complete(req, 0, res, 0);
1891 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
1894 io_req_complete_post(req, res, 0);
1897 static void io_req_complete_fail_submit(struct io_kiocb *req)
1900 * We don't submit, fail them all, for that replace hardlinks with
1901 * normal links. Extra REQ_F_LINK is tolerated.
1903 req->flags &= ~REQ_F_HARDLINK;
1904 req->flags |= REQ_F_LINK;
1905 io_req_complete_failed(req, req->result);
1909 * Don't initialise the fields below on every allocation, but do that in
1910 * advance and keep them valid across allocations.
1912 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1916 req->async_data = NULL;
1917 /* not necessary, but safer to zero */
1921 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1922 struct io_submit_state *state)
1924 spin_lock(&ctx->completion_lock);
1925 list_splice_init(&ctx->locked_free_list, &state->free_list);
1926 ctx->locked_free_nr = 0;
1927 spin_unlock(&ctx->completion_lock);
1930 /* Returns true IFF there are requests in the cache */
1931 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1933 struct io_submit_state *state = &ctx->submit_state;
1937 * If we have more than a batch's worth of requests in our IRQ side
1938 * locked cache, grab the lock and move them over to our submission
1941 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1942 io_flush_cached_locked_reqs(ctx, state);
1944 nr = state->free_reqs;
1945 while (!list_empty(&state->free_list)) {
1946 struct io_kiocb *req = list_first_entry(&state->free_list,
1947 struct io_kiocb, inflight_entry);
1949 list_del(&req->inflight_entry);
1950 state->reqs[nr++] = req;
1951 if (nr == ARRAY_SIZE(state->reqs))
1955 state->free_reqs = nr;
1960 * A request might get retired back into the request caches even before opcode
1961 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1962 * Because of that, io_alloc_req() should be called only under ->uring_lock
1963 * and with extra caution to not get a request that is still worked on.
1965 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1966 __must_hold(&ctx->uring_lock)
1968 struct io_submit_state *state = &ctx->submit_state;
1969 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1972 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1974 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1977 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1981 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1982 * retry single alloc to be on the safe side.
1984 if (unlikely(ret <= 0)) {
1985 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1986 if (!state->reqs[0])
1991 for (i = 0; i < ret; i++)
1992 io_preinit_req(state->reqs[i], ctx);
1993 state->free_reqs = ret;
1996 return state->reqs[state->free_reqs];
1999 static inline void io_put_file(struct file *file)
2005 static void io_dismantle_req(struct io_kiocb *req)
2007 unsigned int flags = req->flags;
2009 if (io_req_needs_clean(req))
2011 if (!(flags & REQ_F_FIXED_FILE))
2012 io_put_file(req->file);
2013 if (req->fixed_rsrc_refs)
2014 percpu_ref_put(req->fixed_rsrc_refs);
2015 if (req->async_data) {
2016 kfree(req->async_data);
2017 req->async_data = NULL;
2021 static void __io_free_req(struct io_kiocb *req)
2023 struct io_ring_ctx *ctx = req->ctx;
2025 io_dismantle_req(req);
2026 io_put_task(req->task, 1);
2028 spin_lock(&ctx->completion_lock);
2029 list_add(&req->inflight_entry, &ctx->locked_free_list);
2030 ctx->locked_free_nr++;
2031 spin_unlock(&ctx->completion_lock);
2033 percpu_ref_put(&ctx->refs);
2036 static inline void io_remove_next_linked(struct io_kiocb *req)
2038 struct io_kiocb *nxt = req->link;
2040 req->link = nxt->link;
2044 static bool io_kill_linked_timeout(struct io_kiocb *req)
2045 __must_hold(&req->ctx->completion_lock)
2046 __must_hold(&req->ctx->timeout_lock)
2048 struct io_kiocb *link = req->link;
2050 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2051 struct io_timeout_data *io = link->async_data;
2053 io_remove_next_linked(req);
2054 link->timeout.head = NULL;
2055 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2056 list_del(&link->timeout.list);
2057 io_fill_cqe_req(link, -ECANCELED, 0);
2058 io_put_req_deferred(link);
2065 static void io_fail_links(struct io_kiocb *req)
2066 __must_hold(&req->ctx->completion_lock)
2068 struct io_kiocb *nxt, *link = req->link;
2072 long res = -ECANCELED;
2074 if (link->flags & REQ_F_FAIL)
2080 trace_io_uring_fail_link(req, link);
2081 io_fill_cqe_req(link, res, 0);
2082 io_put_req_deferred(link);
2087 static bool io_disarm_next(struct io_kiocb *req)
2088 __must_hold(&req->ctx->completion_lock)
2090 bool posted = false;
2092 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2093 struct io_kiocb *link = req->link;
2095 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2096 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2097 io_remove_next_linked(req);
2098 io_fill_cqe_req(link, -ECANCELED, 0);
2099 io_put_req_deferred(link);
2102 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2103 struct io_ring_ctx *ctx = req->ctx;
2105 spin_lock_irq(&ctx->timeout_lock);
2106 posted = io_kill_linked_timeout(req);
2107 spin_unlock_irq(&ctx->timeout_lock);
2109 if (unlikely((req->flags & REQ_F_FAIL) &&
2110 !(req->flags & REQ_F_HARDLINK))) {
2111 posted |= (req->link != NULL);
2117 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2119 struct io_kiocb *nxt;
2122 * If LINK is set, we have dependent requests in this chain. If we
2123 * didn't fail this request, queue the first one up, moving any other
2124 * dependencies to the next request. In case of failure, fail the rest
2127 if (req->flags & IO_DISARM_MASK) {
2128 struct io_ring_ctx *ctx = req->ctx;
2131 spin_lock(&ctx->completion_lock);
2132 posted = io_disarm_next(req);
2134 io_commit_cqring(req->ctx);
2135 spin_unlock(&ctx->completion_lock);
2137 io_cqring_ev_posted(ctx);
2144 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2146 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2148 return __io_req_find_next(req);
2151 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2156 if (ctx->submit_state.compl_nr)
2157 io_submit_flush_completions(ctx);
2158 mutex_unlock(&ctx->uring_lock);
2161 percpu_ref_put(&ctx->refs);
2164 static void tctx_task_work(struct callback_head *cb)
2166 bool locked = false;
2167 struct io_ring_ctx *ctx = NULL;
2168 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2172 struct io_wq_work_node *node;
2174 if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
2175 io_submit_flush_completions(ctx);
2177 spin_lock_irq(&tctx->task_lock);
2178 node = tctx->task_list.first;
2179 INIT_WQ_LIST(&tctx->task_list);
2181 tctx->task_running = false;
2182 spin_unlock_irq(&tctx->task_lock);
2187 struct io_wq_work_node *next = node->next;
2188 struct io_kiocb *req = container_of(node, struct io_kiocb,
2191 if (req->ctx != ctx) {
2192 ctx_flush_and_put(ctx, &locked);
2194 /* if not contended, grab and improve batching */
2195 locked = mutex_trylock(&ctx->uring_lock);
2196 percpu_ref_get(&ctx->refs);
2198 req->io_task_work.func(req, &locked);
2200 if (unlikely(need_resched())) {
2201 ctx_flush_and_put(ctx, &locked);
2208 ctx_flush_and_put(ctx, &locked);
2210 /* relaxed read is enough as only the task itself sets ->in_idle */
2211 if (unlikely(atomic_read(&tctx->in_idle)))
2212 io_uring_drop_tctx_refs(current);
2215 static void io_req_task_work_add(struct io_kiocb *req)
2217 struct task_struct *tsk = req->task;
2218 struct io_uring_task *tctx = tsk->io_uring;
2219 enum task_work_notify_mode notify;
2220 struct io_wq_work_node *node;
2221 unsigned long flags;
2224 WARN_ON_ONCE(!tctx);
2226 spin_lock_irqsave(&tctx->task_lock, flags);
2227 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2228 running = tctx->task_running;
2230 tctx->task_running = true;
2231 spin_unlock_irqrestore(&tctx->task_lock, flags);
2233 /* task_work already pending, we're done */
2238 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2239 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2240 * processing task_work. There's no reliable way to tell if TWA_RESUME
2243 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2244 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2245 wake_up_process(tsk);
2249 spin_lock_irqsave(&tctx->task_lock, flags);
2250 tctx->task_running = false;
2251 node = tctx->task_list.first;
2252 INIT_WQ_LIST(&tctx->task_list);
2253 spin_unlock_irqrestore(&tctx->task_lock, flags);
2256 req = container_of(node, struct io_kiocb, io_task_work.node);
2258 if (llist_add(&req->io_task_work.fallback_node,
2259 &req->ctx->fallback_llist))
2260 schedule_delayed_work(&req->ctx->fallback_work, 1);
2264 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2266 struct io_ring_ctx *ctx = req->ctx;
2268 /* not needed for normal modes, but SQPOLL depends on it */
2269 io_tw_lock(ctx, locked);
2270 io_req_complete_failed(req, req->result);
2273 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2275 struct io_ring_ctx *ctx = req->ctx;
2277 io_tw_lock(ctx, locked);
2278 /* req->task == current here, checking PF_EXITING is safe */
2279 if (likely(!(req->task->flags & PF_EXITING)))
2280 __io_queue_sqe(req);
2282 io_req_complete_failed(req, -EFAULT);
2285 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2288 req->io_task_work.func = io_req_task_cancel;
2289 io_req_task_work_add(req);
2292 static void io_req_task_queue(struct io_kiocb *req)
2294 req->io_task_work.func = io_req_task_submit;
2295 io_req_task_work_add(req);
2298 static void io_req_task_queue_reissue(struct io_kiocb *req)
2300 req->io_task_work.func = io_queue_async_work;
2301 io_req_task_work_add(req);
2304 static inline void io_queue_next(struct io_kiocb *req)
2306 struct io_kiocb *nxt = io_req_find_next(req);
2309 io_req_task_queue(nxt);
2312 static void io_free_req(struct io_kiocb *req)
2318 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2324 struct task_struct *task;
2329 static inline void io_init_req_batch(struct req_batch *rb)
2336 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2337 struct req_batch *rb)
2340 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2342 io_put_task(rb->task, rb->task_refs);
2345 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2346 struct io_submit_state *state)
2349 io_dismantle_req(req);
2351 if (req->task != rb->task) {
2353 io_put_task(rb->task, rb->task_refs);
2354 rb->task = req->task;
2360 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2361 state->reqs[state->free_reqs++] = req;
2363 list_add(&req->inflight_entry, &state->free_list);
2366 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2367 __must_hold(&ctx->uring_lock)
2369 struct io_submit_state *state = &ctx->submit_state;
2370 int i, nr = state->compl_nr;
2371 struct req_batch rb;
2373 spin_lock(&ctx->completion_lock);
2374 for (i = 0; i < nr; i++) {
2375 struct io_kiocb *req = state->compl_reqs[i];
2377 __io_fill_cqe(ctx, req->user_data, req->result,
2380 io_commit_cqring(ctx);
2381 spin_unlock(&ctx->completion_lock);
2382 io_cqring_ev_posted(ctx);
2384 io_init_req_batch(&rb);
2385 for (i = 0; i < nr; i++) {
2386 struct io_kiocb *req = state->compl_reqs[i];
2388 if (req_ref_put_and_test(req))
2389 io_req_free_batch(&rb, req, &ctx->submit_state);
2392 io_req_free_batch_finish(ctx, &rb);
2393 state->compl_nr = 0;
2397 * Drop reference to request, return next in chain (if there is one) if this
2398 * was the last reference to this request.
2400 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2402 struct io_kiocb *nxt = NULL;
2404 if (req_ref_put_and_test(req)) {
2405 nxt = io_req_find_next(req);
2411 static inline void io_put_req(struct io_kiocb *req)
2413 if (req_ref_put_and_test(req))
2417 static inline void io_put_req_deferred(struct io_kiocb *req)
2419 if (req_ref_put_and_test(req)) {
2420 req->io_task_work.func = io_free_req_work;
2421 io_req_task_work_add(req);
2425 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2427 /* See comment at the top of this file */
2429 return __io_cqring_events(ctx);
2432 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2434 struct io_rings *rings = ctx->rings;
2436 /* make sure SQ entry isn't read before tail */
2437 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2440 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2442 unsigned int cflags;
2444 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2445 cflags |= IORING_CQE_F_BUFFER;
2446 req->flags &= ~REQ_F_BUFFER_SELECTED;
2451 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2453 struct io_buffer *kbuf;
2455 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2457 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2458 return io_put_kbuf(req, kbuf);
2461 static inline bool io_run_task_work(void)
2464 * PF_IO_WORKER never returns to userspace, so check here if we have
2465 * notify work that needs processing.
2467 if (current->flags & PF_IO_WORKER &&
2468 test_thread_flag(TIF_NOTIFY_RESUME)) {
2469 __set_current_state(TASK_RUNNING);
2470 tracehook_notify_resume(NULL);
2472 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2473 __set_current_state(TASK_RUNNING);
2474 tracehook_notify_signal();
2482 * Find and free completed poll iocbs
2484 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2485 struct list_head *done)
2487 struct req_batch rb;
2488 struct io_kiocb *req;
2490 /* order with ->result store in io_complete_rw_iopoll() */
2493 io_init_req_batch(&rb);
2494 while (!list_empty(done)) {
2495 struct io_uring_cqe *cqe;
2498 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2499 list_del(&req->inflight_entry);
2500 cflags = io_put_rw_kbuf(req);
2503 cqe = io_get_cqe(ctx);
2505 WRITE_ONCE(cqe->user_data, req->user_data);
2506 WRITE_ONCE(cqe->res, req->result);
2507 WRITE_ONCE(cqe->flags, cflags);
2509 spin_lock(&ctx->completion_lock);
2510 io_cqring_event_overflow(ctx, req->user_data,
2511 req->result, cflags);
2512 spin_unlock(&ctx->completion_lock);
2515 if (req_ref_put_and_test(req))
2516 io_req_free_batch(&rb, req, &ctx->submit_state);
2519 if (io_commit_needs_flush(ctx)) {
2520 spin_lock(&ctx->completion_lock);
2521 __io_commit_cqring_flush(ctx);
2522 spin_unlock(&ctx->completion_lock);
2524 __io_commit_cqring(ctx);
2525 io_cqring_ev_posted_iopoll(ctx);
2526 io_req_free_batch_finish(ctx, &rb);
2529 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2532 struct io_kiocb *req, *tmp;
2537 * Only spin for completions if we don't have multiple devices hanging
2538 * off our complete list, and we're under the requested amount.
2540 spin = !ctx->poll_multi_queue && *nr_events < min;
2542 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2543 struct kiocb *kiocb = &req->rw.kiocb;
2547 * Move completed and retryable entries to our local lists.
2548 * If we find a request that requires polling, break out
2549 * and complete those lists first, if we have entries there.
2551 if (READ_ONCE(req->iopoll_completed)) {
2552 list_move_tail(&req->inflight_entry, &done);
2555 if (!list_empty(&done))
2558 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2559 if (unlikely(ret < 0))
2564 /* iopoll may have completed current req */
2565 if (READ_ONCE(req->iopoll_completed))
2566 list_move_tail(&req->inflight_entry, &done);
2569 if (!list_empty(&done))
2570 io_iopoll_complete(ctx, nr_events, &done);
2576 * We can't just wait for polled events to come to us, we have to actively
2577 * find and complete them.
2579 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2581 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2584 mutex_lock(&ctx->uring_lock);
2585 while (!list_empty(&ctx->iopoll_list)) {
2586 unsigned int nr_events = 0;
2588 io_do_iopoll(ctx, &nr_events, 0);
2590 /* let it sleep and repeat later if can't complete a request */
2594 * Ensure we allow local-to-the-cpu processing to take place,
2595 * in this case we need to ensure that we reap all events.
2596 * Also let task_work, etc. to progress by releasing the mutex
2598 if (need_resched()) {
2599 mutex_unlock(&ctx->uring_lock);
2601 mutex_lock(&ctx->uring_lock);
2604 mutex_unlock(&ctx->uring_lock);
2607 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2609 unsigned int nr_events = 0;
2613 * We disallow the app entering submit/complete with polling, but we
2614 * still need to lock the ring to prevent racing with polled issue
2615 * that got punted to a workqueue.
2617 mutex_lock(&ctx->uring_lock);
2619 * Don't enter poll loop if we already have events pending.
2620 * If we do, we can potentially be spinning for commands that
2621 * already triggered a CQE (eg in error).
2623 if (test_bit(0, &ctx->check_cq_overflow))
2624 __io_cqring_overflow_flush(ctx, false);
2625 if (io_cqring_events(ctx))
2629 * If a submit got punted to a workqueue, we can have the
2630 * application entering polling for a command before it gets
2631 * issued. That app will hold the uring_lock for the duration
2632 * of the poll right here, so we need to take a breather every
2633 * now and then to ensure that the issue has a chance to add
2634 * the poll to the issued list. Otherwise we can spin here
2635 * forever, while the workqueue is stuck trying to acquire the
2638 if (list_empty(&ctx->iopoll_list)) {
2639 u32 tail = ctx->cached_cq_tail;
2641 mutex_unlock(&ctx->uring_lock);
2643 mutex_lock(&ctx->uring_lock);
2645 /* some requests don't go through iopoll_list */
2646 if (tail != ctx->cached_cq_tail ||
2647 list_empty(&ctx->iopoll_list))
2650 ret = io_do_iopoll(ctx, &nr_events, min);
2652 if (task_sigpending(current)) {
2656 } while (!ret && nr_events < min && !need_resched());
2658 mutex_unlock(&ctx->uring_lock);
2662 static void kiocb_end_write(struct io_kiocb *req)
2665 * Tell lockdep we inherited freeze protection from submission
2668 if (req->flags & REQ_F_ISREG) {
2669 struct super_block *sb = file_inode(req->file)->i_sb;
2671 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2677 static bool io_resubmit_prep(struct io_kiocb *req)
2679 struct io_async_rw *rw = req->async_data;
2682 return !io_req_prep_async(req);
2683 iov_iter_restore(&rw->iter, &rw->iter_state);
2687 static bool io_rw_should_reissue(struct io_kiocb *req)
2689 umode_t mode = file_inode(req->file)->i_mode;
2690 struct io_ring_ctx *ctx = req->ctx;
2692 if (!S_ISBLK(mode) && !S_ISREG(mode))
2694 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2695 !(ctx->flags & IORING_SETUP_IOPOLL)))
2698 * If ref is dying, we might be running poll reap from the exit work.
2699 * Don't attempt to reissue from that path, just let it fail with
2702 if (percpu_ref_is_dying(&ctx->refs))
2705 * Play it safe and assume not safe to re-import and reissue if we're
2706 * not in the original thread group (or in task context).
2708 if (!same_thread_group(req->task, current) || !in_task())
2713 static bool io_resubmit_prep(struct io_kiocb *req)
2717 static bool io_rw_should_reissue(struct io_kiocb *req)
2724 * Trigger the notifications after having done some IO, and finish the write
2725 * accounting, if any.
2727 static void io_req_io_end(struct io_kiocb *req)
2729 struct io_rw *rw = &req->rw;
2731 if (rw->kiocb.ki_flags & IOCB_WRITE) {
2732 kiocb_end_write(req);
2733 fsnotify_modify(req->file);
2735 fsnotify_access(req->file);
2739 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2741 if (res != req->result) {
2742 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2743 io_rw_should_reissue(req)) {
2745 * Reissue will start accounting again, finish the
2749 req->flags |= REQ_F_REISSUE;
2758 static inline int io_fixup_rw_res(struct io_kiocb *req, long res)
2760 struct io_async_rw *io = req->async_data;
2762 /* add previously done IO, if any */
2763 if (io && io->bytes_done > 0) {
2765 res = io->bytes_done;
2767 res += io->bytes_done;
2772 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2774 unsigned int cflags = io_put_rw_kbuf(req);
2775 int res = req->result;
2778 struct io_ring_ctx *ctx = req->ctx;
2779 struct io_submit_state *state = &ctx->submit_state;
2781 io_req_complete_state(req, res, cflags);
2782 state->compl_reqs[state->compl_nr++] = req;
2783 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2784 io_submit_flush_completions(ctx);
2786 io_req_complete_post(req, res, cflags);
2790 static void io_req_rw_complete(struct io_kiocb *req, bool *locked)
2793 io_req_task_complete(req, locked);
2796 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2798 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2800 if (__io_complete_rw_common(req, res))
2802 req->result = io_fixup_rw_res(req, res);
2803 req->io_task_work.func = io_req_rw_complete;
2804 io_req_task_work_add(req);
2807 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2809 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2811 if (kiocb->ki_flags & IOCB_WRITE)
2812 kiocb_end_write(req);
2813 if (unlikely(res != req->result)) {
2814 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2815 req->flags |= REQ_F_REISSUE;
2820 WRITE_ONCE(req->result, res);
2821 /* order with io_iopoll_complete() checking ->result */
2823 WRITE_ONCE(req->iopoll_completed, 1);
2827 * After the iocb has been issued, it's safe to be found on the poll list.
2828 * Adding the kiocb to the list AFTER submission ensures that we don't
2829 * find it from a io_do_iopoll() thread before the issuer is done
2830 * accessing the kiocb cookie.
2832 static void io_iopoll_req_issued(struct io_kiocb *req)
2834 struct io_ring_ctx *ctx = req->ctx;
2835 const bool in_async = io_wq_current_is_worker();
2837 /* workqueue context doesn't hold uring_lock, grab it now */
2838 if (unlikely(in_async))
2839 mutex_lock(&ctx->uring_lock);
2842 * Track whether we have multiple files in our lists. This will impact
2843 * how we do polling eventually, not spinning if we're on potentially
2844 * different devices.
2846 if (list_empty(&ctx->iopoll_list)) {
2847 ctx->poll_multi_queue = false;
2848 } else if (!ctx->poll_multi_queue) {
2849 struct io_kiocb *list_req;
2850 unsigned int queue_num0, queue_num1;
2852 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2855 if (list_req->file != req->file) {
2856 ctx->poll_multi_queue = true;
2858 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2859 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2860 if (queue_num0 != queue_num1)
2861 ctx->poll_multi_queue = true;
2866 * For fast devices, IO may have already completed. If it has, add
2867 * it to the front so we find it first.
2869 if (READ_ONCE(req->iopoll_completed))
2870 list_add(&req->inflight_entry, &ctx->iopoll_list);
2872 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2874 if (unlikely(in_async)) {
2876 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2877 * in sq thread task context or in io worker task context. If
2878 * current task context is sq thread, we don't need to check
2879 * whether should wake up sq thread.
2881 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2882 wq_has_sleeper(&ctx->sq_data->wait))
2883 wake_up(&ctx->sq_data->wait);
2885 mutex_unlock(&ctx->uring_lock);
2889 static bool io_bdev_nowait(struct block_device *bdev)
2891 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2895 * If we tracked the file through the SCM inflight mechanism, we could support
2896 * any file. For now, just ensure that anything potentially problematic is done
2899 static bool __io_file_supports_nowait(struct file *file, int rw)
2901 umode_t mode = file_inode(file)->i_mode;
2903 if (S_ISBLK(mode)) {
2904 if (IS_ENABLED(CONFIG_BLOCK) &&
2905 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2911 if (S_ISREG(mode)) {
2912 if (IS_ENABLED(CONFIG_BLOCK) &&
2913 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2914 file->f_op != &io_uring_fops)
2919 /* any ->read/write should understand O_NONBLOCK */
2920 if (file->f_flags & O_NONBLOCK)
2923 if (!(file->f_mode & FMODE_NOWAIT))
2927 return file->f_op->read_iter != NULL;
2929 return file->f_op->write_iter != NULL;
2932 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2934 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2936 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2939 return __io_file_supports_nowait(req->file, rw);
2942 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2945 struct io_ring_ctx *ctx = req->ctx;
2946 struct kiocb *kiocb = &req->rw.kiocb;
2947 struct file *file = req->file;
2951 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2952 req->flags |= REQ_F_ISREG;
2954 kiocb->ki_pos = READ_ONCE(sqe->off);
2955 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2956 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2957 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2962 * If the file is marked O_NONBLOCK, still allow retry for it if it
2963 * supports async. Otherwise it's impossible to use O_NONBLOCK files
2964 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2966 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2967 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req, rw)))
2968 req->flags |= REQ_F_NOWAIT;
2970 ioprio = READ_ONCE(sqe->ioprio);
2972 ret = ioprio_check_cap(ioprio);
2976 kiocb->ki_ioprio = ioprio;
2978 kiocb->ki_ioprio = get_current_ioprio();
2980 if (ctx->flags & IORING_SETUP_IOPOLL) {
2981 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2982 !kiocb->ki_filp->f_op->iopoll)
2985 kiocb->ki_flags |= IOCB_HIPRI;
2986 kiocb->ki_complete = io_complete_rw_iopoll;
2987 req->iopoll_completed = 0;
2989 if (kiocb->ki_flags & IOCB_HIPRI)
2991 kiocb->ki_complete = io_complete_rw;
2994 /* used for fixed read/write too - just read unconditionally */
2995 req->buf_index = READ_ONCE(sqe->buf_index);
2998 if (req->opcode == IORING_OP_READ_FIXED ||
2999 req->opcode == IORING_OP_WRITE_FIXED) {
3000 struct io_ring_ctx *ctx = req->ctx;
3003 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3005 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3006 req->imu = ctx->user_bufs[index];
3007 io_req_set_rsrc_node(req);
3010 req->rw.addr = READ_ONCE(sqe->addr);
3011 req->rw.len = READ_ONCE(sqe->len);
3015 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3021 case -ERESTARTNOINTR:
3022 case -ERESTARTNOHAND:
3023 case -ERESTART_RESTARTBLOCK:
3025 * We can't just restart the syscall, since previously
3026 * submitted sqes may already be in progress. Just fail this
3032 kiocb->ki_complete(kiocb, ret, 0);
3036 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3038 struct kiocb *kiocb = &req->rw.kiocb;
3040 if (kiocb->ki_pos != -1)
3041 return &kiocb->ki_pos;
3043 if (!(req->file->f_mode & FMODE_STREAM)) {
3044 req->flags |= REQ_F_CUR_POS;
3045 kiocb->ki_pos = req->file->f_pos;
3046 return &kiocb->ki_pos;
3053 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
3054 unsigned int issue_flags)
3056 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3058 if (req->flags & REQ_F_CUR_POS)
3059 req->file->f_pos = kiocb->ki_pos;
3060 if (ret >= 0 && (kiocb->ki_complete == io_complete_rw)) {
3061 if (!__io_complete_rw_common(req, ret)) {
3063 * Safe to call io_end from here as we're inline
3064 * from the submission path.
3067 __io_req_complete(req, issue_flags,
3068 io_fixup_rw_res(req, ret),
3069 io_put_rw_kbuf(req));
3072 io_rw_done(kiocb, ret);
3075 if (req->flags & REQ_F_REISSUE) {
3076 req->flags &= ~REQ_F_REISSUE;
3077 if (io_resubmit_prep(req)) {
3078 io_req_task_queue_reissue(req);
3080 unsigned int cflags = io_put_rw_kbuf(req);
3081 struct io_ring_ctx *ctx = req->ctx;
3083 ret = io_fixup_rw_res(req, ret);
3085 if (!(issue_flags & IO_URING_F_NONBLOCK)) {
3086 mutex_lock(&ctx->uring_lock);
3087 __io_req_complete(req, issue_flags, ret, cflags);
3088 mutex_unlock(&ctx->uring_lock);
3090 __io_req_complete(req, issue_flags, ret, cflags);
3096 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3097 struct io_mapped_ubuf *imu)
3099 size_t len = req->rw.len;
3100 u64 buf_end, buf_addr = req->rw.addr;
3103 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3105 /* not inside the mapped region */
3106 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3110 * May not be a start of buffer, set size appropriately
3111 * and advance us to the beginning.
3113 offset = buf_addr - imu->ubuf;
3114 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3118 * Don't use iov_iter_advance() here, as it's really slow for
3119 * using the latter parts of a big fixed buffer - it iterates
3120 * over each segment manually. We can cheat a bit here, because
3123 * 1) it's a BVEC iter, we set it up
3124 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3125 * first and last bvec
3127 * So just find our index, and adjust the iterator afterwards.
3128 * If the offset is within the first bvec (or the whole first
3129 * bvec, just use iov_iter_advance(). This makes it easier
3130 * since we can just skip the first segment, which may not
3131 * be PAGE_SIZE aligned.
3133 const struct bio_vec *bvec = imu->bvec;
3135 if (offset < bvec->bv_len) {
3136 iov_iter_advance(iter, offset);
3138 unsigned long seg_skip;
3140 /* skip first vec */
3141 offset -= bvec->bv_len;
3142 seg_skip = 1 + (offset >> PAGE_SHIFT);
3144 iter->bvec = bvec + seg_skip;
3145 iter->nr_segs -= seg_skip;
3146 iter->count -= bvec->bv_len + offset;
3147 iter->iov_offset = offset & ~PAGE_MASK;
3154 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3156 if (WARN_ON_ONCE(!req->imu))
3158 return __io_import_fixed(req, rw, iter, req->imu);
3161 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3164 mutex_unlock(&ctx->uring_lock);
3167 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3170 * "Normal" inline submissions always hold the uring_lock, since we
3171 * grab it from the system call. Same is true for the SQPOLL offload.
3172 * The only exception is when we've detached the request and issue it
3173 * from an async worker thread, grab the lock for that case.
3176 mutex_lock(&ctx->uring_lock);
3179 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3180 int bgid, struct io_buffer *kbuf,
3183 struct io_buffer *head;
3185 if (req->flags & REQ_F_BUFFER_SELECTED)
3188 io_ring_submit_lock(req->ctx, needs_lock);
3190 lockdep_assert_held(&req->ctx->uring_lock);
3192 head = xa_load(&req->ctx->io_buffers, bgid);
3194 if (!list_empty(&head->list)) {
3195 kbuf = list_last_entry(&head->list, struct io_buffer,
3197 list_del(&kbuf->list);
3200 xa_erase(&req->ctx->io_buffers, bgid);
3202 if (*len > kbuf->len)
3205 kbuf = ERR_PTR(-ENOBUFS);
3208 io_ring_submit_unlock(req->ctx, needs_lock);
3213 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3216 struct io_buffer *kbuf;
3219 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3220 bgid = req->buf_index;
3221 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3224 req->rw.addr = (u64) (unsigned long) kbuf;
3225 req->flags |= REQ_F_BUFFER_SELECTED;
3226 return u64_to_user_ptr(kbuf->addr);
3229 #ifdef CONFIG_COMPAT
3230 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3233 struct compat_iovec __user *uiov;
3234 compat_ssize_t clen;
3238 uiov = u64_to_user_ptr(req->rw.addr);
3239 if (!access_ok(uiov, sizeof(*uiov)))
3241 if (__get_user(clen, &uiov->iov_len))
3247 buf = io_rw_buffer_select(req, &len, needs_lock);
3249 return PTR_ERR(buf);
3250 iov[0].iov_base = buf;
3251 iov[0].iov_len = (compat_size_t) len;
3256 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3259 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3263 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3266 len = iov[0].iov_len;
3269 buf = io_rw_buffer_select(req, &len, needs_lock);
3271 return PTR_ERR(buf);
3272 iov[0].iov_base = buf;
3273 iov[0].iov_len = len;
3277 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3280 if (req->flags & REQ_F_BUFFER_SELECTED) {
3281 struct io_buffer *kbuf;
3283 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3284 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3285 iov[0].iov_len = kbuf->len;
3288 if (req->rw.len != 1)
3291 #ifdef CONFIG_COMPAT
3292 if (req->ctx->compat)
3293 return io_compat_import(req, iov, needs_lock);
3296 return __io_iov_buffer_select(req, iov, needs_lock);
3299 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3300 struct iov_iter *iter, bool needs_lock)
3302 void __user *buf = u64_to_user_ptr(req->rw.addr);
3303 size_t sqe_len = req->rw.len;
3304 u8 opcode = req->opcode;
3307 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3309 return io_import_fixed(req, rw, iter);
3312 /* buffer index only valid with fixed read/write, or buffer select */
3313 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3316 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3317 if (req->flags & REQ_F_BUFFER_SELECT) {
3318 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3320 return PTR_ERR(buf);
3321 req->rw.len = sqe_len;
3324 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3329 if (req->flags & REQ_F_BUFFER_SELECT) {
3330 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3332 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3337 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3341 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3343 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3347 * For files that don't have ->read_iter() and ->write_iter(), handle them
3348 * by looping over ->read() or ->write() manually.
3350 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3352 struct kiocb *kiocb = &req->rw.kiocb;
3353 struct file *file = req->file;
3358 * Don't support polled IO through this interface, and we can't
3359 * support non-blocking either. For the latter, this just causes
3360 * the kiocb to be handled from an async context.
3362 if (kiocb->ki_flags & IOCB_HIPRI)
3364 if (kiocb->ki_flags & IOCB_NOWAIT)
3367 ppos = io_kiocb_ppos(kiocb);
3369 while (iov_iter_count(iter)) {
3373 if (!iov_iter_is_bvec(iter)) {
3374 iovec = iov_iter_iovec(iter);
3376 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3377 iovec.iov_len = req->rw.len;
3381 nr = file->f_op->read(file, iovec.iov_base,
3382 iovec.iov_len, ppos);
3384 nr = file->f_op->write(file, iovec.iov_base,
3385 iovec.iov_len, ppos);
3394 if (!iov_iter_is_bvec(iter)) {
3395 iov_iter_advance(iter, nr);
3402 if (nr != iovec.iov_len)
3409 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3410 const struct iovec *fast_iov, struct iov_iter *iter)
3412 struct io_async_rw *rw = req->async_data;
3414 memcpy(&rw->iter, iter, sizeof(*iter));
3415 rw->free_iovec = iovec;
3417 /* can only be fixed buffers, no need to do anything */
3418 if (iov_iter_is_bvec(iter))
3421 unsigned iov_off = 0;
3423 rw->iter.iov = rw->fast_iov;
3424 if (iter->iov != fast_iov) {
3425 iov_off = iter->iov - fast_iov;
3426 rw->iter.iov += iov_off;
3428 if (rw->fast_iov != fast_iov)
3429 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3430 sizeof(struct iovec) * iter->nr_segs);
3432 req->flags |= REQ_F_NEED_CLEANUP;
3436 static inline int io_alloc_async_data(struct io_kiocb *req)
3438 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3439 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3440 return req->async_data == NULL;
3443 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3444 const struct iovec *fast_iov,
3445 struct iov_iter *iter, bool force)
3447 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3449 if (!req->async_data) {
3450 struct io_async_rw *iorw;
3452 if (io_alloc_async_data(req)) {
3457 io_req_map_rw(req, iovec, fast_iov, iter);
3458 iorw = req->async_data;
3459 /* we've copied and mapped the iter, ensure state is saved */
3460 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3465 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3467 struct io_async_rw *iorw = req->async_data;
3468 struct iovec *iov = iorw->fast_iov;
3471 iorw->bytes_done = 0;
3472 iorw->free_iovec = NULL;
3474 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3475 if (unlikely(ret < 0))
3479 iorw->free_iovec = iov;
3480 req->flags |= REQ_F_NEED_CLEANUP;
3482 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3486 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3488 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3490 return io_prep_rw(req, sqe, READ);
3494 * This is our waitqueue callback handler, registered through lock_page_async()
3495 * when we initially tried to do the IO with the iocb armed our waitqueue.
3496 * This gets called when the page is unlocked, and we generally expect that to
3497 * happen when the page IO is completed and the page is now uptodate. This will
3498 * queue a task_work based retry of the operation, attempting to copy the data
3499 * again. If the latter fails because the page was NOT uptodate, then we will
3500 * do a thread based blocking retry of the operation. That's the unexpected
3503 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3504 int sync, void *arg)
3506 struct wait_page_queue *wpq;
3507 struct io_kiocb *req = wait->private;
3508 struct wait_page_key *key = arg;
3510 wpq = container_of(wait, struct wait_page_queue, wait);
3512 if (!wake_page_match(wpq, key))
3515 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3516 list_del_init(&wait->entry);
3517 io_req_task_queue(req);
3522 * This controls whether a given IO request should be armed for async page
3523 * based retry. If we return false here, the request is handed to the async
3524 * worker threads for retry. If we're doing buffered reads on a regular file,
3525 * we prepare a private wait_page_queue entry and retry the operation. This
3526 * will either succeed because the page is now uptodate and unlocked, or it
3527 * will register a callback when the page is unlocked at IO completion. Through
3528 * that callback, io_uring uses task_work to setup a retry of the operation.
3529 * That retry will attempt the buffered read again. The retry will generally
3530 * succeed, or in rare cases where it fails, we then fall back to using the
3531 * async worker threads for a blocking retry.
3533 static bool io_rw_should_retry(struct io_kiocb *req)
3535 struct io_async_rw *rw = req->async_data;
3536 struct wait_page_queue *wait = &rw->wpq;
3537 struct kiocb *kiocb = &req->rw.kiocb;
3539 /* never retry for NOWAIT, we just complete with -EAGAIN */
3540 if (req->flags & REQ_F_NOWAIT)
3543 /* Only for buffered IO */
3544 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3548 * just use poll if we can, and don't attempt if the fs doesn't
3549 * support callback based unlocks
3551 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3554 wait->wait.func = io_async_buf_func;
3555 wait->wait.private = req;
3556 wait->wait.flags = 0;
3557 INIT_LIST_HEAD(&wait->wait.entry);
3558 kiocb->ki_flags |= IOCB_WAITQ;
3559 kiocb->ki_flags &= ~IOCB_NOWAIT;
3560 kiocb->ki_waitq = wait;
3564 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3566 if (req->file->f_op->read_iter)
3567 return call_read_iter(req->file, &req->rw.kiocb, iter);
3568 else if (req->file->f_op->read)
3569 return loop_rw_iter(READ, req, iter);
3574 static bool need_read_all(struct io_kiocb *req)
3576 return req->flags & REQ_F_ISREG ||
3577 S_ISBLK(file_inode(req->file)->i_mode);
3580 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3582 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3583 struct kiocb *kiocb = &req->rw.kiocb;
3584 struct iov_iter __iter, *iter = &__iter;
3585 struct io_async_rw *rw = req->async_data;
3586 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3587 struct iov_iter_state __state, *state;
3593 state = &rw->iter_state;
3595 * We come here from an earlier attempt, restore our state to
3596 * match in case it doesn't. It's cheap enough that we don't
3597 * need to make this conditional.
3599 iov_iter_restore(iter, state);
3602 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3606 iov_iter_save_state(iter, state);
3608 req->result = iov_iter_count(iter);
3610 /* Ensure we clear previously set non-block flag */
3611 if (!force_nonblock)
3612 kiocb->ki_flags &= ~IOCB_NOWAIT;
3614 kiocb->ki_flags |= IOCB_NOWAIT;
3616 /* If the file doesn't support async, just async punt */
3617 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3618 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3619 return ret ?: -EAGAIN;
3622 ppos = io_kiocb_update_pos(req);
3624 ret = rw_verify_area(READ, req->file, ppos, req->result);
3625 if (unlikely(ret)) {
3630 ret = io_iter_do_read(req, iter);
3632 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3633 req->flags &= ~REQ_F_REISSUE;
3634 /* IOPOLL retry should happen for io-wq threads */
3635 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3637 /* no retry on NONBLOCK nor RWF_NOWAIT */
3638 if (req->flags & REQ_F_NOWAIT)
3641 } else if (ret == -EIOCBQUEUED) {
3643 } else if (ret <= 0 || ret == req->result || !force_nonblock ||
3644 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3645 /* read all, failed, already did sync or don't want to retry */
3650 * Don't depend on the iter state matching what was consumed, or being
3651 * untouched in case of error. Restore it and we'll advance it
3652 * manually if we need to.
3654 iov_iter_restore(iter, state);
3656 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3661 rw = req->async_data;
3663 * Now use our persistent iterator and state, if we aren't already.
3664 * We've restored and mapped the iter to match.
3666 if (iter != &rw->iter) {
3668 state = &rw->iter_state;
3673 * We end up here because of a partial read, either from
3674 * above or inside this loop. Advance the iter by the bytes
3675 * that were consumed.
3677 iov_iter_advance(iter, ret);
3678 if (!iov_iter_count(iter))
3680 rw->bytes_done += ret;
3681 iov_iter_save_state(iter, state);
3683 /* if we can retry, do so with the callbacks armed */
3684 if (!io_rw_should_retry(req)) {
3685 kiocb->ki_flags &= ~IOCB_WAITQ;
3689 req->result = iov_iter_count(iter);
3691 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3692 * we get -EIOCBQUEUED, then we'll get a notification when the
3693 * desired page gets unlocked. We can also get a partial read
3694 * here, and if we do, then just retry at the new offset.
3696 ret = io_iter_do_read(req, iter);
3697 if (ret == -EIOCBQUEUED)
3699 /* we got some bytes, but not all. retry. */
3700 kiocb->ki_flags &= ~IOCB_WAITQ;
3701 iov_iter_restore(iter, state);
3704 kiocb_done(kiocb, ret, issue_flags);
3706 /* it's faster to check here then delegate to kfree */
3712 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3714 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3716 return io_prep_rw(req, sqe, WRITE);
3719 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3721 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3722 struct kiocb *kiocb = &req->rw.kiocb;
3723 struct iov_iter __iter, *iter = &__iter;
3724 struct io_async_rw *rw = req->async_data;
3725 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3726 struct iov_iter_state __state, *state;
3732 state = &rw->iter_state;
3733 iov_iter_restore(iter, state);
3736 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3740 iov_iter_save_state(iter, state);
3742 req->result = iov_iter_count(iter);
3744 /* Ensure we clear previously set non-block flag */
3745 if (!force_nonblock)
3746 kiocb->ki_flags &= ~IOCB_NOWAIT;
3748 kiocb->ki_flags |= IOCB_NOWAIT;
3750 /* If the file doesn't support async, just async punt */
3751 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3754 /* file path doesn't support NOWAIT for non-direct_IO */
3755 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3756 (req->flags & REQ_F_ISREG))
3759 ppos = io_kiocb_update_pos(req);
3761 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3766 * Open-code file_start_write here to grab freeze protection,
3767 * which will be released by another thread in
3768 * io_complete_rw(). Fool lockdep by telling it the lock got
3769 * released so that it doesn't complain about the held lock when
3770 * we return to userspace.
3772 if (req->flags & REQ_F_ISREG) {
3773 sb_start_write(file_inode(req->file)->i_sb);
3774 __sb_writers_release(file_inode(req->file)->i_sb,
3777 kiocb->ki_flags |= IOCB_WRITE;
3779 if (req->file->f_op->write_iter)
3780 ret2 = call_write_iter(req->file, kiocb, iter);
3781 else if (req->file->f_op->write)
3782 ret2 = loop_rw_iter(WRITE, req, iter);
3786 if (req->flags & REQ_F_REISSUE) {
3787 req->flags &= ~REQ_F_REISSUE;
3792 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3793 * retry them without IOCB_NOWAIT.
3795 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3797 /* no retry on NONBLOCK nor RWF_NOWAIT */
3798 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3800 if (!force_nonblock || ret2 != -EAGAIN) {
3801 /* IOPOLL retry should happen for io-wq threads */
3802 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3805 kiocb_done(kiocb, ret2, issue_flags);
3808 iov_iter_restore(iter, state);
3809 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3811 if (kiocb->ki_flags & IOCB_WRITE)
3812 kiocb_end_write(req);
3818 /* it's reportedly faster than delegating the null check to kfree() */
3824 static int io_renameat_prep(struct io_kiocb *req,
3825 const struct io_uring_sqe *sqe)
3827 struct io_rename *ren = &req->rename;
3828 const char __user *oldf, *newf;
3830 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3832 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3834 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3837 ren->old_dfd = READ_ONCE(sqe->fd);
3838 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3839 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3840 ren->new_dfd = READ_ONCE(sqe->len);
3841 ren->flags = READ_ONCE(sqe->rename_flags);
3843 ren->oldpath = getname(oldf);
3844 if (IS_ERR(ren->oldpath))
3845 return PTR_ERR(ren->oldpath);
3847 ren->newpath = getname(newf);
3848 if (IS_ERR(ren->newpath)) {
3849 putname(ren->oldpath);
3850 return PTR_ERR(ren->newpath);
3853 req->flags |= REQ_F_NEED_CLEANUP;
3857 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3859 struct io_rename *ren = &req->rename;
3862 if (issue_flags & IO_URING_F_NONBLOCK)
3865 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3866 ren->newpath, ren->flags);
3868 req->flags &= ~REQ_F_NEED_CLEANUP;
3871 io_req_complete(req, ret);
3875 static int io_unlinkat_prep(struct io_kiocb *req,
3876 const struct io_uring_sqe *sqe)
3878 struct io_unlink *un = &req->unlink;
3879 const char __user *fname;
3881 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3883 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3886 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3889 un->dfd = READ_ONCE(sqe->fd);
3891 un->flags = READ_ONCE(sqe->unlink_flags);
3892 if (un->flags & ~AT_REMOVEDIR)
3895 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3896 un->filename = getname(fname);
3897 if (IS_ERR(un->filename))
3898 return PTR_ERR(un->filename);
3900 req->flags |= REQ_F_NEED_CLEANUP;
3904 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3906 struct io_unlink *un = &req->unlink;
3909 if (issue_flags & IO_URING_F_NONBLOCK)
3912 if (un->flags & AT_REMOVEDIR)
3913 ret = do_rmdir(un->dfd, un->filename);
3915 ret = do_unlinkat(un->dfd, un->filename);
3917 req->flags &= ~REQ_F_NEED_CLEANUP;
3920 io_req_complete(req, ret);
3924 static int io_shutdown_prep(struct io_kiocb *req,
3925 const struct io_uring_sqe *sqe)
3927 #if defined(CONFIG_NET)
3928 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3930 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3931 sqe->buf_index || sqe->splice_fd_in))
3934 req->shutdown.how = READ_ONCE(sqe->len);
3941 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3943 #if defined(CONFIG_NET)
3944 struct socket *sock;
3947 if (issue_flags & IO_URING_F_NONBLOCK)
3950 sock = sock_from_file(req->file, &ret);
3951 if (unlikely(!sock))
3954 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3957 io_req_complete(req, ret);
3964 static int __io_splice_prep(struct io_kiocb *req,
3965 const struct io_uring_sqe *sqe)
3967 struct io_splice *sp = &req->splice;
3968 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3970 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3973 sp->len = READ_ONCE(sqe->len);
3974 sp->flags = READ_ONCE(sqe->splice_flags);
3975 if (unlikely(sp->flags & ~valid_flags))
3977 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
3981 static int io_tee_prep(struct io_kiocb *req,
3982 const struct io_uring_sqe *sqe)
3984 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3986 return __io_splice_prep(req, sqe);
3989 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3991 struct io_splice *sp = &req->splice;
3992 struct file *out = sp->file_out;
3993 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3997 if (issue_flags & IO_URING_F_NONBLOCK)
4000 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4001 (sp->flags & SPLICE_F_FD_IN_FIXED), issue_flags);
4008 ret = do_tee(in, out, sp->len, flags);
4010 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4015 io_req_complete(req, ret);
4019 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4021 struct io_splice *sp = &req->splice;
4023 sp->off_in = READ_ONCE(sqe->splice_off_in);
4024 sp->off_out = READ_ONCE(sqe->off);
4025 return __io_splice_prep(req, sqe);
4028 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4030 struct io_splice *sp = &req->splice;
4031 struct file *out = sp->file_out;
4032 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4033 loff_t *poff_in, *poff_out;
4037 if (issue_flags & IO_URING_F_NONBLOCK)
4040 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4041 (sp->flags & SPLICE_F_FD_IN_FIXED), issue_flags);
4047 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4048 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4051 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4053 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4058 io_req_complete(req, ret);
4063 * IORING_OP_NOP just posts a completion event, nothing else.
4065 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4067 struct io_ring_ctx *ctx = req->ctx;
4069 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4072 __io_req_complete(req, issue_flags, 0, 0);
4076 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4078 struct io_ring_ctx *ctx = req->ctx;
4080 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4082 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4086 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4087 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4090 req->sync.off = READ_ONCE(sqe->off);
4091 req->sync.len = READ_ONCE(sqe->len);
4095 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4097 loff_t end = req->sync.off + req->sync.len;
4100 /* fsync always requires a blocking context */
4101 if (issue_flags & IO_URING_F_NONBLOCK)
4104 ret = vfs_fsync_range(req->file, req->sync.off,
4105 end > 0 ? end : LLONG_MAX,
4106 req->sync.flags & IORING_FSYNC_DATASYNC);
4109 io_req_complete(req, ret);
4113 static int io_fallocate_prep(struct io_kiocb *req,
4114 const struct io_uring_sqe *sqe)
4116 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4119 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4122 req->sync.off = READ_ONCE(sqe->off);
4123 req->sync.len = READ_ONCE(sqe->addr);
4124 req->sync.mode = READ_ONCE(sqe->len);
4128 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4132 /* fallocate always requiring blocking context */
4133 if (issue_flags & IO_URING_F_NONBLOCK)
4135 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4140 fsnotify_modify(req->file);
4141 io_req_complete(req, ret);
4145 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4147 const char __user *fname;
4150 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4152 if (unlikely(sqe->ioprio || sqe->buf_index))
4154 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4157 /* open.how should be already initialised */
4158 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4159 req->open.how.flags |= O_LARGEFILE;
4161 req->open.dfd = READ_ONCE(sqe->fd);
4162 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4163 req->open.filename = getname(fname);
4164 if (IS_ERR(req->open.filename)) {
4165 ret = PTR_ERR(req->open.filename);
4166 req->open.filename = NULL;
4170 req->open.file_slot = READ_ONCE(sqe->file_index);
4171 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4174 req->open.nofile = rlimit(RLIMIT_NOFILE);
4175 req->flags |= REQ_F_NEED_CLEANUP;
4179 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4181 u64 mode = READ_ONCE(sqe->len);
4182 u64 flags = READ_ONCE(sqe->open_flags);
4184 req->open.how = build_open_how(flags, mode);
4185 return __io_openat_prep(req, sqe);
4188 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4190 struct open_how __user *how;
4194 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4195 len = READ_ONCE(sqe->len);
4196 if (len < OPEN_HOW_SIZE_VER0)
4199 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4204 return __io_openat_prep(req, sqe);
4207 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4209 struct open_flags op;
4211 bool resolve_nonblock, nonblock_set;
4212 bool fixed = !!req->open.file_slot;
4215 ret = build_open_flags(&req->open.how, &op);
4218 nonblock_set = op.open_flag & O_NONBLOCK;
4219 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4220 if (issue_flags & IO_URING_F_NONBLOCK) {
4222 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4223 * it'll always -EAGAIN. Note that we test for __O_TMPFILE
4224 * because O_TMPFILE includes O_DIRECTORY, which isn't a flag
4225 * we need to force async for.
4227 if (req->open.how.flags & (O_TRUNC | O_CREAT | __O_TMPFILE))
4229 op.lookup_flags |= LOOKUP_CACHED;
4230 op.open_flag |= O_NONBLOCK;
4234 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4239 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4242 * We could hang on to this 'fd' on retrying, but seems like
4243 * marginal gain for something that is now known to be a slower
4244 * path. So just put it, and we'll get a new one when we retry.
4249 ret = PTR_ERR(file);
4250 /* only retry if RESOLVE_CACHED wasn't already set by application */
4251 if (ret == -EAGAIN &&
4252 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4257 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4258 file->f_flags &= ~O_NONBLOCK;
4259 fsnotify_open(file);
4262 fd_install(ret, file);
4264 ret = io_install_fixed_file(req, file, issue_flags,
4265 req->open.file_slot - 1);
4267 putname(req->open.filename);
4268 req->flags &= ~REQ_F_NEED_CLEANUP;
4271 __io_req_complete(req, issue_flags, ret, 0);
4275 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4277 return io_openat2(req, issue_flags);
4280 static int io_remove_buffers_prep(struct io_kiocb *req,
4281 const struct io_uring_sqe *sqe)
4283 struct io_provide_buf *p = &req->pbuf;
4286 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4290 tmp = READ_ONCE(sqe->fd);
4291 if (!tmp || tmp > USHRT_MAX)
4294 memset(p, 0, sizeof(*p));
4296 p->bgid = READ_ONCE(sqe->buf_group);
4300 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4301 int bgid, unsigned nbufs)
4305 /* shouldn't happen */
4309 /* the head kbuf is the list itself */
4310 while (!list_empty(&buf->list)) {
4311 struct io_buffer *nxt;
4313 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4314 list_del(&nxt->list);
4322 xa_erase(&ctx->io_buffers, bgid);
4327 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4329 struct io_provide_buf *p = &req->pbuf;
4330 struct io_ring_ctx *ctx = req->ctx;
4331 struct io_buffer *head;
4333 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4335 io_ring_submit_lock(ctx, !force_nonblock);
4337 lockdep_assert_held(&ctx->uring_lock);
4340 head = xa_load(&ctx->io_buffers, p->bgid);
4342 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4346 /* complete before unlock, IOPOLL may need the lock */
4347 __io_req_complete(req, issue_flags, ret, 0);
4348 io_ring_submit_unlock(ctx, !force_nonblock);
4352 static int io_provide_buffers_prep(struct io_kiocb *req,
4353 const struct io_uring_sqe *sqe)
4355 unsigned long size, tmp_check;
4356 struct io_provide_buf *p = &req->pbuf;
4359 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4362 tmp = READ_ONCE(sqe->fd);
4363 if (!tmp || tmp > USHRT_MAX)
4366 p->addr = READ_ONCE(sqe->addr);
4367 p->len = READ_ONCE(sqe->len);
4369 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4372 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4375 size = (unsigned long)p->len * p->nbufs;
4376 if (!access_ok(u64_to_user_ptr(p->addr), size))
4379 p->bgid = READ_ONCE(sqe->buf_group);
4380 tmp = READ_ONCE(sqe->off);
4381 if (tmp > USHRT_MAX)
4387 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4389 struct io_buffer *buf;
4390 u64 addr = pbuf->addr;
4391 int i, bid = pbuf->bid;
4393 for (i = 0; i < pbuf->nbufs; i++) {
4394 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4399 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4404 INIT_LIST_HEAD(&buf->list);
4407 list_add_tail(&buf->list, &(*head)->list);
4412 return i ? i : -ENOMEM;
4415 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4417 struct io_provide_buf *p = &req->pbuf;
4418 struct io_ring_ctx *ctx = req->ctx;
4419 struct io_buffer *head, *list;
4421 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4423 io_ring_submit_lock(ctx, !force_nonblock);
4425 lockdep_assert_held(&ctx->uring_lock);
4427 list = head = xa_load(&ctx->io_buffers, p->bgid);
4429 ret = io_add_buffers(p, &head);
4430 if (ret >= 0 && !list) {
4431 ret = xa_insert(&ctx->io_buffers, p->bgid, head,
4432 GFP_KERNEL_ACCOUNT);
4434 __io_remove_buffers(ctx, head, p->bgid, -1U);
4438 /* complete before unlock, IOPOLL may need the lock */
4439 __io_req_complete(req, issue_flags, ret, 0);
4440 io_ring_submit_unlock(ctx, !force_nonblock);
4444 static int io_epoll_ctl_prep(struct io_kiocb *req,
4445 const struct io_uring_sqe *sqe)
4447 #if defined(CONFIG_EPOLL)
4448 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4450 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4453 req->epoll.epfd = READ_ONCE(sqe->fd);
4454 req->epoll.op = READ_ONCE(sqe->len);
4455 req->epoll.fd = READ_ONCE(sqe->off);
4457 if (ep_op_has_event(req->epoll.op)) {
4458 struct epoll_event __user *ev;
4460 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4461 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4471 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4473 #if defined(CONFIG_EPOLL)
4474 struct io_epoll *ie = &req->epoll;
4476 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4478 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4479 if (force_nonblock && ret == -EAGAIN)
4484 __io_req_complete(req, issue_flags, ret, 0);
4491 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4493 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4494 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4496 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4499 req->madvise.addr = READ_ONCE(sqe->addr);
4500 req->madvise.len = READ_ONCE(sqe->len);
4501 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4508 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4510 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4511 struct io_madvise *ma = &req->madvise;
4514 if (issue_flags & IO_URING_F_NONBLOCK)
4517 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4520 io_req_complete(req, ret);
4527 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4529 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4531 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4534 req->fadvise.offset = READ_ONCE(sqe->off);
4535 req->fadvise.len = READ_ONCE(sqe->len);
4536 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4540 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4542 struct io_fadvise *fa = &req->fadvise;
4545 if (issue_flags & IO_URING_F_NONBLOCK) {
4546 switch (fa->advice) {
4547 case POSIX_FADV_NORMAL:
4548 case POSIX_FADV_RANDOM:
4549 case POSIX_FADV_SEQUENTIAL:
4556 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4559 __io_req_complete(req, issue_flags, ret, 0);
4563 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4565 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4567 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4569 if (req->flags & REQ_F_FIXED_FILE)
4572 req->statx.dfd = READ_ONCE(sqe->fd);
4573 req->statx.mask = READ_ONCE(sqe->len);
4574 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4575 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4576 req->statx.flags = READ_ONCE(sqe->statx_flags);
4581 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4583 struct io_statx *ctx = &req->statx;
4586 if (issue_flags & IO_URING_F_NONBLOCK)
4589 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4594 io_req_complete(req, ret);
4598 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4600 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4602 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4603 sqe->rw_flags || sqe->buf_index)
4605 if (req->flags & REQ_F_FIXED_FILE)
4608 req->close.fd = READ_ONCE(sqe->fd);
4609 req->close.file_slot = READ_ONCE(sqe->file_index);
4610 if (req->close.file_slot && req->close.fd)
4616 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4618 struct files_struct *files = current->files;
4619 struct io_close *close = &req->close;
4620 struct fdtable *fdt;
4621 struct file *file = NULL;
4624 if (req->close.file_slot) {
4625 ret = io_close_fixed(req, issue_flags);
4629 spin_lock(&files->file_lock);
4630 fdt = files_fdtable(files);
4631 if (close->fd >= fdt->max_fds) {
4632 spin_unlock(&files->file_lock);
4635 file = fdt->fd[close->fd];
4636 if (!file || file->f_op == &io_uring_fops) {
4637 spin_unlock(&files->file_lock);
4642 /* if the file has a flush method, be safe and punt to async */
4643 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4644 spin_unlock(&files->file_lock);
4648 ret = __close_fd_get_file(close->fd, &file);
4649 spin_unlock(&files->file_lock);
4656 /* No ->flush() or already async, safely close from here */
4657 ret = filp_close(file, current->files);
4663 __io_req_complete(req, issue_flags, ret, 0);
4667 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4669 struct io_ring_ctx *ctx = req->ctx;
4671 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4673 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4677 req->sync.off = READ_ONCE(sqe->off);
4678 req->sync.len = READ_ONCE(sqe->len);
4679 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4683 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4687 /* sync_file_range always requires a blocking context */
4688 if (issue_flags & IO_URING_F_NONBLOCK)
4691 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4695 io_req_complete(req, ret);
4699 #if defined(CONFIG_NET)
4700 static bool io_net_retry(struct socket *sock, int flags)
4702 if (!(flags & MSG_WAITALL))
4704 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
4707 static int io_setup_async_msg(struct io_kiocb *req,
4708 struct io_async_msghdr *kmsg)
4710 struct io_async_msghdr *async_msg = req->async_data;
4714 if (io_alloc_async_data(req)) {
4715 kfree(kmsg->free_iov);
4718 async_msg = req->async_data;
4719 req->flags |= REQ_F_NEED_CLEANUP;
4720 memcpy(async_msg, kmsg, sizeof(*kmsg));
4721 if (async_msg->msg.msg_name)
4722 async_msg->msg.msg_name = &async_msg->addr;
4723 /* if were using fast_iov, set it to the new one */
4724 if (!kmsg->free_iov) {
4725 size_t fast_idx = kmsg->msg.msg_iter.iov - kmsg->fast_iov;
4726 async_msg->msg.msg_iter.iov = &async_msg->fast_iov[fast_idx];
4732 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4733 struct io_async_msghdr *iomsg)
4735 struct io_sr_msg *sr = &req->sr_msg;
4738 iomsg->msg.msg_name = &iomsg->addr;
4739 iomsg->free_iov = iomsg->fast_iov;
4740 ret = sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4741 req->sr_msg.msg_flags, &iomsg->free_iov);
4742 /* save msg_control as sys_sendmsg() overwrites it */
4743 sr->msg_control = iomsg->msg.msg_control;
4747 static int io_sendmsg_prep_async(struct io_kiocb *req)
4751 ret = io_sendmsg_copy_hdr(req, req->async_data);
4753 req->flags |= REQ_F_NEED_CLEANUP;
4757 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4759 struct io_sr_msg *sr = &req->sr_msg;
4761 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4763 if (unlikely(sqe->addr2 || sqe->file_index))
4765 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
4768 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4769 sr->len = READ_ONCE(sqe->len);
4770 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4771 if (sr->msg_flags & MSG_DONTWAIT)
4772 req->flags |= REQ_F_NOWAIT;
4774 #ifdef CONFIG_COMPAT
4775 if (req->ctx->compat)
4776 sr->msg_flags |= MSG_CMSG_COMPAT;
4782 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4784 struct io_async_msghdr iomsg, *kmsg;
4785 struct io_sr_msg *sr = &req->sr_msg;
4786 struct socket *sock;
4791 sock = sock_from_file(req->file, &ret);
4792 if (unlikely(!sock))
4795 kmsg = req->async_data;
4797 ret = io_sendmsg_copy_hdr(req, &iomsg);
4802 kmsg->msg.msg_control = sr->msg_control;
4805 flags = req->sr_msg.msg_flags;
4806 if (issue_flags & IO_URING_F_NONBLOCK)
4807 flags |= MSG_DONTWAIT;
4808 if (flags & MSG_WAITALL)
4809 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4811 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4813 if (ret < min_ret) {
4814 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4815 return io_setup_async_msg(req, kmsg);
4816 if (ret == -ERESTARTSYS)
4818 if (ret > 0 && io_net_retry(sock, flags)) {
4820 req->flags |= REQ_F_PARTIAL_IO;
4821 return io_setup_async_msg(req, kmsg);
4825 /* fast path, check for non-NULL to avoid function call */
4827 kfree(kmsg->free_iov);
4828 req->flags &= ~REQ_F_NEED_CLEANUP;
4831 else if (sr->done_io)
4833 __io_req_complete(req, issue_flags, ret, 0);
4837 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4839 struct io_sr_msg *sr = &req->sr_msg;
4842 struct socket *sock;
4847 sock = sock_from_file(req->file, &ret);
4848 if (unlikely(!sock))
4851 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4855 msg.msg_name = NULL;
4856 msg.msg_control = NULL;
4857 msg.msg_controllen = 0;
4858 msg.msg_namelen = 0;
4860 flags = req->sr_msg.msg_flags;
4861 if (issue_flags & IO_URING_F_NONBLOCK)
4862 flags |= MSG_DONTWAIT;
4863 if (flags & MSG_WAITALL)
4864 min_ret = iov_iter_count(&msg.msg_iter);
4866 msg.msg_flags = flags;
4867 ret = sock_sendmsg(sock, &msg);
4868 if (ret < min_ret) {
4869 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4871 if (ret == -ERESTARTSYS)
4873 if (ret > 0 && io_net_retry(sock, flags)) {
4877 req->flags |= REQ_F_PARTIAL_IO;
4884 else if (sr->done_io)
4886 __io_req_complete(req, issue_flags, ret, 0);
4890 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4891 struct io_async_msghdr *iomsg)
4893 struct io_sr_msg *sr = &req->sr_msg;
4894 struct iovec __user *uiov;
4898 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4899 &iomsg->uaddr, &uiov, &iov_len);
4903 if (req->flags & REQ_F_BUFFER_SELECT) {
4906 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4908 sr->len = iomsg->fast_iov[0].iov_len;
4909 iomsg->free_iov = NULL;
4911 iomsg->free_iov = iomsg->fast_iov;
4912 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4913 &iomsg->free_iov, &iomsg->msg.msg_iter,
4922 #ifdef CONFIG_COMPAT
4923 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4924 struct io_async_msghdr *iomsg)
4926 struct io_sr_msg *sr = &req->sr_msg;
4927 struct compat_iovec __user *uiov;
4932 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4937 uiov = compat_ptr(ptr);
4938 if (req->flags & REQ_F_BUFFER_SELECT) {
4939 compat_ssize_t clen;
4943 if (!access_ok(uiov, sizeof(*uiov)))
4945 if (__get_user(clen, &uiov->iov_len))
4950 iomsg->free_iov = NULL;
4952 iomsg->free_iov = iomsg->fast_iov;
4953 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4954 UIO_FASTIOV, &iomsg->free_iov,
4955 &iomsg->msg.msg_iter, true);
4964 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4965 struct io_async_msghdr *iomsg)
4967 iomsg->msg.msg_name = &iomsg->addr;
4969 #ifdef CONFIG_COMPAT
4970 if (req->ctx->compat)
4971 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4974 return __io_recvmsg_copy_hdr(req, iomsg);
4977 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4980 struct io_sr_msg *sr = &req->sr_msg;
4981 struct io_buffer *kbuf;
4983 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4988 req->flags |= REQ_F_BUFFER_SELECTED;
4992 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4994 return io_put_kbuf(req, req->sr_msg.kbuf);
4997 static int io_recvmsg_prep_async(struct io_kiocb *req)
5001 ret = io_recvmsg_copy_hdr(req, req->async_data);
5003 req->flags |= REQ_F_NEED_CLEANUP;
5007 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5009 struct io_sr_msg *sr = &req->sr_msg;
5011 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5013 if (unlikely(sqe->addr2 || sqe->file_index))
5015 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
5018 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5019 sr->len = READ_ONCE(sqe->len);
5020 sr->bgid = READ_ONCE(sqe->buf_group);
5021 sr->msg_flags = READ_ONCE(sqe->msg_flags);
5022 if (sr->msg_flags & MSG_DONTWAIT)
5023 req->flags |= REQ_F_NOWAIT;
5025 #ifdef CONFIG_COMPAT
5026 if (req->ctx->compat)
5027 sr->msg_flags |= MSG_CMSG_COMPAT;
5033 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5035 struct io_async_msghdr iomsg, *kmsg;
5036 struct io_sr_msg *sr = &req->sr_msg;
5037 struct socket *sock;
5038 struct io_buffer *kbuf;
5041 int ret, cflags = 0;
5042 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5044 sock = sock_from_file(req->file, &ret);
5045 if (unlikely(!sock))
5048 kmsg = req->async_data;
5050 ret = io_recvmsg_copy_hdr(req, &iomsg);
5056 if (req->flags & REQ_F_BUFFER_SELECT) {
5057 kbuf = io_recv_buffer_select(req, !force_nonblock);
5059 return PTR_ERR(kbuf);
5060 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5061 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5062 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5063 1, req->sr_msg.len);
5066 flags = req->sr_msg.msg_flags;
5068 flags |= MSG_DONTWAIT;
5069 if (flags & MSG_WAITALL && !kmsg->msg.msg_controllen)
5070 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5072 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5073 kmsg->uaddr, flags);
5074 if (ret < min_ret) {
5075 if (ret == -EAGAIN && force_nonblock)
5076 return io_setup_async_msg(req, kmsg);
5077 if (ret == -ERESTARTSYS)
5079 if (ret > 0 && io_net_retry(sock, flags)) {
5080 kmsg->msg.msg_controllen = 0;
5081 kmsg->msg.msg_control = NULL;
5083 req->flags |= REQ_F_PARTIAL_IO;
5084 return io_setup_async_msg(req, kmsg);
5087 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5091 if (req->flags & REQ_F_BUFFER_SELECTED)
5092 cflags = io_put_recv_kbuf(req);
5093 /* fast path, check for non-NULL to avoid function call */
5095 kfree(kmsg->free_iov);
5096 req->flags &= ~REQ_F_NEED_CLEANUP;
5099 else if (sr->done_io)
5101 __io_req_complete(req, issue_flags, ret, cflags);
5105 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5107 struct io_buffer *kbuf;
5108 struct io_sr_msg *sr = &req->sr_msg;
5110 void __user *buf = sr->buf;
5111 struct socket *sock;
5115 int ret, cflags = 0;
5116 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5118 sock = sock_from_file(req->file, &ret);
5119 if (unlikely(!sock))
5122 if (req->flags & REQ_F_BUFFER_SELECT) {
5123 kbuf = io_recv_buffer_select(req, !force_nonblock);
5125 return PTR_ERR(kbuf);
5126 buf = u64_to_user_ptr(kbuf->addr);
5129 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5133 msg.msg_name = NULL;
5134 msg.msg_control = NULL;
5135 msg.msg_controllen = 0;
5136 msg.msg_namelen = 0;
5137 msg.msg_iocb = NULL;
5140 flags = req->sr_msg.msg_flags;
5142 flags |= MSG_DONTWAIT;
5143 if (flags & MSG_WAITALL)
5144 min_ret = iov_iter_count(&msg.msg_iter);
5146 ret = sock_recvmsg(sock, &msg, flags);
5147 if (ret < min_ret) {
5148 if (ret == -EAGAIN && force_nonblock)
5150 if (ret == -ERESTARTSYS)
5152 if (ret > 0 && io_net_retry(sock, flags)) {
5156 req->flags |= REQ_F_PARTIAL_IO;
5160 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5164 if (req->flags & REQ_F_BUFFER_SELECTED)
5165 cflags = io_put_recv_kbuf(req);
5168 else if (sr->done_io)
5170 __io_req_complete(req, issue_flags, ret, cflags);
5174 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5176 struct io_accept *accept = &req->accept;
5178 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5180 if (sqe->ioprio || sqe->len || sqe->buf_index)
5183 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5184 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5185 accept->flags = READ_ONCE(sqe->accept_flags);
5186 accept->nofile = rlimit(RLIMIT_NOFILE);
5188 accept->file_slot = READ_ONCE(sqe->file_index);
5189 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5191 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5193 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5194 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5198 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5200 struct io_accept *accept = &req->accept;
5201 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5202 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5203 bool fixed = !!accept->file_slot;
5208 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5209 if (unlikely(fd < 0))
5212 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5218 ret = PTR_ERR(file);
5220 req->flags |= REQ_F_PARTIAL_IO;
5221 if (ret == -EAGAIN && force_nonblock)
5223 if (ret == -ERESTARTSYS)
5226 } else if (!fixed) {
5227 fd_install(fd, file);
5230 ret = io_install_fixed_file(req, file, issue_flags,
5231 accept->file_slot - 1);
5233 __io_req_complete(req, issue_flags, ret, 0);
5237 static int io_connect_prep_async(struct io_kiocb *req)
5239 struct io_async_connect *io = req->async_data;
5240 struct io_connect *conn = &req->connect;
5242 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5245 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5247 struct io_connect *conn = &req->connect;
5249 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5251 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5255 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5256 conn->addr_len = READ_ONCE(sqe->addr2);
5260 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5262 struct io_async_connect __io, *io;
5263 unsigned file_flags;
5265 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5267 if (req->async_data) {
5268 io = req->async_data;
5270 ret = move_addr_to_kernel(req->connect.addr,
5271 req->connect.addr_len,
5278 file_flags = force_nonblock ? O_NONBLOCK : 0;
5280 ret = __sys_connect_file(req->file, &io->address,
5281 req->connect.addr_len, file_flags);
5282 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5283 if (req->async_data)
5285 if (io_alloc_async_data(req)) {
5289 memcpy(req->async_data, &__io, sizeof(__io));
5292 if (ret == -ERESTARTSYS)
5297 __io_req_complete(req, issue_flags, ret, 0);
5300 #else /* !CONFIG_NET */
5301 #define IO_NETOP_FN(op) \
5302 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5304 return -EOPNOTSUPP; \
5307 #define IO_NETOP_PREP(op) \
5309 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5311 return -EOPNOTSUPP; \
5314 #define IO_NETOP_PREP_ASYNC(op) \
5316 static int io_##op##_prep_async(struct io_kiocb *req) \
5318 return -EOPNOTSUPP; \
5321 IO_NETOP_PREP_ASYNC(sendmsg);
5322 IO_NETOP_PREP_ASYNC(recvmsg);
5323 IO_NETOP_PREP_ASYNC(connect);
5324 IO_NETOP_PREP(accept);
5327 #endif /* CONFIG_NET */
5329 struct io_poll_table {
5330 struct poll_table_struct pt;
5331 struct io_kiocb *req;
5336 #define IO_POLL_CANCEL_FLAG BIT(31)
5337 #define IO_POLL_RETRY_FLAG BIT(30)
5338 #define IO_POLL_REF_MASK GENMASK(29, 0)
5341 * We usually have 1-2 refs taken, 128 is more than enough and we want to
5342 * maximise the margin between this amount and the moment when it overflows.
5344 #define IO_POLL_REF_BIAS 128
5346 static bool io_poll_get_ownership_slowpath(struct io_kiocb *req)
5351 * poll_refs are already elevated and we don't have much hope for
5352 * grabbing the ownership. Instead of incrementing set a retry flag
5353 * to notify the loop that there might have been some change.
5355 v = atomic_fetch_or(IO_POLL_RETRY_FLAG, &req->poll_refs);
5356 if (v & IO_POLL_REF_MASK)
5358 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5362 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5363 * bump it and acquire ownership. It's disallowed to modify requests while not
5364 * owning it, that prevents from races for enqueueing task_work's and b/w
5365 * arming poll and wakeups.
5367 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5369 if (unlikely(atomic_read(&req->poll_refs) >= IO_POLL_REF_BIAS))
5370 return io_poll_get_ownership_slowpath(req);
5371 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5374 static void io_poll_mark_cancelled(struct io_kiocb *req)
5376 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5379 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5381 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5382 if (req->opcode == IORING_OP_POLL_ADD)
5383 return req->async_data;
5384 return req->apoll->double_poll;
5387 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5389 if (req->opcode == IORING_OP_POLL_ADD)
5391 return &req->apoll->poll;
5394 static void io_poll_req_insert(struct io_kiocb *req)
5396 struct io_ring_ctx *ctx = req->ctx;
5397 struct hlist_head *list;
5399 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5400 hlist_add_head(&req->hash_node, list);
5403 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5404 wait_queue_func_t wake_func)
5407 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5408 /* mask in events that we always want/need */
5409 poll->events = events | IO_POLL_UNMASK;
5410 INIT_LIST_HEAD(&poll->wait.entry);
5411 init_waitqueue_func_entry(&poll->wait, wake_func);
5414 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5416 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5419 spin_lock_irq(&head->lock);
5420 list_del_init(&poll->wait.entry);
5422 spin_unlock_irq(&head->lock);
5426 static void io_poll_remove_entries(struct io_kiocb *req)
5428 struct io_poll_iocb *poll = io_poll_get_single(req);
5429 struct io_poll_iocb *poll_double = io_poll_get_double(req);
5432 * While we hold the waitqueue lock and the waitqueue is nonempty,
5433 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5434 * lock in the first place can race with the waitqueue being freed.
5436 * We solve this as eventpoll does: by taking advantage of the fact that
5437 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5438 * we enter rcu_read_lock() and see that the pointer to the queue is
5439 * non-NULL, we can then lock it without the memory being freed out from
5442 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5443 * case the caller deletes the entry from the queue, leaving it empty.
5444 * In that case, only RCU prevents the queue memory from being freed.
5447 io_poll_remove_entry(poll);
5449 io_poll_remove_entry(poll_double);
5454 * All poll tw should go through this. Checks for poll events, manages
5455 * references, does rewait, etc.
5457 * Returns a negative error on failure. >0 when no action require, which is
5458 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5459 * the request, then the mask is stored in req->result.
5461 static int io_poll_check_events(struct io_kiocb *req)
5463 struct io_ring_ctx *ctx = req->ctx;
5464 struct io_poll_iocb *poll = io_poll_get_single(req);
5467 /* req->task == current here, checking PF_EXITING is safe */
5468 if (unlikely(req->task->flags & PF_EXITING))
5469 io_poll_mark_cancelled(req);
5472 v = atomic_read(&req->poll_refs);
5474 /* tw handler should be the owner, and so have some references */
5475 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5477 if (v & IO_POLL_CANCEL_FLAG)
5480 * cqe.res contains only events of the first wake up
5481 * and all others are be lost. Redo vfs_poll() to get
5484 if ((v & IO_POLL_REF_MASK) != 1)
5486 if (v & IO_POLL_RETRY_FLAG) {
5489 * We won't find new events that came in between
5490 * vfs_poll and the ref put unless we clear the
5493 atomic_andnot(IO_POLL_RETRY_FLAG, &req->poll_refs);
5494 v &= ~IO_POLL_RETRY_FLAG;
5498 struct poll_table_struct pt = { ._key = poll->events };
5500 req->result = vfs_poll(req->file, &pt) & poll->events;
5503 /* multishot, just fill an CQE and proceed */
5504 if (req->result && !(poll->events & EPOLLONESHOT)) {
5505 __poll_t mask = mangle_poll(req->result & poll->events);
5508 spin_lock(&ctx->completion_lock);
5509 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5511 io_commit_cqring(ctx);
5512 spin_unlock(&ctx->completion_lock);
5513 if (unlikely(!filled))
5515 io_cqring_ev_posted(ctx);
5516 } else if (req->result) {
5520 /* force the next iteration to vfs_poll() */
5524 * Release all references, retry if someone tried to restart
5525 * task_work while we were executing it.
5527 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs) &
5533 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5535 struct io_ring_ctx *ctx = req->ctx;
5538 ret = io_poll_check_events(req);
5543 req->result = mangle_poll(req->result & req->poll.events);
5549 io_poll_remove_entries(req);
5550 spin_lock(&ctx->completion_lock);
5551 hash_del(&req->hash_node);
5552 spin_unlock(&ctx->completion_lock);
5553 io_req_complete_post(req, req->result, 0);
5556 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5558 struct io_ring_ctx *ctx = req->ctx;
5561 ret = io_poll_check_events(req);
5565 io_tw_lock(req->ctx, locked);
5566 io_poll_remove_entries(req);
5567 spin_lock(&ctx->completion_lock);
5568 hash_del(&req->hash_node);
5569 spin_unlock(&ctx->completion_lock);
5572 io_req_task_submit(req, locked);
5574 io_req_complete_failed(req, ret);
5577 static void __io_poll_execute(struct io_kiocb *req, int mask)
5580 if (req->opcode == IORING_OP_POLL_ADD)
5581 req->io_task_work.func = io_poll_task_func;
5583 req->io_task_work.func = io_apoll_task_func;
5585 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5586 io_req_task_work_add(req);
5589 static inline void io_poll_execute(struct io_kiocb *req, int res)
5591 if (io_poll_get_ownership(req))
5592 __io_poll_execute(req, res);
5595 static void io_poll_cancel_req(struct io_kiocb *req)
5597 io_poll_mark_cancelled(req);
5598 /* kick tw, which should complete the request */
5599 io_poll_execute(req, 0);
5602 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5605 struct io_kiocb *req = wait->private;
5606 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5608 __poll_t mask = key_to_poll(key);
5610 if (unlikely(mask & POLLFREE)) {
5611 io_poll_mark_cancelled(req);
5612 /* we have to kick tw in case it's not already */
5613 io_poll_execute(req, 0);
5616 * If the waitqueue is being freed early but someone is already
5617 * holds ownership over it, we have to tear down the request as
5618 * best we can. That means immediately removing the request from
5619 * its waitqueue and preventing all further accesses to the
5620 * waitqueue via the request.
5622 list_del_init(&poll->wait.entry);
5625 * Careful: this *must* be the last step, since as soon
5626 * as req->head is NULL'ed out, the request can be
5627 * completed and freed, since aio_poll_complete_work()
5628 * will no longer need to take the waitqueue lock.
5630 smp_store_release(&poll->head, NULL);
5634 /* for instances that support it check for an event match first */
5635 if (mask && !(mask & poll->events))
5638 if (io_poll_get_ownership(req)) {
5640 * If we trigger a multishot poll off our own wakeup path,
5641 * disable multishot as there is a circular dependency between
5642 * CQ posting and triggering the event.
5644 if (mask & EPOLL_URING_WAKE)
5645 poll->events |= EPOLLONESHOT;
5647 __io_poll_execute(req, mask);
5652 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5653 struct wait_queue_head *head,
5654 struct io_poll_iocb **poll_ptr)
5656 struct io_kiocb *req = pt->req;
5659 * The file being polled uses multiple waitqueues for poll handling
5660 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5663 if (unlikely(pt->nr_entries)) {
5664 struct io_poll_iocb *first = poll;
5666 /* double add on the same waitqueue head, ignore */
5667 if (first->head == head)
5669 /* already have a 2nd entry, fail a third attempt */
5671 if ((*poll_ptr)->head == head)
5673 pt->error = -EINVAL;
5677 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5679 pt->error = -ENOMEM;
5682 io_init_poll_iocb(poll, first->events, first->wait.func);
5688 poll->wait.private = req;
5690 if (poll->events & EPOLLEXCLUSIVE)
5691 add_wait_queue_exclusive(head, &poll->wait);
5693 add_wait_queue(head, &poll->wait);
5696 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5697 struct poll_table_struct *p)
5699 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5701 __io_queue_proc(&pt->req->poll, pt, head,
5702 (struct io_poll_iocb **) &pt->req->async_data);
5705 static int __io_arm_poll_handler(struct io_kiocb *req,
5706 struct io_poll_iocb *poll,
5707 struct io_poll_table *ipt, __poll_t mask)
5709 struct io_ring_ctx *ctx = req->ctx;
5711 INIT_HLIST_NODE(&req->hash_node);
5712 io_init_poll_iocb(poll, mask, io_poll_wake);
5713 poll->file = req->file;
5714 poll->wait.private = req;
5716 ipt->pt._key = mask;
5719 ipt->nr_entries = 0;
5722 * Take the ownership to delay any tw execution up until we're done
5723 * with poll arming. see io_poll_get_ownership().
5725 atomic_set(&req->poll_refs, 1);
5726 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5728 if (mask && (poll->events & EPOLLONESHOT)) {
5729 io_poll_remove_entries(req);
5730 /* no one else has access to the req, forget about the ref */
5733 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5734 io_poll_remove_entries(req);
5736 ipt->error = -EINVAL;
5740 spin_lock(&ctx->completion_lock);
5741 io_poll_req_insert(req);
5742 spin_unlock(&ctx->completion_lock);
5745 /* can't multishot if failed, just queue the event we've got */
5746 if (unlikely(ipt->error || !ipt->nr_entries)) {
5747 poll->events |= EPOLLONESHOT;
5750 __io_poll_execute(req, mask);
5755 * Try to release ownership. If we see a change of state, e.g.
5756 * poll was waken up, queue up a tw, it'll deal with it.
5758 if (atomic_cmpxchg(&req->poll_refs, 1, 0) != 1)
5759 __io_poll_execute(req, 0);
5763 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5764 struct poll_table_struct *p)
5766 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5767 struct async_poll *apoll = pt->req->apoll;
5769 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5779 * We can't reliably detect loops in repeated poll triggers and issue
5780 * subsequently failing. But rather than fail these immediately, allow a
5781 * certain amount of retries before we give up. Given that this condition
5782 * should _rarely_ trigger even once, we should be fine with a larger value.
5784 #define APOLL_MAX_RETRY 128
5786 static int io_arm_poll_handler(struct io_kiocb *req)
5788 const struct io_op_def *def = &io_op_defs[req->opcode];
5789 struct io_ring_ctx *ctx = req->ctx;
5790 struct async_poll *apoll;
5791 struct io_poll_table ipt;
5792 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
5795 if (!req->file || !file_can_poll(req->file))
5796 return IO_APOLL_ABORTED;
5797 if (!def->pollin && !def->pollout)
5798 return IO_APOLL_ABORTED;
5801 mask |= POLLIN | POLLRDNORM;
5803 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5804 if ((req->opcode == IORING_OP_RECVMSG) &&
5805 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5808 mask |= POLLOUT | POLLWRNORM;
5811 if (req->flags & REQ_F_POLLED) {
5813 kfree(apoll->double_poll);
5814 if (unlikely(!--apoll->poll.retries)) {
5815 apoll->double_poll = NULL;
5816 return IO_APOLL_ABORTED;
5819 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5820 if (unlikely(!apoll))
5821 return IO_APOLL_ABORTED;
5822 apoll->poll.retries = APOLL_MAX_RETRY;
5824 apoll->double_poll = NULL;
5826 req->flags |= REQ_F_POLLED;
5827 ipt.pt._qproc = io_async_queue_proc;
5829 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5830 if (ret || ipt.error)
5831 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5833 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5834 mask, apoll->poll.events);
5839 * Returns true if we found and killed one or more poll requests
5841 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5844 struct hlist_node *tmp;
5845 struct io_kiocb *req;
5849 spin_lock(&ctx->completion_lock);
5850 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5851 struct hlist_head *list;
5853 list = &ctx->cancel_hash[i];
5854 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5855 if (io_match_task_safe(req, tsk, cancel_all)) {
5856 hlist_del_init(&req->hash_node);
5857 io_poll_cancel_req(req);
5862 spin_unlock(&ctx->completion_lock);
5866 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5868 __must_hold(&ctx->completion_lock)
5870 struct hlist_head *list;
5871 struct io_kiocb *req;
5873 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5874 hlist_for_each_entry(req, list, hash_node) {
5875 if (sqe_addr != req->user_data)
5877 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5884 static bool io_poll_disarm(struct io_kiocb *req)
5885 __must_hold(&ctx->completion_lock)
5887 if (!io_poll_get_ownership(req))
5889 io_poll_remove_entries(req);
5890 hash_del(&req->hash_node);
5894 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5896 __must_hold(&ctx->completion_lock)
5898 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
5902 io_poll_cancel_req(req);
5906 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5911 events = READ_ONCE(sqe->poll32_events);
5913 events = swahw32(events);
5915 if (!(flags & IORING_POLL_ADD_MULTI))
5916 events |= EPOLLONESHOT;
5917 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5920 static int io_poll_update_prep(struct io_kiocb *req,
5921 const struct io_uring_sqe *sqe)
5923 struct io_poll_update *upd = &req->poll_update;
5926 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5928 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5930 flags = READ_ONCE(sqe->len);
5931 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5932 IORING_POLL_ADD_MULTI))
5934 /* meaningless without update */
5935 if (flags == IORING_POLL_ADD_MULTI)
5938 upd->old_user_data = READ_ONCE(sqe->addr);
5939 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5940 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5942 upd->new_user_data = READ_ONCE(sqe->off);
5943 if (!upd->update_user_data && upd->new_user_data)
5945 if (upd->update_events)
5946 upd->events = io_poll_parse_events(sqe, flags);
5947 else if (sqe->poll32_events)
5953 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5955 struct io_poll_iocb *poll = &req->poll;
5958 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5960 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5962 flags = READ_ONCE(sqe->len);
5963 if (flags & ~IORING_POLL_ADD_MULTI)
5966 io_req_set_refcount(req);
5967 poll->events = io_poll_parse_events(sqe, flags);
5971 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5973 struct io_poll_iocb *poll = &req->poll;
5974 struct io_poll_table ipt;
5977 ipt.pt._qproc = io_poll_queue_proc;
5979 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
5980 if (!ret && ipt.error)
5982 ret = ret ?: ipt.error;
5984 __io_req_complete(req, issue_flags, ret, 0);
5988 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5990 struct io_ring_ctx *ctx = req->ctx;
5991 struct io_kiocb *preq;
5994 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5996 spin_lock(&ctx->completion_lock);
5997 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5998 if (!preq || !io_poll_disarm(preq)) {
5999 spin_unlock(&ctx->completion_lock);
6000 ret = preq ? -EALREADY : -ENOENT;
6003 spin_unlock(&ctx->completion_lock);
6005 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6006 /* only mask one event flags, keep behavior flags */
6007 if (req->poll_update.update_events) {
6008 preq->poll.events &= ~0xffff;
6009 preq->poll.events |= req->poll_update.events & 0xffff;
6010 preq->poll.events |= IO_POLL_UNMASK;
6012 if (req->poll_update.update_user_data)
6013 preq->user_data = req->poll_update.new_user_data;
6015 ret2 = io_poll_add(preq, issue_flags);
6016 /* successfully updated, don't complete poll request */
6021 io_req_complete(preq, -ECANCELED);
6025 /* complete update request, we're done with it */
6026 io_req_complete(req, ret);
6027 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6031 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
6034 io_req_complete_post(req, -ETIME, 0);
6037 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6039 struct io_timeout_data *data = container_of(timer,
6040 struct io_timeout_data, timer);
6041 struct io_kiocb *req = data->req;
6042 struct io_ring_ctx *ctx = req->ctx;
6043 unsigned long flags;
6045 spin_lock_irqsave(&ctx->timeout_lock, flags);
6046 list_del_init(&req->timeout.list);
6047 atomic_set(&req->ctx->cq_timeouts,
6048 atomic_read(&req->ctx->cq_timeouts) + 1);
6049 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6051 req->io_task_work.func = io_req_task_timeout;
6052 io_req_task_work_add(req);
6053 return HRTIMER_NORESTART;
6056 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6058 __must_hold(&ctx->timeout_lock)
6060 struct io_timeout_data *io;
6061 struct io_kiocb *req;
6064 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6065 found = user_data == req->user_data;
6070 return ERR_PTR(-ENOENT);
6072 io = req->async_data;
6073 if (hrtimer_try_to_cancel(&io->timer) == -1)
6074 return ERR_PTR(-EALREADY);
6075 list_del_init(&req->timeout.list);
6079 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6080 __must_hold(&ctx->completion_lock)
6081 __must_hold(&ctx->timeout_lock)
6083 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6086 return PTR_ERR(req);
6089 io_fill_cqe_req(req, -ECANCELED, 0);
6090 io_put_req_deferred(req);
6094 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6096 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6097 case IORING_TIMEOUT_BOOTTIME:
6098 return CLOCK_BOOTTIME;
6099 case IORING_TIMEOUT_REALTIME:
6100 return CLOCK_REALTIME;
6102 /* can't happen, vetted at prep time */
6106 return CLOCK_MONOTONIC;
6110 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6111 struct timespec64 *ts, enum hrtimer_mode mode)
6112 __must_hold(&ctx->timeout_lock)
6114 struct io_timeout_data *io;
6115 struct io_kiocb *req;
6118 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6119 found = user_data == req->user_data;
6126 io = req->async_data;
6127 if (hrtimer_try_to_cancel(&io->timer) == -1)
6129 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6130 io->timer.function = io_link_timeout_fn;
6131 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6135 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6136 struct timespec64 *ts, enum hrtimer_mode mode)
6137 __must_hold(&ctx->timeout_lock)
6139 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6140 struct io_timeout_data *data;
6143 return PTR_ERR(req);
6145 req->timeout.off = 0; /* noseq */
6146 data = req->async_data;
6147 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6148 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6149 data->timer.function = io_timeout_fn;
6150 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6154 static int io_timeout_remove_prep(struct io_kiocb *req,
6155 const struct io_uring_sqe *sqe)
6157 struct io_timeout_rem *tr = &req->timeout_rem;
6159 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6161 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6163 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6166 tr->ltimeout = false;
6167 tr->addr = READ_ONCE(sqe->addr);
6168 tr->flags = READ_ONCE(sqe->timeout_flags);
6169 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6170 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6172 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6173 tr->ltimeout = true;
6174 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6176 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6178 } else if (tr->flags) {
6179 /* timeout removal doesn't support flags */
6186 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6188 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6193 * Remove or update an existing timeout command
6195 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6197 struct io_timeout_rem *tr = &req->timeout_rem;
6198 struct io_ring_ctx *ctx = req->ctx;
6201 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6202 spin_lock(&ctx->completion_lock);
6203 spin_lock_irq(&ctx->timeout_lock);
6204 ret = io_timeout_cancel(ctx, tr->addr);
6205 spin_unlock_irq(&ctx->timeout_lock);
6206 spin_unlock(&ctx->completion_lock);
6208 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6210 spin_lock_irq(&ctx->timeout_lock);
6212 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6214 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6215 spin_unlock_irq(&ctx->timeout_lock);
6220 io_req_complete_post(req, ret, 0);
6224 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6225 bool is_timeout_link)
6227 struct io_timeout_data *data;
6229 u32 off = READ_ONCE(sqe->off);
6231 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6233 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6236 if (off && is_timeout_link)
6238 flags = READ_ONCE(sqe->timeout_flags);
6239 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
6241 /* more than one clock specified is invalid, obviously */
6242 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6245 INIT_LIST_HEAD(&req->timeout.list);
6246 req->timeout.off = off;
6247 if (unlikely(off && !req->ctx->off_timeout_used))
6248 req->ctx->off_timeout_used = true;
6250 if (!req->async_data && io_alloc_async_data(req))
6253 data = req->async_data;
6255 data->flags = flags;
6257 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6260 INIT_LIST_HEAD(&req->timeout.list);
6261 data->mode = io_translate_timeout_mode(flags);
6262 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6264 if (is_timeout_link) {
6265 struct io_submit_link *link = &req->ctx->submit_state.link;
6269 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6271 req->timeout.head = link->last;
6272 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6277 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6279 struct io_ring_ctx *ctx = req->ctx;
6280 struct io_timeout_data *data = req->async_data;
6281 struct list_head *entry;
6282 u32 tail, off = req->timeout.off;
6284 spin_lock_irq(&ctx->timeout_lock);
6287 * sqe->off holds how many events that need to occur for this
6288 * timeout event to be satisfied. If it isn't set, then this is
6289 * a pure timeout request, sequence isn't used.
6291 if (io_is_timeout_noseq(req)) {
6292 entry = ctx->timeout_list.prev;
6296 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6297 req->timeout.target_seq = tail + off;
6299 /* Update the last seq here in case io_flush_timeouts() hasn't.
6300 * This is safe because ->completion_lock is held, and submissions
6301 * and completions are never mixed in the same ->completion_lock section.
6303 ctx->cq_last_tm_flush = tail;
6306 * Insertion sort, ensuring the first entry in the list is always
6307 * the one we need first.
6309 list_for_each_prev(entry, &ctx->timeout_list) {
6310 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6313 if (io_is_timeout_noseq(nxt))
6315 /* nxt.seq is behind @tail, otherwise would've been completed */
6316 if (off >= nxt->timeout.target_seq - tail)
6320 list_add(&req->timeout.list, entry);
6321 data->timer.function = io_timeout_fn;
6322 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6323 spin_unlock_irq(&ctx->timeout_lock);
6327 struct io_cancel_data {
6328 struct io_ring_ctx *ctx;
6332 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6334 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6335 struct io_cancel_data *cd = data;
6337 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6340 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6341 struct io_ring_ctx *ctx)
6343 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6344 enum io_wq_cancel cancel_ret;
6347 if (!tctx || !tctx->io_wq)
6350 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6351 switch (cancel_ret) {
6352 case IO_WQ_CANCEL_OK:
6355 case IO_WQ_CANCEL_RUNNING:
6358 case IO_WQ_CANCEL_NOTFOUND:
6366 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6368 struct io_ring_ctx *ctx = req->ctx;
6371 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6373 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6377 spin_lock(&ctx->completion_lock);
6378 spin_lock_irq(&ctx->timeout_lock);
6379 ret = io_timeout_cancel(ctx, sqe_addr);
6380 spin_unlock_irq(&ctx->timeout_lock);
6383 ret = io_poll_cancel(ctx, sqe_addr, false);
6385 spin_unlock(&ctx->completion_lock);
6389 static int io_async_cancel_prep(struct io_kiocb *req,
6390 const struct io_uring_sqe *sqe)
6392 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6394 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6396 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6400 req->cancel.addr = READ_ONCE(sqe->addr);
6404 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6406 struct io_ring_ctx *ctx = req->ctx;
6407 u64 sqe_addr = req->cancel.addr;
6408 struct io_tctx_node *node;
6411 ret = io_try_cancel_userdata(req, sqe_addr);
6415 /* slow path, try all io-wq's */
6416 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6418 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6419 struct io_uring_task *tctx = node->task->io_uring;
6421 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6425 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6429 io_req_complete_post(req, ret, 0);
6433 static int io_rsrc_update_prep(struct io_kiocb *req,
6434 const struct io_uring_sqe *sqe)
6436 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6438 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6441 req->rsrc_update.offset = READ_ONCE(sqe->off);
6442 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6443 if (!req->rsrc_update.nr_args)
6445 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6449 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6451 struct io_ring_ctx *ctx = req->ctx;
6452 struct io_uring_rsrc_update2 up;
6455 up.offset = req->rsrc_update.offset;
6456 up.data = req->rsrc_update.arg;
6462 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6463 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6464 &up, req->rsrc_update.nr_args);
6465 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6469 __io_req_complete(req, issue_flags, ret, 0);
6473 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6475 switch (req->opcode) {
6478 case IORING_OP_READV:
6479 case IORING_OP_READ_FIXED:
6480 case IORING_OP_READ:
6481 return io_read_prep(req, sqe);
6482 case IORING_OP_WRITEV:
6483 case IORING_OP_WRITE_FIXED:
6484 case IORING_OP_WRITE:
6485 return io_write_prep(req, sqe);
6486 case IORING_OP_POLL_ADD:
6487 return io_poll_add_prep(req, sqe);
6488 case IORING_OP_POLL_REMOVE:
6489 return io_poll_update_prep(req, sqe);
6490 case IORING_OP_FSYNC:
6491 return io_fsync_prep(req, sqe);
6492 case IORING_OP_SYNC_FILE_RANGE:
6493 return io_sfr_prep(req, sqe);
6494 case IORING_OP_SENDMSG:
6495 case IORING_OP_SEND:
6496 return io_sendmsg_prep(req, sqe);
6497 case IORING_OP_RECVMSG:
6498 case IORING_OP_RECV:
6499 return io_recvmsg_prep(req, sqe);
6500 case IORING_OP_CONNECT:
6501 return io_connect_prep(req, sqe);
6502 case IORING_OP_TIMEOUT:
6503 return io_timeout_prep(req, sqe, false);
6504 case IORING_OP_TIMEOUT_REMOVE:
6505 return io_timeout_remove_prep(req, sqe);
6506 case IORING_OP_ASYNC_CANCEL:
6507 return io_async_cancel_prep(req, sqe);
6508 case IORING_OP_LINK_TIMEOUT:
6509 return io_timeout_prep(req, sqe, true);
6510 case IORING_OP_ACCEPT:
6511 return io_accept_prep(req, sqe);
6512 case IORING_OP_FALLOCATE:
6513 return io_fallocate_prep(req, sqe);
6514 case IORING_OP_OPENAT:
6515 return io_openat_prep(req, sqe);
6516 case IORING_OP_CLOSE:
6517 return io_close_prep(req, sqe);
6518 case IORING_OP_FILES_UPDATE:
6519 return io_rsrc_update_prep(req, sqe);
6520 case IORING_OP_STATX:
6521 return io_statx_prep(req, sqe);
6522 case IORING_OP_FADVISE:
6523 return io_fadvise_prep(req, sqe);
6524 case IORING_OP_MADVISE:
6525 return io_madvise_prep(req, sqe);
6526 case IORING_OP_OPENAT2:
6527 return io_openat2_prep(req, sqe);
6528 case IORING_OP_EPOLL_CTL:
6529 return io_epoll_ctl_prep(req, sqe);
6530 case IORING_OP_SPLICE:
6531 return io_splice_prep(req, sqe);
6532 case IORING_OP_PROVIDE_BUFFERS:
6533 return io_provide_buffers_prep(req, sqe);
6534 case IORING_OP_REMOVE_BUFFERS:
6535 return io_remove_buffers_prep(req, sqe);
6537 return io_tee_prep(req, sqe);
6538 case IORING_OP_SHUTDOWN:
6539 return io_shutdown_prep(req, sqe);
6540 case IORING_OP_RENAMEAT:
6541 return io_renameat_prep(req, sqe);
6542 case IORING_OP_UNLINKAT:
6543 return io_unlinkat_prep(req, sqe);
6546 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6551 static int io_req_prep_async(struct io_kiocb *req)
6553 if (!io_op_defs[req->opcode].needs_async_setup)
6555 if (WARN_ON_ONCE(req->async_data))
6557 if (io_alloc_async_data(req))
6560 switch (req->opcode) {
6561 case IORING_OP_READV:
6562 return io_rw_prep_async(req, READ);
6563 case IORING_OP_WRITEV:
6564 return io_rw_prep_async(req, WRITE);
6565 case IORING_OP_SENDMSG:
6566 return io_sendmsg_prep_async(req);
6567 case IORING_OP_RECVMSG:
6568 return io_recvmsg_prep_async(req);
6569 case IORING_OP_CONNECT:
6570 return io_connect_prep_async(req);
6572 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6577 static u32 io_get_sequence(struct io_kiocb *req)
6579 u32 seq = req->ctx->cached_sq_head;
6581 /* need original cached_sq_head, but it was increased for each req */
6582 io_for_each_link(req, req)
6587 static bool io_drain_req(struct io_kiocb *req)
6589 struct io_kiocb *pos;
6590 struct io_ring_ctx *ctx = req->ctx;
6591 struct io_defer_entry *de;
6595 if (req->flags & REQ_F_FAIL) {
6596 io_req_complete_fail_submit(req);
6601 * If we need to drain a request in the middle of a link, drain the
6602 * head request and the next request/link after the current link.
6603 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6604 * maintained for every request of our link.
6606 if (ctx->drain_next) {
6607 req->flags |= REQ_F_IO_DRAIN;
6608 ctx->drain_next = false;
6610 /* not interested in head, start from the first linked */
6611 io_for_each_link(pos, req->link) {
6612 if (pos->flags & REQ_F_IO_DRAIN) {
6613 ctx->drain_next = true;
6614 req->flags |= REQ_F_IO_DRAIN;
6619 /* Still need defer if there is pending req in defer list. */
6620 spin_lock(&ctx->completion_lock);
6621 if (likely(list_empty_careful(&ctx->defer_list) &&
6622 !(req->flags & REQ_F_IO_DRAIN))) {
6623 spin_unlock(&ctx->completion_lock);
6624 ctx->drain_active = false;
6627 spin_unlock(&ctx->completion_lock);
6629 seq = io_get_sequence(req);
6630 /* Still a chance to pass the sequence check */
6631 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6634 ret = io_req_prep_async(req);
6637 io_prep_async_link(req);
6638 de = kmalloc(sizeof(*de), GFP_KERNEL);
6642 io_req_complete_failed(req, ret);
6646 spin_lock(&ctx->completion_lock);
6647 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6648 spin_unlock(&ctx->completion_lock);
6650 io_queue_async_work(req, NULL);
6654 trace_io_uring_defer(ctx, req, req->user_data);
6657 list_add_tail(&de->list, &ctx->defer_list);
6658 spin_unlock(&ctx->completion_lock);
6662 static void io_clean_op(struct io_kiocb *req)
6664 if (req->flags & REQ_F_BUFFER_SELECTED) {
6665 switch (req->opcode) {
6666 case IORING_OP_READV:
6667 case IORING_OP_READ_FIXED:
6668 case IORING_OP_READ:
6669 kfree((void *)(unsigned long)req->rw.addr);
6671 case IORING_OP_RECVMSG:
6672 case IORING_OP_RECV:
6673 kfree(req->sr_msg.kbuf);
6678 if (req->flags & REQ_F_NEED_CLEANUP) {
6679 switch (req->opcode) {
6680 case IORING_OP_READV:
6681 case IORING_OP_READ_FIXED:
6682 case IORING_OP_READ:
6683 case IORING_OP_WRITEV:
6684 case IORING_OP_WRITE_FIXED:
6685 case IORING_OP_WRITE: {
6686 struct io_async_rw *io = req->async_data;
6688 kfree(io->free_iovec);
6691 case IORING_OP_RECVMSG:
6692 case IORING_OP_SENDMSG: {
6693 struct io_async_msghdr *io = req->async_data;
6695 kfree(io->free_iov);
6698 case IORING_OP_OPENAT:
6699 case IORING_OP_OPENAT2:
6700 if (req->open.filename)
6701 putname(req->open.filename);
6703 case IORING_OP_RENAMEAT:
6704 putname(req->rename.oldpath);
6705 putname(req->rename.newpath);
6707 case IORING_OP_UNLINKAT:
6708 putname(req->unlink.filename);
6712 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6713 kfree(req->apoll->double_poll);
6717 if (req->flags & REQ_F_INFLIGHT) {
6718 struct io_uring_task *tctx = req->task->io_uring;
6720 atomic_dec(&tctx->inflight_tracked);
6722 if (req->flags & REQ_F_CREDS)
6723 put_cred(req->creds);
6725 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6728 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6730 struct io_ring_ctx *ctx = req->ctx;
6731 const struct cred *creds = NULL;
6734 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6735 creds = override_creds(req->creds);
6737 switch (req->opcode) {
6739 ret = io_nop(req, issue_flags);
6741 case IORING_OP_READV:
6742 case IORING_OP_READ_FIXED:
6743 case IORING_OP_READ:
6744 ret = io_read(req, issue_flags);
6746 case IORING_OP_WRITEV:
6747 case IORING_OP_WRITE_FIXED:
6748 case IORING_OP_WRITE:
6749 ret = io_write(req, issue_flags);
6751 case IORING_OP_FSYNC:
6752 ret = io_fsync(req, issue_flags);
6754 case IORING_OP_POLL_ADD:
6755 ret = io_poll_add(req, issue_flags);
6757 case IORING_OP_POLL_REMOVE:
6758 ret = io_poll_update(req, issue_flags);
6760 case IORING_OP_SYNC_FILE_RANGE:
6761 ret = io_sync_file_range(req, issue_flags);
6763 case IORING_OP_SENDMSG:
6764 ret = io_sendmsg(req, issue_flags);
6766 case IORING_OP_SEND:
6767 ret = io_send(req, issue_flags);
6769 case IORING_OP_RECVMSG:
6770 ret = io_recvmsg(req, issue_flags);
6772 case IORING_OP_RECV:
6773 ret = io_recv(req, issue_flags);
6775 case IORING_OP_TIMEOUT:
6776 ret = io_timeout(req, issue_flags);
6778 case IORING_OP_TIMEOUT_REMOVE:
6779 ret = io_timeout_remove(req, issue_flags);
6781 case IORING_OP_ACCEPT:
6782 ret = io_accept(req, issue_flags);
6784 case IORING_OP_CONNECT:
6785 ret = io_connect(req, issue_flags);
6787 case IORING_OP_ASYNC_CANCEL:
6788 ret = io_async_cancel(req, issue_flags);
6790 case IORING_OP_FALLOCATE:
6791 ret = io_fallocate(req, issue_flags);
6793 case IORING_OP_OPENAT:
6794 ret = io_openat(req, issue_flags);
6796 case IORING_OP_CLOSE:
6797 ret = io_close(req, issue_flags);
6799 case IORING_OP_FILES_UPDATE:
6800 ret = io_files_update(req, issue_flags);
6802 case IORING_OP_STATX:
6803 ret = io_statx(req, issue_flags);
6805 case IORING_OP_FADVISE:
6806 ret = io_fadvise(req, issue_flags);
6808 case IORING_OP_MADVISE:
6809 ret = io_madvise(req, issue_flags);
6811 case IORING_OP_OPENAT2:
6812 ret = io_openat2(req, issue_flags);
6814 case IORING_OP_EPOLL_CTL:
6815 ret = io_epoll_ctl(req, issue_flags);
6817 case IORING_OP_SPLICE:
6818 ret = io_splice(req, issue_flags);
6820 case IORING_OP_PROVIDE_BUFFERS:
6821 ret = io_provide_buffers(req, issue_flags);
6823 case IORING_OP_REMOVE_BUFFERS:
6824 ret = io_remove_buffers(req, issue_flags);
6827 ret = io_tee(req, issue_flags);
6829 case IORING_OP_SHUTDOWN:
6830 ret = io_shutdown(req, issue_flags);
6832 case IORING_OP_RENAMEAT:
6833 ret = io_renameat(req, issue_flags);
6835 case IORING_OP_UNLINKAT:
6836 ret = io_unlinkat(req, issue_flags);
6844 revert_creds(creds);
6847 /* If the op doesn't have a file, we're not polling for it */
6848 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6849 io_iopoll_req_issued(req);
6854 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6856 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6858 req = io_put_req_find_next(req);
6859 return req ? &req->work : NULL;
6862 static void io_wq_submit_work(struct io_wq_work *work)
6864 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6865 struct io_kiocb *timeout;
6868 /* one will be dropped by ->io_free_work() after returning to io-wq */
6869 if (!(req->flags & REQ_F_REFCOUNT))
6870 __io_req_set_refcount(req, 2);
6874 timeout = io_prep_linked_timeout(req);
6876 io_queue_linked_timeout(timeout);
6878 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6879 if (work->flags & IO_WQ_WORK_CANCEL)
6884 ret = io_issue_sqe(req, 0);
6886 * We can get EAGAIN for polled IO even though we're
6887 * forcing a sync submission from here, since we can't
6888 * wait for request slots on the block side.
6890 if (ret != -EAGAIN || !(req->ctx->flags & IORING_SETUP_IOPOLL))
6892 if (io_wq_worker_stopped())
6895 * If REQ_F_NOWAIT is set, then don't wait or retry with
6896 * poll. -EAGAIN is final for that case.
6898 if (req->flags & REQ_F_NOWAIT)
6905 /* avoid locking problems by failing it from a clean context */
6907 io_req_task_queue_fail(req, ret);
6910 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6913 return &table->files[i];
6916 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6919 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6921 return (struct file *) (slot->file_ptr & FFS_MASK);
6924 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6926 unsigned long file_ptr = (unsigned long) file;
6928 if (__io_file_supports_nowait(file, READ))
6929 file_ptr |= FFS_ASYNC_READ;
6930 if (__io_file_supports_nowait(file, WRITE))
6931 file_ptr |= FFS_ASYNC_WRITE;
6932 if (S_ISREG(file_inode(file)->i_mode))
6933 file_ptr |= FFS_ISREG;
6934 file_slot->file_ptr = file_ptr;
6937 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6938 struct io_kiocb *req, int fd,
6939 unsigned int issue_flags)
6941 struct file *file = NULL;
6942 unsigned long file_ptr;
6944 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6946 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6948 fd = array_index_nospec(fd, ctx->nr_user_files);
6949 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6950 file = (struct file *) (file_ptr & FFS_MASK);
6951 file_ptr &= ~FFS_MASK;
6952 /* mask in overlapping REQ_F and FFS bits */
6953 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6954 io_req_set_rsrc_node(req);
6956 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6960 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6961 struct io_kiocb *req, int fd)
6963 struct file *file = fget(fd);
6965 trace_io_uring_file_get(ctx, fd);
6967 /* we don't allow fixed io_uring files */
6968 if (file && unlikely(file->f_op == &io_uring_fops))
6969 io_req_track_inflight(req);
6973 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6974 struct io_kiocb *req, int fd, bool fixed,
6975 unsigned int issue_flags)
6978 return io_file_get_fixed(ctx, req, fd, issue_flags);
6980 return io_file_get_normal(ctx, req, fd);
6983 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6985 struct io_kiocb *prev = req->timeout.prev;
6989 if (!(req->task->flags & PF_EXITING))
6990 ret = io_try_cancel_userdata(req, prev->user_data);
6991 io_req_complete_post(req, ret ?: -ETIME, 0);
6994 io_req_complete_post(req, -ETIME, 0);
6998 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7000 struct io_timeout_data *data = container_of(timer,
7001 struct io_timeout_data, timer);
7002 struct io_kiocb *prev, *req = data->req;
7003 struct io_ring_ctx *ctx = req->ctx;
7004 unsigned long flags;
7006 spin_lock_irqsave(&ctx->timeout_lock, flags);
7007 prev = req->timeout.head;
7008 req->timeout.head = NULL;
7011 * We don't expect the list to be empty, that will only happen if we
7012 * race with the completion of the linked work.
7015 io_remove_next_linked(prev);
7016 if (!req_ref_inc_not_zero(prev))
7019 list_del(&req->timeout.list);
7020 req->timeout.prev = prev;
7021 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7023 req->io_task_work.func = io_req_task_link_timeout;
7024 io_req_task_work_add(req);
7025 return HRTIMER_NORESTART;
7028 static void io_queue_linked_timeout(struct io_kiocb *req)
7030 struct io_ring_ctx *ctx = req->ctx;
7032 spin_lock_irq(&ctx->timeout_lock);
7034 * If the back reference is NULL, then our linked request finished
7035 * before we got a chance to setup the timer
7037 if (req->timeout.head) {
7038 struct io_timeout_data *data = req->async_data;
7040 data->timer.function = io_link_timeout_fn;
7041 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7043 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7045 spin_unlock_irq(&ctx->timeout_lock);
7046 /* drop submission reference */
7050 static void __io_queue_sqe(struct io_kiocb *req)
7051 __must_hold(&req->ctx->uring_lock)
7053 struct io_kiocb *linked_timeout;
7057 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7060 * We async punt it if the file wasn't marked NOWAIT, or if the file
7061 * doesn't support non-blocking read/write attempts
7064 if (req->flags & REQ_F_COMPLETE_INLINE) {
7065 struct io_ring_ctx *ctx = req->ctx;
7066 struct io_submit_state *state = &ctx->submit_state;
7068 state->compl_reqs[state->compl_nr++] = req;
7069 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
7070 io_submit_flush_completions(ctx);
7074 linked_timeout = io_prep_linked_timeout(req);
7076 io_queue_linked_timeout(linked_timeout);
7077 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7078 linked_timeout = io_prep_linked_timeout(req);
7080 switch (io_arm_poll_handler(req)) {
7081 case IO_APOLL_READY:
7083 io_queue_linked_timeout(linked_timeout);
7085 case IO_APOLL_ABORTED:
7087 * Queued up for async execution, worker will release
7088 * submit reference when the iocb is actually submitted.
7090 io_queue_async_work(req, NULL);
7095 io_queue_linked_timeout(linked_timeout);
7097 io_req_complete_failed(req, ret);
7101 static inline void io_queue_sqe(struct io_kiocb *req)
7102 __must_hold(&req->ctx->uring_lock)
7104 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
7107 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
7108 __io_queue_sqe(req);
7109 } else if (req->flags & REQ_F_FAIL) {
7110 io_req_complete_fail_submit(req);
7112 int ret = io_req_prep_async(req);
7115 io_req_complete_failed(req, ret);
7117 io_queue_async_work(req, NULL);
7122 * Check SQE restrictions (opcode and flags).
7124 * Returns 'true' if SQE is allowed, 'false' otherwise.
7126 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7127 struct io_kiocb *req,
7128 unsigned int sqe_flags)
7130 if (likely(!ctx->restricted))
7133 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7136 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7137 ctx->restrictions.sqe_flags_required)
7140 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7141 ctx->restrictions.sqe_flags_required))
7147 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7148 const struct io_uring_sqe *sqe)
7149 __must_hold(&ctx->uring_lock)
7151 struct io_submit_state *state;
7152 unsigned int sqe_flags;
7153 int personality, ret = 0;
7155 /* req is partially pre-initialised, see io_preinit_req() */
7156 req->opcode = READ_ONCE(sqe->opcode);
7157 /* same numerical values with corresponding REQ_F_*, safe to copy */
7158 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7159 req->user_data = READ_ONCE(sqe->user_data);
7161 req->fixed_rsrc_refs = NULL;
7162 req->task = current;
7164 /* enforce forwards compatibility on users */
7165 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
7167 if (unlikely(req->opcode >= IORING_OP_LAST))
7169 if (!io_check_restriction(ctx, req, sqe_flags))
7172 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7173 !io_op_defs[req->opcode].buffer_select)
7175 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
7176 ctx->drain_active = true;
7178 personality = READ_ONCE(sqe->personality);
7180 req->creds = xa_load(&ctx->personalities, personality);
7183 get_cred(req->creds);
7184 req->flags |= REQ_F_CREDS;
7186 state = &ctx->submit_state;
7189 * Plug now if we have more than 1 IO left after this, and the target
7190 * is potentially a read/write to block based storage.
7192 if (!state->plug_started && state->ios_left > 1 &&
7193 io_op_defs[req->opcode].plug) {
7194 blk_start_plug(&state->plug);
7195 state->plug_started = true;
7198 if (io_op_defs[req->opcode].needs_file) {
7199 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7200 (sqe_flags & IOSQE_FIXED_FILE),
7201 IO_URING_F_NONBLOCK);
7202 if (unlikely(!req->file))
7210 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7211 const struct io_uring_sqe *sqe)
7212 __must_hold(&ctx->uring_lock)
7214 struct io_submit_link *link = &ctx->submit_state.link;
7217 ret = io_init_req(ctx, req, sqe);
7218 if (unlikely(ret)) {
7220 /* fail even hard links since we don't submit */
7223 * we can judge a link req is failed or cancelled by if
7224 * REQ_F_FAIL is set, but the head is an exception since
7225 * it may be set REQ_F_FAIL because of other req's failure
7226 * so let's leverage req->result to distinguish if a head
7227 * is set REQ_F_FAIL because of its failure or other req's
7228 * failure so that we can set the correct ret code for it.
7229 * init result here to avoid affecting the normal path.
7231 if (!(link->head->flags & REQ_F_FAIL))
7232 req_fail_link_node(link->head, -ECANCELED);
7233 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7235 * the current req is a normal req, we should return
7236 * error and thus break the submittion loop.
7238 io_req_complete_failed(req, ret);
7241 req_fail_link_node(req, ret);
7243 ret = io_req_prep(req, sqe);
7248 /* don't need @sqe from now on */
7249 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7251 ctx->flags & IORING_SETUP_SQPOLL);
7254 * If we already have a head request, queue this one for async
7255 * submittal once the head completes. If we don't have a head but
7256 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7257 * submitted sync once the chain is complete. If none of those
7258 * conditions are true (normal request), then just queue it.
7261 struct io_kiocb *head = link->head;
7263 if (!(req->flags & REQ_F_FAIL)) {
7264 ret = io_req_prep_async(req);
7265 if (unlikely(ret)) {
7266 req_fail_link_node(req, ret);
7267 if (!(head->flags & REQ_F_FAIL))
7268 req_fail_link_node(head, -ECANCELED);
7271 trace_io_uring_link(ctx, req, head);
7272 link->last->link = req;
7275 /* last request of a link, enqueue the link */
7276 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7281 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7293 * Batched submission is done, ensure local IO is flushed out.
7295 static void io_submit_state_end(struct io_submit_state *state,
7296 struct io_ring_ctx *ctx)
7298 if (state->link.head)
7299 io_queue_sqe(state->link.head);
7300 if (state->compl_nr)
7301 io_submit_flush_completions(ctx);
7302 if (state->plug_started)
7303 blk_finish_plug(&state->plug);
7307 * Start submission side cache.
7309 static void io_submit_state_start(struct io_submit_state *state,
7310 unsigned int max_ios)
7312 state->plug_started = false;
7313 state->ios_left = max_ios;
7314 /* set only head, no need to init link_last in advance */
7315 state->link.head = NULL;
7318 static void io_commit_sqring(struct io_ring_ctx *ctx)
7320 struct io_rings *rings = ctx->rings;
7323 * Ensure any loads from the SQEs are done at this point,
7324 * since once we write the new head, the application could
7325 * write new data to them.
7327 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7331 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7332 * that is mapped by userspace. This means that care needs to be taken to
7333 * ensure that reads are stable, as we cannot rely on userspace always
7334 * being a good citizen. If members of the sqe are validated and then later
7335 * used, it's important that those reads are done through READ_ONCE() to
7336 * prevent a re-load down the line.
7338 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7340 unsigned head, mask = ctx->sq_entries - 1;
7341 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7344 * The cached sq head (or cq tail) serves two purposes:
7346 * 1) allows us to batch the cost of updating the user visible
7348 * 2) allows the kernel side to track the head on its own, even
7349 * though the application is the one updating it.
7351 head = READ_ONCE(ctx->sq_array[sq_idx]);
7352 if (likely(head < ctx->sq_entries))
7353 return &ctx->sq_sqes[head];
7355 /* drop invalid entries */
7357 WRITE_ONCE(ctx->rings->sq_dropped,
7358 READ_ONCE(ctx->rings->sq_dropped) + 1);
7362 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7363 __must_hold(&ctx->uring_lock)
7367 /* make sure SQ entry isn't read before tail */
7368 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7369 if (!percpu_ref_tryget_many(&ctx->refs, nr))
7371 io_get_task_refs(nr);
7373 io_submit_state_start(&ctx->submit_state, nr);
7374 while (submitted < nr) {
7375 const struct io_uring_sqe *sqe;
7376 struct io_kiocb *req;
7378 req = io_alloc_req(ctx);
7379 if (unlikely(!req)) {
7381 submitted = -EAGAIN;
7384 sqe = io_get_sqe(ctx);
7385 if (unlikely(!sqe)) {
7386 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7389 /* will complete beyond this point, count as submitted */
7391 if (io_submit_sqe(ctx, req, sqe))
7395 if (unlikely(submitted != nr)) {
7396 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7397 int unused = nr - ref_used;
7399 current->io_uring->cached_refs += unused;
7400 percpu_ref_put_many(&ctx->refs, unused);
7403 io_submit_state_end(&ctx->submit_state, ctx);
7404 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7405 io_commit_sqring(ctx);
7410 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7412 return READ_ONCE(sqd->state);
7415 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7417 /* Tell userspace we may need a wakeup call */
7418 spin_lock(&ctx->completion_lock);
7419 WRITE_ONCE(ctx->rings->sq_flags,
7420 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7421 spin_unlock(&ctx->completion_lock);
7424 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7426 spin_lock(&ctx->completion_lock);
7427 WRITE_ONCE(ctx->rings->sq_flags,
7428 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7429 spin_unlock(&ctx->completion_lock);
7432 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7434 unsigned int to_submit;
7437 to_submit = io_sqring_entries(ctx);
7438 /* if we're handling multiple rings, cap submit size for fairness */
7439 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7440 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7442 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7443 unsigned nr_events = 0;
7444 const struct cred *creds = NULL;
7446 if (ctx->sq_creds != current_cred())
7447 creds = override_creds(ctx->sq_creds);
7449 mutex_lock(&ctx->uring_lock);
7450 if (!list_empty(&ctx->iopoll_list))
7451 io_do_iopoll(ctx, &nr_events, 0);
7454 * Don't submit if refs are dying, good for io_uring_register(),
7455 * but also it is relied upon by io_ring_exit_work()
7457 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7458 !(ctx->flags & IORING_SETUP_R_DISABLED))
7459 ret = io_submit_sqes(ctx, to_submit);
7460 mutex_unlock(&ctx->uring_lock);
7462 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7463 wake_up(&ctx->sqo_sq_wait);
7465 revert_creds(creds);
7471 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7473 struct io_ring_ctx *ctx;
7474 unsigned sq_thread_idle = 0;
7476 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7477 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7478 sqd->sq_thread_idle = sq_thread_idle;
7481 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7483 bool did_sig = false;
7484 struct ksignal ksig;
7486 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7487 signal_pending(current)) {
7488 mutex_unlock(&sqd->lock);
7489 if (signal_pending(current))
7490 did_sig = get_signal(&ksig);
7492 mutex_lock(&sqd->lock);
7494 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7497 static int io_sq_thread(void *data)
7499 struct io_sq_data *sqd = data;
7500 struct io_ring_ctx *ctx;
7501 unsigned long timeout = 0;
7502 char buf[TASK_COMM_LEN];
7505 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7506 set_task_comm(current, buf);
7508 if (sqd->sq_cpu != -1)
7509 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7511 set_cpus_allowed_ptr(current, cpu_online_mask);
7512 current->flags |= PF_NO_SETAFFINITY;
7514 mutex_lock(&sqd->lock);
7516 bool cap_entries, sqt_spin = false;
7518 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7519 if (io_sqd_handle_event(sqd))
7521 timeout = jiffies + sqd->sq_thread_idle;
7524 cap_entries = !list_is_singular(&sqd->ctx_list);
7525 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7526 int ret = __io_sq_thread(ctx, cap_entries);
7528 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7531 if (io_run_task_work())
7534 if (sqt_spin || !time_after(jiffies, timeout)) {
7537 timeout = jiffies + sqd->sq_thread_idle;
7541 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7542 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7543 bool needs_sched = true;
7545 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7546 io_ring_set_wakeup_flag(ctx);
7548 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7549 !list_empty_careful(&ctx->iopoll_list)) {
7550 needs_sched = false;
7553 if (io_sqring_entries(ctx)) {
7554 needs_sched = false;
7560 mutex_unlock(&sqd->lock);
7562 mutex_lock(&sqd->lock);
7564 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7565 io_ring_clear_wakeup_flag(ctx);
7568 finish_wait(&sqd->wait, &wait);
7569 timeout = jiffies + sqd->sq_thread_idle;
7572 io_uring_cancel_generic(true, sqd);
7574 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7575 io_ring_set_wakeup_flag(ctx);
7577 mutex_unlock(&sqd->lock);
7579 complete(&sqd->exited);
7583 struct io_wait_queue {
7584 struct wait_queue_entry wq;
7585 struct io_ring_ctx *ctx;
7587 unsigned nr_timeouts;
7590 static inline bool io_should_wake(struct io_wait_queue *iowq)
7592 struct io_ring_ctx *ctx = iowq->ctx;
7593 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7596 * Wake up if we have enough events, or if a timeout occurred since we
7597 * started waiting. For timeouts, we always want to return to userspace,
7598 * regardless of event count.
7600 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7603 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7604 int wake_flags, void *key)
7606 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7610 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7611 * the task, and the next invocation will do it.
7613 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7614 return autoremove_wake_function(curr, mode, wake_flags, key);
7618 static int io_run_task_work_sig(void)
7620 if (io_run_task_work())
7622 if (!signal_pending(current))
7624 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7625 return -ERESTARTSYS;
7629 static bool current_pending_io(void)
7631 struct io_uring_task *tctx = current->io_uring;
7635 return percpu_counter_read_positive(&tctx->inflight);
7638 /* when returns >0, the caller should retry */
7639 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7640 struct io_wait_queue *iowq,
7645 /* make sure we run task_work before checking for signals */
7646 ret = io_run_task_work_sig();
7647 if (ret || io_should_wake(iowq))
7649 /* let the caller flush overflows, retry */
7650 if (test_bit(0, &ctx->check_cq_overflow))
7654 * Mark us as being in io_wait if we have pending requests, so cpufreq
7655 * can take into account that the task is waiting for IO - turns out
7656 * to be important for low QD IO.
7658 if (current_pending_io())
7659 current->in_iowait = 1;
7661 if (!schedule_hrtimeout(timeout, HRTIMER_MODE_ABS))
7663 current->in_iowait = 0;
7668 * Wait until events become available, if we don't already have some. The
7669 * application must reap them itself, as they reside on the shared cq ring.
7671 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7672 const sigset_t __user *sig, size_t sigsz,
7673 struct __kernel_timespec __user *uts)
7675 struct io_wait_queue iowq;
7676 struct io_rings *rings = ctx->rings;
7677 ktime_t timeout = KTIME_MAX;
7681 io_cqring_overflow_flush(ctx);
7682 if (io_cqring_events(ctx) >= min_events)
7684 if (!io_run_task_work())
7689 struct timespec64 ts;
7691 if (get_timespec64(&ts, uts))
7693 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7697 #ifdef CONFIG_COMPAT
7698 if (in_compat_syscall())
7699 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7703 ret = set_user_sigmask(sig, sigsz);
7709 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7710 iowq.wq.private = current;
7711 INIT_LIST_HEAD(&iowq.wq.entry);
7713 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7714 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7716 trace_io_uring_cqring_wait(ctx, min_events);
7718 /* if we can't even flush overflow, don't wait for more */
7719 if (!io_cqring_overflow_flush(ctx)) {
7723 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7724 TASK_INTERRUPTIBLE);
7725 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7726 finish_wait(&ctx->cq_wait, &iowq.wq);
7730 restore_saved_sigmask_unless(ret == -EINTR);
7732 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7735 static void io_free_page_table(void **table, size_t size)
7737 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7739 for (i = 0; i < nr_tables; i++)
7744 static void **io_alloc_page_table(size_t size)
7746 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7747 size_t init_size = size;
7750 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7754 for (i = 0; i < nr_tables; i++) {
7755 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7757 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7759 io_free_page_table(table, init_size);
7767 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7769 percpu_ref_exit(&ref_node->refs);
7773 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7775 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7776 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7777 unsigned long flags;
7778 bool first_add = false;
7779 unsigned long delay = HZ;
7781 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7784 /* if we are mid-quiesce then do not delay */
7785 if (node->rsrc_data->quiesce)
7788 while (!list_empty(&ctx->rsrc_ref_list)) {
7789 node = list_first_entry(&ctx->rsrc_ref_list,
7790 struct io_rsrc_node, node);
7791 /* recycle ref nodes in order */
7794 list_del(&node->node);
7795 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7797 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7800 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7803 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7805 struct io_rsrc_node *ref_node;
7807 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7811 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7816 INIT_LIST_HEAD(&ref_node->node);
7817 INIT_LIST_HEAD(&ref_node->rsrc_list);
7818 ref_node->done = false;
7822 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7823 struct io_rsrc_data *data_to_kill)
7825 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7826 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7829 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7831 rsrc_node->rsrc_data = data_to_kill;
7832 spin_lock_irq(&ctx->rsrc_ref_lock);
7833 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7834 spin_unlock_irq(&ctx->rsrc_ref_lock);
7836 atomic_inc(&data_to_kill->refs);
7837 percpu_ref_kill(&rsrc_node->refs);
7838 ctx->rsrc_node = NULL;
7841 if (!ctx->rsrc_node) {
7842 ctx->rsrc_node = ctx->rsrc_backup_node;
7843 ctx->rsrc_backup_node = NULL;
7847 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7849 if (ctx->rsrc_backup_node)
7851 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7852 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7855 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7859 /* As we may drop ->uring_lock, other task may have started quiesce */
7863 data->quiesce = true;
7865 ret = io_rsrc_node_switch_start(ctx);
7868 io_rsrc_node_switch(ctx, data);
7870 /* kill initial ref, already quiesced if zero */
7871 if (atomic_dec_and_test(&data->refs))
7873 mutex_unlock(&ctx->uring_lock);
7874 flush_delayed_work(&ctx->rsrc_put_work);
7875 ret = wait_for_completion_interruptible(&data->done);
7877 mutex_lock(&ctx->uring_lock);
7878 if (atomic_read(&data->refs) > 0) {
7880 * it has been revived by another thread while
7883 mutex_unlock(&ctx->uring_lock);
7889 atomic_inc(&data->refs);
7890 /* wait for all works potentially completing data->done */
7891 flush_delayed_work(&ctx->rsrc_put_work);
7892 reinit_completion(&data->done);
7894 ret = io_run_task_work_sig();
7895 mutex_lock(&ctx->uring_lock);
7897 data->quiesce = false;
7902 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7904 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7905 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7907 return &data->tags[table_idx][off];
7910 static void io_rsrc_data_free(struct io_rsrc_data *data)
7912 size_t size = data->nr * sizeof(data->tags[0][0]);
7915 io_free_page_table((void **)data->tags, size);
7919 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7920 u64 __user *utags, unsigned nr,
7921 struct io_rsrc_data **pdata)
7923 struct io_rsrc_data *data;
7927 data = kzalloc(sizeof(*data), GFP_KERNEL);
7930 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7938 data->do_put = do_put;
7941 for (i = 0; i < nr; i++) {
7942 u64 *tag_slot = io_get_tag_slot(data, i);
7944 if (copy_from_user(tag_slot, &utags[i],
7950 atomic_set(&data->refs, 1);
7951 init_completion(&data->done);
7955 io_rsrc_data_free(data);
7959 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7961 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7962 GFP_KERNEL_ACCOUNT);
7963 return !!table->files;
7966 static void io_free_file_tables(struct io_file_table *table)
7968 kvfree(table->files);
7969 table->files = NULL;
7972 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7976 for (i = 0; i < ctx->nr_user_files; i++) {
7979 file = io_file_from_index(ctx, i);
7983 io_free_file_tables(&ctx->file_table);
7984 io_rsrc_data_free(ctx->file_data);
7985 ctx->file_data = NULL;
7986 ctx->nr_user_files = 0;
7989 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7991 unsigned nr = ctx->nr_user_files;
7994 if (!ctx->file_data)
7998 * Quiesce may unlock ->uring_lock, and while it's not held
7999 * prevent new requests using the table.
8001 ctx->nr_user_files = 0;
8002 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8003 ctx->nr_user_files = nr;
8005 __io_sqe_files_unregister(ctx);
8009 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8010 __releases(&sqd->lock)
8012 WARN_ON_ONCE(sqd->thread == current);
8015 * Do the dance but not conditional clear_bit() because it'd race with
8016 * other threads incrementing park_pending and setting the bit.
8018 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8019 if (atomic_dec_return(&sqd->park_pending))
8020 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8021 mutex_unlock(&sqd->lock);
8024 static void io_sq_thread_park(struct io_sq_data *sqd)
8025 __acquires(&sqd->lock)
8027 WARN_ON_ONCE(sqd->thread == current);
8029 atomic_inc(&sqd->park_pending);
8030 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8031 mutex_lock(&sqd->lock);
8033 wake_up_process(sqd->thread);
8036 static void io_sq_thread_stop(struct io_sq_data *sqd)
8038 WARN_ON_ONCE(sqd->thread == current);
8039 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8041 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8042 mutex_lock(&sqd->lock);
8044 wake_up_process(sqd->thread);
8045 mutex_unlock(&sqd->lock);
8046 wait_for_completion(&sqd->exited);
8049 static void io_put_sq_data(struct io_sq_data *sqd)
8051 if (refcount_dec_and_test(&sqd->refs)) {
8052 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8054 io_sq_thread_stop(sqd);
8059 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8061 struct io_sq_data *sqd = ctx->sq_data;
8064 io_sq_thread_park(sqd);
8065 list_del_init(&ctx->sqd_list);
8066 io_sqd_update_thread_idle(sqd);
8067 io_sq_thread_unpark(sqd);
8069 io_put_sq_data(sqd);
8070 ctx->sq_data = NULL;
8074 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8076 struct io_ring_ctx *ctx_attach;
8077 struct io_sq_data *sqd;
8080 f = fdget(p->wq_fd);
8082 return ERR_PTR(-ENXIO);
8083 if (f.file->f_op != &io_uring_fops) {
8085 return ERR_PTR(-EINVAL);
8088 ctx_attach = f.file->private_data;
8089 sqd = ctx_attach->sq_data;
8092 return ERR_PTR(-EINVAL);
8094 if (sqd->task_tgid != current->tgid) {
8096 return ERR_PTR(-EPERM);
8099 refcount_inc(&sqd->refs);
8104 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8107 struct io_sq_data *sqd;
8110 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8111 sqd = io_attach_sq_data(p);
8116 /* fall through for EPERM case, setup new sqd/task */
8117 if (PTR_ERR(sqd) != -EPERM)
8121 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8123 return ERR_PTR(-ENOMEM);
8125 atomic_set(&sqd->park_pending, 0);
8126 refcount_set(&sqd->refs, 1);
8127 INIT_LIST_HEAD(&sqd->ctx_list);
8128 mutex_init(&sqd->lock);
8129 init_waitqueue_head(&sqd->wait);
8130 init_completion(&sqd->exited);
8134 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8136 struct file *file = prsrc->file;
8141 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8143 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8144 struct io_ring_ctx *ctx = rsrc_data->ctx;
8145 struct io_rsrc_put *prsrc, *tmp;
8147 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8148 list_del(&prsrc->list);
8151 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8153 io_ring_submit_lock(ctx, lock_ring);
8154 spin_lock(&ctx->completion_lock);
8155 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8156 io_commit_cqring(ctx);
8157 spin_unlock(&ctx->completion_lock);
8158 io_cqring_ev_posted(ctx);
8159 io_ring_submit_unlock(ctx, lock_ring);
8162 rsrc_data->do_put(ctx, prsrc);
8166 io_rsrc_node_destroy(ref_node);
8167 if (atomic_dec_and_test(&rsrc_data->refs))
8168 complete(&rsrc_data->done);
8171 static void io_rsrc_put_work(struct work_struct *work)
8173 struct io_ring_ctx *ctx;
8174 struct llist_node *node;
8176 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8177 node = llist_del_all(&ctx->rsrc_put_llist);
8180 struct io_rsrc_node *ref_node;
8181 struct llist_node *next = node->next;
8183 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8184 __io_rsrc_put_work(ref_node);
8189 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8190 unsigned nr_args, u64 __user *tags)
8192 __s32 __user *fds = (__s32 __user *) arg;
8201 if (nr_args > IORING_MAX_FIXED_FILES)
8203 if (nr_args > rlimit(RLIMIT_NOFILE))
8205 ret = io_rsrc_node_switch_start(ctx);
8208 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8214 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8217 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8218 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8222 /* allow sparse sets */
8225 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8232 if (unlikely(!file))
8236 * Don't allow io_uring instances to be registered. If UNIX
8237 * isn't enabled, then this causes a reference cycle and this
8238 * instance can never get freed. If UNIX is enabled we'll
8239 * handle it just fine, but there's still no point in allowing
8240 * a ring fd as it doesn't support regular read/write anyway.
8242 if (file->f_op == &io_uring_fops) {
8246 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8249 io_rsrc_node_switch(ctx, NULL);
8252 for (i = 0; i < ctx->nr_user_files; i++) {
8253 file = io_file_from_index(ctx, i);
8257 io_free_file_tables(&ctx->file_table);
8258 ctx->nr_user_files = 0;
8260 io_rsrc_data_free(ctx->file_data);
8261 ctx->file_data = NULL;
8265 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8266 struct io_rsrc_node *node, void *rsrc)
8268 u64 *tag_slot = io_get_tag_slot(data, idx);
8269 struct io_rsrc_put *prsrc;
8271 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8275 prsrc->tag = *tag_slot;
8278 list_add(&prsrc->list, &node->rsrc_list);
8282 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8283 unsigned int issue_flags, u32 slot_index)
8285 struct io_ring_ctx *ctx = req->ctx;
8286 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8287 bool needs_switch = false;
8288 struct io_fixed_file *file_slot;
8291 io_ring_submit_lock(ctx, !force_nonblock);
8292 if (file->f_op == &io_uring_fops)
8295 if (!ctx->file_data)
8298 if (slot_index >= ctx->nr_user_files)
8301 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8302 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8304 if (file_slot->file_ptr) {
8305 struct file *old_file;
8307 ret = io_rsrc_node_switch_start(ctx);
8311 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8312 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8313 ctx->rsrc_node, old_file);
8316 file_slot->file_ptr = 0;
8317 needs_switch = true;
8320 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8321 io_fixed_file_set(file_slot, file);
8325 io_rsrc_node_switch(ctx, ctx->file_data);
8326 io_ring_submit_unlock(ctx, !force_nonblock);
8332 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8334 unsigned int offset = req->close.file_slot - 1;
8335 struct io_ring_ctx *ctx = req->ctx;
8336 struct io_fixed_file *file_slot;
8340 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8342 if (unlikely(!ctx->file_data))
8345 if (offset >= ctx->nr_user_files)
8347 ret = io_rsrc_node_switch_start(ctx);
8351 offset = array_index_nospec(offset, ctx->nr_user_files);
8352 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
8354 if (!file_slot->file_ptr)
8357 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8358 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8362 file_slot->file_ptr = 0;
8363 io_rsrc_node_switch(ctx, ctx->file_data);
8366 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8370 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8371 struct io_uring_rsrc_update2 *up,
8374 u64 __user *tags = u64_to_user_ptr(up->tags);
8375 __s32 __user *fds = u64_to_user_ptr(up->data);
8376 struct io_rsrc_data *data = ctx->file_data;
8377 struct io_fixed_file *file_slot;
8381 bool needs_switch = false;
8383 if (!ctx->file_data)
8385 if (up->offset + nr_args > ctx->nr_user_files)
8388 for (done = 0; done < nr_args; done++) {
8391 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8392 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8396 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8400 if (fd == IORING_REGISTER_FILES_SKIP)
8403 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8404 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8406 if (file_slot->file_ptr) {
8407 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8408 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
8411 file_slot->file_ptr = 0;
8412 needs_switch = true;
8421 * Don't allow io_uring instances to be registered. If
8422 * UNIX isn't enabled, then this causes a reference
8423 * cycle and this instance can never get freed. If UNIX
8424 * is enabled we'll handle it just fine, but there's
8425 * still no point in allowing a ring fd as it doesn't
8426 * support regular read/write anyway.
8428 if (file->f_op == &io_uring_fops) {
8433 *io_get_tag_slot(data, i) = tag;
8434 io_fixed_file_set(file_slot, file);
8439 io_rsrc_node_switch(ctx, data);
8440 return done ? done : err;
8443 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8444 struct task_struct *task)
8446 struct io_wq_hash *hash;
8447 struct io_wq_data data;
8448 unsigned int concurrency;
8450 mutex_lock(&ctx->uring_lock);
8451 hash = ctx->hash_map;
8453 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8455 mutex_unlock(&ctx->uring_lock);
8456 return ERR_PTR(-ENOMEM);
8458 refcount_set(&hash->refs, 1);
8459 init_waitqueue_head(&hash->wait);
8460 ctx->hash_map = hash;
8462 mutex_unlock(&ctx->uring_lock);
8466 data.free_work = io_wq_free_work;
8467 data.do_work = io_wq_submit_work;
8469 /* Do QD, or 4 * CPUS, whatever is smallest */
8470 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8472 return io_wq_create(concurrency, &data);
8475 static int io_uring_alloc_task_context(struct task_struct *task,
8476 struct io_ring_ctx *ctx)
8478 struct io_uring_task *tctx;
8481 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8482 if (unlikely(!tctx))
8485 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8486 if (unlikely(ret)) {
8491 tctx->io_wq = io_init_wq_offload(ctx, task);
8492 if (IS_ERR(tctx->io_wq)) {
8493 ret = PTR_ERR(tctx->io_wq);
8494 percpu_counter_destroy(&tctx->inflight);
8500 init_waitqueue_head(&tctx->wait);
8501 atomic_set(&tctx->in_idle, 0);
8502 atomic_set(&tctx->inflight_tracked, 0);
8503 task->io_uring = tctx;
8504 spin_lock_init(&tctx->task_lock);
8505 INIT_WQ_LIST(&tctx->task_list);
8506 init_task_work(&tctx->task_work, tctx_task_work);
8510 void __io_uring_free(struct task_struct *tsk)
8512 struct io_uring_task *tctx = tsk->io_uring;
8514 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8515 WARN_ON_ONCE(tctx->io_wq);
8516 WARN_ON_ONCE(tctx->cached_refs);
8518 percpu_counter_destroy(&tctx->inflight);
8520 tsk->io_uring = NULL;
8523 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8524 struct io_uring_params *p)
8528 /* Retain compatibility with failing for an invalid attach attempt */
8529 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8530 IORING_SETUP_ATTACH_WQ) {
8533 f = fdget(p->wq_fd);
8536 if (f.file->f_op != &io_uring_fops) {
8542 if (ctx->flags & IORING_SETUP_SQPOLL) {
8543 struct task_struct *tsk;
8544 struct io_sq_data *sqd;
8547 sqd = io_get_sq_data(p, &attached);
8553 ctx->sq_creds = get_current_cred();
8555 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8556 if (!ctx->sq_thread_idle)
8557 ctx->sq_thread_idle = HZ;
8559 io_sq_thread_park(sqd);
8560 list_add(&ctx->sqd_list, &sqd->ctx_list);
8561 io_sqd_update_thread_idle(sqd);
8562 /* don't attach to a dying SQPOLL thread, would be racy */
8563 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8564 io_sq_thread_unpark(sqd);
8571 if (p->flags & IORING_SETUP_SQ_AFF) {
8572 int cpu = p->sq_thread_cpu;
8575 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8582 sqd->task_pid = current->pid;
8583 sqd->task_tgid = current->tgid;
8584 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8591 ret = io_uring_alloc_task_context(tsk, ctx);
8592 wake_up_new_task(tsk);
8595 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8596 /* Can't have SQ_AFF without SQPOLL */
8603 complete(&ctx->sq_data->exited);
8605 io_sq_thread_finish(ctx);
8609 static inline void __io_unaccount_mem(struct user_struct *user,
8610 unsigned long nr_pages)
8612 atomic_long_sub(nr_pages, &user->locked_vm);
8615 static inline int __io_account_mem(struct user_struct *user,
8616 unsigned long nr_pages)
8618 unsigned long page_limit, cur_pages, new_pages;
8620 /* Don't allow more pages than we can safely lock */
8621 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8624 cur_pages = atomic_long_read(&user->locked_vm);
8625 new_pages = cur_pages + nr_pages;
8626 if (new_pages > page_limit)
8628 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8629 new_pages) != cur_pages);
8634 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8637 __io_unaccount_mem(ctx->user, nr_pages);
8639 if (ctx->mm_account)
8640 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8643 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8648 ret = __io_account_mem(ctx->user, nr_pages);
8653 if (ctx->mm_account)
8654 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8659 static void io_mem_free(void *ptr)
8666 page = virt_to_head_page(ptr);
8667 if (put_page_testzero(page))
8668 free_compound_page(page);
8671 static void *io_mem_alloc(size_t size)
8673 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
8675 return (void *) __get_free_pages(gfp, get_order(size));
8678 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8681 struct io_rings *rings;
8682 size_t off, sq_array_size;
8684 off = struct_size(rings, cqes, cq_entries);
8685 if (off == SIZE_MAX)
8689 off = ALIGN(off, SMP_CACHE_BYTES);
8697 sq_array_size = array_size(sizeof(u32), sq_entries);
8698 if (sq_array_size == SIZE_MAX)
8701 if (check_add_overflow(off, sq_array_size, &off))
8707 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8709 struct io_mapped_ubuf *imu = *slot;
8712 if (imu != ctx->dummy_ubuf) {
8713 for (i = 0; i < imu->nr_bvecs; i++)
8714 unpin_user_page(imu->bvec[i].bv_page);
8715 if (imu->acct_pages)
8716 io_unaccount_mem(ctx, imu->acct_pages);
8722 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8724 io_buffer_unmap(ctx, &prsrc->buf);
8728 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8732 for (i = 0; i < ctx->nr_user_bufs; i++)
8733 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8734 kfree(ctx->user_bufs);
8735 io_rsrc_data_free(ctx->buf_data);
8736 ctx->user_bufs = NULL;
8737 ctx->buf_data = NULL;
8738 ctx->nr_user_bufs = 0;
8741 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8743 unsigned nr = ctx->nr_user_bufs;
8750 * Quiesce may unlock ->uring_lock, and while it's not held
8751 * prevent new requests using the table.
8753 ctx->nr_user_bufs = 0;
8754 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8755 ctx->nr_user_bufs = nr;
8757 __io_sqe_buffers_unregister(ctx);
8761 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8762 void __user *arg, unsigned index)
8764 struct iovec __user *src;
8766 #ifdef CONFIG_COMPAT
8768 struct compat_iovec __user *ciovs;
8769 struct compat_iovec ciov;
8771 ciovs = (struct compat_iovec __user *) arg;
8772 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8775 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8776 dst->iov_len = ciov.iov_len;
8780 src = (struct iovec __user *) arg;
8781 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8787 * Not super efficient, but this is just a registration time. And we do cache
8788 * the last compound head, so generally we'll only do a full search if we don't
8791 * We check if the given compound head page has already been accounted, to
8792 * avoid double accounting it. This allows us to account the full size of the
8793 * page, not just the constituent pages of a huge page.
8795 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8796 int nr_pages, struct page *hpage)
8800 /* check current page array */
8801 for (i = 0; i < nr_pages; i++) {
8802 if (!PageCompound(pages[i]))
8804 if (compound_head(pages[i]) == hpage)
8808 /* check previously registered pages */
8809 for (i = 0; i < ctx->nr_user_bufs; i++) {
8810 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8812 for (j = 0; j < imu->nr_bvecs; j++) {
8813 if (!PageCompound(imu->bvec[j].bv_page))
8815 if (compound_head(imu->bvec[j].bv_page) == hpage)
8823 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8824 int nr_pages, struct io_mapped_ubuf *imu,
8825 struct page **last_hpage)
8829 imu->acct_pages = 0;
8830 for (i = 0; i < nr_pages; i++) {
8831 if (!PageCompound(pages[i])) {
8836 hpage = compound_head(pages[i]);
8837 if (hpage == *last_hpage)
8839 *last_hpage = hpage;
8840 if (headpage_already_acct(ctx, pages, i, hpage))
8842 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8846 if (!imu->acct_pages)
8849 ret = io_account_mem(ctx, imu->acct_pages);
8851 imu->acct_pages = 0;
8855 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8856 struct io_mapped_ubuf **pimu,
8857 struct page **last_hpage)
8859 struct io_mapped_ubuf *imu = NULL;
8860 struct vm_area_struct **vmas = NULL;
8861 struct page **pages = NULL;
8862 unsigned long off, start, end, ubuf;
8864 int ret, pret, nr_pages, i;
8866 if (!iov->iov_base) {
8867 *pimu = ctx->dummy_ubuf;
8871 ubuf = (unsigned long) iov->iov_base;
8872 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8873 start = ubuf >> PAGE_SHIFT;
8874 nr_pages = end - start;
8879 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8883 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8888 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8893 mmap_read_lock(current->mm);
8894 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8896 if (pret == nr_pages) {
8897 struct file *file = vmas[0]->vm_file;
8899 /* don't support file backed memory */
8900 for (i = 0; i < nr_pages; i++) {
8901 if (vmas[i]->vm_file != file) {
8907 if (!vma_is_shmem(vmas[i]) && !is_file_hugepages(file)) {
8913 ret = pret < 0 ? pret : -EFAULT;
8915 mmap_read_unlock(current->mm);
8918 * if we did partial map, or found file backed vmas,
8919 * release any pages we did get
8922 unpin_user_pages(pages, pret);
8926 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8928 unpin_user_pages(pages, pret);
8932 off = ubuf & ~PAGE_MASK;
8933 size = iov->iov_len;
8934 for (i = 0; i < nr_pages; i++) {
8937 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8938 imu->bvec[i].bv_page = pages[i];
8939 imu->bvec[i].bv_len = vec_len;
8940 imu->bvec[i].bv_offset = off;
8944 /* store original address for later verification */
8946 imu->ubuf_end = ubuf + iov->iov_len;
8947 imu->nr_bvecs = nr_pages;
8958 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8960 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8961 return ctx->user_bufs ? 0 : -ENOMEM;
8964 static int io_buffer_validate(struct iovec *iov)
8966 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8969 * Don't impose further limits on the size and buffer
8970 * constraints here, we'll -EINVAL later when IO is
8971 * submitted if they are wrong.
8974 return iov->iov_len ? -EFAULT : 0;
8978 /* arbitrary limit, but we need something */
8979 if (iov->iov_len > SZ_1G)
8982 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8988 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8989 unsigned int nr_args, u64 __user *tags)
8991 struct page *last_hpage = NULL;
8992 struct io_rsrc_data *data;
8998 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9000 ret = io_rsrc_node_switch_start(ctx);
9003 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9006 ret = io_buffers_map_alloc(ctx, nr_args);
9008 io_rsrc_data_free(data);
9012 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9013 ret = io_copy_iov(ctx, &iov, arg, i);
9016 ret = io_buffer_validate(&iov);
9019 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9024 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9030 WARN_ON_ONCE(ctx->buf_data);
9032 ctx->buf_data = data;
9034 __io_sqe_buffers_unregister(ctx);
9036 io_rsrc_node_switch(ctx, NULL);
9040 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9041 struct io_uring_rsrc_update2 *up,
9042 unsigned int nr_args)
9044 u64 __user *tags = u64_to_user_ptr(up->tags);
9045 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9046 struct page *last_hpage = NULL;
9047 bool needs_switch = false;
9053 if (up->offset + nr_args > ctx->nr_user_bufs)
9056 for (done = 0; done < nr_args; done++) {
9057 struct io_mapped_ubuf *imu;
9058 int offset = up->offset + done;
9061 err = io_copy_iov(ctx, &iov, iovs, done);
9064 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9068 err = io_buffer_validate(&iov);
9071 if (!iov.iov_base && tag) {
9075 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9079 i = array_index_nospec(offset, ctx->nr_user_bufs);
9080 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9081 err = io_queue_rsrc_removal(ctx->buf_data, i,
9082 ctx->rsrc_node, ctx->user_bufs[i]);
9083 if (unlikely(err)) {
9084 io_buffer_unmap(ctx, &imu);
9087 ctx->user_bufs[i] = NULL;
9088 needs_switch = true;
9091 ctx->user_bufs[i] = imu;
9092 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9096 io_rsrc_node_switch(ctx, ctx->buf_data);
9097 return done ? done : err;
9100 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9102 __s32 __user *fds = arg;
9108 if (copy_from_user(&fd, fds, sizeof(*fds)))
9111 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9112 if (IS_ERR(ctx->cq_ev_fd)) {
9113 int ret = PTR_ERR(ctx->cq_ev_fd);
9115 ctx->cq_ev_fd = NULL;
9122 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9124 if (ctx->cq_ev_fd) {
9125 eventfd_ctx_put(ctx->cq_ev_fd);
9126 ctx->cq_ev_fd = NULL;
9133 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9135 struct io_buffer *buf;
9136 unsigned long index;
9138 xa_for_each(&ctx->io_buffers, index, buf)
9139 __io_remove_buffers(ctx, buf, index, -1U);
9142 static void io_req_cache_free(struct list_head *list)
9144 struct io_kiocb *req, *nxt;
9146 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
9147 list_del(&req->inflight_entry);
9148 kmem_cache_free(req_cachep, req);
9152 static void io_req_caches_free(struct io_ring_ctx *ctx)
9154 struct io_submit_state *state = &ctx->submit_state;
9156 mutex_lock(&ctx->uring_lock);
9158 if (state->free_reqs) {
9159 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9160 state->free_reqs = 0;
9163 io_flush_cached_locked_reqs(ctx, state);
9164 io_req_cache_free(&state->free_list);
9165 mutex_unlock(&ctx->uring_lock);
9168 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9170 if (data && !atomic_dec_and_test(&data->refs))
9171 wait_for_completion(&data->done);
9174 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
9176 io_sq_thread_finish(ctx);
9178 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9179 io_wait_rsrc_data(ctx->buf_data);
9180 io_wait_rsrc_data(ctx->file_data);
9182 mutex_lock(&ctx->uring_lock);
9184 __io_sqe_buffers_unregister(ctx);
9186 __io_sqe_files_unregister(ctx);
9188 __io_cqring_overflow_flush(ctx, true);
9189 mutex_unlock(&ctx->uring_lock);
9190 io_eventfd_unregister(ctx);
9191 io_destroy_buffers(ctx);
9193 put_cred(ctx->sq_creds);
9195 /* there are no registered resources left, nobody uses it */
9197 io_rsrc_node_destroy(ctx->rsrc_node);
9198 if (ctx->rsrc_backup_node)
9199 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9200 flush_delayed_work(&ctx->rsrc_put_work);
9202 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9203 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9205 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9207 if (ctx->mm_account) {
9208 mmdrop(ctx->mm_account);
9209 ctx->mm_account = NULL;
9212 io_mem_free(ctx->rings);
9213 io_mem_free(ctx->sq_sqes);
9215 percpu_ref_exit(&ctx->refs);
9216 free_uid(ctx->user);
9217 io_req_caches_free(ctx);
9219 io_wq_put_hash(ctx->hash_map);
9220 kfree(ctx->cancel_hash);
9221 kfree(ctx->dummy_ubuf);
9225 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9227 struct io_ring_ctx *ctx = file->private_data;
9230 poll_wait(file, &ctx->poll_wait, wait);
9232 * synchronizes with barrier from wq_has_sleeper call in
9236 if (!io_sqring_full(ctx))
9237 mask |= EPOLLOUT | EPOLLWRNORM;
9240 * Don't flush cqring overflow list here, just do a simple check.
9241 * Otherwise there could possible be ABBA deadlock:
9244 * lock(&ctx->uring_lock);
9246 * lock(&ctx->uring_lock);
9249 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9250 * pushs them to do the flush.
9252 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9253 mask |= EPOLLIN | EPOLLRDNORM;
9258 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9260 const struct cred *creds;
9262 creds = xa_erase(&ctx->personalities, id);
9271 struct io_tctx_exit {
9272 struct callback_head task_work;
9273 struct completion completion;
9274 struct io_ring_ctx *ctx;
9277 static void io_tctx_exit_cb(struct callback_head *cb)
9279 struct io_uring_task *tctx = current->io_uring;
9280 struct io_tctx_exit *work;
9282 work = container_of(cb, struct io_tctx_exit, task_work);
9284 * When @in_idle, we're in cancellation and it's racy to remove the
9285 * node. It'll be removed by the end of cancellation, just ignore it.
9286 * tctx can be NULL if the queueing of this task_work raced with
9287 * work cancelation off the exec path.
9289 if (tctx && !atomic_read(&tctx->in_idle))
9290 io_uring_del_tctx_node((unsigned long)work->ctx);
9291 complete(&work->completion);
9294 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9296 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9298 return req->ctx == data;
9301 static void io_ring_exit_work(struct work_struct *work)
9303 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9304 unsigned long timeout = jiffies + HZ * 60 * 5;
9305 unsigned long interval = HZ / 20;
9306 struct io_tctx_exit exit;
9307 struct io_tctx_node *node;
9311 * If we're doing polled IO and end up having requests being
9312 * submitted async (out-of-line), then completions can come in while
9313 * we're waiting for refs to drop. We need to reap these manually,
9314 * as nobody else will be looking for them.
9317 io_uring_try_cancel_requests(ctx, NULL, true);
9319 struct io_sq_data *sqd = ctx->sq_data;
9320 struct task_struct *tsk;
9322 io_sq_thread_park(sqd);
9324 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9325 io_wq_cancel_cb(tsk->io_uring->io_wq,
9326 io_cancel_ctx_cb, ctx, true);
9327 io_sq_thread_unpark(sqd);
9330 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9331 /* there is little hope left, don't run it too often */
9335 * This is really an uninterruptible wait, as it has to be
9336 * complete. But it's also run from a kworker, which doesn't
9337 * take signals, so it's fine to make it interruptible. This
9338 * avoids scenarios where we knowingly can wait much longer
9339 * on completions, for example if someone does a SIGSTOP on
9340 * a task that needs to finish task_work to make this loop
9341 * complete. That's a synthetic situation that should not
9342 * cause a stuck task backtrace, and hence a potential panic
9343 * on stuck tasks if that is enabled.
9345 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
9347 init_completion(&exit.completion);
9348 init_task_work(&exit.task_work, io_tctx_exit_cb);
9351 * Some may use context even when all refs and requests have been put,
9352 * and they are free to do so while still holding uring_lock or
9353 * completion_lock, see io_req_task_submit(). Apart from other work,
9354 * this lock/unlock section also waits them to finish.
9356 mutex_lock(&ctx->uring_lock);
9357 while (!list_empty(&ctx->tctx_list)) {
9358 WARN_ON_ONCE(time_after(jiffies, timeout));
9360 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9362 /* don't spin on a single task if cancellation failed */
9363 list_rotate_left(&ctx->tctx_list);
9364 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9365 if (WARN_ON_ONCE(ret))
9367 wake_up_process(node->task);
9369 mutex_unlock(&ctx->uring_lock);
9371 * See comment above for
9372 * wait_for_completion_interruptible_timeout() on why this
9373 * wait is marked as interruptible.
9375 wait_for_completion_interruptible(&exit.completion);
9376 mutex_lock(&ctx->uring_lock);
9378 mutex_unlock(&ctx->uring_lock);
9379 spin_lock(&ctx->completion_lock);
9380 spin_unlock(&ctx->completion_lock);
9382 io_ring_ctx_free(ctx);
9385 /* Returns true if we found and killed one or more timeouts */
9386 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9389 struct io_kiocb *req, *tmp;
9392 spin_lock(&ctx->completion_lock);
9393 spin_lock_irq(&ctx->timeout_lock);
9394 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9395 if (io_match_task(req, tsk, cancel_all)) {
9396 io_kill_timeout(req, -ECANCELED);
9400 spin_unlock_irq(&ctx->timeout_lock);
9402 io_commit_cqring(ctx);
9403 spin_unlock(&ctx->completion_lock);
9405 io_cqring_ev_posted(ctx);
9406 return canceled != 0;
9409 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9411 unsigned long index;
9412 struct creds *creds;
9414 mutex_lock(&ctx->uring_lock);
9415 percpu_ref_kill(&ctx->refs);
9417 __io_cqring_overflow_flush(ctx, true);
9418 xa_for_each(&ctx->personalities, index, creds)
9419 io_unregister_personality(ctx, index);
9420 mutex_unlock(&ctx->uring_lock);
9422 io_kill_timeouts(ctx, NULL, true);
9423 io_poll_remove_all(ctx, NULL, true);
9425 /* if we failed setting up the ctx, we might not have any rings */
9426 io_iopoll_try_reap_events(ctx);
9428 /* drop cached put refs after potentially doing completions */
9429 if (current->io_uring)
9430 io_uring_drop_tctx_refs(current);
9432 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9434 * Use system_unbound_wq to avoid spawning tons of event kworkers
9435 * if we're exiting a ton of rings at the same time. It just adds
9436 * noise and overhead, there's no discernable change in runtime
9437 * over using system_wq.
9439 queue_work(system_unbound_wq, &ctx->exit_work);
9442 static int io_uring_release(struct inode *inode, struct file *file)
9444 struct io_ring_ctx *ctx = file->private_data;
9446 file->private_data = NULL;
9447 io_ring_ctx_wait_and_kill(ctx);
9451 struct io_task_cancel {
9452 struct task_struct *task;
9456 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9458 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9459 struct io_task_cancel *cancel = data;
9461 return io_match_task_safe(req, cancel->task, cancel->all);
9464 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9465 struct task_struct *task, bool cancel_all)
9467 struct io_defer_entry *de;
9470 spin_lock(&ctx->completion_lock);
9471 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9472 if (io_match_task_safe(de->req, task, cancel_all)) {
9473 list_cut_position(&list, &ctx->defer_list, &de->list);
9477 spin_unlock(&ctx->completion_lock);
9478 if (list_empty(&list))
9481 while (!list_empty(&list)) {
9482 de = list_first_entry(&list, struct io_defer_entry, list);
9483 list_del_init(&de->list);
9484 io_req_complete_failed(de->req, -ECANCELED);
9490 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9492 struct io_tctx_node *node;
9493 enum io_wq_cancel cret;
9496 mutex_lock(&ctx->uring_lock);
9497 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9498 struct io_uring_task *tctx = node->task->io_uring;
9501 * io_wq will stay alive while we hold uring_lock, because it's
9502 * killed after ctx nodes, which requires to take the lock.
9504 if (!tctx || !tctx->io_wq)
9506 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9507 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9509 mutex_unlock(&ctx->uring_lock);
9514 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9515 struct task_struct *task,
9518 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9519 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9522 enum io_wq_cancel cret;
9526 ret |= io_uring_try_cancel_iowq(ctx);
9527 } else if (tctx && tctx->io_wq) {
9529 * Cancels requests of all rings, not only @ctx, but
9530 * it's fine as the task is in exit/exec.
9532 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9534 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9537 /* SQPOLL thread does its own polling */
9538 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9539 (ctx->sq_data && ctx->sq_data->thread == current)) {
9540 while (!list_empty_careful(&ctx->iopoll_list)) {
9541 io_iopoll_try_reap_events(ctx);
9547 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9548 ret |= io_poll_remove_all(ctx, task, cancel_all);
9549 ret |= io_kill_timeouts(ctx, task, cancel_all);
9551 ret |= io_run_task_work();
9558 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9560 struct io_uring_task *tctx = current->io_uring;
9561 struct io_tctx_node *node;
9564 if (unlikely(!tctx)) {
9565 ret = io_uring_alloc_task_context(current, ctx);
9569 tctx = current->io_uring;
9570 if (ctx->iowq_limits_set) {
9571 unsigned int limits[2] = { ctx->iowq_limits[0],
9572 ctx->iowq_limits[1], };
9574 ret = io_wq_max_workers(tctx->io_wq, limits);
9579 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9580 node = kmalloc(sizeof(*node), GFP_KERNEL);
9584 node->task = current;
9586 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9593 mutex_lock(&ctx->uring_lock);
9594 list_add(&node->ctx_node, &ctx->tctx_list);
9595 mutex_unlock(&ctx->uring_lock);
9602 * Note that this task has used io_uring. We use it for cancelation purposes.
9604 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9606 struct io_uring_task *tctx = current->io_uring;
9608 if (likely(tctx && tctx->last == ctx))
9610 return __io_uring_add_tctx_node(ctx);
9614 * Remove this io_uring_file -> task mapping.
9616 static void io_uring_del_tctx_node(unsigned long index)
9618 struct io_uring_task *tctx = current->io_uring;
9619 struct io_tctx_node *node;
9623 node = xa_erase(&tctx->xa, index);
9627 WARN_ON_ONCE(current != node->task);
9628 WARN_ON_ONCE(list_empty(&node->ctx_node));
9630 mutex_lock(&node->ctx->uring_lock);
9631 list_del(&node->ctx_node);
9632 mutex_unlock(&node->ctx->uring_lock);
9634 if (tctx->last == node->ctx)
9639 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9641 struct io_wq *wq = tctx->io_wq;
9642 struct io_tctx_node *node;
9643 unsigned long index;
9645 xa_for_each(&tctx->xa, index, node) {
9646 io_uring_del_tctx_node(index);
9651 * Must be after io_uring_del_task_file() (removes nodes under
9652 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9654 io_wq_put_and_exit(wq);
9659 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9662 return atomic_read(&tctx->inflight_tracked);
9663 return percpu_counter_sum(&tctx->inflight);
9667 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9668 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
9670 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9672 struct io_uring_task *tctx = current->io_uring;
9673 struct io_ring_ctx *ctx;
9677 WARN_ON_ONCE(sqd && sqd->thread != current);
9679 if (!current->io_uring)
9682 io_wq_exit_start(tctx->io_wq);
9684 atomic_inc(&tctx->in_idle);
9686 io_uring_drop_tctx_refs(current);
9687 /* read completions before cancelations */
9688 inflight = tctx_inflight(tctx, !cancel_all);
9693 struct io_tctx_node *node;
9694 unsigned long index;
9696 xa_for_each(&tctx->xa, index, node) {
9697 /* sqpoll task will cancel all its requests */
9698 if (node->ctx->sq_data)
9700 io_uring_try_cancel_requests(node->ctx, current,
9704 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9705 io_uring_try_cancel_requests(ctx, current,
9709 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
9711 io_uring_drop_tctx_refs(current);
9714 * If we've seen completions, retry without waiting. This
9715 * avoids a race where a completion comes in before we did
9716 * prepare_to_wait().
9718 if (inflight == tctx_inflight(tctx, !cancel_all))
9720 finish_wait(&tctx->wait, &wait);
9723 io_uring_clean_tctx(tctx);
9726 * We shouldn't run task_works after cancel, so just leave
9727 * ->in_idle set for normal exit.
9729 atomic_dec(&tctx->in_idle);
9730 /* for exec all current's requests should be gone, kill tctx */
9731 __io_uring_free(current);
9735 void __io_uring_cancel(bool cancel_all)
9737 io_uring_cancel_generic(cancel_all, NULL);
9740 static void *io_uring_validate_mmap_request(struct file *file,
9741 loff_t pgoff, size_t sz)
9743 struct io_ring_ctx *ctx = file->private_data;
9744 loff_t offset = pgoff << PAGE_SHIFT;
9749 case IORING_OFF_SQ_RING:
9750 case IORING_OFF_CQ_RING:
9753 case IORING_OFF_SQES:
9757 return ERR_PTR(-EINVAL);
9760 page = virt_to_head_page(ptr);
9761 if (sz > page_size(page))
9762 return ERR_PTR(-EINVAL);
9769 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9771 size_t sz = vma->vm_end - vma->vm_start;
9775 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9777 return PTR_ERR(ptr);
9779 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9780 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9783 #else /* !CONFIG_MMU */
9785 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9787 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9790 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9792 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9795 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9796 unsigned long addr, unsigned long len,
9797 unsigned long pgoff, unsigned long flags)
9801 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9803 return PTR_ERR(ptr);
9805 return (unsigned long) ptr;
9808 #endif /* !CONFIG_MMU */
9810 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9815 if (!io_sqring_full(ctx))
9817 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9819 if (!io_sqring_full(ctx))
9822 } while (!signal_pending(current));
9824 finish_wait(&ctx->sqo_sq_wait, &wait);
9828 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9829 struct __kernel_timespec __user **ts,
9830 const sigset_t __user **sig)
9832 struct io_uring_getevents_arg arg;
9835 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9836 * is just a pointer to the sigset_t.
9838 if (!(flags & IORING_ENTER_EXT_ARG)) {
9839 *sig = (const sigset_t __user *) argp;
9845 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9846 * timespec and sigset_t pointers if good.
9848 if (*argsz != sizeof(arg))
9850 if (copy_from_user(&arg, argp, sizeof(arg)))
9854 *sig = u64_to_user_ptr(arg.sigmask);
9855 *argsz = arg.sigmask_sz;
9856 *ts = u64_to_user_ptr(arg.ts);
9860 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9861 u32, min_complete, u32, flags, const void __user *, argp,
9864 struct io_ring_ctx *ctx;
9871 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9872 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9876 if (unlikely(!f.file))
9880 if (unlikely(f.file->f_op != &io_uring_fops))
9884 ctx = f.file->private_data;
9885 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9889 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9893 * For SQ polling, the thread will do all submissions and completions.
9894 * Just return the requested submit count, and wake the thread if
9898 if (ctx->flags & IORING_SETUP_SQPOLL) {
9899 io_cqring_overflow_flush(ctx);
9901 if (unlikely(ctx->sq_data->thread == NULL)) {
9905 if (flags & IORING_ENTER_SQ_WAKEUP)
9906 wake_up(&ctx->sq_data->wait);
9907 if (flags & IORING_ENTER_SQ_WAIT) {
9908 ret = io_sqpoll_wait_sq(ctx);
9912 submitted = to_submit;
9913 } else if (to_submit) {
9914 ret = io_uring_add_tctx_node(ctx);
9917 mutex_lock(&ctx->uring_lock);
9918 submitted = io_submit_sqes(ctx, to_submit);
9919 mutex_unlock(&ctx->uring_lock);
9921 if (submitted != to_submit)
9924 if (flags & IORING_ENTER_GETEVENTS) {
9925 const sigset_t __user *sig;
9926 struct __kernel_timespec __user *ts;
9928 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9932 min_complete = min(min_complete, ctx->cq_entries);
9935 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9936 * space applications don't need to do io completion events
9937 * polling again, they can rely on io_sq_thread to do polling
9938 * work, which can reduce cpu usage and uring_lock contention.
9940 if (ctx->flags & IORING_SETUP_IOPOLL &&
9941 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9942 ret = io_iopoll_check(ctx, min_complete);
9944 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9949 percpu_ref_put(&ctx->refs);
9952 return submitted ? submitted : ret;
9955 #ifdef CONFIG_PROC_FS
9956 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9957 const struct cred *cred)
9959 struct user_namespace *uns = seq_user_ns(m);
9960 struct group_info *gi;
9965 seq_printf(m, "%5d\n", id);
9966 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9967 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9968 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9969 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9970 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9971 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9972 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9973 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9974 seq_puts(m, "\n\tGroups:\t");
9975 gi = cred->group_info;
9976 for (g = 0; g < gi->ngroups; g++) {
9977 seq_put_decimal_ull(m, g ? " " : "",
9978 from_kgid_munged(uns, gi->gid[g]));
9980 seq_puts(m, "\n\tCapEff:\t");
9981 cap = cred->cap_effective;
9982 CAP_FOR_EACH_U32(__capi)
9983 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9988 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9990 int sq_pid = -1, sq_cpu = -1;
9995 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9996 * since fdinfo case grabs it in the opposite direction of normal use
9997 * cases. If we fail to get the lock, we just don't iterate any
9998 * structures that could be going away outside the io_uring mutex.
10000 has_lock = mutex_trylock(&ctx->uring_lock);
10002 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10003 struct io_sq_data *sq = ctx->sq_data;
10005 if (mutex_trylock(&sq->lock)) {
10007 sq_pid = task_pid_nr(sq->thread);
10008 sq_cpu = task_cpu(sq->thread);
10010 mutex_unlock(&sq->lock);
10014 seq_printf(m, "SqThread:\t%d\n", sq_pid);
10015 seq_printf(m, "SqThreadCpu:\t%d\n", sq_cpu);
10016 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10017 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10018 struct file *f = io_file_from_index(ctx, i);
10021 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10023 seq_printf(m, "%5u: <none>\n", i);
10025 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10026 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10027 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10028 unsigned int len = buf->ubuf_end - buf->ubuf;
10030 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10032 if (has_lock && !xa_empty(&ctx->personalities)) {
10033 unsigned long index;
10034 const struct cred *cred;
10036 seq_printf(m, "Personalities:\n");
10037 xa_for_each(&ctx->personalities, index, cred)
10038 io_uring_show_cred(m, index, cred);
10040 seq_printf(m, "PollList:\n");
10041 spin_lock(&ctx->completion_lock);
10042 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10043 struct hlist_head *list = &ctx->cancel_hash[i];
10044 struct io_kiocb *req;
10046 hlist_for_each_entry(req, list, hash_node)
10047 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10048 req->task->task_works != NULL);
10050 spin_unlock(&ctx->completion_lock);
10052 mutex_unlock(&ctx->uring_lock);
10055 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10057 struct io_ring_ctx *ctx = f->private_data;
10059 if (percpu_ref_tryget(&ctx->refs)) {
10060 __io_uring_show_fdinfo(ctx, m);
10061 percpu_ref_put(&ctx->refs);
10066 static const struct file_operations io_uring_fops = {
10067 .release = io_uring_release,
10068 .mmap = io_uring_mmap,
10070 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10071 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10073 .poll = io_uring_poll,
10074 #ifdef CONFIG_PROC_FS
10075 .show_fdinfo = io_uring_show_fdinfo,
10079 bool io_is_uring_fops(struct file *file)
10081 return file->f_op == &io_uring_fops;
10084 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10085 struct io_uring_params *p)
10087 struct io_rings *rings;
10088 size_t size, sq_array_offset;
10090 /* make sure these are sane, as we already accounted them */
10091 ctx->sq_entries = p->sq_entries;
10092 ctx->cq_entries = p->cq_entries;
10094 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10095 if (size == SIZE_MAX)
10098 rings = io_mem_alloc(size);
10102 ctx->rings = rings;
10103 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10104 rings->sq_ring_mask = p->sq_entries - 1;
10105 rings->cq_ring_mask = p->cq_entries - 1;
10106 rings->sq_ring_entries = p->sq_entries;
10107 rings->cq_ring_entries = p->cq_entries;
10109 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10110 if (size == SIZE_MAX) {
10111 io_mem_free(ctx->rings);
10116 ctx->sq_sqes = io_mem_alloc(size);
10117 if (!ctx->sq_sqes) {
10118 io_mem_free(ctx->rings);
10126 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10130 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10134 ret = io_uring_add_tctx_node(ctx);
10139 fd_install(fd, file);
10144 * Allocate an anonymous fd, this is what constitutes the application
10145 * visible backing of an io_uring instance. The application mmaps this
10146 * fd to gain access to the SQ/CQ ring details.
10148 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10150 return anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
10151 O_RDWR | O_CLOEXEC);
10154 static int io_uring_create(unsigned entries, struct io_uring_params *p,
10155 struct io_uring_params __user *params)
10157 struct io_ring_ctx *ctx;
10163 if (entries > IORING_MAX_ENTRIES) {
10164 if (!(p->flags & IORING_SETUP_CLAMP))
10166 entries = IORING_MAX_ENTRIES;
10170 * Use twice as many entries for the CQ ring. It's possible for the
10171 * application to drive a higher depth than the size of the SQ ring,
10172 * since the sqes are only used at submission time. This allows for
10173 * some flexibility in overcommitting a bit. If the application has
10174 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10175 * of CQ ring entries manually.
10177 p->sq_entries = roundup_pow_of_two(entries);
10178 if (p->flags & IORING_SETUP_CQSIZE) {
10180 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10181 * to a power-of-two, if it isn't already. We do NOT impose
10182 * any cq vs sq ring sizing.
10184 if (!p->cq_entries)
10186 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10187 if (!(p->flags & IORING_SETUP_CLAMP))
10189 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10191 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10192 if (p->cq_entries < p->sq_entries)
10195 p->cq_entries = 2 * p->sq_entries;
10198 ctx = io_ring_ctx_alloc(p);
10201 ctx->compat = in_compat_syscall();
10202 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
10203 ctx->user = get_uid(current_user());
10206 * This is just grabbed for accounting purposes. When a process exits,
10207 * the mm is exited and dropped before the files, hence we need to hang
10208 * on to this mm purely for the purposes of being able to unaccount
10209 * memory (locked/pinned vm). It's not used for anything else.
10211 mmgrab(current->mm);
10212 ctx->mm_account = current->mm;
10214 ret = io_allocate_scq_urings(ctx, p);
10218 ret = io_sq_offload_create(ctx, p);
10221 /* always set a rsrc node */
10222 ret = io_rsrc_node_switch_start(ctx);
10225 io_rsrc_node_switch(ctx, NULL);
10227 memset(&p->sq_off, 0, sizeof(p->sq_off));
10228 p->sq_off.head = offsetof(struct io_rings, sq.head);
10229 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10230 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10231 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10232 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10233 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10234 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10236 memset(&p->cq_off, 0, sizeof(p->cq_off));
10237 p->cq_off.head = offsetof(struct io_rings, cq.head);
10238 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10239 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10240 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10241 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10242 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10243 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10245 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10246 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10247 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10248 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10249 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10250 IORING_FEAT_RSRC_TAGS;
10252 if (copy_to_user(params, p, sizeof(*p))) {
10257 file = io_uring_get_file(ctx);
10258 if (IS_ERR(file)) {
10259 ret = PTR_ERR(file);
10264 * Install ring fd as the very last thing, so we don't risk someone
10265 * having closed it before we finish setup
10267 ret = io_uring_install_fd(ctx, file);
10269 /* fput will clean it up */
10274 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10277 io_ring_ctx_wait_and_kill(ctx);
10282 * Sets up an aio uring context, and returns the fd. Applications asks for a
10283 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10284 * params structure passed in.
10286 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10288 struct io_uring_params p;
10291 if (copy_from_user(&p, params, sizeof(p)))
10293 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10298 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10299 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10300 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10301 IORING_SETUP_R_DISABLED))
10304 return io_uring_create(entries, &p, params);
10307 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10308 struct io_uring_params __user *, params)
10310 return io_uring_setup(entries, params);
10313 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10315 struct io_uring_probe *p;
10319 size = struct_size(p, ops, nr_args);
10320 if (size == SIZE_MAX)
10322 p = kzalloc(size, GFP_KERNEL);
10327 if (copy_from_user(p, arg, size))
10330 if (memchr_inv(p, 0, size))
10333 p->last_op = IORING_OP_LAST - 1;
10334 if (nr_args > IORING_OP_LAST)
10335 nr_args = IORING_OP_LAST;
10337 for (i = 0; i < nr_args; i++) {
10339 if (!io_op_defs[i].not_supported)
10340 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10345 if (copy_to_user(arg, p, size))
10352 static int io_register_personality(struct io_ring_ctx *ctx)
10354 const struct cred *creds;
10358 creds = get_current_cred();
10360 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10361 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10369 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10370 unsigned int nr_args)
10372 struct io_uring_restriction *res;
10376 /* Restrictions allowed only if rings started disabled */
10377 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10380 /* We allow only a single restrictions registration */
10381 if (ctx->restrictions.registered)
10384 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10387 size = array_size(nr_args, sizeof(*res));
10388 if (size == SIZE_MAX)
10391 res = memdup_user(arg, size);
10393 return PTR_ERR(res);
10397 for (i = 0; i < nr_args; i++) {
10398 switch (res[i].opcode) {
10399 case IORING_RESTRICTION_REGISTER_OP:
10400 if (res[i].register_op >= IORING_REGISTER_LAST) {
10405 __set_bit(res[i].register_op,
10406 ctx->restrictions.register_op);
10408 case IORING_RESTRICTION_SQE_OP:
10409 if (res[i].sqe_op >= IORING_OP_LAST) {
10414 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10416 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10417 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10419 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10420 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10429 /* Reset all restrictions if an error happened */
10431 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10433 ctx->restrictions.registered = true;
10439 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10441 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10444 if (ctx->restrictions.registered)
10445 ctx->restricted = 1;
10447 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10448 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10449 wake_up(&ctx->sq_data->wait);
10453 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10454 struct io_uring_rsrc_update2 *up,
10460 if (check_add_overflow(up->offset, nr_args, &tmp))
10462 err = io_rsrc_node_switch_start(ctx);
10467 case IORING_RSRC_FILE:
10468 return __io_sqe_files_update(ctx, up, nr_args);
10469 case IORING_RSRC_BUFFER:
10470 return __io_sqe_buffers_update(ctx, up, nr_args);
10475 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10478 struct io_uring_rsrc_update2 up;
10482 memset(&up, 0, sizeof(up));
10483 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10485 if (up.resv || up.resv2)
10487 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10490 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10491 unsigned size, unsigned type)
10493 struct io_uring_rsrc_update2 up;
10495 if (size != sizeof(up))
10497 if (copy_from_user(&up, arg, sizeof(up)))
10499 if (!up.nr || up.resv || up.resv2)
10501 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10504 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10505 unsigned int size, unsigned int type)
10507 struct io_uring_rsrc_register rr;
10509 /* keep it extendible */
10510 if (size != sizeof(rr))
10513 memset(&rr, 0, sizeof(rr));
10514 if (copy_from_user(&rr, arg, size))
10516 if (!rr.nr || rr.resv || rr.resv2)
10520 case IORING_RSRC_FILE:
10521 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10522 rr.nr, u64_to_user_ptr(rr.tags));
10523 case IORING_RSRC_BUFFER:
10524 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10525 rr.nr, u64_to_user_ptr(rr.tags));
10530 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10533 struct io_uring_task *tctx = current->io_uring;
10534 cpumask_var_t new_mask;
10537 if (!tctx || !tctx->io_wq)
10540 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10543 cpumask_clear(new_mask);
10544 if (len > cpumask_size())
10545 len = cpumask_size();
10547 #ifdef CONFIG_COMPAT
10548 if (in_compat_syscall()) {
10549 ret = compat_get_bitmap(cpumask_bits(new_mask),
10550 (const compat_ulong_t __user *)arg,
10551 len * 8 /* CHAR_BIT */);
10553 ret = copy_from_user(new_mask, arg, len);
10556 ret = copy_from_user(new_mask, arg, len);
10560 free_cpumask_var(new_mask);
10564 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10565 free_cpumask_var(new_mask);
10569 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10571 struct io_uring_task *tctx = current->io_uring;
10573 if (!tctx || !tctx->io_wq)
10576 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10579 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10581 __must_hold(&ctx->uring_lock)
10583 struct io_tctx_node *node;
10584 struct io_uring_task *tctx = NULL;
10585 struct io_sq_data *sqd = NULL;
10586 __u32 new_count[2];
10589 if (copy_from_user(new_count, arg, sizeof(new_count)))
10591 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10592 if (new_count[i] > INT_MAX)
10595 if (ctx->flags & IORING_SETUP_SQPOLL) {
10596 sqd = ctx->sq_data;
10599 * Observe the correct sqd->lock -> ctx->uring_lock
10600 * ordering. Fine to drop uring_lock here, we hold
10601 * a ref to the ctx.
10603 refcount_inc(&sqd->refs);
10604 mutex_unlock(&ctx->uring_lock);
10605 mutex_lock(&sqd->lock);
10606 mutex_lock(&ctx->uring_lock);
10608 tctx = sqd->thread->io_uring;
10611 tctx = current->io_uring;
10614 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
10616 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10618 ctx->iowq_limits[i] = new_count[i];
10619 ctx->iowq_limits_set = true;
10622 if (tctx && tctx->io_wq) {
10623 ret = io_wq_max_workers(tctx->io_wq, new_count);
10627 memset(new_count, 0, sizeof(new_count));
10631 mutex_unlock(&sqd->lock);
10632 io_put_sq_data(sqd);
10635 if (copy_to_user(arg, new_count, sizeof(new_count)))
10638 /* that's it for SQPOLL, only the SQPOLL task creates requests */
10642 /* now propagate the restriction to all registered users */
10643 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10644 struct io_uring_task *tctx = node->task->io_uring;
10646 if (WARN_ON_ONCE(!tctx->io_wq))
10649 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10650 new_count[i] = ctx->iowq_limits[i];
10651 /* ignore errors, it always returns zero anyway */
10652 (void)io_wq_max_workers(tctx->io_wq, new_count);
10657 mutex_unlock(&sqd->lock);
10658 io_put_sq_data(sqd);
10663 static bool io_register_op_must_quiesce(int op)
10666 case IORING_REGISTER_BUFFERS:
10667 case IORING_UNREGISTER_BUFFERS:
10668 case IORING_REGISTER_FILES:
10669 case IORING_UNREGISTER_FILES:
10670 case IORING_REGISTER_FILES_UPDATE:
10671 case IORING_REGISTER_PROBE:
10672 case IORING_REGISTER_PERSONALITY:
10673 case IORING_UNREGISTER_PERSONALITY:
10674 case IORING_REGISTER_FILES2:
10675 case IORING_REGISTER_FILES_UPDATE2:
10676 case IORING_REGISTER_BUFFERS2:
10677 case IORING_REGISTER_BUFFERS_UPDATE:
10678 case IORING_REGISTER_IOWQ_AFF:
10679 case IORING_UNREGISTER_IOWQ_AFF:
10680 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10687 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10691 percpu_ref_kill(&ctx->refs);
10694 * Drop uring mutex before waiting for references to exit. If another
10695 * thread is currently inside io_uring_enter() it might need to grab the
10696 * uring_lock to make progress. If we hold it here across the drain
10697 * wait, then we can deadlock. It's safe to drop the mutex here, since
10698 * no new references will come in after we've killed the percpu ref.
10700 mutex_unlock(&ctx->uring_lock);
10702 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10705 ret = io_run_task_work_sig();
10706 } while (ret >= 0);
10707 mutex_lock(&ctx->uring_lock);
10710 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10714 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10715 void __user *arg, unsigned nr_args)
10716 __releases(ctx->uring_lock)
10717 __acquires(ctx->uring_lock)
10722 * We're inside the ring mutex, if the ref is already dying, then
10723 * someone else killed the ctx or is already going through
10724 * io_uring_register().
10726 if (percpu_ref_is_dying(&ctx->refs))
10729 if (ctx->restricted) {
10730 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10731 if (!test_bit(opcode, ctx->restrictions.register_op))
10735 if (io_register_op_must_quiesce(opcode)) {
10736 ret = io_ctx_quiesce(ctx);
10742 case IORING_REGISTER_BUFFERS:
10743 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10745 case IORING_UNREGISTER_BUFFERS:
10747 if (arg || nr_args)
10749 ret = io_sqe_buffers_unregister(ctx);
10751 case IORING_REGISTER_FILES:
10752 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10754 case IORING_UNREGISTER_FILES:
10756 if (arg || nr_args)
10758 ret = io_sqe_files_unregister(ctx);
10760 case IORING_REGISTER_FILES_UPDATE:
10761 ret = io_register_files_update(ctx, arg, nr_args);
10763 case IORING_REGISTER_EVENTFD:
10764 case IORING_REGISTER_EVENTFD_ASYNC:
10768 ret = io_eventfd_register(ctx, arg);
10771 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10772 ctx->eventfd_async = 1;
10774 ctx->eventfd_async = 0;
10776 case IORING_UNREGISTER_EVENTFD:
10778 if (arg || nr_args)
10780 ret = io_eventfd_unregister(ctx);
10782 case IORING_REGISTER_PROBE:
10784 if (!arg || nr_args > 256)
10786 ret = io_probe(ctx, arg, nr_args);
10788 case IORING_REGISTER_PERSONALITY:
10790 if (arg || nr_args)
10792 ret = io_register_personality(ctx);
10794 case IORING_UNREGISTER_PERSONALITY:
10798 ret = io_unregister_personality(ctx, nr_args);
10800 case IORING_REGISTER_ENABLE_RINGS:
10802 if (arg || nr_args)
10804 ret = io_register_enable_rings(ctx);
10806 case IORING_REGISTER_RESTRICTIONS:
10807 ret = io_register_restrictions(ctx, arg, nr_args);
10809 case IORING_REGISTER_FILES2:
10810 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10812 case IORING_REGISTER_FILES_UPDATE2:
10813 ret = io_register_rsrc_update(ctx, arg, nr_args,
10816 case IORING_REGISTER_BUFFERS2:
10817 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10819 case IORING_REGISTER_BUFFERS_UPDATE:
10820 ret = io_register_rsrc_update(ctx, arg, nr_args,
10821 IORING_RSRC_BUFFER);
10823 case IORING_REGISTER_IOWQ_AFF:
10825 if (!arg || !nr_args)
10827 ret = io_register_iowq_aff(ctx, arg, nr_args);
10829 case IORING_UNREGISTER_IOWQ_AFF:
10831 if (arg || nr_args)
10833 ret = io_unregister_iowq_aff(ctx);
10835 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10837 if (!arg || nr_args != 2)
10839 ret = io_register_iowq_max_workers(ctx, arg);
10846 if (io_register_op_must_quiesce(opcode)) {
10847 /* bring the ctx back to life */
10848 percpu_ref_reinit(&ctx->refs);
10849 reinit_completion(&ctx->ref_comp);
10854 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10855 void __user *, arg, unsigned int, nr_args)
10857 struct io_ring_ctx *ctx;
10861 if (opcode >= IORING_REGISTER_LAST)
10869 if (f.file->f_op != &io_uring_fops)
10872 ctx = f.file->private_data;
10874 io_run_task_work();
10876 mutex_lock(&ctx->uring_lock);
10877 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10878 mutex_unlock(&ctx->uring_lock);
10879 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10880 ctx->cq_ev_fd != NULL, ret);
10886 static int __init io_uring_init(void)
10888 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10889 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10890 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10893 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10894 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10895 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10896 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10897 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10898 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10899 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10900 BUILD_BUG_SQE_ELEM(8, __u64, off);
10901 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10902 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10903 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10904 BUILD_BUG_SQE_ELEM(24, __u32, len);
10905 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10906 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10907 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10908 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10909 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10910 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10911 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10912 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10913 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10914 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10915 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10916 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10917 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10918 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10919 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10920 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10921 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10922 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10923 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10924 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10925 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
10927 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10928 sizeof(struct io_uring_rsrc_update));
10929 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10930 sizeof(struct io_uring_rsrc_update2));
10932 /* ->buf_index is u16 */
10933 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
10935 /* should fit into one byte */
10936 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10938 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10939 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
10941 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10945 __initcall(io_uring_init);