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