io_uring: use regular request ref counts
[linux-2.6-block.git] / fs / io_uring.c
CommitLineData
2b188cc1
JA
1// 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
c992fe29 27 * Copyright (c) 2018-2019 Christoph Hellwig
2b188cc1
JA
28 */
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>
6c271ce2 47#include <linux/kthread.h>
2b188cc1 48#include <linux/blkdev.h>
edafccee 49#include <linux/bvec.h>
2b188cc1
JA
50#include <linux/net.h>
51#include <net/sock.h>
52#include <net/af_unix.h>
6b06314c 53#include <net/scm.h>
2b188cc1
JA
54#include <linux/anon_inodes.h>
55#include <linux/sched/mm.h>
56#include <linux/uaccess.h>
57#include <linux/nospec.h>
edafccee
JA
58#include <linux/sizes.h>
59#include <linux/hugetlb.h>
2b188cc1
JA
60
61#include <uapi/linux/io_uring.h>
62
63#include "internal.h"
64
65#define IORING_MAX_ENTRIES 4096
6b06314c 66#define IORING_MAX_FIXED_FILES 1024
2b188cc1
JA
67
68struct io_uring {
69 u32 head ____cacheline_aligned_in_smp;
70 u32 tail ____cacheline_aligned_in_smp;
71};
72
73struct io_sq_ring {
74 struct io_uring r;
75 u32 ring_mask;
76 u32 ring_entries;
77 u32 dropped;
78 u32 flags;
79 u32 array[];
80};
81
82struct io_cq_ring {
83 struct io_uring r;
84 u32 ring_mask;
85 u32 ring_entries;
86 u32 overflow;
87 struct io_uring_cqe cqes[];
88};
89
edafccee
JA
90struct io_mapped_ubuf {
91 u64 ubuf;
92 size_t len;
93 struct bio_vec *bvec;
94 unsigned int nr_bvecs;
95};
96
31b51510
JA
97struct async_list {
98 spinlock_t lock;
99 atomic_t cnt;
100 struct list_head list;
101
102 struct file *file;
103 off_t io_end;
104 size_t io_pages;
105};
106
2b188cc1
JA
107struct io_ring_ctx {
108 struct {
109 struct percpu_ref refs;
110 } ____cacheline_aligned_in_smp;
111
112 struct {
113 unsigned int flags;
114 bool compat;
115 bool account_mem;
116
117 /* SQ ring */
118 struct io_sq_ring *sq_ring;
119 unsigned cached_sq_head;
120 unsigned sq_entries;
121 unsigned sq_mask;
6c271ce2 122 unsigned sq_thread_idle;
2b188cc1
JA
123 struct io_uring_sqe *sq_sqes;
124 } ____cacheline_aligned_in_smp;
125
126 /* IO offload */
127 struct workqueue_struct *sqo_wq;
6c271ce2 128 struct task_struct *sqo_thread; /* if using sq thread polling */
2b188cc1 129 struct mm_struct *sqo_mm;
6c271ce2
JA
130 wait_queue_head_t sqo_wait;
131 unsigned sqo_stop;
2b188cc1
JA
132
133 struct {
134 /* CQ ring */
135 struct io_cq_ring *cq_ring;
136 unsigned cached_cq_tail;
137 unsigned cq_entries;
138 unsigned cq_mask;
139 struct wait_queue_head cq_wait;
140 struct fasync_struct *cq_fasync;
141 } ____cacheline_aligned_in_smp;
142
6b06314c
JA
143 /*
144 * If used, fixed file set. Writers must ensure that ->refs is dead,
145 * readers must ensure that ->refs is alive as long as the file* is
146 * used. Only updated through io_uring_register(2).
147 */
148 struct file **user_files;
149 unsigned nr_user_files;
150
edafccee
JA
151 /* if used, fixed mapped user buffers */
152 unsigned nr_user_bufs;
153 struct io_mapped_ubuf *user_bufs;
154
2b188cc1
JA
155 struct user_struct *user;
156
157 struct completion ctx_done;
158
159 struct {
160 struct mutex uring_lock;
161 wait_queue_head_t wait;
162 } ____cacheline_aligned_in_smp;
163
164 struct {
165 spinlock_t completion_lock;
def596e9
JA
166 bool poll_multi_file;
167 /*
168 * ->poll_list is protected by the ctx->uring_lock for
169 * io_uring instances that don't use IORING_SETUP_SQPOLL.
170 * For SQPOLL, only the single threaded io_sq_thread() will
171 * manipulate the list, hence no extra locking is needed there.
172 */
173 struct list_head poll_list;
221c5eb2 174 struct list_head cancel_list;
2b188cc1
JA
175 } ____cacheline_aligned_in_smp;
176
31b51510
JA
177 struct async_list pending_async[2];
178
2b188cc1
JA
179#if defined(CONFIG_UNIX)
180 struct socket *ring_sock;
181#endif
182};
183
184struct sqe_submit {
185 const struct io_uring_sqe *sqe;
186 unsigned short index;
187 bool has_user;
def596e9 188 bool needs_lock;
6c271ce2 189 bool needs_fixed_file;
2b188cc1
JA
190};
191
221c5eb2
JA
192struct io_poll_iocb {
193 struct file *file;
194 struct wait_queue_head *head;
195 __poll_t events;
196 bool woken;
197 bool canceled;
198 struct wait_queue_entry wait;
199};
200
2b188cc1 201struct io_kiocb {
221c5eb2
JA
202 union {
203 struct kiocb rw;
204 struct io_poll_iocb poll;
205 };
2b188cc1
JA
206
207 struct sqe_submit submit;
208
209 struct io_ring_ctx *ctx;
210 struct list_head list;
211 unsigned int flags;
c16361c1 212 refcount_t refs;
2b188cc1 213#define REQ_F_FORCE_NONBLOCK 1 /* inline submission attempt */
def596e9 214#define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
6b06314c 215#define REQ_F_FIXED_FILE 4 /* ctx owns file */
31b51510 216#define REQ_F_SEQ_PREV 8 /* sequential with previous */
2b188cc1 217 u64 user_data;
def596e9 218 u64 error;
2b188cc1
JA
219
220 struct work_struct work;
221};
222
223#define IO_PLUG_THRESHOLD 2
def596e9 224#define IO_IOPOLL_BATCH 8
2b188cc1 225
9a56a232
JA
226struct io_submit_state {
227 struct blk_plug plug;
228
2579f913
JA
229 /*
230 * io_kiocb alloc cache
231 */
232 void *reqs[IO_IOPOLL_BATCH];
233 unsigned int free_reqs;
234 unsigned int cur_req;
235
9a56a232
JA
236 /*
237 * File reference cache
238 */
239 struct file *file;
240 unsigned int fd;
241 unsigned int has_refs;
242 unsigned int used_refs;
243 unsigned int ios_left;
244};
245
2b188cc1
JA
246static struct kmem_cache *req_cachep;
247
248static const struct file_operations io_uring_fops;
249
250struct sock *io_uring_get_socket(struct file *file)
251{
252#if defined(CONFIG_UNIX)
253 if (file->f_op == &io_uring_fops) {
254 struct io_ring_ctx *ctx = file->private_data;
255
256 return ctx->ring_sock->sk;
257 }
258#endif
259 return NULL;
260}
261EXPORT_SYMBOL(io_uring_get_socket);
262
263static void io_ring_ctx_ref_free(struct percpu_ref *ref)
264{
265 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
266
267 complete(&ctx->ctx_done);
268}
269
270static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
271{
272 struct io_ring_ctx *ctx;
31b51510 273 int i;
2b188cc1
JA
274
275 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
276 if (!ctx)
277 return NULL;
278
279 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 0, GFP_KERNEL)) {
280 kfree(ctx);
281 return NULL;
282 }
283
284 ctx->flags = p->flags;
285 init_waitqueue_head(&ctx->cq_wait);
286 init_completion(&ctx->ctx_done);
287 mutex_init(&ctx->uring_lock);
288 init_waitqueue_head(&ctx->wait);
31b51510
JA
289 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
290 spin_lock_init(&ctx->pending_async[i].lock);
291 INIT_LIST_HEAD(&ctx->pending_async[i].list);
292 atomic_set(&ctx->pending_async[i].cnt, 0);
293 }
2b188cc1 294 spin_lock_init(&ctx->completion_lock);
def596e9 295 INIT_LIST_HEAD(&ctx->poll_list);
221c5eb2 296 INIT_LIST_HEAD(&ctx->cancel_list);
2b188cc1
JA
297 return ctx;
298}
299
300static void io_commit_cqring(struct io_ring_ctx *ctx)
301{
302 struct io_cq_ring *ring = ctx->cq_ring;
303
304 if (ctx->cached_cq_tail != READ_ONCE(ring->r.tail)) {
305 /* order cqe stores with ring update */
306 smp_store_release(&ring->r.tail, ctx->cached_cq_tail);
307
308 /*
309 * Write sider barrier of tail update, app has read side. See
310 * comment at the top of this file.
311 */
312 smp_wmb();
313
314 if (wq_has_sleeper(&ctx->cq_wait)) {
315 wake_up_interruptible(&ctx->cq_wait);
316 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
317 }
318 }
319}
320
321static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
322{
323 struct io_cq_ring *ring = ctx->cq_ring;
324 unsigned tail;
325
326 tail = ctx->cached_cq_tail;
327 /* See comment at the top of the file */
328 smp_rmb();
329 if (tail + 1 == READ_ONCE(ring->r.head))
330 return NULL;
331
332 ctx->cached_cq_tail++;
333 return &ring->cqes[tail & ctx->cq_mask];
334}
335
336static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
337 long res, unsigned ev_flags)
338{
339 struct io_uring_cqe *cqe;
340
341 /*
342 * If we can't get a cq entry, userspace overflowed the
343 * submission (by quite a lot). Increment the overflow count in
344 * the ring.
345 */
346 cqe = io_get_cqring(ctx);
347 if (cqe) {
348 WRITE_ONCE(cqe->user_data, ki_user_data);
349 WRITE_ONCE(cqe->res, res);
350 WRITE_ONCE(cqe->flags, ev_flags);
351 } else {
352 unsigned overflow = READ_ONCE(ctx->cq_ring->overflow);
353
354 WRITE_ONCE(ctx->cq_ring->overflow, overflow + 1);
355 }
356}
357
358static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 ki_user_data,
359 long res, unsigned ev_flags)
360{
361 unsigned long flags;
362
363 spin_lock_irqsave(&ctx->completion_lock, flags);
364 io_cqring_fill_event(ctx, ki_user_data, res, ev_flags);
365 io_commit_cqring(ctx);
366 spin_unlock_irqrestore(&ctx->completion_lock, flags);
367
368 if (waitqueue_active(&ctx->wait))
369 wake_up(&ctx->wait);
6c271ce2
JA
370 if (waitqueue_active(&ctx->sqo_wait))
371 wake_up(&ctx->sqo_wait);
2b188cc1
JA
372}
373
374static void io_ring_drop_ctx_refs(struct io_ring_ctx *ctx, unsigned refs)
375{
376 percpu_ref_put_many(&ctx->refs, refs);
377
378 if (waitqueue_active(&ctx->wait))
379 wake_up(&ctx->wait);
380}
381
2579f913
JA
382static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
383 struct io_submit_state *state)
2b188cc1
JA
384{
385 struct io_kiocb *req;
386
387 if (!percpu_ref_tryget(&ctx->refs))
388 return NULL;
389
2579f913
JA
390 if (!state) {
391 req = kmem_cache_alloc(req_cachep, __GFP_NOWARN);
392 if (unlikely(!req))
393 goto out;
394 } else if (!state->free_reqs) {
395 size_t sz;
396 int ret;
397
398 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
399 ret = kmem_cache_alloc_bulk(req_cachep, __GFP_NOWARN, sz,
400 state->reqs);
401 if (unlikely(ret <= 0))
402 goto out;
403 state->free_reqs = ret - 1;
404 state->cur_req = 1;
405 req = state->reqs[0];
406 } else {
407 req = state->reqs[state->cur_req];
408 state->free_reqs--;
409 state->cur_req++;
2b188cc1
JA
410 }
411
2579f913
JA
412 req->ctx = ctx;
413 req->flags = 0;
e65ef56d
JA
414 /* one is dropped after submission, the other at completion */
415 refcount_set(&req->refs, 2);
2579f913
JA
416 return req;
417out:
2b188cc1
JA
418 io_ring_drop_ctx_refs(ctx, 1);
419 return NULL;
420}
421
def596e9
JA
422static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
423{
424 if (*nr) {
425 kmem_cache_free_bulk(req_cachep, *nr, reqs);
426 io_ring_drop_ctx_refs(ctx, *nr);
427 *nr = 0;
428 }
429}
430
2b188cc1
JA
431static void io_free_req(struct io_kiocb *req)
432{
e65ef56d
JA
433 io_ring_drop_ctx_refs(req->ctx, 1);
434 kmem_cache_free(req_cachep, req);
435}
436
437static void io_put_req(struct io_kiocb *req)
438{
439 if (refcount_dec_and_test(&req->refs))
440 io_free_req(req);
2b188cc1
JA
441}
442
def596e9
JA
443/*
444 * Find and free completed poll iocbs
445 */
446static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
447 struct list_head *done)
448{
449 void *reqs[IO_IOPOLL_BATCH];
9a56a232
JA
450 int file_count, to_free;
451 struct file *file = NULL;
def596e9 452 struct io_kiocb *req;
def596e9 453
9a56a232 454 file_count = to_free = 0;
def596e9
JA
455 while (!list_empty(done)) {
456 req = list_first_entry(done, struct io_kiocb, list);
457 list_del(&req->list);
458
459 io_cqring_fill_event(ctx, req->user_data, req->error, 0);
460
e65ef56d
JA
461 if (refcount_dec_and_test(&req->refs))
462 reqs[to_free++] = req;
def596e9
JA
463 (*nr_events)++;
464
9a56a232
JA
465 /*
466 * Batched puts of the same file, to avoid dirtying the
467 * file usage count multiple times, if avoidable.
468 */
6b06314c
JA
469 if (!(req->flags & REQ_F_FIXED_FILE)) {
470 if (!file) {
471 file = req->rw.ki_filp;
472 file_count = 1;
473 } else if (file == req->rw.ki_filp) {
474 file_count++;
475 } else {
476 fput_many(file, file_count);
477 file = req->rw.ki_filp;
478 file_count = 1;
479 }
9a56a232
JA
480 }
481
def596e9
JA
482 if (to_free == ARRAY_SIZE(reqs))
483 io_free_req_many(ctx, reqs, &to_free);
484 }
485 io_commit_cqring(ctx);
486
9a56a232
JA
487 if (file)
488 fput_many(file, file_count);
def596e9
JA
489 io_free_req_many(ctx, reqs, &to_free);
490}
491
492static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
493 long min)
494{
495 struct io_kiocb *req, *tmp;
496 LIST_HEAD(done);
497 bool spin;
498 int ret;
499
500 /*
501 * Only spin for completions if we don't have multiple devices hanging
502 * off our complete list, and we're under the requested amount.
503 */
504 spin = !ctx->poll_multi_file && *nr_events < min;
505
506 ret = 0;
507 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
508 struct kiocb *kiocb = &req->rw;
509
510 /*
511 * Move completed entries to our local list. If we find a
512 * request that requires polling, break out and complete
513 * the done list first, if we have entries there.
514 */
515 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
516 list_move_tail(&req->list, &done);
517 continue;
518 }
519 if (!list_empty(&done))
520 break;
521
522 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
523 if (ret < 0)
524 break;
525
526 if (ret && spin)
527 spin = false;
528 ret = 0;
529 }
530
531 if (!list_empty(&done))
532 io_iopoll_complete(ctx, nr_events, &done);
533
534 return ret;
535}
536
537/*
538 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
539 * non-spinning poll check - we'll still enter the driver poll loop, but only
540 * as a non-spinning completion check.
541 */
542static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
543 long min)
544{
545 while (!list_empty(&ctx->poll_list)) {
546 int ret;
547
548 ret = io_do_iopoll(ctx, nr_events, min);
549 if (ret < 0)
550 return ret;
551 if (!min || *nr_events >= min)
552 return 0;
553 }
554
555 return 1;
556}
557
558/*
559 * We can't just wait for polled events to come to us, we have to actively
560 * find and complete them.
561 */
562static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
563{
564 if (!(ctx->flags & IORING_SETUP_IOPOLL))
565 return;
566
567 mutex_lock(&ctx->uring_lock);
568 while (!list_empty(&ctx->poll_list)) {
569 unsigned int nr_events = 0;
570
571 io_iopoll_getevents(ctx, &nr_events, 1);
572 }
573 mutex_unlock(&ctx->uring_lock);
574}
575
576static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
577 long min)
578{
579 int ret = 0;
580
581 do {
582 int tmin = 0;
583
584 if (*nr_events < min)
585 tmin = min - *nr_events;
586
587 ret = io_iopoll_getevents(ctx, nr_events, tmin);
588 if (ret <= 0)
589 break;
590 ret = 0;
591 } while (min && !*nr_events && !need_resched());
592
593 return ret;
594}
595
2b188cc1
JA
596static void kiocb_end_write(struct kiocb *kiocb)
597{
598 if (kiocb->ki_flags & IOCB_WRITE) {
599 struct inode *inode = file_inode(kiocb->ki_filp);
600
601 /*
602 * Tell lockdep we inherited freeze protection from submission
603 * thread.
604 */
605 if (S_ISREG(inode->i_mode))
606 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
607 file_end_write(kiocb->ki_filp);
608 }
609}
610
6b06314c
JA
611static void io_fput(struct io_kiocb *req)
612{
613 if (!(req->flags & REQ_F_FIXED_FILE))
614 fput(req->rw.ki_filp);
615}
616
2b188cc1
JA
617static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
618{
619 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
620
621 kiocb_end_write(kiocb);
622
6b06314c 623 io_fput(req);
2b188cc1 624 io_cqring_add_event(req->ctx, req->user_data, res, 0);
e65ef56d 625 io_put_req(req);
2b188cc1
JA
626}
627
def596e9
JA
628static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
629{
630 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
631
632 kiocb_end_write(kiocb);
633
634 req->error = res;
635 if (res != -EAGAIN)
636 req->flags |= REQ_F_IOPOLL_COMPLETED;
637}
638
639/*
640 * After the iocb has been issued, it's safe to be found on the poll list.
641 * Adding the kiocb to the list AFTER submission ensures that we don't
642 * find it from a io_iopoll_getevents() thread before the issuer is done
643 * accessing the kiocb cookie.
644 */
645static void io_iopoll_req_issued(struct io_kiocb *req)
646{
647 struct io_ring_ctx *ctx = req->ctx;
648
649 /*
650 * Track whether we have multiple files in our lists. This will impact
651 * how we do polling eventually, not spinning if we're on potentially
652 * different devices.
653 */
654 if (list_empty(&ctx->poll_list)) {
655 ctx->poll_multi_file = false;
656 } else if (!ctx->poll_multi_file) {
657 struct io_kiocb *list_req;
658
659 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
660 list);
661 if (list_req->rw.ki_filp != req->rw.ki_filp)
662 ctx->poll_multi_file = true;
663 }
664
665 /*
666 * For fast devices, IO may have already completed. If it has, add
667 * it to the front so we find it first.
668 */
669 if (req->flags & REQ_F_IOPOLL_COMPLETED)
670 list_add(&req->list, &ctx->poll_list);
671 else
672 list_add_tail(&req->list, &ctx->poll_list);
673}
674
9a56a232
JA
675static void io_file_put(struct io_submit_state *state, struct file *file)
676{
677 if (!state) {
678 fput(file);
679 } else if (state->file) {
680 int diff = state->has_refs - state->used_refs;
681
682 if (diff)
683 fput_many(state->file, diff);
684 state->file = NULL;
685 }
686}
687
688/*
689 * Get as many references to a file as we have IOs left in this submission,
690 * assuming most submissions are for one file, or at least that each file
691 * has more than one submission.
692 */
693static struct file *io_file_get(struct io_submit_state *state, int fd)
694{
695 if (!state)
696 return fget(fd);
697
698 if (state->file) {
699 if (state->fd == fd) {
700 state->used_refs++;
701 state->ios_left--;
702 return state->file;
703 }
704 io_file_put(state, NULL);
705 }
706 state->file = fget_many(fd, state->ios_left);
707 if (!state->file)
708 return NULL;
709
710 state->fd = fd;
711 state->has_refs = state->ios_left;
712 state->used_refs = 1;
713 state->ios_left--;
714 return state->file;
715}
716
2b188cc1
JA
717/*
718 * If we tracked the file through the SCM inflight mechanism, we could support
719 * any file. For now, just ensure that anything potentially problematic is done
720 * inline.
721 */
722static bool io_file_supports_async(struct file *file)
723{
724 umode_t mode = file_inode(file)->i_mode;
725
726 if (S_ISBLK(mode) || S_ISCHR(mode))
727 return true;
728 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
729 return true;
730
731 return false;
732}
733
6c271ce2 734static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
9a56a232 735 bool force_nonblock, struct io_submit_state *state)
2b188cc1 736{
6c271ce2 737 const struct io_uring_sqe *sqe = s->sqe;
def596e9 738 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 739 struct kiocb *kiocb = &req->rw;
6b06314c 740 unsigned ioprio, flags;
2b188cc1
JA
741 int fd, ret;
742
743 /* For -EAGAIN retry, everything is already prepped */
744 if (kiocb->ki_filp)
745 return 0;
746
6b06314c 747 flags = READ_ONCE(sqe->flags);
2b188cc1 748 fd = READ_ONCE(sqe->fd);
6b06314c
JA
749
750 if (flags & IOSQE_FIXED_FILE) {
751 if (unlikely(!ctx->user_files ||
752 (unsigned) fd >= ctx->nr_user_files))
753 return -EBADF;
754 kiocb->ki_filp = ctx->user_files[fd];
755 req->flags |= REQ_F_FIXED_FILE;
756 } else {
6c271ce2
JA
757 if (s->needs_fixed_file)
758 return -EBADF;
6b06314c
JA
759 kiocb->ki_filp = io_file_get(state, fd);
760 if (unlikely(!kiocb->ki_filp))
761 return -EBADF;
762 if (force_nonblock && !io_file_supports_async(kiocb->ki_filp))
763 force_nonblock = false;
764 }
2b188cc1
JA
765 kiocb->ki_pos = READ_ONCE(sqe->off);
766 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
767 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
768
769 ioprio = READ_ONCE(sqe->ioprio);
770 if (ioprio) {
771 ret = ioprio_check_cap(ioprio);
772 if (ret)
773 goto out_fput;
774
775 kiocb->ki_ioprio = ioprio;
776 } else
777 kiocb->ki_ioprio = get_current_ioprio();
778
779 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
780 if (unlikely(ret))
781 goto out_fput;
782 if (force_nonblock) {
783 kiocb->ki_flags |= IOCB_NOWAIT;
784 req->flags |= REQ_F_FORCE_NONBLOCK;
785 }
def596e9
JA
786 if (ctx->flags & IORING_SETUP_IOPOLL) {
787 ret = -EOPNOTSUPP;
788 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
789 !kiocb->ki_filp->f_op->iopoll)
790 goto out_fput;
2b188cc1 791
def596e9
JA
792 req->error = 0;
793 kiocb->ki_flags |= IOCB_HIPRI;
794 kiocb->ki_complete = io_complete_rw_iopoll;
795 } else {
796 if (kiocb->ki_flags & IOCB_HIPRI) {
797 ret = -EINVAL;
798 goto out_fput;
799 }
800 kiocb->ki_complete = io_complete_rw;
801 }
2b188cc1
JA
802 return 0;
803out_fput:
6b06314c
JA
804 if (!(flags & IOSQE_FIXED_FILE)) {
805 /*
806 * in case of error, we didn't use this file reference. drop it.
807 */
808 if (state)
809 state->used_refs--;
810 io_file_put(state, kiocb->ki_filp);
811 }
2b188cc1
JA
812 return ret;
813}
814
815static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
816{
817 switch (ret) {
818 case -EIOCBQUEUED:
819 break;
820 case -ERESTARTSYS:
821 case -ERESTARTNOINTR:
822 case -ERESTARTNOHAND:
823 case -ERESTART_RESTARTBLOCK:
824 /*
825 * We can't just restart the syscall, since previously
826 * submitted sqes may already be in progress. Just fail this
827 * IO with EINTR.
828 */
829 ret = -EINTR;
830 /* fall through */
831 default:
832 kiocb->ki_complete(kiocb, ret, 0);
833 }
834}
835
edafccee
JA
836static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
837 const struct io_uring_sqe *sqe,
838 struct iov_iter *iter)
839{
840 size_t len = READ_ONCE(sqe->len);
841 struct io_mapped_ubuf *imu;
842 unsigned index, buf_index;
843 size_t offset;
844 u64 buf_addr;
845
846 /* attempt to use fixed buffers without having provided iovecs */
847 if (unlikely(!ctx->user_bufs))
848 return -EFAULT;
849
850 buf_index = READ_ONCE(sqe->buf_index);
851 if (unlikely(buf_index >= ctx->nr_user_bufs))
852 return -EFAULT;
853
854 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
855 imu = &ctx->user_bufs[index];
856 buf_addr = READ_ONCE(sqe->addr);
857
858 /* overflow */
859 if (buf_addr + len < buf_addr)
860 return -EFAULT;
861 /* not inside the mapped region */
862 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
863 return -EFAULT;
864
865 /*
866 * May not be a start of buffer, set size appropriately
867 * and advance us to the beginning.
868 */
869 offset = buf_addr - imu->ubuf;
870 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
871 if (offset)
872 iov_iter_advance(iter, offset);
873 return 0;
874}
875
2b188cc1
JA
876static int io_import_iovec(struct io_ring_ctx *ctx, int rw,
877 const struct sqe_submit *s, struct iovec **iovec,
878 struct iov_iter *iter)
879{
880 const struct io_uring_sqe *sqe = s->sqe;
881 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
882 size_t sqe_len = READ_ONCE(sqe->len);
edafccee
JA
883 u8 opcode;
884
885 /*
886 * We're reading ->opcode for the second time, but the first read
887 * doesn't care whether it's _FIXED or not, so it doesn't matter
888 * whether ->opcode changes concurrently. The first read does care
889 * about whether it is a READ or a WRITE, so we don't trust this read
890 * for that purpose and instead let the caller pass in the read/write
891 * flag.
892 */
893 opcode = READ_ONCE(sqe->opcode);
894 if (opcode == IORING_OP_READ_FIXED ||
895 opcode == IORING_OP_WRITE_FIXED) {
896 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
897 *iovec = NULL;
898 return ret;
899 }
2b188cc1
JA
900
901 if (!s->has_user)
902 return -EFAULT;
903
904#ifdef CONFIG_COMPAT
905 if (ctx->compat)
906 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
907 iovec, iter);
908#endif
909
910 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
911}
912
31b51510
JA
913/*
914 * Make a note of the last file/offset/direction we punted to async
915 * context. We'll use this information to see if we can piggy back a
916 * sequential request onto the previous one, if it's still hasn't been
917 * completed by the async worker.
918 */
919static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
920{
921 struct async_list *async_list = &req->ctx->pending_async[rw];
922 struct kiocb *kiocb = &req->rw;
923 struct file *filp = kiocb->ki_filp;
924 off_t io_end = kiocb->ki_pos + len;
925
926 if (filp == async_list->file && kiocb->ki_pos == async_list->io_end) {
927 unsigned long max_pages;
928
929 /* Use 8x RA size as a decent limiter for both reads/writes */
930 max_pages = filp->f_ra.ra_pages;
931 if (!max_pages)
932 max_pages = VM_MAX_READAHEAD >> (PAGE_SHIFT - 10);
933 max_pages *= 8;
934
935 /* If max pages are exceeded, reset the state */
936 len >>= PAGE_SHIFT;
937 if (async_list->io_pages + len <= max_pages) {
938 req->flags |= REQ_F_SEQ_PREV;
939 async_list->io_pages += len;
940 } else {
941 io_end = 0;
942 async_list->io_pages = 0;
943 }
944 }
945
946 /* New file? Reset state. */
947 if (async_list->file != filp) {
948 async_list->io_pages = 0;
949 async_list->file = filp;
950 }
951 async_list->io_end = io_end;
952}
953
2b188cc1 954static ssize_t io_read(struct io_kiocb *req, const struct sqe_submit *s,
9a56a232 955 bool force_nonblock, struct io_submit_state *state)
2b188cc1
JA
956{
957 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
958 struct kiocb *kiocb = &req->rw;
959 struct iov_iter iter;
960 struct file *file;
31b51510 961 size_t iov_count;
2b188cc1
JA
962 ssize_t ret;
963
6c271ce2 964 ret = io_prep_rw(req, s, force_nonblock, state);
2b188cc1
JA
965 if (ret)
966 return ret;
967 file = kiocb->ki_filp;
968
969 ret = -EBADF;
970 if (unlikely(!(file->f_mode & FMODE_READ)))
971 goto out_fput;
972 ret = -EINVAL;
973 if (unlikely(!file->f_op->read_iter))
974 goto out_fput;
975
976 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
977 if (ret)
978 goto out_fput;
979
31b51510
JA
980 iov_count = iov_iter_count(&iter);
981 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
2b188cc1
JA
982 if (!ret) {
983 ssize_t ret2;
984
985 /* Catch -EAGAIN return for forced non-blocking submission */
986 ret2 = call_read_iter(file, kiocb, &iter);
31b51510 987 if (!force_nonblock || ret2 != -EAGAIN) {
2b188cc1 988 io_rw_done(kiocb, ret2);
31b51510
JA
989 } else {
990 /*
991 * If ->needs_lock is true, we're already in async
992 * context.
993 */
994 if (!s->needs_lock)
995 io_async_list_note(READ, req, iov_count);
2b188cc1 996 ret = -EAGAIN;
31b51510 997 }
2b188cc1
JA
998 }
999 kfree(iovec);
1000out_fput:
1001 /* Hold on to the file for -EAGAIN */
1002 if (unlikely(ret && ret != -EAGAIN))
6b06314c 1003 io_fput(req);
2b188cc1
JA
1004 return ret;
1005}
1006
1007static ssize_t io_write(struct io_kiocb *req, const struct sqe_submit *s,
9a56a232 1008 bool force_nonblock, struct io_submit_state *state)
2b188cc1
JA
1009{
1010 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1011 struct kiocb *kiocb = &req->rw;
1012 struct iov_iter iter;
1013 struct file *file;
31b51510 1014 size_t iov_count;
2b188cc1
JA
1015 ssize_t ret;
1016
6c271ce2 1017 ret = io_prep_rw(req, s, force_nonblock, state);
2b188cc1
JA
1018 if (ret)
1019 return ret;
2b188cc1
JA
1020
1021 ret = -EBADF;
1022 file = kiocb->ki_filp;
1023 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1024 goto out_fput;
1025 ret = -EINVAL;
1026 if (unlikely(!file->f_op->write_iter))
1027 goto out_fput;
1028
1029 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
1030 if (ret)
1031 goto out_fput;
1032
31b51510
JA
1033 iov_count = iov_iter_count(&iter);
1034
1035 ret = -EAGAIN;
1036 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1037 /* If ->needs_lock is true, we're already in async context. */
1038 if (!s->needs_lock)
1039 io_async_list_note(WRITE, req, iov_count);
1040 goto out_free;
1041 }
1042
1043 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
2b188cc1
JA
1044 if (!ret) {
1045 /*
1046 * Open-code file_start_write here to grab freeze protection,
1047 * which will be released by another thread in
1048 * io_complete_rw(). Fool lockdep by telling it the lock got
1049 * released so that it doesn't complain about the held lock when
1050 * we return to userspace.
1051 */
1052 if (S_ISREG(file_inode(file)->i_mode)) {
1053 __sb_start_write(file_inode(file)->i_sb,
1054 SB_FREEZE_WRITE, true);
1055 __sb_writers_release(file_inode(file)->i_sb,
1056 SB_FREEZE_WRITE);
1057 }
1058 kiocb->ki_flags |= IOCB_WRITE;
1059 io_rw_done(kiocb, call_write_iter(file, kiocb, &iter));
1060 }
31b51510 1061out_free:
2b188cc1
JA
1062 kfree(iovec);
1063out_fput:
31b51510
JA
1064 /* Hold on to the file for -EAGAIN */
1065 if (unlikely(ret && ret != -EAGAIN))
6b06314c 1066 io_fput(req);
2b188cc1
JA
1067 return ret;
1068}
1069
1070/*
1071 * IORING_OP_NOP just posts a completion event, nothing else.
1072 */
1073static int io_nop(struct io_kiocb *req, u64 user_data)
1074{
1075 struct io_ring_ctx *ctx = req->ctx;
1076 long err = 0;
1077
def596e9
JA
1078 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1079 return -EINVAL;
1080
2b188cc1
JA
1081 /*
1082 * Twilight zone - it's possible that someone issued an opcode that
1083 * has a file attached, then got -EAGAIN on submission, and changed
1084 * the sqe before we retried it from async context. Avoid dropping
1085 * a file reference for this malicious case, and flag the error.
1086 */
1087 if (req->rw.ki_filp) {
1088 err = -EBADF;
6b06314c 1089 io_fput(req);
2b188cc1
JA
1090 }
1091 io_cqring_add_event(ctx, user_data, err, 0);
e65ef56d 1092 io_put_req(req);
2b188cc1
JA
1093 return 0;
1094}
1095
c992fe29
CH
1096static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1097{
6b06314c
JA
1098 struct io_ring_ctx *ctx = req->ctx;
1099 unsigned flags;
c992fe29
CH
1100 int fd;
1101
1102 /* Prep already done */
1103 if (req->rw.ki_filp)
1104 return 0;
1105
6b06314c 1106 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 1107 return -EINVAL;
edafccee 1108 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
c992fe29
CH
1109 return -EINVAL;
1110
1111 fd = READ_ONCE(sqe->fd);
6b06314c
JA
1112 flags = READ_ONCE(sqe->flags);
1113
1114 if (flags & IOSQE_FIXED_FILE) {
1115 if (unlikely(!ctx->user_files || fd >= ctx->nr_user_files))
1116 return -EBADF;
1117 req->rw.ki_filp = ctx->user_files[fd];
1118 req->flags |= REQ_F_FIXED_FILE;
1119 } else {
1120 req->rw.ki_filp = fget(fd);
1121 if (unlikely(!req->rw.ki_filp))
1122 return -EBADF;
1123 }
c992fe29
CH
1124
1125 return 0;
1126}
1127
1128static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1129 bool force_nonblock)
1130{
1131 loff_t sqe_off = READ_ONCE(sqe->off);
1132 loff_t sqe_len = READ_ONCE(sqe->len);
1133 loff_t end = sqe_off + sqe_len;
1134 unsigned fsync_flags;
1135 int ret;
1136
1137 fsync_flags = READ_ONCE(sqe->fsync_flags);
1138 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1139 return -EINVAL;
1140
1141 ret = io_prep_fsync(req, sqe);
1142 if (ret)
1143 return ret;
1144
1145 /* fsync always requires a blocking context */
1146 if (force_nonblock)
1147 return -EAGAIN;
1148
1149 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1150 end > 0 ? end : LLONG_MAX,
1151 fsync_flags & IORING_FSYNC_DATASYNC);
1152
6b06314c 1153 io_fput(req);
c992fe29 1154 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
e65ef56d 1155 io_put_req(req);
c992fe29
CH
1156 return 0;
1157}
1158
221c5eb2
JA
1159static void io_poll_remove_one(struct io_kiocb *req)
1160{
1161 struct io_poll_iocb *poll = &req->poll;
1162
1163 spin_lock(&poll->head->lock);
1164 WRITE_ONCE(poll->canceled, true);
1165 if (!list_empty(&poll->wait.entry)) {
1166 list_del_init(&poll->wait.entry);
1167 queue_work(req->ctx->sqo_wq, &req->work);
1168 }
1169 spin_unlock(&poll->head->lock);
1170
1171 list_del_init(&req->list);
1172}
1173
1174static void io_poll_remove_all(struct io_ring_ctx *ctx)
1175{
1176 struct io_kiocb *req;
1177
1178 spin_lock_irq(&ctx->completion_lock);
1179 while (!list_empty(&ctx->cancel_list)) {
1180 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1181 io_poll_remove_one(req);
1182 }
1183 spin_unlock_irq(&ctx->completion_lock);
1184}
1185
1186/*
1187 * Find a running poll command that matches one specified in sqe->addr,
1188 * and remove it if found.
1189 */
1190static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1191{
1192 struct io_ring_ctx *ctx = req->ctx;
1193 struct io_kiocb *poll_req, *next;
1194 int ret = -ENOENT;
1195
1196 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1197 return -EINVAL;
1198 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1199 sqe->poll_events)
1200 return -EINVAL;
1201
1202 spin_lock_irq(&ctx->completion_lock);
1203 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1204 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1205 io_poll_remove_one(poll_req);
1206 ret = 0;
1207 break;
1208 }
1209 }
1210 spin_unlock_irq(&ctx->completion_lock);
1211
1212 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
e65ef56d 1213 io_put_req(req);
221c5eb2
JA
1214 return 0;
1215}
1216
1217static void io_poll_complete(struct io_kiocb *req, __poll_t mask)
1218{
1219 io_cqring_add_event(req->ctx, req->user_data, mangle_poll(mask), 0);
1220 io_fput(req);
e65ef56d 1221 io_put_req(req);
221c5eb2
JA
1222}
1223
1224static void io_poll_complete_work(struct work_struct *work)
1225{
1226 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1227 struct io_poll_iocb *poll = &req->poll;
1228 struct poll_table_struct pt = { ._key = poll->events };
1229 struct io_ring_ctx *ctx = req->ctx;
1230 __poll_t mask = 0;
1231
1232 if (!READ_ONCE(poll->canceled))
1233 mask = vfs_poll(poll->file, &pt) & poll->events;
1234
1235 /*
1236 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1237 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1238 * synchronize with them. In the cancellation case the list_del_init
1239 * itself is not actually needed, but harmless so we keep it in to
1240 * avoid further branches in the fast path.
1241 */
1242 spin_lock_irq(&ctx->completion_lock);
1243 if (!mask && !READ_ONCE(poll->canceled)) {
1244 add_wait_queue(poll->head, &poll->wait);
1245 spin_unlock_irq(&ctx->completion_lock);
1246 return;
1247 }
1248 list_del_init(&req->list);
1249 spin_unlock_irq(&ctx->completion_lock);
1250
1251 io_poll_complete(req, mask);
1252}
1253
1254static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1255 void *key)
1256{
1257 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1258 wait);
1259 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1260 struct io_ring_ctx *ctx = req->ctx;
1261 __poll_t mask = key_to_poll(key);
1262
1263 poll->woken = true;
1264
1265 /* for instances that support it check for an event match first: */
1266 if (mask) {
1267 unsigned long flags;
1268
1269 if (!(mask & poll->events))
1270 return 0;
1271
1272 /* try to complete the iocb inline if we can: */
1273 if (spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1274 list_del(&req->list);
1275 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1276
1277 list_del_init(&poll->wait.entry);
1278 io_poll_complete(req, mask);
1279 return 1;
1280 }
1281 }
1282
1283 list_del_init(&poll->wait.entry);
1284 queue_work(ctx->sqo_wq, &req->work);
1285 return 1;
1286}
1287
1288struct io_poll_table {
1289 struct poll_table_struct pt;
1290 struct io_kiocb *req;
1291 int error;
1292};
1293
1294static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1295 struct poll_table_struct *p)
1296{
1297 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1298
1299 if (unlikely(pt->req->poll.head)) {
1300 pt->error = -EINVAL;
1301 return;
1302 }
1303
1304 pt->error = 0;
1305 pt->req->poll.head = head;
1306 add_wait_queue(head, &pt->req->poll.wait);
1307}
1308
1309static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1310{
1311 struct io_poll_iocb *poll = &req->poll;
1312 struct io_ring_ctx *ctx = req->ctx;
1313 struct io_poll_table ipt;
1314 unsigned flags;
1315 __poll_t mask;
1316 u16 events;
1317 int fd;
1318
1319 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1320 return -EINVAL;
1321 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1322 return -EINVAL;
1323
1324 INIT_WORK(&req->work, io_poll_complete_work);
1325 events = READ_ONCE(sqe->poll_events);
1326 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1327
1328 flags = READ_ONCE(sqe->flags);
1329 fd = READ_ONCE(sqe->fd);
1330
1331 if (flags & IOSQE_FIXED_FILE) {
1332 if (unlikely(!ctx->user_files || fd >= ctx->nr_user_files))
1333 return -EBADF;
1334 poll->file = ctx->user_files[fd];
1335 req->flags |= REQ_F_FIXED_FILE;
1336 } else {
1337 poll->file = fget(fd);
1338 }
1339 if (unlikely(!poll->file))
1340 return -EBADF;
1341
1342 poll->head = NULL;
1343 poll->woken = false;
1344 poll->canceled = false;
1345
1346 ipt.pt._qproc = io_poll_queue_proc;
1347 ipt.pt._key = poll->events;
1348 ipt.req = req;
1349 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1350
1351 /* initialized the list so that we can do list_empty checks */
1352 INIT_LIST_HEAD(&poll->wait.entry);
1353 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1354
221c5eb2
JA
1355 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
1356 if (unlikely(!poll->head)) {
1357 /* we did not manage to set up a waitqueue, done */
1358 goto out;
1359 }
1360
1361 spin_lock_irq(&ctx->completion_lock);
1362 spin_lock(&poll->head->lock);
1363 if (poll->woken) {
1364 /* wake_up context handles the rest */
1365 mask = 0;
1366 ipt.error = 0;
1367 } else if (mask || ipt.error) {
1368 /* if we get an error or a mask we are done */
1369 WARN_ON_ONCE(list_empty(&poll->wait.entry));
1370 list_del_init(&poll->wait.entry);
1371 } else {
1372 /* actually waiting for an event */
1373 list_add_tail(&req->list, &ctx->cancel_list);
1374 }
1375 spin_unlock(&poll->head->lock);
1376 spin_unlock_irq(&ctx->completion_lock);
1377
1378out:
1379 if (unlikely(ipt.error)) {
1380 if (!(flags & IOSQE_FIXED_FILE))
1381 fput(poll->file);
1382 /*
1383 * Drop one of our refs to this req, __io_submit_sqe() will
1384 * drop the other one since we're returning an error.
1385 */
e65ef56d 1386 io_put_req(req);
221c5eb2
JA
1387 return ipt.error;
1388 }
1389
1390 if (mask)
1391 io_poll_complete(req, mask);
221c5eb2
JA
1392 return 0;
1393}
1394
2b188cc1 1395static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
9a56a232
JA
1396 const struct sqe_submit *s, bool force_nonblock,
1397 struct io_submit_state *state)
2b188cc1
JA
1398{
1399 ssize_t ret;
1400 int opcode;
1401
1402 if (unlikely(s->index >= ctx->sq_entries))
1403 return -EINVAL;
1404 req->user_data = READ_ONCE(s->sqe->user_data);
1405
1406 opcode = READ_ONCE(s->sqe->opcode);
1407 switch (opcode) {
1408 case IORING_OP_NOP:
1409 ret = io_nop(req, req->user_data);
1410 break;
1411 case IORING_OP_READV:
edafccee
JA
1412 if (unlikely(s->sqe->buf_index))
1413 return -EINVAL;
9a56a232 1414 ret = io_read(req, s, force_nonblock, state);
2b188cc1
JA
1415 break;
1416 case IORING_OP_WRITEV:
edafccee
JA
1417 if (unlikely(s->sqe->buf_index))
1418 return -EINVAL;
1419 ret = io_write(req, s, force_nonblock, state);
1420 break;
1421 case IORING_OP_READ_FIXED:
1422 ret = io_read(req, s, force_nonblock, state);
1423 break;
1424 case IORING_OP_WRITE_FIXED:
9a56a232 1425 ret = io_write(req, s, force_nonblock, state);
2b188cc1 1426 break;
c992fe29
CH
1427 case IORING_OP_FSYNC:
1428 ret = io_fsync(req, s->sqe, force_nonblock);
1429 break;
221c5eb2
JA
1430 case IORING_OP_POLL_ADD:
1431 ret = io_poll_add(req, s->sqe);
1432 break;
1433 case IORING_OP_POLL_REMOVE:
1434 ret = io_poll_remove(req, s->sqe);
1435 break;
2b188cc1
JA
1436 default:
1437 ret = -EINVAL;
1438 break;
1439 }
1440
def596e9
JA
1441 if (ret)
1442 return ret;
1443
1444 if (ctx->flags & IORING_SETUP_IOPOLL) {
1445 if (req->error == -EAGAIN)
1446 return -EAGAIN;
1447
1448 /* workqueue context doesn't hold uring_lock, grab it now */
1449 if (s->needs_lock)
1450 mutex_lock(&ctx->uring_lock);
1451 io_iopoll_req_issued(req);
1452 if (s->needs_lock)
1453 mutex_unlock(&ctx->uring_lock);
1454 }
1455
1456 return 0;
2b188cc1
JA
1457}
1458
31b51510
JA
1459static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
1460 const struct io_uring_sqe *sqe)
1461{
1462 switch (sqe->opcode) {
1463 case IORING_OP_READV:
1464 case IORING_OP_READ_FIXED:
1465 return &ctx->pending_async[READ];
1466 case IORING_OP_WRITEV:
1467 case IORING_OP_WRITE_FIXED:
1468 return &ctx->pending_async[WRITE];
1469 default:
1470 return NULL;
1471 }
1472}
1473
edafccee
JA
1474static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
1475{
1476 u8 opcode = READ_ONCE(sqe->opcode);
1477
1478 return !(opcode == IORING_OP_READ_FIXED ||
1479 opcode == IORING_OP_WRITE_FIXED);
1480}
1481
2b188cc1
JA
1482static void io_sq_wq_submit_work(struct work_struct *work)
1483{
1484 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2b188cc1 1485 struct io_ring_ctx *ctx = req->ctx;
31b51510
JA
1486 struct mm_struct *cur_mm = NULL;
1487 struct async_list *async_list;
1488 LIST_HEAD(req_list);
edafccee 1489 mm_segment_t old_fs;
2b188cc1
JA
1490 int ret;
1491
31b51510
JA
1492 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
1493restart:
1494 do {
1495 struct sqe_submit *s = &req->submit;
1496 const struct io_uring_sqe *sqe = s->sqe;
2b188cc1 1497
31b51510
JA
1498 /* Ensure we clear previously set forced non-block flag */
1499 req->flags &= ~REQ_F_FORCE_NONBLOCK;
1500 req->rw.ki_flags &= ~IOCB_NOWAIT;
1501
1502 ret = 0;
1503 if (io_sqe_needs_user(sqe) && !cur_mm) {
1504 if (!mmget_not_zero(ctx->sqo_mm)) {
1505 ret = -EFAULT;
1506 } else {
1507 cur_mm = ctx->sqo_mm;
1508 use_mm(cur_mm);
1509 old_fs = get_fs();
1510 set_fs(USER_DS);
1511 }
1512 }
1513
1514 if (!ret) {
1515 s->has_user = cur_mm != NULL;
1516 s->needs_lock = true;
1517 do {
1518 ret = __io_submit_sqe(ctx, req, s, false, NULL);
1519 /*
1520 * We can get EAGAIN for polled IO even though
1521 * we're forcing a sync submission from here,
1522 * since we can't wait for request slots on the
1523 * block side.
1524 */
1525 if (ret != -EAGAIN)
1526 break;
1527 cond_resched();
1528 } while (1);
e65ef56d
JA
1529
1530 /* drop submission reference */
1531 io_put_req(req);
31b51510
JA
1532 }
1533 if (ret) {
1534 io_cqring_add_event(ctx, sqe->user_data, ret, 0);
e65ef56d 1535 io_put_req(req);
31b51510
JA
1536 }
1537
1538 /* async context always use a copy of the sqe */
1539 kfree(sqe);
1540
1541 if (!async_list)
1542 break;
1543 if (!list_empty(&req_list)) {
1544 req = list_first_entry(&req_list, struct io_kiocb,
1545 list);
1546 list_del(&req->list);
1547 continue;
1548 }
1549 if (list_empty(&async_list->list))
1550 break;
1551
1552 req = NULL;
1553 spin_lock(&async_list->lock);
1554 if (list_empty(&async_list->list)) {
1555 spin_unlock(&async_list->lock);
1556 break;
1557 }
1558 list_splice_init(&async_list->list, &req_list);
1559 spin_unlock(&async_list->lock);
1560
1561 req = list_first_entry(&req_list, struct io_kiocb, list);
1562 list_del(&req->list);
1563 } while (req);
edafccee
JA
1564
1565 /*
31b51510
JA
1566 * Rare case of racing with a submitter. If we find the count has
1567 * dropped to zero AND we have pending work items, then restart
1568 * the processing. This is a tiny race window.
edafccee 1569 */
31b51510
JA
1570 if (async_list) {
1571 ret = atomic_dec_return(&async_list->cnt);
1572 while (!ret && !list_empty(&async_list->list)) {
1573 spin_lock(&async_list->lock);
1574 atomic_inc(&async_list->cnt);
1575 list_splice_init(&async_list->list, &req_list);
1576 spin_unlock(&async_list->lock);
1577
1578 if (!list_empty(&req_list)) {
1579 req = list_first_entry(&req_list,
1580 struct io_kiocb, list);
1581 list_del(&req->list);
1582 goto restart;
1583 }
1584 ret = atomic_dec_return(&async_list->cnt);
edafccee 1585 }
edafccee 1586 }
2b188cc1 1587
31b51510 1588 if (cur_mm) {
edafccee 1589 set_fs(old_fs);
31b51510
JA
1590 unuse_mm(cur_mm);
1591 mmput(cur_mm);
2b188cc1 1592 }
31b51510 1593}
2b188cc1 1594
31b51510
JA
1595/*
1596 * See if we can piggy back onto previously submitted work, that is still
1597 * running. We currently only allow this if the new request is sequential
1598 * to the previous one we punted.
1599 */
1600static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
1601{
1602 bool ret = false;
1603
1604 if (!list)
1605 return false;
1606 if (!(req->flags & REQ_F_SEQ_PREV))
1607 return false;
1608 if (!atomic_read(&list->cnt))
1609 return false;
1610
1611 ret = true;
1612 spin_lock(&list->lock);
1613 list_add_tail(&req->list, &list->list);
1614 if (!atomic_read(&list->cnt)) {
1615 list_del_init(&req->list);
1616 ret = false;
1617 }
1618 spin_unlock(&list->lock);
1619 return ret;
2b188cc1
JA
1620}
1621
9a56a232
JA
1622static int io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
1623 struct io_submit_state *state)
2b188cc1
JA
1624{
1625 struct io_kiocb *req;
1626 ssize_t ret;
1627
1628 /* enforce forwards compatibility on users */
6b06314c 1629 if (unlikely(s->sqe->flags & ~IOSQE_FIXED_FILE))
2b188cc1
JA
1630 return -EINVAL;
1631
2579f913 1632 req = io_get_req(ctx, state);
2b188cc1
JA
1633 if (unlikely(!req))
1634 return -EAGAIN;
1635
1636 req->rw.ki_filp = NULL;
1637
9a56a232 1638 ret = __io_submit_sqe(ctx, req, s, true, state);
2b188cc1
JA
1639 if (ret == -EAGAIN) {
1640 struct io_uring_sqe *sqe_copy;
1641
1642 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1643 if (sqe_copy) {
31b51510
JA
1644 struct async_list *list;
1645
2b188cc1
JA
1646 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
1647 s->sqe = sqe_copy;
1648
1649 memcpy(&req->submit, s, sizeof(*s));
31b51510
JA
1650 list = io_async_list_from_sqe(ctx, s->sqe);
1651 if (!io_add_to_prev_work(list, req)) {
1652 if (list)
1653 atomic_inc(&list->cnt);
1654 INIT_WORK(&req->work, io_sq_wq_submit_work);
1655 queue_work(ctx->sqo_wq, &req->work);
1656 }
e65ef56d
JA
1657
1658 /*
1659 * Queued up for async execution, worker will release
1660 * submit reference when the iocb is actually
1661 * submitted.
1662 */
1663 return 0;
2b188cc1
JA
1664 }
1665 }
e65ef56d
JA
1666
1667 /* drop submission reference */
1668 io_put_req(req);
1669
1670 /* and drop final reference, if we failed */
2b188cc1 1671 if (ret)
e65ef56d 1672 io_put_req(req);
2b188cc1
JA
1673
1674 return ret;
1675}
1676
9a56a232
JA
1677/*
1678 * Batched submission is done, ensure local IO is flushed out.
1679 */
1680static void io_submit_state_end(struct io_submit_state *state)
1681{
1682 blk_finish_plug(&state->plug);
1683 io_file_put(state, NULL);
2579f913
JA
1684 if (state->free_reqs)
1685 kmem_cache_free_bulk(req_cachep, state->free_reqs,
1686 &state->reqs[state->cur_req]);
9a56a232
JA
1687}
1688
1689/*
1690 * Start submission side cache.
1691 */
1692static void io_submit_state_start(struct io_submit_state *state,
1693 struct io_ring_ctx *ctx, unsigned max_ios)
1694{
1695 blk_start_plug(&state->plug);
2579f913 1696 state->free_reqs = 0;
9a56a232
JA
1697 state->file = NULL;
1698 state->ios_left = max_ios;
1699}
1700
2b188cc1
JA
1701static void io_commit_sqring(struct io_ring_ctx *ctx)
1702{
1703 struct io_sq_ring *ring = ctx->sq_ring;
1704
1705 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
1706 /*
1707 * Ensure any loads from the SQEs are done at this point,
1708 * since once we write the new head, the application could
1709 * write new data to them.
1710 */
1711 smp_store_release(&ring->r.head, ctx->cached_sq_head);
1712
1713 /*
1714 * write side barrier of head update, app has read side. See
1715 * comment at the top of this file
1716 */
1717 smp_wmb();
1718 }
1719}
1720
1721/*
1722 * Undo last io_get_sqring()
1723 */
1724static void io_drop_sqring(struct io_ring_ctx *ctx)
1725{
1726 ctx->cached_sq_head--;
1727}
1728
1729/*
1730 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
1731 * that is mapped by userspace. This means that care needs to be taken to
1732 * ensure that reads are stable, as we cannot rely on userspace always
1733 * being a good citizen. If members of the sqe are validated and then later
1734 * used, it's important that those reads are done through READ_ONCE() to
1735 * prevent a re-load down the line.
1736 */
1737static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
1738{
1739 struct io_sq_ring *ring = ctx->sq_ring;
1740 unsigned head;
1741
1742 /*
1743 * The cached sq head (or cq tail) serves two purposes:
1744 *
1745 * 1) allows us to batch the cost of updating the user visible
1746 * head updates.
1747 * 2) allows the kernel side to track the head on its own, even
1748 * though the application is the one updating it.
1749 */
1750 head = ctx->cached_sq_head;
1751 /* See comment at the top of this file */
1752 smp_rmb();
1753 if (head == READ_ONCE(ring->r.tail))
1754 return false;
1755
1756 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
1757 if (head < ctx->sq_entries) {
1758 s->index = head;
1759 s->sqe = &ctx->sq_sqes[head];
1760 ctx->cached_sq_head++;
1761 return true;
1762 }
1763
1764 /* drop invalid entries */
1765 ctx->cached_sq_head++;
1766 ring->dropped++;
1767 /* See comment at the top of this file */
1768 smp_wmb();
1769 return false;
1770}
1771
6c271ce2
JA
1772static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
1773 unsigned int nr, bool has_user, bool mm_fault)
1774{
1775 struct io_submit_state state, *statep = NULL;
1776 int ret, i, submitted = 0;
1777
1778 if (nr > IO_PLUG_THRESHOLD) {
1779 io_submit_state_start(&state, ctx, nr);
1780 statep = &state;
1781 }
1782
1783 for (i = 0; i < nr; i++) {
1784 if (unlikely(mm_fault)) {
1785 ret = -EFAULT;
1786 } else {
1787 sqes[i].has_user = has_user;
1788 sqes[i].needs_lock = true;
1789 sqes[i].needs_fixed_file = true;
1790 ret = io_submit_sqe(ctx, &sqes[i], statep);
1791 }
1792 if (!ret) {
1793 submitted++;
1794 continue;
1795 }
1796
1797 io_cqring_add_event(ctx, sqes[i].sqe->user_data, ret, 0);
1798 }
1799
1800 if (statep)
1801 io_submit_state_end(&state);
1802
1803 return submitted;
1804}
1805
1806static int io_sq_thread(void *data)
1807{
1808 struct sqe_submit sqes[IO_IOPOLL_BATCH];
1809 struct io_ring_ctx *ctx = data;
1810 struct mm_struct *cur_mm = NULL;
1811 mm_segment_t old_fs;
1812 DEFINE_WAIT(wait);
1813 unsigned inflight;
1814 unsigned long timeout;
1815
1816 old_fs = get_fs();
1817 set_fs(USER_DS);
1818
1819 timeout = inflight = 0;
1820 while (!kthread_should_stop() && !ctx->sqo_stop) {
1821 bool all_fixed, mm_fault = false;
1822 int i;
1823
1824 if (inflight) {
1825 unsigned nr_events = 0;
1826
1827 if (ctx->flags & IORING_SETUP_IOPOLL) {
1828 /*
1829 * We disallow the app entering submit/complete
1830 * with polling, but we still need to lock the
1831 * ring to prevent racing with polled issue
1832 * that got punted to a workqueue.
1833 */
1834 mutex_lock(&ctx->uring_lock);
1835 io_iopoll_check(ctx, &nr_events, 0);
1836 mutex_unlock(&ctx->uring_lock);
1837 } else {
1838 /*
1839 * Normal IO, just pretend everything completed.
1840 * We don't have to poll completions for that.
1841 */
1842 nr_events = inflight;
1843 }
1844
1845 inflight -= nr_events;
1846 if (!inflight)
1847 timeout = jiffies + ctx->sq_thread_idle;
1848 }
1849
1850 if (!io_get_sqring(ctx, &sqes[0])) {
1851 /*
1852 * We're polling. If we're within the defined idle
1853 * period, then let us spin without work before going
1854 * to sleep.
1855 */
1856 if (inflight || !time_after(jiffies, timeout)) {
1857 cpu_relax();
1858 continue;
1859 }
1860
1861 /*
1862 * Drop cur_mm before scheduling, we can't hold it for
1863 * long periods (or over schedule()). Do this before
1864 * adding ourselves to the waitqueue, as the unuse/drop
1865 * may sleep.
1866 */
1867 if (cur_mm) {
1868 unuse_mm(cur_mm);
1869 mmput(cur_mm);
1870 cur_mm = NULL;
1871 }
1872
1873 prepare_to_wait(&ctx->sqo_wait, &wait,
1874 TASK_INTERRUPTIBLE);
1875
1876 /* Tell userspace we may need a wakeup call */
1877 ctx->sq_ring->flags |= IORING_SQ_NEED_WAKEUP;
1878 smp_wmb();
1879
1880 if (!io_get_sqring(ctx, &sqes[0])) {
1881 if (kthread_should_stop()) {
1882 finish_wait(&ctx->sqo_wait, &wait);
1883 break;
1884 }
1885 if (signal_pending(current))
1886 flush_signals(current);
1887 schedule();
1888 finish_wait(&ctx->sqo_wait, &wait);
1889
1890 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
1891 smp_wmb();
1892 continue;
1893 }
1894 finish_wait(&ctx->sqo_wait, &wait);
1895
1896 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
1897 smp_wmb();
1898 }
1899
1900 i = 0;
1901 all_fixed = true;
1902 do {
1903 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
1904 all_fixed = false;
1905
1906 i++;
1907 if (i == ARRAY_SIZE(sqes))
1908 break;
1909 } while (io_get_sqring(ctx, &sqes[i]));
1910
1911 /* Unless all new commands are FIXED regions, grab mm */
1912 if (!all_fixed && !cur_mm) {
1913 mm_fault = !mmget_not_zero(ctx->sqo_mm);
1914 if (!mm_fault) {
1915 use_mm(ctx->sqo_mm);
1916 cur_mm = ctx->sqo_mm;
1917 }
1918 }
1919
1920 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
1921 mm_fault);
1922
1923 /* Commit SQ ring head once we've consumed all SQEs */
1924 io_commit_sqring(ctx);
1925 }
1926
1927 set_fs(old_fs);
1928 if (cur_mm) {
1929 unuse_mm(cur_mm);
1930 mmput(cur_mm);
1931 }
1932 return 0;
1933}
1934
2b188cc1
JA
1935static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
1936{
9a56a232 1937 struct io_submit_state state, *statep = NULL;
2b188cc1 1938 int i, ret = 0, submit = 0;
2b188cc1 1939
9a56a232
JA
1940 if (to_submit > IO_PLUG_THRESHOLD) {
1941 io_submit_state_start(&state, ctx, to_submit);
1942 statep = &state;
1943 }
2b188cc1
JA
1944
1945 for (i = 0; i < to_submit; i++) {
1946 struct sqe_submit s;
1947
1948 if (!io_get_sqring(ctx, &s))
1949 break;
1950
1951 s.has_user = true;
def596e9 1952 s.needs_lock = false;
6c271ce2 1953 s.needs_fixed_file = false;
def596e9 1954
9a56a232 1955 ret = io_submit_sqe(ctx, &s, statep);
2b188cc1
JA
1956 if (ret) {
1957 io_drop_sqring(ctx);
1958 break;
1959 }
1960
1961 submit++;
1962 }
1963 io_commit_sqring(ctx);
1964
9a56a232
JA
1965 if (statep)
1966 io_submit_state_end(statep);
2b188cc1
JA
1967
1968 return submit ? submit : ret;
1969}
1970
1971static unsigned io_cqring_events(struct io_cq_ring *ring)
1972{
1973 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
1974}
1975
1976/*
1977 * Wait until events become available, if we don't already have some. The
1978 * application must reap them itself, as they reside on the shared cq ring.
1979 */
1980static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
1981 const sigset_t __user *sig, size_t sigsz)
1982{
1983 struct io_cq_ring *ring = ctx->cq_ring;
1984 sigset_t ksigmask, sigsaved;
1985 DEFINE_WAIT(wait);
1986 int ret;
1987
1988 /* See comment at the top of this file */
1989 smp_rmb();
1990 if (io_cqring_events(ring) >= min_events)
1991 return 0;
1992
1993 if (sig) {
1994 ret = set_user_sigmask(sig, &ksigmask, &sigsaved, sigsz);
1995 if (ret)
1996 return ret;
1997 }
1998
1999 do {
2000 prepare_to_wait(&ctx->wait, &wait, TASK_INTERRUPTIBLE);
2001
2002 ret = 0;
2003 /* See comment at the top of this file */
2004 smp_rmb();
2005 if (io_cqring_events(ring) >= min_events)
2006 break;
2007
2008 schedule();
2009
2010 ret = -EINTR;
2011 if (signal_pending(current))
2012 break;
2013 } while (1);
2014
2015 finish_wait(&ctx->wait, &wait);
2016
2017 if (sig)
2018 restore_user_sigmask(sig, &sigsaved);
2019
2020 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
2021}
2022
6b06314c
JA
2023static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
2024{
2025#if defined(CONFIG_UNIX)
2026 if (ctx->ring_sock) {
2027 struct sock *sock = ctx->ring_sock->sk;
2028 struct sk_buff *skb;
2029
2030 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
2031 kfree_skb(skb);
2032 }
2033#else
2034 int i;
2035
2036 for (i = 0; i < ctx->nr_user_files; i++)
2037 fput(ctx->user_files[i]);
2038#endif
2039}
2040
2041static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
2042{
2043 if (!ctx->user_files)
2044 return -ENXIO;
2045
2046 __io_sqe_files_unregister(ctx);
2047 kfree(ctx->user_files);
2048 ctx->user_files = NULL;
2049 ctx->nr_user_files = 0;
2050 return 0;
2051}
2052
6c271ce2
JA
2053static void io_sq_thread_stop(struct io_ring_ctx *ctx)
2054{
2055 if (ctx->sqo_thread) {
2056 ctx->sqo_stop = 1;
2057 mb();
2058 kthread_stop(ctx->sqo_thread);
2059 ctx->sqo_thread = NULL;
2060 }
2061}
2062
6b06314c
JA
2063static void io_finish_async(struct io_ring_ctx *ctx)
2064{
6c271ce2
JA
2065 io_sq_thread_stop(ctx);
2066
6b06314c
JA
2067 if (ctx->sqo_wq) {
2068 destroy_workqueue(ctx->sqo_wq);
2069 ctx->sqo_wq = NULL;
2070 }
2071}
2072
2073#if defined(CONFIG_UNIX)
2074static void io_destruct_skb(struct sk_buff *skb)
2075{
2076 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
2077
2078 io_finish_async(ctx);
2079 unix_destruct_scm(skb);
2080}
2081
2082/*
2083 * Ensure the UNIX gc is aware of our file set, so we are certain that
2084 * the io_uring can be safely unregistered on process exit, even if we have
2085 * loops in the file referencing.
2086 */
2087static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
2088{
2089 struct sock *sk = ctx->ring_sock->sk;
2090 struct scm_fp_list *fpl;
2091 struct sk_buff *skb;
2092 int i;
2093
2094 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
2095 unsigned long inflight = ctx->user->unix_inflight + nr;
2096
2097 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
2098 return -EMFILE;
2099 }
2100
2101 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
2102 if (!fpl)
2103 return -ENOMEM;
2104
2105 skb = alloc_skb(0, GFP_KERNEL);
2106 if (!skb) {
2107 kfree(fpl);
2108 return -ENOMEM;
2109 }
2110
2111 skb->sk = sk;
2112 skb->destructor = io_destruct_skb;
2113
2114 fpl->user = get_uid(ctx->user);
2115 for (i = 0; i < nr; i++) {
2116 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
2117 unix_inflight(fpl->user, fpl->fp[i]);
2118 }
2119
2120 fpl->max = fpl->count = nr;
2121 UNIXCB(skb).fp = fpl;
2122 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2123 skb_queue_head(&sk->sk_receive_queue, skb);
2124
2125 for (i = 0; i < nr; i++)
2126 fput(fpl->fp[i]);
2127
2128 return 0;
2129}
2130
2131/*
2132 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
2133 * causes regular reference counting to break down. We rely on the UNIX
2134 * garbage collection to take care of this problem for us.
2135 */
2136static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2137{
2138 unsigned left, total;
2139 int ret = 0;
2140
2141 total = 0;
2142 left = ctx->nr_user_files;
2143 while (left) {
2144 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
2145 int ret;
2146
2147 ret = __io_sqe_files_scm(ctx, this_files, total);
2148 if (ret)
2149 break;
2150 left -= this_files;
2151 total += this_files;
2152 }
2153
2154 if (!ret)
2155 return 0;
2156
2157 while (total < ctx->nr_user_files) {
2158 fput(ctx->user_files[total]);
2159 total++;
2160 }
2161
2162 return ret;
2163}
2164#else
2165static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2166{
2167 return 0;
2168}
2169#endif
2170
2171static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
2172 unsigned nr_args)
2173{
2174 __s32 __user *fds = (__s32 __user *) arg;
2175 int fd, ret = 0;
2176 unsigned i;
2177
2178 if (ctx->user_files)
2179 return -EBUSY;
2180 if (!nr_args)
2181 return -EINVAL;
2182 if (nr_args > IORING_MAX_FIXED_FILES)
2183 return -EMFILE;
2184
2185 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
2186 if (!ctx->user_files)
2187 return -ENOMEM;
2188
2189 for (i = 0; i < nr_args; i++) {
2190 ret = -EFAULT;
2191 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
2192 break;
2193
2194 ctx->user_files[i] = fget(fd);
2195
2196 ret = -EBADF;
2197 if (!ctx->user_files[i])
2198 break;
2199 /*
2200 * Don't allow io_uring instances to be registered. If UNIX
2201 * isn't enabled, then this causes a reference cycle and this
2202 * instance can never get freed. If UNIX is enabled we'll
2203 * handle it just fine, but there's still no point in allowing
2204 * a ring fd as it doesn't support regular read/write anyway.
2205 */
2206 if (ctx->user_files[i]->f_op == &io_uring_fops) {
2207 fput(ctx->user_files[i]);
2208 break;
2209 }
2210 ctx->nr_user_files++;
2211 ret = 0;
2212 }
2213
2214 if (ret) {
2215 for (i = 0; i < ctx->nr_user_files; i++)
2216 fput(ctx->user_files[i]);
2217
2218 kfree(ctx->user_files);
2219 ctx->nr_user_files = 0;
2220 return ret;
2221 }
2222
2223 ret = io_sqe_files_scm(ctx);
2224 if (ret)
2225 io_sqe_files_unregister(ctx);
2226
2227 return ret;
2228}
2229
6c271ce2
JA
2230static int io_sq_offload_start(struct io_ring_ctx *ctx,
2231 struct io_uring_params *p)
2b188cc1
JA
2232{
2233 int ret;
2234
6c271ce2 2235 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
2236 mmgrab(current->mm);
2237 ctx->sqo_mm = current->mm;
2238
6c271ce2
JA
2239 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
2240 if (!ctx->sq_thread_idle)
2241 ctx->sq_thread_idle = HZ;
2242
2243 ret = -EINVAL;
2244 if (!cpu_possible(p->sq_thread_cpu))
2245 goto err;
2246
2247 if (ctx->flags & IORING_SETUP_SQPOLL) {
2248 if (p->flags & IORING_SETUP_SQ_AFF) {
2249 int cpu;
2250
2251 cpu = array_index_nospec(p->sq_thread_cpu, NR_CPUS);
2252 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
2253 ctx, cpu,
2254 "io_uring-sq");
2255 } else {
2256 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
2257 "io_uring-sq");
2258 }
2259 if (IS_ERR(ctx->sqo_thread)) {
2260 ret = PTR_ERR(ctx->sqo_thread);
2261 ctx->sqo_thread = NULL;
2262 goto err;
2263 }
2264 wake_up_process(ctx->sqo_thread);
2265 } else if (p->flags & IORING_SETUP_SQ_AFF) {
2266 /* Can't have SQ_AFF without SQPOLL */
2267 ret = -EINVAL;
2268 goto err;
2269 }
2270
2b188cc1
JA
2271 /* Do QD, or 2 * CPUS, whatever is smallest */
2272 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
2273 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
2274 if (!ctx->sqo_wq) {
2275 ret = -ENOMEM;
2276 goto err;
2277 }
2278
2279 return 0;
2280err:
6c271ce2 2281 io_sq_thread_stop(ctx);
2b188cc1
JA
2282 mmdrop(ctx->sqo_mm);
2283 ctx->sqo_mm = NULL;
2284 return ret;
2285}
2286
2287static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
2288{
2289 atomic_long_sub(nr_pages, &user->locked_vm);
2290}
2291
2292static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
2293{
2294 unsigned long page_limit, cur_pages, new_pages;
2295
2296 /* Don't allow more pages than we can safely lock */
2297 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
2298
2299 do {
2300 cur_pages = atomic_long_read(&user->locked_vm);
2301 new_pages = cur_pages + nr_pages;
2302 if (new_pages > page_limit)
2303 return -ENOMEM;
2304 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
2305 new_pages) != cur_pages);
2306
2307 return 0;
2308}
2309
2310static void io_mem_free(void *ptr)
2311{
2312 struct page *page = virt_to_head_page(ptr);
2313
2314 if (put_page_testzero(page))
2315 free_compound_page(page);
2316}
2317
2318static void *io_mem_alloc(size_t size)
2319{
2320 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
2321 __GFP_NORETRY;
2322
2323 return (void *) __get_free_pages(gfp_flags, get_order(size));
2324}
2325
2326static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
2327{
2328 struct io_sq_ring *sq_ring;
2329 struct io_cq_ring *cq_ring;
2330 size_t bytes;
2331
2332 bytes = struct_size(sq_ring, array, sq_entries);
2333 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
2334 bytes += struct_size(cq_ring, cqes, cq_entries);
2335
2336 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
2337}
2338
edafccee
JA
2339static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
2340{
2341 int i, j;
2342
2343 if (!ctx->user_bufs)
2344 return -ENXIO;
2345
2346 for (i = 0; i < ctx->nr_user_bufs; i++) {
2347 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2348
2349 for (j = 0; j < imu->nr_bvecs; j++)
2350 put_page(imu->bvec[j].bv_page);
2351
2352 if (ctx->account_mem)
2353 io_unaccount_mem(ctx->user, imu->nr_bvecs);
2354 kfree(imu->bvec);
2355 imu->nr_bvecs = 0;
2356 }
2357
2358 kfree(ctx->user_bufs);
2359 ctx->user_bufs = NULL;
2360 ctx->nr_user_bufs = 0;
2361 return 0;
2362}
2363
2364static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
2365 void __user *arg, unsigned index)
2366{
2367 struct iovec __user *src;
2368
2369#ifdef CONFIG_COMPAT
2370 if (ctx->compat) {
2371 struct compat_iovec __user *ciovs;
2372 struct compat_iovec ciov;
2373
2374 ciovs = (struct compat_iovec __user *) arg;
2375 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
2376 return -EFAULT;
2377
2378 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
2379 dst->iov_len = ciov.iov_len;
2380 return 0;
2381 }
2382#endif
2383 src = (struct iovec __user *) arg;
2384 if (copy_from_user(dst, &src[index], sizeof(*dst)))
2385 return -EFAULT;
2386 return 0;
2387}
2388
2389static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
2390 unsigned nr_args)
2391{
2392 struct vm_area_struct **vmas = NULL;
2393 struct page **pages = NULL;
2394 int i, j, got_pages = 0;
2395 int ret = -EINVAL;
2396
2397 if (ctx->user_bufs)
2398 return -EBUSY;
2399 if (!nr_args || nr_args > UIO_MAXIOV)
2400 return -EINVAL;
2401
2402 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
2403 GFP_KERNEL);
2404 if (!ctx->user_bufs)
2405 return -ENOMEM;
2406
2407 for (i = 0; i < nr_args; i++) {
2408 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2409 unsigned long off, start, end, ubuf;
2410 int pret, nr_pages;
2411 struct iovec iov;
2412 size_t size;
2413
2414 ret = io_copy_iov(ctx, &iov, arg, i);
2415 if (ret)
2416 break;
2417
2418 /*
2419 * Don't impose further limits on the size and buffer
2420 * constraints here, we'll -EINVAL later when IO is
2421 * submitted if they are wrong.
2422 */
2423 ret = -EFAULT;
2424 if (!iov.iov_base || !iov.iov_len)
2425 goto err;
2426
2427 /* arbitrary limit, but we need something */
2428 if (iov.iov_len > SZ_1G)
2429 goto err;
2430
2431 ubuf = (unsigned long) iov.iov_base;
2432 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2433 start = ubuf >> PAGE_SHIFT;
2434 nr_pages = end - start;
2435
2436 if (ctx->account_mem) {
2437 ret = io_account_mem(ctx->user, nr_pages);
2438 if (ret)
2439 goto err;
2440 }
2441
2442 ret = 0;
2443 if (!pages || nr_pages > got_pages) {
2444 kfree(vmas);
2445 kfree(pages);
2446 pages = kmalloc_array(nr_pages, sizeof(struct page *),
2447 GFP_KERNEL);
2448 vmas = kmalloc_array(nr_pages,
2449 sizeof(struct vm_area_struct *),
2450 GFP_KERNEL);
2451 if (!pages || !vmas) {
2452 ret = -ENOMEM;
2453 if (ctx->account_mem)
2454 io_unaccount_mem(ctx->user, nr_pages);
2455 goto err;
2456 }
2457 got_pages = nr_pages;
2458 }
2459
2460 imu->bvec = kmalloc_array(nr_pages, sizeof(struct bio_vec),
2461 GFP_KERNEL);
2462 ret = -ENOMEM;
2463 if (!imu->bvec) {
2464 if (ctx->account_mem)
2465 io_unaccount_mem(ctx->user, nr_pages);
2466 goto err;
2467 }
2468
2469 ret = 0;
2470 down_read(&current->mm->mmap_sem);
2471 pret = get_user_pages_longterm(ubuf, nr_pages, FOLL_WRITE,
2472 pages, vmas);
2473 if (pret == nr_pages) {
2474 /* don't support file backed memory */
2475 for (j = 0; j < nr_pages; j++) {
2476 struct vm_area_struct *vma = vmas[j];
2477
2478 if (vma->vm_file &&
2479 !is_file_hugepages(vma->vm_file)) {
2480 ret = -EOPNOTSUPP;
2481 break;
2482 }
2483 }
2484 } else {
2485 ret = pret < 0 ? pret : -EFAULT;
2486 }
2487 up_read(&current->mm->mmap_sem);
2488 if (ret) {
2489 /*
2490 * if we did partial map, or found file backed vmas,
2491 * release any pages we did get
2492 */
2493 if (pret > 0) {
2494 for (j = 0; j < pret; j++)
2495 put_page(pages[j]);
2496 }
2497 if (ctx->account_mem)
2498 io_unaccount_mem(ctx->user, nr_pages);
2499 goto err;
2500 }
2501
2502 off = ubuf & ~PAGE_MASK;
2503 size = iov.iov_len;
2504 for (j = 0; j < nr_pages; j++) {
2505 size_t vec_len;
2506
2507 vec_len = min_t(size_t, size, PAGE_SIZE - off);
2508 imu->bvec[j].bv_page = pages[j];
2509 imu->bvec[j].bv_len = vec_len;
2510 imu->bvec[j].bv_offset = off;
2511 off = 0;
2512 size -= vec_len;
2513 }
2514 /* store original address for later verification */
2515 imu->ubuf = ubuf;
2516 imu->len = iov.iov_len;
2517 imu->nr_bvecs = nr_pages;
2518
2519 ctx->nr_user_bufs++;
2520 }
2521 kfree(pages);
2522 kfree(vmas);
2523 return 0;
2524err:
2525 kfree(pages);
2526 kfree(vmas);
2527 io_sqe_buffer_unregister(ctx);
2528 return ret;
2529}
2530
2b188cc1
JA
2531static void io_ring_ctx_free(struct io_ring_ctx *ctx)
2532{
6b06314c 2533 io_finish_async(ctx);
2b188cc1
JA
2534 if (ctx->sqo_mm)
2535 mmdrop(ctx->sqo_mm);
def596e9
JA
2536
2537 io_iopoll_reap_events(ctx);
edafccee 2538 io_sqe_buffer_unregister(ctx);
6b06314c 2539 io_sqe_files_unregister(ctx);
def596e9 2540
2b188cc1
JA
2541#if defined(CONFIG_UNIX)
2542 if (ctx->ring_sock)
2543 sock_release(ctx->ring_sock);
2544#endif
2545
2546 io_mem_free(ctx->sq_ring);
2547 io_mem_free(ctx->sq_sqes);
2548 io_mem_free(ctx->cq_ring);
2549
2550 percpu_ref_exit(&ctx->refs);
2551 if (ctx->account_mem)
2552 io_unaccount_mem(ctx->user,
2553 ring_pages(ctx->sq_entries, ctx->cq_entries));
2554 free_uid(ctx->user);
2555 kfree(ctx);
2556}
2557
2558static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2559{
2560 struct io_ring_ctx *ctx = file->private_data;
2561 __poll_t mask = 0;
2562
2563 poll_wait(file, &ctx->cq_wait, wait);
2564 /* See comment at the top of this file */
2565 smp_rmb();
2566 if (READ_ONCE(ctx->sq_ring->r.tail) + 1 != ctx->cached_sq_head)
2567 mask |= EPOLLOUT | EPOLLWRNORM;
2568 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
2569 mask |= EPOLLIN | EPOLLRDNORM;
2570
2571 return mask;
2572}
2573
2574static int io_uring_fasync(int fd, struct file *file, int on)
2575{
2576 struct io_ring_ctx *ctx = file->private_data;
2577
2578 return fasync_helper(fd, file, on, &ctx->cq_fasync);
2579}
2580
2581static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2582{
2583 mutex_lock(&ctx->uring_lock);
2584 percpu_ref_kill(&ctx->refs);
2585 mutex_unlock(&ctx->uring_lock);
2586
221c5eb2 2587 io_poll_remove_all(ctx);
def596e9 2588 io_iopoll_reap_events(ctx);
2b188cc1
JA
2589 wait_for_completion(&ctx->ctx_done);
2590 io_ring_ctx_free(ctx);
2591}
2592
2593static int io_uring_release(struct inode *inode, struct file *file)
2594{
2595 struct io_ring_ctx *ctx = file->private_data;
2596
2597 file->private_data = NULL;
2598 io_ring_ctx_wait_and_kill(ctx);
2599 return 0;
2600}
2601
2602static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2603{
2604 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
2605 unsigned long sz = vma->vm_end - vma->vm_start;
2606 struct io_ring_ctx *ctx = file->private_data;
2607 unsigned long pfn;
2608 struct page *page;
2609 void *ptr;
2610
2611 switch (offset) {
2612 case IORING_OFF_SQ_RING:
2613 ptr = ctx->sq_ring;
2614 break;
2615 case IORING_OFF_SQES:
2616 ptr = ctx->sq_sqes;
2617 break;
2618 case IORING_OFF_CQ_RING:
2619 ptr = ctx->cq_ring;
2620 break;
2621 default:
2622 return -EINVAL;
2623 }
2624
2625 page = virt_to_head_page(ptr);
2626 if (sz > (PAGE_SIZE << compound_order(page)))
2627 return -EINVAL;
2628
2629 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
2630 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2631}
2632
2633SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
2634 u32, min_complete, u32, flags, const sigset_t __user *, sig,
2635 size_t, sigsz)
2636{
2637 struct io_ring_ctx *ctx;
2638 long ret = -EBADF;
2639 int submitted = 0;
2640 struct fd f;
2641
6c271ce2 2642 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
2643 return -EINVAL;
2644
2645 f = fdget(fd);
2646 if (!f.file)
2647 return -EBADF;
2648
2649 ret = -EOPNOTSUPP;
2650 if (f.file->f_op != &io_uring_fops)
2651 goto out_fput;
2652
2653 ret = -ENXIO;
2654 ctx = f.file->private_data;
2655 if (!percpu_ref_tryget(&ctx->refs))
2656 goto out_fput;
2657
6c271ce2
JA
2658 /*
2659 * For SQ polling, the thread will do all submissions and completions.
2660 * Just return the requested submit count, and wake the thread if
2661 * we were asked to.
2662 */
2663 if (ctx->flags & IORING_SETUP_SQPOLL) {
2664 if (flags & IORING_ENTER_SQ_WAKEUP)
2665 wake_up(&ctx->sqo_wait);
2666 submitted = to_submit;
2667 goto out_ctx;
2668 }
2669
2b188cc1
JA
2670 ret = 0;
2671 if (to_submit) {
2672 to_submit = min(to_submit, ctx->sq_entries);
2673
2674 mutex_lock(&ctx->uring_lock);
2675 submitted = io_ring_submit(ctx, to_submit);
2676 mutex_unlock(&ctx->uring_lock);
2677
2678 if (submitted < 0)
2679 goto out_ctx;
2680 }
2681 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
2682 unsigned nr_events = 0;
2683
2b188cc1
JA
2684 min_complete = min(min_complete, ctx->cq_entries);
2685
2686 /*
2687 * The application could have included the 'to_submit' count
2688 * in how many events it wanted to wait for. If we failed to
2689 * submit the desired count, we may need to adjust the number
2690 * of events to poll/wait for.
2691 */
2692 if (submitted < to_submit)
2693 min_complete = min_t(unsigned, submitted, min_complete);
2694
def596e9
JA
2695 if (ctx->flags & IORING_SETUP_IOPOLL) {
2696 mutex_lock(&ctx->uring_lock);
2697 ret = io_iopoll_check(ctx, &nr_events, min_complete);
2698 mutex_unlock(&ctx->uring_lock);
2699 } else {
2700 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
2701 }
2b188cc1
JA
2702 }
2703
2704out_ctx:
2705 io_ring_drop_ctx_refs(ctx, 1);
2706out_fput:
2707 fdput(f);
2708 return submitted ? submitted : ret;
2709}
2710
2711static const struct file_operations io_uring_fops = {
2712 .release = io_uring_release,
2713 .mmap = io_uring_mmap,
2714 .poll = io_uring_poll,
2715 .fasync = io_uring_fasync,
2716};
2717
2718static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2719 struct io_uring_params *p)
2720{
2721 struct io_sq_ring *sq_ring;
2722 struct io_cq_ring *cq_ring;
2723 size_t size;
2724
2725 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
2726 if (!sq_ring)
2727 return -ENOMEM;
2728
2729 ctx->sq_ring = sq_ring;
2730 sq_ring->ring_mask = p->sq_entries - 1;
2731 sq_ring->ring_entries = p->sq_entries;
2732 ctx->sq_mask = sq_ring->ring_mask;
2733 ctx->sq_entries = sq_ring->ring_entries;
2734
2735 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
2736 if (size == SIZE_MAX)
2737 return -EOVERFLOW;
2738
2739 ctx->sq_sqes = io_mem_alloc(size);
2740 if (!ctx->sq_sqes) {
2741 io_mem_free(ctx->sq_ring);
2742 return -ENOMEM;
2743 }
2744
2745 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
2746 if (!cq_ring) {
2747 io_mem_free(ctx->sq_ring);
2748 io_mem_free(ctx->sq_sqes);
2749 return -ENOMEM;
2750 }
2751
2752 ctx->cq_ring = cq_ring;
2753 cq_ring->ring_mask = p->cq_entries - 1;
2754 cq_ring->ring_entries = p->cq_entries;
2755 ctx->cq_mask = cq_ring->ring_mask;
2756 ctx->cq_entries = cq_ring->ring_entries;
2757 return 0;
2758}
2759
2760/*
2761 * Allocate an anonymous fd, this is what constitutes the application
2762 * visible backing of an io_uring instance. The application mmaps this
2763 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
2764 * we have to tie this fd to a socket for file garbage collection purposes.
2765 */
2766static int io_uring_get_fd(struct io_ring_ctx *ctx)
2767{
2768 struct file *file;
2769 int ret;
2770
2771#if defined(CONFIG_UNIX)
2772 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
2773 &ctx->ring_sock);
2774 if (ret)
2775 return ret;
2776#endif
2777
2778 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2779 if (ret < 0)
2780 goto err;
2781
2782 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
2783 O_RDWR | O_CLOEXEC);
2784 if (IS_ERR(file)) {
2785 put_unused_fd(ret);
2786 ret = PTR_ERR(file);
2787 goto err;
2788 }
2789
2790#if defined(CONFIG_UNIX)
2791 ctx->ring_sock->file = file;
6b06314c 2792 ctx->ring_sock->sk->sk_user_data = ctx;
2b188cc1
JA
2793#endif
2794 fd_install(ret, file);
2795 return ret;
2796err:
2797#if defined(CONFIG_UNIX)
2798 sock_release(ctx->ring_sock);
2799 ctx->ring_sock = NULL;
2800#endif
2801 return ret;
2802}
2803
2804static int io_uring_create(unsigned entries, struct io_uring_params *p)
2805{
2806 struct user_struct *user = NULL;
2807 struct io_ring_ctx *ctx;
2808 bool account_mem;
2809 int ret;
2810
2811 if (!entries || entries > IORING_MAX_ENTRIES)
2812 return -EINVAL;
2813
2814 /*
2815 * Use twice as many entries for the CQ ring. It's possible for the
2816 * application to drive a higher depth than the size of the SQ ring,
2817 * since the sqes are only used at submission time. This allows for
2818 * some flexibility in overcommitting a bit.
2819 */
2820 p->sq_entries = roundup_pow_of_two(entries);
2821 p->cq_entries = 2 * p->sq_entries;
2822
2823 user = get_uid(current_user());
2824 account_mem = !capable(CAP_IPC_LOCK);
2825
2826 if (account_mem) {
2827 ret = io_account_mem(user,
2828 ring_pages(p->sq_entries, p->cq_entries));
2829 if (ret) {
2830 free_uid(user);
2831 return ret;
2832 }
2833 }
2834
2835 ctx = io_ring_ctx_alloc(p);
2836 if (!ctx) {
2837 if (account_mem)
2838 io_unaccount_mem(user, ring_pages(p->sq_entries,
2839 p->cq_entries));
2840 free_uid(user);
2841 return -ENOMEM;
2842 }
2843 ctx->compat = in_compat_syscall();
2844 ctx->account_mem = account_mem;
2845 ctx->user = user;
2846
2847 ret = io_allocate_scq_urings(ctx, p);
2848 if (ret)
2849 goto err;
2850
6c271ce2 2851 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
2852 if (ret)
2853 goto err;
2854
2855 ret = io_uring_get_fd(ctx);
2856 if (ret < 0)
2857 goto err;
2858
2859 memset(&p->sq_off, 0, sizeof(p->sq_off));
2860 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
2861 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
2862 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
2863 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
2864 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
2865 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
2866 p->sq_off.array = offsetof(struct io_sq_ring, array);
2867
2868 memset(&p->cq_off, 0, sizeof(p->cq_off));
2869 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
2870 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
2871 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
2872 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
2873 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
2874 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
2875 return ret;
2876err:
2877 io_ring_ctx_wait_and_kill(ctx);
2878 return ret;
2879}
2880
2881/*
2882 * Sets up an aio uring context, and returns the fd. Applications asks for a
2883 * ring size, we return the actual sq/cq ring sizes (among other things) in the
2884 * params structure passed in.
2885 */
2886static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
2887{
2888 struct io_uring_params p;
2889 long ret;
2890 int i;
2891
2892 if (copy_from_user(&p, params, sizeof(p)))
2893 return -EFAULT;
2894 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
2895 if (p.resv[i])
2896 return -EINVAL;
2897 }
2898
6c271ce2
JA
2899 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
2900 IORING_SETUP_SQ_AFF))
2b188cc1
JA
2901 return -EINVAL;
2902
2903 ret = io_uring_create(entries, &p);
2904 if (ret < 0)
2905 return ret;
2906
2907 if (copy_to_user(params, &p, sizeof(p)))
2908 return -EFAULT;
2909
2910 return ret;
2911}
2912
2913SYSCALL_DEFINE2(io_uring_setup, u32, entries,
2914 struct io_uring_params __user *, params)
2915{
2916 return io_uring_setup(entries, params);
2917}
2918
edafccee
JA
2919static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
2920 void __user *arg, unsigned nr_args)
2921{
2922 int ret;
2923
2924 percpu_ref_kill(&ctx->refs);
2925 wait_for_completion(&ctx->ctx_done);
2926
2927 switch (opcode) {
2928 case IORING_REGISTER_BUFFERS:
2929 ret = io_sqe_buffer_register(ctx, arg, nr_args);
2930 break;
2931 case IORING_UNREGISTER_BUFFERS:
2932 ret = -EINVAL;
2933 if (arg || nr_args)
2934 break;
2935 ret = io_sqe_buffer_unregister(ctx);
2936 break;
6b06314c
JA
2937 case IORING_REGISTER_FILES:
2938 ret = io_sqe_files_register(ctx, arg, nr_args);
2939 break;
2940 case IORING_UNREGISTER_FILES:
2941 ret = -EINVAL;
2942 if (arg || nr_args)
2943 break;
2944 ret = io_sqe_files_unregister(ctx);
2945 break;
edafccee
JA
2946 default:
2947 ret = -EINVAL;
2948 break;
2949 }
2950
2951 /* bring the ctx back to life */
2952 reinit_completion(&ctx->ctx_done);
2953 percpu_ref_reinit(&ctx->refs);
2954 return ret;
2955}
2956
2957SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
2958 void __user *, arg, unsigned int, nr_args)
2959{
2960 struct io_ring_ctx *ctx;
2961 long ret = -EBADF;
2962 struct fd f;
2963
2964 f = fdget(fd);
2965 if (!f.file)
2966 return -EBADF;
2967
2968 ret = -EOPNOTSUPP;
2969 if (f.file->f_op != &io_uring_fops)
2970 goto out_fput;
2971
2972 ctx = f.file->private_data;
2973
2974 mutex_lock(&ctx->uring_lock);
2975 ret = __io_uring_register(ctx, opcode, arg, nr_args);
2976 mutex_unlock(&ctx->uring_lock);
2977out_fput:
2978 fdput(f);
2979 return ret;
2980}
2981
2b188cc1
JA
2982static int __init io_uring_init(void)
2983{
2984 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
2985 return 0;
2986};
2987__initcall(io_uring_init);