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 static struct kmem_cache *req_cachep;
170 static const struct file_operations io_uring_fops;
172 struct sock *io_uring_get_socket(struct file *file)
174 #if defined(CONFIG_UNIX)
175 if (file->f_op == &io_uring_fops) {
176 struct io_ring_ctx *ctx = file->private_data;
178 return ctx->ring_sock->sk;
183 EXPORT_SYMBOL(io_uring_get_socket);
185 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
187 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
189 complete(&ctx->ctx_done);
192 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
194 struct io_ring_ctx *ctx;
196 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
200 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 0, GFP_KERNEL)) {
205 ctx->flags = p->flags;
206 init_waitqueue_head(&ctx->cq_wait);
207 init_completion(&ctx->ctx_done);
208 mutex_init(&ctx->uring_lock);
209 init_waitqueue_head(&ctx->wait);
210 spin_lock_init(&ctx->completion_lock);
211 INIT_LIST_HEAD(&ctx->poll_list);
215 static void io_commit_cqring(struct io_ring_ctx *ctx)
217 struct io_cq_ring *ring = ctx->cq_ring;
219 if (ctx->cached_cq_tail != READ_ONCE(ring->r.tail)) {
220 /* order cqe stores with ring update */
221 smp_store_release(&ring->r.tail, ctx->cached_cq_tail);
224 * Write sider barrier of tail update, app has read side. See
225 * comment at the top of this file.
229 if (wq_has_sleeper(&ctx->cq_wait)) {
230 wake_up_interruptible(&ctx->cq_wait);
231 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
236 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
238 struct io_cq_ring *ring = ctx->cq_ring;
241 tail = ctx->cached_cq_tail;
242 /* See comment at the top of the file */
244 if (tail + 1 == READ_ONCE(ring->r.head))
247 ctx->cached_cq_tail++;
248 return &ring->cqes[tail & ctx->cq_mask];
251 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
252 long res, unsigned ev_flags)
254 struct io_uring_cqe *cqe;
257 * If we can't get a cq entry, userspace overflowed the
258 * submission (by quite a lot). Increment the overflow count in
261 cqe = io_get_cqring(ctx);
263 WRITE_ONCE(cqe->user_data, ki_user_data);
264 WRITE_ONCE(cqe->res, res);
265 WRITE_ONCE(cqe->flags, ev_flags);
267 unsigned overflow = READ_ONCE(ctx->cq_ring->overflow);
269 WRITE_ONCE(ctx->cq_ring->overflow, overflow + 1);
273 static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 ki_user_data,
274 long res, unsigned ev_flags)
278 spin_lock_irqsave(&ctx->completion_lock, flags);
279 io_cqring_fill_event(ctx, ki_user_data, res, ev_flags);
280 io_commit_cqring(ctx);
281 spin_unlock_irqrestore(&ctx->completion_lock, flags);
283 if (waitqueue_active(&ctx->wait))
287 static void io_ring_drop_ctx_refs(struct io_ring_ctx *ctx, unsigned refs)
289 percpu_ref_put_many(&ctx->refs, refs);
291 if (waitqueue_active(&ctx->wait))
295 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx)
297 struct io_kiocb *req;
299 if (!percpu_ref_tryget(&ctx->refs))
302 req = kmem_cache_alloc(req_cachep, __GFP_NOWARN);
309 io_ring_drop_ctx_refs(ctx, 1);
313 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
316 kmem_cache_free_bulk(req_cachep, *nr, reqs);
317 io_ring_drop_ctx_refs(ctx, *nr);
322 static void io_free_req(struct io_kiocb *req)
324 io_ring_drop_ctx_refs(req->ctx, 1);
325 kmem_cache_free(req_cachep, req);
329 * Find and free completed poll iocbs
331 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
332 struct list_head *done)
334 void *reqs[IO_IOPOLL_BATCH];
335 struct io_kiocb *req;
338 while (!list_empty(done)) {
339 req = list_first_entry(done, struct io_kiocb, list);
340 list_del(&req->list);
342 io_cqring_fill_event(ctx, req->user_data, req->error, 0);
344 reqs[to_free++] = req;
347 fput(req->rw.ki_filp);
348 if (to_free == ARRAY_SIZE(reqs))
349 io_free_req_many(ctx, reqs, &to_free);
351 io_commit_cqring(ctx);
353 io_free_req_many(ctx, reqs, &to_free);
356 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
359 struct io_kiocb *req, *tmp;
365 * Only spin for completions if we don't have multiple devices hanging
366 * off our complete list, and we're under the requested amount.
368 spin = !ctx->poll_multi_file && *nr_events < min;
371 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
372 struct kiocb *kiocb = &req->rw;
375 * Move completed entries to our local list. If we find a
376 * request that requires polling, break out and complete
377 * the done list first, if we have entries there.
379 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
380 list_move_tail(&req->list, &done);
383 if (!list_empty(&done))
386 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
395 if (!list_empty(&done))
396 io_iopoll_complete(ctx, nr_events, &done);
402 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
403 * non-spinning poll check - we'll still enter the driver poll loop, but only
404 * as a non-spinning completion check.
406 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
409 while (!list_empty(&ctx->poll_list)) {
412 ret = io_do_iopoll(ctx, nr_events, min);
415 if (!min || *nr_events >= min)
423 * We can't just wait for polled events to come to us, we have to actively
424 * find and complete them.
426 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
428 if (!(ctx->flags & IORING_SETUP_IOPOLL))
431 mutex_lock(&ctx->uring_lock);
432 while (!list_empty(&ctx->poll_list)) {
433 unsigned int nr_events = 0;
435 io_iopoll_getevents(ctx, &nr_events, 1);
437 mutex_unlock(&ctx->uring_lock);
440 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
448 if (*nr_events < min)
449 tmin = min - *nr_events;
451 ret = io_iopoll_getevents(ctx, nr_events, tmin);
455 } while (min && !*nr_events && !need_resched());
460 static void kiocb_end_write(struct kiocb *kiocb)
462 if (kiocb->ki_flags & IOCB_WRITE) {
463 struct inode *inode = file_inode(kiocb->ki_filp);
466 * Tell lockdep we inherited freeze protection from submission
469 if (S_ISREG(inode->i_mode))
470 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
471 file_end_write(kiocb->ki_filp);
475 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
477 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
479 kiocb_end_write(kiocb);
481 fput(kiocb->ki_filp);
482 io_cqring_add_event(req->ctx, req->user_data, res, 0);
486 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
488 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
490 kiocb_end_write(kiocb);
494 req->flags |= REQ_F_IOPOLL_COMPLETED;
498 * After the iocb has been issued, it's safe to be found on the poll list.
499 * Adding the kiocb to the list AFTER submission ensures that we don't
500 * find it from a io_iopoll_getevents() thread before the issuer is done
501 * accessing the kiocb cookie.
503 static void io_iopoll_req_issued(struct io_kiocb *req)
505 struct io_ring_ctx *ctx = req->ctx;
508 * Track whether we have multiple files in our lists. This will impact
509 * how we do polling eventually, not spinning if we're on potentially
512 if (list_empty(&ctx->poll_list)) {
513 ctx->poll_multi_file = false;
514 } else if (!ctx->poll_multi_file) {
515 struct io_kiocb *list_req;
517 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
519 if (list_req->rw.ki_filp != req->rw.ki_filp)
520 ctx->poll_multi_file = true;
524 * For fast devices, IO may have already completed. If it has, add
525 * it to the front so we find it first.
527 if (req->flags & REQ_F_IOPOLL_COMPLETED)
528 list_add(&req->list, &ctx->poll_list);
530 list_add_tail(&req->list, &ctx->poll_list);
534 * If we tracked the file through the SCM inflight mechanism, we could support
535 * any file. For now, just ensure that anything potentially problematic is done
538 static bool io_file_supports_async(struct file *file)
540 umode_t mode = file_inode(file)->i_mode;
542 if (S_ISBLK(mode) || S_ISCHR(mode))
544 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
550 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
553 struct io_ring_ctx *ctx = req->ctx;
554 struct kiocb *kiocb = &req->rw;
558 /* For -EAGAIN retry, everything is already prepped */
562 fd = READ_ONCE(sqe->fd);
563 kiocb->ki_filp = fget(fd);
564 if (unlikely(!kiocb->ki_filp))
566 if (force_nonblock && !io_file_supports_async(kiocb->ki_filp))
567 force_nonblock = false;
568 kiocb->ki_pos = READ_ONCE(sqe->off);
569 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
570 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
572 ioprio = READ_ONCE(sqe->ioprio);
574 ret = ioprio_check_cap(ioprio);
578 kiocb->ki_ioprio = ioprio;
580 kiocb->ki_ioprio = get_current_ioprio();
582 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
585 if (force_nonblock) {
586 kiocb->ki_flags |= IOCB_NOWAIT;
587 req->flags |= REQ_F_FORCE_NONBLOCK;
589 if (ctx->flags & IORING_SETUP_IOPOLL) {
591 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
592 !kiocb->ki_filp->f_op->iopoll)
596 kiocb->ki_flags |= IOCB_HIPRI;
597 kiocb->ki_complete = io_complete_rw_iopoll;
599 if (kiocb->ki_flags & IOCB_HIPRI) {
603 kiocb->ki_complete = io_complete_rw;
607 fput(kiocb->ki_filp);
611 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
617 case -ERESTARTNOINTR:
618 case -ERESTARTNOHAND:
619 case -ERESTART_RESTARTBLOCK:
621 * We can't just restart the syscall, since previously
622 * submitted sqes may already be in progress. Just fail this
628 kiocb->ki_complete(kiocb, ret, 0);
632 static int io_import_iovec(struct io_ring_ctx *ctx, int rw,
633 const struct sqe_submit *s, struct iovec **iovec,
634 struct iov_iter *iter)
636 const struct io_uring_sqe *sqe = s->sqe;
637 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
638 size_t sqe_len = READ_ONCE(sqe->len);
645 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
649 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
652 static ssize_t io_read(struct io_kiocb *req, const struct sqe_submit *s,
655 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
656 struct kiocb *kiocb = &req->rw;
657 struct iov_iter iter;
661 ret = io_prep_rw(req, s->sqe, force_nonblock);
664 file = kiocb->ki_filp;
667 if (unlikely(!(file->f_mode & FMODE_READ)))
670 if (unlikely(!file->f_op->read_iter))
673 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
677 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_iter_count(&iter));
681 /* Catch -EAGAIN return for forced non-blocking submission */
682 ret2 = call_read_iter(file, kiocb, &iter);
683 if (!force_nonblock || ret2 != -EAGAIN)
684 io_rw_done(kiocb, ret2);
690 /* Hold on to the file for -EAGAIN */
691 if (unlikely(ret && ret != -EAGAIN))
696 static ssize_t io_write(struct io_kiocb *req, const struct sqe_submit *s,
699 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
700 struct kiocb *kiocb = &req->rw;
701 struct iov_iter iter;
705 ret = io_prep_rw(req, s->sqe, force_nonblock);
708 /* Hold on to the file for -EAGAIN */
709 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT))
713 file = kiocb->ki_filp;
714 if (unlikely(!(file->f_mode & FMODE_WRITE)))
717 if (unlikely(!file->f_op->write_iter))
720 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
724 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos,
725 iov_iter_count(&iter));
728 * Open-code file_start_write here to grab freeze protection,
729 * which will be released by another thread in
730 * io_complete_rw(). Fool lockdep by telling it the lock got
731 * released so that it doesn't complain about the held lock when
732 * we return to userspace.
734 if (S_ISREG(file_inode(file)->i_mode)) {
735 __sb_start_write(file_inode(file)->i_sb,
736 SB_FREEZE_WRITE, true);
737 __sb_writers_release(file_inode(file)->i_sb,
740 kiocb->ki_flags |= IOCB_WRITE;
741 io_rw_done(kiocb, call_write_iter(file, kiocb, &iter));
751 * IORING_OP_NOP just posts a completion event, nothing else.
753 static int io_nop(struct io_kiocb *req, u64 user_data)
755 struct io_ring_ctx *ctx = req->ctx;
758 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
762 * Twilight zone - it's possible that someone issued an opcode that
763 * has a file attached, then got -EAGAIN on submission, and changed
764 * the sqe before we retried it from async context. Avoid dropping
765 * a file reference for this malicious case, and flag the error.
767 if (req->rw.ki_filp) {
769 fput(req->rw.ki_filp);
771 io_cqring_add_event(ctx, user_data, err, 0);
776 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
780 /* Prep already done */
784 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
786 if (unlikely(sqe->addr || sqe->ioprio))
789 fd = READ_ONCE(sqe->fd);
790 req->rw.ki_filp = fget(fd);
791 if (unlikely(!req->rw.ki_filp))
797 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
800 loff_t sqe_off = READ_ONCE(sqe->off);
801 loff_t sqe_len = READ_ONCE(sqe->len);
802 loff_t end = sqe_off + sqe_len;
803 unsigned fsync_flags;
806 fsync_flags = READ_ONCE(sqe->fsync_flags);
807 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
810 ret = io_prep_fsync(req, sqe);
814 /* fsync always requires a blocking context */
818 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
819 end > 0 ? end : LLONG_MAX,
820 fsync_flags & IORING_FSYNC_DATASYNC);
822 fput(req->rw.ki_filp);
823 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
828 static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
829 const struct sqe_submit *s, bool force_nonblock)
834 if (unlikely(s->index >= ctx->sq_entries))
836 req->user_data = READ_ONCE(s->sqe->user_data);
838 opcode = READ_ONCE(s->sqe->opcode);
841 ret = io_nop(req, req->user_data);
843 case IORING_OP_READV:
844 ret = io_read(req, s, force_nonblock);
846 case IORING_OP_WRITEV:
847 ret = io_write(req, s, force_nonblock);
849 case IORING_OP_FSYNC:
850 ret = io_fsync(req, s->sqe, force_nonblock);
860 if (ctx->flags & IORING_SETUP_IOPOLL) {
861 if (req->error == -EAGAIN)
864 /* workqueue context doesn't hold uring_lock, grab it now */
866 mutex_lock(&ctx->uring_lock);
867 io_iopoll_req_issued(req);
869 mutex_unlock(&ctx->uring_lock);
875 static void io_sq_wq_submit_work(struct work_struct *work)
877 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
878 struct sqe_submit *s = &req->submit;
879 const struct io_uring_sqe *sqe = s->sqe;
880 struct io_ring_ctx *ctx = req->ctx;
881 mm_segment_t old_fs = get_fs();
884 /* Ensure we clear previously set forced non-block flag */
885 req->flags &= ~REQ_F_FORCE_NONBLOCK;
886 req->rw.ki_flags &= ~IOCB_NOWAIT;
888 if (!mmget_not_zero(ctx->sqo_mm)) {
896 s->needs_lock = true;
899 ret = __io_submit_sqe(ctx, req, s, false);
901 * We can get EAGAIN for polled IO even though we're forcing
902 * a sync submission from here, since we can't wait for
903 * request slots on the block side.
911 unuse_mm(ctx->sqo_mm);
915 io_cqring_add_event(ctx, sqe->user_data, ret, 0);
919 /* async context always use a copy of the sqe */
923 static int io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s)
925 struct io_kiocb *req;
928 /* enforce forwards compatibility on users */
929 if (unlikely(s->sqe->flags))
932 req = io_get_req(ctx);
936 req->rw.ki_filp = NULL;
938 ret = __io_submit_sqe(ctx, req, s, true);
939 if (ret == -EAGAIN) {
940 struct io_uring_sqe *sqe_copy;
942 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
944 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
947 memcpy(&req->submit, s, sizeof(*s));
948 INIT_WORK(&req->work, io_sq_wq_submit_work);
949 queue_work(ctx->sqo_wq, &req->work);
959 static void io_commit_sqring(struct io_ring_ctx *ctx)
961 struct io_sq_ring *ring = ctx->sq_ring;
963 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
965 * Ensure any loads from the SQEs are done at this point,
966 * since once we write the new head, the application could
967 * write new data to them.
969 smp_store_release(&ring->r.head, ctx->cached_sq_head);
972 * write side barrier of head update, app has read side. See
973 * comment at the top of this file
980 * Undo last io_get_sqring()
982 static void io_drop_sqring(struct io_ring_ctx *ctx)
984 ctx->cached_sq_head--;
988 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
989 * that is mapped by userspace. This means that care needs to be taken to
990 * ensure that reads are stable, as we cannot rely on userspace always
991 * being a good citizen. If members of the sqe are validated and then later
992 * used, it's important that those reads are done through READ_ONCE() to
993 * prevent a re-load down the line.
995 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
997 struct io_sq_ring *ring = ctx->sq_ring;
1001 * The cached sq head (or cq tail) serves two purposes:
1003 * 1) allows us to batch the cost of updating the user visible
1005 * 2) allows the kernel side to track the head on its own, even
1006 * though the application is the one updating it.
1008 head = ctx->cached_sq_head;
1009 /* See comment at the top of this file */
1011 if (head == READ_ONCE(ring->r.tail))
1014 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
1015 if (head < ctx->sq_entries) {
1017 s->sqe = &ctx->sq_sqes[head];
1018 ctx->cached_sq_head++;
1022 /* drop invalid entries */
1023 ctx->cached_sq_head++;
1025 /* See comment at the top of this file */
1030 static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
1032 int i, ret = 0, submit = 0;
1033 struct blk_plug plug;
1035 if (to_submit > IO_PLUG_THRESHOLD)
1036 blk_start_plug(&plug);
1038 for (i = 0; i < to_submit; i++) {
1039 struct sqe_submit s;
1041 if (!io_get_sqring(ctx, &s))
1045 s.needs_lock = false;
1047 ret = io_submit_sqe(ctx, &s);
1049 io_drop_sqring(ctx);
1055 io_commit_sqring(ctx);
1057 if (to_submit > IO_PLUG_THRESHOLD)
1058 blk_finish_plug(&plug);
1060 return submit ? submit : ret;
1063 static unsigned io_cqring_events(struct io_cq_ring *ring)
1065 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
1069 * Wait until events become available, if we don't already have some. The
1070 * application must reap them itself, as they reside on the shared cq ring.
1072 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
1073 const sigset_t __user *sig, size_t sigsz)
1075 struct io_cq_ring *ring = ctx->cq_ring;
1076 sigset_t ksigmask, sigsaved;
1080 /* See comment at the top of this file */
1082 if (io_cqring_events(ring) >= min_events)
1086 ret = set_user_sigmask(sig, &ksigmask, &sigsaved, sigsz);
1092 prepare_to_wait(&ctx->wait, &wait, TASK_INTERRUPTIBLE);
1095 /* See comment at the top of this file */
1097 if (io_cqring_events(ring) >= min_events)
1103 if (signal_pending(current))
1107 finish_wait(&ctx->wait, &wait);
1110 restore_user_sigmask(sig, &sigsaved);
1112 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
1115 static int io_sq_offload_start(struct io_ring_ctx *ctx)
1119 mmgrab(current->mm);
1120 ctx->sqo_mm = current->mm;
1122 /* Do QD, or 2 * CPUS, whatever is smallest */
1123 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
1124 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
1132 mmdrop(ctx->sqo_mm);
1137 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
1139 atomic_long_sub(nr_pages, &user->locked_vm);
1142 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
1144 unsigned long page_limit, cur_pages, new_pages;
1146 /* Don't allow more pages than we can safely lock */
1147 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1150 cur_pages = atomic_long_read(&user->locked_vm);
1151 new_pages = cur_pages + nr_pages;
1152 if (new_pages > page_limit)
1154 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
1155 new_pages) != cur_pages);
1160 static void io_mem_free(void *ptr)
1162 struct page *page = virt_to_head_page(ptr);
1164 if (put_page_testzero(page))
1165 free_compound_page(page);
1168 static void *io_mem_alloc(size_t size)
1170 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
1173 return (void *) __get_free_pages(gfp_flags, get_order(size));
1176 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
1178 struct io_sq_ring *sq_ring;
1179 struct io_cq_ring *cq_ring;
1182 bytes = struct_size(sq_ring, array, sq_entries);
1183 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
1184 bytes += struct_size(cq_ring, cqes, cq_entries);
1186 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
1189 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
1192 destroy_workqueue(ctx->sqo_wq);
1194 mmdrop(ctx->sqo_mm);
1196 io_iopoll_reap_events(ctx);
1198 #if defined(CONFIG_UNIX)
1200 sock_release(ctx->ring_sock);
1203 io_mem_free(ctx->sq_ring);
1204 io_mem_free(ctx->sq_sqes);
1205 io_mem_free(ctx->cq_ring);
1207 percpu_ref_exit(&ctx->refs);
1208 if (ctx->account_mem)
1209 io_unaccount_mem(ctx->user,
1210 ring_pages(ctx->sq_entries, ctx->cq_entries));
1211 free_uid(ctx->user);
1215 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
1217 struct io_ring_ctx *ctx = file->private_data;
1220 poll_wait(file, &ctx->cq_wait, wait);
1221 /* See comment at the top of this file */
1223 if (READ_ONCE(ctx->sq_ring->r.tail) + 1 != ctx->cached_sq_head)
1224 mask |= EPOLLOUT | EPOLLWRNORM;
1225 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
1226 mask |= EPOLLIN | EPOLLRDNORM;
1231 static int io_uring_fasync(int fd, struct file *file, int on)
1233 struct io_ring_ctx *ctx = file->private_data;
1235 return fasync_helper(fd, file, on, &ctx->cq_fasync);
1238 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
1240 mutex_lock(&ctx->uring_lock);
1241 percpu_ref_kill(&ctx->refs);
1242 mutex_unlock(&ctx->uring_lock);
1244 io_iopoll_reap_events(ctx);
1245 wait_for_completion(&ctx->ctx_done);
1246 io_ring_ctx_free(ctx);
1249 static int io_uring_release(struct inode *inode, struct file *file)
1251 struct io_ring_ctx *ctx = file->private_data;
1253 file->private_data = NULL;
1254 io_ring_ctx_wait_and_kill(ctx);
1258 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
1260 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
1261 unsigned long sz = vma->vm_end - vma->vm_start;
1262 struct io_ring_ctx *ctx = file->private_data;
1268 case IORING_OFF_SQ_RING:
1271 case IORING_OFF_SQES:
1274 case IORING_OFF_CQ_RING:
1281 page = virt_to_head_page(ptr);
1282 if (sz > (PAGE_SIZE << compound_order(page)))
1285 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
1286 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
1289 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
1290 u32, min_complete, u32, flags, const sigset_t __user *, sig,
1293 struct io_ring_ctx *ctx;
1298 if (flags & ~IORING_ENTER_GETEVENTS)
1306 if (f.file->f_op != &io_uring_fops)
1310 ctx = f.file->private_data;
1311 if (!percpu_ref_tryget(&ctx->refs))
1316 to_submit = min(to_submit, ctx->sq_entries);
1318 mutex_lock(&ctx->uring_lock);
1319 submitted = io_ring_submit(ctx, to_submit);
1320 mutex_unlock(&ctx->uring_lock);
1325 if (flags & IORING_ENTER_GETEVENTS) {
1326 unsigned nr_events = 0;
1328 min_complete = min(min_complete, ctx->cq_entries);
1331 * The application could have included the 'to_submit' count
1332 * in how many events it wanted to wait for. If we failed to
1333 * submit the desired count, we may need to adjust the number
1334 * of events to poll/wait for.
1336 if (submitted < to_submit)
1337 min_complete = min_t(unsigned, submitted, min_complete);
1339 if (ctx->flags & IORING_SETUP_IOPOLL) {
1340 mutex_lock(&ctx->uring_lock);
1341 ret = io_iopoll_check(ctx, &nr_events, min_complete);
1342 mutex_unlock(&ctx->uring_lock);
1344 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
1349 io_ring_drop_ctx_refs(ctx, 1);
1352 return submitted ? submitted : ret;
1355 static const struct file_operations io_uring_fops = {
1356 .release = io_uring_release,
1357 .mmap = io_uring_mmap,
1358 .poll = io_uring_poll,
1359 .fasync = io_uring_fasync,
1362 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
1363 struct io_uring_params *p)
1365 struct io_sq_ring *sq_ring;
1366 struct io_cq_ring *cq_ring;
1369 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
1373 ctx->sq_ring = sq_ring;
1374 sq_ring->ring_mask = p->sq_entries - 1;
1375 sq_ring->ring_entries = p->sq_entries;
1376 ctx->sq_mask = sq_ring->ring_mask;
1377 ctx->sq_entries = sq_ring->ring_entries;
1379 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
1380 if (size == SIZE_MAX)
1383 ctx->sq_sqes = io_mem_alloc(size);
1384 if (!ctx->sq_sqes) {
1385 io_mem_free(ctx->sq_ring);
1389 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
1391 io_mem_free(ctx->sq_ring);
1392 io_mem_free(ctx->sq_sqes);
1396 ctx->cq_ring = cq_ring;
1397 cq_ring->ring_mask = p->cq_entries - 1;
1398 cq_ring->ring_entries = p->cq_entries;
1399 ctx->cq_mask = cq_ring->ring_mask;
1400 ctx->cq_entries = cq_ring->ring_entries;
1405 * Allocate an anonymous fd, this is what constitutes the application
1406 * visible backing of an io_uring instance. The application mmaps this
1407 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
1408 * we have to tie this fd to a socket for file garbage collection purposes.
1410 static int io_uring_get_fd(struct io_ring_ctx *ctx)
1415 #if defined(CONFIG_UNIX)
1416 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
1422 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
1426 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
1427 O_RDWR | O_CLOEXEC);
1430 ret = PTR_ERR(file);
1434 #if defined(CONFIG_UNIX)
1435 ctx->ring_sock->file = file;
1437 fd_install(ret, file);
1440 #if defined(CONFIG_UNIX)
1441 sock_release(ctx->ring_sock);
1442 ctx->ring_sock = NULL;
1447 static int io_uring_create(unsigned entries, struct io_uring_params *p)
1449 struct user_struct *user = NULL;
1450 struct io_ring_ctx *ctx;
1454 if (!entries || entries > IORING_MAX_ENTRIES)
1458 * Use twice as many entries for the CQ ring. It's possible for the
1459 * application to drive a higher depth than the size of the SQ ring,
1460 * since the sqes are only used at submission time. This allows for
1461 * some flexibility in overcommitting a bit.
1463 p->sq_entries = roundup_pow_of_two(entries);
1464 p->cq_entries = 2 * p->sq_entries;
1466 user = get_uid(current_user());
1467 account_mem = !capable(CAP_IPC_LOCK);
1470 ret = io_account_mem(user,
1471 ring_pages(p->sq_entries, p->cq_entries));
1478 ctx = io_ring_ctx_alloc(p);
1481 io_unaccount_mem(user, ring_pages(p->sq_entries,
1486 ctx->compat = in_compat_syscall();
1487 ctx->account_mem = account_mem;
1490 ret = io_allocate_scq_urings(ctx, p);
1494 ret = io_sq_offload_start(ctx);
1498 ret = io_uring_get_fd(ctx);
1502 memset(&p->sq_off, 0, sizeof(p->sq_off));
1503 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
1504 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
1505 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
1506 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
1507 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
1508 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
1509 p->sq_off.array = offsetof(struct io_sq_ring, array);
1511 memset(&p->cq_off, 0, sizeof(p->cq_off));
1512 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
1513 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
1514 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
1515 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
1516 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
1517 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
1520 io_ring_ctx_wait_and_kill(ctx);
1525 * Sets up an aio uring context, and returns the fd. Applications asks for a
1526 * ring size, we return the actual sq/cq ring sizes (among other things) in the
1527 * params structure passed in.
1529 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
1531 struct io_uring_params p;
1535 if (copy_from_user(&p, params, sizeof(p)))
1537 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
1542 if (p.flags & ~IORING_SETUP_IOPOLL)
1545 ret = io_uring_create(entries, &p);
1549 if (copy_to_user(params, &p, sizeof(p)))
1555 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
1556 struct io_uring_params __user *, params)
1558 return io_uring_setup(entries, params);
1561 static int __init io_uring_init(void)
1563 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
1566 __initcall(io_uring_init);