1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/fs_struct.h>
79 #include <linux/splice.h>
80 #include <linux/task_work.h>
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
85 #include <uapi/linux/io_uring.h>
90 #define IORING_MAX_ENTRIES 32768
91 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
96 #define IORING_FILE_TABLE_SHIFT 9
97 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
98 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
99 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
102 u32 head ____cacheline_aligned_in_smp;
103 u32 tail ____cacheline_aligned_in_smp;
107 * This data is shared with the application through the mmap at offsets
108 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
110 * The offsets to the member fields are published through struct
111 * io_sqring_offsets when calling io_uring_setup.
115 * Head and tail offsets into the ring; the offsets need to be
116 * masked to get valid indices.
118 * The kernel controls head of the sq ring and the tail of the cq ring,
119 * and the application controls tail of the sq ring and the head of the
122 struct io_uring sq, cq;
124 * Bitmasks to apply to head and tail offsets (constant, equals
127 u32 sq_ring_mask, cq_ring_mask;
128 /* Ring sizes (constant, power of 2) */
129 u32 sq_ring_entries, cq_ring_entries;
131 * Number of invalid entries dropped by the kernel due to
132 * invalid index stored in array
134 * Written by the kernel, shouldn't be modified by the
135 * application (i.e. get number of "new events" by comparing to
138 * After a new SQ head value was read by the application this
139 * counter includes all submissions that were dropped reaching
140 * the new SQ head (and possibly more).
146 * Written by the kernel, shouldn't be modified by the
149 * The application needs a full memory barrier before checking
150 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
156 * Written by the application, shouldn't be modified by the
161 * Number of completion events lost because the queue was full;
162 * this should be avoided by the application by making sure
163 * there are not more requests pending than there is space in
164 * the completion queue.
166 * Written by the kernel, shouldn't be modified by the
167 * application (i.e. get number of "new events" by comparing to
170 * As completion events come in out of order this counter is not
171 * ordered with any other data.
175 * Ring buffer of completion events.
177 * The kernel writes completion events fresh every time they are
178 * produced, so the application is allowed to modify pending
181 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
184 struct io_mapped_ubuf {
187 struct bio_vec *bvec;
188 unsigned int nr_bvecs;
191 struct fixed_file_table {
195 struct fixed_file_ref_node {
196 struct percpu_ref refs;
197 struct list_head node;
198 struct list_head file_list;
199 struct fixed_file_data *file_data;
200 struct llist_node llist;
203 struct fixed_file_data {
204 struct fixed_file_table *table;
205 struct io_ring_ctx *ctx;
207 struct percpu_ref *cur_refs;
208 struct percpu_ref refs;
209 struct completion done;
210 struct list_head ref_list;
215 struct list_head list;
223 struct percpu_ref refs;
224 } ____cacheline_aligned_in_smp;
228 unsigned int compat: 1;
229 unsigned int account_mem: 1;
230 unsigned int cq_overflow_flushed: 1;
231 unsigned int drain_next: 1;
232 unsigned int eventfd_async: 1;
235 * Ring buffer of indices into array of io_uring_sqe, which is
236 * mmapped by the application using the IORING_OFF_SQES offset.
238 * This indirection could e.g. be used to assign fixed
239 * io_uring_sqe entries to operations and only submit them to
240 * the queue when needed.
242 * The kernel modifies neither the indices array nor the entries
246 unsigned cached_sq_head;
249 unsigned sq_thread_idle;
250 unsigned cached_sq_dropped;
251 atomic_t cached_cq_overflow;
252 unsigned long sq_check_overflow;
254 struct list_head defer_list;
255 struct list_head timeout_list;
256 struct list_head cq_overflow_list;
258 wait_queue_head_t inflight_wait;
259 struct io_uring_sqe *sq_sqes;
260 } ____cacheline_aligned_in_smp;
262 struct io_rings *rings;
266 struct task_struct *sqo_thread; /* if using sq thread polling */
267 struct mm_struct *sqo_mm;
268 wait_queue_head_t sqo_wait;
271 * If used, fixed file set. Writers must ensure that ->refs is dead,
272 * readers must ensure that ->refs is alive as long as the file* is
273 * used. Only updated through io_uring_register(2).
275 struct fixed_file_data *file_data;
276 unsigned nr_user_files;
278 struct file *ring_file;
280 /* if used, fixed mapped user buffers */
281 unsigned nr_user_bufs;
282 struct io_mapped_ubuf *user_bufs;
284 struct user_struct *user;
286 const struct cred *creds;
288 struct completion ref_comp;
289 struct completion sq_thread_comp;
291 /* if all else fails... */
292 struct io_kiocb *fallback_req;
294 #if defined(CONFIG_UNIX)
295 struct socket *ring_sock;
298 struct idr io_buffer_idr;
300 struct idr personality_idr;
303 unsigned cached_cq_tail;
306 atomic_t cq_timeouts;
307 unsigned long cq_check_overflow;
308 struct wait_queue_head cq_wait;
309 struct fasync_struct *cq_fasync;
310 struct eventfd_ctx *cq_ev_fd;
311 } ____cacheline_aligned_in_smp;
314 struct mutex uring_lock;
315 wait_queue_head_t wait;
316 } ____cacheline_aligned_in_smp;
319 spinlock_t completion_lock;
322 * ->poll_list is protected by the ctx->uring_lock for
323 * io_uring instances that don't use IORING_SETUP_SQPOLL.
324 * For SQPOLL, only the single threaded io_sq_thread() will
325 * manipulate the list, hence no extra locking is needed there.
327 struct list_head poll_list;
328 struct hlist_head *cancel_hash;
329 unsigned cancel_hash_bits;
330 bool poll_multi_file;
332 spinlock_t inflight_lock;
333 struct list_head inflight_list;
334 } ____cacheline_aligned_in_smp;
336 struct delayed_work file_put_work;
337 struct llist_head file_put_llist;
339 struct work_struct exit_work;
343 * First field must be the file pointer in all the
344 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
346 struct io_poll_iocb {
349 struct wait_queue_head *head;
355 struct wait_queue_entry wait;
360 struct file *put_file;
364 struct io_timeout_data {
365 struct io_kiocb *req;
366 struct hrtimer timer;
367 struct timespec64 ts;
368 enum hrtimer_mode mode;
373 struct sockaddr __user *addr;
374 int __user *addr_len;
376 unsigned long nofile;
401 /* NOTE: kiocb has the file as the first member, so don't do it here */
409 struct sockaddr __user *addr;
416 struct user_msghdr __user *msg;
422 struct io_buffer *kbuf;
428 struct filename *filename;
430 unsigned long nofile;
433 struct io_files_update {
459 struct epoll_event event;
463 struct file *file_out;
464 struct file *file_in;
471 struct io_provide_buf {
485 const char __user *filename;
486 struct statx __user *buffer;
489 struct io_async_connect {
490 struct sockaddr_storage address;
493 struct io_async_msghdr {
494 struct iovec fast_iov[UIO_FASTIOV];
496 struct sockaddr __user *uaddr;
498 struct sockaddr_storage addr;
502 struct iovec fast_iov[UIO_FASTIOV];
508 struct io_async_ctx {
510 struct io_async_rw rw;
511 struct io_async_msghdr msg;
512 struct io_async_connect connect;
513 struct io_timeout_data timeout;
518 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
519 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
520 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
521 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
522 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
523 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
531 REQ_F_LINK_TIMEOUT_BIT,
535 REQ_F_TIMEOUT_NOSEQ_BIT,
536 REQ_F_COMP_LOCKED_BIT,
537 REQ_F_NEED_CLEANUP_BIT,
540 REQ_F_BUFFER_SELECTED_BIT,
541 REQ_F_NO_FILE_TABLE_BIT,
542 REQ_F_QUEUE_TIMEOUT_BIT,
543 REQ_F_WORK_INITIALIZED_BIT,
544 REQ_F_TASK_PINNED_BIT,
546 /* not a real bit, just to check we're not overflowing the space */
552 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
553 /* drain existing IO first */
554 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
556 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
557 /* doesn't sever on completion < 0 */
558 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
560 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
561 /* IOSQE_BUFFER_SELECT */
562 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
565 REQ_F_LINK_HEAD = BIT(REQ_F_LINK_HEAD_BIT),
566 /* already grabbed next link */
567 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
568 /* fail rest of links */
569 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
570 /* on inflight list */
571 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
572 /* read/write uses file position */
573 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
574 /* must not punt to workers */
575 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
576 /* has linked timeout */
577 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
578 /* timeout request */
579 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
581 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
582 /* must be punted even for NONBLOCK */
583 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
584 /* no timeout sequence */
585 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
586 /* completion under lock */
587 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
589 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
590 /* in overflow list */
591 REQ_F_OVERFLOW = BIT(REQ_F_OVERFLOW_BIT),
592 /* already went through poll handler */
593 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
594 /* buffer already selected */
595 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
596 /* doesn't need file table for this request */
597 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
598 /* needs to queue linked timeout */
599 REQ_F_QUEUE_TIMEOUT = BIT(REQ_F_QUEUE_TIMEOUT_BIT),
600 /* io_wq_work is initialized */
601 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
602 /* req->task is refcounted */
603 REQ_F_TASK_PINNED = BIT(REQ_F_TASK_PINNED_BIT),
607 struct io_poll_iocb poll;
608 struct io_poll_iocb *double_poll;
609 struct io_wq_work work;
613 * NOTE! Each of the iocb union members has the file pointer
614 * as the first entry in their struct definition. So you can
615 * access the file pointer through any of the sub-structs,
616 * or directly as just 'ki_filp' in this struct.
622 struct io_poll_iocb poll;
623 struct io_accept accept;
625 struct io_cancel cancel;
626 struct io_timeout timeout;
627 struct io_connect connect;
628 struct io_sr_msg sr_msg;
630 struct io_close close;
631 struct io_files_update files_update;
632 struct io_fadvise fadvise;
633 struct io_madvise madvise;
634 struct io_epoll epoll;
635 struct io_splice splice;
636 struct io_provide_buf pbuf;
637 struct io_statx statx;
640 struct io_async_ctx *io;
643 /* polled IO has completed */
648 struct io_ring_ctx *ctx;
649 struct list_head list;
652 struct task_struct *task;
658 struct list_head link_list;
660 struct list_head inflight_entry;
662 struct percpu_ref *fixed_file_refs;
666 * Only commands that never go async can use the below fields,
667 * obviously. Right now only IORING_OP_POLL_ADD uses them, and
668 * async armed poll handlers for regular commands. The latter
669 * restore the work, if needed.
672 struct callback_head task_work;
673 struct hlist_node hash_node;
674 struct async_poll *apoll;
676 struct io_wq_work work;
680 #define IO_PLUG_THRESHOLD 2
681 #define IO_IOPOLL_BATCH 8
683 struct io_submit_state {
684 struct blk_plug plug;
687 * io_kiocb alloc cache
689 void *reqs[IO_IOPOLL_BATCH];
690 unsigned int free_reqs;
693 * File reference cache
697 unsigned int has_refs;
698 unsigned int used_refs;
699 unsigned int ios_left;
703 /* needs req->io allocated for deferral/async */
704 unsigned async_ctx : 1;
705 /* needs current->mm setup, does mm access */
706 unsigned needs_mm : 1;
707 /* needs req->file assigned */
708 unsigned needs_file : 1;
709 /* don't fail if file grab fails */
710 unsigned needs_file_no_error : 1;
711 /* hash wq insertion if file is a regular file */
712 unsigned hash_reg_file : 1;
713 /* unbound wq insertion if file is a non-regular file */
714 unsigned unbound_nonreg_file : 1;
715 /* opcode is not supported by this kernel */
716 unsigned not_supported : 1;
717 /* needs file table */
718 unsigned file_table : 1;
720 unsigned needs_fs : 1;
721 /* set if opcode supports polled "wait" */
723 unsigned pollout : 1;
724 /* op supports buffer selection */
725 unsigned buffer_select : 1;
728 static const struct io_op_def io_op_defs[] = {
729 [IORING_OP_NOP] = {},
730 [IORING_OP_READV] = {
734 .unbound_nonreg_file = 1,
738 [IORING_OP_WRITEV] = {
743 .unbound_nonreg_file = 1,
746 [IORING_OP_FSYNC] = {
749 [IORING_OP_READ_FIXED] = {
751 .unbound_nonreg_file = 1,
754 [IORING_OP_WRITE_FIXED] = {
757 .unbound_nonreg_file = 1,
760 [IORING_OP_POLL_ADD] = {
762 .unbound_nonreg_file = 1,
764 [IORING_OP_POLL_REMOVE] = {},
765 [IORING_OP_SYNC_FILE_RANGE] = {
768 [IORING_OP_SENDMSG] = {
772 .unbound_nonreg_file = 1,
776 [IORING_OP_RECVMSG] = {
780 .unbound_nonreg_file = 1,
785 [IORING_OP_TIMEOUT] = {
789 [IORING_OP_TIMEOUT_REMOVE] = {},
790 [IORING_OP_ACCEPT] = {
793 .unbound_nonreg_file = 1,
797 [IORING_OP_ASYNC_CANCEL] = {},
798 [IORING_OP_LINK_TIMEOUT] = {
802 [IORING_OP_CONNECT] = {
806 .unbound_nonreg_file = 1,
809 [IORING_OP_FALLOCATE] = {
812 [IORING_OP_OPENAT] = {
816 [IORING_OP_CLOSE] = {
818 .needs_file_no_error = 1,
821 [IORING_OP_FILES_UPDATE] = {
825 [IORING_OP_STATX] = {
833 .unbound_nonreg_file = 1,
837 [IORING_OP_WRITE] = {
840 .unbound_nonreg_file = 1,
843 [IORING_OP_FADVISE] = {
846 [IORING_OP_MADVISE] = {
852 .unbound_nonreg_file = 1,
858 .unbound_nonreg_file = 1,
862 [IORING_OP_OPENAT2] = {
866 [IORING_OP_EPOLL_CTL] = {
867 .unbound_nonreg_file = 1,
870 [IORING_OP_SPLICE] = {
873 .unbound_nonreg_file = 1,
875 [IORING_OP_PROVIDE_BUFFERS] = {},
876 [IORING_OP_REMOVE_BUFFERS] = {},
880 .unbound_nonreg_file = 1,
884 static void io_wq_submit_work(struct io_wq_work **workptr);
885 static void io_cqring_fill_event(struct io_kiocb *req, long res);
886 static void io_put_req(struct io_kiocb *req);
887 static void __io_double_put_req(struct io_kiocb *req);
888 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
889 static void io_queue_linked_timeout(struct io_kiocb *req);
890 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
891 struct io_uring_files_update *ip,
893 static int io_grab_files(struct io_kiocb *req);
894 static void io_complete_rw_common(struct kiocb *kiocb, long res);
895 static void io_cleanup_req(struct io_kiocb *req);
896 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
897 int fd, struct file **out_file, bool fixed);
898 static void __io_queue_sqe(struct io_kiocb *req,
899 const struct io_uring_sqe *sqe);
901 static struct kmem_cache *req_cachep;
903 static const struct file_operations io_uring_fops;
905 struct sock *io_uring_get_socket(struct file *file)
907 #if defined(CONFIG_UNIX)
908 if (file->f_op == &io_uring_fops) {
909 struct io_ring_ctx *ctx = file->private_data;
911 return ctx->ring_sock->sk;
916 EXPORT_SYMBOL(io_uring_get_socket);
918 static void io_get_req_task(struct io_kiocb *req)
920 if (req->flags & REQ_F_TASK_PINNED)
922 get_task_struct(req->task);
923 req->flags |= REQ_F_TASK_PINNED;
926 /* not idempotent -- it doesn't clear REQ_F_TASK_PINNED */
927 static void __io_put_req_task(struct io_kiocb *req)
929 if (req->flags & REQ_F_TASK_PINNED)
930 put_task_struct(req->task);
933 static void io_file_put_work(struct work_struct *work);
936 * Note: must call io_req_init_async() for the first time you
937 * touch any members of io_wq_work.
939 static inline void io_req_init_async(struct io_kiocb *req)
941 if (req->flags & REQ_F_WORK_INITIALIZED)
944 memset(&req->work, 0, sizeof(req->work));
945 req->flags |= REQ_F_WORK_INITIALIZED;
948 static inline bool io_async_submit(struct io_ring_ctx *ctx)
950 return ctx->flags & IORING_SETUP_SQPOLL;
953 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
955 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
957 complete(&ctx->ref_comp);
960 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
962 struct io_ring_ctx *ctx;
965 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
969 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
970 if (!ctx->fallback_req)
974 * Use 5 bits less than the max cq entries, that should give us around
975 * 32 entries per hash list if totally full and uniformly spread.
977 hash_bits = ilog2(p->cq_entries);
981 ctx->cancel_hash_bits = hash_bits;
982 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
984 if (!ctx->cancel_hash)
986 __hash_init(ctx->cancel_hash, 1U << hash_bits);
988 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
989 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
992 ctx->flags = p->flags;
993 init_waitqueue_head(&ctx->sqo_wait);
994 init_waitqueue_head(&ctx->cq_wait);
995 INIT_LIST_HEAD(&ctx->cq_overflow_list);
996 init_completion(&ctx->ref_comp);
997 init_completion(&ctx->sq_thread_comp);
998 idr_init(&ctx->io_buffer_idr);
999 idr_init(&ctx->personality_idr);
1000 mutex_init(&ctx->uring_lock);
1001 init_waitqueue_head(&ctx->wait);
1002 spin_lock_init(&ctx->completion_lock);
1003 INIT_LIST_HEAD(&ctx->poll_list);
1004 INIT_LIST_HEAD(&ctx->defer_list);
1005 INIT_LIST_HEAD(&ctx->timeout_list);
1006 init_waitqueue_head(&ctx->inflight_wait);
1007 spin_lock_init(&ctx->inflight_lock);
1008 INIT_LIST_HEAD(&ctx->inflight_list);
1009 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1010 init_llist_head(&ctx->file_put_llist);
1013 if (ctx->fallback_req)
1014 kmem_cache_free(req_cachep, ctx->fallback_req);
1015 kfree(ctx->cancel_hash);
1020 static inline bool __req_need_defer(struct io_kiocb *req)
1022 struct io_ring_ctx *ctx = req->ctx;
1024 return req->sequence != ctx->cached_cq_tail
1025 + atomic_read(&ctx->cached_cq_overflow);
1028 static inline bool req_need_defer(struct io_kiocb *req)
1030 if (unlikely(req->flags & REQ_F_IO_DRAIN))
1031 return __req_need_defer(req);
1036 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1038 struct io_rings *rings = ctx->rings;
1040 /* order cqe stores with ring update */
1041 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1043 if (wq_has_sleeper(&ctx->cq_wait)) {
1044 wake_up_interruptible(&ctx->cq_wait);
1045 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1049 static inline void io_req_work_grab_env(struct io_kiocb *req,
1050 const struct io_op_def *def)
1052 if (!req->work.mm && def->needs_mm) {
1053 mmgrab(current->mm);
1054 req->work.mm = current->mm;
1056 if (!req->work.creds)
1057 req->work.creds = get_current_cred();
1058 if (!req->work.fs && def->needs_fs) {
1059 spin_lock(¤t->fs->lock);
1060 if (!current->fs->in_exec) {
1061 req->work.fs = current->fs;
1062 req->work.fs->users++;
1064 req->work.flags |= IO_WQ_WORK_CANCEL;
1066 spin_unlock(¤t->fs->lock);
1070 static inline void io_req_work_drop_env(struct io_kiocb *req)
1072 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1076 mmdrop(req->work.mm);
1077 req->work.mm = NULL;
1079 if (req->work.creds) {
1080 put_cred(req->work.creds);
1081 req->work.creds = NULL;
1084 struct fs_struct *fs = req->work.fs;
1086 spin_lock(&req->work.fs->lock);
1089 spin_unlock(&req->work.fs->lock);
1095 static inline void io_prep_async_work(struct io_kiocb *req,
1096 struct io_kiocb **link)
1098 const struct io_op_def *def = &io_op_defs[req->opcode];
1100 io_req_init_async(req);
1102 if (req->flags & REQ_F_ISREG) {
1103 if (def->hash_reg_file)
1104 io_wq_hash_work(&req->work, file_inode(req->file));
1106 if (def->unbound_nonreg_file)
1107 req->work.flags |= IO_WQ_WORK_UNBOUND;
1110 io_req_work_grab_env(req, def);
1112 *link = io_prep_linked_timeout(req);
1115 static inline void io_queue_async_work(struct io_kiocb *req)
1117 struct io_ring_ctx *ctx = req->ctx;
1118 struct io_kiocb *link;
1120 io_prep_async_work(req, &link);
1122 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1123 &req->work, req->flags);
1124 io_wq_enqueue(ctx->io_wq, &req->work);
1127 io_queue_linked_timeout(link);
1130 static void io_kill_timeout(struct io_kiocb *req)
1134 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1136 atomic_inc(&req->ctx->cq_timeouts);
1137 list_del_init(&req->list);
1138 req->flags |= REQ_F_COMP_LOCKED;
1139 io_cqring_fill_event(req, 0);
1144 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1146 struct io_kiocb *req, *tmp;
1148 spin_lock_irq(&ctx->completion_lock);
1149 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1150 io_kill_timeout(req);
1151 spin_unlock_irq(&ctx->completion_lock);
1154 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1157 struct io_kiocb *req = list_first_entry(&ctx->defer_list,
1158 struct io_kiocb, list);
1160 if (req_need_defer(req))
1162 list_del_init(&req->list);
1163 io_queue_async_work(req);
1164 } while (!list_empty(&ctx->defer_list));
1167 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1169 while (!list_empty(&ctx->timeout_list)) {
1170 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1171 struct io_kiocb, list);
1173 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
1175 if (req->timeout.target_seq != ctx->cached_cq_tail
1176 - atomic_read(&ctx->cq_timeouts))
1179 list_del_init(&req->list);
1180 io_kill_timeout(req);
1184 static void io_commit_cqring(struct io_ring_ctx *ctx)
1186 io_flush_timeouts(ctx);
1187 __io_commit_cqring(ctx);
1189 if (unlikely(!list_empty(&ctx->defer_list)))
1190 __io_queue_deferred(ctx);
1193 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1195 struct io_rings *rings = ctx->rings;
1198 tail = ctx->cached_cq_tail;
1200 * writes to the cq entry need to come after reading head; the
1201 * control dependency is enough as we're using WRITE_ONCE to
1204 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1207 ctx->cached_cq_tail++;
1208 return &rings->cqes[tail & ctx->cq_mask];
1211 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1215 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1217 if (!ctx->eventfd_async)
1219 return io_wq_current_is_worker();
1222 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1224 if (waitqueue_active(&ctx->wait))
1225 wake_up(&ctx->wait);
1226 if (waitqueue_active(&ctx->sqo_wait))
1227 wake_up(&ctx->sqo_wait);
1228 if (io_should_trigger_evfd(ctx))
1229 eventfd_signal(ctx->cq_ev_fd, 1);
1232 /* Returns true if there are no backlogged entries after the flush */
1233 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1235 struct io_rings *rings = ctx->rings;
1236 struct io_uring_cqe *cqe;
1237 struct io_kiocb *req;
1238 unsigned long flags;
1242 if (list_empty_careful(&ctx->cq_overflow_list))
1244 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1245 rings->cq_ring_entries))
1249 spin_lock_irqsave(&ctx->completion_lock, flags);
1251 /* if force is set, the ring is going away. always drop after that */
1253 ctx->cq_overflow_flushed = 1;
1256 while (!list_empty(&ctx->cq_overflow_list)) {
1257 cqe = io_get_cqring(ctx);
1261 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1263 list_move(&req->list, &list);
1264 req->flags &= ~REQ_F_OVERFLOW;
1266 WRITE_ONCE(cqe->user_data, req->user_data);
1267 WRITE_ONCE(cqe->res, req->result);
1268 WRITE_ONCE(cqe->flags, req->cflags);
1270 WRITE_ONCE(ctx->rings->cq_overflow,
1271 atomic_inc_return(&ctx->cached_cq_overflow));
1275 io_commit_cqring(ctx);
1277 clear_bit(0, &ctx->sq_check_overflow);
1278 clear_bit(0, &ctx->cq_check_overflow);
1279 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1281 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1282 io_cqring_ev_posted(ctx);
1284 while (!list_empty(&list)) {
1285 req = list_first_entry(&list, struct io_kiocb, list);
1286 list_del(&req->list);
1293 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1295 struct io_ring_ctx *ctx = req->ctx;
1296 struct io_uring_cqe *cqe;
1298 trace_io_uring_complete(ctx, req->user_data, res);
1301 * If we can't get a cq entry, userspace overflowed the
1302 * submission (by quite a lot). Increment the overflow count in
1305 cqe = io_get_cqring(ctx);
1307 WRITE_ONCE(cqe->user_data, req->user_data);
1308 WRITE_ONCE(cqe->res, res);
1309 WRITE_ONCE(cqe->flags, cflags);
1310 } else if (ctx->cq_overflow_flushed) {
1311 WRITE_ONCE(ctx->rings->cq_overflow,
1312 atomic_inc_return(&ctx->cached_cq_overflow));
1314 if (list_empty(&ctx->cq_overflow_list)) {
1315 set_bit(0, &ctx->sq_check_overflow);
1316 set_bit(0, &ctx->cq_check_overflow);
1317 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1319 req->flags |= REQ_F_OVERFLOW;
1320 refcount_inc(&req->refs);
1322 req->cflags = cflags;
1323 list_add_tail(&req->list, &ctx->cq_overflow_list);
1327 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1329 __io_cqring_fill_event(req, res, 0);
1332 static void __io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1334 struct io_ring_ctx *ctx = req->ctx;
1335 unsigned long flags;
1337 spin_lock_irqsave(&ctx->completion_lock, flags);
1338 __io_cqring_fill_event(req, res, cflags);
1339 io_commit_cqring(ctx);
1340 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1342 io_cqring_ev_posted(ctx);
1345 static void io_cqring_add_event(struct io_kiocb *req, long res)
1347 __io_cqring_add_event(req, res, 0);
1350 static inline bool io_is_fallback_req(struct io_kiocb *req)
1352 return req == (struct io_kiocb *)
1353 ((unsigned long) req->ctx->fallback_req & ~1UL);
1356 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1358 struct io_kiocb *req;
1360 req = ctx->fallback_req;
1361 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1367 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1368 struct io_submit_state *state)
1370 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1371 struct io_kiocb *req;
1374 req = kmem_cache_alloc(req_cachep, gfp);
1377 } else if (!state->free_reqs) {
1381 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1382 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1385 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1386 * retry single alloc to be on the safe side.
1388 if (unlikely(ret <= 0)) {
1389 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1390 if (!state->reqs[0])
1394 state->free_reqs = ret - 1;
1395 req = state->reqs[ret - 1];
1398 req = state->reqs[state->free_reqs];
1403 return io_get_fallback_req(ctx);
1406 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1410 percpu_ref_put(req->fixed_file_refs);
1415 static void __io_req_aux_free(struct io_kiocb *req)
1417 if (req->flags & REQ_F_NEED_CLEANUP)
1418 io_cleanup_req(req);
1422 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1423 __io_put_req_task(req);
1424 io_req_work_drop_env(req);
1427 static void __io_free_req(struct io_kiocb *req)
1429 __io_req_aux_free(req);
1431 if (req->flags & REQ_F_INFLIGHT) {
1432 struct io_ring_ctx *ctx = req->ctx;
1433 unsigned long flags;
1435 spin_lock_irqsave(&ctx->inflight_lock, flags);
1436 list_del(&req->inflight_entry);
1437 if (waitqueue_active(&ctx->inflight_wait))
1438 wake_up(&ctx->inflight_wait);
1439 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1442 percpu_ref_put(&req->ctx->refs);
1443 if (likely(!io_is_fallback_req(req)))
1444 kmem_cache_free(req_cachep, req);
1446 clear_bit_unlock(0, (unsigned long *) &req->ctx->fallback_req);
1450 void *reqs[IO_IOPOLL_BATCH];
1455 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1459 if (rb->need_iter) {
1460 int i, inflight = 0;
1461 unsigned long flags;
1463 for (i = 0; i < rb->to_free; i++) {
1464 struct io_kiocb *req = rb->reqs[i];
1466 if (req->flags & REQ_F_INFLIGHT)
1468 __io_req_aux_free(req);
1473 spin_lock_irqsave(&ctx->inflight_lock, flags);
1474 for (i = 0; i < rb->to_free; i++) {
1475 struct io_kiocb *req = rb->reqs[i];
1477 if (req->flags & REQ_F_INFLIGHT) {
1478 list_del(&req->inflight_entry);
1483 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1485 if (waitqueue_active(&ctx->inflight_wait))
1486 wake_up(&ctx->inflight_wait);
1489 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1490 percpu_ref_put_many(&ctx->refs, rb->to_free);
1491 rb->to_free = rb->need_iter = 0;
1494 static bool io_link_cancel_timeout(struct io_kiocb *req)
1496 struct io_ring_ctx *ctx = req->ctx;
1499 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1501 io_cqring_fill_event(req, -ECANCELED);
1502 io_commit_cqring(ctx);
1503 req->flags &= ~REQ_F_LINK_HEAD;
1511 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1513 struct io_ring_ctx *ctx = req->ctx;
1514 bool wake_ev = false;
1516 /* Already got next link */
1517 if (req->flags & REQ_F_LINK_NEXT)
1521 * The list should never be empty when we are called here. But could
1522 * potentially happen if the chain is messed up, check to be on the
1525 while (!list_empty(&req->link_list)) {
1526 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1527 struct io_kiocb, link_list);
1529 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1530 (nxt->flags & REQ_F_TIMEOUT))) {
1531 list_del_init(&nxt->link_list);
1532 wake_ev |= io_link_cancel_timeout(nxt);
1533 req->flags &= ~REQ_F_LINK_TIMEOUT;
1537 list_del_init(&req->link_list);
1538 if (!list_empty(&nxt->link_list))
1539 nxt->flags |= REQ_F_LINK_HEAD;
1544 req->flags |= REQ_F_LINK_NEXT;
1546 io_cqring_ev_posted(ctx);
1550 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1552 static void io_fail_links(struct io_kiocb *req)
1554 struct io_ring_ctx *ctx = req->ctx;
1555 unsigned long flags;
1557 spin_lock_irqsave(&ctx->completion_lock, flags);
1559 while (!list_empty(&req->link_list)) {
1560 struct io_kiocb *link = list_first_entry(&req->link_list,
1561 struct io_kiocb, link_list);
1563 list_del_init(&link->link_list);
1564 trace_io_uring_fail_link(req, link);
1566 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1567 link->opcode == IORING_OP_LINK_TIMEOUT) {
1568 io_link_cancel_timeout(link);
1570 io_cqring_fill_event(link, -ECANCELED);
1571 __io_double_put_req(link);
1573 req->flags &= ~REQ_F_LINK_TIMEOUT;
1576 io_commit_cqring(ctx);
1577 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1578 io_cqring_ev_posted(ctx);
1581 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1583 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1587 * If LINK is set, we have dependent requests in this chain. If we
1588 * didn't fail this request, queue the first one up, moving any other
1589 * dependencies to the next request. In case of failure, fail the rest
1592 if (req->flags & REQ_F_FAIL_LINK) {
1594 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1595 REQ_F_LINK_TIMEOUT) {
1596 struct io_ring_ctx *ctx = req->ctx;
1597 unsigned long flags;
1600 * If this is a timeout link, we could be racing with the
1601 * timeout timer. Grab the completion lock for this case to
1602 * protect against that.
1604 spin_lock_irqsave(&ctx->completion_lock, flags);
1605 io_req_link_next(req, nxt);
1606 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1608 io_req_link_next(req, nxt);
1612 static void io_free_req(struct io_kiocb *req)
1614 struct io_kiocb *nxt = NULL;
1616 io_req_find_next(req, &nxt);
1620 io_queue_async_work(nxt);
1623 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
1625 struct io_kiocb *link;
1626 const struct io_op_def *def = &io_op_defs[nxt->opcode];
1628 if ((nxt->flags & REQ_F_ISREG) && def->hash_reg_file)
1629 io_wq_hash_work(&nxt->work, file_inode(nxt->file));
1631 *workptr = &nxt->work;
1632 link = io_prep_linked_timeout(nxt);
1634 nxt->flags |= REQ_F_QUEUE_TIMEOUT;
1638 * Drop reference to request, return next in chain (if there is one) if this
1639 * was the last reference to this request.
1641 __attribute__((nonnull))
1642 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1644 if (refcount_dec_and_test(&req->refs)) {
1645 io_req_find_next(req, nxtptr);
1650 static void io_put_req(struct io_kiocb *req)
1652 if (refcount_dec_and_test(&req->refs))
1656 static void io_steal_work(struct io_kiocb *req,
1657 struct io_wq_work **workptr)
1660 * It's in an io-wq worker, so there always should be at least
1661 * one reference, which will be dropped in io_put_work() just
1662 * after the current handler returns.
1664 * It also means, that if the counter dropped to 1, then there is
1665 * no asynchronous users left, so it's safe to steal the next work.
1667 if (refcount_read(&req->refs) == 1) {
1668 struct io_kiocb *nxt = NULL;
1670 io_req_find_next(req, &nxt);
1672 io_wq_assign_next(workptr, nxt);
1677 * Must only be used if we don't need to care about links, usually from
1678 * within the completion handling itself.
1680 static void __io_double_put_req(struct io_kiocb *req)
1682 /* drop both submit and complete references */
1683 if (refcount_sub_and_test(2, &req->refs))
1687 static void io_double_put_req(struct io_kiocb *req)
1689 /* drop both submit and complete references */
1690 if (refcount_sub_and_test(2, &req->refs))
1694 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1696 struct io_rings *rings = ctx->rings;
1698 if (test_bit(0, &ctx->cq_check_overflow)) {
1700 * noflush == true is from the waitqueue handler, just ensure
1701 * we wake up the task, and the next invocation will flush the
1702 * entries. We cannot safely to it from here.
1704 if (noflush && !list_empty(&ctx->cq_overflow_list))
1707 io_cqring_overflow_flush(ctx, false);
1710 /* See comment at the top of this file */
1712 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1715 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1717 struct io_rings *rings = ctx->rings;
1719 /* make sure SQ entry isn't read before tail */
1720 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1723 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1725 if ((req->flags & REQ_F_LINK_HEAD) || io_is_fallback_req(req))
1728 if (req->file || req->io)
1731 rb->reqs[rb->to_free++] = req;
1732 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1733 io_free_req_many(req->ctx, rb);
1737 static int io_put_kbuf(struct io_kiocb *req)
1739 struct io_buffer *kbuf;
1742 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
1743 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1744 cflags |= IORING_CQE_F_BUFFER;
1750 static void io_iopoll_queue(struct list_head *again)
1752 struct io_kiocb *req;
1755 req = list_first_entry(again, struct io_kiocb, list);
1756 list_del(&req->list);
1758 /* shouldn't happen unless io_uring is dying, cancel reqs */
1759 if (unlikely(!current->mm)) {
1760 io_complete_rw_common(&req->rw.kiocb, -EAGAIN);
1765 refcount_inc(&req->refs);
1766 io_queue_async_work(req);
1767 } while (!list_empty(again));
1771 * Find and free completed poll iocbs
1773 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1774 struct list_head *done)
1776 struct req_batch rb;
1777 struct io_kiocb *req;
1780 /* order with ->result store in io_complete_rw_iopoll() */
1783 rb.to_free = rb.need_iter = 0;
1784 while (!list_empty(done)) {
1787 req = list_first_entry(done, struct io_kiocb, list);
1788 if (READ_ONCE(req->result) == -EAGAIN) {
1789 req->iopoll_completed = 0;
1790 list_move_tail(&req->list, &again);
1793 list_del(&req->list);
1795 if (req->flags & REQ_F_BUFFER_SELECTED)
1796 cflags = io_put_kbuf(req);
1798 __io_cqring_fill_event(req, req->result, cflags);
1801 if (refcount_dec_and_test(&req->refs) &&
1802 !io_req_multi_free(&rb, req))
1806 io_commit_cqring(ctx);
1807 if (ctx->flags & IORING_SETUP_SQPOLL)
1808 io_cqring_ev_posted(ctx);
1809 io_free_req_many(ctx, &rb);
1811 if (!list_empty(&again))
1812 io_iopoll_queue(&again);
1815 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1818 struct io_kiocb *req, *tmp;
1824 * Only spin for completions if we don't have multiple devices hanging
1825 * off our complete list, and we're under the requested amount.
1827 spin = !ctx->poll_multi_file && *nr_events < min;
1830 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1831 struct kiocb *kiocb = &req->rw.kiocb;
1834 * Move completed and retryable entries to our local lists.
1835 * If we find a request that requires polling, break out
1836 * and complete those lists first, if we have entries there.
1838 if (READ_ONCE(req->iopoll_completed)) {
1839 list_move_tail(&req->list, &done);
1842 if (!list_empty(&done))
1845 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1854 if (!list_empty(&done))
1855 io_iopoll_complete(ctx, nr_events, &done);
1861 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1862 * non-spinning poll check - we'll still enter the driver poll loop, but only
1863 * as a non-spinning completion check.
1865 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1868 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1871 ret = io_do_iopoll(ctx, nr_events, min);
1874 if (!min || *nr_events >= min)
1882 * We can't just wait for polled events to come to us, we have to actively
1883 * find and complete them.
1885 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1887 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1890 mutex_lock(&ctx->uring_lock);
1891 while (!list_empty(&ctx->poll_list)) {
1892 unsigned int nr_events = 0;
1894 io_iopoll_getevents(ctx, &nr_events, 1);
1897 * Ensure we allow local-to-the-cpu processing to take place,
1898 * in this case we need to ensure that we reap all events.
1902 mutex_unlock(&ctx->uring_lock);
1905 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1908 int iters = 0, ret = 0;
1911 * We disallow the app entering submit/complete with polling, but we
1912 * still need to lock the ring to prevent racing with polled issue
1913 * that got punted to a workqueue.
1915 mutex_lock(&ctx->uring_lock);
1920 * Don't enter poll loop if we already have events pending.
1921 * If we do, we can potentially be spinning for commands that
1922 * already triggered a CQE (eg in error).
1924 if (io_cqring_events(ctx, false))
1928 * If a submit got punted to a workqueue, we can have the
1929 * application entering polling for a command before it gets
1930 * issued. That app will hold the uring_lock for the duration
1931 * of the poll right here, so we need to take a breather every
1932 * now and then to ensure that the issue has a chance to add
1933 * the poll to the issued list. Otherwise we can spin here
1934 * forever, while the workqueue is stuck trying to acquire the
1937 if (!(++iters & 7)) {
1938 mutex_unlock(&ctx->uring_lock);
1939 mutex_lock(&ctx->uring_lock);
1942 if (*nr_events < min)
1943 tmin = min - *nr_events;
1945 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1949 } while (min && !*nr_events && !need_resched());
1951 mutex_unlock(&ctx->uring_lock);
1955 static void kiocb_end_write(struct io_kiocb *req)
1958 * Tell lockdep we inherited freeze protection from submission
1961 if (req->flags & REQ_F_ISREG) {
1962 struct inode *inode = file_inode(req->file);
1964 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1966 file_end_write(req->file);
1969 static inline void req_set_fail_links(struct io_kiocb *req)
1971 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1972 req->flags |= REQ_F_FAIL_LINK;
1975 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1977 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1980 if (kiocb->ki_flags & IOCB_WRITE)
1981 kiocb_end_write(req);
1983 if (res != req->result)
1984 req_set_fail_links(req);
1985 if (req->flags & REQ_F_BUFFER_SELECTED)
1986 cflags = io_put_kbuf(req);
1987 __io_cqring_add_event(req, res, cflags);
1990 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1992 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1994 io_complete_rw_common(kiocb, res);
1998 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2000 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2002 if (kiocb->ki_flags & IOCB_WRITE)
2003 kiocb_end_write(req);
2005 if (res != -EAGAIN && res != req->result)
2006 req_set_fail_links(req);
2008 WRITE_ONCE(req->result, res);
2009 /* order with io_poll_complete() checking ->result */
2011 WRITE_ONCE(req->iopoll_completed, 1);
2015 * After the iocb has been issued, it's safe to be found on the poll list.
2016 * Adding the kiocb to the list AFTER submission ensures that we don't
2017 * find it from a io_iopoll_getevents() thread before the issuer is done
2018 * accessing the kiocb cookie.
2020 static void io_iopoll_req_issued(struct io_kiocb *req)
2022 struct io_ring_ctx *ctx = req->ctx;
2025 * Track whether we have multiple files in our lists. This will impact
2026 * how we do polling eventually, not spinning if we're on potentially
2027 * different devices.
2029 if (list_empty(&ctx->poll_list)) {
2030 ctx->poll_multi_file = false;
2031 } else if (!ctx->poll_multi_file) {
2032 struct io_kiocb *list_req;
2034 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
2036 if (list_req->file != req->file)
2037 ctx->poll_multi_file = true;
2041 * For fast devices, IO may have already completed. If it has, add
2042 * it to the front so we find it first.
2044 if (READ_ONCE(req->iopoll_completed))
2045 list_add(&req->list, &ctx->poll_list);
2047 list_add_tail(&req->list, &ctx->poll_list);
2049 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2050 wq_has_sleeper(&ctx->sqo_wait))
2051 wake_up(&ctx->sqo_wait);
2054 static void __io_state_file_put(struct io_submit_state *state)
2056 int diff = state->has_refs - state->used_refs;
2059 fput_many(state->file, diff);
2063 static inline void io_state_file_put(struct io_submit_state *state)
2066 __io_state_file_put(state);
2070 * Get as many references to a file as we have IOs left in this submission,
2071 * assuming most submissions are for one file, or at least that each file
2072 * has more than one submission.
2074 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2080 if (state->fd == fd) {
2085 __io_state_file_put(state);
2087 state->file = fget_many(fd, state->ios_left);
2092 state->has_refs = state->ios_left;
2093 state->used_refs = 1;
2099 * If we tracked the file through the SCM inflight mechanism, we could support
2100 * any file. For now, just ensure that anything potentially problematic is done
2103 static bool io_file_supports_async(struct file *file, int rw)
2105 umode_t mode = file_inode(file)->i_mode;
2107 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
2109 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
2112 /* any ->read/write should understand O_NONBLOCK */
2113 if (file->f_flags & O_NONBLOCK)
2116 if (!(file->f_mode & FMODE_NOWAIT))
2120 return file->f_op->read_iter != NULL;
2122 return file->f_op->write_iter != NULL;
2125 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2126 bool force_nonblock)
2128 struct io_ring_ctx *ctx = req->ctx;
2129 struct kiocb *kiocb = &req->rw.kiocb;
2133 if (S_ISREG(file_inode(req->file)->i_mode))
2134 req->flags |= REQ_F_ISREG;
2136 kiocb->ki_pos = READ_ONCE(sqe->off);
2137 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2138 req->flags |= REQ_F_CUR_POS;
2139 kiocb->ki_pos = req->file->f_pos;
2141 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2142 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2143 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2147 ioprio = READ_ONCE(sqe->ioprio);
2149 ret = ioprio_check_cap(ioprio);
2153 kiocb->ki_ioprio = ioprio;
2155 kiocb->ki_ioprio = get_current_ioprio();
2157 /* don't allow async punt if RWF_NOWAIT was requested */
2158 if (kiocb->ki_flags & IOCB_NOWAIT)
2159 req->flags |= REQ_F_NOWAIT;
2162 kiocb->ki_flags |= IOCB_NOWAIT;
2164 if (ctx->flags & IORING_SETUP_IOPOLL) {
2165 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2166 !kiocb->ki_filp->f_op->iopoll)
2169 kiocb->ki_flags |= IOCB_HIPRI;
2170 kiocb->ki_complete = io_complete_rw_iopoll;
2172 req->iopoll_completed = 0;
2174 if (kiocb->ki_flags & IOCB_HIPRI)
2176 kiocb->ki_complete = io_complete_rw;
2179 req->rw.addr = READ_ONCE(sqe->addr);
2180 req->rw.len = READ_ONCE(sqe->len);
2181 req->buf_index = READ_ONCE(sqe->buf_index);
2185 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2191 case -ERESTARTNOINTR:
2192 case -ERESTARTNOHAND:
2193 case -ERESTART_RESTARTBLOCK:
2195 * We can't just restart the syscall, since previously
2196 * submitted sqes may already be in progress. Just fail this
2202 kiocb->ki_complete(kiocb, ret, 0);
2206 static void kiocb_done(struct kiocb *kiocb, ssize_t ret)
2208 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2210 if (req->flags & REQ_F_CUR_POS)
2211 req->file->f_pos = kiocb->ki_pos;
2212 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2213 io_complete_rw(kiocb, ret, 0);
2215 io_rw_done(kiocb, ret);
2218 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2219 struct iov_iter *iter)
2221 struct io_ring_ctx *ctx = req->ctx;
2222 size_t len = req->rw.len;
2223 struct io_mapped_ubuf *imu;
2224 u16 index, buf_index;
2228 /* attempt to use fixed buffers without having provided iovecs */
2229 if (unlikely(!ctx->user_bufs))
2232 buf_index = req->buf_index;
2233 if (unlikely(buf_index >= ctx->nr_user_bufs))
2236 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2237 imu = &ctx->user_bufs[index];
2238 buf_addr = req->rw.addr;
2241 if (buf_addr + len < buf_addr)
2243 /* not inside the mapped region */
2244 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2248 * May not be a start of buffer, set size appropriately
2249 * and advance us to the beginning.
2251 offset = buf_addr - imu->ubuf;
2252 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2256 * Don't use iov_iter_advance() here, as it's really slow for
2257 * using the latter parts of a big fixed buffer - it iterates
2258 * over each segment manually. We can cheat a bit here, because
2261 * 1) it's a BVEC iter, we set it up
2262 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2263 * first and last bvec
2265 * So just find our index, and adjust the iterator afterwards.
2266 * If the offset is within the first bvec (or the whole first
2267 * bvec, just use iov_iter_advance(). This makes it easier
2268 * since we can just skip the first segment, which may not
2269 * be PAGE_SIZE aligned.
2271 const struct bio_vec *bvec = imu->bvec;
2273 if (offset <= bvec->bv_len) {
2274 iov_iter_advance(iter, offset);
2276 unsigned long seg_skip;
2278 /* skip first vec */
2279 offset -= bvec->bv_len;
2280 seg_skip = 1 + (offset >> PAGE_SHIFT);
2282 iter->bvec = bvec + seg_skip;
2283 iter->nr_segs -= seg_skip;
2284 iter->count -= bvec->bv_len + offset;
2285 iter->iov_offset = offset & ~PAGE_MASK;
2292 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2295 mutex_unlock(&ctx->uring_lock);
2298 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2301 * "Normal" inline submissions always hold the uring_lock, since we
2302 * grab it from the system call. Same is true for the SQPOLL offload.
2303 * The only exception is when we've detached the request and issue it
2304 * from an async worker thread, grab the lock for that case.
2307 mutex_lock(&ctx->uring_lock);
2310 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2311 int bgid, struct io_buffer *kbuf,
2314 struct io_buffer *head;
2316 if (req->flags & REQ_F_BUFFER_SELECTED)
2319 io_ring_submit_lock(req->ctx, needs_lock);
2321 lockdep_assert_held(&req->ctx->uring_lock);
2323 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2325 if (!list_empty(&head->list)) {
2326 kbuf = list_last_entry(&head->list, struct io_buffer,
2328 list_del(&kbuf->list);
2331 idr_remove(&req->ctx->io_buffer_idr, bgid);
2333 if (*len > kbuf->len)
2336 kbuf = ERR_PTR(-ENOBUFS);
2339 io_ring_submit_unlock(req->ctx, needs_lock);
2344 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2347 struct io_buffer *kbuf;
2350 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2351 bgid = req->buf_index;
2352 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2355 req->rw.addr = (u64) (unsigned long) kbuf;
2356 req->flags |= REQ_F_BUFFER_SELECTED;
2357 return u64_to_user_ptr(kbuf->addr);
2360 #ifdef CONFIG_COMPAT
2361 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2364 struct compat_iovec __user *uiov;
2365 compat_ssize_t clen;
2369 uiov = u64_to_user_ptr(req->rw.addr);
2370 if (!access_ok(uiov, sizeof(*uiov)))
2372 if (__get_user(clen, &uiov->iov_len))
2378 buf = io_rw_buffer_select(req, &len, needs_lock);
2380 return PTR_ERR(buf);
2381 iov[0].iov_base = buf;
2382 iov[0].iov_len = (compat_size_t) len;
2387 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2390 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2394 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2397 len = iov[0].iov_len;
2400 buf = io_rw_buffer_select(req, &len, needs_lock);
2402 return PTR_ERR(buf);
2403 iov[0].iov_base = buf;
2404 iov[0].iov_len = len;
2408 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2411 if (req->flags & REQ_F_BUFFER_SELECTED) {
2412 struct io_buffer *kbuf;
2414 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2415 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2416 iov[0].iov_len = kbuf->len;
2421 else if (req->rw.len > 1)
2424 #ifdef CONFIG_COMPAT
2425 if (req->ctx->compat)
2426 return io_compat_import(req, iov, needs_lock);
2429 return __io_iov_buffer_select(req, iov, needs_lock);
2432 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2433 struct iovec **iovec, struct iov_iter *iter,
2436 void __user *buf = u64_to_user_ptr(req->rw.addr);
2437 size_t sqe_len = req->rw.len;
2441 opcode = req->opcode;
2442 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2444 return io_import_fixed(req, rw, iter);
2447 /* buffer index only valid with fixed read/write, or buffer select */
2448 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2451 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2452 if (req->flags & REQ_F_BUFFER_SELECT) {
2453 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2456 return PTR_ERR(buf);
2458 req->rw.len = sqe_len;
2461 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2463 return ret < 0 ? ret : sqe_len;
2467 struct io_async_rw *iorw = &req->io->rw;
2470 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2471 if (iorw->iov == iorw->fast_iov)
2476 if (req->flags & REQ_F_BUFFER_SELECT) {
2477 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2479 ret = (*iovec)->iov_len;
2480 iov_iter_init(iter, rw, *iovec, 1, ret);
2486 #ifdef CONFIG_COMPAT
2487 if (req->ctx->compat)
2488 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2492 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2496 * For files that don't have ->read_iter() and ->write_iter(), handle them
2497 * by looping over ->read() or ->write() manually.
2499 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2500 struct iov_iter *iter)
2505 * Don't support polled IO through this interface, and we can't
2506 * support non-blocking either. For the latter, this just causes
2507 * the kiocb to be handled from an async context.
2509 if (kiocb->ki_flags & IOCB_HIPRI)
2511 if (kiocb->ki_flags & IOCB_NOWAIT)
2514 while (iov_iter_count(iter)) {
2518 if (!iov_iter_is_bvec(iter)) {
2519 iovec = iov_iter_iovec(iter);
2521 /* fixed buffers import bvec */
2522 iovec.iov_base = kmap(iter->bvec->bv_page)
2524 iovec.iov_len = min(iter->count,
2525 iter->bvec->bv_len - iter->iov_offset);
2529 nr = file->f_op->read(file, iovec.iov_base,
2530 iovec.iov_len, &kiocb->ki_pos);
2532 nr = file->f_op->write(file, iovec.iov_base,
2533 iovec.iov_len, &kiocb->ki_pos);
2536 if (iov_iter_is_bvec(iter))
2537 kunmap(iter->bvec->bv_page);
2545 if (nr != iovec.iov_len)
2547 iov_iter_advance(iter, nr);
2553 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2554 struct iovec *iovec, struct iovec *fast_iov,
2555 struct iov_iter *iter)
2557 req->io->rw.nr_segs = iter->nr_segs;
2558 req->io->rw.size = io_size;
2559 req->io->rw.iov = iovec;
2560 if (!req->io->rw.iov) {
2561 req->io->rw.iov = req->io->rw.fast_iov;
2562 if (req->io->rw.iov != fast_iov)
2563 memcpy(req->io->rw.iov, fast_iov,
2564 sizeof(struct iovec) * iter->nr_segs);
2566 req->flags |= REQ_F_NEED_CLEANUP;
2570 static inline int __io_alloc_async_ctx(struct io_kiocb *req)
2572 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2573 return req->io == NULL;
2576 static int io_alloc_async_ctx(struct io_kiocb *req)
2578 if (!io_op_defs[req->opcode].async_ctx)
2581 return __io_alloc_async_ctx(req);
2584 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2585 struct iovec *iovec, struct iovec *fast_iov,
2586 struct iov_iter *iter)
2588 if (!io_op_defs[req->opcode].async_ctx)
2591 if (__io_alloc_async_ctx(req))
2594 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2599 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2600 bool force_nonblock)
2602 struct io_async_ctx *io;
2603 struct iov_iter iter;
2606 ret = io_prep_rw(req, sqe, force_nonblock);
2610 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2613 /* either don't need iovec imported or already have it */
2614 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2618 io->rw.iov = io->rw.fast_iov;
2620 ret = io_import_iovec(READ, req, &io->rw.iov, &iter, !force_nonblock);
2625 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2629 static int io_read(struct io_kiocb *req, bool force_nonblock)
2631 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2632 struct kiocb *kiocb = &req->rw.kiocb;
2633 struct iov_iter iter;
2635 ssize_t io_size, ret;
2637 ret = io_import_iovec(READ, req, &iovec, &iter, !force_nonblock);
2641 /* Ensure we clear previously set non-block flag */
2642 if (!force_nonblock)
2643 kiocb->ki_flags &= ~IOCB_NOWAIT;
2647 if (req->flags & REQ_F_LINK_HEAD)
2648 req->result = io_size;
2651 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2652 * we know to async punt it even if it was opened O_NONBLOCK
2654 if (force_nonblock && !io_file_supports_async(req->file, READ))
2657 iov_count = iov_iter_count(&iter);
2658 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2662 if (req->file->f_op->read_iter)
2663 ret2 = call_read_iter(req->file, kiocb, &iter);
2665 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2667 /* Catch -EAGAIN return for forced non-blocking submission */
2668 if (!force_nonblock || ret2 != -EAGAIN) {
2669 kiocb_done(kiocb, ret2);
2672 ret = io_setup_async_rw(req, io_size, iovec,
2673 inline_vecs, &iter);
2676 /* any defer here is final, must blocking retry */
2677 if (!(req->flags & REQ_F_NOWAIT) &&
2678 !file_can_poll(req->file))
2679 req->flags |= REQ_F_MUST_PUNT;
2684 if (!(req->flags & REQ_F_NEED_CLEANUP))
2689 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2690 bool force_nonblock)
2692 struct io_async_ctx *io;
2693 struct iov_iter iter;
2696 ret = io_prep_rw(req, sqe, force_nonblock);
2700 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2703 req->fsize = rlimit(RLIMIT_FSIZE);
2705 /* either don't need iovec imported or already have it */
2706 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2710 io->rw.iov = io->rw.fast_iov;
2712 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter, !force_nonblock);
2717 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2721 static int io_write(struct io_kiocb *req, bool force_nonblock)
2723 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2724 struct kiocb *kiocb = &req->rw.kiocb;
2725 struct iov_iter iter;
2727 ssize_t ret, io_size;
2729 ret = io_import_iovec(WRITE, req, &iovec, &iter, !force_nonblock);
2733 /* Ensure we clear previously set non-block flag */
2734 if (!force_nonblock)
2735 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2739 if (req->flags & REQ_F_LINK_HEAD)
2740 req->result = io_size;
2743 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2744 * we know to async punt it even if it was opened O_NONBLOCK
2746 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
2749 /* file path doesn't support NOWAIT for non-direct_IO */
2750 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2751 (req->flags & REQ_F_ISREG))
2754 iov_count = iov_iter_count(&iter);
2755 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2760 * Open-code file_start_write here to grab freeze protection,
2761 * which will be released by another thread in
2762 * io_complete_rw(). Fool lockdep by telling it the lock got
2763 * released so that it doesn't complain about the held lock when
2764 * we return to userspace.
2766 if (req->flags & REQ_F_ISREG) {
2767 __sb_start_write(file_inode(req->file)->i_sb,
2768 SB_FREEZE_WRITE, true);
2769 __sb_writers_release(file_inode(req->file)->i_sb,
2772 kiocb->ki_flags |= IOCB_WRITE;
2774 if (!force_nonblock)
2775 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
2777 if (req->file->f_op->write_iter)
2778 ret2 = call_write_iter(req->file, kiocb, &iter);
2780 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2782 if (!force_nonblock)
2783 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
2786 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
2787 * retry them without IOCB_NOWAIT.
2789 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2791 if (!force_nonblock || ret2 != -EAGAIN) {
2792 kiocb_done(kiocb, ret2);
2795 ret = io_setup_async_rw(req, io_size, iovec,
2796 inline_vecs, &iter);
2799 /* any defer here is final, must blocking retry */
2800 if (!(req->flags & REQ_F_NOWAIT) &&
2801 !file_can_poll(req->file))
2802 req->flags |= REQ_F_MUST_PUNT;
2807 if (!(req->flags & REQ_F_NEED_CLEANUP))
2812 static int __io_splice_prep(struct io_kiocb *req,
2813 const struct io_uring_sqe *sqe)
2815 struct io_splice* sp = &req->splice;
2816 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
2819 if (req->flags & REQ_F_NEED_CLEANUP)
2821 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2825 sp->len = READ_ONCE(sqe->len);
2826 sp->flags = READ_ONCE(sqe->splice_flags);
2828 if (unlikely(sp->flags & ~valid_flags))
2831 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
2832 (sp->flags & SPLICE_F_FD_IN_FIXED));
2835 req->flags |= REQ_F_NEED_CLEANUP;
2837 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
2839 * Splice operation will be punted aync, and here need to
2840 * modify io_wq_work.flags, so initialize io_wq_work firstly.
2842 io_req_init_async(req);
2843 req->work.flags |= IO_WQ_WORK_UNBOUND;
2849 static int io_tee_prep(struct io_kiocb *req,
2850 const struct io_uring_sqe *sqe)
2852 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
2854 return __io_splice_prep(req, sqe);
2857 static int io_tee(struct io_kiocb *req, bool force_nonblock)
2859 struct io_splice *sp = &req->splice;
2860 struct file *in = sp->file_in;
2861 struct file *out = sp->file_out;
2862 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
2868 ret = do_tee(in, out, sp->len, flags);
2870 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
2871 req->flags &= ~REQ_F_NEED_CLEANUP;
2873 io_cqring_add_event(req, ret);
2875 req_set_fail_links(req);
2880 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2882 struct io_splice* sp = &req->splice;
2884 sp->off_in = READ_ONCE(sqe->splice_off_in);
2885 sp->off_out = READ_ONCE(sqe->off);
2886 return __io_splice_prep(req, sqe);
2889 static int io_splice(struct io_kiocb *req, bool force_nonblock)
2891 struct io_splice *sp = &req->splice;
2892 struct file *in = sp->file_in;
2893 struct file *out = sp->file_out;
2894 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
2895 loff_t *poff_in, *poff_out;
2901 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
2902 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
2905 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
2907 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
2908 req->flags &= ~REQ_F_NEED_CLEANUP;
2910 io_cqring_add_event(req, ret);
2912 req_set_fail_links(req);
2918 * IORING_OP_NOP just posts a completion event, nothing else.
2920 static int io_nop(struct io_kiocb *req)
2922 struct io_ring_ctx *ctx = req->ctx;
2924 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2927 io_cqring_add_event(req, 0);
2932 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2934 struct io_ring_ctx *ctx = req->ctx;
2939 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2941 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2944 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2945 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2948 req->sync.off = READ_ONCE(sqe->off);
2949 req->sync.len = READ_ONCE(sqe->len);
2953 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
2955 loff_t end = req->sync.off + req->sync.len;
2958 /* fsync always requires a blocking context */
2962 ret = vfs_fsync_range(req->file, req->sync.off,
2963 end > 0 ? end : LLONG_MAX,
2964 req->sync.flags & IORING_FSYNC_DATASYNC);
2966 req_set_fail_links(req);
2967 io_cqring_add_event(req, ret);
2972 static int io_fallocate_prep(struct io_kiocb *req,
2973 const struct io_uring_sqe *sqe)
2975 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2977 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2980 req->sync.off = READ_ONCE(sqe->off);
2981 req->sync.len = READ_ONCE(sqe->addr);
2982 req->sync.mode = READ_ONCE(sqe->len);
2983 req->fsize = rlimit(RLIMIT_FSIZE);
2987 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
2991 /* fallocate always requiring blocking context */
2995 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
2996 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2998 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3000 req_set_fail_links(req);
3001 io_cqring_add_event(req, ret);
3006 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3008 const char __user *fname;
3011 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3013 if (unlikely(sqe->ioprio || sqe->buf_index))
3015 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3018 /* open.how should be already initialised */
3019 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3020 req->open.how.flags |= O_LARGEFILE;
3022 req->open.dfd = READ_ONCE(sqe->fd);
3023 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3024 req->open.filename = getname(fname);
3025 if (IS_ERR(req->open.filename)) {
3026 ret = PTR_ERR(req->open.filename);
3027 req->open.filename = NULL;
3030 req->open.nofile = rlimit(RLIMIT_NOFILE);
3031 req->flags |= REQ_F_NEED_CLEANUP;
3035 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3039 if (req->flags & REQ_F_NEED_CLEANUP)
3041 mode = READ_ONCE(sqe->len);
3042 flags = READ_ONCE(sqe->open_flags);
3043 req->open.how = build_open_how(flags, mode);
3044 return __io_openat_prep(req, sqe);
3047 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3049 struct open_how __user *how;
3053 if (req->flags & REQ_F_NEED_CLEANUP)
3055 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3056 len = READ_ONCE(sqe->len);
3057 if (len < OPEN_HOW_SIZE_VER0)
3060 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3065 return __io_openat_prep(req, sqe);
3068 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3070 struct open_flags op;
3077 ret = build_open_flags(&req->open.how, &op);
3081 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3085 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3088 ret = PTR_ERR(file);
3090 fsnotify_open(file);
3091 fd_install(ret, file);
3094 putname(req->open.filename);
3095 req->flags &= ~REQ_F_NEED_CLEANUP;
3097 req_set_fail_links(req);
3098 io_cqring_add_event(req, ret);
3103 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3105 return io_openat2(req, force_nonblock);
3108 static int io_remove_buffers_prep(struct io_kiocb *req,
3109 const struct io_uring_sqe *sqe)
3111 struct io_provide_buf *p = &req->pbuf;
3114 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3117 tmp = READ_ONCE(sqe->fd);
3118 if (!tmp || tmp > USHRT_MAX)
3121 memset(p, 0, sizeof(*p));
3123 p->bgid = READ_ONCE(sqe->buf_group);
3127 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3128 int bgid, unsigned nbufs)
3132 /* shouldn't happen */
3136 /* the head kbuf is the list itself */
3137 while (!list_empty(&buf->list)) {
3138 struct io_buffer *nxt;
3140 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3141 list_del(&nxt->list);
3148 idr_remove(&ctx->io_buffer_idr, bgid);
3153 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock)
3155 struct io_provide_buf *p = &req->pbuf;
3156 struct io_ring_ctx *ctx = req->ctx;
3157 struct io_buffer *head;
3160 io_ring_submit_lock(ctx, !force_nonblock);
3162 lockdep_assert_held(&ctx->uring_lock);
3165 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3167 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3169 io_ring_submit_lock(ctx, !force_nonblock);
3171 req_set_fail_links(req);
3172 io_cqring_add_event(req, ret);
3177 static int io_provide_buffers_prep(struct io_kiocb *req,
3178 const struct io_uring_sqe *sqe)
3180 struct io_provide_buf *p = &req->pbuf;
3183 if (sqe->ioprio || sqe->rw_flags)
3186 tmp = READ_ONCE(sqe->fd);
3187 if (!tmp || tmp > USHRT_MAX)
3190 p->addr = READ_ONCE(sqe->addr);
3191 p->len = READ_ONCE(sqe->len);
3193 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3196 p->bgid = READ_ONCE(sqe->buf_group);
3197 tmp = READ_ONCE(sqe->off);
3198 if (tmp > USHRT_MAX)
3204 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3206 struct io_buffer *buf;
3207 u64 addr = pbuf->addr;
3208 int i, bid = pbuf->bid;
3210 for (i = 0; i < pbuf->nbufs; i++) {
3211 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3216 buf->len = pbuf->len;
3221 INIT_LIST_HEAD(&buf->list);
3224 list_add_tail(&buf->list, &(*head)->list);
3228 return i ? i : -ENOMEM;
3231 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock)
3233 struct io_provide_buf *p = &req->pbuf;
3234 struct io_ring_ctx *ctx = req->ctx;
3235 struct io_buffer *head, *list;
3238 io_ring_submit_lock(ctx, !force_nonblock);
3240 lockdep_assert_held(&ctx->uring_lock);
3242 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3244 ret = io_add_buffers(p, &head);
3249 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3252 __io_remove_buffers(ctx, head, p->bgid, -1U);
3257 io_ring_submit_unlock(ctx, !force_nonblock);
3259 req_set_fail_links(req);
3260 io_cqring_add_event(req, ret);
3265 static int io_epoll_ctl_prep(struct io_kiocb *req,
3266 const struct io_uring_sqe *sqe)
3268 #if defined(CONFIG_EPOLL)
3269 if (sqe->ioprio || sqe->buf_index)
3271 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3274 req->epoll.epfd = READ_ONCE(sqe->fd);
3275 req->epoll.op = READ_ONCE(sqe->len);
3276 req->epoll.fd = READ_ONCE(sqe->off);
3278 if (ep_op_has_event(req->epoll.op)) {
3279 struct epoll_event __user *ev;
3281 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3282 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3292 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock)
3294 #if defined(CONFIG_EPOLL)
3295 struct io_epoll *ie = &req->epoll;
3298 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3299 if (force_nonblock && ret == -EAGAIN)
3303 req_set_fail_links(req);
3304 io_cqring_add_event(req, ret);
3312 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3314 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3315 if (sqe->ioprio || sqe->buf_index || sqe->off)
3317 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3320 req->madvise.addr = READ_ONCE(sqe->addr);
3321 req->madvise.len = READ_ONCE(sqe->len);
3322 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3329 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3331 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3332 struct io_madvise *ma = &req->madvise;
3338 ret = do_madvise(ma->addr, ma->len, ma->advice);
3340 req_set_fail_links(req);
3341 io_cqring_add_event(req, ret);
3349 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3351 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3353 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3356 req->fadvise.offset = READ_ONCE(sqe->off);
3357 req->fadvise.len = READ_ONCE(sqe->len);
3358 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3362 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3364 struct io_fadvise *fa = &req->fadvise;
3367 if (force_nonblock) {
3368 switch (fa->advice) {
3369 case POSIX_FADV_NORMAL:
3370 case POSIX_FADV_RANDOM:
3371 case POSIX_FADV_SEQUENTIAL:
3378 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3380 req_set_fail_links(req);
3381 io_cqring_add_event(req, ret);
3386 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3388 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3390 if (sqe->ioprio || sqe->buf_index)
3392 if (req->flags & REQ_F_FIXED_FILE)
3395 req->statx.dfd = READ_ONCE(sqe->fd);
3396 req->statx.mask = READ_ONCE(sqe->len);
3397 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
3398 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3399 req->statx.flags = READ_ONCE(sqe->statx_flags);
3404 static int io_statx(struct io_kiocb *req, bool force_nonblock)
3406 struct io_statx *ctx = &req->statx;
3409 if (force_nonblock) {
3410 /* only need file table for an actual valid fd */
3411 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
3412 req->flags |= REQ_F_NO_FILE_TABLE;
3416 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
3420 req_set_fail_links(req);
3421 io_cqring_add_event(req, ret);
3426 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3429 * If we queue this for async, it must not be cancellable. That would
3430 * leave the 'file' in an undeterminate state, and here need to modify
3431 * io_wq_work.flags, so initialize io_wq_work firstly.
3433 io_req_init_async(req);
3434 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
3436 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3438 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
3439 sqe->rw_flags || sqe->buf_index)
3441 if (req->flags & REQ_F_FIXED_FILE)
3444 req->close.fd = READ_ONCE(sqe->fd);
3445 if ((req->file && req->file->f_op == &io_uring_fops) ||
3446 req->close.fd == req->ctx->ring_fd)
3449 req->close.put_file = NULL;
3453 static int io_close(struct io_kiocb *req, bool force_nonblock)
3455 struct io_close *close = &req->close;
3458 /* might be already done during nonblock submission */
3459 if (!close->put_file) {
3460 ret = __close_fd_get_file(close->fd, &close->put_file);
3462 return (ret == -ENOENT) ? -EBADF : ret;
3465 /* if the file has a flush method, be safe and punt to async */
3466 if (close->put_file->f_op->flush && force_nonblock) {
3467 /* avoid grabbing files - we don't need the files */
3468 req->flags |= REQ_F_NO_FILE_TABLE | REQ_F_MUST_PUNT;
3472 /* No ->flush() or already async, safely close from here */
3473 ret = filp_close(close->put_file, req->work.files);
3475 req_set_fail_links(req);
3476 io_cqring_add_event(req, ret);
3477 fput(close->put_file);
3478 close->put_file = NULL;
3483 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3485 struct io_ring_ctx *ctx = req->ctx;
3490 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3492 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3495 req->sync.off = READ_ONCE(sqe->off);
3496 req->sync.len = READ_ONCE(sqe->len);
3497 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
3501 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
3505 /* sync_file_range always requires a blocking context */
3509 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
3512 req_set_fail_links(req);
3513 io_cqring_add_event(req, ret);
3518 #if defined(CONFIG_NET)
3519 static int io_setup_async_msg(struct io_kiocb *req,
3520 struct io_async_msghdr *kmsg)
3524 if (io_alloc_async_ctx(req)) {
3525 if (kmsg->iov != kmsg->fast_iov)
3529 req->flags |= REQ_F_NEED_CLEANUP;
3530 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3534 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3536 struct io_sr_msg *sr = &req->sr_msg;
3537 struct io_async_ctx *io = req->io;
3540 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3543 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3544 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3545 sr->len = READ_ONCE(sqe->len);
3547 #ifdef CONFIG_COMPAT
3548 if (req->ctx->compat)
3549 sr->msg_flags |= MSG_CMSG_COMPAT;
3552 if (!io || req->opcode == IORING_OP_SEND)
3554 /* iovec is already imported */
3555 if (req->flags & REQ_F_NEED_CLEANUP)
3558 io->msg.msg.msg_name = &io->msg.addr;
3559 io->msg.iov = io->msg.fast_iov;
3560 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3563 req->flags |= REQ_F_NEED_CLEANUP;
3567 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
3569 struct io_async_msghdr *kmsg = NULL;
3570 struct socket *sock;
3573 sock = sock_from_file(req->file, &ret);
3575 struct io_async_ctx io;
3579 kmsg = &req->io->msg;
3580 kmsg->msg.msg_name = &req->io->msg.addr;
3581 /* if iov is set, it's allocated already */
3583 kmsg->iov = kmsg->fast_iov;
3584 kmsg->msg.msg_iter.iov = kmsg->iov;
3586 struct io_sr_msg *sr = &req->sr_msg;
3589 kmsg->msg.msg_name = &io.msg.addr;
3591 io.msg.iov = io.msg.fast_iov;
3592 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3593 sr->msg_flags, &io.msg.iov);
3598 flags = req->sr_msg.msg_flags;
3599 if (flags & MSG_DONTWAIT)
3600 req->flags |= REQ_F_NOWAIT;
3601 else if (force_nonblock)
3602 flags |= MSG_DONTWAIT;
3604 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3605 if (force_nonblock && ret == -EAGAIN)
3606 return io_setup_async_msg(req, kmsg);
3607 if (ret == -ERESTARTSYS)
3611 if (kmsg && kmsg->iov != kmsg->fast_iov)
3613 req->flags &= ~REQ_F_NEED_CLEANUP;
3614 io_cqring_add_event(req, ret);
3616 req_set_fail_links(req);
3621 static int io_send(struct io_kiocb *req, bool force_nonblock)
3623 struct socket *sock;
3626 sock = sock_from_file(req->file, &ret);
3628 struct io_sr_msg *sr = &req->sr_msg;
3633 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3638 msg.msg_name = NULL;
3639 msg.msg_control = NULL;
3640 msg.msg_controllen = 0;
3641 msg.msg_namelen = 0;
3643 flags = req->sr_msg.msg_flags;
3644 if (flags & MSG_DONTWAIT)
3645 req->flags |= REQ_F_NOWAIT;
3646 else if (force_nonblock)
3647 flags |= MSG_DONTWAIT;
3649 msg.msg_flags = flags;
3650 ret = sock_sendmsg(sock, &msg);
3651 if (force_nonblock && ret == -EAGAIN)
3653 if (ret == -ERESTARTSYS)
3657 io_cqring_add_event(req, ret);
3659 req_set_fail_links(req);
3664 static int __io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3666 struct io_sr_msg *sr = &req->sr_msg;
3667 struct iovec __user *uiov;
3671 ret = __copy_msghdr_from_user(&io->msg.msg, sr->msg, &io->msg.uaddr,
3676 if (req->flags & REQ_F_BUFFER_SELECT) {
3679 if (copy_from_user(io->msg.iov, uiov, sizeof(*uiov)))
3681 sr->len = io->msg.iov[0].iov_len;
3682 iov_iter_init(&io->msg.msg.msg_iter, READ, io->msg.iov, 1,
3686 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
3687 &io->msg.iov, &io->msg.msg.msg_iter);
3695 #ifdef CONFIG_COMPAT
3696 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
3697 struct io_async_ctx *io)
3699 struct compat_msghdr __user *msg_compat;
3700 struct io_sr_msg *sr = &req->sr_msg;
3701 struct compat_iovec __user *uiov;
3706 msg_compat = (struct compat_msghdr __user *) sr->msg;
3707 ret = __get_compat_msghdr(&io->msg.msg, msg_compat, &io->msg.uaddr,
3712 uiov = compat_ptr(ptr);
3713 if (req->flags & REQ_F_BUFFER_SELECT) {
3714 compat_ssize_t clen;
3718 if (!access_ok(uiov, sizeof(*uiov)))
3720 if (__get_user(clen, &uiov->iov_len))
3724 sr->len = io->msg.iov[0].iov_len;
3727 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
3729 &io->msg.msg.msg_iter);
3738 static int io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3740 io->msg.msg.msg_name = &io->msg.addr;
3741 io->msg.iov = io->msg.fast_iov;
3743 #ifdef CONFIG_COMPAT
3744 if (req->ctx->compat)
3745 return __io_compat_recvmsg_copy_hdr(req, io);
3748 return __io_recvmsg_copy_hdr(req, io);
3751 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
3752 int *cflags, bool needs_lock)
3754 struct io_sr_msg *sr = &req->sr_msg;
3755 struct io_buffer *kbuf;
3757 if (!(req->flags & REQ_F_BUFFER_SELECT))
3760 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
3765 req->flags |= REQ_F_BUFFER_SELECTED;
3767 *cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
3768 *cflags |= IORING_CQE_F_BUFFER;
3772 static int io_recvmsg_prep(struct io_kiocb *req,
3773 const struct io_uring_sqe *sqe)
3775 struct io_sr_msg *sr = &req->sr_msg;
3776 struct io_async_ctx *io = req->io;
3779 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3782 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3783 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3784 sr->len = READ_ONCE(sqe->len);
3785 sr->bgid = READ_ONCE(sqe->buf_group);
3787 #ifdef CONFIG_COMPAT
3788 if (req->ctx->compat)
3789 sr->msg_flags |= MSG_CMSG_COMPAT;
3792 if (!io || req->opcode == IORING_OP_RECV)
3794 /* iovec is already imported */
3795 if (req->flags & REQ_F_NEED_CLEANUP)
3798 ret = io_recvmsg_copy_hdr(req, io);
3800 req->flags |= REQ_F_NEED_CLEANUP;
3804 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
3806 struct io_async_msghdr *kmsg = NULL;
3807 struct socket *sock;
3808 int ret, cflags = 0;
3810 sock = sock_from_file(req->file, &ret);
3812 struct io_buffer *kbuf;
3813 struct io_async_ctx io;
3817 kmsg = &req->io->msg;
3818 kmsg->msg.msg_name = &req->io->msg.addr;
3819 /* if iov is set, it's allocated already */
3821 kmsg->iov = kmsg->fast_iov;
3822 kmsg->msg.msg_iter.iov = kmsg->iov;
3825 kmsg->msg.msg_name = &io.msg.addr;
3827 ret = io_recvmsg_copy_hdr(req, &io);
3832 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
3834 return PTR_ERR(kbuf);
3836 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3837 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
3838 1, req->sr_msg.len);
3841 flags = req->sr_msg.msg_flags;
3842 if (flags & MSG_DONTWAIT)
3843 req->flags |= REQ_F_NOWAIT;
3844 else if (force_nonblock)
3845 flags |= MSG_DONTWAIT;
3847 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3848 kmsg->uaddr, flags);
3849 if (force_nonblock && ret == -EAGAIN) {
3850 ret = io_setup_async_msg(req, kmsg);
3855 if (ret == -ERESTARTSYS)
3861 if (kmsg && kmsg->iov != kmsg->fast_iov)
3863 req->flags &= ~REQ_F_NEED_CLEANUP;
3864 __io_cqring_add_event(req, ret, cflags);
3866 req_set_fail_links(req);
3871 static int io_recv(struct io_kiocb *req, bool force_nonblock)
3873 struct io_buffer *kbuf = NULL;
3874 struct socket *sock;
3875 int ret, cflags = 0;
3877 sock = sock_from_file(req->file, &ret);
3879 struct io_sr_msg *sr = &req->sr_msg;
3880 void __user *buf = sr->buf;
3885 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
3887 return PTR_ERR(kbuf);
3889 buf = u64_to_user_ptr(kbuf->addr);
3891 ret = import_single_range(READ, buf, sr->len, &iov,
3898 req->flags |= REQ_F_NEED_CLEANUP;
3899 msg.msg_name = NULL;
3900 msg.msg_control = NULL;
3901 msg.msg_controllen = 0;
3902 msg.msg_namelen = 0;
3903 msg.msg_iocb = NULL;
3906 flags = req->sr_msg.msg_flags;
3907 if (flags & MSG_DONTWAIT)
3908 req->flags |= REQ_F_NOWAIT;
3909 else if (force_nonblock)
3910 flags |= MSG_DONTWAIT;
3912 ret = sock_recvmsg(sock, &msg, flags);
3913 if (force_nonblock && ret == -EAGAIN)
3915 if (ret == -ERESTARTSYS)
3920 req->flags &= ~REQ_F_NEED_CLEANUP;
3921 __io_cqring_add_event(req, ret, cflags);
3923 req_set_fail_links(req);
3928 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3930 struct io_accept *accept = &req->accept;
3932 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3934 if (sqe->ioprio || sqe->len || sqe->buf_index)
3937 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3938 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3939 accept->flags = READ_ONCE(sqe->accept_flags);
3940 accept->nofile = rlimit(RLIMIT_NOFILE);
3944 static int io_accept(struct io_kiocb *req, bool force_nonblock)
3946 struct io_accept *accept = &req->accept;
3947 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
3950 if (req->file->f_flags & O_NONBLOCK)
3951 req->flags |= REQ_F_NOWAIT;
3953 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3954 accept->addr_len, accept->flags,
3956 if (ret == -EAGAIN && force_nonblock)
3959 if (ret == -ERESTARTSYS)
3961 req_set_fail_links(req);
3963 io_cqring_add_event(req, ret);
3968 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3970 struct io_connect *conn = &req->connect;
3971 struct io_async_ctx *io = req->io;
3973 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3975 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3978 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3979 conn->addr_len = READ_ONCE(sqe->addr2);
3984 return move_addr_to_kernel(conn->addr, conn->addr_len,
3985 &io->connect.address);
3988 static int io_connect(struct io_kiocb *req, bool force_nonblock)
3990 struct io_async_ctx __io, *io;
3991 unsigned file_flags;
3997 ret = move_addr_to_kernel(req->connect.addr,
3998 req->connect.addr_len,
3999 &__io.connect.address);
4005 file_flags = force_nonblock ? O_NONBLOCK : 0;
4007 ret = __sys_connect_file(req->file, &io->connect.address,
4008 req->connect.addr_len, file_flags);
4009 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4012 if (io_alloc_async_ctx(req)) {
4016 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
4019 if (ret == -ERESTARTSYS)
4023 req_set_fail_links(req);
4024 io_cqring_add_event(req, ret);
4028 #else /* !CONFIG_NET */
4029 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4034 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
4039 static int io_send(struct io_kiocb *req, bool force_nonblock)
4044 static int io_recvmsg_prep(struct io_kiocb *req,
4045 const struct io_uring_sqe *sqe)
4050 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
4055 static int io_recv(struct io_kiocb *req, bool force_nonblock)
4060 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4065 static int io_accept(struct io_kiocb *req, bool force_nonblock)
4070 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4075 static int io_connect(struct io_kiocb *req, bool force_nonblock)
4079 #endif /* CONFIG_NET */
4081 struct io_poll_table {
4082 struct poll_table_struct pt;
4083 struct io_kiocb *req;
4087 static int io_req_task_work_add(struct io_kiocb *req, struct callback_head *cb)
4089 struct task_struct *tsk = req->task;
4090 struct io_ring_ctx *ctx = req->ctx;
4091 int ret, notify = TWA_RESUME;
4094 * SQPOLL kernel thread doesn't need notification, just a wakeup.
4095 * If we're not using an eventfd, then TWA_RESUME is always fine,
4096 * as we won't have dependencies between request completions for
4097 * other kernel wait conditions.
4099 if (ctx->flags & IORING_SETUP_SQPOLL)
4101 else if (ctx->cq_ev_fd)
4102 notify = TWA_SIGNAL;
4104 ret = task_work_add(tsk, cb, notify);
4106 wake_up_process(tsk);
4110 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4111 __poll_t mask, task_work_func_t func)
4113 struct task_struct *tsk;
4116 /* for instances that support it check for an event match first: */
4117 if (mask && !(mask & poll->events))
4120 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4122 list_del_init(&poll->wait.entry);
4126 init_task_work(&req->task_work, func);
4128 * If this fails, then the task is exiting. When a task exits, the
4129 * work gets canceled, so just cancel this request as well instead
4130 * of executing it. We can't safely execute it anyway, as we may not
4131 * have the needed state needed for it anyway.
4133 ret = io_req_task_work_add(req, &req->task_work);
4134 if (unlikely(ret)) {
4135 WRITE_ONCE(poll->canceled, true);
4136 tsk = io_wq_get_task(req->ctx->io_wq);
4137 task_work_add(tsk, &req->task_work, 0);
4138 wake_up_process(tsk);
4143 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4144 __acquires(&req->ctx->completion_lock)
4146 struct io_ring_ctx *ctx = req->ctx;
4148 if (!req->result && !READ_ONCE(poll->canceled)) {
4149 struct poll_table_struct pt = { ._key = poll->events };
4151 req->result = vfs_poll(req->file, &pt) & poll->events;
4154 spin_lock_irq(&ctx->completion_lock);
4155 if (!req->result && !READ_ONCE(poll->canceled)) {
4156 add_wait_queue(poll->head, &poll->wait);
4163 static void io_poll_remove_double(struct io_kiocb *req, void *data)
4165 struct io_poll_iocb *poll = data;
4167 lockdep_assert_held(&req->ctx->completion_lock);
4169 if (poll && poll->head) {
4170 struct wait_queue_head *head = poll->head;
4172 spin_lock(&head->lock);
4173 list_del_init(&poll->wait.entry);
4174 if (poll->wait.private)
4175 refcount_dec(&req->refs);
4177 spin_unlock(&head->lock);
4181 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4183 struct io_ring_ctx *ctx = req->ctx;
4185 io_poll_remove_double(req, req->io);
4186 req->poll.done = true;
4187 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4188 io_commit_cqring(ctx);
4191 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4193 struct io_ring_ctx *ctx = req->ctx;
4195 if (io_poll_rewait(req, &req->poll)) {
4196 spin_unlock_irq(&ctx->completion_lock);
4200 hash_del(&req->hash_node);
4201 io_poll_complete(req, req->result, 0);
4202 req->flags |= REQ_F_COMP_LOCKED;
4203 io_put_req_find_next(req, nxt);
4204 spin_unlock_irq(&ctx->completion_lock);
4206 io_cqring_ev_posted(ctx);
4209 static void io_poll_task_func(struct callback_head *cb)
4211 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4212 struct io_kiocb *nxt = NULL;
4214 io_poll_task_handler(req, &nxt);
4216 struct io_ring_ctx *ctx = nxt->ctx;
4218 mutex_lock(&ctx->uring_lock);
4219 __io_queue_sqe(nxt, NULL);
4220 mutex_unlock(&ctx->uring_lock);
4224 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4225 int sync, void *key)
4227 struct io_kiocb *req = wait->private;
4228 struct io_poll_iocb *poll = req->apoll->double_poll;
4229 __poll_t mask = key_to_poll(key);
4231 /* for instances that support it check for an event match first: */
4232 if (mask && !(mask & poll->events))
4235 if (poll && poll->head) {
4238 spin_lock(&poll->head->lock);
4239 done = list_empty(&poll->wait.entry);
4241 list_del_init(&poll->wait.entry);
4242 spin_unlock(&poll->head->lock);
4244 __io_async_wake(req, poll, mask, io_poll_task_func);
4246 refcount_dec(&req->refs);
4250 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4251 wait_queue_func_t wake_func)
4255 poll->canceled = false;
4256 poll->events = events;
4257 INIT_LIST_HEAD(&poll->wait.entry);
4258 init_waitqueue_func_entry(&poll->wait, wake_func);
4261 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4262 struct wait_queue_head *head,
4263 struct io_poll_iocb **poll_ptr)
4265 struct io_kiocb *req = pt->req;
4268 * If poll->head is already set, it's because the file being polled
4269 * uses multiple waitqueues for poll handling (eg one for read, one
4270 * for write). Setup a separate io_poll_iocb if this happens.
4272 if (unlikely(poll->head)) {
4273 /* already have a 2nd entry, fail a third attempt */
4275 pt->error = -EINVAL;
4278 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4280 pt->error = -ENOMEM;
4283 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4284 refcount_inc(&req->refs);
4285 poll->wait.private = req;
4291 add_wait_queue(head, &poll->wait);
4294 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4295 struct poll_table_struct *p)
4297 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4298 struct async_poll *apoll = pt->req->apoll;
4300 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
4303 static void io_sq_thread_drop_mm(struct io_ring_ctx *ctx)
4305 struct mm_struct *mm = current->mm;
4308 kthread_unuse_mm(mm);
4313 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
4314 struct io_kiocb *req)
4316 if (io_op_defs[req->opcode].needs_mm && !current->mm) {
4317 if (unlikely(!mmget_not_zero(ctx->sqo_mm)))
4319 kthread_use_mm(ctx->sqo_mm);
4325 static void io_async_task_func(struct callback_head *cb)
4327 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4328 struct async_poll *apoll = req->apoll;
4329 struct io_ring_ctx *ctx = req->ctx;
4330 bool canceled = false;
4332 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4334 if (io_poll_rewait(req, &apoll->poll)) {
4335 spin_unlock_irq(&ctx->completion_lock);
4339 /* If req is still hashed, it cannot have been canceled. Don't check. */
4340 if (hash_hashed(&req->hash_node)) {
4341 hash_del(&req->hash_node);
4343 canceled = READ_ONCE(apoll->poll.canceled);
4345 io_cqring_fill_event(req, -ECANCELED);
4346 io_commit_cqring(ctx);
4350 io_poll_remove_double(req, apoll->double_poll);
4351 spin_unlock_irq(&ctx->completion_lock);
4353 /* restore ->work in case we need to retry again */
4354 if (req->flags & REQ_F_WORK_INITIALIZED)
4355 memcpy(&req->work, &apoll->work, sizeof(req->work));
4356 kfree(apoll->double_poll);
4360 __set_current_state(TASK_RUNNING);
4361 if (io_sq_thread_acquire_mm(ctx, req)) {
4362 io_cqring_add_event(req, -EFAULT);
4365 mutex_lock(&ctx->uring_lock);
4366 __io_queue_sqe(req, NULL);
4367 mutex_unlock(&ctx->uring_lock);
4369 io_cqring_ev_posted(ctx);
4371 req_set_fail_links(req);
4372 io_double_put_req(req);
4376 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4379 struct io_kiocb *req = wait->private;
4380 struct io_poll_iocb *poll = &req->apoll->poll;
4382 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4385 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4388 static void io_poll_req_insert(struct io_kiocb *req)
4390 struct io_ring_ctx *ctx = req->ctx;
4391 struct hlist_head *list;
4393 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4394 hlist_add_head(&req->hash_node, list);
4397 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4398 struct io_poll_iocb *poll,
4399 struct io_poll_table *ipt, __poll_t mask,
4400 wait_queue_func_t wake_func)
4401 __acquires(&ctx->completion_lock)
4403 struct io_ring_ctx *ctx = req->ctx;
4404 bool cancel = false;
4406 poll->file = req->file;
4407 io_init_poll_iocb(poll, mask, wake_func);
4408 poll->wait.private = req;
4410 ipt->pt._key = mask;
4412 ipt->error = -EINVAL;
4414 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4416 spin_lock_irq(&ctx->completion_lock);
4417 if (likely(poll->head)) {
4418 spin_lock(&poll->head->lock);
4419 if (unlikely(list_empty(&poll->wait.entry))) {
4425 if (mask || ipt->error)
4426 list_del_init(&poll->wait.entry);
4428 WRITE_ONCE(poll->canceled, true);
4429 else if (!poll->done) /* actually waiting for an event */
4430 io_poll_req_insert(req);
4431 spin_unlock(&poll->head->lock);
4437 static bool io_arm_poll_handler(struct io_kiocb *req)
4439 const struct io_op_def *def = &io_op_defs[req->opcode];
4440 struct io_ring_ctx *ctx = req->ctx;
4441 struct async_poll *apoll;
4442 struct io_poll_table ipt;
4445 if (!req->file || !file_can_poll(req->file))
4447 if (req->flags & (REQ_F_MUST_PUNT | REQ_F_POLLED))
4449 if (!def->pollin && !def->pollout)
4452 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4453 if (unlikely(!apoll))
4455 apoll->double_poll = NULL;
4457 req->flags |= REQ_F_POLLED;
4458 if (req->flags & REQ_F_WORK_INITIALIZED)
4459 memcpy(&apoll->work, &req->work, sizeof(req->work));
4461 io_get_req_task(req);
4463 INIT_HLIST_NODE(&req->hash_node);
4467 mask |= POLLIN | POLLRDNORM;
4469 mask |= POLLOUT | POLLWRNORM;
4470 mask |= POLLERR | POLLPRI;
4472 ipt.pt._qproc = io_async_queue_proc;
4474 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
4477 io_poll_remove_double(req, apoll->double_poll);
4478 spin_unlock_irq(&ctx->completion_lock);
4479 if (req->flags & REQ_F_WORK_INITIALIZED)
4480 memcpy(&req->work, &apoll->work, sizeof(req->work));
4481 kfree(apoll->double_poll);
4485 spin_unlock_irq(&ctx->completion_lock);
4486 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
4487 apoll->poll.events);
4491 static bool __io_poll_remove_one(struct io_kiocb *req,
4492 struct io_poll_iocb *poll)
4494 bool do_complete = false;
4496 spin_lock(&poll->head->lock);
4497 WRITE_ONCE(poll->canceled, true);
4498 if (!list_empty(&poll->wait.entry)) {
4499 list_del_init(&poll->wait.entry);
4502 spin_unlock(&poll->head->lock);
4503 hash_del(&req->hash_node);
4507 static bool io_poll_remove_one(struct io_kiocb *req)
4511 if (req->opcode == IORING_OP_POLL_ADD) {
4512 io_poll_remove_double(req, req->io);
4513 do_complete = __io_poll_remove_one(req, &req->poll);
4515 struct async_poll *apoll = req->apoll;
4517 io_poll_remove_double(req, apoll->double_poll);
4519 /* non-poll requests have submit ref still */
4520 do_complete = __io_poll_remove_one(req, &apoll->poll);
4524 * restore ->work because we will call
4525 * io_req_work_drop_env below when dropping the
4528 if (req->flags & REQ_F_WORK_INITIALIZED)
4529 memcpy(&req->work, &apoll->work,
4531 kfree(apoll->double_poll);
4537 io_cqring_fill_event(req, -ECANCELED);
4538 io_commit_cqring(req->ctx);
4539 req->flags |= REQ_F_COMP_LOCKED;
4546 static void io_poll_remove_all(struct io_ring_ctx *ctx)
4548 struct hlist_node *tmp;
4549 struct io_kiocb *req;
4552 spin_lock_irq(&ctx->completion_lock);
4553 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
4554 struct hlist_head *list;
4556 list = &ctx->cancel_hash[i];
4557 hlist_for_each_entry_safe(req, tmp, list, hash_node)
4558 posted += io_poll_remove_one(req);
4560 spin_unlock_irq(&ctx->completion_lock);
4563 io_cqring_ev_posted(ctx);
4566 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
4568 struct hlist_head *list;
4569 struct io_kiocb *req;
4571 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
4572 hlist_for_each_entry(req, list, hash_node) {
4573 if (sqe_addr != req->user_data)
4575 if (io_poll_remove_one(req))
4583 static int io_poll_remove_prep(struct io_kiocb *req,
4584 const struct io_uring_sqe *sqe)
4586 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4588 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4592 req->poll.addr = READ_ONCE(sqe->addr);
4597 * Find a running poll command that matches one specified in sqe->addr,
4598 * and remove it if found.
4600 static int io_poll_remove(struct io_kiocb *req)
4602 struct io_ring_ctx *ctx = req->ctx;
4606 addr = req->poll.addr;
4607 spin_lock_irq(&ctx->completion_lock);
4608 ret = io_poll_cancel(ctx, addr);
4609 spin_unlock_irq(&ctx->completion_lock);
4611 io_cqring_add_event(req, ret);
4613 req_set_fail_links(req);
4618 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4621 struct io_kiocb *req = wait->private;
4622 struct io_poll_iocb *poll = &req->poll;
4624 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
4627 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
4628 struct poll_table_struct *p)
4630 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4632 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->io);
4635 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4637 struct io_poll_iocb *poll = &req->poll;
4640 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4642 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
4647 events = READ_ONCE(sqe->poll_events);
4648 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
4650 io_get_req_task(req);
4654 static int io_poll_add(struct io_kiocb *req)
4656 struct io_poll_iocb *poll = &req->poll;
4657 struct io_ring_ctx *ctx = req->ctx;
4658 struct io_poll_table ipt;
4661 INIT_HLIST_NODE(&req->hash_node);
4662 INIT_LIST_HEAD(&req->list);
4663 ipt.pt._qproc = io_poll_queue_proc;
4665 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
4668 if (mask) { /* no async, we'd stolen it */
4670 io_poll_complete(req, mask, 0);
4672 spin_unlock_irq(&ctx->completion_lock);
4675 io_cqring_ev_posted(ctx);
4681 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
4683 struct io_timeout_data *data = container_of(timer,
4684 struct io_timeout_data, timer);
4685 struct io_kiocb *req = data->req;
4686 struct io_ring_ctx *ctx = req->ctx;
4687 unsigned long flags;
4689 atomic_inc(&ctx->cq_timeouts);
4691 spin_lock_irqsave(&ctx->completion_lock, flags);
4693 * We could be racing with timeout deletion. If the list is empty,
4694 * then timeout lookup already found it and will be handling it.
4696 if (!list_empty(&req->list))
4697 list_del_init(&req->list);
4699 io_cqring_fill_event(req, -ETIME);
4700 io_commit_cqring(ctx);
4701 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4703 io_cqring_ev_posted(ctx);
4704 req_set_fail_links(req);
4706 return HRTIMER_NORESTART;
4709 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
4711 struct io_kiocb *req;
4714 list_for_each_entry(req, &ctx->timeout_list, list) {
4715 if (user_data == req->user_data) {
4716 list_del_init(&req->list);
4725 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
4729 req_set_fail_links(req);
4730 io_cqring_fill_event(req, -ECANCELED);
4735 static int io_timeout_remove_prep(struct io_kiocb *req,
4736 const struct io_uring_sqe *sqe)
4738 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4740 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
4742 if (sqe->ioprio || sqe->buf_index || sqe->len)
4745 req->timeout.addr = READ_ONCE(sqe->addr);
4746 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
4747 if (req->timeout.flags)
4754 * Remove or update an existing timeout command
4756 static int io_timeout_remove(struct io_kiocb *req)
4758 struct io_ring_ctx *ctx = req->ctx;
4761 spin_lock_irq(&ctx->completion_lock);
4762 ret = io_timeout_cancel(ctx, req->timeout.addr);
4764 io_cqring_fill_event(req, ret);
4765 io_commit_cqring(ctx);
4766 spin_unlock_irq(&ctx->completion_lock);
4767 io_cqring_ev_posted(ctx);
4769 req_set_fail_links(req);
4774 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4775 bool is_timeout_link)
4777 struct io_timeout_data *data;
4779 u32 off = READ_ONCE(sqe->off);
4781 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4783 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
4785 if (off && is_timeout_link)
4787 flags = READ_ONCE(sqe->timeout_flags);
4788 if (flags & ~IORING_TIMEOUT_ABS)
4791 req->timeout.off = off;
4793 if (!req->io && io_alloc_async_ctx(req))
4796 data = &req->io->timeout;
4798 req->flags |= REQ_F_TIMEOUT;
4800 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
4803 if (flags & IORING_TIMEOUT_ABS)
4804 data->mode = HRTIMER_MODE_ABS;
4806 data->mode = HRTIMER_MODE_REL;
4808 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
4812 static int io_timeout(struct io_kiocb *req)
4814 struct io_ring_ctx *ctx = req->ctx;
4815 struct io_timeout_data *data = &req->io->timeout;
4816 struct list_head *entry;
4817 u32 tail, off = req->timeout.off;
4819 spin_lock_irq(&ctx->completion_lock);
4822 * sqe->off holds how many events that need to occur for this
4823 * timeout event to be satisfied. If it isn't set, then this is
4824 * a pure timeout request, sequence isn't used.
4827 req->flags |= REQ_F_TIMEOUT_NOSEQ;
4828 entry = ctx->timeout_list.prev;
4832 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
4833 req->timeout.target_seq = tail + off;
4836 * Insertion sort, ensuring the first entry in the list is always
4837 * the one we need first.
4839 list_for_each_prev(entry, &ctx->timeout_list) {
4840 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
4842 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
4844 /* nxt.seq is behind @tail, otherwise would've been completed */
4845 if (off >= nxt->timeout.target_seq - tail)
4849 list_add(&req->list, entry);
4850 data->timer.function = io_timeout_fn;
4851 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
4852 spin_unlock_irq(&ctx->completion_lock);
4856 static bool io_cancel_cb(struct io_wq_work *work, void *data)
4858 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4860 return req->user_data == (unsigned long) data;
4863 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
4865 enum io_wq_cancel cancel_ret;
4868 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
4869 switch (cancel_ret) {
4870 case IO_WQ_CANCEL_OK:
4873 case IO_WQ_CANCEL_RUNNING:
4876 case IO_WQ_CANCEL_NOTFOUND:
4884 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
4885 struct io_kiocb *req, __u64 sqe_addr,
4888 unsigned long flags;
4891 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
4892 if (ret != -ENOENT) {
4893 spin_lock_irqsave(&ctx->completion_lock, flags);
4897 spin_lock_irqsave(&ctx->completion_lock, flags);
4898 ret = io_timeout_cancel(ctx, sqe_addr);
4901 ret = io_poll_cancel(ctx, sqe_addr);
4905 io_cqring_fill_event(req, ret);
4906 io_commit_cqring(ctx);
4907 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4908 io_cqring_ev_posted(ctx);
4911 req_set_fail_links(req);
4915 static int io_async_cancel_prep(struct io_kiocb *req,
4916 const struct io_uring_sqe *sqe)
4918 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4920 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
4922 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
4925 req->cancel.addr = READ_ONCE(sqe->addr);
4929 static int io_async_cancel(struct io_kiocb *req)
4931 struct io_ring_ctx *ctx = req->ctx;
4933 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
4937 static int io_files_update_prep(struct io_kiocb *req,
4938 const struct io_uring_sqe *sqe)
4940 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
4942 if (sqe->ioprio || sqe->rw_flags)
4945 req->files_update.offset = READ_ONCE(sqe->off);
4946 req->files_update.nr_args = READ_ONCE(sqe->len);
4947 if (!req->files_update.nr_args)
4949 req->files_update.arg = READ_ONCE(sqe->addr);
4953 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
4955 struct io_ring_ctx *ctx = req->ctx;
4956 struct io_uring_files_update up;
4962 up.offset = req->files_update.offset;
4963 up.fds = req->files_update.arg;
4965 mutex_lock(&ctx->uring_lock);
4966 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
4967 mutex_unlock(&ctx->uring_lock);
4970 req_set_fail_links(req);
4971 io_cqring_add_event(req, ret);
4976 static int io_req_defer_prep(struct io_kiocb *req,
4977 const struct io_uring_sqe *sqe)
4984 io_req_init_async(req);
4986 if (io_op_defs[req->opcode].file_table) {
4987 ret = io_grab_files(req);
4992 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
4994 switch (req->opcode) {
4997 case IORING_OP_READV:
4998 case IORING_OP_READ_FIXED:
4999 case IORING_OP_READ:
5000 ret = io_read_prep(req, sqe, true);
5002 case IORING_OP_WRITEV:
5003 case IORING_OP_WRITE_FIXED:
5004 case IORING_OP_WRITE:
5005 ret = io_write_prep(req, sqe, true);
5007 case IORING_OP_POLL_ADD:
5008 ret = io_poll_add_prep(req, sqe);
5010 case IORING_OP_POLL_REMOVE:
5011 ret = io_poll_remove_prep(req, sqe);
5013 case IORING_OP_FSYNC:
5014 ret = io_prep_fsync(req, sqe);
5016 case IORING_OP_SYNC_FILE_RANGE:
5017 ret = io_prep_sfr(req, sqe);
5019 case IORING_OP_SENDMSG:
5020 case IORING_OP_SEND:
5021 ret = io_sendmsg_prep(req, sqe);
5023 case IORING_OP_RECVMSG:
5024 case IORING_OP_RECV:
5025 ret = io_recvmsg_prep(req, sqe);
5027 case IORING_OP_CONNECT:
5028 ret = io_connect_prep(req, sqe);
5030 case IORING_OP_TIMEOUT:
5031 ret = io_timeout_prep(req, sqe, false);
5033 case IORING_OP_TIMEOUT_REMOVE:
5034 ret = io_timeout_remove_prep(req, sqe);
5036 case IORING_OP_ASYNC_CANCEL:
5037 ret = io_async_cancel_prep(req, sqe);
5039 case IORING_OP_LINK_TIMEOUT:
5040 ret = io_timeout_prep(req, sqe, true);
5042 case IORING_OP_ACCEPT:
5043 ret = io_accept_prep(req, sqe);
5045 case IORING_OP_FALLOCATE:
5046 ret = io_fallocate_prep(req, sqe);
5048 case IORING_OP_OPENAT:
5049 ret = io_openat_prep(req, sqe);
5051 case IORING_OP_CLOSE:
5052 ret = io_close_prep(req, sqe);
5054 case IORING_OP_FILES_UPDATE:
5055 ret = io_files_update_prep(req, sqe);
5057 case IORING_OP_STATX:
5058 ret = io_statx_prep(req, sqe);
5060 case IORING_OP_FADVISE:
5061 ret = io_fadvise_prep(req, sqe);
5063 case IORING_OP_MADVISE:
5064 ret = io_madvise_prep(req, sqe);
5066 case IORING_OP_OPENAT2:
5067 ret = io_openat2_prep(req, sqe);
5069 case IORING_OP_EPOLL_CTL:
5070 ret = io_epoll_ctl_prep(req, sqe);
5072 case IORING_OP_SPLICE:
5073 ret = io_splice_prep(req, sqe);
5075 case IORING_OP_PROVIDE_BUFFERS:
5076 ret = io_provide_buffers_prep(req, sqe);
5078 case IORING_OP_REMOVE_BUFFERS:
5079 ret = io_remove_buffers_prep(req, sqe);
5082 ret = io_tee_prep(req, sqe);
5085 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5094 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5096 struct io_ring_ctx *ctx = req->ctx;
5099 /* Still need defer if there is pending req in defer list. */
5100 if (!req_need_defer(req) && list_empty_careful(&ctx->defer_list))
5104 if (io_alloc_async_ctx(req))
5106 ret = io_req_defer_prep(req, sqe);
5111 spin_lock_irq(&ctx->completion_lock);
5112 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
5113 spin_unlock_irq(&ctx->completion_lock);
5117 trace_io_uring_defer(ctx, req, req->user_data);
5118 list_add_tail(&req->list, &ctx->defer_list);
5119 spin_unlock_irq(&ctx->completion_lock);
5120 return -EIOCBQUEUED;
5123 static void io_cleanup_req(struct io_kiocb *req)
5125 struct io_async_ctx *io = req->io;
5127 switch (req->opcode) {
5128 case IORING_OP_READV:
5129 case IORING_OP_READ_FIXED:
5130 case IORING_OP_READ:
5131 if (req->flags & REQ_F_BUFFER_SELECTED)
5132 kfree((void *)(unsigned long)req->rw.addr);
5134 case IORING_OP_WRITEV:
5135 case IORING_OP_WRITE_FIXED:
5136 case IORING_OP_WRITE:
5137 if (io->rw.iov != io->rw.fast_iov)
5140 case IORING_OP_RECVMSG:
5141 if (req->flags & REQ_F_BUFFER_SELECTED)
5142 kfree(req->sr_msg.kbuf);
5144 case IORING_OP_SENDMSG:
5145 if (io->msg.iov != io->msg.fast_iov)
5148 case IORING_OP_RECV:
5149 if (req->flags & REQ_F_BUFFER_SELECTED)
5150 kfree(req->sr_msg.kbuf);
5152 case IORING_OP_OPENAT:
5153 case IORING_OP_OPENAT2:
5155 case IORING_OP_SPLICE:
5157 io_put_file(req, req->splice.file_in,
5158 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5162 req->flags &= ~REQ_F_NEED_CLEANUP;
5165 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5166 bool force_nonblock)
5168 struct io_ring_ctx *ctx = req->ctx;
5171 switch (req->opcode) {
5175 case IORING_OP_READV:
5176 case IORING_OP_READ_FIXED:
5177 case IORING_OP_READ:
5179 ret = io_read_prep(req, sqe, force_nonblock);
5183 ret = io_read(req, force_nonblock);
5185 case IORING_OP_WRITEV:
5186 case IORING_OP_WRITE_FIXED:
5187 case IORING_OP_WRITE:
5189 ret = io_write_prep(req, sqe, force_nonblock);
5193 ret = io_write(req, force_nonblock);
5195 case IORING_OP_FSYNC:
5197 ret = io_prep_fsync(req, sqe);
5201 ret = io_fsync(req, force_nonblock);
5203 case IORING_OP_POLL_ADD:
5205 ret = io_poll_add_prep(req, sqe);
5209 ret = io_poll_add(req);
5211 case IORING_OP_POLL_REMOVE:
5213 ret = io_poll_remove_prep(req, sqe);
5217 ret = io_poll_remove(req);
5219 case IORING_OP_SYNC_FILE_RANGE:
5221 ret = io_prep_sfr(req, sqe);
5225 ret = io_sync_file_range(req, force_nonblock);
5227 case IORING_OP_SENDMSG:
5228 case IORING_OP_SEND:
5230 ret = io_sendmsg_prep(req, sqe);
5234 if (req->opcode == IORING_OP_SENDMSG)
5235 ret = io_sendmsg(req, force_nonblock);
5237 ret = io_send(req, force_nonblock);
5239 case IORING_OP_RECVMSG:
5240 case IORING_OP_RECV:
5242 ret = io_recvmsg_prep(req, sqe);
5246 if (req->opcode == IORING_OP_RECVMSG)
5247 ret = io_recvmsg(req, force_nonblock);
5249 ret = io_recv(req, force_nonblock);
5251 case IORING_OP_TIMEOUT:
5253 ret = io_timeout_prep(req, sqe, false);
5257 ret = io_timeout(req);
5259 case IORING_OP_TIMEOUT_REMOVE:
5261 ret = io_timeout_remove_prep(req, sqe);
5265 ret = io_timeout_remove(req);
5267 case IORING_OP_ACCEPT:
5269 ret = io_accept_prep(req, sqe);
5273 ret = io_accept(req, force_nonblock);
5275 case IORING_OP_CONNECT:
5277 ret = io_connect_prep(req, sqe);
5281 ret = io_connect(req, force_nonblock);
5283 case IORING_OP_ASYNC_CANCEL:
5285 ret = io_async_cancel_prep(req, sqe);
5289 ret = io_async_cancel(req);
5291 case IORING_OP_FALLOCATE:
5293 ret = io_fallocate_prep(req, sqe);
5297 ret = io_fallocate(req, force_nonblock);
5299 case IORING_OP_OPENAT:
5301 ret = io_openat_prep(req, sqe);
5305 ret = io_openat(req, force_nonblock);
5307 case IORING_OP_CLOSE:
5309 ret = io_close_prep(req, sqe);
5313 ret = io_close(req, force_nonblock);
5315 case IORING_OP_FILES_UPDATE:
5317 ret = io_files_update_prep(req, sqe);
5321 ret = io_files_update(req, force_nonblock);
5323 case IORING_OP_STATX:
5325 ret = io_statx_prep(req, sqe);
5329 ret = io_statx(req, force_nonblock);
5331 case IORING_OP_FADVISE:
5333 ret = io_fadvise_prep(req, sqe);
5337 ret = io_fadvise(req, force_nonblock);
5339 case IORING_OP_MADVISE:
5341 ret = io_madvise_prep(req, sqe);
5345 ret = io_madvise(req, force_nonblock);
5347 case IORING_OP_OPENAT2:
5349 ret = io_openat2_prep(req, sqe);
5353 ret = io_openat2(req, force_nonblock);
5355 case IORING_OP_EPOLL_CTL:
5357 ret = io_epoll_ctl_prep(req, sqe);
5361 ret = io_epoll_ctl(req, force_nonblock);
5363 case IORING_OP_SPLICE:
5365 ret = io_splice_prep(req, sqe);
5369 ret = io_splice(req, force_nonblock);
5371 case IORING_OP_PROVIDE_BUFFERS:
5373 ret = io_provide_buffers_prep(req, sqe);
5377 ret = io_provide_buffers(req, force_nonblock);
5379 case IORING_OP_REMOVE_BUFFERS:
5381 ret = io_remove_buffers_prep(req, sqe);
5385 ret = io_remove_buffers(req, force_nonblock);
5389 ret = io_tee_prep(req, sqe);
5393 ret = io_tee(req, force_nonblock);
5403 /* If the op doesn't have a file, we're not polling for it */
5404 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5405 const bool in_async = io_wq_current_is_worker();
5407 /* workqueue context doesn't hold uring_lock, grab it now */
5409 mutex_lock(&ctx->uring_lock);
5411 io_iopoll_req_issued(req);
5414 mutex_unlock(&ctx->uring_lock);
5420 static void io_arm_async_linked_timeout(struct io_kiocb *req)
5422 struct io_kiocb *link;
5424 /* link head's timeout is queued in io_queue_async_work() */
5425 if (!(req->flags & REQ_F_QUEUE_TIMEOUT))
5428 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
5429 io_queue_linked_timeout(link);
5432 static void io_wq_submit_work(struct io_wq_work **workptr)
5434 struct io_wq_work *work = *workptr;
5435 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5438 io_arm_async_linked_timeout(req);
5440 /* if NO_CANCEL is set, we must still run the work */
5441 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5442 IO_WQ_WORK_CANCEL) {
5448 ret = io_issue_sqe(req, NULL, false);
5450 * We can get EAGAIN for polled IO even though we're
5451 * forcing a sync submission from here, since we can't
5452 * wait for request slots on the block side.
5461 req_set_fail_links(req);
5462 io_cqring_add_event(req, ret);
5466 io_steal_work(req, workptr);
5469 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5472 struct fixed_file_table *table;
5474 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5475 return table->files[index & IORING_FILE_TABLE_MASK];
5478 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
5479 int fd, struct file **out_file, bool fixed)
5481 struct io_ring_ctx *ctx = req->ctx;
5485 if (unlikely(!ctx->file_data ||
5486 (unsigned) fd >= ctx->nr_user_files))
5488 fd = array_index_nospec(fd, ctx->nr_user_files);
5489 file = io_file_from_index(ctx, fd);
5491 req->fixed_file_refs = ctx->file_data->cur_refs;
5492 percpu_ref_get(req->fixed_file_refs);
5495 trace_io_uring_file_get(ctx, fd);
5496 file = __io_file_get(state, fd);
5499 if (file || io_op_defs[req->opcode].needs_file_no_error) {
5506 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5511 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5512 if (unlikely(!fixed && io_async_submit(req->ctx)))
5515 return io_file_get(state, req, fd, &req->file, fixed);
5518 static int io_grab_files(struct io_kiocb *req)
5521 struct io_ring_ctx *ctx = req->ctx;
5523 if (req->work.files || (req->flags & REQ_F_NO_FILE_TABLE))
5525 if (!ctx->ring_file)
5529 spin_lock_irq(&ctx->inflight_lock);
5531 * We use the f_ops->flush() handler to ensure that we can flush
5532 * out work accessing these files if the fd is closed. Check if
5533 * the fd has changed since we started down this path, and disallow
5534 * this operation if it has.
5536 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
5537 list_add(&req->inflight_entry, &ctx->inflight_list);
5538 req->flags |= REQ_F_INFLIGHT;
5539 req->work.files = current->files;
5542 spin_unlock_irq(&ctx->inflight_lock);
5548 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5550 struct io_timeout_data *data = container_of(timer,
5551 struct io_timeout_data, timer);
5552 struct io_kiocb *req = data->req;
5553 struct io_ring_ctx *ctx = req->ctx;
5554 struct io_kiocb *prev = NULL;
5555 unsigned long flags;
5557 spin_lock_irqsave(&ctx->completion_lock, flags);
5560 * We don't expect the list to be empty, that will only happen if we
5561 * race with the completion of the linked work.
5563 if (!list_empty(&req->link_list)) {
5564 prev = list_entry(req->link_list.prev, struct io_kiocb,
5566 if (refcount_inc_not_zero(&prev->refs)) {
5567 list_del_init(&req->link_list);
5568 prev->flags &= ~REQ_F_LINK_TIMEOUT;
5573 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5576 req_set_fail_links(prev);
5577 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
5580 io_cqring_add_event(req, -ETIME);
5583 return HRTIMER_NORESTART;
5586 static void io_queue_linked_timeout(struct io_kiocb *req)
5588 struct io_ring_ctx *ctx = req->ctx;
5591 * If the list is now empty, then our linked request finished before
5592 * we got a chance to setup the timer
5594 spin_lock_irq(&ctx->completion_lock);
5595 if (!list_empty(&req->link_list)) {
5596 struct io_timeout_data *data = &req->io->timeout;
5598 data->timer.function = io_link_timeout_fn;
5599 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
5602 spin_unlock_irq(&ctx->completion_lock);
5604 /* drop submission reference */
5608 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
5610 struct io_kiocb *nxt;
5612 if (!(req->flags & REQ_F_LINK_HEAD))
5614 /* for polled retry, if flag is set, we already went through here */
5615 if (req->flags & REQ_F_POLLED)
5618 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
5620 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
5623 req->flags |= REQ_F_LINK_TIMEOUT;
5627 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5629 struct io_kiocb *linked_timeout;
5630 struct io_kiocb *nxt;
5631 const struct cred *old_creds = NULL;
5635 linked_timeout = io_prep_linked_timeout(req);
5637 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
5638 req->work.creds != current_cred()) {
5640 revert_creds(old_creds);
5641 if (old_creds == req->work.creds)
5642 old_creds = NULL; /* restored original creds */
5644 old_creds = override_creds(req->work.creds);
5647 ret = io_issue_sqe(req, sqe, true);
5650 * We async punt it if the file wasn't marked NOWAIT, or if the file
5651 * doesn't support non-blocking read/write attempts
5653 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
5654 (req->flags & REQ_F_MUST_PUNT))) {
5655 if (io_arm_poll_handler(req)) {
5657 io_queue_linked_timeout(linked_timeout);
5661 io_req_init_async(req);
5663 if (io_op_defs[req->opcode].file_table) {
5664 ret = io_grab_files(req);
5670 * Queued up for async execution, worker will release
5671 * submit reference when the iocb is actually submitted.
5673 io_queue_async_work(req);
5679 /* drop submission reference */
5680 io_put_req_find_next(req, &nxt);
5682 if (linked_timeout) {
5684 io_queue_linked_timeout(linked_timeout);
5686 io_put_req(linked_timeout);
5689 /* and drop final reference, if we failed */
5691 io_cqring_add_event(req, ret);
5692 req_set_fail_links(req);
5698 if (req->flags & REQ_F_FORCE_ASYNC)
5704 revert_creds(old_creds);
5707 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5711 ret = io_req_defer(req, sqe);
5713 if (ret != -EIOCBQUEUED) {
5715 io_cqring_add_event(req, ret);
5716 req_set_fail_links(req);
5717 io_double_put_req(req);
5719 } else if (req->flags & REQ_F_FORCE_ASYNC) {
5722 if (io_alloc_async_ctx(req))
5724 ret = io_req_defer_prep(req, sqe);
5725 if (unlikely(ret < 0))
5730 * Never try inline submit of IOSQE_ASYNC is set, go straight
5731 * to async execution.
5733 io_req_init_async(req);
5734 req->work.flags |= IO_WQ_WORK_CONCURRENT;
5735 io_queue_async_work(req);
5737 __io_queue_sqe(req, sqe);
5741 static inline void io_queue_link_head(struct io_kiocb *req)
5743 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
5744 io_cqring_add_event(req, -ECANCELED);
5745 io_double_put_req(req);
5747 io_queue_sqe(req, NULL);
5750 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5751 struct io_kiocb **link)
5753 struct io_ring_ctx *ctx = req->ctx;
5757 * If we already have a head request, queue this one for async
5758 * submittal once the head completes. If we don't have a head but
5759 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
5760 * submitted sync once the chain is complete. If none of those
5761 * conditions are true (normal request), then just queue it.
5764 struct io_kiocb *head = *link;
5767 * Taking sequential execution of a link, draining both sides
5768 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
5769 * requests in the link. So, it drains the head and the
5770 * next after the link request. The last one is done via
5771 * drain_next flag to persist the effect across calls.
5773 if (req->flags & REQ_F_IO_DRAIN) {
5774 head->flags |= REQ_F_IO_DRAIN;
5775 ctx->drain_next = 1;
5777 if (io_alloc_async_ctx(req))
5780 ret = io_req_defer_prep(req, sqe);
5782 /* fail even hard links since we don't submit */
5783 head->flags |= REQ_F_FAIL_LINK;
5786 trace_io_uring_link(ctx, req, head);
5787 list_add_tail(&req->link_list, &head->link_list);
5789 /* last request of a link, enqueue the link */
5790 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
5791 io_queue_link_head(head);
5795 if (unlikely(ctx->drain_next)) {
5796 req->flags |= REQ_F_IO_DRAIN;
5797 ctx->drain_next = 0;
5799 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
5800 req->flags |= REQ_F_LINK_HEAD;
5801 INIT_LIST_HEAD(&req->link_list);
5803 if (io_alloc_async_ctx(req))
5806 ret = io_req_defer_prep(req, sqe);
5808 req->flags |= REQ_F_FAIL_LINK;
5811 io_queue_sqe(req, sqe);
5819 * Batched submission is done, ensure local IO is flushed out.
5821 static void io_submit_state_end(struct io_submit_state *state)
5823 blk_finish_plug(&state->plug);
5824 io_state_file_put(state);
5825 if (state->free_reqs)
5826 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
5830 * Start submission side cache.
5832 static void io_submit_state_start(struct io_submit_state *state,
5833 unsigned int max_ios)
5835 blk_start_plug(&state->plug);
5836 state->free_reqs = 0;
5838 state->ios_left = max_ios;
5841 static void io_commit_sqring(struct io_ring_ctx *ctx)
5843 struct io_rings *rings = ctx->rings;
5846 * Ensure any loads from the SQEs are done at this point,
5847 * since once we write the new head, the application could
5848 * write new data to them.
5850 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
5854 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
5855 * that is mapped by userspace. This means that care needs to be taken to
5856 * ensure that reads are stable, as we cannot rely on userspace always
5857 * being a good citizen. If members of the sqe are validated and then later
5858 * used, it's important that those reads are done through READ_ONCE() to
5859 * prevent a re-load down the line.
5861 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
5863 u32 *sq_array = ctx->sq_array;
5867 * The cached sq head (or cq tail) serves two purposes:
5869 * 1) allows us to batch the cost of updating the user visible
5871 * 2) allows the kernel side to track the head on its own, even
5872 * though the application is the one updating it.
5874 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
5875 if (likely(head < ctx->sq_entries))
5876 return &ctx->sq_sqes[head];
5878 /* drop invalid entries */
5879 ctx->cached_sq_dropped++;
5880 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
5884 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
5886 ctx->cached_sq_head++;
5889 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
5890 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
5891 IOSQE_BUFFER_SELECT)
5893 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
5894 const struct io_uring_sqe *sqe,
5895 struct io_submit_state *state)
5897 unsigned int sqe_flags;
5901 * All io need record the previous position, if LINK vs DARIN,
5902 * it can be used to mark the position of the first IO in the
5905 req->sequence = ctx->cached_sq_head - ctx->cached_sq_dropped;
5906 req->opcode = READ_ONCE(sqe->opcode);
5907 req->user_data = READ_ONCE(sqe->user_data);
5912 /* one is dropped after submission, the other at completion */
5913 refcount_set(&req->refs, 2);
5914 req->task = current;
5917 if (unlikely(req->opcode >= IORING_OP_LAST))
5920 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
5923 sqe_flags = READ_ONCE(sqe->flags);
5924 /* enforce forwards compatibility on users */
5925 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
5928 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
5929 !io_op_defs[req->opcode].buffer_select)
5932 id = READ_ONCE(sqe->personality);
5934 io_req_init_async(req);
5935 req->work.creds = idr_find(&ctx->personality_idr, id);
5936 if (unlikely(!req->work.creds))
5938 get_cred(req->work.creds);
5941 /* same numerical values with corresponding REQ_F_*, safe to copy */
5942 req->flags |= sqe_flags;
5944 if (!io_op_defs[req->opcode].needs_file)
5947 return io_req_set_file(state, req, READ_ONCE(sqe->fd));
5950 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
5951 struct file *ring_file, int ring_fd)
5953 struct io_submit_state state, *statep = NULL;
5954 struct io_kiocb *link = NULL;
5955 int i, submitted = 0;
5957 /* if we have a backlog and couldn't flush it all, return BUSY */
5958 if (test_bit(0, &ctx->sq_check_overflow)) {
5959 if (!list_empty(&ctx->cq_overflow_list) &&
5960 !io_cqring_overflow_flush(ctx, false))
5964 /* make sure SQ entry isn't read before tail */
5965 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
5967 if (!percpu_ref_tryget_many(&ctx->refs, nr))
5970 if (nr > IO_PLUG_THRESHOLD) {
5971 io_submit_state_start(&state, nr);
5975 ctx->ring_fd = ring_fd;
5976 ctx->ring_file = ring_file;
5978 for (i = 0; i < nr; i++) {
5979 const struct io_uring_sqe *sqe;
5980 struct io_kiocb *req;
5983 sqe = io_get_sqe(ctx);
5984 if (unlikely(!sqe)) {
5985 io_consume_sqe(ctx);
5988 req = io_alloc_req(ctx, statep);
5989 if (unlikely(!req)) {
5991 submitted = -EAGAIN;
5995 err = io_init_req(ctx, req, sqe, statep);
5996 io_consume_sqe(ctx);
5997 /* will complete beyond this point, count as submitted */
6000 if (unlikely(err)) {
6002 io_cqring_add_event(req, err);
6003 io_double_put_req(req);
6007 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6008 true, io_async_submit(ctx));
6009 err = io_submit_sqe(req, sqe, &link);
6014 if (unlikely(submitted != nr)) {
6015 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6017 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6020 io_queue_link_head(link);
6022 io_submit_state_end(&state);
6024 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6025 io_commit_sqring(ctx);
6030 static int io_sq_thread(void *data)
6032 struct io_ring_ctx *ctx = data;
6033 const struct cred *old_cred;
6035 unsigned long timeout;
6038 complete(&ctx->sq_thread_comp);
6040 old_cred = override_creds(ctx->creds);
6042 timeout = jiffies + ctx->sq_thread_idle;
6043 while (!kthread_should_park()) {
6044 unsigned int to_submit;
6046 if (!list_empty(&ctx->poll_list)) {
6047 unsigned nr_events = 0;
6049 mutex_lock(&ctx->uring_lock);
6050 if (!list_empty(&ctx->poll_list))
6051 io_iopoll_getevents(ctx, &nr_events, 0);
6053 timeout = jiffies + ctx->sq_thread_idle;
6054 mutex_unlock(&ctx->uring_lock);
6057 to_submit = io_sqring_entries(ctx);
6060 * If submit got -EBUSY, flag us as needing the application
6061 * to enter the kernel to reap and flush events.
6063 if (!to_submit || ret == -EBUSY || need_resched()) {
6065 * Drop cur_mm before scheduling, we can't hold it for
6066 * long periods (or over schedule()). Do this before
6067 * adding ourselves to the waitqueue, as the unuse/drop
6070 io_sq_thread_drop_mm(ctx);
6073 * We're polling. If we're within the defined idle
6074 * period, then let us spin without work before going
6075 * to sleep. The exception is if we got EBUSY doing
6076 * more IO, we should wait for the application to
6077 * reap events and wake us up.
6079 if (!list_empty(&ctx->poll_list) || need_resched() ||
6080 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6081 !percpu_ref_is_dying(&ctx->refs))) {
6082 if (current->task_works)
6088 prepare_to_wait(&ctx->sqo_wait, &wait,
6089 TASK_INTERRUPTIBLE);
6092 * While doing polled IO, before going to sleep, we need
6093 * to check if there are new reqs added to poll_list, it
6094 * is because reqs may have been punted to io worker and
6095 * will be added to poll_list later, hence check the
6098 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6099 !list_empty_careful(&ctx->poll_list)) {
6100 finish_wait(&ctx->sqo_wait, &wait);
6104 /* Tell userspace we may need a wakeup call */
6105 spin_lock_irq(&ctx->completion_lock);
6106 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6107 spin_unlock_irq(&ctx->completion_lock);
6109 to_submit = io_sqring_entries(ctx);
6110 if (!to_submit || ret == -EBUSY) {
6111 if (kthread_should_park()) {
6112 finish_wait(&ctx->sqo_wait, &wait);
6115 if (current->task_works) {
6117 finish_wait(&ctx->sqo_wait, &wait);
6120 if (signal_pending(current))
6121 flush_signals(current);
6123 finish_wait(&ctx->sqo_wait, &wait);
6125 spin_lock_irq(&ctx->completion_lock);
6126 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6127 spin_unlock_irq(&ctx->completion_lock);
6131 finish_wait(&ctx->sqo_wait, &wait);
6133 spin_lock_irq(&ctx->completion_lock);
6134 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6135 spin_unlock_irq(&ctx->completion_lock);
6138 mutex_lock(&ctx->uring_lock);
6139 if (likely(!percpu_ref_is_dying(&ctx->refs)))
6140 ret = io_submit_sqes(ctx, to_submit, NULL, -1);
6141 mutex_unlock(&ctx->uring_lock);
6142 timeout = jiffies + ctx->sq_thread_idle;
6145 if (current->task_works)
6148 io_sq_thread_drop_mm(ctx);
6149 revert_creds(old_cred);
6156 struct io_wait_queue {
6157 struct wait_queue_entry wq;
6158 struct io_ring_ctx *ctx;
6160 unsigned nr_timeouts;
6163 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6165 struct io_ring_ctx *ctx = iowq->ctx;
6168 * Wake up if we have enough events, or if a timeout occurred since we
6169 * started waiting. For timeouts, we always want to return to userspace,
6170 * regardless of event count.
6172 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6173 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6176 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6177 int wake_flags, void *key)
6179 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6182 /* use noflush == true, as we can't safely rely on locking context */
6183 if (!io_should_wake(iowq, true))
6186 return autoremove_wake_function(curr, mode, wake_flags, key);
6190 * Wait until events become available, if we don't already have some. The
6191 * application must reap them itself, as they reside on the shared cq ring.
6193 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6194 const sigset_t __user *sig, size_t sigsz)
6196 struct io_wait_queue iowq = {
6199 .func = io_wake_function,
6200 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6203 .to_wait = min_events,
6205 struct io_rings *rings = ctx->rings;
6209 if (io_cqring_events(ctx, false) >= min_events)
6211 if (!current->task_works)
6217 #ifdef CONFIG_COMPAT
6218 if (in_compat_syscall())
6219 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6223 ret = set_user_sigmask(sig, sigsz);
6229 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6230 trace_io_uring_cqring_wait(ctx, min_events);
6232 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6233 TASK_INTERRUPTIBLE);
6234 /* make sure we run task_work before checking for signals */
6235 if (current->task_works)
6237 if (signal_pending(current)) {
6238 if (current->jobctl & JOBCTL_TASK_WORK) {
6239 spin_lock_irq(¤t->sighand->siglock);
6240 current->jobctl &= ~JOBCTL_TASK_WORK;
6241 recalc_sigpending();
6242 spin_unlock_irq(¤t->sighand->siglock);
6248 if (io_should_wake(&iowq, false))
6252 finish_wait(&ctx->wait, &iowq.wq);
6254 restore_saved_sigmask_unless(ret == -EINTR);
6256 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6259 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6261 #if defined(CONFIG_UNIX)
6262 if (ctx->ring_sock) {
6263 struct sock *sock = ctx->ring_sock->sk;
6264 struct sk_buff *skb;
6266 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6272 for (i = 0; i < ctx->nr_user_files; i++) {
6275 file = io_file_from_index(ctx, i);
6282 static void io_file_ref_kill(struct percpu_ref *ref)
6284 struct fixed_file_data *data;
6286 data = container_of(ref, struct fixed_file_data, refs);
6287 complete(&data->done);
6290 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6292 struct fixed_file_data *data = ctx->file_data;
6293 struct fixed_file_ref_node *ref_node = NULL;
6294 unsigned nr_tables, i;
6299 spin_lock(&data->lock);
6300 if (!list_empty(&data->ref_list))
6301 ref_node = list_first_entry(&data->ref_list,
6302 struct fixed_file_ref_node, node);
6303 spin_unlock(&data->lock);
6305 percpu_ref_kill(&ref_node->refs);
6307 percpu_ref_kill(&data->refs);
6309 /* wait for all refs nodes to complete */
6310 flush_delayed_work(&ctx->file_put_work);
6311 wait_for_completion(&data->done);
6313 __io_sqe_files_unregister(ctx);
6314 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6315 for (i = 0; i < nr_tables; i++)
6316 kfree(data->table[i].files);
6318 percpu_ref_exit(&data->refs);
6320 ctx->file_data = NULL;
6321 ctx->nr_user_files = 0;
6325 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6327 if (ctx->sqo_thread) {
6328 wait_for_completion(&ctx->sq_thread_comp);
6330 * The park is a bit of a work-around, without it we get
6331 * warning spews on shutdown with SQPOLL set and affinity
6332 * set to a single CPU.
6334 kthread_park(ctx->sqo_thread);
6335 kthread_stop(ctx->sqo_thread);
6336 ctx->sqo_thread = NULL;
6340 static void io_finish_async(struct io_ring_ctx *ctx)
6342 io_sq_thread_stop(ctx);
6345 io_wq_destroy(ctx->io_wq);
6350 #if defined(CONFIG_UNIX)
6352 * Ensure the UNIX gc is aware of our file set, so we are certain that
6353 * the io_uring can be safely unregistered on process exit, even if we have
6354 * loops in the file referencing.
6356 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6358 struct sock *sk = ctx->ring_sock->sk;
6359 struct scm_fp_list *fpl;
6360 struct sk_buff *skb;
6363 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6367 skb = alloc_skb(0, GFP_KERNEL);
6376 fpl->user = get_uid(ctx->user);
6377 for (i = 0; i < nr; i++) {
6378 struct file *file = io_file_from_index(ctx, i + offset);
6382 fpl->fp[nr_files] = get_file(file);
6383 unix_inflight(fpl->user, fpl->fp[nr_files]);
6388 fpl->max = SCM_MAX_FD;
6389 fpl->count = nr_files;
6390 UNIXCB(skb).fp = fpl;
6391 skb->destructor = unix_destruct_scm;
6392 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
6393 skb_queue_head(&sk->sk_receive_queue, skb);
6395 for (i = 0; i < nr_files; i++)
6406 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
6407 * causes regular reference counting to break down. We rely on the UNIX
6408 * garbage collection to take care of this problem for us.
6410 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6412 unsigned left, total;
6416 left = ctx->nr_user_files;
6418 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6420 ret = __io_sqe_files_scm(ctx, this_files, total);
6424 total += this_files;
6430 while (total < ctx->nr_user_files) {
6431 struct file *file = io_file_from_index(ctx, total);
6441 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6447 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
6452 for (i = 0; i < nr_tables; i++) {
6453 struct fixed_file_table *table = &ctx->file_data->table[i];
6454 unsigned this_files;
6456 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
6457 table->files = kcalloc(this_files, sizeof(struct file *),
6461 nr_files -= this_files;
6467 for (i = 0; i < nr_tables; i++) {
6468 struct fixed_file_table *table = &ctx->file_data->table[i];
6469 kfree(table->files);
6474 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
6476 #if defined(CONFIG_UNIX)
6477 struct sock *sock = ctx->ring_sock->sk;
6478 struct sk_buff_head list, *head = &sock->sk_receive_queue;
6479 struct sk_buff *skb;
6482 __skb_queue_head_init(&list);
6485 * Find the skb that holds this file in its SCM_RIGHTS. When found,
6486 * remove this entry and rearrange the file array.
6488 skb = skb_dequeue(head);
6490 struct scm_fp_list *fp;
6492 fp = UNIXCB(skb).fp;
6493 for (i = 0; i < fp->count; i++) {
6496 if (fp->fp[i] != file)
6499 unix_notinflight(fp->user, fp->fp[i]);
6500 left = fp->count - 1 - i;
6502 memmove(&fp->fp[i], &fp->fp[i + 1],
6503 left * sizeof(struct file *));
6510 __skb_queue_tail(&list, skb);
6520 __skb_queue_tail(&list, skb);
6522 skb = skb_dequeue(head);
6525 if (skb_peek(&list)) {
6526 spin_lock_irq(&head->lock);
6527 while ((skb = __skb_dequeue(&list)) != NULL)
6528 __skb_queue_tail(head, skb);
6529 spin_unlock_irq(&head->lock);
6536 struct io_file_put {
6537 struct list_head list;
6541 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
6543 struct fixed_file_data *file_data = ref_node->file_data;
6544 struct io_ring_ctx *ctx = file_data->ctx;
6545 struct io_file_put *pfile, *tmp;
6547 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
6548 list_del(&pfile->list);
6549 io_ring_file_put(ctx, pfile->file);
6553 spin_lock(&file_data->lock);
6554 list_del(&ref_node->node);
6555 spin_unlock(&file_data->lock);
6557 percpu_ref_exit(&ref_node->refs);
6559 percpu_ref_put(&file_data->refs);
6562 static void io_file_put_work(struct work_struct *work)
6564 struct io_ring_ctx *ctx;
6565 struct llist_node *node;
6567 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
6568 node = llist_del_all(&ctx->file_put_llist);
6571 struct fixed_file_ref_node *ref_node;
6572 struct llist_node *next = node->next;
6574 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
6575 __io_file_put_work(ref_node);
6580 static void io_file_data_ref_zero(struct percpu_ref *ref)
6582 struct fixed_file_ref_node *ref_node;
6583 struct io_ring_ctx *ctx;
6587 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
6588 ctx = ref_node->file_data->ctx;
6590 if (percpu_ref_is_dying(&ctx->file_data->refs))
6593 first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
6595 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
6597 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
6600 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
6601 struct io_ring_ctx *ctx)
6603 struct fixed_file_ref_node *ref_node;
6605 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
6607 return ERR_PTR(-ENOMEM);
6609 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
6612 return ERR_PTR(-ENOMEM);
6614 INIT_LIST_HEAD(&ref_node->node);
6615 INIT_LIST_HEAD(&ref_node->file_list);
6616 ref_node->file_data = ctx->file_data;
6620 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
6622 percpu_ref_exit(&ref_node->refs);
6626 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
6629 __s32 __user *fds = (__s32 __user *) arg;
6634 struct fixed_file_ref_node *ref_node;
6640 if (nr_args > IORING_MAX_FIXED_FILES)
6643 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
6644 if (!ctx->file_data)
6646 ctx->file_data->ctx = ctx;
6647 init_completion(&ctx->file_data->done);
6648 INIT_LIST_HEAD(&ctx->file_data->ref_list);
6649 spin_lock_init(&ctx->file_data->lock);
6651 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
6652 ctx->file_data->table = kcalloc(nr_tables,
6653 sizeof(struct fixed_file_table),
6655 if (!ctx->file_data->table) {
6656 kfree(ctx->file_data);
6657 ctx->file_data = NULL;
6661 if (percpu_ref_init(&ctx->file_data->refs, io_file_ref_kill,
6662 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
6663 kfree(ctx->file_data->table);
6664 kfree(ctx->file_data);
6665 ctx->file_data = NULL;
6669 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
6670 percpu_ref_exit(&ctx->file_data->refs);
6671 kfree(ctx->file_data->table);
6672 kfree(ctx->file_data);
6673 ctx->file_data = NULL;
6677 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
6678 struct fixed_file_table *table;
6682 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
6684 /* allow sparse sets */
6690 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6691 index = i & IORING_FILE_TABLE_MASK;
6699 * Don't allow io_uring instances to be registered. If UNIX
6700 * isn't enabled, then this causes a reference cycle and this
6701 * instance can never get freed. If UNIX is enabled we'll
6702 * handle it just fine, but there's still no point in allowing
6703 * a ring fd as it doesn't support regular read/write anyway.
6705 if (file->f_op == &io_uring_fops) {
6710 table->files[index] = file;
6714 for (i = 0; i < ctx->nr_user_files; i++) {
6715 file = io_file_from_index(ctx, i);
6719 for (i = 0; i < nr_tables; i++)
6720 kfree(ctx->file_data->table[i].files);
6722 percpu_ref_exit(&ctx->file_data->refs);
6723 kfree(ctx->file_data->table);
6724 kfree(ctx->file_data);
6725 ctx->file_data = NULL;
6726 ctx->nr_user_files = 0;
6730 ret = io_sqe_files_scm(ctx);
6732 io_sqe_files_unregister(ctx);
6736 ref_node = alloc_fixed_file_ref_node(ctx);
6737 if (IS_ERR(ref_node)) {
6738 io_sqe_files_unregister(ctx);
6739 return PTR_ERR(ref_node);
6742 ctx->file_data->cur_refs = &ref_node->refs;
6743 spin_lock(&ctx->file_data->lock);
6744 list_add(&ref_node->node, &ctx->file_data->ref_list);
6745 spin_unlock(&ctx->file_data->lock);
6746 percpu_ref_get(&ctx->file_data->refs);
6750 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
6753 #if defined(CONFIG_UNIX)
6754 struct sock *sock = ctx->ring_sock->sk;
6755 struct sk_buff_head *head = &sock->sk_receive_queue;
6756 struct sk_buff *skb;
6759 * See if we can merge this file into an existing skb SCM_RIGHTS
6760 * file set. If there's no room, fall back to allocating a new skb
6761 * and filling it in.
6763 spin_lock_irq(&head->lock);
6764 skb = skb_peek(head);
6766 struct scm_fp_list *fpl = UNIXCB(skb).fp;
6768 if (fpl->count < SCM_MAX_FD) {
6769 __skb_unlink(skb, head);
6770 spin_unlock_irq(&head->lock);
6771 fpl->fp[fpl->count] = get_file(file);
6772 unix_inflight(fpl->user, fpl->fp[fpl->count]);
6774 spin_lock_irq(&head->lock);
6775 __skb_queue_head(head, skb);
6780 spin_unlock_irq(&head->lock);
6787 return __io_sqe_files_scm(ctx, 1, index);
6793 static int io_queue_file_removal(struct fixed_file_data *data,
6796 struct io_file_put *pfile;
6797 struct percpu_ref *refs = data->cur_refs;
6798 struct fixed_file_ref_node *ref_node;
6800 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
6804 ref_node = container_of(refs, struct fixed_file_ref_node, refs);
6806 list_add(&pfile->list, &ref_node->file_list);
6811 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
6812 struct io_uring_files_update *up,
6815 struct fixed_file_data *data = ctx->file_data;
6816 struct fixed_file_ref_node *ref_node;
6821 bool needs_switch = false;
6823 if (check_add_overflow(up->offset, nr_args, &done))
6825 if (done > ctx->nr_user_files)
6828 ref_node = alloc_fixed_file_ref_node(ctx);
6829 if (IS_ERR(ref_node))
6830 return PTR_ERR(ref_node);
6833 fds = u64_to_user_ptr(up->fds);
6835 struct fixed_file_table *table;
6839 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
6843 i = array_index_nospec(up->offset, ctx->nr_user_files);
6844 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6845 index = i & IORING_FILE_TABLE_MASK;
6846 if (table->files[index]) {
6847 file = io_file_from_index(ctx, index);
6848 err = io_queue_file_removal(data, file);
6851 table->files[index] = NULL;
6852 needs_switch = true;
6861 * Don't allow io_uring instances to be registered. If
6862 * UNIX isn't enabled, then this causes a reference
6863 * cycle and this instance can never get freed. If UNIX
6864 * is enabled we'll handle it just fine, but there's
6865 * still no point in allowing a ring fd as it doesn't
6866 * support regular read/write anyway.
6868 if (file->f_op == &io_uring_fops) {
6873 table->files[index] = file;
6874 err = io_sqe_file_register(ctx, file, i);
6886 percpu_ref_kill(data->cur_refs);
6887 spin_lock(&data->lock);
6888 list_add(&ref_node->node, &data->ref_list);
6889 data->cur_refs = &ref_node->refs;
6890 spin_unlock(&data->lock);
6891 percpu_ref_get(&ctx->file_data->refs);
6893 destroy_fixed_file_ref_node(ref_node);
6895 return done ? done : err;
6898 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
6901 struct io_uring_files_update up;
6903 if (!ctx->file_data)
6907 if (copy_from_user(&up, arg, sizeof(up)))
6912 return __io_sqe_files_update(ctx, &up, nr_args);
6915 static void io_free_work(struct io_wq_work *work)
6917 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6919 /* Consider that io_steal_work() relies on this ref */
6923 static int io_init_wq_offload(struct io_ring_ctx *ctx,
6924 struct io_uring_params *p)
6926 struct io_wq_data data;
6928 struct io_ring_ctx *ctx_attach;
6929 unsigned int concurrency;
6932 data.user = ctx->user;
6933 data.free_work = io_free_work;
6934 data.do_work = io_wq_submit_work;
6936 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
6937 /* Do QD, or 4 * CPUS, whatever is smallest */
6938 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
6940 ctx->io_wq = io_wq_create(concurrency, &data);
6941 if (IS_ERR(ctx->io_wq)) {
6942 ret = PTR_ERR(ctx->io_wq);
6948 f = fdget(p->wq_fd);
6952 if (f.file->f_op != &io_uring_fops) {
6957 ctx_attach = f.file->private_data;
6958 /* @io_wq is protected by holding the fd */
6959 if (!io_wq_get(ctx_attach->io_wq, &data)) {
6964 ctx->io_wq = ctx_attach->io_wq;
6970 static int io_sq_offload_start(struct io_ring_ctx *ctx,
6971 struct io_uring_params *p)
6975 mmgrab(current->mm);
6976 ctx->sqo_mm = current->mm;
6978 if (ctx->flags & IORING_SETUP_SQPOLL) {
6980 if (!capable(CAP_SYS_ADMIN))
6983 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
6984 if (!ctx->sq_thread_idle)
6985 ctx->sq_thread_idle = HZ;
6987 if (p->flags & IORING_SETUP_SQ_AFF) {
6988 int cpu = p->sq_thread_cpu;
6991 if (cpu >= nr_cpu_ids)
6993 if (!cpu_online(cpu))
6996 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
7000 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
7003 if (IS_ERR(ctx->sqo_thread)) {
7004 ret = PTR_ERR(ctx->sqo_thread);
7005 ctx->sqo_thread = NULL;
7008 wake_up_process(ctx->sqo_thread);
7009 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7010 /* Can't have SQ_AFF without SQPOLL */
7015 ret = io_init_wq_offload(ctx, p);
7021 io_finish_async(ctx);
7022 mmdrop(ctx->sqo_mm);
7027 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
7029 atomic_long_sub(nr_pages, &user->locked_vm);
7032 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
7034 unsigned long page_limit, cur_pages, new_pages;
7036 /* Don't allow more pages than we can safely lock */
7037 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7040 cur_pages = atomic_long_read(&user->locked_vm);
7041 new_pages = cur_pages + nr_pages;
7042 if (new_pages > page_limit)
7044 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7045 new_pages) != cur_pages);
7050 static void io_mem_free(void *ptr)
7057 page = virt_to_head_page(ptr);
7058 if (put_page_testzero(page))
7059 free_compound_page(page);
7062 static void *io_mem_alloc(size_t size)
7064 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7067 return (void *) __get_free_pages(gfp_flags, get_order(size));
7070 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7073 struct io_rings *rings;
7074 size_t off, sq_array_size;
7076 off = struct_size(rings, cqes, cq_entries);
7077 if (off == SIZE_MAX)
7081 off = ALIGN(off, SMP_CACHE_BYTES);
7086 sq_array_size = array_size(sizeof(u32), sq_entries);
7087 if (sq_array_size == SIZE_MAX)
7090 if (check_add_overflow(off, sq_array_size, &off))
7099 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7103 pages = (size_t)1 << get_order(
7104 rings_size(sq_entries, cq_entries, NULL));
7105 pages += (size_t)1 << get_order(
7106 array_size(sizeof(struct io_uring_sqe), sq_entries));
7111 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7115 if (!ctx->user_bufs)
7118 for (i = 0; i < ctx->nr_user_bufs; i++) {
7119 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7121 for (j = 0; j < imu->nr_bvecs; j++)
7122 unpin_user_page(imu->bvec[j].bv_page);
7124 if (ctx->account_mem)
7125 io_unaccount_mem(ctx->user, imu->nr_bvecs);
7130 kfree(ctx->user_bufs);
7131 ctx->user_bufs = NULL;
7132 ctx->nr_user_bufs = 0;
7136 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7137 void __user *arg, unsigned index)
7139 struct iovec __user *src;
7141 #ifdef CONFIG_COMPAT
7143 struct compat_iovec __user *ciovs;
7144 struct compat_iovec ciov;
7146 ciovs = (struct compat_iovec __user *) arg;
7147 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7150 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7151 dst->iov_len = ciov.iov_len;
7155 src = (struct iovec __user *) arg;
7156 if (copy_from_user(dst, &src[index], sizeof(*dst)))
7161 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7164 struct vm_area_struct **vmas = NULL;
7165 struct page **pages = NULL;
7166 int i, j, got_pages = 0;
7171 if (!nr_args || nr_args > UIO_MAXIOV)
7174 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7176 if (!ctx->user_bufs)
7179 for (i = 0; i < nr_args; i++) {
7180 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7181 unsigned long off, start, end, ubuf;
7186 ret = io_copy_iov(ctx, &iov, arg, i);
7191 * Don't impose further limits on the size and buffer
7192 * constraints here, we'll -EINVAL later when IO is
7193 * submitted if they are wrong.
7196 if (!iov.iov_base || !iov.iov_len)
7199 /* arbitrary limit, but we need something */
7200 if (iov.iov_len > SZ_1G)
7203 ubuf = (unsigned long) iov.iov_base;
7204 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7205 start = ubuf >> PAGE_SHIFT;
7206 nr_pages = end - start;
7208 if (ctx->account_mem) {
7209 ret = io_account_mem(ctx->user, nr_pages);
7215 if (!pages || nr_pages > got_pages) {
7218 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7220 vmas = kvmalloc_array(nr_pages,
7221 sizeof(struct vm_area_struct *),
7223 if (!pages || !vmas) {
7225 if (ctx->account_mem)
7226 io_unaccount_mem(ctx->user, nr_pages);
7229 got_pages = nr_pages;
7232 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7236 if (ctx->account_mem)
7237 io_unaccount_mem(ctx->user, nr_pages);
7242 mmap_read_lock(current->mm);
7243 pret = pin_user_pages(ubuf, nr_pages,
7244 FOLL_WRITE | FOLL_LONGTERM,
7246 if (pret == nr_pages) {
7247 /* don't support file backed memory */
7248 for (j = 0; j < nr_pages; j++) {
7249 struct vm_area_struct *vma = vmas[j];
7252 !is_file_hugepages(vma->vm_file)) {
7258 ret = pret < 0 ? pret : -EFAULT;
7260 mmap_read_unlock(current->mm);
7263 * if we did partial map, or found file backed vmas,
7264 * release any pages we did get
7267 unpin_user_pages(pages, pret);
7268 if (ctx->account_mem)
7269 io_unaccount_mem(ctx->user, nr_pages);
7274 off = ubuf & ~PAGE_MASK;
7276 for (j = 0; j < nr_pages; j++) {
7279 vec_len = min_t(size_t, size, PAGE_SIZE - off);
7280 imu->bvec[j].bv_page = pages[j];
7281 imu->bvec[j].bv_len = vec_len;
7282 imu->bvec[j].bv_offset = off;
7286 /* store original address for later verification */
7288 imu->len = iov.iov_len;
7289 imu->nr_bvecs = nr_pages;
7291 ctx->nr_user_bufs++;
7299 io_sqe_buffer_unregister(ctx);
7303 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
7305 __s32 __user *fds = arg;
7311 if (copy_from_user(&fd, fds, sizeof(*fds)))
7314 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
7315 if (IS_ERR(ctx->cq_ev_fd)) {
7316 int ret = PTR_ERR(ctx->cq_ev_fd);
7317 ctx->cq_ev_fd = NULL;
7324 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
7326 if (ctx->cq_ev_fd) {
7327 eventfd_ctx_put(ctx->cq_ev_fd);
7328 ctx->cq_ev_fd = NULL;
7335 static int __io_destroy_buffers(int id, void *p, void *data)
7337 struct io_ring_ctx *ctx = data;
7338 struct io_buffer *buf = p;
7340 __io_remove_buffers(ctx, buf, id, -1U);
7344 static void io_destroy_buffers(struct io_ring_ctx *ctx)
7346 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
7347 idr_destroy(&ctx->io_buffer_idr);
7350 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
7352 io_finish_async(ctx);
7354 mmdrop(ctx->sqo_mm);
7356 io_iopoll_reap_events(ctx);
7357 io_sqe_buffer_unregister(ctx);
7358 io_sqe_files_unregister(ctx);
7359 io_eventfd_unregister(ctx);
7360 io_destroy_buffers(ctx);
7361 idr_destroy(&ctx->personality_idr);
7363 #if defined(CONFIG_UNIX)
7364 if (ctx->ring_sock) {
7365 ctx->ring_sock->file = NULL; /* so that iput() is called */
7366 sock_release(ctx->ring_sock);
7370 io_mem_free(ctx->rings);
7371 io_mem_free(ctx->sq_sqes);
7373 percpu_ref_exit(&ctx->refs);
7374 free_uid(ctx->user);
7375 put_cred(ctx->creds);
7376 kfree(ctx->cancel_hash);
7377 kmem_cache_free(req_cachep, ctx->fallback_req);
7381 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
7383 struct io_ring_ctx *ctx = file->private_data;
7386 poll_wait(file, &ctx->cq_wait, wait);
7388 * synchronizes with barrier from wq_has_sleeper call in
7392 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
7393 ctx->rings->sq_ring_entries)
7394 mask |= EPOLLOUT | EPOLLWRNORM;
7395 if (io_cqring_events(ctx, false))
7396 mask |= EPOLLIN | EPOLLRDNORM;
7401 static int io_uring_fasync(int fd, struct file *file, int on)
7403 struct io_ring_ctx *ctx = file->private_data;
7405 return fasync_helper(fd, file, on, &ctx->cq_fasync);
7408 static int io_remove_personalities(int id, void *p, void *data)
7410 struct io_ring_ctx *ctx = data;
7411 const struct cred *cred;
7413 cred = idr_remove(&ctx->personality_idr, id);
7419 static void io_ring_exit_work(struct work_struct *work)
7421 struct io_ring_ctx *ctx;
7423 ctx = container_of(work, struct io_ring_ctx, exit_work);
7425 io_cqring_overflow_flush(ctx, true);
7428 * If we're doing polled IO and end up having requests being
7429 * submitted async (out-of-line), then completions can come in while
7430 * we're waiting for refs to drop. We need to reap these manually,
7431 * as nobody else will be looking for them.
7433 while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20)) {
7434 io_iopoll_reap_events(ctx);
7436 io_cqring_overflow_flush(ctx, true);
7438 io_ring_ctx_free(ctx);
7441 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
7443 mutex_lock(&ctx->uring_lock);
7444 percpu_ref_kill(&ctx->refs);
7445 mutex_unlock(&ctx->uring_lock);
7447 io_kill_timeouts(ctx);
7448 io_poll_remove_all(ctx);
7451 io_wq_cancel_all(ctx->io_wq);
7453 io_iopoll_reap_events(ctx);
7454 /* if we failed setting up the ctx, we might not have any rings */
7456 io_cqring_overflow_flush(ctx, true);
7457 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
7460 * Do this upfront, so we won't have a grace period where the ring
7461 * is closed but resources aren't reaped yet. This can cause
7462 * spurious failure in setting up a new ring.
7464 if (ctx->account_mem)
7465 io_unaccount_mem(ctx->user,
7466 ring_pages(ctx->sq_entries, ctx->cq_entries));
7468 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
7469 queue_work(system_wq, &ctx->exit_work);
7472 static int io_uring_release(struct inode *inode, struct file *file)
7474 struct io_ring_ctx *ctx = file->private_data;
7476 file->private_data = NULL;
7477 io_ring_ctx_wait_and_kill(ctx);
7481 static bool io_wq_files_match(struct io_wq_work *work, void *data)
7483 struct files_struct *files = data;
7485 return work->files == files;
7488 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
7489 struct files_struct *files)
7491 if (list_empty_careful(&ctx->inflight_list))
7494 /* cancel all at once, should be faster than doing it one by one*/
7495 io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
7497 while (!list_empty_careful(&ctx->inflight_list)) {
7498 struct io_kiocb *cancel_req = NULL, *req;
7501 spin_lock_irq(&ctx->inflight_lock);
7502 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
7503 if (req->work.files != files)
7505 /* req is being completed, ignore */
7506 if (!refcount_inc_not_zero(&req->refs))
7512 prepare_to_wait(&ctx->inflight_wait, &wait,
7513 TASK_UNINTERRUPTIBLE);
7514 spin_unlock_irq(&ctx->inflight_lock);
7516 /* We need to keep going until we don't find a matching req */
7520 if (cancel_req->flags & REQ_F_OVERFLOW) {
7521 spin_lock_irq(&ctx->completion_lock);
7522 list_del(&cancel_req->list);
7523 cancel_req->flags &= ~REQ_F_OVERFLOW;
7524 if (list_empty(&ctx->cq_overflow_list)) {
7525 clear_bit(0, &ctx->sq_check_overflow);
7526 clear_bit(0, &ctx->cq_check_overflow);
7527 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
7529 spin_unlock_irq(&ctx->completion_lock);
7531 WRITE_ONCE(ctx->rings->cq_overflow,
7532 atomic_inc_return(&ctx->cached_cq_overflow));
7535 * Put inflight ref and overflow ref. If that's
7536 * all we had, then we're done with this request.
7538 if (refcount_sub_and_test(2, &cancel_req->refs)) {
7539 io_free_req(cancel_req);
7540 finish_wait(&ctx->inflight_wait, &wait);
7544 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
7545 io_put_req(cancel_req);
7549 finish_wait(&ctx->inflight_wait, &wait);
7553 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
7555 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7556 struct task_struct *task = data;
7558 return req->task == task;
7561 static int io_uring_flush(struct file *file, void *data)
7563 struct io_ring_ctx *ctx = file->private_data;
7565 io_uring_cancel_files(ctx, data);
7568 * If the task is going away, cancel work it may have pending
7570 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
7571 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, current, true);
7576 static void *io_uring_validate_mmap_request(struct file *file,
7577 loff_t pgoff, size_t sz)
7579 struct io_ring_ctx *ctx = file->private_data;
7580 loff_t offset = pgoff << PAGE_SHIFT;
7585 case IORING_OFF_SQ_RING:
7586 case IORING_OFF_CQ_RING:
7589 case IORING_OFF_SQES:
7593 return ERR_PTR(-EINVAL);
7596 page = virt_to_head_page(ptr);
7597 if (sz > page_size(page))
7598 return ERR_PTR(-EINVAL);
7605 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7607 size_t sz = vma->vm_end - vma->vm_start;
7611 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
7613 return PTR_ERR(ptr);
7615 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
7616 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
7619 #else /* !CONFIG_MMU */
7621 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7623 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
7626 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
7628 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
7631 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
7632 unsigned long addr, unsigned long len,
7633 unsigned long pgoff, unsigned long flags)
7637 ptr = io_uring_validate_mmap_request(file, pgoff, len);
7639 return PTR_ERR(ptr);
7641 return (unsigned long) ptr;
7644 #endif /* !CONFIG_MMU */
7646 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
7647 u32, min_complete, u32, flags, const sigset_t __user *, sig,
7650 struct io_ring_ctx *ctx;
7655 if (current->task_works)
7658 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
7666 if (f.file->f_op != &io_uring_fops)
7670 ctx = f.file->private_data;
7671 if (!percpu_ref_tryget(&ctx->refs))
7675 * For SQ polling, the thread will do all submissions and completions.
7676 * Just return the requested submit count, and wake the thread if
7680 if (ctx->flags & IORING_SETUP_SQPOLL) {
7681 if (!list_empty_careful(&ctx->cq_overflow_list))
7682 io_cqring_overflow_flush(ctx, false);
7683 if (flags & IORING_ENTER_SQ_WAKEUP)
7684 wake_up(&ctx->sqo_wait);
7685 submitted = to_submit;
7686 } else if (to_submit) {
7687 mutex_lock(&ctx->uring_lock);
7688 submitted = io_submit_sqes(ctx, to_submit, f.file, fd);
7689 mutex_unlock(&ctx->uring_lock);
7691 if (submitted != to_submit)
7694 if (flags & IORING_ENTER_GETEVENTS) {
7695 unsigned nr_events = 0;
7697 min_complete = min(min_complete, ctx->cq_entries);
7700 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
7701 * space applications don't need to do io completion events
7702 * polling again, they can rely on io_sq_thread to do polling
7703 * work, which can reduce cpu usage and uring_lock contention.
7705 if (ctx->flags & IORING_SETUP_IOPOLL &&
7706 !(ctx->flags & IORING_SETUP_SQPOLL)) {
7707 ret = io_iopoll_check(ctx, &nr_events, min_complete);
7709 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
7714 percpu_ref_put(&ctx->refs);
7717 return submitted ? submitted : ret;
7720 #ifdef CONFIG_PROC_FS
7721 static int io_uring_show_cred(int id, void *p, void *data)
7723 const struct cred *cred = p;
7724 struct seq_file *m = data;
7725 struct user_namespace *uns = seq_user_ns(m);
7726 struct group_info *gi;
7731 seq_printf(m, "%5d\n", id);
7732 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
7733 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
7734 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
7735 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
7736 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
7737 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
7738 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
7739 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
7740 seq_puts(m, "\n\tGroups:\t");
7741 gi = cred->group_info;
7742 for (g = 0; g < gi->ngroups; g++) {
7743 seq_put_decimal_ull(m, g ? " " : "",
7744 from_kgid_munged(uns, gi->gid[g]));
7746 seq_puts(m, "\n\tCapEff:\t");
7747 cap = cred->cap_effective;
7748 CAP_FOR_EACH_U32(__capi)
7749 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
7754 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
7758 mutex_lock(&ctx->uring_lock);
7759 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
7760 for (i = 0; i < ctx->nr_user_files; i++) {
7761 struct fixed_file_table *table;
7764 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7765 f = table->files[i & IORING_FILE_TABLE_MASK];
7767 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
7769 seq_printf(m, "%5u: <none>\n", i);
7771 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
7772 for (i = 0; i < ctx->nr_user_bufs; i++) {
7773 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
7775 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
7776 (unsigned int) buf->len);
7778 if (!idr_is_empty(&ctx->personality_idr)) {
7779 seq_printf(m, "Personalities:\n");
7780 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
7782 seq_printf(m, "PollList:\n");
7783 spin_lock_irq(&ctx->completion_lock);
7784 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7785 struct hlist_head *list = &ctx->cancel_hash[i];
7786 struct io_kiocb *req;
7788 hlist_for_each_entry(req, list, hash_node)
7789 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
7790 req->task->task_works != NULL);
7792 spin_unlock_irq(&ctx->completion_lock);
7793 mutex_unlock(&ctx->uring_lock);
7796 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
7798 struct io_ring_ctx *ctx = f->private_data;
7800 if (percpu_ref_tryget(&ctx->refs)) {
7801 __io_uring_show_fdinfo(ctx, m);
7802 percpu_ref_put(&ctx->refs);
7807 static const struct file_operations io_uring_fops = {
7808 .release = io_uring_release,
7809 .flush = io_uring_flush,
7810 .mmap = io_uring_mmap,
7812 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
7813 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
7815 .poll = io_uring_poll,
7816 .fasync = io_uring_fasync,
7817 #ifdef CONFIG_PROC_FS
7818 .show_fdinfo = io_uring_show_fdinfo,
7822 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
7823 struct io_uring_params *p)
7825 struct io_rings *rings;
7826 size_t size, sq_array_offset;
7828 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
7829 if (size == SIZE_MAX)
7832 rings = io_mem_alloc(size);
7837 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
7838 rings->sq_ring_mask = p->sq_entries - 1;
7839 rings->cq_ring_mask = p->cq_entries - 1;
7840 rings->sq_ring_entries = p->sq_entries;
7841 rings->cq_ring_entries = p->cq_entries;
7842 ctx->sq_mask = rings->sq_ring_mask;
7843 ctx->cq_mask = rings->cq_ring_mask;
7844 ctx->sq_entries = rings->sq_ring_entries;
7845 ctx->cq_entries = rings->cq_ring_entries;
7847 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
7848 if (size == SIZE_MAX) {
7849 io_mem_free(ctx->rings);
7854 ctx->sq_sqes = io_mem_alloc(size);
7855 if (!ctx->sq_sqes) {
7856 io_mem_free(ctx->rings);
7865 * Allocate an anonymous fd, this is what constitutes the application
7866 * visible backing of an io_uring instance. The application mmaps this
7867 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
7868 * we have to tie this fd to a socket for file garbage collection purposes.
7870 static int io_uring_get_fd(struct io_ring_ctx *ctx)
7875 #if defined(CONFIG_UNIX)
7876 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
7882 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
7886 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
7887 O_RDWR | O_CLOEXEC);
7890 ret = PTR_ERR(file);
7894 #if defined(CONFIG_UNIX)
7895 ctx->ring_sock->file = file;
7897 fd_install(ret, file);
7900 #if defined(CONFIG_UNIX)
7901 sock_release(ctx->ring_sock);
7902 ctx->ring_sock = NULL;
7907 static int io_uring_create(unsigned entries, struct io_uring_params *p,
7908 struct io_uring_params __user *params)
7910 struct user_struct *user = NULL;
7911 struct io_ring_ctx *ctx;
7917 if (entries > IORING_MAX_ENTRIES) {
7918 if (!(p->flags & IORING_SETUP_CLAMP))
7920 entries = IORING_MAX_ENTRIES;
7924 * Use twice as many entries for the CQ ring. It's possible for the
7925 * application to drive a higher depth than the size of the SQ ring,
7926 * since the sqes are only used at submission time. This allows for
7927 * some flexibility in overcommitting a bit. If the application has
7928 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
7929 * of CQ ring entries manually.
7931 p->sq_entries = roundup_pow_of_two(entries);
7932 if (p->flags & IORING_SETUP_CQSIZE) {
7934 * If IORING_SETUP_CQSIZE is set, we do the same roundup
7935 * to a power-of-two, if it isn't already. We do NOT impose
7936 * any cq vs sq ring sizing.
7938 if (p->cq_entries < p->sq_entries)
7940 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
7941 if (!(p->flags & IORING_SETUP_CLAMP))
7943 p->cq_entries = IORING_MAX_CQ_ENTRIES;
7945 p->cq_entries = roundup_pow_of_two(p->cq_entries);
7947 p->cq_entries = 2 * p->sq_entries;
7950 user = get_uid(current_user());
7951 account_mem = !capable(CAP_IPC_LOCK);
7954 ret = io_account_mem(user,
7955 ring_pages(p->sq_entries, p->cq_entries));
7962 ctx = io_ring_ctx_alloc(p);
7965 io_unaccount_mem(user, ring_pages(p->sq_entries,
7970 ctx->compat = in_compat_syscall();
7971 ctx->account_mem = account_mem;
7973 ctx->creds = get_current_cred();
7975 ret = io_allocate_scq_urings(ctx, p);
7979 ret = io_sq_offload_start(ctx, p);
7983 memset(&p->sq_off, 0, sizeof(p->sq_off));
7984 p->sq_off.head = offsetof(struct io_rings, sq.head);
7985 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
7986 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
7987 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
7988 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
7989 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
7990 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
7992 memset(&p->cq_off, 0, sizeof(p->cq_off));
7993 p->cq_off.head = offsetof(struct io_rings, cq.head);
7994 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
7995 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
7996 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
7997 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
7998 p->cq_off.cqes = offsetof(struct io_rings, cqes);
7999 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
8001 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
8002 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
8003 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL;
8005 if (copy_to_user(params, p, sizeof(*p))) {
8010 * Install ring fd as the very last thing, so we don't risk someone
8011 * having closed it before we finish setup
8013 ret = io_uring_get_fd(ctx);
8017 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
8020 io_ring_ctx_wait_and_kill(ctx);
8025 * Sets up an aio uring context, and returns the fd. Applications asks for a
8026 * ring size, we return the actual sq/cq ring sizes (among other things) in the
8027 * params structure passed in.
8029 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
8031 struct io_uring_params p;
8034 if (copy_from_user(&p, params, sizeof(p)))
8036 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
8041 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8042 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
8043 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
8046 return io_uring_create(entries, &p, params);
8049 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
8050 struct io_uring_params __user *, params)
8052 return io_uring_setup(entries, params);
8055 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
8057 struct io_uring_probe *p;
8061 size = struct_size(p, ops, nr_args);
8062 if (size == SIZE_MAX)
8064 p = kzalloc(size, GFP_KERNEL);
8069 if (copy_from_user(p, arg, size))
8072 if (memchr_inv(p, 0, size))
8075 p->last_op = IORING_OP_LAST - 1;
8076 if (nr_args > IORING_OP_LAST)
8077 nr_args = IORING_OP_LAST;
8079 for (i = 0; i < nr_args; i++) {
8081 if (!io_op_defs[i].not_supported)
8082 p->ops[i].flags = IO_URING_OP_SUPPORTED;
8087 if (copy_to_user(arg, p, size))
8094 static int io_register_personality(struct io_ring_ctx *ctx)
8096 const struct cred *creds = get_current_cred();
8099 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
8100 USHRT_MAX, GFP_KERNEL);
8106 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8108 const struct cred *old_creds;
8110 old_creds = idr_remove(&ctx->personality_idr, id);
8112 put_cred(old_creds);
8119 static bool io_register_op_must_quiesce(int op)
8122 case IORING_UNREGISTER_FILES:
8123 case IORING_REGISTER_FILES_UPDATE:
8124 case IORING_REGISTER_PROBE:
8125 case IORING_REGISTER_PERSONALITY:
8126 case IORING_UNREGISTER_PERSONALITY:
8133 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
8134 void __user *arg, unsigned nr_args)
8135 __releases(ctx->uring_lock)
8136 __acquires(ctx->uring_lock)
8141 * We're inside the ring mutex, if the ref is already dying, then
8142 * someone else killed the ctx or is already going through
8143 * io_uring_register().
8145 if (percpu_ref_is_dying(&ctx->refs))
8148 if (io_register_op_must_quiesce(opcode)) {
8149 percpu_ref_kill(&ctx->refs);
8152 * Drop uring mutex before waiting for references to exit. If
8153 * another thread is currently inside io_uring_enter() it might
8154 * need to grab the uring_lock to make progress. If we hold it
8155 * here across the drain wait, then we can deadlock. It's safe
8156 * to drop the mutex here, since no new references will come in
8157 * after we've killed the percpu ref.
8159 mutex_unlock(&ctx->uring_lock);
8160 ret = wait_for_completion_interruptible(&ctx->ref_comp);
8161 mutex_lock(&ctx->uring_lock);
8163 percpu_ref_resurrect(&ctx->refs);
8170 case IORING_REGISTER_BUFFERS:
8171 ret = io_sqe_buffer_register(ctx, arg, nr_args);
8173 case IORING_UNREGISTER_BUFFERS:
8177 ret = io_sqe_buffer_unregister(ctx);
8179 case IORING_REGISTER_FILES:
8180 ret = io_sqe_files_register(ctx, arg, nr_args);
8182 case IORING_UNREGISTER_FILES:
8186 ret = io_sqe_files_unregister(ctx);
8188 case IORING_REGISTER_FILES_UPDATE:
8189 ret = io_sqe_files_update(ctx, arg, nr_args);
8191 case IORING_REGISTER_EVENTFD:
8192 case IORING_REGISTER_EVENTFD_ASYNC:
8196 ret = io_eventfd_register(ctx, arg);
8199 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
8200 ctx->eventfd_async = 1;
8202 ctx->eventfd_async = 0;
8204 case IORING_UNREGISTER_EVENTFD:
8208 ret = io_eventfd_unregister(ctx);
8210 case IORING_REGISTER_PROBE:
8212 if (!arg || nr_args > 256)
8214 ret = io_probe(ctx, arg, nr_args);
8216 case IORING_REGISTER_PERSONALITY:
8220 ret = io_register_personality(ctx);
8222 case IORING_UNREGISTER_PERSONALITY:
8226 ret = io_unregister_personality(ctx, nr_args);
8233 if (io_register_op_must_quiesce(opcode)) {
8234 /* bring the ctx back to life */
8235 percpu_ref_reinit(&ctx->refs);
8237 reinit_completion(&ctx->ref_comp);
8242 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
8243 void __user *, arg, unsigned int, nr_args)
8245 struct io_ring_ctx *ctx;
8254 if (f.file->f_op != &io_uring_fops)
8257 ctx = f.file->private_data;
8259 mutex_lock(&ctx->uring_lock);
8260 ret = __io_uring_register(ctx, opcode, arg, nr_args);
8261 mutex_unlock(&ctx->uring_lock);
8262 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
8263 ctx->cq_ev_fd != NULL, ret);
8269 static int __init io_uring_init(void)
8271 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
8272 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
8273 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
8276 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
8277 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
8278 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
8279 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
8280 BUILD_BUG_SQE_ELEM(1, __u8, flags);
8281 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
8282 BUILD_BUG_SQE_ELEM(4, __s32, fd);
8283 BUILD_BUG_SQE_ELEM(8, __u64, off);
8284 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
8285 BUILD_BUG_SQE_ELEM(16, __u64, addr);
8286 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
8287 BUILD_BUG_SQE_ELEM(24, __u32, len);
8288 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
8289 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
8290 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
8291 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
8292 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
8293 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
8294 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
8295 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
8296 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
8297 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
8298 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
8299 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
8300 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
8301 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
8302 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
8303 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
8304 BUILD_BUG_SQE_ELEM(42, __u16, personality);
8305 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
8307 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
8308 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
8309 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
8312 __initcall(io_uring_init);