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. When the application reads the CQ ring
8 * tail, it must use an appropriate smp_rmb() to order with the smp_wmb()
9 * the kernel uses after writing the tail. Failure to do so could cause a
10 * delay in when the application notices that completion events available.
11 * This isn't a fatal condition. Likewise, the application must use an
12 * appropriate smp_wmb() both before writing the SQ tail, and after writing
13 * the SQ tail. The first one orders the sqe writes with the tail write, and
14 * the latter is paired with the smp_rmb() the kernel will issue before
15 * reading the SQ tail on submission.
17 * Also see the examples in the liburing library:
19 * git://git.kernel.dk/liburing
21 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
22 * from data shared between the kernel and application. This is done both
23 * for ordering purposes, but also to ensure that once a value is loaded from
24 * data that the application could potentially modify, it remains stable.
26 * Copyright (C) 2018-2019 Jens Axboe
27 * Copyright (c) 2018-2019 Christoph Hellwig
29 #include <linux/kernel.h>
30 #include <linux/init.h>
31 #include <linux/errno.h>
32 #include <linux/syscalls.h>
33 #include <linux/compat.h>
34 #include <linux/refcount.h>
35 #include <linux/uio.h>
37 #include <linux/sched/signal.h>
39 #include <linux/file.h>
40 #include <linux/fdtable.h>
42 #include <linux/mman.h>
43 #include <linux/mmu_context.h>
44 #include <linux/percpu.h>
45 #include <linux/slab.h>
46 #include <linux/workqueue.h>
47 #include <linux/blkdev.h>
48 #include <linux/net.h>
50 #include <net/af_unix.h>
51 #include <linux/anon_inodes.h>
52 #include <linux/sched/mm.h>
53 #include <linux/uaccess.h>
54 #include <linux/nospec.h>
56 #include <uapi/linux/io_uring.h>
60 #define IORING_MAX_ENTRIES 4096
63 u32 head ____cacheline_aligned_in_smp;
64 u32 tail ____cacheline_aligned_in_smp;
81 struct io_uring_cqe cqes[];
86 struct percpu_ref refs;
87 } ____cacheline_aligned_in_smp;
95 struct io_sq_ring *sq_ring;
96 unsigned cached_sq_head;
99 struct io_uring_sqe *sq_sqes;
100 } ____cacheline_aligned_in_smp;
103 struct workqueue_struct *sqo_wq;
104 struct mm_struct *sqo_mm;
108 struct io_cq_ring *cq_ring;
109 unsigned cached_cq_tail;
112 struct wait_queue_head cq_wait;
113 struct fasync_struct *cq_fasync;
114 } ____cacheline_aligned_in_smp;
116 struct user_struct *user;
118 struct completion ctx_done;
121 struct mutex uring_lock;
122 wait_queue_head_t wait;
123 } ____cacheline_aligned_in_smp;
126 spinlock_t completion_lock;
127 bool poll_multi_file;
129 * ->poll_list is protected by the ctx->uring_lock for
130 * io_uring instances that don't use IORING_SETUP_SQPOLL.
131 * For SQPOLL, only the single threaded io_sq_thread() will
132 * manipulate the list, hence no extra locking is needed there.
134 struct list_head poll_list;
135 } ____cacheline_aligned_in_smp;
137 #if defined(CONFIG_UNIX)
138 struct socket *ring_sock;
143 const struct io_uring_sqe *sqe;
144 unsigned short index;
152 struct sqe_submit submit;
154 struct io_ring_ctx *ctx;
155 struct list_head list;
157 #define REQ_F_FORCE_NONBLOCK 1 /* inline submission attempt */
158 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
162 struct work_struct work;
165 #define IO_PLUG_THRESHOLD 2
166 #define IO_IOPOLL_BATCH 8
168 struct io_submit_state {
169 struct blk_plug plug;
172 * File reference cache
176 unsigned int has_refs;
177 unsigned int used_refs;
178 unsigned int ios_left;
181 static struct kmem_cache *req_cachep;
183 static const struct file_operations io_uring_fops;
185 struct sock *io_uring_get_socket(struct file *file)
187 #if defined(CONFIG_UNIX)
188 if (file->f_op == &io_uring_fops) {
189 struct io_ring_ctx *ctx = file->private_data;
191 return ctx->ring_sock->sk;
196 EXPORT_SYMBOL(io_uring_get_socket);
198 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
200 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
202 complete(&ctx->ctx_done);
205 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
207 struct io_ring_ctx *ctx;
209 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
213 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 0, GFP_KERNEL)) {
218 ctx->flags = p->flags;
219 init_waitqueue_head(&ctx->cq_wait);
220 init_completion(&ctx->ctx_done);
221 mutex_init(&ctx->uring_lock);
222 init_waitqueue_head(&ctx->wait);
223 spin_lock_init(&ctx->completion_lock);
224 INIT_LIST_HEAD(&ctx->poll_list);
228 static void io_commit_cqring(struct io_ring_ctx *ctx)
230 struct io_cq_ring *ring = ctx->cq_ring;
232 if (ctx->cached_cq_tail != READ_ONCE(ring->r.tail)) {
233 /* order cqe stores with ring update */
234 smp_store_release(&ring->r.tail, ctx->cached_cq_tail);
237 * Write sider barrier of tail update, app has read side. See
238 * comment at the top of this file.
242 if (wq_has_sleeper(&ctx->cq_wait)) {
243 wake_up_interruptible(&ctx->cq_wait);
244 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
249 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
251 struct io_cq_ring *ring = ctx->cq_ring;
254 tail = ctx->cached_cq_tail;
255 /* See comment at the top of the file */
257 if (tail + 1 == READ_ONCE(ring->r.head))
260 ctx->cached_cq_tail++;
261 return &ring->cqes[tail & ctx->cq_mask];
264 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
265 long res, unsigned ev_flags)
267 struct io_uring_cqe *cqe;
270 * If we can't get a cq entry, userspace overflowed the
271 * submission (by quite a lot). Increment the overflow count in
274 cqe = io_get_cqring(ctx);
276 WRITE_ONCE(cqe->user_data, ki_user_data);
277 WRITE_ONCE(cqe->res, res);
278 WRITE_ONCE(cqe->flags, ev_flags);
280 unsigned overflow = READ_ONCE(ctx->cq_ring->overflow);
282 WRITE_ONCE(ctx->cq_ring->overflow, overflow + 1);
286 static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 ki_user_data,
287 long res, unsigned ev_flags)
291 spin_lock_irqsave(&ctx->completion_lock, flags);
292 io_cqring_fill_event(ctx, ki_user_data, res, ev_flags);
293 io_commit_cqring(ctx);
294 spin_unlock_irqrestore(&ctx->completion_lock, flags);
296 if (waitqueue_active(&ctx->wait))
300 static void io_ring_drop_ctx_refs(struct io_ring_ctx *ctx, unsigned refs)
302 percpu_ref_put_many(&ctx->refs, refs);
304 if (waitqueue_active(&ctx->wait))
308 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx)
310 struct io_kiocb *req;
312 if (!percpu_ref_tryget(&ctx->refs))
315 req = kmem_cache_alloc(req_cachep, __GFP_NOWARN);
322 io_ring_drop_ctx_refs(ctx, 1);
326 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
329 kmem_cache_free_bulk(req_cachep, *nr, reqs);
330 io_ring_drop_ctx_refs(ctx, *nr);
335 static void io_free_req(struct io_kiocb *req)
337 io_ring_drop_ctx_refs(req->ctx, 1);
338 kmem_cache_free(req_cachep, req);
342 * Find and free completed poll iocbs
344 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
345 struct list_head *done)
347 void *reqs[IO_IOPOLL_BATCH];
348 int file_count, to_free;
349 struct file *file = NULL;
350 struct io_kiocb *req;
352 file_count = to_free = 0;
353 while (!list_empty(done)) {
354 req = list_first_entry(done, struct io_kiocb, list);
355 list_del(&req->list);
357 io_cqring_fill_event(ctx, req->user_data, req->error, 0);
359 reqs[to_free++] = req;
363 * Batched puts of the same file, to avoid dirtying the
364 * file usage count multiple times, if avoidable.
367 file = req->rw.ki_filp;
369 } else if (file == req->rw.ki_filp) {
372 fput_many(file, file_count);
373 file = req->rw.ki_filp;
377 if (to_free == ARRAY_SIZE(reqs))
378 io_free_req_many(ctx, reqs, &to_free);
380 io_commit_cqring(ctx);
383 fput_many(file, file_count);
384 io_free_req_many(ctx, reqs, &to_free);
387 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
390 struct io_kiocb *req, *tmp;
396 * Only spin for completions if we don't have multiple devices hanging
397 * off our complete list, and we're under the requested amount.
399 spin = !ctx->poll_multi_file && *nr_events < min;
402 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
403 struct kiocb *kiocb = &req->rw;
406 * Move completed entries to our local list. If we find a
407 * request that requires polling, break out and complete
408 * the done list first, if we have entries there.
410 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
411 list_move_tail(&req->list, &done);
414 if (!list_empty(&done))
417 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
426 if (!list_empty(&done))
427 io_iopoll_complete(ctx, nr_events, &done);
433 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
434 * non-spinning poll check - we'll still enter the driver poll loop, but only
435 * as a non-spinning completion check.
437 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
440 while (!list_empty(&ctx->poll_list)) {
443 ret = io_do_iopoll(ctx, nr_events, min);
446 if (!min || *nr_events >= min)
454 * We can't just wait for polled events to come to us, we have to actively
455 * find and complete them.
457 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
459 if (!(ctx->flags & IORING_SETUP_IOPOLL))
462 mutex_lock(&ctx->uring_lock);
463 while (!list_empty(&ctx->poll_list)) {
464 unsigned int nr_events = 0;
466 io_iopoll_getevents(ctx, &nr_events, 1);
468 mutex_unlock(&ctx->uring_lock);
471 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
479 if (*nr_events < min)
480 tmin = min - *nr_events;
482 ret = io_iopoll_getevents(ctx, nr_events, tmin);
486 } while (min && !*nr_events && !need_resched());
491 static void kiocb_end_write(struct kiocb *kiocb)
493 if (kiocb->ki_flags & IOCB_WRITE) {
494 struct inode *inode = file_inode(kiocb->ki_filp);
497 * Tell lockdep we inherited freeze protection from submission
500 if (S_ISREG(inode->i_mode))
501 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
502 file_end_write(kiocb->ki_filp);
506 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
508 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
510 kiocb_end_write(kiocb);
512 fput(kiocb->ki_filp);
513 io_cqring_add_event(req->ctx, req->user_data, res, 0);
517 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
519 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
521 kiocb_end_write(kiocb);
525 req->flags |= REQ_F_IOPOLL_COMPLETED;
529 * After the iocb has been issued, it's safe to be found on the poll list.
530 * Adding the kiocb to the list AFTER submission ensures that we don't
531 * find it from a io_iopoll_getevents() thread before the issuer is done
532 * accessing the kiocb cookie.
534 static void io_iopoll_req_issued(struct io_kiocb *req)
536 struct io_ring_ctx *ctx = req->ctx;
539 * Track whether we have multiple files in our lists. This will impact
540 * how we do polling eventually, not spinning if we're on potentially
543 if (list_empty(&ctx->poll_list)) {
544 ctx->poll_multi_file = false;
545 } else if (!ctx->poll_multi_file) {
546 struct io_kiocb *list_req;
548 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
550 if (list_req->rw.ki_filp != req->rw.ki_filp)
551 ctx->poll_multi_file = true;
555 * For fast devices, IO may have already completed. If it has, add
556 * it to the front so we find it first.
558 if (req->flags & REQ_F_IOPOLL_COMPLETED)
559 list_add(&req->list, &ctx->poll_list);
561 list_add_tail(&req->list, &ctx->poll_list);
564 static void io_file_put(struct io_submit_state *state, struct file *file)
568 } else if (state->file) {
569 int diff = state->has_refs - state->used_refs;
572 fput_many(state->file, diff);
578 * Get as many references to a file as we have IOs left in this submission,
579 * assuming most submissions are for one file, or at least that each file
580 * has more than one submission.
582 static struct file *io_file_get(struct io_submit_state *state, int fd)
588 if (state->fd == fd) {
593 io_file_put(state, NULL);
595 state->file = fget_many(fd, state->ios_left);
600 state->has_refs = state->ios_left;
601 state->used_refs = 1;
607 * If we tracked the file through the SCM inflight mechanism, we could support
608 * any file. For now, just ensure that anything potentially problematic is done
611 static bool io_file_supports_async(struct file *file)
613 umode_t mode = file_inode(file)->i_mode;
615 if (S_ISBLK(mode) || S_ISCHR(mode))
617 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
623 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
624 bool force_nonblock, struct io_submit_state *state)
626 struct io_ring_ctx *ctx = req->ctx;
627 struct kiocb *kiocb = &req->rw;
631 /* For -EAGAIN retry, everything is already prepped */
635 fd = READ_ONCE(sqe->fd);
636 kiocb->ki_filp = io_file_get(state, fd);
637 if (unlikely(!kiocb->ki_filp))
639 if (force_nonblock && !io_file_supports_async(kiocb->ki_filp))
640 force_nonblock = false;
641 kiocb->ki_pos = READ_ONCE(sqe->off);
642 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
643 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
645 ioprio = READ_ONCE(sqe->ioprio);
647 ret = ioprio_check_cap(ioprio);
651 kiocb->ki_ioprio = ioprio;
653 kiocb->ki_ioprio = get_current_ioprio();
655 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
658 if (force_nonblock) {
659 kiocb->ki_flags |= IOCB_NOWAIT;
660 req->flags |= REQ_F_FORCE_NONBLOCK;
662 if (ctx->flags & IORING_SETUP_IOPOLL) {
664 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
665 !kiocb->ki_filp->f_op->iopoll)
669 kiocb->ki_flags |= IOCB_HIPRI;
670 kiocb->ki_complete = io_complete_rw_iopoll;
672 if (kiocb->ki_flags & IOCB_HIPRI) {
676 kiocb->ki_complete = io_complete_rw;
680 /* in case of error, we didn't use this file reference. drop it. */
683 io_file_put(state, kiocb->ki_filp);
687 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
693 case -ERESTARTNOINTR:
694 case -ERESTARTNOHAND:
695 case -ERESTART_RESTARTBLOCK:
697 * We can't just restart the syscall, since previously
698 * submitted sqes may already be in progress. Just fail this
704 kiocb->ki_complete(kiocb, ret, 0);
708 static int io_import_iovec(struct io_ring_ctx *ctx, int rw,
709 const struct sqe_submit *s, struct iovec **iovec,
710 struct iov_iter *iter)
712 const struct io_uring_sqe *sqe = s->sqe;
713 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
714 size_t sqe_len = READ_ONCE(sqe->len);
721 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
725 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
728 static ssize_t io_read(struct io_kiocb *req, const struct sqe_submit *s,
729 bool force_nonblock, struct io_submit_state *state)
731 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
732 struct kiocb *kiocb = &req->rw;
733 struct iov_iter iter;
737 ret = io_prep_rw(req, s->sqe, force_nonblock, state);
740 file = kiocb->ki_filp;
743 if (unlikely(!(file->f_mode & FMODE_READ)))
746 if (unlikely(!file->f_op->read_iter))
749 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
753 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_iter_count(&iter));
757 /* Catch -EAGAIN return for forced non-blocking submission */
758 ret2 = call_read_iter(file, kiocb, &iter);
759 if (!force_nonblock || ret2 != -EAGAIN)
760 io_rw_done(kiocb, ret2);
766 /* Hold on to the file for -EAGAIN */
767 if (unlikely(ret && ret != -EAGAIN))
772 static ssize_t io_write(struct io_kiocb *req, const struct sqe_submit *s,
773 bool force_nonblock, struct io_submit_state *state)
775 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
776 struct kiocb *kiocb = &req->rw;
777 struct iov_iter iter;
781 ret = io_prep_rw(req, s->sqe, force_nonblock, state);
784 /* Hold on to the file for -EAGAIN */
785 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT))
789 file = kiocb->ki_filp;
790 if (unlikely(!(file->f_mode & FMODE_WRITE)))
793 if (unlikely(!file->f_op->write_iter))
796 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
800 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos,
801 iov_iter_count(&iter));
804 * Open-code file_start_write here to grab freeze protection,
805 * which will be released by another thread in
806 * io_complete_rw(). Fool lockdep by telling it the lock got
807 * released so that it doesn't complain about the held lock when
808 * we return to userspace.
810 if (S_ISREG(file_inode(file)->i_mode)) {
811 __sb_start_write(file_inode(file)->i_sb,
812 SB_FREEZE_WRITE, true);
813 __sb_writers_release(file_inode(file)->i_sb,
816 kiocb->ki_flags |= IOCB_WRITE;
817 io_rw_done(kiocb, call_write_iter(file, kiocb, &iter));
827 * IORING_OP_NOP just posts a completion event, nothing else.
829 static int io_nop(struct io_kiocb *req, u64 user_data)
831 struct io_ring_ctx *ctx = req->ctx;
834 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
838 * Twilight zone - it's possible that someone issued an opcode that
839 * has a file attached, then got -EAGAIN on submission, and changed
840 * the sqe before we retried it from async context. Avoid dropping
841 * a file reference for this malicious case, and flag the error.
843 if (req->rw.ki_filp) {
845 fput(req->rw.ki_filp);
847 io_cqring_add_event(ctx, user_data, err, 0);
852 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
856 /* Prep already done */
860 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
862 if (unlikely(sqe->addr || sqe->ioprio))
865 fd = READ_ONCE(sqe->fd);
866 req->rw.ki_filp = fget(fd);
867 if (unlikely(!req->rw.ki_filp))
873 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
876 loff_t sqe_off = READ_ONCE(sqe->off);
877 loff_t sqe_len = READ_ONCE(sqe->len);
878 loff_t end = sqe_off + sqe_len;
879 unsigned fsync_flags;
882 fsync_flags = READ_ONCE(sqe->fsync_flags);
883 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
886 ret = io_prep_fsync(req, sqe);
890 /* fsync always requires a blocking context */
894 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
895 end > 0 ? end : LLONG_MAX,
896 fsync_flags & IORING_FSYNC_DATASYNC);
898 fput(req->rw.ki_filp);
899 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
904 static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
905 const struct sqe_submit *s, bool force_nonblock,
906 struct io_submit_state *state)
911 if (unlikely(s->index >= ctx->sq_entries))
913 req->user_data = READ_ONCE(s->sqe->user_data);
915 opcode = READ_ONCE(s->sqe->opcode);
918 ret = io_nop(req, req->user_data);
920 case IORING_OP_READV:
921 ret = io_read(req, s, force_nonblock, state);
923 case IORING_OP_WRITEV:
924 ret = io_write(req, s, force_nonblock, state);
926 case IORING_OP_FSYNC:
927 ret = io_fsync(req, s->sqe, force_nonblock);
937 if (ctx->flags & IORING_SETUP_IOPOLL) {
938 if (req->error == -EAGAIN)
941 /* workqueue context doesn't hold uring_lock, grab it now */
943 mutex_lock(&ctx->uring_lock);
944 io_iopoll_req_issued(req);
946 mutex_unlock(&ctx->uring_lock);
952 static void io_sq_wq_submit_work(struct work_struct *work)
954 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
955 struct sqe_submit *s = &req->submit;
956 const struct io_uring_sqe *sqe = s->sqe;
957 struct io_ring_ctx *ctx = req->ctx;
958 mm_segment_t old_fs = get_fs();
961 /* Ensure we clear previously set forced non-block flag */
962 req->flags &= ~REQ_F_FORCE_NONBLOCK;
963 req->rw.ki_flags &= ~IOCB_NOWAIT;
965 if (!mmget_not_zero(ctx->sqo_mm)) {
973 s->needs_lock = true;
976 ret = __io_submit_sqe(ctx, req, s, false, NULL);
978 * We can get EAGAIN for polled IO even though we're forcing
979 * a sync submission from here, since we can't wait for
980 * request slots on the block side.
988 unuse_mm(ctx->sqo_mm);
992 io_cqring_add_event(ctx, sqe->user_data, ret, 0);
996 /* async context always use a copy of the sqe */
1000 static int io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
1001 struct io_submit_state *state)
1003 struct io_kiocb *req;
1006 /* enforce forwards compatibility on users */
1007 if (unlikely(s->sqe->flags))
1010 req = io_get_req(ctx);
1014 req->rw.ki_filp = NULL;
1016 ret = __io_submit_sqe(ctx, req, s, true, state);
1017 if (ret == -EAGAIN) {
1018 struct io_uring_sqe *sqe_copy;
1020 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1022 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
1025 memcpy(&req->submit, s, sizeof(*s));
1026 INIT_WORK(&req->work, io_sq_wq_submit_work);
1027 queue_work(ctx->sqo_wq, &req->work);
1038 * Batched submission is done, ensure local IO is flushed out.
1040 static void io_submit_state_end(struct io_submit_state *state)
1042 blk_finish_plug(&state->plug);
1043 io_file_put(state, NULL);
1047 * Start submission side cache.
1049 static void io_submit_state_start(struct io_submit_state *state,
1050 struct io_ring_ctx *ctx, unsigned max_ios)
1052 blk_start_plug(&state->plug);
1054 state->ios_left = max_ios;
1057 static void io_commit_sqring(struct io_ring_ctx *ctx)
1059 struct io_sq_ring *ring = ctx->sq_ring;
1061 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
1063 * Ensure any loads from the SQEs are done at this point,
1064 * since once we write the new head, the application could
1065 * write new data to them.
1067 smp_store_release(&ring->r.head, ctx->cached_sq_head);
1070 * write side barrier of head update, app has read side. See
1071 * comment at the top of this file
1078 * Undo last io_get_sqring()
1080 static void io_drop_sqring(struct io_ring_ctx *ctx)
1082 ctx->cached_sq_head--;
1086 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
1087 * that is mapped by userspace. This means that care needs to be taken to
1088 * ensure that reads are stable, as we cannot rely on userspace always
1089 * being a good citizen. If members of the sqe are validated and then later
1090 * used, it's important that those reads are done through READ_ONCE() to
1091 * prevent a re-load down the line.
1093 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
1095 struct io_sq_ring *ring = ctx->sq_ring;
1099 * The cached sq head (or cq tail) serves two purposes:
1101 * 1) allows us to batch the cost of updating the user visible
1103 * 2) allows the kernel side to track the head on its own, even
1104 * though the application is the one updating it.
1106 head = ctx->cached_sq_head;
1107 /* See comment at the top of this file */
1109 if (head == READ_ONCE(ring->r.tail))
1112 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
1113 if (head < ctx->sq_entries) {
1115 s->sqe = &ctx->sq_sqes[head];
1116 ctx->cached_sq_head++;
1120 /* drop invalid entries */
1121 ctx->cached_sq_head++;
1123 /* See comment at the top of this file */
1128 static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
1130 struct io_submit_state state, *statep = NULL;
1131 int i, ret = 0, submit = 0;
1133 if (to_submit > IO_PLUG_THRESHOLD) {
1134 io_submit_state_start(&state, ctx, to_submit);
1138 for (i = 0; i < to_submit; i++) {
1139 struct sqe_submit s;
1141 if (!io_get_sqring(ctx, &s))
1145 s.needs_lock = false;
1147 ret = io_submit_sqe(ctx, &s, statep);
1149 io_drop_sqring(ctx);
1155 io_commit_sqring(ctx);
1158 io_submit_state_end(statep);
1160 return submit ? submit : ret;
1163 static unsigned io_cqring_events(struct io_cq_ring *ring)
1165 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
1169 * Wait until events become available, if we don't already have some. The
1170 * application must reap them itself, as they reside on the shared cq ring.
1172 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
1173 const sigset_t __user *sig, size_t sigsz)
1175 struct io_cq_ring *ring = ctx->cq_ring;
1176 sigset_t ksigmask, sigsaved;
1180 /* See comment at the top of this file */
1182 if (io_cqring_events(ring) >= min_events)
1186 ret = set_user_sigmask(sig, &ksigmask, &sigsaved, sigsz);
1192 prepare_to_wait(&ctx->wait, &wait, TASK_INTERRUPTIBLE);
1195 /* See comment at the top of this file */
1197 if (io_cqring_events(ring) >= min_events)
1203 if (signal_pending(current))
1207 finish_wait(&ctx->wait, &wait);
1210 restore_user_sigmask(sig, &sigsaved);
1212 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
1215 static int io_sq_offload_start(struct io_ring_ctx *ctx)
1219 mmgrab(current->mm);
1220 ctx->sqo_mm = current->mm;
1222 /* Do QD, or 2 * CPUS, whatever is smallest */
1223 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
1224 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
1232 mmdrop(ctx->sqo_mm);
1237 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
1239 atomic_long_sub(nr_pages, &user->locked_vm);
1242 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
1244 unsigned long page_limit, cur_pages, new_pages;
1246 /* Don't allow more pages than we can safely lock */
1247 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1250 cur_pages = atomic_long_read(&user->locked_vm);
1251 new_pages = cur_pages + nr_pages;
1252 if (new_pages > page_limit)
1254 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
1255 new_pages) != cur_pages);
1260 static void io_mem_free(void *ptr)
1262 struct page *page = virt_to_head_page(ptr);
1264 if (put_page_testzero(page))
1265 free_compound_page(page);
1268 static void *io_mem_alloc(size_t size)
1270 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
1273 return (void *) __get_free_pages(gfp_flags, get_order(size));
1276 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
1278 struct io_sq_ring *sq_ring;
1279 struct io_cq_ring *cq_ring;
1282 bytes = struct_size(sq_ring, array, sq_entries);
1283 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
1284 bytes += struct_size(cq_ring, cqes, cq_entries);
1286 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
1289 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
1292 destroy_workqueue(ctx->sqo_wq);
1294 mmdrop(ctx->sqo_mm);
1296 io_iopoll_reap_events(ctx);
1298 #if defined(CONFIG_UNIX)
1300 sock_release(ctx->ring_sock);
1303 io_mem_free(ctx->sq_ring);
1304 io_mem_free(ctx->sq_sqes);
1305 io_mem_free(ctx->cq_ring);
1307 percpu_ref_exit(&ctx->refs);
1308 if (ctx->account_mem)
1309 io_unaccount_mem(ctx->user,
1310 ring_pages(ctx->sq_entries, ctx->cq_entries));
1311 free_uid(ctx->user);
1315 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
1317 struct io_ring_ctx *ctx = file->private_data;
1320 poll_wait(file, &ctx->cq_wait, wait);
1321 /* See comment at the top of this file */
1323 if (READ_ONCE(ctx->sq_ring->r.tail) + 1 != ctx->cached_sq_head)
1324 mask |= EPOLLOUT | EPOLLWRNORM;
1325 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
1326 mask |= EPOLLIN | EPOLLRDNORM;
1331 static int io_uring_fasync(int fd, struct file *file, int on)
1333 struct io_ring_ctx *ctx = file->private_data;
1335 return fasync_helper(fd, file, on, &ctx->cq_fasync);
1338 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
1340 mutex_lock(&ctx->uring_lock);
1341 percpu_ref_kill(&ctx->refs);
1342 mutex_unlock(&ctx->uring_lock);
1344 io_iopoll_reap_events(ctx);
1345 wait_for_completion(&ctx->ctx_done);
1346 io_ring_ctx_free(ctx);
1349 static int io_uring_release(struct inode *inode, struct file *file)
1351 struct io_ring_ctx *ctx = file->private_data;
1353 file->private_data = NULL;
1354 io_ring_ctx_wait_and_kill(ctx);
1358 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
1360 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
1361 unsigned long sz = vma->vm_end - vma->vm_start;
1362 struct io_ring_ctx *ctx = file->private_data;
1368 case IORING_OFF_SQ_RING:
1371 case IORING_OFF_SQES:
1374 case IORING_OFF_CQ_RING:
1381 page = virt_to_head_page(ptr);
1382 if (sz > (PAGE_SIZE << compound_order(page)))
1385 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
1386 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
1389 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
1390 u32, min_complete, u32, flags, const sigset_t __user *, sig,
1393 struct io_ring_ctx *ctx;
1398 if (flags & ~IORING_ENTER_GETEVENTS)
1406 if (f.file->f_op != &io_uring_fops)
1410 ctx = f.file->private_data;
1411 if (!percpu_ref_tryget(&ctx->refs))
1416 to_submit = min(to_submit, ctx->sq_entries);
1418 mutex_lock(&ctx->uring_lock);
1419 submitted = io_ring_submit(ctx, to_submit);
1420 mutex_unlock(&ctx->uring_lock);
1425 if (flags & IORING_ENTER_GETEVENTS) {
1426 unsigned nr_events = 0;
1428 min_complete = min(min_complete, ctx->cq_entries);
1431 * The application could have included the 'to_submit' count
1432 * in how many events it wanted to wait for. If we failed to
1433 * submit the desired count, we may need to adjust the number
1434 * of events to poll/wait for.
1436 if (submitted < to_submit)
1437 min_complete = min_t(unsigned, submitted, min_complete);
1439 if (ctx->flags & IORING_SETUP_IOPOLL) {
1440 mutex_lock(&ctx->uring_lock);
1441 ret = io_iopoll_check(ctx, &nr_events, min_complete);
1442 mutex_unlock(&ctx->uring_lock);
1444 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
1449 io_ring_drop_ctx_refs(ctx, 1);
1452 return submitted ? submitted : ret;
1455 static const struct file_operations io_uring_fops = {
1456 .release = io_uring_release,
1457 .mmap = io_uring_mmap,
1458 .poll = io_uring_poll,
1459 .fasync = io_uring_fasync,
1462 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
1463 struct io_uring_params *p)
1465 struct io_sq_ring *sq_ring;
1466 struct io_cq_ring *cq_ring;
1469 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
1473 ctx->sq_ring = sq_ring;
1474 sq_ring->ring_mask = p->sq_entries - 1;
1475 sq_ring->ring_entries = p->sq_entries;
1476 ctx->sq_mask = sq_ring->ring_mask;
1477 ctx->sq_entries = sq_ring->ring_entries;
1479 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
1480 if (size == SIZE_MAX)
1483 ctx->sq_sqes = io_mem_alloc(size);
1484 if (!ctx->sq_sqes) {
1485 io_mem_free(ctx->sq_ring);
1489 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
1491 io_mem_free(ctx->sq_ring);
1492 io_mem_free(ctx->sq_sqes);
1496 ctx->cq_ring = cq_ring;
1497 cq_ring->ring_mask = p->cq_entries - 1;
1498 cq_ring->ring_entries = p->cq_entries;
1499 ctx->cq_mask = cq_ring->ring_mask;
1500 ctx->cq_entries = cq_ring->ring_entries;
1505 * Allocate an anonymous fd, this is what constitutes the application
1506 * visible backing of an io_uring instance. The application mmaps this
1507 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
1508 * we have to tie this fd to a socket for file garbage collection purposes.
1510 static int io_uring_get_fd(struct io_ring_ctx *ctx)
1515 #if defined(CONFIG_UNIX)
1516 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
1522 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
1526 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
1527 O_RDWR | O_CLOEXEC);
1530 ret = PTR_ERR(file);
1534 #if defined(CONFIG_UNIX)
1535 ctx->ring_sock->file = file;
1537 fd_install(ret, file);
1540 #if defined(CONFIG_UNIX)
1541 sock_release(ctx->ring_sock);
1542 ctx->ring_sock = NULL;
1547 static int io_uring_create(unsigned entries, struct io_uring_params *p)
1549 struct user_struct *user = NULL;
1550 struct io_ring_ctx *ctx;
1554 if (!entries || entries > IORING_MAX_ENTRIES)
1558 * Use twice as many entries for the CQ ring. It's possible for the
1559 * application to drive a higher depth than the size of the SQ ring,
1560 * since the sqes are only used at submission time. This allows for
1561 * some flexibility in overcommitting a bit.
1563 p->sq_entries = roundup_pow_of_two(entries);
1564 p->cq_entries = 2 * p->sq_entries;
1566 user = get_uid(current_user());
1567 account_mem = !capable(CAP_IPC_LOCK);
1570 ret = io_account_mem(user,
1571 ring_pages(p->sq_entries, p->cq_entries));
1578 ctx = io_ring_ctx_alloc(p);
1581 io_unaccount_mem(user, ring_pages(p->sq_entries,
1586 ctx->compat = in_compat_syscall();
1587 ctx->account_mem = account_mem;
1590 ret = io_allocate_scq_urings(ctx, p);
1594 ret = io_sq_offload_start(ctx);
1598 ret = io_uring_get_fd(ctx);
1602 memset(&p->sq_off, 0, sizeof(p->sq_off));
1603 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
1604 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
1605 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
1606 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
1607 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
1608 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
1609 p->sq_off.array = offsetof(struct io_sq_ring, array);
1611 memset(&p->cq_off, 0, sizeof(p->cq_off));
1612 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
1613 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
1614 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
1615 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
1616 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
1617 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
1620 io_ring_ctx_wait_and_kill(ctx);
1625 * Sets up an aio uring context, and returns the fd. Applications asks for a
1626 * ring size, we return the actual sq/cq ring sizes (among other things) in the
1627 * params structure passed in.
1629 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
1631 struct io_uring_params p;
1635 if (copy_from_user(&p, params, sizeof(p)))
1637 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
1642 if (p.flags & ~IORING_SETUP_IOPOLL)
1645 ret = io_uring_create(entries, &p);
1649 if (copy_to_user(params, &p, sizeof(p)))
1655 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
1656 struct io_uring_params __user *, params)
1658 return io_uring_setup(entries, params);
1661 static int __init io_uring_init(void)
1663 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
1666 __initcall(io_uring_init);