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 <linux/refcount.h>
48 #include <linux/uio.h>
50 #include <linux/sched/signal.h>
52 #include <linux/file.h>
53 #include <linux/fdtable.h>
55 #include <linux/mman.h>
56 #include <linux/mmu_context.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/workqueue.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>
74 #include <uapi/linux/io_uring.h>
78 #define IORING_MAX_ENTRIES 32768
79 #define IORING_MAX_FIXED_FILES 1024
82 u32 head ____cacheline_aligned_in_smp
;
83 u32 tail ____cacheline_aligned_in_smp
;
87 * This data is shared with the application through the mmap at offsets
88 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
90 * The offsets to the member fields are published through struct
91 * io_sqring_offsets when calling io_uring_setup.
95 * Head and tail offsets into the ring; the offsets need to be
96 * masked to get valid indices.
98 * The kernel controls head of the sq ring and the tail of the cq ring,
99 * and the application controls tail of the sq ring and the head of the
102 struct io_uring sq
, cq
;
104 * Bitmasks to apply to head and tail offsets (constant, equals
107 u32 sq_ring_mask
, cq_ring_mask
;
108 /* Ring sizes (constant, power of 2) */
109 u32 sq_ring_entries
, cq_ring_entries
;
111 * Number of invalid entries dropped by the kernel due to
112 * invalid index stored in array
114 * Written by the kernel, shouldn't be modified by the
115 * application (i.e. get number of "new events" by comparing to
118 * After a new SQ head value was read by the application this
119 * counter includes all submissions that were dropped reaching
120 * the new SQ head (and possibly more).
126 * Written by the kernel, shouldn't be modified by the
129 * The application needs a full memory barrier before checking
130 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
134 * Number of completion events lost because the queue was full;
135 * this should be avoided by the application by making sure
136 * there are not more requests pending thatn there is space in
137 * the completion queue.
139 * Written by the kernel, shouldn't be modified by the
140 * application (i.e. get number of "new events" by comparing to
143 * As completion events come in out of order this counter is not
144 * ordered with any other data.
148 * Ring buffer of completion events.
150 * The kernel writes completion events fresh every time they are
151 * produced, so the application is allowed to modify pending
154 struct io_uring_cqe cqes
[] ____cacheline_aligned_in_smp
;
157 struct io_mapped_ubuf
{
160 struct bio_vec
*bvec
;
161 unsigned int nr_bvecs
;
167 struct list_head list
;
176 struct percpu_ref refs
;
177 } ____cacheline_aligned_in_smp
;
185 * Ring buffer of indices into array of io_uring_sqe, which is
186 * mmapped by the application using the IORING_OFF_SQES offset.
188 * This indirection could e.g. be used to assign fixed
189 * io_uring_sqe entries to operations and only submit them to
190 * the queue when needed.
192 * The kernel modifies neither the indices array nor the entries
196 unsigned cached_sq_head
;
199 unsigned sq_thread_idle
;
200 unsigned cached_sq_dropped
;
201 struct io_uring_sqe
*sq_sqes
;
203 struct list_head defer_list
;
204 struct list_head timeout_list
;
205 } ____cacheline_aligned_in_smp
;
208 struct workqueue_struct
*sqo_wq
[2];
209 struct task_struct
*sqo_thread
; /* if using sq thread polling */
210 struct mm_struct
*sqo_mm
;
211 wait_queue_head_t sqo_wait
;
212 struct completion sqo_thread_started
;
215 unsigned cached_cq_tail
;
216 atomic_t cached_cq_overflow
;
219 struct wait_queue_head cq_wait
;
220 struct fasync_struct
*cq_fasync
;
221 struct eventfd_ctx
*cq_ev_fd
;
222 atomic_t cq_timeouts
;
223 } ____cacheline_aligned_in_smp
;
225 struct io_rings
*rings
;
228 * If used, fixed file set. Writers must ensure that ->refs is dead,
229 * readers must ensure that ->refs is alive as long as the file* is
230 * used. Only updated through io_uring_register(2).
232 struct file
**user_files
;
233 unsigned nr_user_files
;
235 /* if used, fixed mapped user buffers */
236 unsigned nr_user_bufs
;
237 struct io_mapped_ubuf
*user_bufs
;
239 struct user_struct
*user
;
241 struct completion ctx_done
;
244 struct mutex uring_lock
;
245 wait_queue_head_t wait
;
246 } ____cacheline_aligned_in_smp
;
249 spinlock_t completion_lock
;
250 bool poll_multi_file
;
252 * ->poll_list is protected by the ctx->uring_lock for
253 * io_uring instances that don't use IORING_SETUP_SQPOLL.
254 * For SQPOLL, only the single threaded io_sq_thread() will
255 * manipulate the list, hence no extra locking is needed there.
257 struct list_head poll_list
;
258 struct list_head cancel_list
;
259 } ____cacheline_aligned_in_smp
;
261 struct async_list pending_async
[2];
263 #if defined(CONFIG_UNIX)
264 struct socket
*ring_sock
;
269 const struct io_uring_sqe
*sqe
;
270 unsigned short index
;
274 bool needs_fixed_file
;
278 * First field must be the file pointer in all the
279 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
281 struct io_poll_iocb
{
283 struct wait_queue_head
*head
;
287 struct wait_queue_entry wait
;
292 struct hrtimer timer
;
296 * NOTE! Each of the iocb union members has the file pointer
297 * as the first entry in their struct definition. So you can
298 * access the file pointer through any of the sub-structs,
299 * or directly as just 'ki_filp' in this struct.
305 struct io_poll_iocb poll
;
306 struct io_timeout timeout
;
309 struct sqe_submit submit
;
311 struct io_ring_ctx
*ctx
;
312 struct list_head list
;
313 struct list_head link_list
;
316 #define REQ_F_NOWAIT 1 /* must not punt to workers */
317 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
318 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
319 #define REQ_F_SEQ_PREV 8 /* sequential with previous */
320 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
321 #define REQ_F_IO_DRAINED 32 /* drain done */
322 #define REQ_F_LINK 64 /* linked sqes */
323 #define REQ_F_LINK_DONE 128 /* linked sqes done */
324 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
325 #define REQ_F_SHADOW_DRAIN 512 /* link-drain shadow req */
326 #define REQ_F_TIMEOUT 1024 /* timeout request */
327 #define REQ_F_ISREG 2048 /* regular file */
328 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
333 struct work_struct work
;
336 #define IO_PLUG_THRESHOLD 2
337 #define IO_IOPOLL_BATCH 8
339 struct io_submit_state
{
340 struct blk_plug plug
;
343 * io_kiocb alloc cache
345 void *reqs
[IO_IOPOLL_BATCH
];
346 unsigned int free_reqs
;
347 unsigned int cur_req
;
350 * File reference cache
354 unsigned int has_refs
;
355 unsigned int used_refs
;
356 unsigned int ios_left
;
359 static void io_sq_wq_submit_work(struct work_struct
*work
);
360 static void io_cqring_fill_event(struct io_ring_ctx
*ctx
, u64 ki_user_data
,
362 static void __io_free_req(struct io_kiocb
*req
);
364 static struct kmem_cache
*req_cachep
;
366 static const struct file_operations io_uring_fops
;
368 struct sock
*io_uring_get_socket(struct file
*file
)
370 #if defined(CONFIG_UNIX)
371 if (file
->f_op
== &io_uring_fops
) {
372 struct io_ring_ctx
*ctx
= file
->private_data
;
374 return ctx
->ring_sock
->sk
;
379 EXPORT_SYMBOL(io_uring_get_socket
);
381 static void io_ring_ctx_ref_free(struct percpu_ref
*ref
)
383 struct io_ring_ctx
*ctx
= container_of(ref
, struct io_ring_ctx
, refs
);
385 complete(&ctx
->ctx_done
);
388 static struct io_ring_ctx
*io_ring_ctx_alloc(struct io_uring_params
*p
)
390 struct io_ring_ctx
*ctx
;
393 ctx
= kzalloc(sizeof(*ctx
), GFP_KERNEL
);
397 if (percpu_ref_init(&ctx
->refs
, io_ring_ctx_ref_free
,
398 PERCPU_REF_ALLOW_REINIT
, GFP_KERNEL
)) {
403 ctx
->flags
= p
->flags
;
404 init_waitqueue_head(&ctx
->cq_wait
);
405 init_completion(&ctx
->ctx_done
);
406 init_completion(&ctx
->sqo_thread_started
);
407 mutex_init(&ctx
->uring_lock
);
408 init_waitqueue_head(&ctx
->wait
);
409 for (i
= 0; i
< ARRAY_SIZE(ctx
->pending_async
); i
++) {
410 spin_lock_init(&ctx
->pending_async
[i
].lock
);
411 INIT_LIST_HEAD(&ctx
->pending_async
[i
].list
);
412 atomic_set(&ctx
->pending_async
[i
].cnt
, 0);
414 spin_lock_init(&ctx
->completion_lock
);
415 INIT_LIST_HEAD(&ctx
->poll_list
);
416 INIT_LIST_HEAD(&ctx
->cancel_list
);
417 INIT_LIST_HEAD(&ctx
->defer_list
);
418 INIT_LIST_HEAD(&ctx
->timeout_list
);
422 static inline bool __io_sequence_defer(struct io_ring_ctx
*ctx
,
423 struct io_kiocb
*req
)
425 return req
->sequence
!= ctx
->cached_cq_tail
+ ctx
->cached_sq_dropped
426 + atomic_read(&ctx
->cached_cq_overflow
);
429 static inline bool io_sequence_defer(struct io_ring_ctx
*ctx
,
430 struct io_kiocb
*req
)
432 if ((req
->flags
& (REQ_F_IO_DRAIN
|REQ_F_IO_DRAINED
)) != REQ_F_IO_DRAIN
)
435 return __io_sequence_defer(ctx
, req
);
438 static struct io_kiocb
*io_get_deferred_req(struct io_ring_ctx
*ctx
)
440 struct io_kiocb
*req
;
442 req
= list_first_entry_or_null(&ctx
->defer_list
, struct io_kiocb
, list
);
443 if (req
&& !io_sequence_defer(ctx
, req
)) {
444 list_del_init(&req
->list
);
451 static struct io_kiocb
*io_get_timeout_req(struct io_ring_ctx
*ctx
)
453 struct io_kiocb
*req
;
455 req
= list_first_entry_or_null(&ctx
->timeout_list
, struct io_kiocb
, list
);
456 if (req
&& !__io_sequence_defer(ctx
, req
)) {
457 list_del_init(&req
->list
);
464 static void __io_commit_cqring(struct io_ring_ctx
*ctx
)
466 struct io_rings
*rings
= ctx
->rings
;
468 if (ctx
->cached_cq_tail
!= READ_ONCE(rings
->cq
.tail
)) {
469 /* order cqe stores with ring update */
470 smp_store_release(&rings
->cq
.tail
, ctx
->cached_cq_tail
);
472 if (wq_has_sleeper(&ctx
->cq_wait
)) {
473 wake_up_interruptible(&ctx
->cq_wait
);
474 kill_fasync(&ctx
->cq_fasync
, SIGIO
, POLL_IN
);
479 static inline void io_queue_async_work(struct io_ring_ctx
*ctx
,
480 struct io_kiocb
*req
)
484 if (req
->submit
.sqe
) {
485 switch (req
->submit
.sqe
->opcode
) {
486 case IORING_OP_WRITEV
:
487 case IORING_OP_WRITE_FIXED
:
488 rw
= !(req
->rw
.ki_flags
& IOCB_DIRECT
);
493 queue_work(ctx
->sqo_wq
[rw
], &req
->work
);
496 static void io_kill_timeout(struct io_kiocb
*req
)
500 ret
= hrtimer_try_to_cancel(&req
->timeout
.timer
);
502 atomic_inc(&req
->ctx
->cq_timeouts
);
503 list_del(&req
->list
);
504 io_cqring_fill_event(req
->ctx
, req
->user_data
, 0);
509 static void io_kill_timeouts(struct io_ring_ctx
*ctx
)
511 struct io_kiocb
*req
, *tmp
;
513 spin_lock_irq(&ctx
->completion_lock
);
514 list_for_each_entry_safe(req
, tmp
, &ctx
->timeout_list
, list
)
515 io_kill_timeout(req
);
516 spin_unlock_irq(&ctx
->completion_lock
);
519 static void io_commit_cqring(struct io_ring_ctx
*ctx
)
521 struct io_kiocb
*req
;
523 while ((req
= io_get_timeout_req(ctx
)) != NULL
)
524 io_kill_timeout(req
);
526 __io_commit_cqring(ctx
);
528 while ((req
= io_get_deferred_req(ctx
)) != NULL
) {
529 if (req
->flags
& REQ_F_SHADOW_DRAIN
) {
530 /* Just for drain, free it. */
534 req
->flags
|= REQ_F_IO_DRAINED
;
535 io_queue_async_work(ctx
, req
);
539 static struct io_uring_cqe
*io_get_cqring(struct io_ring_ctx
*ctx
)
541 struct io_rings
*rings
= ctx
->rings
;
544 tail
= ctx
->cached_cq_tail
;
546 * writes to the cq entry need to come after reading head; the
547 * control dependency is enough as we're using WRITE_ONCE to
550 if (tail
- READ_ONCE(rings
->cq
.head
) == rings
->cq_ring_entries
)
553 ctx
->cached_cq_tail
++;
554 return &rings
->cqes
[tail
& ctx
->cq_mask
];
557 static void io_cqring_fill_event(struct io_ring_ctx
*ctx
, u64 ki_user_data
,
560 struct io_uring_cqe
*cqe
;
563 * If we can't get a cq entry, userspace overflowed the
564 * submission (by quite a lot). Increment the overflow count in
567 cqe
= io_get_cqring(ctx
);
569 WRITE_ONCE(cqe
->user_data
, ki_user_data
);
570 WRITE_ONCE(cqe
->res
, res
);
571 WRITE_ONCE(cqe
->flags
, 0);
573 WRITE_ONCE(ctx
->rings
->cq_overflow
,
574 atomic_inc_return(&ctx
->cached_cq_overflow
));
578 static void io_cqring_ev_posted(struct io_ring_ctx
*ctx
)
580 if (waitqueue_active(&ctx
->wait
))
582 if (waitqueue_active(&ctx
->sqo_wait
))
583 wake_up(&ctx
->sqo_wait
);
585 eventfd_signal(ctx
->cq_ev_fd
, 1);
588 static void io_cqring_add_event(struct io_ring_ctx
*ctx
, u64 user_data
,
593 spin_lock_irqsave(&ctx
->completion_lock
, flags
);
594 io_cqring_fill_event(ctx
, user_data
, res
);
595 io_commit_cqring(ctx
);
596 spin_unlock_irqrestore(&ctx
->completion_lock
, flags
);
598 io_cqring_ev_posted(ctx
);
601 static struct io_kiocb
*io_get_req(struct io_ring_ctx
*ctx
,
602 struct io_submit_state
*state
)
604 gfp_t gfp
= GFP_KERNEL
| __GFP_NOWARN
;
605 struct io_kiocb
*req
;
607 if (!percpu_ref_tryget(&ctx
->refs
))
611 req
= kmem_cache_alloc(req_cachep
, gfp
);
614 } else if (!state
->free_reqs
) {
618 sz
= min_t(size_t, state
->ios_left
, ARRAY_SIZE(state
->reqs
));
619 ret
= kmem_cache_alloc_bulk(req_cachep
, gfp
, sz
, state
->reqs
);
622 * Bulk alloc is all-or-nothing. If we fail to get a batch,
623 * retry single alloc to be on the safe side.
625 if (unlikely(ret
<= 0)) {
626 state
->reqs
[0] = kmem_cache_alloc(req_cachep
, gfp
);
631 state
->free_reqs
= ret
- 1;
633 req
= state
->reqs
[0];
635 req
= state
->reqs
[state
->cur_req
];
643 /* one is dropped after submission, the other at completion */
644 refcount_set(&req
->refs
, 2);
648 percpu_ref_put(&ctx
->refs
);
652 static void io_free_req_many(struct io_ring_ctx
*ctx
, void **reqs
, int *nr
)
655 kmem_cache_free_bulk(req_cachep
, *nr
, reqs
);
656 percpu_ref_put_many(&ctx
->refs
, *nr
);
661 static void __io_free_req(struct io_kiocb
*req
)
663 if (req
->file
&& !(req
->flags
& REQ_F_FIXED_FILE
))
665 percpu_ref_put(&req
->ctx
->refs
);
666 kmem_cache_free(req_cachep
, req
);
669 static void io_req_link_next(struct io_kiocb
*req
)
671 struct io_kiocb
*nxt
;
674 * The list should never be empty when we are called here. But could
675 * potentially happen if the chain is messed up, check to be on the
678 nxt
= list_first_entry_or_null(&req
->link_list
, struct io_kiocb
, list
);
680 list_del(&nxt
->list
);
681 if (!list_empty(&req
->link_list
)) {
682 INIT_LIST_HEAD(&nxt
->link_list
);
683 list_splice(&req
->link_list
, &nxt
->link_list
);
684 nxt
->flags
|= REQ_F_LINK
;
687 nxt
->flags
|= REQ_F_LINK_DONE
;
688 INIT_WORK(&nxt
->work
, io_sq_wq_submit_work
);
689 io_queue_async_work(req
->ctx
, nxt
);
694 * Called if REQ_F_LINK is set, and we fail the head request
696 static void io_fail_links(struct io_kiocb
*req
)
698 struct io_kiocb
*link
;
700 while (!list_empty(&req
->link_list
)) {
701 link
= list_first_entry(&req
->link_list
, struct io_kiocb
, list
);
702 list_del(&link
->list
);
704 io_cqring_add_event(req
->ctx
, link
->user_data
, -ECANCELED
);
709 static void io_free_req(struct io_kiocb
*req
)
712 * If LINK is set, we have dependent requests in this chain. If we
713 * didn't fail this request, queue the first one up, moving any other
714 * dependencies to the next request. In case of failure, fail the rest
717 if (req
->flags
& REQ_F_LINK
) {
718 if (req
->flags
& REQ_F_FAIL_LINK
)
721 io_req_link_next(req
);
727 static void io_put_req(struct io_kiocb
*req
)
729 if (refcount_dec_and_test(&req
->refs
))
733 static unsigned io_cqring_events(struct io_rings
*rings
)
735 /* See comment at the top of this file */
737 return READ_ONCE(rings
->cq
.tail
) - READ_ONCE(rings
->cq
.head
);
740 static inline unsigned int io_sqring_entries(struct io_ring_ctx
*ctx
)
742 struct io_rings
*rings
= ctx
->rings
;
744 /* make sure SQ entry isn't read before tail */
745 return smp_load_acquire(&rings
->sq
.tail
) - ctx
->cached_sq_head
;
749 * Find and free completed poll iocbs
751 static void io_iopoll_complete(struct io_ring_ctx
*ctx
, unsigned int *nr_events
,
752 struct list_head
*done
)
754 void *reqs
[IO_IOPOLL_BATCH
];
755 struct io_kiocb
*req
;
759 while (!list_empty(done
)) {
760 req
= list_first_entry(done
, struct io_kiocb
, list
);
761 list_del(&req
->list
);
763 io_cqring_fill_event(ctx
, req
->user_data
, req
->result
);
766 if (refcount_dec_and_test(&req
->refs
)) {
767 /* If we're not using fixed files, we have to pair the
768 * completion part with the file put. Use regular
769 * completions for those, only batch free for fixed
770 * file and non-linked commands.
772 if ((req
->flags
& (REQ_F_FIXED_FILE
|REQ_F_LINK
)) ==
774 reqs
[to_free
++] = req
;
775 if (to_free
== ARRAY_SIZE(reqs
))
776 io_free_req_many(ctx
, reqs
, &to_free
);
783 io_commit_cqring(ctx
);
784 io_free_req_many(ctx
, reqs
, &to_free
);
787 static int io_do_iopoll(struct io_ring_ctx
*ctx
, unsigned int *nr_events
,
790 struct io_kiocb
*req
, *tmp
;
796 * Only spin for completions if we don't have multiple devices hanging
797 * off our complete list, and we're under the requested amount.
799 spin
= !ctx
->poll_multi_file
&& *nr_events
< min
;
802 list_for_each_entry_safe(req
, tmp
, &ctx
->poll_list
, list
) {
803 struct kiocb
*kiocb
= &req
->rw
;
806 * Move completed entries to our local list. If we find a
807 * request that requires polling, break out and complete
808 * the done list first, if we have entries there.
810 if (req
->flags
& REQ_F_IOPOLL_COMPLETED
) {
811 list_move_tail(&req
->list
, &done
);
814 if (!list_empty(&done
))
817 ret
= kiocb
->ki_filp
->f_op
->iopoll(kiocb
, spin
);
826 if (!list_empty(&done
))
827 io_iopoll_complete(ctx
, nr_events
, &done
);
833 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
834 * non-spinning poll check - we'll still enter the driver poll loop, but only
835 * as a non-spinning completion check.
837 static int io_iopoll_getevents(struct io_ring_ctx
*ctx
, unsigned int *nr_events
,
840 while (!list_empty(&ctx
->poll_list
) && !need_resched()) {
843 ret
= io_do_iopoll(ctx
, nr_events
, min
);
846 if (!min
|| *nr_events
>= min
)
854 * We can't just wait for polled events to come to us, we have to actively
855 * find and complete them.
857 static void io_iopoll_reap_events(struct io_ring_ctx
*ctx
)
859 if (!(ctx
->flags
& IORING_SETUP_IOPOLL
))
862 mutex_lock(&ctx
->uring_lock
);
863 while (!list_empty(&ctx
->poll_list
)) {
864 unsigned int nr_events
= 0;
866 io_iopoll_getevents(ctx
, &nr_events
, 1);
869 * Ensure we allow local-to-the-cpu processing to take place,
870 * in this case we need to ensure that we reap all events.
874 mutex_unlock(&ctx
->uring_lock
);
877 static int __io_iopoll_check(struct io_ring_ctx
*ctx
, unsigned *nr_events
,
880 int iters
= 0, ret
= 0;
886 * Don't enter poll loop if we already have events pending.
887 * If we do, we can potentially be spinning for commands that
888 * already triggered a CQE (eg in error).
890 if (io_cqring_events(ctx
->rings
))
894 * If a submit got punted to a workqueue, we can have the
895 * application entering polling for a command before it gets
896 * issued. That app will hold the uring_lock for the duration
897 * of the poll right here, so we need to take a breather every
898 * now and then to ensure that the issue has a chance to add
899 * the poll to the issued list. Otherwise we can spin here
900 * forever, while the workqueue is stuck trying to acquire the
903 if (!(++iters
& 7)) {
904 mutex_unlock(&ctx
->uring_lock
);
905 mutex_lock(&ctx
->uring_lock
);
908 if (*nr_events
< min
)
909 tmin
= min
- *nr_events
;
911 ret
= io_iopoll_getevents(ctx
, nr_events
, tmin
);
915 } while (min
&& !*nr_events
&& !need_resched());
920 static int io_iopoll_check(struct io_ring_ctx
*ctx
, unsigned *nr_events
,
926 * We disallow the app entering submit/complete with polling, but we
927 * still need to lock the ring to prevent racing with polled issue
928 * that got punted to a workqueue.
930 mutex_lock(&ctx
->uring_lock
);
931 ret
= __io_iopoll_check(ctx
, nr_events
, min
);
932 mutex_unlock(&ctx
->uring_lock
);
936 static void kiocb_end_write(struct io_kiocb
*req
)
939 * Tell lockdep we inherited freeze protection from submission
942 if (req
->flags
& REQ_F_ISREG
) {
943 struct inode
*inode
= file_inode(req
->file
);
945 __sb_writers_acquired(inode
->i_sb
, SB_FREEZE_WRITE
);
947 file_end_write(req
->file
);
950 static void io_complete_rw(struct kiocb
*kiocb
, long res
, long res2
)
952 struct io_kiocb
*req
= container_of(kiocb
, struct io_kiocb
, rw
);
954 if (kiocb
->ki_flags
& IOCB_WRITE
)
955 kiocb_end_write(req
);
957 if ((req
->flags
& REQ_F_LINK
) && res
!= req
->result
)
958 req
->flags
|= REQ_F_FAIL_LINK
;
959 io_cqring_add_event(req
->ctx
, req
->user_data
, res
);
963 static void io_complete_rw_iopoll(struct kiocb
*kiocb
, long res
, long res2
)
965 struct io_kiocb
*req
= container_of(kiocb
, struct io_kiocb
, rw
);
967 if (kiocb
->ki_flags
& IOCB_WRITE
)
968 kiocb_end_write(req
);
970 if ((req
->flags
& REQ_F_LINK
) && res
!= req
->result
)
971 req
->flags
|= REQ_F_FAIL_LINK
;
974 req
->flags
|= REQ_F_IOPOLL_COMPLETED
;
978 * After the iocb has been issued, it's safe to be found on the poll list.
979 * Adding the kiocb to the list AFTER submission ensures that we don't
980 * find it from a io_iopoll_getevents() thread before the issuer is done
981 * accessing the kiocb cookie.
983 static void io_iopoll_req_issued(struct io_kiocb
*req
)
985 struct io_ring_ctx
*ctx
= req
->ctx
;
988 * Track whether we have multiple files in our lists. This will impact
989 * how we do polling eventually, not spinning if we're on potentially
992 if (list_empty(&ctx
->poll_list
)) {
993 ctx
->poll_multi_file
= false;
994 } else if (!ctx
->poll_multi_file
) {
995 struct io_kiocb
*list_req
;
997 list_req
= list_first_entry(&ctx
->poll_list
, struct io_kiocb
,
999 if (list_req
->rw
.ki_filp
!= req
->rw
.ki_filp
)
1000 ctx
->poll_multi_file
= true;
1004 * For fast devices, IO may have already completed. If it has, add
1005 * it to the front so we find it first.
1007 if (req
->flags
& REQ_F_IOPOLL_COMPLETED
)
1008 list_add(&req
->list
, &ctx
->poll_list
);
1010 list_add_tail(&req
->list
, &ctx
->poll_list
);
1013 static void io_file_put(struct io_submit_state
*state
)
1016 int diff
= state
->has_refs
- state
->used_refs
;
1019 fput_many(state
->file
, diff
);
1025 * Get as many references to a file as we have IOs left in this submission,
1026 * assuming most submissions are for one file, or at least that each file
1027 * has more than one submission.
1029 static struct file
*io_file_get(struct io_submit_state
*state
, int fd
)
1035 if (state
->fd
== fd
) {
1042 state
->file
= fget_many(fd
, state
->ios_left
);
1047 state
->has_refs
= state
->ios_left
;
1048 state
->used_refs
= 1;
1054 * If we tracked the file through the SCM inflight mechanism, we could support
1055 * any file. For now, just ensure that anything potentially problematic is done
1058 static bool io_file_supports_async(struct file
*file
)
1060 umode_t mode
= file_inode(file
)->i_mode
;
1062 if (S_ISBLK(mode
) || S_ISCHR(mode
))
1064 if (S_ISREG(mode
) && file
->f_op
!= &io_uring_fops
)
1070 static int io_prep_rw(struct io_kiocb
*req
, const struct sqe_submit
*s
,
1071 bool force_nonblock
)
1073 const struct io_uring_sqe
*sqe
= s
->sqe
;
1074 struct io_ring_ctx
*ctx
= req
->ctx
;
1075 struct kiocb
*kiocb
= &req
->rw
;
1082 if (S_ISREG(file_inode(req
->file
)->i_mode
))
1083 req
->flags
|= REQ_F_ISREG
;
1086 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1087 * we know to async punt it even if it was opened O_NONBLOCK
1089 if (force_nonblock
&& !io_file_supports_async(req
->file
)) {
1090 req
->flags
|= REQ_F_MUST_PUNT
;
1094 kiocb
->ki_pos
= READ_ONCE(sqe
->off
);
1095 kiocb
->ki_flags
= iocb_flags(kiocb
->ki_filp
);
1096 kiocb
->ki_hint
= ki_hint_validate(file_write_hint(kiocb
->ki_filp
));
1098 ioprio
= READ_ONCE(sqe
->ioprio
);
1100 ret
= ioprio_check_cap(ioprio
);
1104 kiocb
->ki_ioprio
= ioprio
;
1106 kiocb
->ki_ioprio
= get_current_ioprio();
1108 ret
= kiocb_set_rw_flags(kiocb
, READ_ONCE(sqe
->rw_flags
));
1112 /* don't allow async punt if RWF_NOWAIT was requested */
1113 if ((kiocb
->ki_flags
& IOCB_NOWAIT
) ||
1114 (req
->file
->f_flags
& O_NONBLOCK
))
1115 req
->flags
|= REQ_F_NOWAIT
;
1118 kiocb
->ki_flags
|= IOCB_NOWAIT
;
1120 if (ctx
->flags
& IORING_SETUP_IOPOLL
) {
1121 if (!(kiocb
->ki_flags
& IOCB_DIRECT
) ||
1122 !kiocb
->ki_filp
->f_op
->iopoll
)
1125 kiocb
->ki_flags
|= IOCB_HIPRI
;
1126 kiocb
->ki_complete
= io_complete_rw_iopoll
;
1128 if (kiocb
->ki_flags
& IOCB_HIPRI
)
1130 kiocb
->ki_complete
= io_complete_rw
;
1135 static inline void io_rw_done(struct kiocb
*kiocb
, ssize_t ret
)
1141 case -ERESTARTNOINTR
:
1142 case -ERESTARTNOHAND
:
1143 case -ERESTART_RESTARTBLOCK
:
1145 * We can't just restart the syscall, since previously
1146 * submitted sqes may already be in progress. Just fail this
1152 kiocb
->ki_complete(kiocb
, ret
, 0);
1156 static int io_import_fixed(struct io_ring_ctx
*ctx
, int rw
,
1157 const struct io_uring_sqe
*sqe
,
1158 struct iov_iter
*iter
)
1160 size_t len
= READ_ONCE(sqe
->len
);
1161 struct io_mapped_ubuf
*imu
;
1162 unsigned index
, buf_index
;
1166 /* attempt to use fixed buffers without having provided iovecs */
1167 if (unlikely(!ctx
->user_bufs
))
1170 buf_index
= READ_ONCE(sqe
->buf_index
);
1171 if (unlikely(buf_index
>= ctx
->nr_user_bufs
))
1174 index
= array_index_nospec(buf_index
, ctx
->nr_user_bufs
);
1175 imu
= &ctx
->user_bufs
[index
];
1176 buf_addr
= READ_ONCE(sqe
->addr
);
1179 if (buf_addr
+ len
< buf_addr
)
1181 /* not inside the mapped region */
1182 if (buf_addr
< imu
->ubuf
|| buf_addr
+ len
> imu
->ubuf
+ imu
->len
)
1186 * May not be a start of buffer, set size appropriately
1187 * and advance us to the beginning.
1189 offset
= buf_addr
- imu
->ubuf
;
1190 iov_iter_bvec(iter
, rw
, imu
->bvec
, imu
->nr_bvecs
, offset
+ len
);
1194 * Don't use iov_iter_advance() here, as it's really slow for
1195 * using the latter parts of a big fixed buffer - it iterates
1196 * over each segment manually. We can cheat a bit here, because
1199 * 1) it's a BVEC iter, we set it up
1200 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1201 * first and last bvec
1203 * So just find our index, and adjust the iterator afterwards.
1204 * If the offset is within the first bvec (or the whole first
1205 * bvec, just use iov_iter_advance(). This makes it easier
1206 * since we can just skip the first segment, which may not
1207 * be PAGE_SIZE aligned.
1209 const struct bio_vec
*bvec
= imu
->bvec
;
1211 if (offset
<= bvec
->bv_len
) {
1212 iov_iter_advance(iter
, offset
);
1214 unsigned long seg_skip
;
1216 /* skip first vec */
1217 offset
-= bvec
->bv_len
;
1218 seg_skip
= 1 + (offset
>> PAGE_SHIFT
);
1220 iter
->bvec
= bvec
+ seg_skip
;
1221 iter
->nr_segs
-= seg_skip
;
1222 iter
->count
-= bvec
->bv_len
+ offset
;
1223 iter
->iov_offset
= offset
& ~PAGE_MASK
;
1230 static ssize_t
io_import_iovec(struct io_ring_ctx
*ctx
, int rw
,
1231 const struct sqe_submit
*s
, struct iovec
**iovec
,
1232 struct iov_iter
*iter
)
1234 const struct io_uring_sqe
*sqe
= s
->sqe
;
1235 void __user
*buf
= u64_to_user_ptr(READ_ONCE(sqe
->addr
));
1236 size_t sqe_len
= READ_ONCE(sqe
->len
);
1240 * We're reading ->opcode for the second time, but the first read
1241 * doesn't care whether it's _FIXED or not, so it doesn't matter
1242 * whether ->opcode changes concurrently. The first read does care
1243 * about whether it is a READ or a WRITE, so we don't trust this read
1244 * for that purpose and instead let the caller pass in the read/write
1247 opcode
= READ_ONCE(sqe
->opcode
);
1248 if (opcode
== IORING_OP_READ_FIXED
||
1249 opcode
== IORING_OP_WRITE_FIXED
) {
1250 ssize_t ret
= io_import_fixed(ctx
, rw
, sqe
, iter
);
1258 #ifdef CONFIG_COMPAT
1260 return compat_import_iovec(rw
, buf
, sqe_len
, UIO_FASTIOV
,
1264 return import_iovec(rw
, buf
, sqe_len
, UIO_FASTIOV
, iovec
, iter
);
1267 static inline bool io_should_merge(struct async_list
*al
, struct kiocb
*kiocb
)
1269 if (al
->file
== kiocb
->ki_filp
) {
1273 * Allow merging if we're anywhere in the range of the same
1274 * page. Generally this happens for sub-page reads or writes,
1275 * and it's beneficial to allow the first worker to bring the
1276 * page in and the piggy backed work can then work on the
1279 start
= al
->io_start
& PAGE_MASK
;
1280 end
= (al
->io_start
+ al
->io_len
+ PAGE_SIZE
- 1) & PAGE_MASK
;
1281 if (kiocb
->ki_pos
>= start
&& kiocb
->ki_pos
<= end
)
1290 * Make a note of the last file/offset/direction we punted to async
1291 * context. We'll use this information to see if we can piggy back a
1292 * sequential request onto the previous one, if it's still hasn't been
1293 * completed by the async worker.
1295 static void io_async_list_note(int rw
, struct io_kiocb
*req
, size_t len
)
1297 struct async_list
*async_list
= &req
->ctx
->pending_async
[rw
];
1298 struct kiocb
*kiocb
= &req
->rw
;
1299 struct file
*filp
= kiocb
->ki_filp
;
1301 if (io_should_merge(async_list
, kiocb
)) {
1302 unsigned long max_bytes
;
1304 /* Use 8x RA size as a decent limiter for both reads/writes */
1305 max_bytes
= filp
->f_ra
.ra_pages
<< (PAGE_SHIFT
+ 3);
1307 max_bytes
= VM_READAHEAD_PAGES
<< (PAGE_SHIFT
+ 3);
1309 /* If max len are exceeded, reset the state */
1310 if (async_list
->io_len
+ len
<= max_bytes
) {
1311 req
->flags
|= REQ_F_SEQ_PREV
;
1312 async_list
->io_len
+= len
;
1314 async_list
->file
= NULL
;
1318 /* New file? Reset state. */
1319 if (async_list
->file
!= filp
) {
1320 async_list
->io_start
= kiocb
->ki_pos
;
1321 async_list
->io_len
= len
;
1322 async_list
->file
= filp
;
1327 * For files that don't have ->read_iter() and ->write_iter(), handle them
1328 * by looping over ->read() or ->write() manually.
1330 static ssize_t
loop_rw_iter(int rw
, struct file
*file
, struct kiocb
*kiocb
,
1331 struct iov_iter
*iter
)
1336 * Don't support polled IO through this interface, and we can't
1337 * support non-blocking either. For the latter, this just causes
1338 * the kiocb to be handled from an async context.
1340 if (kiocb
->ki_flags
& IOCB_HIPRI
)
1342 if (kiocb
->ki_flags
& IOCB_NOWAIT
)
1345 while (iov_iter_count(iter
)) {
1346 struct iovec iovec
= iov_iter_iovec(iter
);
1350 nr
= file
->f_op
->read(file
, iovec
.iov_base
,
1351 iovec
.iov_len
, &kiocb
->ki_pos
);
1353 nr
= file
->f_op
->write(file
, iovec
.iov_base
,
1354 iovec
.iov_len
, &kiocb
->ki_pos
);
1363 if (nr
!= iovec
.iov_len
)
1365 iov_iter_advance(iter
, nr
);
1371 static int io_read(struct io_kiocb
*req
, const struct sqe_submit
*s
,
1372 bool force_nonblock
)
1374 struct iovec inline_vecs
[UIO_FASTIOV
], *iovec
= inline_vecs
;
1375 struct kiocb
*kiocb
= &req
->rw
;
1376 struct iov_iter iter
;
1379 ssize_t read_size
, ret
;
1381 ret
= io_prep_rw(req
, s
, force_nonblock
);
1384 file
= kiocb
->ki_filp
;
1386 if (unlikely(!(file
->f_mode
& FMODE_READ
)))
1389 ret
= io_import_iovec(req
->ctx
, READ
, s
, &iovec
, &iter
);
1394 if (req
->flags
& REQ_F_LINK
)
1395 req
->result
= read_size
;
1397 iov_count
= iov_iter_count(&iter
);
1398 ret
= rw_verify_area(READ
, file
, &kiocb
->ki_pos
, iov_count
);
1402 if (file
->f_op
->read_iter
)
1403 ret2
= call_read_iter(file
, kiocb
, &iter
);
1405 ret2
= loop_rw_iter(READ
, file
, kiocb
, &iter
);
1408 * In case of a short read, punt to async. This can happen
1409 * if we have data partially cached. Alternatively we can
1410 * return the short read, in which case the application will
1411 * need to issue another SQE and wait for it. That SQE will
1412 * need async punt anyway, so it's more efficient to do it
1415 if (force_nonblock
&& !(req
->flags
& REQ_F_NOWAIT
) &&
1416 (req
->flags
& REQ_F_ISREG
) &&
1417 ret2
> 0 && ret2
< read_size
)
1419 /* Catch -EAGAIN return for forced non-blocking submission */
1420 if (!force_nonblock
|| ret2
!= -EAGAIN
) {
1421 io_rw_done(kiocb
, ret2
);
1424 * If ->needs_lock is true, we're already in async
1428 io_async_list_note(READ
, req
, iov_count
);
1436 static int io_write(struct io_kiocb
*req
, const struct sqe_submit
*s
,
1437 bool force_nonblock
)
1439 struct iovec inline_vecs
[UIO_FASTIOV
], *iovec
= inline_vecs
;
1440 struct kiocb
*kiocb
= &req
->rw
;
1441 struct iov_iter iter
;
1446 ret
= io_prep_rw(req
, s
, force_nonblock
);
1450 file
= kiocb
->ki_filp
;
1451 if (unlikely(!(file
->f_mode
& FMODE_WRITE
)))
1454 ret
= io_import_iovec(req
->ctx
, WRITE
, s
, &iovec
, &iter
);
1458 if (req
->flags
& REQ_F_LINK
)
1461 iov_count
= iov_iter_count(&iter
);
1464 if (force_nonblock
&& !(kiocb
->ki_flags
& IOCB_DIRECT
)) {
1465 /* If ->needs_lock is true, we're already in async context. */
1467 io_async_list_note(WRITE
, req
, iov_count
);
1471 ret
= rw_verify_area(WRITE
, file
, &kiocb
->ki_pos
, iov_count
);
1476 * Open-code file_start_write here to grab freeze protection,
1477 * which will be released by another thread in
1478 * io_complete_rw(). Fool lockdep by telling it the lock got
1479 * released so that it doesn't complain about the held lock when
1480 * we return to userspace.
1482 if (req
->flags
& REQ_F_ISREG
) {
1483 __sb_start_write(file_inode(file
)->i_sb
,
1484 SB_FREEZE_WRITE
, true);
1485 __sb_writers_release(file_inode(file
)->i_sb
,
1488 kiocb
->ki_flags
|= IOCB_WRITE
;
1490 if (file
->f_op
->write_iter
)
1491 ret2
= call_write_iter(file
, kiocb
, &iter
);
1493 ret2
= loop_rw_iter(WRITE
, file
, kiocb
, &iter
);
1494 if (!force_nonblock
|| ret2
!= -EAGAIN
) {
1495 io_rw_done(kiocb
, ret2
);
1498 * If ->needs_lock is true, we're already in async
1502 io_async_list_note(WRITE
, req
, iov_count
);
1512 * IORING_OP_NOP just posts a completion event, nothing else.
1514 static int io_nop(struct io_kiocb
*req
, u64 user_data
)
1516 struct io_ring_ctx
*ctx
= req
->ctx
;
1519 if (unlikely(ctx
->flags
& IORING_SETUP_IOPOLL
))
1522 io_cqring_add_event(ctx
, user_data
, err
);
1527 static int io_prep_fsync(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1529 struct io_ring_ctx
*ctx
= req
->ctx
;
1534 if (unlikely(ctx
->flags
& IORING_SETUP_IOPOLL
))
1536 if (unlikely(sqe
->addr
|| sqe
->ioprio
|| sqe
->buf_index
))
1542 static int io_fsync(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
,
1543 bool force_nonblock
)
1545 loff_t sqe_off
= READ_ONCE(sqe
->off
);
1546 loff_t sqe_len
= READ_ONCE(sqe
->len
);
1547 loff_t end
= sqe_off
+ sqe_len
;
1548 unsigned fsync_flags
;
1551 fsync_flags
= READ_ONCE(sqe
->fsync_flags
);
1552 if (unlikely(fsync_flags
& ~IORING_FSYNC_DATASYNC
))
1555 ret
= io_prep_fsync(req
, sqe
);
1559 /* fsync always requires a blocking context */
1563 ret
= vfs_fsync_range(req
->rw
.ki_filp
, sqe_off
,
1564 end
> 0 ? end
: LLONG_MAX
,
1565 fsync_flags
& IORING_FSYNC_DATASYNC
);
1567 if (ret
< 0 && (req
->flags
& REQ_F_LINK
))
1568 req
->flags
|= REQ_F_FAIL_LINK
;
1569 io_cqring_add_event(req
->ctx
, sqe
->user_data
, ret
);
1574 static int io_prep_sfr(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1576 struct io_ring_ctx
*ctx
= req
->ctx
;
1582 if (unlikely(ctx
->flags
& IORING_SETUP_IOPOLL
))
1584 if (unlikely(sqe
->addr
|| sqe
->ioprio
|| sqe
->buf_index
))
1590 static int io_sync_file_range(struct io_kiocb
*req
,
1591 const struct io_uring_sqe
*sqe
,
1592 bool force_nonblock
)
1599 ret
= io_prep_sfr(req
, sqe
);
1603 /* sync_file_range always requires a blocking context */
1607 sqe_off
= READ_ONCE(sqe
->off
);
1608 sqe_len
= READ_ONCE(sqe
->len
);
1609 flags
= READ_ONCE(sqe
->sync_range_flags
);
1611 ret
= sync_file_range(req
->rw
.ki_filp
, sqe_off
, sqe_len
, flags
);
1613 if (ret
< 0 && (req
->flags
& REQ_F_LINK
))
1614 req
->flags
|= REQ_F_FAIL_LINK
;
1615 io_cqring_add_event(req
->ctx
, sqe
->user_data
, ret
);
1620 #if defined(CONFIG_NET)
1621 static int io_send_recvmsg(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
,
1622 bool force_nonblock
,
1623 long (*fn
)(struct socket
*, struct user_msghdr __user
*,
1626 struct socket
*sock
;
1629 if (unlikely(req
->ctx
->flags
& IORING_SETUP_IOPOLL
))
1632 sock
= sock_from_file(req
->file
, &ret
);
1634 struct user_msghdr __user
*msg
;
1637 flags
= READ_ONCE(sqe
->msg_flags
);
1638 if (flags
& MSG_DONTWAIT
)
1639 req
->flags
|= REQ_F_NOWAIT
;
1640 else if (force_nonblock
)
1641 flags
|= MSG_DONTWAIT
;
1643 msg
= (struct user_msghdr __user
*) (unsigned long)
1644 READ_ONCE(sqe
->addr
);
1646 ret
= fn(sock
, msg
, flags
);
1647 if (force_nonblock
&& ret
== -EAGAIN
)
1651 io_cqring_add_event(req
->ctx
, sqe
->user_data
, ret
);
1657 static int io_sendmsg(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
,
1658 bool force_nonblock
)
1660 #if defined(CONFIG_NET)
1661 return io_send_recvmsg(req
, sqe
, force_nonblock
, __sys_sendmsg_sock
);
1667 static int io_recvmsg(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
,
1668 bool force_nonblock
)
1670 #if defined(CONFIG_NET)
1671 return io_send_recvmsg(req
, sqe
, force_nonblock
, __sys_recvmsg_sock
);
1677 static void io_poll_remove_one(struct io_kiocb
*req
)
1679 struct io_poll_iocb
*poll
= &req
->poll
;
1681 spin_lock(&poll
->head
->lock
);
1682 WRITE_ONCE(poll
->canceled
, true);
1683 if (!list_empty(&poll
->wait
.entry
)) {
1684 list_del_init(&poll
->wait
.entry
);
1685 io_queue_async_work(req
->ctx
, req
);
1687 spin_unlock(&poll
->head
->lock
);
1689 list_del_init(&req
->list
);
1692 static void io_poll_remove_all(struct io_ring_ctx
*ctx
)
1694 struct io_kiocb
*req
;
1696 spin_lock_irq(&ctx
->completion_lock
);
1697 while (!list_empty(&ctx
->cancel_list
)) {
1698 req
= list_first_entry(&ctx
->cancel_list
, struct io_kiocb
,list
);
1699 io_poll_remove_one(req
);
1701 spin_unlock_irq(&ctx
->completion_lock
);
1705 * Find a running poll command that matches one specified in sqe->addr,
1706 * and remove it if found.
1708 static int io_poll_remove(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1710 struct io_ring_ctx
*ctx
= req
->ctx
;
1711 struct io_kiocb
*poll_req
, *next
;
1714 if (unlikely(req
->ctx
->flags
& IORING_SETUP_IOPOLL
))
1716 if (sqe
->ioprio
|| sqe
->off
|| sqe
->len
|| sqe
->buf_index
||
1720 spin_lock_irq(&ctx
->completion_lock
);
1721 list_for_each_entry_safe(poll_req
, next
, &ctx
->cancel_list
, list
) {
1722 if (READ_ONCE(sqe
->addr
) == poll_req
->user_data
) {
1723 io_poll_remove_one(poll_req
);
1728 spin_unlock_irq(&ctx
->completion_lock
);
1730 io_cqring_add_event(req
->ctx
, sqe
->user_data
, ret
);
1735 static void io_poll_complete(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
1738 req
->poll
.done
= true;
1739 io_cqring_fill_event(ctx
, req
->user_data
, mangle_poll(mask
));
1740 io_commit_cqring(ctx
);
1743 static void io_poll_complete_work(struct work_struct
*work
)
1745 struct io_kiocb
*req
= container_of(work
, struct io_kiocb
, work
);
1746 struct io_poll_iocb
*poll
= &req
->poll
;
1747 struct poll_table_struct pt
= { ._key
= poll
->events
};
1748 struct io_ring_ctx
*ctx
= req
->ctx
;
1751 if (!READ_ONCE(poll
->canceled
))
1752 mask
= vfs_poll(poll
->file
, &pt
) & poll
->events
;
1755 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1756 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1757 * synchronize with them. In the cancellation case the list_del_init
1758 * itself is not actually needed, but harmless so we keep it in to
1759 * avoid further branches in the fast path.
1761 spin_lock_irq(&ctx
->completion_lock
);
1762 if (!mask
&& !READ_ONCE(poll
->canceled
)) {
1763 add_wait_queue(poll
->head
, &poll
->wait
);
1764 spin_unlock_irq(&ctx
->completion_lock
);
1767 list_del_init(&req
->list
);
1768 io_poll_complete(ctx
, req
, mask
);
1769 spin_unlock_irq(&ctx
->completion_lock
);
1771 io_cqring_ev_posted(ctx
);
1775 static int io_poll_wake(struct wait_queue_entry
*wait
, unsigned mode
, int sync
,
1778 struct io_poll_iocb
*poll
= container_of(wait
, struct io_poll_iocb
,
1780 struct io_kiocb
*req
= container_of(poll
, struct io_kiocb
, poll
);
1781 struct io_ring_ctx
*ctx
= req
->ctx
;
1782 __poll_t mask
= key_to_poll(key
);
1783 unsigned long flags
;
1785 /* for instances that support it check for an event match first: */
1786 if (mask
&& !(mask
& poll
->events
))
1789 list_del_init(&poll
->wait
.entry
);
1791 if (mask
&& spin_trylock_irqsave(&ctx
->completion_lock
, flags
)) {
1792 list_del(&req
->list
);
1793 io_poll_complete(ctx
, req
, mask
);
1794 spin_unlock_irqrestore(&ctx
->completion_lock
, flags
);
1796 io_cqring_ev_posted(ctx
);
1799 io_queue_async_work(ctx
, req
);
1805 struct io_poll_table
{
1806 struct poll_table_struct pt
;
1807 struct io_kiocb
*req
;
1811 static void io_poll_queue_proc(struct file
*file
, struct wait_queue_head
*head
,
1812 struct poll_table_struct
*p
)
1814 struct io_poll_table
*pt
= container_of(p
, struct io_poll_table
, pt
);
1816 if (unlikely(pt
->req
->poll
.head
)) {
1817 pt
->error
= -EINVAL
;
1822 pt
->req
->poll
.head
= head
;
1823 add_wait_queue(head
, &pt
->req
->poll
.wait
);
1826 static int io_poll_add(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1828 struct io_poll_iocb
*poll
= &req
->poll
;
1829 struct io_ring_ctx
*ctx
= req
->ctx
;
1830 struct io_poll_table ipt
;
1831 bool cancel
= false;
1835 if (unlikely(req
->ctx
->flags
& IORING_SETUP_IOPOLL
))
1837 if (sqe
->addr
|| sqe
->ioprio
|| sqe
->off
|| sqe
->len
|| sqe
->buf_index
)
1842 req
->submit
.sqe
= NULL
;
1843 INIT_WORK(&req
->work
, io_poll_complete_work
);
1844 events
= READ_ONCE(sqe
->poll_events
);
1845 poll
->events
= demangle_poll(events
) | EPOLLERR
| EPOLLHUP
;
1849 poll
->canceled
= false;
1851 ipt
.pt
._qproc
= io_poll_queue_proc
;
1852 ipt
.pt
._key
= poll
->events
;
1854 ipt
.error
= -EINVAL
; /* same as no support for IOCB_CMD_POLL */
1856 /* initialized the list so that we can do list_empty checks */
1857 INIT_LIST_HEAD(&poll
->wait
.entry
);
1858 init_waitqueue_func_entry(&poll
->wait
, io_poll_wake
);
1860 INIT_LIST_HEAD(&req
->list
);
1862 mask
= vfs_poll(poll
->file
, &ipt
.pt
) & poll
->events
;
1864 spin_lock_irq(&ctx
->completion_lock
);
1865 if (likely(poll
->head
)) {
1866 spin_lock(&poll
->head
->lock
);
1867 if (unlikely(list_empty(&poll
->wait
.entry
))) {
1873 if (mask
|| ipt
.error
)
1874 list_del_init(&poll
->wait
.entry
);
1876 WRITE_ONCE(poll
->canceled
, true);
1877 else if (!poll
->done
) /* actually waiting for an event */
1878 list_add_tail(&req
->list
, &ctx
->cancel_list
);
1879 spin_unlock(&poll
->head
->lock
);
1881 if (mask
) { /* no async, we'd stolen it */
1883 io_poll_complete(ctx
, req
, mask
);
1885 spin_unlock_irq(&ctx
->completion_lock
);
1888 io_cqring_ev_posted(ctx
);
1894 static enum hrtimer_restart
io_timeout_fn(struct hrtimer
*timer
)
1896 struct io_ring_ctx
*ctx
;
1897 struct io_kiocb
*req
, *prev
;
1898 unsigned long flags
;
1900 req
= container_of(timer
, struct io_kiocb
, timeout
.timer
);
1902 atomic_inc(&ctx
->cq_timeouts
);
1904 spin_lock_irqsave(&ctx
->completion_lock
, flags
);
1906 * Adjust the reqs sequence before the current one because it
1907 * will consume a slot in the cq_ring and the the cq_tail pointer
1908 * will be increased, otherwise other timeout reqs may return in
1909 * advance without waiting for enough wait_nr.
1912 list_for_each_entry_continue_reverse(prev
, &ctx
->timeout_list
, list
)
1914 list_del(&req
->list
);
1916 io_cqring_fill_event(ctx
, req
->user_data
, -ETIME
);
1917 io_commit_cqring(ctx
);
1918 spin_unlock_irqrestore(&ctx
->completion_lock
, flags
);
1920 io_cqring_ev_posted(ctx
);
1923 return HRTIMER_NORESTART
;
1926 static int io_timeout(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1929 struct io_ring_ctx
*ctx
= req
->ctx
;
1930 struct list_head
*entry
;
1931 struct timespec64 ts
;
1934 if (unlikely(ctx
->flags
& IORING_SETUP_IOPOLL
))
1936 if (sqe
->flags
|| sqe
->ioprio
|| sqe
->buf_index
|| sqe
->timeout_flags
||
1940 if (get_timespec64(&ts
, u64_to_user_ptr(sqe
->addr
)))
1944 * sqe->off holds how many events that need to occur for this
1945 * timeout event to be satisfied.
1947 count
= READ_ONCE(sqe
->off
);
1951 req
->sequence
= ctx
->cached_sq_head
+ count
- 1;
1952 /* reuse it to store the count */
1953 req
->submit
.sequence
= count
;
1954 req
->flags
|= REQ_F_TIMEOUT
;
1957 * Insertion sort, ensuring the first entry in the list is always
1958 * the one we need first.
1960 spin_lock_irq(&ctx
->completion_lock
);
1961 list_for_each_prev(entry
, &ctx
->timeout_list
) {
1962 struct io_kiocb
*nxt
= list_entry(entry
, struct io_kiocb
, list
);
1963 unsigned nxt_sq_head
;
1964 long long tmp
, tmp_nxt
;
1967 * Since cached_sq_head + count - 1 can overflow, use type long
1970 tmp
= (long long)ctx
->cached_sq_head
+ count
- 1;
1971 nxt_sq_head
= nxt
->sequence
- nxt
->submit
.sequence
+ 1;
1972 tmp_nxt
= (long long)nxt_sq_head
+ nxt
->submit
.sequence
- 1;
1975 * cached_sq_head may overflow, and it will never overflow twice
1976 * once there is some timeout req still be valid.
1978 if (ctx
->cached_sq_head
< nxt_sq_head
)
1985 * Sequence of reqs after the insert one and itself should
1986 * be adjusted because each timeout req consumes a slot.
1991 req
->sequence
-= span
;
1992 list_add(&req
->list
, entry
);
1993 spin_unlock_irq(&ctx
->completion_lock
);
1995 hrtimer_init(&req
->timeout
.timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
1996 req
->timeout
.timer
.function
= io_timeout_fn
;
1997 hrtimer_start(&req
->timeout
.timer
, timespec64_to_ktime(ts
),
2002 static int io_req_defer(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2003 const struct io_uring_sqe
*sqe
)
2005 struct io_uring_sqe
*sqe_copy
;
2007 if (!io_sequence_defer(ctx
, req
) && list_empty(&ctx
->defer_list
))
2010 sqe_copy
= kmalloc(sizeof(*sqe_copy
), GFP_KERNEL
);
2014 spin_lock_irq(&ctx
->completion_lock
);
2015 if (!io_sequence_defer(ctx
, req
) && list_empty(&ctx
->defer_list
)) {
2016 spin_unlock_irq(&ctx
->completion_lock
);
2021 memcpy(sqe_copy
, sqe
, sizeof(*sqe_copy
));
2022 req
->submit
.sqe
= sqe_copy
;
2024 INIT_WORK(&req
->work
, io_sq_wq_submit_work
);
2025 list_add_tail(&req
->list
, &ctx
->defer_list
);
2026 spin_unlock_irq(&ctx
->completion_lock
);
2027 return -EIOCBQUEUED
;
2030 static int __io_submit_sqe(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2031 const struct sqe_submit
*s
, bool force_nonblock
)
2035 req
->user_data
= READ_ONCE(s
->sqe
->user_data
);
2037 if (unlikely(s
->index
>= ctx
->sq_entries
))
2040 opcode
= READ_ONCE(s
->sqe
->opcode
);
2043 ret
= io_nop(req
, req
->user_data
);
2045 case IORING_OP_READV
:
2046 if (unlikely(s
->sqe
->buf_index
))
2048 ret
= io_read(req
, s
, force_nonblock
);
2050 case IORING_OP_WRITEV
:
2051 if (unlikely(s
->sqe
->buf_index
))
2053 ret
= io_write(req
, s
, force_nonblock
);
2055 case IORING_OP_READ_FIXED
:
2056 ret
= io_read(req
, s
, force_nonblock
);
2058 case IORING_OP_WRITE_FIXED
:
2059 ret
= io_write(req
, s
, force_nonblock
);
2061 case IORING_OP_FSYNC
:
2062 ret
= io_fsync(req
, s
->sqe
, force_nonblock
);
2064 case IORING_OP_POLL_ADD
:
2065 ret
= io_poll_add(req
, s
->sqe
);
2067 case IORING_OP_POLL_REMOVE
:
2068 ret
= io_poll_remove(req
, s
->sqe
);
2070 case IORING_OP_SYNC_FILE_RANGE
:
2071 ret
= io_sync_file_range(req
, s
->sqe
, force_nonblock
);
2073 case IORING_OP_SENDMSG
:
2074 ret
= io_sendmsg(req
, s
->sqe
, force_nonblock
);
2076 case IORING_OP_RECVMSG
:
2077 ret
= io_recvmsg(req
, s
->sqe
, force_nonblock
);
2079 case IORING_OP_TIMEOUT
:
2080 ret
= io_timeout(req
, s
->sqe
);
2090 if (ctx
->flags
& IORING_SETUP_IOPOLL
) {
2091 if (req
->result
== -EAGAIN
)
2094 /* workqueue context doesn't hold uring_lock, grab it now */
2096 mutex_lock(&ctx
->uring_lock
);
2097 io_iopoll_req_issued(req
);
2099 mutex_unlock(&ctx
->uring_lock
);
2105 static struct async_list
*io_async_list_from_sqe(struct io_ring_ctx
*ctx
,
2106 const struct io_uring_sqe
*sqe
)
2108 switch (sqe
->opcode
) {
2109 case IORING_OP_READV
:
2110 case IORING_OP_READ_FIXED
:
2111 return &ctx
->pending_async
[READ
];
2112 case IORING_OP_WRITEV
:
2113 case IORING_OP_WRITE_FIXED
:
2114 return &ctx
->pending_async
[WRITE
];
2120 static inline bool io_sqe_needs_user(const struct io_uring_sqe
*sqe
)
2122 u8 opcode
= READ_ONCE(sqe
->opcode
);
2124 return !(opcode
== IORING_OP_READ_FIXED
||
2125 opcode
== IORING_OP_WRITE_FIXED
);
2128 static void io_sq_wq_submit_work(struct work_struct
*work
)
2130 struct io_kiocb
*req
= container_of(work
, struct io_kiocb
, work
);
2131 struct io_ring_ctx
*ctx
= req
->ctx
;
2132 struct mm_struct
*cur_mm
= NULL
;
2133 struct async_list
*async_list
;
2134 LIST_HEAD(req_list
);
2135 mm_segment_t old_fs
;
2138 async_list
= io_async_list_from_sqe(ctx
, req
->submit
.sqe
);
2141 struct sqe_submit
*s
= &req
->submit
;
2142 const struct io_uring_sqe
*sqe
= s
->sqe
;
2143 unsigned int flags
= req
->flags
;
2145 /* Ensure we clear previously set non-block flag */
2146 req
->rw
.ki_flags
&= ~IOCB_NOWAIT
;
2149 if (io_sqe_needs_user(sqe
) && !cur_mm
) {
2150 if (!mmget_not_zero(ctx
->sqo_mm
)) {
2153 cur_mm
= ctx
->sqo_mm
;
2161 s
->has_user
= cur_mm
!= NULL
;
2162 s
->needs_lock
= true;
2164 ret
= __io_submit_sqe(ctx
, req
, s
, false);
2166 * We can get EAGAIN for polled IO even though
2167 * we're forcing a sync submission from here,
2168 * since we can't wait for request slots on the
2177 /* drop submission reference */
2181 io_cqring_add_event(ctx
, sqe
->user_data
, ret
);
2185 /* async context always use a copy of the sqe */
2188 /* req from defer and link list needn't decrease async cnt */
2189 if (flags
& (REQ_F_IO_DRAINED
| REQ_F_LINK_DONE
))
2194 if (!list_empty(&req_list
)) {
2195 req
= list_first_entry(&req_list
, struct io_kiocb
,
2197 list_del(&req
->list
);
2200 if (list_empty(&async_list
->list
))
2204 spin_lock(&async_list
->lock
);
2205 if (list_empty(&async_list
->list
)) {
2206 spin_unlock(&async_list
->lock
);
2209 list_splice_init(&async_list
->list
, &req_list
);
2210 spin_unlock(&async_list
->lock
);
2212 req
= list_first_entry(&req_list
, struct io_kiocb
, list
);
2213 list_del(&req
->list
);
2217 * Rare case of racing with a submitter. If we find the count has
2218 * dropped to zero AND we have pending work items, then restart
2219 * the processing. This is a tiny race window.
2222 ret
= atomic_dec_return(&async_list
->cnt
);
2223 while (!ret
&& !list_empty(&async_list
->list
)) {
2224 spin_lock(&async_list
->lock
);
2225 atomic_inc(&async_list
->cnt
);
2226 list_splice_init(&async_list
->list
, &req_list
);
2227 spin_unlock(&async_list
->lock
);
2229 if (!list_empty(&req_list
)) {
2230 req
= list_first_entry(&req_list
,
2231 struct io_kiocb
, list
);
2232 list_del(&req
->list
);
2235 ret
= atomic_dec_return(&async_list
->cnt
);
2248 * See if we can piggy back onto previously submitted work, that is still
2249 * running. We currently only allow this if the new request is sequential
2250 * to the previous one we punted.
2252 static bool io_add_to_prev_work(struct async_list
*list
, struct io_kiocb
*req
)
2258 if (!(req
->flags
& REQ_F_SEQ_PREV
))
2260 if (!atomic_read(&list
->cnt
))
2264 spin_lock(&list
->lock
);
2265 list_add_tail(&req
->list
, &list
->list
);
2267 * Ensure we see a simultaneous modification from io_sq_wq_submit_work()
2270 if (!atomic_read(&list
->cnt
)) {
2271 list_del_init(&req
->list
);
2274 spin_unlock(&list
->lock
);
2278 static bool io_op_needs_file(const struct io_uring_sqe
*sqe
)
2280 int op
= READ_ONCE(sqe
->opcode
);
2284 case IORING_OP_POLL_REMOVE
:
2291 static int io_req_set_file(struct io_ring_ctx
*ctx
, const struct sqe_submit
*s
,
2292 struct io_submit_state
*state
, struct io_kiocb
*req
)
2297 flags
= READ_ONCE(s
->sqe
->flags
);
2298 fd
= READ_ONCE(s
->sqe
->fd
);
2300 if (flags
& IOSQE_IO_DRAIN
)
2301 req
->flags
|= REQ_F_IO_DRAIN
;
2303 * All io need record the previous position, if LINK vs DARIN,
2304 * it can be used to mark the position of the first IO in the
2307 req
->sequence
= s
->sequence
;
2309 if (!io_op_needs_file(s
->sqe
))
2312 if (flags
& IOSQE_FIXED_FILE
) {
2313 if (unlikely(!ctx
->user_files
||
2314 (unsigned) fd
>= ctx
->nr_user_files
))
2316 req
->file
= ctx
->user_files
[fd
];
2317 req
->flags
|= REQ_F_FIXED_FILE
;
2319 if (s
->needs_fixed_file
)
2321 req
->file
= io_file_get(state
, fd
);
2322 if (unlikely(!req
->file
))
2329 static int __io_queue_sqe(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2330 struct sqe_submit
*s
)
2334 ret
= __io_submit_sqe(ctx
, req
, s
, true);
2337 * We async punt it if the file wasn't marked NOWAIT, or if the file
2338 * doesn't support non-blocking read/write attempts
2340 if (ret
== -EAGAIN
&& (!(req
->flags
& REQ_F_NOWAIT
) ||
2341 (req
->flags
& REQ_F_MUST_PUNT
))) {
2342 struct io_uring_sqe
*sqe_copy
;
2344 sqe_copy
= kmemdup(s
->sqe
, sizeof(*sqe_copy
), GFP_KERNEL
);
2346 struct async_list
*list
;
2349 memcpy(&req
->submit
, s
, sizeof(*s
));
2350 list
= io_async_list_from_sqe(ctx
, s
->sqe
);
2351 if (!io_add_to_prev_work(list
, req
)) {
2353 atomic_inc(&list
->cnt
);
2354 INIT_WORK(&req
->work
, io_sq_wq_submit_work
);
2355 io_queue_async_work(ctx
, req
);
2359 * Queued up for async execution, worker will release
2360 * submit reference when the iocb is actually submitted.
2366 /* drop submission reference */
2369 /* and drop final reference, if we failed */
2371 io_cqring_add_event(ctx
, req
->user_data
, ret
);
2372 if (req
->flags
& REQ_F_LINK
)
2373 req
->flags
|= REQ_F_FAIL_LINK
;
2380 static int io_queue_sqe(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2381 struct sqe_submit
*s
)
2385 ret
= io_req_defer(ctx
, req
, s
->sqe
);
2387 if (ret
!= -EIOCBQUEUED
) {
2389 io_cqring_add_event(ctx
, s
->sqe
->user_data
, ret
);
2394 return __io_queue_sqe(ctx
, req
, s
);
2397 static int io_queue_link_head(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2398 struct sqe_submit
*s
, struct io_kiocb
*shadow
)
2401 int need_submit
= false;
2404 return io_queue_sqe(ctx
, req
, s
);
2407 * Mark the first IO in link list as DRAIN, let all the following
2408 * IOs enter the defer list. all IO needs to be completed before link
2411 req
->flags
|= REQ_F_IO_DRAIN
;
2412 ret
= io_req_defer(ctx
, req
, s
->sqe
);
2414 if (ret
!= -EIOCBQUEUED
) {
2416 io_cqring_add_event(ctx
, s
->sqe
->user_data
, ret
);
2421 * If ret == 0 means that all IOs in front of link io are
2422 * running done. let's queue link head.
2427 /* Insert shadow req to defer_list, blocking next IOs */
2428 spin_lock_irq(&ctx
->completion_lock
);
2429 list_add_tail(&shadow
->list
, &ctx
->defer_list
);
2430 spin_unlock_irq(&ctx
->completion_lock
);
2433 return __io_queue_sqe(ctx
, req
, s
);
2438 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2440 static void io_submit_sqe(struct io_ring_ctx
*ctx
, struct sqe_submit
*s
,
2441 struct io_submit_state
*state
, struct io_kiocb
**link
)
2443 struct io_uring_sqe
*sqe_copy
;
2444 struct io_kiocb
*req
;
2447 /* enforce forwards compatibility on users */
2448 if (unlikely(s
->sqe
->flags
& ~SQE_VALID_FLAGS
)) {
2453 req
= io_get_req(ctx
, state
);
2454 if (unlikely(!req
)) {
2459 ret
= io_req_set_file(ctx
, s
, state
, req
);
2460 if (unlikely(ret
)) {
2464 io_cqring_add_event(ctx
, s
->sqe
->user_data
, ret
);
2468 req
->user_data
= s
->sqe
->user_data
;
2471 * If we already have a head request, queue this one for async
2472 * submittal once the head completes. If we don't have a head but
2473 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2474 * submitted sync once the chain is complete. If none of those
2475 * conditions are true (normal request), then just queue it.
2478 struct io_kiocb
*prev
= *link
;
2480 sqe_copy
= kmemdup(s
->sqe
, sizeof(*sqe_copy
), GFP_KERNEL
);
2487 memcpy(&req
->submit
, s
, sizeof(*s
));
2488 list_add_tail(&req
->list
, &prev
->link_list
);
2489 } else if (s
->sqe
->flags
& IOSQE_IO_LINK
) {
2490 req
->flags
|= REQ_F_LINK
;
2492 memcpy(&req
->submit
, s
, sizeof(*s
));
2493 INIT_LIST_HEAD(&req
->link_list
);
2496 io_queue_sqe(ctx
, req
, s
);
2501 * Batched submission is done, ensure local IO is flushed out.
2503 static void io_submit_state_end(struct io_submit_state
*state
)
2505 blk_finish_plug(&state
->plug
);
2507 if (state
->free_reqs
)
2508 kmem_cache_free_bulk(req_cachep
, state
->free_reqs
,
2509 &state
->reqs
[state
->cur_req
]);
2513 * Start submission side cache.
2515 static void io_submit_state_start(struct io_submit_state
*state
,
2516 struct io_ring_ctx
*ctx
, unsigned max_ios
)
2518 blk_start_plug(&state
->plug
);
2519 state
->free_reqs
= 0;
2521 state
->ios_left
= max_ios
;
2524 static void io_commit_sqring(struct io_ring_ctx
*ctx
)
2526 struct io_rings
*rings
= ctx
->rings
;
2528 if (ctx
->cached_sq_head
!= READ_ONCE(rings
->sq
.head
)) {
2530 * Ensure any loads from the SQEs are done at this point,
2531 * since once we write the new head, the application could
2532 * write new data to them.
2534 smp_store_release(&rings
->sq
.head
, ctx
->cached_sq_head
);
2539 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2540 * that is mapped by userspace. This means that care needs to be taken to
2541 * ensure that reads are stable, as we cannot rely on userspace always
2542 * being a good citizen. If members of the sqe are validated and then later
2543 * used, it's important that those reads are done through READ_ONCE() to
2544 * prevent a re-load down the line.
2546 static bool io_get_sqring(struct io_ring_ctx
*ctx
, struct sqe_submit
*s
)
2548 struct io_rings
*rings
= ctx
->rings
;
2549 u32
*sq_array
= ctx
->sq_array
;
2553 * The cached sq head (or cq tail) serves two purposes:
2555 * 1) allows us to batch the cost of updating the user visible
2557 * 2) allows the kernel side to track the head on its own, even
2558 * though the application is the one updating it.
2560 head
= ctx
->cached_sq_head
;
2561 /* make sure SQ entry isn't read before tail */
2562 if (head
== smp_load_acquire(&rings
->sq
.tail
))
2565 head
= READ_ONCE(sq_array
[head
& ctx
->sq_mask
]);
2566 if (head
< ctx
->sq_entries
) {
2568 s
->sqe
= &ctx
->sq_sqes
[head
];
2569 s
->sequence
= ctx
->cached_sq_head
;
2570 ctx
->cached_sq_head
++;
2574 /* drop invalid entries */
2575 ctx
->cached_sq_head
++;
2576 ctx
->cached_sq_dropped
++;
2577 WRITE_ONCE(rings
->sq_dropped
, ctx
->cached_sq_dropped
);
2581 static int io_submit_sqes(struct io_ring_ctx
*ctx
, unsigned int nr
,
2582 bool has_user
, bool mm_fault
)
2584 struct io_submit_state state
, *statep
= NULL
;
2585 struct io_kiocb
*link
= NULL
;
2586 struct io_kiocb
*shadow_req
= NULL
;
2587 bool prev_was_link
= false;
2588 int i
, submitted
= 0;
2590 if (nr
> IO_PLUG_THRESHOLD
) {
2591 io_submit_state_start(&state
, ctx
, nr
);
2595 for (i
= 0; i
< nr
; i
++) {
2596 struct sqe_submit s
;
2598 if (!io_get_sqring(ctx
, &s
))
2602 * If previous wasn't linked and we have a linked command,
2603 * that's the end of the chain. Submit the previous link.
2605 if (!prev_was_link
&& link
) {
2606 io_queue_link_head(ctx
, link
, &link
->submit
, shadow_req
);
2610 prev_was_link
= (s
.sqe
->flags
& IOSQE_IO_LINK
) != 0;
2612 if (link
&& (s
.sqe
->flags
& IOSQE_IO_DRAIN
)) {
2614 shadow_req
= io_get_req(ctx
, NULL
);
2615 if (unlikely(!shadow_req
))
2617 shadow_req
->flags
|= (REQ_F_IO_DRAIN
| REQ_F_SHADOW_DRAIN
);
2618 refcount_dec(&shadow_req
->refs
);
2620 shadow_req
->sequence
= s
.sequence
;
2624 if (unlikely(mm_fault
)) {
2625 io_cqring_add_event(ctx
, s
.sqe
->user_data
,
2628 s
.has_user
= has_user
;
2629 s
.needs_lock
= true;
2630 s
.needs_fixed_file
= true;
2631 io_submit_sqe(ctx
, &s
, statep
, &link
);
2637 io_queue_link_head(ctx
, link
, &link
->submit
, shadow_req
);
2639 io_submit_state_end(&state
);
2644 static int io_sq_thread(void *data
)
2646 struct io_ring_ctx
*ctx
= data
;
2647 struct mm_struct
*cur_mm
= NULL
;
2648 mm_segment_t old_fs
;
2651 unsigned long timeout
;
2653 complete(&ctx
->sqo_thread_started
);
2658 timeout
= inflight
= 0;
2659 while (!kthread_should_park()) {
2660 bool mm_fault
= false;
2661 unsigned int to_submit
;
2664 unsigned nr_events
= 0;
2666 if (ctx
->flags
& IORING_SETUP_IOPOLL
) {
2668 * inflight is the count of the maximum possible
2669 * entries we submitted, but it can be smaller
2670 * if we dropped some of them. If we don't have
2671 * poll entries available, then we know that we
2672 * have nothing left to poll for. Reset the
2673 * inflight count to zero in that case.
2675 mutex_lock(&ctx
->uring_lock
);
2676 if (!list_empty(&ctx
->poll_list
))
2677 __io_iopoll_check(ctx
, &nr_events
, 0);
2680 mutex_unlock(&ctx
->uring_lock
);
2683 * Normal IO, just pretend everything completed.
2684 * We don't have to poll completions for that.
2686 nr_events
= inflight
;
2689 inflight
-= nr_events
;
2691 timeout
= jiffies
+ ctx
->sq_thread_idle
;
2694 to_submit
= io_sqring_entries(ctx
);
2697 * We're polling. If we're within the defined idle
2698 * period, then let us spin without work before going
2701 if (inflight
|| !time_after(jiffies
, timeout
)) {
2707 * Drop cur_mm before scheduling, we can't hold it for
2708 * long periods (or over schedule()). Do this before
2709 * adding ourselves to the waitqueue, as the unuse/drop
2718 prepare_to_wait(&ctx
->sqo_wait
, &wait
,
2719 TASK_INTERRUPTIBLE
);
2721 /* Tell userspace we may need a wakeup call */
2722 ctx
->rings
->sq_flags
|= IORING_SQ_NEED_WAKEUP
;
2723 /* make sure to read SQ tail after writing flags */
2726 to_submit
= io_sqring_entries(ctx
);
2728 if (kthread_should_park()) {
2729 finish_wait(&ctx
->sqo_wait
, &wait
);
2732 if (signal_pending(current
))
2733 flush_signals(current
);
2735 finish_wait(&ctx
->sqo_wait
, &wait
);
2737 ctx
->rings
->sq_flags
&= ~IORING_SQ_NEED_WAKEUP
;
2740 finish_wait(&ctx
->sqo_wait
, &wait
);
2742 ctx
->rings
->sq_flags
&= ~IORING_SQ_NEED_WAKEUP
;
2745 /* Unless all new commands are FIXED regions, grab mm */
2747 mm_fault
= !mmget_not_zero(ctx
->sqo_mm
);
2749 use_mm(ctx
->sqo_mm
);
2750 cur_mm
= ctx
->sqo_mm
;
2754 to_submit
= min(to_submit
, ctx
->sq_entries
);
2755 inflight
+= io_submit_sqes(ctx
, to_submit
, cur_mm
!= NULL
,
2758 /* Commit SQ ring head once we've consumed all SQEs */
2759 io_commit_sqring(ctx
);
2773 static int io_ring_submit(struct io_ring_ctx
*ctx
, unsigned int to_submit
)
2775 struct io_submit_state state
, *statep
= NULL
;
2776 struct io_kiocb
*link
= NULL
;
2777 struct io_kiocb
*shadow_req
= NULL
;
2778 bool prev_was_link
= false;
2781 if (to_submit
> IO_PLUG_THRESHOLD
) {
2782 io_submit_state_start(&state
, ctx
, to_submit
);
2786 for (i
= 0; i
< to_submit
; i
++) {
2787 struct sqe_submit s
;
2789 if (!io_get_sqring(ctx
, &s
))
2793 * If previous wasn't linked and we have a linked command,
2794 * that's the end of the chain. Submit the previous link.
2796 if (!prev_was_link
&& link
) {
2797 io_queue_link_head(ctx
, link
, &link
->submit
, shadow_req
);
2801 prev_was_link
= (s
.sqe
->flags
& IOSQE_IO_LINK
) != 0;
2803 if (link
&& (s
.sqe
->flags
& IOSQE_IO_DRAIN
)) {
2805 shadow_req
= io_get_req(ctx
, NULL
);
2806 if (unlikely(!shadow_req
))
2808 shadow_req
->flags
|= (REQ_F_IO_DRAIN
| REQ_F_SHADOW_DRAIN
);
2809 refcount_dec(&shadow_req
->refs
);
2811 shadow_req
->sequence
= s
.sequence
;
2816 s
.needs_lock
= false;
2817 s
.needs_fixed_file
= false;
2819 io_submit_sqe(ctx
, &s
, statep
, &link
);
2823 io_queue_link_head(ctx
, link
, &link
->submit
, shadow_req
);
2825 io_submit_state_end(statep
);
2827 io_commit_sqring(ctx
);
2832 struct io_wait_queue
{
2833 struct wait_queue_entry wq
;
2834 struct io_ring_ctx
*ctx
;
2836 unsigned nr_timeouts
;
2839 static inline bool io_should_wake(struct io_wait_queue
*iowq
)
2841 struct io_ring_ctx
*ctx
= iowq
->ctx
;
2844 * Wake up if we have enough events, or if a timeout occured since we
2845 * started waiting. For timeouts, we always want to return to userspace,
2846 * regardless of event count.
2848 return io_cqring_events(ctx
->rings
) >= iowq
->to_wait
||
2849 atomic_read(&ctx
->cq_timeouts
) != iowq
->nr_timeouts
;
2852 static int io_wake_function(struct wait_queue_entry
*curr
, unsigned int mode
,
2853 int wake_flags
, void *key
)
2855 struct io_wait_queue
*iowq
= container_of(curr
, struct io_wait_queue
,
2858 if (!io_should_wake(iowq
))
2861 return autoremove_wake_function(curr
, mode
, wake_flags
, key
);
2865 * Wait until events become available, if we don't already have some. The
2866 * application must reap them itself, as they reside on the shared cq ring.
2868 static int io_cqring_wait(struct io_ring_ctx
*ctx
, int min_events
,
2869 const sigset_t __user
*sig
, size_t sigsz
)
2871 struct io_wait_queue iowq
= {
2874 .func
= io_wake_function
,
2875 .entry
= LIST_HEAD_INIT(iowq
.wq
.entry
),
2878 .to_wait
= min_events
,
2880 struct io_rings
*rings
= ctx
->rings
;
2883 if (io_cqring_events(rings
) >= min_events
)
2887 #ifdef CONFIG_COMPAT
2888 if (in_compat_syscall())
2889 ret
= set_compat_user_sigmask((const compat_sigset_t __user
*)sig
,
2893 ret
= set_user_sigmask(sig
, sigsz
);
2900 iowq
.nr_timeouts
= atomic_read(&ctx
->cq_timeouts
);
2902 prepare_to_wait_exclusive(&ctx
->wait
, &iowq
.wq
,
2903 TASK_INTERRUPTIBLE
);
2904 if (io_should_wake(&iowq
))
2907 if (signal_pending(current
)) {
2912 finish_wait(&ctx
->wait
, &iowq
.wq
);
2914 restore_saved_sigmask_unless(ret
== -ERESTARTSYS
);
2915 if (ret
== -ERESTARTSYS
)
2918 return READ_ONCE(rings
->cq
.head
) == READ_ONCE(rings
->cq
.tail
) ? ret
: 0;
2921 static void __io_sqe_files_unregister(struct io_ring_ctx
*ctx
)
2923 #if defined(CONFIG_UNIX)
2924 if (ctx
->ring_sock
) {
2925 struct sock
*sock
= ctx
->ring_sock
->sk
;
2926 struct sk_buff
*skb
;
2928 while ((skb
= skb_dequeue(&sock
->sk_receive_queue
)) != NULL
)
2934 for (i
= 0; i
< ctx
->nr_user_files
; i
++)
2935 fput(ctx
->user_files
[i
]);
2939 static int io_sqe_files_unregister(struct io_ring_ctx
*ctx
)
2941 if (!ctx
->user_files
)
2944 __io_sqe_files_unregister(ctx
);
2945 kfree(ctx
->user_files
);
2946 ctx
->user_files
= NULL
;
2947 ctx
->nr_user_files
= 0;
2951 static void io_sq_thread_stop(struct io_ring_ctx
*ctx
)
2953 if (ctx
->sqo_thread
) {
2954 wait_for_completion(&ctx
->sqo_thread_started
);
2956 * The park is a bit of a work-around, without it we get
2957 * warning spews on shutdown with SQPOLL set and affinity
2958 * set to a single CPU.
2960 kthread_park(ctx
->sqo_thread
);
2961 kthread_stop(ctx
->sqo_thread
);
2962 ctx
->sqo_thread
= NULL
;
2966 static void io_finish_async(struct io_ring_ctx
*ctx
)
2970 io_sq_thread_stop(ctx
);
2972 for (i
= 0; i
< ARRAY_SIZE(ctx
->sqo_wq
); i
++) {
2973 if (ctx
->sqo_wq
[i
]) {
2974 destroy_workqueue(ctx
->sqo_wq
[i
]);
2975 ctx
->sqo_wq
[i
] = NULL
;
2980 #if defined(CONFIG_UNIX)
2981 static void io_destruct_skb(struct sk_buff
*skb
)
2983 struct io_ring_ctx
*ctx
= skb
->sk
->sk_user_data
;
2986 for (i
= 0; i
< ARRAY_SIZE(ctx
->sqo_wq
); i
++)
2988 flush_workqueue(ctx
->sqo_wq
[i
]);
2990 unix_destruct_scm(skb
);
2994 * Ensure the UNIX gc is aware of our file set, so we are certain that
2995 * the io_uring can be safely unregistered on process exit, even if we have
2996 * loops in the file referencing.
2998 static int __io_sqe_files_scm(struct io_ring_ctx
*ctx
, int nr
, int offset
)
3000 struct sock
*sk
= ctx
->ring_sock
->sk
;
3001 struct scm_fp_list
*fpl
;
3002 struct sk_buff
*skb
;
3005 if (!capable(CAP_SYS_RESOURCE
) && !capable(CAP_SYS_ADMIN
)) {
3006 unsigned long inflight
= ctx
->user
->unix_inflight
+ nr
;
3008 if (inflight
> task_rlimit(current
, RLIMIT_NOFILE
))
3012 fpl
= kzalloc(sizeof(*fpl
), GFP_KERNEL
);
3016 skb
= alloc_skb(0, GFP_KERNEL
);
3023 skb
->destructor
= io_destruct_skb
;
3025 fpl
->user
= get_uid(ctx
->user
);
3026 for (i
= 0; i
< nr
; i
++) {
3027 fpl
->fp
[i
] = get_file(ctx
->user_files
[i
+ offset
]);
3028 unix_inflight(fpl
->user
, fpl
->fp
[i
]);
3031 fpl
->max
= fpl
->count
= nr
;
3032 UNIXCB(skb
).fp
= fpl
;
3033 refcount_add(skb
->truesize
, &sk
->sk_wmem_alloc
);
3034 skb_queue_head(&sk
->sk_receive_queue
, skb
);
3036 for (i
= 0; i
< nr
; i
++)
3043 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
3044 * causes regular reference counting to break down. We rely on the UNIX
3045 * garbage collection to take care of this problem for us.
3047 static int io_sqe_files_scm(struct io_ring_ctx
*ctx
)
3049 unsigned left
, total
;
3053 left
= ctx
->nr_user_files
;
3055 unsigned this_files
= min_t(unsigned, left
, SCM_MAX_FD
);
3057 ret
= __io_sqe_files_scm(ctx
, this_files
, total
);
3061 total
+= this_files
;
3067 while (total
< ctx
->nr_user_files
) {
3068 fput(ctx
->user_files
[total
]);
3075 static int io_sqe_files_scm(struct io_ring_ctx
*ctx
)
3081 static int io_sqe_files_register(struct io_ring_ctx
*ctx
, void __user
*arg
,
3084 __s32 __user
*fds
= (__s32 __user
*) arg
;
3088 if (ctx
->user_files
)
3092 if (nr_args
> IORING_MAX_FIXED_FILES
)
3095 ctx
->user_files
= kcalloc(nr_args
, sizeof(struct file
*), GFP_KERNEL
);
3096 if (!ctx
->user_files
)
3099 for (i
= 0; i
< nr_args
; i
++) {
3101 if (copy_from_user(&fd
, &fds
[i
], sizeof(fd
)))
3104 ctx
->user_files
[i
] = fget(fd
);
3107 if (!ctx
->user_files
[i
])
3110 * Don't allow io_uring instances to be registered. If UNIX
3111 * isn't enabled, then this causes a reference cycle and this
3112 * instance can never get freed. If UNIX is enabled we'll
3113 * handle it just fine, but there's still no point in allowing
3114 * a ring fd as it doesn't support regular read/write anyway.
3116 if (ctx
->user_files
[i
]->f_op
== &io_uring_fops
) {
3117 fput(ctx
->user_files
[i
]);
3120 ctx
->nr_user_files
++;
3125 for (i
= 0; i
< ctx
->nr_user_files
; i
++)
3126 fput(ctx
->user_files
[i
]);
3128 kfree(ctx
->user_files
);
3129 ctx
->user_files
= NULL
;
3130 ctx
->nr_user_files
= 0;
3134 ret
= io_sqe_files_scm(ctx
);
3136 io_sqe_files_unregister(ctx
);
3141 static int io_sq_offload_start(struct io_ring_ctx
*ctx
,
3142 struct io_uring_params
*p
)
3146 init_waitqueue_head(&ctx
->sqo_wait
);
3147 mmgrab(current
->mm
);
3148 ctx
->sqo_mm
= current
->mm
;
3150 if (ctx
->flags
& IORING_SETUP_SQPOLL
) {
3152 if (!capable(CAP_SYS_ADMIN
))
3155 ctx
->sq_thread_idle
= msecs_to_jiffies(p
->sq_thread_idle
);
3156 if (!ctx
->sq_thread_idle
)
3157 ctx
->sq_thread_idle
= HZ
;
3159 if (p
->flags
& IORING_SETUP_SQ_AFF
) {
3160 int cpu
= p
->sq_thread_cpu
;
3163 if (cpu
>= nr_cpu_ids
)
3165 if (!cpu_online(cpu
))
3168 ctx
->sqo_thread
= kthread_create_on_cpu(io_sq_thread
,
3172 ctx
->sqo_thread
= kthread_create(io_sq_thread
, ctx
,
3175 if (IS_ERR(ctx
->sqo_thread
)) {
3176 ret
= PTR_ERR(ctx
->sqo_thread
);
3177 ctx
->sqo_thread
= NULL
;
3180 wake_up_process(ctx
->sqo_thread
);
3181 } else if (p
->flags
& IORING_SETUP_SQ_AFF
) {
3182 /* Can't have SQ_AFF without SQPOLL */
3187 /* Do QD, or 2 * CPUS, whatever is smallest */
3188 ctx
->sqo_wq
[0] = alloc_workqueue("io_ring-wq",
3189 WQ_UNBOUND
| WQ_FREEZABLE
,
3190 min(ctx
->sq_entries
- 1, 2 * num_online_cpus()));
3191 if (!ctx
->sqo_wq
[0]) {
3197 * This is for buffered writes, where we want to limit the parallelism
3198 * due to file locking in file systems. As "normal" buffered writes
3199 * should parellelize on writeout quite nicely, limit us to having 2
3200 * pending. This avoids massive contention on the inode when doing
3201 * buffered async writes.
3203 ctx
->sqo_wq
[1] = alloc_workqueue("io_ring-write-wq",
3204 WQ_UNBOUND
| WQ_FREEZABLE
, 2);
3205 if (!ctx
->sqo_wq
[1]) {
3212 io_finish_async(ctx
);
3213 mmdrop(ctx
->sqo_mm
);
3218 static void io_unaccount_mem(struct user_struct
*user
, unsigned long nr_pages
)
3220 atomic_long_sub(nr_pages
, &user
->locked_vm
);
3223 static int io_account_mem(struct user_struct
*user
, unsigned long nr_pages
)
3225 unsigned long page_limit
, cur_pages
, new_pages
;
3227 /* Don't allow more pages than we can safely lock */
3228 page_limit
= rlimit(RLIMIT_MEMLOCK
) >> PAGE_SHIFT
;
3231 cur_pages
= atomic_long_read(&user
->locked_vm
);
3232 new_pages
= cur_pages
+ nr_pages
;
3233 if (new_pages
> page_limit
)
3235 } while (atomic_long_cmpxchg(&user
->locked_vm
, cur_pages
,
3236 new_pages
) != cur_pages
);
3241 static void io_mem_free(void *ptr
)
3248 page
= virt_to_head_page(ptr
);
3249 if (put_page_testzero(page
))
3250 free_compound_page(page
);
3253 static void *io_mem_alloc(size_t size
)
3255 gfp_t gfp_flags
= GFP_KERNEL
| __GFP_ZERO
| __GFP_NOWARN
| __GFP_COMP
|
3258 return (void *) __get_free_pages(gfp_flags
, get_order(size
));
3261 static unsigned long rings_size(unsigned sq_entries
, unsigned cq_entries
,
3264 struct io_rings
*rings
;
3265 size_t off
, sq_array_size
;
3267 off
= struct_size(rings
, cqes
, cq_entries
);
3268 if (off
== SIZE_MAX
)
3272 off
= ALIGN(off
, SMP_CACHE_BYTES
);
3277 sq_array_size
= array_size(sizeof(u32
), sq_entries
);
3278 if (sq_array_size
== SIZE_MAX
)
3281 if (check_add_overflow(off
, sq_array_size
, &off
))
3290 static unsigned long ring_pages(unsigned sq_entries
, unsigned cq_entries
)
3294 pages
= (size_t)1 << get_order(
3295 rings_size(sq_entries
, cq_entries
, NULL
));
3296 pages
+= (size_t)1 << get_order(
3297 array_size(sizeof(struct io_uring_sqe
), sq_entries
));
3302 static int io_sqe_buffer_unregister(struct io_ring_ctx
*ctx
)
3306 if (!ctx
->user_bufs
)
3309 for (i
= 0; i
< ctx
->nr_user_bufs
; i
++) {
3310 struct io_mapped_ubuf
*imu
= &ctx
->user_bufs
[i
];
3312 for (j
= 0; j
< imu
->nr_bvecs
; j
++)
3313 put_user_page(imu
->bvec
[j
].bv_page
);
3315 if (ctx
->account_mem
)
3316 io_unaccount_mem(ctx
->user
, imu
->nr_bvecs
);
3321 kfree(ctx
->user_bufs
);
3322 ctx
->user_bufs
= NULL
;
3323 ctx
->nr_user_bufs
= 0;
3327 static int io_copy_iov(struct io_ring_ctx
*ctx
, struct iovec
*dst
,
3328 void __user
*arg
, unsigned index
)
3330 struct iovec __user
*src
;
3332 #ifdef CONFIG_COMPAT
3334 struct compat_iovec __user
*ciovs
;
3335 struct compat_iovec ciov
;
3337 ciovs
= (struct compat_iovec __user
*) arg
;
3338 if (copy_from_user(&ciov
, &ciovs
[index
], sizeof(ciov
)))
3341 dst
->iov_base
= (void __user
*) (unsigned long) ciov
.iov_base
;
3342 dst
->iov_len
= ciov
.iov_len
;
3346 src
= (struct iovec __user
*) arg
;
3347 if (copy_from_user(dst
, &src
[index
], sizeof(*dst
)))
3352 static int io_sqe_buffer_register(struct io_ring_ctx
*ctx
, void __user
*arg
,
3355 struct vm_area_struct
**vmas
= NULL
;
3356 struct page
**pages
= NULL
;
3357 int i
, j
, got_pages
= 0;
3362 if (!nr_args
|| nr_args
> UIO_MAXIOV
)
3365 ctx
->user_bufs
= kcalloc(nr_args
, sizeof(struct io_mapped_ubuf
),
3367 if (!ctx
->user_bufs
)
3370 for (i
= 0; i
< nr_args
; i
++) {
3371 struct io_mapped_ubuf
*imu
= &ctx
->user_bufs
[i
];
3372 unsigned long off
, start
, end
, ubuf
;
3377 ret
= io_copy_iov(ctx
, &iov
, arg
, i
);
3382 * Don't impose further limits on the size and buffer
3383 * constraints here, we'll -EINVAL later when IO is
3384 * submitted if they are wrong.
3387 if (!iov
.iov_base
|| !iov
.iov_len
)
3390 /* arbitrary limit, but we need something */
3391 if (iov
.iov_len
> SZ_1G
)
3394 ubuf
= (unsigned long) iov
.iov_base
;
3395 end
= (ubuf
+ iov
.iov_len
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
3396 start
= ubuf
>> PAGE_SHIFT
;
3397 nr_pages
= end
- start
;
3399 if (ctx
->account_mem
) {
3400 ret
= io_account_mem(ctx
->user
, nr_pages
);
3406 if (!pages
|| nr_pages
> got_pages
) {
3409 pages
= kvmalloc_array(nr_pages
, sizeof(struct page
*),
3411 vmas
= kvmalloc_array(nr_pages
,
3412 sizeof(struct vm_area_struct
*),
3414 if (!pages
|| !vmas
) {
3416 if (ctx
->account_mem
)
3417 io_unaccount_mem(ctx
->user
, nr_pages
);
3420 got_pages
= nr_pages
;
3423 imu
->bvec
= kvmalloc_array(nr_pages
, sizeof(struct bio_vec
),
3427 if (ctx
->account_mem
)
3428 io_unaccount_mem(ctx
->user
, nr_pages
);
3433 down_read(¤t
->mm
->mmap_sem
);
3434 pret
= get_user_pages(ubuf
, nr_pages
,
3435 FOLL_WRITE
| FOLL_LONGTERM
,
3437 if (pret
== nr_pages
) {
3438 /* don't support file backed memory */
3439 for (j
= 0; j
< nr_pages
; j
++) {
3440 struct vm_area_struct
*vma
= vmas
[j
];
3443 !is_file_hugepages(vma
->vm_file
)) {
3449 ret
= pret
< 0 ? pret
: -EFAULT
;
3451 up_read(¤t
->mm
->mmap_sem
);
3454 * if we did partial map, or found file backed vmas,
3455 * release any pages we did get
3458 put_user_pages(pages
, pret
);
3459 if (ctx
->account_mem
)
3460 io_unaccount_mem(ctx
->user
, nr_pages
);
3465 off
= ubuf
& ~PAGE_MASK
;
3467 for (j
= 0; j
< nr_pages
; j
++) {
3470 vec_len
= min_t(size_t, size
, PAGE_SIZE
- off
);
3471 imu
->bvec
[j
].bv_page
= pages
[j
];
3472 imu
->bvec
[j
].bv_len
= vec_len
;
3473 imu
->bvec
[j
].bv_offset
= off
;
3477 /* store original address for later verification */
3479 imu
->len
= iov
.iov_len
;
3480 imu
->nr_bvecs
= nr_pages
;
3482 ctx
->nr_user_bufs
++;
3490 io_sqe_buffer_unregister(ctx
);
3494 static int io_eventfd_register(struct io_ring_ctx
*ctx
, void __user
*arg
)
3496 __s32 __user
*fds
= arg
;
3502 if (copy_from_user(&fd
, fds
, sizeof(*fds
)))
3505 ctx
->cq_ev_fd
= eventfd_ctx_fdget(fd
);
3506 if (IS_ERR(ctx
->cq_ev_fd
)) {
3507 int ret
= PTR_ERR(ctx
->cq_ev_fd
);
3508 ctx
->cq_ev_fd
= NULL
;
3515 static int io_eventfd_unregister(struct io_ring_ctx
*ctx
)
3517 if (ctx
->cq_ev_fd
) {
3518 eventfd_ctx_put(ctx
->cq_ev_fd
);
3519 ctx
->cq_ev_fd
= NULL
;
3526 static void io_ring_ctx_free(struct io_ring_ctx
*ctx
)
3528 io_finish_async(ctx
);
3530 mmdrop(ctx
->sqo_mm
);
3532 io_iopoll_reap_events(ctx
);
3533 io_sqe_buffer_unregister(ctx
);
3534 io_sqe_files_unregister(ctx
);
3535 io_eventfd_unregister(ctx
);
3537 #if defined(CONFIG_UNIX)
3538 if (ctx
->ring_sock
) {
3539 ctx
->ring_sock
->file
= NULL
; /* so that iput() is called */
3540 sock_release(ctx
->ring_sock
);
3544 io_mem_free(ctx
->rings
);
3545 io_mem_free(ctx
->sq_sqes
);
3547 percpu_ref_exit(&ctx
->refs
);
3548 if (ctx
->account_mem
)
3549 io_unaccount_mem(ctx
->user
,
3550 ring_pages(ctx
->sq_entries
, ctx
->cq_entries
));
3551 free_uid(ctx
->user
);
3555 static __poll_t
io_uring_poll(struct file
*file
, poll_table
*wait
)
3557 struct io_ring_ctx
*ctx
= file
->private_data
;
3560 poll_wait(file
, &ctx
->cq_wait
, wait
);
3562 * synchronizes with barrier from wq_has_sleeper call in
3566 if (READ_ONCE(ctx
->rings
->sq
.tail
) - ctx
->cached_sq_head
!=
3567 ctx
->rings
->sq_ring_entries
)
3568 mask
|= EPOLLOUT
| EPOLLWRNORM
;
3569 if (READ_ONCE(ctx
->rings
->cq
.head
) != ctx
->cached_cq_tail
)
3570 mask
|= EPOLLIN
| EPOLLRDNORM
;
3575 static int io_uring_fasync(int fd
, struct file
*file
, int on
)
3577 struct io_ring_ctx
*ctx
= file
->private_data
;
3579 return fasync_helper(fd
, file
, on
, &ctx
->cq_fasync
);
3582 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx
*ctx
)
3584 mutex_lock(&ctx
->uring_lock
);
3585 percpu_ref_kill(&ctx
->refs
);
3586 mutex_unlock(&ctx
->uring_lock
);
3588 io_kill_timeouts(ctx
);
3589 io_poll_remove_all(ctx
);
3590 io_iopoll_reap_events(ctx
);
3591 wait_for_completion(&ctx
->ctx_done
);
3592 io_ring_ctx_free(ctx
);
3595 static int io_uring_release(struct inode
*inode
, struct file
*file
)
3597 struct io_ring_ctx
*ctx
= file
->private_data
;
3599 file
->private_data
= NULL
;
3600 io_ring_ctx_wait_and_kill(ctx
);
3604 static int io_uring_mmap(struct file
*file
, struct vm_area_struct
*vma
)
3606 loff_t offset
= (loff_t
) vma
->vm_pgoff
<< PAGE_SHIFT
;
3607 unsigned long sz
= vma
->vm_end
- vma
->vm_start
;
3608 struct io_ring_ctx
*ctx
= file
->private_data
;
3614 case IORING_OFF_SQ_RING
:
3615 case IORING_OFF_CQ_RING
:
3618 case IORING_OFF_SQES
:
3625 page
= virt_to_head_page(ptr
);
3626 if (sz
> page_size(page
))
3629 pfn
= virt_to_phys(ptr
) >> PAGE_SHIFT
;
3630 return remap_pfn_range(vma
, vma
->vm_start
, pfn
, sz
, vma
->vm_page_prot
);
3633 SYSCALL_DEFINE6(io_uring_enter
, unsigned int, fd
, u32
, to_submit
,
3634 u32
, min_complete
, u32
, flags
, const sigset_t __user
*, sig
,
3637 struct io_ring_ctx
*ctx
;
3642 if (flags
& ~(IORING_ENTER_GETEVENTS
| IORING_ENTER_SQ_WAKEUP
))
3650 if (f
.file
->f_op
!= &io_uring_fops
)
3654 ctx
= f
.file
->private_data
;
3655 if (!percpu_ref_tryget(&ctx
->refs
))
3659 * For SQ polling, the thread will do all submissions and completions.
3660 * Just return the requested submit count, and wake the thread if
3664 if (ctx
->flags
& IORING_SETUP_SQPOLL
) {
3665 if (flags
& IORING_ENTER_SQ_WAKEUP
)
3666 wake_up(&ctx
->sqo_wait
);
3667 submitted
= to_submit
;
3668 } else if (to_submit
) {
3669 to_submit
= min(to_submit
, ctx
->sq_entries
);
3671 mutex_lock(&ctx
->uring_lock
);
3672 submitted
= io_ring_submit(ctx
, to_submit
);
3673 mutex_unlock(&ctx
->uring_lock
);
3675 if (flags
& IORING_ENTER_GETEVENTS
) {
3676 unsigned nr_events
= 0;
3678 min_complete
= min(min_complete
, ctx
->cq_entries
);
3680 if (ctx
->flags
& IORING_SETUP_IOPOLL
) {
3681 ret
= io_iopoll_check(ctx
, &nr_events
, min_complete
);
3683 ret
= io_cqring_wait(ctx
, min_complete
, sig
, sigsz
);
3687 percpu_ref_put(&ctx
->refs
);
3690 return submitted
? submitted
: ret
;
3693 static const struct file_operations io_uring_fops
= {
3694 .release
= io_uring_release
,
3695 .mmap
= io_uring_mmap
,
3696 .poll
= io_uring_poll
,
3697 .fasync
= io_uring_fasync
,
3700 static int io_allocate_scq_urings(struct io_ring_ctx
*ctx
,
3701 struct io_uring_params
*p
)
3703 struct io_rings
*rings
;
3704 size_t size
, sq_array_offset
;
3706 size
= rings_size(p
->sq_entries
, p
->cq_entries
, &sq_array_offset
);
3707 if (size
== SIZE_MAX
)
3710 rings
= io_mem_alloc(size
);
3715 ctx
->sq_array
= (u32
*)((char *)rings
+ sq_array_offset
);
3716 rings
->sq_ring_mask
= p
->sq_entries
- 1;
3717 rings
->cq_ring_mask
= p
->cq_entries
- 1;
3718 rings
->sq_ring_entries
= p
->sq_entries
;
3719 rings
->cq_ring_entries
= p
->cq_entries
;
3720 ctx
->sq_mask
= rings
->sq_ring_mask
;
3721 ctx
->cq_mask
= rings
->cq_ring_mask
;
3722 ctx
->sq_entries
= rings
->sq_ring_entries
;
3723 ctx
->cq_entries
= rings
->cq_ring_entries
;
3725 size
= array_size(sizeof(struct io_uring_sqe
), p
->sq_entries
);
3726 if (size
== SIZE_MAX
)
3729 ctx
->sq_sqes
= io_mem_alloc(size
);
3737 * Allocate an anonymous fd, this is what constitutes the application
3738 * visible backing of an io_uring instance. The application mmaps this
3739 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3740 * we have to tie this fd to a socket for file garbage collection purposes.
3742 static int io_uring_get_fd(struct io_ring_ctx
*ctx
)
3747 #if defined(CONFIG_UNIX)
3748 ret
= sock_create_kern(&init_net
, PF_UNIX
, SOCK_RAW
, IPPROTO_IP
,
3754 ret
= get_unused_fd_flags(O_RDWR
| O_CLOEXEC
);
3758 file
= anon_inode_getfile("[io_uring]", &io_uring_fops
, ctx
,
3759 O_RDWR
| O_CLOEXEC
);
3762 ret
= PTR_ERR(file
);
3766 #if defined(CONFIG_UNIX)
3767 ctx
->ring_sock
->file
= file
;
3768 ctx
->ring_sock
->sk
->sk_user_data
= ctx
;
3770 fd_install(ret
, file
);
3773 #if defined(CONFIG_UNIX)
3774 sock_release(ctx
->ring_sock
);
3775 ctx
->ring_sock
= NULL
;
3780 static int io_uring_create(unsigned entries
, struct io_uring_params
*p
)
3782 struct user_struct
*user
= NULL
;
3783 struct io_ring_ctx
*ctx
;
3787 if (!entries
|| entries
> IORING_MAX_ENTRIES
)
3791 * Use twice as many entries for the CQ ring. It's possible for the
3792 * application to drive a higher depth than the size of the SQ ring,
3793 * since the sqes are only used at submission time. This allows for
3794 * some flexibility in overcommitting a bit.
3796 p
->sq_entries
= roundup_pow_of_two(entries
);
3797 p
->cq_entries
= 2 * p
->sq_entries
;
3799 user
= get_uid(current_user());
3800 account_mem
= !capable(CAP_IPC_LOCK
);
3803 ret
= io_account_mem(user
,
3804 ring_pages(p
->sq_entries
, p
->cq_entries
));
3811 ctx
= io_ring_ctx_alloc(p
);
3814 io_unaccount_mem(user
, ring_pages(p
->sq_entries
,
3819 ctx
->compat
= in_compat_syscall();
3820 ctx
->account_mem
= account_mem
;
3823 ret
= io_allocate_scq_urings(ctx
, p
);
3827 ret
= io_sq_offload_start(ctx
, p
);
3831 ret
= io_uring_get_fd(ctx
);
3835 memset(&p
->sq_off
, 0, sizeof(p
->sq_off
));
3836 p
->sq_off
.head
= offsetof(struct io_rings
, sq
.head
);
3837 p
->sq_off
.tail
= offsetof(struct io_rings
, sq
.tail
);
3838 p
->sq_off
.ring_mask
= offsetof(struct io_rings
, sq_ring_mask
);
3839 p
->sq_off
.ring_entries
= offsetof(struct io_rings
, sq_ring_entries
);
3840 p
->sq_off
.flags
= offsetof(struct io_rings
, sq_flags
);
3841 p
->sq_off
.dropped
= offsetof(struct io_rings
, sq_dropped
);
3842 p
->sq_off
.array
= (char *)ctx
->sq_array
- (char *)ctx
->rings
;
3844 memset(&p
->cq_off
, 0, sizeof(p
->cq_off
));
3845 p
->cq_off
.head
= offsetof(struct io_rings
, cq
.head
);
3846 p
->cq_off
.tail
= offsetof(struct io_rings
, cq
.tail
);
3847 p
->cq_off
.ring_mask
= offsetof(struct io_rings
, cq_ring_mask
);
3848 p
->cq_off
.ring_entries
= offsetof(struct io_rings
, cq_ring_entries
);
3849 p
->cq_off
.overflow
= offsetof(struct io_rings
, cq_overflow
);
3850 p
->cq_off
.cqes
= offsetof(struct io_rings
, cqes
);
3852 p
->features
= IORING_FEAT_SINGLE_MMAP
;
3855 io_ring_ctx_wait_and_kill(ctx
);
3860 * Sets up an aio uring context, and returns the fd. Applications asks for a
3861 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3862 * params structure passed in.
3864 static long io_uring_setup(u32 entries
, struct io_uring_params __user
*params
)
3866 struct io_uring_params p
;
3870 if (copy_from_user(&p
, params
, sizeof(p
)))
3872 for (i
= 0; i
< ARRAY_SIZE(p
.resv
); i
++) {
3877 if (p
.flags
& ~(IORING_SETUP_IOPOLL
| IORING_SETUP_SQPOLL
|
3878 IORING_SETUP_SQ_AFF
))
3881 ret
= io_uring_create(entries
, &p
);
3885 if (copy_to_user(params
, &p
, sizeof(p
)))
3891 SYSCALL_DEFINE2(io_uring_setup
, u32
, entries
,
3892 struct io_uring_params __user
*, params
)
3894 return io_uring_setup(entries
, params
);
3897 static int __io_uring_register(struct io_ring_ctx
*ctx
, unsigned opcode
,
3898 void __user
*arg
, unsigned nr_args
)
3899 __releases(ctx
->uring_lock
)
3900 __acquires(ctx
->uring_lock
)
3905 * We're inside the ring mutex, if the ref is already dying, then
3906 * someone else killed the ctx or is already going through
3907 * io_uring_register().
3909 if (percpu_ref_is_dying(&ctx
->refs
))
3912 percpu_ref_kill(&ctx
->refs
);
3915 * Drop uring mutex before waiting for references to exit. If another
3916 * thread is currently inside io_uring_enter() it might need to grab
3917 * the uring_lock to make progress. If we hold it here across the drain
3918 * wait, then we can deadlock. It's safe to drop the mutex here, since
3919 * no new references will come in after we've killed the percpu ref.
3921 mutex_unlock(&ctx
->uring_lock
);
3922 wait_for_completion(&ctx
->ctx_done
);
3923 mutex_lock(&ctx
->uring_lock
);
3926 case IORING_REGISTER_BUFFERS
:
3927 ret
= io_sqe_buffer_register(ctx
, arg
, nr_args
);
3929 case IORING_UNREGISTER_BUFFERS
:
3933 ret
= io_sqe_buffer_unregister(ctx
);
3935 case IORING_REGISTER_FILES
:
3936 ret
= io_sqe_files_register(ctx
, arg
, nr_args
);
3938 case IORING_UNREGISTER_FILES
:
3942 ret
= io_sqe_files_unregister(ctx
);
3944 case IORING_REGISTER_EVENTFD
:
3948 ret
= io_eventfd_register(ctx
, arg
);
3950 case IORING_UNREGISTER_EVENTFD
:
3954 ret
= io_eventfd_unregister(ctx
);
3961 /* bring the ctx back to life */
3962 reinit_completion(&ctx
->ctx_done
);
3963 percpu_ref_reinit(&ctx
->refs
);
3967 SYSCALL_DEFINE4(io_uring_register
, unsigned int, fd
, unsigned int, opcode
,
3968 void __user
*, arg
, unsigned int, nr_args
)
3970 struct io_ring_ctx
*ctx
;
3979 if (f
.file
->f_op
!= &io_uring_fops
)
3982 ctx
= f
.file
->private_data
;
3984 mutex_lock(&ctx
->uring_lock
);
3985 ret
= __io_uring_register(ctx
, opcode
, arg
, nr_args
);
3986 mutex_unlock(&ctx
->uring_lock
);
3992 static int __init
io_uring_init(void)
3994 req_cachep
= KMEM_CACHE(io_kiocb
, SLAB_HWCACHE_ALIGN
| SLAB_PANIC
);
3997 __initcall(io_uring_init
);