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/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <net/busy_poll.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/splice.h>
79 #include <linux/task_work.h>
80 #include <linux/pagemap.h>
81 #include <linux/io_uring.h>
82 #include <linux/audit.h>
83 #include <linux/security.h>
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
88 #include <uapi/linux/io_uring.h>
93 #define IORING_MAX_ENTRIES 32768
94 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
98 #define IORING_MAX_FIXED_FILES (1U << 15)
99 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
100 IORING_REGISTER_LAST + IORING_OP_LAST)
102 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
103 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
104 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
106 #define IORING_MAX_REG_BUFFERS (1U << 14)
108 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
109 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
111 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
112 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
114 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
115 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
118 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
121 u32 head ____cacheline_aligned_in_smp;
122 u32 tail ____cacheline_aligned_in_smp;
126 * This data is shared with the application through the mmap at offsets
127 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
129 * The offsets to the member fields are published through struct
130 * io_sqring_offsets when calling io_uring_setup.
134 * Head and tail offsets into the ring; the offsets need to be
135 * masked to get valid indices.
137 * The kernel controls head of the sq ring and the tail of the cq ring,
138 * and the application controls tail of the sq ring and the head of the
141 struct io_uring sq, cq;
143 * Bitmasks to apply to head and tail offsets (constant, equals
146 u32 sq_ring_mask, cq_ring_mask;
147 /* Ring sizes (constant, power of 2) */
148 u32 sq_ring_entries, cq_ring_entries;
150 * Number of invalid entries dropped by the kernel due to
151 * invalid index stored in array
153 * Written by the kernel, shouldn't be modified by the
154 * application (i.e. get number of "new events" by comparing to
157 * After a new SQ head value was read by the application this
158 * counter includes all submissions that were dropped reaching
159 * the new SQ head (and possibly more).
165 * Written by the kernel, shouldn't be modified by the
168 * The application needs a full memory barrier before checking
169 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
175 * Written by the application, shouldn't be modified by the
180 * Number of completion events lost because the queue was full;
181 * this should be avoided by the application by making sure
182 * there are not more requests pending than there is space in
183 * the completion queue.
185 * Written by the kernel, shouldn't be modified by the
186 * application (i.e. get number of "new events" by comparing to
189 * As completion events come in out of order this counter is not
190 * ordered with any other data.
194 * Ring buffer of completion events.
196 * The kernel writes completion events fresh every time they are
197 * produced, so the application is allowed to modify pending
200 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
203 enum io_uring_cmd_flags {
204 IO_URING_F_COMPLETE_DEFER = 1,
205 IO_URING_F_UNLOCKED = 2,
206 /* int's last bit, sign checks are usually faster than a bit test */
207 IO_URING_F_NONBLOCK = INT_MIN,
210 struct io_mapped_ubuf {
213 unsigned int nr_bvecs;
214 unsigned long acct_pages;
215 struct bio_vec bvec[];
220 struct io_overflow_cqe {
221 struct io_uring_cqe cqe;
222 struct list_head list;
225 struct io_fixed_file {
226 /* file * with additional FFS_* flags */
227 unsigned long file_ptr;
231 struct list_head list;
236 struct io_mapped_ubuf *buf;
240 struct io_file_table {
241 struct io_fixed_file *files;
244 struct io_rsrc_node {
245 struct percpu_ref refs;
246 struct list_head node;
247 struct list_head rsrc_list;
248 struct io_rsrc_data *rsrc_data;
249 struct llist_node llist;
253 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
255 struct io_rsrc_data {
256 struct io_ring_ctx *ctx;
262 struct completion done;
266 struct io_buffer_list {
267 struct list_head list;
268 struct list_head buf_list;
273 struct list_head list;
280 struct io_restriction {
281 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
282 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
283 u8 sqe_flags_allowed;
284 u8 sqe_flags_required;
289 IO_SQ_THREAD_SHOULD_STOP = 0,
290 IO_SQ_THREAD_SHOULD_PARK,
295 atomic_t park_pending;
298 /* ctx's that are using this sqd */
299 struct list_head ctx_list;
301 struct task_struct *thread;
302 struct wait_queue_head wait;
304 unsigned sq_thread_idle;
310 struct completion exited;
313 #define IO_COMPL_BATCH 32
314 #define IO_REQ_CACHE_SIZE 32
315 #define IO_REQ_ALLOC_BATCH 8
317 struct io_submit_link {
318 struct io_kiocb *head;
319 struct io_kiocb *last;
322 struct io_submit_state {
323 /* inline/task_work completion list, under ->uring_lock */
324 struct io_wq_work_node free_list;
325 /* batch completion logic */
326 struct io_wq_work_list compl_reqs;
327 struct io_submit_link link;
332 unsigned short submit_nr;
333 struct blk_plug plug;
337 struct eventfd_ctx *cq_ev_fd;
338 unsigned int eventfd_async: 1;
342 #define IO_BUFFERS_HASH_BITS 5
345 /* const or read-mostly hot data */
347 struct percpu_ref refs;
349 struct io_rings *rings;
351 unsigned int compat: 1;
352 unsigned int drain_next: 1;
353 unsigned int restricted: 1;
354 unsigned int off_timeout_used: 1;
355 unsigned int drain_active: 1;
356 unsigned int drain_disabled: 1;
357 unsigned int has_evfd: 1;
358 } ____cacheline_aligned_in_smp;
360 /* submission data */
362 struct mutex uring_lock;
365 * Ring buffer of indices into array of io_uring_sqe, which is
366 * mmapped by the application using the IORING_OFF_SQES offset.
368 * This indirection could e.g. be used to assign fixed
369 * io_uring_sqe entries to operations and only submit them to
370 * the queue when needed.
372 * The kernel modifies neither the indices array nor the entries
376 struct io_uring_sqe *sq_sqes;
377 unsigned cached_sq_head;
379 struct list_head defer_list;
382 * Fixed resources fast path, should be accessed only under
383 * uring_lock, and updated through io_uring_register(2)
385 struct io_rsrc_node *rsrc_node;
386 int rsrc_cached_refs;
387 struct io_file_table file_table;
388 unsigned nr_user_files;
389 unsigned nr_user_bufs;
390 struct io_mapped_ubuf **user_bufs;
392 struct io_submit_state submit_state;
393 struct list_head timeout_list;
394 struct list_head ltimeout_list;
395 struct list_head cq_overflow_list;
396 struct list_head *io_buffers;
397 struct list_head io_buffers_cache;
398 struct list_head apoll_cache;
399 struct xarray personalities;
401 unsigned sq_thread_idle;
402 } ____cacheline_aligned_in_smp;
404 /* IRQ completion list, under ->completion_lock */
405 struct io_wq_work_list locked_free_list;
406 unsigned int locked_free_nr;
408 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
409 struct io_sq_data *sq_data; /* if using sq thread polling */
411 struct wait_queue_head sqo_sq_wait;
412 struct list_head sqd_list;
414 unsigned long check_cq_overflow;
415 #ifdef CONFIG_NET_RX_BUSY_POLL
416 /* used to track busy poll napi_id */
417 struct list_head napi_list;
418 spinlock_t napi_lock; /* napi_list lock */
422 unsigned cached_cq_tail;
424 struct io_ev_fd __rcu *io_ev_fd;
425 struct wait_queue_head cq_wait;
427 atomic_t cq_timeouts;
428 unsigned cq_last_tm_flush;
429 } ____cacheline_aligned_in_smp;
432 spinlock_t completion_lock;
434 spinlock_t timeout_lock;
437 * ->iopoll_list is protected by the ctx->uring_lock for
438 * io_uring instances that don't use IORING_SETUP_SQPOLL.
439 * For SQPOLL, only the single threaded io_sq_thread() will
440 * manipulate the list, hence no extra locking is needed there.
442 struct io_wq_work_list iopoll_list;
443 struct hlist_head *cancel_hash;
444 unsigned cancel_hash_bits;
445 bool poll_multi_queue;
447 struct list_head io_buffers_comp;
448 } ____cacheline_aligned_in_smp;
450 struct io_restriction restrictions;
452 /* slow path rsrc auxilary data, used by update/register */
454 struct io_rsrc_node *rsrc_backup_node;
455 struct io_mapped_ubuf *dummy_ubuf;
456 struct io_rsrc_data *file_data;
457 struct io_rsrc_data *buf_data;
459 struct delayed_work rsrc_put_work;
460 struct llist_head rsrc_put_llist;
461 struct list_head rsrc_ref_list;
462 spinlock_t rsrc_ref_lock;
464 struct list_head io_buffers_pages;
467 /* Keep this last, we don't need it for the fast path */
469 #if defined(CONFIG_UNIX)
470 struct socket *ring_sock;
472 /* hashed buffered write serialization */
473 struct io_wq_hash *hash_map;
475 /* Only used for accounting purposes */
476 struct user_struct *user;
477 struct mm_struct *mm_account;
479 /* ctx exit and cancelation */
480 struct llist_head fallback_llist;
481 struct delayed_work fallback_work;
482 struct work_struct exit_work;
483 struct list_head tctx_list;
484 struct completion ref_comp;
486 bool iowq_limits_set;
491 * Arbitrary limit, can be raised if need be
493 #define IO_RINGFD_REG_MAX 16
495 struct io_uring_task {
496 /* submission side */
499 struct wait_queue_head wait;
500 const struct io_ring_ctx *last;
502 struct percpu_counter inflight;
503 atomic_t inflight_tracked;
506 spinlock_t task_lock;
507 struct io_wq_work_list task_list;
508 struct io_wq_work_list prior_task_list;
509 struct callback_head task_work;
510 struct file **registered_rings;
515 * First field must be the file pointer in all the
516 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
518 struct io_poll_iocb {
520 struct wait_queue_head *head;
522 struct wait_queue_entry wait;
525 struct io_poll_update {
531 bool update_user_data;
540 struct io_timeout_data {
541 struct io_kiocb *req;
542 struct hrtimer timer;
543 struct timespec64 ts;
544 enum hrtimer_mode mode;
550 struct sockaddr __user *addr;
551 int __user *addr_len;
554 unsigned long nofile;
574 struct list_head list;
575 /* head of the link, used by linked timeouts only */
576 struct io_kiocb *head;
577 /* for linked completions */
578 struct io_kiocb *prev;
581 struct io_timeout_rem {
586 struct timespec64 ts;
592 /* NOTE: kiocb has the file as the first member, so don't do it here */
600 struct sockaddr __user *addr;
607 struct compat_msghdr __user *umsg_compat;
608 struct user_msghdr __user *umsg;
620 struct filename *filename;
622 unsigned long nofile;
625 struct io_rsrc_update {
651 struct epoll_event event;
655 struct file *file_out;
656 struct file *file_in;
663 struct io_provide_buf {
677 struct filename *filename;
678 struct statx __user *buffer;
690 struct filename *oldpath;
691 struct filename *newpath;
699 struct filename *filename;
706 struct filename *filename;
712 struct filename *oldpath;
713 struct filename *newpath;
720 struct filename *oldpath;
721 struct filename *newpath;
731 struct io_async_connect {
732 struct sockaddr_storage address;
735 struct io_async_msghdr {
736 struct iovec fast_iov[UIO_FASTIOV];
737 /* points to an allocated iov, if NULL we use fast_iov instead */
738 struct iovec *free_iov;
739 struct sockaddr __user *uaddr;
741 struct sockaddr_storage addr;
745 struct iov_iter iter;
746 struct iov_iter_state iter_state;
747 struct iovec fast_iov[UIO_FASTIOV];
751 struct io_rw_state s;
752 const struct iovec *free_iovec;
754 struct wait_page_queue wpq;
758 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
759 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
760 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
761 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
762 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
763 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
764 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
766 /* first byte is taken by user flags, shift it to not overlap */
771 REQ_F_LINK_TIMEOUT_BIT,
772 REQ_F_NEED_CLEANUP_BIT,
774 REQ_F_BUFFER_SELECTED_BIT,
775 REQ_F_COMPLETE_INLINE_BIT,
779 REQ_F_ARM_LTIMEOUT_BIT,
780 REQ_F_ASYNC_DATA_BIT,
781 REQ_F_SKIP_LINK_CQES_BIT,
782 REQ_F_SINGLE_POLL_BIT,
783 REQ_F_DOUBLE_POLL_BIT,
784 /* keep async read/write and isreg together and in order */
785 REQ_F_SUPPORT_NOWAIT_BIT,
788 /* not a real bit, just to check we're not overflowing the space */
794 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
795 /* drain existing IO first */
796 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
798 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
799 /* doesn't sever on completion < 0 */
800 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
802 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
803 /* IOSQE_BUFFER_SELECT */
804 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
805 /* IOSQE_CQE_SKIP_SUCCESS */
806 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
808 /* fail rest of links */
809 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
810 /* on inflight list, should be cancelled and waited on exit reliably */
811 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
812 /* read/write uses file position */
813 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
814 /* must not punt to workers */
815 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
816 /* has or had linked timeout */
817 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
819 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
820 /* already went through poll handler */
821 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
822 /* buffer already selected */
823 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
824 /* completion is deferred through io_comp_state */
825 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
826 /* caller should reissue async */
827 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
828 /* supports async reads/writes */
829 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
831 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
832 /* has creds assigned */
833 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
834 /* skip refcounting if not set */
835 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
836 /* there is a linked timeout that has to be armed */
837 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
838 /* ->async_data allocated */
839 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
840 /* don't post CQEs while failing linked requests */
841 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
842 /* single poll may be active */
843 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
844 /* double poll may active */
845 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
849 struct io_poll_iocb poll;
850 struct io_poll_iocb *double_poll;
853 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
855 struct io_task_work {
857 struct io_wq_work_node node;
858 struct llist_node fallback_node;
860 io_req_tw_func_t func;
864 IORING_RSRC_FILE = 0,
865 IORING_RSRC_BUFFER = 1,
869 * NOTE! Each of the iocb union members has the file pointer
870 * as the first entry in their struct definition. So you can
871 * access the file pointer through any of the sub-structs,
872 * or directly as just 'file' in this struct.
878 struct io_poll_iocb poll;
879 struct io_poll_update poll_update;
880 struct io_accept accept;
882 struct io_cancel cancel;
883 struct io_timeout timeout;
884 struct io_timeout_rem timeout_rem;
885 struct io_connect connect;
886 struct io_sr_msg sr_msg;
888 struct io_close close;
889 struct io_rsrc_update rsrc_update;
890 struct io_fadvise fadvise;
891 struct io_madvise madvise;
892 struct io_epoll epoll;
893 struct io_splice splice;
894 struct io_provide_buf pbuf;
895 struct io_statx statx;
896 struct io_shutdown shutdown;
897 struct io_rename rename;
898 struct io_unlink unlink;
899 struct io_mkdir mkdir;
900 struct io_symlink symlink;
901 struct io_hardlink hardlink;
906 /* polled IO has completed */
915 struct io_ring_ctx *ctx;
916 struct task_struct *task;
918 struct percpu_ref *fixed_rsrc_refs;
919 /* store used ubuf, so we can prevent reloading */
920 struct io_mapped_ubuf *imu;
922 /* used by request caches, completion batching and iopoll */
923 struct io_wq_work_node comp_list;
926 struct io_kiocb *link;
927 struct io_task_work io_task_work;
928 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
929 struct hlist_node hash_node;
930 /* internal polling, see IORING_FEAT_FAST_POLL */
931 struct async_poll *apoll;
932 /* opcode allocated if it needs to store data for async defer */
934 /* custom credentials, valid IFF REQ_F_CREDS is set */
935 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
936 struct io_buffer *kbuf;
937 const struct cred *creds;
938 struct io_wq_work work;
941 struct io_tctx_node {
942 struct list_head ctx_node;
943 struct task_struct *task;
944 struct io_ring_ctx *ctx;
947 struct io_defer_entry {
948 struct list_head list;
949 struct io_kiocb *req;
954 /* needs req->file assigned */
955 unsigned needs_file : 1;
956 /* should block plug */
958 /* hash wq insertion if file is a regular file */
959 unsigned hash_reg_file : 1;
960 /* unbound wq insertion if file is a non-regular file */
961 unsigned unbound_nonreg_file : 1;
962 /* set if opcode supports polled "wait" */
964 unsigned pollout : 1;
965 /* op supports buffer selection */
966 unsigned buffer_select : 1;
967 /* do prep async if is going to be punted */
968 unsigned needs_async_setup : 1;
969 /* opcode is not supported by this kernel */
970 unsigned not_supported : 1;
972 unsigned audit_skip : 1;
973 /* size of async data needed, if any */
974 unsigned short async_size;
977 static const struct io_op_def io_op_defs[] = {
978 [IORING_OP_NOP] = {},
979 [IORING_OP_READV] = {
981 .unbound_nonreg_file = 1,
984 .needs_async_setup = 1,
987 .async_size = sizeof(struct io_async_rw),
989 [IORING_OP_WRITEV] = {
992 .unbound_nonreg_file = 1,
994 .needs_async_setup = 1,
997 .async_size = sizeof(struct io_async_rw),
999 [IORING_OP_FSYNC] = {
1003 [IORING_OP_READ_FIXED] = {
1005 .unbound_nonreg_file = 1,
1009 .async_size = sizeof(struct io_async_rw),
1011 [IORING_OP_WRITE_FIXED] = {
1014 .unbound_nonreg_file = 1,
1018 .async_size = sizeof(struct io_async_rw),
1020 [IORING_OP_POLL_ADD] = {
1022 .unbound_nonreg_file = 1,
1025 [IORING_OP_POLL_REMOVE] = {
1028 [IORING_OP_SYNC_FILE_RANGE] = {
1032 [IORING_OP_SENDMSG] = {
1034 .unbound_nonreg_file = 1,
1036 .needs_async_setup = 1,
1037 .async_size = sizeof(struct io_async_msghdr),
1039 [IORING_OP_RECVMSG] = {
1041 .unbound_nonreg_file = 1,
1044 .needs_async_setup = 1,
1045 .async_size = sizeof(struct io_async_msghdr),
1047 [IORING_OP_TIMEOUT] = {
1049 .async_size = sizeof(struct io_timeout_data),
1051 [IORING_OP_TIMEOUT_REMOVE] = {
1052 /* used by timeout updates' prep() */
1055 [IORING_OP_ACCEPT] = {
1057 .unbound_nonreg_file = 1,
1060 [IORING_OP_ASYNC_CANCEL] = {
1063 [IORING_OP_LINK_TIMEOUT] = {
1065 .async_size = sizeof(struct io_timeout_data),
1067 [IORING_OP_CONNECT] = {
1069 .unbound_nonreg_file = 1,
1071 .needs_async_setup = 1,
1072 .async_size = sizeof(struct io_async_connect),
1074 [IORING_OP_FALLOCATE] = {
1077 [IORING_OP_OPENAT] = {},
1078 [IORING_OP_CLOSE] = {},
1079 [IORING_OP_FILES_UPDATE] = {
1082 [IORING_OP_STATX] = {
1085 [IORING_OP_READ] = {
1087 .unbound_nonreg_file = 1,
1092 .async_size = sizeof(struct io_async_rw),
1094 [IORING_OP_WRITE] = {
1097 .unbound_nonreg_file = 1,
1101 .async_size = sizeof(struct io_async_rw),
1103 [IORING_OP_FADVISE] = {
1107 [IORING_OP_MADVISE] = {},
1108 [IORING_OP_SEND] = {
1110 .unbound_nonreg_file = 1,
1114 [IORING_OP_RECV] = {
1116 .unbound_nonreg_file = 1,
1121 [IORING_OP_OPENAT2] = {
1123 [IORING_OP_EPOLL_CTL] = {
1124 .unbound_nonreg_file = 1,
1127 [IORING_OP_SPLICE] = {
1130 .unbound_nonreg_file = 1,
1133 [IORING_OP_PROVIDE_BUFFERS] = {
1136 [IORING_OP_REMOVE_BUFFERS] = {
1142 .unbound_nonreg_file = 1,
1145 [IORING_OP_SHUTDOWN] = {
1148 [IORING_OP_RENAMEAT] = {},
1149 [IORING_OP_UNLINKAT] = {},
1150 [IORING_OP_MKDIRAT] = {},
1151 [IORING_OP_SYMLINKAT] = {},
1152 [IORING_OP_LINKAT] = {},
1153 [IORING_OP_MSG_RING] = {
1158 /* requests with any of those set should undergo io_disarm_next() */
1159 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1161 static bool io_disarm_next(struct io_kiocb *req);
1162 static void io_uring_del_tctx_node(unsigned long index);
1163 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1164 struct task_struct *task,
1166 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1168 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1170 static void io_put_req(struct io_kiocb *req);
1171 static void io_put_req_deferred(struct io_kiocb *req);
1172 static void io_dismantle_req(struct io_kiocb *req);
1173 static void io_queue_linked_timeout(struct io_kiocb *req);
1174 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1175 struct io_uring_rsrc_update2 *up,
1177 static void io_clean_op(struct io_kiocb *req);
1178 static struct file *io_file_get(struct io_ring_ctx *ctx,
1179 struct io_kiocb *req, int fd, bool fixed);
1180 static void __io_queue_sqe(struct io_kiocb *req);
1181 static void io_rsrc_put_work(struct work_struct *work);
1183 static void io_req_task_queue(struct io_kiocb *req);
1184 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1185 static int io_req_prep_async(struct io_kiocb *req);
1187 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1188 unsigned int issue_flags, u32 slot_index);
1189 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1191 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1192 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1194 static struct kmem_cache *req_cachep;
1196 static const struct file_operations io_uring_fops;
1198 struct sock *io_uring_get_socket(struct file *file)
1200 #if defined(CONFIG_UNIX)
1201 if (file->f_op == &io_uring_fops) {
1202 struct io_ring_ctx *ctx = file->private_data;
1204 return ctx->ring_sock->sk;
1209 EXPORT_SYMBOL(io_uring_get_socket);
1211 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1214 mutex_lock(&ctx->uring_lock);
1219 #define io_for_each_link(pos, head) \
1220 for (pos = (head); pos; pos = pos->link)
1223 * Shamelessly stolen from the mm implementation of page reference checking,
1224 * see commit f958d7b528b1 for details.
1226 #define req_ref_zero_or_close_to_overflow(req) \
1227 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1229 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1231 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1232 return atomic_inc_not_zero(&req->refs);
1235 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1237 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1240 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1241 return atomic_dec_and_test(&req->refs);
1244 static inline void req_ref_get(struct io_kiocb *req)
1246 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1247 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1248 atomic_inc(&req->refs);
1251 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1253 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1254 __io_submit_flush_completions(ctx);
1257 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1259 if (!(req->flags & REQ_F_REFCOUNT)) {
1260 req->flags |= REQ_F_REFCOUNT;
1261 atomic_set(&req->refs, nr);
1265 static inline void io_req_set_refcount(struct io_kiocb *req)
1267 __io_req_set_refcount(req, 1);
1270 #define IO_RSRC_REF_BATCH 100
1272 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1273 struct io_ring_ctx *ctx)
1274 __must_hold(&ctx->uring_lock)
1276 struct percpu_ref *ref = req->fixed_rsrc_refs;
1279 if (ref == &ctx->rsrc_node->refs)
1280 ctx->rsrc_cached_refs++;
1282 percpu_ref_put(ref);
1286 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1288 if (req->fixed_rsrc_refs)
1289 percpu_ref_put(req->fixed_rsrc_refs);
1292 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1293 __must_hold(&ctx->uring_lock)
1295 if (ctx->rsrc_cached_refs) {
1296 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1297 ctx->rsrc_cached_refs = 0;
1301 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1302 __must_hold(&ctx->uring_lock)
1304 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1305 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1308 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1309 struct io_ring_ctx *ctx)
1311 if (!req->fixed_rsrc_refs) {
1312 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1313 ctx->rsrc_cached_refs--;
1314 if (unlikely(ctx->rsrc_cached_refs < 0))
1315 io_rsrc_refs_refill(ctx);
1319 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1321 struct io_buffer *kbuf = req->kbuf;
1322 unsigned int cflags;
1324 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
1325 req->flags &= ~REQ_F_BUFFER_SELECTED;
1326 list_add(&kbuf->list, list);
1331 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1333 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1335 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1338 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1339 unsigned issue_flags)
1341 unsigned int cflags;
1343 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1347 * We can add this buffer back to two lists:
1349 * 1) The io_buffers_cache list. This one is protected by the
1350 * ctx->uring_lock. If we already hold this lock, add back to this
1351 * list as we can grab it from issue as well.
1352 * 2) The io_buffers_comp list. This one is protected by the
1353 * ctx->completion_lock.
1355 * We migrate buffers from the comp_list to the issue cache list
1358 if (issue_flags & IO_URING_F_UNLOCKED) {
1359 struct io_ring_ctx *ctx = req->ctx;
1361 spin_lock(&ctx->completion_lock);
1362 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1363 spin_unlock(&ctx->completion_lock);
1365 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1371 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1374 struct list_head *hash_list;
1375 struct io_buffer_list *bl;
1377 hash_list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
1378 list_for_each_entry(bl, hash_list, list)
1379 if (bl->bgid == bgid || bgid == -1U)
1385 static void io_kbuf_recycle(struct io_kiocb *req)
1387 struct io_ring_ctx *ctx = req->ctx;
1388 struct io_buffer_list *bl;
1389 struct io_buffer *buf;
1391 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1394 lockdep_assert_held(&ctx->uring_lock);
1397 bl = io_buffer_get_list(ctx, buf->bgid);
1398 list_add(&buf->list, &bl->buf_list);
1399 req->flags &= ~REQ_F_BUFFER_SELECTED;
1403 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1405 __must_hold(&req->ctx->timeout_lock)
1407 struct io_kiocb *req;
1409 if (task && head->task != task)
1414 io_for_each_link(req, head) {
1415 if (req->flags & REQ_F_INFLIGHT)
1421 static bool io_match_linked(struct io_kiocb *head)
1423 struct io_kiocb *req;
1425 io_for_each_link(req, head) {
1426 if (req->flags & REQ_F_INFLIGHT)
1433 * As io_match_task() but protected against racing with linked timeouts.
1434 * User must not hold timeout_lock.
1436 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1441 if (task && head->task != task)
1446 if (head->flags & REQ_F_LINK_TIMEOUT) {
1447 struct io_ring_ctx *ctx = head->ctx;
1449 /* protect against races with linked timeouts */
1450 spin_lock_irq(&ctx->timeout_lock);
1451 matched = io_match_linked(head);
1452 spin_unlock_irq(&ctx->timeout_lock);
1454 matched = io_match_linked(head);
1459 static inline bool req_has_async_data(struct io_kiocb *req)
1461 return req->flags & REQ_F_ASYNC_DATA;
1464 static inline void req_set_fail(struct io_kiocb *req)
1466 req->flags |= REQ_F_FAIL;
1467 if (req->flags & REQ_F_CQE_SKIP) {
1468 req->flags &= ~REQ_F_CQE_SKIP;
1469 req->flags |= REQ_F_SKIP_LINK_CQES;
1473 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1479 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1481 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1483 complete(&ctx->ref_comp);
1486 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1488 return !req->timeout.off;
1491 static __cold void io_fallback_req_func(struct work_struct *work)
1493 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1494 fallback_work.work);
1495 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1496 struct io_kiocb *req, *tmp;
1497 bool locked = false;
1499 percpu_ref_get(&ctx->refs);
1500 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1501 req->io_task_work.func(req, &locked);
1504 io_submit_flush_completions(ctx);
1505 mutex_unlock(&ctx->uring_lock);
1507 percpu_ref_put(&ctx->refs);
1510 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1512 struct io_ring_ctx *ctx;
1515 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1520 * Use 5 bits less than the max cq entries, that should give us around
1521 * 32 entries per hash list if totally full and uniformly spread.
1523 hash_bits = ilog2(p->cq_entries);
1527 ctx->cancel_hash_bits = hash_bits;
1528 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1530 if (!ctx->cancel_hash)
1532 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1534 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1535 if (!ctx->dummy_ubuf)
1537 /* set invalid range, so io_import_fixed() fails meeting it */
1538 ctx->dummy_ubuf->ubuf = -1UL;
1540 ctx->io_buffers = kcalloc(1U << IO_BUFFERS_HASH_BITS,
1541 sizeof(struct list_head), GFP_KERNEL);
1542 if (!ctx->io_buffers)
1544 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++)
1545 INIT_LIST_HEAD(&ctx->io_buffers[i]);
1547 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1548 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1551 ctx->flags = p->flags;
1552 init_waitqueue_head(&ctx->sqo_sq_wait);
1553 INIT_LIST_HEAD(&ctx->sqd_list);
1554 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1555 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1556 INIT_LIST_HEAD(&ctx->apoll_cache);
1557 init_completion(&ctx->ref_comp);
1558 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1559 mutex_init(&ctx->uring_lock);
1560 init_waitqueue_head(&ctx->cq_wait);
1561 spin_lock_init(&ctx->completion_lock);
1562 spin_lock_init(&ctx->timeout_lock);
1563 INIT_WQ_LIST(&ctx->iopoll_list);
1564 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1565 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1566 INIT_LIST_HEAD(&ctx->defer_list);
1567 INIT_LIST_HEAD(&ctx->timeout_list);
1568 INIT_LIST_HEAD(&ctx->ltimeout_list);
1569 spin_lock_init(&ctx->rsrc_ref_lock);
1570 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1571 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1572 init_llist_head(&ctx->rsrc_put_llist);
1573 INIT_LIST_HEAD(&ctx->tctx_list);
1574 ctx->submit_state.free_list.next = NULL;
1575 INIT_WQ_LIST(&ctx->locked_free_list);
1576 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1577 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1578 #ifdef CONFIG_NET_RX_BUSY_POLL
1579 INIT_LIST_HEAD(&ctx->napi_list);
1580 spin_lock_init(&ctx->napi_lock);
1584 kfree(ctx->dummy_ubuf);
1585 kfree(ctx->cancel_hash);
1586 kfree(ctx->io_buffers);
1591 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1593 struct io_rings *r = ctx->rings;
1595 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1599 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1601 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1602 struct io_ring_ctx *ctx = req->ctx;
1604 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1610 #define FFS_NOWAIT 0x1UL
1611 #define FFS_ISREG 0x2UL
1612 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1614 static inline bool io_req_ffs_set(struct io_kiocb *req)
1616 return req->flags & REQ_F_FIXED_FILE;
1619 static inline void io_req_track_inflight(struct io_kiocb *req)
1621 if (!(req->flags & REQ_F_INFLIGHT)) {
1622 req->flags |= REQ_F_INFLIGHT;
1623 atomic_inc(¤t->io_uring->inflight_tracked);
1627 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1629 if (WARN_ON_ONCE(!req->link))
1632 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1633 req->flags |= REQ_F_LINK_TIMEOUT;
1635 /* linked timeouts should have two refs once prep'ed */
1636 io_req_set_refcount(req);
1637 __io_req_set_refcount(req->link, 2);
1641 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1643 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1645 return __io_prep_linked_timeout(req);
1648 static void io_prep_async_work(struct io_kiocb *req)
1650 const struct io_op_def *def = &io_op_defs[req->opcode];
1651 struct io_ring_ctx *ctx = req->ctx;
1653 if (!(req->flags & REQ_F_CREDS)) {
1654 req->flags |= REQ_F_CREDS;
1655 req->creds = get_current_cred();
1658 req->work.list.next = NULL;
1659 req->work.flags = 0;
1660 if (req->flags & REQ_F_FORCE_ASYNC)
1661 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1663 if (req->flags & REQ_F_ISREG) {
1664 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1665 io_wq_hash_work(&req->work, file_inode(req->file));
1666 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1667 if (def->unbound_nonreg_file)
1668 req->work.flags |= IO_WQ_WORK_UNBOUND;
1671 switch (req->opcode) {
1672 case IORING_OP_SPLICE:
1674 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1675 req->work.flags |= IO_WQ_WORK_UNBOUND;
1680 static void io_prep_async_link(struct io_kiocb *req)
1682 struct io_kiocb *cur;
1684 if (req->flags & REQ_F_LINK_TIMEOUT) {
1685 struct io_ring_ctx *ctx = req->ctx;
1687 spin_lock_irq(&ctx->timeout_lock);
1688 io_for_each_link(cur, req)
1689 io_prep_async_work(cur);
1690 spin_unlock_irq(&ctx->timeout_lock);
1692 io_for_each_link(cur, req)
1693 io_prep_async_work(cur);
1697 static inline void io_req_add_compl_list(struct io_kiocb *req)
1699 struct io_ring_ctx *ctx = req->ctx;
1700 struct io_submit_state *state = &ctx->submit_state;
1702 if (!(req->flags & REQ_F_CQE_SKIP))
1703 ctx->submit_state.flush_cqes = true;
1704 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1707 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1709 struct io_ring_ctx *ctx = req->ctx;
1710 struct io_kiocb *link = io_prep_linked_timeout(req);
1711 struct io_uring_task *tctx = req->task->io_uring;
1714 BUG_ON(!tctx->io_wq);
1716 /* init ->work of the whole link before punting */
1717 io_prep_async_link(req);
1720 * Not expected to happen, but if we do have a bug where this _can_
1721 * happen, catch it here and ensure the request is marked as
1722 * canceled. That will make io-wq go through the usual work cancel
1723 * procedure rather than attempt to run this request (or create a new
1726 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1727 req->work.flags |= IO_WQ_WORK_CANCEL;
1729 trace_io_uring_queue_async_work(ctx, req, req->user_data, req->opcode, req->flags,
1730 &req->work, io_wq_is_hashed(&req->work));
1731 io_wq_enqueue(tctx->io_wq, &req->work);
1733 io_queue_linked_timeout(link);
1736 static void io_kill_timeout(struct io_kiocb *req, int status)
1737 __must_hold(&req->ctx->completion_lock)
1738 __must_hold(&req->ctx->timeout_lock)
1740 struct io_timeout_data *io = req->async_data;
1742 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1745 atomic_set(&req->ctx->cq_timeouts,
1746 atomic_read(&req->ctx->cq_timeouts) + 1);
1747 list_del_init(&req->timeout.list);
1748 io_fill_cqe_req(req, status, 0);
1749 io_put_req_deferred(req);
1753 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1755 while (!list_empty(&ctx->defer_list)) {
1756 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1757 struct io_defer_entry, list);
1759 if (req_need_defer(de->req, de->seq))
1761 list_del_init(&de->list);
1762 io_req_task_queue(de->req);
1767 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1768 __must_hold(&ctx->completion_lock)
1770 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1772 spin_lock_irq(&ctx->timeout_lock);
1773 while (!list_empty(&ctx->timeout_list)) {
1774 u32 events_needed, events_got;
1775 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1776 struct io_kiocb, timeout.list);
1778 if (io_is_timeout_noseq(req))
1782 * Since seq can easily wrap around over time, subtract
1783 * the last seq at which timeouts were flushed before comparing.
1784 * Assuming not more than 2^31-1 events have happened since,
1785 * these subtractions won't have wrapped, so we can check if
1786 * target is in [last_seq, current_seq] by comparing the two.
1788 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1789 events_got = seq - ctx->cq_last_tm_flush;
1790 if (events_got < events_needed)
1793 list_del_init(&req->timeout.list);
1794 io_kill_timeout(req, 0);
1796 ctx->cq_last_tm_flush = seq;
1797 spin_unlock_irq(&ctx->timeout_lock);
1800 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1802 /* order cqe stores with ring update */
1803 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1806 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1808 if (ctx->off_timeout_used || ctx->drain_active) {
1809 spin_lock(&ctx->completion_lock);
1810 if (ctx->off_timeout_used)
1811 io_flush_timeouts(ctx);
1812 if (ctx->drain_active)
1813 io_queue_deferred(ctx);
1814 io_commit_cqring(ctx);
1815 spin_unlock(&ctx->completion_lock);
1818 io_eventfd_signal(ctx);
1821 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1823 struct io_rings *r = ctx->rings;
1825 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1828 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1830 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1833 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1835 struct io_rings *rings = ctx->rings;
1836 unsigned tail, mask = ctx->cq_entries - 1;
1839 * writes to the cq entry need to come after reading head; the
1840 * control dependency is enough as we're using WRITE_ONCE to
1843 if (__io_cqring_events(ctx) == ctx->cq_entries)
1846 tail = ctx->cached_cq_tail++;
1847 return &rings->cqes[tail & mask];
1850 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1852 struct io_ev_fd *ev_fd;
1856 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1857 * and eventfd_signal
1859 ev_fd = rcu_dereference(ctx->io_ev_fd);
1862 * Check again if ev_fd exists incase an io_eventfd_unregister call
1863 * completed between the NULL check of ctx->io_ev_fd at the start of
1864 * the function and rcu_read_lock.
1866 if (unlikely(!ev_fd))
1868 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1871 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1872 eventfd_signal(ev_fd->cq_ev_fd, 1);
1877 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1880 * wake_up_all() may seem excessive, but io_wake_function() and
1881 * io_should_wake() handle the termination of the loop and only
1882 * wake as many waiters as we need to.
1884 if (wq_has_sleeper(&ctx->cq_wait))
1885 wake_up_all(&ctx->cq_wait);
1889 * This should only get called when at least one event has been posted.
1890 * Some applications rely on the eventfd notification count only changing
1891 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1892 * 1:1 relationship between how many times this function is called (and
1893 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1895 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1897 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1899 __io_commit_cqring_flush(ctx);
1901 io_cqring_wake(ctx);
1904 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1906 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1908 __io_commit_cqring_flush(ctx);
1910 if (ctx->flags & IORING_SETUP_SQPOLL)
1911 io_cqring_wake(ctx);
1914 /* Returns true if there are no backlogged entries after the flush */
1915 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1917 bool all_flushed, posted;
1919 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1923 spin_lock(&ctx->completion_lock);
1924 while (!list_empty(&ctx->cq_overflow_list)) {
1925 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1926 struct io_overflow_cqe *ocqe;
1930 ocqe = list_first_entry(&ctx->cq_overflow_list,
1931 struct io_overflow_cqe, list);
1933 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1935 io_account_cq_overflow(ctx);
1938 list_del(&ocqe->list);
1942 all_flushed = list_empty(&ctx->cq_overflow_list);
1944 clear_bit(0, &ctx->check_cq_overflow);
1945 WRITE_ONCE(ctx->rings->sq_flags,
1946 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1950 io_commit_cqring(ctx);
1951 spin_unlock(&ctx->completion_lock);
1953 io_cqring_ev_posted(ctx);
1957 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1961 if (test_bit(0, &ctx->check_cq_overflow)) {
1962 /* iopoll syncs against uring_lock, not completion_lock */
1963 if (ctx->flags & IORING_SETUP_IOPOLL)
1964 mutex_lock(&ctx->uring_lock);
1965 ret = __io_cqring_overflow_flush(ctx, false);
1966 if (ctx->flags & IORING_SETUP_IOPOLL)
1967 mutex_unlock(&ctx->uring_lock);
1973 /* must to be called somewhat shortly after putting a request */
1974 static inline void io_put_task(struct task_struct *task, int nr)
1976 struct io_uring_task *tctx = task->io_uring;
1978 if (likely(task == current)) {
1979 tctx->cached_refs += nr;
1981 percpu_counter_sub(&tctx->inflight, nr);
1982 if (unlikely(atomic_read(&tctx->in_idle)))
1983 wake_up(&tctx->wait);
1984 put_task_struct_many(task, nr);
1988 static void io_task_refs_refill(struct io_uring_task *tctx)
1990 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1992 percpu_counter_add(&tctx->inflight, refill);
1993 refcount_add(refill, ¤t->usage);
1994 tctx->cached_refs += refill;
1997 static inline void io_get_task_refs(int nr)
1999 struct io_uring_task *tctx = current->io_uring;
2001 tctx->cached_refs -= nr;
2002 if (unlikely(tctx->cached_refs < 0))
2003 io_task_refs_refill(tctx);
2006 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2008 struct io_uring_task *tctx = task->io_uring;
2009 unsigned int refs = tctx->cached_refs;
2012 tctx->cached_refs = 0;
2013 percpu_counter_sub(&tctx->inflight, refs);
2014 put_task_struct_many(task, refs);
2018 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2019 s32 res, u32 cflags)
2021 struct io_overflow_cqe *ocqe;
2023 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
2026 * If we're in ring overflow flush mode, or in task cancel mode,
2027 * or cannot allocate an overflow entry, then we need to drop it
2030 io_account_cq_overflow(ctx);
2033 if (list_empty(&ctx->cq_overflow_list)) {
2034 set_bit(0, &ctx->check_cq_overflow);
2035 WRITE_ONCE(ctx->rings->sq_flags,
2036 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2039 ocqe->cqe.user_data = user_data;
2040 ocqe->cqe.res = res;
2041 ocqe->cqe.flags = cflags;
2042 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2046 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2047 s32 res, u32 cflags)
2049 struct io_uring_cqe *cqe;
2052 * If we can't get a cq entry, userspace overflowed the
2053 * submission (by quite a lot). Increment the overflow count in
2056 cqe = io_get_cqe(ctx);
2058 WRITE_ONCE(cqe->user_data, user_data);
2059 WRITE_ONCE(cqe->res, res);
2060 WRITE_ONCE(cqe->flags, cflags);
2063 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2066 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2068 trace_io_uring_complete(req->ctx, req, req->user_data, res, cflags);
2069 return __io_fill_cqe(req->ctx, req->user_data, res, cflags);
2072 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2074 if (!(req->flags & REQ_F_CQE_SKIP))
2075 __io_fill_cqe_req(req, res, cflags);
2078 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2079 s32 res, u32 cflags)
2082 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2083 return __io_fill_cqe(ctx, user_data, res, cflags);
2086 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2089 struct io_ring_ctx *ctx = req->ctx;
2091 if (!(req->flags & REQ_F_CQE_SKIP))
2092 __io_fill_cqe_req(req, res, cflags);
2094 * If we're the last reference to this request, add to our locked
2097 if (req_ref_put_and_test(req)) {
2098 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
2099 if (req->flags & IO_DISARM_MASK)
2100 io_disarm_next(req);
2102 io_req_task_queue(req->link);
2106 io_req_put_rsrc(req, ctx);
2107 io_dismantle_req(req);
2108 io_put_task(req->task, 1);
2109 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2110 ctx->locked_free_nr++;
2114 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2117 struct io_ring_ctx *ctx = req->ctx;
2119 spin_lock(&ctx->completion_lock);
2120 __io_req_complete_post(req, res, cflags);
2121 io_commit_cqring(ctx);
2122 spin_unlock(&ctx->completion_lock);
2123 io_cqring_ev_posted(ctx);
2126 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2130 req->cflags = cflags;
2131 req->flags |= REQ_F_COMPLETE_INLINE;
2134 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2135 s32 res, u32 cflags)
2137 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2138 io_req_complete_state(req, res, cflags);
2140 io_req_complete_post(req, res, cflags);
2143 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2145 __io_req_complete(req, 0, res, 0);
2148 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2151 io_req_complete_post(req, res, io_put_kbuf(req, 0));
2154 static void io_req_complete_fail_submit(struct io_kiocb *req)
2157 * We don't submit, fail them all, for that replace hardlinks with
2158 * normal links. Extra REQ_F_LINK is tolerated.
2160 req->flags &= ~REQ_F_HARDLINK;
2161 req->flags |= REQ_F_LINK;
2162 io_req_complete_failed(req, req->result);
2166 * Don't initialise the fields below on every allocation, but do that in
2167 * advance and keep them valid across allocations.
2169 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2173 req->async_data = NULL;
2174 /* not necessary, but safer to zero */
2178 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2179 struct io_submit_state *state)
2181 spin_lock(&ctx->completion_lock);
2182 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2183 ctx->locked_free_nr = 0;
2184 spin_unlock(&ctx->completion_lock);
2187 /* Returns true IFF there are requests in the cache */
2188 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2190 struct io_submit_state *state = &ctx->submit_state;
2193 * If we have more than a batch's worth of requests in our IRQ side
2194 * locked cache, grab the lock and move them over to our submission
2197 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2198 io_flush_cached_locked_reqs(ctx, state);
2199 return !!state->free_list.next;
2203 * A request might get retired back into the request caches even before opcode
2204 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2205 * Because of that, io_alloc_req() should be called only under ->uring_lock
2206 * and with extra caution to not get a request that is still worked on.
2208 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2209 __must_hold(&ctx->uring_lock)
2211 struct io_submit_state *state = &ctx->submit_state;
2212 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2213 void *reqs[IO_REQ_ALLOC_BATCH];
2214 struct io_kiocb *req;
2217 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2220 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2223 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2224 * retry single alloc to be on the safe side.
2226 if (unlikely(ret <= 0)) {
2227 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2233 percpu_ref_get_many(&ctx->refs, ret);
2234 for (i = 0; i < ret; i++) {
2237 io_preinit_req(req, ctx);
2238 wq_stack_add_head(&req->comp_list, &state->free_list);
2243 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2245 if (unlikely(!ctx->submit_state.free_list.next))
2246 return __io_alloc_req_refill(ctx);
2250 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2252 struct io_wq_work_node *node;
2254 node = wq_stack_extract(&ctx->submit_state.free_list);
2255 return container_of(node, struct io_kiocb, comp_list);
2258 static inline void io_put_file(struct file *file)
2264 static inline void io_dismantle_req(struct io_kiocb *req)
2266 unsigned int flags = req->flags;
2268 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2270 if (!(flags & REQ_F_FIXED_FILE))
2271 io_put_file(req->file);
2274 static __cold void __io_free_req(struct io_kiocb *req)
2276 struct io_ring_ctx *ctx = req->ctx;
2278 io_req_put_rsrc(req, ctx);
2279 io_dismantle_req(req);
2280 io_put_task(req->task, 1);
2282 spin_lock(&ctx->completion_lock);
2283 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2284 ctx->locked_free_nr++;
2285 spin_unlock(&ctx->completion_lock);
2288 static inline void io_remove_next_linked(struct io_kiocb *req)
2290 struct io_kiocb *nxt = req->link;
2292 req->link = nxt->link;
2296 static bool io_kill_linked_timeout(struct io_kiocb *req)
2297 __must_hold(&req->ctx->completion_lock)
2298 __must_hold(&req->ctx->timeout_lock)
2300 struct io_kiocb *link = req->link;
2302 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2303 struct io_timeout_data *io = link->async_data;
2305 io_remove_next_linked(req);
2306 link->timeout.head = NULL;
2307 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2308 list_del(&link->timeout.list);
2309 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2310 io_fill_cqe_req(link, -ECANCELED, 0);
2311 io_put_req_deferred(link);
2318 static void io_fail_links(struct io_kiocb *req)
2319 __must_hold(&req->ctx->completion_lock)
2321 struct io_kiocb *nxt, *link = req->link;
2322 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2326 long res = -ECANCELED;
2328 if (link->flags & REQ_F_FAIL)
2334 trace_io_uring_fail_link(req->ctx, req, req->user_data,
2338 link->flags &= ~REQ_F_CQE_SKIP;
2339 io_fill_cqe_req(link, res, 0);
2341 io_put_req_deferred(link);
2346 static bool io_disarm_next(struct io_kiocb *req)
2347 __must_hold(&req->ctx->completion_lock)
2349 bool posted = false;
2351 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2352 struct io_kiocb *link = req->link;
2354 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2355 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2356 io_remove_next_linked(req);
2357 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2358 io_fill_cqe_req(link, -ECANCELED, 0);
2359 io_put_req_deferred(link);
2362 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2363 struct io_ring_ctx *ctx = req->ctx;
2365 spin_lock_irq(&ctx->timeout_lock);
2366 posted = io_kill_linked_timeout(req);
2367 spin_unlock_irq(&ctx->timeout_lock);
2369 if (unlikely((req->flags & REQ_F_FAIL) &&
2370 !(req->flags & REQ_F_HARDLINK))) {
2371 posted |= (req->link != NULL);
2377 static void __io_req_find_next_prep(struct io_kiocb *req)
2379 struct io_ring_ctx *ctx = req->ctx;
2382 spin_lock(&ctx->completion_lock);
2383 posted = io_disarm_next(req);
2385 io_commit_cqring(ctx);
2386 spin_unlock(&ctx->completion_lock);
2388 io_cqring_ev_posted(ctx);
2391 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2393 struct io_kiocb *nxt;
2395 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2398 * If LINK is set, we have dependent requests in this chain. If we
2399 * didn't fail this request, queue the first one up, moving any other
2400 * dependencies to the next request. In case of failure, fail the rest
2403 if (unlikely(req->flags & IO_DISARM_MASK))
2404 __io_req_find_next_prep(req);
2410 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2415 io_submit_flush_completions(ctx);
2416 mutex_unlock(&ctx->uring_lock);
2419 percpu_ref_put(&ctx->refs);
2422 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2424 io_commit_cqring(ctx);
2425 spin_unlock(&ctx->completion_lock);
2426 io_cqring_ev_posted(ctx);
2429 static void handle_prev_tw_list(struct io_wq_work_node *node,
2430 struct io_ring_ctx **ctx, bool *uring_locked)
2432 if (*ctx && !*uring_locked)
2433 spin_lock(&(*ctx)->completion_lock);
2436 struct io_wq_work_node *next = node->next;
2437 struct io_kiocb *req = container_of(node, struct io_kiocb,
2440 if (req->ctx != *ctx) {
2441 if (unlikely(!*uring_locked && *ctx))
2442 ctx_commit_and_unlock(*ctx);
2444 ctx_flush_and_put(*ctx, uring_locked);
2446 /* if not contended, grab and improve batching */
2447 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2448 percpu_ref_get(&(*ctx)->refs);
2449 if (unlikely(!*uring_locked))
2450 spin_lock(&(*ctx)->completion_lock);
2452 if (likely(*uring_locked))
2453 req->io_task_work.func(req, uring_locked);
2455 __io_req_complete_post(req, req->result,
2456 io_put_kbuf_comp(req));
2460 if (unlikely(!*uring_locked))
2461 ctx_commit_and_unlock(*ctx);
2464 static void handle_tw_list(struct io_wq_work_node *node,
2465 struct io_ring_ctx **ctx, bool *locked)
2468 struct io_wq_work_node *next = node->next;
2469 struct io_kiocb *req = container_of(node, struct io_kiocb,
2472 if (req->ctx != *ctx) {
2473 ctx_flush_and_put(*ctx, locked);
2475 /* if not contended, grab and improve batching */
2476 *locked = mutex_trylock(&(*ctx)->uring_lock);
2477 percpu_ref_get(&(*ctx)->refs);
2479 req->io_task_work.func(req, locked);
2484 static void tctx_task_work(struct callback_head *cb)
2486 bool uring_locked = false;
2487 struct io_ring_ctx *ctx = NULL;
2488 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2492 struct io_wq_work_node *node1, *node2;
2494 if (!tctx->task_list.first &&
2495 !tctx->prior_task_list.first && uring_locked)
2496 io_submit_flush_completions(ctx);
2498 spin_lock_irq(&tctx->task_lock);
2499 node1 = tctx->prior_task_list.first;
2500 node2 = tctx->task_list.first;
2501 INIT_WQ_LIST(&tctx->task_list);
2502 INIT_WQ_LIST(&tctx->prior_task_list);
2503 if (!node2 && !node1)
2504 tctx->task_running = false;
2505 spin_unlock_irq(&tctx->task_lock);
2506 if (!node2 && !node1)
2510 handle_prev_tw_list(node1, &ctx, &uring_locked);
2513 handle_tw_list(node2, &ctx, &uring_locked);
2517 ctx_flush_and_put(ctx, &uring_locked);
2519 /* relaxed read is enough as only the task itself sets ->in_idle */
2520 if (unlikely(atomic_read(&tctx->in_idle)))
2521 io_uring_drop_tctx_refs(current);
2524 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2526 struct task_struct *tsk = req->task;
2527 struct io_uring_task *tctx = tsk->io_uring;
2528 enum task_work_notify_mode notify;
2529 struct io_wq_work_node *node;
2530 unsigned long flags;
2533 WARN_ON_ONCE(!tctx);
2535 spin_lock_irqsave(&tctx->task_lock, flags);
2537 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2539 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2540 running = tctx->task_running;
2542 tctx->task_running = true;
2543 spin_unlock_irqrestore(&tctx->task_lock, flags);
2545 /* task_work already pending, we're done */
2550 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2551 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2552 * processing task_work. There's no reliable way to tell if TWA_RESUME
2555 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2556 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2557 if (notify == TWA_NONE)
2558 wake_up_process(tsk);
2562 spin_lock_irqsave(&tctx->task_lock, flags);
2563 tctx->task_running = false;
2564 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2565 spin_unlock_irqrestore(&tctx->task_lock, flags);
2568 req = container_of(node, struct io_kiocb, io_task_work.node);
2570 if (llist_add(&req->io_task_work.fallback_node,
2571 &req->ctx->fallback_llist))
2572 schedule_delayed_work(&req->ctx->fallback_work, 1);
2576 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2578 struct io_ring_ctx *ctx = req->ctx;
2580 /* not needed for normal modes, but SQPOLL depends on it */
2581 io_tw_lock(ctx, locked);
2582 io_req_complete_failed(req, req->result);
2585 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2587 struct io_ring_ctx *ctx = req->ctx;
2589 io_tw_lock(ctx, locked);
2590 /* req->task == current here, checking PF_EXITING is safe */
2591 if (likely(!(req->task->flags & PF_EXITING)))
2592 __io_queue_sqe(req);
2594 io_req_complete_failed(req, -EFAULT);
2597 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2600 req->io_task_work.func = io_req_task_cancel;
2601 io_req_task_work_add(req, false);
2604 static void io_req_task_queue(struct io_kiocb *req)
2606 req->io_task_work.func = io_req_task_submit;
2607 io_req_task_work_add(req, false);
2610 static void io_req_task_queue_reissue(struct io_kiocb *req)
2612 req->io_task_work.func = io_queue_async_work;
2613 io_req_task_work_add(req, false);
2616 static inline void io_queue_next(struct io_kiocb *req)
2618 struct io_kiocb *nxt = io_req_find_next(req);
2621 io_req_task_queue(nxt);
2624 static void io_free_req(struct io_kiocb *req)
2630 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2635 static void io_free_batch_list(struct io_ring_ctx *ctx,
2636 struct io_wq_work_node *node)
2637 __must_hold(&ctx->uring_lock)
2639 struct task_struct *task = NULL;
2643 struct io_kiocb *req = container_of(node, struct io_kiocb,
2646 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2647 node = req->comp_list.next;
2648 if (!req_ref_put_and_test(req))
2652 io_req_put_rsrc_locked(req, ctx);
2654 io_dismantle_req(req);
2656 if (req->task != task) {
2658 io_put_task(task, task_refs);
2663 node = req->comp_list.next;
2664 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2668 io_put_task(task, task_refs);
2671 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2672 __must_hold(&ctx->uring_lock)
2674 struct io_wq_work_node *node, *prev;
2675 struct io_submit_state *state = &ctx->submit_state;
2677 if (state->flush_cqes) {
2678 spin_lock(&ctx->completion_lock);
2679 wq_list_for_each(node, prev, &state->compl_reqs) {
2680 struct io_kiocb *req = container_of(node, struct io_kiocb,
2683 if (!(req->flags & REQ_F_CQE_SKIP))
2684 __io_fill_cqe_req(req, req->result, req->cflags);
2685 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2686 struct async_poll *apoll = req->apoll;
2688 if (apoll->double_poll)
2689 kfree(apoll->double_poll);
2690 list_add(&apoll->poll.wait.entry,
2692 req->flags &= ~REQ_F_POLLED;
2696 io_commit_cqring(ctx);
2697 spin_unlock(&ctx->completion_lock);
2698 io_cqring_ev_posted(ctx);
2699 state->flush_cqes = false;
2702 io_free_batch_list(ctx, state->compl_reqs.first);
2703 INIT_WQ_LIST(&state->compl_reqs);
2707 * Drop reference to request, return next in chain (if there is one) if this
2708 * was the last reference to this request.
2710 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2712 struct io_kiocb *nxt = NULL;
2714 if (req_ref_put_and_test(req)) {
2715 nxt = io_req_find_next(req);
2721 static inline void io_put_req(struct io_kiocb *req)
2723 if (req_ref_put_and_test(req))
2727 static inline void io_put_req_deferred(struct io_kiocb *req)
2729 if (req_ref_put_and_test(req)) {
2730 req->io_task_work.func = io_free_req_work;
2731 io_req_task_work_add(req, false);
2735 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2737 /* See comment at the top of this file */
2739 return __io_cqring_events(ctx);
2742 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2744 struct io_rings *rings = ctx->rings;
2746 /* make sure SQ entry isn't read before tail */
2747 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2750 static inline bool io_run_task_work(void)
2752 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2753 __set_current_state(TASK_RUNNING);
2754 clear_notify_signal();
2755 if (task_work_pending(current))
2763 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2765 struct io_wq_work_node *pos, *start, *prev;
2766 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2767 DEFINE_IO_COMP_BATCH(iob);
2771 * Only spin for completions if we don't have multiple devices hanging
2772 * off our complete list.
2774 if (ctx->poll_multi_queue || force_nonspin)
2775 poll_flags |= BLK_POLL_ONESHOT;
2777 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2778 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2779 struct kiocb *kiocb = &req->rw.kiocb;
2783 * Move completed and retryable entries to our local lists.
2784 * If we find a request that requires polling, break out
2785 * and complete those lists first, if we have entries there.
2787 if (READ_ONCE(req->iopoll_completed))
2790 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2791 if (unlikely(ret < 0))
2794 poll_flags |= BLK_POLL_ONESHOT;
2796 /* iopoll may have completed current req */
2797 if (!rq_list_empty(iob.req_list) ||
2798 READ_ONCE(req->iopoll_completed))
2802 if (!rq_list_empty(iob.req_list))
2808 wq_list_for_each_resume(pos, prev) {
2809 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2811 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2812 if (!smp_load_acquire(&req->iopoll_completed))
2814 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2817 __io_fill_cqe_req(req, req->result, io_put_kbuf(req, 0));
2821 if (unlikely(!nr_events))
2824 io_commit_cqring(ctx);
2825 io_cqring_ev_posted_iopoll(ctx);
2826 pos = start ? start->next : ctx->iopoll_list.first;
2827 wq_list_cut(&ctx->iopoll_list, prev, start);
2828 io_free_batch_list(ctx, pos);
2833 * We can't just wait for polled events to come to us, we have to actively
2834 * find and complete them.
2836 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2838 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2841 mutex_lock(&ctx->uring_lock);
2842 while (!wq_list_empty(&ctx->iopoll_list)) {
2843 /* let it sleep and repeat later if can't complete a request */
2844 if (io_do_iopoll(ctx, true) == 0)
2847 * Ensure we allow local-to-the-cpu processing to take place,
2848 * in this case we need to ensure that we reap all events.
2849 * Also let task_work, etc. to progress by releasing the mutex
2851 if (need_resched()) {
2852 mutex_unlock(&ctx->uring_lock);
2854 mutex_lock(&ctx->uring_lock);
2857 mutex_unlock(&ctx->uring_lock);
2860 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2862 unsigned int nr_events = 0;
2866 * We disallow the app entering submit/complete with polling, but we
2867 * still need to lock the ring to prevent racing with polled issue
2868 * that got punted to a workqueue.
2870 mutex_lock(&ctx->uring_lock);
2872 * Don't enter poll loop if we already have events pending.
2873 * If we do, we can potentially be spinning for commands that
2874 * already triggered a CQE (eg in error).
2876 if (test_bit(0, &ctx->check_cq_overflow))
2877 __io_cqring_overflow_flush(ctx, false);
2878 if (io_cqring_events(ctx))
2882 * If a submit got punted to a workqueue, we can have the
2883 * application entering polling for a command before it gets
2884 * issued. That app will hold the uring_lock for the duration
2885 * of the poll right here, so we need to take a breather every
2886 * now and then to ensure that the issue has a chance to add
2887 * the poll to the issued list. Otherwise we can spin here
2888 * forever, while the workqueue is stuck trying to acquire the
2891 if (wq_list_empty(&ctx->iopoll_list)) {
2892 u32 tail = ctx->cached_cq_tail;
2894 mutex_unlock(&ctx->uring_lock);
2896 mutex_lock(&ctx->uring_lock);
2898 /* some requests don't go through iopoll_list */
2899 if (tail != ctx->cached_cq_tail ||
2900 wq_list_empty(&ctx->iopoll_list))
2903 ret = io_do_iopoll(ctx, !min);
2908 } while (nr_events < min && !need_resched());
2910 mutex_unlock(&ctx->uring_lock);
2914 static void kiocb_end_write(struct io_kiocb *req)
2917 * Tell lockdep we inherited freeze protection from submission
2920 if (req->flags & REQ_F_ISREG) {
2921 struct super_block *sb = file_inode(req->file)->i_sb;
2923 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2929 static bool io_resubmit_prep(struct io_kiocb *req)
2931 struct io_async_rw *rw = req->async_data;
2933 if (!req_has_async_data(req))
2934 return !io_req_prep_async(req);
2935 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2939 static bool io_rw_should_reissue(struct io_kiocb *req)
2941 umode_t mode = file_inode(req->file)->i_mode;
2942 struct io_ring_ctx *ctx = req->ctx;
2944 if (!S_ISBLK(mode) && !S_ISREG(mode))
2946 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2947 !(ctx->flags & IORING_SETUP_IOPOLL)))
2950 * If ref is dying, we might be running poll reap from the exit work.
2951 * Don't attempt to reissue from that path, just let it fail with
2954 if (percpu_ref_is_dying(&ctx->refs))
2957 * Play it safe and assume not safe to re-import and reissue if we're
2958 * not in the original thread group (or in task context).
2960 if (!same_thread_group(req->task, current) || !in_task())
2965 static bool io_resubmit_prep(struct io_kiocb *req)
2969 static bool io_rw_should_reissue(struct io_kiocb *req)
2975 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2977 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2978 kiocb_end_write(req);
2979 if (unlikely(res != req->result)) {
2980 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2981 io_rw_should_reissue(req)) {
2982 req->flags |= REQ_F_REISSUE;
2991 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2993 int res = req->result;
2996 io_req_complete_state(req, res, io_put_kbuf(req, 0));
2997 io_req_add_compl_list(req);
2999 io_req_complete_post(req, res,
3000 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3004 static void __io_complete_rw(struct io_kiocb *req, long res,
3005 unsigned int issue_flags)
3007 if (__io_complete_rw_common(req, res))
3009 __io_req_complete(req, issue_flags, req->result,
3010 io_put_kbuf(req, issue_flags));
3013 static void io_complete_rw(struct kiocb *kiocb, long res)
3015 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3017 if (__io_complete_rw_common(req, res))
3020 req->io_task_work.func = io_req_task_complete;
3021 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3024 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3026 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3028 if (kiocb->ki_flags & IOCB_WRITE)
3029 kiocb_end_write(req);
3030 if (unlikely(res != req->result)) {
3031 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3032 req->flags |= REQ_F_REISSUE;
3038 /* order with io_iopoll_complete() checking ->iopoll_completed */
3039 smp_store_release(&req->iopoll_completed, 1);
3043 * After the iocb has been issued, it's safe to be found on the poll list.
3044 * Adding the kiocb to the list AFTER submission ensures that we don't
3045 * find it from a io_do_iopoll() thread before the issuer is done
3046 * accessing the kiocb cookie.
3048 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3050 struct io_ring_ctx *ctx = req->ctx;
3051 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3053 /* workqueue context doesn't hold uring_lock, grab it now */
3054 if (unlikely(needs_lock))
3055 mutex_lock(&ctx->uring_lock);
3058 * Track whether we have multiple files in our lists. This will impact
3059 * how we do polling eventually, not spinning if we're on potentially
3060 * different devices.
3062 if (wq_list_empty(&ctx->iopoll_list)) {
3063 ctx->poll_multi_queue = false;
3064 } else if (!ctx->poll_multi_queue) {
3065 struct io_kiocb *list_req;
3067 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3069 if (list_req->file != req->file)
3070 ctx->poll_multi_queue = true;
3074 * For fast devices, IO may have already completed. If it has, add
3075 * it to the front so we find it first.
3077 if (READ_ONCE(req->iopoll_completed))
3078 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3080 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3082 if (unlikely(needs_lock)) {
3084 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3085 * in sq thread task context or in io worker task context. If
3086 * current task context is sq thread, we don't need to check
3087 * whether should wake up sq thread.
3089 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3090 wq_has_sleeper(&ctx->sq_data->wait))
3091 wake_up(&ctx->sq_data->wait);
3093 mutex_unlock(&ctx->uring_lock);
3097 static bool io_bdev_nowait(struct block_device *bdev)
3099 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3103 * If we tracked the file through the SCM inflight mechanism, we could support
3104 * any file. For now, just ensure that anything potentially problematic is done
3107 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3109 if (S_ISBLK(mode)) {
3110 if (IS_ENABLED(CONFIG_BLOCK) &&
3111 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3117 if (S_ISREG(mode)) {
3118 if (IS_ENABLED(CONFIG_BLOCK) &&
3119 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3120 file->f_op != &io_uring_fops)
3125 /* any ->read/write should understand O_NONBLOCK */
3126 if (file->f_flags & O_NONBLOCK)
3128 return file->f_mode & FMODE_NOWAIT;
3132 * If we tracked the file through the SCM inflight mechanism, we could support
3133 * any file. For now, just ensure that anything potentially problematic is done
3136 static unsigned int io_file_get_flags(struct file *file)
3138 umode_t mode = file_inode(file)->i_mode;
3139 unsigned int res = 0;
3143 if (__io_file_supports_nowait(file, mode))
3148 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3150 return req->flags & REQ_F_SUPPORT_NOWAIT;
3153 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3155 struct io_ring_ctx *ctx = req->ctx;
3156 struct kiocb *kiocb = &req->rw.kiocb;
3157 struct file *file = req->file;
3161 if (!io_req_ffs_set(req))
3162 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3164 kiocb->ki_pos = READ_ONCE(sqe->off);
3165 kiocb->ki_flags = iocb_flags(file);
3166 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3171 * If the file is marked O_NONBLOCK, still allow retry for it if it
3172 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3173 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3175 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3176 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3177 req->flags |= REQ_F_NOWAIT;
3179 if (ctx->flags & IORING_SETUP_IOPOLL) {
3180 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3183 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3184 kiocb->ki_complete = io_complete_rw_iopoll;
3185 req->iopoll_completed = 0;
3187 if (kiocb->ki_flags & IOCB_HIPRI)
3189 kiocb->ki_complete = io_complete_rw;
3192 ioprio = READ_ONCE(sqe->ioprio);
3194 ret = ioprio_check_cap(ioprio);
3198 kiocb->ki_ioprio = ioprio;
3200 kiocb->ki_ioprio = get_current_ioprio();
3204 req->rw.addr = READ_ONCE(sqe->addr);
3205 req->rw.len = READ_ONCE(sqe->len);
3206 req->buf_index = READ_ONCE(sqe->buf_index);
3210 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3216 case -ERESTARTNOINTR:
3217 case -ERESTARTNOHAND:
3218 case -ERESTART_RESTARTBLOCK:
3220 * We can't just restart the syscall, since previously
3221 * submitted sqes may already be in progress. Just fail this
3227 kiocb->ki_complete(kiocb, ret);
3231 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3233 struct kiocb *kiocb = &req->rw.kiocb;
3234 bool is_stream = req->file->f_mode & FMODE_STREAM;
3236 if (kiocb->ki_pos == -1) {
3238 req->flags |= REQ_F_CUR_POS;
3239 kiocb->ki_pos = req->file->f_pos;
3240 return &kiocb->ki_pos;
3246 return is_stream ? NULL : &kiocb->ki_pos;
3249 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3250 unsigned int issue_flags)
3252 struct io_async_rw *io = req->async_data;
3254 /* add previously done IO, if any */
3255 if (req_has_async_data(req) && io->bytes_done > 0) {
3257 ret = io->bytes_done;
3259 ret += io->bytes_done;
3262 if (req->flags & REQ_F_CUR_POS)
3263 req->file->f_pos = req->rw.kiocb.ki_pos;
3264 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3265 __io_complete_rw(req, ret, issue_flags);
3267 io_rw_done(&req->rw.kiocb, ret);
3269 if (req->flags & REQ_F_REISSUE) {
3270 req->flags &= ~REQ_F_REISSUE;
3271 if (io_resubmit_prep(req))
3272 io_req_task_queue_reissue(req);
3274 io_req_task_queue_fail(req, ret);
3278 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3279 struct io_mapped_ubuf *imu)
3281 size_t len = req->rw.len;
3282 u64 buf_end, buf_addr = req->rw.addr;
3285 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3287 /* not inside the mapped region */
3288 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3292 * May not be a start of buffer, set size appropriately
3293 * and advance us to the beginning.
3295 offset = buf_addr - imu->ubuf;
3296 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3300 * Don't use iov_iter_advance() here, as it's really slow for
3301 * using the latter parts of a big fixed buffer - it iterates
3302 * over each segment manually. We can cheat a bit here, because
3305 * 1) it's a BVEC iter, we set it up
3306 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3307 * first and last bvec
3309 * So just find our index, and adjust the iterator afterwards.
3310 * If the offset is within the first bvec (or the whole first
3311 * bvec, just use iov_iter_advance(). This makes it easier
3312 * since we can just skip the first segment, which may not
3313 * be PAGE_SIZE aligned.
3315 const struct bio_vec *bvec = imu->bvec;
3317 if (offset <= bvec->bv_len) {
3318 iov_iter_advance(iter, offset);
3320 unsigned long seg_skip;
3322 /* skip first vec */
3323 offset -= bvec->bv_len;
3324 seg_skip = 1 + (offset >> PAGE_SHIFT);
3326 iter->bvec = bvec + seg_skip;
3327 iter->nr_segs -= seg_skip;
3328 iter->count -= bvec->bv_len + offset;
3329 iter->iov_offset = offset & ~PAGE_MASK;
3336 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3338 struct io_mapped_ubuf *imu = req->imu;
3339 u16 index, buf_index = req->buf_index;
3342 struct io_ring_ctx *ctx = req->ctx;
3344 if (unlikely(buf_index >= ctx->nr_user_bufs))
3346 io_req_set_rsrc_node(req, ctx);
3347 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3348 imu = READ_ONCE(ctx->user_bufs[index]);
3351 return __io_import_fixed(req, rw, iter, imu);
3354 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3357 mutex_unlock(&ctx->uring_lock);
3360 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3363 * "Normal" inline submissions always hold the uring_lock, since we
3364 * grab it from the system call. Same is true for the SQPOLL offload.
3365 * The only exception is when we've detached the request and issue it
3366 * from an async worker thread, grab the lock for that case.
3369 mutex_lock(&ctx->uring_lock);
3372 static void io_buffer_add_list(struct io_ring_ctx *ctx,
3373 struct io_buffer_list *bl, unsigned int bgid)
3375 struct list_head *list;
3377 list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
3378 INIT_LIST_HEAD(&bl->buf_list);
3380 list_add(&bl->list, list);
3383 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3384 int bgid, unsigned int issue_flags)
3386 struct io_buffer *kbuf = req->kbuf;
3387 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3388 struct io_ring_ctx *ctx = req->ctx;
3389 struct io_buffer_list *bl;
3391 if (req->flags & REQ_F_BUFFER_SELECTED)
3394 io_ring_submit_lock(ctx, needs_lock);
3396 lockdep_assert_held(&ctx->uring_lock);
3398 bl = io_buffer_get_list(ctx, bgid);
3399 if (bl && !list_empty(&bl->buf_list)) {
3400 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3401 list_del(&kbuf->list);
3402 if (*len > kbuf->len)
3404 req->flags |= REQ_F_BUFFER_SELECTED;
3407 kbuf = ERR_PTR(-ENOBUFS);
3410 io_ring_submit_unlock(req->ctx, needs_lock);
3414 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3415 unsigned int issue_flags)
3417 struct io_buffer *kbuf;
3420 bgid = req->buf_index;
3421 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3424 return u64_to_user_ptr(kbuf->addr);
3427 #ifdef CONFIG_COMPAT
3428 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3429 unsigned int issue_flags)
3431 struct compat_iovec __user *uiov;
3432 compat_ssize_t clen;
3436 uiov = u64_to_user_ptr(req->rw.addr);
3437 if (!access_ok(uiov, sizeof(*uiov)))
3439 if (__get_user(clen, &uiov->iov_len))
3445 buf = io_rw_buffer_select(req, &len, issue_flags);
3447 return PTR_ERR(buf);
3448 iov[0].iov_base = buf;
3449 iov[0].iov_len = (compat_size_t) len;
3454 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3455 unsigned int issue_flags)
3457 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3461 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3464 len = iov[0].iov_len;
3467 buf = io_rw_buffer_select(req, &len, issue_flags);
3469 return PTR_ERR(buf);
3470 iov[0].iov_base = buf;
3471 iov[0].iov_len = len;
3475 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3476 unsigned int issue_flags)
3478 if (req->flags & REQ_F_BUFFER_SELECTED) {
3479 struct io_buffer *kbuf = req->kbuf;
3481 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3482 iov[0].iov_len = kbuf->len;
3485 if (req->rw.len != 1)
3488 #ifdef CONFIG_COMPAT
3489 if (req->ctx->compat)
3490 return io_compat_import(req, iov, issue_flags);
3493 return __io_iov_buffer_select(req, iov, issue_flags);
3496 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3497 struct io_rw_state *s,
3498 unsigned int issue_flags)
3500 struct iov_iter *iter = &s->iter;
3501 u8 opcode = req->opcode;
3502 struct iovec *iovec;
3507 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3508 ret = io_import_fixed(req, rw, iter);
3510 return ERR_PTR(ret);
3514 /* buffer index only valid with fixed read/write, or buffer select */
3515 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3516 return ERR_PTR(-EINVAL);
3518 buf = u64_to_user_ptr(req->rw.addr);
3519 sqe_len = req->rw.len;
3521 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3522 if (req->flags & REQ_F_BUFFER_SELECT) {
3523 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3525 return ERR_CAST(buf);
3526 req->rw.len = sqe_len;
3529 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3531 return ERR_PTR(ret);
3535 iovec = s->fast_iov;
3536 if (req->flags & REQ_F_BUFFER_SELECT) {
3537 ret = io_iov_buffer_select(req, iovec, issue_flags);
3539 return ERR_PTR(ret);
3540 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3544 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3546 if (unlikely(ret < 0))
3547 return ERR_PTR(ret);
3551 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3552 struct iovec **iovec, struct io_rw_state *s,
3553 unsigned int issue_flags)
3555 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3556 if (unlikely(IS_ERR(*iovec)))
3557 return PTR_ERR(*iovec);
3559 iov_iter_save_state(&s->iter, &s->iter_state);
3563 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3565 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3569 * For files that don't have ->read_iter() and ->write_iter(), handle them
3570 * by looping over ->read() or ->write() manually.
3572 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3574 struct kiocb *kiocb = &req->rw.kiocb;
3575 struct file *file = req->file;
3580 * Don't support polled IO through this interface, and we can't
3581 * support non-blocking either. For the latter, this just causes
3582 * the kiocb to be handled from an async context.
3584 if (kiocb->ki_flags & IOCB_HIPRI)
3586 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3587 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3590 ppos = io_kiocb_ppos(kiocb);
3592 while (iov_iter_count(iter)) {
3596 if (!iov_iter_is_bvec(iter)) {
3597 iovec = iov_iter_iovec(iter);
3599 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3600 iovec.iov_len = req->rw.len;
3604 nr = file->f_op->read(file, iovec.iov_base,
3605 iovec.iov_len, ppos);
3607 nr = file->f_op->write(file, iovec.iov_base,
3608 iovec.iov_len, ppos);
3617 if (!iov_iter_is_bvec(iter)) {
3618 iov_iter_advance(iter, nr);
3625 if (nr != iovec.iov_len)
3632 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3633 const struct iovec *fast_iov, struct iov_iter *iter)
3635 struct io_async_rw *rw = req->async_data;
3637 memcpy(&rw->s.iter, iter, sizeof(*iter));
3638 rw->free_iovec = iovec;
3640 /* can only be fixed buffers, no need to do anything */
3641 if (iov_iter_is_bvec(iter))
3644 unsigned iov_off = 0;
3646 rw->s.iter.iov = rw->s.fast_iov;
3647 if (iter->iov != fast_iov) {
3648 iov_off = iter->iov - fast_iov;
3649 rw->s.iter.iov += iov_off;
3651 if (rw->s.fast_iov != fast_iov)
3652 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3653 sizeof(struct iovec) * iter->nr_segs);
3655 req->flags |= REQ_F_NEED_CLEANUP;
3659 static inline bool io_alloc_async_data(struct io_kiocb *req)
3661 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3662 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3663 if (req->async_data) {
3664 req->flags |= REQ_F_ASYNC_DATA;
3670 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3671 struct io_rw_state *s, bool force)
3673 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3675 if (!req_has_async_data(req)) {
3676 struct io_async_rw *iorw;
3678 if (io_alloc_async_data(req)) {
3683 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3684 iorw = req->async_data;
3685 /* we've copied and mapped the iter, ensure state is saved */
3686 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3691 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3693 struct io_async_rw *iorw = req->async_data;
3697 /* submission path, ->uring_lock should already be taken */
3698 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3699 if (unlikely(ret < 0))
3702 iorw->bytes_done = 0;
3703 iorw->free_iovec = iov;
3705 req->flags |= REQ_F_NEED_CLEANUP;
3709 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3711 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3713 return io_prep_rw(req, sqe);
3717 * This is our waitqueue callback handler, registered through __folio_lock_async()
3718 * when we initially tried to do the IO with the iocb armed our waitqueue.
3719 * This gets called when the page is unlocked, and we generally expect that to
3720 * happen when the page IO is completed and the page is now uptodate. This will
3721 * queue a task_work based retry of the operation, attempting to copy the data
3722 * again. If the latter fails because the page was NOT uptodate, then we will
3723 * do a thread based blocking retry of the operation. That's the unexpected
3726 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3727 int sync, void *arg)
3729 struct wait_page_queue *wpq;
3730 struct io_kiocb *req = wait->private;
3731 struct wait_page_key *key = arg;
3733 wpq = container_of(wait, struct wait_page_queue, wait);
3735 if (!wake_page_match(wpq, key))
3738 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3739 list_del_init(&wait->entry);
3740 io_req_task_queue(req);
3745 * This controls whether a given IO request should be armed for async page
3746 * based retry. If we return false here, the request is handed to the async
3747 * worker threads for retry. If we're doing buffered reads on a regular file,
3748 * we prepare a private wait_page_queue entry and retry the operation. This
3749 * will either succeed because the page is now uptodate and unlocked, or it
3750 * will register a callback when the page is unlocked at IO completion. Through
3751 * that callback, io_uring uses task_work to setup a retry of the operation.
3752 * That retry will attempt the buffered read again. The retry will generally
3753 * succeed, or in rare cases where it fails, we then fall back to using the
3754 * async worker threads for a blocking retry.
3756 static bool io_rw_should_retry(struct io_kiocb *req)
3758 struct io_async_rw *rw = req->async_data;
3759 struct wait_page_queue *wait = &rw->wpq;
3760 struct kiocb *kiocb = &req->rw.kiocb;
3762 /* never retry for NOWAIT, we just complete with -EAGAIN */
3763 if (req->flags & REQ_F_NOWAIT)
3766 /* Only for buffered IO */
3767 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3771 * just use poll if we can, and don't attempt if the fs doesn't
3772 * support callback based unlocks
3774 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3777 wait->wait.func = io_async_buf_func;
3778 wait->wait.private = req;
3779 wait->wait.flags = 0;
3780 INIT_LIST_HEAD(&wait->wait.entry);
3781 kiocb->ki_flags |= IOCB_WAITQ;
3782 kiocb->ki_flags &= ~IOCB_NOWAIT;
3783 kiocb->ki_waitq = wait;
3787 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3789 if (likely(req->file->f_op->read_iter))
3790 return call_read_iter(req->file, &req->rw.kiocb, iter);
3791 else if (req->file->f_op->read)
3792 return loop_rw_iter(READ, req, iter);
3797 static bool need_read_all(struct io_kiocb *req)
3799 return req->flags & REQ_F_ISREG ||
3800 S_ISBLK(file_inode(req->file)->i_mode);
3803 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3805 struct io_rw_state __s, *s = &__s;
3806 struct iovec *iovec;
3807 struct kiocb *kiocb = &req->rw.kiocb;
3808 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3809 struct io_async_rw *rw;
3813 if (!req_has_async_data(req)) {
3814 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3815 if (unlikely(ret < 0))
3819 * Safe and required to re-import if we're using provided
3820 * buffers, as we dropped the selected one before retry.
3822 if (req->flags & REQ_F_BUFFER_SELECT) {
3823 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3824 if (unlikely(ret < 0))
3828 rw = req->async_data;
3831 * We come here from an earlier attempt, restore our state to
3832 * match in case it doesn't. It's cheap enough that we don't
3833 * need to make this conditional.
3835 iov_iter_restore(&s->iter, &s->iter_state);
3838 req->result = iov_iter_count(&s->iter);
3840 if (force_nonblock) {
3841 /* If the file doesn't support async, just async punt */
3842 if (unlikely(!io_file_supports_nowait(req))) {
3843 ret = io_setup_async_rw(req, iovec, s, true);
3844 return ret ?: -EAGAIN;
3846 kiocb->ki_flags |= IOCB_NOWAIT;
3848 /* Ensure we clear previously set non-block flag */
3849 kiocb->ki_flags &= ~IOCB_NOWAIT;
3852 ppos = io_kiocb_update_pos(req);
3854 ret = rw_verify_area(READ, req->file, ppos, req->result);
3855 if (unlikely(ret)) {
3860 ret = io_iter_do_read(req, &s->iter);
3862 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3863 req->flags &= ~REQ_F_REISSUE;
3864 /* if we can poll, just do that */
3865 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3867 /* IOPOLL retry should happen for io-wq threads */
3868 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3870 /* no retry on NONBLOCK nor RWF_NOWAIT */
3871 if (req->flags & REQ_F_NOWAIT)
3874 } else if (ret == -EIOCBQUEUED) {
3876 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3877 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3878 /* read all, failed, already did sync or don't want to retry */
3883 * Don't depend on the iter state matching what was consumed, or being
3884 * untouched in case of error. Restore it and we'll advance it
3885 * manually if we need to.
3887 iov_iter_restore(&s->iter, &s->iter_state);
3889 ret2 = io_setup_async_rw(req, iovec, s, true);
3894 rw = req->async_data;
3897 * Now use our persistent iterator and state, if we aren't already.
3898 * We've restored and mapped the iter to match.
3903 * We end up here because of a partial read, either from
3904 * above or inside this loop. Advance the iter by the bytes
3905 * that were consumed.
3907 iov_iter_advance(&s->iter, ret);
3908 if (!iov_iter_count(&s->iter))
3910 rw->bytes_done += ret;
3911 iov_iter_save_state(&s->iter, &s->iter_state);
3913 /* if we can retry, do so with the callbacks armed */
3914 if (!io_rw_should_retry(req)) {
3915 kiocb->ki_flags &= ~IOCB_WAITQ;
3920 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3921 * we get -EIOCBQUEUED, then we'll get a notification when the
3922 * desired page gets unlocked. We can also get a partial read
3923 * here, and if we do, then just retry at the new offset.
3925 ret = io_iter_do_read(req, &s->iter);
3926 if (ret == -EIOCBQUEUED)
3928 /* we got some bytes, but not all. retry. */
3929 kiocb->ki_flags &= ~IOCB_WAITQ;
3930 iov_iter_restore(&s->iter, &s->iter_state);
3933 kiocb_done(req, ret, issue_flags);
3935 /* it's faster to check here then delegate to kfree */
3941 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3943 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3945 return io_prep_rw(req, sqe);
3948 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3950 struct io_rw_state __s, *s = &__s;
3951 struct iovec *iovec;
3952 struct kiocb *kiocb = &req->rw.kiocb;
3953 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3957 if (!req_has_async_data(req)) {
3958 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3959 if (unlikely(ret < 0))
3962 struct io_async_rw *rw = req->async_data;
3965 iov_iter_restore(&s->iter, &s->iter_state);
3968 req->result = iov_iter_count(&s->iter);
3970 if (force_nonblock) {
3971 /* If the file doesn't support async, just async punt */
3972 if (unlikely(!io_file_supports_nowait(req)))
3975 /* file path doesn't support NOWAIT for non-direct_IO */
3976 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3977 (req->flags & REQ_F_ISREG))
3980 kiocb->ki_flags |= IOCB_NOWAIT;
3982 /* Ensure we clear previously set non-block flag */
3983 kiocb->ki_flags &= ~IOCB_NOWAIT;
3986 ppos = io_kiocb_update_pos(req);
3988 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3993 * Open-code file_start_write here to grab freeze protection,
3994 * which will be released by another thread in
3995 * io_complete_rw(). Fool lockdep by telling it the lock got
3996 * released so that it doesn't complain about the held lock when
3997 * we return to userspace.
3999 if (req->flags & REQ_F_ISREG) {
4000 sb_start_write(file_inode(req->file)->i_sb);
4001 __sb_writers_release(file_inode(req->file)->i_sb,
4004 kiocb->ki_flags |= IOCB_WRITE;
4006 if (likely(req->file->f_op->write_iter))
4007 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4008 else if (req->file->f_op->write)
4009 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4013 if (req->flags & REQ_F_REISSUE) {
4014 req->flags &= ~REQ_F_REISSUE;
4019 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4020 * retry them without IOCB_NOWAIT.
4022 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4024 /* no retry on NONBLOCK nor RWF_NOWAIT */
4025 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4027 if (!force_nonblock || ret2 != -EAGAIN) {
4028 /* IOPOLL retry should happen for io-wq threads */
4029 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4032 kiocb_done(req, ret2, issue_flags);
4035 iov_iter_restore(&s->iter, &s->iter_state);
4036 ret = io_setup_async_rw(req, iovec, s, false);
4037 return ret ?: -EAGAIN;
4040 /* it's reportedly faster than delegating the null check to kfree() */
4046 static int io_renameat_prep(struct io_kiocb *req,
4047 const struct io_uring_sqe *sqe)
4049 struct io_rename *ren = &req->rename;
4050 const char __user *oldf, *newf;
4052 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4054 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4056 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4059 ren->old_dfd = READ_ONCE(sqe->fd);
4060 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4061 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4062 ren->new_dfd = READ_ONCE(sqe->len);
4063 ren->flags = READ_ONCE(sqe->rename_flags);
4065 ren->oldpath = getname(oldf);
4066 if (IS_ERR(ren->oldpath))
4067 return PTR_ERR(ren->oldpath);
4069 ren->newpath = getname(newf);
4070 if (IS_ERR(ren->newpath)) {
4071 putname(ren->oldpath);
4072 return PTR_ERR(ren->newpath);
4075 req->flags |= REQ_F_NEED_CLEANUP;
4079 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4081 struct io_rename *ren = &req->rename;
4084 if (issue_flags & IO_URING_F_NONBLOCK)
4087 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4088 ren->newpath, ren->flags);
4090 req->flags &= ~REQ_F_NEED_CLEANUP;
4093 io_req_complete(req, ret);
4097 static int io_unlinkat_prep(struct io_kiocb *req,
4098 const struct io_uring_sqe *sqe)
4100 struct io_unlink *un = &req->unlink;
4101 const char __user *fname;
4103 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4105 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4108 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4111 un->dfd = READ_ONCE(sqe->fd);
4113 un->flags = READ_ONCE(sqe->unlink_flags);
4114 if (un->flags & ~AT_REMOVEDIR)
4117 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4118 un->filename = getname(fname);
4119 if (IS_ERR(un->filename))
4120 return PTR_ERR(un->filename);
4122 req->flags |= REQ_F_NEED_CLEANUP;
4126 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4128 struct io_unlink *un = &req->unlink;
4131 if (issue_flags & IO_URING_F_NONBLOCK)
4134 if (un->flags & AT_REMOVEDIR)
4135 ret = do_rmdir(un->dfd, un->filename);
4137 ret = do_unlinkat(un->dfd, un->filename);
4139 req->flags &= ~REQ_F_NEED_CLEANUP;
4142 io_req_complete(req, ret);
4146 static int io_mkdirat_prep(struct io_kiocb *req,
4147 const struct io_uring_sqe *sqe)
4149 struct io_mkdir *mkd = &req->mkdir;
4150 const char __user *fname;
4152 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4154 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4157 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4160 mkd->dfd = READ_ONCE(sqe->fd);
4161 mkd->mode = READ_ONCE(sqe->len);
4163 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4164 mkd->filename = getname(fname);
4165 if (IS_ERR(mkd->filename))
4166 return PTR_ERR(mkd->filename);
4168 req->flags |= REQ_F_NEED_CLEANUP;
4172 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4174 struct io_mkdir *mkd = &req->mkdir;
4177 if (issue_flags & IO_URING_F_NONBLOCK)
4180 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4182 req->flags &= ~REQ_F_NEED_CLEANUP;
4185 io_req_complete(req, ret);
4189 static int io_symlinkat_prep(struct io_kiocb *req,
4190 const struct io_uring_sqe *sqe)
4192 struct io_symlink *sl = &req->symlink;
4193 const char __user *oldpath, *newpath;
4195 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4197 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4200 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4203 sl->new_dfd = READ_ONCE(sqe->fd);
4204 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4205 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4207 sl->oldpath = getname(oldpath);
4208 if (IS_ERR(sl->oldpath))
4209 return PTR_ERR(sl->oldpath);
4211 sl->newpath = getname(newpath);
4212 if (IS_ERR(sl->newpath)) {
4213 putname(sl->oldpath);
4214 return PTR_ERR(sl->newpath);
4217 req->flags |= REQ_F_NEED_CLEANUP;
4221 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4223 struct io_symlink *sl = &req->symlink;
4226 if (issue_flags & IO_URING_F_NONBLOCK)
4229 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4231 req->flags &= ~REQ_F_NEED_CLEANUP;
4234 io_req_complete(req, ret);
4238 static int io_linkat_prep(struct io_kiocb *req,
4239 const struct io_uring_sqe *sqe)
4241 struct io_hardlink *lnk = &req->hardlink;
4242 const char __user *oldf, *newf;
4244 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4246 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4248 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4251 lnk->old_dfd = READ_ONCE(sqe->fd);
4252 lnk->new_dfd = READ_ONCE(sqe->len);
4253 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4254 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4255 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4257 lnk->oldpath = getname(oldf);
4258 if (IS_ERR(lnk->oldpath))
4259 return PTR_ERR(lnk->oldpath);
4261 lnk->newpath = getname(newf);
4262 if (IS_ERR(lnk->newpath)) {
4263 putname(lnk->oldpath);
4264 return PTR_ERR(lnk->newpath);
4267 req->flags |= REQ_F_NEED_CLEANUP;
4271 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4273 struct io_hardlink *lnk = &req->hardlink;
4276 if (issue_flags & IO_URING_F_NONBLOCK)
4279 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4280 lnk->newpath, lnk->flags);
4282 req->flags &= ~REQ_F_NEED_CLEANUP;
4285 io_req_complete(req, ret);
4289 static int io_shutdown_prep(struct io_kiocb *req,
4290 const struct io_uring_sqe *sqe)
4292 #if defined(CONFIG_NET)
4293 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4295 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4296 sqe->buf_index || sqe->splice_fd_in))
4299 req->shutdown.how = READ_ONCE(sqe->len);
4306 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4308 #if defined(CONFIG_NET)
4309 struct socket *sock;
4312 if (issue_flags & IO_URING_F_NONBLOCK)
4315 sock = sock_from_file(req->file);
4316 if (unlikely(!sock))
4319 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4322 io_req_complete(req, ret);
4329 static int __io_splice_prep(struct io_kiocb *req,
4330 const struct io_uring_sqe *sqe)
4332 struct io_splice *sp = &req->splice;
4333 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4335 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4339 sp->len = READ_ONCE(sqe->len);
4340 sp->flags = READ_ONCE(sqe->splice_flags);
4342 if (unlikely(sp->flags & ~valid_flags))
4345 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
4346 (sp->flags & SPLICE_F_FD_IN_FIXED));
4349 req->flags |= REQ_F_NEED_CLEANUP;
4353 static int io_tee_prep(struct io_kiocb *req,
4354 const struct io_uring_sqe *sqe)
4356 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4358 return __io_splice_prep(req, sqe);
4361 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4363 struct io_splice *sp = &req->splice;
4364 struct file *in = sp->file_in;
4365 struct file *out = sp->file_out;
4366 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4369 if (issue_flags & IO_URING_F_NONBLOCK)
4372 ret = do_tee(in, out, sp->len, flags);
4374 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4376 req->flags &= ~REQ_F_NEED_CLEANUP;
4380 io_req_complete(req, ret);
4384 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4386 struct io_splice *sp = &req->splice;
4388 sp->off_in = READ_ONCE(sqe->splice_off_in);
4389 sp->off_out = READ_ONCE(sqe->off);
4390 return __io_splice_prep(req, sqe);
4393 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4395 struct io_splice *sp = &req->splice;
4396 struct file *in = sp->file_in;
4397 struct file *out = sp->file_out;
4398 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4399 loff_t *poff_in, *poff_out;
4402 if (issue_flags & IO_URING_F_NONBLOCK)
4405 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4406 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4409 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4411 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4413 req->flags &= ~REQ_F_NEED_CLEANUP;
4417 io_req_complete(req, ret);
4422 * IORING_OP_NOP just posts a completion event, nothing else.
4424 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4426 struct io_ring_ctx *ctx = req->ctx;
4428 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4431 __io_req_complete(req, issue_flags, 0, 0);
4435 static int io_msg_ring_prep(struct io_kiocb *req,
4436 const struct io_uring_sqe *sqe)
4438 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4439 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4442 if (req->file->f_op != &io_uring_fops)
4445 req->msg.user_data = READ_ONCE(sqe->off);
4446 req->msg.len = READ_ONCE(sqe->len);
4450 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4452 struct io_ring_ctx *target_ctx;
4453 struct io_msg *msg = &req->msg;
4454 int ret = -EOVERFLOW;
4457 target_ctx = req->file->private_data;
4459 spin_lock(&target_ctx->completion_lock);
4460 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len,
4462 io_commit_cqring(target_ctx);
4463 spin_unlock(&target_ctx->completion_lock);
4466 io_cqring_ev_posted(target_ctx);
4470 __io_req_complete(req, issue_flags, ret, 0);
4474 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4476 struct io_ring_ctx *ctx = req->ctx;
4481 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4483 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4487 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4488 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4491 req->sync.off = READ_ONCE(sqe->off);
4492 req->sync.len = READ_ONCE(sqe->len);
4496 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4498 loff_t end = req->sync.off + req->sync.len;
4501 /* fsync always requires a blocking context */
4502 if (issue_flags & IO_URING_F_NONBLOCK)
4505 ret = vfs_fsync_range(req->file, req->sync.off,
4506 end > 0 ? end : LLONG_MAX,
4507 req->sync.flags & IORING_FSYNC_DATASYNC);
4510 io_req_complete(req, ret);
4514 static int io_fallocate_prep(struct io_kiocb *req,
4515 const struct io_uring_sqe *sqe)
4517 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4520 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4523 req->sync.off = READ_ONCE(sqe->off);
4524 req->sync.len = READ_ONCE(sqe->addr);
4525 req->sync.mode = READ_ONCE(sqe->len);
4529 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4533 /* fallocate always requiring blocking context */
4534 if (issue_flags & IO_URING_F_NONBLOCK)
4536 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4540 io_req_complete(req, ret);
4544 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4546 const char __user *fname;
4549 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4551 if (unlikely(sqe->ioprio || sqe->buf_index))
4553 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4556 /* open.how should be already initialised */
4557 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4558 req->open.how.flags |= O_LARGEFILE;
4560 req->open.dfd = READ_ONCE(sqe->fd);
4561 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4562 req->open.filename = getname(fname);
4563 if (IS_ERR(req->open.filename)) {
4564 ret = PTR_ERR(req->open.filename);
4565 req->open.filename = NULL;
4569 req->open.file_slot = READ_ONCE(sqe->file_index);
4570 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4573 req->open.nofile = rlimit(RLIMIT_NOFILE);
4574 req->flags |= REQ_F_NEED_CLEANUP;
4578 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4580 u64 mode = READ_ONCE(sqe->len);
4581 u64 flags = READ_ONCE(sqe->open_flags);
4583 req->open.how = build_open_how(flags, mode);
4584 return __io_openat_prep(req, sqe);
4587 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4589 struct open_how __user *how;
4593 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4594 len = READ_ONCE(sqe->len);
4595 if (len < OPEN_HOW_SIZE_VER0)
4598 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4603 return __io_openat_prep(req, sqe);
4606 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4608 struct open_flags op;
4610 bool resolve_nonblock, nonblock_set;
4611 bool fixed = !!req->open.file_slot;
4614 ret = build_open_flags(&req->open.how, &op);
4617 nonblock_set = op.open_flag & O_NONBLOCK;
4618 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4619 if (issue_flags & IO_URING_F_NONBLOCK) {
4621 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4622 * it'll always -EAGAIN
4624 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4626 op.lookup_flags |= LOOKUP_CACHED;
4627 op.open_flag |= O_NONBLOCK;
4631 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4636 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4639 * We could hang on to this 'fd' on retrying, but seems like
4640 * marginal gain for something that is now known to be a slower
4641 * path. So just put it, and we'll get a new one when we retry.
4646 ret = PTR_ERR(file);
4647 /* only retry if RESOLVE_CACHED wasn't already set by application */
4648 if (ret == -EAGAIN &&
4649 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4654 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4655 file->f_flags &= ~O_NONBLOCK;
4656 fsnotify_open(file);
4659 fd_install(ret, file);
4661 ret = io_install_fixed_file(req, file, issue_flags,
4662 req->open.file_slot - 1);
4664 putname(req->open.filename);
4665 req->flags &= ~REQ_F_NEED_CLEANUP;
4668 __io_req_complete(req, issue_flags, ret, 0);
4672 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4674 return io_openat2(req, issue_flags);
4677 static int io_remove_buffers_prep(struct io_kiocb *req,
4678 const struct io_uring_sqe *sqe)
4680 struct io_provide_buf *p = &req->pbuf;
4683 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4687 tmp = READ_ONCE(sqe->fd);
4688 if (!tmp || tmp > USHRT_MAX)
4691 memset(p, 0, sizeof(*p));
4693 p->bgid = READ_ONCE(sqe->buf_group);
4697 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4698 struct io_buffer_list *bl, unsigned nbufs)
4702 /* shouldn't happen */
4706 /* the head kbuf is the list itself */
4707 while (!list_empty(&bl->buf_list)) {
4708 struct io_buffer *nxt;
4710 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4711 list_del(&nxt->list);
4721 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4723 struct io_provide_buf *p = &req->pbuf;
4724 struct io_ring_ctx *ctx = req->ctx;
4725 struct io_buffer_list *bl;
4727 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4729 io_ring_submit_lock(ctx, needs_lock);
4731 lockdep_assert_held(&ctx->uring_lock);
4734 bl = io_buffer_get_list(ctx, p->bgid);
4736 ret = __io_remove_buffers(ctx, bl, p->nbufs);
4740 /* complete before unlock, IOPOLL may need the lock */
4741 __io_req_complete(req, issue_flags, ret, 0);
4742 io_ring_submit_unlock(ctx, needs_lock);
4746 static int io_provide_buffers_prep(struct io_kiocb *req,
4747 const struct io_uring_sqe *sqe)
4749 unsigned long size, tmp_check;
4750 struct io_provide_buf *p = &req->pbuf;
4753 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4756 tmp = READ_ONCE(sqe->fd);
4757 if (!tmp || tmp > USHRT_MAX)
4760 p->addr = READ_ONCE(sqe->addr);
4761 p->len = READ_ONCE(sqe->len);
4763 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4766 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4769 size = (unsigned long)p->len * p->nbufs;
4770 if (!access_ok(u64_to_user_ptr(p->addr), size))
4773 p->bgid = READ_ONCE(sqe->buf_group);
4774 tmp = READ_ONCE(sqe->off);
4775 if (tmp > USHRT_MAX)
4781 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4783 struct io_buffer *buf;
4788 * Completions that don't happen inline (eg not under uring_lock) will
4789 * add to ->io_buffers_comp. If we don't have any free buffers, check
4790 * the completion list and splice those entries first.
4792 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4793 spin_lock(&ctx->completion_lock);
4794 if (!list_empty(&ctx->io_buffers_comp)) {
4795 list_splice_init(&ctx->io_buffers_comp,
4796 &ctx->io_buffers_cache);
4797 spin_unlock(&ctx->completion_lock);
4800 spin_unlock(&ctx->completion_lock);
4804 * No free buffers and no completion entries either. Allocate a new
4805 * page worth of buffer entries and add those to our freelist.
4807 page = alloc_page(GFP_KERNEL_ACCOUNT);
4811 list_add(&page->lru, &ctx->io_buffers_pages);
4813 buf = page_address(page);
4814 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4815 while (bufs_in_page) {
4816 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4824 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4825 struct io_buffer_list *bl)
4827 struct io_buffer *buf;
4828 u64 addr = pbuf->addr;
4829 int i, bid = pbuf->bid;
4831 for (i = 0; i < pbuf->nbufs; i++) {
4832 if (list_empty(&ctx->io_buffers_cache) &&
4833 io_refill_buffer_cache(ctx))
4835 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4837 list_move_tail(&buf->list, &bl->buf_list);
4839 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4841 buf->bgid = pbuf->bgid;
4847 return i ? 0 : -ENOMEM;
4850 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4852 struct io_provide_buf *p = &req->pbuf;
4853 struct io_ring_ctx *ctx = req->ctx;
4854 struct io_buffer_list *bl;
4856 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4858 io_ring_submit_lock(ctx, needs_lock);
4860 lockdep_assert_held(&ctx->uring_lock);
4862 bl = io_buffer_get_list(ctx, p->bgid);
4863 if (unlikely(!bl)) {
4864 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
4869 io_buffer_add_list(ctx, bl, p->bgid);
4872 ret = io_add_buffers(ctx, p, bl);
4876 /* complete before unlock, IOPOLL may need the lock */
4877 __io_req_complete(req, issue_flags, ret, 0);
4878 io_ring_submit_unlock(ctx, needs_lock);
4882 static int io_epoll_ctl_prep(struct io_kiocb *req,
4883 const struct io_uring_sqe *sqe)
4885 #if defined(CONFIG_EPOLL)
4886 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4888 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4891 req->epoll.epfd = READ_ONCE(sqe->fd);
4892 req->epoll.op = READ_ONCE(sqe->len);
4893 req->epoll.fd = READ_ONCE(sqe->off);
4895 if (ep_op_has_event(req->epoll.op)) {
4896 struct epoll_event __user *ev;
4898 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4899 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4909 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4911 #if defined(CONFIG_EPOLL)
4912 struct io_epoll *ie = &req->epoll;
4914 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4916 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4917 if (force_nonblock && ret == -EAGAIN)
4922 __io_req_complete(req, issue_flags, ret, 0);
4929 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4931 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4932 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4934 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4937 req->madvise.addr = READ_ONCE(sqe->addr);
4938 req->madvise.len = READ_ONCE(sqe->len);
4939 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4946 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4948 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4949 struct io_madvise *ma = &req->madvise;
4952 if (issue_flags & IO_URING_F_NONBLOCK)
4955 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4958 io_req_complete(req, ret);
4965 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4967 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4969 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4972 req->fadvise.offset = READ_ONCE(sqe->off);
4973 req->fadvise.len = READ_ONCE(sqe->len);
4974 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4978 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4980 struct io_fadvise *fa = &req->fadvise;
4983 if (issue_flags & IO_URING_F_NONBLOCK) {
4984 switch (fa->advice) {
4985 case POSIX_FADV_NORMAL:
4986 case POSIX_FADV_RANDOM:
4987 case POSIX_FADV_SEQUENTIAL:
4994 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4997 __io_req_complete(req, issue_flags, ret, 0);
5001 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5003 const char __user *path;
5005 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5007 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5009 if (req->flags & REQ_F_FIXED_FILE)
5012 req->statx.dfd = READ_ONCE(sqe->fd);
5013 req->statx.mask = READ_ONCE(sqe->len);
5014 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5015 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5016 req->statx.flags = READ_ONCE(sqe->statx_flags);
5018 req->statx.filename = getname_flags(path,
5019 getname_statx_lookup_flags(req->statx.flags),
5022 if (IS_ERR(req->statx.filename)) {
5023 int ret = PTR_ERR(req->statx.filename);
5025 req->statx.filename = NULL;
5029 req->flags |= REQ_F_NEED_CLEANUP;
5033 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5035 struct io_statx *ctx = &req->statx;
5038 if (issue_flags & IO_URING_F_NONBLOCK)
5041 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5046 io_req_complete(req, ret);
5050 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5052 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5054 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
5055 sqe->rw_flags || sqe->buf_index)
5057 if (req->flags & REQ_F_FIXED_FILE)
5060 req->close.fd = READ_ONCE(sqe->fd);
5061 req->close.file_slot = READ_ONCE(sqe->file_index);
5062 if (req->close.file_slot && req->close.fd)
5068 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5070 struct files_struct *files = current->files;
5071 struct io_close *close = &req->close;
5072 struct fdtable *fdt;
5073 struct file *file = NULL;
5076 if (req->close.file_slot) {
5077 ret = io_close_fixed(req, issue_flags);
5081 spin_lock(&files->file_lock);
5082 fdt = files_fdtable(files);
5083 if (close->fd >= fdt->max_fds) {
5084 spin_unlock(&files->file_lock);
5087 file = fdt->fd[close->fd];
5088 if (!file || file->f_op == &io_uring_fops) {
5089 spin_unlock(&files->file_lock);
5094 /* if the file has a flush method, be safe and punt to async */
5095 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5096 spin_unlock(&files->file_lock);
5100 ret = __close_fd_get_file(close->fd, &file);
5101 spin_unlock(&files->file_lock);
5108 /* No ->flush() or already async, safely close from here */
5109 ret = filp_close(file, current->files);
5115 __io_req_complete(req, issue_flags, ret, 0);
5119 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5121 struct io_ring_ctx *ctx = req->ctx;
5123 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5125 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5129 req->sync.off = READ_ONCE(sqe->off);
5130 req->sync.len = READ_ONCE(sqe->len);
5131 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5135 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5139 /* sync_file_range always requires a blocking context */
5140 if (issue_flags & IO_URING_F_NONBLOCK)
5143 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5147 io_req_complete(req, ret);
5151 #if defined(CONFIG_NET)
5152 static int io_setup_async_msg(struct io_kiocb *req,
5153 struct io_async_msghdr *kmsg)
5155 struct io_async_msghdr *async_msg = req->async_data;
5159 if (io_alloc_async_data(req)) {
5160 kfree(kmsg->free_iov);
5163 async_msg = req->async_data;
5164 req->flags |= REQ_F_NEED_CLEANUP;
5165 memcpy(async_msg, kmsg, sizeof(*kmsg));
5166 async_msg->msg.msg_name = &async_msg->addr;
5167 /* if were using fast_iov, set it to the new one */
5168 if (!async_msg->free_iov)
5169 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5174 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5175 struct io_async_msghdr *iomsg)
5177 iomsg->msg.msg_name = &iomsg->addr;
5178 iomsg->free_iov = iomsg->fast_iov;
5179 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5180 req->sr_msg.msg_flags, &iomsg->free_iov);
5183 static int io_sendmsg_prep_async(struct io_kiocb *req)
5187 ret = io_sendmsg_copy_hdr(req, req->async_data);
5189 req->flags |= REQ_F_NEED_CLEANUP;
5193 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5195 struct io_sr_msg *sr = &req->sr_msg;
5197 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5200 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5201 sr->len = READ_ONCE(sqe->len);
5202 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5203 if (sr->msg_flags & MSG_DONTWAIT)
5204 req->flags |= REQ_F_NOWAIT;
5206 #ifdef CONFIG_COMPAT
5207 if (req->ctx->compat)
5208 sr->msg_flags |= MSG_CMSG_COMPAT;
5213 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5215 struct io_async_msghdr iomsg, *kmsg;
5216 struct socket *sock;
5221 sock = sock_from_file(req->file);
5222 if (unlikely(!sock))
5225 if (req_has_async_data(req)) {
5226 kmsg = req->async_data;
5228 ret = io_sendmsg_copy_hdr(req, &iomsg);
5234 flags = req->sr_msg.msg_flags;
5235 if (issue_flags & IO_URING_F_NONBLOCK)
5236 flags |= MSG_DONTWAIT;
5237 if (flags & MSG_WAITALL)
5238 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5240 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5242 if (ret < min_ret) {
5243 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5244 return io_setup_async_msg(req, kmsg);
5245 if (ret == -ERESTARTSYS)
5249 /* fast path, check for non-NULL to avoid function call */
5251 kfree(kmsg->free_iov);
5252 req->flags &= ~REQ_F_NEED_CLEANUP;
5253 __io_req_complete(req, issue_flags, ret, 0);
5257 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5259 struct io_sr_msg *sr = &req->sr_msg;
5262 struct socket *sock;
5267 sock = sock_from_file(req->file);
5268 if (unlikely(!sock))
5271 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5275 msg.msg_name = NULL;
5276 msg.msg_control = NULL;
5277 msg.msg_controllen = 0;
5278 msg.msg_namelen = 0;
5280 flags = req->sr_msg.msg_flags;
5281 if (issue_flags & IO_URING_F_NONBLOCK)
5282 flags |= MSG_DONTWAIT;
5283 if (flags & MSG_WAITALL)
5284 min_ret = iov_iter_count(&msg.msg_iter);
5286 msg.msg_flags = flags;
5287 ret = sock_sendmsg(sock, &msg);
5288 if (ret < min_ret) {
5289 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5291 if (ret == -ERESTARTSYS)
5295 __io_req_complete(req, issue_flags, ret, 0);
5299 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5300 struct io_async_msghdr *iomsg)
5302 struct io_sr_msg *sr = &req->sr_msg;
5303 struct iovec __user *uiov;
5307 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5308 &iomsg->uaddr, &uiov, &iov_len);
5312 if (req->flags & REQ_F_BUFFER_SELECT) {
5315 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5317 sr->len = iomsg->fast_iov[0].iov_len;
5318 iomsg->free_iov = NULL;
5320 iomsg->free_iov = iomsg->fast_iov;
5321 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5322 &iomsg->free_iov, &iomsg->msg.msg_iter,
5331 #ifdef CONFIG_COMPAT
5332 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5333 struct io_async_msghdr *iomsg)
5335 struct io_sr_msg *sr = &req->sr_msg;
5336 struct compat_iovec __user *uiov;
5341 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5346 uiov = compat_ptr(ptr);
5347 if (req->flags & REQ_F_BUFFER_SELECT) {
5348 compat_ssize_t clen;
5352 if (!access_ok(uiov, sizeof(*uiov)))
5354 if (__get_user(clen, &uiov->iov_len))
5359 iomsg->free_iov = NULL;
5361 iomsg->free_iov = iomsg->fast_iov;
5362 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5363 UIO_FASTIOV, &iomsg->free_iov,
5364 &iomsg->msg.msg_iter, true);
5373 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5374 struct io_async_msghdr *iomsg)
5376 iomsg->msg.msg_name = &iomsg->addr;
5378 #ifdef CONFIG_COMPAT
5379 if (req->ctx->compat)
5380 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5383 return __io_recvmsg_copy_hdr(req, iomsg);
5386 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5387 unsigned int issue_flags)
5389 struct io_sr_msg *sr = &req->sr_msg;
5391 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5394 static int io_recvmsg_prep_async(struct io_kiocb *req)
5398 ret = io_recvmsg_copy_hdr(req, req->async_data);
5400 req->flags |= REQ_F_NEED_CLEANUP;
5404 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5406 struct io_sr_msg *sr = &req->sr_msg;
5408 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5411 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5412 sr->len = READ_ONCE(sqe->len);
5413 sr->bgid = READ_ONCE(sqe->buf_group);
5414 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5415 if (sr->msg_flags & MSG_DONTWAIT)
5416 req->flags |= REQ_F_NOWAIT;
5418 #ifdef CONFIG_COMPAT
5419 if (req->ctx->compat)
5420 sr->msg_flags |= MSG_CMSG_COMPAT;
5425 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5427 struct io_async_msghdr iomsg, *kmsg;
5428 struct socket *sock;
5429 struct io_buffer *kbuf;
5431 int ret, min_ret = 0;
5432 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5434 sock = sock_from_file(req->file);
5435 if (unlikely(!sock))
5438 if (req_has_async_data(req)) {
5439 kmsg = req->async_data;
5441 ret = io_recvmsg_copy_hdr(req, &iomsg);
5447 if (req->flags & REQ_F_BUFFER_SELECT) {
5448 kbuf = io_recv_buffer_select(req, issue_flags);
5450 return PTR_ERR(kbuf);
5451 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5452 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5453 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5454 1, req->sr_msg.len);
5457 flags = req->sr_msg.msg_flags;
5459 flags |= MSG_DONTWAIT;
5460 if (flags & MSG_WAITALL)
5461 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5463 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5464 kmsg->uaddr, flags);
5465 if (ret < min_ret) {
5466 if (ret == -EAGAIN && force_nonblock)
5467 return io_setup_async_msg(req, kmsg);
5468 if (ret == -ERESTARTSYS)
5471 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5475 /* fast path, check for non-NULL to avoid function call */
5477 kfree(kmsg->free_iov);
5478 req->flags &= ~REQ_F_NEED_CLEANUP;
5479 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5483 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5485 struct io_buffer *kbuf;
5486 struct io_sr_msg *sr = &req->sr_msg;
5488 void __user *buf = sr->buf;
5489 struct socket *sock;
5492 int ret, min_ret = 0;
5493 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5495 sock = sock_from_file(req->file);
5496 if (unlikely(!sock))
5499 if (req->flags & REQ_F_BUFFER_SELECT) {
5500 kbuf = io_recv_buffer_select(req, issue_flags);
5502 return PTR_ERR(kbuf);
5503 buf = u64_to_user_ptr(kbuf->addr);
5506 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5510 msg.msg_name = NULL;
5511 msg.msg_control = NULL;
5512 msg.msg_controllen = 0;
5513 msg.msg_namelen = 0;
5514 msg.msg_iocb = NULL;
5517 flags = req->sr_msg.msg_flags;
5519 flags |= MSG_DONTWAIT;
5520 if (flags & MSG_WAITALL)
5521 min_ret = iov_iter_count(&msg.msg_iter);
5523 ret = sock_recvmsg(sock, &msg, flags);
5524 if (ret < min_ret) {
5525 if (ret == -EAGAIN && force_nonblock)
5527 if (ret == -ERESTARTSYS)
5530 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5535 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5539 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5541 struct io_accept *accept = &req->accept;
5543 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5545 if (sqe->ioprio || sqe->len || sqe->buf_index)
5548 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5549 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5550 accept->flags = READ_ONCE(sqe->accept_flags);
5551 accept->nofile = rlimit(RLIMIT_NOFILE);
5553 accept->file_slot = READ_ONCE(sqe->file_index);
5554 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5556 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5558 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5559 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5563 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5565 struct io_accept *accept = &req->accept;
5566 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5567 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5568 bool fixed = !!accept->file_slot;
5572 if (req->file->f_flags & O_NONBLOCK)
5573 req->flags |= REQ_F_NOWAIT;
5576 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5577 if (unlikely(fd < 0))
5580 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5585 ret = PTR_ERR(file);
5586 if (ret == -EAGAIN && force_nonblock)
5588 if (ret == -ERESTARTSYS)
5591 } else if (!fixed) {
5592 fd_install(fd, file);
5595 ret = io_install_fixed_file(req, file, issue_flags,
5596 accept->file_slot - 1);
5598 __io_req_complete(req, issue_flags, ret, 0);
5602 static int io_connect_prep_async(struct io_kiocb *req)
5604 struct io_async_connect *io = req->async_data;
5605 struct io_connect *conn = &req->connect;
5607 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5610 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5612 struct io_connect *conn = &req->connect;
5614 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5616 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5620 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5621 conn->addr_len = READ_ONCE(sqe->addr2);
5625 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5627 struct io_async_connect __io, *io;
5628 unsigned file_flags;
5630 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5632 if (req_has_async_data(req)) {
5633 io = req->async_data;
5635 ret = move_addr_to_kernel(req->connect.addr,
5636 req->connect.addr_len,
5643 file_flags = force_nonblock ? O_NONBLOCK : 0;
5645 ret = __sys_connect_file(req->file, &io->address,
5646 req->connect.addr_len, file_flags);
5647 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5648 if (req_has_async_data(req))
5650 if (io_alloc_async_data(req)) {
5654 memcpy(req->async_data, &__io, sizeof(__io));
5657 if (ret == -ERESTARTSYS)
5662 __io_req_complete(req, issue_flags, ret, 0);
5665 #else /* !CONFIG_NET */
5666 #define IO_NETOP_FN(op) \
5667 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5669 return -EOPNOTSUPP; \
5672 #define IO_NETOP_PREP(op) \
5674 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5676 return -EOPNOTSUPP; \
5679 #define IO_NETOP_PREP_ASYNC(op) \
5681 static int io_##op##_prep_async(struct io_kiocb *req) \
5683 return -EOPNOTSUPP; \
5686 IO_NETOP_PREP_ASYNC(sendmsg);
5687 IO_NETOP_PREP_ASYNC(recvmsg);
5688 IO_NETOP_PREP_ASYNC(connect);
5689 IO_NETOP_PREP(accept);
5692 #endif /* CONFIG_NET */
5694 #ifdef CONFIG_NET_RX_BUSY_POLL
5696 #define NAPI_TIMEOUT (60 * SEC_CONVERSION)
5699 struct list_head list;
5700 unsigned int napi_id;
5701 unsigned long timeout;
5705 * Add busy poll NAPI ID from sk.
5707 static void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5709 unsigned int napi_id;
5710 struct socket *sock;
5712 struct napi_entry *ne;
5714 if (!net_busy_loop_on())
5717 sock = sock_from_file(file);
5725 napi_id = READ_ONCE(sk->sk_napi_id);
5727 /* Non-NAPI IDs can be rejected */
5728 if (napi_id < MIN_NAPI_ID)
5731 spin_lock(&ctx->napi_lock);
5732 list_for_each_entry(ne, &ctx->napi_list, list) {
5733 if (ne->napi_id == napi_id) {
5734 ne->timeout = jiffies + NAPI_TIMEOUT;
5739 ne = kmalloc(sizeof(*ne), GFP_NOWAIT);
5743 ne->napi_id = napi_id;
5744 ne->timeout = jiffies + NAPI_TIMEOUT;
5745 list_add_tail(&ne->list, &ctx->napi_list);
5747 spin_unlock(&ctx->napi_lock);
5750 static inline void io_check_napi_entry_timeout(struct napi_entry *ne)
5752 if (time_after(jiffies, ne->timeout)) {
5753 list_del(&ne->list);
5759 * Busy poll if globally on and supporting sockets found
5761 static bool io_napi_busy_loop(struct list_head *napi_list)
5763 struct napi_entry *ne, *n;
5765 list_for_each_entry_safe(ne, n, napi_list, list) {
5766 napi_busy_loop(ne->napi_id, NULL, NULL, true,
5768 io_check_napi_entry_timeout(ne);
5770 return !list_empty(napi_list);
5773 static void io_free_napi_list(struct io_ring_ctx *ctx)
5775 spin_lock(&ctx->napi_lock);
5776 while (!list_empty(&ctx->napi_list)) {
5777 struct napi_entry *ne =
5778 list_first_entry(&ctx->napi_list, struct napi_entry,
5781 list_del(&ne->list);
5784 spin_unlock(&ctx->napi_lock);
5787 static inline void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5791 static inline void io_free_napi_list(struct io_ring_ctx *ctx)
5794 #endif /* CONFIG_NET_RX_BUSY_POLL */
5796 struct io_poll_table {
5797 struct poll_table_struct pt;
5798 struct io_kiocb *req;
5803 #define IO_POLL_CANCEL_FLAG BIT(31)
5804 #define IO_POLL_REF_MASK ((1u << 20)-1)
5807 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5808 * bump it and acquire ownership. It's disallowed to modify requests while not
5809 * owning it, that prevents from races for enqueueing task_work's and b/w
5810 * arming poll and wakeups.
5812 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5814 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5817 static void io_poll_mark_cancelled(struct io_kiocb *req)
5819 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5822 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5824 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5825 if (req->opcode == IORING_OP_POLL_ADD)
5826 return req->async_data;
5827 return req->apoll->double_poll;
5830 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5832 if (req->opcode == IORING_OP_POLL_ADD)
5834 return &req->apoll->poll;
5837 static void io_poll_req_insert(struct io_kiocb *req)
5839 struct io_ring_ctx *ctx = req->ctx;
5840 struct hlist_head *list;
5842 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5843 hlist_add_head(&req->hash_node, list);
5846 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5847 wait_queue_func_t wake_func)
5850 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5851 /* mask in events that we always want/need */
5852 poll->events = events | IO_POLL_UNMASK;
5853 INIT_LIST_HEAD(&poll->wait.entry);
5854 init_waitqueue_func_entry(&poll->wait, wake_func);
5857 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5859 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5862 spin_lock_irq(&head->lock);
5863 list_del_init(&poll->wait.entry);
5865 spin_unlock_irq(&head->lock);
5869 static void io_poll_remove_entries(struct io_kiocb *req)
5872 * Nothing to do if neither of those flags are set. Avoid dipping
5873 * into the poll/apoll/double cachelines if we can.
5875 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5879 * While we hold the waitqueue lock and the waitqueue is nonempty,
5880 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5881 * lock in the first place can race with the waitqueue being freed.
5883 * We solve this as eventpoll does: by taking advantage of the fact that
5884 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5885 * we enter rcu_read_lock() and see that the pointer to the queue is
5886 * non-NULL, we can then lock it without the memory being freed out from
5889 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5890 * case the caller deletes the entry from the queue, leaving it empty.
5891 * In that case, only RCU prevents the queue memory from being freed.
5894 if (req->flags & REQ_F_SINGLE_POLL)
5895 io_poll_remove_entry(io_poll_get_single(req));
5896 if (req->flags & REQ_F_DOUBLE_POLL)
5897 io_poll_remove_entry(io_poll_get_double(req));
5902 * All poll tw should go through this. Checks for poll events, manages
5903 * references, does rewait, etc.
5905 * Returns a negative error on failure. >0 when no action require, which is
5906 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5907 * the request, then the mask is stored in req->result.
5909 static int io_poll_check_events(struct io_kiocb *req)
5911 struct io_ring_ctx *ctx = req->ctx;
5912 struct io_poll_iocb *poll = io_poll_get_single(req);
5915 /* req->task == current here, checking PF_EXITING is safe */
5916 if (unlikely(req->task->flags & PF_EXITING))
5917 io_poll_mark_cancelled(req);
5920 v = atomic_read(&req->poll_refs);
5922 /* tw handler should be the owner, and so have some references */
5923 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5925 if (v & IO_POLL_CANCEL_FLAG)
5929 struct poll_table_struct pt = { ._key = req->cflags };
5931 req->result = vfs_poll(req->file, &pt) & req->cflags;
5934 /* multishot, just fill an CQE and proceed */
5935 if (req->result && !(req->cflags & EPOLLONESHOT)) {
5936 __poll_t mask = mangle_poll(req->result & poll->events);
5939 spin_lock(&ctx->completion_lock);
5940 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5942 io_commit_cqring(ctx);
5943 spin_unlock(&ctx->completion_lock);
5944 if (unlikely(!filled))
5946 io_cqring_ev_posted(ctx);
5947 io_add_napi(req->file, ctx);
5948 } else if (req->result) {
5953 * Release all references, retry if someone tried to restart
5954 * task_work while we were executing it.
5956 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5961 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5963 struct io_ring_ctx *ctx = req->ctx;
5966 ret = io_poll_check_events(req);
5971 req->result = mangle_poll(req->result & req->poll.events);
5977 io_poll_remove_entries(req);
5978 spin_lock(&ctx->completion_lock);
5979 hash_del(&req->hash_node);
5980 __io_req_complete_post(req, req->result, 0);
5981 io_commit_cqring(ctx);
5982 spin_unlock(&ctx->completion_lock);
5983 io_cqring_ev_posted(ctx);
5986 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5988 struct io_ring_ctx *ctx = req->ctx;
5991 ret = io_poll_check_events(req);
5995 io_poll_remove_entries(req);
5996 spin_lock(&ctx->completion_lock);
5997 hash_del(&req->hash_node);
5998 spin_unlock(&ctx->completion_lock);
6001 io_req_task_submit(req, locked);
6003 io_req_complete_failed(req, ret);
6006 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
6010 * This is useful for poll that is armed on behalf of another
6011 * request, and where the wakeup path could be on a different
6012 * CPU. We want to avoid pulling in req->apoll->events for that
6015 req->cflags = events;
6016 if (req->opcode == IORING_OP_POLL_ADD)
6017 req->io_task_work.func = io_poll_task_func;
6019 req->io_task_work.func = io_apoll_task_func;
6021 trace_io_uring_task_add(req->ctx, req, req->user_data, req->opcode, mask);
6022 io_req_task_work_add(req, false);
6025 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
6027 if (io_poll_get_ownership(req))
6028 __io_poll_execute(req, res, events);
6031 static void io_poll_cancel_req(struct io_kiocb *req)
6033 io_poll_mark_cancelled(req);
6034 /* kick tw, which should complete the request */
6035 io_poll_execute(req, 0, 0);
6038 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6041 struct io_kiocb *req = wait->private;
6042 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6044 __poll_t mask = key_to_poll(key);
6046 if (unlikely(mask & POLLFREE)) {
6047 io_poll_mark_cancelled(req);
6048 /* we have to kick tw in case it's not already */
6049 io_poll_execute(req, 0, poll->events);
6052 * If the waitqueue is being freed early but someone is already
6053 * holds ownership over it, we have to tear down the request as
6054 * best we can. That means immediately removing the request from
6055 * its waitqueue and preventing all further accesses to the
6056 * waitqueue via the request.
6058 list_del_init(&poll->wait.entry);
6061 * Careful: this *must* be the last step, since as soon
6062 * as req->head is NULL'ed out, the request can be
6063 * completed and freed, since aio_poll_complete_work()
6064 * will no longer need to take the waitqueue lock.
6066 smp_store_release(&poll->head, NULL);
6070 /* for instances that support it check for an event match first */
6071 if (mask && !(mask & poll->events))
6074 if (io_poll_get_ownership(req)) {
6075 /* optional, saves extra locking for removal in tw handler */
6076 if (mask && poll->events & EPOLLONESHOT) {
6077 list_del_init(&poll->wait.entry);
6079 req->flags &= ~REQ_F_SINGLE_POLL;
6081 __io_poll_execute(req, mask, poll->events);
6086 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6087 struct wait_queue_head *head,
6088 struct io_poll_iocb **poll_ptr)
6090 struct io_kiocb *req = pt->req;
6093 * The file being polled uses multiple waitqueues for poll handling
6094 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6097 if (unlikely(pt->nr_entries)) {
6098 struct io_poll_iocb *first = poll;
6100 /* double add on the same waitqueue head, ignore */
6101 if (first->head == head)
6103 /* already have a 2nd entry, fail a third attempt */
6105 if ((*poll_ptr)->head == head)
6107 pt->error = -EINVAL;
6111 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6113 pt->error = -ENOMEM;
6116 req->flags |= REQ_F_DOUBLE_POLL;
6117 io_init_poll_iocb(poll, first->events, first->wait.func);
6119 if (req->opcode == IORING_OP_POLL_ADD)
6120 req->flags |= REQ_F_ASYNC_DATA;
6123 req->flags |= REQ_F_SINGLE_POLL;
6126 poll->wait.private = req;
6128 if (poll->events & EPOLLEXCLUSIVE)
6129 add_wait_queue_exclusive(head, &poll->wait);
6131 add_wait_queue(head, &poll->wait);
6134 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6135 struct poll_table_struct *p)
6137 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6139 __io_queue_proc(&pt->req->poll, pt, head,
6140 (struct io_poll_iocb **) &pt->req->async_data);
6143 static int __io_arm_poll_handler(struct io_kiocb *req,
6144 struct io_poll_iocb *poll,
6145 struct io_poll_table *ipt, __poll_t mask)
6147 struct io_ring_ctx *ctx = req->ctx;
6150 INIT_HLIST_NODE(&req->hash_node);
6151 io_init_poll_iocb(poll, mask, io_poll_wake);
6152 poll->file = req->file;
6153 poll->wait.private = req;
6155 ipt->pt._key = mask;
6158 ipt->nr_entries = 0;
6161 * Take the ownership to delay any tw execution up until we're done
6162 * with poll arming. see io_poll_get_ownership().
6164 atomic_set(&req->poll_refs, 1);
6165 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6167 if (mask && (poll->events & EPOLLONESHOT)) {
6168 io_poll_remove_entries(req);
6169 /* no one else has access to the req, forget about the ref */
6172 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6173 io_poll_remove_entries(req);
6175 ipt->error = -EINVAL;
6179 spin_lock(&ctx->completion_lock);
6180 io_poll_req_insert(req);
6181 spin_unlock(&ctx->completion_lock);
6184 /* can't multishot if failed, just queue the event we've got */
6185 if (unlikely(ipt->error || !ipt->nr_entries))
6186 poll->events |= EPOLLONESHOT;
6187 __io_poll_execute(req, mask, poll->events);
6190 io_add_napi(req->file, req->ctx);
6193 * Release ownership. If someone tried to queue a tw while it was
6194 * locked, kick it off for them.
6196 v = atomic_dec_return(&req->poll_refs);
6197 if (unlikely(v & IO_POLL_REF_MASK))
6198 __io_poll_execute(req, 0, poll->events);
6202 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6203 struct poll_table_struct *p)
6205 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6206 struct async_poll *apoll = pt->req->apoll;
6208 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6217 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6219 const struct io_op_def *def = &io_op_defs[req->opcode];
6220 struct io_ring_ctx *ctx = req->ctx;
6221 struct async_poll *apoll;
6222 struct io_poll_table ipt;
6223 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6226 if (!def->pollin && !def->pollout)
6227 return IO_APOLL_ABORTED;
6228 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6229 return IO_APOLL_ABORTED;
6232 mask |= POLLIN | POLLRDNORM;
6234 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6235 if ((req->opcode == IORING_OP_RECVMSG) &&
6236 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6239 mask |= POLLOUT | POLLWRNORM;
6242 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6243 !list_empty(&ctx->apoll_cache)) {
6244 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6246 list_del_init(&apoll->poll.wait.entry);
6248 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6249 if (unlikely(!apoll))
6250 return IO_APOLL_ABORTED;
6252 apoll->double_poll = NULL;
6254 req->flags |= REQ_F_POLLED;
6255 ipt.pt._qproc = io_async_queue_proc;
6257 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6258 if (ret || ipt.error)
6259 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6261 trace_io_uring_poll_arm(ctx, req, req->user_data, req->opcode,
6262 mask, apoll->poll.events);
6267 * Returns true if we found and killed one or more poll requests
6269 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6270 struct task_struct *tsk, bool cancel_all)
6272 struct hlist_node *tmp;
6273 struct io_kiocb *req;
6277 spin_lock(&ctx->completion_lock);
6278 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6279 struct hlist_head *list;
6281 list = &ctx->cancel_hash[i];
6282 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6283 if (io_match_task_safe(req, tsk, cancel_all)) {
6284 io_poll_cancel_req(req);
6289 spin_unlock(&ctx->completion_lock);
6293 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6295 __must_hold(&ctx->completion_lock)
6297 struct hlist_head *list;
6298 struct io_kiocb *req;
6300 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6301 hlist_for_each_entry(req, list, hash_node) {
6302 if (sqe_addr != req->user_data)
6304 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6311 static bool io_poll_disarm(struct io_kiocb *req)
6312 __must_hold(&ctx->completion_lock)
6314 if (!io_poll_get_ownership(req))
6316 io_poll_remove_entries(req);
6317 hash_del(&req->hash_node);
6321 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6323 __must_hold(&ctx->completion_lock)
6325 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6329 io_poll_cancel_req(req);
6333 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6338 events = READ_ONCE(sqe->poll32_events);
6340 events = swahw32(events);
6342 if (!(flags & IORING_POLL_ADD_MULTI))
6343 events |= EPOLLONESHOT;
6344 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6347 static int io_poll_update_prep(struct io_kiocb *req,
6348 const struct io_uring_sqe *sqe)
6350 struct io_poll_update *upd = &req->poll_update;
6353 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6355 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6357 flags = READ_ONCE(sqe->len);
6358 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6359 IORING_POLL_ADD_MULTI))
6361 /* meaningless without update */
6362 if (flags == IORING_POLL_ADD_MULTI)
6365 upd->old_user_data = READ_ONCE(sqe->addr);
6366 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6367 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6369 upd->new_user_data = READ_ONCE(sqe->off);
6370 if (!upd->update_user_data && upd->new_user_data)
6372 if (upd->update_events)
6373 upd->events = io_poll_parse_events(sqe, flags);
6374 else if (sqe->poll32_events)
6380 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6382 struct io_poll_iocb *poll = &req->poll;
6385 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6387 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6389 flags = READ_ONCE(sqe->len);
6390 if (flags & ~IORING_POLL_ADD_MULTI)
6392 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6395 io_req_set_refcount(req);
6396 req->cflags = poll->events = io_poll_parse_events(sqe, flags);
6400 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6402 struct io_poll_iocb *poll = &req->poll;
6403 struct io_poll_table ipt;
6406 ipt.pt._qproc = io_poll_queue_proc;
6408 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6409 ret = ret ?: ipt.error;
6411 __io_req_complete(req, issue_flags, ret, 0);
6415 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6417 struct io_ring_ctx *ctx = req->ctx;
6418 struct io_kiocb *preq;
6422 spin_lock(&ctx->completion_lock);
6423 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6424 if (!preq || !io_poll_disarm(preq)) {
6425 spin_unlock(&ctx->completion_lock);
6426 ret = preq ? -EALREADY : -ENOENT;
6429 spin_unlock(&ctx->completion_lock);
6431 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6432 /* only mask one event flags, keep behavior flags */
6433 if (req->poll_update.update_events) {
6434 preq->poll.events &= ~0xffff;
6435 preq->poll.events |= req->poll_update.events & 0xffff;
6436 preq->poll.events |= IO_POLL_UNMASK;
6438 if (req->poll_update.update_user_data)
6439 preq->user_data = req->poll_update.new_user_data;
6441 ret2 = io_poll_add(preq, issue_flags);
6442 /* successfully updated, don't complete poll request */
6448 preq->result = -ECANCELED;
6449 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6450 io_req_task_complete(preq, &locked);
6454 /* complete update request, we're done with it */
6455 __io_req_complete(req, issue_flags, ret, 0);
6459 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6461 struct io_timeout_data *data = container_of(timer,
6462 struct io_timeout_data, timer);
6463 struct io_kiocb *req = data->req;
6464 struct io_ring_ctx *ctx = req->ctx;
6465 unsigned long flags;
6467 spin_lock_irqsave(&ctx->timeout_lock, flags);
6468 list_del_init(&req->timeout.list);
6469 atomic_set(&req->ctx->cq_timeouts,
6470 atomic_read(&req->ctx->cq_timeouts) + 1);
6471 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6473 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6476 req->result = -ETIME;
6477 req->io_task_work.func = io_req_task_complete;
6478 io_req_task_work_add(req, false);
6479 return HRTIMER_NORESTART;
6482 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6484 __must_hold(&ctx->timeout_lock)
6486 struct io_timeout_data *io;
6487 struct io_kiocb *req;
6490 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6491 found = user_data == req->user_data;
6496 return ERR_PTR(-ENOENT);
6498 io = req->async_data;
6499 if (hrtimer_try_to_cancel(&io->timer) == -1)
6500 return ERR_PTR(-EALREADY);
6501 list_del_init(&req->timeout.list);
6505 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6506 __must_hold(&ctx->completion_lock)
6507 __must_hold(&ctx->timeout_lock)
6509 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6512 return PTR_ERR(req);
6513 io_req_task_queue_fail(req, -ECANCELED);
6517 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6519 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6520 case IORING_TIMEOUT_BOOTTIME:
6521 return CLOCK_BOOTTIME;
6522 case IORING_TIMEOUT_REALTIME:
6523 return CLOCK_REALTIME;
6525 /* can't happen, vetted at prep time */
6529 return CLOCK_MONOTONIC;
6533 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6534 struct timespec64 *ts, enum hrtimer_mode mode)
6535 __must_hold(&ctx->timeout_lock)
6537 struct io_timeout_data *io;
6538 struct io_kiocb *req;
6541 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6542 found = user_data == req->user_data;
6549 io = req->async_data;
6550 if (hrtimer_try_to_cancel(&io->timer) == -1)
6552 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6553 io->timer.function = io_link_timeout_fn;
6554 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6558 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6559 struct timespec64 *ts, enum hrtimer_mode mode)
6560 __must_hold(&ctx->timeout_lock)
6562 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6563 struct io_timeout_data *data;
6566 return PTR_ERR(req);
6568 req->timeout.off = 0; /* noseq */
6569 data = req->async_data;
6570 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6571 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6572 data->timer.function = io_timeout_fn;
6573 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6577 static int io_timeout_remove_prep(struct io_kiocb *req,
6578 const struct io_uring_sqe *sqe)
6580 struct io_timeout_rem *tr = &req->timeout_rem;
6582 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6584 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6586 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6589 tr->ltimeout = false;
6590 tr->addr = READ_ONCE(sqe->addr);
6591 tr->flags = READ_ONCE(sqe->timeout_flags);
6592 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6593 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6595 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6596 tr->ltimeout = true;
6597 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6599 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6601 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6603 } else if (tr->flags) {
6604 /* timeout removal doesn't support flags */
6611 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6613 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6618 * Remove or update an existing timeout command
6620 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6622 struct io_timeout_rem *tr = &req->timeout_rem;
6623 struct io_ring_ctx *ctx = req->ctx;
6626 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6627 spin_lock(&ctx->completion_lock);
6628 spin_lock_irq(&ctx->timeout_lock);
6629 ret = io_timeout_cancel(ctx, tr->addr);
6630 spin_unlock_irq(&ctx->timeout_lock);
6631 spin_unlock(&ctx->completion_lock);
6633 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6635 spin_lock_irq(&ctx->timeout_lock);
6637 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6639 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6640 spin_unlock_irq(&ctx->timeout_lock);
6645 io_req_complete_post(req, ret, 0);
6649 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6650 bool is_timeout_link)
6652 struct io_timeout_data *data;
6654 u32 off = READ_ONCE(sqe->off);
6656 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6658 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6661 if (off && is_timeout_link)
6663 flags = READ_ONCE(sqe->timeout_flags);
6664 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6665 IORING_TIMEOUT_ETIME_SUCCESS))
6667 /* more than one clock specified is invalid, obviously */
6668 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6671 INIT_LIST_HEAD(&req->timeout.list);
6672 req->timeout.off = off;
6673 if (unlikely(off && !req->ctx->off_timeout_used))
6674 req->ctx->off_timeout_used = true;
6676 if (WARN_ON_ONCE(req_has_async_data(req)))
6678 if (io_alloc_async_data(req))
6681 data = req->async_data;
6683 data->flags = flags;
6685 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6688 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6691 data->mode = io_translate_timeout_mode(flags);
6692 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6694 if (is_timeout_link) {
6695 struct io_submit_link *link = &req->ctx->submit_state.link;
6699 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6701 req->timeout.head = link->last;
6702 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6707 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6709 struct io_ring_ctx *ctx = req->ctx;
6710 struct io_timeout_data *data = req->async_data;
6711 struct list_head *entry;
6712 u32 tail, off = req->timeout.off;
6714 spin_lock_irq(&ctx->timeout_lock);
6717 * sqe->off holds how many events that need to occur for this
6718 * timeout event to be satisfied. If it isn't set, then this is
6719 * a pure timeout request, sequence isn't used.
6721 if (io_is_timeout_noseq(req)) {
6722 entry = ctx->timeout_list.prev;
6726 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6727 req->timeout.target_seq = tail + off;
6729 /* Update the last seq here in case io_flush_timeouts() hasn't.
6730 * This is safe because ->completion_lock is held, and submissions
6731 * and completions are never mixed in the same ->completion_lock section.
6733 ctx->cq_last_tm_flush = tail;
6736 * Insertion sort, ensuring the first entry in the list is always
6737 * the one we need first.
6739 list_for_each_prev(entry, &ctx->timeout_list) {
6740 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6743 if (io_is_timeout_noseq(nxt))
6745 /* nxt.seq is behind @tail, otherwise would've been completed */
6746 if (off >= nxt->timeout.target_seq - tail)
6750 list_add(&req->timeout.list, entry);
6751 data->timer.function = io_timeout_fn;
6752 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6753 spin_unlock_irq(&ctx->timeout_lock);
6757 struct io_cancel_data {
6758 struct io_ring_ctx *ctx;
6762 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6764 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6765 struct io_cancel_data *cd = data;
6767 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6770 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6771 struct io_ring_ctx *ctx)
6773 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6774 enum io_wq_cancel cancel_ret;
6777 if (!tctx || !tctx->io_wq)
6780 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6781 switch (cancel_ret) {
6782 case IO_WQ_CANCEL_OK:
6785 case IO_WQ_CANCEL_RUNNING:
6788 case IO_WQ_CANCEL_NOTFOUND:
6796 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6798 struct io_ring_ctx *ctx = req->ctx;
6801 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6803 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6805 * Fall-through even for -EALREADY, as we may have poll armed
6806 * that need unarming.
6811 spin_lock(&ctx->completion_lock);
6812 ret = io_poll_cancel(ctx, sqe_addr, false);
6816 spin_lock_irq(&ctx->timeout_lock);
6817 ret = io_timeout_cancel(ctx, sqe_addr);
6818 spin_unlock_irq(&ctx->timeout_lock);
6820 spin_unlock(&ctx->completion_lock);
6824 static int io_async_cancel_prep(struct io_kiocb *req,
6825 const struct io_uring_sqe *sqe)
6827 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6829 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6831 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6835 req->cancel.addr = READ_ONCE(sqe->addr);
6839 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6841 struct io_ring_ctx *ctx = req->ctx;
6842 u64 sqe_addr = req->cancel.addr;
6843 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6844 struct io_tctx_node *node;
6847 ret = io_try_cancel_userdata(req, sqe_addr);
6851 /* slow path, try all io-wq's */
6852 io_ring_submit_lock(ctx, needs_lock);
6854 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6855 struct io_uring_task *tctx = node->task->io_uring;
6857 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6861 io_ring_submit_unlock(ctx, needs_lock);
6865 io_req_complete_post(req, ret, 0);
6869 static int io_rsrc_update_prep(struct io_kiocb *req,
6870 const struct io_uring_sqe *sqe)
6872 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6874 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6877 req->rsrc_update.offset = READ_ONCE(sqe->off);
6878 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6879 if (!req->rsrc_update.nr_args)
6881 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6885 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6887 struct io_ring_ctx *ctx = req->ctx;
6888 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6889 struct io_uring_rsrc_update2 up;
6892 up.offset = req->rsrc_update.offset;
6893 up.data = req->rsrc_update.arg;
6898 io_ring_submit_lock(ctx, needs_lock);
6899 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6900 &up, req->rsrc_update.nr_args);
6901 io_ring_submit_unlock(ctx, needs_lock);
6905 __io_req_complete(req, issue_flags, ret, 0);
6909 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6911 switch (req->opcode) {
6914 case IORING_OP_READV:
6915 case IORING_OP_READ_FIXED:
6916 case IORING_OP_READ:
6917 return io_read_prep(req, sqe);
6918 case IORING_OP_WRITEV:
6919 case IORING_OP_WRITE_FIXED:
6920 case IORING_OP_WRITE:
6921 return io_write_prep(req, sqe);
6922 case IORING_OP_POLL_ADD:
6923 return io_poll_add_prep(req, sqe);
6924 case IORING_OP_POLL_REMOVE:
6925 return io_poll_update_prep(req, sqe);
6926 case IORING_OP_FSYNC:
6927 return io_fsync_prep(req, sqe);
6928 case IORING_OP_SYNC_FILE_RANGE:
6929 return io_sfr_prep(req, sqe);
6930 case IORING_OP_SENDMSG:
6931 case IORING_OP_SEND:
6932 return io_sendmsg_prep(req, sqe);
6933 case IORING_OP_RECVMSG:
6934 case IORING_OP_RECV:
6935 return io_recvmsg_prep(req, sqe);
6936 case IORING_OP_CONNECT:
6937 return io_connect_prep(req, sqe);
6938 case IORING_OP_TIMEOUT:
6939 return io_timeout_prep(req, sqe, false);
6940 case IORING_OP_TIMEOUT_REMOVE:
6941 return io_timeout_remove_prep(req, sqe);
6942 case IORING_OP_ASYNC_CANCEL:
6943 return io_async_cancel_prep(req, sqe);
6944 case IORING_OP_LINK_TIMEOUT:
6945 return io_timeout_prep(req, sqe, true);
6946 case IORING_OP_ACCEPT:
6947 return io_accept_prep(req, sqe);
6948 case IORING_OP_FALLOCATE:
6949 return io_fallocate_prep(req, sqe);
6950 case IORING_OP_OPENAT:
6951 return io_openat_prep(req, sqe);
6952 case IORING_OP_CLOSE:
6953 return io_close_prep(req, sqe);
6954 case IORING_OP_FILES_UPDATE:
6955 return io_rsrc_update_prep(req, sqe);
6956 case IORING_OP_STATX:
6957 return io_statx_prep(req, sqe);
6958 case IORING_OP_FADVISE:
6959 return io_fadvise_prep(req, sqe);
6960 case IORING_OP_MADVISE:
6961 return io_madvise_prep(req, sqe);
6962 case IORING_OP_OPENAT2:
6963 return io_openat2_prep(req, sqe);
6964 case IORING_OP_EPOLL_CTL:
6965 return io_epoll_ctl_prep(req, sqe);
6966 case IORING_OP_SPLICE:
6967 return io_splice_prep(req, sqe);
6968 case IORING_OP_PROVIDE_BUFFERS:
6969 return io_provide_buffers_prep(req, sqe);
6970 case IORING_OP_REMOVE_BUFFERS:
6971 return io_remove_buffers_prep(req, sqe);
6973 return io_tee_prep(req, sqe);
6974 case IORING_OP_SHUTDOWN:
6975 return io_shutdown_prep(req, sqe);
6976 case IORING_OP_RENAMEAT:
6977 return io_renameat_prep(req, sqe);
6978 case IORING_OP_UNLINKAT:
6979 return io_unlinkat_prep(req, sqe);
6980 case IORING_OP_MKDIRAT:
6981 return io_mkdirat_prep(req, sqe);
6982 case IORING_OP_SYMLINKAT:
6983 return io_symlinkat_prep(req, sqe);
6984 case IORING_OP_LINKAT:
6985 return io_linkat_prep(req, sqe);
6986 case IORING_OP_MSG_RING:
6987 return io_msg_ring_prep(req, sqe);
6990 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6995 static int io_req_prep_async(struct io_kiocb *req)
6997 if (!io_op_defs[req->opcode].needs_async_setup)
6999 if (WARN_ON_ONCE(req_has_async_data(req)))
7001 if (io_alloc_async_data(req))
7004 switch (req->opcode) {
7005 case IORING_OP_READV:
7006 return io_rw_prep_async(req, READ);
7007 case IORING_OP_WRITEV:
7008 return io_rw_prep_async(req, WRITE);
7009 case IORING_OP_SENDMSG:
7010 return io_sendmsg_prep_async(req);
7011 case IORING_OP_RECVMSG:
7012 return io_recvmsg_prep_async(req);
7013 case IORING_OP_CONNECT:
7014 return io_connect_prep_async(req);
7016 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
7021 static u32 io_get_sequence(struct io_kiocb *req)
7023 u32 seq = req->ctx->cached_sq_head;
7025 /* need original cached_sq_head, but it was increased for each req */
7026 io_for_each_link(req, req)
7031 static __cold void io_drain_req(struct io_kiocb *req)
7033 struct io_ring_ctx *ctx = req->ctx;
7034 struct io_defer_entry *de;
7036 u32 seq = io_get_sequence(req);
7038 /* Still need defer if there is pending req in defer list. */
7039 spin_lock(&ctx->completion_lock);
7040 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7041 spin_unlock(&ctx->completion_lock);
7043 ctx->drain_active = false;
7044 io_req_task_queue(req);
7047 spin_unlock(&ctx->completion_lock);
7049 ret = io_req_prep_async(req);
7052 io_req_complete_failed(req, ret);
7055 io_prep_async_link(req);
7056 de = kmalloc(sizeof(*de), GFP_KERNEL);
7062 spin_lock(&ctx->completion_lock);
7063 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7064 spin_unlock(&ctx->completion_lock);
7069 trace_io_uring_defer(ctx, req, req->user_data, req->opcode);
7072 list_add_tail(&de->list, &ctx->defer_list);
7073 spin_unlock(&ctx->completion_lock);
7076 static void io_clean_op(struct io_kiocb *req)
7078 if (req->flags & REQ_F_BUFFER_SELECTED)
7079 io_put_kbuf_comp(req);
7081 if (req->flags & REQ_F_NEED_CLEANUP) {
7082 switch (req->opcode) {
7083 case IORING_OP_READV:
7084 case IORING_OP_READ_FIXED:
7085 case IORING_OP_READ:
7086 case IORING_OP_WRITEV:
7087 case IORING_OP_WRITE_FIXED:
7088 case IORING_OP_WRITE: {
7089 struct io_async_rw *io = req->async_data;
7091 kfree(io->free_iovec);
7094 case IORING_OP_RECVMSG:
7095 case IORING_OP_SENDMSG: {
7096 struct io_async_msghdr *io = req->async_data;
7098 kfree(io->free_iov);
7101 case IORING_OP_SPLICE:
7103 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
7104 io_put_file(req->splice.file_in);
7106 case IORING_OP_OPENAT:
7107 case IORING_OP_OPENAT2:
7108 if (req->open.filename)
7109 putname(req->open.filename);
7111 case IORING_OP_RENAMEAT:
7112 putname(req->rename.oldpath);
7113 putname(req->rename.newpath);
7115 case IORING_OP_UNLINKAT:
7116 putname(req->unlink.filename);
7118 case IORING_OP_MKDIRAT:
7119 putname(req->mkdir.filename);
7121 case IORING_OP_SYMLINKAT:
7122 putname(req->symlink.oldpath);
7123 putname(req->symlink.newpath);
7125 case IORING_OP_LINKAT:
7126 putname(req->hardlink.oldpath);
7127 putname(req->hardlink.newpath);
7129 case IORING_OP_STATX:
7130 if (req->statx.filename)
7131 putname(req->statx.filename);
7135 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7136 kfree(req->apoll->double_poll);
7140 if (req->flags & REQ_F_INFLIGHT) {
7141 struct io_uring_task *tctx = req->task->io_uring;
7143 atomic_dec(&tctx->inflight_tracked);
7145 if (req->flags & REQ_F_CREDS)
7146 put_cred(req->creds);
7147 if (req->flags & REQ_F_ASYNC_DATA) {
7148 kfree(req->async_data);
7149 req->async_data = NULL;
7151 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7154 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7156 const struct cred *creds = NULL;
7159 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7160 creds = override_creds(req->creds);
7162 if (!io_op_defs[req->opcode].audit_skip)
7163 audit_uring_entry(req->opcode);
7165 switch (req->opcode) {
7167 ret = io_nop(req, issue_flags);
7169 case IORING_OP_READV:
7170 case IORING_OP_READ_FIXED:
7171 case IORING_OP_READ:
7172 ret = io_read(req, issue_flags);
7174 case IORING_OP_WRITEV:
7175 case IORING_OP_WRITE_FIXED:
7176 case IORING_OP_WRITE:
7177 ret = io_write(req, issue_flags);
7179 case IORING_OP_FSYNC:
7180 ret = io_fsync(req, issue_flags);
7182 case IORING_OP_POLL_ADD:
7183 ret = io_poll_add(req, issue_flags);
7185 case IORING_OP_POLL_REMOVE:
7186 ret = io_poll_update(req, issue_flags);
7188 case IORING_OP_SYNC_FILE_RANGE:
7189 ret = io_sync_file_range(req, issue_flags);
7191 case IORING_OP_SENDMSG:
7192 ret = io_sendmsg(req, issue_flags);
7194 case IORING_OP_SEND:
7195 ret = io_send(req, issue_flags);
7197 case IORING_OP_RECVMSG:
7198 ret = io_recvmsg(req, issue_flags);
7200 case IORING_OP_RECV:
7201 ret = io_recv(req, issue_flags);
7203 case IORING_OP_TIMEOUT:
7204 ret = io_timeout(req, issue_flags);
7206 case IORING_OP_TIMEOUT_REMOVE:
7207 ret = io_timeout_remove(req, issue_flags);
7209 case IORING_OP_ACCEPT:
7210 ret = io_accept(req, issue_flags);
7212 case IORING_OP_CONNECT:
7213 ret = io_connect(req, issue_flags);
7215 case IORING_OP_ASYNC_CANCEL:
7216 ret = io_async_cancel(req, issue_flags);
7218 case IORING_OP_FALLOCATE:
7219 ret = io_fallocate(req, issue_flags);
7221 case IORING_OP_OPENAT:
7222 ret = io_openat(req, issue_flags);
7224 case IORING_OP_CLOSE:
7225 ret = io_close(req, issue_flags);
7227 case IORING_OP_FILES_UPDATE:
7228 ret = io_files_update(req, issue_flags);
7230 case IORING_OP_STATX:
7231 ret = io_statx(req, issue_flags);
7233 case IORING_OP_FADVISE:
7234 ret = io_fadvise(req, issue_flags);
7236 case IORING_OP_MADVISE:
7237 ret = io_madvise(req, issue_flags);
7239 case IORING_OP_OPENAT2:
7240 ret = io_openat2(req, issue_flags);
7242 case IORING_OP_EPOLL_CTL:
7243 ret = io_epoll_ctl(req, issue_flags);
7245 case IORING_OP_SPLICE:
7246 ret = io_splice(req, issue_flags);
7248 case IORING_OP_PROVIDE_BUFFERS:
7249 ret = io_provide_buffers(req, issue_flags);
7251 case IORING_OP_REMOVE_BUFFERS:
7252 ret = io_remove_buffers(req, issue_flags);
7255 ret = io_tee(req, issue_flags);
7257 case IORING_OP_SHUTDOWN:
7258 ret = io_shutdown(req, issue_flags);
7260 case IORING_OP_RENAMEAT:
7261 ret = io_renameat(req, issue_flags);
7263 case IORING_OP_UNLINKAT:
7264 ret = io_unlinkat(req, issue_flags);
7266 case IORING_OP_MKDIRAT:
7267 ret = io_mkdirat(req, issue_flags);
7269 case IORING_OP_SYMLINKAT:
7270 ret = io_symlinkat(req, issue_flags);
7272 case IORING_OP_LINKAT:
7273 ret = io_linkat(req, issue_flags);
7275 case IORING_OP_MSG_RING:
7276 ret = io_msg_ring(req, issue_flags);
7283 if (!io_op_defs[req->opcode].audit_skip)
7284 audit_uring_exit(!ret, ret);
7287 revert_creds(creds);
7290 /* If the op doesn't have a file, we're not polling for it */
7291 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7292 io_iopoll_req_issued(req, issue_flags);
7297 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7299 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7301 req = io_put_req_find_next(req);
7302 return req ? &req->work : NULL;
7305 static void io_wq_submit_work(struct io_wq_work *work)
7307 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7308 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7309 bool needs_poll = false;
7310 struct io_kiocb *timeout;
7313 /* one will be dropped by ->io_free_work() after returning to io-wq */
7314 if (!(req->flags & REQ_F_REFCOUNT))
7315 __io_req_set_refcount(req, 2);
7319 timeout = io_prep_linked_timeout(req);
7321 io_queue_linked_timeout(timeout);
7323 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7324 if (work->flags & IO_WQ_WORK_CANCEL) {
7325 io_req_task_queue_fail(req, -ECANCELED);
7329 if (req->flags & REQ_F_FORCE_ASYNC) {
7330 const struct io_op_def *def = &io_op_defs[req->opcode];
7331 bool opcode_poll = def->pollin || def->pollout;
7333 if (opcode_poll && file_can_poll(req->file)) {
7335 issue_flags |= IO_URING_F_NONBLOCK;
7340 ret = io_issue_sqe(req, issue_flags);
7344 * We can get EAGAIN for iopolled IO even though we're
7345 * forcing a sync submission from here, since we can't
7346 * wait for request slots on the block side.
7353 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7355 /* aborted or ready, in either case retry blocking */
7357 issue_flags &= ~IO_URING_F_NONBLOCK;
7360 /* avoid locking problems by failing it from a clean context */
7362 io_req_task_queue_fail(req, ret);
7365 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7368 return &table->files[i];
7371 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7374 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7376 return (struct file *) (slot->file_ptr & FFS_MASK);
7379 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7381 unsigned long file_ptr = (unsigned long) file;
7383 file_ptr |= io_file_get_flags(file);
7384 file_slot->file_ptr = file_ptr;
7387 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
7388 struct io_kiocb *req, int fd)
7391 unsigned long file_ptr;
7393 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7395 fd = array_index_nospec(fd, ctx->nr_user_files);
7396 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7397 file = (struct file *) (file_ptr & FFS_MASK);
7398 file_ptr &= ~FFS_MASK;
7399 /* mask in overlapping REQ_F and FFS bits */
7400 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7401 io_req_set_rsrc_node(req, ctx);
7405 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
7406 struct io_kiocb *req, int fd)
7408 struct file *file = fget(fd);
7410 trace_io_uring_file_get(ctx, req, req->user_data, fd);
7412 /* we don't allow fixed io_uring files */
7413 if (file && unlikely(file->f_op == &io_uring_fops))
7414 io_req_track_inflight(req);
7418 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
7419 struct io_kiocb *req, int fd, bool fixed)
7422 return io_file_get_fixed(ctx, req, fd);
7424 return io_file_get_normal(ctx, req, fd);
7427 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7429 struct io_kiocb *prev = req->timeout.prev;
7433 if (!(req->task->flags & PF_EXITING))
7434 ret = io_try_cancel_userdata(req, prev->user_data);
7435 io_req_complete_post(req, ret ?: -ETIME, 0);
7438 io_req_complete_post(req, -ETIME, 0);
7442 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7444 struct io_timeout_data *data = container_of(timer,
7445 struct io_timeout_data, timer);
7446 struct io_kiocb *prev, *req = data->req;
7447 struct io_ring_ctx *ctx = req->ctx;
7448 unsigned long flags;
7450 spin_lock_irqsave(&ctx->timeout_lock, flags);
7451 prev = req->timeout.head;
7452 req->timeout.head = NULL;
7455 * We don't expect the list to be empty, that will only happen if we
7456 * race with the completion of the linked work.
7459 io_remove_next_linked(prev);
7460 if (!req_ref_inc_not_zero(prev))
7463 list_del(&req->timeout.list);
7464 req->timeout.prev = prev;
7465 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7467 req->io_task_work.func = io_req_task_link_timeout;
7468 io_req_task_work_add(req, false);
7469 return HRTIMER_NORESTART;
7472 static void io_queue_linked_timeout(struct io_kiocb *req)
7474 struct io_ring_ctx *ctx = req->ctx;
7476 spin_lock_irq(&ctx->timeout_lock);
7478 * If the back reference is NULL, then our linked request finished
7479 * before we got a chance to setup the timer
7481 if (req->timeout.head) {
7482 struct io_timeout_data *data = req->async_data;
7484 data->timer.function = io_link_timeout_fn;
7485 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7487 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7489 spin_unlock_irq(&ctx->timeout_lock);
7490 /* drop submission reference */
7494 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7495 __must_hold(&req->ctx->uring_lock)
7497 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7499 switch (io_arm_poll_handler(req, 0)) {
7500 case IO_APOLL_READY:
7501 io_req_task_queue(req);
7503 case IO_APOLL_ABORTED:
7505 * Queued up for async execution, worker will release
7506 * submit reference when the iocb is actually submitted.
7508 io_kbuf_recycle(req);
7509 io_queue_async_work(req, NULL);
7512 io_kbuf_recycle(req);
7517 io_queue_linked_timeout(linked_timeout);
7520 static inline void __io_queue_sqe(struct io_kiocb *req)
7521 __must_hold(&req->ctx->uring_lock)
7523 struct io_kiocb *linked_timeout;
7526 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7528 if (req->flags & REQ_F_COMPLETE_INLINE) {
7529 io_req_add_compl_list(req);
7533 * We async punt it if the file wasn't marked NOWAIT, or if the file
7534 * doesn't support non-blocking read/write attempts
7537 linked_timeout = io_prep_linked_timeout(req);
7539 io_queue_linked_timeout(linked_timeout);
7540 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7541 io_queue_sqe_arm_apoll(req);
7543 io_req_complete_failed(req, ret);
7547 static void io_queue_sqe_fallback(struct io_kiocb *req)
7548 __must_hold(&req->ctx->uring_lock)
7550 if (req->flags & REQ_F_FAIL) {
7551 io_req_complete_fail_submit(req);
7552 } else if (unlikely(req->ctx->drain_active)) {
7555 int ret = io_req_prep_async(req);
7558 io_req_complete_failed(req, ret);
7560 io_queue_async_work(req, NULL);
7564 static inline void io_queue_sqe(struct io_kiocb *req)
7565 __must_hold(&req->ctx->uring_lock)
7567 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7568 __io_queue_sqe(req);
7570 io_queue_sqe_fallback(req);
7574 * Check SQE restrictions (opcode and flags).
7576 * Returns 'true' if SQE is allowed, 'false' otherwise.
7578 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7579 struct io_kiocb *req,
7580 unsigned int sqe_flags)
7582 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7585 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7586 ctx->restrictions.sqe_flags_required)
7589 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7590 ctx->restrictions.sqe_flags_required))
7596 static void io_init_req_drain(struct io_kiocb *req)
7598 struct io_ring_ctx *ctx = req->ctx;
7599 struct io_kiocb *head = ctx->submit_state.link.head;
7601 ctx->drain_active = true;
7604 * If we need to drain a request in the middle of a link, drain
7605 * the head request and the next request/link after the current
7606 * link. Considering sequential execution of links,
7607 * REQ_F_IO_DRAIN will be maintained for every request of our
7610 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7611 ctx->drain_next = true;
7615 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7616 const struct io_uring_sqe *sqe)
7617 __must_hold(&ctx->uring_lock)
7619 unsigned int sqe_flags;
7623 /* req is partially pre-initialised, see io_preinit_req() */
7624 req->opcode = opcode = READ_ONCE(sqe->opcode);
7625 /* same numerical values with corresponding REQ_F_*, safe to copy */
7626 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7627 req->user_data = READ_ONCE(sqe->user_data);
7629 req->fixed_rsrc_refs = NULL;
7630 req->task = current;
7632 if (unlikely(opcode >= IORING_OP_LAST)) {
7636 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7637 /* enforce forwards compatibility on users */
7638 if (sqe_flags & ~SQE_VALID_FLAGS)
7640 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7641 !io_op_defs[opcode].buffer_select)
7643 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7644 ctx->drain_disabled = true;
7645 if (sqe_flags & IOSQE_IO_DRAIN) {
7646 if (ctx->drain_disabled)
7648 io_init_req_drain(req);
7651 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7652 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7654 /* knock it to the slow queue path, will be drained there */
7655 if (ctx->drain_active)
7656 req->flags |= REQ_F_FORCE_ASYNC;
7657 /* if there is no link, we're at "next" request and need to drain */
7658 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7659 ctx->drain_next = false;
7660 ctx->drain_active = true;
7661 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7665 if (io_op_defs[opcode].needs_file) {
7666 struct io_submit_state *state = &ctx->submit_state;
7669 * Plug now if we have more than 2 IO left after this, and the
7670 * target is potentially a read/write to block based storage.
7672 if (state->need_plug && io_op_defs[opcode].plug) {
7673 state->plug_started = true;
7674 state->need_plug = false;
7675 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7678 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7679 (sqe_flags & IOSQE_FIXED_FILE));
7680 if (unlikely(!req->file))
7684 personality = READ_ONCE(sqe->personality);
7688 req->creds = xa_load(&ctx->personalities, personality);
7691 get_cred(req->creds);
7692 ret = security_uring_override_creds(req->creds);
7694 put_cred(req->creds);
7697 req->flags |= REQ_F_CREDS;
7700 return io_req_prep(req, sqe);
7703 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7704 const struct io_uring_sqe *sqe)
7705 __must_hold(&ctx->uring_lock)
7707 struct io_submit_link *link = &ctx->submit_state.link;
7710 ret = io_init_req(ctx, req, sqe);
7711 if (unlikely(ret)) {
7712 trace_io_uring_req_failed(sqe, ctx, req, ret);
7714 /* fail even hard links since we don't submit */
7717 * we can judge a link req is failed or cancelled by if
7718 * REQ_F_FAIL is set, but the head is an exception since
7719 * it may be set REQ_F_FAIL because of other req's failure
7720 * so let's leverage req->result to distinguish if a head
7721 * is set REQ_F_FAIL because of its failure or other req's
7722 * failure so that we can set the correct ret code for it.
7723 * init result here to avoid affecting the normal path.
7725 if (!(link->head->flags & REQ_F_FAIL))
7726 req_fail_link_node(link->head, -ECANCELED);
7727 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7729 * the current req is a normal req, we should return
7730 * error and thus break the submittion loop.
7732 io_req_complete_failed(req, ret);
7735 req_fail_link_node(req, ret);
7738 /* don't need @sqe from now on */
7739 trace_io_uring_submit_sqe(ctx, req, req->user_data, req->opcode,
7741 ctx->flags & IORING_SETUP_SQPOLL);
7744 * If we already have a head request, queue this one for async
7745 * submittal once the head completes. If we don't have a head but
7746 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7747 * submitted sync once the chain is complete. If none of those
7748 * conditions are true (normal request), then just queue it.
7751 struct io_kiocb *head = link->head;
7753 if (!(req->flags & REQ_F_FAIL)) {
7754 ret = io_req_prep_async(req);
7755 if (unlikely(ret)) {
7756 req_fail_link_node(req, ret);
7757 if (!(head->flags & REQ_F_FAIL))
7758 req_fail_link_node(head, -ECANCELED);
7761 trace_io_uring_link(ctx, req, head);
7762 link->last->link = req;
7765 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7767 /* last request of a link, enqueue the link */
7770 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7781 * Batched submission is done, ensure local IO is flushed out.
7783 static void io_submit_state_end(struct io_ring_ctx *ctx)
7785 struct io_submit_state *state = &ctx->submit_state;
7787 if (state->link.head)
7788 io_queue_sqe(state->link.head);
7789 /* flush only after queuing links as they can generate completions */
7790 io_submit_flush_completions(ctx);
7791 if (state->plug_started)
7792 blk_finish_plug(&state->plug);
7796 * Start submission side cache.
7798 static void io_submit_state_start(struct io_submit_state *state,
7799 unsigned int max_ios)
7801 state->plug_started = false;
7802 state->need_plug = max_ios > 2;
7803 state->submit_nr = max_ios;
7804 /* set only head, no need to init link_last in advance */
7805 state->link.head = NULL;
7808 static void io_commit_sqring(struct io_ring_ctx *ctx)
7810 struct io_rings *rings = ctx->rings;
7813 * Ensure any loads from the SQEs are done at this point,
7814 * since once we write the new head, the application could
7815 * write new data to them.
7817 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7821 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7822 * that is mapped by userspace. This means that care needs to be taken to
7823 * ensure that reads are stable, as we cannot rely on userspace always
7824 * being a good citizen. If members of the sqe are validated and then later
7825 * used, it's important that those reads are done through READ_ONCE() to
7826 * prevent a re-load down the line.
7828 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7830 unsigned head, mask = ctx->sq_entries - 1;
7831 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7834 * The cached sq head (or cq tail) serves two purposes:
7836 * 1) allows us to batch the cost of updating the user visible
7838 * 2) allows the kernel side to track the head on its own, even
7839 * though the application is the one updating it.
7841 head = READ_ONCE(ctx->sq_array[sq_idx]);
7842 if (likely(head < ctx->sq_entries))
7843 return &ctx->sq_sqes[head];
7845 /* drop invalid entries */
7847 WRITE_ONCE(ctx->rings->sq_dropped,
7848 READ_ONCE(ctx->rings->sq_dropped) + 1);
7852 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7853 __must_hold(&ctx->uring_lock)
7855 unsigned int entries = io_sqring_entries(ctx);
7858 if (unlikely(!entries))
7860 /* make sure SQ entry isn't read before tail */
7861 nr = min3(nr, ctx->sq_entries, entries);
7862 io_get_task_refs(nr);
7864 io_submit_state_start(&ctx->submit_state, nr);
7866 const struct io_uring_sqe *sqe;
7867 struct io_kiocb *req;
7869 if (unlikely(!io_alloc_req_refill(ctx))) {
7871 submitted = -EAGAIN;
7874 req = io_alloc_req(ctx);
7875 sqe = io_get_sqe(ctx);
7876 if (unlikely(!sqe)) {
7877 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7880 /* will complete beyond this point, count as submitted */
7882 if (io_submit_sqe(ctx, req, sqe)) {
7884 * Continue submitting even for sqe failure if the
7885 * ring was setup with IORING_SETUP_SUBMIT_ALL
7887 if (!(ctx->flags & IORING_SETUP_SUBMIT_ALL))
7890 } while (submitted < nr);
7892 if (unlikely(submitted != nr)) {
7893 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7894 int unused = nr - ref_used;
7896 current->io_uring->cached_refs += unused;
7899 io_submit_state_end(ctx);
7900 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7901 io_commit_sqring(ctx);
7906 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7908 return READ_ONCE(sqd->state);
7911 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7913 /* Tell userspace we may need a wakeup call */
7914 spin_lock(&ctx->completion_lock);
7915 WRITE_ONCE(ctx->rings->sq_flags,
7916 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7917 spin_unlock(&ctx->completion_lock);
7920 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7922 spin_lock(&ctx->completion_lock);
7923 WRITE_ONCE(ctx->rings->sq_flags,
7924 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7925 spin_unlock(&ctx->completion_lock);
7928 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7930 unsigned int to_submit;
7933 to_submit = io_sqring_entries(ctx);
7934 /* if we're handling multiple rings, cap submit size for fairness */
7935 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7936 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7938 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7939 const struct cred *creds = NULL;
7941 if (ctx->sq_creds != current_cred())
7942 creds = override_creds(ctx->sq_creds);
7944 mutex_lock(&ctx->uring_lock);
7945 if (!wq_list_empty(&ctx->iopoll_list))
7946 io_do_iopoll(ctx, true);
7949 * Don't submit if refs are dying, good for io_uring_register(),
7950 * but also it is relied upon by io_ring_exit_work()
7952 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7953 !(ctx->flags & IORING_SETUP_R_DISABLED))
7954 ret = io_submit_sqes(ctx, to_submit);
7955 mutex_unlock(&ctx->uring_lock);
7956 #ifdef CONFIG_NET_RX_BUSY_POLL
7957 spin_lock(&ctx->napi_lock);
7958 if (!list_empty(&ctx->napi_list) &&
7959 io_napi_busy_loop(&ctx->napi_list))
7961 spin_unlock(&ctx->napi_lock);
7963 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7964 wake_up(&ctx->sqo_sq_wait);
7966 revert_creds(creds);
7972 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7974 struct io_ring_ctx *ctx;
7975 unsigned sq_thread_idle = 0;
7977 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7978 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7979 sqd->sq_thread_idle = sq_thread_idle;
7982 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7984 bool did_sig = false;
7985 struct ksignal ksig;
7987 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7988 signal_pending(current)) {
7989 mutex_unlock(&sqd->lock);
7990 if (signal_pending(current))
7991 did_sig = get_signal(&ksig);
7993 mutex_lock(&sqd->lock);
7995 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7998 static int io_sq_thread(void *data)
8000 struct io_sq_data *sqd = data;
8001 struct io_ring_ctx *ctx;
8002 unsigned long timeout = 0;
8003 char buf[TASK_COMM_LEN];
8006 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8007 set_task_comm(current, buf);
8009 if (sqd->sq_cpu != -1)
8010 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8012 set_cpus_allowed_ptr(current, cpu_online_mask);
8013 current->flags |= PF_NO_SETAFFINITY;
8015 audit_alloc_kernel(current);
8017 mutex_lock(&sqd->lock);
8019 bool cap_entries, sqt_spin = false;
8021 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8022 if (io_sqd_handle_event(sqd))
8024 timeout = jiffies + sqd->sq_thread_idle;
8027 cap_entries = !list_is_singular(&sqd->ctx_list);
8028 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8029 int ret = __io_sq_thread(ctx, cap_entries);
8031 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8034 if (io_run_task_work())
8037 if (sqt_spin || !time_after(jiffies, timeout)) {
8040 timeout = jiffies + sqd->sq_thread_idle;
8044 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8045 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8046 bool needs_sched = true;
8048 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8049 io_ring_set_wakeup_flag(ctx);
8051 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8052 !wq_list_empty(&ctx->iopoll_list)) {
8053 needs_sched = false;
8056 if (io_sqring_entries(ctx)) {
8057 needs_sched = false;
8063 mutex_unlock(&sqd->lock);
8065 mutex_lock(&sqd->lock);
8067 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8068 io_ring_clear_wakeup_flag(ctx);
8071 finish_wait(&sqd->wait, &wait);
8072 timeout = jiffies + sqd->sq_thread_idle;
8075 io_uring_cancel_generic(true, sqd);
8077 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8078 io_ring_set_wakeup_flag(ctx);
8080 mutex_unlock(&sqd->lock);
8082 audit_free(current);
8084 complete(&sqd->exited);
8088 struct io_wait_queue {
8089 struct wait_queue_entry wq;
8090 struct io_ring_ctx *ctx;
8092 unsigned nr_timeouts;
8093 #ifdef CONFIG_NET_RX_BUSY_POLL
8094 unsigned busy_poll_to;
8098 static inline bool io_should_wake(struct io_wait_queue *iowq)
8100 struct io_ring_ctx *ctx = iowq->ctx;
8101 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8104 * Wake up if we have enough events, or if a timeout occurred since we
8105 * started waiting. For timeouts, we always want to return to userspace,
8106 * regardless of event count.
8108 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8111 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8112 int wake_flags, void *key)
8114 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8118 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8119 * the task, and the next invocation will do it.
8121 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
8122 return autoremove_wake_function(curr, mode, wake_flags, key);
8126 static int io_run_task_work_sig(void)
8128 if (io_run_task_work())
8130 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8131 return -ERESTARTSYS;
8132 if (task_sigpending(current))
8137 /* when returns >0, the caller should retry */
8138 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8139 struct io_wait_queue *iowq,
8144 /* make sure we run task_work before checking for signals */
8145 ret = io_run_task_work_sig();
8146 if (ret || io_should_wake(iowq))
8148 /* let the caller flush overflows, retry */
8149 if (test_bit(0, &ctx->check_cq_overflow))
8152 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8157 #ifdef CONFIG_NET_RX_BUSY_POLL
8158 static void io_adjust_busy_loop_timeout(struct timespec64 *ts,
8159 struct io_wait_queue *iowq)
8161 unsigned busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8162 struct timespec64 pollto = ns_to_timespec64(1000 * (s64)busy_poll_to);
8164 if (timespec64_compare(ts, &pollto) > 0) {
8165 *ts = timespec64_sub(*ts, pollto);
8166 iowq->busy_poll_to = busy_poll_to;
8168 u64 to = timespec64_to_ns(ts);
8171 iowq->busy_poll_to = to;
8177 static inline bool io_busy_loop_timeout(unsigned long start_time,
8178 unsigned long bp_usec)
8181 unsigned long end_time = start_time + bp_usec;
8182 unsigned long now = busy_loop_current_time();
8184 return time_after(now, end_time);
8189 static bool io_busy_loop_end(void *p, unsigned long start_time)
8191 struct io_wait_queue *iowq = p;
8193 return signal_pending(current) ||
8194 io_should_wake(iowq) ||
8195 io_busy_loop_timeout(start_time, iowq->busy_poll_to);
8198 static void io_blocking_napi_busy_loop(struct list_head *napi_list,
8199 struct io_wait_queue *iowq)
8201 unsigned long start_time =
8202 list_is_singular(napi_list) ? 0 :
8203 busy_loop_current_time();
8206 if (list_is_singular(napi_list)) {
8207 struct napi_entry *ne =
8208 list_first_entry(napi_list,
8209 struct napi_entry, list);
8211 napi_busy_loop(ne->napi_id, io_busy_loop_end, iowq,
8212 true, BUSY_POLL_BUDGET);
8213 io_check_napi_entry_timeout(ne);
8216 } while (io_napi_busy_loop(napi_list) &&
8217 !io_busy_loop_end(iowq, start_time));
8220 static void io_putback_napi_list(struct io_ring_ctx *ctx,
8221 struct list_head *napi_list)
8223 struct napi_entry *cne, *lne;
8225 spin_lock(&ctx->napi_lock);
8226 list_for_each_entry(cne, &ctx->napi_list, list)
8227 list_for_each_entry(lne, napi_list, list)
8228 if (cne->napi_id == lne->napi_id) {
8229 list_del(&lne->list);
8233 list_splice(napi_list, &ctx->napi_list);
8234 spin_unlock(&ctx->napi_lock);
8236 #endif /* CONFIG_NET_RX_BUSY_POLL */
8239 * Wait until events become available, if we don't already have some. The
8240 * application must reap them itself, as they reside on the shared cq ring.
8242 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8243 const sigset_t __user *sig, size_t sigsz,
8244 struct __kernel_timespec __user *uts)
8246 struct io_wait_queue iowq;
8247 struct io_rings *rings = ctx->rings;
8248 ktime_t timeout = KTIME_MAX;
8250 #ifdef CONFIG_NET_RX_BUSY_POLL
8251 LIST_HEAD(local_napi_list);
8255 io_cqring_overflow_flush(ctx);
8256 if (io_cqring_events(ctx) >= min_events)
8258 if (!io_run_task_work())
8263 #ifdef CONFIG_COMPAT
8264 if (in_compat_syscall())
8265 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8269 ret = set_user_sigmask(sig, sigsz);
8275 #ifdef CONFIG_NET_RX_BUSY_POLL
8276 iowq.busy_poll_to = 0;
8277 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8278 spin_lock(&ctx->napi_lock);
8279 list_splice_init(&ctx->napi_list, &local_napi_list);
8280 spin_unlock(&ctx->napi_lock);
8284 struct timespec64 ts;
8286 if (get_timespec64(&ts, uts))
8288 #ifdef CONFIG_NET_RX_BUSY_POLL
8289 if (!list_empty(&local_napi_list))
8290 io_adjust_busy_loop_timeout(&ts, &iowq);
8292 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8294 #ifdef CONFIG_NET_RX_BUSY_POLL
8295 else if (!list_empty(&local_napi_list))
8296 iowq.busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8299 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8300 iowq.wq.private = current;
8301 INIT_LIST_HEAD(&iowq.wq.entry);
8303 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8304 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8306 trace_io_uring_cqring_wait(ctx, min_events);
8307 #ifdef CONFIG_NET_RX_BUSY_POLL
8308 if (iowq.busy_poll_to)
8309 io_blocking_napi_busy_loop(&local_napi_list, &iowq);
8310 if (!list_empty(&local_napi_list))
8311 io_putback_napi_list(ctx, &local_napi_list);
8314 /* if we can't even flush overflow, don't wait for more */
8315 if (!io_cqring_overflow_flush(ctx)) {
8319 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8320 TASK_INTERRUPTIBLE);
8321 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8322 finish_wait(&ctx->cq_wait, &iowq.wq);
8326 restore_saved_sigmask_unless(ret == -EINTR);
8328 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8331 static void io_free_page_table(void **table, size_t size)
8333 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8335 for (i = 0; i < nr_tables; i++)
8340 static __cold void **io_alloc_page_table(size_t size)
8342 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8343 size_t init_size = size;
8346 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8350 for (i = 0; i < nr_tables; i++) {
8351 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8353 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8355 io_free_page_table(table, init_size);
8363 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8365 percpu_ref_exit(&ref_node->refs);
8369 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8371 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8372 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8373 unsigned long flags;
8374 bool first_add = false;
8375 unsigned long delay = HZ;
8377 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8380 /* if we are mid-quiesce then do not delay */
8381 if (node->rsrc_data->quiesce)
8384 while (!list_empty(&ctx->rsrc_ref_list)) {
8385 node = list_first_entry(&ctx->rsrc_ref_list,
8386 struct io_rsrc_node, node);
8387 /* recycle ref nodes in order */
8390 list_del(&node->node);
8391 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8393 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8396 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8399 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8401 struct io_rsrc_node *ref_node;
8403 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8407 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8412 INIT_LIST_HEAD(&ref_node->node);
8413 INIT_LIST_HEAD(&ref_node->rsrc_list);
8414 ref_node->done = false;
8418 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8419 struct io_rsrc_data *data_to_kill)
8420 __must_hold(&ctx->uring_lock)
8422 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8423 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8425 io_rsrc_refs_drop(ctx);
8428 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8430 rsrc_node->rsrc_data = data_to_kill;
8431 spin_lock_irq(&ctx->rsrc_ref_lock);
8432 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8433 spin_unlock_irq(&ctx->rsrc_ref_lock);
8435 atomic_inc(&data_to_kill->refs);
8436 percpu_ref_kill(&rsrc_node->refs);
8437 ctx->rsrc_node = NULL;
8440 if (!ctx->rsrc_node) {
8441 ctx->rsrc_node = ctx->rsrc_backup_node;
8442 ctx->rsrc_backup_node = NULL;
8446 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8448 if (ctx->rsrc_backup_node)
8450 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8451 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8454 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8455 struct io_ring_ctx *ctx)
8459 /* As we may drop ->uring_lock, other task may have started quiesce */
8463 data->quiesce = true;
8465 ret = io_rsrc_node_switch_start(ctx);
8468 io_rsrc_node_switch(ctx, data);
8470 /* kill initial ref, already quiesced if zero */
8471 if (atomic_dec_and_test(&data->refs))
8473 mutex_unlock(&ctx->uring_lock);
8474 flush_delayed_work(&ctx->rsrc_put_work);
8475 ret = wait_for_completion_interruptible(&data->done);
8477 mutex_lock(&ctx->uring_lock);
8478 if (atomic_read(&data->refs) > 0) {
8480 * it has been revived by another thread while
8483 mutex_unlock(&ctx->uring_lock);
8489 atomic_inc(&data->refs);
8490 /* wait for all works potentially completing data->done */
8491 flush_delayed_work(&ctx->rsrc_put_work);
8492 reinit_completion(&data->done);
8494 ret = io_run_task_work_sig();
8495 mutex_lock(&ctx->uring_lock);
8497 data->quiesce = false;
8502 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8504 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8505 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8507 return &data->tags[table_idx][off];
8510 static void io_rsrc_data_free(struct io_rsrc_data *data)
8512 size_t size = data->nr * sizeof(data->tags[0][0]);
8515 io_free_page_table((void **)data->tags, size);
8519 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8520 u64 __user *utags, unsigned nr,
8521 struct io_rsrc_data **pdata)
8523 struct io_rsrc_data *data;
8527 data = kzalloc(sizeof(*data), GFP_KERNEL);
8530 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8538 data->do_put = do_put;
8541 for (i = 0; i < nr; i++) {
8542 u64 *tag_slot = io_get_tag_slot(data, i);
8544 if (copy_from_user(tag_slot, &utags[i],
8550 atomic_set(&data->refs, 1);
8551 init_completion(&data->done);
8555 io_rsrc_data_free(data);
8559 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8561 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8562 GFP_KERNEL_ACCOUNT);
8563 return !!table->files;
8566 static void io_free_file_tables(struct io_file_table *table)
8568 kvfree(table->files);
8569 table->files = NULL;
8572 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8574 #if defined(CONFIG_UNIX)
8575 if (ctx->ring_sock) {
8576 struct sock *sock = ctx->ring_sock->sk;
8577 struct sk_buff *skb;
8579 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8585 for (i = 0; i < ctx->nr_user_files; i++) {
8588 file = io_file_from_index(ctx, i);
8593 io_free_file_tables(&ctx->file_table);
8594 io_rsrc_data_free(ctx->file_data);
8595 ctx->file_data = NULL;
8596 ctx->nr_user_files = 0;
8599 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8603 if (!ctx->file_data)
8605 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8607 __io_sqe_files_unregister(ctx);
8611 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8612 __releases(&sqd->lock)
8614 WARN_ON_ONCE(sqd->thread == current);
8617 * Do the dance but not conditional clear_bit() because it'd race with
8618 * other threads incrementing park_pending and setting the bit.
8620 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8621 if (atomic_dec_return(&sqd->park_pending))
8622 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8623 mutex_unlock(&sqd->lock);
8626 static void io_sq_thread_park(struct io_sq_data *sqd)
8627 __acquires(&sqd->lock)
8629 WARN_ON_ONCE(sqd->thread == current);
8631 atomic_inc(&sqd->park_pending);
8632 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8633 mutex_lock(&sqd->lock);
8635 wake_up_process(sqd->thread);
8638 static void io_sq_thread_stop(struct io_sq_data *sqd)
8640 WARN_ON_ONCE(sqd->thread == current);
8641 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8643 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8644 mutex_lock(&sqd->lock);
8646 wake_up_process(sqd->thread);
8647 mutex_unlock(&sqd->lock);
8648 wait_for_completion(&sqd->exited);
8651 static void io_put_sq_data(struct io_sq_data *sqd)
8653 if (refcount_dec_and_test(&sqd->refs)) {
8654 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8656 io_sq_thread_stop(sqd);
8661 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8663 struct io_sq_data *sqd = ctx->sq_data;
8666 io_sq_thread_park(sqd);
8667 list_del_init(&ctx->sqd_list);
8668 io_sqd_update_thread_idle(sqd);
8669 io_sq_thread_unpark(sqd);
8671 io_put_sq_data(sqd);
8672 ctx->sq_data = NULL;
8676 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8678 struct io_ring_ctx *ctx_attach;
8679 struct io_sq_data *sqd;
8682 f = fdget(p->wq_fd);
8684 return ERR_PTR(-ENXIO);
8685 if (f.file->f_op != &io_uring_fops) {
8687 return ERR_PTR(-EINVAL);
8690 ctx_attach = f.file->private_data;
8691 sqd = ctx_attach->sq_data;
8694 return ERR_PTR(-EINVAL);
8696 if (sqd->task_tgid != current->tgid) {
8698 return ERR_PTR(-EPERM);
8701 refcount_inc(&sqd->refs);
8706 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8709 struct io_sq_data *sqd;
8712 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8713 sqd = io_attach_sq_data(p);
8718 /* fall through for EPERM case, setup new sqd/task */
8719 if (PTR_ERR(sqd) != -EPERM)
8723 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8725 return ERR_PTR(-ENOMEM);
8727 atomic_set(&sqd->park_pending, 0);
8728 refcount_set(&sqd->refs, 1);
8729 INIT_LIST_HEAD(&sqd->ctx_list);
8730 mutex_init(&sqd->lock);
8731 init_waitqueue_head(&sqd->wait);
8732 init_completion(&sqd->exited);
8736 #if defined(CONFIG_UNIX)
8738 * Ensure the UNIX gc is aware of our file set, so we are certain that
8739 * the io_uring can be safely unregistered on process exit, even if we have
8740 * loops in the file referencing.
8742 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8744 struct sock *sk = ctx->ring_sock->sk;
8745 struct scm_fp_list *fpl;
8746 struct sk_buff *skb;
8749 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8753 skb = alloc_skb(0, GFP_KERNEL);
8762 fpl->user = get_uid(current_user());
8763 for (i = 0; i < nr; i++) {
8764 struct file *file = io_file_from_index(ctx, i + offset);
8768 fpl->fp[nr_files] = get_file(file);
8769 unix_inflight(fpl->user, fpl->fp[nr_files]);
8774 fpl->max = SCM_MAX_FD;
8775 fpl->count = nr_files;
8776 UNIXCB(skb).fp = fpl;
8777 skb->destructor = unix_destruct_scm;
8778 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8779 skb_queue_head(&sk->sk_receive_queue, skb);
8781 for (i = 0; i < nr_files; i++)
8792 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8793 * causes regular reference counting to break down. We rely on the UNIX
8794 * garbage collection to take care of this problem for us.
8796 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8798 unsigned left, total;
8802 left = ctx->nr_user_files;
8804 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8806 ret = __io_sqe_files_scm(ctx, this_files, total);
8810 total += this_files;
8816 while (total < ctx->nr_user_files) {
8817 struct file *file = io_file_from_index(ctx, total);
8827 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8833 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8835 struct file *file = prsrc->file;
8836 #if defined(CONFIG_UNIX)
8837 struct sock *sock = ctx->ring_sock->sk;
8838 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8839 struct sk_buff *skb;
8842 __skb_queue_head_init(&list);
8845 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8846 * remove this entry and rearrange the file array.
8848 skb = skb_dequeue(head);
8850 struct scm_fp_list *fp;
8852 fp = UNIXCB(skb).fp;
8853 for (i = 0; i < fp->count; i++) {
8856 if (fp->fp[i] != file)
8859 unix_notinflight(fp->user, fp->fp[i]);
8860 left = fp->count - 1 - i;
8862 memmove(&fp->fp[i], &fp->fp[i + 1],
8863 left * sizeof(struct file *));
8870 __skb_queue_tail(&list, skb);
8880 __skb_queue_tail(&list, skb);
8882 skb = skb_dequeue(head);
8885 if (skb_peek(&list)) {
8886 spin_lock_irq(&head->lock);
8887 while ((skb = __skb_dequeue(&list)) != NULL)
8888 __skb_queue_tail(head, skb);
8889 spin_unlock_irq(&head->lock);
8896 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8898 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8899 struct io_ring_ctx *ctx = rsrc_data->ctx;
8900 struct io_rsrc_put *prsrc, *tmp;
8902 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8903 list_del(&prsrc->list);
8906 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8908 io_ring_submit_lock(ctx, lock_ring);
8909 spin_lock(&ctx->completion_lock);
8910 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8911 io_commit_cqring(ctx);
8912 spin_unlock(&ctx->completion_lock);
8913 io_cqring_ev_posted(ctx);
8914 io_ring_submit_unlock(ctx, lock_ring);
8917 rsrc_data->do_put(ctx, prsrc);
8921 io_rsrc_node_destroy(ref_node);
8922 if (atomic_dec_and_test(&rsrc_data->refs))
8923 complete(&rsrc_data->done);
8926 static void io_rsrc_put_work(struct work_struct *work)
8928 struct io_ring_ctx *ctx;
8929 struct llist_node *node;
8931 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8932 node = llist_del_all(&ctx->rsrc_put_llist);
8935 struct io_rsrc_node *ref_node;
8936 struct llist_node *next = node->next;
8938 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8939 __io_rsrc_put_work(ref_node);
8944 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8945 unsigned nr_args, u64 __user *tags)
8947 __s32 __user *fds = (__s32 __user *) arg;
8956 if (nr_args > IORING_MAX_FIXED_FILES)
8958 if (nr_args > rlimit(RLIMIT_NOFILE))
8960 ret = io_rsrc_node_switch_start(ctx);
8963 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8969 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8972 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8973 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8977 /* allow sparse sets */
8980 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8987 if (unlikely(!file))
8991 * Don't allow io_uring instances to be registered. If UNIX
8992 * isn't enabled, then this causes a reference cycle and this
8993 * instance can never get freed. If UNIX is enabled we'll
8994 * handle it just fine, but there's still no point in allowing
8995 * a ring fd as it doesn't support regular read/write anyway.
8997 if (file->f_op == &io_uring_fops) {
9001 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
9004 ret = io_sqe_files_scm(ctx);
9006 __io_sqe_files_unregister(ctx);
9010 io_rsrc_node_switch(ctx, NULL);
9013 for (i = 0; i < ctx->nr_user_files; i++) {
9014 file = io_file_from_index(ctx, i);
9018 io_free_file_tables(&ctx->file_table);
9019 ctx->nr_user_files = 0;
9021 io_rsrc_data_free(ctx->file_data);
9022 ctx->file_data = NULL;
9026 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
9029 #if defined(CONFIG_UNIX)
9030 struct sock *sock = ctx->ring_sock->sk;
9031 struct sk_buff_head *head = &sock->sk_receive_queue;
9032 struct sk_buff *skb;
9035 * See if we can merge this file into an existing skb SCM_RIGHTS
9036 * file set. If there's no room, fall back to allocating a new skb
9037 * and filling it in.
9039 spin_lock_irq(&head->lock);
9040 skb = skb_peek(head);
9042 struct scm_fp_list *fpl = UNIXCB(skb).fp;
9044 if (fpl->count < SCM_MAX_FD) {
9045 __skb_unlink(skb, head);
9046 spin_unlock_irq(&head->lock);
9047 fpl->fp[fpl->count] = get_file(file);
9048 unix_inflight(fpl->user, fpl->fp[fpl->count]);
9050 spin_lock_irq(&head->lock);
9051 __skb_queue_head(head, skb);
9056 spin_unlock_irq(&head->lock);
9063 return __io_sqe_files_scm(ctx, 1, index);
9069 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9070 struct io_rsrc_node *node, void *rsrc)
9072 struct io_rsrc_put *prsrc;
9074 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9078 prsrc->tag = *io_get_tag_slot(data, idx);
9080 list_add(&prsrc->list, &node->rsrc_list);
9084 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9085 unsigned int issue_flags, u32 slot_index)
9087 struct io_ring_ctx *ctx = req->ctx;
9088 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9089 bool needs_switch = false;
9090 struct io_fixed_file *file_slot;
9093 io_ring_submit_lock(ctx, needs_lock);
9094 if (file->f_op == &io_uring_fops)
9097 if (!ctx->file_data)
9100 if (slot_index >= ctx->nr_user_files)
9103 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9104 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9106 if (file_slot->file_ptr) {
9107 struct file *old_file;
9109 ret = io_rsrc_node_switch_start(ctx);
9113 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9114 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9115 ctx->rsrc_node, old_file);
9118 file_slot->file_ptr = 0;
9119 needs_switch = true;
9122 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9123 io_fixed_file_set(file_slot, file);
9124 ret = io_sqe_file_register(ctx, file, slot_index);
9126 file_slot->file_ptr = 0;
9133 io_rsrc_node_switch(ctx, ctx->file_data);
9134 io_ring_submit_unlock(ctx, needs_lock);
9140 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9142 unsigned int offset = req->close.file_slot - 1;
9143 struct io_ring_ctx *ctx = req->ctx;
9144 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9145 struct io_fixed_file *file_slot;
9149 io_ring_submit_lock(ctx, needs_lock);
9151 if (unlikely(!ctx->file_data))
9154 if (offset >= ctx->nr_user_files)
9156 ret = io_rsrc_node_switch_start(ctx);
9160 i = array_index_nospec(offset, ctx->nr_user_files);
9161 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9163 if (!file_slot->file_ptr)
9166 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9167 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9171 file_slot->file_ptr = 0;
9172 io_rsrc_node_switch(ctx, ctx->file_data);
9175 io_ring_submit_unlock(ctx, needs_lock);
9179 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9180 struct io_uring_rsrc_update2 *up,
9183 u64 __user *tags = u64_to_user_ptr(up->tags);
9184 __s32 __user *fds = u64_to_user_ptr(up->data);
9185 struct io_rsrc_data *data = ctx->file_data;
9186 struct io_fixed_file *file_slot;
9190 bool needs_switch = false;
9192 if (!ctx->file_data)
9194 if (up->offset + nr_args > ctx->nr_user_files)
9197 for (done = 0; done < nr_args; done++) {
9200 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9201 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9205 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9209 if (fd == IORING_REGISTER_FILES_SKIP)
9212 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9213 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9215 if (file_slot->file_ptr) {
9216 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9217 err = io_queue_rsrc_removal(data, up->offset + done,
9218 ctx->rsrc_node, file);
9221 file_slot->file_ptr = 0;
9222 needs_switch = true;
9231 * Don't allow io_uring instances to be registered. If
9232 * UNIX isn't enabled, then this causes a reference
9233 * cycle and this instance can never get freed. If UNIX
9234 * is enabled we'll handle it just fine, but there's
9235 * still no point in allowing a ring fd as it doesn't
9236 * support regular read/write anyway.
9238 if (file->f_op == &io_uring_fops) {
9243 *io_get_tag_slot(data, up->offset + done) = tag;
9244 io_fixed_file_set(file_slot, file);
9245 err = io_sqe_file_register(ctx, file, i);
9247 file_slot->file_ptr = 0;
9255 io_rsrc_node_switch(ctx, data);
9256 return done ? done : err;
9259 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9260 struct task_struct *task)
9262 struct io_wq_hash *hash;
9263 struct io_wq_data data;
9264 unsigned int concurrency;
9266 mutex_lock(&ctx->uring_lock);
9267 hash = ctx->hash_map;
9269 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9271 mutex_unlock(&ctx->uring_lock);
9272 return ERR_PTR(-ENOMEM);
9274 refcount_set(&hash->refs, 1);
9275 init_waitqueue_head(&hash->wait);
9276 ctx->hash_map = hash;
9278 mutex_unlock(&ctx->uring_lock);
9282 data.free_work = io_wq_free_work;
9283 data.do_work = io_wq_submit_work;
9285 /* Do QD, or 4 * CPUS, whatever is smallest */
9286 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9288 return io_wq_create(concurrency, &data);
9291 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9292 struct io_ring_ctx *ctx)
9294 struct io_uring_task *tctx;
9297 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9298 if (unlikely(!tctx))
9301 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9302 sizeof(struct file *), GFP_KERNEL);
9303 if (unlikely(!tctx->registered_rings)) {
9308 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9309 if (unlikely(ret)) {
9310 kfree(tctx->registered_rings);
9315 tctx->io_wq = io_init_wq_offload(ctx, task);
9316 if (IS_ERR(tctx->io_wq)) {
9317 ret = PTR_ERR(tctx->io_wq);
9318 percpu_counter_destroy(&tctx->inflight);
9319 kfree(tctx->registered_rings);
9325 init_waitqueue_head(&tctx->wait);
9326 atomic_set(&tctx->in_idle, 0);
9327 atomic_set(&tctx->inflight_tracked, 0);
9328 task->io_uring = tctx;
9329 spin_lock_init(&tctx->task_lock);
9330 INIT_WQ_LIST(&tctx->task_list);
9331 INIT_WQ_LIST(&tctx->prior_task_list);
9332 init_task_work(&tctx->task_work, tctx_task_work);
9336 void __io_uring_free(struct task_struct *tsk)
9338 struct io_uring_task *tctx = tsk->io_uring;
9340 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9341 WARN_ON_ONCE(tctx->io_wq);
9342 WARN_ON_ONCE(tctx->cached_refs);
9344 kfree(tctx->registered_rings);
9345 percpu_counter_destroy(&tctx->inflight);
9347 tsk->io_uring = NULL;
9350 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9351 struct io_uring_params *p)
9355 /* Retain compatibility with failing for an invalid attach attempt */
9356 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9357 IORING_SETUP_ATTACH_WQ) {
9360 f = fdget(p->wq_fd);
9363 if (f.file->f_op != &io_uring_fops) {
9369 if (ctx->flags & IORING_SETUP_SQPOLL) {
9370 struct task_struct *tsk;
9371 struct io_sq_data *sqd;
9374 ret = security_uring_sqpoll();
9378 sqd = io_get_sq_data(p, &attached);
9384 ctx->sq_creds = get_current_cred();
9386 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9387 if (!ctx->sq_thread_idle)
9388 ctx->sq_thread_idle = HZ;
9390 io_sq_thread_park(sqd);
9391 list_add(&ctx->sqd_list, &sqd->ctx_list);
9392 io_sqd_update_thread_idle(sqd);
9393 /* don't attach to a dying SQPOLL thread, would be racy */
9394 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9395 io_sq_thread_unpark(sqd);
9402 if (p->flags & IORING_SETUP_SQ_AFF) {
9403 int cpu = p->sq_thread_cpu;
9406 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9413 sqd->task_pid = current->pid;
9414 sqd->task_tgid = current->tgid;
9415 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9422 ret = io_uring_alloc_task_context(tsk, ctx);
9423 wake_up_new_task(tsk);
9426 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9427 /* Can't have SQ_AFF without SQPOLL */
9434 complete(&ctx->sq_data->exited);
9436 io_sq_thread_finish(ctx);
9440 static inline void __io_unaccount_mem(struct user_struct *user,
9441 unsigned long nr_pages)
9443 atomic_long_sub(nr_pages, &user->locked_vm);
9446 static inline int __io_account_mem(struct user_struct *user,
9447 unsigned long nr_pages)
9449 unsigned long page_limit, cur_pages, new_pages;
9451 /* Don't allow more pages than we can safely lock */
9452 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9455 cur_pages = atomic_long_read(&user->locked_vm);
9456 new_pages = cur_pages + nr_pages;
9457 if (new_pages > page_limit)
9459 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9460 new_pages) != cur_pages);
9465 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9468 __io_unaccount_mem(ctx->user, nr_pages);
9470 if (ctx->mm_account)
9471 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9474 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9479 ret = __io_account_mem(ctx->user, nr_pages);
9484 if (ctx->mm_account)
9485 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9490 static void io_mem_free(void *ptr)
9497 page = virt_to_head_page(ptr);
9498 if (put_page_testzero(page))
9499 free_compound_page(page);
9502 static void *io_mem_alloc(size_t size)
9504 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9506 return (void *) __get_free_pages(gfp, get_order(size));
9509 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9512 struct io_rings *rings;
9513 size_t off, sq_array_size;
9515 off = struct_size(rings, cqes, cq_entries);
9516 if (off == SIZE_MAX)
9520 off = ALIGN(off, SMP_CACHE_BYTES);
9528 sq_array_size = array_size(sizeof(u32), sq_entries);
9529 if (sq_array_size == SIZE_MAX)
9532 if (check_add_overflow(off, sq_array_size, &off))
9538 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9540 struct io_mapped_ubuf *imu = *slot;
9543 if (imu != ctx->dummy_ubuf) {
9544 for (i = 0; i < imu->nr_bvecs; i++)
9545 unpin_user_page(imu->bvec[i].bv_page);
9546 if (imu->acct_pages)
9547 io_unaccount_mem(ctx, imu->acct_pages);
9553 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9555 io_buffer_unmap(ctx, &prsrc->buf);
9559 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9563 for (i = 0; i < ctx->nr_user_bufs; i++)
9564 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9565 kfree(ctx->user_bufs);
9566 io_rsrc_data_free(ctx->buf_data);
9567 ctx->user_bufs = NULL;
9568 ctx->buf_data = NULL;
9569 ctx->nr_user_bufs = 0;
9572 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9579 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9581 __io_sqe_buffers_unregister(ctx);
9585 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9586 void __user *arg, unsigned index)
9588 struct iovec __user *src;
9590 #ifdef CONFIG_COMPAT
9592 struct compat_iovec __user *ciovs;
9593 struct compat_iovec ciov;
9595 ciovs = (struct compat_iovec __user *) arg;
9596 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9599 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9600 dst->iov_len = ciov.iov_len;
9604 src = (struct iovec __user *) arg;
9605 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9611 * Not super efficient, but this is just a registration time. And we do cache
9612 * the last compound head, so generally we'll only do a full search if we don't
9615 * We check if the given compound head page has already been accounted, to
9616 * avoid double accounting it. This allows us to account the full size of the
9617 * page, not just the constituent pages of a huge page.
9619 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9620 int nr_pages, struct page *hpage)
9624 /* check current page array */
9625 for (i = 0; i < nr_pages; i++) {
9626 if (!PageCompound(pages[i]))
9628 if (compound_head(pages[i]) == hpage)
9632 /* check previously registered pages */
9633 for (i = 0; i < ctx->nr_user_bufs; i++) {
9634 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9636 for (j = 0; j < imu->nr_bvecs; j++) {
9637 if (!PageCompound(imu->bvec[j].bv_page))
9639 if (compound_head(imu->bvec[j].bv_page) == hpage)
9647 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9648 int nr_pages, struct io_mapped_ubuf *imu,
9649 struct page **last_hpage)
9653 imu->acct_pages = 0;
9654 for (i = 0; i < nr_pages; i++) {
9655 if (!PageCompound(pages[i])) {
9660 hpage = compound_head(pages[i]);
9661 if (hpage == *last_hpage)
9663 *last_hpage = hpage;
9664 if (headpage_already_acct(ctx, pages, i, hpage))
9666 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9670 if (!imu->acct_pages)
9673 ret = io_account_mem(ctx, imu->acct_pages);
9675 imu->acct_pages = 0;
9679 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9680 struct io_mapped_ubuf **pimu,
9681 struct page **last_hpage)
9683 struct io_mapped_ubuf *imu = NULL;
9684 struct vm_area_struct **vmas = NULL;
9685 struct page **pages = NULL;
9686 unsigned long off, start, end, ubuf;
9688 int ret, pret, nr_pages, i;
9690 if (!iov->iov_base) {
9691 *pimu = ctx->dummy_ubuf;
9695 ubuf = (unsigned long) iov->iov_base;
9696 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9697 start = ubuf >> PAGE_SHIFT;
9698 nr_pages = end - start;
9703 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9707 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9712 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9717 mmap_read_lock(current->mm);
9718 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9720 if (pret == nr_pages) {
9721 /* don't support file backed memory */
9722 for (i = 0; i < nr_pages; i++) {
9723 struct vm_area_struct *vma = vmas[i];
9725 if (vma_is_shmem(vma))
9728 !is_file_hugepages(vma->vm_file)) {
9734 ret = pret < 0 ? pret : -EFAULT;
9736 mmap_read_unlock(current->mm);
9739 * if we did partial map, or found file backed vmas,
9740 * release any pages we did get
9743 unpin_user_pages(pages, pret);
9747 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9749 unpin_user_pages(pages, pret);
9753 off = ubuf & ~PAGE_MASK;
9754 size = iov->iov_len;
9755 for (i = 0; i < nr_pages; i++) {
9758 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9759 imu->bvec[i].bv_page = pages[i];
9760 imu->bvec[i].bv_len = vec_len;
9761 imu->bvec[i].bv_offset = off;
9765 /* store original address for later verification */
9767 imu->ubuf_end = ubuf + iov->iov_len;
9768 imu->nr_bvecs = nr_pages;
9779 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9781 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9782 return ctx->user_bufs ? 0 : -ENOMEM;
9785 static int io_buffer_validate(struct iovec *iov)
9787 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9790 * Don't impose further limits on the size and buffer
9791 * constraints here, we'll -EINVAL later when IO is
9792 * submitted if they are wrong.
9795 return iov->iov_len ? -EFAULT : 0;
9799 /* arbitrary limit, but we need something */
9800 if (iov->iov_len > SZ_1G)
9803 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9809 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9810 unsigned int nr_args, u64 __user *tags)
9812 struct page *last_hpage = NULL;
9813 struct io_rsrc_data *data;
9819 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9821 ret = io_rsrc_node_switch_start(ctx);
9824 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9827 ret = io_buffers_map_alloc(ctx, nr_args);
9829 io_rsrc_data_free(data);
9833 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9834 ret = io_copy_iov(ctx, &iov, arg, i);
9837 ret = io_buffer_validate(&iov);
9840 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9845 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9851 WARN_ON_ONCE(ctx->buf_data);
9853 ctx->buf_data = data;
9855 __io_sqe_buffers_unregister(ctx);
9857 io_rsrc_node_switch(ctx, NULL);
9861 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9862 struct io_uring_rsrc_update2 *up,
9863 unsigned int nr_args)
9865 u64 __user *tags = u64_to_user_ptr(up->tags);
9866 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9867 struct page *last_hpage = NULL;
9868 bool needs_switch = false;
9874 if (up->offset + nr_args > ctx->nr_user_bufs)
9877 for (done = 0; done < nr_args; done++) {
9878 struct io_mapped_ubuf *imu;
9879 int offset = up->offset + done;
9882 err = io_copy_iov(ctx, &iov, iovs, done);
9885 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9889 err = io_buffer_validate(&iov);
9892 if (!iov.iov_base && tag) {
9896 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9900 i = array_index_nospec(offset, ctx->nr_user_bufs);
9901 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9902 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9903 ctx->rsrc_node, ctx->user_bufs[i]);
9904 if (unlikely(err)) {
9905 io_buffer_unmap(ctx, &imu);
9908 ctx->user_bufs[i] = NULL;
9909 needs_switch = true;
9912 ctx->user_bufs[i] = imu;
9913 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9917 io_rsrc_node_switch(ctx, ctx->buf_data);
9918 return done ? done : err;
9921 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9922 unsigned int eventfd_async)
9924 struct io_ev_fd *ev_fd;
9925 __s32 __user *fds = arg;
9928 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9929 lockdep_is_held(&ctx->uring_lock));
9933 if (copy_from_user(&fd, fds, sizeof(*fds)))
9936 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9940 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9941 if (IS_ERR(ev_fd->cq_ev_fd)) {
9942 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9946 ev_fd->eventfd_async = eventfd_async;
9947 ctx->has_evfd = true;
9948 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
9952 static void io_eventfd_put(struct rcu_head *rcu)
9954 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9956 eventfd_ctx_put(ev_fd->cq_ev_fd);
9960 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9962 struct io_ev_fd *ev_fd;
9964 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9965 lockdep_is_held(&ctx->uring_lock));
9967 ctx->has_evfd = false;
9968 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9969 call_rcu(&ev_fd->rcu, io_eventfd_put);
9976 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9980 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++) {
9981 struct list_head *list = &ctx->io_buffers[i];
9983 while (!list_empty(list)) {
9984 struct io_buffer_list *bl;
9986 bl = list_first_entry(list, struct io_buffer_list, list);
9987 __io_remove_buffers(ctx, bl, -1U);
9988 list_del(&bl->list);
9993 while (!list_empty(&ctx->io_buffers_pages)) {
9996 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9997 list_del_init(&page->lru);
10002 static void io_req_caches_free(struct io_ring_ctx *ctx)
10004 struct io_submit_state *state = &ctx->submit_state;
10007 mutex_lock(&ctx->uring_lock);
10008 io_flush_cached_locked_reqs(ctx, state);
10010 while (state->free_list.next) {
10011 struct io_wq_work_node *node;
10012 struct io_kiocb *req;
10014 node = wq_stack_extract(&state->free_list);
10015 req = container_of(node, struct io_kiocb, comp_list);
10016 kmem_cache_free(req_cachep, req);
10020 percpu_ref_put_many(&ctx->refs, nr);
10021 mutex_unlock(&ctx->uring_lock);
10024 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10026 if (data && !atomic_dec_and_test(&data->refs))
10027 wait_for_completion(&data->done);
10030 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10032 struct async_poll *apoll;
10034 while (!list_empty(&ctx->apoll_cache)) {
10035 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10037 list_del(&apoll->poll.wait.entry);
10042 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10044 io_sq_thread_finish(ctx);
10046 if (ctx->mm_account) {
10047 mmdrop(ctx->mm_account);
10048 ctx->mm_account = NULL;
10051 io_rsrc_refs_drop(ctx);
10052 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10053 io_wait_rsrc_data(ctx->buf_data);
10054 io_wait_rsrc_data(ctx->file_data);
10056 mutex_lock(&ctx->uring_lock);
10058 __io_sqe_buffers_unregister(ctx);
10059 if (ctx->file_data)
10060 __io_sqe_files_unregister(ctx);
10062 __io_cqring_overflow_flush(ctx, true);
10063 io_eventfd_unregister(ctx);
10064 io_flush_apoll_cache(ctx);
10065 mutex_unlock(&ctx->uring_lock);
10066 io_destroy_buffers(ctx);
10068 put_cred(ctx->sq_creds);
10070 /* there are no registered resources left, nobody uses it */
10071 if (ctx->rsrc_node)
10072 io_rsrc_node_destroy(ctx->rsrc_node);
10073 if (ctx->rsrc_backup_node)
10074 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10075 flush_delayed_work(&ctx->rsrc_put_work);
10076 flush_delayed_work(&ctx->fallback_work);
10078 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10079 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10081 #if defined(CONFIG_UNIX)
10082 if (ctx->ring_sock) {
10083 ctx->ring_sock->file = NULL; /* so that iput() is called */
10084 sock_release(ctx->ring_sock);
10087 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10089 io_mem_free(ctx->rings);
10090 io_mem_free(ctx->sq_sqes);
10092 percpu_ref_exit(&ctx->refs);
10093 free_uid(ctx->user);
10094 io_req_caches_free(ctx);
10096 io_wq_put_hash(ctx->hash_map);
10097 io_free_napi_list(ctx);
10098 kfree(ctx->cancel_hash);
10099 kfree(ctx->dummy_ubuf);
10100 kfree(ctx->io_buffers);
10104 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10106 struct io_ring_ctx *ctx = file->private_data;
10109 poll_wait(file, &ctx->cq_wait, wait);
10111 * synchronizes with barrier from wq_has_sleeper call in
10115 if (!io_sqring_full(ctx))
10116 mask |= EPOLLOUT | EPOLLWRNORM;
10119 * Don't flush cqring overflow list here, just do a simple check.
10120 * Otherwise there could possible be ABBA deadlock:
10123 * lock(&ctx->uring_lock);
10125 * lock(&ctx->uring_lock);
10128 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10129 * pushs them to do the flush.
10131 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
10132 mask |= EPOLLIN | EPOLLRDNORM;
10137 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10139 const struct cred *creds;
10141 creds = xa_erase(&ctx->personalities, id);
10150 struct io_tctx_exit {
10151 struct callback_head task_work;
10152 struct completion completion;
10153 struct io_ring_ctx *ctx;
10156 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10158 struct io_uring_task *tctx = current->io_uring;
10159 struct io_tctx_exit *work;
10161 work = container_of(cb, struct io_tctx_exit, task_work);
10163 * When @in_idle, we're in cancellation and it's racy to remove the
10164 * node. It'll be removed by the end of cancellation, just ignore it.
10166 if (!atomic_read(&tctx->in_idle))
10167 io_uring_del_tctx_node((unsigned long)work->ctx);
10168 complete(&work->completion);
10171 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10173 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10175 return req->ctx == data;
10178 static __cold void io_ring_exit_work(struct work_struct *work)
10180 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10181 unsigned long timeout = jiffies + HZ * 60 * 5;
10182 unsigned long interval = HZ / 20;
10183 struct io_tctx_exit exit;
10184 struct io_tctx_node *node;
10188 * If we're doing polled IO and end up having requests being
10189 * submitted async (out-of-line), then completions can come in while
10190 * we're waiting for refs to drop. We need to reap these manually,
10191 * as nobody else will be looking for them.
10194 io_uring_try_cancel_requests(ctx, NULL, true);
10195 if (ctx->sq_data) {
10196 struct io_sq_data *sqd = ctx->sq_data;
10197 struct task_struct *tsk;
10199 io_sq_thread_park(sqd);
10201 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10202 io_wq_cancel_cb(tsk->io_uring->io_wq,
10203 io_cancel_ctx_cb, ctx, true);
10204 io_sq_thread_unpark(sqd);
10207 io_req_caches_free(ctx);
10209 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10210 /* there is little hope left, don't run it too often */
10211 interval = HZ * 60;
10213 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10215 init_completion(&exit.completion);
10216 init_task_work(&exit.task_work, io_tctx_exit_cb);
10219 * Some may use context even when all refs and requests have been put,
10220 * and they are free to do so while still holding uring_lock or
10221 * completion_lock, see io_req_task_submit(). Apart from other work,
10222 * this lock/unlock section also waits them to finish.
10224 mutex_lock(&ctx->uring_lock);
10225 while (!list_empty(&ctx->tctx_list)) {
10226 WARN_ON_ONCE(time_after(jiffies, timeout));
10228 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10230 /* don't spin on a single task if cancellation failed */
10231 list_rotate_left(&ctx->tctx_list);
10232 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10233 if (WARN_ON_ONCE(ret))
10236 mutex_unlock(&ctx->uring_lock);
10237 wait_for_completion(&exit.completion);
10238 mutex_lock(&ctx->uring_lock);
10240 mutex_unlock(&ctx->uring_lock);
10241 spin_lock(&ctx->completion_lock);
10242 spin_unlock(&ctx->completion_lock);
10244 io_ring_ctx_free(ctx);
10247 /* Returns true if we found and killed one or more timeouts */
10248 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10249 struct task_struct *tsk, bool cancel_all)
10251 struct io_kiocb *req, *tmp;
10254 spin_lock(&ctx->completion_lock);
10255 spin_lock_irq(&ctx->timeout_lock);
10256 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10257 if (io_match_task(req, tsk, cancel_all)) {
10258 io_kill_timeout(req, -ECANCELED);
10262 spin_unlock_irq(&ctx->timeout_lock);
10264 io_commit_cqring(ctx);
10265 spin_unlock(&ctx->completion_lock);
10267 io_cqring_ev_posted(ctx);
10268 return canceled != 0;
10271 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10273 unsigned long index;
10274 struct creds *creds;
10276 mutex_lock(&ctx->uring_lock);
10277 percpu_ref_kill(&ctx->refs);
10279 __io_cqring_overflow_flush(ctx, true);
10280 xa_for_each(&ctx->personalities, index, creds)
10281 io_unregister_personality(ctx, index);
10282 mutex_unlock(&ctx->uring_lock);
10284 io_kill_timeouts(ctx, NULL, true);
10285 io_poll_remove_all(ctx, NULL, true);
10287 /* if we failed setting up the ctx, we might not have any rings */
10288 io_iopoll_try_reap_events(ctx);
10290 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10292 * Use system_unbound_wq to avoid spawning tons of event kworkers
10293 * if we're exiting a ton of rings at the same time. It just adds
10294 * noise and overhead, there's no discernable change in runtime
10295 * over using system_wq.
10297 queue_work(system_unbound_wq, &ctx->exit_work);
10300 static int io_uring_release(struct inode *inode, struct file *file)
10302 struct io_ring_ctx *ctx = file->private_data;
10304 file->private_data = NULL;
10305 io_ring_ctx_wait_and_kill(ctx);
10309 struct io_task_cancel {
10310 struct task_struct *task;
10314 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10316 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10317 struct io_task_cancel *cancel = data;
10319 return io_match_task_safe(req, cancel->task, cancel->all);
10322 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10323 struct task_struct *task,
10326 struct io_defer_entry *de;
10329 spin_lock(&ctx->completion_lock);
10330 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10331 if (io_match_task_safe(de->req, task, cancel_all)) {
10332 list_cut_position(&list, &ctx->defer_list, &de->list);
10336 spin_unlock(&ctx->completion_lock);
10337 if (list_empty(&list))
10340 while (!list_empty(&list)) {
10341 de = list_first_entry(&list, struct io_defer_entry, list);
10342 list_del_init(&de->list);
10343 io_req_complete_failed(de->req, -ECANCELED);
10349 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10351 struct io_tctx_node *node;
10352 enum io_wq_cancel cret;
10355 mutex_lock(&ctx->uring_lock);
10356 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10357 struct io_uring_task *tctx = node->task->io_uring;
10360 * io_wq will stay alive while we hold uring_lock, because it's
10361 * killed after ctx nodes, which requires to take the lock.
10363 if (!tctx || !tctx->io_wq)
10365 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10366 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10368 mutex_unlock(&ctx->uring_lock);
10373 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10374 struct task_struct *task,
10377 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10378 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10381 enum io_wq_cancel cret;
10385 ret |= io_uring_try_cancel_iowq(ctx);
10386 } else if (tctx && tctx->io_wq) {
10388 * Cancels requests of all rings, not only @ctx, but
10389 * it's fine as the task is in exit/exec.
10391 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10393 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10396 /* SQPOLL thread does its own polling */
10397 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10398 (ctx->sq_data && ctx->sq_data->thread == current)) {
10399 while (!wq_list_empty(&ctx->iopoll_list)) {
10400 io_iopoll_try_reap_events(ctx);
10405 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10406 ret |= io_poll_remove_all(ctx, task, cancel_all);
10407 ret |= io_kill_timeouts(ctx, task, cancel_all);
10409 ret |= io_run_task_work();
10416 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10418 struct io_uring_task *tctx = current->io_uring;
10419 struct io_tctx_node *node;
10422 if (unlikely(!tctx)) {
10423 ret = io_uring_alloc_task_context(current, ctx);
10427 tctx = current->io_uring;
10428 if (ctx->iowq_limits_set) {
10429 unsigned int limits[2] = { ctx->iowq_limits[0],
10430 ctx->iowq_limits[1], };
10432 ret = io_wq_max_workers(tctx->io_wq, limits);
10437 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10438 node = kmalloc(sizeof(*node), GFP_KERNEL);
10442 node->task = current;
10444 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10445 node, GFP_KERNEL));
10451 mutex_lock(&ctx->uring_lock);
10452 list_add(&node->ctx_node, &ctx->tctx_list);
10453 mutex_unlock(&ctx->uring_lock);
10460 * Note that this task has used io_uring. We use it for cancelation purposes.
10462 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10464 struct io_uring_task *tctx = current->io_uring;
10466 if (likely(tctx && tctx->last == ctx))
10468 return __io_uring_add_tctx_node(ctx);
10472 * Remove this io_uring_file -> task mapping.
10474 static __cold void io_uring_del_tctx_node(unsigned long index)
10476 struct io_uring_task *tctx = current->io_uring;
10477 struct io_tctx_node *node;
10481 node = xa_erase(&tctx->xa, index);
10485 WARN_ON_ONCE(current != node->task);
10486 WARN_ON_ONCE(list_empty(&node->ctx_node));
10488 mutex_lock(&node->ctx->uring_lock);
10489 list_del(&node->ctx_node);
10490 mutex_unlock(&node->ctx->uring_lock);
10492 if (tctx->last == node->ctx)
10497 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10499 struct io_wq *wq = tctx->io_wq;
10500 struct io_tctx_node *node;
10501 unsigned long index;
10503 xa_for_each(&tctx->xa, index, node) {
10504 io_uring_del_tctx_node(index);
10509 * Must be after io_uring_del_tctx_node() (removes nodes under
10510 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10512 io_wq_put_and_exit(wq);
10513 tctx->io_wq = NULL;
10517 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10520 return atomic_read(&tctx->inflight_tracked);
10521 return percpu_counter_sum(&tctx->inflight);
10525 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10526 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10528 static __cold void io_uring_cancel_generic(bool cancel_all,
10529 struct io_sq_data *sqd)
10531 struct io_uring_task *tctx = current->io_uring;
10532 struct io_ring_ctx *ctx;
10536 WARN_ON_ONCE(sqd && sqd->thread != current);
10538 if (!current->io_uring)
10541 io_wq_exit_start(tctx->io_wq);
10543 atomic_inc(&tctx->in_idle);
10545 io_uring_drop_tctx_refs(current);
10546 /* read completions before cancelations */
10547 inflight = tctx_inflight(tctx, !cancel_all);
10552 struct io_tctx_node *node;
10553 unsigned long index;
10555 xa_for_each(&tctx->xa, index, node) {
10556 /* sqpoll task will cancel all its requests */
10557 if (node->ctx->sq_data)
10559 io_uring_try_cancel_requests(node->ctx, current,
10563 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10564 io_uring_try_cancel_requests(ctx, current,
10568 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10569 io_run_task_work();
10570 io_uring_drop_tctx_refs(current);
10573 * If we've seen completions, retry without waiting. This
10574 * avoids a race where a completion comes in before we did
10575 * prepare_to_wait().
10577 if (inflight == tctx_inflight(tctx, !cancel_all))
10579 finish_wait(&tctx->wait, &wait);
10582 io_uring_clean_tctx(tctx);
10585 * We shouldn't run task_works after cancel, so just leave
10586 * ->in_idle set for normal exit.
10588 atomic_dec(&tctx->in_idle);
10589 /* for exec all current's requests should be gone, kill tctx */
10590 __io_uring_free(current);
10594 void __io_uring_cancel(bool cancel_all)
10596 io_uring_cancel_generic(cancel_all, NULL);
10599 void io_uring_unreg_ringfd(void)
10601 struct io_uring_task *tctx = current->io_uring;
10604 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10605 if (tctx->registered_rings[i]) {
10606 fput(tctx->registered_rings[i]);
10607 tctx->registered_rings[i] = NULL;
10612 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10613 int start, int end)
10618 for (offset = start; offset < end; offset++) {
10619 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10620 if (tctx->registered_rings[offset])
10626 } else if (file->f_op != &io_uring_fops) {
10628 return -EOPNOTSUPP;
10630 tctx->registered_rings[offset] = file;
10638 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10639 * invocation. User passes in an array of struct io_uring_rsrc_update
10640 * with ->data set to the ring_fd, and ->offset given for the desired
10641 * index. If no index is desired, application may set ->offset == -1U
10642 * and we'll find an available index. Returns number of entries
10643 * successfully processed, or < 0 on error if none were processed.
10645 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10648 struct io_uring_rsrc_update __user *arg = __arg;
10649 struct io_uring_rsrc_update reg;
10650 struct io_uring_task *tctx;
10653 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10656 mutex_unlock(&ctx->uring_lock);
10657 ret = io_uring_add_tctx_node(ctx);
10658 mutex_lock(&ctx->uring_lock);
10662 tctx = current->io_uring;
10663 for (i = 0; i < nr_args; i++) {
10666 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10671 if (reg.offset == -1U) {
10673 end = IO_RINGFD_REG_MAX;
10675 if (reg.offset >= IO_RINGFD_REG_MAX) {
10679 start = reg.offset;
10683 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10688 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10689 fput(tctx->registered_rings[reg.offset]);
10690 tctx->registered_rings[reg.offset] = NULL;
10696 return i ? i : ret;
10699 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10702 struct io_uring_rsrc_update __user *arg = __arg;
10703 struct io_uring_task *tctx = current->io_uring;
10704 struct io_uring_rsrc_update reg;
10707 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10712 for (i = 0; i < nr_args; i++) {
10713 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10717 if (reg.offset >= IO_RINGFD_REG_MAX) {
10722 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10723 if (tctx->registered_rings[reg.offset]) {
10724 fput(tctx->registered_rings[reg.offset]);
10725 tctx->registered_rings[reg.offset] = NULL;
10729 return i ? i : ret;
10732 static void *io_uring_validate_mmap_request(struct file *file,
10733 loff_t pgoff, size_t sz)
10735 struct io_ring_ctx *ctx = file->private_data;
10736 loff_t offset = pgoff << PAGE_SHIFT;
10741 case IORING_OFF_SQ_RING:
10742 case IORING_OFF_CQ_RING:
10745 case IORING_OFF_SQES:
10746 ptr = ctx->sq_sqes;
10749 return ERR_PTR(-EINVAL);
10752 page = virt_to_head_page(ptr);
10753 if (sz > page_size(page))
10754 return ERR_PTR(-EINVAL);
10761 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10763 size_t sz = vma->vm_end - vma->vm_start;
10767 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10769 return PTR_ERR(ptr);
10771 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10772 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10775 #else /* !CONFIG_MMU */
10777 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10779 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10782 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10784 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10787 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10788 unsigned long addr, unsigned long len,
10789 unsigned long pgoff, unsigned long flags)
10793 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10795 return PTR_ERR(ptr);
10797 return (unsigned long) ptr;
10800 #endif /* !CONFIG_MMU */
10802 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10807 if (!io_sqring_full(ctx))
10809 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10811 if (!io_sqring_full(ctx))
10814 } while (!signal_pending(current));
10816 finish_wait(&ctx->sqo_sq_wait, &wait);
10820 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10821 struct __kernel_timespec __user **ts,
10822 const sigset_t __user **sig)
10824 struct io_uring_getevents_arg arg;
10827 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10828 * is just a pointer to the sigset_t.
10830 if (!(flags & IORING_ENTER_EXT_ARG)) {
10831 *sig = (const sigset_t __user *) argp;
10837 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10838 * timespec and sigset_t pointers if good.
10840 if (*argsz != sizeof(arg))
10842 if (copy_from_user(&arg, argp, sizeof(arg)))
10844 *sig = u64_to_user_ptr(arg.sigmask);
10845 *argsz = arg.sigmask_sz;
10846 *ts = u64_to_user_ptr(arg.ts);
10850 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10851 u32, min_complete, u32, flags, const void __user *, argp,
10854 struct io_ring_ctx *ctx;
10859 io_run_task_work();
10861 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10862 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10863 IORING_ENTER_REGISTERED_RING)))
10867 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10868 * need only dereference our task private array to find it.
10870 if (flags & IORING_ENTER_REGISTERED_RING) {
10871 struct io_uring_task *tctx = current->io_uring;
10873 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10875 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10876 f.file = tctx->registered_rings[fd];
10877 if (unlikely(!f.file))
10881 if (unlikely(!f.file))
10886 if (unlikely(f.file->f_op != &io_uring_fops))
10890 ctx = f.file->private_data;
10891 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10895 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10899 * For SQ polling, the thread will do all submissions and completions.
10900 * Just return the requested submit count, and wake the thread if
10901 * we were asked to.
10904 if (ctx->flags & IORING_SETUP_SQPOLL) {
10905 io_cqring_overflow_flush(ctx);
10907 if (unlikely(ctx->sq_data->thread == NULL)) {
10911 if (flags & IORING_ENTER_SQ_WAKEUP)
10912 wake_up(&ctx->sq_data->wait);
10913 if (flags & IORING_ENTER_SQ_WAIT) {
10914 ret = io_sqpoll_wait_sq(ctx);
10918 submitted = to_submit;
10919 } else if (to_submit) {
10920 ret = io_uring_add_tctx_node(ctx);
10923 mutex_lock(&ctx->uring_lock);
10924 submitted = io_submit_sqes(ctx, to_submit);
10925 mutex_unlock(&ctx->uring_lock);
10927 if (submitted != to_submit)
10930 if (flags & IORING_ENTER_GETEVENTS) {
10931 const sigset_t __user *sig;
10932 struct __kernel_timespec __user *ts;
10934 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10938 min_complete = min(min_complete, ctx->cq_entries);
10941 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10942 * space applications don't need to do io completion events
10943 * polling again, they can rely on io_sq_thread to do polling
10944 * work, which can reduce cpu usage and uring_lock contention.
10946 if (ctx->flags & IORING_SETUP_IOPOLL &&
10947 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10948 ret = io_iopoll_check(ctx, min_complete);
10950 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10955 percpu_ref_put(&ctx->refs);
10957 if (!(flags & IORING_ENTER_REGISTERED_RING))
10959 return submitted ? submitted : ret;
10962 #ifdef CONFIG_PROC_FS
10963 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10964 const struct cred *cred)
10966 struct user_namespace *uns = seq_user_ns(m);
10967 struct group_info *gi;
10972 seq_printf(m, "%5d\n", id);
10973 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10974 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10975 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10976 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10977 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10978 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10979 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10980 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10981 seq_puts(m, "\n\tGroups:\t");
10982 gi = cred->group_info;
10983 for (g = 0; g < gi->ngroups; g++) {
10984 seq_put_decimal_ull(m, g ? " " : "",
10985 from_kgid_munged(uns, gi->gid[g]));
10987 seq_puts(m, "\n\tCapEff:\t");
10988 cap = cred->cap_effective;
10989 CAP_FOR_EACH_U32(__capi)
10990 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10995 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10996 struct seq_file *m)
10998 struct io_sq_data *sq = NULL;
10999 struct io_overflow_cqe *ocqe;
11000 struct io_rings *r = ctx->rings;
11001 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11002 unsigned int sq_head = READ_ONCE(r->sq.head);
11003 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11004 unsigned int cq_head = READ_ONCE(r->cq.head);
11005 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11006 unsigned int sq_entries, cq_entries;
11011 * we may get imprecise sqe and cqe info if uring is actively running
11012 * since we get cached_sq_head and cached_cq_tail without uring_lock
11013 * and sq_tail and cq_head are changed by userspace. But it's ok since
11014 * we usually use these info when it is stuck.
11016 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11017 seq_printf(m, "SqHead:\t%u\n", sq_head);
11018 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11019 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11020 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11021 seq_printf(m, "CqHead:\t%u\n", cq_head);
11022 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11023 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11024 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11025 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11026 for (i = 0; i < sq_entries; i++) {
11027 unsigned int entry = i + sq_head;
11028 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11029 struct io_uring_sqe *sqe;
11031 if (sq_idx > sq_mask)
11033 sqe = &ctx->sq_sqes[sq_idx];
11034 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11035 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11038 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11039 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11040 for (i = 0; i < cq_entries; i++) {
11041 unsigned int entry = i + cq_head;
11042 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
11044 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11045 entry & cq_mask, cqe->user_data, cqe->res,
11050 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11051 * since fdinfo case grabs it in the opposite direction of normal use
11052 * cases. If we fail to get the lock, we just don't iterate any
11053 * structures that could be going away outside the io_uring mutex.
11055 has_lock = mutex_trylock(&ctx->uring_lock);
11057 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11063 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11064 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11065 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11066 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11067 struct file *f = io_file_from_index(ctx, i);
11070 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11072 seq_printf(m, "%5u: <none>\n", i);
11074 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11075 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11076 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11077 unsigned int len = buf->ubuf_end - buf->ubuf;
11079 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11081 if (has_lock && !xa_empty(&ctx->personalities)) {
11082 unsigned long index;
11083 const struct cred *cred;
11085 seq_printf(m, "Personalities:\n");
11086 xa_for_each(&ctx->personalities, index, cred)
11087 io_uring_show_cred(m, index, cred);
11090 mutex_unlock(&ctx->uring_lock);
11092 seq_puts(m, "PollList:\n");
11093 spin_lock(&ctx->completion_lock);
11094 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11095 struct hlist_head *list = &ctx->cancel_hash[i];
11096 struct io_kiocb *req;
11098 hlist_for_each_entry(req, list, hash_node)
11099 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11100 task_work_pending(req->task));
11103 seq_puts(m, "CqOverflowList:\n");
11104 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11105 struct io_uring_cqe *cqe = &ocqe->cqe;
11107 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11108 cqe->user_data, cqe->res, cqe->flags);
11112 spin_unlock(&ctx->completion_lock);
11115 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11117 struct io_ring_ctx *ctx = f->private_data;
11119 if (percpu_ref_tryget(&ctx->refs)) {
11120 __io_uring_show_fdinfo(ctx, m);
11121 percpu_ref_put(&ctx->refs);
11126 static const struct file_operations io_uring_fops = {
11127 .release = io_uring_release,
11128 .mmap = io_uring_mmap,
11130 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11131 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11133 .poll = io_uring_poll,
11134 #ifdef CONFIG_PROC_FS
11135 .show_fdinfo = io_uring_show_fdinfo,
11139 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11140 struct io_uring_params *p)
11142 struct io_rings *rings;
11143 size_t size, sq_array_offset;
11145 /* make sure these are sane, as we already accounted them */
11146 ctx->sq_entries = p->sq_entries;
11147 ctx->cq_entries = p->cq_entries;
11149 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
11150 if (size == SIZE_MAX)
11153 rings = io_mem_alloc(size);
11157 ctx->rings = rings;
11158 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11159 rings->sq_ring_mask = p->sq_entries - 1;
11160 rings->cq_ring_mask = p->cq_entries - 1;
11161 rings->sq_ring_entries = p->sq_entries;
11162 rings->cq_ring_entries = p->cq_entries;
11164 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11165 if (size == SIZE_MAX) {
11166 io_mem_free(ctx->rings);
11171 ctx->sq_sqes = io_mem_alloc(size);
11172 if (!ctx->sq_sqes) {
11173 io_mem_free(ctx->rings);
11181 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11185 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11189 ret = io_uring_add_tctx_node(ctx);
11194 fd_install(fd, file);
11199 * Allocate an anonymous fd, this is what constitutes the application
11200 * visible backing of an io_uring instance. The application mmaps this
11201 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11202 * we have to tie this fd to a socket for file garbage collection purposes.
11204 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11207 #if defined(CONFIG_UNIX)
11210 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11213 return ERR_PTR(ret);
11216 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11217 O_RDWR | O_CLOEXEC, NULL);
11218 #if defined(CONFIG_UNIX)
11219 if (IS_ERR(file)) {
11220 sock_release(ctx->ring_sock);
11221 ctx->ring_sock = NULL;
11223 ctx->ring_sock->file = file;
11229 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11230 struct io_uring_params __user *params)
11232 struct io_ring_ctx *ctx;
11238 if (entries > IORING_MAX_ENTRIES) {
11239 if (!(p->flags & IORING_SETUP_CLAMP))
11241 entries = IORING_MAX_ENTRIES;
11245 * Use twice as many entries for the CQ ring. It's possible for the
11246 * application to drive a higher depth than the size of the SQ ring,
11247 * since the sqes are only used at submission time. This allows for
11248 * some flexibility in overcommitting a bit. If the application has
11249 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11250 * of CQ ring entries manually.
11252 p->sq_entries = roundup_pow_of_two(entries);
11253 if (p->flags & IORING_SETUP_CQSIZE) {
11255 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11256 * to a power-of-two, if it isn't already. We do NOT impose
11257 * any cq vs sq ring sizing.
11259 if (!p->cq_entries)
11261 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11262 if (!(p->flags & IORING_SETUP_CLAMP))
11264 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11266 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11267 if (p->cq_entries < p->sq_entries)
11270 p->cq_entries = 2 * p->sq_entries;
11273 ctx = io_ring_ctx_alloc(p);
11276 ctx->compat = in_compat_syscall();
11277 if (!capable(CAP_IPC_LOCK))
11278 ctx->user = get_uid(current_user());
11281 * This is just grabbed for accounting purposes. When a process exits,
11282 * the mm is exited and dropped before the files, hence we need to hang
11283 * on to this mm purely for the purposes of being able to unaccount
11284 * memory (locked/pinned vm). It's not used for anything else.
11286 mmgrab(current->mm);
11287 ctx->mm_account = current->mm;
11289 ret = io_allocate_scq_urings(ctx, p);
11293 ret = io_sq_offload_create(ctx, p);
11296 /* always set a rsrc node */
11297 ret = io_rsrc_node_switch_start(ctx);
11300 io_rsrc_node_switch(ctx, NULL);
11302 memset(&p->sq_off, 0, sizeof(p->sq_off));
11303 p->sq_off.head = offsetof(struct io_rings, sq.head);
11304 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11305 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11306 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11307 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11308 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11309 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11311 memset(&p->cq_off, 0, sizeof(p->cq_off));
11312 p->cq_off.head = offsetof(struct io_rings, cq.head);
11313 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11314 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11315 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11316 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11317 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11318 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11320 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11321 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11322 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11323 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11324 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11325 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP;
11327 if (copy_to_user(params, p, sizeof(*p))) {
11332 file = io_uring_get_file(ctx);
11333 if (IS_ERR(file)) {
11334 ret = PTR_ERR(file);
11339 * Install ring fd as the very last thing, so we don't risk someone
11340 * having closed it before we finish setup
11342 ret = io_uring_install_fd(ctx, file);
11344 /* fput will clean it up */
11349 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11352 io_ring_ctx_wait_and_kill(ctx);
11357 * Sets up an aio uring context, and returns the fd. Applications asks for a
11358 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11359 * params structure passed in.
11361 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11363 struct io_uring_params p;
11366 if (copy_from_user(&p, params, sizeof(p)))
11368 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11373 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11374 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11375 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11376 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
11379 return io_uring_create(entries, &p, params);
11382 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11383 struct io_uring_params __user *, params)
11385 return io_uring_setup(entries, params);
11388 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11391 struct io_uring_probe *p;
11395 size = struct_size(p, ops, nr_args);
11396 if (size == SIZE_MAX)
11398 p = kzalloc(size, GFP_KERNEL);
11403 if (copy_from_user(p, arg, size))
11406 if (memchr_inv(p, 0, size))
11409 p->last_op = IORING_OP_LAST - 1;
11410 if (nr_args > IORING_OP_LAST)
11411 nr_args = IORING_OP_LAST;
11413 for (i = 0; i < nr_args; i++) {
11415 if (!io_op_defs[i].not_supported)
11416 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11421 if (copy_to_user(arg, p, size))
11428 static int io_register_personality(struct io_ring_ctx *ctx)
11430 const struct cred *creds;
11434 creds = get_current_cred();
11436 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11437 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11445 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11446 void __user *arg, unsigned int nr_args)
11448 struct io_uring_restriction *res;
11452 /* Restrictions allowed only if rings started disabled */
11453 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11456 /* We allow only a single restrictions registration */
11457 if (ctx->restrictions.registered)
11460 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11463 size = array_size(nr_args, sizeof(*res));
11464 if (size == SIZE_MAX)
11467 res = memdup_user(arg, size);
11469 return PTR_ERR(res);
11473 for (i = 0; i < nr_args; i++) {
11474 switch (res[i].opcode) {
11475 case IORING_RESTRICTION_REGISTER_OP:
11476 if (res[i].register_op >= IORING_REGISTER_LAST) {
11481 __set_bit(res[i].register_op,
11482 ctx->restrictions.register_op);
11484 case IORING_RESTRICTION_SQE_OP:
11485 if (res[i].sqe_op >= IORING_OP_LAST) {
11490 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11492 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11493 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11495 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11496 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11505 /* Reset all restrictions if an error happened */
11507 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11509 ctx->restrictions.registered = true;
11515 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11517 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11520 if (ctx->restrictions.registered)
11521 ctx->restricted = 1;
11523 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11524 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11525 wake_up(&ctx->sq_data->wait);
11529 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11530 struct io_uring_rsrc_update2 *up,
11538 if (check_add_overflow(up->offset, nr_args, &tmp))
11540 err = io_rsrc_node_switch_start(ctx);
11545 case IORING_RSRC_FILE:
11546 return __io_sqe_files_update(ctx, up, nr_args);
11547 case IORING_RSRC_BUFFER:
11548 return __io_sqe_buffers_update(ctx, up, nr_args);
11553 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11556 struct io_uring_rsrc_update2 up;
11560 memset(&up, 0, sizeof(up));
11561 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11563 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11566 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11567 unsigned size, unsigned type)
11569 struct io_uring_rsrc_update2 up;
11571 if (size != sizeof(up))
11573 if (copy_from_user(&up, arg, sizeof(up)))
11575 if (!up.nr || up.resv)
11577 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11580 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11581 unsigned int size, unsigned int type)
11583 struct io_uring_rsrc_register rr;
11585 /* keep it extendible */
11586 if (size != sizeof(rr))
11589 memset(&rr, 0, sizeof(rr));
11590 if (copy_from_user(&rr, arg, size))
11592 if (!rr.nr || rr.resv || rr.resv2)
11596 case IORING_RSRC_FILE:
11597 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11598 rr.nr, u64_to_user_ptr(rr.tags));
11599 case IORING_RSRC_BUFFER:
11600 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11601 rr.nr, u64_to_user_ptr(rr.tags));
11606 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11607 void __user *arg, unsigned len)
11609 struct io_uring_task *tctx = current->io_uring;
11610 cpumask_var_t new_mask;
11613 if (!tctx || !tctx->io_wq)
11616 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11619 cpumask_clear(new_mask);
11620 if (len > cpumask_size())
11621 len = cpumask_size();
11623 if (copy_from_user(new_mask, arg, len)) {
11624 free_cpumask_var(new_mask);
11628 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11629 free_cpumask_var(new_mask);
11633 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11635 struct io_uring_task *tctx = current->io_uring;
11637 if (!tctx || !tctx->io_wq)
11640 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11643 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11645 __must_hold(&ctx->uring_lock)
11647 struct io_tctx_node *node;
11648 struct io_uring_task *tctx = NULL;
11649 struct io_sq_data *sqd = NULL;
11650 __u32 new_count[2];
11653 if (copy_from_user(new_count, arg, sizeof(new_count)))
11655 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11656 if (new_count[i] > INT_MAX)
11659 if (ctx->flags & IORING_SETUP_SQPOLL) {
11660 sqd = ctx->sq_data;
11663 * Observe the correct sqd->lock -> ctx->uring_lock
11664 * ordering. Fine to drop uring_lock here, we hold
11665 * a ref to the ctx.
11667 refcount_inc(&sqd->refs);
11668 mutex_unlock(&ctx->uring_lock);
11669 mutex_lock(&sqd->lock);
11670 mutex_lock(&ctx->uring_lock);
11672 tctx = sqd->thread->io_uring;
11675 tctx = current->io_uring;
11678 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11680 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11682 ctx->iowq_limits[i] = new_count[i];
11683 ctx->iowq_limits_set = true;
11685 if (tctx && tctx->io_wq) {
11686 ret = io_wq_max_workers(tctx->io_wq, new_count);
11690 memset(new_count, 0, sizeof(new_count));
11694 mutex_unlock(&sqd->lock);
11695 io_put_sq_data(sqd);
11698 if (copy_to_user(arg, new_count, sizeof(new_count)))
11701 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11705 /* now propagate the restriction to all registered users */
11706 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11707 struct io_uring_task *tctx = node->task->io_uring;
11709 if (WARN_ON_ONCE(!tctx->io_wq))
11712 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11713 new_count[i] = ctx->iowq_limits[i];
11714 /* ignore errors, it always returns zero anyway */
11715 (void)io_wq_max_workers(tctx->io_wq, new_count);
11720 mutex_unlock(&sqd->lock);
11721 io_put_sq_data(sqd);
11726 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11727 void __user *arg, unsigned nr_args)
11728 __releases(ctx->uring_lock)
11729 __acquires(ctx->uring_lock)
11734 * We're inside the ring mutex, if the ref is already dying, then
11735 * someone else killed the ctx or is already going through
11736 * io_uring_register().
11738 if (percpu_ref_is_dying(&ctx->refs))
11741 if (ctx->restricted) {
11742 if (opcode >= IORING_REGISTER_LAST)
11744 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11745 if (!test_bit(opcode, ctx->restrictions.register_op))
11750 case IORING_REGISTER_BUFFERS:
11751 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11753 case IORING_UNREGISTER_BUFFERS:
11755 if (arg || nr_args)
11757 ret = io_sqe_buffers_unregister(ctx);
11759 case IORING_REGISTER_FILES:
11760 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11762 case IORING_UNREGISTER_FILES:
11764 if (arg || nr_args)
11766 ret = io_sqe_files_unregister(ctx);
11768 case IORING_REGISTER_FILES_UPDATE:
11769 ret = io_register_files_update(ctx, arg, nr_args);
11771 case IORING_REGISTER_EVENTFD:
11775 ret = io_eventfd_register(ctx, arg, 0);
11777 case IORING_REGISTER_EVENTFD_ASYNC:
11781 ret = io_eventfd_register(ctx, arg, 1);
11783 case IORING_UNREGISTER_EVENTFD:
11785 if (arg || nr_args)
11787 ret = io_eventfd_unregister(ctx);
11789 case IORING_REGISTER_PROBE:
11791 if (!arg || nr_args > 256)
11793 ret = io_probe(ctx, arg, nr_args);
11795 case IORING_REGISTER_PERSONALITY:
11797 if (arg || nr_args)
11799 ret = io_register_personality(ctx);
11801 case IORING_UNREGISTER_PERSONALITY:
11805 ret = io_unregister_personality(ctx, nr_args);
11807 case IORING_REGISTER_ENABLE_RINGS:
11809 if (arg || nr_args)
11811 ret = io_register_enable_rings(ctx);
11813 case IORING_REGISTER_RESTRICTIONS:
11814 ret = io_register_restrictions(ctx, arg, nr_args);
11816 case IORING_REGISTER_FILES2:
11817 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11819 case IORING_REGISTER_FILES_UPDATE2:
11820 ret = io_register_rsrc_update(ctx, arg, nr_args,
11823 case IORING_REGISTER_BUFFERS2:
11824 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11826 case IORING_REGISTER_BUFFERS_UPDATE:
11827 ret = io_register_rsrc_update(ctx, arg, nr_args,
11828 IORING_RSRC_BUFFER);
11830 case IORING_REGISTER_IOWQ_AFF:
11832 if (!arg || !nr_args)
11834 ret = io_register_iowq_aff(ctx, arg, nr_args);
11836 case IORING_UNREGISTER_IOWQ_AFF:
11838 if (arg || nr_args)
11840 ret = io_unregister_iowq_aff(ctx);
11842 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11844 if (!arg || nr_args != 2)
11846 ret = io_register_iowq_max_workers(ctx, arg);
11848 case IORING_REGISTER_RING_FDS:
11849 ret = io_ringfd_register(ctx, arg, nr_args);
11851 case IORING_UNREGISTER_RING_FDS:
11852 ret = io_ringfd_unregister(ctx, arg, nr_args);
11862 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11863 void __user *, arg, unsigned int, nr_args)
11865 struct io_ring_ctx *ctx;
11874 if (f.file->f_op != &io_uring_fops)
11877 ctx = f.file->private_data;
11879 io_run_task_work();
11881 mutex_lock(&ctx->uring_lock);
11882 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11883 mutex_unlock(&ctx->uring_lock);
11884 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11890 static int __init io_uring_init(void)
11892 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11893 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11894 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11897 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11898 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11899 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11900 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11901 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11902 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11903 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11904 BUILD_BUG_SQE_ELEM(8, __u64, off);
11905 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11906 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11907 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11908 BUILD_BUG_SQE_ELEM(24, __u32, len);
11909 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11910 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11911 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11912 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11913 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11914 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11915 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11916 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11917 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11918 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11919 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11920 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11921 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11922 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11923 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11924 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11925 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11926 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11927 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11928 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11929 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11931 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11932 sizeof(struct io_uring_rsrc_update));
11933 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11934 sizeof(struct io_uring_rsrc_update2));
11936 /* ->buf_index is u16 */
11937 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11939 /* should fit into one byte */
11940 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11941 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11942 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11944 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11945 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11947 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11951 __initcall(io_uring_init);