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