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 struct io_uring_sqe *sq_sqes;
202 struct list_head defer_list;
203 struct list_head timeout_list;
204 } ____cacheline_aligned_in_smp;
207 struct workqueue_struct *sqo_wq[2];
208 struct task_struct *sqo_thread; /* if using sq thread polling */
209 struct mm_struct *sqo_mm;
210 wait_queue_head_t sqo_wait;
211 struct completion sqo_thread_started;
214 unsigned cached_cq_tail;
217 struct wait_queue_head cq_wait;
218 struct fasync_struct *cq_fasync;
219 struct eventfd_ctx *cq_ev_fd;
220 atomic_t cq_timeouts;
221 } ____cacheline_aligned_in_smp;
223 struct io_rings *rings;
226 * If used, fixed file set. Writers must ensure that ->refs is dead,
227 * readers must ensure that ->refs is alive as long as the file* is
228 * used. Only updated through io_uring_register(2).
230 struct file **user_files;
231 unsigned nr_user_files;
233 /* if used, fixed mapped user buffers */
234 unsigned nr_user_bufs;
235 struct io_mapped_ubuf *user_bufs;
237 struct user_struct *user;
239 struct completion ctx_done;
242 struct mutex uring_lock;
243 wait_queue_head_t wait;
244 } ____cacheline_aligned_in_smp;
247 spinlock_t completion_lock;
248 bool poll_multi_file;
250 * ->poll_list is protected by the ctx->uring_lock for
251 * io_uring instances that don't use IORING_SETUP_SQPOLL.
252 * For SQPOLL, only the single threaded io_sq_thread() will
253 * manipulate the list, hence no extra locking is needed there.
255 struct list_head poll_list;
256 struct list_head cancel_list;
257 } ____cacheline_aligned_in_smp;
259 struct async_list pending_async[2];
261 #if defined(CONFIG_UNIX)
262 struct socket *ring_sock;
267 const struct io_uring_sqe *sqe;
268 unsigned short index;
272 bool needs_fixed_file;
276 * First field must be the file pointer in all the
277 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
279 struct io_poll_iocb {
281 struct wait_queue_head *head;
285 struct wait_queue_entry wait;
290 struct hrtimer timer;
294 * NOTE! Each of the iocb union members has the file pointer
295 * as the first entry in their struct definition. So you can
296 * access the file pointer through any of the sub-structs,
297 * or directly as just 'ki_filp' in this struct.
303 struct io_poll_iocb poll;
304 struct io_timeout timeout;
307 struct sqe_submit submit;
309 struct io_ring_ctx *ctx;
310 struct list_head list;
311 struct list_head link_list;
314 #define REQ_F_NOWAIT 1 /* must not punt to workers */
315 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
316 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
317 #define REQ_F_SEQ_PREV 8 /* sequential with previous */
318 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
319 #define REQ_F_IO_DRAINED 32 /* drain done */
320 #define REQ_F_LINK 64 /* linked sqes */
321 #define REQ_F_LINK_DONE 128 /* linked sqes done */
322 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
323 #define REQ_F_SHADOW_DRAIN 512 /* link-drain shadow req */
324 #define REQ_F_TIMEOUT 1024 /* timeout request */
329 struct work_struct work;
332 #define IO_PLUG_THRESHOLD 2
333 #define IO_IOPOLL_BATCH 8
335 struct io_submit_state {
336 struct blk_plug plug;
339 * io_kiocb alloc cache
341 void *reqs[IO_IOPOLL_BATCH];
342 unsigned int free_reqs;
343 unsigned int cur_req;
346 * File reference cache
350 unsigned int has_refs;
351 unsigned int used_refs;
352 unsigned int ios_left;
355 static void io_sq_wq_submit_work(struct work_struct *work);
356 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
358 static void __io_free_req(struct io_kiocb *req);
360 static struct kmem_cache *req_cachep;
362 static const struct file_operations io_uring_fops;
364 struct sock *io_uring_get_socket(struct file *file)
366 #if defined(CONFIG_UNIX)
367 if (file->f_op == &io_uring_fops) {
368 struct io_ring_ctx *ctx = file->private_data;
370 return ctx->ring_sock->sk;
375 EXPORT_SYMBOL(io_uring_get_socket);
377 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
379 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
381 complete(&ctx->ctx_done);
384 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
386 struct io_ring_ctx *ctx;
389 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
393 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
394 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
399 ctx->flags = p->flags;
400 init_waitqueue_head(&ctx->cq_wait);
401 init_completion(&ctx->ctx_done);
402 init_completion(&ctx->sqo_thread_started);
403 mutex_init(&ctx->uring_lock);
404 init_waitqueue_head(&ctx->wait);
405 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
406 spin_lock_init(&ctx->pending_async[i].lock);
407 INIT_LIST_HEAD(&ctx->pending_async[i].list);
408 atomic_set(&ctx->pending_async[i].cnt, 0);
410 spin_lock_init(&ctx->completion_lock);
411 INIT_LIST_HEAD(&ctx->poll_list);
412 INIT_LIST_HEAD(&ctx->cancel_list);
413 INIT_LIST_HEAD(&ctx->defer_list);
414 INIT_LIST_HEAD(&ctx->timeout_list);
418 static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
419 struct io_kiocb *req)
421 /* timeout requests always honor sequence */
422 if (!(req->flags & REQ_F_TIMEOUT) &&
423 (req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
426 return req->sequence != ctx->cached_cq_tail + ctx->rings->sq_dropped;
429 static struct io_kiocb *__io_get_deferred_req(struct io_ring_ctx *ctx,
430 struct list_head *list)
432 struct io_kiocb *req;
434 if (list_empty(list))
437 req = list_first_entry(list, struct io_kiocb, list);
438 if (!io_sequence_defer(ctx, req)) {
439 list_del_init(&req->list);
446 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
448 return __io_get_deferred_req(ctx, &ctx->defer_list);
451 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
453 return __io_get_deferred_req(ctx, &ctx->timeout_list);
456 static void __io_commit_cqring(struct io_ring_ctx *ctx)
458 struct io_rings *rings = ctx->rings;
460 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
461 /* order cqe stores with ring update */
462 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
464 if (wq_has_sleeper(&ctx->cq_wait)) {
465 wake_up_interruptible(&ctx->cq_wait);
466 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
471 static inline void io_queue_async_work(struct io_ring_ctx *ctx,
472 struct io_kiocb *req)
476 if (req->submit.sqe) {
477 switch (req->submit.sqe->opcode) {
478 case IORING_OP_WRITEV:
479 case IORING_OP_WRITE_FIXED:
480 rw = !(req->rw.ki_flags & IOCB_DIRECT);
485 queue_work(ctx->sqo_wq[rw], &req->work);
488 static void io_kill_timeout(struct io_kiocb *req)
492 ret = hrtimer_try_to_cancel(&req->timeout.timer);
494 atomic_inc(&req->ctx->cq_timeouts);
495 list_del(&req->list);
496 io_cqring_fill_event(req->ctx, req->user_data, 0);
501 static void io_kill_timeouts(struct io_ring_ctx *ctx)
503 struct io_kiocb *req, *tmp;
505 spin_lock_irq(&ctx->completion_lock);
506 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
507 io_kill_timeout(req);
508 spin_unlock_irq(&ctx->completion_lock);
511 static void io_commit_cqring(struct io_ring_ctx *ctx)
513 struct io_kiocb *req;
515 while ((req = io_get_timeout_req(ctx)) != NULL)
516 io_kill_timeout(req);
518 __io_commit_cqring(ctx);
520 while ((req = io_get_deferred_req(ctx)) != NULL) {
521 if (req->flags & REQ_F_SHADOW_DRAIN) {
522 /* Just for drain, free it. */
526 req->flags |= REQ_F_IO_DRAINED;
527 io_queue_async_work(ctx, req);
531 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
533 struct io_rings *rings = ctx->rings;
536 tail = ctx->cached_cq_tail;
538 * writes to the cq entry need to come after reading head; the
539 * control dependency is enough as we're using WRITE_ONCE to
542 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
545 ctx->cached_cq_tail++;
546 return &rings->cqes[tail & ctx->cq_mask];
549 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
552 struct io_uring_cqe *cqe;
555 * If we can't get a cq entry, userspace overflowed the
556 * submission (by quite a lot). Increment the overflow count in
559 cqe = io_get_cqring(ctx);
561 WRITE_ONCE(cqe->user_data, ki_user_data);
562 WRITE_ONCE(cqe->res, res);
563 WRITE_ONCE(cqe->flags, 0);
565 unsigned overflow = READ_ONCE(ctx->rings->cq_overflow);
567 WRITE_ONCE(ctx->rings->cq_overflow, overflow + 1);
571 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
573 if (waitqueue_active(&ctx->wait))
575 if (waitqueue_active(&ctx->sqo_wait))
576 wake_up(&ctx->sqo_wait);
578 eventfd_signal(ctx->cq_ev_fd, 1);
581 static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
586 spin_lock_irqsave(&ctx->completion_lock, flags);
587 io_cqring_fill_event(ctx, user_data, res);
588 io_commit_cqring(ctx);
589 spin_unlock_irqrestore(&ctx->completion_lock, flags);
591 io_cqring_ev_posted(ctx);
594 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
595 struct io_submit_state *state)
597 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
598 struct io_kiocb *req;
600 if (!percpu_ref_tryget(&ctx->refs))
604 req = kmem_cache_alloc(req_cachep, gfp);
607 } else if (!state->free_reqs) {
611 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
612 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
615 * Bulk alloc is all-or-nothing. If we fail to get a batch,
616 * retry single alloc to be on the safe side.
618 if (unlikely(ret <= 0)) {
619 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
624 state->free_reqs = ret - 1;
626 req = state->reqs[0];
628 req = state->reqs[state->cur_req];
636 /* one is dropped after submission, the other at completion */
637 refcount_set(&req->refs, 2);
641 percpu_ref_put(&ctx->refs);
645 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
648 kmem_cache_free_bulk(req_cachep, *nr, reqs);
649 percpu_ref_put_many(&ctx->refs, *nr);
654 static void __io_free_req(struct io_kiocb *req)
656 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
658 percpu_ref_put(&req->ctx->refs);
659 kmem_cache_free(req_cachep, req);
662 static void io_req_link_next(struct io_kiocb *req)
664 struct io_kiocb *nxt;
667 * The list should never be empty when we are called here. But could
668 * potentially happen if the chain is messed up, check to be on the
671 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
673 list_del(&nxt->list);
674 if (!list_empty(&req->link_list)) {
675 INIT_LIST_HEAD(&nxt->link_list);
676 list_splice(&req->link_list, &nxt->link_list);
677 nxt->flags |= REQ_F_LINK;
680 nxt->flags |= REQ_F_LINK_DONE;
681 INIT_WORK(&nxt->work, io_sq_wq_submit_work);
682 io_queue_async_work(req->ctx, nxt);
687 * Called if REQ_F_LINK is set, and we fail the head request
689 static void io_fail_links(struct io_kiocb *req)
691 struct io_kiocb *link;
693 while (!list_empty(&req->link_list)) {
694 link = list_first_entry(&req->link_list, struct io_kiocb, list);
695 list_del(&link->list);
697 io_cqring_add_event(req->ctx, link->user_data, -ECANCELED);
702 static void io_free_req(struct io_kiocb *req)
705 * If LINK is set, we have dependent requests in this chain. If we
706 * didn't fail this request, queue the first one up, moving any other
707 * dependencies to the next request. In case of failure, fail the rest
710 if (req->flags & REQ_F_LINK) {
711 if (req->flags & REQ_F_FAIL_LINK)
714 io_req_link_next(req);
720 static void io_put_req(struct io_kiocb *req)
722 if (refcount_dec_and_test(&req->refs))
726 static unsigned io_cqring_events(struct io_rings *rings)
728 /* See comment at the top of this file */
730 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
734 * Find and free completed poll iocbs
736 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
737 struct list_head *done)
739 void *reqs[IO_IOPOLL_BATCH];
740 struct io_kiocb *req;
744 while (!list_empty(done)) {
745 req = list_first_entry(done, struct io_kiocb, list);
746 list_del(&req->list);
748 io_cqring_fill_event(ctx, req->user_data, req->result);
751 if (refcount_dec_and_test(&req->refs)) {
752 /* If we're not using fixed files, we have to pair the
753 * completion part with the file put. Use regular
754 * completions for those, only batch free for fixed
755 * file and non-linked commands.
757 if ((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
759 reqs[to_free++] = req;
760 if (to_free == ARRAY_SIZE(reqs))
761 io_free_req_many(ctx, reqs, &to_free);
768 io_commit_cqring(ctx);
769 io_free_req_many(ctx, reqs, &to_free);
772 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
775 struct io_kiocb *req, *tmp;
781 * Only spin for completions if we don't have multiple devices hanging
782 * off our complete list, and we're under the requested amount.
784 spin = !ctx->poll_multi_file && *nr_events < min;
787 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
788 struct kiocb *kiocb = &req->rw;
791 * Move completed entries to our local list. If we find a
792 * request that requires polling, break out and complete
793 * the done list first, if we have entries there.
795 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
796 list_move_tail(&req->list, &done);
799 if (!list_empty(&done))
802 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
811 if (!list_empty(&done))
812 io_iopoll_complete(ctx, nr_events, &done);
818 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
819 * non-spinning poll check - we'll still enter the driver poll loop, but only
820 * as a non-spinning completion check.
822 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
825 while (!list_empty(&ctx->poll_list) && !need_resched()) {
828 ret = io_do_iopoll(ctx, nr_events, min);
831 if (!min || *nr_events >= min)
839 * We can't just wait for polled events to come to us, we have to actively
840 * find and complete them.
842 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
844 if (!(ctx->flags & IORING_SETUP_IOPOLL))
847 mutex_lock(&ctx->uring_lock);
848 while (!list_empty(&ctx->poll_list)) {
849 unsigned int nr_events = 0;
851 io_iopoll_getevents(ctx, &nr_events, 1);
854 * Ensure we allow local-to-the-cpu processing to take place,
855 * in this case we need to ensure that we reap all events.
859 mutex_unlock(&ctx->uring_lock);
862 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
868 * We disallow the app entering submit/complete with polling, but we
869 * still need to lock the ring to prevent racing with polled issue
870 * that got punted to a workqueue.
872 mutex_lock(&ctx->uring_lock);
879 * Don't enter poll loop if we already have events pending.
880 * If we do, we can potentially be spinning for commands that
881 * already triggered a CQE (eg in error).
883 if (io_cqring_events(ctx->rings))
887 * If a submit got punted to a workqueue, we can have the
888 * application entering polling for a command before it gets
889 * issued. That app will hold the uring_lock for the duration
890 * of the poll right here, so we need to take a breather every
891 * now and then to ensure that the issue has a chance to add
892 * the poll to the issued list. Otherwise we can spin here
893 * forever, while the workqueue is stuck trying to acquire the
896 if (!(++iters & 7)) {
897 mutex_unlock(&ctx->uring_lock);
898 mutex_lock(&ctx->uring_lock);
901 if (*nr_events < min)
902 tmin = min - *nr_events;
904 ret = io_iopoll_getevents(ctx, nr_events, tmin);
908 } while (min && !*nr_events && !need_resched());
910 mutex_unlock(&ctx->uring_lock);
914 static void kiocb_end_write(struct kiocb *kiocb)
916 if (kiocb->ki_flags & IOCB_WRITE) {
917 struct inode *inode = file_inode(kiocb->ki_filp);
920 * Tell lockdep we inherited freeze protection from submission
923 if (S_ISREG(inode->i_mode))
924 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
925 file_end_write(kiocb->ki_filp);
929 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
931 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
933 kiocb_end_write(kiocb);
935 if ((req->flags & REQ_F_LINK) && res != req->result)
936 req->flags |= REQ_F_FAIL_LINK;
937 io_cqring_add_event(req->ctx, req->user_data, res);
941 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
943 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
945 kiocb_end_write(kiocb);
947 if ((req->flags & REQ_F_LINK) && res != req->result)
948 req->flags |= REQ_F_FAIL_LINK;
951 req->flags |= REQ_F_IOPOLL_COMPLETED;
955 * After the iocb has been issued, it's safe to be found on the poll list.
956 * Adding the kiocb to the list AFTER submission ensures that we don't
957 * find it from a io_iopoll_getevents() thread before the issuer is done
958 * accessing the kiocb cookie.
960 static void io_iopoll_req_issued(struct io_kiocb *req)
962 struct io_ring_ctx *ctx = req->ctx;
965 * Track whether we have multiple files in our lists. This will impact
966 * how we do polling eventually, not spinning if we're on potentially
969 if (list_empty(&ctx->poll_list)) {
970 ctx->poll_multi_file = false;
971 } else if (!ctx->poll_multi_file) {
972 struct io_kiocb *list_req;
974 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
976 if (list_req->rw.ki_filp != req->rw.ki_filp)
977 ctx->poll_multi_file = true;
981 * For fast devices, IO may have already completed. If it has, add
982 * it to the front so we find it first.
984 if (req->flags & REQ_F_IOPOLL_COMPLETED)
985 list_add(&req->list, &ctx->poll_list);
987 list_add_tail(&req->list, &ctx->poll_list);
990 static void io_file_put(struct io_submit_state *state)
993 int diff = state->has_refs - state->used_refs;
996 fput_many(state->file, diff);
1002 * Get as many references to a file as we have IOs left in this submission,
1003 * assuming most submissions are for one file, or at least that each file
1004 * has more than one submission.
1006 static struct file *io_file_get(struct io_submit_state *state, int fd)
1012 if (state->fd == fd) {
1019 state->file = fget_many(fd, state->ios_left);
1024 state->has_refs = state->ios_left;
1025 state->used_refs = 1;
1031 * If we tracked the file through the SCM inflight mechanism, we could support
1032 * any file. For now, just ensure that anything potentially problematic is done
1035 static bool io_file_supports_async(struct file *file)
1037 umode_t mode = file_inode(file)->i_mode;
1039 if (S_ISBLK(mode) || S_ISCHR(mode))
1041 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1047 static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
1048 bool force_nonblock)
1050 const struct io_uring_sqe *sqe = s->sqe;
1051 struct io_ring_ctx *ctx = req->ctx;
1052 struct kiocb *kiocb = &req->rw;
1059 if (force_nonblock && !io_file_supports_async(req->file))
1060 force_nonblock = false;
1062 kiocb->ki_pos = READ_ONCE(sqe->off);
1063 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1064 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1066 ioprio = READ_ONCE(sqe->ioprio);
1068 ret = ioprio_check_cap(ioprio);
1072 kiocb->ki_ioprio = ioprio;
1074 kiocb->ki_ioprio = get_current_ioprio();
1076 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1080 /* don't allow async punt if RWF_NOWAIT was requested */
1081 if (kiocb->ki_flags & IOCB_NOWAIT)
1082 req->flags |= REQ_F_NOWAIT;
1085 kiocb->ki_flags |= IOCB_NOWAIT;
1087 if (ctx->flags & IORING_SETUP_IOPOLL) {
1088 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1089 !kiocb->ki_filp->f_op->iopoll)
1092 kiocb->ki_flags |= IOCB_HIPRI;
1093 kiocb->ki_complete = io_complete_rw_iopoll;
1095 if (kiocb->ki_flags & IOCB_HIPRI)
1097 kiocb->ki_complete = io_complete_rw;
1102 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1108 case -ERESTARTNOINTR:
1109 case -ERESTARTNOHAND:
1110 case -ERESTART_RESTARTBLOCK:
1112 * We can't just restart the syscall, since previously
1113 * submitted sqes may already be in progress. Just fail this
1119 kiocb->ki_complete(kiocb, ret, 0);
1123 static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
1124 const struct io_uring_sqe *sqe,
1125 struct iov_iter *iter)
1127 size_t len = READ_ONCE(sqe->len);
1128 struct io_mapped_ubuf *imu;
1129 unsigned index, buf_index;
1133 /* attempt to use fixed buffers without having provided iovecs */
1134 if (unlikely(!ctx->user_bufs))
1137 buf_index = READ_ONCE(sqe->buf_index);
1138 if (unlikely(buf_index >= ctx->nr_user_bufs))
1141 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1142 imu = &ctx->user_bufs[index];
1143 buf_addr = READ_ONCE(sqe->addr);
1146 if (buf_addr + len < buf_addr)
1148 /* not inside the mapped region */
1149 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1153 * May not be a start of buffer, set size appropriately
1154 * and advance us to the beginning.
1156 offset = buf_addr - imu->ubuf;
1157 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1161 * Don't use iov_iter_advance() here, as it's really slow for
1162 * using the latter parts of a big fixed buffer - it iterates
1163 * over each segment manually. We can cheat a bit here, because
1166 * 1) it's a BVEC iter, we set it up
1167 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1168 * first and last bvec
1170 * So just find our index, and adjust the iterator afterwards.
1171 * If the offset is within the first bvec (or the whole first
1172 * bvec, just use iov_iter_advance(). This makes it easier
1173 * since we can just skip the first segment, which may not
1174 * be PAGE_SIZE aligned.
1176 const struct bio_vec *bvec = imu->bvec;
1178 if (offset <= bvec->bv_len) {
1179 iov_iter_advance(iter, offset);
1181 unsigned long seg_skip;
1183 /* skip first vec */
1184 offset -= bvec->bv_len;
1185 seg_skip = 1 + (offset >> PAGE_SHIFT);
1187 iter->bvec = bvec + seg_skip;
1188 iter->nr_segs -= seg_skip;
1189 iter->count -= bvec->bv_len + offset;
1190 iter->iov_offset = offset & ~PAGE_MASK;
1197 static ssize_t io_import_iovec(struct io_ring_ctx *ctx, int rw,
1198 const struct sqe_submit *s, struct iovec **iovec,
1199 struct iov_iter *iter)
1201 const struct io_uring_sqe *sqe = s->sqe;
1202 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1203 size_t sqe_len = READ_ONCE(sqe->len);
1207 * We're reading ->opcode for the second time, but the first read
1208 * doesn't care whether it's _FIXED or not, so it doesn't matter
1209 * whether ->opcode changes concurrently. The first read does care
1210 * about whether it is a READ or a WRITE, so we don't trust this read
1211 * for that purpose and instead let the caller pass in the read/write
1214 opcode = READ_ONCE(sqe->opcode);
1215 if (opcode == IORING_OP_READ_FIXED ||
1216 opcode == IORING_OP_WRITE_FIXED) {
1217 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
1225 #ifdef CONFIG_COMPAT
1227 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1231 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1234 static inline bool io_should_merge(struct async_list *al, struct kiocb *kiocb)
1236 if (al->file == kiocb->ki_filp) {
1240 * Allow merging if we're anywhere in the range of the same
1241 * page. Generally this happens for sub-page reads or writes,
1242 * and it's beneficial to allow the first worker to bring the
1243 * page in and the piggy backed work can then work on the
1246 start = al->io_start & PAGE_MASK;
1247 end = (al->io_start + al->io_len + PAGE_SIZE - 1) & PAGE_MASK;
1248 if (kiocb->ki_pos >= start && kiocb->ki_pos <= end)
1257 * Make a note of the last file/offset/direction we punted to async
1258 * context. We'll use this information to see if we can piggy back a
1259 * sequential request onto the previous one, if it's still hasn't been
1260 * completed by the async worker.
1262 static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
1264 struct async_list *async_list = &req->ctx->pending_async[rw];
1265 struct kiocb *kiocb = &req->rw;
1266 struct file *filp = kiocb->ki_filp;
1268 if (io_should_merge(async_list, kiocb)) {
1269 unsigned long max_bytes;
1271 /* Use 8x RA size as a decent limiter for both reads/writes */
1272 max_bytes = filp->f_ra.ra_pages << (PAGE_SHIFT + 3);
1274 max_bytes = VM_READAHEAD_PAGES << (PAGE_SHIFT + 3);
1276 /* If max len are exceeded, reset the state */
1277 if (async_list->io_len + len <= max_bytes) {
1278 req->flags |= REQ_F_SEQ_PREV;
1279 async_list->io_len += len;
1281 async_list->file = NULL;
1285 /* New file? Reset state. */
1286 if (async_list->file != filp) {
1287 async_list->io_start = kiocb->ki_pos;
1288 async_list->io_len = len;
1289 async_list->file = filp;
1294 * For files that don't have ->read_iter() and ->write_iter(), handle them
1295 * by looping over ->read() or ->write() manually.
1297 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1298 struct iov_iter *iter)
1303 * Don't support polled IO through this interface, and we can't
1304 * support non-blocking either. For the latter, this just causes
1305 * the kiocb to be handled from an async context.
1307 if (kiocb->ki_flags & IOCB_HIPRI)
1309 if (kiocb->ki_flags & IOCB_NOWAIT)
1312 while (iov_iter_count(iter)) {
1313 struct iovec iovec = iov_iter_iovec(iter);
1317 nr = file->f_op->read(file, iovec.iov_base,
1318 iovec.iov_len, &kiocb->ki_pos);
1320 nr = file->f_op->write(file, iovec.iov_base,
1321 iovec.iov_len, &kiocb->ki_pos);
1330 if (nr != iovec.iov_len)
1332 iov_iter_advance(iter, nr);
1338 static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
1339 bool force_nonblock)
1341 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1342 struct kiocb *kiocb = &req->rw;
1343 struct iov_iter iter;
1346 ssize_t read_size, ret;
1348 ret = io_prep_rw(req, s, force_nonblock);
1351 file = kiocb->ki_filp;
1353 if (unlikely(!(file->f_mode & FMODE_READ)))
1356 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
1361 if (req->flags & REQ_F_LINK)
1362 req->result = read_size;
1364 iov_count = iov_iter_count(&iter);
1365 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1369 if (file->f_op->read_iter)
1370 ret2 = call_read_iter(file, kiocb, &iter);
1372 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1375 * In case of a short read, punt to async. This can happen
1376 * if we have data partially cached. Alternatively we can
1377 * return the short read, in which case the application will
1378 * need to issue another SQE and wait for it. That SQE will
1379 * need async punt anyway, so it's more efficient to do it
1382 if (force_nonblock && ret2 > 0 && ret2 < read_size)
1384 /* Catch -EAGAIN return for forced non-blocking submission */
1385 if (!force_nonblock || ret2 != -EAGAIN) {
1386 io_rw_done(kiocb, ret2);
1389 * If ->needs_lock is true, we're already in async
1393 io_async_list_note(READ, req, iov_count);
1401 static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
1402 bool force_nonblock)
1404 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1405 struct kiocb *kiocb = &req->rw;
1406 struct iov_iter iter;
1411 ret = io_prep_rw(req, s, force_nonblock);
1415 file = kiocb->ki_filp;
1416 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1419 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
1423 if (req->flags & REQ_F_LINK)
1426 iov_count = iov_iter_count(&iter);
1429 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1430 /* If ->needs_lock is true, we're already in async context. */
1432 io_async_list_note(WRITE, req, iov_count);
1436 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1441 * Open-code file_start_write here to grab freeze protection,
1442 * which will be released by another thread in
1443 * io_complete_rw(). Fool lockdep by telling it the lock got
1444 * released so that it doesn't complain about the held lock when
1445 * we return to userspace.
1447 if (S_ISREG(file_inode(file)->i_mode)) {
1448 __sb_start_write(file_inode(file)->i_sb,
1449 SB_FREEZE_WRITE, true);
1450 __sb_writers_release(file_inode(file)->i_sb,
1453 kiocb->ki_flags |= IOCB_WRITE;
1455 if (file->f_op->write_iter)
1456 ret2 = call_write_iter(file, kiocb, &iter);
1458 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1459 if (!force_nonblock || ret2 != -EAGAIN) {
1460 io_rw_done(kiocb, ret2);
1463 * If ->needs_lock is true, we're already in async
1467 io_async_list_note(WRITE, req, iov_count);
1477 * IORING_OP_NOP just posts a completion event, nothing else.
1479 static int io_nop(struct io_kiocb *req, u64 user_data)
1481 struct io_ring_ctx *ctx = req->ctx;
1484 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1487 io_cqring_add_event(ctx, user_data, err);
1492 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1494 struct io_ring_ctx *ctx = req->ctx;
1499 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1501 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1507 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1508 bool force_nonblock)
1510 loff_t sqe_off = READ_ONCE(sqe->off);
1511 loff_t sqe_len = READ_ONCE(sqe->len);
1512 loff_t end = sqe_off + sqe_len;
1513 unsigned fsync_flags;
1516 fsync_flags = READ_ONCE(sqe->fsync_flags);
1517 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1520 ret = io_prep_fsync(req, sqe);
1524 /* fsync always requires a blocking context */
1528 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1529 end > 0 ? end : LLONG_MAX,
1530 fsync_flags & IORING_FSYNC_DATASYNC);
1532 if (ret < 0 && (req->flags & REQ_F_LINK))
1533 req->flags |= REQ_F_FAIL_LINK;
1534 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1539 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1541 struct io_ring_ctx *ctx = req->ctx;
1547 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1549 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1555 static int io_sync_file_range(struct io_kiocb *req,
1556 const struct io_uring_sqe *sqe,
1557 bool force_nonblock)
1564 ret = io_prep_sfr(req, sqe);
1568 /* sync_file_range always requires a blocking context */
1572 sqe_off = READ_ONCE(sqe->off);
1573 sqe_len = READ_ONCE(sqe->len);
1574 flags = READ_ONCE(sqe->sync_range_flags);
1576 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1578 if (ret < 0 && (req->flags & REQ_F_LINK))
1579 req->flags |= REQ_F_FAIL_LINK;
1580 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1585 #if defined(CONFIG_NET)
1586 static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1587 bool force_nonblock,
1588 long (*fn)(struct socket *, struct user_msghdr __user *,
1591 struct socket *sock;
1594 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1597 sock = sock_from_file(req->file, &ret);
1599 struct user_msghdr __user *msg;
1602 flags = READ_ONCE(sqe->msg_flags);
1603 if (flags & MSG_DONTWAIT)
1604 req->flags |= REQ_F_NOWAIT;
1605 else if (force_nonblock)
1606 flags |= MSG_DONTWAIT;
1608 msg = (struct user_msghdr __user *) (unsigned long)
1609 READ_ONCE(sqe->addr);
1611 ret = fn(sock, msg, flags);
1612 if (force_nonblock && ret == -EAGAIN)
1616 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1622 static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1623 bool force_nonblock)
1625 #if defined(CONFIG_NET)
1626 return io_send_recvmsg(req, sqe, force_nonblock, __sys_sendmsg_sock);
1632 static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1633 bool force_nonblock)
1635 #if defined(CONFIG_NET)
1636 return io_send_recvmsg(req, sqe, force_nonblock, __sys_recvmsg_sock);
1642 static void io_poll_remove_one(struct io_kiocb *req)
1644 struct io_poll_iocb *poll = &req->poll;
1646 spin_lock(&poll->head->lock);
1647 WRITE_ONCE(poll->canceled, true);
1648 if (!list_empty(&poll->wait.entry)) {
1649 list_del_init(&poll->wait.entry);
1650 io_queue_async_work(req->ctx, req);
1652 spin_unlock(&poll->head->lock);
1654 list_del_init(&req->list);
1657 static void io_poll_remove_all(struct io_ring_ctx *ctx)
1659 struct io_kiocb *req;
1661 spin_lock_irq(&ctx->completion_lock);
1662 while (!list_empty(&ctx->cancel_list)) {
1663 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1664 io_poll_remove_one(req);
1666 spin_unlock_irq(&ctx->completion_lock);
1670 * Find a running poll command that matches one specified in sqe->addr,
1671 * and remove it if found.
1673 static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1675 struct io_ring_ctx *ctx = req->ctx;
1676 struct io_kiocb *poll_req, *next;
1679 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1681 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1685 spin_lock_irq(&ctx->completion_lock);
1686 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1687 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1688 io_poll_remove_one(poll_req);
1693 spin_unlock_irq(&ctx->completion_lock);
1695 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1700 static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1703 req->poll.done = true;
1704 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask));
1705 io_commit_cqring(ctx);
1708 static void io_poll_complete_work(struct work_struct *work)
1710 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1711 struct io_poll_iocb *poll = &req->poll;
1712 struct poll_table_struct pt = { ._key = poll->events };
1713 struct io_ring_ctx *ctx = req->ctx;
1716 if (!READ_ONCE(poll->canceled))
1717 mask = vfs_poll(poll->file, &pt) & poll->events;
1720 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1721 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1722 * synchronize with them. In the cancellation case the list_del_init
1723 * itself is not actually needed, but harmless so we keep it in to
1724 * avoid further branches in the fast path.
1726 spin_lock_irq(&ctx->completion_lock);
1727 if (!mask && !READ_ONCE(poll->canceled)) {
1728 add_wait_queue(poll->head, &poll->wait);
1729 spin_unlock_irq(&ctx->completion_lock);
1732 list_del_init(&req->list);
1733 io_poll_complete(ctx, req, mask);
1734 spin_unlock_irq(&ctx->completion_lock);
1736 io_cqring_ev_posted(ctx);
1740 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1743 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1745 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1746 struct io_ring_ctx *ctx = req->ctx;
1747 __poll_t mask = key_to_poll(key);
1748 unsigned long flags;
1750 /* for instances that support it check for an event match first: */
1751 if (mask && !(mask & poll->events))
1754 list_del_init(&poll->wait.entry);
1756 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1757 list_del(&req->list);
1758 io_poll_complete(ctx, req, mask);
1759 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1761 io_cqring_ev_posted(ctx);
1764 io_queue_async_work(ctx, req);
1770 struct io_poll_table {
1771 struct poll_table_struct pt;
1772 struct io_kiocb *req;
1776 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1777 struct poll_table_struct *p)
1779 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1781 if (unlikely(pt->req->poll.head)) {
1782 pt->error = -EINVAL;
1787 pt->req->poll.head = head;
1788 add_wait_queue(head, &pt->req->poll.wait);
1791 static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1793 struct io_poll_iocb *poll = &req->poll;
1794 struct io_ring_ctx *ctx = req->ctx;
1795 struct io_poll_table ipt;
1796 bool cancel = false;
1800 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1802 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1807 req->submit.sqe = NULL;
1808 INIT_WORK(&req->work, io_poll_complete_work);
1809 events = READ_ONCE(sqe->poll_events);
1810 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1814 poll->canceled = false;
1816 ipt.pt._qproc = io_poll_queue_proc;
1817 ipt.pt._key = poll->events;
1819 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1821 /* initialized the list so that we can do list_empty checks */
1822 INIT_LIST_HEAD(&poll->wait.entry);
1823 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1825 INIT_LIST_HEAD(&req->list);
1827 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
1829 spin_lock_irq(&ctx->completion_lock);
1830 if (likely(poll->head)) {
1831 spin_lock(&poll->head->lock);
1832 if (unlikely(list_empty(&poll->wait.entry))) {
1838 if (mask || ipt.error)
1839 list_del_init(&poll->wait.entry);
1841 WRITE_ONCE(poll->canceled, true);
1842 else if (!poll->done) /* actually waiting for an event */
1843 list_add_tail(&req->list, &ctx->cancel_list);
1844 spin_unlock(&poll->head->lock);
1846 if (mask) { /* no async, we'd stolen it */
1848 io_poll_complete(ctx, req, mask);
1850 spin_unlock_irq(&ctx->completion_lock);
1853 io_cqring_ev_posted(ctx);
1859 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
1861 struct io_ring_ctx *ctx;
1862 struct io_kiocb *req;
1863 unsigned long flags;
1865 req = container_of(timer, struct io_kiocb, timeout.timer);
1867 atomic_inc(&ctx->cq_timeouts);
1869 spin_lock_irqsave(&ctx->completion_lock, flags);
1870 list_del(&req->list);
1872 io_cqring_fill_event(ctx, req->user_data, -ETIME);
1873 io_commit_cqring(ctx);
1874 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1876 io_cqring_ev_posted(ctx);
1879 return HRTIMER_NORESTART;
1882 static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1884 unsigned count, req_dist, tail_index;
1885 struct io_ring_ctx *ctx = req->ctx;
1886 struct list_head *entry;
1887 struct timespec64 ts;
1889 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1891 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->timeout_flags ||
1895 if (get_timespec64(&ts, u64_to_user_ptr(sqe->addr)))
1899 * sqe->off holds how many events that need to occur for this
1900 * timeout event to be satisfied.
1902 count = READ_ONCE(sqe->off);
1906 req->sequence = ctx->cached_sq_head + count - 1;
1907 req->flags |= REQ_F_TIMEOUT;
1910 * Insertion sort, ensuring the first entry in the list is always
1911 * the one we need first.
1913 tail_index = ctx->cached_cq_tail - ctx->rings->sq_dropped;
1914 req_dist = req->sequence - tail_index;
1915 spin_lock_irq(&ctx->completion_lock);
1916 list_for_each_prev(entry, &ctx->timeout_list) {
1917 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
1920 dist = nxt->sequence - tail_index;
1921 if (req_dist >= dist)
1924 list_add(&req->list, entry);
1925 spin_unlock_irq(&ctx->completion_lock);
1927 hrtimer_init(&req->timeout.timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1928 req->timeout.timer.function = io_timeout_fn;
1929 hrtimer_start(&req->timeout.timer, timespec64_to_ktime(ts),
1934 static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
1935 const struct io_uring_sqe *sqe)
1937 struct io_uring_sqe *sqe_copy;
1939 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
1942 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1946 spin_lock_irq(&ctx->completion_lock);
1947 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
1948 spin_unlock_irq(&ctx->completion_lock);
1953 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
1954 req->submit.sqe = sqe_copy;
1956 INIT_WORK(&req->work, io_sq_wq_submit_work);
1957 list_add_tail(&req->list, &ctx->defer_list);
1958 spin_unlock_irq(&ctx->completion_lock);
1959 return -EIOCBQUEUED;
1962 static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
1963 const struct sqe_submit *s, bool force_nonblock)
1967 req->user_data = READ_ONCE(s->sqe->user_data);
1969 if (unlikely(s->index >= ctx->sq_entries))
1972 opcode = READ_ONCE(s->sqe->opcode);
1975 ret = io_nop(req, req->user_data);
1977 case IORING_OP_READV:
1978 if (unlikely(s->sqe->buf_index))
1980 ret = io_read(req, s, force_nonblock);
1982 case IORING_OP_WRITEV:
1983 if (unlikely(s->sqe->buf_index))
1985 ret = io_write(req, s, force_nonblock);
1987 case IORING_OP_READ_FIXED:
1988 ret = io_read(req, s, force_nonblock);
1990 case IORING_OP_WRITE_FIXED:
1991 ret = io_write(req, s, force_nonblock);
1993 case IORING_OP_FSYNC:
1994 ret = io_fsync(req, s->sqe, force_nonblock);
1996 case IORING_OP_POLL_ADD:
1997 ret = io_poll_add(req, s->sqe);
1999 case IORING_OP_POLL_REMOVE:
2000 ret = io_poll_remove(req, s->sqe);
2002 case IORING_OP_SYNC_FILE_RANGE:
2003 ret = io_sync_file_range(req, s->sqe, force_nonblock);
2005 case IORING_OP_SENDMSG:
2006 ret = io_sendmsg(req, s->sqe, force_nonblock);
2008 case IORING_OP_RECVMSG:
2009 ret = io_recvmsg(req, s->sqe, force_nonblock);
2011 case IORING_OP_TIMEOUT:
2012 ret = io_timeout(req, s->sqe);
2022 if (ctx->flags & IORING_SETUP_IOPOLL) {
2023 if (req->result == -EAGAIN)
2026 /* workqueue context doesn't hold uring_lock, grab it now */
2028 mutex_lock(&ctx->uring_lock);
2029 io_iopoll_req_issued(req);
2031 mutex_unlock(&ctx->uring_lock);
2037 static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
2038 const struct io_uring_sqe *sqe)
2040 switch (sqe->opcode) {
2041 case IORING_OP_READV:
2042 case IORING_OP_READ_FIXED:
2043 return &ctx->pending_async[READ];
2044 case IORING_OP_WRITEV:
2045 case IORING_OP_WRITE_FIXED:
2046 return &ctx->pending_async[WRITE];
2052 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
2054 u8 opcode = READ_ONCE(sqe->opcode);
2056 return !(opcode == IORING_OP_READ_FIXED ||
2057 opcode == IORING_OP_WRITE_FIXED);
2060 static void io_sq_wq_submit_work(struct work_struct *work)
2062 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2063 struct io_ring_ctx *ctx = req->ctx;
2064 struct mm_struct *cur_mm = NULL;
2065 struct async_list *async_list;
2066 LIST_HEAD(req_list);
2067 mm_segment_t old_fs;
2070 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
2073 struct sqe_submit *s = &req->submit;
2074 const struct io_uring_sqe *sqe = s->sqe;
2075 unsigned int flags = req->flags;
2077 /* Ensure we clear previously set non-block flag */
2078 req->rw.ki_flags &= ~IOCB_NOWAIT;
2081 if (io_sqe_needs_user(sqe) && !cur_mm) {
2082 if (!mmget_not_zero(ctx->sqo_mm)) {
2085 cur_mm = ctx->sqo_mm;
2093 s->has_user = cur_mm != NULL;
2094 s->needs_lock = true;
2096 ret = __io_submit_sqe(ctx, req, s, false);
2098 * We can get EAGAIN for polled IO even though
2099 * we're forcing a sync submission from here,
2100 * since we can't wait for request slots on the
2109 /* drop submission reference */
2113 io_cqring_add_event(ctx, sqe->user_data, ret);
2117 /* async context always use a copy of the sqe */
2120 /* req from defer and link list needn't decrease async cnt */
2121 if (flags & (REQ_F_IO_DRAINED | REQ_F_LINK_DONE))
2126 if (!list_empty(&req_list)) {
2127 req = list_first_entry(&req_list, struct io_kiocb,
2129 list_del(&req->list);
2132 if (list_empty(&async_list->list))
2136 spin_lock(&async_list->lock);
2137 if (list_empty(&async_list->list)) {
2138 spin_unlock(&async_list->lock);
2141 list_splice_init(&async_list->list, &req_list);
2142 spin_unlock(&async_list->lock);
2144 req = list_first_entry(&req_list, struct io_kiocb, list);
2145 list_del(&req->list);
2149 * Rare case of racing with a submitter. If we find the count has
2150 * dropped to zero AND we have pending work items, then restart
2151 * the processing. This is a tiny race window.
2154 ret = atomic_dec_return(&async_list->cnt);
2155 while (!ret && !list_empty(&async_list->list)) {
2156 spin_lock(&async_list->lock);
2157 atomic_inc(&async_list->cnt);
2158 list_splice_init(&async_list->list, &req_list);
2159 spin_unlock(&async_list->lock);
2161 if (!list_empty(&req_list)) {
2162 req = list_first_entry(&req_list,
2163 struct io_kiocb, list);
2164 list_del(&req->list);
2167 ret = atomic_dec_return(&async_list->cnt);
2180 * See if we can piggy back onto previously submitted work, that is still
2181 * running. We currently only allow this if the new request is sequential
2182 * to the previous one we punted.
2184 static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
2190 if (!(req->flags & REQ_F_SEQ_PREV))
2192 if (!atomic_read(&list->cnt))
2196 spin_lock(&list->lock);
2197 list_add_tail(&req->list, &list->list);
2199 * Ensure we see a simultaneous modification from io_sq_wq_submit_work()
2202 if (!atomic_read(&list->cnt)) {
2203 list_del_init(&req->list);
2206 spin_unlock(&list->lock);
2210 static bool io_op_needs_file(const struct io_uring_sqe *sqe)
2212 int op = READ_ONCE(sqe->opcode);
2216 case IORING_OP_POLL_REMOVE:
2223 static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
2224 struct io_submit_state *state, struct io_kiocb *req)
2229 flags = READ_ONCE(s->sqe->flags);
2230 fd = READ_ONCE(s->sqe->fd);
2232 if (flags & IOSQE_IO_DRAIN)
2233 req->flags |= REQ_F_IO_DRAIN;
2235 * All io need record the previous position, if LINK vs DARIN,
2236 * it can be used to mark the position of the first IO in the
2239 req->sequence = s->sequence;
2241 if (!io_op_needs_file(s->sqe))
2244 if (flags & IOSQE_FIXED_FILE) {
2245 if (unlikely(!ctx->user_files ||
2246 (unsigned) fd >= ctx->nr_user_files))
2248 req->file = ctx->user_files[fd];
2249 req->flags |= REQ_F_FIXED_FILE;
2251 if (s->needs_fixed_file)
2253 req->file = io_file_get(state, fd);
2254 if (unlikely(!req->file))
2261 static int __io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2262 struct sqe_submit *s, bool force_nonblock)
2266 ret = __io_submit_sqe(ctx, req, s, force_nonblock);
2267 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
2268 struct io_uring_sqe *sqe_copy;
2270 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2272 struct async_list *list;
2275 memcpy(&req->submit, s, sizeof(*s));
2276 list = io_async_list_from_sqe(ctx, s->sqe);
2277 if (!io_add_to_prev_work(list, req)) {
2279 atomic_inc(&list->cnt);
2280 INIT_WORK(&req->work, io_sq_wq_submit_work);
2281 io_queue_async_work(ctx, req);
2285 * Queued up for async execution, worker will release
2286 * submit reference when the iocb is actually submitted.
2292 /* drop submission reference */
2295 /* and drop final reference, if we failed */
2297 io_cqring_add_event(ctx, req->user_data, ret);
2298 if (req->flags & REQ_F_LINK)
2299 req->flags |= REQ_F_FAIL_LINK;
2306 static int io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2307 struct sqe_submit *s, bool force_nonblock)
2311 ret = io_req_defer(ctx, req, s->sqe);
2313 if (ret != -EIOCBQUEUED) {
2315 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2320 return __io_queue_sqe(ctx, req, s, force_nonblock);
2323 static int io_queue_link_head(struct io_ring_ctx *ctx, struct io_kiocb *req,
2324 struct sqe_submit *s, struct io_kiocb *shadow,
2325 bool force_nonblock)
2328 int need_submit = false;
2331 return io_queue_sqe(ctx, req, s, force_nonblock);
2334 * Mark the first IO in link list as DRAIN, let all the following
2335 * IOs enter the defer list. all IO needs to be completed before link
2338 req->flags |= REQ_F_IO_DRAIN;
2339 ret = io_req_defer(ctx, req, s->sqe);
2341 if (ret != -EIOCBQUEUED) {
2343 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2348 * If ret == 0 means that all IOs in front of link io are
2349 * running done. let's queue link head.
2354 /* Insert shadow req to defer_list, blocking next IOs */
2355 spin_lock_irq(&ctx->completion_lock);
2356 list_add_tail(&shadow->list, &ctx->defer_list);
2357 spin_unlock_irq(&ctx->completion_lock);
2360 return __io_queue_sqe(ctx, req, s, force_nonblock);
2365 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2367 static void io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
2368 struct io_submit_state *state, struct io_kiocb **link,
2369 bool force_nonblock)
2371 struct io_uring_sqe *sqe_copy;
2372 struct io_kiocb *req;
2375 /* enforce forwards compatibility on users */
2376 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
2381 req = io_get_req(ctx, state);
2382 if (unlikely(!req)) {
2387 ret = io_req_set_file(ctx, s, state, req);
2388 if (unlikely(ret)) {
2392 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2397 * If we already have a head request, queue this one for async
2398 * submittal once the head completes. If we don't have a head but
2399 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2400 * submitted sync once the chain is complete. If none of those
2401 * conditions are true (normal request), then just queue it.
2404 struct io_kiocb *prev = *link;
2406 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2413 memcpy(&req->submit, s, sizeof(*s));
2414 list_add_tail(&req->list, &prev->link_list);
2415 } else if (s->sqe->flags & IOSQE_IO_LINK) {
2416 req->flags |= REQ_F_LINK;
2418 memcpy(&req->submit, s, sizeof(*s));
2419 INIT_LIST_HEAD(&req->link_list);
2422 io_queue_sqe(ctx, req, s, force_nonblock);
2427 * Batched submission is done, ensure local IO is flushed out.
2429 static void io_submit_state_end(struct io_submit_state *state)
2431 blk_finish_plug(&state->plug);
2433 if (state->free_reqs)
2434 kmem_cache_free_bulk(req_cachep, state->free_reqs,
2435 &state->reqs[state->cur_req]);
2439 * Start submission side cache.
2441 static void io_submit_state_start(struct io_submit_state *state,
2442 struct io_ring_ctx *ctx, unsigned max_ios)
2444 blk_start_plug(&state->plug);
2445 state->free_reqs = 0;
2447 state->ios_left = max_ios;
2450 static void io_commit_sqring(struct io_ring_ctx *ctx)
2452 struct io_rings *rings = ctx->rings;
2454 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
2456 * Ensure any loads from the SQEs are done at this point,
2457 * since once we write the new head, the application could
2458 * write new data to them.
2460 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2465 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2466 * that is mapped by userspace. This means that care needs to be taken to
2467 * ensure that reads are stable, as we cannot rely on userspace always
2468 * being a good citizen. If members of the sqe are validated and then later
2469 * used, it's important that those reads are done through READ_ONCE() to
2470 * prevent a re-load down the line.
2472 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
2474 struct io_rings *rings = ctx->rings;
2475 u32 *sq_array = ctx->sq_array;
2479 * The cached sq head (or cq tail) serves two purposes:
2481 * 1) allows us to batch the cost of updating the user visible
2483 * 2) allows the kernel side to track the head on its own, even
2484 * though the application is the one updating it.
2486 head = ctx->cached_sq_head;
2487 /* make sure SQ entry isn't read before tail */
2488 if (head == smp_load_acquire(&rings->sq.tail))
2491 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
2492 if (head < ctx->sq_entries) {
2494 s->sqe = &ctx->sq_sqes[head];
2495 s->sequence = ctx->cached_sq_head;
2496 ctx->cached_sq_head++;
2500 /* drop invalid entries */
2501 ctx->cached_sq_head++;
2502 rings->sq_dropped++;
2506 static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
2507 unsigned int nr, bool has_user, bool mm_fault)
2509 struct io_submit_state state, *statep = NULL;
2510 struct io_kiocb *link = NULL;
2511 struct io_kiocb *shadow_req = NULL;
2512 bool prev_was_link = false;
2513 int i, submitted = 0;
2515 if (nr > IO_PLUG_THRESHOLD) {
2516 io_submit_state_start(&state, ctx, nr);
2520 for (i = 0; i < nr; i++) {
2522 * If previous wasn't linked and we have a linked command,
2523 * that's the end of the chain. Submit the previous link.
2525 if (!prev_was_link && link) {
2526 io_queue_link_head(ctx, link, &link->submit, shadow_req,
2531 prev_was_link = (sqes[i].sqe->flags & IOSQE_IO_LINK) != 0;
2533 if (link && (sqes[i].sqe->flags & IOSQE_IO_DRAIN)) {
2535 shadow_req = io_get_req(ctx, NULL);
2536 if (unlikely(!shadow_req))
2538 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2539 refcount_dec(&shadow_req->refs);
2541 shadow_req->sequence = sqes[i].sequence;
2545 if (unlikely(mm_fault)) {
2546 io_cqring_add_event(ctx, sqes[i].sqe->user_data,
2549 sqes[i].has_user = has_user;
2550 sqes[i].needs_lock = true;
2551 sqes[i].needs_fixed_file = true;
2552 io_submit_sqe(ctx, &sqes[i], statep, &link, true);
2558 io_queue_link_head(ctx, link, &link->submit, shadow_req, true);
2560 io_submit_state_end(&state);
2565 static int io_sq_thread(void *data)
2567 struct sqe_submit sqes[IO_IOPOLL_BATCH];
2568 struct io_ring_ctx *ctx = data;
2569 struct mm_struct *cur_mm = NULL;
2570 mm_segment_t old_fs;
2573 unsigned long timeout;
2575 complete(&ctx->sqo_thread_started);
2580 timeout = inflight = 0;
2581 while (!kthread_should_park()) {
2582 bool all_fixed, mm_fault = false;
2586 unsigned nr_events = 0;
2588 if (ctx->flags & IORING_SETUP_IOPOLL) {
2589 io_iopoll_check(ctx, &nr_events, 0);
2592 * Normal IO, just pretend everything completed.
2593 * We don't have to poll completions for that.
2595 nr_events = inflight;
2598 inflight -= nr_events;
2600 timeout = jiffies + ctx->sq_thread_idle;
2603 if (!io_get_sqring(ctx, &sqes[0])) {
2605 * We're polling. If we're within the defined idle
2606 * period, then let us spin without work before going
2609 if (inflight || !time_after(jiffies, timeout)) {
2615 * Drop cur_mm before scheduling, we can't hold it for
2616 * long periods (or over schedule()). Do this before
2617 * adding ourselves to the waitqueue, as the unuse/drop
2626 prepare_to_wait(&ctx->sqo_wait, &wait,
2627 TASK_INTERRUPTIBLE);
2629 /* Tell userspace we may need a wakeup call */
2630 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
2631 /* make sure to read SQ tail after writing flags */
2634 if (!io_get_sqring(ctx, &sqes[0])) {
2635 if (kthread_should_park()) {
2636 finish_wait(&ctx->sqo_wait, &wait);
2639 if (signal_pending(current))
2640 flush_signals(current);
2642 finish_wait(&ctx->sqo_wait, &wait);
2644 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2647 finish_wait(&ctx->sqo_wait, &wait);
2649 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2655 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
2659 if (i == ARRAY_SIZE(sqes))
2661 } while (io_get_sqring(ctx, &sqes[i]));
2663 /* Unless all new commands are FIXED regions, grab mm */
2664 if (!all_fixed && !cur_mm) {
2665 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2667 use_mm(ctx->sqo_mm);
2668 cur_mm = ctx->sqo_mm;
2672 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
2675 /* Commit SQ ring head once we've consumed all SQEs */
2676 io_commit_sqring(ctx);
2690 static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit,
2691 bool block_for_last)
2693 struct io_submit_state state, *statep = NULL;
2694 struct io_kiocb *link = NULL;
2695 struct io_kiocb *shadow_req = NULL;
2696 bool prev_was_link = false;
2699 if (to_submit > IO_PLUG_THRESHOLD) {
2700 io_submit_state_start(&state, ctx, to_submit);
2704 for (i = 0; i < to_submit; i++) {
2705 bool force_nonblock = true;
2706 struct sqe_submit s;
2708 if (!io_get_sqring(ctx, &s))
2712 * If previous wasn't linked and we have a linked command,
2713 * that's the end of the chain. Submit the previous link.
2715 if (!prev_was_link && link) {
2716 io_queue_link_head(ctx, link, &link->submit, shadow_req,
2721 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2723 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
2725 shadow_req = io_get_req(ctx, NULL);
2726 if (unlikely(!shadow_req))
2728 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2729 refcount_dec(&shadow_req->refs);
2731 shadow_req->sequence = s.sequence;
2736 s.needs_lock = false;
2737 s.needs_fixed_file = false;
2741 * The caller will block for events after submit, submit the
2742 * last IO non-blocking. This is either the only IO it's
2743 * submitting, or it already submitted the previous ones. This
2744 * improves performance by avoiding an async punt that we don't
2747 if (block_for_last && submit == to_submit)
2748 force_nonblock = false;
2750 io_submit_sqe(ctx, &s, statep, &link, force_nonblock);
2752 io_commit_sqring(ctx);
2755 io_queue_link_head(ctx, link, &link->submit, shadow_req,
2758 io_submit_state_end(statep);
2763 struct io_wait_queue {
2764 struct wait_queue_entry wq;
2765 struct io_ring_ctx *ctx;
2767 unsigned nr_timeouts;
2770 static inline bool io_should_wake(struct io_wait_queue *iowq)
2772 struct io_ring_ctx *ctx = iowq->ctx;
2775 * Wake up if we have enough events, or if a timeout occured since we
2776 * started waiting. For timeouts, we always want to return to userspace,
2777 * regardless of event count.
2779 return io_cqring_events(ctx->rings) >= iowq->to_wait ||
2780 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2783 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2784 int wake_flags, void *key)
2786 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
2789 if (!io_should_wake(iowq))
2792 return autoremove_wake_function(curr, mode, wake_flags, key);
2796 * Wait until events become available, if we don't already have some. The
2797 * application must reap them itself, as they reside on the shared cq ring.
2799 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2800 const sigset_t __user *sig, size_t sigsz)
2802 struct io_wait_queue iowq = {
2805 .func = io_wake_function,
2806 .entry = LIST_HEAD_INIT(iowq.wq.entry),
2809 .to_wait = min_events,
2811 struct io_rings *rings = ctx->rings;
2814 if (io_cqring_events(rings) >= min_events)
2818 #ifdef CONFIG_COMPAT
2819 if (in_compat_syscall())
2820 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2824 ret = set_user_sigmask(sig, sigsz);
2831 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2833 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
2834 TASK_INTERRUPTIBLE);
2835 if (io_should_wake(&iowq))
2838 if (signal_pending(current)) {
2843 finish_wait(&ctx->wait, &iowq.wq);
2845 restore_saved_sigmask_unless(ret == -ERESTARTSYS);
2846 if (ret == -ERESTARTSYS)
2849 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2852 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
2854 #if defined(CONFIG_UNIX)
2855 if (ctx->ring_sock) {
2856 struct sock *sock = ctx->ring_sock->sk;
2857 struct sk_buff *skb;
2859 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
2865 for (i = 0; i < ctx->nr_user_files; i++)
2866 fput(ctx->user_files[i]);
2870 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
2872 if (!ctx->user_files)
2875 __io_sqe_files_unregister(ctx);
2876 kfree(ctx->user_files);
2877 ctx->user_files = NULL;
2878 ctx->nr_user_files = 0;
2882 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
2884 if (ctx->sqo_thread) {
2885 wait_for_completion(&ctx->sqo_thread_started);
2887 * The park is a bit of a work-around, without it we get
2888 * warning spews on shutdown with SQPOLL set and affinity
2889 * set to a single CPU.
2891 kthread_park(ctx->sqo_thread);
2892 kthread_stop(ctx->sqo_thread);
2893 ctx->sqo_thread = NULL;
2897 static void io_finish_async(struct io_ring_ctx *ctx)
2901 io_sq_thread_stop(ctx);
2903 for (i = 0; i < ARRAY_SIZE(ctx->sqo_wq); i++) {
2904 if (ctx->sqo_wq[i]) {
2905 destroy_workqueue(ctx->sqo_wq[i]);
2906 ctx->sqo_wq[i] = NULL;
2911 #if defined(CONFIG_UNIX)
2912 static void io_destruct_skb(struct sk_buff *skb)
2914 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
2917 for (i = 0; i < ARRAY_SIZE(ctx->sqo_wq); i++)
2919 flush_workqueue(ctx->sqo_wq[i]);
2921 unix_destruct_scm(skb);
2925 * Ensure the UNIX gc is aware of our file set, so we are certain that
2926 * the io_uring can be safely unregistered on process exit, even if we have
2927 * loops in the file referencing.
2929 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
2931 struct sock *sk = ctx->ring_sock->sk;
2932 struct scm_fp_list *fpl;
2933 struct sk_buff *skb;
2936 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
2937 unsigned long inflight = ctx->user->unix_inflight + nr;
2939 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
2943 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
2947 skb = alloc_skb(0, GFP_KERNEL);
2954 skb->destructor = io_destruct_skb;
2956 fpl->user = get_uid(ctx->user);
2957 for (i = 0; i < nr; i++) {
2958 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
2959 unix_inflight(fpl->user, fpl->fp[i]);
2962 fpl->max = fpl->count = nr;
2963 UNIXCB(skb).fp = fpl;
2964 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2965 skb_queue_head(&sk->sk_receive_queue, skb);
2967 for (i = 0; i < nr; i++)
2974 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
2975 * causes regular reference counting to break down. We rely on the UNIX
2976 * garbage collection to take care of this problem for us.
2978 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2980 unsigned left, total;
2984 left = ctx->nr_user_files;
2986 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
2988 ret = __io_sqe_files_scm(ctx, this_files, total);
2992 total += this_files;
2998 while (total < ctx->nr_user_files) {
2999 fput(ctx->user_files[total]);
3006 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3012 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3015 __s32 __user *fds = (__s32 __user *) arg;
3019 if (ctx->user_files)
3023 if (nr_args > IORING_MAX_FIXED_FILES)
3026 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
3027 if (!ctx->user_files)
3030 for (i = 0; i < nr_args; i++) {
3032 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3035 ctx->user_files[i] = fget(fd);
3038 if (!ctx->user_files[i])
3041 * Don't allow io_uring instances to be registered. If UNIX
3042 * isn't enabled, then this causes a reference cycle and this
3043 * instance can never get freed. If UNIX is enabled we'll
3044 * handle it just fine, but there's still no point in allowing
3045 * a ring fd as it doesn't support regular read/write anyway.
3047 if (ctx->user_files[i]->f_op == &io_uring_fops) {
3048 fput(ctx->user_files[i]);
3051 ctx->nr_user_files++;
3056 for (i = 0; i < ctx->nr_user_files; i++)
3057 fput(ctx->user_files[i]);
3059 kfree(ctx->user_files);
3060 ctx->user_files = NULL;
3061 ctx->nr_user_files = 0;
3065 ret = io_sqe_files_scm(ctx);
3067 io_sqe_files_unregister(ctx);
3072 static int io_sq_offload_start(struct io_ring_ctx *ctx,
3073 struct io_uring_params *p)
3077 init_waitqueue_head(&ctx->sqo_wait);
3078 mmgrab(current->mm);
3079 ctx->sqo_mm = current->mm;
3081 if (ctx->flags & IORING_SETUP_SQPOLL) {
3083 if (!capable(CAP_SYS_ADMIN))
3086 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3087 if (!ctx->sq_thread_idle)
3088 ctx->sq_thread_idle = HZ;
3090 if (p->flags & IORING_SETUP_SQ_AFF) {
3091 int cpu = p->sq_thread_cpu;
3094 if (cpu >= nr_cpu_ids)
3096 if (!cpu_online(cpu))
3099 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3103 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3106 if (IS_ERR(ctx->sqo_thread)) {
3107 ret = PTR_ERR(ctx->sqo_thread);
3108 ctx->sqo_thread = NULL;
3111 wake_up_process(ctx->sqo_thread);
3112 } else if (p->flags & IORING_SETUP_SQ_AFF) {
3113 /* Can't have SQ_AFF without SQPOLL */
3118 /* Do QD, or 2 * CPUS, whatever is smallest */
3119 ctx->sqo_wq[0] = alloc_workqueue("io_ring-wq",
3120 WQ_UNBOUND | WQ_FREEZABLE,
3121 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
3122 if (!ctx->sqo_wq[0]) {
3128 * This is for buffered writes, where we want to limit the parallelism
3129 * due to file locking in file systems. As "normal" buffered writes
3130 * should parellelize on writeout quite nicely, limit us to having 2
3131 * pending. This avoids massive contention on the inode when doing
3132 * buffered async writes.
3134 ctx->sqo_wq[1] = alloc_workqueue("io_ring-write-wq",
3135 WQ_UNBOUND | WQ_FREEZABLE, 2);
3136 if (!ctx->sqo_wq[1]) {
3143 io_finish_async(ctx);
3144 mmdrop(ctx->sqo_mm);
3149 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
3151 atomic_long_sub(nr_pages, &user->locked_vm);
3154 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
3156 unsigned long page_limit, cur_pages, new_pages;
3158 /* Don't allow more pages than we can safely lock */
3159 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
3162 cur_pages = atomic_long_read(&user->locked_vm);
3163 new_pages = cur_pages + nr_pages;
3164 if (new_pages > page_limit)
3166 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
3167 new_pages) != cur_pages);
3172 static void io_mem_free(void *ptr)
3179 page = virt_to_head_page(ptr);
3180 if (put_page_testzero(page))
3181 free_compound_page(page);
3184 static void *io_mem_alloc(size_t size)
3186 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
3189 return (void *) __get_free_pages(gfp_flags, get_order(size));
3192 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
3195 struct io_rings *rings;
3196 size_t off, sq_array_size;
3198 off = struct_size(rings, cqes, cq_entries);
3199 if (off == SIZE_MAX)
3203 off = ALIGN(off, SMP_CACHE_BYTES);
3208 sq_array_size = array_size(sizeof(u32), sq_entries);
3209 if (sq_array_size == SIZE_MAX)
3212 if (check_add_overflow(off, sq_array_size, &off))
3221 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
3225 pages = (size_t)1 << get_order(
3226 rings_size(sq_entries, cq_entries, NULL));
3227 pages += (size_t)1 << get_order(
3228 array_size(sizeof(struct io_uring_sqe), sq_entries));
3233 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
3237 if (!ctx->user_bufs)
3240 for (i = 0; i < ctx->nr_user_bufs; i++) {
3241 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3243 for (j = 0; j < imu->nr_bvecs; j++)
3244 put_user_page(imu->bvec[j].bv_page);
3246 if (ctx->account_mem)
3247 io_unaccount_mem(ctx->user, imu->nr_bvecs);
3252 kfree(ctx->user_bufs);
3253 ctx->user_bufs = NULL;
3254 ctx->nr_user_bufs = 0;
3258 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
3259 void __user *arg, unsigned index)
3261 struct iovec __user *src;
3263 #ifdef CONFIG_COMPAT
3265 struct compat_iovec __user *ciovs;
3266 struct compat_iovec ciov;
3268 ciovs = (struct compat_iovec __user *) arg;
3269 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
3272 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
3273 dst->iov_len = ciov.iov_len;
3277 src = (struct iovec __user *) arg;
3278 if (copy_from_user(dst, &src[index], sizeof(*dst)))
3283 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
3286 struct vm_area_struct **vmas = NULL;
3287 struct page **pages = NULL;
3288 int i, j, got_pages = 0;
3293 if (!nr_args || nr_args > UIO_MAXIOV)
3296 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
3298 if (!ctx->user_bufs)
3301 for (i = 0; i < nr_args; i++) {
3302 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3303 unsigned long off, start, end, ubuf;
3308 ret = io_copy_iov(ctx, &iov, arg, i);
3313 * Don't impose further limits on the size and buffer
3314 * constraints here, we'll -EINVAL later when IO is
3315 * submitted if they are wrong.
3318 if (!iov.iov_base || !iov.iov_len)
3321 /* arbitrary limit, but we need something */
3322 if (iov.iov_len > SZ_1G)
3325 ubuf = (unsigned long) iov.iov_base;
3326 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
3327 start = ubuf >> PAGE_SHIFT;
3328 nr_pages = end - start;
3330 if (ctx->account_mem) {
3331 ret = io_account_mem(ctx->user, nr_pages);
3337 if (!pages || nr_pages > got_pages) {
3340 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
3342 vmas = kvmalloc_array(nr_pages,
3343 sizeof(struct vm_area_struct *),
3345 if (!pages || !vmas) {
3347 if (ctx->account_mem)
3348 io_unaccount_mem(ctx->user, nr_pages);
3351 got_pages = nr_pages;
3354 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
3358 if (ctx->account_mem)
3359 io_unaccount_mem(ctx->user, nr_pages);
3364 down_read(¤t->mm->mmap_sem);
3365 pret = get_user_pages(ubuf, nr_pages,
3366 FOLL_WRITE | FOLL_LONGTERM,
3368 if (pret == nr_pages) {
3369 /* don't support file backed memory */
3370 for (j = 0; j < nr_pages; j++) {
3371 struct vm_area_struct *vma = vmas[j];
3374 !is_file_hugepages(vma->vm_file)) {
3380 ret = pret < 0 ? pret : -EFAULT;
3382 up_read(¤t->mm->mmap_sem);
3385 * if we did partial map, or found file backed vmas,
3386 * release any pages we did get
3389 put_user_pages(pages, pret);
3390 if (ctx->account_mem)
3391 io_unaccount_mem(ctx->user, nr_pages);
3396 off = ubuf & ~PAGE_MASK;
3398 for (j = 0; j < nr_pages; j++) {
3401 vec_len = min_t(size_t, size, PAGE_SIZE - off);
3402 imu->bvec[j].bv_page = pages[j];
3403 imu->bvec[j].bv_len = vec_len;
3404 imu->bvec[j].bv_offset = off;
3408 /* store original address for later verification */
3410 imu->len = iov.iov_len;
3411 imu->nr_bvecs = nr_pages;
3413 ctx->nr_user_bufs++;
3421 io_sqe_buffer_unregister(ctx);
3425 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
3427 __s32 __user *fds = arg;
3433 if (copy_from_user(&fd, fds, sizeof(*fds)))
3436 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
3437 if (IS_ERR(ctx->cq_ev_fd)) {
3438 int ret = PTR_ERR(ctx->cq_ev_fd);
3439 ctx->cq_ev_fd = NULL;
3446 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
3448 if (ctx->cq_ev_fd) {
3449 eventfd_ctx_put(ctx->cq_ev_fd);
3450 ctx->cq_ev_fd = NULL;
3457 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
3459 io_finish_async(ctx);
3461 mmdrop(ctx->sqo_mm);
3463 io_iopoll_reap_events(ctx);
3464 io_sqe_buffer_unregister(ctx);
3465 io_sqe_files_unregister(ctx);
3466 io_eventfd_unregister(ctx);
3468 #if defined(CONFIG_UNIX)
3469 if (ctx->ring_sock) {
3470 ctx->ring_sock->file = NULL; /* so that iput() is called */
3471 sock_release(ctx->ring_sock);
3475 io_mem_free(ctx->rings);
3476 io_mem_free(ctx->sq_sqes);
3478 percpu_ref_exit(&ctx->refs);
3479 if (ctx->account_mem)
3480 io_unaccount_mem(ctx->user,
3481 ring_pages(ctx->sq_entries, ctx->cq_entries));
3482 free_uid(ctx->user);
3486 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3488 struct io_ring_ctx *ctx = file->private_data;
3491 poll_wait(file, &ctx->cq_wait, wait);
3493 * synchronizes with barrier from wq_has_sleeper call in
3497 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
3498 ctx->rings->sq_ring_entries)
3499 mask |= EPOLLOUT | EPOLLWRNORM;
3500 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
3501 mask |= EPOLLIN | EPOLLRDNORM;
3506 static int io_uring_fasync(int fd, struct file *file, int on)
3508 struct io_ring_ctx *ctx = file->private_data;
3510 return fasync_helper(fd, file, on, &ctx->cq_fasync);
3513 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3515 mutex_lock(&ctx->uring_lock);
3516 percpu_ref_kill(&ctx->refs);
3517 mutex_unlock(&ctx->uring_lock);
3519 io_kill_timeouts(ctx);
3520 io_poll_remove_all(ctx);
3521 io_iopoll_reap_events(ctx);
3522 wait_for_completion(&ctx->ctx_done);
3523 io_ring_ctx_free(ctx);
3526 static int io_uring_release(struct inode *inode, struct file *file)
3528 struct io_ring_ctx *ctx = file->private_data;
3530 file->private_data = NULL;
3531 io_ring_ctx_wait_and_kill(ctx);
3535 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3537 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
3538 unsigned long sz = vma->vm_end - vma->vm_start;
3539 struct io_ring_ctx *ctx = file->private_data;
3545 case IORING_OFF_SQ_RING:
3546 case IORING_OFF_CQ_RING:
3549 case IORING_OFF_SQES:
3556 page = virt_to_head_page(ptr);
3557 if (sz > page_size(page))
3560 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3561 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3564 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3565 u32, min_complete, u32, flags, const sigset_t __user *, sig,
3568 struct io_ring_ctx *ctx;
3573 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
3581 if (f.file->f_op != &io_uring_fops)
3585 ctx = f.file->private_data;
3586 if (!percpu_ref_tryget(&ctx->refs))
3590 * For SQ polling, the thread will do all submissions and completions.
3591 * Just return the requested submit count, and wake the thread if
3595 if (ctx->flags & IORING_SETUP_SQPOLL) {
3596 if (flags & IORING_ENTER_SQ_WAKEUP)
3597 wake_up(&ctx->sqo_wait);
3598 submitted = to_submit;
3599 } else if (to_submit) {
3600 bool block_for_last = false;
3602 to_submit = min(to_submit, ctx->sq_entries);
3605 * Allow last submission to block in a series, IFF the caller
3606 * asked to wait for events and we don't currently have
3607 * enough. This potentially avoids an async punt.
3609 if (to_submit == min_complete &&
3610 io_cqring_events(ctx->rings) < min_complete)
3611 block_for_last = true;
3613 mutex_lock(&ctx->uring_lock);
3614 submitted = io_ring_submit(ctx, to_submit, block_for_last);
3615 mutex_unlock(&ctx->uring_lock);
3617 if (flags & IORING_ENTER_GETEVENTS) {
3618 unsigned nr_events = 0;
3620 min_complete = min(min_complete, ctx->cq_entries);
3622 if (ctx->flags & IORING_SETUP_IOPOLL) {
3623 ret = io_iopoll_check(ctx, &nr_events, min_complete);
3625 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
3629 percpu_ref_put(&ctx->refs);
3632 return submitted ? submitted : ret;
3635 static const struct file_operations io_uring_fops = {
3636 .release = io_uring_release,
3637 .mmap = io_uring_mmap,
3638 .poll = io_uring_poll,
3639 .fasync = io_uring_fasync,
3642 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3643 struct io_uring_params *p)
3645 struct io_rings *rings;
3646 size_t size, sq_array_offset;
3648 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
3649 if (size == SIZE_MAX)
3652 rings = io_mem_alloc(size);
3657 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3658 rings->sq_ring_mask = p->sq_entries - 1;
3659 rings->cq_ring_mask = p->cq_entries - 1;
3660 rings->sq_ring_entries = p->sq_entries;
3661 rings->cq_ring_entries = p->cq_entries;
3662 ctx->sq_mask = rings->sq_ring_mask;
3663 ctx->cq_mask = rings->cq_ring_mask;
3664 ctx->sq_entries = rings->sq_ring_entries;
3665 ctx->cq_entries = rings->cq_ring_entries;
3667 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3668 if (size == SIZE_MAX)
3671 ctx->sq_sqes = io_mem_alloc(size);
3679 * Allocate an anonymous fd, this is what constitutes the application
3680 * visible backing of an io_uring instance. The application mmaps this
3681 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3682 * we have to tie this fd to a socket for file garbage collection purposes.
3684 static int io_uring_get_fd(struct io_ring_ctx *ctx)
3689 #if defined(CONFIG_UNIX)
3690 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3696 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3700 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
3701 O_RDWR | O_CLOEXEC);
3704 ret = PTR_ERR(file);
3708 #if defined(CONFIG_UNIX)
3709 ctx->ring_sock->file = file;
3710 ctx->ring_sock->sk->sk_user_data = ctx;
3712 fd_install(ret, file);
3715 #if defined(CONFIG_UNIX)
3716 sock_release(ctx->ring_sock);
3717 ctx->ring_sock = NULL;
3722 static int io_uring_create(unsigned entries, struct io_uring_params *p)
3724 struct user_struct *user = NULL;
3725 struct io_ring_ctx *ctx;
3729 if (!entries || entries > IORING_MAX_ENTRIES)
3733 * Use twice as many entries for the CQ ring. It's possible for the
3734 * application to drive a higher depth than the size of the SQ ring,
3735 * since the sqes are only used at submission time. This allows for
3736 * some flexibility in overcommitting a bit.
3738 p->sq_entries = roundup_pow_of_two(entries);
3739 p->cq_entries = 2 * p->sq_entries;
3741 user = get_uid(current_user());
3742 account_mem = !capable(CAP_IPC_LOCK);
3745 ret = io_account_mem(user,
3746 ring_pages(p->sq_entries, p->cq_entries));
3753 ctx = io_ring_ctx_alloc(p);
3756 io_unaccount_mem(user, ring_pages(p->sq_entries,
3761 ctx->compat = in_compat_syscall();
3762 ctx->account_mem = account_mem;
3765 ret = io_allocate_scq_urings(ctx, p);
3769 ret = io_sq_offload_start(ctx, p);
3773 ret = io_uring_get_fd(ctx);
3777 memset(&p->sq_off, 0, sizeof(p->sq_off));
3778 p->sq_off.head = offsetof(struct io_rings, sq.head);
3779 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3780 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3781 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3782 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3783 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3784 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3786 memset(&p->cq_off, 0, sizeof(p->cq_off));
3787 p->cq_off.head = offsetof(struct io_rings, cq.head);
3788 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3789 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3790 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3791 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3792 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3794 p->features = IORING_FEAT_SINGLE_MMAP;
3797 io_ring_ctx_wait_and_kill(ctx);
3802 * Sets up an aio uring context, and returns the fd. Applications asks for a
3803 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3804 * params structure passed in.
3806 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3808 struct io_uring_params p;
3812 if (copy_from_user(&p, params, sizeof(p)))
3814 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3819 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3820 IORING_SETUP_SQ_AFF))
3823 ret = io_uring_create(entries, &p);
3827 if (copy_to_user(params, &p, sizeof(p)))
3833 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3834 struct io_uring_params __user *, params)
3836 return io_uring_setup(entries, params);
3839 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3840 void __user *arg, unsigned nr_args)
3841 __releases(ctx->uring_lock)
3842 __acquires(ctx->uring_lock)
3847 * We're inside the ring mutex, if the ref is already dying, then
3848 * someone else killed the ctx or is already going through
3849 * io_uring_register().
3851 if (percpu_ref_is_dying(&ctx->refs))
3854 percpu_ref_kill(&ctx->refs);
3857 * Drop uring mutex before waiting for references to exit. If another
3858 * thread is currently inside io_uring_enter() it might need to grab
3859 * the uring_lock to make progress. If we hold it here across the drain
3860 * wait, then we can deadlock. It's safe to drop the mutex here, since
3861 * no new references will come in after we've killed the percpu ref.
3863 mutex_unlock(&ctx->uring_lock);
3864 wait_for_completion(&ctx->ctx_done);
3865 mutex_lock(&ctx->uring_lock);
3868 case IORING_REGISTER_BUFFERS:
3869 ret = io_sqe_buffer_register(ctx, arg, nr_args);
3871 case IORING_UNREGISTER_BUFFERS:
3875 ret = io_sqe_buffer_unregister(ctx);
3877 case IORING_REGISTER_FILES:
3878 ret = io_sqe_files_register(ctx, arg, nr_args);
3880 case IORING_UNREGISTER_FILES:
3884 ret = io_sqe_files_unregister(ctx);
3886 case IORING_REGISTER_EVENTFD:
3890 ret = io_eventfd_register(ctx, arg);
3892 case IORING_UNREGISTER_EVENTFD:
3896 ret = io_eventfd_unregister(ctx);
3903 /* bring the ctx back to life */
3904 reinit_completion(&ctx->ctx_done);
3905 percpu_ref_reinit(&ctx->refs);
3909 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3910 void __user *, arg, unsigned int, nr_args)
3912 struct io_ring_ctx *ctx;
3921 if (f.file->f_op != &io_uring_fops)
3924 ctx = f.file->private_data;
3926 mutex_lock(&ctx->uring_lock);
3927 ret = __io_uring_register(ctx, opcode, arg, nr_args);
3928 mutex_unlock(&ctx->uring_lock);
3934 static int __init io_uring_init(void)
3936 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
3939 __initcall(io_uring_init);