1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/freezer.h>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
97 #define IORING_FILE_TABLE_SHIFT 9
98 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
99 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
100 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
101 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
102 IORING_REGISTER_LAST + IORING_OP_LAST)
104 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
105 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
109 u32 head ____cacheline_aligned_in_smp;
110 u32 tail ____cacheline_aligned_in_smp;
114 * This data is shared with the application through the mmap at offsets
115 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
117 * The offsets to the member fields are published through struct
118 * io_sqring_offsets when calling io_uring_setup.
122 * Head and tail offsets into the ring; the offsets need to be
123 * masked to get valid indices.
125 * The kernel controls head of the sq ring and the tail of the cq ring,
126 * and the application controls tail of the sq ring and the head of the
129 struct io_uring sq, cq;
131 * Bitmasks to apply to head and tail offsets (constant, equals
134 u32 sq_ring_mask, cq_ring_mask;
135 /* Ring sizes (constant, power of 2) */
136 u32 sq_ring_entries, cq_ring_entries;
138 * Number of invalid entries dropped by the kernel due to
139 * invalid index stored in array
141 * Written by the kernel, shouldn't be modified by the
142 * application (i.e. get number of "new events" by comparing to
145 * After a new SQ head value was read by the application this
146 * counter includes all submissions that were dropped reaching
147 * the new SQ head (and possibly more).
153 * Written by the kernel, shouldn't be modified by the
156 * The application needs a full memory barrier before checking
157 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
163 * Written by the application, shouldn't be modified by the
168 * Number of completion events lost because the queue was full;
169 * this should be avoided by the application by making sure
170 * there are not more requests pending than there is space in
171 * the completion queue.
173 * Written by the kernel, shouldn't be modified by the
174 * application (i.e. get number of "new events" by comparing to
177 * As completion events come in out of order this counter is not
178 * ordered with any other data.
182 * Ring buffer of completion events.
184 * The kernel writes completion events fresh every time they are
185 * produced, so the application is allowed to modify pending
188 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
191 enum io_uring_cmd_flags {
192 IO_URING_F_NONBLOCK = 1,
193 IO_URING_F_COMPLETE_DEFER = 2,
196 struct io_mapped_ubuf {
199 struct bio_vec *bvec;
200 unsigned int nr_bvecs;
201 unsigned long acct_pages;
207 struct list_head list;
214 struct fixed_rsrc_table {
218 struct fixed_rsrc_ref_node {
219 struct percpu_ref refs;
220 struct list_head node;
221 struct list_head rsrc_list;
222 struct fixed_rsrc_data *rsrc_data;
223 void (*rsrc_put)(struct io_ring_ctx *ctx,
224 struct io_rsrc_put *prsrc);
225 struct llist_node llist;
229 struct fixed_rsrc_data {
230 struct fixed_rsrc_table *table;
231 struct io_ring_ctx *ctx;
233 struct fixed_rsrc_ref_node *node;
234 struct percpu_ref refs;
235 struct completion done;
240 struct list_head list;
246 struct io_restriction {
247 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
248 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
249 u8 sqe_flags_allowed;
250 u8 sqe_flags_required;
255 IO_SQ_THREAD_SHOULD_STOP = 0,
256 IO_SQ_THREAD_SHOULD_PARK,
263 /* ctx's that are using this sqd */
264 struct list_head ctx_list;
265 struct list_head ctx_new_list;
266 struct mutex ctx_lock;
268 struct task_struct *thread;
269 struct wait_queue_head wait;
271 unsigned sq_thread_idle;
276 struct completion startup;
277 struct completion parked;
278 struct completion exited;
281 #define IO_IOPOLL_BATCH 8
282 #define IO_COMPL_BATCH 32
283 #define IO_REQ_CACHE_SIZE 32
284 #define IO_REQ_ALLOC_BATCH 8
286 struct io_comp_state {
287 struct io_kiocb *reqs[IO_COMPL_BATCH];
289 unsigned int locked_free_nr;
290 /* inline/task_work completion list, under ->uring_lock */
291 struct list_head free_list;
292 /* IRQ completion list, under ->completion_lock */
293 struct list_head locked_free_list;
296 struct io_submit_link {
297 struct io_kiocb *head;
298 struct io_kiocb *last;
301 struct io_submit_state {
302 struct blk_plug plug;
303 struct io_submit_link link;
306 * io_kiocb alloc cache
308 void *reqs[IO_REQ_CACHE_SIZE];
309 unsigned int free_reqs;
314 * Batch completion logic
316 struct io_comp_state comp;
319 * File reference cache
323 unsigned int file_refs;
324 unsigned int ios_left;
329 struct percpu_ref refs;
330 } ____cacheline_aligned_in_smp;
334 unsigned int compat: 1;
335 unsigned int cq_overflow_flushed: 1;
336 unsigned int drain_next: 1;
337 unsigned int eventfd_async: 1;
338 unsigned int restricted: 1;
339 unsigned int sqo_exec: 1;
342 * Ring buffer of indices into array of io_uring_sqe, which is
343 * mmapped by the application using the IORING_OFF_SQES offset.
345 * This indirection could e.g. be used to assign fixed
346 * io_uring_sqe entries to operations and only submit them to
347 * the queue when needed.
349 * The kernel modifies neither the indices array nor the entries
353 unsigned cached_sq_head;
356 unsigned sq_thread_idle;
357 unsigned cached_sq_dropped;
358 unsigned cached_cq_overflow;
359 unsigned long sq_check_overflow;
361 /* hashed buffered write serialization */
362 struct io_wq_hash *hash_map;
364 struct list_head defer_list;
365 struct list_head timeout_list;
366 struct list_head cq_overflow_list;
368 struct io_uring_sqe *sq_sqes;
369 } ____cacheline_aligned_in_smp;
372 struct mutex uring_lock;
373 wait_queue_head_t wait;
374 } ____cacheline_aligned_in_smp;
376 struct io_submit_state submit_state;
378 struct io_rings *rings;
380 /* Only used for accounting purposes */
381 struct mm_struct *mm_account;
383 struct io_sq_data *sq_data; /* if using sq thread polling */
385 struct wait_queue_head sqo_sq_wait;
386 struct list_head sqd_list;
389 * If used, fixed file set. Writers must ensure that ->refs is dead,
390 * readers must ensure that ->refs is alive as long as the file* is
391 * used. Only updated through io_uring_register(2).
393 struct fixed_rsrc_data *file_data;
394 unsigned nr_user_files;
396 /* if used, fixed mapped user buffers */
397 unsigned nr_user_bufs;
398 struct io_mapped_ubuf *user_bufs;
400 struct user_struct *user;
402 struct completion ref_comp;
403 struct completion sq_thread_comp;
405 #if defined(CONFIG_UNIX)
406 struct socket *ring_sock;
409 struct idr io_buffer_idr;
411 struct idr personality_idr;
414 unsigned cached_cq_tail;
417 atomic_t cq_timeouts;
418 unsigned cq_last_tm_flush;
419 unsigned long cq_check_overflow;
420 struct wait_queue_head cq_wait;
421 struct fasync_struct *cq_fasync;
422 struct eventfd_ctx *cq_ev_fd;
423 } ____cacheline_aligned_in_smp;
426 spinlock_t completion_lock;
429 * ->iopoll_list is protected by the ctx->uring_lock for
430 * io_uring instances that don't use IORING_SETUP_SQPOLL.
431 * For SQPOLL, only the single threaded io_sq_thread() will
432 * manipulate the list, hence no extra locking is needed there.
434 struct list_head iopoll_list;
435 struct hlist_head *cancel_hash;
436 unsigned cancel_hash_bits;
437 bool poll_multi_file;
439 spinlock_t inflight_lock;
440 struct list_head inflight_list;
441 } ____cacheline_aligned_in_smp;
443 struct delayed_work rsrc_put_work;
444 struct llist_head rsrc_put_llist;
445 struct list_head rsrc_ref_list;
446 spinlock_t rsrc_ref_lock;
448 struct io_restriction restrictions;
451 struct callback_head *exit_task_work;
453 struct wait_queue_head hash_wait;
455 /* Keep this last, we don't need it for the fast path */
456 struct work_struct exit_work;
460 * First field must be the file pointer in all the
461 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
463 struct io_poll_iocb {
465 struct wait_queue_head *head;
469 struct wait_queue_entry wait;
472 struct io_poll_remove {
482 struct io_timeout_data {
483 struct io_kiocb *req;
484 struct hrtimer timer;
485 struct timespec64 ts;
486 enum hrtimer_mode mode;
491 struct sockaddr __user *addr;
492 int __user *addr_len;
494 unsigned long nofile;
514 struct list_head list;
515 /* head of the link, used by linked timeouts only */
516 struct io_kiocb *head;
519 struct io_timeout_rem {
524 struct timespec64 ts;
529 /* NOTE: kiocb has the file as the first member, so don't do it here */
537 struct sockaddr __user *addr;
544 struct user_msghdr __user *umsg;
550 struct io_buffer *kbuf;
556 struct filename *filename;
558 unsigned long nofile;
561 struct io_rsrc_update {
587 struct epoll_event event;
591 struct file *file_out;
592 struct file *file_in;
599 struct io_provide_buf {
613 const char __user *filename;
614 struct statx __user *buffer;
626 struct filename *oldpath;
627 struct filename *newpath;
635 struct filename *filename;
638 struct io_completion {
640 struct list_head list;
644 struct io_async_connect {
645 struct sockaddr_storage address;
648 struct io_async_msghdr {
649 struct iovec fast_iov[UIO_FASTIOV];
650 /* points to an allocated iov, if NULL we use fast_iov instead */
651 struct iovec *free_iov;
652 struct sockaddr __user *uaddr;
654 struct sockaddr_storage addr;
658 struct iovec fast_iov[UIO_FASTIOV];
659 const struct iovec *free_iovec;
660 struct iov_iter iter;
662 struct wait_page_queue wpq;
666 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
667 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
668 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
669 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
670 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
671 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
677 REQ_F_LINK_TIMEOUT_BIT,
679 REQ_F_NEED_CLEANUP_BIT,
681 REQ_F_BUFFER_SELECTED_BIT,
682 REQ_F_NO_FILE_TABLE_BIT,
683 REQ_F_LTIMEOUT_ACTIVE_BIT,
684 REQ_F_COMPLETE_INLINE_BIT,
686 /* not a real bit, just to check we're not overflowing the space */
692 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
693 /* drain existing IO first */
694 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
696 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
697 /* doesn't sever on completion < 0 */
698 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
700 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
701 /* IOSQE_BUFFER_SELECT */
702 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
704 /* fail rest of links */
705 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
706 /* on inflight list, should be cancelled and waited on exit reliably */
707 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
708 /* read/write uses file position */
709 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
710 /* must not punt to workers */
711 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
712 /* has or had linked timeout */
713 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
715 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
717 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
718 /* already went through poll handler */
719 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
720 /* buffer already selected */
721 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
722 /* doesn't need file table for this request */
723 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
724 /* linked timeout is active, i.e. prepared by link's head */
725 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
726 /* completion is deferred through io_comp_state */
727 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
731 struct io_poll_iocb poll;
732 struct io_poll_iocb *double_poll;
735 struct io_task_work {
736 struct io_wq_work_node node;
737 task_work_func_t func;
741 * NOTE! Each of the iocb union members has the file pointer
742 * as the first entry in their struct definition. So you can
743 * access the file pointer through any of the sub-structs,
744 * or directly as just 'ki_filp' in this struct.
750 struct io_poll_iocb poll;
751 struct io_poll_remove poll_remove;
752 struct io_accept accept;
754 struct io_cancel cancel;
755 struct io_timeout timeout;
756 struct io_timeout_rem timeout_rem;
757 struct io_connect connect;
758 struct io_sr_msg sr_msg;
760 struct io_close close;
761 struct io_rsrc_update rsrc_update;
762 struct io_fadvise fadvise;
763 struct io_madvise madvise;
764 struct io_epoll epoll;
765 struct io_splice splice;
766 struct io_provide_buf pbuf;
767 struct io_statx statx;
768 struct io_shutdown shutdown;
769 struct io_rename rename;
770 struct io_unlink unlink;
771 /* use only after cleaning per-op data, see io_clean_op() */
772 struct io_completion compl;
775 /* opcode allocated if it needs to store data for async defer */
778 /* polled IO has completed */
784 struct io_ring_ctx *ctx;
787 struct task_struct *task;
790 struct io_kiocb *link;
791 struct percpu_ref *fixed_rsrc_refs;
794 * 1. used with ctx->iopoll_list with reads/writes
795 * 2. to track reqs with ->files (see io_op_def::file_table)
797 struct list_head inflight_entry;
799 struct io_task_work io_task_work;
800 struct callback_head task_work;
802 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
803 struct hlist_node hash_node;
804 struct async_poll *apoll;
805 struct io_wq_work work;
808 struct io_defer_entry {
809 struct list_head list;
810 struct io_kiocb *req;
815 /* needs req->file assigned */
816 unsigned needs_file : 1;
817 /* hash wq insertion if file is a regular file */
818 unsigned hash_reg_file : 1;
819 /* unbound wq insertion if file is a non-regular file */
820 unsigned unbound_nonreg_file : 1;
821 /* opcode is not supported by this kernel */
822 unsigned not_supported : 1;
823 /* set if opcode supports polled "wait" */
825 unsigned pollout : 1;
826 /* op supports buffer selection */
827 unsigned buffer_select : 1;
828 /* must always have async data allocated */
829 unsigned needs_async_data : 1;
830 /* should block plug */
832 /* size of async data needed, if any */
833 unsigned short async_size;
836 static const struct io_op_def io_op_defs[] = {
837 [IORING_OP_NOP] = {},
838 [IORING_OP_READV] = {
840 .unbound_nonreg_file = 1,
843 .needs_async_data = 1,
845 .async_size = sizeof(struct io_async_rw),
847 [IORING_OP_WRITEV] = {
850 .unbound_nonreg_file = 1,
852 .needs_async_data = 1,
854 .async_size = sizeof(struct io_async_rw),
856 [IORING_OP_FSYNC] = {
859 [IORING_OP_READ_FIXED] = {
861 .unbound_nonreg_file = 1,
864 .async_size = sizeof(struct io_async_rw),
866 [IORING_OP_WRITE_FIXED] = {
869 .unbound_nonreg_file = 1,
872 .async_size = sizeof(struct io_async_rw),
874 [IORING_OP_POLL_ADD] = {
876 .unbound_nonreg_file = 1,
878 [IORING_OP_POLL_REMOVE] = {},
879 [IORING_OP_SYNC_FILE_RANGE] = {
882 [IORING_OP_SENDMSG] = {
884 .unbound_nonreg_file = 1,
886 .needs_async_data = 1,
887 .async_size = sizeof(struct io_async_msghdr),
889 [IORING_OP_RECVMSG] = {
891 .unbound_nonreg_file = 1,
894 .needs_async_data = 1,
895 .async_size = sizeof(struct io_async_msghdr),
897 [IORING_OP_TIMEOUT] = {
898 .needs_async_data = 1,
899 .async_size = sizeof(struct io_timeout_data),
901 [IORING_OP_TIMEOUT_REMOVE] = {
902 /* used by timeout updates' prep() */
904 [IORING_OP_ACCEPT] = {
906 .unbound_nonreg_file = 1,
909 [IORING_OP_ASYNC_CANCEL] = {},
910 [IORING_OP_LINK_TIMEOUT] = {
911 .needs_async_data = 1,
912 .async_size = sizeof(struct io_timeout_data),
914 [IORING_OP_CONNECT] = {
916 .unbound_nonreg_file = 1,
918 .needs_async_data = 1,
919 .async_size = sizeof(struct io_async_connect),
921 [IORING_OP_FALLOCATE] = {
924 [IORING_OP_OPENAT] = {},
925 [IORING_OP_CLOSE] = {},
926 [IORING_OP_FILES_UPDATE] = {},
927 [IORING_OP_STATX] = {},
930 .unbound_nonreg_file = 1,
934 .async_size = sizeof(struct io_async_rw),
936 [IORING_OP_WRITE] = {
938 .unbound_nonreg_file = 1,
941 .async_size = sizeof(struct io_async_rw),
943 [IORING_OP_FADVISE] = {
946 [IORING_OP_MADVISE] = {},
949 .unbound_nonreg_file = 1,
954 .unbound_nonreg_file = 1,
958 [IORING_OP_OPENAT2] = {
960 [IORING_OP_EPOLL_CTL] = {
961 .unbound_nonreg_file = 1,
963 [IORING_OP_SPLICE] = {
966 .unbound_nonreg_file = 1,
968 [IORING_OP_PROVIDE_BUFFERS] = {},
969 [IORING_OP_REMOVE_BUFFERS] = {},
973 .unbound_nonreg_file = 1,
975 [IORING_OP_SHUTDOWN] = {
978 [IORING_OP_RENAMEAT] = {},
979 [IORING_OP_UNLINKAT] = {},
982 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
983 struct task_struct *task,
984 struct files_struct *files);
985 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
986 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
987 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
988 struct io_ring_ctx *ctx);
989 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
991 static bool io_rw_reissue(struct io_kiocb *req);
992 static void io_cqring_fill_event(struct io_kiocb *req, long res);
993 static void io_put_req(struct io_kiocb *req);
994 static void io_put_req_deferred(struct io_kiocb *req, int nr);
995 static void io_double_put_req(struct io_kiocb *req);
996 static void io_dismantle_req(struct io_kiocb *req);
997 static void io_put_task(struct task_struct *task, int nr);
998 static void io_queue_next(struct io_kiocb *req);
999 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1000 static void __io_queue_linked_timeout(struct io_kiocb *req);
1001 static void io_queue_linked_timeout(struct io_kiocb *req);
1002 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1003 struct io_uring_rsrc_update *ip,
1005 static void __io_clean_op(struct io_kiocb *req);
1006 static struct file *io_file_get(struct io_submit_state *state,
1007 struct io_kiocb *req, int fd, bool fixed);
1008 static void __io_queue_sqe(struct io_kiocb *req);
1009 static void io_rsrc_put_work(struct work_struct *work);
1011 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1012 struct iov_iter *iter, bool needs_lock);
1013 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1014 const struct iovec *fast_iov,
1015 struct iov_iter *iter, bool force);
1016 static void io_req_task_queue(struct io_kiocb *req);
1017 static void io_submit_flush_completions(struct io_comp_state *cs,
1018 struct io_ring_ctx *ctx);
1020 static struct kmem_cache *req_cachep;
1022 static const struct file_operations io_uring_fops;
1024 struct sock *io_uring_get_socket(struct file *file)
1026 #if defined(CONFIG_UNIX)
1027 if (file->f_op == &io_uring_fops) {
1028 struct io_ring_ctx *ctx = file->private_data;
1030 return ctx->ring_sock->sk;
1035 EXPORT_SYMBOL(io_uring_get_socket);
1037 #define io_for_each_link(pos, head) \
1038 for (pos = (head); pos; pos = pos->link)
1040 static inline void io_clean_op(struct io_kiocb *req)
1042 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1046 static inline void io_set_resource_node(struct io_kiocb *req)
1048 struct io_ring_ctx *ctx = req->ctx;
1050 if (!req->fixed_rsrc_refs) {
1051 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1052 percpu_ref_get(req->fixed_rsrc_refs);
1056 static bool io_match_task(struct io_kiocb *head,
1057 struct task_struct *task,
1058 struct files_struct *files)
1060 struct io_kiocb *req;
1062 if (task && head->task != task) {
1063 /* in terms of cancelation, always match if req task is dead */
1064 if (head->task->flags & PF_EXITING)
1071 io_for_each_link(req, head) {
1072 if (req->flags & REQ_F_INFLIGHT)
1074 if (req->task->files == files)
1080 static inline void req_set_fail_links(struct io_kiocb *req)
1082 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1083 req->flags |= REQ_F_FAIL_LINK;
1086 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1088 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1090 complete(&ctx->ref_comp);
1093 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1095 return !req->timeout.off;
1098 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1100 struct io_ring_ctx *ctx;
1103 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1108 * Use 5 bits less than the max cq entries, that should give us around
1109 * 32 entries per hash list if totally full and uniformly spread.
1111 hash_bits = ilog2(p->cq_entries);
1115 ctx->cancel_hash_bits = hash_bits;
1116 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1118 if (!ctx->cancel_hash)
1120 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1122 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1123 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1126 ctx->flags = p->flags;
1127 init_waitqueue_head(&ctx->sqo_sq_wait);
1128 INIT_LIST_HEAD(&ctx->sqd_list);
1129 init_waitqueue_head(&ctx->cq_wait);
1130 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1131 init_completion(&ctx->ref_comp);
1132 init_completion(&ctx->sq_thread_comp);
1133 idr_init(&ctx->io_buffer_idr);
1134 idr_init(&ctx->personality_idr);
1135 mutex_init(&ctx->uring_lock);
1136 init_waitqueue_head(&ctx->wait);
1137 spin_lock_init(&ctx->completion_lock);
1138 INIT_LIST_HEAD(&ctx->iopoll_list);
1139 INIT_LIST_HEAD(&ctx->defer_list);
1140 INIT_LIST_HEAD(&ctx->timeout_list);
1141 spin_lock_init(&ctx->inflight_lock);
1142 INIT_LIST_HEAD(&ctx->inflight_list);
1143 spin_lock_init(&ctx->rsrc_ref_lock);
1144 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1145 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1146 init_llist_head(&ctx->rsrc_put_llist);
1147 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1148 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1151 kfree(ctx->cancel_hash);
1156 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1158 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1159 struct io_ring_ctx *ctx = req->ctx;
1161 return seq != ctx->cached_cq_tail
1162 + READ_ONCE(ctx->cached_cq_overflow);
1168 static void io_req_track_inflight(struct io_kiocb *req)
1170 struct io_ring_ctx *ctx = req->ctx;
1172 if (!(req->flags & REQ_F_INFLIGHT)) {
1173 req->flags |= REQ_F_INFLIGHT;
1175 spin_lock_irq(&ctx->inflight_lock);
1176 list_add(&req->inflight_entry, &ctx->inflight_list);
1177 spin_unlock_irq(&ctx->inflight_lock);
1181 static void io_prep_async_work(struct io_kiocb *req)
1183 const struct io_op_def *def = &io_op_defs[req->opcode];
1184 struct io_ring_ctx *ctx = req->ctx;
1186 if (!req->work.creds)
1187 req->work.creds = get_current_cred();
1189 if (req->flags & REQ_F_FORCE_ASYNC)
1190 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1192 if (req->flags & REQ_F_ISREG) {
1193 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1194 io_wq_hash_work(&req->work, file_inode(req->file));
1196 if (def->unbound_nonreg_file)
1197 req->work.flags |= IO_WQ_WORK_UNBOUND;
1201 static void io_prep_async_link(struct io_kiocb *req)
1203 struct io_kiocb *cur;
1205 io_for_each_link(cur, req)
1206 io_prep_async_work(cur);
1209 static void io_queue_async_work(struct io_kiocb *req)
1211 struct io_ring_ctx *ctx = req->ctx;
1212 struct io_kiocb *link = io_prep_linked_timeout(req);
1213 struct io_uring_task *tctx = req->task->io_uring;
1216 BUG_ON(!tctx->io_wq);
1218 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1219 &req->work, req->flags);
1220 /* init ->work of the whole link before punting */
1221 io_prep_async_link(req);
1222 io_wq_enqueue(tctx->io_wq, &req->work);
1224 io_queue_linked_timeout(link);
1227 static void io_kill_timeout(struct io_kiocb *req)
1229 struct io_timeout_data *io = req->async_data;
1232 ret = hrtimer_try_to_cancel(&io->timer);
1234 atomic_set(&req->ctx->cq_timeouts,
1235 atomic_read(&req->ctx->cq_timeouts) + 1);
1236 list_del_init(&req->timeout.list);
1237 io_cqring_fill_event(req, 0);
1238 io_put_req_deferred(req, 1);
1243 * Returns true if we found and killed one or more timeouts
1245 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1246 struct files_struct *files)
1248 struct io_kiocb *req, *tmp;
1251 spin_lock_irq(&ctx->completion_lock);
1252 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1253 if (io_match_task(req, tsk, files)) {
1254 io_kill_timeout(req);
1258 spin_unlock_irq(&ctx->completion_lock);
1259 return canceled != 0;
1262 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1265 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1266 struct io_defer_entry, list);
1268 if (req_need_defer(de->req, de->seq))
1270 list_del_init(&de->list);
1271 io_req_task_queue(de->req);
1273 } while (!list_empty(&ctx->defer_list));
1276 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1280 if (list_empty(&ctx->timeout_list))
1283 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1286 u32 events_needed, events_got;
1287 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1288 struct io_kiocb, timeout.list);
1290 if (io_is_timeout_noseq(req))
1294 * Since seq can easily wrap around over time, subtract
1295 * the last seq at which timeouts were flushed before comparing.
1296 * Assuming not more than 2^31-1 events have happened since,
1297 * these subtractions won't have wrapped, so we can check if
1298 * target is in [last_seq, current_seq] by comparing the two.
1300 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1301 events_got = seq - ctx->cq_last_tm_flush;
1302 if (events_got < events_needed)
1305 list_del_init(&req->timeout.list);
1306 io_kill_timeout(req);
1307 } while (!list_empty(&ctx->timeout_list));
1309 ctx->cq_last_tm_flush = seq;
1312 static void io_commit_cqring(struct io_ring_ctx *ctx)
1314 io_flush_timeouts(ctx);
1316 /* order cqe stores with ring update */
1317 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1319 if (unlikely(!list_empty(&ctx->defer_list)))
1320 __io_queue_deferred(ctx);
1323 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1325 struct io_rings *r = ctx->rings;
1327 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1330 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1332 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1335 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1337 struct io_rings *rings = ctx->rings;
1341 * writes to the cq entry need to come after reading head; the
1342 * control dependency is enough as we're using WRITE_ONCE to
1345 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1348 tail = ctx->cached_cq_tail++;
1349 return &rings->cqes[tail & ctx->cq_mask];
1352 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1356 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1358 if (!ctx->eventfd_async)
1360 return io_wq_current_is_worker();
1363 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1365 /* see waitqueue_active() comment */
1368 if (waitqueue_active(&ctx->wait))
1369 wake_up(&ctx->wait);
1370 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1371 wake_up(&ctx->sq_data->wait);
1372 if (io_should_trigger_evfd(ctx))
1373 eventfd_signal(ctx->cq_ev_fd, 1);
1374 if (waitqueue_active(&ctx->cq_wait)) {
1375 wake_up_interruptible(&ctx->cq_wait);
1376 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1380 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1382 /* see waitqueue_active() comment */
1385 if (ctx->flags & IORING_SETUP_SQPOLL) {
1386 if (waitqueue_active(&ctx->wait))
1387 wake_up(&ctx->wait);
1389 if (io_should_trigger_evfd(ctx))
1390 eventfd_signal(ctx->cq_ev_fd, 1);
1391 if (waitqueue_active(&ctx->cq_wait)) {
1392 wake_up_interruptible(&ctx->cq_wait);
1393 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1397 /* Returns true if there are no backlogged entries after the flush */
1398 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1399 struct task_struct *tsk,
1400 struct files_struct *files)
1402 struct io_rings *rings = ctx->rings;
1403 struct io_kiocb *req, *tmp;
1404 struct io_uring_cqe *cqe;
1405 unsigned long flags;
1406 bool all_flushed, posted;
1409 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1413 spin_lock_irqsave(&ctx->completion_lock, flags);
1414 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1415 if (!io_match_task(req, tsk, files))
1418 cqe = io_get_cqring(ctx);
1422 list_move(&req->compl.list, &list);
1424 WRITE_ONCE(cqe->user_data, req->user_data);
1425 WRITE_ONCE(cqe->res, req->result);
1426 WRITE_ONCE(cqe->flags, req->compl.cflags);
1428 ctx->cached_cq_overflow++;
1429 WRITE_ONCE(ctx->rings->cq_overflow,
1430 ctx->cached_cq_overflow);
1435 all_flushed = list_empty(&ctx->cq_overflow_list);
1437 clear_bit(0, &ctx->sq_check_overflow);
1438 clear_bit(0, &ctx->cq_check_overflow);
1439 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1443 io_commit_cqring(ctx);
1444 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1446 io_cqring_ev_posted(ctx);
1448 while (!list_empty(&list)) {
1449 req = list_first_entry(&list, struct io_kiocb, compl.list);
1450 list_del(&req->compl.list);
1457 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1458 struct task_struct *tsk,
1459 struct files_struct *files)
1463 if (test_bit(0, &ctx->cq_check_overflow)) {
1464 /* iopoll syncs against uring_lock, not completion_lock */
1465 if (ctx->flags & IORING_SETUP_IOPOLL)
1466 mutex_lock(&ctx->uring_lock);
1467 ret = __io_cqring_overflow_flush(ctx, force, tsk, files);
1468 if (ctx->flags & IORING_SETUP_IOPOLL)
1469 mutex_unlock(&ctx->uring_lock);
1475 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1477 struct io_ring_ctx *ctx = req->ctx;
1478 struct io_uring_cqe *cqe;
1480 trace_io_uring_complete(ctx, req->user_data, res);
1483 * If we can't get a cq entry, userspace overflowed the
1484 * submission (by quite a lot). Increment the overflow count in
1487 cqe = io_get_cqring(ctx);
1489 WRITE_ONCE(cqe->user_data, req->user_data);
1490 WRITE_ONCE(cqe->res, res);
1491 WRITE_ONCE(cqe->flags, cflags);
1492 } else if (ctx->cq_overflow_flushed ||
1493 atomic_read(&req->task->io_uring->in_idle)) {
1495 * If we're in ring overflow flush mode, or in task cancel mode,
1496 * then we cannot store the request for later flushing, we need
1497 * to drop it on the floor.
1499 ctx->cached_cq_overflow++;
1500 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1502 if (list_empty(&ctx->cq_overflow_list)) {
1503 set_bit(0, &ctx->sq_check_overflow);
1504 set_bit(0, &ctx->cq_check_overflow);
1505 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1509 req->compl.cflags = cflags;
1510 refcount_inc(&req->refs);
1511 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1515 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1517 __io_cqring_fill_event(req, res, 0);
1520 static inline void io_req_complete_post(struct io_kiocb *req, long res,
1521 unsigned int cflags)
1523 struct io_ring_ctx *ctx = req->ctx;
1524 unsigned long flags;
1526 spin_lock_irqsave(&ctx->completion_lock, flags);
1527 __io_cqring_fill_event(req, res, cflags);
1528 io_commit_cqring(ctx);
1530 * If we're the last reference to this request, add to our locked
1533 if (refcount_dec_and_test(&req->refs)) {
1534 struct io_comp_state *cs = &ctx->submit_state.comp;
1536 io_dismantle_req(req);
1537 io_put_task(req->task, 1);
1538 list_add(&req->compl.list, &cs->locked_free_list);
1539 cs->locked_free_nr++;
1542 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1544 io_cqring_ev_posted(ctx);
1547 percpu_ref_put(&ctx->refs);
1551 static void io_req_complete_state(struct io_kiocb *req, long res,
1552 unsigned int cflags)
1556 req->compl.cflags = cflags;
1557 req->flags |= REQ_F_COMPLETE_INLINE;
1560 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1561 long res, unsigned cflags)
1563 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1564 io_req_complete_state(req, res, cflags);
1566 io_req_complete_post(req, res, cflags);
1569 static inline void io_req_complete(struct io_kiocb *req, long res)
1571 __io_req_complete(req, 0, res, 0);
1574 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1576 struct io_submit_state *state = &ctx->submit_state;
1577 struct io_comp_state *cs = &state->comp;
1578 struct io_kiocb *req = NULL;
1581 * If we have more than a batch's worth of requests in our IRQ side
1582 * locked cache, grab the lock and move them over to our submission
1585 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1586 spin_lock_irq(&ctx->completion_lock);
1587 list_splice_init(&cs->locked_free_list, &cs->free_list);
1588 cs->locked_free_nr = 0;
1589 spin_unlock_irq(&ctx->completion_lock);
1592 while (!list_empty(&cs->free_list)) {
1593 req = list_first_entry(&cs->free_list, struct io_kiocb,
1595 list_del(&req->compl.list);
1596 state->reqs[state->free_reqs++] = req;
1597 if (state->free_reqs == ARRAY_SIZE(state->reqs))
1604 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1606 struct io_submit_state *state = &ctx->submit_state;
1608 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1610 if (!state->free_reqs) {
1611 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1614 if (io_flush_cached_reqs(ctx))
1617 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1621 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1622 * retry single alloc to be on the safe side.
1624 if (unlikely(ret <= 0)) {
1625 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1626 if (!state->reqs[0])
1630 state->free_reqs = ret;
1634 return state->reqs[state->free_reqs];
1637 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1644 static void io_dismantle_req(struct io_kiocb *req)
1648 if (req->async_data)
1649 kfree(req->async_data);
1651 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1652 if (req->fixed_rsrc_refs)
1653 percpu_ref_put(req->fixed_rsrc_refs);
1654 if (req->work.creds) {
1655 put_cred(req->work.creds);
1656 req->work.creds = NULL;
1659 if (req->flags & REQ_F_INFLIGHT) {
1660 struct io_ring_ctx *ctx = req->ctx;
1661 unsigned long flags;
1663 spin_lock_irqsave(&ctx->inflight_lock, flags);
1664 list_del(&req->inflight_entry);
1665 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1666 req->flags &= ~REQ_F_INFLIGHT;
1670 /* must to be called somewhat shortly after putting a request */
1671 static inline void io_put_task(struct task_struct *task, int nr)
1673 struct io_uring_task *tctx = task->io_uring;
1675 percpu_counter_sub(&tctx->inflight, nr);
1676 if (unlikely(atomic_read(&tctx->in_idle)))
1677 wake_up(&tctx->wait);
1678 put_task_struct_many(task, nr);
1681 static void __io_free_req(struct io_kiocb *req)
1683 struct io_ring_ctx *ctx = req->ctx;
1685 io_dismantle_req(req);
1686 io_put_task(req->task, 1);
1688 kmem_cache_free(req_cachep, req);
1689 percpu_ref_put(&ctx->refs);
1692 static inline void io_remove_next_linked(struct io_kiocb *req)
1694 struct io_kiocb *nxt = req->link;
1696 req->link = nxt->link;
1700 static void io_kill_linked_timeout(struct io_kiocb *req)
1702 struct io_ring_ctx *ctx = req->ctx;
1703 struct io_kiocb *link;
1704 bool cancelled = false;
1705 unsigned long flags;
1707 spin_lock_irqsave(&ctx->completion_lock, flags);
1711 * Can happen if a linked timeout fired and link had been like
1712 * req -> link t-out -> link t-out [-> ...]
1714 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1715 struct io_timeout_data *io = link->async_data;
1718 io_remove_next_linked(req);
1719 link->timeout.head = NULL;
1720 ret = hrtimer_try_to_cancel(&io->timer);
1722 io_cqring_fill_event(link, -ECANCELED);
1723 io_commit_cqring(ctx);
1727 req->flags &= ~REQ_F_LINK_TIMEOUT;
1728 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1731 io_cqring_ev_posted(ctx);
1737 static void io_fail_links(struct io_kiocb *req)
1739 struct io_kiocb *link, *nxt;
1740 struct io_ring_ctx *ctx = req->ctx;
1741 unsigned long flags;
1743 spin_lock_irqsave(&ctx->completion_lock, flags);
1751 trace_io_uring_fail_link(req, link);
1752 io_cqring_fill_event(link, -ECANCELED);
1754 io_put_req_deferred(link, 2);
1757 io_commit_cqring(ctx);
1758 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1760 io_cqring_ev_posted(ctx);
1763 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1765 if (req->flags & REQ_F_LINK_TIMEOUT)
1766 io_kill_linked_timeout(req);
1769 * If LINK is set, we have dependent requests in this chain. If we
1770 * didn't fail this request, queue the first one up, moving any other
1771 * dependencies to the next request. In case of failure, fail the rest
1774 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
1775 struct io_kiocb *nxt = req->link;
1784 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1786 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1788 return __io_req_find_next(req);
1791 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1795 if (ctx->submit_state.comp.nr) {
1796 mutex_lock(&ctx->uring_lock);
1797 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1798 mutex_unlock(&ctx->uring_lock);
1800 percpu_ref_put(&ctx->refs);
1803 static bool __tctx_task_work(struct io_uring_task *tctx)
1805 struct io_ring_ctx *ctx = NULL;
1806 struct io_wq_work_list list;
1807 struct io_wq_work_node *node;
1809 if (wq_list_empty(&tctx->task_list))
1812 spin_lock_irq(&tctx->task_lock);
1813 list = tctx->task_list;
1814 INIT_WQ_LIST(&tctx->task_list);
1815 spin_unlock_irq(&tctx->task_lock);
1819 struct io_wq_work_node *next = node->next;
1820 struct io_kiocb *req;
1822 req = container_of(node, struct io_kiocb, io_task_work.node);
1823 if (req->ctx != ctx) {
1824 ctx_flush_and_put(ctx);
1826 percpu_ref_get(&ctx->refs);
1829 req->task_work.func(&req->task_work);
1833 ctx_flush_and_put(ctx);
1834 return list.first != NULL;
1837 static void tctx_task_work(struct callback_head *cb)
1839 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1841 clear_bit(0, &tctx->task_state);
1843 while (__tctx_task_work(tctx))
1847 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
1848 enum task_work_notify_mode notify)
1850 struct io_uring_task *tctx = tsk->io_uring;
1851 struct io_wq_work_node *node, *prev;
1852 unsigned long flags;
1855 WARN_ON_ONCE(!tctx);
1857 spin_lock_irqsave(&tctx->task_lock, flags);
1858 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1859 spin_unlock_irqrestore(&tctx->task_lock, flags);
1861 /* task_work already pending, we're done */
1862 if (test_bit(0, &tctx->task_state) ||
1863 test_and_set_bit(0, &tctx->task_state))
1866 if (!task_work_add(tsk, &tctx->task_work, notify))
1870 * Slow path - we failed, find and delete work. if the work is not
1871 * in the list, it got run and we're fine.
1874 spin_lock_irqsave(&tctx->task_lock, flags);
1875 wq_list_for_each(node, prev, &tctx->task_list) {
1876 if (&req->io_task_work.node == node) {
1877 wq_list_del(&tctx->task_list, node, prev);
1882 spin_unlock_irqrestore(&tctx->task_lock, flags);
1883 clear_bit(0, &tctx->task_state);
1887 static int io_req_task_work_add(struct io_kiocb *req)
1889 struct task_struct *tsk = req->task;
1890 struct io_ring_ctx *ctx = req->ctx;
1891 enum task_work_notify_mode notify;
1894 if (tsk->flags & PF_EXITING)
1898 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1899 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1900 * processing task_work. There's no reliable way to tell if TWA_RESUME
1904 if (!(ctx->flags & IORING_SETUP_SQPOLL))
1905 notify = TWA_SIGNAL;
1907 ret = io_task_work_add(tsk, req, notify);
1909 wake_up_process(tsk);
1914 static void io_req_task_work_add_fallback(struct io_kiocb *req,
1915 task_work_func_t cb)
1917 struct io_ring_ctx *ctx = req->ctx;
1918 struct callback_head *head;
1920 init_task_work(&req->task_work, cb);
1922 head = READ_ONCE(ctx->exit_task_work);
1923 req->task_work.next = head;
1924 } while (cmpxchg(&ctx->exit_task_work, head, &req->task_work) != head);
1927 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1929 struct io_ring_ctx *ctx = req->ctx;
1931 spin_lock_irq(&ctx->completion_lock);
1932 io_cqring_fill_event(req, error);
1933 io_commit_cqring(ctx);
1934 spin_unlock_irq(&ctx->completion_lock);
1936 io_cqring_ev_posted(ctx);
1937 req_set_fail_links(req);
1938 io_double_put_req(req);
1941 static void io_req_task_cancel(struct callback_head *cb)
1943 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1944 struct io_ring_ctx *ctx = req->ctx;
1946 mutex_lock(&ctx->uring_lock);
1947 __io_req_task_cancel(req, req->result);
1948 mutex_unlock(&ctx->uring_lock);
1949 percpu_ref_put(&ctx->refs);
1952 static void __io_req_task_submit(struct io_kiocb *req)
1954 struct io_ring_ctx *ctx = req->ctx;
1956 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
1957 mutex_lock(&ctx->uring_lock);
1958 if (!(current->flags & PF_EXITING) && !current->in_execve)
1959 __io_queue_sqe(req);
1961 __io_req_task_cancel(req, -EFAULT);
1962 mutex_unlock(&ctx->uring_lock);
1965 static void io_req_task_submit(struct callback_head *cb)
1967 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1969 __io_req_task_submit(req);
1972 static void io_req_task_queue(struct io_kiocb *req)
1976 req->task_work.func = io_req_task_submit;
1977 ret = io_req_task_work_add(req);
1978 if (unlikely(ret)) {
1979 req->result = -ECANCELED;
1980 percpu_ref_get(&req->ctx->refs);
1981 io_req_task_work_add_fallback(req, io_req_task_cancel);
1985 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1987 percpu_ref_get(&req->ctx->refs);
1989 req->task_work.func = io_req_task_cancel;
1991 if (unlikely(io_req_task_work_add(req)))
1992 io_req_task_work_add_fallback(req, io_req_task_cancel);
1995 static inline void io_queue_next(struct io_kiocb *req)
1997 struct io_kiocb *nxt = io_req_find_next(req);
2000 io_req_task_queue(nxt);
2003 static void io_free_req(struct io_kiocb *req)
2010 struct task_struct *task;
2015 static inline void io_init_req_batch(struct req_batch *rb)
2022 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2023 struct req_batch *rb)
2026 io_put_task(rb->task, rb->task_refs);
2028 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2031 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2032 struct io_submit_state *state)
2036 if (req->task != rb->task) {
2038 io_put_task(rb->task, rb->task_refs);
2039 rb->task = req->task;
2045 io_dismantle_req(req);
2046 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2047 state->reqs[state->free_reqs++] = req;
2049 list_add(&req->compl.list, &state->comp.free_list);
2052 static void io_submit_flush_completions(struct io_comp_state *cs,
2053 struct io_ring_ctx *ctx)
2056 struct io_kiocb *req;
2057 struct req_batch rb;
2059 io_init_req_batch(&rb);
2060 spin_lock_irq(&ctx->completion_lock);
2061 for (i = 0; i < nr; i++) {
2063 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2065 io_commit_cqring(ctx);
2066 spin_unlock_irq(&ctx->completion_lock);
2068 io_cqring_ev_posted(ctx);
2069 for (i = 0; i < nr; i++) {
2072 /* submission and completion refs */
2073 if (refcount_sub_and_test(2, &req->refs))
2074 io_req_free_batch(&rb, req, &ctx->submit_state);
2077 io_req_free_batch_finish(ctx, &rb);
2082 * Drop reference to request, return next in chain (if there is one) if this
2083 * was the last reference to this request.
2085 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2087 struct io_kiocb *nxt = NULL;
2089 if (refcount_dec_and_test(&req->refs)) {
2090 nxt = io_req_find_next(req);
2096 static void io_put_req(struct io_kiocb *req)
2098 if (refcount_dec_and_test(&req->refs))
2102 static void io_put_req_deferred_cb(struct callback_head *cb)
2104 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2109 static void io_free_req_deferred(struct io_kiocb *req)
2113 req->task_work.func = io_put_req_deferred_cb;
2114 ret = io_req_task_work_add(req);
2116 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2119 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2121 if (refcount_sub_and_test(refs, &req->refs))
2122 io_free_req_deferred(req);
2125 static void io_double_put_req(struct io_kiocb *req)
2127 /* drop both submit and complete references */
2128 if (refcount_sub_and_test(2, &req->refs))
2132 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2134 /* See comment at the top of this file */
2136 return __io_cqring_events(ctx);
2139 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2141 struct io_rings *rings = ctx->rings;
2143 /* make sure SQ entry isn't read before tail */
2144 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2147 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2149 unsigned int cflags;
2151 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2152 cflags |= IORING_CQE_F_BUFFER;
2153 req->flags &= ~REQ_F_BUFFER_SELECTED;
2158 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2160 struct io_buffer *kbuf;
2162 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2163 return io_put_kbuf(req, kbuf);
2166 static inline bool io_run_task_work(void)
2169 * Not safe to run on exiting task, and the task_work handling will
2170 * not add work to such a task.
2172 if (unlikely(current->flags & PF_EXITING))
2174 if (current->task_works) {
2175 __set_current_state(TASK_RUNNING);
2184 * Find and free completed poll iocbs
2186 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2187 struct list_head *done)
2189 struct req_batch rb;
2190 struct io_kiocb *req;
2192 /* order with ->result store in io_complete_rw_iopoll() */
2195 io_init_req_batch(&rb);
2196 while (!list_empty(done)) {
2199 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2200 list_del(&req->inflight_entry);
2202 if (READ_ONCE(req->result) == -EAGAIN) {
2203 req->iopoll_completed = 0;
2204 if (io_rw_reissue(req))
2208 if (req->flags & REQ_F_BUFFER_SELECTED)
2209 cflags = io_put_rw_kbuf(req);
2211 __io_cqring_fill_event(req, req->result, cflags);
2214 if (refcount_dec_and_test(&req->refs))
2215 io_req_free_batch(&rb, req, &ctx->submit_state);
2218 io_commit_cqring(ctx);
2219 io_cqring_ev_posted_iopoll(ctx);
2220 io_req_free_batch_finish(ctx, &rb);
2223 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2226 struct io_kiocb *req, *tmp;
2232 * Only spin for completions if we don't have multiple devices hanging
2233 * off our complete list, and we're under the requested amount.
2235 spin = !ctx->poll_multi_file && *nr_events < min;
2238 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2239 struct kiocb *kiocb = &req->rw.kiocb;
2242 * Move completed and retryable entries to our local lists.
2243 * If we find a request that requires polling, break out
2244 * and complete those lists first, if we have entries there.
2246 if (READ_ONCE(req->iopoll_completed)) {
2247 list_move_tail(&req->inflight_entry, &done);
2250 if (!list_empty(&done))
2253 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2257 /* iopoll may have completed current req */
2258 if (READ_ONCE(req->iopoll_completed))
2259 list_move_tail(&req->inflight_entry, &done);
2266 if (!list_empty(&done))
2267 io_iopoll_complete(ctx, nr_events, &done);
2273 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2274 * non-spinning poll check - we'll still enter the driver poll loop, but only
2275 * as a non-spinning completion check.
2277 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2280 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2283 ret = io_do_iopoll(ctx, nr_events, min);
2286 if (*nr_events >= min)
2294 * We can't just wait for polled events to come to us, we have to actively
2295 * find and complete them.
2297 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2299 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2302 mutex_lock(&ctx->uring_lock);
2303 while (!list_empty(&ctx->iopoll_list)) {
2304 unsigned int nr_events = 0;
2306 io_do_iopoll(ctx, &nr_events, 0);
2308 /* let it sleep and repeat later if can't complete a request */
2312 * Ensure we allow local-to-the-cpu processing to take place,
2313 * in this case we need to ensure that we reap all events.
2314 * Also let task_work, etc. to progress by releasing the mutex
2316 if (need_resched()) {
2317 mutex_unlock(&ctx->uring_lock);
2319 mutex_lock(&ctx->uring_lock);
2322 mutex_unlock(&ctx->uring_lock);
2325 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2327 unsigned int nr_events = 0;
2328 int iters = 0, ret = 0;
2331 * We disallow the app entering submit/complete with polling, but we
2332 * still need to lock the ring to prevent racing with polled issue
2333 * that got punted to a workqueue.
2335 mutex_lock(&ctx->uring_lock);
2338 * Don't enter poll loop if we already have events pending.
2339 * If we do, we can potentially be spinning for commands that
2340 * already triggered a CQE (eg in error).
2342 if (test_bit(0, &ctx->cq_check_overflow))
2343 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2344 if (io_cqring_events(ctx))
2348 * If a submit got punted to a workqueue, we can have the
2349 * application entering polling for a command before it gets
2350 * issued. That app will hold the uring_lock for the duration
2351 * of the poll right here, so we need to take a breather every
2352 * now and then to ensure that the issue has a chance to add
2353 * the poll to the issued list. Otherwise we can spin here
2354 * forever, while the workqueue is stuck trying to acquire the
2357 if (!(++iters & 7)) {
2358 mutex_unlock(&ctx->uring_lock);
2360 mutex_lock(&ctx->uring_lock);
2363 ret = io_iopoll_getevents(ctx, &nr_events, min);
2367 } while (min && !nr_events && !need_resched());
2369 mutex_unlock(&ctx->uring_lock);
2373 static void kiocb_end_write(struct io_kiocb *req)
2376 * Tell lockdep we inherited freeze protection from submission
2379 if (req->flags & REQ_F_ISREG) {
2380 struct inode *inode = file_inode(req->file);
2382 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2384 file_end_write(req->file);
2388 static bool io_resubmit_prep(struct io_kiocb *req)
2390 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2392 struct iov_iter iter;
2394 /* already prepared */
2395 if (req->async_data)
2398 switch (req->opcode) {
2399 case IORING_OP_READV:
2400 case IORING_OP_READ_FIXED:
2401 case IORING_OP_READ:
2404 case IORING_OP_WRITEV:
2405 case IORING_OP_WRITE_FIXED:
2406 case IORING_OP_WRITE:
2410 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2415 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2418 return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2421 static bool io_rw_should_reissue(struct io_kiocb *req)
2423 umode_t mode = file_inode(req->file)->i_mode;
2424 struct io_ring_ctx *ctx = req->ctx;
2426 if (!S_ISBLK(mode) && !S_ISREG(mode))
2428 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2429 !(ctx->flags & IORING_SETUP_IOPOLL)))
2432 * If ref is dying, we might be running poll reap from the exit work.
2433 * Don't attempt to reissue from that path, just let it fail with
2436 if (percpu_ref_is_dying(&ctx->refs))
2442 static bool io_rw_reissue(struct io_kiocb *req)
2445 if (!io_rw_should_reissue(req))
2448 lockdep_assert_held(&req->ctx->uring_lock);
2450 if (io_resubmit_prep(req)) {
2451 refcount_inc(&req->refs);
2452 io_queue_async_work(req);
2455 req_set_fail_links(req);
2460 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2461 unsigned int issue_flags)
2465 if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_reissue(req))
2467 if (res != req->result)
2468 req_set_fail_links(req);
2470 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2471 kiocb_end_write(req);
2472 if (req->flags & REQ_F_BUFFER_SELECTED)
2473 cflags = io_put_rw_kbuf(req);
2474 __io_req_complete(req, issue_flags, res, cflags);
2477 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2479 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2481 __io_complete_rw(req, res, res2, 0);
2484 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2486 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2489 /* Rewind iter, if we have one. iopoll path resubmits as usual */
2490 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2491 struct io_async_rw *rw = req->async_data;
2494 iov_iter_revert(&rw->iter,
2495 req->result - iov_iter_count(&rw->iter));
2496 else if (!io_resubmit_prep(req))
2501 if (kiocb->ki_flags & IOCB_WRITE)
2502 kiocb_end_write(req);
2504 if (res != -EAGAIN && res != req->result)
2505 req_set_fail_links(req);
2507 WRITE_ONCE(req->result, res);
2508 /* order with io_poll_complete() checking ->result */
2510 WRITE_ONCE(req->iopoll_completed, 1);
2514 * After the iocb has been issued, it's safe to be found on the poll list.
2515 * Adding the kiocb to the list AFTER submission ensures that we don't
2516 * find it from a io_iopoll_getevents() thread before the issuer is done
2517 * accessing the kiocb cookie.
2519 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2521 struct io_ring_ctx *ctx = req->ctx;
2524 * Track whether we have multiple files in our lists. This will impact
2525 * how we do polling eventually, not spinning if we're on potentially
2526 * different devices.
2528 if (list_empty(&ctx->iopoll_list)) {
2529 ctx->poll_multi_file = false;
2530 } else if (!ctx->poll_multi_file) {
2531 struct io_kiocb *list_req;
2533 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2535 if (list_req->file != req->file)
2536 ctx->poll_multi_file = true;
2540 * For fast devices, IO may have already completed. If it has, add
2541 * it to the front so we find it first.
2543 if (READ_ONCE(req->iopoll_completed))
2544 list_add(&req->inflight_entry, &ctx->iopoll_list);
2546 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2549 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2550 * task context or in io worker task context. If current task context is
2551 * sq thread, we don't need to check whether should wake up sq thread.
2553 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2554 wq_has_sleeper(&ctx->sq_data->wait))
2555 wake_up(&ctx->sq_data->wait);
2558 static inline void io_state_file_put(struct io_submit_state *state)
2560 if (state->file_refs) {
2561 fput_many(state->file, state->file_refs);
2562 state->file_refs = 0;
2567 * Get as many references to a file as we have IOs left in this submission,
2568 * assuming most submissions are for one file, or at least that each file
2569 * has more than one submission.
2571 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2576 if (state->file_refs) {
2577 if (state->fd == fd) {
2581 io_state_file_put(state);
2583 state->file = fget_many(fd, state->ios_left);
2584 if (unlikely(!state->file))
2588 state->file_refs = state->ios_left - 1;
2592 static bool io_bdev_nowait(struct block_device *bdev)
2594 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2598 * If we tracked the file through the SCM inflight mechanism, we could support
2599 * any file. For now, just ensure that anything potentially problematic is done
2602 static bool io_file_supports_async(struct file *file, int rw)
2604 umode_t mode = file_inode(file)->i_mode;
2606 if (S_ISBLK(mode)) {
2607 if (IS_ENABLED(CONFIG_BLOCK) &&
2608 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2612 if (S_ISCHR(mode) || S_ISSOCK(mode))
2614 if (S_ISREG(mode)) {
2615 if (IS_ENABLED(CONFIG_BLOCK) &&
2616 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2617 file->f_op != &io_uring_fops)
2622 /* any ->read/write should understand O_NONBLOCK */
2623 if (file->f_flags & O_NONBLOCK)
2626 if (!(file->f_mode & FMODE_NOWAIT))
2630 return file->f_op->read_iter != NULL;
2632 return file->f_op->write_iter != NULL;
2635 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2637 struct io_ring_ctx *ctx = req->ctx;
2638 struct kiocb *kiocb = &req->rw.kiocb;
2639 struct file *file = req->file;
2643 if (S_ISREG(file_inode(file)->i_mode))
2644 req->flags |= REQ_F_ISREG;
2646 kiocb->ki_pos = READ_ONCE(sqe->off);
2647 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2648 req->flags |= REQ_F_CUR_POS;
2649 kiocb->ki_pos = file->f_pos;
2651 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2652 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2653 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2657 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2658 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2659 req->flags |= REQ_F_NOWAIT;
2661 ioprio = READ_ONCE(sqe->ioprio);
2663 ret = ioprio_check_cap(ioprio);
2667 kiocb->ki_ioprio = ioprio;
2669 kiocb->ki_ioprio = get_current_ioprio();
2671 if (ctx->flags & IORING_SETUP_IOPOLL) {
2672 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2673 !kiocb->ki_filp->f_op->iopoll)
2676 kiocb->ki_flags |= IOCB_HIPRI;
2677 kiocb->ki_complete = io_complete_rw_iopoll;
2678 req->iopoll_completed = 0;
2680 if (kiocb->ki_flags & IOCB_HIPRI)
2682 kiocb->ki_complete = io_complete_rw;
2685 req->rw.addr = READ_ONCE(sqe->addr);
2686 req->rw.len = READ_ONCE(sqe->len);
2687 req->buf_index = READ_ONCE(sqe->buf_index);
2691 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2697 case -ERESTARTNOINTR:
2698 case -ERESTARTNOHAND:
2699 case -ERESTART_RESTARTBLOCK:
2701 * We can't just restart the syscall, since previously
2702 * submitted sqes may already be in progress. Just fail this
2708 kiocb->ki_complete(kiocb, ret, 0);
2712 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2713 unsigned int issue_flags)
2715 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2716 struct io_async_rw *io = req->async_data;
2718 /* add previously done IO, if any */
2719 if (io && io->bytes_done > 0) {
2721 ret = io->bytes_done;
2723 ret += io->bytes_done;
2726 if (req->flags & REQ_F_CUR_POS)
2727 req->file->f_pos = kiocb->ki_pos;
2728 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2729 __io_complete_rw(req, ret, 0, issue_flags);
2731 io_rw_done(kiocb, ret);
2734 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2736 struct io_ring_ctx *ctx = req->ctx;
2737 size_t len = req->rw.len;
2738 struct io_mapped_ubuf *imu;
2739 u16 index, buf_index = req->buf_index;
2743 if (unlikely(buf_index >= ctx->nr_user_bufs))
2745 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2746 imu = &ctx->user_bufs[index];
2747 buf_addr = req->rw.addr;
2750 if (buf_addr + len < buf_addr)
2752 /* not inside the mapped region */
2753 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2757 * May not be a start of buffer, set size appropriately
2758 * and advance us to the beginning.
2760 offset = buf_addr - imu->ubuf;
2761 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2765 * Don't use iov_iter_advance() here, as it's really slow for
2766 * using the latter parts of a big fixed buffer - it iterates
2767 * over each segment manually. We can cheat a bit here, because
2770 * 1) it's a BVEC iter, we set it up
2771 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2772 * first and last bvec
2774 * So just find our index, and adjust the iterator afterwards.
2775 * If the offset is within the first bvec (or the whole first
2776 * bvec, just use iov_iter_advance(). This makes it easier
2777 * since we can just skip the first segment, which may not
2778 * be PAGE_SIZE aligned.
2780 const struct bio_vec *bvec = imu->bvec;
2782 if (offset <= bvec->bv_len) {
2783 iov_iter_advance(iter, offset);
2785 unsigned long seg_skip;
2787 /* skip first vec */
2788 offset -= bvec->bv_len;
2789 seg_skip = 1 + (offset >> PAGE_SHIFT);
2791 iter->bvec = bvec + seg_skip;
2792 iter->nr_segs -= seg_skip;
2793 iter->count -= bvec->bv_len + offset;
2794 iter->iov_offset = offset & ~PAGE_MASK;
2801 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2804 mutex_unlock(&ctx->uring_lock);
2807 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2810 * "Normal" inline submissions always hold the uring_lock, since we
2811 * grab it from the system call. Same is true for the SQPOLL offload.
2812 * The only exception is when we've detached the request and issue it
2813 * from an async worker thread, grab the lock for that case.
2816 mutex_lock(&ctx->uring_lock);
2819 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2820 int bgid, struct io_buffer *kbuf,
2823 struct io_buffer *head;
2825 if (req->flags & REQ_F_BUFFER_SELECTED)
2828 io_ring_submit_lock(req->ctx, needs_lock);
2830 lockdep_assert_held(&req->ctx->uring_lock);
2832 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2834 if (!list_empty(&head->list)) {
2835 kbuf = list_last_entry(&head->list, struct io_buffer,
2837 list_del(&kbuf->list);
2840 idr_remove(&req->ctx->io_buffer_idr, bgid);
2842 if (*len > kbuf->len)
2845 kbuf = ERR_PTR(-ENOBUFS);
2848 io_ring_submit_unlock(req->ctx, needs_lock);
2853 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2856 struct io_buffer *kbuf;
2859 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2860 bgid = req->buf_index;
2861 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2864 req->rw.addr = (u64) (unsigned long) kbuf;
2865 req->flags |= REQ_F_BUFFER_SELECTED;
2866 return u64_to_user_ptr(kbuf->addr);
2869 #ifdef CONFIG_COMPAT
2870 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2873 struct compat_iovec __user *uiov;
2874 compat_ssize_t clen;
2878 uiov = u64_to_user_ptr(req->rw.addr);
2879 if (!access_ok(uiov, sizeof(*uiov)))
2881 if (__get_user(clen, &uiov->iov_len))
2887 buf = io_rw_buffer_select(req, &len, needs_lock);
2889 return PTR_ERR(buf);
2890 iov[0].iov_base = buf;
2891 iov[0].iov_len = (compat_size_t) len;
2896 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2899 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2903 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2906 len = iov[0].iov_len;
2909 buf = io_rw_buffer_select(req, &len, needs_lock);
2911 return PTR_ERR(buf);
2912 iov[0].iov_base = buf;
2913 iov[0].iov_len = len;
2917 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2920 if (req->flags & REQ_F_BUFFER_SELECTED) {
2921 struct io_buffer *kbuf;
2923 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2924 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2925 iov[0].iov_len = kbuf->len;
2928 if (req->rw.len != 1)
2931 #ifdef CONFIG_COMPAT
2932 if (req->ctx->compat)
2933 return io_compat_import(req, iov, needs_lock);
2936 return __io_iov_buffer_select(req, iov, needs_lock);
2939 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2940 struct iov_iter *iter, bool needs_lock)
2942 void __user *buf = u64_to_user_ptr(req->rw.addr);
2943 size_t sqe_len = req->rw.len;
2944 u8 opcode = req->opcode;
2947 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2949 return io_import_fixed(req, rw, iter);
2952 /* buffer index only valid with fixed read/write, or buffer select */
2953 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2956 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2957 if (req->flags & REQ_F_BUFFER_SELECT) {
2958 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2960 return PTR_ERR(buf);
2961 req->rw.len = sqe_len;
2964 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2969 if (req->flags & REQ_F_BUFFER_SELECT) {
2970 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2972 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
2977 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
2981 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2983 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
2987 * For files that don't have ->read_iter() and ->write_iter(), handle them
2988 * by looping over ->read() or ->write() manually.
2990 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
2992 struct kiocb *kiocb = &req->rw.kiocb;
2993 struct file *file = req->file;
2997 * Don't support polled IO through this interface, and we can't
2998 * support non-blocking either. For the latter, this just causes
2999 * the kiocb to be handled from an async context.
3001 if (kiocb->ki_flags & IOCB_HIPRI)
3003 if (kiocb->ki_flags & IOCB_NOWAIT)
3006 while (iov_iter_count(iter)) {
3010 if (!iov_iter_is_bvec(iter)) {
3011 iovec = iov_iter_iovec(iter);
3013 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3014 iovec.iov_len = req->rw.len;
3018 nr = file->f_op->read(file, iovec.iov_base,
3019 iovec.iov_len, io_kiocb_ppos(kiocb));
3021 nr = file->f_op->write(file, iovec.iov_base,
3022 iovec.iov_len, io_kiocb_ppos(kiocb));
3031 if (nr != iovec.iov_len)
3035 iov_iter_advance(iter, nr);
3041 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3042 const struct iovec *fast_iov, struct iov_iter *iter)
3044 struct io_async_rw *rw = req->async_data;
3046 memcpy(&rw->iter, iter, sizeof(*iter));
3047 rw->free_iovec = iovec;
3049 /* can only be fixed buffers, no need to do anything */
3050 if (iov_iter_is_bvec(iter))
3053 unsigned iov_off = 0;
3055 rw->iter.iov = rw->fast_iov;
3056 if (iter->iov != fast_iov) {
3057 iov_off = iter->iov - fast_iov;
3058 rw->iter.iov += iov_off;
3060 if (rw->fast_iov != fast_iov)
3061 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3062 sizeof(struct iovec) * iter->nr_segs);
3064 req->flags |= REQ_F_NEED_CLEANUP;
3068 static inline int __io_alloc_async_data(struct io_kiocb *req)
3070 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3071 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3072 return req->async_data == NULL;
3075 static int io_alloc_async_data(struct io_kiocb *req)
3077 if (!io_op_defs[req->opcode].needs_async_data)
3080 return __io_alloc_async_data(req);
3083 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3084 const struct iovec *fast_iov,
3085 struct iov_iter *iter, bool force)
3087 if (!force && !io_op_defs[req->opcode].needs_async_data)
3089 if (!req->async_data) {
3090 if (__io_alloc_async_data(req)) {
3095 io_req_map_rw(req, iovec, fast_iov, iter);
3100 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3102 struct io_async_rw *iorw = req->async_data;
3103 struct iovec *iov = iorw->fast_iov;
3106 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3107 if (unlikely(ret < 0))
3110 iorw->bytes_done = 0;
3111 iorw->free_iovec = iov;
3113 req->flags |= REQ_F_NEED_CLEANUP;
3117 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3119 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3121 return io_prep_rw(req, sqe);
3125 * This is our waitqueue callback handler, registered through lock_page_async()
3126 * when we initially tried to do the IO with the iocb armed our waitqueue.
3127 * This gets called when the page is unlocked, and we generally expect that to
3128 * happen when the page IO is completed and the page is now uptodate. This will
3129 * queue a task_work based retry of the operation, attempting to copy the data
3130 * again. If the latter fails because the page was NOT uptodate, then we will
3131 * do a thread based blocking retry of the operation. That's the unexpected
3134 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3135 int sync, void *arg)
3137 struct wait_page_queue *wpq;
3138 struct io_kiocb *req = wait->private;
3139 struct wait_page_key *key = arg;
3141 wpq = container_of(wait, struct wait_page_queue, wait);
3143 if (!wake_page_match(wpq, key))
3146 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3147 list_del_init(&wait->entry);
3149 /* submit ref gets dropped, acquire a new one */
3150 refcount_inc(&req->refs);
3151 io_req_task_queue(req);
3156 * This controls whether a given IO request should be armed for async page
3157 * based retry. If we return false here, the request is handed to the async
3158 * worker threads for retry. If we're doing buffered reads on a regular file,
3159 * we prepare a private wait_page_queue entry and retry the operation. This
3160 * will either succeed because the page is now uptodate and unlocked, or it
3161 * will register a callback when the page is unlocked at IO completion. Through
3162 * that callback, io_uring uses task_work to setup a retry of the operation.
3163 * That retry will attempt the buffered read again. The retry will generally
3164 * succeed, or in rare cases where it fails, we then fall back to using the
3165 * async worker threads for a blocking retry.
3167 static bool io_rw_should_retry(struct io_kiocb *req)
3169 struct io_async_rw *rw = req->async_data;
3170 struct wait_page_queue *wait = &rw->wpq;
3171 struct kiocb *kiocb = &req->rw.kiocb;
3173 /* never retry for NOWAIT, we just complete with -EAGAIN */
3174 if (req->flags & REQ_F_NOWAIT)
3177 /* Only for buffered IO */
3178 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3182 * just use poll if we can, and don't attempt if the fs doesn't
3183 * support callback based unlocks
3185 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3188 wait->wait.func = io_async_buf_func;
3189 wait->wait.private = req;
3190 wait->wait.flags = 0;
3191 INIT_LIST_HEAD(&wait->wait.entry);
3192 kiocb->ki_flags |= IOCB_WAITQ;
3193 kiocb->ki_flags &= ~IOCB_NOWAIT;
3194 kiocb->ki_waitq = wait;
3198 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3200 if (req->file->f_op->read_iter)
3201 return call_read_iter(req->file, &req->rw.kiocb, iter);
3202 else if (req->file->f_op->read)
3203 return loop_rw_iter(READ, req, iter);
3208 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3210 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3211 struct kiocb *kiocb = &req->rw.kiocb;
3212 struct iov_iter __iter, *iter = &__iter;
3213 struct io_async_rw *rw = req->async_data;
3214 ssize_t io_size, ret, ret2;
3215 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3221 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3225 io_size = iov_iter_count(iter);
3226 req->result = io_size;
3228 /* Ensure we clear previously set non-block flag */
3229 if (!force_nonblock)
3230 kiocb->ki_flags &= ~IOCB_NOWAIT;
3232 kiocb->ki_flags |= IOCB_NOWAIT;
3234 /* If the file doesn't support async, just async punt */
3235 if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3236 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3237 return ret ?: -EAGAIN;
3240 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3241 if (unlikely(ret)) {
3246 ret = io_iter_do_read(req, iter);
3248 if (ret == -EIOCBQUEUED) {
3249 if (req->async_data)
3250 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3252 } else if (ret == -EAGAIN) {
3253 /* IOPOLL retry should happen for io-wq threads */
3254 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3256 /* no retry on NONBLOCK nor RWF_NOWAIT */
3257 if (req->flags & REQ_F_NOWAIT)
3259 /* some cases will consume bytes even on error returns */
3260 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3262 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3263 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3264 /* read all, failed, already did sync or don't want to retry */
3268 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3273 rw = req->async_data;
3274 /* now use our persistent iterator, if we aren't already */
3279 rw->bytes_done += ret;
3280 /* if we can retry, do so with the callbacks armed */
3281 if (!io_rw_should_retry(req)) {
3282 kiocb->ki_flags &= ~IOCB_WAITQ;
3287 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3288 * we get -EIOCBQUEUED, then we'll get a notification when the
3289 * desired page gets unlocked. We can also get a partial read
3290 * here, and if we do, then just retry at the new offset.
3292 ret = io_iter_do_read(req, iter);
3293 if (ret == -EIOCBQUEUED)
3295 /* we got some bytes, but not all. retry. */
3296 kiocb->ki_flags &= ~IOCB_WAITQ;
3297 } while (ret > 0 && ret < io_size);
3299 kiocb_done(kiocb, ret, issue_flags);
3301 /* it's faster to check here then delegate to kfree */
3307 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3309 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3311 return io_prep_rw(req, sqe);
3314 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3316 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3317 struct kiocb *kiocb = &req->rw.kiocb;
3318 struct iov_iter __iter, *iter = &__iter;
3319 struct io_async_rw *rw = req->async_data;
3320 ssize_t ret, ret2, io_size;
3321 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3327 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3331 io_size = iov_iter_count(iter);
3332 req->result = io_size;
3334 /* Ensure we clear previously set non-block flag */
3335 if (!force_nonblock)
3336 kiocb->ki_flags &= ~IOCB_NOWAIT;
3338 kiocb->ki_flags |= IOCB_NOWAIT;
3340 /* If the file doesn't support async, just async punt */
3341 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3344 /* file path doesn't support NOWAIT for non-direct_IO */
3345 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3346 (req->flags & REQ_F_ISREG))
3349 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3354 * Open-code file_start_write here to grab freeze protection,
3355 * which will be released by another thread in
3356 * io_complete_rw(). Fool lockdep by telling it the lock got
3357 * released so that it doesn't complain about the held lock when
3358 * we return to userspace.
3360 if (req->flags & REQ_F_ISREG) {
3361 sb_start_write(file_inode(req->file)->i_sb);
3362 __sb_writers_release(file_inode(req->file)->i_sb,
3365 kiocb->ki_flags |= IOCB_WRITE;
3367 if (req->file->f_op->write_iter)
3368 ret2 = call_write_iter(req->file, kiocb, iter);
3369 else if (req->file->f_op->write)
3370 ret2 = loop_rw_iter(WRITE, req, iter);
3375 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3376 * retry them without IOCB_NOWAIT.
3378 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3380 /* no retry on NONBLOCK nor RWF_NOWAIT */
3381 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3383 if (ret2 == -EIOCBQUEUED && req->async_data)
3384 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3385 if (!force_nonblock || ret2 != -EAGAIN) {
3386 /* IOPOLL retry should happen for io-wq threads */
3387 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3390 kiocb_done(kiocb, ret2, issue_flags);
3393 /* some cases will consume bytes even on error returns */
3394 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3395 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3396 return ret ?: -EAGAIN;
3399 /* it's reportedly faster than delegating the null check to kfree() */
3405 static int io_renameat_prep(struct io_kiocb *req,
3406 const struct io_uring_sqe *sqe)
3408 struct io_rename *ren = &req->rename;
3409 const char __user *oldf, *newf;
3411 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3414 ren->old_dfd = READ_ONCE(sqe->fd);
3415 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3416 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3417 ren->new_dfd = READ_ONCE(sqe->len);
3418 ren->flags = READ_ONCE(sqe->rename_flags);
3420 ren->oldpath = getname(oldf);
3421 if (IS_ERR(ren->oldpath))
3422 return PTR_ERR(ren->oldpath);
3424 ren->newpath = getname(newf);
3425 if (IS_ERR(ren->newpath)) {
3426 putname(ren->oldpath);
3427 return PTR_ERR(ren->newpath);
3430 req->flags |= REQ_F_NEED_CLEANUP;
3434 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3436 struct io_rename *ren = &req->rename;
3439 if (issue_flags & IO_URING_F_NONBLOCK)
3442 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3443 ren->newpath, ren->flags);
3445 req->flags &= ~REQ_F_NEED_CLEANUP;
3447 req_set_fail_links(req);
3448 io_req_complete(req, ret);
3452 static int io_unlinkat_prep(struct io_kiocb *req,
3453 const struct io_uring_sqe *sqe)
3455 struct io_unlink *un = &req->unlink;
3456 const char __user *fname;
3458 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3461 un->dfd = READ_ONCE(sqe->fd);
3463 un->flags = READ_ONCE(sqe->unlink_flags);
3464 if (un->flags & ~AT_REMOVEDIR)
3467 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3468 un->filename = getname(fname);
3469 if (IS_ERR(un->filename))
3470 return PTR_ERR(un->filename);
3472 req->flags |= REQ_F_NEED_CLEANUP;
3476 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3478 struct io_unlink *un = &req->unlink;
3481 if (issue_flags & IO_URING_F_NONBLOCK)
3484 if (un->flags & AT_REMOVEDIR)
3485 ret = do_rmdir(un->dfd, un->filename);
3487 ret = do_unlinkat(un->dfd, un->filename);
3489 req->flags &= ~REQ_F_NEED_CLEANUP;
3491 req_set_fail_links(req);
3492 io_req_complete(req, ret);
3496 static int io_shutdown_prep(struct io_kiocb *req,
3497 const struct io_uring_sqe *sqe)
3499 #if defined(CONFIG_NET)
3500 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3502 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3506 req->shutdown.how = READ_ONCE(sqe->len);
3513 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3515 #if defined(CONFIG_NET)
3516 struct socket *sock;
3519 if (issue_flags & IO_URING_F_NONBLOCK)
3522 sock = sock_from_file(req->file);
3523 if (unlikely(!sock))
3526 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3528 req_set_fail_links(req);
3529 io_req_complete(req, ret);
3536 static int __io_splice_prep(struct io_kiocb *req,
3537 const struct io_uring_sqe *sqe)
3539 struct io_splice* sp = &req->splice;
3540 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3542 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3546 sp->len = READ_ONCE(sqe->len);
3547 sp->flags = READ_ONCE(sqe->splice_flags);
3549 if (unlikely(sp->flags & ~valid_flags))
3552 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3553 (sp->flags & SPLICE_F_FD_IN_FIXED));
3556 req->flags |= REQ_F_NEED_CLEANUP;
3558 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3560 * Splice operation will be punted aync, and here need to
3561 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3563 req->work.flags |= IO_WQ_WORK_UNBOUND;
3569 static int io_tee_prep(struct io_kiocb *req,
3570 const struct io_uring_sqe *sqe)
3572 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3574 return __io_splice_prep(req, sqe);
3577 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3579 struct io_splice *sp = &req->splice;
3580 struct file *in = sp->file_in;
3581 struct file *out = sp->file_out;
3582 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3585 if (issue_flags & IO_URING_F_NONBLOCK)
3588 ret = do_tee(in, out, sp->len, flags);
3590 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3591 req->flags &= ~REQ_F_NEED_CLEANUP;
3594 req_set_fail_links(req);
3595 io_req_complete(req, ret);
3599 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3601 struct io_splice* sp = &req->splice;
3603 sp->off_in = READ_ONCE(sqe->splice_off_in);
3604 sp->off_out = READ_ONCE(sqe->off);
3605 return __io_splice_prep(req, sqe);
3608 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3610 struct io_splice *sp = &req->splice;
3611 struct file *in = sp->file_in;
3612 struct file *out = sp->file_out;
3613 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3614 loff_t *poff_in, *poff_out;
3617 if (issue_flags & IO_URING_F_NONBLOCK)
3620 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3621 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3624 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3626 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3627 req->flags &= ~REQ_F_NEED_CLEANUP;
3630 req_set_fail_links(req);
3631 io_req_complete(req, ret);
3636 * IORING_OP_NOP just posts a completion event, nothing else.
3638 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3640 struct io_ring_ctx *ctx = req->ctx;
3642 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3645 __io_req_complete(req, issue_flags, 0, 0);
3649 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3651 struct io_ring_ctx *ctx = req->ctx;
3656 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3658 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3661 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3662 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3665 req->sync.off = READ_ONCE(sqe->off);
3666 req->sync.len = READ_ONCE(sqe->len);
3670 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3672 loff_t end = req->sync.off + req->sync.len;
3675 /* fsync always requires a blocking context */
3676 if (issue_flags & IO_URING_F_NONBLOCK)
3679 ret = vfs_fsync_range(req->file, req->sync.off,
3680 end > 0 ? end : LLONG_MAX,
3681 req->sync.flags & IORING_FSYNC_DATASYNC);
3683 req_set_fail_links(req);
3684 io_req_complete(req, ret);
3688 static int io_fallocate_prep(struct io_kiocb *req,
3689 const struct io_uring_sqe *sqe)
3691 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3693 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3696 req->sync.off = READ_ONCE(sqe->off);
3697 req->sync.len = READ_ONCE(sqe->addr);
3698 req->sync.mode = READ_ONCE(sqe->len);
3702 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3706 /* fallocate always requiring blocking context */
3707 if (issue_flags & IO_URING_F_NONBLOCK)
3709 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3712 req_set_fail_links(req);
3713 io_req_complete(req, ret);
3717 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3719 const char __user *fname;
3722 if (unlikely(sqe->ioprio || sqe->buf_index))
3724 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3727 /* open.how should be already initialised */
3728 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3729 req->open.how.flags |= O_LARGEFILE;
3731 req->open.dfd = READ_ONCE(sqe->fd);
3732 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3733 req->open.filename = getname(fname);
3734 if (IS_ERR(req->open.filename)) {
3735 ret = PTR_ERR(req->open.filename);
3736 req->open.filename = NULL;
3739 req->open.nofile = rlimit(RLIMIT_NOFILE);
3740 req->flags |= REQ_F_NEED_CLEANUP;
3744 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3748 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3750 mode = READ_ONCE(sqe->len);
3751 flags = READ_ONCE(sqe->open_flags);
3752 req->open.how = build_open_how(flags, mode);
3753 return __io_openat_prep(req, sqe);
3756 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3758 struct open_how __user *how;
3762 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3764 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3765 len = READ_ONCE(sqe->len);
3766 if (len < OPEN_HOW_SIZE_VER0)
3769 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3774 return __io_openat_prep(req, sqe);
3777 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3779 struct open_flags op;
3782 bool resolve_nonblock;
3785 ret = build_open_flags(&req->open.how, &op);
3788 nonblock_set = op.open_flag & O_NONBLOCK;
3789 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3790 if (issue_flags & IO_URING_F_NONBLOCK) {
3792 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3793 * it'll always -EAGAIN
3795 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3797 op.lookup_flags |= LOOKUP_CACHED;
3798 op.open_flag |= O_NONBLOCK;
3801 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3805 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3806 /* only retry if RESOLVE_CACHED wasn't already set by application */
3807 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3808 file == ERR_PTR(-EAGAIN)) {
3810 * We could hang on to this 'fd', but seems like marginal
3811 * gain for something that is now known to be a slower path.
3812 * So just put it, and we'll get a new one when we retry.
3820 ret = PTR_ERR(file);
3822 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3823 file->f_flags &= ~O_NONBLOCK;
3824 fsnotify_open(file);
3825 fd_install(ret, file);
3828 putname(req->open.filename);
3829 req->flags &= ~REQ_F_NEED_CLEANUP;
3831 req_set_fail_links(req);
3832 io_req_complete(req, ret);
3836 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3838 return io_openat2(req, issue_flags);
3841 static int io_remove_buffers_prep(struct io_kiocb *req,
3842 const struct io_uring_sqe *sqe)
3844 struct io_provide_buf *p = &req->pbuf;
3847 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3850 tmp = READ_ONCE(sqe->fd);
3851 if (!tmp || tmp > USHRT_MAX)
3854 memset(p, 0, sizeof(*p));
3856 p->bgid = READ_ONCE(sqe->buf_group);
3860 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3861 int bgid, unsigned nbufs)
3865 /* shouldn't happen */
3869 /* the head kbuf is the list itself */
3870 while (!list_empty(&buf->list)) {
3871 struct io_buffer *nxt;
3873 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3874 list_del(&nxt->list);
3881 idr_remove(&ctx->io_buffer_idr, bgid);
3886 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3888 struct io_provide_buf *p = &req->pbuf;
3889 struct io_ring_ctx *ctx = req->ctx;
3890 struct io_buffer *head;
3892 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3894 io_ring_submit_lock(ctx, !force_nonblock);
3896 lockdep_assert_held(&ctx->uring_lock);
3899 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3901 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3903 req_set_fail_links(req);
3905 /* need to hold the lock to complete IOPOLL requests */
3906 if (ctx->flags & IORING_SETUP_IOPOLL) {
3907 __io_req_complete(req, issue_flags, ret, 0);
3908 io_ring_submit_unlock(ctx, !force_nonblock);
3910 io_ring_submit_unlock(ctx, !force_nonblock);
3911 __io_req_complete(req, issue_flags, ret, 0);
3916 static int io_provide_buffers_prep(struct io_kiocb *req,
3917 const struct io_uring_sqe *sqe)
3919 struct io_provide_buf *p = &req->pbuf;
3922 if (sqe->ioprio || sqe->rw_flags)
3925 tmp = READ_ONCE(sqe->fd);
3926 if (!tmp || tmp > USHRT_MAX)
3929 p->addr = READ_ONCE(sqe->addr);
3930 p->len = READ_ONCE(sqe->len);
3932 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3935 p->bgid = READ_ONCE(sqe->buf_group);
3936 tmp = READ_ONCE(sqe->off);
3937 if (tmp > USHRT_MAX)
3943 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3945 struct io_buffer *buf;
3946 u64 addr = pbuf->addr;
3947 int i, bid = pbuf->bid;
3949 for (i = 0; i < pbuf->nbufs; i++) {
3950 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3955 buf->len = pbuf->len;
3960 INIT_LIST_HEAD(&buf->list);
3963 list_add_tail(&buf->list, &(*head)->list);
3967 return i ? i : -ENOMEM;
3970 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3972 struct io_provide_buf *p = &req->pbuf;
3973 struct io_ring_ctx *ctx = req->ctx;
3974 struct io_buffer *head, *list;
3976 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3978 io_ring_submit_lock(ctx, !force_nonblock);
3980 lockdep_assert_held(&ctx->uring_lock);
3982 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3984 ret = io_add_buffers(p, &head);
3989 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3992 __io_remove_buffers(ctx, head, p->bgid, -1U);
3998 req_set_fail_links(req);
4000 /* need to hold the lock to complete IOPOLL requests */
4001 if (ctx->flags & IORING_SETUP_IOPOLL) {
4002 __io_req_complete(req, issue_flags, ret, 0);
4003 io_ring_submit_unlock(ctx, !force_nonblock);
4005 io_ring_submit_unlock(ctx, !force_nonblock);
4006 __io_req_complete(req, issue_flags, ret, 0);
4011 static int io_epoll_ctl_prep(struct io_kiocb *req,
4012 const struct io_uring_sqe *sqe)
4014 #if defined(CONFIG_EPOLL)
4015 if (sqe->ioprio || sqe->buf_index)
4017 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4020 req->epoll.epfd = READ_ONCE(sqe->fd);
4021 req->epoll.op = READ_ONCE(sqe->len);
4022 req->epoll.fd = READ_ONCE(sqe->off);
4024 if (ep_op_has_event(req->epoll.op)) {
4025 struct epoll_event __user *ev;
4027 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4028 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4038 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4040 #if defined(CONFIG_EPOLL)
4041 struct io_epoll *ie = &req->epoll;
4043 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4045 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4046 if (force_nonblock && ret == -EAGAIN)
4050 req_set_fail_links(req);
4051 __io_req_complete(req, issue_flags, ret, 0);
4058 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4060 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4061 if (sqe->ioprio || sqe->buf_index || sqe->off)
4063 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4066 req->madvise.addr = READ_ONCE(sqe->addr);
4067 req->madvise.len = READ_ONCE(sqe->len);
4068 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4075 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4077 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4078 struct io_madvise *ma = &req->madvise;
4081 if (issue_flags & IO_URING_F_NONBLOCK)
4084 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4086 req_set_fail_links(req);
4087 io_req_complete(req, ret);
4094 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4096 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4098 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4101 req->fadvise.offset = READ_ONCE(sqe->off);
4102 req->fadvise.len = READ_ONCE(sqe->len);
4103 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4107 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4109 struct io_fadvise *fa = &req->fadvise;
4112 if (issue_flags & IO_URING_F_NONBLOCK) {
4113 switch (fa->advice) {
4114 case POSIX_FADV_NORMAL:
4115 case POSIX_FADV_RANDOM:
4116 case POSIX_FADV_SEQUENTIAL:
4123 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4125 req_set_fail_links(req);
4126 io_req_complete(req, ret);
4130 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4132 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4134 if (sqe->ioprio || sqe->buf_index)
4136 if (req->flags & REQ_F_FIXED_FILE)
4139 req->statx.dfd = READ_ONCE(sqe->fd);
4140 req->statx.mask = READ_ONCE(sqe->len);
4141 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4142 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4143 req->statx.flags = READ_ONCE(sqe->statx_flags);
4148 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4150 struct io_statx *ctx = &req->statx;
4153 if (issue_flags & IO_URING_F_NONBLOCK) {
4154 /* only need file table for an actual valid fd */
4155 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4156 req->flags |= REQ_F_NO_FILE_TABLE;
4160 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4164 req_set_fail_links(req);
4165 io_req_complete(req, ret);
4169 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4171 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4173 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4174 sqe->rw_flags || sqe->buf_index)
4176 if (req->flags & REQ_F_FIXED_FILE)
4179 req->close.fd = READ_ONCE(sqe->fd);
4183 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4185 struct files_struct *files = current->files;
4186 struct io_close *close = &req->close;
4187 struct fdtable *fdt;
4193 spin_lock(&files->file_lock);
4194 fdt = files_fdtable(files);
4195 if (close->fd >= fdt->max_fds) {
4196 spin_unlock(&files->file_lock);
4199 file = fdt->fd[close->fd];
4201 spin_unlock(&files->file_lock);
4205 if (file->f_op == &io_uring_fops) {
4206 spin_unlock(&files->file_lock);
4211 /* if the file has a flush method, be safe and punt to async */
4212 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4213 spin_unlock(&files->file_lock);
4217 ret = __close_fd_get_file(close->fd, &file);
4218 spin_unlock(&files->file_lock);
4225 /* No ->flush() or already async, safely close from here */
4226 ret = filp_close(file, current->files);
4229 req_set_fail_links(req);
4232 __io_req_complete(req, issue_flags, ret, 0);
4236 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4238 struct io_ring_ctx *ctx = req->ctx;
4240 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4242 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4245 req->sync.off = READ_ONCE(sqe->off);
4246 req->sync.len = READ_ONCE(sqe->len);
4247 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4251 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4255 /* sync_file_range always requires a blocking context */
4256 if (issue_flags & IO_URING_F_NONBLOCK)
4259 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4262 req_set_fail_links(req);
4263 io_req_complete(req, ret);
4267 #if defined(CONFIG_NET)
4268 static int io_setup_async_msg(struct io_kiocb *req,
4269 struct io_async_msghdr *kmsg)
4271 struct io_async_msghdr *async_msg = req->async_data;
4275 if (io_alloc_async_data(req)) {
4276 kfree(kmsg->free_iov);
4279 async_msg = req->async_data;
4280 req->flags |= REQ_F_NEED_CLEANUP;
4281 memcpy(async_msg, kmsg, sizeof(*kmsg));
4282 async_msg->msg.msg_name = &async_msg->addr;
4283 /* if were using fast_iov, set it to the new one */
4284 if (!async_msg->free_iov)
4285 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4290 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4291 struct io_async_msghdr *iomsg)
4293 iomsg->msg.msg_name = &iomsg->addr;
4294 iomsg->free_iov = iomsg->fast_iov;
4295 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4296 req->sr_msg.msg_flags, &iomsg->free_iov);
4299 static int io_sendmsg_prep_async(struct io_kiocb *req)
4303 if (!io_op_defs[req->opcode].needs_async_data)
4305 ret = io_sendmsg_copy_hdr(req, req->async_data);
4307 req->flags |= REQ_F_NEED_CLEANUP;
4311 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4313 struct io_sr_msg *sr = &req->sr_msg;
4315 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4318 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4319 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4320 sr->len = READ_ONCE(sqe->len);
4322 #ifdef CONFIG_COMPAT
4323 if (req->ctx->compat)
4324 sr->msg_flags |= MSG_CMSG_COMPAT;
4329 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4331 struct io_async_msghdr iomsg, *kmsg;
4332 struct socket *sock;
4336 sock = sock_from_file(req->file);
4337 if (unlikely(!sock))
4340 kmsg = req->async_data;
4342 ret = io_sendmsg_copy_hdr(req, &iomsg);
4348 flags = req->sr_msg.msg_flags;
4349 if (flags & MSG_DONTWAIT)
4350 req->flags |= REQ_F_NOWAIT;
4351 else if (issue_flags & IO_URING_F_NONBLOCK)
4352 flags |= MSG_DONTWAIT;
4354 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4355 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4356 return io_setup_async_msg(req, kmsg);
4357 if (ret == -ERESTARTSYS)
4360 /* fast path, check for non-NULL to avoid function call */
4362 kfree(kmsg->free_iov);
4363 req->flags &= ~REQ_F_NEED_CLEANUP;
4365 req_set_fail_links(req);
4366 __io_req_complete(req, issue_flags, ret, 0);
4370 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4372 struct io_sr_msg *sr = &req->sr_msg;
4375 struct socket *sock;
4379 sock = sock_from_file(req->file);
4380 if (unlikely(!sock))
4383 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4387 msg.msg_name = NULL;
4388 msg.msg_control = NULL;
4389 msg.msg_controllen = 0;
4390 msg.msg_namelen = 0;
4392 flags = req->sr_msg.msg_flags;
4393 if (flags & MSG_DONTWAIT)
4394 req->flags |= REQ_F_NOWAIT;
4395 else if (issue_flags & IO_URING_F_NONBLOCK)
4396 flags |= MSG_DONTWAIT;
4398 msg.msg_flags = flags;
4399 ret = sock_sendmsg(sock, &msg);
4400 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4402 if (ret == -ERESTARTSYS)
4406 req_set_fail_links(req);
4407 __io_req_complete(req, issue_flags, ret, 0);
4411 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4412 struct io_async_msghdr *iomsg)
4414 struct io_sr_msg *sr = &req->sr_msg;
4415 struct iovec __user *uiov;
4419 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4420 &iomsg->uaddr, &uiov, &iov_len);
4424 if (req->flags & REQ_F_BUFFER_SELECT) {
4427 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4429 sr->len = iomsg->fast_iov[0].iov_len;
4430 iomsg->free_iov = NULL;
4432 iomsg->free_iov = iomsg->fast_iov;
4433 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4434 &iomsg->free_iov, &iomsg->msg.msg_iter,
4443 #ifdef CONFIG_COMPAT
4444 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4445 struct io_async_msghdr *iomsg)
4447 struct compat_msghdr __user *msg_compat;
4448 struct io_sr_msg *sr = &req->sr_msg;
4449 struct compat_iovec __user *uiov;
4454 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4455 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4460 uiov = compat_ptr(ptr);
4461 if (req->flags & REQ_F_BUFFER_SELECT) {
4462 compat_ssize_t clen;
4466 if (!access_ok(uiov, sizeof(*uiov)))
4468 if (__get_user(clen, &uiov->iov_len))
4473 iomsg->free_iov = NULL;
4475 iomsg->free_iov = iomsg->fast_iov;
4476 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4477 UIO_FASTIOV, &iomsg->free_iov,
4478 &iomsg->msg.msg_iter, true);
4487 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4488 struct io_async_msghdr *iomsg)
4490 iomsg->msg.msg_name = &iomsg->addr;
4492 #ifdef CONFIG_COMPAT
4493 if (req->ctx->compat)
4494 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4497 return __io_recvmsg_copy_hdr(req, iomsg);
4500 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4503 struct io_sr_msg *sr = &req->sr_msg;
4504 struct io_buffer *kbuf;
4506 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4511 req->flags |= REQ_F_BUFFER_SELECTED;
4515 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4517 return io_put_kbuf(req, req->sr_msg.kbuf);
4520 static int io_recvmsg_prep_async(struct io_kiocb *req)
4524 if (!io_op_defs[req->opcode].needs_async_data)
4526 ret = io_recvmsg_copy_hdr(req, req->async_data);
4528 req->flags |= REQ_F_NEED_CLEANUP;
4532 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4534 struct io_sr_msg *sr = &req->sr_msg;
4536 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4539 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4540 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4541 sr->len = READ_ONCE(sqe->len);
4542 sr->bgid = READ_ONCE(sqe->buf_group);
4544 #ifdef CONFIG_COMPAT
4545 if (req->ctx->compat)
4546 sr->msg_flags |= MSG_CMSG_COMPAT;
4551 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4553 struct io_async_msghdr iomsg, *kmsg;
4554 struct socket *sock;
4555 struct io_buffer *kbuf;
4557 int ret, cflags = 0;
4558 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4560 sock = sock_from_file(req->file);
4561 if (unlikely(!sock))
4564 kmsg = req->async_data;
4566 ret = io_recvmsg_copy_hdr(req, &iomsg);
4572 if (req->flags & REQ_F_BUFFER_SELECT) {
4573 kbuf = io_recv_buffer_select(req, !force_nonblock);
4575 return PTR_ERR(kbuf);
4576 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4577 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4578 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4579 1, req->sr_msg.len);
4582 flags = req->sr_msg.msg_flags;
4583 if (flags & MSG_DONTWAIT)
4584 req->flags |= REQ_F_NOWAIT;
4585 else if (force_nonblock)
4586 flags |= MSG_DONTWAIT;
4588 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4589 kmsg->uaddr, flags);
4590 if (force_nonblock && ret == -EAGAIN)
4591 return io_setup_async_msg(req, kmsg);
4592 if (ret == -ERESTARTSYS)
4595 if (req->flags & REQ_F_BUFFER_SELECTED)
4596 cflags = io_put_recv_kbuf(req);
4597 /* fast path, check for non-NULL to avoid function call */
4599 kfree(kmsg->free_iov);
4600 req->flags &= ~REQ_F_NEED_CLEANUP;
4602 req_set_fail_links(req);
4603 __io_req_complete(req, issue_flags, ret, cflags);
4607 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4609 struct io_buffer *kbuf;
4610 struct io_sr_msg *sr = &req->sr_msg;
4612 void __user *buf = sr->buf;
4613 struct socket *sock;
4616 int ret, cflags = 0;
4617 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4619 sock = sock_from_file(req->file);
4620 if (unlikely(!sock))
4623 if (req->flags & REQ_F_BUFFER_SELECT) {
4624 kbuf = io_recv_buffer_select(req, !force_nonblock);
4626 return PTR_ERR(kbuf);
4627 buf = u64_to_user_ptr(kbuf->addr);
4630 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4634 msg.msg_name = NULL;
4635 msg.msg_control = NULL;
4636 msg.msg_controllen = 0;
4637 msg.msg_namelen = 0;
4638 msg.msg_iocb = NULL;
4641 flags = req->sr_msg.msg_flags;
4642 if (flags & MSG_DONTWAIT)
4643 req->flags |= REQ_F_NOWAIT;
4644 else if (force_nonblock)
4645 flags |= MSG_DONTWAIT;
4647 ret = sock_recvmsg(sock, &msg, flags);
4648 if (force_nonblock && ret == -EAGAIN)
4650 if (ret == -ERESTARTSYS)
4653 if (req->flags & REQ_F_BUFFER_SELECTED)
4654 cflags = io_put_recv_kbuf(req);
4656 req_set_fail_links(req);
4657 __io_req_complete(req, issue_flags, ret, cflags);
4661 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4663 struct io_accept *accept = &req->accept;
4665 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4667 if (sqe->ioprio || sqe->len || sqe->buf_index)
4670 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4671 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4672 accept->flags = READ_ONCE(sqe->accept_flags);
4673 accept->nofile = rlimit(RLIMIT_NOFILE);
4677 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4679 struct io_accept *accept = &req->accept;
4680 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4681 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4684 if (req->file->f_flags & O_NONBLOCK)
4685 req->flags |= REQ_F_NOWAIT;
4687 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4688 accept->addr_len, accept->flags,
4690 if (ret == -EAGAIN && force_nonblock)
4693 if (ret == -ERESTARTSYS)
4695 req_set_fail_links(req);
4697 __io_req_complete(req, issue_flags, ret, 0);
4701 static int io_connect_prep_async(struct io_kiocb *req)
4703 struct io_async_connect *io = req->async_data;
4704 struct io_connect *conn = &req->connect;
4706 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4709 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4711 struct io_connect *conn = &req->connect;
4713 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4715 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4718 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4719 conn->addr_len = READ_ONCE(sqe->addr2);
4723 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4725 struct io_async_connect __io, *io;
4726 unsigned file_flags;
4728 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4730 if (req->async_data) {
4731 io = req->async_data;
4733 ret = move_addr_to_kernel(req->connect.addr,
4734 req->connect.addr_len,
4741 file_flags = force_nonblock ? O_NONBLOCK : 0;
4743 ret = __sys_connect_file(req->file, &io->address,
4744 req->connect.addr_len, file_flags);
4745 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4746 if (req->async_data)
4748 if (io_alloc_async_data(req)) {
4752 io = req->async_data;
4753 memcpy(req->async_data, &__io, sizeof(__io));
4756 if (ret == -ERESTARTSYS)
4760 req_set_fail_links(req);
4761 __io_req_complete(req, issue_flags, ret, 0);
4764 #else /* !CONFIG_NET */
4765 #define IO_NETOP_FN(op) \
4766 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4768 return -EOPNOTSUPP; \
4771 #define IO_NETOP_PREP(op) \
4773 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4775 return -EOPNOTSUPP; \
4778 #define IO_NETOP_PREP_ASYNC(op) \
4780 static int io_##op##_prep_async(struct io_kiocb *req) \
4782 return -EOPNOTSUPP; \
4785 IO_NETOP_PREP_ASYNC(sendmsg);
4786 IO_NETOP_PREP_ASYNC(recvmsg);
4787 IO_NETOP_PREP_ASYNC(connect);
4788 IO_NETOP_PREP(accept);
4791 #endif /* CONFIG_NET */
4793 struct io_poll_table {
4794 struct poll_table_struct pt;
4795 struct io_kiocb *req;
4799 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4800 __poll_t mask, task_work_func_t func)
4804 /* for instances that support it check for an event match first: */
4805 if (mask && !(mask & poll->events))
4808 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4810 list_del_init(&poll->wait.entry);
4813 req->task_work.func = func;
4814 percpu_ref_get(&req->ctx->refs);
4817 * If this fails, then the task is exiting. When a task exits, the
4818 * work gets canceled, so just cancel this request as well instead
4819 * of executing it. We can't safely execute it anyway, as we may not
4820 * have the needed state needed for it anyway.
4822 ret = io_req_task_work_add(req);
4823 if (unlikely(ret)) {
4824 WRITE_ONCE(poll->canceled, true);
4825 io_req_task_work_add_fallback(req, func);
4830 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4831 __acquires(&req->ctx->completion_lock)
4833 struct io_ring_ctx *ctx = req->ctx;
4835 if (!req->result && !READ_ONCE(poll->canceled)) {
4836 struct poll_table_struct pt = { ._key = poll->events };
4838 req->result = vfs_poll(req->file, &pt) & poll->events;
4841 spin_lock_irq(&ctx->completion_lock);
4842 if (!req->result && !READ_ONCE(poll->canceled)) {
4843 add_wait_queue(poll->head, &poll->wait);
4850 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4852 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4853 if (req->opcode == IORING_OP_POLL_ADD)
4854 return req->async_data;
4855 return req->apoll->double_poll;
4858 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4860 if (req->opcode == IORING_OP_POLL_ADD)
4862 return &req->apoll->poll;
4865 static void io_poll_remove_double(struct io_kiocb *req)
4867 struct io_poll_iocb *poll = io_poll_get_double(req);
4869 lockdep_assert_held(&req->ctx->completion_lock);
4871 if (poll && poll->head) {
4872 struct wait_queue_head *head = poll->head;
4874 spin_lock(&head->lock);
4875 list_del_init(&poll->wait.entry);
4876 if (poll->wait.private)
4877 refcount_dec(&req->refs);
4879 spin_unlock(&head->lock);
4883 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4885 struct io_ring_ctx *ctx = req->ctx;
4887 io_poll_remove_double(req);
4888 req->poll.done = true;
4889 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4890 io_commit_cqring(ctx);
4893 static void io_poll_task_func(struct callback_head *cb)
4895 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4896 struct io_ring_ctx *ctx = req->ctx;
4897 struct io_kiocb *nxt;
4899 if (io_poll_rewait(req, &req->poll)) {
4900 spin_unlock_irq(&ctx->completion_lock);
4902 hash_del(&req->hash_node);
4903 io_poll_complete(req, req->result, 0);
4904 spin_unlock_irq(&ctx->completion_lock);
4906 nxt = io_put_req_find_next(req);
4907 io_cqring_ev_posted(ctx);
4909 __io_req_task_submit(nxt);
4912 percpu_ref_put(&ctx->refs);
4915 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4916 int sync, void *key)
4918 struct io_kiocb *req = wait->private;
4919 struct io_poll_iocb *poll = io_poll_get_single(req);
4920 __poll_t mask = key_to_poll(key);
4922 /* for instances that support it check for an event match first: */
4923 if (mask && !(mask & poll->events))
4926 list_del_init(&wait->entry);
4928 if (poll && poll->head) {
4931 spin_lock(&poll->head->lock);
4932 done = list_empty(&poll->wait.entry);
4934 list_del_init(&poll->wait.entry);
4935 /* make sure double remove sees this as being gone */
4936 wait->private = NULL;
4937 spin_unlock(&poll->head->lock);
4939 /* use wait func handler, so it matches the rq type */
4940 poll->wait.func(&poll->wait, mode, sync, key);
4943 refcount_dec(&req->refs);
4947 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4948 wait_queue_func_t wake_func)
4952 poll->canceled = false;
4953 poll->events = events;
4954 INIT_LIST_HEAD(&poll->wait.entry);
4955 init_waitqueue_func_entry(&poll->wait, wake_func);
4958 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4959 struct wait_queue_head *head,
4960 struct io_poll_iocb **poll_ptr)
4962 struct io_kiocb *req = pt->req;
4965 * If poll->head is already set, it's because the file being polled
4966 * uses multiple waitqueues for poll handling (eg one for read, one
4967 * for write). Setup a separate io_poll_iocb if this happens.
4969 if (unlikely(poll->head)) {
4970 struct io_poll_iocb *poll_one = poll;
4972 /* already have a 2nd entry, fail a third attempt */
4974 pt->error = -EINVAL;
4977 /* double add on the same waitqueue head, ignore */
4978 if (poll->head == head)
4980 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4982 pt->error = -ENOMEM;
4985 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
4986 refcount_inc(&req->refs);
4987 poll->wait.private = req;
4994 if (poll->events & EPOLLEXCLUSIVE)
4995 add_wait_queue_exclusive(head, &poll->wait);
4997 add_wait_queue(head, &poll->wait);
5000 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5001 struct poll_table_struct *p)
5003 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5004 struct async_poll *apoll = pt->req->apoll;
5006 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5009 static void io_async_task_func(struct callback_head *cb)
5011 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5012 struct async_poll *apoll = req->apoll;
5013 struct io_ring_ctx *ctx = req->ctx;
5015 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5017 if (io_poll_rewait(req, &apoll->poll)) {
5018 spin_unlock_irq(&ctx->completion_lock);
5019 percpu_ref_put(&ctx->refs);
5023 /* If req is still hashed, it cannot have been canceled. Don't check. */
5024 if (hash_hashed(&req->hash_node))
5025 hash_del(&req->hash_node);
5027 io_poll_remove_double(req);
5028 spin_unlock_irq(&ctx->completion_lock);
5030 if (!READ_ONCE(apoll->poll.canceled))
5031 __io_req_task_submit(req);
5033 __io_req_task_cancel(req, -ECANCELED);
5035 percpu_ref_put(&ctx->refs);
5036 kfree(apoll->double_poll);
5040 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5043 struct io_kiocb *req = wait->private;
5044 struct io_poll_iocb *poll = &req->apoll->poll;
5046 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5049 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5052 static void io_poll_req_insert(struct io_kiocb *req)
5054 struct io_ring_ctx *ctx = req->ctx;
5055 struct hlist_head *list;
5057 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5058 hlist_add_head(&req->hash_node, list);
5061 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5062 struct io_poll_iocb *poll,
5063 struct io_poll_table *ipt, __poll_t mask,
5064 wait_queue_func_t wake_func)
5065 __acquires(&ctx->completion_lock)
5067 struct io_ring_ctx *ctx = req->ctx;
5068 bool cancel = false;
5070 INIT_HLIST_NODE(&req->hash_node);
5071 io_init_poll_iocb(poll, mask, wake_func);
5072 poll->file = req->file;
5073 poll->wait.private = req;
5075 ipt->pt._key = mask;
5077 ipt->error = -EINVAL;
5079 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5081 spin_lock_irq(&ctx->completion_lock);
5082 if (likely(poll->head)) {
5083 spin_lock(&poll->head->lock);
5084 if (unlikely(list_empty(&poll->wait.entry))) {
5090 if (mask || ipt->error)
5091 list_del_init(&poll->wait.entry);
5093 WRITE_ONCE(poll->canceled, true);
5094 else if (!poll->done) /* actually waiting for an event */
5095 io_poll_req_insert(req);
5096 spin_unlock(&poll->head->lock);
5102 static bool io_arm_poll_handler(struct io_kiocb *req)
5104 const struct io_op_def *def = &io_op_defs[req->opcode];
5105 struct io_ring_ctx *ctx = req->ctx;
5106 struct async_poll *apoll;
5107 struct io_poll_table ipt;
5111 if (!req->file || !file_can_poll(req->file))
5113 if (req->flags & REQ_F_POLLED)
5117 else if (def->pollout)
5121 /* if we can't nonblock try, then no point in arming a poll handler */
5122 if (!io_file_supports_async(req->file, rw))
5125 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5126 if (unlikely(!apoll))
5128 apoll->double_poll = NULL;
5130 req->flags |= REQ_F_POLLED;
5135 mask |= POLLIN | POLLRDNORM;
5137 mask |= POLLOUT | POLLWRNORM;
5139 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5140 if ((req->opcode == IORING_OP_RECVMSG) &&
5141 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5144 mask |= POLLERR | POLLPRI;
5146 ipt.pt._qproc = io_async_queue_proc;
5148 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5150 if (ret || ipt.error) {
5151 io_poll_remove_double(req);
5152 spin_unlock_irq(&ctx->completion_lock);
5153 kfree(apoll->double_poll);
5157 spin_unlock_irq(&ctx->completion_lock);
5158 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5159 apoll->poll.events);
5163 static bool __io_poll_remove_one(struct io_kiocb *req,
5164 struct io_poll_iocb *poll)
5166 bool do_complete = false;
5168 spin_lock(&poll->head->lock);
5169 WRITE_ONCE(poll->canceled, true);
5170 if (!list_empty(&poll->wait.entry)) {
5171 list_del_init(&poll->wait.entry);
5174 spin_unlock(&poll->head->lock);
5175 hash_del(&req->hash_node);
5179 static bool io_poll_remove_one(struct io_kiocb *req)
5183 io_poll_remove_double(req);
5185 if (req->opcode == IORING_OP_POLL_ADD) {
5186 do_complete = __io_poll_remove_one(req, &req->poll);
5188 struct async_poll *apoll = req->apoll;
5190 /* non-poll requests have submit ref still */
5191 do_complete = __io_poll_remove_one(req, &apoll->poll);
5194 kfree(apoll->double_poll);
5200 io_cqring_fill_event(req, -ECANCELED);
5201 io_commit_cqring(req->ctx);
5202 req_set_fail_links(req);
5203 io_put_req_deferred(req, 1);
5210 * Returns true if we found and killed one or more poll requests
5212 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5213 struct files_struct *files)
5215 struct hlist_node *tmp;
5216 struct io_kiocb *req;
5219 spin_lock_irq(&ctx->completion_lock);
5220 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5221 struct hlist_head *list;
5223 list = &ctx->cancel_hash[i];
5224 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5225 if (io_match_task(req, tsk, files))
5226 posted += io_poll_remove_one(req);
5229 spin_unlock_irq(&ctx->completion_lock);
5232 io_cqring_ev_posted(ctx);
5237 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5239 struct hlist_head *list;
5240 struct io_kiocb *req;
5242 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5243 hlist_for_each_entry(req, list, hash_node) {
5244 if (sqe_addr != req->user_data)
5246 if (io_poll_remove_one(req))
5254 static int io_poll_remove_prep(struct io_kiocb *req,
5255 const struct io_uring_sqe *sqe)
5257 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5259 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5263 req->poll_remove.addr = READ_ONCE(sqe->addr);
5268 * Find a running poll command that matches one specified in sqe->addr,
5269 * and remove it if found.
5271 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5273 struct io_ring_ctx *ctx = req->ctx;
5276 spin_lock_irq(&ctx->completion_lock);
5277 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5278 spin_unlock_irq(&ctx->completion_lock);
5281 req_set_fail_links(req);
5282 io_req_complete(req, ret);
5286 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5289 struct io_kiocb *req = wait->private;
5290 struct io_poll_iocb *poll = &req->poll;
5292 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5295 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5296 struct poll_table_struct *p)
5298 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5300 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5303 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5305 struct io_poll_iocb *poll = &req->poll;
5308 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5310 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5313 events = READ_ONCE(sqe->poll32_events);
5315 events = swahw32(events);
5317 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5318 (events & EPOLLEXCLUSIVE);
5322 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5324 struct io_poll_iocb *poll = &req->poll;
5325 struct io_ring_ctx *ctx = req->ctx;
5326 struct io_poll_table ipt;
5329 ipt.pt._qproc = io_poll_queue_proc;
5331 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5334 if (mask) { /* no async, we'd stolen it */
5336 io_poll_complete(req, mask, 0);
5338 spin_unlock_irq(&ctx->completion_lock);
5341 io_cqring_ev_posted(ctx);
5347 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5349 struct io_timeout_data *data = container_of(timer,
5350 struct io_timeout_data, timer);
5351 struct io_kiocb *req = data->req;
5352 struct io_ring_ctx *ctx = req->ctx;
5353 unsigned long flags;
5355 spin_lock_irqsave(&ctx->completion_lock, flags);
5356 list_del_init(&req->timeout.list);
5357 atomic_set(&req->ctx->cq_timeouts,
5358 atomic_read(&req->ctx->cq_timeouts) + 1);
5360 io_cqring_fill_event(req, -ETIME);
5361 io_commit_cqring(ctx);
5362 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5364 io_cqring_ev_posted(ctx);
5365 req_set_fail_links(req);
5367 return HRTIMER_NORESTART;
5370 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5373 struct io_timeout_data *io;
5374 struct io_kiocb *req;
5377 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5378 if (user_data == req->user_data) {
5385 return ERR_PTR(ret);
5387 io = req->async_data;
5388 ret = hrtimer_try_to_cancel(&io->timer);
5390 return ERR_PTR(-EALREADY);
5391 list_del_init(&req->timeout.list);
5395 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5397 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5400 return PTR_ERR(req);
5402 req_set_fail_links(req);
5403 io_cqring_fill_event(req, -ECANCELED);
5404 io_put_req_deferred(req, 1);
5408 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5409 struct timespec64 *ts, enum hrtimer_mode mode)
5411 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5412 struct io_timeout_data *data;
5415 return PTR_ERR(req);
5417 req->timeout.off = 0; /* noseq */
5418 data = req->async_data;
5419 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5420 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5421 data->timer.function = io_timeout_fn;
5422 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5426 static int io_timeout_remove_prep(struct io_kiocb *req,
5427 const struct io_uring_sqe *sqe)
5429 struct io_timeout_rem *tr = &req->timeout_rem;
5431 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5433 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5435 if (sqe->ioprio || sqe->buf_index || sqe->len)
5438 tr->addr = READ_ONCE(sqe->addr);
5439 tr->flags = READ_ONCE(sqe->timeout_flags);
5440 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5441 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5443 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5445 } else if (tr->flags) {
5446 /* timeout removal doesn't support flags */
5453 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5455 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5460 * Remove or update an existing timeout command
5462 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5464 struct io_timeout_rem *tr = &req->timeout_rem;
5465 struct io_ring_ctx *ctx = req->ctx;
5468 spin_lock_irq(&ctx->completion_lock);
5469 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5470 ret = io_timeout_cancel(ctx, tr->addr);
5472 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5473 io_translate_timeout_mode(tr->flags));
5475 io_cqring_fill_event(req, ret);
5476 io_commit_cqring(ctx);
5477 spin_unlock_irq(&ctx->completion_lock);
5478 io_cqring_ev_posted(ctx);
5480 req_set_fail_links(req);
5485 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5486 bool is_timeout_link)
5488 struct io_timeout_data *data;
5490 u32 off = READ_ONCE(sqe->off);
5492 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5494 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5496 if (off && is_timeout_link)
5498 flags = READ_ONCE(sqe->timeout_flags);
5499 if (flags & ~IORING_TIMEOUT_ABS)
5502 req->timeout.off = off;
5504 if (!req->async_data && io_alloc_async_data(req))
5507 data = req->async_data;
5510 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5513 data->mode = io_translate_timeout_mode(flags);
5514 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5515 io_req_track_inflight(req);
5519 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5521 struct io_ring_ctx *ctx = req->ctx;
5522 struct io_timeout_data *data = req->async_data;
5523 struct list_head *entry;
5524 u32 tail, off = req->timeout.off;
5526 spin_lock_irq(&ctx->completion_lock);
5529 * sqe->off holds how many events that need to occur for this
5530 * timeout event to be satisfied. If it isn't set, then this is
5531 * a pure timeout request, sequence isn't used.
5533 if (io_is_timeout_noseq(req)) {
5534 entry = ctx->timeout_list.prev;
5538 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5539 req->timeout.target_seq = tail + off;
5541 /* Update the last seq here in case io_flush_timeouts() hasn't.
5542 * This is safe because ->completion_lock is held, and submissions
5543 * and completions are never mixed in the same ->completion_lock section.
5545 ctx->cq_last_tm_flush = tail;
5548 * Insertion sort, ensuring the first entry in the list is always
5549 * the one we need first.
5551 list_for_each_prev(entry, &ctx->timeout_list) {
5552 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5555 if (io_is_timeout_noseq(nxt))
5557 /* nxt.seq is behind @tail, otherwise would've been completed */
5558 if (off >= nxt->timeout.target_seq - tail)
5562 list_add(&req->timeout.list, entry);
5563 data->timer.function = io_timeout_fn;
5564 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5565 spin_unlock_irq(&ctx->completion_lock);
5569 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5571 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5573 return req->user_data == (unsigned long) data;
5576 static int io_async_cancel_one(struct io_uring_task *tctx, void *sqe_addr)
5578 enum io_wq_cancel cancel_ret;
5584 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, sqe_addr, false);
5585 switch (cancel_ret) {
5586 case IO_WQ_CANCEL_OK:
5589 case IO_WQ_CANCEL_RUNNING:
5592 case IO_WQ_CANCEL_NOTFOUND:
5600 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5601 struct io_kiocb *req, __u64 sqe_addr,
5604 unsigned long flags;
5607 ret = io_async_cancel_one(req->task->io_uring,
5608 (void *) (unsigned long) sqe_addr);
5609 if (ret != -ENOENT) {
5610 spin_lock_irqsave(&ctx->completion_lock, flags);
5614 spin_lock_irqsave(&ctx->completion_lock, flags);
5615 ret = io_timeout_cancel(ctx, sqe_addr);
5618 ret = io_poll_cancel(ctx, sqe_addr);
5622 io_cqring_fill_event(req, ret);
5623 io_commit_cqring(ctx);
5624 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5625 io_cqring_ev_posted(ctx);
5628 req_set_fail_links(req);
5632 static int io_async_cancel_prep(struct io_kiocb *req,
5633 const struct io_uring_sqe *sqe)
5635 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5637 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5639 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5642 req->cancel.addr = READ_ONCE(sqe->addr);
5646 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5648 struct io_ring_ctx *ctx = req->ctx;
5650 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5654 static int io_rsrc_update_prep(struct io_kiocb *req,
5655 const struct io_uring_sqe *sqe)
5657 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5659 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5661 if (sqe->ioprio || sqe->rw_flags)
5664 req->rsrc_update.offset = READ_ONCE(sqe->off);
5665 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5666 if (!req->rsrc_update.nr_args)
5668 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5672 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5674 struct io_ring_ctx *ctx = req->ctx;
5675 struct io_uring_rsrc_update up;
5678 if (issue_flags & IO_URING_F_NONBLOCK)
5681 up.offset = req->rsrc_update.offset;
5682 up.data = req->rsrc_update.arg;
5684 mutex_lock(&ctx->uring_lock);
5685 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5686 mutex_unlock(&ctx->uring_lock);
5689 req_set_fail_links(req);
5690 __io_req_complete(req, issue_flags, ret, 0);
5694 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5696 switch (req->opcode) {
5699 case IORING_OP_READV:
5700 case IORING_OP_READ_FIXED:
5701 case IORING_OP_READ:
5702 return io_read_prep(req, sqe);
5703 case IORING_OP_WRITEV:
5704 case IORING_OP_WRITE_FIXED:
5705 case IORING_OP_WRITE:
5706 return io_write_prep(req, sqe);
5707 case IORING_OP_POLL_ADD:
5708 return io_poll_add_prep(req, sqe);
5709 case IORING_OP_POLL_REMOVE:
5710 return io_poll_remove_prep(req, sqe);
5711 case IORING_OP_FSYNC:
5712 return io_fsync_prep(req, sqe);
5713 case IORING_OP_SYNC_FILE_RANGE:
5714 return io_sfr_prep(req, sqe);
5715 case IORING_OP_SENDMSG:
5716 case IORING_OP_SEND:
5717 return io_sendmsg_prep(req, sqe);
5718 case IORING_OP_RECVMSG:
5719 case IORING_OP_RECV:
5720 return io_recvmsg_prep(req, sqe);
5721 case IORING_OP_CONNECT:
5722 return io_connect_prep(req, sqe);
5723 case IORING_OP_TIMEOUT:
5724 return io_timeout_prep(req, sqe, false);
5725 case IORING_OP_TIMEOUT_REMOVE:
5726 return io_timeout_remove_prep(req, sqe);
5727 case IORING_OP_ASYNC_CANCEL:
5728 return io_async_cancel_prep(req, sqe);
5729 case IORING_OP_LINK_TIMEOUT:
5730 return io_timeout_prep(req, sqe, true);
5731 case IORING_OP_ACCEPT:
5732 return io_accept_prep(req, sqe);
5733 case IORING_OP_FALLOCATE:
5734 return io_fallocate_prep(req, sqe);
5735 case IORING_OP_OPENAT:
5736 return io_openat_prep(req, sqe);
5737 case IORING_OP_CLOSE:
5738 return io_close_prep(req, sqe);
5739 case IORING_OP_FILES_UPDATE:
5740 return io_rsrc_update_prep(req, sqe);
5741 case IORING_OP_STATX:
5742 return io_statx_prep(req, sqe);
5743 case IORING_OP_FADVISE:
5744 return io_fadvise_prep(req, sqe);
5745 case IORING_OP_MADVISE:
5746 return io_madvise_prep(req, sqe);
5747 case IORING_OP_OPENAT2:
5748 return io_openat2_prep(req, sqe);
5749 case IORING_OP_EPOLL_CTL:
5750 return io_epoll_ctl_prep(req, sqe);
5751 case IORING_OP_SPLICE:
5752 return io_splice_prep(req, sqe);
5753 case IORING_OP_PROVIDE_BUFFERS:
5754 return io_provide_buffers_prep(req, sqe);
5755 case IORING_OP_REMOVE_BUFFERS:
5756 return io_remove_buffers_prep(req, sqe);
5758 return io_tee_prep(req, sqe);
5759 case IORING_OP_SHUTDOWN:
5760 return io_shutdown_prep(req, sqe);
5761 case IORING_OP_RENAMEAT:
5762 return io_renameat_prep(req, sqe);
5763 case IORING_OP_UNLINKAT:
5764 return io_unlinkat_prep(req, sqe);
5767 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5772 static int io_req_prep_async(struct io_kiocb *req)
5774 switch (req->opcode) {
5775 case IORING_OP_READV:
5776 case IORING_OP_READ_FIXED:
5777 case IORING_OP_READ:
5778 return io_rw_prep_async(req, READ);
5779 case IORING_OP_WRITEV:
5780 case IORING_OP_WRITE_FIXED:
5781 case IORING_OP_WRITE:
5782 return io_rw_prep_async(req, WRITE);
5783 case IORING_OP_SENDMSG:
5784 case IORING_OP_SEND:
5785 return io_sendmsg_prep_async(req);
5786 case IORING_OP_RECVMSG:
5787 case IORING_OP_RECV:
5788 return io_recvmsg_prep_async(req);
5789 case IORING_OP_CONNECT:
5790 return io_connect_prep_async(req);
5795 static int io_req_defer_prep(struct io_kiocb *req)
5797 if (!io_op_defs[req->opcode].needs_async_data)
5799 /* some opcodes init it during the inital prep */
5800 if (req->async_data)
5802 if (__io_alloc_async_data(req))
5804 return io_req_prep_async(req);
5807 static u32 io_get_sequence(struct io_kiocb *req)
5809 struct io_kiocb *pos;
5810 struct io_ring_ctx *ctx = req->ctx;
5811 u32 total_submitted, nr_reqs = 0;
5813 io_for_each_link(pos, req)
5816 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5817 return total_submitted - nr_reqs;
5820 static int io_req_defer(struct io_kiocb *req)
5822 struct io_ring_ctx *ctx = req->ctx;
5823 struct io_defer_entry *de;
5827 /* Still need defer if there is pending req in defer list. */
5828 if (likely(list_empty_careful(&ctx->defer_list) &&
5829 !(req->flags & REQ_F_IO_DRAIN)))
5832 seq = io_get_sequence(req);
5833 /* Still a chance to pass the sequence check */
5834 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5837 ret = io_req_defer_prep(req);
5840 io_prep_async_link(req);
5841 de = kmalloc(sizeof(*de), GFP_KERNEL);
5845 spin_lock_irq(&ctx->completion_lock);
5846 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5847 spin_unlock_irq(&ctx->completion_lock);
5849 io_queue_async_work(req);
5850 return -EIOCBQUEUED;
5853 trace_io_uring_defer(ctx, req, req->user_data);
5856 list_add_tail(&de->list, &ctx->defer_list);
5857 spin_unlock_irq(&ctx->completion_lock);
5858 return -EIOCBQUEUED;
5861 static void __io_clean_op(struct io_kiocb *req)
5863 if (req->flags & REQ_F_BUFFER_SELECTED) {
5864 switch (req->opcode) {
5865 case IORING_OP_READV:
5866 case IORING_OP_READ_FIXED:
5867 case IORING_OP_READ:
5868 kfree((void *)(unsigned long)req->rw.addr);
5870 case IORING_OP_RECVMSG:
5871 case IORING_OP_RECV:
5872 kfree(req->sr_msg.kbuf);
5875 req->flags &= ~REQ_F_BUFFER_SELECTED;
5878 if (req->flags & REQ_F_NEED_CLEANUP) {
5879 switch (req->opcode) {
5880 case IORING_OP_READV:
5881 case IORING_OP_READ_FIXED:
5882 case IORING_OP_READ:
5883 case IORING_OP_WRITEV:
5884 case IORING_OP_WRITE_FIXED:
5885 case IORING_OP_WRITE: {
5886 struct io_async_rw *io = req->async_data;
5888 kfree(io->free_iovec);
5891 case IORING_OP_RECVMSG:
5892 case IORING_OP_SENDMSG: {
5893 struct io_async_msghdr *io = req->async_data;
5895 kfree(io->free_iov);
5898 case IORING_OP_SPLICE:
5900 io_put_file(req, req->splice.file_in,
5901 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5903 case IORING_OP_OPENAT:
5904 case IORING_OP_OPENAT2:
5905 if (req->open.filename)
5906 putname(req->open.filename);
5908 case IORING_OP_RENAMEAT:
5909 putname(req->rename.oldpath);
5910 putname(req->rename.newpath);
5912 case IORING_OP_UNLINKAT:
5913 putname(req->unlink.filename);
5916 req->flags &= ~REQ_F_NEED_CLEANUP;
5920 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
5922 struct io_ring_ctx *ctx = req->ctx;
5923 const struct cred *creds = NULL;
5926 if (req->work.creds && req->work.creds != current_cred())
5927 creds = override_creds(req->work.creds);
5929 switch (req->opcode) {
5931 ret = io_nop(req, issue_flags);
5933 case IORING_OP_READV:
5934 case IORING_OP_READ_FIXED:
5935 case IORING_OP_READ:
5936 ret = io_read(req, issue_flags);
5938 case IORING_OP_WRITEV:
5939 case IORING_OP_WRITE_FIXED:
5940 case IORING_OP_WRITE:
5941 ret = io_write(req, issue_flags);
5943 case IORING_OP_FSYNC:
5944 ret = io_fsync(req, issue_flags);
5946 case IORING_OP_POLL_ADD:
5947 ret = io_poll_add(req, issue_flags);
5949 case IORING_OP_POLL_REMOVE:
5950 ret = io_poll_remove(req, issue_flags);
5952 case IORING_OP_SYNC_FILE_RANGE:
5953 ret = io_sync_file_range(req, issue_flags);
5955 case IORING_OP_SENDMSG:
5956 ret = io_sendmsg(req, issue_flags);
5958 case IORING_OP_SEND:
5959 ret = io_send(req, issue_flags);
5961 case IORING_OP_RECVMSG:
5962 ret = io_recvmsg(req, issue_flags);
5964 case IORING_OP_RECV:
5965 ret = io_recv(req, issue_flags);
5967 case IORING_OP_TIMEOUT:
5968 ret = io_timeout(req, issue_flags);
5970 case IORING_OP_TIMEOUT_REMOVE:
5971 ret = io_timeout_remove(req, issue_flags);
5973 case IORING_OP_ACCEPT:
5974 ret = io_accept(req, issue_flags);
5976 case IORING_OP_CONNECT:
5977 ret = io_connect(req, issue_flags);
5979 case IORING_OP_ASYNC_CANCEL:
5980 ret = io_async_cancel(req, issue_flags);
5982 case IORING_OP_FALLOCATE:
5983 ret = io_fallocate(req, issue_flags);
5985 case IORING_OP_OPENAT:
5986 ret = io_openat(req, issue_flags);
5988 case IORING_OP_CLOSE:
5989 ret = io_close(req, issue_flags);
5991 case IORING_OP_FILES_UPDATE:
5992 ret = io_files_update(req, issue_flags);
5994 case IORING_OP_STATX:
5995 ret = io_statx(req, issue_flags);
5997 case IORING_OP_FADVISE:
5998 ret = io_fadvise(req, issue_flags);
6000 case IORING_OP_MADVISE:
6001 ret = io_madvise(req, issue_flags);
6003 case IORING_OP_OPENAT2:
6004 ret = io_openat2(req, issue_flags);
6006 case IORING_OP_EPOLL_CTL:
6007 ret = io_epoll_ctl(req, issue_flags);
6009 case IORING_OP_SPLICE:
6010 ret = io_splice(req, issue_flags);
6012 case IORING_OP_PROVIDE_BUFFERS:
6013 ret = io_provide_buffers(req, issue_flags);
6015 case IORING_OP_REMOVE_BUFFERS:
6016 ret = io_remove_buffers(req, issue_flags);
6019 ret = io_tee(req, issue_flags);
6021 case IORING_OP_SHUTDOWN:
6022 ret = io_shutdown(req, issue_flags);
6024 case IORING_OP_RENAMEAT:
6025 ret = io_renameat(req, issue_flags);
6027 case IORING_OP_UNLINKAT:
6028 ret = io_unlinkat(req, issue_flags);
6036 revert_creds(creds);
6041 /* If the op doesn't have a file, we're not polling for it */
6042 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6043 const bool in_async = io_wq_current_is_worker();
6045 /* workqueue context doesn't hold uring_lock, grab it now */
6047 mutex_lock(&ctx->uring_lock);
6049 io_iopoll_req_issued(req, in_async);
6052 mutex_unlock(&ctx->uring_lock);
6058 static void io_wq_submit_work(struct io_wq_work *work)
6060 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6061 struct io_kiocb *timeout;
6064 timeout = io_prep_linked_timeout(req);
6066 io_queue_linked_timeout(timeout);
6068 if (work->flags & IO_WQ_WORK_CANCEL)
6073 ret = io_issue_sqe(req, 0);
6075 * We can get EAGAIN for polled IO even though we're
6076 * forcing a sync submission from here, since we can't
6077 * wait for request slots on the block side.
6085 /* avoid locking problems by failing it from a clean context */
6087 /* io-wq is going to take one down */
6088 refcount_inc(&req->refs);
6089 io_req_task_queue_fail(req, ret);
6093 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6096 struct fixed_rsrc_table *table;
6098 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6099 return table->files[index & IORING_FILE_TABLE_MASK];
6102 static struct file *io_file_get(struct io_submit_state *state,
6103 struct io_kiocb *req, int fd, bool fixed)
6105 struct io_ring_ctx *ctx = req->ctx;
6109 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6111 fd = array_index_nospec(fd, ctx->nr_user_files);
6112 file = io_file_from_index(ctx, fd);
6113 io_set_resource_node(req);
6115 trace_io_uring_file_get(ctx, fd);
6116 file = __io_file_get(state, fd);
6119 if (file && unlikely(file->f_op == &io_uring_fops))
6120 io_req_track_inflight(req);
6124 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6126 struct io_timeout_data *data = container_of(timer,
6127 struct io_timeout_data, timer);
6128 struct io_kiocb *prev, *req = data->req;
6129 struct io_ring_ctx *ctx = req->ctx;
6130 unsigned long flags;
6132 spin_lock_irqsave(&ctx->completion_lock, flags);
6133 prev = req->timeout.head;
6134 req->timeout.head = NULL;
6137 * We don't expect the list to be empty, that will only happen if we
6138 * race with the completion of the linked work.
6140 if (prev && refcount_inc_not_zero(&prev->refs))
6141 io_remove_next_linked(prev);
6144 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6147 req_set_fail_links(prev);
6148 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6149 io_put_req_deferred(prev, 1);
6151 io_req_complete_post(req, -ETIME, 0);
6152 io_put_req_deferred(req, 1);
6154 return HRTIMER_NORESTART;
6157 static void __io_queue_linked_timeout(struct io_kiocb *req)
6160 * If the back reference is NULL, then our linked request finished
6161 * before we got a chance to setup the timer
6163 if (req->timeout.head) {
6164 struct io_timeout_data *data = req->async_data;
6166 data->timer.function = io_link_timeout_fn;
6167 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6172 static void io_queue_linked_timeout(struct io_kiocb *req)
6174 struct io_ring_ctx *ctx = req->ctx;
6176 spin_lock_irq(&ctx->completion_lock);
6177 __io_queue_linked_timeout(req);
6178 spin_unlock_irq(&ctx->completion_lock);
6180 /* drop submission reference */
6184 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6186 struct io_kiocb *nxt = req->link;
6188 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6189 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6192 nxt->timeout.head = req;
6193 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6194 req->flags |= REQ_F_LINK_TIMEOUT;
6198 static void __io_queue_sqe(struct io_kiocb *req)
6200 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6203 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6206 * We async punt it if the file wasn't marked NOWAIT, or if the file
6207 * doesn't support non-blocking read/write attempts
6209 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6210 if (!io_arm_poll_handler(req)) {
6212 * Queued up for async execution, worker will release
6213 * submit reference when the iocb is actually submitted.
6215 io_queue_async_work(req);
6217 } else if (likely(!ret)) {
6218 /* drop submission reference */
6219 if (req->flags & REQ_F_COMPLETE_INLINE) {
6220 struct io_ring_ctx *ctx = req->ctx;
6221 struct io_comp_state *cs = &ctx->submit_state.comp;
6223 cs->reqs[cs->nr++] = req;
6224 if (cs->nr == ARRAY_SIZE(cs->reqs))
6225 io_submit_flush_completions(cs, ctx);
6230 req_set_fail_links(req);
6232 io_req_complete(req, ret);
6235 io_queue_linked_timeout(linked_timeout);
6238 static void io_queue_sqe(struct io_kiocb *req)
6242 ret = io_req_defer(req);
6244 if (ret != -EIOCBQUEUED) {
6246 req_set_fail_links(req);
6248 io_req_complete(req, ret);
6250 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6251 ret = io_req_defer_prep(req);
6254 io_queue_async_work(req);
6256 __io_queue_sqe(req);
6261 * Check SQE restrictions (opcode and flags).
6263 * Returns 'true' if SQE is allowed, 'false' otherwise.
6265 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6266 struct io_kiocb *req,
6267 unsigned int sqe_flags)
6269 if (!ctx->restricted)
6272 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6275 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6276 ctx->restrictions.sqe_flags_required)
6279 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6280 ctx->restrictions.sqe_flags_required))
6286 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6287 const struct io_uring_sqe *sqe)
6289 struct io_submit_state *state;
6290 unsigned int sqe_flags;
6291 int personality, ret = 0;
6293 req->opcode = READ_ONCE(sqe->opcode);
6294 /* same numerical values with corresponding REQ_F_*, safe to copy */
6295 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6296 req->user_data = READ_ONCE(sqe->user_data);
6297 req->async_data = NULL;
6301 req->fixed_rsrc_refs = NULL;
6302 /* one is dropped after submission, the other at completion */
6303 refcount_set(&req->refs, 2);
6304 req->task = current;
6307 /* enforce forwards compatibility on users */
6308 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6313 if (unlikely(req->opcode >= IORING_OP_LAST))
6316 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6319 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6320 !io_op_defs[req->opcode].buffer_select)
6323 req->work.list.next = NULL;
6324 personality = READ_ONCE(sqe->personality);
6326 req->work.creds = idr_find(&ctx->personality_idr, personality);
6327 if (!req->work.creds)
6329 get_cred(req->work.creds);
6331 req->work.creds = NULL;
6333 req->work.flags = 0;
6334 state = &ctx->submit_state;
6337 * Plug now if we have more than 1 IO left after this, and the target
6338 * is potentially a read/write to block based storage.
6340 if (!state->plug_started && state->ios_left > 1 &&
6341 io_op_defs[req->opcode].plug) {
6342 blk_start_plug(&state->plug);
6343 state->plug_started = true;
6346 if (io_op_defs[req->opcode].needs_file) {
6347 bool fixed = req->flags & REQ_F_FIXED_FILE;
6349 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6350 if (unlikely(!req->file))
6358 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6359 const struct io_uring_sqe *sqe)
6361 struct io_submit_link *link = &ctx->submit_state.link;
6364 ret = io_init_req(ctx, req, sqe);
6365 if (unlikely(ret)) {
6368 io_req_complete(req, ret);
6370 /* fail even hard links since we don't submit */
6371 link->head->flags |= REQ_F_FAIL_LINK;
6372 io_put_req(link->head);
6373 io_req_complete(link->head, -ECANCELED);
6378 ret = io_req_prep(req, sqe);
6382 /* don't need @sqe from now on */
6383 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6384 true, ctx->flags & IORING_SETUP_SQPOLL);
6387 * If we already have a head request, queue this one for async
6388 * submittal once the head completes. If we don't have a head but
6389 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6390 * submitted sync once the chain is complete. If none of those
6391 * conditions are true (normal request), then just queue it.
6394 struct io_kiocb *head = link->head;
6397 * Taking sequential execution of a link, draining both sides
6398 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6399 * requests in the link. So, it drains the head and the
6400 * next after the link request. The last one is done via
6401 * drain_next flag to persist the effect across calls.
6403 if (req->flags & REQ_F_IO_DRAIN) {
6404 head->flags |= REQ_F_IO_DRAIN;
6405 ctx->drain_next = 1;
6407 ret = io_req_defer_prep(req);
6410 trace_io_uring_link(ctx, req, head);
6411 link->last->link = req;
6414 /* last request of a link, enqueue the link */
6415 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6420 if (unlikely(ctx->drain_next)) {
6421 req->flags |= REQ_F_IO_DRAIN;
6422 ctx->drain_next = 0;
6424 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6436 * Batched submission is done, ensure local IO is flushed out.
6438 static void io_submit_state_end(struct io_submit_state *state,
6439 struct io_ring_ctx *ctx)
6441 if (state->link.head)
6442 io_queue_sqe(state->link.head);
6444 io_submit_flush_completions(&state->comp, ctx);
6445 if (state->plug_started)
6446 blk_finish_plug(&state->plug);
6447 io_state_file_put(state);
6451 * Start submission side cache.
6453 static void io_submit_state_start(struct io_submit_state *state,
6454 unsigned int max_ios)
6456 state->plug_started = false;
6457 state->ios_left = max_ios;
6458 /* set only head, no need to init link_last in advance */
6459 state->link.head = NULL;
6462 static void io_commit_sqring(struct io_ring_ctx *ctx)
6464 struct io_rings *rings = ctx->rings;
6467 * Ensure any loads from the SQEs are done at this point,
6468 * since once we write the new head, the application could
6469 * write new data to them.
6471 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6475 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6476 * that is mapped by userspace. This means that care needs to be taken to
6477 * ensure that reads are stable, as we cannot rely on userspace always
6478 * being a good citizen. If members of the sqe are validated and then later
6479 * used, it's important that those reads are done through READ_ONCE() to
6480 * prevent a re-load down the line.
6482 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6484 u32 *sq_array = ctx->sq_array;
6488 * The cached sq head (or cq tail) serves two purposes:
6490 * 1) allows us to batch the cost of updating the user visible
6492 * 2) allows the kernel side to track the head on its own, even
6493 * though the application is the one updating it.
6495 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6496 if (likely(head < ctx->sq_entries))
6497 return &ctx->sq_sqes[head];
6499 /* drop invalid entries */
6500 ctx->cached_sq_dropped++;
6501 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6505 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6509 /* if we have a backlog and couldn't flush it all, return BUSY */
6510 if (test_bit(0, &ctx->sq_check_overflow)) {
6511 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6515 /* make sure SQ entry isn't read before tail */
6516 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6518 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6521 percpu_counter_add(¤t->io_uring->inflight, nr);
6522 refcount_add(nr, ¤t->usage);
6523 io_submit_state_start(&ctx->submit_state, nr);
6525 while (submitted < nr) {
6526 const struct io_uring_sqe *sqe;
6527 struct io_kiocb *req;
6529 req = io_alloc_req(ctx);
6530 if (unlikely(!req)) {
6532 submitted = -EAGAIN;
6535 sqe = io_get_sqe(ctx);
6536 if (unlikely(!sqe)) {
6537 kmem_cache_free(req_cachep, req);
6540 /* will complete beyond this point, count as submitted */
6542 if (io_submit_sqe(ctx, req, sqe))
6546 if (unlikely(submitted != nr)) {
6547 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6548 struct io_uring_task *tctx = current->io_uring;
6549 int unused = nr - ref_used;
6551 percpu_ref_put_many(&ctx->refs, unused);
6552 percpu_counter_sub(&tctx->inflight, unused);
6553 put_task_struct_many(current, unused);
6556 io_submit_state_end(&ctx->submit_state, ctx);
6557 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6558 io_commit_sqring(ctx);
6563 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6565 /* Tell userspace we may need a wakeup call */
6566 spin_lock_irq(&ctx->completion_lock);
6567 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6568 spin_unlock_irq(&ctx->completion_lock);
6571 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6573 spin_lock_irq(&ctx->completion_lock);
6574 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6575 spin_unlock_irq(&ctx->completion_lock);
6578 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6580 unsigned int to_submit;
6583 to_submit = io_sqring_entries(ctx);
6584 /* if we're handling multiple rings, cap submit size for fairness */
6585 if (cap_entries && to_submit > 8)
6588 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6589 unsigned nr_events = 0;
6591 mutex_lock(&ctx->uring_lock);
6592 if (!list_empty(&ctx->iopoll_list))
6593 io_do_iopoll(ctx, &nr_events, 0);
6595 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)))
6596 ret = io_submit_sqes(ctx, to_submit);
6597 mutex_unlock(&ctx->uring_lock);
6600 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6601 wake_up(&ctx->sqo_sq_wait);
6606 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6608 struct io_ring_ctx *ctx;
6609 unsigned sq_thread_idle = 0;
6611 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6612 if (sq_thread_idle < ctx->sq_thread_idle)
6613 sq_thread_idle = ctx->sq_thread_idle;
6616 sqd->sq_thread_idle = sq_thread_idle;
6619 static void io_sqd_init_new(struct io_sq_data *sqd)
6621 struct io_ring_ctx *ctx;
6623 while (!list_empty(&sqd->ctx_new_list)) {
6624 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6625 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6626 complete(&ctx->sq_thread_comp);
6629 io_sqd_update_thread_idle(sqd);
6632 static bool io_sq_thread_should_stop(struct io_sq_data *sqd)
6634 return test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6637 static bool io_sq_thread_should_park(struct io_sq_data *sqd)
6639 return test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
6642 static void io_sq_thread_parkme(struct io_sq_data *sqd)
6646 * TASK_PARKED is a special state; we must serialize against
6647 * possible pending wakeups to avoid store-store collisions on
6650 * Such a collision might possibly result in the task state
6651 * changin from TASK_PARKED and us failing the
6652 * wait_task_inactive() in kthread_park().
6654 set_special_state(TASK_PARKED);
6655 if (!test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state))
6659 * Thread is going to call schedule(), do not preempt it,
6660 * or the caller of kthread_park() may spend more time in
6661 * wait_task_inactive().
6664 complete(&sqd->parked);
6665 schedule_preempt_disabled();
6668 __set_current_state(TASK_RUNNING);
6671 static int io_sq_thread(void *data)
6673 struct io_sq_data *sqd = data;
6674 struct io_ring_ctx *ctx;
6675 unsigned long timeout = 0;
6676 char buf[TASK_COMM_LEN];
6679 sprintf(buf, "iou-sqp-%d", sqd->task_pid);
6680 set_task_comm(current, buf);
6681 current->pf_io_worker = NULL;
6683 if (sqd->sq_cpu != -1)
6684 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6686 set_cpus_allowed_ptr(current, cpu_online_mask);
6687 current->flags |= PF_NO_SETAFFINITY;
6689 wait_for_completion(&sqd->startup);
6691 while (!io_sq_thread_should_stop(sqd)) {
6693 bool cap_entries, sqt_spin, needs_sched;
6696 * Any changes to the sqd lists are synchronized through the
6697 * thread parking. This synchronizes the thread vs users,
6698 * the users are synchronized on the sqd->ctx_lock.
6700 if (io_sq_thread_should_park(sqd)) {
6701 io_sq_thread_parkme(sqd);
6704 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
6705 io_sqd_init_new(sqd);
6706 timeout = jiffies + sqd->sq_thread_idle;
6708 if (fatal_signal_pending(current))
6711 cap_entries = !list_is_singular(&sqd->ctx_list);
6712 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6713 ret = __io_sq_thread(ctx, cap_entries);
6714 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6718 if (sqt_spin || !time_after(jiffies, timeout)) {
6722 timeout = jiffies + sqd->sq_thread_idle;
6727 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6728 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6729 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6730 !list_empty_careful(&ctx->iopoll_list)) {
6731 needs_sched = false;
6734 if (io_sqring_entries(ctx)) {
6735 needs_sched = false;
6740 if (needs_sched && !io_sq_thread_should_park(sqd)) {
6741 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6742 io_ring_set_wakeup_flag(ctx);
6746 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6747 io_ring_clear_wakeup_flag(ctx);
6750 finish_wait(&sqd->wait, &wait);
6751 timeout = jiffies + sqd->sq_thread_idle;
6754 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6755 io_uring_cancel_sqpoll(ctx);
6760 * Ensure that we park properly if racing with someone trying to park
6761 * while we're exiting. If we fail to grab the lock, check park and
6762 * park if necessary. The ordering with the park bit and the lock
6763 * ensures that we catch this reliably.
6765 if (!mutex_trylock(&sqd->lock)) {
6766 if (io_sq_thread_should_park(sqd))
6767 io_sq_thread_parkme(sqd);
6768 mutex_lock(&sqd->lock);
6772 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6774 io_ring_set_wakeup_flag(ctx);
6777 complete(&sqd->exited);
6778 mutex_unlock(&sqd->lock);
6782 struct io_wait_queue {
6783 struct wait_queue_entry wq;
6784 struct io_ring_ctx *ctx;
6786 unsigned nr_timeouts;
6789 static inline bool io_should_wake(struct io_wait_queue *iowq)
6791 struct io_ring_ctx *ctx = iowq->ctx;
6794 * Wake up if we have enough events, or if a timeout occurred since we
6795 * started waiting. For timeouts, we always want to return to userspace,
6796 * regardless of event count.
6798 return io_cqring_events(ctx) >= iowq->to_wait ||
6799 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6802 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6803 int wake_flags, void *key)
6805 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6809 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6810 * the task, and the next invocation will do it.
6812 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6813 return autoremove_wake_function(curr, mode, wake_flags, key);
6817 static int io_run_task_work_sig(void)
6819 if (io_run_task_work())
6821 if (!signal_pending(current))
6823 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
6824 return -ERESTARTSYS;
6828 /* when returns >0, the caller should retry */
6829 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6830 struct io_wait_queue *iowq,
6831 signed long *timeout)
6835 /* make sure we run task_work before checking for signals */
6836 ret = io_run_task_work_sig();
6837 if (ret || io_should_wake(iowq))
6839 /* let the caller flush overflows, retry */
6840 if (test_bit(0, &ctx->cq_check_overflow))
6843 *timeout = schedule_timeout(*timeout);
6844 return !*timeout ? -ETIME : 1;
6848 * Wait until events become available, if we don't already have some. The
6849 * application must reap them itself, as they reside on the shared cq ring.
6851 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6852 const sigset_t __user *sig, size_t sigsz,
6853 struct __kernel_timespec __user *uts)
6855 struct io_wait_queue iowq = {
6858 .func = io_wake_function,
6859 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6862 .to_wait = min_events,
6864 struct io_rings *rings = ctx->rings;
6865 signed long timeout = MAX_SCHEDULE_TIMEOUT;
6869 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6870 if (io_cqring_events(ctx) >= min_events)
6872 if (!io_run_task_work())
6877 #ifdef CONFIG_COMPAT
6878 if (in_compat_syscall())
6879 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6883 ret = set_user_sigmask(sig, sigsz);
6890 struct timespec64 ts;
6892 if (get_timespec64(&ts, uts))
6894 timeout = timespec64_to_jiffies(&ts);
6897 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6898 trace_io_uring_cqring_wait(ctx, min_events);
6900 /* if we can't even flush overflow, don't wait for more */
6901 if (!io_cqring_overflow_flush(ctx, false, NULL, NULL)) {
6905 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6906 TASK_INTERRUPTIBLE);
6907 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
6908 finish_wait(&ctx->wait, &iowq.wq);
6912 restore_saved_sigmask_unless(ret == -EINTR);
6914 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6917 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6919 #if defined(CONFIG_UNIX)
6920 if (ctx->ring_sock) {
6921 struct sock *sock = ctx->ring_sock->sk;
6922 struct sk_buff *skb;
6924 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6930 for (i = 0; i < ctx->nr_user_files; i++) {
6933 file = io_file_from_index(ctx, i);
6940 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
6942 struct fixed_rsrc_data *data;
6944 data = container_of(ref, struct fixed_rsrc_data, refs);
6945 complete(&data->done);
6948 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
6950 spin_lock_bh(&ctx->rsrc_ref_lock);
6953 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
6955 spin_unlock_bh(&ctx->rsrc_ref_lock);
6958 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
6959 struct fixed_rsrc_data *rsrc_data,
6960 struct fixed_rsrc_ref_node *ref_node)
6962 io_rsrc_ref_lock(ctx);
6963 rsrc_data->node = ref_node;
6964 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
6965 io_rsrc_ref_unlock(ctx);
6966 percpu_ref_get(&rsrc_data->refs);
6969 static void io_sqe_rsrc_kill_node(struct io_ring_ctx *ctx, struct fixed_rsrc_data *data)
6971 struct fixed_rsrc_ref_node *ref_node = NULL;
6973 io_rsrc_ref_lock(ctx);
6974 ref_node = data->node;
6976 io_rsrc_ref_unlock(ctx);
6978 percpu_ref_kill(&ref_node->refs);
6981 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
6982 struct io_ring_ctx *ctx,
6983 void (*rsrc_put)(struct io_ring_ctx *ctx,
6984 struct io_rsrc_put *prsrc))
6986 struct fixed_rsrc_ref_node *backup_node;
6992 data->quiesce = true;
6995 backup_node = alloc_fixed_rsrc_ref_node(ctx);
6998 backup_node->rsrc_data = data;
6999 backup_node->rsrc_put = rsrc_put;
7001 io_sqe_rsrc_kill_node(ctx, data);
7002 percpu_ref_kill(&data->refs);
7003 flush_delayed_work(&ctx->rsrc_put_work);
7005 ret = wait_for_completion_interruptible(&data->done);
7009 percpu_ref_resurrect(&data->refs);
7010 io_sqe_rsrc_set_node(ctx, data, backup_node);
7012 reinit_completion(&data->done);
7013 mutex_unlock(&ctx->uring_lock);
7014 ret = io_run_task_work_sig();
7015 mutex_lock(&ctx->uring_lock);
7017 data->quiesce = false;
7020 destroy_fixed_rsrc_ref_node(backup_node);
7024 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7026 struct fixed_rsrc_data *data;
7028 data = kzalloc(sizeof(*data), GFP_KERNEL);
7032 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7033 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7038 init_completion(&data->done);
7042 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7044 percpu_ref_exit(&data->refs);
7049 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7051 struct fixed_rsrc_data *data = ctx->file_data;
7052 unsigned nr_tables, i;
7056 * percpu_ref_is_dying() is to stop parallel files unregister
7057 * Since we possibly drop uring lock later in this function to
7060 if (!data || percpu_ref_is_dying(&data->refs))
7062 ret = io_rsrc_ref_quiesce(data, ctx, io_ring_file_put);
7066 __io_sqe_files_unregister(ctx);
7067 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7068 for (i = 0; i < nr_tables; i++)
7069 kfree(data->table[i].files);
7070 free_fixed_rsrc_data(data);
7071 ctx->file_data = NULL;
7072 ctx->nr_user_files = 0;
7076 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7077 __releases(&sqd->lock)
7079 if (sqd->thread == current)
7081 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7083 wake_up_state(sqd->thread, TASK_PARKED);
7084 mutex_unlock(&sqd->lock);
7087 static void io_sq_thread_park(struct io_sq_data *sqd)
7088 __acquires(&sqd->lock)
7090 if (sqd->thread == current)
7092 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7093 mutex_lock(&sqd->lock);
7095 wake_up_process(sqd->thread);
7096 wait_for_completion(&sqd->parked);
7100 static void io_sq_thread_stop(struct io_sq_data *sqd)
7102 if (test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state))
7104 mutex_lock(&sqd->lock);
7106 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7107 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state));
7108 wake_up_process(sqd->thread);
7109 mutex_unlock(&sqd->lock);
7110 wait_for_completion(&sqd->exited);
7111 WARN_ON_ONCE(sqd->thread);
7113 mutex_unlock(&sqd->lock);
7117 static void io_put_sq_data(struct io_sq_data *sqd)
7119 if (refcount_dec_and_test(&sqd->refs)) {
7120 io_sq_thread_stop(sqd);
7125 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7127 struct io_sq_data *sqd = ctx->sq_data;
7130 complete(&sqd->startup);
7132 wait_for_completion(&ctx->sq_thread_comp);
7133 io_sq_thread_park(sqd);
7136 mutex_lock(&sqd->ctx_lock);
7137 list_del(&ctx->sqd_list);
7138 io_sqd_update_thread_idle(sqd);
7139 mutex_unlock(&sqd->ctx_lock);
7142 io_sq_thread_unpark(sqd);
7144 io_put_sq_data(sqd);
7145 ctx->sq_data = NULL;
7149 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7151 struct io_ring_ctx *ctx_attach;
7152 struct io_sq_data *sqd;
7155 f = fdget(p->wq_fd);
7157 return ERR_PTR(-ENXIO);
7158 if (f.file->f_op != &io_uring_fops) {
7160 return ERR_PTR(-EINVAL);
7163 ctx_attach = f.file->private_data;
7164 sqd = ctx_attach->sq_data;
7167 return ERR_PTR(-EINVAL);
7170 refcount_inc(&sqd->refs);
7175 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7177 struct io_sq_data *sqd;
7179 if (p->flags & IORING_SETUP_ATTACH_WQ)
7180 return io_attach_sq_data(p);
7182 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7184 return ERR_PTR(-ENOMEM);
7186 refcount_set(&sqd->refs, 1);
7187 INIT_LIST_HEAD(&sqd->ctx_list);
7188 INIT_LIST_HEAD(&sqd->ctx_new_list);
7189 mutex_init(&sqd->ctx_lock);
7190 mutex_init(&sqd->lock);
7191 init_waitqueue_head(&sqd->wait);
7192 init_completion(&sqd->startup);
7193 init_completion(&sqd->parked);
7194 init_completion(&sqd->exited);
7198 #if defined(CONFIG_UNIX)
7200 * Ensure the UNIX gc is aware of our file set, so we are certain that
7201 * the io_uring can be safely unregistered on process exit, even if we have
7202 * loops in the file referencing.
7204 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7206 struct sock *sk = ctx->ring_sock->sk;
7207 struct scm_fp_list *fpl;
7208 struct sk_buff *skb;
7211 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7215 skb = alloc_skb(0, GFP_KERNEL);
7224 fpl->user = get_uid(current_user());
7225 for (i = 0; i < nr; i++) {
7226 struct file *file = io_file_from_index(ctx, i + offset);
7230 fpl->fp[nr_files] = get_file(file);
7231 unix_inflight(fpl->user, fpl->fp[nr_files]);
7236 fpl->max = SCM_MAX_FD;
7237 fpl->count = nr_files;
7238 UNIXCB(skb).fp = fpl;
7239 skb->destructor = unix_destruct_scm;
7240 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7241 skb_queue_head(&sk->sk_receive_queue, skb);
7243 for (i = 0; i < nr_files; i++)
7254 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7255 * causes regular reference counting to break down. We rely on the UNIX
7256 * garbage collection to take care of this problem for us.
7258 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7260 unsigned left, total;
7264 left = ctx->nr_user_files;
7266 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7268 ret = __io_sqe_files_scm(ctx, this_files, total);
7272 total += this_files;
7278 while (total < ctx->nr_user_files) {
7279 struct file *file = io_file_from_index(ctx, total);
7289 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7295 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7296 unsigned nr_tables, unsigned nr_files)
7300 for (i = 0; i < nr_tables; i++) {
7301 struct fixed_rsrc_table *table = &file_data->table[i];
7302 unsigned this_files;
7304 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7305 table->files = kcalloc(this_files, sizeof(struct file *),
7309 nr_files -= this_files;
7315 for (i = 0; i < nr_tables; i++) {
7316 struct fixed_rsrc_table *table = &file_data->table[i];
7317 kfree(table->files);
7322 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7324 struct file *file = prsrc->file;
7325 #if defined(CONFIG_UNIX)
7326 struct sock *sock = ctx->ring_sock->sk;
7327 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7328 struct sk_buff *skb;
7331 __skb_queue_head_init(&list);
7334 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7335 * remove this entry and rearrange the file array.
7337 skb = skb_dequeue(head);
7339 struct scm_fp_list *fp;
7341 fp = UNIXCB(skb).fp;
7342 for (i = 0; i < fp->count; i++) {
7345 if (fp->fp[i] != file)
7348 unix_notinflight(fp->user, fp->fp[i]);
7349 left = fp->count - 1 - i;
7351 memmove(&fp->fp[i], &fp->fp[i + 1],
7352 left * sizeof(struct file *));
7359 __skb_queue_tail(&list, skb);
7369 __skb_queue_tail(&list, skb);
7371 skb = skb_dequeue(head);
7374 if (skb_peek(&list)) {
7375 spin_lock_irq(&head->lock);
7376 while ((skb = __skb_dequeue(&list)) != NULL)
7377 __skb_queue_tail(head, skb);
7378 spin_unlock_irq(&head->lock);
7385 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7387 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7388 struct io_ring_ctx *ctx = rsrc_data->ctx;
7389 struct io_rsrc_put *prsrc, *tmp;
7391 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7392 list_del(&prsrc->list);
7393 ref_node->rsrc_put(ctx, prsrc);
7397 percpu_ref_exit(&ref_node->refs);
7399 percpu_ref_put(&rsrc_data->refs);
7402 static void io_rsrc_put_work(struct work_struct *work)
7404 struct io_ring_ctx *ctx;
7405 struct llist_node *node;
7407 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7408 node = llist_del_all(&ctx->rsrc_put_llist);
7411 struct fixed_rsrc_ref_node *ref_node;
7412 struct llist_node *next = node->next;
7414 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7415 __io_rsrc_put_work(ref_node);
7420 static struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
7423 struct fixed_rsrc_table *table;
7425 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7426 return &table->files[i & IORING_FILE_TABLE_MASK];
7429 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7431 struct fixed_rsrc_ref_node *ref_node;
7432 struct fixed_rsrc_data *data;
7433 struct io_ring_ctx *ctx;
7434 bool first_add = false;
7437 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7438 data = ref_node->rsrc_data;
7441 io_rsrc_ref_lock(ctx);
7442 ref_node->done = true;
7444 while (!list_empty(&ctx->rsrc_ref_list)) {
7445 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7446 struct fixed_rsrc_ref_node, node);
7447 /* recycle ref nodes in order */
7448 if (!ref_node->done)
7450 list_del(&ref_node->node);
7451 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7453 io_rsrc_ref_unlock(ctx);
7455 if (percpu_ref_is_dying(&data->refs))
7459 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7461 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7464 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7465 struct io_ring_ctx *ctx)
7467 struct fixed_rsrc_ref_node *ref_node;
7469 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7473 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7478 INIT_LIST_HEAD(&ref_node->node);
7479 INIT_LIST_HEAD(&ref_node->rsrc_list);
7480 ref_node->done = false;
7484 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7485 struct fixed_rsrc_ref_node *ref_node)
7487 ref_node->rsrc_data = ctx->file_data;
7488 ref_node->rsrc_put = io_ring_file_put;
7491 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7493 percpu_ref_exit(&ref_node->refs);
7498 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7501 __s32 __user *fds = (__s32 __user *) arg;
7502 unsigned nr_tables, i;
7504 int fd, ret = -ENOMEM;
7505 struct fixed_rsrc_ref_node *ref_node;
7506 struct fixed_rsrc_data *file_data;
7512 if (nr_args > IORING_MAX_FIXED_FILES)
7515 file_data = alloc_fixed_rsrc_data(ctx);
7518 ctx->file_data = file_data;
7520 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7521 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7523 if (!file_data->table)
7526 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7529 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7530 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7534 /* allow sparse sets */
7544 * Don't allow io_uring instances to be registered. If UNIX
7545 * isn't enabled, then this causes a reference cycle and this
7546 * instance can never get freed. If UNIX is enabled we'll
7547 * handle it just fine, but there's still no point in allowing
7548 * a ring fd as it doesn't support regular read/write anyway.
7550 if (file->f_op == &io_uring_fops) {
7554 *io_fixed_file_slot(file_data, i) = file;
7557 ret = io_sqe_files_scm(ctx);
7559 io_sqe_files_unregister(ctx);
7563 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7565 io_sqe_files_unregister(ctx);
7568 init_fixed_file_ref_node(ctx, ref_node);
7570 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7573 for (i = 0; i < ctx->nr_user_files; i++) {
7574 file = io_file_from_index(ctx, i);
7578 for (i = 0; i < nr_tables; i++)
7579 kfree(file_data->table[i].files);
7580 ctx->nr_user_files = 0;
7582 free_fixed_rsrc_data(ctx->file_data);
7583 ctx->file_data = NULL;
7587 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7590 #if defined(CONFIG_UNIX)
7591 struct sock *sock = ctx->ring_sock->sk;
7592 struct sk_buff_head *head = &sock->sk_receive_queue;
7593 struct sk_buff *skb;
7596 * See if we can merge this file into an existing skb SCM_RIGHTS
7597 * file set. If there's no room, fall back to allocating a new skb
7598 * and filling it in.
7600 spin_lock_irq(&head->lock);
7601 skb = skb_peek(head);
7603 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7605 if (fpl->count < SCM_MAX_FD) {
7606 __skb_unlink(skb, head);
7607 spin_unlock_irq(&head->lock);
7608 fpl->fp[fpl->count] = get_file(file);
7609 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7611 spin_lock_irq(&head->lock);
7612 __skb_queue_head(head, skb);
7617 spin_unlock_irq(&head->lock);
7624 return __io_sqe_files_scm(ctx, 1, index);
7630 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7632 struct io_rsrc_put *prsrc;
7633 struct fixed_rsrc_ref_node *ref_node = data->node;
7635 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7640 list_add(&prsrc->list, &ref_node->rsrc_list);
7645 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7648 return io_queue_rsrc_removal(data, (void *)file);
7651 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7652 struct io_uring_rsrc_update *up,
7655 struct fixed_rsrc_data *data = ctx->file_data;
7656 struct fixed_rsrc_ref_node *ref_node;
7657 struct file *file, **file_slot;
7661 bool needs_switch = false;
7663 if (check_add_overflow(up->offset, nr_args, &done))
7665 if (done > ctx->nr_user_files)
7668 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7671 init_fixed_file_ref_node(ctx, ref_node);
7673 fds = u64_to_user_ptr(up->data);
7674 for (done = 0; done < nr_args; done++) {
7676 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7680 if (fd == IORING_REGISTER_FILES_SKIP)
7683 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7684 file_slot = io_fixed_file_slot(ctx->file_data, i);
7687 err = io_queue_file_removal(data, *file_slot);
7691 needs_switch = true;
7700 * Don't allow io_uring instances to be registered. If
7701 * UNIX isn't enabled, then this causes a reference
7702 * cycle and this instance can never get freed. If UNIX
7703 * is enabled we'll handle it just fine, but there's
7704 * still no point in allowing a ring fd as it doesn't
7705 * support regular read/write anyway.
7707 if (file->f_op == &io_uring_fops) {
7713 err = io_sqe_file_register(ctx, file, i);
7723 percpu_ref_kill(&data->node->refs);
7724 io_sqe_rsrc_set_node(ctx, data, ref_node);
7726 destroy_fixed_rsrc_ref_node(ref_node);
7728 return done ? done : err;
7731 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7734 struct io_uring_rsrc_update up;
7736 if (!ctx->file_data)
7740 if (copy_from_user(&up, arg, sizeof(up)))
7745 return __io_sqe_files_update(ctx, &up, nr_args);
7748 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7750 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7752 req = io_put_req_find_next(req);
7753 return req ? &req->work : NULL;
7756 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx)
7758 struct io_wq_hash *hash;
7759 struct io_wq_data data;
7760 unsigned int concurrency;
7762 hash = ctx->hash_map;
7764 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7766 return ERR_PTR(-ENOMEM);
7767 refcount_set(&hash->refs, 1);
7768 init_waitqueue_head(&hash->wait);
7769 ctx->hash_map = hash;
7773 data.free_work = io_free_work;
7774 data.do_work = io_wq_submit_work;
7776 /* Do QD, or 4 * CPUS, whatever is smallest */
7777 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7779 return io_wq_create(concurrency, &data);
7782 static int io_uring_alloc_task_context(struct task_struct *task,
7783 struct io_ring_ctx *ctx)
7785 struct io_uring_task *tctx;
7788 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7789 if (unlikely(!tctx))
7792 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7793 if (unlikely(ret)) {
7798 tctx->io_wq = io_init_wq_offload(ctx);
7799 if (IS_ERR(tctx->io_wq)) {
7800 ret = PTR_ERR(tctx->io_wq);
7801 percpu_counter_destroy(&tctx->inflight);
7807 init_waitqueue_head(&tctx->wait);
7809 atomic_set(&tctx->in_idle, 0);
7810 tctx->sqpoll = false;
7811 task->io_uring = tctx;
7812 spin_lock_init(&tctx->task_lock);
7813 INIT_WQ_LIST(&tctx->task_list);
7814 tctx->task_state = 0;
7815 init_task_work(&tctx->task_work, tctx_task_work);
7819 void __io_uring_free(struct task_struct *tsk)
7821 struct io_uring_task *tctx = tsk->io_uring;
7823 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7824 WARN_ON_ONCE(tctx->io_wq);
7826 percpu_counter_destroy(&tctx->inflight);
7828 tsk->io_uring = NULL;
7831 static int io_sq_thread_fork(struct io_sq_data *sqd, struct io_ring_ctx *ctx)
7833 struct task_struct *tsk;
7836 clear_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7837 reinit_completion(&sqd->parked);
7839 sqd->task_pid = current->pid;
7840 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
7842 return PTR_ERR(tsk);
7843 ret = io_uring_alloc_task_context(tsk, ctx);
7845 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7847 wake_up_new_task(tsk);
7851 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7852 struct io_uring_params *p)
7856 /* Retain compatibility with failing for an invalid attach attempt */
7857 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7858 IORING_SETUP_ATTACH_WQ) {
7861 f = fdget(p->wq_fd);
7864 if (f.file->f_op != &io_uring_fops) {
7870 if (ctx->flags & IORING_SETUP_SQPOLL) {
7871 struct task_struct *tsk;
7872 struct io_sq_data *sqd;
7875 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
7878 sqd = io_get_sq_data(p);
7885 io_sq_thread_park(sqd);
7886 mutex_lock(&sqd->ctx_lock);
7887 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7888 mutex_unlock(&sqd->ctx_lock);
7889 io_sq_thread_unpark(sqd);
7891 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7892 if (!ctx->sq_thread_idle)
7893 ctx->sq_thread_idle = HZ;
7898 if (p->flags & IORING_SETUP_SQ_AFF) {
7899 int cpu = p->sq_thread_cpu;
7902 if (cpu >= nr_cpu_ids)
7904 if (!cpu_online(cpu))
7912 sqd->task_pid = current->pid;
7913 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
7918 ret = io_uring_alloc_task_context(tsk, ctx);
7920 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7922 wake_up_new_task(tsk);
7925 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7926 /* Can't have SQ_AFF without SQPOLL */
7933 io_sq_thread_finish(ctx);
7937 static void io_sq_offload_start(struct io_ring_ctx *ctx)
7939 struct io_sq_data *sqd = ctx->sq_data;
7941 ctx->flags &= ~IORING_SETUP_R_DISABLED;
7942 if (ctx->flags & IORING_SETUP_SQPOLL)
7943 complete(&sqd->startup);
7946 static inline void __io_unaccount_mem(struct user_struct *user,
7947 unsigned long nr_pages)
7949 atomic_long_sub(nr_pages, &user->locked_vm);
7952 static inline int __io_account_mem(struct user_struct *user,
7953 unsigned long nr_pages)
7955 unsigned long page_limit, cur_pages, new_pages;
7957 /* Don't allow more pages than we can safely lock */
7958 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7961 cur_pages = atomic_long_read(&user->locked_vm);
7962 new_pages = cur_pages + nr_pages;
7963 if (new_pages > page_limit)
7965 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7966 new_pages) != cur_pages);
7971 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7974 __io_unaccount_mem(ctx->user, nr_pages);
7976 if (ctx->mm_account)
7977 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
7980 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7985 ret = __io_account_mem(ctx->user, nr_pages);
7990 if (ctx->mm_account)
7991 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
7996 static void io_mem_free(void *ptr)
8003 page = virt_to_head_page(ptr);
8004 if (put_page_testzero(page))
8005 free_compound_page(page);
8008 static void *io_mem_alloc(size_t size)
8010 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8011 __GFP_NORETRY | __GFP_ACCOUNT;
8013 return (void *) __get_free_pages(gfp_flags, get_order(size));
8016 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8019 struct io_rings *rings;
8020 size_t off, sq_array_size;
8022 off = struct_size(rings, cqes, cq_entries);
8023 if (off == SIZE_MAX)
8027 off = ALIGN(off, SMP_CACHE_BYTES);
8035 sq_array_size = array_size(sizeof(u32), sq_entries);
8036 if (sq_array_size == SIZE_MAX)
8039 if (check_add_overflow(off, sq_array_size, &off))
8045 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8049 if (!ctx->user_bufs)
8052 for (i = 0; i < ctx->nr_user_bufs; i++) {
8053 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8055 for (j = 0; j < imu->nr_bvecs; j++)
8056 unpin_user_page(imu->bvec[j].bv_page);
8058 if (imu->acct_pages)
8059 io_unaccount_mem(ctx, imu->acct_pages);
8064 kfree(ctx->user_bufs);
8065 ctx->user_bufs = NULL;
8066 ctx->nr_user_bufs = 0;
8070 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8071 void __user *arg, unsigned index)
8073 struct iovec __user *src;
8075 #ifdef CONFIG_COMPAT
8077 struct compat_iovec __user *ciovs;
8078 struct compat_iovec ciov;
8080 ciovs = (struct compat_iovec __user *) arg;
8081 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8084 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8085 dst->iov_len = ciov.iov_len;
8089 src = (struct iovec __user *) arg;
8090 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8096 * Not super efficient, but this is just a registration time. And we do cache
8097 * the last compound head, so generally we'll only do a full search if we don't
8100 * We check if the given compound head page has already been accounted, to
8101 * avoid double accounting it. This allows us to account the full size of the
8102 * page, not just the constituent pages of a huge page.
8104 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8105 int nr_pages, struct page *hpage)
8109 /* check current page array */
8110 for (i = 0; i < nr_pages; i++) {
8111 if (!PageCompound(pages[i]))
8113 if (compound_head(pages[i]) == hpage)
8117 /* check previously registered pages */
8118 for (i = 0; i < ctx->nr_user_bufs; i++) {
8119 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8121 for (j = 0; j < imu->nr_bvecs; j++) {
8122 if (!PageCompound(imu->bvec[j].bv_page))
8124 if (compound_head(imu->bvec[j].bv_page) == hpage)
8132 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8133 int nr_pages, struct io_mapped_ubuf *imu,
8134 struct page **last_hpage)
8138 for (i = 0; i < nr_pages; i++) {
8139 if (!PageCompound(pages[i])) {
8144 hpage = compound_head(pages[i]);
8145 if (hpage == *last_hpage)
8147 *last_hpage = hpage;
8148 if (headpage_already_acct(ctx, pages, i, hpage))
8150 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8154 if (!imu->acct_pages)
8157 ret = io_account_mem(ctx, imu->acct_pages);
8159 imu->acct_pages = 0;
8163 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8164 struct io_mapped_ubuf *imu,
8165 struct page **last_hpage)
8167 struct vm_area_struct **vmas = NULL;
8168 struct page **pages = NULL;
8169 unsigned long off, start, end, ubuf;
8171 int ret, pret, nr_pages, i;
8173 ubuf = (unsigned long) iov->iov_base;
8174 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8175 start = ubuf >> PAGE_SHIFT;
8176 nr_pages = end - start;
8180 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8184 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8189 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8195 mmap_read_lock(current->mm);
8196 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8198 if (pret == nr_pages) {
8199 /* don't support file backed memory */
8200 for (i = 0; i < nr_pages; i++) {
8201 struct vm_area_struct *vma = vmas[i];
8204 !is_file_hugepages(vma->vm_file)) {
8210 ret = pret < 0 ? pret : -EFAULT;
8212 mmap_read_unlock(current->mm);
8215 * if we did partial map, or found file backed vmas,
8216 * release any pages we did get
8219 unpin_user_pages(pages, pret);
8224 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8226 unpin_user_pages(pages, pret);
8231 off = ubuf & ~PAGE_MASK;
8232 size = iov->iov_len;
8233 for (i = 0; i < nr_pages; i++) {
8236 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8237 imu->bvec[i].bv_page = pages[i];
8238 imu->bvec[i].bv_len = vec_len;
8239 imu->bvec[i].bv_offset = off;
8243 /* store original address for later verification */
8245 imu->len = iov->iov_len;
8246 imu->nr_bvecs = nr_pages;
8254 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8258 if (!nr_args || nr_args > UIO_MAXIOV)
8261 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8263 if (!ctx->user_bufs)
8269 static int io_buffer_validate(struct iovec *iov)
8272 * Don't impose further limits on the size and buffer
8273 * constraints here, we'll -EINVAL later when IO is
8274 * submitted if they are wrong.
8276 if (!iov->iov_base || !iov->iov_len)
8279 /* arbitrary limit, but we need something */
8280 if (iov->iov_len > SZ_1G)
8286 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8287 unsigned int nr_args)
8291 struct page *last_hpage = NULL;
8293 ret = io_buffers_map_alloc(ctx, nr_args);
8297 for (i = 0; i < nr_args; i++) {
8298 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8300 ret = io_copy_iov(ctx, &iov, arg, i);
8304 ret = io_buffer_validate(&iov);
8308 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8312 ctx->nr_user_bufs++;
8316 io_sqe_buffers_unregister(ctx);
8321 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8323 __s32 __user *fds = arg;
8329 if (copy_from_user(&fd, fds, sizeof(*fds)))
8332 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8333 if (IS_ERR(ctx->cq_ev_fd)) {
8334 int ret = PTR_ERR(ctx->cq_ev_fd);
8335 ctx->cq_ev_fd = NULL;
8342 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8344 if (ctx->cq_ev_fd) {
8345 eventfd_ctx_put(ctx->cq_ev_fd);
8346 ctx->cq_ev_fd = NULL;
8353 static int __io_destroy_buffers(int id, void *p, void *data)
8355 struct io_ring_ctx *ctx = data;
8356 struct io_buffer *buf = p;
8358 __io_remove_buffers(ctx, buf, id, -1U);
8362 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8364 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8365 idr_destroy(&ctx->io_buffer_idr);
8368 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8370 struct io_kiocb *req, *nxt;
8372 list_for_each_entry_safe(req, nxt, list, compl.list) {
8373 if (tsk && req->task != tsk)
8375 list_del(&req->compl.list);
8376 kmem_cache_free(req_cachep, req);
8380 static void io_req_caches_free(struct io_ring_ctx *ctx)
8382 struct io_submit_state *submit_state = &ctx->submit_state;
8383 struct io_comp_state *cs = &ctx->submit_state.comp;
8385 mutex_lock(&ctx->uring_lock);
8387 if (submit_state->free_reqs) {
8388 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8389 submit_state->reqs);
8390 submit_state->free_reqs = 0;
8393 spin_lock_irq(&ctx->completion_lock);
8394 list_splice_init(&cs->locked_free_list, &cs->free_list);
8395 cs->locked_free_nr = 0;
8396 spin_unlock_irq(&ctx->completion_lock);
8398 io_req_cache_free(&cs->free_list, NULL);
8400 mutex_unlock(&ctx->uring_lock);
8403 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8406 * Some may use context even when all refs and requests have been put,
8407 * and they are free to do so while still holding uring_lock, see
8408 * __io_req_task_submit(). Wait for them to finish.
8410 mutex_lock(&ctx->uring_lock);
8411 mutex_unlock(&ctx->uring_lock);
8413 io_sq_thread_finish(ctx);
8414 io_sqe_buffers_unregister(ctx);
8416 if (ctx->mm_account) {
8417 mmdrop(ctx->mm_account);
8418 ctx->mm_account = NULL;
8421 mutex_lock(&ctx->uring_lock);
8422 io_sqe_files_unregister(ctx);
8423 mutex_unlock(&ctx->uring_lock);
8424 io_eventfd_unregister(ctx);
8425 io_destroy_buffers(ctx);
8426 idr_destroy(&ctx->personality_idr);
8428 #if defined(CONFIG_UNIX)
8429 if (ctx->ring_sock) {
8430 ctx->ring_sock->file = NULL; /* so that iput() is called */
8431 sock_release(ctx->ring_sock);
8435 io_mem_free(ctx->rings);
8436 io_mem_free(ctx->sq_sqes);
8438 percpu_ref_exit(&ctx->refs);
8439 free_uid(ctx->user);
8440 io_req_caches_free(ctx);
8442 io_wq_put_hash(ctx->hash_map);
8443 kfree(ctx->cancel_hash);
8447 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8449 struct io_ring_ctx *ctx = file->private_data;
8452 poll_wait(file, &ctx->cq_wait, wait);
8454 * synchronizes with barrier from wq_has_sleeper call in
8458 if (!io_sqring_full(ctx))
8459 mask |= EPOLLOUT | EPOLLWRNORM;
8462 * Don't flush cqring overflow list here, just do a simple check.
8463 * Otherwise there could possible be ABBA deadlock:
8466 * lock(&ctx->uring_lock);
8468 * lock(&ctx->uring_lock);
8471 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8472 * pushs them to do the flush.
8474 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8475 mask |= EPOLLIN | EPOLLRDNORM;
8480 static int io_uring_fasync(int fd, struct file *file, int on)
8482 struct io_ring_ctx *ctx = file->private_data;
8484 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8487 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8489 const struct cred *creds;
8491 creds = idr_remove(&ctx->personality_idr, id);
8500 static int io_remove_personalities(int id, void *p, void *data)
8502 struct io_ring_ctx *ctx = data;
8504 io_unregister_personality(ctx, id);
8508 static bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8510 struct callback_head *work, *next;
8511 bool executed = false;
8514 work = xchg(&ctx->exit_task_work, NULL);
8530 static void io_ring_exit_work(struct work_struct *work)
8532 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8536 * If we're doing polled IO and end up having requests being
8537 * submitted async (out-of-line), then completions can come in while
8538 * we're waiting for refs to drop. We need to reap these manually,
8539 * as nobody else will be looking for them.
8542 io_uring_try_cancel_requests(ctx, NULL, NULL);
8543 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8544 io_ring_ctx_free(ctx);
8547 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8549 mutex_lock(&ctx->uring_lock);
8550 percpu_ref_kill(&ctx->refs);
8551 /* if force is set, the ring is going away. always drop after that */
8552 ctx->cq_overflow_flushed = 1;
8554 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8555 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8556 mutex_unlock(&ctx->uring_lock);
8558 io_kill_timeouts(ctx, NULL, NULL);
8559 io_poll_remove_all(ctx, NULL, NULL);
8561 /* if we failed setting up the ctx, we might not have any rings */
8562 io_iopoll_try_reap_events(ctx);
8564 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8566 * Use system_unbound_wq to avoid spawning tons of event kworkers
8567 * if we're exiting a ton of rings at the same time. It just adds
8568 * noise and overhead, there's no discernable change in runtime
8569 * over using system_wq.
8571 queue_work(system_unbound_wq, &ctx->exit_work);
8574 static int io_uring_release(struct inode *inode, struct file *file)
8576 struct io_ring_ctx *ctx = file->private_data;
8578 file->private_data = NULL;
8579 io_ring_ctx_wait_and_kill(ctx);
8583 struct io_task_cancel {
8584 struct task_struct *task;
8585 struct files_struct *files;
8588 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8590 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8591 struct io_task_cancel *cancel = data;
8594 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8595 unsigned long flags;
8596 struct io_ring_ctx *ctx = req->ctx;
8598 /* protect against races with linked timeouts */
8599 spin_lock_irqsave(&ctx->completion_lock, flags);
8600 ret = io_match_task(req, cancel->task, cancel->files);
8601 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8603 ret = io_match_task(req, cancel->task, cancel->files);
8608 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8609 struct task_struct *task,
8610 struct files_struct *files)
8612 struct io_defer_entry *de = NULL;
8615 spin_lock_irq(&ctx->completion_lock);
8616 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8617 if (io_match_task(de->req, task, files)) {
8618 list_cut_position(&list, &ctx->defer_list, &de->list);
8622 spin_unlock_irq(&ctx->completion_lock);
8624 while (!list_empty(&list)) {
8625 de = list_first_entry(&list, struct io_defer_entry, list);
8626 list_del_init(&de->list);
8627 req_set_fail_links(de->req);
8628 io_put_req(de->req);
8629 io_req_complete(de->req, -ECANCELED);
8634 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8635 struct task_struct *task,
8636 struct files_struct *files)
8638 struct io_task_cancel cancel = { .task = task, .files = files, };
8639 struct task_struct *tctx_task = task ?: current;
8640 struct io_uring_task *tctx = tctx_task->io_uring;
8643 enum io_wq_cancel cret;
8646 if (tctx && tctx->io_wq) {
8647 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8649 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8652 /* SQPOLL thread does its own polling */
8653 if (!(ctx->flags & IORING_SETUP_SQPOLL) && !files) {
8654 while (!list_empty_careful(&ctx->iopoll_list)) {
8655 io_iopoll_try_reap_events(ctx);
8660 ret |= io_poll_remove_all(ctx, task, files);
8661 ret |= io_kill_timeouts(ctx, task, files);
8662 ret |= io_run_task_work();
8663 ret |= io_run_ctx_fallback(ctx);
8664 io_cqring_overflow_flush(ctx, true, task, files);
8671 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8672 struct task_struct *task,
8673 struct files_struct *files)
8675 struct io_kiocb *req;
8678 spin_lock_irq(&ctx->inflight_lock);
8679 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8680 cnt += io_match_task(req, task, files);
8681 spin_unlock_irq(&ctx->inflight_lock);
8685 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8686 struct task_struct *task,
8687 struct files_struct *files)
8689 while (!list_empty_careful(&ctx->inflight_list)) {
8693 inflight = io_uring_count_inflight(ctx, task, files);
8697 io_uring_try_cancel_requests(ctx, task, files);
8700 io_sq_thread_unpark(ctx->sq_data);
8701 prepare_to_wait(&task->io_uring->wait, &wait,
8702 TASK_UNINTERRUPTIBLE);
8703 if (inflight == io_uring_count_inflight(ctx, task, files))
8705 finish_wait(&task->io_uring->wait, &wait);
8707 io_sq_thread_park(ctx->sq_data);
8712 * We need to iteratively cancel requests, in case a request has dependent
8713 * hard links. These persist even for failure of cancelations, hence keep
8714 * looping until none are found.
8716 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8717 struct files_struct *files)
8719 struct task_struct *task = current;
8721 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8722 /* never started, nothing to cancel */
8723 if (ctx->flags & IORING_SETUP_R_DISABLED) {
8724 io_sq_offload_start(ctx);
8727 io_sq_thread_park(ctx->sq_data);
8728 task = ctx->sq_data->thread;
8730 atomic_inc(&task->io_uring->in_idle);
8733 io_cancel_defer_files(ctx, task, files);
8735 io_uring_cancel_files(ctx, task, files);
8737 io_uring_try_cancel_requests(ctx, task, NULL);
8740 atomic_dec(&task->io_uring->in_idle);
8742 io_sq_thread_unpark(ctx->sq_data);
8746 * Note that this task has used io_uring. We use it for cancelation purposes.
8748 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
8750 struct io_uring_task *tctx = current->io_uring;
8753 if (unlikely(!tctx)) {
8754 ret = io_uring_alloc_task_context(current, ctx);
8757 tctx = current->io_uring;
8759 if (tctx->last != file) {
8760 void *old = xa_load(&tctx->xa, (unsigned long)file);
8764 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
8775 * This is race safe in that the task itself is doing this, hence it
8776 * cannot be going through the exit/cancel paths at the same time.
8777 * This cannot be modified while exit/cancel is running.
8779 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
8780 tctx->sqpoll = true;
8786 * Remove this io_uring_file -> task mapping.
8788 static void io_uring_del_task_file(struct file *file)
8790 struct io_uring_task *tctx = current->io_uring;
8792 if (tctx->last == file)
8794 file = xa_erase(&tctx->xa, (unsigned long)file);
8799 static void io_uring_clean_tctx(struct io_uring_task *tctx)
8802 unsigned long index;
8804 xa_for_each(&tctx->xa, index, file)
8805 io_uring_del_task_file(file);
8807 io_wq_put_and_exit(tctx->io_wq);
8812 void __io_uring_files_cancel(struct files_struct *files)
8814 struct io_uring_task *tctx = current->io_uring;
8816 unsigned long index;
8818 /* make sure overflow events are dropped */
8819 atomic_inc(&tctx->in_idle);
8820 xa_for_each(&tctx->xa, index, file)
8821 io_uring_cancel_task_requests(file->private_data, files);
8822 atomic_dec(&tctx->in_idle);
8825 io_uring_clean_tctx(tctx);
8828 static s64 tctx_inflight(struct io_uring_task *tctx)
8830 return percpu_counter_sum(&tctx->inflight);
8833 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
8835 struct io_sq_data *sqd = ctx->sq_data;
8836 struct io_uring_task *tctx;
8842 io_sq_thread_park(sqd);
8843 if (!sqd->thread || !sqd->thread->io_uring) {
8844 io_sq_thread_unpark(sqd);
8847 tctx = ctx->sq_data->thread->io_uring;
8848 atomic_inc(&tctx->in_idle);
8850 /* read completions before cancelations */
8851 inflight = tctx_inflight(tctx);
8854 io_uring_cancel_task_requests(ctx, NULL);
8856 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8858 * If we've seen completions, retry without waiting. This
8859 * avoids a race where a completion comes in before we did
8860 * prepare_to_wait().
8862 if (inflight == tctx_inflight(tctx))
8864 finish_wait(&tctx->wait, &wait);
8866 atomic_dec(&tctx->in_idle);
8867 io_sq_thread_unpark(sqd);
8871 * Find any io_uring fd that this task has registered or done IO on, and cancel
8874 void __io_uring_task_cancel(void)
8876 struct io_uring_task *tctx = current->io_uring;
8880 /* make sure overflow events are dropped */
8881 atomic_inc(&tctx->in_idle);
8885 unsigned long index;
8887 xa_for_each(&tctx->xa, index, file)
8888 io_uring_cancel_sqpoll(file->private_data);
8892 /* read completions before cancelations */
8893 inflight = tctx_inflight(tctx);
8896 __io_uring_files_cancel(NULL);
8898 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8901 * If we've seen completions, retry without waiting. This
8902 * avoids a race where a completion comes in before we did
8903 * prepare_to_wait().
8905 if (inflight == tctx_inflight(tctx))
8907 finish_wait(&tctx->wait, &wait);
8910 atomic_dec(&tctx->in_idle);
8912 io_uring_clean_tctx(tctx);
8913 /* all current's requests should be gone, we can kill tctx */
8914 __io_uring_free(current);
8917 static void *io_uring_validate_mmap_request(struct file *file,
8918 loff_t pgoff, size_t sz)
8920 struct io_ring_ctx *ctx = file->private_data;
8921 loff_t offset = pgoff << PAGE_SHIFT;
8926 case IORING_OFF_SQ_RING:
8927 case IORING_OFF_CQ_RING:
8930 case IORING_OFF_SQES:
8934 return ERR_PTR(-EINVAL);
8937 page = virt_to_head_page(ptr);
8938 if (sz > page_size(page))
8939 return ERR_PTR(-EINVAL);
8946 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8948 size_t sz = vma->vm_end - vma->vm_start;
8952 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
8954 return PTR_ERR(ptr);
8956 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
8957 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
8960 #else /* !CONFIG_MMU */
8962 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8964 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
8967 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
8969 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
8972 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
8973 unsigned long addr, unsigned long len,
8974 unsigned long pgoff, unsigned long flags)
8978 ptr = io_uring_validate_mmap_request(file, pgoff, len);
8980 return PTR_ERR(ptr);
8982 return (unsigned long) ptr;
8985 #endif /* !CONFIG_MMU */
8987 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
8993 if (!io_sqring_full(ctx))
8995 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
8997 if (!io_sqring_full(ctx))
9000 } while (!signal_pending(current));
9002 finish_wait(&ctx->sqo_sq_wait, &wait);
9006 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9007 struct __kernel_timespec __user **ts,
9008 const sigset_t __user **sig)
9010 struct io_uring_getevents_arg arg;
9013 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9014 * is just a pointer to the sigset_t.
9016 if (!(flags & IORING_ENTER_EXT_ARG)) {
9017 *sig = (const sigset_t __user *) argp;
9023 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9024 * timespec and sigset_t pointers if good.
9026 if (*argsz != sizeof(arg))
9028 if (copy_from_user(&arg, argp, sizeof(arg)))
9030 *sig = u64_to_user_ptr(arg.sigmask);
9031 *argsz = arg.sigmask_sz;
9032 *ts = u64_to_user_ptr(arg.ts);
9036 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9037 u32, min_complete, u32, flags, const void __user *, argp,
9040 struct io_ring_ctx *ctx;
9047 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9048 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9056 if (f.file->f_op != &io_uring_fops)
9060 ctx = f.file->private_data;
9061 if (!percpu_ref_tryget(&ctx->refs))
9065 if (ctx->flags & IORING_SETUP_R_DISABLED)
9069 * For SQ polling, the thread will do all submissions and completions.
9070 * Just return the requested submit count, and wake the thread if
9074 if (ctx->flags & IORING_SETUP_SQPOLL) {
9075 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9077 if (unlikely(ctx->sqo_exec)) {
9078 ret = io_sq_thread_fork(ctx->sq_data, ctx);
9084 if (flags & IORING_ENTER_SQ_WAKEUP)
9085 wake_up(&ctx->sq_data->wait);
9086 if (flags & IORING_ENTER_SQ_WAIT) {
9087 ret = io_sqpoll_wait_sq(ctx);
9091 submitted = to_submit;
9092 } else if (to_submit) {
9093 ret = io_uring_add_task_file(ctx, f.file);
9096 mutex_lock(&ctx->uring_lock);
9097 submitted = io_submit_sqes(ctx, to_submit);
9098 mutex_unlock(&ctx->uring_lock);
9100 if (submitted != to_submit)
9103 if (flags & IORING_ENTER_GETEVENTS) {
9104 const sigset_t __user *sig;
9105 struct __kernel_timespec __user *ts;
9107 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9111 min_complete = min(min_complete, ctx->cq_entries);
9114 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9115 * space applications don't need to do io completion events
9116 * polling again, they can rely on io_sq_thread to do polling
9117 * work, which can reduce cpu usage and uring_lock contention.
9119 if (ctx->flags & IORING_SETUP_IOPOLL &&
9120 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9121 ret = io_iopoll_check(ctx, min_complete);
9123 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9128 percpu_ref_put(&ctx->refs);
9131 return submitted ? submitted : ret;
9134 #ifdef CONFIG_PROC_FS
9135 static int io_uring_show_cred(int id, void *p, void *data)
9137 const struct cred *cred = p;
9138 struct seq_file *m = data;
9139 struct user_namespace *uns = seq_user_ns(m);
9140 struct group_info *gi;
9145 seq_printf(m, "%5d\n", id);
9146 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9147 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9148 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9149 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9150 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9151 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9152 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9153 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9154 seq_puts(m, "\n\tGroups:\t");
9155 gi = cred->group_info;
9156 for (g = 0; g < gi->ngroups; g++) {
9157 seq_put_decimal_ull(m, g ? " " : "",
9158 from_kgid_munged(uns, gi->gid[g]));
9160 seq_puts(m, "\n\tCapEff:\t");
9161 cap = cred->cap_effective;
9162 CAP_FOR_EACH_U32(__capi)
9163 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9168 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9170 struct io_sq_data *sq = NULL;
9175 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9176 * since fdinfo case grabs it in the opposite direction of normal use
9177 * cases. If we fail to get the lock, we just don't iterate any
9178 * structures that could be going away outside the io_uring mutex.
9180 has_lock = mutex_trylock(&ctx->uring_lock);
9182 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9188 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9189 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9190 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9191 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9192 struct file *f = *io_fixed_file_slot(ctx->file_data, i);
9195 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9197 seq_printf(m, "%5u: <none>\n", i);
9199 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9200 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9201 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9203 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9204 (unsigned int) buf->len);
9206 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9207 seq_printf(m, "Personalities:\n");
9208 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9210 seq_printf(m, "PollList:\n");
9211 spin_lock_irq(&ctx->completion_lock);
9212 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9213 struct hlist_head *list = &ctx->cancel_hash[i];
9214 struct io_kiocb *req;
9216 hlist_for_each_entry(req, list, hash_node)
9217 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9218 req->task->task_works != NULL);
9220 spin_unlock_irq(&ctx->completion_lock);
9222 mutex_unlock(&ctx->uring_lock);
9225 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9227 struct io_ring_ctx *ctx = f->private_data;
9229 if (percpu_ref_tryget(&ctx->refs)) {
9230 __io_uring_show_fdinfo(ctx, m);
9231 percpu_ref_put(&ctx->refs);
9236 static const struct file_operations io_uring_fops = {
9237 .release = io_uring_release,
9238 .mmap = io_uring_mmap,
9240 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9241 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9243 .poll = io_uring_poll,
9244 .fasync = io_uring_fasync,
9245 #ifdef CONFIG_PROC_FS
9246 .show_fdinfo = io_uring_show_fdinfo,
9250 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9251 struct io_uring_params *p)
9253 struct io_rings *rings;
9254 size_t size, sq_array_offset;
9256 /* make sure these are sane, as we already accounted them */
9257 ctx->sq_entries = p->sq_entries;
9258 ctx->cq_entries = p->cq_entries;
9260 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9261 if (size == SIZE_MAX)
9264 rings = io_mem_alloc(size);
9269 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9270 rings->sq_ring_mask = p->sq_entries - 1;
9271 rings->cq_ring_mask = p->cq_entries - 1;
9272 rings->sq_ring_entries = p->sq_entries;
9273 rings->cq_ring_entries = p->cq_entries;
9274 ctx->sq_mask = rings->sq_ring_mask;
9275 ctx->cq_mask = rings->cq_ring_mask;
9277 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9278 if (size == SIZE_MAX) {
9279 io_mem_free(ctx->rings);
9284 ctx->sq_sqes = io_mem_alloc(size);
9285 if (!ctx->sq_sqes) {
9286 io_mem_free(ctx->rings);
9294 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9298 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9302 ret = io_uring_add_task_file(ctx, file);
9307 fd_install(fd, file);
9312 * Allocate an anonymous fd, this is what constitutes the application
9313 * visible backing of an io_uring instance. The application mmaps this
9314 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9315 * we have to tie this fd to a socket for file garbage collection purposes.
9317 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9320 #if defined(CONFIG_UNIX)
9323 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9326 return ERR_PTR(ret);
9329 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9330 O_RDWR | O_CLOEXEC);
9331 #if defined(CONFIG_UNIX)
9333 sock_release(ctx->ring_sock);
9334 ctx->ring_sock = NULL;
9336 ctx->ring_sock->file = file;
9342 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9343 struct io_uring_params __user *params)
9345 struct io_ring_ctx *ctx;
9351 if (entries > IORING_MAX_ENTRIES) {
9352 if (!(p->flags & IORING_SETUP_CLAMP))
9354 entries = IORING_MAX_ENTRIES;
9358 * Use twice as many entries for the CQ ring. It's possible for the
9359 * application to drive a higher depth than the size of the SQ ring,
9360 * since the sqes are only used at submission time. This allows for
9361 * some flexibility in overcommitting a bit. If the application has
9362 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9363 * of CQ ring entries manually.
9365 p->sq_entries = roundup_pow_of_two(entries);
9366 if (p->flags & IORING_SETUP_CQSIZE) {
9368 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9369 * to a power-of-two, if it isn't already. We do NOT impose
9370 * any cq vs sq ring sizing.
9374 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9375 if (!(p->flags & IORING_SETUP_CLAMP))
9377 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9379 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9380 if (p->cq_entries < p->sq_entries)
9383 p->cq_entries = 2 * p->sq_entries;
9386 ctx = io_ring_ctx_alloc(p);
9389 ctx->compat = in_compat_syscall();
9390 if (!capable(CAP_IPC_LOCK))
9391 ctx->user = get_uid(current_user());
9394 * This is just grabbed for accounting purposes. When a process exits,
9395 * the mm is exited and dropped before the files, hence we need to hang
9396 * on to this mm purely for the purposes of being able to unaccount
9397 * memory (locked/pinned vm). It's not used for anything else.
9399 mmgrab(current->mm);
9400 ctx->mm_account = current->mm;
9402 ret = io_allocate_scq_urings(ctx, p);
9406 ret = io_sq_offload_create(ctx, p);
9410 if (!(p->flags & IORING_SETUP_R_DISABLED))
9411 io_sq_offload_start(ctx);
9413 memset(&p->sq_off, 0, sizeof(p->sq_off));
9414 p->sq_off.head = offsetof(struct io_rings, sq.head);
9415 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9416 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9417 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9418 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9419 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9420 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9422 memset(&p->cq_off, 0, sizeof(p->cq_off));
9423 p->cq_off.head = offsetof(struct io_rings, cq.head);
9424 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9425 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9426 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9427 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9428 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9429 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9431 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9432 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9433 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9434 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9435 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9437 if (copy_to_user(params, p, sizeof(*p))) {
9442 file = io_uring_get_file(ctx);
9444 ret = PTR_ERR(file);
9449 * Install ring fd as the very last thing, so we don't risk someone
9450 * having closed it before we finish setup
9452 ret = io_uring_install_fd(ctx, file);
9454 /* fput will clean it up */
9459 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9462 io_ring_ctx_wait_and_kill(ctx);
9467 * Sets up an aio uring context, and returns the fd. Applications asks for a
9468 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9469 * params structure passed in.
9471 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9473 struct io_uring_params p;
9476 if (copy_from_user(&p, params, sizeof(p)))
9478 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9483 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9484 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9485 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9486 IORING_SETUP_R_DISABLED))
9489 return io_uring_create(entries, &p, params);
9492 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9493 struct io_uring_params __user *, params)
9495 return io_uring_setup(entries, params);
9498 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9500 struct io_uring_probe *p;
9504 size = struct_size(p, ops, nr_args);
9505 if (size == SIZE_MAX)
9507 p = kzalloc(size, GFP_KERNEL);
9512 if (copy_from_user(p, arg, size))
9515 if (memchr_inv(p, 0, size))
9518 p->last_op = IORING_OP_LAST - 1;
9519 if (nr_args > IORING_OP_LAST)
9520 nr_args = IORING_OP_LAST;
9522 for (i = 0; i < nr_args; i++) {
9524 if (!io_op_defs[i].not_supported)
9525 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9530 if (copy_to_user(arg, p, size))
9537 static int io_register_personality(struct io_ring_ctx *ctx)
9539 const struct cred *creds;
9542 creds = get_current_cred();
9544 ret = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
9545 USHRT_MAX, GFP_KERNEL);
9551 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9552 unsigned int nr_args)
9554 struct io_uring_restriction *res;
9558 /* Restrictions allowed only if rings started disabled */
9559 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9562 /* We allow only a single restrictions registration */
9563 if (ctx->restrictions.registered)
9566 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9569 size = array_size(nr_args, sizeof(*res));
9570 if (size == SIZE_MAX)
9573 res = memdup_user(arg, size);
9575 return PTR_ERR(res);
9579 for (i = 0; i < nr_args; i++) {
9580 switch (res[i].opcode) {
9581 case IORING_RESTRICTION_REGISTER_OP:
9582 if (res[i].register_op >= IORING_REGISTER_LAST) {
9587 __set_bit(res[i].register_op,
9588 ctx->restrictions.register_op);
9590 case IORING_RESTRICTION_SQE_OP:
9591 if (res[i].sqe_op >= IORING_OP_LAST) {
9596 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9598 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9599 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9601 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9602 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9611 /* Reset all restrictions if an error happened */
9613 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9615 ctx->restrictions.registered = true;
9621 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9623 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9626 if (ctx->restrictions.registered)
9627 ctx->restricted = 1;
9629 io_sq_offload_start(ctx);
9633 static bool io_register_op_must_quiesce(int op)
9636 case IORING_UNREGISTER_FILES:
9637 case IORING_REGISTER_FILES_UPDATE:
9638 case IORING_REGISTER_PROBE:
9639 case IORING_REGISTER_PERSONALITY:
9640 case IORING_UNREGISTER_PERSONALITY:
9647 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9648 void __user *arg, unsigned nr_args)
9649 __releases(ctx->uring_lock)
9650 __acquires(ctx->uring_lock)
9655 * We're inside the ring mutex, if the ref is already dying, then
9656 * someone else killed the ctx or is already going through
9657 * io_uring_register().
9659 if (percpu_ref_is_dying(&ctx->refs))
9662 if (io_register_op_must_quiesce(opcode)) {
9663 percpu_ref_kill(&ctx->refs);
9666 * Drop uring mutex before waiting for references to exit. If
9667 * another thread is currently inside io_uring_enter() it might
9668 * need to grab the uring_lock to make progress. If we hold it
9669 * here across the drain wait, then we can deadlock. It's safe
9670 * to drop the mutex here, since no new references will come in
9671 * after we've killed the percpu ref.
9673 mutex_unlock(&ctx->uring_lock);
9675 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9678 ret = io_run_task_work_sig();
9683 mutex_lock(&ctx->uring_lock);
9686 percpu_ref_resurrect(&ctx->refs);
9691 if (ctx->restricted) {
9692 if (opcode >= IORING_REGISTER_LAST) {
9697 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9704 case IORING_REGISTER_BUFFERS:
9705 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9707 case IORING_UNREGISTER_BUFFERS:
9711 ret = io_sqe_buffers_unregister(ctx);
9713 case IORING_REGISTER_FILES:
9714 ret = io_sqe_files_register(ctx, arg, nr_args);
9716 case IORING_UNREGISTER_FILES:
9720 ret = io_sqe_files_unregister(ctx);
9722 case IORING_REGISTER_FILES_UPDATE:
9723 ret = io_sqe_files_update(ctx, arg, nr_args);
9725 case IORING_REGISTER_EVENTFD:
9726 case IORING_REGISTER_EVENTFD_ASYNC:
9730 ret = io_eventfd_register(ctx, arg);
9733 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9734 ctx->eventfd_async = 1;
9736 ctx->eventfd_async = 0;
9738 case IORING_UNREGISTER_EVENTFD:
9742 ret = io_eventfd_unregister(ctx);
9744 case IORING_REGISTER_PROBE:
9746 if (!arg || nr_args > 256)
9748 ret = io_probe(ctx, arg, nr_args);
9750 case IORING_REGISTER_PERSONALITY:
9754 ret = io_register_personality(ctx);
9756 case IORING_UNREGISTER_PERSONALITY:
9760 ret = io_unregister_personality(ctx, nr_args);
9762 case IORING_REGISTER_ENABLE_RINGS:
9766 ret = io_register_enable_rings(ctx);
9768 case IORING_REGISTER_RESTRICTIONS:
9769 ret = io_register_restrictions(ctx, arg, nr_args);
9777 if (io_register_op_must_quiesce(opcode)) {
9778 /* bring the ctx back to life */
9779 percpu_ref_reinit(&ctx->refs);
9781 reinit_completion(&ctx->ref_comp);
9786 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9787 void __user *, arg, unsigned int, nr_args)
9789 struct io_ring_ctx *ctx;
9798 if (f.file->f_op != &io_uring_fops)
9801 ctx = f.file->private_data;
9805 mutex_lock(&ctx->uring_lock);
9806 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9807 mutex_unlock(&ctx->uring_lock);
9808 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9809 ctx->cq_ev_fd != NULL, ret);
9815 static int __init io_uring_init(void)
9817 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9818 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9819 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9822 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9823 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9824 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9825 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9826 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9827 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9828 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9829 BUILD_BUG_SQE_ELEM(8, __u64, off);
9830 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9831 BUILD_BUG_SQE_ELEM(16, __u64, addr);
9832 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
9833 BUILD_BUG_SQE_ELEM(24, __u32, len);
9834 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9835 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9836 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9837 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
9838 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9839 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
9840 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9841 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9842 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9843 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9844 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9845 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9846 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9847 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
9848 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9849 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9850 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9851 BUILD_BUG_SQE_ELEM(42, __u16, personality);
9852 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
9854 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9855 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9856 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
9860 __initcall(io_uring_init);