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