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