blob: 745413d927128a3a5e2f021657309ab21a4fe42e [file] [log] [blame]
Jens Axboe2b188cc2019-01-07 10:46:33 -07001// SPDX-License-Identifier: GPL-2.0
2/*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
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.
16 *
17 * Also see the examples in the liburing library:
18 *
19 * git://git.kernel.dk/liburing
20 *
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.
25 *
26 * Copyright (C) 2018-2019 Jens Axboe
Christoph Hellwigc992fe22019-01-11 09:43:02 -070027 * Copyright (c) 2018-2019 Christoph Hellwig
Jens Axboe2b188cc2019-01-07 10:46:33 -070028 */
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>
36
37#include <linux/sched/signal.h>
38#include <linux/fs.h>
39#include <linux/file.h>
40#include <linux/fdtable.h>
41#include <linux/mm.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>
49#include <net/sock.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>
55
56#include <uapi/linux/io_uring.h>
57
58#include "internal.h"
59
60#define IORING_MAX_ENTRIES 4096
61
62struct io_uring {
63 u32 head ____cacheline_aligned_in_smp;
64 u32 tail ____cacheline_aligned_in_smp;
65};
66
67struct io_sq_ring {
68 struct io_uring r;
69 u32 ring_mask;
70 u32 ring_entries;
71 u32 dropped;
72 u32 flags;
73 u32 array[];
74};
75
76struct io_cq_ring {
77 struct io_uring r;
78 u32 ring_mask;
79 u32 ring_entries;
80 u32 overflow;
81 struct io_uring_cqe cqes[];
82};
83
84struct io_ring_ctx {
85 struct {
86 struct percpu_ref refs;
87 } ____cacheline_aligned_in_smp;
88
89 struct {
90 unsigned int flags;
91 bool compat;
92 bool account_mem;
93
94 /* SQ ring */
95 struct io_sq_ring *sq_ring;
96 unsigned cached_sq_head;
97 unsigned sq_entries;
98 unsigned sq_mask;
99 struct io_uring_sqe *sq_sqes;
100 } ____cacheline_aligned_in_smp;
101
102 /* IO offload */
103 struct workqueue_struct *sqo_wq;
104 struct mm_struct *sqo_mm;
105
106 struct {
107 /* CQ ring */
108 struct io_cq_ring *cq_ring;
109 unsigned cached_cq_tail;
110 unsigned cq_entries;
111 unsigned cq_mask;
112 struct wait_queue_head cq_wait;
113 struct fasync_struct *cq_fasync;
114 } ____cacheline_aligned_in_smp;
115
116 struct user_struct *user;
117
118 struct completion ctx_done;
119
120 struct {
121 struct mutex uring_lock;
122 wait_queue_head_t wait;
123 } ____cacheline_aligned_in_smp;
124
125 struct {
126 spinlock_t completion_lock;
127 } ____cacheline_aligned_in_smp;
128
129#if defined(CONFIG_UNIX)
130 struct socket *ring_sock;
131#endif
132};
133
134struct sqe_submit {
135 const struct io_uring_sqe *sqe;
136 unsigned short index;
137 bool has_user;
138};
139
140struct io_kiocb {
141 struct kiocb rw;
142
143 struct sqe_submit submit;
144
145 struct io_ring_ctx *ctx;
146 struct list_head list;
147 unsigned int flags;
148#define REQ_F_FORCE_NONBLOCK 1 /* inline submission attempt */
149 u64 user_data;
150
151 struct work_struct work;
152};
153
154#define IO_PLUG_THRESHOLD 2
155
156static struct kmem_cache *req_cachep;
157
158static const struct file_operations io_uring_fops;
159
160struct sock *io_uring_get_socket(struct file *file)
161{
162#if defined(CONFIG_UNIX)
163 if (file->f_op == &io_uring_fops) {
164 struct io_ring_ctx *ctx = file->private_data;
165
166 return ctx->ring_sock->sk;
167 }
168#endif
169 return NULL;
170}
171EXPORT_SYMBOL(io_uring_get_socket);
172
173static void io_ring_ctx_ref_free(struct percpu_ref *ref)
174{
175 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
176
177 complete(&ctx->ctx_done);
178}
179
180static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
181{
182 struct io_ring_ctx *ctx;
183
184 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
185 if (!ctx)
186 return NULL;
187
188 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 0, GFP_KERNEL)) {
189 kfree(ctx);
190 return NULL;
191 }
192
193 ctx->flags = p->flags;
194 init_waitqueue_head(&ctx->cq_wait);
195 init_completion(&ctx->ctx_done);
196 mutex_init(&ctx->uring_lock);
197 init_waitqueue_head(&ctx->wait);
198 spin_lock_init(&ctx->completion_lock);
199 return ctx;
200}
201
202static void io_commit_cqring(struct io_ring_ctx *ctx)
203{
204 struct io_cq_ring *ring = ctx->cq_ring;
205
206 if (ctx->cached_cq_tail != READ_ONCE(ring->r.tail)) {
207 /* order cqe stores with ring update */
208 smp_store_release(&ring->r.tail, ctx->cached_cq_tail);
209
210 /*
211 * Write sider barrier of tail update, app has read side. See
212 * comment at the top of this file.
213 */
214 smp_wmb();
215
216 if (wq_has_sleeper(&ctx->cq_wait)) {
217 wake_up_interruptible(&ctx->cq_wait);
218 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
219 }
220 }
221}
222
223static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
224{
225 struct io_cq_ring *ring = ctx->cq_ring;
226 unsigned tail;
227
228 tail = ctx->cached_cq_tail;
229 /* See comment at the top of the file */
230 smp_rmb();
231 if (tail + 1 == READ_ONCE(ring->r.head))
232 return NULL;
233
234 ctx->cached_cq_tail++;
235 return &ring->cqes[tail & ctx->cq_mask];
236}
237
238static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
239 long res, unsigned ev_flags)
240{
241 struct io_uring_cqe *cqe;
242
243 /*
244 * If we can't get a cq entry, userspace overflowed the
245 * submission (by quite a lot). Increment the overflow count in
246 * the ring.
247 */
248 cqe = io_get_cqring(ctx);
249 if (cqe) {
250 WRITE_ONCE(cqe->user_data, ki_user_data);
251 WRITE_ONCE(cqe->res, res);
252 WRITE_ONCE(cqe->flags, ev_flags);
253 } else {
254 unsigned overflow = READ_ONCE(ctx->cq_ring->overflow);
255
256 WRITE_ONCE(ctx->cq_ring->overflow, overflow + 1);
257 }
258}
259
260static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 ki_user_data,
261 long res, unsigned ev_flags)
262{
263 unsigned long flags;
264
265 spin_lock_irqsave(&ctx->completion_lock, flags);
266 io_cqring_fill_event(ctx, ki_user_data, res, ev_flags);
267 io_commit_cqring(ctx);
268 spin_unlock_irqrestore(&ctx->completion_lock, flags);
269
270 if (waitqueue_active(&ctx->wait))
271 wake_up(&ctx->wait);
272}
273
274static void io_ring_drop_ctx_refs(struct io_ring_ctx *ctx, unsigned refs)
275{
276 percpu_ref_put_many(&ctx->refs, refs);
277
278 if (waitqueue_active(&ctx->wait))
279 wake_up(&ctx->wait);
280}
281
282static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx)
283{
284 struct io_kiocb *req;
285
286 if (!percpu_ref_tryget(&ctx->refs))
287 return NULL;
288
289 req = kmem_cache_alloc(req_cachep, __GFP_NOWARN);
290 if (req) {
291 req->ctx = ctx;
292 req->flags = 0;
293 return req;
294 }
295
296 io_ring_drop_ctx_refs(ctx, 1);
297 return NULL;
298}
299
300static void io_free_req(struct io_kiocb *req)
301{
302 io_ring_drop_ctx_refs(req->ctx, 1);
303 kmem_cache_free(req_cachep, req);
304}
305
306static void kiocb_end_write(struct kiocb *kiocb)
307{
308 if (kiocb->ki_flags & IOCB_WRITE) {
309 struct inode *inode = file_inode(kiocb->ki_filp);
310
311 /*
312 * Tell lockdep we inherited freeze protection from submission
313 * thread.
314 */
315 if (S_ISREG(inode->i_mode))
316 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
317 file_end_write(kiocb->ki_filp);
318 }
319}
320
321static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
322{
323 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
324
325 kiocb_end_write(kiocb);
326
327 fput(kiocb->ki_filp);
328 io_cqring_add_event(req->ctx, req->user_data, res, 0);
329 io_free_req(req);
330}
331
332/*
333 * If we tracked the file through the SCM inflight mechanism, we could support
334 * any file. For now, just ensure that anything potentially problematic is done
335 * inline.
336 */
337static bool io_file_supports_async(struct file *file)
338{
339 umode_t mode = file_inode(file)->i_mode;
340
341 if (S_ISBLK(mode) || S_ISCHR(mode))
342 return true;
343 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
344 return true;
345
346 return false;
347}
348
349static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
350 bool force_nonblock)
351{
352 struct kiocb *kiocb = &req->rw;
353 unsigned ioprio;
354 int fd, ret;
355
356 /* For -EAGAIN retry, everything is already prepped */
357 if (kiocb->ki_filp)
358 return 0;
359
360 fd = READ_ONCE(sqe->fd);
361 kiocb->ki_filp = fget(fd);
362 if (unlikely(!kiocb->ki_filp))
363 return -EBADF;
364 if (force_nonblock && !io_file_supports_async(kiocb->ki_filp))
365 force_nonblock = false;
366 kiocb->ki_pos = READ_ONCE(sqe->off);
367 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
368 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
369
370 ioprio = READ_ONCE(sqe->ioprio);
371 if (ioprio) {
372 ret = ioprio_check_cap(ioprio);
373 if (ret)
374 goto out_fput;
375
376 kiocb->ki_ioprio = ioprio;
377 } else
378 kiocb->ki_ioprio = get_current_ioprio();
379
380 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
381 if (unlikely(ret))
382 goto out_fput;
383 if (force_nonblock) {
384 kiocb->ki_flags |= IOCB_NOWAIT;
385 req->flags |= REQ_F_FORCE_NONBLOCK;
386 }
387 if (kiocb->ki_flags & IOCB_HIPRI) {
388 ret = -EINVAL;
389 goto out_fput;
390 }
391
392 kiocb->ki_complete = io_complete_rw;
393 return 0;
394out_fput:
395 fput(kiocb->ki_filp);
396 return ret;
397}
398
399static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
400{
401 switch (ret) {
402 case -EIOCBQUEUED:
403 break;
404 case -ERESTARTSYS:
405 case -ERESTARTNOINTR:
406 case -ERESTARTNOHAND:
407 case -ERESTART_RESTARTBLOCK:
408 /*
409 * We can't just restart the syscall, since previously
410 * submitted sqes may already be in progress. Just fail this
411 * IO with EINTR.
412 */
413 ret = -EINTR;
414 /* fall through */
415 default:
416 kiocb->ki_complete(kiocb, ret, 0);
417 }
418}
419
420static int io_import_iovec(struct io_ring_ctx *ctx, int rw,
421 const struct sqe_submit *s, struct iovec **iovec,
422 struct iov_iter *iter)
423{
424 const struct io_uring_sqe *sqe = s->sqe;
425 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
426 size_t sqe_len = READ_ONCE(sqe->len);
427
428 if (!s->has_user)
429 return -EFAULT;
430
431#ifdef CONFIG_COMPAT
432 if (ctx->compat)
433 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
434 iovec, iter);
435#endif
436
437 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
438}
439
440static ssize_t io_read(struct io_kiocb *req, const struct sqe_submit *s,
441 bool force_nonblock)
442{
443 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
444 struct kiocb *kiocb = &req->rw;
445 struct iov_iter iter;
446 struct file *file;
447 ssize_t ret;
448
449 ret = io_prep_rw(req, s->sqe, force_nonblock);
450 if (ret)
451 return ret;
452 file = kiocb->ki_filp;
453
454 ret = -EBADF;
455 if (unlikely(!(file->f_mode & FMODE_READ)))
456 goto out_fput;
457 ret = -EINVAL;
458 if (unlikely(!file->f_op->read_iter))
459 goto out_fput;
460
461 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
462 if (ret)
463 goto out_fput;
464
465 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_iter_count(&iter));
466 if (!ret) {
467 ssize_t ret2;
468
469 /* Catch -EAGAIN return for forced non-blocking submission */
470 ret2 = call_read_iter(file, kiocb, &iter);
471 if (!force_nonblock || ret2 != -EAGAIN)
472 io_rw_done(kiocb, ret2);
473 else
474 ret = -EAGAIN;
475 }
476 kfree(iovec);
477out_fput:
478 /* Hold on to the file for -EAGAIN */
479 if (unlikely(ret && ret != -EAGAIN))
480 fput(file);
481 return ret;
482}
483
484static ssize_t io_write(struct io_kiocb *req, const struct sqe_submit *s,
485 bool force_nonblock)
486{
487 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
488 struct kiocb *kiocb = &req->rw;
489 struct iov_iter iter;
490 struct file *file;
491 ssize_t ret;
492
493 ret = io_prep_rw(req, s->sqe, force_nonblock);
494 if (ret)
495 return ret;
496 /* Hold on to the file for -EAGAIN */
497 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT))
498 return -EAGAIN;
499
500 ret = -EBADF;
501 file = kiocb->ki_filp;
502 if (unlikely(!(file->f_mode & FMODE_WRITE)))
503 goto out_fput;
504 ret = -EINVAL;
505 if (unlikely(!file->f_op->write_iter))
506 goto out_fput;
507
508 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
509 if (ret)
510 goto out_fput;
511
512 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos,
513 iov_iter_count(&iter));
514 if (!ret) {
515 /*
516 * Open-code file_start_write here to grab freeze protection,
517 * which will be released by another thread in
518 * io_complete_rw(). Fool lockdep by telling it the lock got
519 * released so that it doesn't complain about the held lock when
520 * we return to userspace.
521 */
522 if (S_ISREG(file_inode(file)->i_mode)) {
523 __sb_start_write(file_inode(file)->i_sb,
524 SB_FREEZE_WRITE, true);
525 __sb_writers_release(file_inode(file)->i_sb,
526 SB_FREEZE_WRITE);
527 }
528 kiocb->ki_flags |= IOCB_WRITE;
529 io_rw_done(kiocb, call_write_iter(file, kiocb, &iter));
530 }
531 kfree(iovec);
532out_fput:
533 if (unlikely(ret))
534 fput(file);
535 return ret;
536}
537
538/*
539 * IORING_OP_NOP just posts a completion event, nothing else.
540 */
541static int io_nop(struct io_kiocb *req, u64 user_data)
542{
543 struct io_ring_ctx *ctx = req->ctx;
544 long err = 0;
545
546 /*
547 * Twilight zone - it's possible that someone issued an opcode that
548 * has a file attached, then got -EAGAIN on submission, and changed
549 * the sqe before we retried it from async context. Avoid dropping
550 * a file reference for this malicious case, and flag the error.
551 */
552 if (req->rw.ki_filp) {
553 err = -EBADF;
554 fput(req->rw.ki_filp);
555 }
556 io_cqring_add_event(ctx, user_data, err, 0);
557 io_free_req(req);
558 return 0;
559}
560
Christoph Hellwigc992fe22019-01-11 09:43:02 -0700561static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
562{
563 int fd;
564
565 /* Prep already done */
566 if (req->rw.ki_filp)
567 return 0;
568
569 if (unlikely(sqe->addr || sqe->ioprio))
570 return -EINVAL;
571
572 fd = READ_ONCE(sqe->fd);
573 req->rw.ki_filp = fget(fd);
574 if (unlikely(!req->rw.ki_filp))
575 return -EBADF;
576
577 return 0;
578}
579
580static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
581 bool force_nonblock)
582{
583 loff_t sqe_off = READ_ONCE(sqe->off);
584 loff_t sqe_len = READ_ONCE(sqe->len);
585 loff_t end = sqe_off + sqe_len;
586 unsigned fsync_flags;
587 int ret;
588
589 fsync_flags = READ_ONCE(sqe->fsync_flags);
590 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
591 return -EINVAL;
592
593 ret = io_prep_fsync(req, sqe);
594 if (ret)
595 return ret;
596
597 /* fsync always requires a blocking context */
598 if (force_nonblock)
599 return -EAGAIN;
600
601 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
602 end > 0 ? end : LLONG_MAX,
603 fsync_flags & IORING_FSYNC_DATASYNC);
604
605 fput(req->rw.ki_filp);
606 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
607 io_free_req(req);
608 return 0;
609}
610
Jens Axboe2b188cc2019-01-07 10:46:33 -0700611static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
612 const struct sqe_submit *s, bool force_nonblock)
613{
614 ssize_t ret;
615 int opcode;
616
617 if (unlikely(s->index >= ctx->sq_entries))
618 return -EINVAL;
619 req->user_data = READ_ONCE(s->sqe->user_data);
620
621 opcode = READ_ONCE(s->sqe->opcode);
622 switch (opcode) {
623 case IORING_OP_NOP:
624 ret = io_nop(req, req->user_data);
625 break;
626 case IORING_OP_READV:
627 ret = io_read(req, s, force_nonblock);
628 break;
629 case IORING_OP_WRITEV:
630 ret = io_write(req, s, force_nonblock);
631 break;
Christoph Hellwigc992fe22019-01-11 09:43:02 -0700632 case IORING_OP_FSYNC:
633 ret = io_fsync(req, s->sqe, force_nonblock);
634 break;
Jens Axboe2b188cc2019-01-07 10:46:33 -0700635 default:
636 ret = -EINVAL;
637 break;
638 }
639
640 return ret;
641}
642
643static void io_sq_wq_submit_work(struct work_struct *work)
644{
645 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
646 struct sqe_submit *s = &req->submit;
647 const struct io_uring_sqe *sqe = s->sqe;
648 struct io_ring_ctx *ctx = req->ctx;
649 mm_segment_t old_fs = get_fs();
650 int ret;
651
652 /* Ensure we clear previously set forced non-block flag */
653 req->flags &= ~REQ_F_FORCE_NONBLOCK;
654 req->rw.ki_flags &= ~IOCB_NOWAIT;
655
656 if (!mmget_not_zero(ctx->sqo_mm)) {
657 ret = -EFAULT;
658 goto err;
659 }
660
661 use_mm(ctx->sqo_mm);
662 set_fs(USER_DS);
663 s->has_user = true;
664
665 ret = __io_submit_sqe(ctx, req, s, false);
666
667 set_fs(old_fs);
668 unuse_mm(ctx->sqo_mm);
669 mmput(ctx->sqo_mm);
670err:
671 if (ret) {
672 io_cqring_add_event(ctx, sqe->user_data, ret, 0);
673 io_free_req(req);
674 }
675
676 /* async context always use a copy of the sqe */
677 kfree(sqe);
678}
679
680static int io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s)
681{
682 struct io_kiocb *req;
683 ssize_t ret;
684
685 /* enforce forwards compatibility on users */
686 if (unlikely(s->sqe->flags))
687 return -EINVAL;
688
689 req = io_get_req(ctx);
690 if (unlikely(!req))
691 return -EAGAIN;
692
693 req->rw.ki_filp = NULL;
694
695 ret = __io_submit_sqe(ctx, req, s, true);
696 if (ret == -EAGAIN) {
697 struct io_uring_sqe *sqe_copy;
698
699 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
700 if (sqe_copy) {
701 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
702 s->sqe = sqe_copy;
703
704 memcpy(&req->submit, s, sizeof(*s));
705 INIT_WORK(&req->work, io_sq_wq_submit_work);
706 queue_work(ctx->sqo_wq, &req->work);
707 ret = 0;
708 }
709 }
710 if (ret)
711 io_free_req(req);
712
713 return ret;
714}
715
716static void io_commit_sqring(struct io_ring_ctx *ctx)
717{
718 struct io_sq_ring *ring = ctx->sq_ring;
719
720 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
721 /*
722 * Ensure any loads from the SQEs are done at this point,
723 * since once we write the new head, the application could
724 * write new data to them.
725 */
726 smp_store_release(&ring->r.head, ctx->cached_sq_head);
727
728 /*
729 * write side barrier of head update, app has read side. See
730 * comment at the top of this file
731 */
732 smp_wmb();
733 }
734}
735
736/*
737 * Undo last io_get_sqring()
738 */
739static void io_drop_sqring(struct io_ring_ctx *ctx)
740{
741 ctx->cached_sq_head--;
742}
743
744/*
745 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
746 * that is mapped by userspace. This means that care needs to be taken to
747 * ensure that reads are stable, as we cannot rely on userspace always
748 * being a good citizen. If members of the sqe are validated and then later
749 * used, it's important that those reads are done through READ_ONCE() to
750 * prevent a re-load down the line.
751 */
752static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
753{
754 struct io_sq_ring *ring = ctx->sq_ring;
755 unsigned head;
756
757 /*
758 * The cached sq head (or cq tail) serves two purposes:
759 *
760 * 1) allows us to batch the cost of updating the user visible
761 * head updates.
762 * 2) allows the kernel side to track the head on its own, even
763 * though the application is the one updating it.
764 */
765 head = ctx->cached_sq_head;
766 /* See comment at the top of this file */
767 smp_rmb();
768 if (head == READ_ONCE(ring->r.tail))
769 return false;
770
771 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
772 if (head < ctx->sq_entries) {
773 s->index = head;
774 s->sqe = &ctx->sq_sqes[head];
775 ctx->cached_sq_head++;
776 return true;
777 }
778
779 /* drop invalid entries */
780 ctx->cached_sq_head++;
781 ring->dropped++;
782 /* See comment at the top of this file */
783 smp_wmb();
784 return false;
785}
786
787static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
788{
789 int i, ret = 0, submit = 0;
790 struct blk_plug plug;
791
792 if (to_submit > IO_PLUG_THRESHOLD)
793 blk_start_plug(&plug);
794
795 for (i = 0; i < to_submit; i++) {
796 struct sqe_submit s;
797
798 if (!io_get_sqring(ctx, &s))
799 break;
800
801 s.has_user = true;
802 ret = io_submit_sqe(ctx, &s);
803 if (ret) {
804 io_drop_sqring(ctx);
805 break;
806 }
807
808 submit++;
809 }
810 io_commit_sqring(ctx);
811
812 if (to_submit > IO_PLUG_THRESHOLD)
813 blk_finish_plug(&plug);
814
815 return submit ? submit : ret;
816}
817
818static unsigned io_cqring_events(struct io_cq_ring *ring)
819{
820 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
821}
822
823/*
824 * Wait until events become available, if we don't already have some. The
825 * application must reap them itself, as they reside on the shared cq ring.
826 */
827static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
828 const sigset_t __user *sig, size_t sigsz)
829{
830 struct io_cq_ring *ring = ctx->cq_ring;
831 sigset_t ksigmask, sigsaved;
832 DEFINE_WAIT(wait);
833 int ret;
834
835 /* See comment at the top of this file */
836 smp_rmb();
837 if (io_cqring_events(ring) >= min_events)
838 return 0;
839
840 if (sig) {
841 ret = set_user_sigmask(sig, &ksigmask, &sigsaved, sigsz);
842 if (ret)
843 return ret;
844 }
845
846 do {
847 prepare_to_wait(&ctx->wait, &wait, TASK_INTERRUPTIBLE);
848
849 ret = 0;
850 /* See comment at the top of this file */
851 smp_rmb();
852 if (io_cqring_events(ring) >= min_events)
853 break;
854
855 schedule();
856
857 ret = -EINTR;
858 if (signal_pending(current))
859 break;
860 } while (1);
861
862 finish_wait(&ctx->wait, &wait);
863
864 if (sig)
865 restore_user_sigmask(sig, &sigsaved);
866
867 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
868}
869
870static int io_sq_offload_start(struct io_ring_ctx *ctx)
871{
872 int ret;
873
874 mmgrab(current->mm);
875 ctx->sqo_mm = current->mm;
876
877 /* Do QD, or 2 * CPUS, whatever is smallest */
878 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
879 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
880 if (!ctx->sqo_wq) {
881 ret = -ENOMEM;
882 goto err;
883 }
884
885 return 0;
886err:
887 mmdrop(ctx->sqo_mm);
888 ctx->sqo_mm = NULL;
889 return ret;
890}
891
892static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
893{
894 atomic_long_sub(nr_pages, &user->locked_vm);
895}
896
897static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
898{
899 unsigned long page_limit, cur_pages, new_pages;
900
901 /* Don't allow more pages than we can safely lock */
902 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
903
904 do {
905 cur_pages = atomic_long_read(&user->locked_vm);
906 new_pages = cur_pages + nr_pages;
907 if (new_pages > page_limit)
908 return -ENOMEM;
909 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
910 new_pages) != cur_pages);
911
912 return 0;
913}
914
915static void io_mem_free(void *ptr)
916{
917 struct page *page = virt_to_head_page(ptr);
918
919 if (put_page_testzero(page))
920 free_compound_page(page);
921}
922
923static void *io_mem_alloc(size_t size)
924{
925 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
926 __GFP_NORETRY;
927
928 return (void *) __get_free_pages(gfp_flags, get_order(size));
929}
930
931static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
932{
933 struct io_sq_ring *sq_ring;
934 struct io_cq_ring *cq_ring;
935 size_t bytes;
936
937 bytes = struct_size(sq_ring, array, sq_entries);
938 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
939 bytes += struct_size(cq_ring, cqes, cq_entries);
940
941 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
942}
943
944static void io_ring_ctx_free(struct io_ring_ctx *ctx)
945{
946 if (ctx->sqo_wq)
947 destroy_workqueue(ctx->sqo_wq);
948 if (ctx->sqo_mm)
949 mmdrop(ctx->sqo_mm);
950#if defined(CONFIG_UNIX)
951 if (ctx->ring_sock)
952 sock_release(ctx->ring_sock);
953#endif
954
955 io_mem_free(ctx->sq_ring);
956 io_mem_free(ctx->sq_sqes);
957 io_mem_free(ctx->cq_ring);
958
959 percpu_ref_exit(&ctx->refs);
960 if (ctx->account_mem)
961 io_unaccount_mem(ctx->user,
962 ring_pages(ctx->sq_entries, ctx->cq_entries));
963 free_uid(ctx->user);
964 kfree(ctx);
965}
966
967static __poll_t io_uring_poll(struct file *file, poll_table *wait)
968{
969 struct io_ring_ctx *ctx = file->private_data;
970 __poll_t mask = 0;
971
972 poll_wait(file, &ctx->cq_wait, wait);
973 /* See comment at the top of this file */
974 smp_rmb();
975 if (READ_ONCE(ctx->sq_ring->r.tail) + 1 != ctx->cached_sq_head)
976 mask |= EPOLLOUT | EPOLLWRNORM;
977 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
978 mask |= EPOLLIN | EPOLLRDNORM;
979
980 return mask;
981}
982
983static int io_uring_fasync(int fd, struct file *file, int on)
984{
985 struct io_ring_ctx *ctx = file->private_data;
986
987 return fasync_helper(fd, file, on, &ctx->cq_fasync);
988}
989
990static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
991{
992 mutex_lock(&ctx->uring_lock);
993 percpu_ref_kill(&ctx->refs);
994 mutex_unlock(&ctx->uring_lock);
995
996 wait_for_completion(&ctx->ctx_done);
997 io_ring_ctx_free(ctx);
998}
999
1000static int io_uring_release(struct inode *inode, struct file *file)
1001{
1002 struct io_ring_ctx *ctx = file->private_data;
1003
1004 file->private_data = NULL;
1005 io_ring_ctx_wait_and_kill(ctx);
1006 return 0;
1007}
1008
1009static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
1010{
1011 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
1012 unsigned long sz = vma->vm_end - vma->vm_start;
1013 struct io_ring_ctx *ctx = file->private_data;
1014 unsigned long pfn;
1015 struct page *page;
1016 void *ptr;
1017
1018 switch (offset) {
1019 case IORING_OFF_SQ_RING:
1020 ptr = ctx->sq_ring;
1021 break;
1022 case IORING_OFF_SQES:
1023 ptr = ctx->sq_sqes;
1024 break;
1025 case IORING_OFF_CQ_RING:
1026 ptr = ctx->cq_ring;
1027 break;
1028 default:
1029 return -EINVAL;
1030 }
1031
1032 page = virt_to_head_page(ptr);
1033 if (sz > (PAGE_SIZE << compound_order(page)))
1034 return -EINVAL;
1035
1036 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
1037 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
1038}
1039
1040SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
1041 u32, min_complete, u32, flags, const sigset_t __user *, sig,
1042 size_t, sigsz)
1043{
1044 struct io_ring_ctx *ctx;
1045 long ret = -EBADF;
1046 int submitted = 0;
1047 struct fd f;
1048
1049 if (flags & ~IORING_ENTER_GETEVENTS)
1050 return -EINVAL;
1051
1052 f = fdget(fd);
1053 if (!f.file)
1054 return -EBADF;
1055
1056 ret = -EOPNOTSUPP;
1057 if (f.file->f_op != &io_uring_fops)
1058 goto out_fput;
1059
1060 ret = -ENXIO;
1061 ctx = f.file->private_data;
1062 if (!percpu_ref_tryget(&ctx->refs))
1063 goto out_fput;
1064
1065 ret = 0;
1066 if (to_submit) {
1067 to_submit = min(to_submit, ctx->sq_entries);
1068
1069 mutex_lock(&ctx->uring_lock);
1070 submitted = io_ring_submit(ctx, to_submit);
1071 mutex_unlock(&ctx->uring_lock);
1072
1073 if (submitted < 0)
1074 goto out_ctx;
1075 }
1076 if (flags & IORING_ENTER_GETEVENTS) {
1077 min_complete = min(min_complete, ctx->cq_entries);
1078
1079 /*
1080 * The application could have included the 'to_submit' count
1081 * in how many events it wanted to wait for. If we failed to
1082 * submit the desired count, we may need to adjust the number
1083 * of events to poll/wait for.
1084 */
1085 if (submitted < to_submit)
1086 min_complete = min_t(unsigned, submitted, min_complete);
1087
1088 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
1089 }
1090
1091out_ctx:
1092 io_ring_drop_ctx_refs(ctx, 1);
1093out_fput:
1094 fdput(f);
1095 return submitted ? submitted : ret;
1096}
1097
1098static const struct file_operations io_uring_fops = {
1099 .release = io_uring_release,
1100 .mmap = io_uring_mmap,
1101 .poll = io_uring_poll,
1102 .fasync = io_uring_fasync,
1103};
1104
1105static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
1106 struct io_uring_params *p)
1107{
1108 struct io_sq_ring *sq_ring;
1109 struct io_cq_ring *cq_ring;
1110 size_t size;
1111
1112 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
1113 if (!sq_ring)
1114 return -ENOMEM;
1115
1116 ctx->sq_ring = sq_ring;
1117 sq_ring->ring_mask = p->sq_entries - 1;
1118 sq_ring->ring_entries = p->sq_entries;
1119 ctx->sq_mask = sq_ring->ring_mask;
1120 ctx->sq_entries = sq_ring->ring_entries;
1121
1122 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
1123 if (size == SIZE_MAX)
1124 return -EOVERFLOW;
1125
1126 ctx->sq_sqes = io_mem_alloc(size);
1127 if (!ctx->sq_sqes) {
1128 io_mem_free(ctx->sq_ring);
1129 return -ENOMEM;
1130 }
1131
1132 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
1133 if (!cq_ring) {
1134 io_mem_free(ctx->sq_ring);
1135 io_mem_free(ctx->sq_sqes);
1136 return -ENOMEM;
1137 }
1138
1139 ctx->cq_ring = cq_ring;
1140 cq_ring->ring_mask = p->cq_entries - 1;
1141 cq_ring->ring_entries = p->cq_entries;
1142 ctx->cq_mask = cq_ring->ring_mask;
1143 ctx->cq_entries = cq_ring->ring_entries;
1144 return 0;
1145}
1146
1147/*
1148 * Allocate an anonymous fd, this is what constitutes the application
1149 * visible backing of an io_uring instance. The application mmaps this
1150 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
1151 * we have to tie this fd to a socket for file garbage collection purposes.
1152 */
1153static int io_uring_get_fd(struct io_ring_ctx *ctx)
1154{
1155 struct file *file;
1156 int ret;
1157
1158#if defined(CONFIG_UNIX)
1159 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
1160 &ctx->ring_sock);
1161 if (ret)
1162 return ret;
1163#endif
1164
1165 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
1166 if (ret < 0)
1167 goto err;
1168
1169 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
1170 O_RDWR | O_CLOEXEC);
1171 if (IS_ERR(file)) {
1172 put_unused_fd(ret);
1173 ret = PTR_ERR(file);
1174 goto err;
1175 }
1176
1177#if defined(CONFIG_UNIX)
1178 ctx->ring_sock->file = file;
1179#endif
1180 fd_install(ret, file);
1181 return ret;
1182err:
1183#if defined(CONFIG_UNIX)
1184 sock_release(ctx->ring_sock);
1185 ctx->ring_sock = NULL;
1186#endif
1187 return ret;
1188}
1189
1190static int io_uring_create(unsigned entries, struct io_uring_params *p)
1191{
1192 struct user_struct *user = NULL;
1193 struct io_ring_ctx *ctx;
1194 bool account_mem;
1195 int ret;
1196
1197 if (!entries || entries > IORING_MAX_ENTRIES)
1198 return -EINVAL;
1199
1200 /*
1201 * Use twice as many entries for the CQ ring. It's possible for the
1202 * application to drive a higher depth than the size of the SQ ring,
1203 * since the sqes are only used at submission time. This allows for
1204 * some flexibility in overcommitting a bit.
1205 */
1206 p->sq_entries = roundup_pow_of_two(entries);
1207 p->cq_entries = 2 * p->sq_entries;
1208
1209 user = get_uid(current_user());
1210 account_mem = !capable(CAP_IPC_LOCK);
1211
1212 if (account_mem) {
1213 ret = io_account_mem(user,
1214 ring_pages(p->sq_entries, p->cq_entries));
1215 if (ret) {
1216 free_uid(user);
1217 return ret;
1218 }
1219 }
1220
1221 ctx = io_ring_ctx_alloc(p);
1222 if (!ctx) {
1223 if (account_mem)
1224 io_unaccount_mem(user, ring_pages(p->sq_entries,
1225 p->cq_entries));
1226 free_uid(user);
1227 return -ENOMEM;
1228 }
1229 ctx->compat = in_compat_syscall();
1230 ctx->account_mem = account_mem;
1231 ctx->user = user;
1232
1233 ret = io_allocate_scq_urings(ctx, p);
1234 if (ret)
1235 goto err;
1236
1237 ret = io_sq_offload_start(ctx);
1238 if (ret)
1239 goto err;
1240
1241 ret = io_uring_get_fd(ctx);
1242 if (ret < 0)
1243 goto err;
1244
1245 memset(&p->sq_off, 0, sizeof(p->sq_off));
1246 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
1247 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
1248 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
1249 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
1250 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
1251 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
1252 p->sq_off.array = offsetof(struct io_sq_ring, array);
1253
1254 memset(&p->cq_off, 0, sizeof(p->cq_off));
1255 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
1256 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
1257 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
1258 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
1259 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
1260 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
1261 return ret;
1262err:
1263 io_ring_ctx_wait_and_kill(ctx);
1264 return ret;
1265}
1266
1267/*
1268 * Sets up an aio uring context, and returns the fd. Applications asks for a
1269 * ring size, we return the actual sq/cq ring sizes (among other things) in the
1270 * params structure passed in.
1271 */
1272static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
1273{
1274 struct io_uring_params p;
1275 long ret;
1276 int i;
1277
1278 if (copy_from_user(&p, params, sizeof(p)))
1279 return -EFAULT;
1280 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
1281 if (p.resv[i])
1282 return -EINVAL;
1283 }
1284
1285 if (p.flags)
1286 return -EINVAL;
1287
1288 ret = io_uring_create(entries, &p);
1289 if (ret < 0)
1290 return ret;
1291
1292 if (copy_to_user(params, &p, sizeof(p)))
1293 return -EFAULT;
1294
1295 return ret;
1296}
1297
1298SYSCALL_DEFINE2(io_uring_setup, u32, entries,
1299 struct io_uring_params __user *, params)
1300{
1301 return io_uring_setup(entries, params);
1302}
1303
1304static int __init io_uring_init(void)
1305{
1306 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
1307 return 0;
1308};
1309__initcall(io_uring_init);