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/kthread.h>
48 #include <linux/blkdev.h>
49 #include <linux/bvec.h>
50 #include <linux/net.h>
52 #include <net/af_unix.h>
54 #include <linux/anon_inodes.h>
55 #include <linux/sched/mm.h>
56 #include <linux/uaccess.h>
57 #include <linux/nospec.h>
58 #include <linux/sizes.h>
59 #include <linux/hugetlb.h>
61 #include <uapi/linux/io_uring.h>
65 #define IORING_MAX_ENTRIES 4096
66 #define IORING_MAX_FIXED_FILES 1024
69 u32 head ____cacheline_aligned_in_smp;
70 u32 tail ____cacheline_aligned_in_smp;
87 struct io_uring_cqe cqes[];
90 struct io_mapped_ubuf {
94 unsigned int nr_bvecs;
99 struct percpu_ref refs;
100 } ____cacheline_aligned_in_smp;
108 struct io_sq_ring *sq_ring;
109 unsigned cached_sq_head;
112 unsigned sq_thread_idle;
113 struct io_uring_sqe *sq_sqes;
114 } ____cacheline_aligned_in_smp;
117 struct workqueue_struct *sqo_wq;
118 struct task_struct *sqo_thread; /* if using sq thread polling */
119 struct mm_struct *sqo_mm;
120 wait_queue_head_t sqo_wait;
125 struct io_cq_ring *cq_ring;
126 unsigned cached_cq_tail;
129 struct wait_queue_head cq_wait;
130 struct fasync_struct *cq_fasync;
131 } ____cacheline_aligned_in_smp;
134 * If used, fixed file set. Writers must ensure that ->refs is dead,
135 * readers must ensure that ->refs is alive as long as the file* is
136 * used. Only updated through io_uring_register(2).
138 struct file **user_files;
139 unsigned nr_user_files;
141 /* if used, fixed mapped user buffers */
142 unsigned nr_user_bufs;
143 struct io_mapped_ubuf *user_bufs;
145 struct user_struct *user;
147 struct completion ctx_done;
150 struct mutex uring_lock;
151 wait_queue_head_t wait;
152 } ____cacheline_aligned_in_smp;
155 spinlock_t completion_lock;
156 bool poll_multi_file;
158 * ->poll_list is protected by the ctx->uring_lock for
159 * io_uring instances that don't use IORING_SETUP_SQPOLL.
160 * For SQPOLL, only the single threaded io_sq_thread() will
161 * manipulate the list, hence no extra locking is needed there.
163 struct list_head poll_list;
164 } ____cacheline_aligned_in_smp;
166 #if defined(CONFIG_UNIX)
167 struct socket *ring_sock;
172 const struct io_uring_sqe *sqe;
173 unsigned short index;
176 bool needs_fixed_file;
182 struct sqe_submit submit;
184 struct io_ring_ctx *ctx;
185 struct list_head list;
187 #define REQ_F_FORCE_NONBLOCK 1 /* inline submission attempt */
188 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
189 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
193 struct work_struct work;
196 #define IO_PLUG_THRESHOLD 2
197 #define IO_IOPOLL_BATCH 8
199 struct io_submit_state {
200 struct blk_plug plug;
203 * io_kiocb alloc cache
205 void *reqs[IO_IOPOLL_BATCH];
206 unsigned int free_reqs;
207 unsigned int cur_req;
210 * File reference cache
214 unsigned int has_refs;
215 unsigned int used_refs;
216 unsigned int ios_left;
219 static struct kmem_cache *req_cachep;
221 static const struct file_operations io_uring_fops;
223 struct sock *io_uring_get_socket(struct file *file)
225 #if defined(CONFIG_UNIX)
226 if (file->f_op == &io_uring_fops) {
227 struct io_ring_ctx *ctx = file->private_data;
229 return ctx->ring_sock->sk;
234 EXPORT_SYMBOL(io_uring_get_socket);
236 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
238 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
240 complete(&ctx->ctx_done);
243 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
245 struct io_ring_ctx *ctx;
247 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
251 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 0, GFP_KERNEL)) {
256 ctx->flags = p->flags;
257 init_waitqueue_head(&ctx->cq_wait);
258 init_completion(&ctx->ctx_done);
259 mutex_init(&ctx->uring_lock);
260 init_waitqueue_head(&ctx->wait);
261 spin_lock_init(&ctx->completion_lock);
262 INIT_LIST_HEAD(&ctx->poll_list);
266 static void io_commit_cqring(struct io_ring_ctx *ctx)
268 struct io_cq_ring *ring = ctx->cq_ring;
270 if (ctx->cached_cq_tail != READ_ONCE(ring->r.tail)) {
271 /* order cqe stores with ring update */
272 smp_store_release(&ring->r.tail, ctx->cached_cq_tail);
275 * Write sider barrier of tail update, app has read side. See
276 * comment at the top of this file.
280 if (wq_has_sleeper(&ctx->cq_wait)) {
281 wake_up_interruptible(&ctx->cq_wait);
282 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
287 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
289 struct io_cq_ring *ring = ctx->cq_ring;
292 tail = ctx->cached_cq_tail;
293 /* See comment at the top of the file */
295 if (tail + 1 == READ_ONCE(ring->r.head))
298 ctx->cached_cq_tail++;
299 return &ring->cqes[tail & ctx->cq_mask];
302 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
303 long res, unsigned ev_flags)
305 struct io_uring_cqe *cqe;
308 * If we can't get a cq entry, userspace overflowed the
309 * submission (by quite a lot). Increment the overflow count in
312 cqe = io_get_cqring(ctx);
314 WRITE_ONCE(cqe->user_data, ki_user_data);
315 WRITE_ONCE(cqe->res, res);
316 WRITE_ONCE(cqe->flags, ev_flags);
318 unsigned overflow = READ_ONCE(ctx->cq_ring->overflow);
320 WRITE_ONCE(ctx->cq_ring->overflow, overflow + 1);
324 static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 ki_user_data,
325 long res, unsigned ev_flags)
329 spin_lock_irqsave(&ctx->completion_lock, flags);
330 io_cqring_fill_event(ctx, ki_user_data, res, ev_flags);
331 io_commit_cqring(ctx);
332 spin_unlock_irqrestore(&ctx->completion_lock, flags);
334 if (waitqueue_active(&ctx->wait))
336 if (waitqueue_active(&ctx->sqo_wait))
337 wake_up(&ctx->sqo_wait);
340 static void io_ring_drop_ctx_refs(struct io_ring_ctx *ctx, unsigned refs)
342 percpu_ref_put_many(&ctx->refs, refs);
344 if (waitqueue_active(&ctx->wait))
348 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
349 struct io_submit_state *state)
351 struct io_kiocb *req;
353 if (!percpu_ref_tryget(&ctx->refs))
357 req = kmem_cache_alloc(req_cachep, __GFP_NOWARN);
360 } else if (!state->free_reqs) {
364 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
365 ret = kmem_cache_alloc_bulk(req_cachep, __GFP_NOWARN, sz,
367 if (unlikely(ret <= 0))
369 state->free_reqs = ret - 1;
371 req = state->reqs[0];
373 req = state->reqs[state->cur_req];
382 io_ring_drop_ctx_refs(ctx, 1);
386 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
389 kmem_cache_free_bulk(req_cachep, *nr, reqs);
390 io_ring_drop_ctx_refs(ctx, *nr);
395 static void io_free_req(struct io_kiocb *req)
397 io_ring_drop_ctx_refs(req->ctx, 1);
398 kmem_cache_free(req_cachep, req);
402 * Find and free completed poll iocbs
404 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
405 struct list_head *done)
407 void *reqs[IO_IOPOLL_BATCH];
408 int file_count, to_free;
409 struct file *file = NULL;
410 struct io_kiocb *req;
412 file_count = to_free = 0;
413 while (!list_empty(done)) {
414 req = list_first_entry(done, struct io_kiocb, list);
415 list_del(&req->list);
417 io_cqring_fill_event(ctx, req->user_data, req->error, 0);
419 reqs[to_free++] = req;
423 * Batched puts of the same file, to avoid dirtying the
424 * file usage count multiple times, if avoidable.
426 if (!(req->flags & REQ_F_FIXED_FILE)) {
428 file = req->rw.ki_filp;
430 } else if (file == req->rw.ki_filp) {
433 fput_many(file, file_count);
434 file = req->rw.ki_filp;
439 if (to_free == ARRAY_SIZE(reqs))
440 io_free_req_many(ctx, reqs, &to_free);
442 io_commit_cqring(ctx);
445 fput_many(file, file_count);
446 io_free_req_many(ctx, reqs, &to_free);
449 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
452 struct io_kiocb *req, *tmp;
458 * Only spin for completions if we don't have multiple devices hanging
459 * off our complete list, and we're under the requested amount.
461 spin = !ctx->poll_multi_file && *nr_events < min;
464 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
465 struct kiocb *kiocb = &req->rw;
468 * Move completed entries to our local list. If we find a
469 * request that requires polling, break out and complete
470 * the done list first, if we have entries there.
472 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
473 list_move_tail(&req->list, &done);
476 if (!list_empty(&done))
479 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
488 if (!list_empty(&done))
489 io_iopoll_complete(ctx, nr_events, &done);
495 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
496 * non-spinning poll check - we'll still enter the driver poll loop, but only
497 * as a non-spinning completion check.
499 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
502 while (!list_empty(&ctx->poll_list)) {
505 ret = io_do_iopoll(ctx, nr_events, min);
508 if (!min || *nr_events >= min)
516 * We can't just wait for polled events to come to us, we have to actively
517 * find and complete them.
519 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
521 if (!(ctx->flags & IORING_SETUP_IOPOLL))
524 mutex_lock(&ctx->uring_lock);
525 while (!list_empty(&ctx->poll_list)) {
526 unsigned int nr_events = 0;
528 io_iopoll_getevents(ctx, &nr_events, 1);
530 mutex_unlock(&ctx->uring_lock);
533 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
541 if (*nr_events < min)
542 tmin = min - *nr_events;
544 ret = io_iopoll_getevents(ctx, nr_events, tmin);
548 } while (min && !*nr_events && !need_resched());
553 static void kiocb_end_write(struct kiocb *kiocb)
555 if (kiocb->ki_flags & IOCB_WRITE) {
556 struct inode *inode = file_inode(kiocb->ki_filp);
559 * Tell lockdep we inherited freeze protection from submission
562 if (S_ISREG(inode->i_mode))
563 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
564 file_end_write(kiocb->ki_filp);
568 static void io_fput(struct io_kiocb *req)
570 if (!(req->flags & REQ_F_FIXED_FILE))
571 fput(req->rw.ki_filp);
574 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
576 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
578 kiocb_end_write(kiocb);
581 io_cqring_add_event(req->ctx, req->user_data, res, 0);
585 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
587 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
589 kiocb_end_write(kiocb);
593 req->flags |= REQ_F_IOPOLL_COMPLETED;
597 * After the iocb has been issued, it's safe to be found on the poll list.
598 * Adding the kiocb to the list AFTER submission ensures that we don't
599 * find it from a io_iopoll_getevents() thread before the issuer is done
600 * accessing the kiocb cookie.
602 static void io_iopoll_req_issued(struct io_kiocb *req)
604 struct io_ring_ctx *ctx = req->ctx;
607 * Track whether we have multiple files in our lists. This will impact
608 * how we do polling eventually, not spinning if we're on potentially
611 if (list_empty(&ctx->poll_list)) {
612 ctx->poll_multi_file = false;
613 } else if (!ctx->poll_multi_file) {
614 struct io_kiocb *list_req;
616 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
618 if (list_req->rw.ki_filp != req->rw.ki_filp)
619 ctx->poll_multi_file = true;
623 * For fast devices, IO may have already completed. If it has, add
624 * it to the front so we find it first.
626 if (req->flags & REQ_F_IOPOLL_COMPLETED)
627 list_add(&req->list, &ctx->poll_list);
629 list_add_tail(&req->list, &ctx->poll_list);
632 static void io_file_put(struct io_submit_state *state, struct file *file)
636 } else if (state->file) {
637 int diff = state->has_refs - state->used_refs;
640 fput_many(state->file, diff);
646 * Get as many references to a file as we have IOs left in this submission,
647 * assuming most submissions are for one file, or at least that each file
648 * has more than one submission.
650 static struct file *io_file_get(struct io_submit_state *state, int fd)
656 if (state->fd == fd) {
661 io_file_put(state, NULL);
663 state->file = fget_many(fd, state->ios_left);
668 state->has_refs = state->ios_left;
669 state->used_refs = 1;
675 * If we tracked the file through the SCM inflight mechanism, we could support
676 * any file. For now, just ensure that anything potentially problematic is done
679 static bool io_file_supports_async(struct file *file)
681 umode_t mode = file_inode(file)->i_mode;
683 if (S_ISBLK(mode) || S_ISCHR(mode))
685 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
691 static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
692 bool force_nonblock, struct io_submit_state *state)
694 const struct io_uring_sqe *sqe = s->sqe;
695 struct io_ring_ctx *ctx = req->ctx;
696 struct kiocb *kiocb = &req->rw;
697 unsigned ioprio, flags;
700 /* For -EAGAIN retry, everything is already prepped */
704 flags = READ_ONCE(sqe->flags);
705 fd = READ_ONCE(sqe->fd);
707 if (flags & IOSQE_FIXED_FILE) {
708 if (unlikely(!ctx->user_files ||
709 (unsigned) fd >= ctx->nr_user_files))
711 kiocb->ki_filp = ctx->user_files[fd];
712 req->flags |= REQ_F_FIXED_FILE;
714 if (s->needs_fixed_file)
716 kiocb->ki_filp = io_file_get(state, fd);
717 if (unlikely(!kiocb->ki_filp))
719 if (force_nonblock && !io_file_supports_async(kiocb->ki_filp))
720 force_nonblock = false;
722 kiocb->ki_pos = READ_ONCE(sqe->off);
723 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
724 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
726 ioprio = READ_ONCE(sqe->ioprio);
728 ret = ioprio_check_cap(ioprio);
732 kiocb->ki_ioprio = ioprio;
734 kiocb->ki_ioprio = get_current_ioprio();
736 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
739 if (force_nonblock) {
740 kiocb->ki_flags |= IOCB_NOWAIT;
741 req->flags |= REQ_F_FORCE_NONBLOCK;
743 if (ctx->flags & IORING_SETUP_IOPOLL) {
745 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
746 !kiocb->ki_filp->f_op->iopoll)
750 kiocb->ki_flags |= IOCB_HIPRI;
751 kiocb->ki_complete = io_complete_rw_iopoll;
753 if (kiocb->ki_flags & IOCB_HIPRI) {
757 kiocb->ki_complete = io_complete_rw;
761 if (!(flags & IOSQE_FIXED_FILE)) {
763 * in case of error, we didn't use this file reference. drop it.
767 io_file_put(state, kiocb->ki_filp);
772 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
778 case -ERESTARTNOINTR:
779 case -ERESTARTNOHAND:
780 case -ERESTART_RESTARTBLOCK:
782 * We can't just restart the syscall, since previously
783 * submitted sqes may already be in progress. Just fail this
789 kiocb->ki_complete(kiocb, ret, 0);
793 static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
794 const struct io_uring_sqe *sqe,
795 struct iov_iter *iter)
797 size_t len = READ_ONCE(sqe->len);
798 struct io_mapped_ubuf *imu;
799 unsigned index, buf_index;
803 /* attempt to use fixed buffers without having provided iovecs */
804 if (unlikely(!ctx->user_bufs))
807 buf_index = READ_ONCE(sqe->buf_index);
808 if (unlikely(buf_index >= ctx->nr_user_bufs))
811 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
812 imu = &ctx->user_bufs[index];
813 buf_addr = READ_ONCE(sqe->addr);
816 if (buf_addr + len < buf_addr)
818 /* not inside the mapped region */
819 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
823 * May not be a start of buffer, set size appropriately
824 * and advance us to the beginning.
826 offset = buf_addr - imu->ubuf;
827 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
829 iov_iter_advance(iter, offset);
833 static int io_import_iovec(struct io_ring_ctx *ctx, int rw,
834 const struct sqe_submit *s, struct iovec **iovec,
835 struct iov_iter *iter)
837 const struct io_uring_sqe *sqe = s->sqe;
838 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
839 size_t sqe_len = READ_ONCE(sqe->len);
843 * We're reading ->opcode for the second time, but the first read
844 * doesn't care whether it's _FIXED or not, so it doesn't matter
845 * whether ->opcode changes concurrently. The first read does care
846 * about whether it is a READ or a WRITE, so we don't trust this read
847 * for that purpose and instead let the caller pass in the read/write
850 opcode = READ_ONCE(sqe->opcode);
851 if (opcode == IORING_OP_READ_FIXED ||
852 opcode == IORING_OP_WRITE_FIXED) {
853 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
863 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
867 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
870 static ssize_t io_read(struct io_kiocb *req, const struct sqe_submit *s,
871 bool force_nonblock, struct io_submit_state *state)
873 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
874 struct kiocb *kiocb = &req->rw;
875 struct iov_iter iter;
879 ret = io_prep_rw(req, s, force_nonblock, state);
882 file = kiocb->ki_filp;
885 if (unlikely(!(file->f_mode & FMODE_READ)))
888 if (unlikely(!file->f_op->read_iter))
891 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
895 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_iter_count(&iter));
899 /* Catch -EAGAIN return for forced non-blocking submission */
900 ret2 = call_read_iter(file, kiocb, &iter);
901 if (!force_nonblock || ret2 != -EAGAIN)
902 io_rw_done(kiocb, ret2);
908 /* Hold on to the file for -EAGAIN */
909 if (unlikely(ret && ret != -EAGAIN))
914 static ssize_t io_write(struct io_kiocb *req, const struct sqe_submit *s,
915 bool force_nonblock, struct io_submit_state *state)
917 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
918 struct kiocb *kiocb = &req->rw;
919 struct iov_iter iter;
923 ret = io_prep_rw(req, s, force_nonblock, state);
926 /* Hold on to the file for -EAGAIN */
927 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT))
931 file = kiocb->ki_filp;
932 if (unlikely(!(file->f_mode & FMODE_WRITE)))
935 if (unlikely(!file->f_op->write_iter))
938 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
942 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos,
943 iov_iter_count(&iter));
946 * Open-code file_start_write here to grab freeze protection,
947 * which will be released by another thread in
948 * io_complete_rw(). Fool lockdep by telling it the lock got
949 * released so that it doesn't complain about the held lock when
950 * we return to userspace.
952 if (S_ISREG(file_inode(file)->i_mode)) {
953 __sb_start_write(file_inode(file)->i_sb,
954 SB_FREEZE_WRITE, true);
955 __sb_writers_release(file_inode(file)->i_sb,
958 kiocb->ki_flags |= IOCB_WRITE;
959 io_rw_done(kiocb, call_write_iter(file, kiocb, &iter));
969 * IORING_OP_NOP just posts a completion event, nothing else.
971 static int io_nop(struct io_kiocb *req, u64 user_data)
973 struct io_ring_ctx *ctx = req->ctx;
976 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
980 * Twilight zone - it's possible that someone issued an opcode that
981 * has a file attached, then got -EAGAIN on submission, and changed
982 * the sqe before we retried it from async context. Avoid dropping
983 * a file reference for this malicious case, and flag the error.
985 if (req->rw.ki_filp) {
989 io_cqring_add_event(ctx, user_data, err, 0);
994 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
996 struct io_ring_ctx *ctx = req->ctx;
1000 /* Prep already done */
1001 if (req->rw.ki_filp)
1004 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1006 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1009 fd = READ_ONCE(sqe->fd);
1010 flags = READ_ONCE(sqe->flags);
1012 if (flags & IOSQE_FIXED_FILE) {
1013 if (unlikely(!ctx->user_files || fd >= ctx->nr_user_files))
1015 req->rw.ki_filp = ctx->user_files[fd];
1016 req->flags |= REQ_F_FIXED_FILE;
1018 req->rw.ki_filp = fget(fd);
1019 if (unlikely(!req->rw.ki_filp))
1026 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1027 bool force_nonblock)
1029 loff_t sqe_off = READ_ONCE(sqe->off);
1030 loff_t sqe_len = READ_ONCE(sqe->len);
1031 loff_t end = sqe_off + sqe_len;
1032 unsigned fsync_flags;
1035 fsync_flags = READ_ONCE(sqe->fsync_flags);
1036 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1039 ret = io_prep_fsync(req, sqe);
1043 /* fsync always requires a blocking context */
1047 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1048 end > 0 ? end : LLONG_MAX,
1049 fsync_flags & IORING_FSYNC_DATASYNC);
1052 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
1057 static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
1058 const struct sqe_submit *s, bool force_nonblock,
1059 struct io_submit_state *state)
1064 if (unlikely(s->index >= ctx->sq_entries))
1066 req->user_data = READ_ONCE(s->sqe->user_data);
1068 opcode = READ_ONCE(s->sqe->opcode);
1071 ret = io_nop(req, req->user_data);
1073 case IORING_OP_READV:
1074 if (unlikely(s->sqe->buf_index))
1076 ret = io_read(req, s, force_nonblock, state);
1078 case IORING_OP_WRITEV:
1079 if (unlikely(s->sqe->buf_index))
1081 ret = io_write(req, s, force_nonblock, state);
1083 case IORING_OP_READ_FIXED:
1084 ret = io_read(req, s, force_nonblock, state);
1086 case IORING_OP_WRITE_FIXED:
1087 ret = io_write(req, s, force_nonblock, state);
1089 case IORING_OP_FSYNC:
1090 ret = io_fsync(req, s->sqe, force_nonblock);
1100 if (ctx->flags & IORING_SETUP_IOPOLL) {
1101 if (req->error == -EAGAIN)
1104 /* workqueue context doesn't hold uring_lock, grab it now */
1106 mutex_lock(&ctx->uring_lock);
1107 io_iopoll_req_issued(req);
1109 mutex_unlock(&ctx->uring_lock);
1115 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
1117 u8 opcode = READ_ONCE(sqe->opcode);
1119 return !(opcode == IORING_OP_READ_FIXED ||
1120 opcode == IORING_OP_WRITE_FIXED);
1123 static void io_sq_wq_submit_work(struct work_struct *work)
1125 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1126 struct sqe_submit *s = &req->submit;
1127 const struct io_uring_sqe *sqe = s->sqe;
1128 struct io_ring_ctx *ctx = req->ctx;
1129 mm_segment_t old_fs;
1133 /* Ensure we clear previously set forced non-block flag */
1134 req->flags &= ~REQ_F_FORCE_NONBLOCK;
1135 req->rw.ki_flags &= ~IOCB_NOWAIT;
1137 s->needs_lock = true;
1138 s->has_user = false;
1141 * If we're doing IO to fixed buffers, we don't need to get/set
1144 needs_user = io_sqe_needs_user(s->sqe);
1146 if (!mmget_not_zero(ctx->sqo_mm)) {
1150 use_mm(ctx->sqo_mm);
1157 ret = __io_submit_sqe(ctx, req, s, false, NULL);
1159 * We can get EAGAIN for polled IO even though we're forcing
1160 * a sync submission from here, since we can't wait for
1161 * request slots on the block side.
1170 unuse_mm(ctx->sqo_mm);
1175 io_cqring_add_event(ctx, sqe->user_data, ret, 0);
1179 /* async context always use a copy of the sqe */
1183 static int io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
1184 struct io_submit_state *state)
1186 struct io_kiocb *req;
1189 /* enforce forwards compatibility on users */
1190 if (unlikely(s->sqe->flags & ~IOSQE_FIXED_FILE))
1193 req = io_get_req(ctx, state);
1197 req->rw.ki_filp = NULL;
1199 ret = __io_submit_sqe(ctx, req, s, true, state);
1200 if (ret == -EAGAIN) {
1201 struct io_uring_sqe *sqe_copy;
1203 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1205 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
1208 memcpy(&req->submit, s, sizeof(*s));
1209 INIT_WORK(&req->work, io_sq_wq_submit_work);
1210 queue_work(ctx->sqo_wq, &req->work);
1221 * Batched submission is done, ensure local IO is flushed out.
1223 static void io_submit_state_end(struct io_submit_state *state)
1225 blk_finish_plug(&state->plug);
1226 io_file_put(state, NULL);
1227 if (state->free_reqs)
1228 kmem_cache_free_bulk(req_cachep, state->free_reqs,
1229 &state->reqs[state->cur_req]);
1233 * Start submission side cache.
1235 static void io_submit_state_start(struct io_submit_state *state,
1236 struct io_ring_ctx *ctx, unsigned max_ios)
1238 blk_start_plug(&state->plug);
1239 state->free_reqs = 0;
1241 state->ios_left = max_ios;
1244 static void io_commit_sqring(struct io_ring_ctx *ctx)
1246 struct io_sq_ring *ring = ctx->sq_ring;
1248 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
1250 * Ensure any loads from the SQEs are done at this point,
1251 * since once we write the new head, the application could
1252 * write new data to them.
1254 smp_store_release(&ring->r.head, ctx->cached_sq_head);
1257 * write side barrier of head update, app has read side. See
1258 * comment at the top of this file
1265 * Undo last io_get_sqring()
1267 static void io_drop_sqring(struct io_ring_ctx *ctx)
1269 ctx->cached_sq_head--;
1273 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
1274 * that is mapped by userspace. This means that care needs to be taken to
1275 * ensure that reads are stable, as we cannot rely on userspace always
1276 * being a good citizen. If members of the sqe are validated and then later
1277 * used, it's important that those reads are done through READ_ONCE() to
1278 * prevent a re-load down the line.
1280 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
1282 struct io_sq_ring *ring = ctx->sq_ring;
1286 * The cached sq head (or cq tail) serves two purposes:
1288 * 1) allows us to batch the cost of updating the user visible
1290 * 2) allows the kernel side to track the head on its own, even
1291 * though the application is the one updating it.
1293 head = ctx->cached_sq_head;
1294 /* See comment at the top of this file */
1296 if (head == READ_ONCE(ring->r.tail))
1299 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
1300 if (head < ctx->sq_entries) {
1302 s->sqe = &ctx->sq_sqes[head];
1303 ctx->cached_sq_head++;
1307 /* drop invalid entries */
1308 ctx->cached_sq_head++;
1310 /* See comment at the top of this file */
1315 static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
1316 unsigned int nr, bool has_user, bool mm_fault)
1318 struct io_submit_state state, *statep = NULL;
1319 int ret, i, submitted = 0;
1321 if (nr > IO_PLUG_THRESHOLD) {
1322 io_submit_state_start(&state, ctx, nr);
1326 for (i = 0; i < nr; i++) {
1327 if (unlikely(mm_fault)) {
1330 sqes[i].has_user = has_user;
1331 sqes[i].needs_lock = true;
1332 sqes[i].needs_fixed_file = true;
1333 ret = io_submit_sqe(ctx, &sqes[i], statep);
1340 io_cqring_add_event(ctx, sqes[i].sqe->user_data, ret, 0);
1344 io_submit_state_end(&state);
1349 static int io_sq_thread(void *data)
1351 struct sqe_submit sqes[IO_IOPOLL_BATCH];
1352 struct io_ring_ctx *ctx = data;
1353 struct mm_struct *cur_mm = NULL;
1354 mm_segment_t old_fs;
1357 unsigned long timeout;
1362 timeout = inflight = 0;
1363 while (!kthread_should_stop() && !ctx->sqo_stop) {
1364 bool all_fixed, mm_fault = false;
1368 unsigned nr_events = 0;
1370 if (ctx->flags & IORING_SETUP_IOPOLL) {
1372 * We disallow the app entering submit/complete
1373 * with polling, but we still need to lock the
1374 * ring to prevent racing with polled issue
1375 * that got punted to a workqueue.
1377 mutex_lock(&ctx->uring_lock);
1378 io_iopoll_check(ctx, &nr_events, 0);
1379 mutex_unlock(&ctx->uring_lock);
1382 * Normal IO, just pretend everything completed.
1383 * We don't have to poll completions for that.
1385 nr_events = inflight;
1388 inflight -= nr_events;
1390 timeout = jiffies + ctx->sq_thread_idle;
1393 if (!io_get_sqring(ctx, &sqes[0])) {
1395 * We're polling. If we're within the defined idle
1396 * period, then let us spin without work before going
1399 if (inflight || !time_after(jiffies, timeout)) {
1405 * Drop cur_mm before scheduling, we can't hold it for
1406 * long periods (or over schedule()). Do this before
1407 * adding ourselves to the waitqueue, as the unuse/drop
1416 prepare_to_wait(&ctx->sqo_wait, &wait,
1417 TASK_INTERRUPTIBLE);
1419 /* Tell userspace we may need a wakeup call */
1420 ctx->sq_ring->flags |= IORING_SQ_NEED_WAKEUP;
1423 if (!io_get_sqring(ctx, &sqes[0])) {
1424 if (kthread_should_stop()) {
1425 finish_wait(&ctx->sqo_wait, &wait);
1428 if (signal_pending(current))
1429 flush_signals(current);
1431 finish_wait(&ctx->sqo_wait, &wait);
1433 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
1437 finish_wait(&ctx->sqo_wait, &wait);
1439 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
1446 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
1450 if (i == ARRAY_SIZE(sqes))
1452 } while (io_get_sqring(ctx, &sqes[i]));
1454 /* Unless all new commands are FIXED regions, grab mm */
1455 if (!all_fixed && !cur_mm) {
1456 mm_fault = !mmget_not_zero(ctx->sqo_mm);
1458 use_mm(ctx->sqo_mm);
1459 cur_mm = ctx->sqo_mm;
1463 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
1466 /* Commit SQ ring head once we've consumed all SQEs */
1467 io_commit_sqring(ctx);
1478 static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
1480 struct io_submit_state state, *statep = NULL;
1481 int i, ret = 0, submit = 0;
1483 if (to_submit > IO_PLUG_THRESHOLD) {
1484 io_submit_state_start(&state, ctx, to_submit);
1488 for (i = 0; i < to_submit; i++) {
1489 struct sqe_submit s;
1491 if (!io_get_sqring(ctx, &s))
1495 s.needs_lock = false;
1496 s.needs_fixed_file = false;
1498 ret = io_submit_sqe(ctx, &s, statep);
1500 io_drop_sqring(ctx);
1506 io_commit_sqring(ctx);
1509 io_submit_state_end(statep);
1511 return submit ? submit : ret;
1514 static unsigned io_cqring_events(struct io_cq_ring *ring)
1516 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
1520 * Wait until events become available, if we don't already have some. The
1521 * application must reap them itself, as they reside on the shared cq ring.
1523 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
1524 const sigset_t __user *sig, size_t sigsz)
1526 struct io_cq_ring *ring = ctx->cq_ring;
1527 sigset_t ksigmask, sigsaved;
1531 /* See comment at the top of this file */
1533 if (io_cqring_events(ring) >= min_events)
1537 ret = set_user_sigmask(sig, &ksigmask, &sigsaved, sigsz);
1543 prepare_to_wait(&ctx->wait, &wait, TASK_INTERRUPTIBLE);
1546 /* See comment at the top of this file */
1548 if (io_cqring_events(ring) >= min_events)
1554 if (signal_pending(current))
1558 finish_wait(&ctx->wait, &wait);
1561 restore_user_sigmask(sig, &sigsaved);
1563 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
1566 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
1568 #if defined(CONFIG_UNIX)
1569 if (ctx->ring_sock) {
1570 struct sock *sock = ctx->ring_sock->sk;
1571 struct sk_buff *skb;
1573 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
1579 for (i = 0; i < ctx->nr_user_files; i++)
1580 fput(ctx->user_files[i]);
1584 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
1586 if (!ctx->user_files)
1589 __io_sqe_files_unregister(ctx);
1590 kfree(ctx->user_files);
1591 ctx->user_files = NULL;
1592 ctx->nr_user_files = 0;
1596 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
1598 if (ctx->sqo_thread) {
1601 kthread_stop(ctx->sqo_thread);
1602 ctx->sqo_thread = NULL;
1606 static void io_finish_async(struct io_ring_ctx *ctx)
1608 io_sq_thread_stop(ctx);
1611 destroy_workqueue(ctx->sqo_wq);
1616 #if defined(CONFIG_UNIX)
1617 static void io_destruct_skb(struct sk_buff *skb)
1619 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
1621 io_finish_async(ctx);
1622 unix_destruct_scm(skb);
1626 * Ensure the UNIX gc is aware of our file set, so we are certain that
1627 * the io_uring can be safely unregistered on process exit, even if we have
1628 * loops in the file referencing.
1630 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
1632 struct sock *sk = ctx->ring_sock->sk;
1633 struct scm_fp_list *fpl;
1634 struct sk_buff *skb;
1637 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
1638 unsigned long inflight = ctx->user->unix_inflight + nr;
1640 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
1644 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
1648 skb = alloc_skb(0, GFP_KERNEL);
1655 skb->destructor = io_destruct_skb;
1657 fpl->user = get_uid(ctx->user);
1658 for (i = 0; i < nr; i++) {
1659 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
1660 unix_inflight(fpl->user, fpl->fp[i]);
1663 fpl->max = fpl->count = nr;
1664 UNIXCB(skb).fp = fpl;
1665 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
1666 skb_queue_head(&sk->sk_receive_queue, skb);
1668 for (i = 0; i < nr; i++)
1675 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
1676 * causes regular reference counting to break down. We rely on the UNIX
1677 * garbage collection to take care of this problem for us.
1679 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
1681 unsigned left, total;
1685 left = ctx->nr_user_files;
1687 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
1690 ret = __io_sqe_files_scm(ctx, this_files, total);
1694 total += this_files;
1700 while (total < ctx->nr_user_files) {
1701 fput(ctx->user_files[total]);
1708 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
1714 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
1717 __s32 __user *fds = (__s32 __user *) arg;
1721 if (ctx->user_files)
1725 if (nr_args > IORING_MAX_FIXED_FILES)
1728 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
1729 if (!ctx->user_files)
1732 for (i = 0; i < nr_args; i++) {
1734 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
1737 ctx->user_files[i] = fget(fd);
1740 if (!ctx->user_files[i])
1743 * Don't allow io_uring instances to be registered. If UNIX
1744 * isn't enabled, then this causes a reference cycle and this
1745 * instance can never get freed. If UNIX is enabled we'll
1746 * handle it just fine, but there's still no point in allowing
1747 * a ring fd as it doesn't support regular read/write anyway.
1749 if (ctx->user_files[i]->f_op == &io_uring_fops) {
1750 fput(ctx->user_files[i]);
1753 ctx->nr_user_files++;
1758 for (i = 0; i < ctx->nr_user_files; i++)
1759 fput(ctx->user_files[i]);
1761 kfree(ctx->user_files);
1762 ctx->nr_user_files = 0;
1766 ret = io_sqe_files_scm(ctx);
1768 io_sqe_files_unregister(ctx);
1773 static int io_sq_offload_start(struct io_ring_ctx *ctx,
1774 struct io_uring_params *p)
1778 init_waitqueue_head(&ctx->sqo_wait);
1779 mmgrab(current->mm);
1780 ctx->sqo_mm = current->mm;
1782 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
1783 if (!ctx->sq_thread_idle)
1784 ctx->sq_thread_idle = HZ;
1787 if (!cpu_possible(p->sq_thread_cpu))
1790 if (ctx->flags & IORING_SETUP_SQPOLL) {
1791 if (p->flags & IORING_SETUP_SQ_AFF) {
1794 cpu = array_index_nospec(p->sq_thread_cpu, NR_CPUS);
1795 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
1799 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
1802 if (IS_ERR(ctx->sqo_thread)) {
1803 ret = PTR_ERR(ctx->sqo_thread);
1804 ctx->sqo_thread = NULL;
1807 wake_up_process(ctx->sqo_thread);
1808 } else if (p->flags & IORING_SETUP_SQ_AFF) {
1809 /* Can't have SQ_AFF without SQPOLL */
1814 /* Do QD, or 2 * CPUS, whatever is smallest */
1815 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
1816 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
1824 io_sq_thread_stop(ctx);
1825 mmdrop(ctx->sqo_mm);
1830 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
1832 atomic_long_sub(nr_pages, &user->locked_vm);
1835 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
1837 unsigned long page_limit, cur_pages, new_pages;
1839 /* Don't allow more pages than we can safely lock */
1840 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1843 cur_pages = atomic_long_read(&user->locked_vm);
1844 new_pages = cur_pages + nr_pages;
1845 if (new_pages > page_limit)
1847 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
1848 new_pages) != cur_pages);
1853 static void io_mem_free(void *ptr)
1855 struct page *page = virt_to_head_page(ptr);
1857 if (put_page_testzero(page))
1858 free_compound_page(page);
1861 static void *io_mem_alloc(size_t size)
1863 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
1866 return (void *) __get_free_pages(gfp_flags, get_order(size));
1869 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
1871 struct io_sq_ring *sq_ring;
1872 struct io_cq_ring *cq_ring;
1875 bytes = struct_size(sq_ring, array, sq_entries);
1876 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
1877 bytes += struct_size(cq_ring, cqes, cq_entries);
1879 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
1882 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
1886 if (!ctx->user_bufs)
1889 for (i = 0; i < ctx->nr_user_bufs; i++) {
1890 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
1892 for (j = 0; j < imu->nr_bvecs; j++)
1893 put_page(imu->bvec[j].bv_page);
1895 if (ctx->account_mem)
1896 io_unaccount_mem(ctx->user, imu->nr_bvecs);
1901 kfree(ctx->user_bufs);
1902 ctx->user_bufs = NULL;
1903 ctx->nr_user_bufs = 0;
1907 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
1908 void __user *arg, unsigned index)
1910 struct iovec __user *src;
1912 #ifdef CONFIG_COMPAT
1914 struct compat_iovec __user *ciovs;
1915 struct compat_iovec ciov;
1917 ciovs = (struct compat_iovec __user *) arg;
1918 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
1921 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
1922 dst->iov_len = ciov.iov_len;
1926 src = (struct iovec __user *) arg;
1927 if (copy_from_user(dst, &src[index], sizeof(*dst)))
1932 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
1935 struct vm_area_struct **vmas = NULL;
1936 struct page **pages = NULL;
1937 int i, j, got_pages = 0;
1942 if (!nr_args || nr_args > UIO_MAXIOV)
1945 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
1947 if (!ctx->user_bufs)
1950 for (i = 0; i < nr_args; i++) {
1951 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
1952 unsigned long off, start, end, ubuf;
1957 ret = io_copy_iov(ctx, &iov, arg, i);
1962 * Don't impose further limits on the size and buffer
1963 * constraints here, we'll -EINVAL later when IO is
1964 * submitted if they are wrong.
1967 if (!iov.iov_base || !iov.iov_len)
1970 /* arbitrary limit, but we need something */
1971 if (iov.iov_len > SZ_1G)
1974 ubuf = (unsigned long) iov.iov_base;
1975 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
1976 start = ubuf >> PAGE_SHIFT;
1977 nr_pages = end - start;
1979 if (ctx->account_mem) {
1980 ret = io_account_mem(ctx->user, nr_pages);
1986 if (!pages || nr_pages > got_pages) {
1989 pages = kmalloc_array(nr_pages, sizeof(struct page *),
1991 vmas = kmalloc_array(nr_pages,
1992 sizeof(struct vm_area_struct *),
1994 if (!pages || !vmas) {
1996 if (ctx->account_mem)
1997 io_unaccount_mem(ctx->user, nr_pages);
2000 got_pages = nr_pages;
2003 imu->bvec = kmalloc_array(nr_pages, sizeof(struct bio_vec),
2007 if (ctx->account_mem)
2008 io_unaccount_mem(ctx->user, nr_pages);
2013 down_read(¤t->mm->mmap_sem);
2014 pret = get_user_pages_longterm(ubuf, nr_pages, FOLL_WRITE,
2016 if (pret == nr_pages) {
2017 /* don't support file backed memory */
2018 for (j = 0; j < nr_pages; j++) {
2019 struct vm_area_struct *vma = vmas[j];
2022 !is_file_hugepages(vma->vm_file)) {
2028 ret = pret < 0 ? pret : -EFAULT;
2030 up_read(¤t->mm->mmap_sem);
2033 * if we did partial map, or found file backed vmas,
2034 * release any pages we did get
2037 for (j = 0; j < pret; j++)
2040 if (ctx->account_mem)
2041 io_unaccount_mem(ctx->user, nr_pages);
2045 off = ubuf & ~PAGE_MASK;
2047 for (j = 0; j < nr_pages; j++) {
2050 vec_len = min_t(size_t, size, PAGE_SIZE - off);
2051 imu->bvec[j].bv_page = pages[j];
2052 imu->bvec[j].bv_len = vec_len;
2053 imu->bvec[j].bv_offset = off;
2057 /* store original address for later verification */
2059 imu->len = iov.iov_len;
2060 imu->nr_bvecs = nr_pages;
2062 ctx->nr_user_bufs++;
2070 io_sqe_buffer_unregister(ctx);
2074 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
2076 io_finish_async(ctx);
2078 mmdrop(ctx->sqo_mm);
2080 io_iopoll_reap_events(ctx);
2081 io_sqe_buffer_unregister(ctx);
2082 io_sqe_files_unregister(ctx);
2084 #if defined(CONFIG_UNIX)
2086 sock_release(ctx->ring_sock);
2089 io_mem_free(ctx->sq_ring);
2090 io_mem_free(ctx->sq_sqes);
2091 io_mem_free(ctx->cq_ring);
2093 percpu_ref_exit(&ctx->refs);
2094 if (ctx->account_mem)
2095 io_unaccount_mem(ctx->user,
2096 ring_pages(ctx->sq_entries, ctx->cq_entries));
2097 free_uid(ctx->user);
2101 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2103 struct io_ring_ctx *ctx = file->private_data;
2106 poll_wait(file, &ctx->cq_wait, wait);
2107 /* See comment at the top of this file */
2109 if (READ_ONCE(ctx->sq_ring->r.tail) + 1 != ctx->cached_sq_head)
2110 mask |= EPOLLOUT | EPOLLWRNORM;
2111 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
2112 mask |= EPOLLIN | EPOLLRDNORM;
2117 static int io_uring_fasync(int fd, struct file *file, int on)
2119 struct io_ring_ctx *ctx = file->private_data;
2121 return fasync_helper(fd, file, on, &ctx->cq_fasync);
2124 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2126 mutex_lock(&ctx->uring_lock);
2127 percpu_ref_kill(&ctx->refs);
2128 mutex_unlock(&ctx->uring_lock);
2130 io_iopoll_reap_events(ctx);
2131 wait_for_completion(&ctx->ctx_done);
2132 io_ring_ctx_free(ctx);
2135 static int io_uring_release(struct inode *inode, struct file *file)
2137 struct io_ring_ctx *ctx = file->private_data;
2139 file->private_data = NULL;
2140 io_ring_ctx_wait_and_kill(ctx);
2144 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2146 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
2147 unsigned long sz = vma->vm_end - vma->vm_start;
2148 struct io_ring_ctx *ctx = file->private_data;
2154 case IORING_OFF_SQ_RING:
2157 case IORING_OFF_SQES:
2160 case IORING_OFF_CQ_RING:
2167 page = virt_to_head_page(ptr);
2168 if (sz > (PAGE_SIZE << compound_order(page)))
2171 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
2172 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2175 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
2176 u32, min_complete, u32, flags, const sigset_t __user *, sig,
2179 struct io_ring_ctx *ctx;
2184 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2192 if (f.file->f_op != &io_uring_fops)
2196 ctx = f.file->private_data;
2197 if (!percpu_ref_tryget(&ctx->refs))
2201 * For SQ polling, the thread will do all submissions and completions.
2202 * Just return the requested submit count, and wake the thread if
2205 if (ctx->flags & IORING_SETUP_SQPOLL) {
2206 if (flags & IORING_ENTER_SQ_WAKEUP)
2207 wake_up(&ctx->sqo_wait);
2208 submitted = to_submit;
2214 to_submit = min(to_submit, ctx->sq_entries);
2216 mutex_lock(&ctx->uring_lock);
2217 submitted = io_ring_submit(ctx, to_submit);
2218 mutex_unlock(&ctx->uring_lock);
2223 if (flags & IORING_ENTER_GETEVENTS) {
2224 unsigned nr_events = 0;
2226 min_complete = min(min_complete, ctx->cq_entries);
2229 * The application could have included the 'to_submit' count
2230 * in how many events it wanted to wait for. If we failed to
2231 * submit the desired count, we may need to adjust the number
2232 * of events to poll/wait for.
2234 if (submitted < to_submit)
2235 min_complete = min_t(unsigned, submitted, min_complete);
2237 if (ctx->flags & IORING_SETUP_IOPOLL) {
2238 mutex_lock(&ctx->uring_lock);
2239 ret = io_iopoll_check(ctx, &nr_events, min_complete);
2240 mutex_unlock(&ctx->uring_lock);
2242 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
2247 io_ring_drop_ctx_refs(ctx, 1);
2250 return submitted ? submitted : ret;
2253 static const struct file_operations io_uring_fops = {
2254 .release = io_uring_release,
2255 .mmap = io_uring_mmap,
2256 .poll = io_uring_poll,
2257 .fasync = io_uring_fasync,
2260 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2261 struct io_uring_params *p)
2263 struct io_sq_ring *sq_ring;
2264 struct io_cq_ring *cq_ring;
2267 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
2271 ctx->sq_ring = sq_ring;
2272 sq_ring->ring_mask = p->sq_entries - 1;
2273 sq_ring->ring_entries = p->sq_entries;
2274 ctx->sq_mask = sq_ring->ring_mask;
2275 ctx->sq_entries = sq_ring->ring_entries;
2277 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
2278 if (size == SIZE_MAX)
2281 ctx->sq_sqes = io_mem_alloc(size);
2282 if (!ctx->sq_sqes) {
2283 io_mem_free(ctx->sq_ring);
2287 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
2289 io_mem_free(ctx->sq_ring);
2290 io_mem_free(ctx->sq_sqes);
2294 ctx->cq_ring = cq_ring;
2295 cq_ring->ring_mask = p->cq_entries - 1;
2296 cq_ring->ring_entries = p->cq_entries;
2297 ctx->cq_mask = cq_ring->ring_mask;
2298 ctx->cq_entries = cq_ring->ring_entries;
2303 * Allocate an anonymous fd, this is what constitutes the application
2304 * visible backing of an io_uring instance. The application mmaps this
2305 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
2306 * we have to tie this fd to a socket for file garbage collection purposes.
2308 static int io_uring_get_fd(struct io_ring_ctx *ctx)
2313 #if defined(CONFIG_UNIX)
2314 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
2320 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2324 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
2325 O_RDWR | O_CLOEXEC);
2328 ret = PTR_ERR(file);
2332 #if defined(CONFIG_UNIX)
2333 ctx->ring_sock->file = file;
2334 ctx->ring_sock->sk->sk_user_data = ctx;
2336 fd_install(ret, file);
2339 #if defined(CONFIG_UNIX)
2340 sock_release(ctx->ring_sock);
2341 ctx->ring_sock = NULL;
2346 static int io_uring_create(unsigned entries, struct io_uring_params *p)
2348 struct user_struct *user = NULL;
2349 struct io_ring_ctx *ctx;
2353 if (!entries || entries > IORING_MAX_ENTRIES)
2357 * Use twice as many entries for the CQ ring. It's possible for the
2358 * application to drive a higher depth than the size of the SQ ring,
2359 * since the sqes are only used at submission time. This allows for
2360 * some flexibility in overcommitting a bit.
2362 p->sq_entries = roundup_pow_of_two(entries);
2363 p->cq_entries = 2 * p->sq_entries;
2365 user = get_uid(current_user());
2366 account_mem = !capable(CAP_IPC_LOCK);
2369 ret = io_account_mem(user,
2370 ring_pages(p->sq_entries, p->cq_entries));
2377 ctx = io_ring_ctx_alloc(p);
2380 io_unaccount_mem(user, ring_pages(p->sq_entries,
2385 ctx->compat = in_compat_syscall();
2386 ctx->account_mem = account_mem;
2389 ret = io_allocate_scq_urings(ctx, p);
2393 ret = io_sq_offload_start(ctx, p);
2397 ret = io_uring_get_fd(ctx);
2401 memset(&p->sq_off, 0, sizeof(p->sq_off));
2402 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
2403 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
2404 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
2405 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
2406 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
2407 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
2408 p->sq_off.array = offsetof(struct io_sq_ring, array);
2410 memset(&p->cq_off, 0, sizeof(p->cq_off));
2411 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
2412 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
2413 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
2414 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
2415 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
2416 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
2419 io_ring_ctx_wait_and_kill(ctx);
2424 * Sets up an aio uring context, and returns the fd. Applications asks for a
2425 * ring size, we return the actual sq/cq ring sizes (among other things) in the
2426 * params structure passed in.
2428 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
2430 struct io_uring_params p;
2434 if (copy_from_user(&p, params, sizeof(p)))
2436 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
2441 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
2442 IORING_SETUP_SQ_AFF))
2445 ret = io_uring_create(entries, &p);
2449 if (copy_to_user(params, &p, sizeof(p)))
2455 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
2456 struct io_uring_params __user *, params)
2458 return io_uring_setup(entries, params);
2461 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
2462 void __user *arg, unsigned nr_args)
2466 percpu_ref_kill(&ctx->refs);
2467 wait_for_completion(&ctx->ctx_done);
2470 case IORING_REGISTER_BUFFERS:
2471 ret = io_sqe_buffer_register(ctx, arg, nr_args);
2473 case IORING_UNREGISTER_BUFFERS:
2477 ret = io_sqe_buffer_unregister(ctx);
2479 case IORING_REGISTER_FILES:
2480 ret = io_sqe_files_register(ctx, arg, nr_args);
2482 case IORING_UNREGISTER_FILES:
2486 ret = io_sqe_files_unregister(ctx);
2493 /* bring the ctx back to life */
2494 reinit_completion(&ctx->ctx_done);
2495 percpu_ref_reinit(&ctx->refs);
2499 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
2500 void __user *, arg, unsigned int, nr_args)
2502 struct io_ring_ctx *ctx;
2511 if (f.file->f_op != &io_uring_fops)
2514 ctx = f.file->private_data;
2516 mutex_lock(&ctx->uring_lock);
2517 ret = __io_uring_register(ctx, opcode, arg, nr_args);
2518 mutex_unlock(&ctx->uring_lock);
2524 static int __init io_uring_init(void)
2526 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
2529 __initcall(io_uring_init);