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