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 */
329 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
334 struct work_struct work
;
337 #define IO_PLUG_THRESHOLD 2
338 #define IO_IOPOLL_BATCH 8
340 struct io_submit_state
{
341 struct blk_plug plug
;
344 * io_kiocb alloc cache
346 void *reqs
[IO_IOPOLL_BATCH
];
347 unsigned int free_reqs
;
348 unsigned int cur_req
;
351 * File reference cache
355 unsigned int has_refs
;
356 unsigned int used_refs
;
357 unsigned int ios_left
;
360 static void io_sq_wq_submit_work(struct work_struct
*work
);
361 static void io_cqring_fill_event(struct io_ring_ctx
*ctx
, u64 ki_user_data
,
363 static void __io_free_req(struct io_kiocb
*req
);
365 static struct kmem_cache
*req_cachep
;
367 static const struct file_operations io_uring_fops
;
369 struct sock
*io_uring_get_socket(struct file
*file
)
371 #if defined(CONFIG_UNIX)
372 if (file
->f_op
== &io_uring_fops
) {
373 struct io_ring_ctx
*ctx
= file
->private_data
;
375 return ctx
->ring_sock
->sk
;
380 EXPORT_SYMBOL(io_uring_get_socket
);
382 static void io_ring_ctx_ref_free(struct percpu_ref
*ref
)
384 struct io_ring_ctx
*ctx
= container_of(ref
, struct io_ring_ctx
, refs
);
386 complete(&ctx
->ctx_done
);
389 static struct io_ring_ctx
*io_ring_ctx_alloc(struct io_uring_params
*p
)
391 struct io_ring_ctx
*ctx
;
394 ctx
= kzalloc(sizeof(*ctx
), GFP_KERNEL
);
398 if (percpu_ref_init(&ctx
->refs
, io_ring_ctx_ref_free
,
399 PERCPU_REF_ALLOW_REINIT
, GFP_KERNEL
)) {
404 ctx
->flags
= p
->flags
;
405 init_waitqueue_head(&ctx
->cq_wait
);
406 init_completion(&ctx
->ctx_done
);
407 init_completion(&ctx
->sqo_thread_started
);
408 mutex_init(&ctx
->uring_lock
);
409 init_waitqueue_head(&ctx
->wait
);
410 for (i
= 0; i
< ARRAY_SIZE(ctx
->pending_async
); i
++) {
411 spin_lock_init(&ctx
->pending_async
[i
].lock
);
412 INIT_LIST_HEAD(&ctx
->pending_async
[i
].list
);
413 atomic_set(&ctx
->pending_async
[i
].cnt
, 0);
415 spin_lock_init(&ctx
->completion_lock
);
416 INIT_LIST_HEAD(&ctx
->poll_list
);
417 INIT_LIST_HEAD(&ctx
->cancel_list
);
418 INIT_LIST_HEAD(&ctx
->defer_list
);
419 INIT_LIST_HEAD(&ctx
->timeout_list
);
423 static inline bool __io_sequence_defer(struct io_ring_ctx
*ctx
,
424 struct io_kiocb
*req
)
426 return req
->sequence
!= ctx
->cached_cq_tail
+ ctx
->cached_sq_dropped
427 + atomic_read(&ctx
->cached_cq_overflow
);
430 static inline bool io_sequence_defer(struct io_ring_ctx
*ctx
,
431 struct io_kiocb
*req
)
433 if ((req
->flags
& (REQ_F_IO_DRAIN
|REQ_F_IO_DRAINED
)) != REQ_F_IO_DRAIN
)
436 return __io_sequence_defer(ctx
, req
);
439 static struct io_kiocb
*io_get_deferred_req(struct io_ring_ctx
*ctx
)
441 struct io_kiocb
*req
;
443 req
= list_first_entry_or_null(&ctx
->defer_list
, struct io_kiocb
, list
);
444 if (req
&& !io_sequence_defer(ctx
, req
)) {
445 list_del_init(&req
->list
);
452 static struct io_kiocb
*io_get_timeout_req(struct io_ring_ctx
*ctx
)
454 struct io_kiocb
*req
;
456 req
= list_first_entry_or_null(&ctx
->timeout_list
, struct io_kiocb
, list
);
458 if (req
->flags
& REQ_F_TIMEOUT_NOSEQ
)
460 if (!__io_sequence_defer(ctx
, req
)) {
461 list_del_init(&req
->list
);
469 static void __io_commit_cqring(struct io_ring_ctx
*ctx
)
471 struct io_rings
*rings
= ctx
->rings
;
473 if (ctx
->cached_cq_tail
!= READ_ONCE(rings
->cq
.tail
)) {
474 /* order cqe stores with ring update */
475 smp_store_release(&rings
->cq
.tail
, ctx
->cached_cq_tail
);
477 if (wq_has_sleeper(&ctx
->cq_wait
)) {
478 wake_up_interruptible(&ctx
->cq_wait
);
479 kill_fasync(&ctx
->cq_fasync
, SIGIO
, POLL_IN
);
484 static inline void io_queue_async_work(struct io_ring_ctx
*ctx
,
485 struct io_kiocb
*req
)
489 if (req
->submit
.sqe
) {
490 switch (req
->submit
.sqe
->opcode
) {
491 case IORING_OP_WRITEV
:
492 case IORING_OP_WRITE_FIXED
:
493 rw
= !(req
->rw
.ki_flags
& IOCB_DIRECT
);
498 queue_work(ctx
->sqo_wq
[rw
], &req
->work
);
501 static void io_kill_timeout(struct io_kiocb
*req
)
505 ret
= hrtimer_try_to_cancel(&req
->timeout
.timer
);
507 atomic_inc(&req
->ctx
->cq_timeouts
);
508 list_del(&req
->list
);
509 io_cqring_fill_event(req
->ctx
, req
->user_data
, 0);
514 static void io_kill_timeouts(struct io_ring_ctx
*ctx
)
516 struct io_kiocb
*req
, *tmp
;
518 spin_lock_irq(&ctx
->completion_lock
);
519 list_for_each_entry_safe(req
, tmp
, &ctx
->timeout_list
, list
)
520 io_kill_timeout(req
);
521 spin_unlock_irq(&ctx
->completion_lock
);
524 static void io_commit_cqring(struct io_ring_ctx
*ctx
)
526 struct io_kiocb
*req
;
528 while ((req
= io_get_timeout_req(ctx
)) != NULL
)
529 io_kill_timeout(req
);
531 __io_commit_cqring(ctx
);
533 while ((req
= io_get_deferred_req(ctx
)) != NULL
) {
534 if (req
->flags
& REQ_F_SHADOW_DRAIN
) {
535 /* Just for drain, free it. */
539 req
->flags
|= REQ_F_IO_DRAINED
;
540 io_queue_async_work(ctx
, req
);
544 static struct io_uring_cqe
*io_get_cqring(struct io_ring_ctx
*ctx
)
546 struct io_rings
*rings
= ctx
->rings
;
549 tail
= ctx
->cached_cq_tail
;
551 * writes to the cq entry need to come after reading head; the
552 * control dependency is enough as we're using WRITE_ONCE to
555 if (tail
- READ_ONCE(rings
->cq
.head
) == rings
->cq_ring_entries
)
558 ctx
->cached_cq_tail
++;
559 return &rings
->cqes
[tail
& ctx
->cq_mask
];
562 static void io_cqring_fill_event(struct io_ring_ctx
*ctx
, u64 ki_user_data
,
565 struct io_uring_cqe
*cqe
;
568 * If we can't get a cq entry, userspace overflowed the
569 * submission (by quite a lot). Increment the overflow count in
572 cqe
= io_get_cqring(ctx
);
574 WRITE_ONCE(cqe
->user_data
, ki_user_data
);
575 WRITE_ONCE(cqe
->res
, res
);
576 WRITE_ONCE(cqe
->flags
, 0);
578 WRITE_ONCE(ctx
->rings
->cq_overflow
,
579 atomic_inc_return(&ctx
->cached_cq_overflow
));
583 static void io_cqring_ev_posted(struct io_ring_ctx
*ctx
)
585 if (waitqueue_active(&ctx
->wait
))
587 if (waitqueue_active(&ctx
->sqo_wait
))
588 wake_up(&ctx
->sqo_wait
);
590 eventfd_signal(ctx
->cq_ev_fd
, 1);
593 static void io_cqring_add_event(struct io_ring_ctx
*ctx
, u64 user_data
,
598 spin_lock_irqsave(&ctx
->completion_lock
, flags
);
599 io_cqring_fill_event(ctx
, user_data
, res
);
600 io_commit_cqring(ctx
);
601 spin_unlock_irqrestore(&ctx
->completion_lock
, flags
);
603 io_cqring_ev_posted(ctx
);
606 static struct io_kiocb
*io_get_req(struct io_ring_ctx
*ctx
,
607 struct io_submit_state
*state
)
609 gfp_t gfp
= GFP_KERNEL
| __GFP_NOWARN
;
610 struct io_kiocb
*req
;
612 if (!percpu_ref_tryget(&ctx
->refs
))
616 req
= kmem_cache_alloc(req_cachep
, gfp
);
619 } else if (!state
->free_reqs
) {
623 sz
= min_t(size_t, state
->ios_left
, ARRAY_SIZE(state
->reqs
));
624 ret
= kmem_cache_alloc_bulk(req_cachep
, gfp
, sz
, state
->reqs
);
627 * Bulk alloc is all-or-nothing. If we fail to get a batch,
628 * retry single alloc to be on the safe side.
630 if (unlikely(ret
<= 0)) {
631 state
->reqs
[0] = kmem_cache_alloc(req_cachep
, gfp
);
636 state
->free_reqs
= ret
- 1;
638 req
= state
->reqs
[0];
640 req
= state
->reqs
[state
->cur_req
];
648 /* one is dropped after submission, the other at completion */
649 refcount_set(&req
->refs
, 2);
653 percpu_ref_put(&ctx
->refs
);
657 static void io_free_req_many(struct io_ring_ctx
*ctx
, void **reqs
, int *nr
)
660 kmem_cache_free_bulk(req_cachep
, *nr
, reqs
);
661 percpu_ref_put_many(&ctx
->refs
, *nr
);
666 static void __io_free_req(struct io_kiocb
*req
)
668 if (req
->file
&& !(req
->flags
& REQ_F_FIXED_FILE
))
670 percpu_ref_put(&req
->ctx
->refs
);
671 kmem_cache_free(req_cachep
, req
);
674 static void io_req_link_next(struct io_kiocb
*req
)
676 struct io_kiocb
*nxt
;
679 * The list should never be empty when we are called here. But could
680 * potentially happen if the chain is messed up, check to be on the
683 nxt
= list_first_entry_or_null(&req
->link_list
, struct io_kiocb
, list
);
685 list_del(&nxt
->list
);
686 if (!list_empty(&req
->link_list
)) {
687 INIT_LIST_HEAD(&nxt
->link_list
);
688 list_splice(&req
->link_list
, &nxt
->link_list
);
689 nxt
->flags
|= REQ_F_LINK
;
692 nxt
->flags
|= REQ_F_LINK_DONE
;
693 INIT_WORK(&nxt
->work
, io_sq_wq_submit_work
);
694 io_queue_async_work(req
->ctx
, nxt
);
699 * Called if REQ_F_LINK is set, and we fail the head request
701 static void io_fail_links(struct io_kiocb
*req
)
703 struct io_kiocb
*link
;
705 while (!list_empty(&req
->link_list
)) {
706 link
= list_first_entry(&req
->link_list
, struct io_kiocb
, list
);
707 list_del(&link
->list
);
709 io_cqring_add_event(req
->ctx
, link
->user_data
, -ECANCELED
);
714 static void io_free_req(struct io_kiocb
*req
)
717 * If LINK is set, we have dependent requests in this chain. If we
718 * didn't fail this request, queue the first one up, moving any other
719 * dependencies to the next request. In case of failure, fail the rest
722 if (req
->flags
& REQ_F_LINK
) {
723 if (req
->flags
& REQ_F_FAIL_LINK
)
726 io_req_link_next(req
);
732 static void io_put_req(struct io_kiocb
*req
)
734 if (refcount_dec_and_test(&req
->refs
))
738 static unsigned io_cqring_events(struct io_rings
*rings
)
740 /* See comment at the top of this file */
742 return READ_ONCE(rings
->cq
.tail
) - READ_ONCE(rings
->cq
.head
);
745 static inline unsigned int io_sqring_entries(struct io_ring_ctx
*ctx
)
747 struct io_rings
*rings
= ctx
->rings
;
749 /* make sure SQ entry isn't read before tail */
750 return smp_load_acquire(&rings
->sq
.tail
) - ctx
->cached_sq_head
;
754 * Find and free completed poll iocbs
756 static void io_iopoll_complete(struct io_ring_ctx
*ctx
, unsigned int *nr_events
,
757 struct list_head
*done
)
759 void *reqs
[IO_IOPOLL_BATCH
];
760 struct io_kiocb
*req
;
764 while (!list_empty(done
)) {
765 req
= list_first_entry(done
, struct io_kiocb
, list
);
766 list_del(&req
->list
);
768 io_cqring_fill_event(ctx
, req
->user_data
, req
->result
);
771 if (refcount_dec_and_test(&req
->refs
)) {
772 /* If we're not using fixed files, we have to pair the
773 * completion part with the file put. Use regular
774 * completions for those, only batch free for fixed
775 * file and non-linked commands.
777 if ((req
->flags
& (REQ_F_FIXED_FILE
|REQ_F_LINK
)) ==
779 reqs
[to_free
++] = req
;
780 if (to_free
== ARRAY_SIZE(reqs
))
781 io_free_req_many(ctx
, reqs
, &to_free
);
788 io_commit_cqring(ctx
);
789 io_free_req_many(ctx
, reqs
, &to_free
);
792 static int io_do_iopoll(struct io_ring_ctx
*ctx
, unsigned int *nr_events
,
795 struct io_kiocb
*req
, *tmp
;
801 * Only spin for completions if we don't have multiple devices hanging
802 * off our complete list, and we're under the requested amount.
804 spin
= !ctx
->poll_multi_file
&& *nr_events
< min
;
807 list_for_each_entry_safe(req
, tmp
, &ctx
->poll_list
, list
) {
808 struct kiocb
*kiocb
= &req
->rw
;
811 * Move completed entries to our local list. If we find a
812 * request that requires polling, break out and complete
813 * the done list first, if we have entries there.
815 if (req
->flags
& REQ_F_IOPOLL_COMPLETED
) {
816 list_move_tail(&req
->list
, &done
);
819 if (!list_empty(&done
))
822 ret
= kiocb
->ki_filp
->f_op
->iopoll(kiocb
, spin
);
831 if (!list_empty(&done
))
832 io_iopoll_complete(ctx
, nr_events
, &done
);
838 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
839 * non-spinning poll check - we'll still enter the driver poll loop, but only
840 * as a non-spinning completion check.
842 static int io_iopoll_getevents(struct io_ring_ctx
*ctx
, unsigned int *nr_events
,
845 while (!list_empty(&ctx
->poll_list
) && !need_resched()) {
848 ret
= io_do_iopoll(ctx
, nr_events
, min
);
851 if (!min
|| *nr_events
>= min
)
859 * We can't just wait for polled events to come to us, we have to actively
860 * find and complete them.
862 static void io_iopoll_reap_events(struct io_ring_ctx
*ctx
)
864 if (!(ctx
->flags
& IORING_SETUP_IOPOLL
))
867 mutex_lock(&ctx
->uring_lock
);
868 while (!list_empty(&ctx
->poll_list
)) {
869 unsigned int nr_events
= 0;
871 io_iopoll_getevents(ctx
, &nr_events
, 1);
874 * Ensure we allow local-to-the-cpu processing to take place,
875 * in this case we need to ensure that we reap all events.
879 mutex_unlock(&ctx
->uring_lock
);
882 static int __io_iopoll_check(struct io_ring_ctx
*ctx
, unsigned *nr_events
,
885 int iters
= 0, ret
= 0;
891 * Don't enter poll loop if we already have events pending.
892 * If we do, we can potentially be spinning for commands that
893 * already triggered a CQE (eg in error).
895 if (io_cqring_events(ctx
->rings
))
899 * If a submit got punted to a workqueue, we can have the
900 * application entering polling for a command before it gets
901 * issued. That app will hold the uring_lock for the duration
902 * of the poll right here, so we need to take a breather every
903 * now and then to ensure that the issue has a chance to add
904 * the poll to the issued list. Otherwise we can spin here
905 * forever, while the workqueue is stuck trying to acquire the
908 if (!(++iters
& 7)) {
909 mutex_unlock(&ctx
->uring_lock
);
910 mutex_lock(&ctx
->uring_lock
);
913 if (*nr_events
< min
)
914 tmin
= min
- *nr_events
;
916 ret
= io_iopoll_getevents(ctx
, nr_events
, tmin
);
920 } while (min
&& !*nr_events
&& !need_resched());
925 static int io_iopoll_check(struct io_ring_ctx
*ctx
, unsigned *nr_events
,
931 * We disallow the app entering submit/complete with polling, but we
932 * still need to lock the ring to prevent racing with polled issue
933 * that got punted to a workqueue.
935 mutex_lock(&ctx
->uring_lock
);
936 ret
= __io_iopoll_check(ctx
, nr_events
, min
);
937 mutex_unlock(&ctx
->uring_lock
);
941 static void kiocb_end_write(struct io_kiocb
*req
)
944 * Tell lockdep we inherited freeze protection from submission
947 if (req
->flags
& REQ_F_ISREG
) {
948 struct inode
*inode
= file_inode(req
->file
);
950 __sb_writers_acquired(inode
->i_sb
, SB_FREEZE_WRITE
);
952 file_end_write(req
->file
);
955 static void io_complete_rw(struct kiocb
*kiocb
, long res
, long res2
)
957 struct io_kiocb
*req
= container_of(kiocb
, struct io_kiocb
, rw
);
959 if (kiocb
->ki_flags
& IOCB_WRITE
)
960 kiocb_end_write(req
);
962 if ((req
->flags
& REQ_F_LINK
) && res
!= req
->result
)
963 req
->flags
|= REQ_F_FAIL_LINK
;
964 io_cqring_add_event(req
->ctx
, req
->user_data
, res
);
968 static void io_complete_rw_iopoll(struct kiocb
*kiocb
, long res
, long res2
)
970 struct io_kiocb
*req
= container_of(kiocb
, struct io_kiocb
, rw
);
972 if (kiocb
->ki_flags
& IOCB_WRITE
)
973 kiocb_end_write(req
);
975 if ((req
->flags
& REQ_F_LINK
) && res
!= req
->result
)
976 req
->flags
|= REQ_F_FAIL_LINK
;
979 req
->flags
|= REQ_F_IOPOLL_COMPLETED
;
983 * After the iocb has been issued, it's safe to be found on the poll list.
984 * Adding the kiocb to the list AFTER submission ensures that we don't
985 * find it from a io_iopoll_getevents() thread before the issuer is done
986 * accessing the kiocb cookie.
988 static void io_iopoll_req_issued(struct io_kiocb
*req
)
990 struct io_ring_ctx
*ctx
= req
->ctx
;
993 * Track whether we have multiple files in our lists. This will impact
994 * how we do polling eventually, not spinning if we're on potentially
997 if (list_empty(&ctx
->poll_list
)) {
998 ctx
->poll_multi_file
= false;
999 } else if (!ctx
->poll_multi_file
) {
1000 struct io_kiocb
*list_req
;
1002 list_req
= list_first_entry(&ctx
->poll_list
, struct io_kiocb
,
1004 if (list_req
->rw
.ki_filp
!= req
->rw
.ki_filp
)
1005 ctx
->poll_multi_file
= true;
1009 * For fast devices, IO may have already completed. If it has, add
1010 * it to the front so we find it first.
1012 if (req
->flags
& REQ_F_IOPOLL_COMPLETED
)
1013 list_add(&req
->list
, &ctx
->poll_list
);
1015 list_add_tail(&req
->list
, &ctx
->poll_list
);
1018 static void io_file_put(struct io_submit_state
*state
)
1021 int diff
= state
->has_refs
- state
->used_refs
;
1024 fput_many(state
->file
, diff
);
1030 * Get as many references to a file as we have IOs left in this submission,
1031 * assuming most submissions are for one file, or at least that each file
1032 * has more than one submission.
1034 static struct file
*io_file_get(struct io_submit_state
*state
, int fd
)
1040 if (state
->fd
== fd
) {
1047 state
->file
= fget_many(fd
, state
->ios_left
);
1052 state
->has_refs
= state
->ios_left
;
1053 state
->used_refs
= 1;
1059 * If we tracked the file through the SCM inflight mechanism, we could support
1060 * any file. For now, just ensure that anything potentially problematic is done
1063 static bool io_file_supports_async(struct file
*file
)
1065 umode_t mode
= file_inode(file
)->i_mode
;
1067 if (S_ISBLK(mode
) || S_ISCHR(mode
))
1069 if (S_ISREG(mode
) && file
->f_op
!= &io_uring_fops
)
1075 static int io_prep_rw(struct io_kiocb
*req
, const struct sqe_submit
*s
,
1076 bool force_nonblock
)
1078 const struct io_uring_sqe
*sqe
= s
->sqe
;
1079 struct io_ring_ctx
*ctx
= req
->ctx
;
1080 struct kiocb
*kiocb
= &req
->rw
;
1087 if (S_ISREG(file_inode(req
->file
)->i_mode
))
1088 req
->flags
|= REQ_F_ISREG
;
1091 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1092 * we know to async punt it even if it was opened O_NONBLOCK
1094 if (force_nonblock
&& !io_file_supports_async(req
->file
)) {
1095 req
->flags
|= REQ_F_MUST_PUNT
;
1099 kiocb
->ki_pos
= READ_ONCE(sqe
->off
);
1100 kiocb
->ki_flags
= iocb_flags(kiocb
->ki_filp
);
1101 kiocb
->ki_hint
= ki_hint_validate(file_write_hint(kiocb
->ki_filp
));
1103 ioprio
= READ_ONCE(sqe
->ioprio
);
1105 ret
= ioprio_check_cap(ioprio
);
1109 kiocb
->ki_ioprio
= ioprio
;
1111 kiocb
->ki_ioprio
= get_current_ioprio();
1113 ret
= kiocb_set_rw_flags(kiocb
, READ_ONCE(sqe
->rw_flags
));
1117 /* don't allow async punt if RWF_NOWAIT was requested */
1118 if ((kiocb
->ki_flags
& IOCB_NOWAIT
) ||
1119 (req
->file
->f_flags
& O_NONBLOCK
))
1120 req
->flags
|= REQ_F_NOWAIT
;
1123 kiocb
->ki_flags
|= IOCB_NOWAIT
;
1125 if (ctx
->flags
& IORING_SETUP_IOPOLL
) {
1126 if (!(kiocb
->ki_flags
& IOCB_DIRECT
) ||
1127 !kiocb
->ki_filp
->f_op
->iopoll
)
1130 kiocb
->ki_flags
|= IOCB_HIPRI
;
1131 kiocb
->ki_complete
= io_complete_rw_iopoll
;
1134 if (kiocb
->ki_flags
& IOCB_HIPRI
)
1136 kiocb
->ki_complete
= io_complete_rw
;
1141 static inline void io_rw_done(struct kiocb
*kiocb
, ssize_t ret
)
1147 case -ERESTARTNOINTR
:
1148 case -ERESTARTNOHAND
:
1149 case -ERESTART_RESTARTBLOCK
:
1151 * We can't just restart the syscall, since previously
1152 * submitted sqes may already be in progress. Just fail this
1158 kiocb
->ki_complete(kiocb
, ret
, 0);
1162 static int io_import_fixed(struct io_ring_ctx
*ctx
, int rw
,
1163 const struct io_uring_sqe
*sqe
,
1164 struct iov_iter
*iter
)
1166 size_t len
= READ_ONCE(sqe
->len
);
1167 struct io_mapped_ubuf
*imu
;
1168 unsigned index
, buf_index
;
1172 /* attempt to use fixed buffers without having provided iovecs */
1173 if (unlikely(!ctx
->user_bufs
))
1176 buf_index
= READ_ONCE(sqe
->buf_index
);
1177 if (unlikely(buf_index
>= ctx
->nr_user_bufs
))
1180 index
= array_index_nospec(buf_index
, ctx
->nr_user_bufs
);
1181 imu
= &ctx
->user_bufs
[index
];
1182 buf_addr
= READ_ONCE(sqe
->addr
);
1185 if (buf_addr
+ len
< buf_addr
)
1187 /* not inside the mapped region */
1188 if (buf_addr
< imu
->ubuf
|| buf_addr
+ len
> imu
->ubuf
+ imu
->len
)
1192 * May not be a start of buffer, set size appropriately
1193 * and advance us to the beginning.
1195 offset
= buf_addr
- imu
->ubuf
;
1196 iov_iter_bvec(iter
, rw
, imu
->bvec
, imu
->nr_bvecs
, offset
+ len
);
1200 * Don't use iov_iter_advance() here, as it's really slow for
1201 * using the latter parts of a big fixed buffer - it iterates
1202 * over each segment manually. We can cheat a bit here, because
1205 * 1) it's a BVEC iter, we set it up
1206 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1207 * first and last bvec
1209 * So just find our index, and adjust the iterator afterwards.
1210 * If the offset is within the first bvec (or the whole first
1211 * bvec, just use iov_iter_advance(). This makes it easier
1212 * since we can just skip the first segment, which may not
1213 * be PAGE_SIZE aligned.
1215 const struct bio_vec
*bvec
= imu
->bvec
;
1217 if (offset
<= bvec
->bv_len
) {
1218 iov_iter_advance(iter
, offset
);
1220 unsigned long seg_skip
;
1222 /* skip first vec */
1223 offset
-= bvec
->bv_len
;
1224 seg_skip
= 1 + (offset
>> PAGE_SHIFT
);
1226 iter
->bvec
= bvec
+ seg_skip
;
1227 iter
->nr_segs
-= seg_skip
;
1228 iter
->count
-= bvec
->bv_len
+ offset
;
1229 iter
->iov_offset
= offset
& ~PAGE_MASK
;
1236 static ssize_t
io_import_iovec(struct io_ring_ctx
*ctx
, int rw
,
1237 const struct sqe_submit
*s
, struct iovec
**iovec
,
1238 struct iov_iter
*iter
)
1240 const struct io_uring_sqe
*sqe
= s
->sqe
;
1241 void __user
*buf
= u64_to_user_ptr(READ_ONCE(sqe
->addr
));
1242 size_t sqe_len
= READ_ONCE(sqe
->len
);
1246 * We're reading ->opcode for the second time, but the first read
1247 * doesn't care whether it's _FIXED or not, so it doesn't matter
1248 * whether ->opcode changes concurrently. The first read does care
1249 * about whether it is a READ or a WRITE, so we don't trust this read
1250 * for that purpose and instead let the caller pass in the read/write
1253 opcode
= READ_ONCE(sqe
->opcode
);
1254 if (opcode
== IORING_OP_READ_FIXED
||
1255 opcode
== IORING_OP_WRITE_FIXED
) {
1256 ssize_t ret
= io_import_fixed(ctx
, rw
, sqe
, iter
);
1264 #ifdef CONFIG_COMPAT
1266 return compat_import_iovec(rw
, buf
, sqe_len
, UIO_FASTIOV
,
1270 return import_iovec(rw
, buf
, sqe_len
, UIO_FASTIOV
, iovec
, iter
);
1273 static inline bool io_should_merge(struct async_list
*al
, struct kiocb
*kiocb
)
1275 if (al
->file
== kiocb
->ki_filp
) {
1279 * Allow merging if we're anywhere in the range of the same
1280 * page. Generally this happens for sub-page reads or writes,
1281 * and it's beneficial to allow the first worker to bring the
1282 * page in and the piggy backed work can then work on the
1285 start
= al
->io_start
& PAGE_MASK
;
1286 end
= (al
->io_start
+ al
->io_len
+ PAGE_SIZE
- 1) & PAGE_MASK
;
1287 if (kiocb
->ki_pos
>= start
&& kiocb
->ki_pos
<= end
)
1296 * Make a note of the last file/offset/direction we punted to async
1297 * context. We'll use this information to see if we can piggy back a
1298 * sequential request onto the previous one, if it's still hasn't been
1299 * completed by the async worker.
1301 static void io_async_list_note(int rw
, struct io_kiocb
*req
, size_t len
)
1303 struct async_list
*async_list
= &req
->ctx
->pending_async
[rw
];
1304 struct kiocb
*kiocb
= &req
->rw
;
1305 struct file
*filp
= kiocb
->ki_filp
;
1307 if (io_should_merge(async_list
, kiocb
)) {
1308 unsigned long max_bytes
;
1310 /* Use 8x RA size as a decent limiter for both reads/writes */
1311 max_bytes
= filp
->f_ra
.ra_pages
<< (PAGE_SHIFT
+ 3);
1313 max_bytes
= VM_READAHEAD_PAGES
<< (PAGE_SHIFT
+ 3);
1315 /* If max len are exceeded, reset the state */
1316 if (async_list
->io_len
+ len
<= max_bytes
) {
1317 req
->flags
|= REQ_F_SEQ_PREV
;
1318 async_list
->io_len
+= len
;
1320 async_list
->file
= NULL
;
1324 /* New file? Reset state. */
1325 if (async_list
->file
!= filp
) {
1326 async_list
->io_start
= kiocb
->ki_pos
;
1327 async_list
->io_len
= len
;
1328 async_list
->file
= filp
;
1333 * For files that don't have ->read_iter() and ->write_iter(), handle them
1334 * by looping over ->read() or ->write() manually.
1336 static ssize_t
loop_rw_iter(int rw
, struct file
*file
, struct kiocb
*kiocb
,
1337 struct iov_iter
*iter
)
1342 * Don't support polled IO through this interface, and we can't
1343 * support non-blocking either. For the latter, this just causes
1344 * the kiocb to be handled from an async context.
1346 if (kiocb
->ki_flags
& IOCB_HIPRI
)
1348 if (kiocb
->ki_flags
& IOCB_NOWAIT
)
1351 while (iov_iter_count(iter
)) {
1352 struct iovec iovec
= iov_iter_iovec(iter
);
1356 nr
= file
->f_op
->read(file
, iovec
.iov_base
,
1357 iovec
.iov_len
, &kiocb
->ki_pos
);
1359 nr
= file
->f_op
->write(file
, iovec
.iov_base
,
1360 iovec
.iov_len
, &kiocb
->ki_pos
);
1369 if (nr
!= iovec
.iov_len
)
1371 iov_iter_advance(iter
, nr
);
1377 static int io_read(struct io_kiocb
*req
, const struct sqe_submit
*s
,
1378 bool force_nonblock
)
1380 struct iovec inline_vecs
[UIO_FASTIOV
], *iovec
= inline_vecs
;
1381 struct kiocb
*kiocb
= &req
->rw
;
1382 struct iov_iter iter
;
1385 ssize_t read_size
, ret
;
1387 ret
= io_prep_rw(req
, s
, force_nonblock
);
1390 file
= kiocb
->ki_filp
;
1392 if (unlikely(!(file
->f_mode
& FMODE_READ
)))
1395 ret
= io_import_iovec(req
->ctx
, READ
, s
, &iovec
, &iter
);
1400 if (req
->flags
& REQ_F_LINK
)
1401 req
->result
= read_size
;
1403 iov_count
= iov_iter_count(&iter
);
1404 ret
= rw_verify_area(READ
, file
, &kiocb
->ki_pos
, iov_count
);
1408 if (file
->f_op
->read_iter
)
1409 ret2
= call_read_iter(file
, kiocb
, &iter
);
1411 ret2
= loop_rw_iter(READ
, file
, kiocb
, &iter
);
1414 * In case of a short read, punt to async. This can happen
1415 * if we have data partially cached. Alternatively we can
1416 * return the short read, in which case the application will
1417 * need to issue another SQE and wait for it. That SQE will
1418 * need async punt anyway, so it's more efficient to do it
1421 if (force_nonblock
&& !(req
->flags
& REQ_F_NOWAIT
) &&
1422 (req
->flags
& REQ_F_ISREG
) &&
1423 ret2
> 0 && ret2
< read_size
)
1425 /* Catch -EAGAIN return for forced non-blocking submission */
1426 if (!force_nonblock
|| ret2
!= -EAGAIN
) {
1427 io_rw_done(kiocb
, ret2
);
1430 * If ->needs_lock is true, we're already in async
1434 io_async_list_note(READ
, req
, iov_count
);
1442 static int io_write(struct io_kiocb
*req
, const struct sqe_submit
*s
,
1443 bool force_nonblock
)
1445 struct iovec inline_vecs
[UIO_FASTIOV
], *iovec
= inline_vecs
;
1446 struct kiocb
*kiocb
= &req
->rw
;
1447 struct iov_iter iter
;
1452 ret
= io_prep_rw(req
, s
, force_nonblock
);
1456 file
= kiocb
->ki_filp
;
1457 if (unlikely(!(file
->f_mode
& FMODE_WRITE
)))
1460 ret
= io_import_iovec(req
->ctx
, WRITE
, s
, &iovec
, &iter
);
1464 if (req
->flags
& REQ_F_LINK
)
1467 iov_count
= iov_iter_count(&iter
);
1470 if (force_nonblock
&& !(kiocb
->ki_flags
& IOCB_DIRECT
)) {
1471 /* If ->needs_lock is true, we're already in async context. */
1473 io_async_list_note(WRITE
, req
, iov_count
);
1477 ret
= rw_verify_area(WRITE
, file
, &kiocb
->ki_pos
, iov_count
);
1482 * Open-code file_start_write here to grab freeze protection,
1483 * which will be released by another thread in
1484 * io_complete_rw(). Fool lockdep by telling it the lock got
1485 * released so that it doesn't complain about the held lock when
1486 * we return to userspace.
1488 if (req
->flags
& REQ_F_ISREG
) {
1489 __sb_start_write(file_inode(file
)->i_sb
,
1490 SB_FREEZE_WRITE
, true);
1491 __sb_writers_release(file_inode(file
)->i_sb
,
1494 kiocb
->ki_flags
|= IOCB_WRITE
;
1496 if (file
->f_op
->write_iter
)
1497 ret2
= call_write_iter(file
, kiocb
, &iter
);
1499 ret2
= loop_rw_iter(WRITE
, file
, kiocb
, &iter
);
1500 if (!force_nonblock
|| ret2
!= -EAGAIN
) {
1501 io_rw_done(kiocb
, ret2
);
1504 * If ->needs_lock is true, we're already in async
1508 io_async_list_note(WRITE
, req
, iov_count
);
1518 * IORING_OP_NOP just posts a completion event, nothing else.
1520 static int io_nop(struct io_kiocb
*req
, u64 user_data
)
1522 struct io_ring_ctx
*ctx
= req
->ctx
;
1525 if (unlikely(ctx
->flags
& IORING_SETUP_IOPOLL
))
1528 io_cqring_add_event(ctx
, user_data
, err
);
1533 static int io_prep_fsync(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1535 struct io_ring_ctx
*ctx
= req
->ctx
;
1540 if (unlikely(ctx
->flags
& IORING_SETUP_IOPOLL
))
1542 if (unlikely(sqe
->addr
|| sqe
->ioprio
|| sqe
->buf_index
))
1548 static int io_fsync(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
,
1549 bool force_nonblock
)
1551 loff_t sqe_off
= READ_ONCE(sqe
->off
);
1552 loff_t sqe_len
= READ_ONCE(sqe
->len
);
1553 loff_t end
= sqe_off
+ sqe_len
;
1554 unsigned fsync_flags
;
1557 fsync_flags
= READ_ONCE(sqe
->fsync_flags
);
1558 if (unlikely(fsync_flags
& ~IORING_FSYNC_DATASYNC
))
1561 ret
= io_prep_fsync(req
, sqe
);
1565 /* fsync always requires a blocking context */
1569 ret
= vfs_fsync_range(req
->rw
.ki_filp
, sqe_off
,
1570 end
> 0 ? end
: LLONG_MAX
,
1571 fsync_flags
& IORING_FSYNC_DATASYNC
);
1573 if (ret
< 0 && (req
->flags
& REQ_F_LINK
))
1574 req
->flags
|= REQ_F_FAIL_LINK
;
1575 io_cqring_add_event(req
->ctx
, sqe
->user_data
, ret
);
1580 static int io_prep_sfr(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1582 struct io_ring_ctx
*ctx
= req
->ctx
;
1588 if (unlikely(ctx
->flags
& IORING_SETUP_IOPOLL
))
1590 if (unlikely(sqe
->addr
|| sqe
->ioprio
|| sqe
->buf_index
))
1596 static int io_sync_file_range(struct io_kiocb
*req
,
1597 const struct io_uring_sqe
*sqe
,
1598 bool force_nonblock
)
1605 ret
= io_prep_sfr(req
, sqe
);
1609 /* sync_file_range always requires a blocking context */
1613 sqe_off
= READ_ONCE(sqe
->off
);
1614 sqe_len
= READ_ONCE(sqe
->len
);
1615 flags
= READ_ONCE(sqe
->sync_range_flags
);
1617 ret
= sync_file_range(req
->rw
.ki_filp
, sqe_off
, sqe_len
, flags
);
1619 if (ret
< 0 && (req
->flags
& REQ_F_LINK
))
1620 req
->flags
|= REQ_F_FAIL_LINK
;
1621 io_cqring_add_event(req
->ctx
, sqe
->user_data
, ret
);
1626 #if defined(CONFIG_NET)
1627 static int io_send_recvmsg(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
,
1628 bool force_nonblock
,
1629 long (*fn
)(struct socket
*, struct user_msghdr __user
*,
1632 struct socket
*sock
;
1635 if (unlikely(req
->ctx
->flags
& IORING_SETUP_IOPOLL
))
1638 sock
= sock_from_file(req
->file
, &ret
);
1640 struct user_msghdr __user
*msg
;
1643 flags
= READ_ONCE(sqe
->msg_flags
);
1644 if (flags
& MSG_DONTWAIT
)
1645 req
->flags
|= REQ_F_NOWAIT
;
1646 else if (force_nonblock
)
1647 flags
|= MSG_DONTWAIT
;
1649 msg
= (struct user_msghdr __user
*) (unsigned long)
1650 READ_ONCE(sqe
->addr
);
1652 ret
= fn(sock
, msg
, flags
);
1653 if (force_nonblock
&& ret
== -EAGAIN
)
1657 io_cqring_add_event(req
->ctx
, sqe
->user_data
, ret
);
1663 static int io_sendmsg(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
,
1664 bool force_nonblock
)
1666 #if defined(CONFIG_NET)
1667 return io_send_recvmsg(req
, sqe
, force_nonblock
, __sys_sendmsg_sock
);
1673 static int io_recvmsg(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
,
1674 bool force_nonblock
)
1676 #if defined(CONFIG_NET)
1677 return io_send_recvmsg(req
, sqe
, force_nonblock
, __sys_recvmsg_sock
);
1683 static void io_poll_remove_one(struct io_kiocb
*req
)
1685 struct io_poll_iocb
*poll
= &req
->poll
;
1687 spin_lock(&poll
->head
->lock
);
1688 WRITE_ONCE(poll
->canceled
, true);
1689 if (!list_empty(&poll
->wait
.entry
)) {
1690 list_del_init(&poll
->wait
.entry
);
1691 io_queue_async_work(req
->ctx
, req
);
1693 spin_unlock(&poll
->head
->lock
);
1695 list_del_init(&req
->list
);
1698 static void io_poll_remove_all(struct io_ring_ctx
*ctx
)
1700 struct io_kiocb
*req
;
1702 spin_lock_irq(&ctx
->completion_lock
);
1703 while (!list_empty(&ctx
->cancel_list
)) {
1704 req
= list_first_entry(&ctx
->cancel_list
, struct io_kiocb
,list
);
1705 io_poll_remove_one(req
);
1707 spin_unlock_irq(&ctx
->completion_lock
);
1711 * Find a running poll command that matches one specified in sqe->addr,
1712 * and remove it if found.
1714 static int io_poll_remove(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1716 struct io_ring_ctx
*ctx
= req
->ctx
;
1717 struct io_kiocb
*poll_req
, *next
;
1720 if (unlikely(req
->ctx
->flags
& IORING_SETUP_IOPOLL
))
1722 if (sqe
->ioprio
|| sqe
->off
|| sqe
->len
|| sqe
->buf_index
||
1726 spin_lock_irq(&ctx
->completion_lock
);
1727 list_for_each_entry_safe(poll_req
, next
, &ctx
->cancel_list
, list
) {
1728 if (READ_ONCE(sqe
->addr
) == poll_req
->user_data
) {
1729 io_poll_remove_one(poll_req
);
1734 spin_unlock_irq(&ctx
->completion_lock
);
1736 io_cqring_add_event(req
->ctx
, sqe
->user_data
, ret
);
1741 static void io_poll_complete(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
1744 req
->poll
.done
= true;
1745 io_cqring_fill_event(ctx
, req
->user_data
, mangle_poll(mask
));
1746 io_commit_cqring(ctx
);
1749 static void io_poll_complete_work(struct work_struct
*work
)
1751 struct io_kiocb
*req
= container_of(work
, struct io_kiocb
, work
);
1752 struct io_poll_iocb
*poll
= &req
->poll
;
1753 struct poll_table_struct pt
= { ._key
= poll
->events
};
1754 struct io_ring_ctx
*ctx
= req
->ctx
;
1757 if (!READ_ONCE(poll
->canceled
))
1758 mask
= vfs_poll(poll
->file
, &pt
) & poll
->events
;
1761 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1762 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1763 * synchronize with them. In the cancellation case the list_del_init
1764 * itself is not actually needed, but harmless so we keep it in to
1765 * avoid further branches in the fast path.
1767 spin_lock_irq(&ctx
->completion_lock
);
1768 if (!mask
&& !READ_ONCE(poll
->canceled
)) {
1769 add_wait_queue(poll
->head
, &poll
->wait
);
1770 spin_unlock_irq(&ctx
->completion_lock
);
1773 list_del_init(&req
->list
);
1774 io_poll_complete(ctx
, req
, mask
);
1775 spin_unlock_irq(&ctx
->completion_lock
);
1777 io_cqring_ev_posted(ctx
);
1781 static int io_poll_wake(struct wait_queue_entry
*wait
, unsigned mode
, int sync
,
1784 struct io_poll_iocb
*poll
= container_of(wait
, struct io_poll_iocb
,
1786 struct io_kiocb
*req
= container_of(poll
, struct io_kiocb
, poll
);
1787 struct io_ring_ctx
*ctx
= req
->ctx
;
1788 __poll_t mask
= key_to_poll(key
);
1789 unsigned long flags
;
1791 /* for instances that support it check for an event match first: */
1792 if (mask
&& !(mask
& poll
->events
))
1795 list_del_init(&poll
->wait
.entry
);
1797 if (mask
&& spin_trylock_irqsave(&ctx
->completion_lock
, flags
)) {
1798 list_del(&req
->list
);
1799 io_poll_complete(ctx
, req
, mask
);
1800 spin_unlock_irqrestore(&ctx
->completion_lock
, flags
);
1802 io_cqring_ev_posted(ctx
);
1805 io_queue_async_work(ctx
, req
);
1811 struct io_poll_table
{
1812 struct poll_table_struct pt
;
1813 struct io_kiocb
*req
;
1817 static void io_poll_queue_proc(struct file
*file
, struct wait_queue_head
*head
,
1818 struct poll_table_struct
*p
)
1820 struct io_poll_table
*pt
= container_of(p
, struct io_poll_table
, pt
);
1822 if (unlikely(pt
->req
->poll
.head
)) {
1823 pt
->error
= -EINVAL
;
1828 pt
->req
->poll
.head
= head
;
1829 add_wait_queue(head
, &pt
->req
->poll
.wait
);
1832 static int io_poll_add(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1834 struct io_poll_iocb
*poll
= &req
->poll
;
1835 struct io_ring_ctx
*ctx
= req
->ctx
;
1836 struct io_poll_table ipt
;
1837 bool cancel
= false;
1841 if (unlikely(req
->ctx
->flags
& IORING_SETUP_IOPOLL
))
1843 if (sqe
->addr
|| sqe
->ioprio
|| sqe
->off
|| sqe
->len
|| sqe
->buf_index
)
1848 req
->submit
.sqe
= NULL
;
1849 INIT_WORK(&req
->work
, io_poll_complete_work
);
1850 events
= READ_ONCE(sqe
->poll_events
);
1851 poll
->events
= demangle_poll(events
) | EPOLLERR
| EPOLLHUP
;
1855 poll
->canceled
= false;
1857 ipt
.pt
._qproc
= io_poll_queue_proc
;
1858 ipt
.pt
._key
= poll
->events
;
1860 ipt
.error
= -EINVAL
; /* same as no support for IOCB_CMD_POLL */
1862 /* initialized the list so that we can do list_empty checks */
1863 INIT_LIST_HEAD(&poll
->wait
.entry
);
1864 init_waitqueue_func_entry(&poll
->wait
, io_poll_wake
);
1866 INIT_LIST_HEAD(&req
->list
);
1868 mask
= vfs_poll(poll
->file
, &ipt
.pt
) & poll
->events
;
1870 spin_lock_irq(&ctx
->completion_lock
);
1871 if (likely(poll
->head
)) {
1872 spin_lock(&poll
->head
->lock
);
1873 if (unlikely(list_empty(&poll
->wait
.entry
))) {
1879 if (mask
|| ipt
.error
)
1880 list_del_init(&poll
->wait
.entry
);
1882 WRITE_ONCE(poll
->canceled
, true);
1883 else if (!poll
->done
) /* actually waiting for an event */
1884 list_add_tail(&req
->list
, &ctx
->cancel_list
);
1885 spin_unlock(&poll
->head
->lock
);
1887 if (mask
) { /* no async, we'd stolen it */
1889 io_poll_complete(ctx
, req
, mask
);
1891 spin_unlock_irq(&ctx
->completion_lock
);
1894 io_cqring_ev_posted(ctx
);
1900 static enum hrtimer_restart
io_timeout_fn(struct hrtimer
*timer
)
1902 struct io_ring_ctx
*ctx
;
1903 struct io_kiocb
*req
, *prev
;
1904 unsigned long flags
;
1906 req
= container_of(timer
, struct io_kiocb
, timeout
.timer
);
1908 atomic_inc(&ctx
->cq_timeouts
);
1910 spin_lock_irqsave(&ctx
->completion_lock
, flags
);
1912 * Adjust the reqs sequence before the current one because it
1913 * will consume a slot in the cq_ring and the the cq_tail pointer
1914 * will be increased, otherwise other timeout reqs may return in
1915 * advance without waiting for enough wait_nr.
1918 list_for_each_entry_continue_reverse(prev
, &ctx
->timeout_list
, list
)
1920 list_del(&req
->list
);
1922 io_cqring_fill_event(ctx
, req
->user_data
, -ETIME
);
1923 io_commit_cqring(ctx
);
1924 spin_unlock_irqrestore(&ctx
->completion_lock
, flags
);
1926 io_cqring_ev_posted(ctx
);
1929 return HRTIMER_NORESTART
;
1932 static int io_timeout(struct io_kiocb
*req
, const struct io_uring_sqe
*sqe
)
1935 struct io_ring_ctx
*ctx
= req
->ctx
;
1936 struct list_head
*entry
;
1937 struct timespec64 ts
;
1940 if (unlikely(ctx
->flags
& IORING_SETUP_IOPOLL
))
1942 if (sqe
->flags
|| sqe
->ioprio
|| sqe
->buf_index
|| sqe
->timeout_flags
||
1946 if (get_timespec64(&ts
, u64_to_user_ptr(sqe
->addr
)))
1949 req
->flags
|= REQ_F_TIMEOUT
;
1952 * sqe->off holds how many events that need to occur for this
1953 * timeout event to be satisfied. If it isn't set, then this is
1954 * a pure timeout request, sequence isn't used.
1956 count
= READ_ONCE(sqe
->off
);
1958 req
->flags
|= REQ_F_TIMEOUT_NOSEQ
;
1959 spin_lock_irq(&ctx
->completion_lock
);
1960 entry
= ctx
->timeout_list
.prev
;
1964 req
->sequence
= ctx
->cached_sq_head
+ count
- 1;
1965 /* reuse it to store the count */
1966 req
->submit
.sequence
= count
;
1969 * Insertion sort, ensuring the first entry in the list is always
1970 * the one we need first.
1972 spin_lock_irq(&ctx
->completion_lock
);
1973 list_for_each_prev(entry
, &ctx
->timeout_list
) {
1974 struct io_kiocb
*nxt
= list_entry(entry
, struct io_kiocb
, list
);
1975 unsigned nxt_sq_head
;
1976 long long tmp
, tmp_nxt
;
1978 if (nxt
->flags
& REQ_F_TIMEOUT_NOSEQ
)
1982 * Since cached_sq_head + count - 1 can overflow, use type long
1985 tmp
= (long long)ctx
->cached_sq_head
+ count
- 1;
1986 nxt_sq_head
= nxt
->sequence
- nxt
->submit
.sequence
+ 1;
1987 tmp_nxt
= (long long)nxt_sq_head
+ nxt
->submit
.sequence
- 1;
1990 * cached_sq_head may overflow, and it will never overflow twice
1991 * once there is some timeout req still be valid.
1993 if (ctx
->cached_sq_head
< nxt_sq_head
)
2000 * Sequence of reqs after the insert one and itself should
2001 * be adjusted because each timeout req consumes a slot.
2006 req
->sequence
-= span
;
2008 list_add(&req
->list
, entry
);
2009 spin_unlock_irq(&ctx
->completion_lock
);
2011 hrtimer_init(&req
->timeout
.timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
2012 req
->timeout
.timer
.function
= io_timeout_fn
;
2013 hrtimer_start(&req
->timeout
.timer
, timespec64_to_ktime(ts
),
2018 static int io_req_defer(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2019 const struct io_uring_sqe
*sqe
)
2021 struct io_uring_sqe
*sqe_copy
;
2023 if (!io_sequence_defer(ctx
, req
) && list_empty(&ctx
->defer_list
))
2026 sqe_copy
= kmalloc(sizeof(*sqe_copy
), GFP_KERNEL
);
2030 spin_lock_irq(&ctx
->completion_lock
);
2031 if (!io_sequence_defer(ctx
, req
) && list_empty(&ctx
->defer_list
)) {
2032 spin_unlock_irq(&ctx
->completion_lock
);
2037 memcpy(sqe_copy
, sqe
, sizeof(*sqe_copy
));
2038 req
->submit
.sqe
= sqe_copy
;
2040 INIT_WORK(&req
->work
, io_sq_wq_submit_work
);
2041 list_add_tail(&req
->list
, &ctx
->defer_list
);
2042 spin_unlock_irq(&ctx
->completion_lock
);
2043 return -EIOCBQUEUED
;
2046 static int __io_submit_sqe(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2047 const struct sqe_submit
*s
, bool force_nonblock
)
2051 req
->user_data
= READ_ONCE(s
->sqe
->user_data
);
2053 if (unlikely(s
->index
>= ctx
->sq_entries
))
2056 opcode
= READ_ONCE(s
->sqe
->opcode
);
2059 ret
= io_nop(req
, req
->user_data
);
2061 case IORING_OP_READV
:
2062 if (unlikely(s
->sqe
->buf_index
))
2064 ret
= io_read(req
, s
, force_nonblock
);
2066 case IORING_OP_WRITEV
:
2067 if (unlikely(s
->sqe
->buf_index
))
2069 ret
= io_write(req
, s
, force_nonblock
);
2071 case IORING_OP_READ_FIXED
:
2072 ret
= io_read(req
, s
, force_nonblock
);
2074 case IORING_OP_WRITE_FIXED
:
2075 ret
= io_write(req
, s
, force_nonblock
);
2077 case IORING_OP_FSYNC
:
2078 ret
= io_fsync(req
, s
->sqe
, force_nonblock
);
2080 case IORING_OP_POLL_ADD
:
2081 ret
= io_poll_add(req
, s
->sqe
);
2083 case IORING_OP_POLL_REMOVE
:
2084 ret
= io_poll_remove(req
, s
->sqe
);
2086 case IORING_OP_SYNC_FILE_RANGE
:
2087 ret
= io_sync_file_range(req
, s
->sqe
, force_nonblock
);
2089 case IORING_OP_SENDMSG
:
2090 ret
= io_sendmsg(req
, s
->sqe
, force_nonblock
);
2092 case IORING_OP_RECVMSG
:
2093 ret
= io_recvmsg(req
, s
->sqe
, force_nonblock
);
2095 case IORING_OP_TIMEOUT
:
2096 ret
= io_timeout(req
, s
->sqe
);
2106 if (ctx
->flags
& IORING_SETUP_IOPOLL
) {
2107 if (req
->result
== -EAGAIN
)
2110 /* workqueue context doesn't hold uring_lock, grab it now */
2112 mutex_lock(&ctx
->uring_lock
);
2113 io_iopoll_req_issued(req
);
2115 mutex_unlock(&ctx
->uring_lock
);
2121 static struct async_list
*io_async_list_from_sqe(struct io_ring_ctx
*ctx
,
2122 const struct io_uring_sqe
*sqe
)
2124 switch (sqe
->opcode
) {
2125 case IORING_OP_READV
:
2126 case IORING_OP_READ_FIXED
:
2127 return &ctx
->pending_async
[READ
];
2128 case IORING_OP_WRITEV
:
2129 case IORING_OP_WRITE_FIXED
:
2130 return &ctx
->pending_async
[WRITE
];
2136 static inline bool io_sqe_needs_user(const struct io_uring_sqe
*sqe
)
2138 u8 opcode
= READ_ONCE(sqe
->opcode
);
2140 return !(opcode
== IORING_OP_READ_FIXED
||
2141 opcode
== IORING_OP_WRITE_FIXED
);
2144 static void io_sq_wq_submit_work(struct work_struct
*work
)
2146 struct io_kiocb
*req
= container_of(work
, struct io_kiocb
, work
);
2147 struct io_ring_ctx
*ctx
= req
->ctx
;
2148 struct mm_struct
*cur_mm
= NULL
;
2149 struct async_list
*async_list
;
2150 LIST_HEAD(req_list
);
2151 mm_segment_t old_fs
;
2154 async_list
= io_async_list_from_sqe(ctx
, req
->submit
.sqe
);
2157 struct sqe_submit
*s
= &req
->submit
;
2158 const struct io_uring_sqe
*sqe
= s
->sqe
;
2159 unsigned int flags
= req
->flags
;
2161 /* Ensure we clear previously set non-block flag */
2162 req
->rw
.ki_flags
&= ~IOCB_NOWAIT
;
2165 if (io_sqe_needs_user(sqe
) && !cur_mm
) {
2166 if (!mmget_not_zero(ctx
->sqo_mm
)) {
2169 cur_mm
= ctx
->sqo_mm
;
2177 s
->has_user
= cur_mm
!= NULL
;
2178 s
->needs_lock
= true;
2180 ret
= __io_submit_sqe(ctx
, req
, s
, false);
2182 * We can get EAGAIN for polled IO even though
2183 * we're forcing a sync submission from here,
2184 * since we can't wait for request slots on the
2193 /* drop submission reference */
2197 io_cqring_add_event(ctx
, sqe
->user_data
, ret
);
2201 /* async context always use a copy of the sqe */
2204 /* req from defer and link list needn't decrease async cnt */
2205 if (flags
& (REQ_F_IO_DRAINED
| REQ_F_LINK_DONE
))
2210 if (!list_empty(&req_list
)) {
2211 req
= list_first_entry(&req_list
, struct io_kiocb
,
2213 list_del(&req
->list
);
2216 if (list_empty(&async_list
->list
))
2220 spin_lock(&async_list
->lock
);
2221 if (list_empty(&async_list
->list
)) {
2222 spin_unlock(&async_list
->lock
);
2225 list_splice_init(&async_list
->list
, &req_list
);
2226 spin_unlock(&async_list
->lock
);
2228 req
= list_first_entry(&req_list
, struct io_kiocb
, list
);
2229 list_del(&req
->list
);
2233 * Rare case of racing with a submitter. If we find the count has
2234 * dropped to zero AND we have pending work items, then restart
2235 * the processing. This is a tiny race window.
2238 ret
= atomic_dec_return(&async_list
->cnt
);
2239 while (!ret
&& !list_empty(&async_list
->list
)) {
2240 spin_lock(&async_list
->lock
);
2241 atomic_inc(&async_list
->cnt
);
2242 list_splice_init(&async_list
->list
, &req_list
);
2243 spin_unlock(&async_list
->lock
);
2245 if (!list_empty(&req_list
)) {
2246 req
= list_first_entry(&req_list
,
2247 struct io_kiocb
, list
);
2248 list_del(&req
->list
);
2251 ret
= atomic_dec_return(&async_list
->cnt
);
2264 * See if we can piggy back onto previously submitted work, that is still
2265 * running. We currently only allow this if the new request is sequential
2266 * to the previous one we punted.
2268 static bool io_add_to_prev_work(struct async_list
*list
, struct io_kiocb
*req
)
2274 if (!(req
->flags
& REQ_F_SEQ_PREV
))
2276 if (!atomic_read(&list
->cnt
))
2280 spin_lock(&list
->lock
);
2281 list_add_tail(&req
->list
, &list
->list
);
2283 * Ensure we see a simultaneous modification from io_sq_wq_submit_work()
2286 if (!atomic_read(&list
->cnt
)) {
2287 list_del_init(&req
->list
);
2290 spin_unlock(&list
->lock
);
2294 static bool io_op_needs_file(const struct io_uring_sqe
*sqe
)
2296 int op
= READ_ONCE(sqe
->opcode
);
2300 case IORING_OP_POLL_REMOVE
:
2301 case IORING_OP_TIMEOUT
:
2308 static int io_req_set_file(struct io_ring_ctx
*ctx
, const struct sqe_submit
*s
,
2309 struct io_submit_state
*state
, struct io_kiocb
*req
)
2314 flags
= READ_ONCE(s
->sqe
->flags
);
2315 fd
= READ_ONCE(s
->sqe
->fd
);
2317 if (flags
& IOSQE_IO_DRAIN
)
2318 req
->flags
|= REQ_F_IO_DRAIN
;
2320 * All io need record the previous position, if LINK vs DARIN,
2321 * it can be used to mark the position of the first IO in the
2324 req
->sequence
= s
->sequence
;
2326 if (!io_op_needs_file(s
->sqe
))
2329 if (flags
& IOSQE_FIXED_FILE
) {
2330 if (unlikely(!ctx
->user_files
||
2331 (unsigned) fd
>= ctx
->nr_user_files
))
2333 req
->file
= ctx
->user_files
[fd
];
2334 req
->flags
|= REQ_F_FIXED_FILE
;
2336 if (s
->needs_fixed_file
)
2338 req
->file
= io_file_get(state
, fd
);
2339 if (unlikely(!req
->file
))
2346 static int __io_queue_sqe(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2347 struct sqe_submit
*s
)
2351 ret
= __io_submit_sqe(ctx
, req
, s
, true);
2354 * We async punt it if the file wasn't marked NOWAIT, or if the file
2355 * doesn't support non-blocking read/write attempts
2357 if (ret
== -EAGAIN
&& (!(req
->flags
& REQ_F_NOWAIT
) ||
2358 (req
->flags
& REQ_F_MUST_PUNT
))) {
2359 struct io_uring_sqe
*sqe_copy
;
2361 sqe_copy
= kmemdup(s
->sqe
, sizeof(*sqe_copy
), GFP_KERNEL
);
2363 struct async_list
*list
;
2366 memcpy(&req
->submit
, s
, sizeof(*s
));
2367 list
= io_async_list_from_sqe(ctx
, s
->sqe
);
2368 if (!io_add_to_prev_work(list
, req
)) {
2370 atomic_inc(&list
->cnt
);
2371 INIT_WORK(&req
->work
, io_sq_wq_submit_work
);
2372 io_queue_async_work(ctx
, req
);
2376 * Queued up for async execution, worker will release
2377 * submit reference when the iocb is actually submitted.
2383 /* drop submission reference */
2386 /* and drop final reference, if we failed */
2388 io_cqring_add_event(ctx
, req
->user_data
, ret
);
2389 if (req
->flags
& REQ_F_LINK
)
2390 req
->flags
|= REQ_F_FAIL_LINK
;
2397 static int io_queue_sqe(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2398 struct sqe_submit
*s
)
2402 ret
= io_req_defer(ctx
, req
, s
->sqe
);
2404 if (ret
!= -EIOCBQUEUED
) {
2406 io_cqring_add_event(ctx
, s
->sqe
->user_data
, ret
);
2411 return __io_queue_sqe(ctx
, req
, s
);
2414 static int io_queue_link_head(struct io_ring_ctx
*ctx
, struct io_kiocb
*req
,
2415 struct sqe_submit
*s
, struct io_kiocb
*shadow
)
2418 int need_submit
= false;
2421 return io_queue_sqe(ctx
, req
, s
);
2424 * Mark the first IO in link list as DRAIN, let all the following
2425 * IOs enter the defer list. all IO needs to be completed before link
2428 req
->flags
|= REQ_F_IO_DRAIN
;
2429 ret
= io_req_defer(ctx
, req
, s
->sqe
);
2431 if (ret
!= -EIOCBQUEUED
) {
2433 __io_free_req(shadow
);
2434 io_cqring_add_event(ctx
, s
->sqe
->user_data
, ret
);
2439 * If ret == 0 means that all IOs in front of link io are
2440 * running done. let's queue link head.
2445 /* Insert shadow req to defer_list, blocking next IOs */
2446 spin_lock_irq(&ctx
->completion_lock
);
2447 list_add_tail(&shadow
->list
, &ctx
->defer_list
);
2448 spin_unlock_irq(&ctx
->completion_lock
);
2451 return __io_queue_sqe(ctx
, req
, s
);
2456 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2458 static void io_submit_sqe(struct io_ring_ctx
*ctx
, struct sqe_submit
*s
,
2459 struct io_submit_state
*state
, struct io_kiocb
**link
)
2461 struct io_uring_sqe
*sqe_copy
;
2462 struct io_kiocb
*req
;
2465 /* enforce forwards compatibility on users */
2466 if (unlikely(s
->sqe
->flags
& ~SQE_VALID_FLAGS
)) {
2471 req
= io_get_req(ctx
, state
);
2472 if (unlikely(!req
)) {
2477 ret
= io_req_set_file(ctx
, s
, state
, req
);
2478 if (unlikely(ret
)) {
2482 io_cqring_add_event(ctx
, s
->sqe
->user_data
, ret
);
2486 req
->user_data
= s
->sqe
->user_data
;
2489 * If we already have a head request, queue this one for async
2490 * submittal once the head completes. If we don't have a head but
2491 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2492 * submitted sync once the chain is complete. If none of those
2493 * conditions are true (normal request), then just queue it.
2496 struct io_kiocb
*prev
= *link
;
2498 sqe_copy
= kmemdup(s
->sqe
, sizeof(*sqe_copy
), GFP_KERNEL
);
2505 memcpy(&req
->submit
, s
, sizeof(*s
));
2506 list_add_tail(&req
->list
, &prev
->link_list
);
2507 } else if (s
->sqe
->flags
& IOSQE_IO_LINK
) {
2508 req
->flags
|= REQ_F_LINK
;
2510 memcpy(&req
->submit
, s
, sizeof(*s
));
2511 INIT_LIST_HEAD(&req
->link_list
);
2514 io_queue_sqe(ctx
, req
, s
);
2519 * Batched submission is done, ensure local IO is flushed out.
2521 static void io_submit_state_end(struct io_submit_state
*state
)
2523 blk_finish_plug(&state
->plug
);
2525 if (state
->free_reqs
)
2526 kmem_cache_free_bulk(req_cachep
, state
->free_reqs
,
2527 &state
->reqs
[state
->cur_req
]);
2531 * Start submission side cache.
2533 static void io_submit_state_start(struct io_submit_state
*state
,
2534 struct io_ring_ctx
*ctx
, unsigned max_ios
)
2536 blk_start_plug(&state
->plug
);
2537 state
->free_reqs
= 0;
2539 state
->ios_left
= max_ios
;
2542 static void io_commit_sqring(struct io_ring_ctx
*ctx
)
2544 struct io_rings
*rings
= ctx
->rings
;
2546 if (ctx
->cached_sq_head
!= READ_ONCE(rings
->sq
.head
)) {
2548 * Ensure any loads from the SQEs are done at this point,
2549 * since once we write the new head, the application could
2550 * write new data to them.
2552 smp_store_release(&rings
->sq
.head
, ctx
->cached_sq_head
);
2557 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2558 * that is mapped by userspace. This means that care needs to be taken to
2559 * ensure that reads are stable, as we cannot rely on userspace always
2560 * being a good citizen. If members of the sqe are validated and then later
2561 * used, it's important that those reads are done through READ_ONCE() to
2562 * prevent a re-load down the line.
2564 static bool io_get_sqring(struct io_ring_ctx
*ctx
, struct sqe_submit
*s
)
2566 struct io_rings
*rings
= ctx
->rings
;
2567 u32
*sq_array
= ctx
->sq_array
;
2571 * The cached sq head (or cq tail) serves two purposes:
2573 * 1) allows us to batch the cost of updating the user visible
2575 * 2) allows the kernel side to track the head on its own, even
2576 * though the application is the one updating it.
2578 head
= ctx
->cached_sq_head
;
2579 /* make sure SQ entry isn't read before tail */
2580 if (head
== smp_load_acquire(&rings
->sq
.tail
))
2583 head
= READ_ONCE(sq_array
[head
& ctx
->sq_mask
]);
2584 if (head
< ctx
->sq_entries
) {
2586 s
->sqe
= &ctx
->sq_sqes
[head
];
2587 s
->sequence
= ctx
->cached_sq_head
;
2588 ctx
->cached_sq_head
++;
2592 /* drop invalid entries */
2593 ctx
->cached_sq_head
++;
2594 ctx
->cached_sq_dropped
++;
2595 WRITE_ONCE(rings
->sq_dropped
, ctx
->cached_sq_dropped
);
2599 static int io_submit_sqes(struct io_ring_ctx
*ctx
, unsigned int nr
,
2600 bool has_user
, bool mm_fault
)
2602 struct io_submit_state state
, *statep
= NULL
;
2603 struct io_kiocb
*link
= NULL
;
2604 struct io_kiocb
*shadow_req
= NULL
;
2605 bool prev_was_link
= false;
2606 int i
, submitted
= 0;
2608 if (nr
> IO_PLUG_THRESHOLD
) {
2609 io_submit_state_start(&state
, ctx
, nr
);
2613 for (i
= 0; i
< nr
; i
++) {
2614 struct sqe_submit s
;
2616 if (!io_get_sqring(ctx
, &s
))
2620 * If previous wasn't linked and we have a linked command,
2621 * that's the end of the chain. Submit the previous link.
2623 if (!prev_was_link
&& link
) {
2624 io_queue_link_head(ctx
, link
, &link
->submit
, shadow_req
);
2628 prev_was_link
= (s
.sqe
->flags
& IOSQE_IO_LINK
) != 0;
2630 if (link
&& (s
.sqe
->flags
& IOSQE_IO_DRAIN
)) {
2632 shadow_req
= io_get_req(ctx
, NULL
);
2633 if (unlikely(!shadow_req
))
2635 shadow_req
->flags
|= (REQ_F_IO_DRAIN
| REQ_F_SHADOW_DRAIN
);
2636 refcount_dec(&shadow_req
->refs
);
2638 shadow_req
->sequence
= s
.sequence
;
2642 if (unlikely(mm_fault
)) {
2643 io_cqring_add_event(ctx
, s
.sqe
->user_data
,
2646 s
.has_user
= has_user
;
2647 s
.needs_lock
= true;
2648 s
.needs_fixed_file
= true;
2649 io_submit_sqe(ctx
, &s
, statep
, &link
);
2655 io_queue_link_head(ctx
, link
, &link
->submit
, shadow_req
);
2657 io_submit_state_end(&state
);
2662 static int io_sq_thread(void *data
)
2664 struct io_ring_ctx
*ctx
= data
;
2665 struct mm_struct
*cur_mm
= NULL
;
2666 mm_segment_t old_fs
;
2669 unsigned long timeout
;
2671 complete(&ctx
->sqo_thread_started
);
2676 timeout
= inflight
= 0;
2677 while (!kthread_should_park()) {
2678 bool mm_fault
= false;
2679 unsigned int to_submit
;
2682 unsigned nr_events
= 0;
2684 if (ctx
->flags
& IORING_SETUP_IOPOLL
) {
2686 * inflight is the count of the maximum possible
2687 * entries we submitted, but it can be smaller
2688 * if we dropped some of them. If we don't have
2689 * poll entries available, then we know that we
2690 * have nothing left to poll for. Reset the
2691 * inflight count to zero in that case.
2693 mutex_lock(&ctx
->uring_lock
);
2694 if (!list_empty(&ctx
->poll_list
))
2695 __io_iopoll_check(ctx
, &nr_events
, 0);
2698 mutex_unlock(&ctx
->uring_lock
);
2701 * Normal IO, just pretend everything completed.
2702 * We don't have to poll completions for that.
2704 nr_events
= inflight
;
2707 inflight
-= nr_events
;
2709 timeout
= jiffies
+ ctx
->sq_thread_idle
;
2712 to_submit
= io_sqring_entries(ctx
);
2715 * We're polling. If we're within the defined idle
2716 * period, then let us spin without work before going
2719 if (inflight
|| !time_after(jiffies
, timeout
)) {
2725 * Drop cur_mm before scheduling, we can't hold it for
2726 * long periods (or over schedule()). Do this before
2727 * adding ourselves to the waitqueue, as the unuse/drop
2736 prepare_to_wait(&ctx
->sqo_wait
, &wait
,
2737 TASK_INTERRUPTIBLE
);
2739 /* Tell userspace we may need a wakeup call */
2740 ctx
->rings
->sq_flags
|= IORING_SQ_NEED_WAKEUP
;
2741 /* make sure to read SQ tail after writing flags */
2744 to_submit
= io_sqring_entries(ctx
);
2746 if (kthread_should_park()) {
2747 finish_wait(&ctx
->sqo_wait
, &wait
);
2750 if (signal_pending(current
))
2751 flush_signals(current
);
2753 finish_wait(&ctx
->sqo_wait
, &wait
);
2755 ctx
->rings
->sq_flags
&= ~IORING_SQ_NEED_WAKEUP
;
2758 finish_wait(&ctx
->sqo_wait
, &wait
);
2760 ctx
->rings
->sq_flags
&= ~IORING_SQ_NEED_WAKEUP
;
2763 /* Unless all new commands are FIXED regions, grab mm */
2765 mm_fault
= !mmget_not_zero(ctx
->sqo_mm
);
2767 use_mm(ctx
->sqo_mm
);
2768 cur_mm
= ctx
->sqo_mm
;
2772 to_submit
= min(to_submit
, ctx
->sq_entries
);
2773 inflight
+= io_submit_sqes(ctx
, to_submit
, cur_mm
!= NULL
,
2776 /* Commit SQ ring head once we've consumed all SQEs */
2777 io_commit_sqring(ctx
);
2791 static int io_ring_submit(struct io_ring_ctx
*ctx
, unsigned int to_submit
)
2793 struct io_submit_state state
, *statep
= NULL
;
2794 struct io_kiocb
*link
= NULL
;
2795 struct io_kiocb
*shadow_req
= NULL
;
2796 bool prev_was_link
= false;
2799 if (to_submit
> IO_PLUG_THRESHOLD
) {
2800 io_submit_state_start(&state
, ctx
, to_submit
);
2804 for (i
= 0; i
< to_submit
; i
++) {
2805 struct sqe_submit s
;
2807 if (!io_get_sqring(ctx
, &s
))
2811 * If previous wasn't linked and we have a linked command,
2812 * that's the end of the chain. Submit the previous link.
2814 if (!prev_was_link
&& link
) {
2815 io_queue_link_head(ctx
, link
, &link
->submit
, shadow_req
);
2819 prev_was_link
= (s
.sqe
->flags
& IOSQE_IO_LINK
) != 0;
2821 if (link
&& (s
.sqe
->flags
& IOSQE_IO_DRAIN
)) {
2823 shadow_req
= io_get_req(ctx
, NULL
);
2824 if (unlikely(!shadow_req
))
2826 shadow_req
->flags
|= (REQ_F_IO_DRAIN
| REQ_F_SHADOW_DRAIN
);
2827 refcount_dec(&shadow_req
->refs
);
2829 shadow_req
->sequence
= s
.sequence
;
2834 s
.needs_lock
= false;
2835 s
.needs_fixed_file
= false;
2837 io_submit_sqe(ctx
, &s
, statep
, &link
);
2841 io_queue_link_head(ctx
, link
, &link
->submit
, shadow_req
);
2843 io_submit_state_end(statep
);
2845 io_commit_sqring(ctx
);
2850 struct io_wait_queue
{
2851 struct wait_queue_entry wq
;
2852 struct io_ring_ctx
*ctx
;
2854 unsigned nr_timeouts
;
2857 static inline bool io_should_wake(struct io_wait_queue
*iowq
)
2859 struct io_ring_ctx
*ctx
= iowq
->ctx
;
2862 * Wake up if we have enough events, or if a timeout occured since we
2863 * started waiting. For timeouts, we always want to return to userspace,
2864 * regardless of event count.
2866 return io_cqring_events(ctx
->rings
) >= iowq
->to_wait
||
2867 atomic_read(&ctx
->cq_timeouts
) != iowq
->nr_timeouts
;
2870 static int io_wake_function(struct wait_queue_entry
*curr
, unsigned int mode
,
2871 int wake_flags
, void *key
)
2873 struct io_wait_queue
*iowq
= container_of(curr
, struct io_wait_queue
,
2876 if (!io_should_wake(iowq
))
2879 return autoremove_wake_function(curr
, mode
, wake_flags
, key
);
2883 * Wait until events become available, if we don't already have some. The
2884 * application must reap them itself, as they reside on the shared cq ring.
2886 static int io_cqring_wait(struct io_ring_ctx
*ctx
, int min_events
,
2887 const sigset_t __user
*sig
, size_t sigsz
)
2889 struct io_wait_queue iowq
= {
2892 .func
= io_wake_function
,
2893 .entry
= LIST_HEAD_INIT(iowq
.wq
.entry
),
2896 .to_wait
= min_events
,
2898 struct io_rings
*rings
= ctx
->rings
;
2901 if (io_cqring_events(rings
) >= min_events
)
2905 #ifdef CONFIG_COMPAT
2906 if (in_compat_syscall())
2907 ret
= set_compat_user_sigmask((const compat_sigset_t __user
*)sig
,
2911 ret
= set_user_sigmask(sig
, sigsz
);
2918 iowq
.nr_timeouts
= atomic_read(&ctx
->cq_timeouts
);
2920 prepare_to_wait_exclusive(&ctx
->wait
, &iowq
.wq
,
2921 TASK_INTERRUPTIBLE
);
2922 if (io_should_wake(&iowq
))
2925 if (signal_pending(current
)) {
2930 finish_wait(&ctx
->wait
, &iowq
.wq
);
2932 restore_saved_sigmask_unless(ret
== -ERESTARTSYS
);
2933 if (ret
== -ERESTARTSYS
)
2936 return READ_ONCE(rings
->cq
.head
) == READ_ONCE(rings
->cq
.tail
) ? ret
: 0;
2939 static void __io_sqe_files_unregister(struct io_ring_ctx
*ctx
)
2941 #if defined(CONFIG_UNIX)
2942 if (ctx
->ring_sock
) {
2943 struct sock
*sock
= ctx
->ring_sock
->sk
;
2944 struct sk_buff
*skb
;
2946 while ((skb
= skb_dequeue(&sock
->sk_receive_queue
)) != NULL
)
2952 for (i
= 0; i
< ctx
->nr_user_files
; i
++)
2953 fput(ctx
->user_files
[i
]);
2957 static int io_sqe_files_unregister(struct io_ring_ctx
*ctx
)
2959 if (!ctx
->user_files
)
2962 __io_sqe_files_unregister(ctx
);
2963 kfree(ctx
->user_files
);
2964 ctx
->user_files
= NULL
;
2965 ctx
->nr_user_files
= 0;
2969 static void io_sq_thread_stop(struct io_ring_ctx
*ctx
)
2971 if (ctx
->sqo_thread
) {
2972 wait_for_completion(&ctx
->sqo_thread_started
);
2974 * The park is a bit of a work-around, without it we get
2975 * warning spews on shutdown with SQPOLL set and affinity
2976 * set to a single CPU.
2978 kthread_park(ctx
->sqo_thread
);
2979 kthread_stop(ctx
->sqo_thread
);
2980 ctx
->sqo_thread
= NULL
;
2984 static void io_finish_async(struct io_ring_ctx
*ctx
)
2988 io_sq_thread_stop(ctx
);
2990 for (i
= 0; i
< ARRAY_SIZE(ctx
->sqo_wq
); i
++) {
2991 if (ctx
->sqo_wq
[i
]) {
2992 destroy_workqueue(ctx
->sqo_wq
[i
]);
2993 ctx
->sqo_wq
[i
] = NULL
;
2998 #if defined(CONFIG_UNIX)
2999 static void io_destruct_skb(struct sk_buff
*skb
)
3001 struct io_ring_ctx
*ctx
= skb
->sk
->sk_user_data
;
3004 for (i
= 0; i
< ARRAY_SIZE(ctx
->sqo_wq
); i
++)
3006 flush_workqueue(ctx
->sqo_wq
[i
]);
3008 unix_destruct_scm(skb
);
3012 * Ensure the UNIX gc is aware of our file set, so we are certain that
3013 * the io_uring can be safely unregistered on process exit, even if we have
3014 * loops in the file referencing.
3016 static int __io_sqe_files_scm(struct io_ring_ctx
*ctx
, int nr
, int offset
)
3018 struct sock
*sk
= ctx
->ring_sock
->sk
;
3019 struct scm_fp_list
*fpl
;
3020 struct sk_buff
*skb
;
3023 if (!capable(CAP_SYS_RESOURCE
) && !capable(CAP_SYS_ADMIN
)) {
3024 unsigned long inflight
= ctx
->user
->unix_inflight
+ nr
;
3026 if (inflight
> task_rlimit(current
, RLIMIT_NOFILE
))
3030 fpl
= kzalloc(sizeof(*fpl
), GFP_KERNEL
);
3034 skb
= alloc_skb(0, GFP_KERNEL
);
3041 skb
->destructor
= io_destruct_skb
;
3043 fpl
->user
= get_uid(ctx
->user
);
3044 for (i
= 0; i
< nr
; i
++) {
3045 fpl
->fp
[i
] = get_file(ctx
->user_files
[i
+ offset
]);
3046 unix_inflight(fpl
->user
, fpl
->fp
[i
]);
3049 fpl
->max
= fpl
->count
= nr
;
3050 UNIXCB(skb
).fp
= fpl
;
3051 refcount_add(skb
->truesize
, &sk
->sk_wmem_alloc
);
3052 skb_queue_head(&sk
->sk_receive_queue
, skb
);
3054 for (i
= 0; i
< nr
; i
++)
3061 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
3062 * causes regular reference counting to break down. We rely on the UNIX
3063 * garbage collection to take care of this problem for us.
3065 static int io_sqe_files_scm(struct io_ring_ctx
*ctx
)
3067 unsigned left
, total
;
3071 left
= ctx
->nr_user_files
;
3073 unsigned this_files
= min_t(unsigned, left
, SCM_MAX_FD
);
3075 ret
= __io_sqe_files_scm(ctx
, this_files
, total
);
3079 total
+= this_files
;
3085 while (total
< ctx
->nr_user_files
) {
3086 fput(ctx
->user_files
[total
]);
3093 static int io_sqe_files_scm(struct io_ring_ctx
*ctx
)
3099 static int io_sqe_files_register(struct io_ring_ctx
*ctx
, void __user
*arg
,
3102 __s32 __user
*fds
= (__s32 __user
*) arg
;
3106 if (ctx
->user_files
)
3110 if (nr_args
> IORING_MAX_FIXED_FILES
)
3113 ctx
->user_files
= kcalloc(nr_args
, sizeof(struct file
*), GFP_KERNEL
);
3114 if (!ctx
->user_files
)
3117 for (i
= 0; i
< nr_args
; i
++) {
3119 if (copy_from_user(&fd
, &fds
[i
], sizeof(fd
)))
3122 ctx
->user_files
[i
] = fget(fd
);
3125 if (!ctx
->user_files
[i
])
3128 * Don't allow io_uring instances to be registered. If UNIX
3129 * isn't enabled, then this causes a reference cycle and this
3130 * instance can never get freed. If UNIX is enabled we'll
3131 * handle it just fine, but there's still no point in allowing
3132 * a ring fd as it doesn't support regular read/write anyway.
3134 if (ctx
->user_files
[i
]->f_op
== &io_uring_fops
) {
3135 fput(ctx
->user_files
[i
]);
3138 ctx
->nr_user_files
++;
3143 for (i
= 0; i
< ctx
->nr_user_files
; i
++)
3144 fput(ctx
->user_files
[i
]);
3146 kfree(ctx
->user_files
);
3147 ctx
->user_files
= NULL
;
3148 ctx
->nr_user_files
= 0;
3152 ret
= io_sqe_files_scm(ctx
);
3154 io_sqe_files_unregister(ctx
);
3159 static int io_sq_offload_start(struct io_ring_ctx
*ctx
,
3160 struct io_uring_params
*p
)
3164 init_waitqueue_head(&ctx
->sqo_wait
);
3165 mmgrab(current
->mm
);
3166 ctx
->sqo_mm
= current
->mm
;
3168 if (ctx
->flags
& IORING_SETUP_SQPOLL
) {
3170 if (!capable(CAP_SYS_ADMIN
))
3173 ctx
->sq_thread_idle
= msecs_to_jiffies(p
->sq_thread_idle
);
3174 if (!ctx
->sq_thread_idle
)
3175 ctx
->sq_thread_idle
= HZ
;
3177 if (p
->flags
& IORING_SETUP_SQ_AFF
) {
3178 int cpu
= p
->sq_thread_cpu
;
3181 if (cpu
>= nr_cpu_ids
)
3183 if (!cpu_online(cpu
))
3186 ctx
->sqo_thread
= kthread_create_on_cpu(io_sq_thread
,
3190 ctx
->sqo_thread
= kthread_create(io_sq_thread
, ctx
,
3193 if (IS_ERR(ctx
->sqo_thread
)) {
3194 ret
= PTR_ERR(ctx
->sqo_thread
);
3195 ctx
->sqo_thread
= NULL
;
3198 wake_up_process(ctx
->sqo_thread
);
3199 } else if (p
->flags
& IORING_SETUP_SQ_AFF
) {
3200 /* Can't have SQ_AFF without SQPOLL */
3205 /* Do QD, or 2 * CPUS, whatever is smallest */
3206 ctx
->sqo_wq
[0] = alloc_workqueue("io_ring-wq",
3207 WQ_UNBOUND
| WQ_FREEZABLE
,
3208 min(ctx
->sq_entries
- 1, 2 * num_online_cpus()));
3209 if (!ctx
->sqo_wq
[0]) {
3215 * This is for buffered writes, where we want to limit the parallelism
3216 * due to file locking in file systems. As "normal" buffered writes
3217 * should parellelize on writeout quite nicely, limit us to having 2
3218 * pending. This avoids massive contention on the inode when doing
3219 * buffered async writes.
3221 ctx
->sqo_wq
[1] = alloc_workqueue("io_ring-write-wq",
3222 WQ_UNBOUND
| WQ_FREEZABLE
, 2);
3223 if (!ctx
->sqo_wq
[1]) {
3230 io_finish_async(ctx
);
3231 mmdrop(ctx
->sqo_mm
);
3236 static void io_unaccount_mem(struct user_struct
*user
, unsigned long nr_pages
)
3238 atomic_long_sub(nr_pages
, &user
->locked_vm
);
3241 static int io_account_mem(struct user_struct
*user
, unsigned long nr_pages
)
3243 unsigned long page_limit
, cur_pages
, new_pages
;
3245 /* Don't allow more pages than we can safely lock */
3246 page_limit
= rlimit(RLIMIT_MEMLOCK
) >> PAGE_SHIFT
;
3249 cur_pages
= atomic_long_read(&user
->locked_vm
);
3250 new_pages
= cur_pages
+ nr_pages
;
3251 if (new_pages
> page_limit
)
3253 } while (atomic_long_cmpxchg(&user
->locked_vm
, cur_pages
,
3254 new_pages
) != cur_pages
);
3259 static void io_mem_free(void *ptr
)
3266 page
= virt_to_head_page(ptr
);
3267 if (put_page_testzero(page
))
3268 free_compound_page(page
);
3271 static void *io_mem_alloc(size_t size
)
3273 gfp_t gfp_flags
= GFP_KERNEL
| __GFP_ZERO
| __GFP_NOWARN
| __GFP_COMP
|
3276 return (void *) __get_free_pages(gfp_flags
, get_order(size
));
3279 static unsigned long rings_size(unsigned sq_entries
, unsigned cq_entries
,
3282 struct io_rings
*rings
;
3283 size_t off
, sq_array_size
;
3285 off
= struct_size(rings
, cqes
, cq_entries
);
3286 if (off
== SIZE_MAX
)
3290 off
= ALIGN(off
, SMP_CACHE_BYTES
);
3295 sq_array_size
= array_size(sizeof(u32
), sq_entries
);
3296 if (sq_array_size
== SIZE_MAX
)
3299 if (check_add_overflow(off
, sq_array_size
, &off
))
3308 static unsigned long ring_pages(unsigned sq_entries
, unsigned cq_entries
)
3312 pages
= (size_t)1 << get_order(
3313 rings_size(sq_entries
, cq_entries
, NULL
));
3314 pages
+= (size_t)1 << get_order(
3315 array_size(sizeof(struct io_uring_sqe
), sq_entries
));
3320 static int io_sqe_buffer_unregister(struct io_ring_ctx
*ctx
)
3324 if (!ctx
->user_bufs
)
3327 for (i
= 0; i
< ctx
->nr_user_bufs
; i
++) {
3328 struct io_mapped_ubuf
*imu
= &ctx
->user_bufs
[i
];
3330 for (j
= 0; j
< imu
->nr_bvecs
; j
++)
3331 put_user_page(imu
->bvec
[j
].bv_page
);
3333 if (ctx
->account_mem
)
3334 io_unaccount_mem(ctx
->user
, imu
->nr_bvecs
);
3339 kfree(ctx
->user_bufs
);
3340 ctx
->user_bufs
= NULL
;
3341 ctx
->nr_user_bufs
= 0;
3345 static int io_copy_iov(struct io_ring_ctx
*ctx
, struct iovec
*dst
,
3346 void __user
*arg
, unsigned index
)
3348 struct iovec __user
*src
;
3350 #ifdef CONFIG_COMPAT
3352 struct compat_iovec __user
*ciovs
;
3353 struct compat_iovec ciov
;
3355 ciovs
= (struct compat_iovec __user
*) arg
;
3356 if (copy_from_user(&ciov
, &ciovs
[index
], sizeof(ciov
)))
3359 dst
->iov_base
= (void __user
*) (unsigned long) ciov
.iov_base
;
3360 dst
->iov_len
= ciov
.iov_len
;
3364 src
= (struct iovec __user
*) arg
;
3365 if (copy_from_user(dst
, &src
[index
], sizeof(*dst
)))
3370 static int io_sqe_buffer_register(struct io_ring_ctx
*ctx
, void __user
*arg
,
3373 struct vm_area_struct
**vmas
= NULL
;
3374 struct page
**pages
= NULL
;
3375 int i
, j
, got_pages
= 0;
3380 if (!nr_args
|| nr_args
> UIO_MAXIOV
)
3383 ctx
->user_bufs
= kcalloc(nr_args
, sizeof(struct io_mapped_ubuf
),
3385 if (!ctx
->user_bufs
)
3388 for (i
= 0; i
< nr_args
; i
++) {
3389 struct io_mapped_ubuf
*imu
= &ctx
->user_bufs
[i
];
3390 unsigned long off
, start
, end
, ubuf
;
3395 ret
= io_copy_iov(ctx
, &iov
, arg
, i
);
3400 * Don't impose further limits on the size and buffer
3401 * constraints here, we'll -EINVAL later when IO is
3402 * submitted if they are wrong.
3405 if (!iov
.iov_base
|| !iov
.iov_len
)
3408 /* arbitrary limit, but we need something */
3409 if (iov
.iov_len
> SZ_1G
)
3412 ubuf
= (unsigned long) iov
.iov_base
;
3413 end
= (ubuf
+ iov
.iov_len
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
3414 start
= ubuf
>> PAGE_SHIFT
;
3415 nr_pages
= end
- start
;
3417 if (ctx
->account_mem
) {
3418 ret
= io_account_mem(ctx
->user
, nr_pages
);
3424 if (!pages
|| nr_pages
> got_pages
) {
3427 pages
= kvmalloc_array(nr_pages
, sizeof(struct page
*),
3429 vmas
= kvmalloc_array(nr_pages
,
3430 sizeof(struct vm_area_struct
*),
3432 if (!pages
|| !vmas
) {
3434 if (ctx
->account_mem
)
3435 io_unaccount_mem(ctx
->user
, nr_pages
);
3438 got_pages
= nr_pages
;
3441 imu
->bvec
= kvmalloc_array(nr_pages
, sizeof(struct bio_vec
),
3445 if (ctx
->account_mem
)
3446 io_unaccount_mem(ctx
->user
, nr_pages
);
3451 down_read(¤t
->mm
->mmap_sem
);
3452 pret
= get_user_pages(ubuf
, nr_pages
,
3453 FOLL_WRITE
| FOLL_LONGTERM
,
3455 if (pret
== nr_pages
) {
3456 /* don't support file backed memory */
3457 for (j
= 0; j
< nr_pages
; j
++) {
3458 struct vm_area_struct
*vma
= vmas
[j
];
3461 !is_file_hugepages(vma
->vm_file
)) {
3467 ret
= pret
< 0 ? pret
: -EFAULT
;
3469 up_read(¤t
->mm
->mmap_sem
);
3472 * if we did partial map, or found file backed vmas,
3473 * release any pages we did get
3476 put_user_pages(pages
, pret
);
3477 if (ctx
->account_mem
)
3478 io_unaccount_mem(ctx
->user
, nr_pages
);
3483 off
= ubuf
& ~PAGE_MASK
;
3485 for (j
= 0; j
< nr_pages
; j
++) {
3488 vec_len
= min_t(size_t, size
, PAGE_SIZE
- off
);
3489 imu
->bvec
[j
].bv_page
= pages
[j
];
3490 imu
->bvec
[j
].bv_len
= vec_len
;
3491 imu
->bvec
[j
].bv_offset
= off
;
3495 /* store original address for later verification */
3497 imu
->len
= iov
.iov_len
;
3498 imu
->nr_bvecs
= nr_pages
;
3500 ctx
->nr_user_bufs
++;
3508 io_sqe_buffer_unregister(ctx
);
3512 static int io_eventfd_register(struct io_ring_ctx
*ctx
, void __user
*arg
)
3514 __s32 __user
*fds
= arg
;
3520 if (copy_from_user(&fd
, fds
, sizeof(*fds
)))
3523 ctx
->cq_ev_fd
= eventfd_ctx_fdget(fd
);
3524 if (IS_ERR(ctx
->cq_ev_fd
)) {
3525 int ret
= PTR_ERR(ctx
->cq_ev_fd
);
3526 ctx
->cq_ev_fd
= NULL
;
3533 static int io_eventfd_unregister(struct io_ring_ctx
*ctx
)
3535 if (ctx
->cq_ev_fd
) {
3536 eventfd_ctx_put(ctx
->cq_ev_fd
);
3537 ctx
->cq_ev_fd
= NULL
;
3544 static void io_ring_ctx_free(struct io_ring_ctx
*ctx
)
3546 io_finish_async(ctx
);
3548 mmdrop(ctx
->sqo_mm
);
3550 io_iopoll_reap_events(ctx
);
3551 io_sqe_buffer_unregister(ctx
);
3552 io_sqe_files_unregister(ctx
);
3553 io_eventfd_unregister(ctx
);
3555 #if defined(CONFIG_UNIX)
3556 if (ctx
->ring_sock
) {
3557 ctx
->ring_sock
->file
= NULL
; /* so that iput() is called */
3558 sock_release(ctx
->ring_sock
);
3562 io_mem_free(ctx
->rings
);
3563 io_mem_free(ctx
->sq_sqes
);
3565 percpu_ref_exit(&ctx
->refs
);
3566 if (ctx
->account_mem
)
3567 io_unaccount_mem(ctx
->user
,
3568 ring_pages(ctx
->sq_entries
, ctx
->cq_entries
));
3569 free_uid(ctx
->user
);
3573 static __poll_t
io_uring_poll(struct file
*file
, poll_table
*wait
)
3575 struct io_ring_ctx
*ctx
= file
->private_data
;
3578 poll_wait(file
, &ctx
->cq_wait
, wait
);
3580 * synchronizes with barrier from wq_has_sleeper call in
3584 if (READ_ONCE(ctx
->rings
->sq
.tail
) - ctx
->cached_sq_head
!=
3585 ctx
->rings
->sq_ring_entries
)
3586 mask
|= EPOLLOUT
| EPOLLWRNORM
;
3587 if (READ_ONCE(ctx
->rings
->cq
.head
) != ctx
->cached_cq_tail
)
3588 mask
|= EPOLLIN
| EPOLLRDNORM
;
3593 static int io_uring_fasync(int fd
, struct file
*file
, int on
)
3595 struct io_ring_ctx
*ctx
= file
->private_data
;
3597 return fasync_helper(fd
, file
, on
, &ctx
->cq_fasync
);
3600 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx
*ctx
)
3602 mutex_lock(&ctx
->uring_lock
);
3603 percpu_ref_kill(&ctx
->refs
);
3604 mutex_unlock(&ctx
->uring_lock
);
3606 io_kill_timeouts(ctx
);
3607 io_poll_remove_all(ctx
);
3608 io_iopoll_reap_events(ctx
);
3609 wait_for_completion(&ctx
->ctx_done
);
3610 io_ring_ctx_free(ctx
);
3613 static int io_uring_release(struct inode
*inode
, struct file
*file
)
3615 struct io_ring_ctx
*ctx
= file
->private_data
;
3617 file
->private_data
= NULL
;
3618 io_ring_ctx_wait_and_kill(ctx
);
3622 static int io_uring_mmap(struct file
*file
, struct vm_area_struct
*vma
)
3624 loff_t offset
= (loff_t
) vma
->vm_pgoff
<< PAGE_SHIFT
;
3625 unsigned long sz
= vma
->vm_end
- vma
->vm_start
;
3626 struct io_ring_ctx
*ctx
= file
->private_data
;
3632 case IORING_OFF_SQ_RING
:
3633 case IORING_OFF_CQ_RING
:
3636 case IORING_OFF_SQES
:
3643 page
= virt_to_head_page(ptr
);
3644 if (sz
> page_size(page
))
3647 pfn
= virt_to_phys(ptr
) >> PAGE_SHIFT
;
3648 return remap_pfn_range(vma
, vma
->vm_start
, pfn
, sz
, vma
->vm_page_prot
);
3651 SYSCALL_DEFINE6(io_uring_enter
, unsigned int, fd
, u32
, to_submit
,
3652 u32
, min_complete
, u32
, flags
, const sigset_t __user
*, sig
,
3655 struct io_ring_ctx
*ctx
;
3660 if (flags
& ~(IORING_ENTER_GETEVENTS
| IORING_ENTER_SQ_WAKEUP
))
3668 if (f
.file
->f_op
!= &io_uring_fops
)
3672 ctx
= f
.file
->private_data
;
3673 if (!percpu_ref_tryget(&ctx
->refs
))
3677 * For SQ polling, the thread will do all submissions and completions.
3678 * Just return the requested submit count, and wake the thread if
3682 if (ctx
->flags
& IORING_SETUP_SQPOLL
) {
3683 if (flags
& IORING_ENTER_SQ_WAKEUP
)
3684 wake_up(&ctx
->sqo_wait
);
3685 submitted
= to_submit
;
3686 } else if (to_submit
) {
3687 to_submit
= min(to_submit
, ctx
->sq_entries
);
3689 mutex_lock(&ctx
->uring_lock
);
3690 submitted
= io_ring_submit(ctx
, to_submit
);
3691 mutex_unlock(&ctx
->uring_lock
);
3693 if (flags
& IORING_ENTER_GETEVENTS
) {
3694 unsigned nr_events
= 0;
3696 min_complete
= min(min_complete
, ctx
->cq_entries
);
3698 if (ctx
->flags
& IORING_SETUP_IOPOLL
) {
3699 ret
= io_iopoll_check(ctx
, &nr_events
, min_complete
);
3701 ret
= io_cqring_wait(ctx
, min_complete
, sig
, sigsz
);
3705 percpu_ref_put(&ctx
->refs
);
3708 return submitted
? submitted
: ret
;
3711 static const struct file_operations io_uring_fops
= {
3712 .release
= io_uring_release
,
3713 .mmap
= io_uring_mmap
,
3714 .poll
= io_uring_poll
,
3715 .fasync
= io_uring_fasync
,
3718 static int io_allocate_scq_urings(struct io_ring_ctx
*ctx
,
3719 struct io_uring_params
*p
)
3721 struct io_rings
*rings
;
3722 size_t size
, sq_array_offset
;
3724 size
= rings_size(p
->sq_entries
, p
->cq_entries
, &sq_array_offset
);
3725 if (size
== SIZE_MAX
)
3728 rings
= io_mem_alloc(size
);
3733 ctx
->sq_array
= (u32
*)((char *)rings
+ sq_array_offset
);
3734 rings
->sq_ring_mask
= p
->sq_entries
- 1;
3735 rings
->cq_ring_mask
= p
->cq_entries
- 1;
3736 rings
->sq_ring_entries
= p
->sq_entries
;
3737 rings
->cq_ring_entries
= p
->cq_entries
;
3738 ctx
->sq_mask
= rings
->sq_ring_mask
;
3739 ctx
->cq_mask
= rings
->cq_ring_mask
;
3740 ctx
->sq_entries
= rings
->sq_ring_entries
;
3741 ctx
->cq_entries
= rings
->cq_ring_entries
;
3743 size
= array_size(sizeof(struct io_uring_sqe
), p
->sq_entries
);
3744 if (size
== SIZE_MAX
)
3747 ctx
->sq_sqes
= io_mem_alloc(size
);
3755 * Allocate an anonymous fd, this is what constitutes the application
3756 * visible backing of an io_uring instance. The application mmaps this
3757 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3758 * we have to tie this fd to a socket for file garbage collection purposes.
3760 static int io_uring_get_fd(struct io_ring_ctx
*ctx
)
3765 #if defined(CONFIG_UNIX)
3766 ret
= sock_create_kern(&init_net
, PF_UNIX
, SOCK_RAW
, IPPROTO_IP
,
3772 ret
= get_unused_fd_flags(O_RDWR
| O_CLOEXEC
);
3776 file
= anon_inode_getfile("[io_uring]", &io_uring_fops
, ctx
,
3777 O_RDWR
| O_CLOEXEC
);
3780 ret
= PTR_ERR(file
);
3784 #if defined(CONFIG_UNIX)
3785 ctx
->ring_sock
->file
= file
;
3786 ctx
->ring_sock
->sk
->sk_user_data
= ctx
;
3788 fd_install(ret
, file
);
3791 #if defined(CONFIG_UNIX)
3792 sock_release(ctx
->ring_sock
);
3793 ctx
->ring_sock
= NULL
;
3798 static int io_uring_create(unsigned entries
, struct io_uring_params
*p
)
3800 struct user_struct
*user
= NULL
;
3801 struct io_ring_ctx
*ctx
;
3805 if (!entries
|| entries
> IORING_MAX_ENTRIES
)
3809 * Use twice as many entries for the CQ ring. It's possible for the
3810 * application to drive a higher depth than the size of the SQ ring,
3811 * since the sqes are only used at submission time. This allows for
3812 * some flexibility in overcommitting a bit.
3814 p
->sq_entries
= roundup_pow_of_two(entries
);
3815 p
->cq_entries
= 2 * p
->sq_entries
;
3817 user
= get_uid(current_user());
3818 account_mem
= !capable(CAP_IPC_LOCK
);
3821 ret
= io_account_mem(user
,
3822 ring_pages(p
->sq_entries
, p
->cq_entries
));
3829 ctx
= io_ring_ctx_alloc(p
);
3832 io_unaccount_mem(user
, ring_pages(p
->sq_entries
,
3837 ctx
->compat
= in_compat_syscall();
3838 ctx
->account_mem
= account_mem
;
3841 ret
= io_allocate_scq_urings(ctx
, p
);
3845 ret
= io_sq_offload_start(ctx
, p
);
3849 memset(&p
->sq_off
, 0, sizeof(p
->sq_off
));
3850 p
->sq_off
.head
= offsetof(struct io_rings
, sq
.head
);
3851 p
->sq_off
.tail
= offsetof(struct io_rings
, sq
.tail
);
3852 p
->sq_off
.ring_mask
= offsetof(struct io_rings
, sq_ring_mask
);
3853 p
->sq_off
.ring_entries
= offsetof(struct io_rings
, sq_ring_entries
);
3854 p
->sq_off
.flags
= offsetof(struct io_rings
, sq_flags
);
3855 p
->sq_off
.dropped
= offsetof(struct io_rings
, sq_dropped
);
3856 p
->sq_off
.array
= (char *)ctx
->sq_array
- (char *)ctx
->rings
;
3858 memset(&p
->cq_off
, 0, sizeof(p
->cq_off
));
3859 p
->cq_off
.head
= offsetof(struct io_rings
, cq
.head
);
3860 p
->cq_off
.tail
= offsetof(struct io_rings
, cq
.tail
);
3861 p
->cq_off
.ring_mask
= offsetof(struct io_rings
, cq_ring_mask
);
3862 p
->cq_off
.ring_entries
= offsetof(struct io_rings
, cq_ring_entries
);
3863 p
->cq_off
.overflow
= offsetof(struct io_rings
, cq_overflow
);
3864 p
->cq_off
.cqes
= offsetof(struct io_rings
, cqes
);
3867 * Install ring fd as the very last thing, so we don't risk someone
3868 * having closed it before we finish setup
3870 ret
= io_uring_get_fd(ctx
);
3874 p
->features
= IORING_FEAT_SINGLE_MMAP
;
3877 io_ring_ctx_wait_and_kill(ctx
);
3882 * Sets up an aio uring context, and returns the fd. Applications asks for a
3883 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3884 * params structure passed in.
3886 static long io_uring_setup(u32 entries
, struct io_uring_params __user
*params
)
3888 struct io_uring_params p
;
3892 if (copy_from_user(&p
, params
, sizeof(p
)))
3894 for (i
= 0; i
< ARRAY_SIZE(p
.resv
); i
++) {
3899 if (p
.flags
& ~(IORING_SETUP_IOPOLL
| IORING_SETUP_SQPOLL
|
3900 IORING_SETUP_SQ_AFF
))
3903 ret
= io_uring_create(entries
, &p
);
3907 if (copy_to_user(params
, &p
, sizeof(p
)))
3913 SYSCALL_DEFINE2(io_uring_setup
, u32
, entries
,
3914 struct io_uring_params __user
*, params
)
3916 return io_uring_setup(entries
, params
);
3919 static int __io_uring_register(struct io_ring_ctx
*ctx
, unsigned opcode
,
3920 void __user
*arg
, unsigned nr_args
)
3921 __releases(ctx
->uring_lock
)
3922 __acquires(ctx
->uring_lock
)
3927 * We're inside the ring mutex, if the ref is already dying, then
3928 * someone else killed the ctx or is already going through
3929 * io_uring_register().
3931 if (percpu_ref_is_dying(&ctx
->refs
))
3934 percpu_ref_kill(&ctx
->refs
);
3937 * Drop uring mutex before waiting for references to exit. If another
3938 * thread is currently inside io_uring_enter() it might need to grab
3939 * the uring_lock to make progress. If we hold it here across the drain
3940 * wait, then we can deadlock. It's safe to drop the mutex here, since
3941 * no new references will come in after we've killed the percpu ref.
3943 mutex_unlock(&ctx
->uring_lock
);
3944 wait_for_completion(&ctx
->ctx_done
);
3945 mutex_lock(&ctx
->uring_lock
);
3948 case IORING_REGISTER_BUFFERS
:
3949 ret
= io_sqe_buffer_register(ctx
, arg
, nr_args
);
3951 case IORING_UNREGISTER_BUFFERS
:
3955 ret
= io_sqe_buffer_unregister(ctx
);
3957 case IORING_REGISTER_FILES
:
3958 ret
= io_sqe_files_register(ctx
, arg
, nr_args
);
3960 case IORING_UNREGISTER_FILES
:
3964 ret
= io_sqe_files_unregister(ctx
);
3966 case IORING_REGISTER_EVENTFD
:
3970 ret
= io_eventfd_register(ctx
, arg
);
3972 case IORING_UNREGISTER_EVENTFD
:
3976 ret
= io_eventfd_unregister(ctx
);
3983 /* bring the ctx back to life */
3984 reinit_completion(&ctx
->ctx_done
);
3985 percpu_ref_reinit(&ctx
->refs
);
3989 SYSCALL_DEFINE4(io_uring_register
, unsigned int, fd
, unsigned int, opcode
,
3990 void __user
*, arg
, unsigned int, nr_args
)
3992 struct io_ring_ctx
*ctx
;
4001 if (f
.file
->f_op
!= &io_uring_fops
)
4004 ctx
= f
.file
->private_data
;
4006 mutex_lock(&ctx
->uring_lock
);
4007 ret
= __io_uring_register(ctx
, opcode
, arg
, nr_args
);
4008 mutex_unlock(&ctx
->uring_lock
);
4014 static int __init
io_uring_init(void)
4016 req_cachep
= KMEM_CACHE(io_kiocb
, SLAB_HWCACHE_ALIGN
| SLAB_PANIC
);
4019 __initcall(io_uring_init
);