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