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