io_uring: make IORING_OP_TIMEOUT_REMOVE deferrable
[platform/kernel/linux-starfive.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/kthread.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
63 #include <net/sock.h>
64 #include <net/af_unix.h>
65 #include <net/scm.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73
74 #define CREATE_TRACE_POINTS
75 #include <trace/events/io_uring.h>
76
77 #include <uapi/linux/io_uring.h>
78
79 #include "internal.h"
80 #include "io-wq.h"
81
82 #define IORING_MAX_ENTRIES      32768
83 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
84
85 /*
86  * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
87  */
88 #define IORING_FILE_TABLE_SHIFT 9
89 #define IORING_MAX_FILES_TABLE  (1U << IORING_FILE_TABLE_SHIFT)
90 #define IORING_FILE_TABLE_MASK  (IORING_MAX_FILES_TABLE - 1)
91 #define IORING_MAX_FIXED_FILES  (64 * IORING_MAX_FILES_TABLE)
92
93 struct io_uring {
94         u32 head ____cacheline_aligned_in_smp;
95         u32 tail ____cacheline_aligned_in_smp;
96 };
97
98 /*
99  * This data is shared with the application through the mmap at offsets
100  * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
101  *
102  * The offsets to the member fields are published through struct
103  * io_sqring_offsets when calling io_uring_setup.
104  */
105 struct io_rings {
106         /*
107          * Head and tail offsets into the ring; the offsets need to be
108          * masked to get valid indices.
109          *
110          * The kernel controls head of the sq ring and the tail of the cq ring,
111          * and the application controls tail of the sq ring and the head of the
112          * cq ring.
113          */
114         struct io_uring         sq, cq;
115         /*
116          * Bitmasks to apply to head and tail offsets (constant, equals
117          * ring_entries - 1)
118          */
119         u32                     sq_ring_mask, cq_ring_mask;
120         /* Ring sizes (constant, power of 2) */
121         u32                     sq_ring_entries, cq_ring_entries;
122         /*
123          * Number of invalid entries dropped by the kernel due to
124          * invalid index stored in array
125          *
126          * Written by the kernel, shouldn't be modified by the
127          * application (i.e. get number of "new events" by comparing to
128          * cached value).
129          *
130          * After a new SQ head value was read by the application this
131          * counter includes all submissions that were dropped reaching
132          * the new SQ head (and possibly more).
133          */
134         u32                     sq_dropped;
135         /*
136          * Runtime flags
137          *
138          * Written by the kernel, shouldn't be modified by the
139          * application.
140          *
141          * The application needs a full memory barrier before checking
142          * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
143          */
144         u32                     sq_flags;
145         /*
146          * Number of completion events lost because the queue was full;
147          * this should be avoided by the application by making sure
148          * there are not more requests pending than there is space in
149          * the completion queue.
150          *
151          * Written by the kernel, shouldn't be modified by the
152          * application (i.e. get number of "new events" by comparing to
153          * cached value).
154          *
155          * As completion events come in out of order this counter is not
156          * ordered with any other data.
157          */
158         u32                     cq_overflow;
159         /*
160          * Ring buffer of completion events.
161          *
162          * The kernel writes completion events fresh every time they are
163          * produced, so the application is allowed to modify pending
164          * entries.
165          */
166         struct io_uring_cqe     cqes[] ____cacheline_aligned_in_smp;
167 };
168
169 struct io_mapped_ubuf {
170         u64             ubuf;
171         size_t          len;
172         struct          bio_vec *bvec;
173         unsigned int    nr_bvecs;
174 };
175
176 struct fixed_file_table {
177         struct file             **files;
178 };
179
180 struct io_ring_ctx {
181         struct {
182                 struct percpu_ref       refs;
183         } ____cacheline_aligned_in_smp;
184
185         struct {
186                 unsigned int            flags;
187                 bool                    compat;
188                 bool                    account_mem;
189                 bool                    cq_overflow_flushed;
190                 bool                    drain_next;
191
192                 /*
193                  * Ring buffer of indices into array of io_uring_sqe, which is
194                  * mmapped by the application using the IORING_OFF_SQES offset.
195                  *
196                  * This indirection could e.g. be used to assign fixed
197                  * io_uring_sqe entries to operations and only submit them to
198                  * the queue when needed.
199                  *
200                  * The kernel modifies neither the indices array nor the entries
201                  * array.
202                  */
203                 u32                     *sq_array;
204                 unsigned                cached_sq_head;
205                 unsigned                sq_entries;
206                 unsigned                sq_mask;
207                 unsigned                sq_thread_idle;
208                 unsigned                cached_sq_dropped;
209                 atomic_t                cached_cq_overflow;
210                 struct io_uring_sqe     *sq_sqes;
211
212                 struct list_head        defer_list;
213                 struct list_head        timeout_list;
214                 struct list_head        cq_overflow_list;
215
216                 wait_queue_head_t       inflight_wait;
217         } ____cacheline_aligned_in_smp;
218
219         struct io_rings *rings;
220
221         /* IO offload */
222         struct io_wq            *io_wq;
223         struct task_struct      *sqo_thread;    /* if using sq thread polling */
224         struct mm_struct        *sqo_mm;
225         wait_queue_head_t       sqo_wait;
226
227         /*
228          * If used, fixed file set. Writers must ensure that ->refs is dead,
229          * readers must ensure that ->refs is alive as long as the file* is
230          * used. Only updated through io_uring_register(2).
231          */
232         struct fixed_file_table *file_table;
233         unsigned                nr_user_files;
234
235         /* if used, fixed mapped user buffers */
236         unsigned                nr_user_bufs;
237         struct io_mapped_ubuf   *user_bufs;
238
239         struct user_struct      *user;
240
241         const struct cred       *creds;
242
243         /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
244         struct completion       *completions;
245
246         /* if all else fails... */
247         struct io_kiocb         *fallback_req;
248
249 #if defined(CONFIG_UNIX)
250         struct socket           *ring_sock;
251 #endif
252
253         struct {
254                 unsigned                cached_cq_tail;
255                 unsigned                cq_entries;
256                 unsigned                cq_mask;
257                 atomic_t                cq_timeouts;
258                 struct wait_queue_head  cq_wait;
259                 struct fasync_struct    *cq_fasync;
260                 struct eventfd_ctx      *cq_ev_fd;
261         } ____cacheline_aligned_in_smp;
262
263         struct {
264                 struct mutex            uring_lock;
265                 wait_queue_head_t       wait;
266         } ____cacheline_aligned_in_smp;
267
268         struct {
269                 spinlock_t              completion_lock;
270                 bool                    poll_multi_file;
271                 /*
272                  * ->poll_list is protected by the ctx->uring_lock for
273                  * io_uring instances that don't use IORING_SETUP_SQPOLL.
274                  * For SQPOLL, only the single threaded io_sq_thread() will
275                  * manipulate the list, hence no extra locking is needed there.
276                  */
277                 struct list_head        poll_list;
278                 struct hlist_head       *cancel_hash;
279                 unsigned                cancel_hash_bits;
280
281                 spinlock_t              inflight_lock;
282                 struct list_head        inflight_list;
283         } ____cacheline_aligned_in_smp;
284 };
285
286 /*
287  * First field must be the file pointer in all the
288  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
289  */
290 struct io_poll_iocb {
291         struct file                     *file;
292         union {
293                 struct wait_queue_head  *head;
294                 u64                     addr;
295         };
296         __poll_t                        events;
297         bool                            done;
298         bool                            canceled;
299         struct wait_queue_entry         wait;
300 };
301
302 struct io_timeout_data {
303         struct io_kiocb                 *req;
304         struct hrtimer                  timer;
305         struct timespec64               ts;
306         enum hrtimer_mode               mode;
307         u32                             seq_offset;
308 };
309
310 struct io_accept {
311         struct file                     *file;
312         struct sockaddr __user          *addr;
313         int __user                      *addr_len;
314         int                             flags;
315 };
316
317 struct io_sync {
318         struct file                     *file;
319         loff_t                          len;
320         loff_t                          off;
321         int                             flags;
322 };
323
324 struct io_cancel {
325         struct file                     *file;
326         u64                             addr;
327 };
328
329 struct io_timeout {
330         struct file                     *file;
331         u64                             addr;
332         int                             flags;
333 };
334
335 struct io_async_connect {
336         struct sockaddr_storage         address;
337 };
338
339 struct io_async_msghdr {
340         struct iovec                    fast_iov[UIO_FASTIOV];
341         struct iovec                    *iov;
342         struct sockaddr __user          *uaddr;
343         struct msghdr                   msg;
344 };
345
346 struct io_async_rw {
347         struct iovec                    fast_iov[UIO_FASTIOV];
348         struct iovec                    *iov;
349         ssize_t                         nr_segs;
350         ssize_t                         size;
351 };
352
353 struct io_async_ctx {
354         struct io_uring_sqe             sqe;
355         union {
356                 struct io_async_rw      rw;
357                 struct io_async_msghdr  msg;
358                 struct io_async_connect connect;
359                 struct io_timeout_data  timeout;
360         };
361 };
362
363 /*
364  * NOTE! Each of the iocb union members has the file pointer
365  * as the first entry in their struct definition. So you can
366  * access the file pointer through any of the sub-structs,
367  * or directly as just 'ki_filp' in this struct.
368  */
369 struct io_kiocb {
370         union {
371                 struct file             *file;
372                 struct kiocb            rw;
373                 struct io_poll_iocb     poll;
374                 struct io_accept        accept;
375                 struct io_sync          sync;
376                 struct io_cancel        cancel;
377                 struct io_timeout       timeout;
378         };
379
380         const struct io_uring_sqe       *sqe;
381         struct io_async_ctx             *io;
382         struct file                     *ring_file;
383         int                             ring_fd;
384         bool                            has_user;
385         bool                            in_async;
386         bool                            needs_fixed_file;
387
388         struct io_ring_ctx      *ctx;
389         union {
390                 struct list_head        list;
391                 struct hlist_node       hash_node;
392         };
393         struct list_head        link_list;
394         unsigned int            flags;
395         refcount_t              refs;
396 #define REQ_F_NOWAIT            1       /* must not punt to workers */
397 #define REQ_F_IOPOLL_COMPLETED  2       /* polled IO has completed */
398 #define REQ_F_FIXED_FILE        4       /* ctx owns file */
399 #define REQ_F_LINK_NEXT         8       /* already grabbed next link */
400 #define REQ_F_IO_DRAIN          16      /* drain existing IO first */
401 #define REQ_F_IO_DRAINED        32      /* drain done */
402 #define REQ_F_LINK              64      /* linked sqes */
403 #define REQ_F_LINK_TIMEOUT      128     /* has linked timeout */
404 #define REQ_F_FAIL_LINK         256     /* fail rest of links */
405 #define REQ_F_DRAIN_LINK        512     /* link should be fully drained */
406 #define REQ_F_TIMEOUT           1024    /* timeout request */
407 #define REQ_F_ISREG             2048    /* regular file */
408 #define REQ_F_MUST_PUNT         4096    /* must be punted even for NONBLOCK */
409 #define REQ_F_TIMEOUT_NOSEQ     8192    /* no timeout sequence */
410 #define REQ_F_INFLIGHT          16384   /* on inflight list */
411 #define REQ_F_COMP_LOCKED       32768   /* completion under lock */
412 #define REQ_F_HARDLINK          65536   /* doesn't sever on completion < 0 */
413 #define REQ_F_PREPPED           131072  /* request already opcode prepared */
414         u64                     user_data;
415         u32                     result;
416         u32                     sequence;
417
418         struct list_head        inflight_entry;
419
420         struct io_wq_work       work;
421 };
422
423 #define IO_PLUG_THRESHOLD               2
424 #define IO_IOPOLL_BATCH                 8
425
426 struct io_submit_state {
427         struct blk_plug         plug;
428
429         /*
430          * io_kiocb alloc cache
431          */
432         void                    *reqs[IO_IOPOLL_BATCH];
433         unsigned                int free_reqs;
434         unsigned                int cur_req;
435
436         /*
437          * File reference cache
438          */
439         struct file             *file;
440         unsigned int            fd;
441         unsigned int            has_refs;
442         unsigned int            used_refs;
443         unsigned int            ios_left;
444 };
445
446 static void io_wq_submit_work(struct io_wq_work **workptr);
447 static void io_cqring_fill_event(struct io_kiocb *req, long res);
448 static void __io_free_req(struct io_kiocb *req);
449 static void io_put_req(struct io_kiocb *req);
450 static void io_double_put_req(struct io_kiocb *req);
451 static void __io_double_put_req(struct io_kiocb *req);
452 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
453 static void io_queue_linked_timeout(struct io_kiocb *req);
454
455 static struct kmem_cache *req_cachep;
456
457 static const struct file_operations io_uring_fops;
458
459 struct sock *io_uring_get_socket(struct file *file)
460 {
461 #if defined(CONFIG_UNIX)
462         if (file->f_op == &io_uring_fops) {
463                 struct io_ring_ctx *ctx = file->private_data;
464
465                 return ctx->ring_sock->sk;
466         }
467 #endif
468         return NULL;
469 }
470 EXPORT_SYMBOL(io_uring_get_socket);
471
472 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
473 {
474         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
475
476         complete(&ctx->completions[0]);
477 }
478
479 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
480 {
481         struct io_ring_ctx *ctx;
482         int hash_bits;
483
484         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
485         if (!ctx)
486                 return NULL;
487
488         ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
489         if (!ctx->fallback_req)
490                 goto err;
491
492         ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
493         if (!ctx->completions)
494                 goto err;
495
496         /*
497          * Use 5 bits less than the max cq entries, that should give us around
498          * 32 entries per hash list if totally full and uniformly spread.
499          */
500         hash_bits = ilog2(p->cq_entries);
501         hash_bits -= 5;
502         if (hash_bits <= 0)
503                 hash_bits = 1;
504         ctx->cancel_hash_bits = hash_bits;
505         ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
506                                         GFP_KERNEL);
507         if (!ctx->cancel_hash)
508                 goto err;
509         __hash_init(ctx->cancel_hash, 1U << hash_bits);
510
511         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
512                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
513                 goto err;
514
515         ctx->flags = p->flags;
516         init_waitqueue_head(&ctx->cq_wait);
517         INIT_LIST_HEAD(&ctx->cq_overflow_list);
518         init_completion(&ctx->completions[0]);
519         init_completion(&ctx->completions[1]);
520         mutex_init(&ctx->uring_lock);
521         init_waitqueue_head(&ctx->wait);
522         spin_lock_init(&ctx->completion_lock);
523         INIT_LIST_HEAD(&ctx->poll_list);
524         INIT_LIST_HEAD(&ctx->defer_list);
525         INIT_LIST_HEAD(&ctx->timeout_list);
526         init_waitqueue_head(&ctx->inflight_wait);
527         spin_lock_init(&ctx->inflight_lock);
528         INIT_LIST_HEAD(&ctx->inflight_list);
529         return ctx;
530 err:
531         if (ctx->fallback_req)
532                 kmem_cache_free(req_cachep, ctx->fallback_req);
533         kfree(ctx->completions);
534         kfree(ctx->cancel_hash);
535         kfree(ctx);
536         return NULL;
537 }
538
539 static inline bool __req_need_defer(struct io_kiocb *req)
540 {
541         struct io_ring_ctx *ctx = req->ctx;
542
543         return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
544                                         + atomic_read(&ctx->cached_cq_overflow);
545 }
546
547 static inline bool req_need_defer(struct io_kiocb *req)
548 {
549         if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) == REQ_F_IO_DRAIN)
550                 return __req_need_defer(req);
551
552         return false;
553 }
554
555 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
556 {
557         struct io_kiocb *req;
558
559         req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
560         if (req && !req_need_defer(req)) {
561                 list_del_init(&req->list);
562                 return req;
563         }
564
565         return NULL;
566 }
567
568 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
569 {
570         struct io_kiocb *req;
571
572         req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
573         if (req) {
574                 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
575                         return NULL;
576                 if (!__req_need_defer(req)) {
577                         list_del_init(&req->list);
578                         return req;
579                 }
580         }
581
582         return NULL;
583 }
584
585 static void __io_commit_cqring(struct io_ring_ctx *ctx)
586 {
587         struct io_rings *rings = ctx->rings;
588
589         if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
590                 /* order cqe stores with ring update */
591                 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
592
593                 if (wq_has_sleeper(&ctx->cq_wait)) {
594                         wake_up_interruptible(&ctx->cq_wait);
595                         kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
596                 }
597         }
598 }
599
600 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
601 {
602         u8 opcode = READ_ONCE(sqe->opcode);
603
604         return !(opcode == IORING_OP_READ_FIXED ||
605                  opcode == IORING_OP_WRITE_FIXED);
606 }
607
608 static inline bool io_prep_async_work(struct io_kiocb *req,
609                                       struct io_kiocb **link)
610 {
611         bool do_hashed = false;
612
613         if (req->sqe) {
614                 switch (req->sqe->opcode) {
615                 case IORING_OP_WRITEV:
616                 case IORING_OP_WRITE_FIXED:
617                         /* only regular files should be hashed for writes */
618                         if (req->flags & REQ_F_ISREG)
619                                 do_hashed = true;
620                         /* fall-through */
621                 case IORING_OP_READV:
622                 case IORING_OP_READ_FIXED:
623                 case IORING_OP_SENDMSG:
624                 case IORING_OP_RECVMSG:
625                 case IORING_OP_ACCEPT:
626                 case IORING_OP_POLL_ADD:
627                 case IORING_OP_CONNECT:
628                         /*
629                          * We know REQ_F_ISREG is not set on some of these
630                          * opcodes, but this enables us to keep the check in
631                          * just one place.
632                          */
633                         if (!(req->flags & REQ_F_ISREG))
634                                 req->work.flags |= IO_WQ_WORK_UNBOUND;
635                         break;
636                 }
637                 if (io_sqe_needs_user(req->sqe))
638                         req->work.flags |= IO_WQ_WORK_NEEDS_USER;
639         }
640
641         *link = io_prep_linked_timeout(req);
642         return do_hashed;
643 }
644
645 static inline void io_queue_async_work(struct io_kiocb *req)
646 {
647         struct io_ring_ctx *ctx = req->ctx;
648         struct io_kiocb *link;
649         bool do_hashed;
650
651         do_hashed = io_prep_async_work(req, &link);
652
653         trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
654                                         req->flags);
655         if (!do_hashed) {
656                 io_wq_enqueue(ctx->io_wq, &req->work);
657         } else {
658                 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
659                                         file_inode(req->file));
660         }
661
662         if (link)
663                 io_queue_linked_timeout(link);
664 }
665
666 static void io_kill_timeout(struct io_kiocb *req)
667 {
668         int ret;
669
670         ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
671         if (ret != -1) {
672                 atomic_inc(&req->ctx->cq_timeouts);
673                 list_del_init(&req->list);
674                 io_cqring_fill_event(req, 0);
675                 io_put_req(req);
676         }
677 }
678
679 static void io_kill_timeouts(struct io_ring_ctx *ctx)
680 {
681         struct io_kiocb *req, *tmp;
682
683         spin_lock_irq(&ctx->completion_lock);
684         list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
685                 io_kill_timeout(req);
686         spin_unlock_irq(&ctx->completion_lock);
687 }
688
689 static void io_commit_cqring(struct io_ring_ctx *ctx)
690 {
691         struct io_kiocb *req;
692
693         while ((req = io_get_timeout_req(ctx)) != NULL)
694                 io_kill_timeout(req);
695
696         __io_commit_cqring(ctx);
697
698         while ((req = io_get_deferred_req(ctx)) != NULL) {
699                 req->flags |= REQ_F_IO_DRAINED;
700                 io_queue_async_work(req);
701         }
702 }
703
704 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
705 {
706         struct io_rings *rings = ctx->rings;
707         unsigned tail;
708
709         tail = ctx->cached_cq_tail;
710         /*
711          * writes to the cq entry need to come after reading head; the
712          * control dependency is enough as we're using WRITE_ONCE to
713          * fill the cq entry
714          */
715         if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
716                 return NULL;
717
718         ctx->cached_cq_tail++;
719         return &rings->cqes[tail & ctx->cq_mask];
720 }
721
722 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
723 {
724         if (waitqueue_active(&ctx->wait))
725                 wake_up(&ctx->wait);
726         if (waitqueue_active(&ctx->sqo_wait))
727                 wake_up(&ctx->sqo_wait);
728         if (ctx->cq_ev_fd)
729                 eventfd_signal(ctx->cq_ev_fd, 1);
730 }
731
732 /* Returns true if there are no backlogged entries after the flush */
733 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
734 {
735         struct io_rings *rings = ctx->rings;
736         struct io_uring_cqe *cqe;
737         struct io_kiocb *req;
738         unsigned long flags;
739         LIST_HEAD(list);
740
741         if (!force) {
742                 if (list_empty_careful(&ctx->cq_overflow_list))
743                         return true;
744                 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
745                     rings->cq_ring_entries))
746                         return false;
747         }
748
749         spin_lock_irqsave(&ctx->completion_lock, flags);
750
751         /* if force is set, the ring is going away. always drop after that */
752         if (force)
753                 ctx->cq_overflow_flushed = true;
754
755         cqe = NULL;
756         while (!list_empty(&ctx->cq_overflow_list)) {
757                 cqe = io_get_cqring(ctx);
758                 if (!cqe && !force)
759                         break;
760
761                 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
762                                                 list);
763                 list_move(&req->list, &list);
764                 if (cqe) {
765                         WRITE_ONCE(cqe->user_data, req->user_data);
766                         WRITE_ONCE(cqe->res, req->result);
767                         WRITE_ONCE(cqe->flags, 0);
768                 } else {
769                         WRITE_ONCE(ctx->rings->cq_overflow,
770                                 atomic_inc_return(&ctx->cached_cq_overflow));
771                 }
772         }
773
774         io_commit_cqring(ctx);
775         spin_unlock_irqrestore(&ctx->completion_lock, flags);
776         io_cqring_ev_posted(ctx);
777
778         while (!list_empty(&list)) {
779                 req = list_first_entry(&list, struct io_kiocb, list);
780                 list_del(&req->list);
781                 io_put_req(req);
782         }
783
784         return cqe != NULL;
785 }
786
787 static void io_cqring_fill_event(struct io_kiocb *req, long res)
788 {
789         struct io_ring_ctx *ctx = req->ctx;
790         struct io_uring_cqe *cqe;
791
792         trace_io_uring_complete(ctx, req->user_data, res);
793
794         /*
795          * If we can't get a cq entry, userspace overflowed the
796          * submission (by quite a lot). Increment the overflow count in
797          * the ring.
798          */
799         cqe = io_get_cqring(ctx);
800         if (likely(cqe)) {
801                 WRITE_ONCE(cqe->user_data, req->user_data);
802                 WRITE_ONCE(cqe->res, res);
803                 WRITE_ONCE(cqe->flags, 0);
804         } else if (ctx->cq_overflow_flushed) {
805                 WRITE_ONCE(ctx->rings->cq_overflow,
806                                 atomic_inc_return(&ctx->cached_cq_overflow));
807         } else {
808                 refcount_inc(&req->refs);
809                 req->result = res;
810                 list_add_tail(&req->list, &ctx->cq_overflow_list);
811         }
812 }
813
814 static void io_cqring_add_event(struct io_kiocb *req, long res)
815 {
816         struct io_ring_ctx *ctx = req->ctx;
817         unsigned long flags;
818
819         spin_lock_irqsave(&ctx->completion_lock, flags);
820         io_cqring_fill_event(req, res);
821         io_commit_cqring(ctx);
822         spin_unlock_irqrestore(&ctx->completion_lock, flags);
823
824         io_cqring_ev_posted(ctx);
825 }
826
827 static inline bool io_is_fallback_req(struct io_kiocb *req)
828 {
829         return req == (struct io_kiocb *)
830                         ((unsigned long) req->ctx->fallback_req & ~1UL);
831 }
832
833 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
834 {
835         struct io_kiocb *req;
836
837         req = ctx->fallback_req;
838         if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
839                 return req;
840
841         return NULL;
842 }
843
844 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
845                                    struct io_submit_state *state)
846 {
847         gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
848         struct io_kiocb *req;
849
850         if (!percpu_ref_tryget(&ctx->refs))
851                 return NULL;
852
853         if (!state) {
854                 req = kmem_cache_alloc(req_cachep, gfp);
855                 if (unlikely(!req))
856                         goto fallback;
857         } else if (!state->free_reqs) {
858                 size_t sz;
859                 int ret;
860
861                 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
862                 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
863
864                 /*
865                  * Bulk alloc is all-or-nothing. If we fail to get a batch,
866                  * retry single alloc to be on the safe side.
867                  */
868                 if (unlikely(ret <= 0)) {
869                         state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
870                         if (!state->reqs[0])
871                                 goto fallback;
872                         ret = 1;
873                 }
874                 state->free_reqs = ret - 1;
875                 state->cur_req = 1;
876                 req = state->reqs[0];
877         } else {
878                 req = state->reqs[state->cur_req];
879                 state->free_reqs--;
880                 state->cur_req++;
881         }
882
883 got_it:
884         req->io = NULL;
885         req->ring_file = NULL;
886         req->file = NULL;
887         req->ctx = ctx;
888         req->flags = 0;
889         /* one is dropped after submission, the other at completion */
890         refcount_set(&req->refs, 2);
891         req->result = 0;
892         INIT_IO_WORK(&req->work, io_wq_submit_work);
893         return req;
894 fallback:
895         req = io_get_fallback_req(ctx);
896         if (req)
897                 goto got_it;
898         percpu_ref_put(&ctx->refs);
899         return NULL;
900 }
901
902 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
903 {
904         if (*nr) {
905                 kmem_cache_free_bulk(req_cachep, *nr, reqs);
906                 percpu_ref_put_many(&ctx->refs, *nr);
907                 *nr = 0;
908         }
909 }
910
911 static void __io_free_req(struct io_kiocb *req)
912 {
913         struct io_ring_ctx *ctx = req->ctx;
914
915         if (req->io)
916                 kfree(req->io);
917         if (req->file && !(req->flags & REQ_F_FIXED_FILE))
918                 fput(req->file);
919         if (req->flags & REQ_F_INFLIGHT) {
920                 unsigned long flags;
921
922                 spin_lock_irqsave(&ctx->inflight_lock, flags);
923                 list_del(&req->inflight_entry);
924                 if (waitqueue_active(&ctx->inflight_wait))
925                         wake_up(&ctx->inflight_wait);
926                 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
927         }
928         percpu_ref_put(&ctx->refs);
929         if (likely(!io_is_fallback_req(req)))
930                 kmem_cache_free(req_cachep, req);
931         else
932                 clear_bit_unlock(0, (unsigned long *) ctx->fallback_req);
933 }
934
935 static bool io_link_cancel_timeout(struct io_kiocb *req)
936 {
937         struct io_ring_ctx *ctx = req->ctx;
938         int ret;
939
940         ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
941         if (ret != -1) {
942                 io_cqring_fill_event(req, -ECANCELED);
943                 io_commit_cqring(ctx);
944                 req->flags &= ~REQ_F_LINK;
945                 io_put_req(req);
946                 return true;
947         }
948
949         return false;
950 }
951
952 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
953 {
954         struct io_ring_ctx *ctx = req->ctx;
955         bool wake_ev = false;
956
957         /* Already got next link */
958         if (req->flags & REQ_F_LINK_NEXT)
959                 return;
960
961         /*
962          * The list should never be empty when we are called here. But could
963          * potentially happen if the chain is messed up, check to be on the
964          * safe side.
965          */
966         while (!list_empty(&req->link_list)) {
967                 struct io_kiocb *nxt = list_first_entry(&req->link_list,
968                                                 struct io_kiocb, link_list);
969
970                 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
971                              (nxt->flags & REQ_F_TIMEOUT))) {
972                         list_del_init(&nxt->link_list);
973                         wake_ev |= io_link_cancel_timeout(nxt);
974                         req->flags &= ~REQ_F_LINK_TIMEOUT;
975                         continue;
976                 }
977
978                 list_del_init(&req->link_list);
979                 if (!list_empty(&nxt->link_list))
980                         nxt->flags |= REQ_F_LINK;
981                 *nxtptr = nxt;
982                 break;
983         }
984
985         req->flags |= REQ_F_LINK_NEXT;
986         if (wake_ev)
987                 io_cqring_ev_posted(ctx);
988 }
989
990 /*
991  * Called if REQ_F_LINK is set, and we fail the head request
992  */
993 static void io_fail_links(struct io_kiocb *req)
994 {
995         struct io_ring_ctx *ctx = req->ctx;
996         unsigned long flags;
997
998         spin_lock_irqsave(&ctx->completion_lock, flags);
999
1000         while (!list_empty(&req->link_list)) {
1001                 struct io_kiocb *link = list_first_entry(&req->link_list,
1002                                                 struct io_kiocb, link_list);
1003
1004                 list_del_init(&link->link_list);
1005                 trace_io_uring_fail_link(req, link);
1006
1007                 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1008                     link->sqe->opcode == IORING_OP_LINK_TIMEOUT) {
1009                         io_link_cancel_timeout(link);
1010                 } else {
1011                         io_cqring_fill_event(link, -ECANCELED);
1012                         __io_double_put_req(link);
1013                 }
1014                 req->flags &= ~REQ_F_LINK_TIMEOUT;
1015         }
1016
1017         io_commit_cqring(ctx);
1018         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1019         io_cqring_ev_posted(ctx);
1020 }
1021
1022 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1023 {
1024         if (likely(!(req->flags & REQ_F_LINK)))
1025                 return;
1026
1027         /*
1028          * If LINK is set, we have dependent requests in this chain. If we
1029          * didn't fail this request, queue the first one up, moving any other
1030          * dependencies to the next request. In case of failure, fail the rest
1031          * of the chain.
1032          */
1033         if (req->flags & REQ_F_FAIL_LINK) {
1034                 io_fail_links(req);
1035         } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1036                         REQ_F_LINK_TIMEOUT) {
1037                 struct io_ring_ctx *ctx = req->ctx;
1038                 unsigned long flags;
1039
1040                 /*
1041                  * If this is a timeout link, we could be racing with the
1042                  * timeout timer. Grab the completion lock for this case to
1043                  * protect against that.
1044                  */
1045                 spin_lock_irqsave(&ctx->completion_lock, flags);
1046                 io_req_link_next(req, nxt);
1047                 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1048         } else {
1049                 io_req_link_next(req, nxt);
1050         }
1051 }
1052
1053 static void io_free_req(struct io_kiocb *req)
1054 {
1055         struct io_kiocb *nxt = NULL;
1056
1057         io_req_find_next(req, &nxt);
1058         __io_free_req(req);
1059
1060         if (nxt)
1061                 io_queue_async_work(nxt);
1062 }
1063
1064 /*
1065  * Drop reference to request, return next in chain (if there is one) if this
1066  * was the last reference to this request.
1067  */
1068 __attribute__((nonnull))
1069 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1070 {
1071         io_req_find_next(req, nxtptr);
1072
1073         if (refcount_dec_and_test(&req->refs))
1074                 __io_free_req(req);
1075 }
1076
1077 static void io_put_req(struct io_kiocb *req)
1078 {
1079         if (refcount_dec_and_test(&req->refs))
1080                 io_free_req(req);
1081 }
1082
1083 /*
1084  * Must only be used if we don't need to care about links, usually from
1085  * within the completion handling itself.
1086  */
1087 static void __io_double_put_req(struct io_kiocb *req)
1088 {
1089         /* drop both submit and complete references */
1090         if (refcount_sub_and_test(2, &req->refs))
1091                 __io_free_req(req);
1092 }
1093
1094 static void io_double_put_req(struct io_kiocb *req)
1095 {
1096         /* drop both submit and complete references */
1097         if (refcount_sub_and_test(2, &req->refs))
1098                 io_free_req(req);
1099 }
1100
1101 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1102 {
1103         struct io_rings *rings = ctx->rings;
1104
1105         /*
1106          * noflush == true is from the waitqueue handler, just ensure we wake
1107          * up the task, and the next invocation will flush the entries. We
1108          * cannot safely to it from here.
1109          */
1110         if (noflush && !list_empty(&ctx->cq_overflow_list))
1111                 return -1U;
1112
1113         io_cqring_overflow_flush(ctx, false);
1114
1115         /* See comment at the top of this file */
1116         smp_rmb();
1117         return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
1118 }
1119
1120 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1121 {
1122         struct io_rings *rings = ctx->rings;
1123
1124         /* make sure SQ entry isn't read before tail */
1125         return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1126 }
1127
1128 /*
1129  * Find and free completed poll iocbs
1130  */
1131 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1132                                struct list_head *done)
1133 {
1134         void *reqs[IO_IOPOLL_BATCH];
1135         struct io_kiocb *req;
1136         int to_free;
1137
1138         to_free = 0;
1139         while (!list_empty(done)) {
1140                 req = list_first_entry(done, struct io_kiocb, list);
1141                 list_del(&req->list);
1142
1143                 io_cqring_fill_event(req, req->result);
1144                 (*nr_events)++;
1145
1146                 if (refcount_dec_and_test(&req->refs)) {
1147                         /* If we're not using fixed files, we have to pair the
1148                          * completion part with the file put. Use regular
1149                          * completions for those, only batch free for fixed
1150                          * file and non-linked commands.
1151                          */
1152                         if (((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
1153                             REQ_F_FIXED_FILE) && !io_is_fallback_req(req) &&
1154                             !req->io) {
1155                                 reqs[to_free++] = req;
1156                                 if (to_free == ARRAY_SIZE(reqs))
1157                                         io_free_req_many(ctx, reqs, &to_free);
1158                         } else {
1159                                 io_free_req(req);
1160                         }
1161                 }
1162         }
1163
1164         io_commit_cqring(ctx);
1165         io_free_req_many(ctx, reqs, &to_free);
1166 }
1167
1168 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1169                         long min)
1170 {
1171         struct io_kiocb *req, *tmp;
1172         LIST_HEAD(done);
1173         bool spin;
1174         int ret;
1175
1176         /*
1177          * Only spin for completions if we don't have multiple devices hanging
1178          * off our complete list, and we're under the requested amount.
1179          */
1180         spin = !ctx->poll_multi_file && *nr_events < min;
1181
1182         ret = 0;
1183         list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1184                 struct kiocb *kiocb = &req->rw;
1185
1186                 /*
1187                  * Move completed entries to our local list. If we find a
1188                  * request that requires polling, break out and complete
1189                  * the done list first, if we have entries there.
1190                  */
1191                 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1192                         list_move_tail(&req->list, &done);
1193                         continue;
1194                 }
1195                 if (!list_empty(&done))
1196                         break;
1197
1198                 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1199                 if (ret < 0)
1200                         break;
1201
1202                 if (ret && spin)
1203                         spin = false;
1204                 ret = 0;
1205         }
1206
1207         if (!list_empty(&done))
1208                 io_iopoll_complete(ctx, nr_events, &done);
1209
1210         return ret;
1211 }
1212
1213 /*
1214  * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1215  * non-spinning poll check - we'll still enter the driver poll loop, but only
1216  * as a non-spinning completion check.
1217  */
1218 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1219                                 long min)
1220 {
1221         while (!list_empty(&ctx->poll_list) && !need_resched()) {
1222                 int ret;
1223
1224                 ret = io_do_iopoll(ctx, nr_events, min);
1225                 if (ret < 0)
1226                         return ret;
1227                 if (!min || *nr_events >= min)
1228                         return 0;
1229         }
1230
1231         return 1;
1232 }
1233
1234 /*
1235  * We can't just wait for polled events to come to us, we have to actively
1236  * find and complete them.
1237  */
1238 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1239 {
1240         if (!(ctx->flags & IORING_SETUP_IOPOLL))
1241                 return;
1242
1243         mutex_lock(&ctx->uring_lock);
1244         while (!list_empty(&ctx->poll_list)) {
1245                 unsigned int nr_events = 0;
1246
1247                 io_iopoll_getevents(ctx, &nr_events, 1);
1248
1249                 /*
1250                  * Ensure we allow local-to-the-cpu processing to take place,
1251                  * in this case we need to ensure that we reap all events.
1252                  */
1253                 cond_resched();
1254         }
1255         mutex_unlock(&ctx->uring_lock);
1256 }
1257
1258 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1259                             long min)
1260 {
1261         int iters = 0, ret = 0;
1262
1263         do {
1264                 int tmin = 0;
1265
1266                 /*
1267                  * Don't enter poll loop if we already have events pending.
1268                  * If we do, we can potentially be spinning for commands that
1269                  * already triggered a CQE (eg in error).
1270                  */
1271                 if (io_cqring_events(ctx, false))
1272                         break;
1273
1274                 /*
1275                  * If a submit got punted to a workqueue, we can have the
1276                  * application entering polling for a command before it gets
1277                  * issued. That app will hold the uring_lock for the duration
1278                  * of the poll right here, so we need to take a breather every
1279                  * now and then to ensure that the issue has a chance to add
1280                  * the poll to the issued list. Otherwise we can spin here
1281                  * forever, while the workqueue is stuck trying to acquire the
1282                  * very same mutex.
1283                  */
1284                 if (!(++iters & 7)) {
1285                         mutex_unlock(&ctx->uring_lock);
1286                         mutex_lock(&ctx->uring_lock);
1287                 }
1288
1289                 if (*nr_events < min)
1290                         tmin = min - *nr_events;
1291
1292                 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1293                 if (ret <= 0)
1294                         break;
1295                 ret = 0;
1296         } while (min && !*nr_events && !need_resched());
1297
1298         return ret;
1299 }
1300
1301 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1302                            long min)
1303 {
1304         int ret;
1305
1306         /*
1307          * We disallow the app entering submit/complete with polling, but we
1308          * still need to lock the ring to prevent racing with polled issue
1309          * that got punted to a workqueue.
1310          */
1311         mutex_lock(&ctx->uring_lock);
1312         ret = __io_iopoll_check(ctx, nr_events, min);
1313         mutex_unlock(&ctx->uring_lock);
1314         return ret;
1315 }
1316
1317 static void kiocb_end_write(struct io_kiocb *req)
1318 {
1319         /*
1320          * Tell lockdep we inherited freeze protection from submission
1321          * thread.
1322          */
1323         if (req->flags & REQ_F_ISREG) {
1324                 struct inode *inode = file_inode(req->file);
1325
1326                 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1327         }
1328         file_end_write(req->file);
1329 }
1330
1331 static inline void req_set_fail_links(struct io_kiocb *req)
1332 {
1333         if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1334                 req->flags |= REQ_F_FAIL_LINK;
1335 }
1336
1337 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1338 {
1339         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1340
1341         if (kiocb->ki_flags & IOCB_WRITE)
1342                 kiocb_end_write(req);
1343
1344         if (res != req->result)
1345                 req_set_fail_links(req);
1346         io_cqring_add_event(req, res);
1347 }
1348
1349 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1350 {
1351         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1352
1353         io_complete_rw_common(kiocb, res);
1354         io_put_req(req);
1355 }
1356
1357 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1358 {
1359         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1360         struct io_kiocb *nxt = NULL;
1361
1362         io_complete_rw_common(kiocb, res);
1363         io_put_req_find_next(req, &nxt);
1364
1365         return nxt;
1366 }
1367
1368 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1369 {
1370         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1371
1372         if (kiocb->ki_flags & IOCB_WRITE)
1373                 kiocb_end_write(req);
1374
1375         if (res != req->result)
1376                 req_set_fail_links(req);
1377         req->result = res;
1378         if (res != -EAGAIN)
1379                 req->flags |= REQ_F_IOPOLL_COMPLETED;
1380 }
1381
1382 /*
1383  * After the iocb has been issued, it's safe to be found on the poll list.
1384  * Adding the kiocb to the list AFTER submission ensures that we don't
1385  * find it from a io_iopoll_getevents() thread before the issuer is done
1386  * accessing the kiocb cookie.
1387  */
1388 static void io_iopoll_req_issued(struct io_kiocb *req)
1389 {
1390         struct io_ring_ctx *ctx = req->ctx;
1391
1392         /*
1393          * Track whether we have multiple files in our lists. This will impact
1394          * how we do polling eventually, not spinning if we're on potentially
1395          * different devices.
1396          */
1397         if (list_empty(&ctx->poll_list)) {
1398                 ctx->poll_multi_file = false;
1399         } else if (!ctx->poll_multi_file) {
1400                 struct io_kiocb *list_req;
1401
1402                 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1403                                                 list);
1404                 if (list_req->rw.ki_filp != req->rw.ki_filp)
1405                         ctx->poll_multi_file = true;
1406         }
1407
1408         /*
1409          * For fast devices, IO may have already completed. If it has, add
1410          * it to the front so we find it first.
1411          */
1412         if (req->flags & REQ_F_IOPOLL_COMPLETED)
1413                 list_add(&req->list, &ctx->poll_list);
1414         else
1415                 list_add_tail(&req->list, &ctx->poll_list);
1416 }
1417
1418 static void io_file_put(struct io_submit_state *state)
1419 {
1420         if (state->file) {
1421                 int diff = state->has_refs - state->used_refs;
1422
1423                 if (diff)
1424                         fput_many(state->file, diff);
1425                 state->file = NULL;
1426         }
1427 }
1428
1429 /*
1430  * Get as many references to a file as we have IOs left in this submission,
1431  * assuming most submissions are for one file, or at least that each file
1432  * has more than one submission.
1433  */
1434 static struct file *io_file_get(struct io_submit_state *state, int fd)
1435 {
1436         if (!state)
1437                 return fget(fd);
1438
1439         if (state->file) {
1440                 if (state->fd == fd) {
1441                         state->used_refs++;
1442                         state->ios_left--;
1443                         return state->file;
1444                 }
1445                 io_file_put(state);
1446         }
1447         state->file = fget_many(fd, state->ios_left);
1448         if (!state->file)
1449                 return NULL;
1450
1451         state->fd = fd;
1452         state->has_refs = state->ios_left;
1453         state->used_refs = 1;
1454         state->ios_left--;
1455         return state->file;
1456 }
1457
1458 /*
1459  * If we tracked the file through the SCM inflight mechanism, we could support
1460  * any file. For now, just ensure that anything potentially problematic is done
1461  * inline.
1462  */
1463 static bool io_file_supports_async(struct file *file)
1464 {
1465         umode_t mode = file_inode(file)->i_mode;
1466
1467         if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1468                 return true;
1469         if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1470                 return true;
1471
1472         return false;
1473 }
1474
1475 static int io_prep_rw(struct io_kiocb *req, bool force_nonblock)
1476 {
1477         const struct io_uring_sqe *sqe = req->sqe;
1478         struct io_ring_ctx *ctx = req->ctx;
1479         struct kiocb *kiocb = &req->rw;
1480         unsigned ioprio;
1481         int ret;
1482
1483         if (!req->file)
1484                 return -EBADF;
1485
1486         if (S_ISREG(file_inode(req->file)->i_mode))
1487                 req->flags |= REQ_F_ISREG;
1488
1489         kiocb->ki_pos = READ_ONCE(sqe->off);
1490         kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1491         kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1492
1493         ioprio = READ_ONCE(sqe->ioprio);
1494         if (ioprio) {
1495                 ret = ioprio_check_cap(ioprio);
1496                 if (ret)
1497                         return ret;
1498
1499                 kiocb->ki_ioprio = ioprio;
1500         } else
1501                 kiocb->ki_ioprio = get_current_ioprio();
1502
1503         ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1504         if (unlikely(ret))
1505                 return ret;
1506
1507         /* don't allow async punt if RWF_NOWAIT was requested */
1508         if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1509             (req->file->f_flags & O_NONBLOCK))
1510                 req->flags |= REQ_F_NOWAIT;
1511
1512         if (force_nonblock)
1513                 kiocb->ki_flags |= IOCB_NOWAIT;
1514
1515         if (ctx->flags & IORING_SETUP_IOPOLL) {
1516                 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1517                     !kiocb->ki_filp->f_op->iopoll)
1518                         return -EOPNOTSUPP;
1519
1520                 kiocb->ki_flags |= IOCB_HIPRI;
1521                 kiocb->ki_complete = io_complete_rw_iopoll;
1522                 req->result = 0;
1523         } else {
1524                 if (kiocb->ki_flags & IOCB_HIPRI)
1525                         return -EINVAL;
1526                 kiocb->ki_complete = io_complete_rw;
1527         }
1528         return 0;
1529 }
1530
1531 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1532 {
1533         switch (ret) {
1534         case -EIOCBQUEUED:
1535                 break;
1536         case -ERESTARTSYS:
1537         case -ERESTARTNOINTR:
1538         case -ERESTARTNOHAND:
1539         case -ERESTART_RESTARTBLOCK:
1540                 /*
1541                  * We can't just restart the syscall, since previously
1542                  * submitted sqes may already be in progress. Just fail this
1543                  * IO with EINTR.
1544                  */
1545                 ret = -EINTR;
1546                 /* fall through */
1547         default:
1548                 kiocb->ki_complete(kiocb, ret, 0);
1549         }
1550 }
1551
1552 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1553                        bool in_async)
1554 {
1555         if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1556                 *nxt = __io_complete_rw(kiocb, ret);
1557         else
1558                 io_rw_done(kiocb, ret);
1559 }
1560
1561 static ssize_t io_import_fixed(struct io_ring_ctx *ctx, int rw,
1562                                const struct io_uring_sqe *sqe,
1563                                struct iov_iter *iter)
1564 {
1565         size_t len = READ_ONCE(sqe->len);
1566         struct io_mapped_ubuf *imu;
1567         unsigned index, buf_index;
1568         size_t offset;
1569         u64 buf_addr;
1570
1571         /* attempt to use fixed buffers without having provided iovecs */
1572         if (unlikely(!ctx->user_bufs))
1573                 return -EFAULT;
1574
1575         buf_index = READ_ONCE(sqe->buf_index);
1576         if (unlikely(buf_index >= ctx->nr_user_bufs))
1577                 return -EFAULT;
1578
1579         index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1580         imu = &ctx->user_bufs[index];
1581         buf_addr = READ_ONCE(sqe->addr);
1582
1583         /* overflow */
1584         if (buf_addr + len < buf_addr)
1585                 return -EFAULT;
1586         /* not inside the mapped region */
1587         if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1588                 return -EFAULT;
1589
1590         /*
1591          * May not be a start of buffer, set size appropriately
1592          * and advance us to the beginning.
1593          */
1594         offset = buf_addr - imu->ubuf;
1595         iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1596
1597         if (offset) {
1598                 /*
1599                  * Don't use iov_iter_advance() here, as it's really slow for
1600                  * using the latter parts of a big fixed buffer - it iterates
1601                  * over each segment manually. We can cheat a bit here, because
1602                  * we know that:
1603                  *
1604                  * 1) it's a BVEC iter, we set it up
1605                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
1606                  *    first and last bvec
1607                  *
1608                  * So just find our index, and adjust the iterator afterwards.
1609                  * If the offset is within the first bvec (or the whole first
1610                  * bvec, just use iov_iter_advance(). This makes it easier
1611                  * since we can just skip the first segment, which may not
1612                  * be PAGE_SIZE aligned.
1613                  */
1614                 const struct bio_vec *bvec = imu->bvec;
1615
1616                 if (offset <= bvec->bv_len) {
1617                         iov_iter_advance(iter, offset);
1618                 } else {
1619                         unsigned long seg_skip;
1620
1621                         /* skip first vec */
1622                         offset -= bvec->bv_len;
1623                         seg_skip = 1 + (offset >> PAGE_SHIFT);
1624
1625                         iter->bvec = bvec + seg_skip;
1626                         iter->nr_segs -= seg_skip;
1627                         iter->count -= bvec->bv_len + offset;
1628                         iter->iov_offset = offset & ~PAGE_MASK;
1629                 }
1630         }
1631
1632         return len;
1633 }
1634
1635 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1636                                struct iovec **iovec, struct iov_iter *iter)
1637 {
1638         const struct io_uring_sqe *sqe = req->sqe;
1639         void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1640         size_t sqe_len = READ_ONCE(sqe->len);
1641         u8 opcode;
1642
1643         /*
1644          * We're reading ->opcode for the second time, but the first read
1645          * doesn't care whether it's _FIXED or not, so it doesn't matter
1646          * whether ->opcode changes concurrently. The first read does care
1647          * about whether it is a READ or a WRITE, so we don't trust this read
1648          * for that purpose and instead let the caller pass in the read/write
1649          * flag.
1650          */
1651         opcode = READ_ONCE(sqe->opcode);
1652         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1653                 *iovec = NULL;
1654                 return io_import_fixed(req->ctx, rw, sqe, iter);
1655         }
1656
1657         if (req->io) {
1658                 struct io_async_rw *iorw = &req->io->rw;
1659
1660                 *iovec = iorw->iov;
1661                 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
1662                 if (iorw->iov == iorw->fast_iov)
1663                         *iovec = NULL;
1664                 return iorw->size;
1665         }
1666
1667         if (!req->has_user)
1668                 return -EFAULT;
1669
1670 #ifdef CONFIG_COMPAT
1671         if (req->ctx->compat)
1672                 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1673                                                 iovec, iter);
1674 #endif
1675
1676         return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1677 }
1678
1679 /*
1680  * For files that don't have ->read_iter() and ->write_iter(), handle them
1681  * by looping over ->read() or ->write() manually.
1682  */
1683 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1684                            struct iov_iter *iter)
1685 {
1686         ssize_t ret = 0;
1687
1688         /*
1689          * Don't support polled IO through this interface, and we can't
1690          * support non-blocking either. For the latter, this just causes
1691          * the kiocb to be handled from an async context.
1692          */
1693         if (kiocb->ki_flags & IOCB_HIPRI)
1694                 return -EOPNOTSUPP;
1695         if (kiocb->ki_flags & IOCB_NOWAIT)
1696                 return -EAGAIN;
1697
1698         while (iov_iter_count(iter)) {
1699                 struct iovec iovec;
1700                 ssize_t nr;
1701
1702                 if (!iov_iter_is_bvec(iter)) {
1703                         iovec = iov_iter_iovec(iter);
1704                 } else {
1705                         /* fixed buffers import bvec */
1706                         iovec.iov_base = kmap(iter->bvec->bv_page)
1707                                                 + iter->iov_offset;
1708                         iovec.iov_len = min(iter->count,
1709                                         iter->bvec->bv_len - iter->iov_offset);
1710                 }
1711
1712                 if (rw == READ) {
1713                         nr = file->f_op->read(file, iovec.iov_base,
1714                                               iovec.iov_len, &kiocb->ki_pos);
1715                 } else {
1716                         nr = file->f_op->write(file, iovec.iov_base,
1717                                                iovec.iov_len, &kiocb->ki_pos);
1718                 }
1719
1720                 if (iov_iter_is_bvec(iter))
1721                         kunmap(iter->bvec->bv_page);
1722
1723                 if (nr < 0) {
1724                         if (!ret)
1725                                 ret = nr;
1726                         break;
1727                 }
1728                 ret += nr;
1729                 if (nr != iovec.iov_len)
1730                         break;
1731                 iov_iter_advance(iter, nr);
1732         }
1733
1734         return ret;
1735 }
1736
1737 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
1738                           struct iovec *iovec, struct iovec *fast_iov,
1739                           struct iov_iter *iter)
1740 {
1741         req->io->rw.nr_segs = iter->nr_segs;
1742         req->io->rw.size = io_size;
1743         req->io->rw.iov = iovec;
1744         if (!req->io->rw.iov) {
1745                 req->io->rw.iov = req->io->rw.fast_iov;
1746                 memcpy(req->io->rw.iov, fast_iov,
1747                         sizeof(struct iovec) * iter->nr_segs);
1748         }
1749 }
1750
1751 static int io_alloc_async_ctx(struct io_kiocb *req)
1752 {
1753         req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
1754         if (req->io) {
1755                 memcpy(&req->io->sqe, req->sqe, sizeof(req->io->sqe));
1756                 req->sqe = &req->io->sqe;
1757                 return 0;
1758         }
1759
1760         return 1;
1761 }
1762
1763 static void io_rw_async(struct io_wq_work **workptr)
1764 {
1765         struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
1766         struct iovec *iov = NULL;
1767
1768         if (req->io->rw.iov != req->io->rw.fast_iov)
1769                 iov = req->io->rw.iov;
1770         io_wq_submit_work(workptr);
1771         kfree(iov);
1772 }
1773
1774 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
1775                              struct iovec *iovec, struct iovec *fast_iov,
1776                              struct iov_iter *iter)
1777 {
1778         if (!req->io && io_alloc_async_ctx(req))
1779                 return -ENOMEM;
1780
1781         io_req_map_rw(req, io_size, iovec, fast_iov, iter);
1782         req->work.func = io_rw_async;
1783         return 0;
1784 }
1785
1786 static int io_read_prep(struct io_kiocb *req, struct iovec **iovec,
1787                         struct iov_iter *iter, bool force_nonblock)
1788 {
1789         ssize_t ret;
1790
1791         ret = io_prep_rw(req, force_nonblock);
1792         if (ret)
1793                 return ret;
1794
1795         if (unlikely(!(req->file->f_mode & FMODE_READ)))
1796                 return -EBADF;
1797
1798         return io_import_iovec(READ, req, iovec, iter);
1799 }
1800
1801 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
1802                    bool force_nonblock)
1803 {
1804         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1805         struct kiocb *kiocb = &req->rw;
1806         struct iov_iter iter;
1807         struct file *file;
1808         size_t iov_count;
1809         ssize_t io_size, ret;
1810
1811         if (!req->io) {
1812                 ret = io_read_prep(req, &iovec, &iter, force_nonblock);
1813                 if (ret < 0)
1814                         return ret;
1815         } else {
1816                 ret = io_import_iovec(READ, req, &iovec, &iter);
1817                 if (ret < 0)
1818                         return ret;
1819         }
1820
1821         file = req->file;
1822         io_size = ret;
1823         if (req->flags & REQ_F_LINK)
1824                 req->result = io_size;
1825
1826         /*
1827          * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1828          * we know to async punt it even if it was opened O_NONBLOCK
1829          */
1830         if (force_nonblock && !io_file_supports_async(file)) {
1831                 req->flags |= REQ_F_MUST_PUNT;
1832                 goto copy_iov;
1833         }
1834
1835         iov_count = iov_iter_count(&iter);
1836         ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1837         if (!ret) {
1838                 ssize_t ret2;
1839
1840                 if (file->f_op->read_iter)
1841                         ret2 = call_read_iter(file, kiocb, &iter);
1842                 else
1843                         ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1844
1845                 /*
1846                  * In case of a short read, punt to async. This can happen
1847                  * if we have data partially cached. Alternatively we can
1848                  * return the short read, in which case the application will
1849                  * need to issue another SQE and wait for it. That SQE will
1850                  * need async punt anyway, so it's more efficient to do it
1851                  * here.
1852                  */
1853                 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1854                     (req->flags & REQ_F_ISREG) &&
1855                     ret2 > 0 && ret2 < io_size)
1856                         ret2 = -EAGAIN;
1857                 /* Catch -EAGAIN return for forced non-blocking submission */
1858                 if (!force_nonblock || ret2 != -EAGAIN) {
1859                         kiocb_done(kiocb, ret2, nxt, req->in_async);
1860                 } else {
1861 copy_iov:
1862                         ret = io_setup_async_rw(req, io_size, iovec,
1863                                                 inline_vecs, &iter);
1864                         if (ret)
1865                                 goto out_free;
1866                         return -EAGAIN;
1867                 }
1868         }
1869 out_free:
1870         if (!io_wq_current_is_worker())
1871                 kfree(iovec);
1872         return ret;
1873 }
1874
1875 static int io_write_prep(struct io_kiocb *req, struct iovec **iovec,
1876                          struct iov_iter *iter, bool force_nonblock)
1877 {
1878         ssize_t ret;
1879
1880         ret = io_prep_rw(req, force_nonblock);
1881         if (ret)
1882                 return ret;
1883
1884         if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
1885                 return -EBADF;
1886
1887         return io_import_iovec(WRITE, req, iovec, iter);
1888 }
1889
1890 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
1891                     bool force_nonblock)
1892 {
1893         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1894         struct kiocb *kiocb = &req->rw;
1895         struct iov_iter iter;
1896         struct file *file;
1897         size_t iov_count;
1898         ssize_t ret, io_size;
1899
1900         if (!req->io) {
1901                 ret = io_write_prep(req, &iovec, &iter, force_nonblock);
1902                 if (ret < 0)
1903                         return ret;
1904         } else {
1905                 ret = io_import_iovec(WRITE, req, &iovec, &iter);
1906                 if (ret < 0)
1907                         return ret;
1908         }
1909
1910         file = kiocb->ki_filp;
1911         io_size = ret;
1912         if (req->flags & REQ_F_LINK)
1913                 req->result = io_size;
1914
1915         /*
1916          * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1917          * we know to async punt it even if it was opened O_NONBLOCK
1918          */
1919         if (force_nonblock && !io_file_supports_async(req->file)) {
1920                 req->flags |= REQ_F_MUST_PUNT;
1921                 goto copy_iov;
1922         }
1923
1924         /* file path doesn't support NOWAIT for non-direct_IO */
1925         if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
1926             (req->flags & REQ_F_ISREG))
1927                 goto copy_iov;
1928
1929         iov_count = iov_iter_count(&iter);
1930         ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1931         if (!ret) {
1932                 ssize_t ret2;
1933
1934                 /*
1935                  * Open-code file_start_write here to grab freeze protection,
1936                  * which will be released by another thread in
1937                  * io_complete_rw().  Fool lockdep by telling it the lock got
1938                  * released so that it doesn't complain about the held lock when
1939                  * we return to userspace.
1940                  */
1941                 if (req->flags & REQ_F_ISREG) {
1942                         __sb_start_write(file_inode(file)->i_sb,
1943                                                 SB_FREEZE_WRITE, true);
1944                         __sb_writers_release(file_inode(file)->i_sb,
1945                                                 SB_FREEZE_WRITE);
1946                 }
1947                 kiocb->ki_flags |= IOCB_WRITE;
1948
1949                 if (file->f_op->write_iter)
1950                         ret2 = call_write_iter(file, kiocb, &iter);
1951                 else
1952                         ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1953                 if (!force_nonblock || ret2 != -EAGAIN) {
1954                         kiocb_done(kiocb, ret2, nxt, req->in_async);
1955                 } else {
1956 copy_iov:
1957                         ret = io_setup_async_rw(req, io_size, iovec,
1958                                                 inline_vecs, &iter);
1959                         if (ret)
1960                                 goto out_free;
1961                         return -EAGAIN;
1962                 }
1963         }
1964 out_free:
1965         if (!io_wq_current_is_worker())
1966                 kfree(iovec);
1967         return ret;
1968 }
1969
1970 /*
1971  * IORING_OP_NOP just posts a completion event, nothing else.
1972  */
1973 static int io_nop(struct io_kiocb *req)
1974 {
1975         struct io_ring_ctx *ctx = req->ctx;
1976
1977         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1978                 return -EINVAL;
1979
1980         io_cqring_add_event(req, 0);
1981         io_put_req(req);
1982         return 0;
1983 }
1984
1985 static int io_prep_fsync(struct io_kiocb *req)
1986 {
1987         const struct io_uring_sqe *sqe = req->sqe;
1988         struct io_ring_ctx *ctx = req->ctx;
1989
1990         if (req->flags & REQ_F_PREPPED)
1991                 return 0;
1992         if (!req->file)
1993                 return -EBADF;
1994
1995         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1996                 return -EINVAL;
1997         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1998                 return -EINVAL;
1999
2000         req->sync.flags = READ_ONCE(sqe->fsync_flags);
2001         if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2002                 return -EINVAL;
2003
2004         req->sync.off = READ_ONCE(sqe->off);
2005         req->sync.len = READ_ONCE(sqe->len);
2006         req->flags |= REQ_F_PREPPED;
2007         return 0;
2008 }
2009
2010 static bool io_req_cancelled(struct io_kiocb *req)
2011 {
2012         if (req->work.flags & IO_WQ_WORK_CANCEL) {
2013                 req_set_fail_links(req);
2014                 io_cqring_add_event(req, -ECANCELED);
2015                 io_put_req(req);
2016                 return true;
2017         }
2018
2019         return false;
2020 }
2021
2022 static void io_fsync_finish(struct io_wq_work **workptr)
2023 {
2024         struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2025         loff_t end = req->sync.off + req->sync.len;
2026         struct io_kiocb *nxt = NULL;
2027         int ret;
2028
2029         if (io_req_cancelled(req))
2030                 return;
2031
2032         ret = vfs_fsync_range(req->rw.ki_filp, req->sync.off,
2033                                 end > 0 ? end : LLONG_MAX,
2034                                 req->sync.flags & IORING_FSYNC_DATASYNC);
2035         if (ret < 0)
2036                 req_set_fail_links(req);
2037         io_cqring_add_event(req, ret);
2038         io_put_req_find_next(req, &nxt);
2039         if (nxt)
2040                 *workptr = &nxt->work;
2041 }
2042
2043 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2044                     bool force_nonblock)
2045 {
2046         struct io_wq_work *work, *old_work;
2047         int ret;
2048
2049         ret = io_prep_fsync(req);
2050         if (ret)
2051                 return ret;
2052
2053         /* fsync always requires a blocking context */
2054         if (force_nonblock) {
2055                 io_put_req(req);
2056                 req->work.func = io_fsync_finish;
2057                 return -EAGAIN;
2058         }
2059
2060         work = old_work = &req->work;
2061         io_fsync_finish(&work);
2062         if (work && work != old_work)
2063                 *nxt = container_of(work, struct io_kiocb, work);
2064         return 0;
2065 }
2066
2067 static int io_prep_sfr(struct io_kiocb *req)
2068 {
2069         const struct io_uring_sqe *sqe = req->sqe;
2070         struct io_ring_ctx *ctx = req->ctx;
2071
2072         if (req->flags & REQ_F_PREPPED)
2073                 return 0;
2074         if (!req->file)
2075                 return -EBADF;
2076
2077         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2078                 return -EINVAL;
2079         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2080                 return -EINVAL;
2081
2082         req->sync.off = READ_ONCE(sqe->off);
2083         req->sync.len = READ_ONCE(sqe->len);
2084         req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2085         req->flags |= REQ_F_PREPPED;
2086         return 0;
2087 }
2088
2089 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2090 {
2091         struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2092         struct io_kiocb *nxt = NULL;
2093         int ret;
2094
2095         if (io_req_cancelled(req))
2096                 return;
2097
2098         ret = sync_file_range(req->rw.ki_filp, req->sync.off, req->sync.len,
2099                                 req->sync.flags);
2100         if (ret < 0)
2101                 req_set_fail_links(req);
2102         io_cqring_add_event(req, ret);
2103         io_put_req_find_next(req, &nxt);
2104         if (nxt)
2105                 *workptr = &nxt->work;
2106 }
2107
2108 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2109                               bool force_nonblock)
2110 {
2111         struct io_wq_work *work, *old_work;
2112         int ret;
2113
2114         ret = io_prep_sfr(req);
2115         if (ret)
2116                 return ret;
2117
2118         /* sync_file_range always requires a blocking context */
2119         if (force_nonblock) {
2120                 io_put_req(req);
2121                 req->work.func = io_sync_file_range_finish;
2122                 return -EAGAIN;
2123         }
2124
2125         work = old_work = &req->work;
2126         io_sync_file_range_finish(&work);
2127         if (work && work != old_work)
2128                 *nxt = container_of(work, struct io_kiocb, work);
2129         return 0;
2130 }
2131
2132 #if defined(CONFIG_NET)
2133 static void io_sendrecv_async(struct io_wq_work **workptr)
2134 {
2135         struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2136         struct iovec *iov = NULL;
2137
2138         if (req->io->rw.iov != req->io->rw.fast_iov)
2139                 iov = req->io->msg.iov;
2140         io_wq_submit_work(workptr);
2141         kfree(iov);
2142 }
2143 #endif
2144
2145 static int io_sendmsg_prep(struct io_kiocb *req, struct io_async_ctx *io)
2146 {
2147 #if defined(CONFIG_NET)
2148         const struct io_uring_sqe *sqe = req->sqe;
2149         struct user_msghdr __user *msg;
2150         unsigned flags;
2151
2152         flags = READ_ONCE(sqe->msg_flags);
2153         msg = (struct user_msghdr __user *)(unsigned long) READ_ONCE(sqe->addr);
2154         io->msg.iov = io->msg.fast_iov;
2155         return sendmsg_copy_msghdr(&io->msg.msg, msg, flags, &io->msg.iov);
2156 #else
2157         return 0;
2158 #endif
2159 }
2160
2161 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2162                       bool force_nonblock)
2163 {
2164 #if defined(CONFIG_NET)
2165         const struct io_uring_sqe *sqe = req->sqe;
2166         struct io_async_msghdr *kmsg = NULL;
2167         struct socket *sock;
2168         int ret;
2169
2170         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2171                 return -EINVAL;
2172
2173         sock = sock_from_file(req->file, &ret);
2174         if (sock) {
2175                 struct io_async_ctx io;
2176                 struct sockaddr_storage addr;
2177                 unsigned flags;
2178
2179                 flags = READ_ONCE(sqe->msg_flags);
2180                 if (flags & MSG_DONTWAIT)
2181                         req->flags |= REQ_F_NOWAIT;
2182                 else if (force_nonblock)
2183                         flags |= MSG_DONTWAIT;
2184
2185                 if (req->io) {
2186                         kmsg = &req->io->msg;
2187                         kmsg->msg.msg_name = &addr;
2188                         /* if iov is set, it's allocated already */
2189                         if (!kmsg->iov)
2190                                 kmsg->iov = kmsg->fast_iov;
2191                         kmsg->msg.msg_iter.iov = kmsg->iov;
2192                 } else {
2193                         kmsg = &io.msg;
2194                         kmsg->msg.msg_name = &addr;
2195                         ret = io_sendmsg_prep(req, &io);
2196                         if (ret)
2197                                 goto out;
2198                 }
2199
2200                 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
2201                 if (force_nonblock && ret == -EAGAIN) {
2202                         if (req->io)
2203                                 return -EAGAIN;
2204                         if (io_alloc_async_ctx(req))
2205                                 return -ENOMEM;
2206                         memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2207                         req->work.func = io_sendrecv_async;
2208                         return -EAGAIN;
2209                 }
2210                 if (ret == -ERESTARTSYS)
2211                         ret = -EINTR;
2212         }
2213
2214 out:
2215         if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2216                 kfree(kmsg->iov);
2217         io_cqring_add_event(req, ret);
2218         if (ret < 0)
2219                 req_set_fail_links(req);
2220         io_put_req_find_next(req, nxt);
2221         return 0;
2222 #else
2223         return -EOPNOTSUPP;
2224 #endif
2225 }
2226
2227 static int io_recvmsg_prep(struct io_kiocb *req, struct io_async_ctx *io)
2228 {
2229 #if defined(CONFIG_NET)
2230         const struct io_uring_sqe *sqe = req->sqe;
2231         struct user_msghdr __user *msg;
2232         unsigned flags;
2233
2234         flags = READ_ONCE(sqe->msg_flags);
2235         msg = (struct user_msghdr __user *)(unsigned long) READ_ONCE(sqe->addr);
2236         io->msg.iov = io->msg.fast_iov;
2237         return recvmsg_copy_msghdr(&io->msg.msg, msg, flags, &io->msg.uaddr,
2238                                         &io->msg.iov);
2239 #else
2240         return 0;
2241 #endif
2242 }
2243
2244 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2245                       bool force_nonblock)
2246 {
2247 #if defined(CONFIG_NET)
2248         const struct io_uring_sqe *sqe = req->sqe;
2249         struct io_async_msghdr *kmsg = NULL;
2250         struct socket *sock;
2251         int ret;
2252
2253         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2254                 return -EINVAL;
2255
2256         sock = sock_from_file(req->file, &ret);
2257         if (sock) {
2258                 struct user_msghdr __user *msg;
2259                 struct io_async_ctx io;
2260                 struct sockaddr_storage addr;
2261                 unsigned flags;
2262
2263                 flags = READ_ONCE(sqe->msg_flags);
2264                 if (flags & MSG_DONTWAIT)
2265                         req->flags |= REQ_F_NOWAIT;
2266                 else if (force_nonblock)
2267                         flags |= MSG_DONTWAIT;
2268
2269                 msg = (struct user_msghdr __user *) (unsigned long)
2270                         READ_ONCE(sqe->addr);
2271                 if (req->io) {
2272                         kmsg = &req->io->msg;
2273                         kmsg->msg.msg_name = &addr;
2274                         /* if iov is set, it's allocated already */
2275                         if (!kmsg->iov)
2276                                 kmsg->iov = kmsg->fast_iov;
2277                         kmsg->msg.msg_iter.iov = kmsg->iov;
2278                 } else {
2279                         kmsg = &io.msg;
2280                         kmsg->msg.msg_name = &addr;
2281                         ret = io_recvmsg_prep(req, &io);
2282                         if (ret)
2283                                 goto out;
2284                 }
2285
2286                 ret = __sys_recvmsg_sock(sock, &kmsg->msg, msg, kmsg->uaddr, flags);
2287                 if (force_nonblock && ret == -EAGAIN) {
2288                         if (req->io)
2289                                 return -EAGAIN;
2290                         if (io_alloc_async_ctx(req))
2291                                 return -ENOMEM;
2292                         memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2293                         req->work.func = io_sendrecv_async;
2294                         return -EAGAIN;
2295                 }
2296                 if (ret == -ERESTARTSYS)
2297                         ret = -EINTR;
2298         }
2299
2300 out:
2301         if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2302                 kfree(kmsg->iov);
2303         io_cqring_add_event(req, ret);
2304         if (ret < 0)
2305                 req_set_fail_links(req);
2306         io_put_req_find_next(req, nxt);
2307         return 0;
2308 #else
2309         return -EOPNOTSUPP;
2310 #endif
2311 }
2312
2313 static int io_accept_prep(struct io_kiocb *req)
2314 {
2315 #if defined(CONFIG_NET)
2316         const struct io_uring_sqe *sqe = req->sqe;
2317         struct io_accept *accept = &req->accept;
2318
2319         if (req->flags & REQ_F_PREPPED)
2320                 return 0;
2321
2322         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2323                 return -EINVAL;
2324         if (sqe->ioprio || sqe->len || sqe->buf_index)
2325                 return -EINVAL;
2326
2327         accept->addr = (struct sockaddr __user *)
2328                                 (unsigned long) READ_ONCE(sqe->addr);
2329         accept->addr_len = (int __user *) (unsigned long) READ_ONCE(sqe->addr2);
2330         accept->flags = READ_ONCE(sqe->accept_flags);
2331         req->flags |= REQ_F_PREPPED;
2332         return 0;
2333 #else
2334         return -EOPNOTSUPP;
2335 #endif
2336 }
2337
2338 #if defined(CONFIG_NET)
2339 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2340                        bool force_nonblock)
2341 {
2342         struct io_accept *accept = &req->accept;
2343         unsigned file_flags;
2344         int ret;
2345
2346         file_flags = force_nonblock ? O_NONBLOCK : 0;
2347         ret = __sys_accept4_file(req->file, file_flags, accept->addr,
2348                                         accept->addr_len, accept->flags);
2349         if (ret == -EAGAIN && force_nonblock)
2350                 return -EAGAIN;
2351         if (ret == -ERESTARTSYS)
2352                 ret = -EINTR;
2353         if (ret < 0)
2354                 req_set_fail_links(req);
2355         io_cqring_add_event(req, ret);
2356         io_put_req_find_next(req, nxt);
2357         return 0;
2358 }
2359
2360 static void io_accept_finish(struct io_wq_work **workptr)
2361 {
2362         struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2363         struct io_kiocb *nxt = NULL;
2364
2365         if (io_req_cancelled(req))
2366                 return;
2367         __io_accept(req, &nxt, false);
2368         if (nxt)
2369                 *workptr = &nxt->work;
2370 }
2371 #endif
2372
2373 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2374                      bool force_nonblock)
2375 {
2376 #if defined(CONFIG_NET)
2377         int ret;
2378
2379         ret = io_accept_prep(req);
2380         if (ret)
2381                 return ret;
2382
2383         ret = __io_accept(req, nxt, force_nonblock);
2384         if (ret == -EAGAIN && force_nonblock) {
2385                 req->work.func = io_accept_finish;
2386                 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2387                 io_put_req(req);
2388                 return -EAGAIN;
2389         }
2390         return 0;
2391 #else
2392         return -EOPNOTSUPP;
2393 #endif
2394 }
2395
2396 static int io_connect_prep(struct io_kiocb *req, struct io_async_ctx *io)
2397 {
2398 #if defined(CONFIG_NET)
2399         const struct io_uring_sqe *sqe = req->sqe;
2400         struct sockaddr __user *addr;
2401         int addr_len;
2402
2403         addr = (struct sockaddr __user *) (unsigned long) READ_ONCE(sqe->addr);
2404         addr_len = READ_ONCE(sqe->addr2);
2405         return move_addr_to_kernel(addr, addr_len, &io->connect.address);
2406 #else
2407         return 0;
2408 #endif
2409 }
2410
2411 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
2412                       bool force_nonblock)
2413 {
2414 #if defined(CONFIG_NET)
2415         const struct io_uring_sqe *sqe = req->sqe;
2416         struct io_async_ctx __io, *io;
2417         unsigned file_flags;
2418         int addr_len, ret;
2419
2420         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2421                 return -EINVAL;
2422         if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
2423                 return -EINVAL;
2424
2425         addr_len = READ_ONCE(sqe->addr2);
2426         file_flags = force_nonblock ? O_NONBLOCK : 0;
2427
2428         if (req->io) {
2429                 io = req->io;
2430         } else {
2431                 ret = io_connect_prep(req, &__io);
2432                 if (ret)
2433                         goto out;
2434                 io = &__io;
2435         }
2436
2437         ret = __sys_connect_file(req->file, &io->connect.address, addr_len,
2438                                         file_flags);
2439         if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
2440                 if (req->io)
2441                         return -EAGAIN;
2442                 if (io_alloc_async_ctx(req)) {
2443                         ret = -ENOMEM;
2444                         goto out;
2445                 }
2446                 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
2447                 return -EAGAIN;
2448         }
2449         if (ret == -ERESTARTSYS)
2450                 ret = -EINTR;
2451 out:
2452         if (ret < 0)
2453                 req_set_fail_links(req);
2454         io_cqring_add_event(req, ret);
2455         io_put_req_find_next(req, nxt);
2456         return 0;
2457 #else
2458         return -EOPNOTSUPP;
2459 #endif
2460 }
2461
2462 static void io_poll_remove_one(struct io_kiocb *req)
2463 {
2464         struct io_poll_iocb *poll = &req->poll;
2465
2466         spin_lock(&poll->head->lock);
2467         WRITE_ONCE(poll->canceled, true);
2468         if (!list_empty(&poll->wait.entry)) {
2469                 list_del_init(&poll->wait.entry);
2470                 io_queue_async_work(req);
2471         }
2472         spin_unlock(&poll->head->lock);
2473         hash_del(&req->hash_node);
2474 }
2475
2476 static void io_poll_remove_all(struct io_ring_ctx *ctx)
2477 {
2478         struct hlist_node *tmp;
2479         struct io_kiocb *req;
2480         int i;
2481
2482         spin_lock_irq(&ctx->completion_lock);
2483         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
2484                 struct hlist_head *list;
2485
2486                 list = &ctx->cancel_hash[i];
2487                 hlist_for_each_entry_safe(req, tmp, list, hash_node)
2488                         io_poll_remove_one(req);
2489         }
2490         spin_unlock_irq(&ctx->completion_lock);
2491 }
2492
2493 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
2494 {
2495         struct hlist_head *list;
2496         struct io_kiocb *req;
2497
2498         list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
2499         hlist_for_each_entry(req, list, hash_node) {
2500                 if (sqe_addr == req->user_data) {
2501                         io_poll_remove_one(req);
2502                         return 0;
2503                 }
2504         }
2505
2506         return -ENOENT;
2507 }
2508
2509 static int io_poll_remove_prep(struct io_kiocb *req)
2510 {
2511         const struct io_uring_sqe *sqe = req->sqe;
2512
2513         if (req->flags & REQ_F_PREPPED)
2514                 return 0;
2515         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2516                 return -EINVAL;
2517         if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
2518             sqe->poll_events)
2519                 return -EINVAL;
2520
2521         req->poll.addr = READ_ONCE(sqe->addr);
2522         req->flags |= REQ_F_PREPPED;
2523         return 0;
2524 }
2525
2526 /*
2527  * Find a running poll command that matches one specified in sqe->addr,
2528  * and remove it if found.
2529  */
2530 static int io_poll_remove(struct io_kiocb *req)
2531 {
2532         struct io_ring_ctx *ctx = req->ctx;
2533         u64 addr;
2534         int ret;
2535
2536         ret = io_poll_remove_prep(req);
2537         if (ret)
2538                 return ret;
2539
2540         addr = req->poll.addr;
2541         spin_lock_irq(&ctx->completion_lock);
2542         ret = io_poll_cancel(ctx, addr);
2543         spin_unlock_irq(&ctx->completion_lock);
2544
2545         io_cqring_add_event(req, ret);
2546         if (ret < 0)
2547                 req_set_fail_links(req);
2548         io_put_req(req);
2549         return 0;
2550 }
2551
2552 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
2553 {
2554         struct io_ring_ctx *ctx = req->ctx;
2555
2556         req->poll.done = true;
2557         if (error)
2558                 io_cqring_fill_event(req, error);
2559         else
2560                 io_cqring_fill_event(req, mangle_poll(mask));
2561         io_commit_cqring(ctx);
2562 }
2563
2564 static void io_poll_complete_work(struct io_wq_work **workptr)
2565 {
2566         struct io_wq_work *work = *workptr;
2567         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2568         struct io_poll_iocb *poll = &req->poll;
2569         struct poll_table_struct pt = { ._key = poll->events };
2570         struct io_ring_ctx *ctx = req->ctx;
2571         struct io_kiocb *nxt = NULL;
2572         __poll_t mask = 0;
2573         int ret = 0;
2574
2575         if (work->flags & IO_WQ_WORK_CANCEL) {
2576                 WRITE_ONCE(poll->canceled, true);
2577                 ret = -ECANCELED;
2578         } else if (READ_ONCE(poll->canceled)) {
2579                 ret = -ECANCELED;
2580         }
2581
2582         if (ret != -ECANCELED)
2583                 mask = vfs_poll(poll->file, &pt) & poll->events;
2584
2585         /*
2586          * Note that ->ki_cancel callers also delete iocb from active_reqs after
2587          * calling ->ki_cancel.  We need the ctx_lock roundtrip here to
2588          * synchronize with them.  In the cancellation case the list_del_init
2589          * itself is not actually needed, but harmless so we keep it in to
2590          * avoid further branches in the fast path.
2591          */
2592         spin_lock_irq(&ctx->completion_lock);
2593         if (!mask && ret != -ECANCELED) {
2594                 add_wait_queue(poll->head, &poll->wait);
2595                 spin_unlock_irq(&ctx->completion_lock);
2596                 return;
2597         }
2598         hash_del(&req->hash_node);
2599         io_poll_complete(req, mask, ret);
2600         spin_unlock_irq(&ctx->completion_lock);
2601
2602         io_cqring_ev_posted(ctx);
2603
2604         if (ret < 0)
2605                 req_set_fail_links(req);
2606         io_put_req_find_next(req, &nxt);
2607         if (nxt)
2608                 *workptr = &nxt->work;
2609 }
2610
2611 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
2612                         void *key)
2613 {
2614         struct io_poll_iocb *poll = wait->private;
2615         struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
2616         struct io_ring_ctx *ctx = req->ctx;
2617         __poll_t mask = key_to_poll(key);
2618         unsigned long flags;
2619
2620         /* for instances that support it check for an event match first: */
2621         if (mask && !(mask & poll->events))
2622                 return 0;
2623
2624         list_del_init(&poll->wait.entry);
2625
2626         /*
2627          * Run completion inline if we can. We're using trylock here because
2628          * we are violating the completion_lock -> poll wq lock ordering.
2629          * If we have a link timeout we're going to need the completion_lock
2630          * for finalizing the request, mark us as having grabbed that already.
2631          */
2632         if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
2633                 hash_del(&req->hash_node);
2634                 io_poll_complete(req, mask, 0);
2635                 req->flags |= REQ_F_COMP_LOCKED;
2636                 io_put_req(req);
2637                 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2638
2639                 io_cqring_ev_posted(ctx);
2640         } else {
2641                 io_queue_async_work(req);
2642         }
2643
2644         return 1;
2645 }
2646
2647 struct io_poll_table {
2648         struct poll_table_struct pt;
2649         struct io_kiocb *req;
2650         int error;
2651 };
2652
2653 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
2654                                struct poll_table_struct *p)
2655 {
2656         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
2657
2658         if (unlikely(pt->req->poll.head)) {
2659                 pt->error = -EINVAL;
2660                 return;
2661         }
2662
2663         pt->error = 0;
2664         pt->req->poll.head = head;
2665         add_wait_queue(head, &pt->req->poll.wait);
2666 }
2667
2668 static void io_poll_req_insert(struct io_kiocb *req)
2669 {
2670         struct io_ring_ctx *ctx = req->ctx;
2671         struct hlist_head *list;
2672
2673         list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
2674         hlist_add_head(&req->hash_node, list);
2675 }
2676
2677 static int io_poll_add_prep(struct io_kiocb *req)
2678 {
2679         const struct io_uring_sqe *sqe = req->sqe;
2680         struct io_poll_iocb *poll = &req->poll;
2681         u16 events;
2682
2683         if (req->flags & REQ_F_PREPPED)
2684                 return 0;
2685         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2686                 return -EINVAL;
2687         if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
2688                 return -EINVAL;
2689         if (!poll->file)
2690                 return -EBADF;
2691
2692         req->flags |= REQ_F_PREPPED;
2693         events = READ_ONCE(sqe->poll_events);
2694         poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
2695         return 0;
2696 }
2697
2698 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
2699 {
2700         struct io_poll_iocb *poll = &req->poll;
2701         struct io_ring_ctx *ctx = req->ctx;
2702         struct io_poll_table ipt;
2703         bool cancel = false;
2704         __poll_t mask;
2705         int ret;
2706
2707         ret = io_poll_add_prep(req);
2708         if (ret)
2709                 return ret;
2710
2711         INIT_IO_WORK(&req->work, io_poll_complete_work);
2712         INIT_HLIST_NODE(&req->hash_node);
2713
2714         poll->head = NULL;
2715         poll->done = false;
2716         poll->canceled = false;
2717
2718         ipt.pt._qproc = io_poll_queue_proc;
2719         ipt.pt._key = poll->events;
2720         ipt.req = req;
2721         ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
2722
2723         /* initialized the list so that we can do list_empty checks */
2724         INIT_LIST_HEAD(&poll->wait.entry);
2725         init_waitqueue_func_entry(&poll->wait, io_poll_wake);
2726         poll->wait.private = poll;
2727
2728         INIT_LIST_HEAD(&req->list);
2729
2730         mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
2731
2732         spin_lock_irq(&ctx->completion_lock);
2733         if (likely(poll->head)) {
2734                 spin_lock(&poll->head->lock);
2735                 if (unlikely(list_empty(&poll->wait.entry))) {
2736                         if (ipt.error)
2737                                 cancel = true;
2738                         ipt.error = 0;
2739                         mask = 0;
2740                 }
2741                 if (mask || ipt.error)
2742                         list_del_init(&poll->wait.entry);
2743                 else if (cancel)
2744                         WRITE_ONCE(poll->canceled, true);
2745                 else if (!poll->done) /* actually waiting for an event */
2746                         io_poll_req_insert(req);
2747                 spin_unlock(&poll->head->lock);
2748         }
2749         if (mask) { /* no async, we'd stolen it */
2750                 ipt.error = 0;
2751                 io_poll_complete(req, mask, 0);
2752         }
2753         spin_unlock_irq(&ctx->completion_lock);
2754
2755         if (mask) {
2756                 io_cqring_ev_posted(ctx);
2757                 io_put_req_find_next(req, nxt);
2758         }
2759         return ipt.error;
2760 }
2761
2762 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
2763 {
2764         struct io_timeout_data *data = container_of(timer,
2765                                                 struct io_timeout_data, timer);
2766         struct io_kiocb *req = data->req;
2767         struct io_ring_ctx *ctx = req->ctx;
2768         unsigned long flags;
2769
2770         atomic_inc(&ctx->cq_timeouts);
2771
2772         spin_lock_irqsave(&ctx->completion_lock, flags);
2773         /*
2774          * We could be racing with timeout deletion. If the list is empty,
2775          * then timeout lookup already found it and will be handling it.
2776          */
2777         if (!list_empty(&req->list)) {
2778                 struct io_kiocb *prev;
2779
2780                 /*
2781                  * Adjust the reqs sequence before the current one because it
2782                  * will consume a slot in the cq_ring and the cq_tail
2783                  * pointer will be increased, otherwise other timeout reqs may
2784                  * return in advance without waiting for enough wait_nr.
2785                  */
2786                 prev = req;
2787                 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
2788                         prev->sequence++;
2789                 list_del_init(&req->list);
2790         }
2791
2792         io_cqring_fill_event(req, -ETIME);
2793         io_commit_cqring(ctx);
2794         spin_unlock_irqrestore(&ctx->completion_lock, flags);
2795
2796         io_cqring_ev_posted(ctx);
2797         req_set_fail_links(req);
2798         io_put_req(req);
2799         return HRTIMER_NORESTART;
2800 }
2801
2802 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
2803 {
2804         struct io_kiocb *req;
2805         int ret = -ENOENT;
2806
2807         list_for_each_entry(req, &ctx->timeout_list, list) {
2808                 if (user_data == req->user_data) {
2809                         list_del_init(&req->list);
2810                         ret = 0;
2811                         break;
2812                 }
2813         }
2814
2815         if (ret == -ENOENT)
2816                 return ret;
2817
2818         ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
2819         if (ret == -1)
2820                 return -EALREADY;
2821
2822         req_set_fail_links(req);
2823         io_cqring_fill_event(req, -ECANCELED);
2824         io_put_req(req);
2825         return 0;
2826 }
2827
2828 static int io_timeout_remove_prep(struct io_kiocb *req)
2829 {
2830         const struct io_uring_sqe *sqe = req->sqe;
2831
2832         if (req->flags & REQ_F_PREPPED)
2833                 return 0;
2834         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2835                 return -EINVAL;
2836         if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
2837                 return -EINVAL;
2838
2839         req->timeout.addr = READ_ONCE(sqe->addr);
2840         req->timeout.flags = READ_ONCE(sqe->timeout_flags);
2841         if (req->timeout.flags)
2842                 return -EINVAL;
2843
2844         req->flags |= REQ_F_PREPPED;
2845         return 0;
2846 }
2847
2848 /*
2849  * Remove or update an existing timeout command
2850  */
2851 static int io_timeout_remove(struct io_kiocb *req)
2852 {
2853         struct io_ring_ctx *ctx = req->ctx;
2854         int ret;
2855
2856         ret = io_timeout_remove_prep(req);
2857         if (ret)
2858                 return ret;
2859
2860         spin_lock_irq(&ctx->completion_lock);
2861         ret = io_timeout_cancel(ctx, req->timeout.addr);
2862
2863         io_cqring_fill_event(req, ret);
2864         io_commit_cqring(ctx);
2865         spin_unlock_irq(&ctx->completion_lock);
2866         io_cqring_ev_posted(ctx);
2867         if (ret < 0)
2868                 req_set_fail_links(req);
2869         io_put_req(req);
2870         return 0;
2871 }
2872
2873 static int io_timeout_prep(struct io_kiocb *req, struct io_async_ctx *io,
2874                            bool is_timeout_link)
2875 {
2876         const struct io_uring_sqe *sqe = req->sqe;
2877         struct io_timeout_data *data;
2878         unsigned flags;
2879
2880         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2881                 return -EINVAL;
2882         if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
2883                 return -EINVAL;
2884         if (sqe->off && is_timeout_link)
2885                 return -EINVAL;
2886         flags = READ_ONCE(sqe->timeout_flags);
2887         if (flags & ~IORING_TIMEOUT_ABS)
2888                 return -EINVAL;
2889
2890         data = &io->timeout;
2891         data->req = req;
2892         req->flags |= REQ_F_TIMEOUT;
2893
2894         if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
2895                 return -EFAULT;
2896
2897         if (flags & IORING_TIMEOUT_ABS)
2898                 data->mode = HRTIMER_MODE_ABS;
2899         else
2900                 data->mode = HRTIMER_MODE_REL;
2901
2902         hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
2903         return 0;
2904 }
2905
2906 static int io_timeout(struct io_kiocb *req)
2907 {
2908         const struct io_uring_sqe *sqe = req->sqe;
2909         unsigned count;
2910         struct io_ring_ctx *ctx = req->ctx;
2911         struct io_timeout_data *data;
2912         struct list_head *entry;
2913         unsigned span = 0;
2914         int ret;
2915
2916         if (!req->io) {
2917                 if (io_alloc_async_ctx(req))
2918                         return -ENOMEM;
2919                 ret = io_timeout_prep(req, req->io, false);
2920                 if (ret)
2921                         return ret;
2922         }
2923         data = &req->io->timeout;
2924
2925         /*
2926          * sqe->off holds how many events that need to occur for this
2927          * timeout event to be satisfied. If it isn't set, then this is
2928          * a pure timeout request, sequence isn't used.
2929          */
2930         count = READ_ONCE(sqe->off);
2931         if (!count) {
2932                 req->flags |= REQ_F_TIMEOUT_NOSEQ;
2933                 spin_lock_irq(&ctx->completion_lock);
2934                 entry = ctx->timeout_list.prev;
2935                 goto add;
2936         }
2937
2938         req->sequence = ctx->cached_sq_head + count - 1;
2939         data->seq_offset = count;
2940
2941         /*
2942          * Insertion sort, ensuring the first entry in the list is always
2943          * the one we need first.
2944          */
2945         spin_lock_irq(&ctx->completion_lock);
2946         list_for_each_prev(entry, &ctx->timeout_list) {
2947                 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
2948                 unsigned nxt_sq_head;
2949                 long long tmp, tmp_nxt;
2950                 u32 nxt_offset = nxt->io->timeout.seq_offset;
2951
2952                 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
2953                         continue;
2954
2955                 /*
2956                  * Since cached_sq_head + count - 1 can overflow, use type long
2957                  * long to store it.
2958                  */
2959                 tmp = (long long)ctx->cached_sq_head + count - 1;
2960                 nxt_sq_head = nxt->sequence - nxt_offset + 1;
2961                 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
2962
2963                 /*
2964                  * cached_sq_head may overflow, and it will never overflow twice
2965                  * once there is some timeout req still be valid.
2966                  */
2967                 if (ctx->cached_sq_head < nxt_sq_head)
2968                         tmp += UINT_MAX;
2969
2970                 if (tmp > tmp_nxt)
2971                         break;
2972
2973                 /*
2974                  * Sequence of reqs after the insert one and itself should
2975                  * be adjusted because each timeout req consumes a slot.
2976                  */
2977                 span++;
2978                 nxt->sequence++;
2979         }
2980         req->sequence -= span;
2981 add:
2982         list_add(&req->list, entry);
2983         data->timer.function = io_timeout_fn;
2984         hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
2985         spin_unlock_irq(&ctx->completion_lock);
2986         return 0;
2987 }
2988
2989 static bool io_cancel_cb(struct io_wq_work *work, void *data)
2990 {
2991         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2992
2993         return req->user_data == (unsigned long) data;
2994 }
2995
2996 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
2997 {
2998         enum io_wq_cancel cancel_ret;
2999         int ret = 0;
3000
3001         cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3002         switch (cancel_ret) {
3003         case IO_WQ_CANCEL_OK:
3004                 ret = 0;
3005                 break;
3006         case IO_WQ_CANCEL_RUNNING:
3007                 ret = -EALREADY;
3008                 break;
3009         case IO_WQ_CANCEL_NOTFOUND:
3010                 ret = -ENOENT;
3011                 break;
3012         }
3013
3014         return ret;
3015 }
3016
3017 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3018                                      struct io_kiocb *req, __u64 sqe_addr,
3019                                      struct io_kiocb **nxt, int success_ret)
3020 {
3021         unsigned long flags;
3022         int ret;
3023
3024         ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3025         if (ret != -ENOENT) {
3026                 spin_lock_irqsave(&ctx->completion_lock, flags);
3027                 goto done;
3028         }
3029
3030         spin_lock_irqsave(&ctx->completion_lock, flags);
3031         ret = io_timeout_cancel(ctx, sqe_addr);
3032         if (ret != -ENOENT)
3033                 goto done;
3034         ret = io_poll_cancel(ctx, sqe_addr);
3035 done:
3036         if (!ret)
3037                 ret = success_ret;
3038         io_cqring_fill_event(req, ret);
3039         io_commit_cqring(ctx);
3040         spin_unlock_irqrestore(&ctx->completion_lock, flags);
3041         io_cqring_ev_posted(ctx);
3042
3043         if (ret < 0)
3044                 req_set_fail_links(req);
3045         io_put_req_find_next(req, nxt);
3046 }
3047
3048 static int io_async_cancel_prep(struct io_kiocb *req)
3049 {
3050         const struct io_uring_sqe *sqe = req->sqe;
3051
3052         if (req->flags & REQ_F_PREPPED)
3053                 return 0;
3054         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3055                 return -EINVAL;
3056         if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
3057             sqe->cancel_flags)
3058                 return -EINVAL;
3059
3060         req->flags |= REQ_F_PREPPED;
3061         req->cancel.addr = READ_ONCE(sqe->addr);
3062         return 0;
3063 }
3064
3065 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
3066 {
3067         struct io_ring_ctx *ctx = req->ctx;
3068         int ret;
3069
3070         ret = io_async_cancel_prep(req);
3071         if (ret)
3072                 return ret;
3073
3074         io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
3075         return 0;
3076 }
3077
3078 static int io_req_defer_prep(struct io_kiocb *req)
3079 {
3080         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3081         struct io_async_ctx *io = req->io;
3082         struct iov_iter iter;
3083         ssize_t ret;
3084
3085         switch (io->sqe.opcode) {
3086         case IORING_OP_READV:
3087         case IORING_OP_READ_FIXED:
3088                 /* ensure prep does right import */
3089                 req->io = NULL;
3090                 ret = io_read_prep(req, &iovec, &iter, true);
3091                 req->io = io;
3092                 if (ret < 0)
3093                         break;
3094                 io_req_map_rw(req, ret, iovec, inline_vecs, &iter);
3095                 ret = 0;
3096                 break;
3097         case IORING_OP_WRITEV:
3098         case IORING_OP_WRITE_FIXED:
3099                 /* ensure prep does right import */
3100                 req->io = NULL;
3101                 ret = io_write_prep(req, &iovec, &iter, true);
3102                 req->io = io;
3103                 if (ret < 0)
3104                         break;
3105                 io_req_map_rw(req, ret, iovec, inline_vecs, &iter);
3106                 ret = 0;
3107                 break;
3108         case IORING_OP_POLL_ADD:
3109                 ret = io_poll_add_prep(req);
3110                 break;
3111         case IORING_OP_POLL_REMOVE:
3112                 ret = io_poll_remove_prep(req);
3113                 break;
3114         case IORING_OP_FSYNC:
3115                 ret = io_prep_fsync(req);
3116                 break;
3117         case IORING_OP_SYNC_FILE_RANGE:
3118                 ret = io_prep_sfr(req);
3119                 break;
3120         case IORING_OP_SENDMSG:
3121                 ret = io_sendmsg_prep(req, io);
3122                 break;
3123         case IORING_OP_RECVMSG:
3124                 ret = io_recvmsg_prep(req, io);
3125                 break;
3126         case IORING_OP_CONNECT:
3127                 ret = io_connect_prep(req, io);
3128                 break;
3129         case IORING_OP_TIMEOUT:
3130                 ret = io_timeout_prep(req, io, false);
3131                 break;
3132         case IORING_OP_TIMEOUT_REMOVE:
3133                 ret = io_timeout_remove_prep(req);
3134                 break;
3135         case IORING_OP_ASYNC_CANCEL:
3136                 ret = io_async_cancel_prep(req);
3137                 break;
3138         case IORING_OP_LINK_TIMEOUT:
3139                 ret = io_timeout_prep(req, io, true);
3140                 break;
3141         case IORING_OP_ACCEPT:
3142                 ret = io_accept_prep(req);
3143                 break;
3144         default:
3145                 ret = 0;
3146                 break;
3147         }
3148
3149         return ret;
3150 }
3151
3152 static int io_req_defer(struct io_kiocb *req)
3153 {
3154         struct io_ring_ctx *ctx = req->ctx;
3155         int ret;
3156
3157         /* Still need defer if there is pending req in defer list. */
3158         if (!req_need_defer(req) && list_empty(&ctx->defer_list))
3159                 return 0;
3160
3161         if (io_alloc_async_ctx(req))
3162                 return -EAGAIN;
3163
3164         ret = io_req_defer_prep(req);
3165         if (ret < 0)
3166                 return ret;
3167
3168         spin_lock_irq(&ctx->completion_lock);
3169         if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
3170                 spin_unlock_irq(&ctx->completion_lock);
3171                 return 0;
3172         }
3173
3174         trace_io_uring_defer(ctx, req, req->user_data);
3175         list_add_tail(&req->list, &ctx->defer_list);
3176         spin_unlock_irq(&ctx->completion_lock);
3177         return -EIOCBQUEUED;
3178 }
3179
3180 __attribute__((nonnull))
3181 static int io_issue_sqe(struct io_kiocb *req, struct io_kiocb **nxt,
3182                         bool force_nonblock)
3183 {
3184         int ret, opcode;
3185         struct io_ring_ctx *ctx = req->ctx;
3186
3187         opcode = READ_ONCE(req->sqe->opcode);
3188         switch (opcode) {
3189         case IORING_OP_NOP:
3190                 ret = io_nop(req);
3191                 break;
3192         case IORING_OP_READV:
3193                 if (unlikely(req->sqe->buf_index))
3194                         return -EINVAL;
3195                 ret = io_read(req, nxt, force_nonblock);
3196                 break;
3197         case IORING_OP_WRITEV:
3198                 if (unlikely(req->sqe->buf_index))
3199                         return -EINVAL;
3200                 ret = io_write(req, nxt, force_nonblock);
3201                 break;
3202         case IORING_OP_READ_FIXED:
3203                 ret = io_read(req, nxt, force_nonblock);
3204                 break;
3205         case IORING_OP_WRITE_FIXED:
3206                 ret = io_write(req, nxt, force_nonblock);
3207                 break;
3208         case IORING_OP_FSYNC:
3209                 ret = io_fsync(req, nxt, force_nonblock);
3210                 break;
3211         case IORING_OP_POLL_ADD:
3212                 ret = io_poll_add(req, nxt);
3213                 break;
3214         case IORING_OP_POLL_REMOVE:
3215                 ret = io_poll_remove(req);
3216                 break;
3217         case IORING_OP_SYNC_FILE_RANGE:
3218                 ret = io_sync_file_range(req, nxt, force_nonblock);
3219                 break;
3220         case IORING_OP_SENDMSG:
3221                 ret = io_sendmsg(req, nxt, force_nonblock);
3222                 break;
3223         case IORING_OP_RECVMSG:
3224                 ret = io_recvmsg(req, nxt, force_nonblock);
3225                 break;
3226         case IORING_OP_TIMEOUT:
3227                 ret = io_timeout(req);
3228                 break;
3229         case IORING_OP_TIMEOUT_REMOVE:
3230                 ret = io_timeout_remove(req);
3231                 break;
3232         case IORING_OP_ACCEPT:
3233                 ret = io_accept(req, nxt, force_nonblock);
3234                 break;
3235         case IORING_OP_CONNECT:
3236                 ret = io_connect(req, nxt, force_nonblock);
3237                 break;
3238         case IORING_OP_ASYNC_CANCEL:
3239                 ret = io_async_cancel(req, nxt);
3240                 break;
3241         default:
3242                 ret = -EINVAL;
3243                 break;
3244         }
3245
3246         if (ret)
3247                 return ret;
3248
3249         if (ctx->flags & IORING_SETUP_IOPOLL) {
3250                 if (req->result == -EAGAIN)
3251                         return -EAGAIN;
3252
3253                 io_iopoll_req_issued(req);
3254         }
3255
3256         return 0;
3257 }
3258
3259 static void io_link_work_cb(struct io_wq_work **workptr)
3260 {
3261         struct io_wq_work *work = *workptr;
3262         struct io_kiocb *link = work->data;
3263
3264         io_queue_linked_timeout(link);
3265         work->func = io_wq_submit_work;
3266 }
3267
3268 static void io_wq_submit_work(struct io_wq_work **workptr)
3269 {
3270         struct io_wq_work *work = *workptr;
3271         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3272         struct io_kiocb *nxt = NULL;
3273         int ret = 0;
3274
3275         /* Ensure we clear previously set non-block flag */
3276         req->rw.ki_flags &= ~IOCB_NOWAIT;
3277
3278         if (work->flags & IO_WQ_WORK_CANCEL)
3279                 ret = -ECANCELED;
3280
3281         if (!ret) {
3282                 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
3283                 req->in_async = true;
3284                 do {
3285                         ret = io_issue_sqe(req, &nxt, false);
3286                         /*
3287                          * We can get EAGAIN for polled IO even though we're
3288                          * forcing a sync submission from here, since we can't
3289                          * wait for request slots on the block side.
3290                          */
3291                         if (ret != -EAGAIN)
3292                                 break;
3293                         cond_resched();
3294                 } while (1);
3295         }
3296
3297         /* drop submission reference */
3298         io_put_req(req);
3299
3300         if (ret) {
3301                 req_set_fail_links(req);
3302                 io_cqring_add_event(req, ret);
3303                 io_put_req(req);
3304         }
3305
3306         /* if a dependent link is ready, pass it back */
3307         if (!ret && nxt) {
3308                 struct io_kiocb *link;
3309
3310                 io_prep_async_work(nxt, &link);
3311                 *workptr = &nxt->work;
3312                 if (link) {
3313                         nxt->work.flags |= IO_WQ_WORK_CB;
3314                         nxt->work.func = io_link_work_cb;
3315                         nxt->work.data = link;
3316                 }
3317         }
3318 }
3319
3320 static bool io_req_op_valid(int op)
3321 {
3322         return op >= IORING_OP_NOP && op < IORING_OP_LAST;
3323 }
3324
3325 static int io_op_needs_file(const struct io_uring_sqe *sqe)
3326 {
3327         int op = READ_ONCE(sqe->opcode);
3328
3329         switch (op) {
3330         case IORING_OP_NOP:
3331         case IORING_OP_POLL_REMOVE:
3332         case IORING_OP_TIMEOUT:
3333         case IORING_OP_TIMEOUT_REMOVE:
3334         case IORING_OP_ASYNC_CANCEL:
3335         case IORING_OP_LINK_TIMEOUT:
3336                 return 0;
3337         default:
3338                 if (io_req_op_valid(op))
3339                         return 1;
3340                 return -EINVAL;
3341         }
3342 }
3343
3344 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
3345                                               int index)
3346 {
3347         struct fixed_file_table *table;
3348
3349         table = &ctx->file_table[index >> IORING_FILE_TABLE_SHIFT];
3350         return table->files[index & IORING_FILE_TABLE_MASK];
3351 }
3352
3353 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req)
3354 {
3355         struct io_ring_ctx *ctx = req->ctx;
3356         unsigned flags;
3357         int fd, ret;
3358
3359         flags = READ_ONCE(req->sqe->flags);
3360         fd = READ_ONCE(req->sqe->fd);
3361
3362         if (flags & IOSQE_IO_DRAIN)
3363                 req->flags |= REQ_F_IO_DRAIN;
3364
3365         ret = io_op_needs_file(req->sqe);
3366         if (ret <= 0)
3367                 return ret;
3368
3369         if (flags & IOSQE_FIXED_FILE) {
3370                 if (unlikely(!ctx->file_table ||
3371                     (unsigned) fd >= ctx->nr_user_files))
3372                         return -EBADF;
3373                 fd = array_index_nospec(fd, ctx->nr_user_files);
3374                 req->file = io_file_from_index(ctx, fd);
3375                 if (!req->file)
3376                         return -EBADF;
3377                 req->flags |= REQ_F_FIXED_FILE;
3378         } else {
3379                 if (req->needs_fixed_file)
3380                         return -EBADF;
3381                 trace_io_uring_file_get(ctx, fd);
3382                 req->file = io_file_get(state, fd);
3383                 if (unlikely(!req->file))
3384                         return -EBADF;
3385         }
3386
3387         return 0;
3388 }
3389
3390 static int io_grab_files(struct io_kiocb *req)
3391 {
3392         int ret = -EBADF;
3393         struct io_ring_ctx *ctx = req->ctx;
3394
3395         rcu_read_lock();
3396         spin_lock_irq(&ctx->inflight_lock);
3397         /*
3398          * We use the f_ops->flush() handler to ensure that we can flush
3399          * out work accessing these files if the fd is closed. Check if
3400          * the fd has changed since we started down this path, and disallow
3401          * this operation if it has.
3402          */
3403         if (fcheck(req->ring_fd) == req->ring_file) {
3404                 list_add(&req->inflight_entry, &ctx->inflight_list);
3405                 req->flags |= REQ_F_INFLIGHT;
3406                 req->work.files = current->files;
3407                 ret = 0;
3408         }
3409         spin_unlock_irq(&ctx->inflight_lock);
3410         rcu_read_unlock();
3411
3412         return ret;
3413 }
3414
3415 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
3416 {
3417         struct io_timeout_data *data = container_of(timer,
3418                                                 struct io_timeout_data, timer);
3419         struct io_kiocb *req = data->req;
3420         struct io_ring_ctx *ctx = req->ctx;
3421         struct io_kiocb *prev = NULL;
3422         unsigned long flags;
3423
3424         spin_lock_irqsave(&ctx->completion_lock, flags);
3425
3426         /*
3427          * We don't expect the list to be empty, that will only happen if we
3428          * race with the completion of the linked work.
3429          */
3430         if (!list_empty(&req->link_list)) {
3431                 prev = list_entry(req->link_list.prev, struct io_kiocb,
3432                                   link_list);
3433                 if (refcount_inc_not_zero(&prev->refs)) {
3434                         list_del_init(&req->link_list);
3435                         prev->flags &= ~REQ_F_LINK_TIMEOUT;
3436                 } else
3437                         prev = NULL;
3438         }
3439
3440         spin_unlock_irqrestore(&ctx->completion_lock, flags);
3441
3442         if (prev) {
3443                 req_set_fail_links(prev);
3444                 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
3445                                                 -ETIME);
3446                 io_put_req(prev);
3447         } else {
3448                 io_cqring_add_event(req, -ETIME);
3449                 io_put_req(req);
3450         }
3451         return HRTIMER_NORESTART;
3452 }
3453
3454 static void io_queue_linked_timeout(struct io_kiocb *req)
3455 {
3456         struct io_ring_ctx *ctx = req->ctx;
3457
3458         /*
3459          * If the list is now empty, then our linked request finished before
3460          * we got a chance to setup the timer
3461          */
3462         spin_lock_irq(&ctx->completion_lock);
3463         if (!list_empty(&req->link_list)) {
3464                 struct io_timeout_data *data = &req->io->timeout;
3465
3466                 data->timer.function = io_link_timeout_fn;
3467                 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
3468                                 data->mode);
3469         }
3470         spin_unlock_irq(&ctx->completion_lock);
3471
3472         /* drop submission reference */
3473         io_put_req(req);
3474 }
3475
3476 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
3477 {
3478         struct io_kiocb *nxt;
3479
3480         if (!(req->flags & REQ_F_LINK))
3481                 return NULL;
3482
3483         nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
3484                                         link_list);
3485         if (!nxt || nxt->sqe->opcode != IORING_OP_LINK_TIMEOUT)
3486                 return NULL;
3487
3488         req->flags |= REQ_F_LINK_TIMEOUT;
3489         return nxt;
3490 }
3491
3492 static void __io_queue_sqe(struct io_kiocb *req)
3493 {
3494         struct io_kiocb *linked_timeout;
3495         struct io_kiocb *nxt = NULL;
3496         int ret;
3497
3498 again:
3499         linked_timeout = io_prep_linked_timeout(req);
3500
3501         ret = io_issue_sqe(req, &nxt, true);
3502
3503         /*
3504          * We async punt it if the file wasn't marked NOWAIT, or if the file
3505          * doesn't support non-blocking read/write attempts
3506          */
3507         if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
3508             (req->flags & REQ_F_MUST_PUNT))) {
3509                 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
3510                         ret = io_grab_files(req);
3511                         if (ret)
3512                                 goto err;
3513                 }
3514
3515                 /*
3516                  * Queued up for async execution, worker will release
3517                  * submit reference when the iocb is actually submitted.
3518                  */
3519                 io_queue_async_work(req);
3520                 goto done_req;
3521         }
3522
3523 err:
3524         /* drop submission reference */
3525         io_put_req(req);
3526
3527         if (linked_timeout) {
3528                 if (!ret)
3529                         io_queue_linked_timeout(linked_timeout);
3530                 else
3531                         io_put_req(linked_timeout);
3532         }
3533
3534         /* and drop final reference, if we failed */
3535         if (ret) {
3536                 io_cqring_add_event(req, ret);
3537                 req_set_fail_links(req);
3538                 io_put_req(req);
3539         }
3540 done_req:
3541         if (nxt) {
3542                 req = nxt;
3543                 nxt = NULL;
3544                 goto again;
3545         }
3546 }
3547
3548 static void io_queue_sqe(struct io_kiocb *req)
3549 {
3550         int ret;
3551
3552         if (unlikely(req->ctx->drain_next)) {
3553                 req->flags |= REQ_F_IO_DRAIN;
3554                 req->ctx->drain_next = false;
3555         }
3556         req->ctx->drain_next = (req->flags & REQ_F_DRAIN_LINK);
3557
3558         ret = io_req_defer(req);
3559         if (ret) {
3560                 if (ret != -EIOCBQUEUED) {
3561                         io_cqring_add_event(req, ret);
3562                         req_set_fail_links(req);
3563                         io_double_put_req(req);
3564                 }
3565         } else
3566                 __io_queue_sqe(req);
3567 }
3568
3569 static inline void io_queue_link_head(struct io_kiocb *req)
3570 {
3571         if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
3572                 io_cqring_add_event(req, -ECANCELED);
3573                 io_double_put_req(req);
3574         } else
3575                 io_queue_sqe(req);
3576 }
3577
3578 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
3579                                 IOSQE_IO_HARDLINK)
3580
3581 static bool io_submit_sqe(struct io_kiocb *req, struct io_submit_state *state,
3582                           struct io_kiocb **link)
3583 {
3584         struct io_ring_ctx *ctx = req->ctx;
3585         int ret;
3586
3587         req->user_data = req->sqe->user_data;
3588
3589         /* enforce forwards compatibility on users */
3590         if (unlikely(req->sqe->flags & ~SQE_VALID_FLAGS)) {
3591                 ret = -EINVAL;
3592                 goto err_req;
3593         }
3594
3595         ret = io_req_set_file(state, req);
3596         if (unlikely(ret)) {
3597 err_req:
3598                 io_cqring_add_event(req, ret);
3599                 io_double_put_req(req);
3600                 return false;
3601         }
3602
3603         /*
3604          * If we already have a head request, queue this one for async
3605          * submittal once the head completes. If we don't have a head but
3606          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
3607          * submitted sync once the chain is complete. If none of those
3608          * conditions are true (normal request), then just queue it.
3609          */
3610         if (*link) {
3611                 struct io_kiocb *prev = *link;
3612
3613                 if (req->sqe->flags & IOSQE_IO_DRAIN)
3614                         (*link)->flags |= REQ_F_DRAIN_LINK | REQ_F_IO_DRAIN;
3615
3616                 if (req->sqe->flags & IOSQE_IO_HARDLINK)
3617                         req->flags |= REQ_F_HARDLINK;
3618
3619                 if (io_alloc_async_ctx(req)) {
3620                         ret = -EAGAIN;
3621                         goto err_req;
3622                 }
3623
3624                 ret = io_req_defer_prep(req);
3625                 if (ret) {
3626                         /* fail even hard links since we don't submit */
3627                         prev->flags |= REQ_F_FAIL_LINK;
3628                         goto err_req;
3629                 }
3630                 trace_io_uring_link(ctx, req, prev);
3631                 list_add_tail(&req->link_list, &prev->link_list);
3632         } else if (req->sqe->flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
3633                 req->flags |= REQ_F_LINK;
3634                 if (req->sqe->flags & IOSQE_IO_HARDLINK)
3635                         req->flags |= REQ_F_HARDLINK;
3636
3637                 INIT_LIST_HEAD(&req->link_list);
3638                 *link = req;
3639         } else {
3640                 io_queue_sqe(req);
3641         }
3642
3643         return true;
3644 }
3645
3646 /*
3647  * Batched submission is done, ensure local IO is flushed out.
3648  */
3649 static void io_submit_state_end(struct io_submit_state *state)
3650 {
3651         blk_finish_plug(&state->plug);
3652         io_file_put(state);
3653         if (state->free_reqs)
3654                 kmem_cache_free_bulk(req_cachep, state->free_reqs,
3655                                         &state->reqs[state->cur_req]);
3656 }
3657
3658 /*
3659  * Start submission side cache.
3660  */
3661 static void io_submit_state_start(struct io_submit_state *state,
3662                                   unsigned int max_ios)
3663 {
3664         blk_start_plug(&state->plug);
3665         state->free_reqs = 0;
3666         state->file = NULL;
3667         state->ios_left = max_ios;
3668 }
3669
3670 static void io_commit_sqring(struct io_ring_ctx *ctx)
3671 {
3672         struct io_rings *rings = ctx->rings;
3673
3674         if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
3675                 /*
3676                  * Ensure any loads from the SQEs are done at this point,
3677                  * since once we write the new head, the application could
3678                  * write new data to them.
3679                  */
3680                 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
3681         }
3682 }
3683
3684 /*
3685  * Fetch an sqe, if one is available. Note that req->sqe will point to memory
3686  * that is mapped by userspace. This means that care needs to be taken to
3687  * ensure that reads are stable, as we cannot rely on userspace always
3688  * being a good citizen. If members of the sqe are validated and then later
3689  * used, it's important that those reads are done through READ_ONCE() to
3690  * prevent a re-load down the line.
3691  */
3692 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req)
3693 {
3694         struct io_rings *rings = ctx->rings;
3695         u32 *sq_array = ctx->sq_array;
3696         unsigned head;
3697
3698         /*
3699          * The cached sq head (or cq tail) serves two purposes:
3700          *
3701          * 1) allows us to batch the cost of updating the user visible
3702          *    head updates.
3703          * 2) allows the kernel side to track the head on its own, even
3704          *    though the application is the one updating it.
3705          */
3706         head = ctx->cached_sq_head;
3707         /* make sure SQ entry isn't read before tail */
3708         if (unlikely(head == smp_load_acquire(&rings->sq.tail)))
3709                 return false;
3710
3711         head = READ_ONCE(sq_array[head & ctx->sq_mask]);
3712         if (likely(head < ctx->sq_entries)) {
3713                 /*
3714                  * All io need record the previous position, if LINK vs DARIN,
3715                  * it can be used to mark the position of the first IO in the
3716                  * link list.
3717                  */
3718                 req->sequence = ctx->cached_sq_head;
3719                 req->sqe = &ctx->sq_sqes[head];
3720                 ctx->cached_sq_head++;
3721                 return true;
3722         }
3723
3724         /* drop invalid entries */
3725         ctx->cached_sq_head++;
3726         ctx->cached_sq_dropped++;
3727         WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
3728         return false;
3729 }
3730
3731 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
3732                           struct file *ring_file, int ring_fd,
3733                           struct mm_struct **mm, bool async)
3734 {
3735         struct io_submit_state state, *statep = NULL;
3736         struct io_kiocb *link = NULL;
3737         int i, submitted = 0;
3738         bool mm_fault = false;
3739
3740         /* if we have a backlog and couldn't flush it all, return BUSY */
3741         if (!list_empty(&ctx->cq_overflow_list) &&
3742             !io_cqring_overflow_flush(ctx, false))
3743                 return -EBUSY;
3744
3745         if (nr > IO_PLUG_THRESHOLD) {
3746                 io_submit_state_start(&state, nr);
3747                 statep = &state;
3748         }
3749
3750         for (i = 0; i < nr; i++) {
3751                 struct io_kiocb *req;
3752                 unsigned int sqe_flags;
3753
3754                 req = io_get_req(ctx, statep);
3755                 if (unlikely(!req)) {
3756                         if (!submitted)
3757                                 submitted = -EAGAIN;
3758                         break;
3759                 }
3760                 if (!io_get_sqring(ctx, req)) {
3761                         __io_free_req(req);
3762                         break;
3763                 }
3764
3765                 if (io_sqe_needs_user(req->sqe) && !*mm) {
3766                         mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
3767                         if (!mm_fault) {
3768                                 use_mm(ctx->sqo_mm);
3769                                 *mm = ctx->sqo_mm;
3770                         }
3771                 }
3772
3773                 submitted++;
3774                 sqe_flags = req->sqe->flags;
3775
3776                 req->ring_file = ring_file;
3777                 req->ring_fd = ring_fd;
3778                 req->has_user = *mm != NULL;
3779                 req->in_async = async;
3780                 req->needs_fixed_file = async;
3781                 trace_io_uring_submit_sqe(ctx, req->sqe->user_data,
3782                                           true, async);
3783                 if (!io_submit_sqe(req, statep, &link))
3784                         break;
3785                 /*
3786                  * If previous wasn't linked and we have a linked command,
3787                  * that's the end of the chain. Submit the previous link.
3788                  */
3789                 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) && link) {
3790                         io_queue_link_head(link);
3791                         link = NULL;
3792                 }
3793         }
3794
3795         if (link)
3796                 io_queue_link_head(link);
3797         if (statep)
3798                 io_submit_state_end(&state);
3799
3800          /* Commit SQ ring head once we've consumed and submitted all SQEs */
3801         io_commit_sqring(ctx);
3802
3803         return submitted;
3804 }
3805
3806 static int io_sq_thread(void *data)
3807 {
3808         struct io_ring_ctx *ctx = data;
3809         struct mm_struct *cur_mm = NULL;
3810         const struct cred *old_cred;
3811         mm_segment_t old_fs;
3812         DEFINE_WAIT(wait);
3813         unsigned inflight;
3814         unsigned long timeout;
3815         int ret;
3816
3817         complete(&ctx->completions[1]);
3818
3819         old_fs = get_fs();
3820         set_fs(USER_DS);
3821         old_cred = override_creds(ctx->creds);
3822
3823         ret = timeout = inflight = 0;
3824         while (!kthread_should_park()) {
3825                 unsigned int to_submit;
3826
3827                 if (inflight) {
3828                         unsigned nr_events = 0;
3829
3830                         if (ctx->flags & IORING_SETUP_IOPOLL) {
3831                                 /*
3832                                  * inflight is the count of the maximum possible
3833                                  * entries we submitted, but it can be smaller
3834                                  * if we dropped some of them. If we don't have
3835                                  * poll entries available, then we know that we
3836                                  * have nothing left to poll for. Reset the
3837                                  * inflight count to zero in that case.
3838                                  */
3839                                 mutex_lock(&ctx->uring_lock);
3840                                 if (!list_empty(&ctx->poll_list))
3841                                         __io_iopoll_check(ctx, &nr_events, 0);
3842                                 else
3843                                         inflight = 0;
3844                                 mutex_unlock(&ctx->uring_lock);
3845                         } else {
3846                                 /*
3847                                  * Normal IO, just pretend everything completed.
3848                                  * We don't have to poll completions for that.
3849                                  */
3850                                 nr_events = inflight;
3851                         }
3852
3853                         inflight -= nr_events;
3854                         if (!inflight)
3855                                 timeout = jiffies + ctx->sq_thread_idle;
3856                 }
3857
3858                 to_submit = io_sqring_entries(ctx);
3859
3860                 /*
3861                  * If submit got -EBUSY, flag us as needing the application
3862                  * to enter the kernel to reap and flush events.
3863                  */
3864                 if (!to_submit || ret == -EBUSY) {
3865                         /*
3866                          * We're polling. If we're within the defined idle
3867                          * period, then let us spin without work before going
3868                          * to sleep. The exception is if we got EBUSY doing
3869                          * more IO, we should wait for the application to
3870                          * reap events and wake us up.
3871                          */
3872                         if (inflight ||
3873                             (!time_after(jiffies, timeout) && ret != -EBUSY)) {
3874                                 cond_resched();
3875                                 continue;
3876                         }
3877
3878                         /*
3879                          * Drop cur_mm before scheduling, we can't hold it for
3880                          * long periods (or over schedule()). Do this before
3881                          * adding ourselves to the waitqueue, as the unuse/drop
3882                          * may sleep.
3883                          */
3884                         if (cur_mm) {
3885                                 unuse_mm(cur_mm);
3886                                 mmput(cur_mm);
3887                                 cur_mm = NULL;
3888                         }
3889
3890                         prepare_to_wait(&ctx->sqo_wait, &wait,
3891                                                 TASK_INTERRUPTIBLE);
3892
3893                         /* Tell userspace we may need a wakeup call */
3894                         ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
3895                         /* make sure to read SQ tail after writing flags */
3896                         smp_mb();
3897
3898                         to_submit = io_sqring_entries(ctx);
3899                         if (!to_submit || ret == -EBUSY) {
3900                                 if (kthread_should_park()) {
3901                                         finish_wait(&ctx->sqo_wait, &wait);
3902                                         break;
3903                                 }
3904                                 if (signal_pending(current))
3905                                         flush_signals(current);
3906                                 schedule();
3907                                 finish_wait(&ctx->sqo_wait, &wait);
3908
3909                                 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3910                                 continue;
3911                         }
3912                         finish_wait(&ctx->sqo_wait, &wait);
3913
3914                         ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3915                 }
3916
3917                 to_submit = min(to_submit, ctx->sq_entries);
3918                 mutex_lock(&ctx->uring_lock);
3919                 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
3920                 mutex_unlock(&ctx->uring_lock);
3921                 if (ret > 0)
3922                         inflight += ret;
3923         }
3924
3925         set_fs(old_fs);
3926         if (cur_mm) {
3927                 unuse_mm(cur_mm);
3928                 mmput(cur_mm);
3929         }
3930         revert_creds(old_cred);
3931
3932         kthread_parkme();
3933
3934         return 0;
3935 }
3936
3937 struct io_wait_queue {
3938         struct wait_queue_entry wq;
3939         struct io_ring_ctx *ctx;
3940         unsigned to_wait;
3941         unsigned nr_timeouts;
3942 };
3943
3944 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
3945 {
3946         struct io_ring_ctx *ctx = iowq->ctx;
3947
3948         /*
3949          * Wake up if we have enough events, or if a timeout occurred since we
3950          * started waiting. For timeouts, we always want to return to userspace,
3951          * regardless of event count.
3952          */
3953         return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
3954                         atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
3955 }
3956
3957 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
3958                             int wake_flags, void *key)
3959 {
3960         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3961                                                         wq);
3962
3963         /* use noflush == true, as we can't safely rely on locking context */
3964         if (!io_should_wake(iowq, true))
3965                 return -1;
3966
3967         return autoremove_wake_function(curr, mode, wake_flags, key);
3968 }
3969
3970 /*
3971  * Wait until events become available, if we don't already have some. The
3972  * application must reap them itself, as they reside on the shared cq ring.
3973  */
3974 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3975                           const sigset_t __user *sig, size_t sigsz)
3976 {
3977         struct io_wait_queue iowq = {
3978                 .wq = {
3979                         .private        = current,
3980                         .func           = io_wake_function,
3981                         .entry          = LIST_HEAD_INIT(iowq.wq.entry),
3982                 },
3983                 .ctx            = ctx,
3984                 .to_wait        = min_events,
3985         };
3986         struct io_rings *rings = ctx->rings;
3987         int ret = 0;
3988
3989         if (io_cqring_events(ctx, false) >= min_events)
3990                 return 0;
3991
3992         if (sig) {
3993 #ifdef CONFIG_COMPAT
3994                 if (in_compat_syscall())
3995                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
3996                                                       sigsz);
3997                 else
3998 #endif
3999                         ret = set_user_sigmask(sig, sigsz);
4000
4001                 if (ret)
4002                         return ret;
4003         }
4004
4005         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
4006         trace_io_uring_cqring_wait(ctx, min_events);
4007         do {
4008                 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
4009                                                 TASK_INTERRUPTIBLE);
4010                 if (io_should_wake(&iowq, false))
4011                         break;
4012                 schedule();
4013                 if (signal_pending(current)) {
4014                         ret = -EINTR;
4015                         break;
4016                 }
4017         } while (1);
4018         finish_wait(&ctx->wait, &iowq.wq);
4019
4020         restore_saved_sigmask_unless(ret == -EINTR);
4021
4022         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
4023 }
4024
4025 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
4026 {
4027 #if defined(CONFIG_UNIX)
4028         if (ctx->ring_sock) {
4029                 struct sock *sock = ctx->ring_sock->sk;
4030                 struct sk_buff *skb;
4031
4032                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
4033                         kfree_skb(skb);
4034         }
4035 #else
4036         int i;
4037
4038         for (i = 0; i < ctx->nr_user_files; i++) {
4039                 struct file *file;
4040
4041                 file = io_file_from_index(ctx, i);
4042                 if (file)
4043                         fput(file);
4044         }
4045 #endif
4046 }
4047
4048 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
4049 {
4050         unsigned nr_tables, i;
4051
4052         if (!ctx->file_table)
4053                 return -ENXIO;
4054
4055         __io_sqe_files_unregister(ctx);
4056         nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
4057         for (i = 0; i < nr_tables; i++)
4058                 kfree(ctx->file_table[i].files);
4059         kfree(ctx->file_table);
4060         ctx->file_table = NULL;
4061         ctx->nr_user_files = 0;
4062         return 0;
4063 }
4064
4065 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
4066 {
4067         if (ctx->sqo_thread) {
4068                 wait_for_completion(&ctx->completions[1]);
4069                 /*
4070                  * The park is a bit of a work-around, without it we get
4071                  * warning spews on shutdown with SQPOLL set and affinity
4072                  * set to a single CPU.
4073                  */
4074                 kthread_park(ctx->sqo_thread);
4075                 kthread_stop(ctx->sqo_thread);
4076                 ctx->sqo_thread = NULL;
4077         }
4078 }
4079
4080 static void io_finish_async(struct io_ring_ctx *ctx)
4081 {
4082         io_sq_thread_stop(ctx);
4083
4084         if (ctx->io_wq) {
4085                 io_wq_destroy(ctx->io_wq);
4086                 ctx->io_wq = NULL;
4087         }
4088 }
4089
4090 #if defined(CONFIG_UNIX)
4091 static void io_destruct_skb(struct sk_buff *skb)
4092 {
4093         struct io_ring_ctx *ctx = skb->sk->sk_user_data;
4094
4095         if (ctx->io_wq)
4096                 io_wq_flush(ctx->io_wq);
4097
4098         unix_destruct_scm(skb);
4099 }
4100
4101 /*
4102  * Ensure the UNIX gc is aware of our file set, so we are certain that
4103  * the io_uring can be safely unregistered on process exit, even if we have
4104  * loops in the file referencing.
4105  */
4106 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
4107 {
4108         struct sock *sk = ctx->ring_sock->sk;
4109         struct scm_fp_list *fpl;
4110         struct sk_buff *skb;
4111         int i, nr_files;
4112
4113         if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
4114                 unsigned long inflight = ctx->user->unix_inflight + nr;
4115
4116                 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
4117                         return -EMFILE;
4118         }
4119
4120         fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
4121         if (!fpl)
4122                 return -ENOMEM;
4123
4124         skb = alloc_skb(0, GFP_KERNEL);
4125         if (!skb) {
4126                 kfree(fpl);
4127                 return -ENOMEM;
4128         }
4129
4130         skb->sk = sk;
4131
4132         nr_files = 0;
4133         fpl->user = get_uid(ctx->user);
4134         for (i = 0; i < nr; i++) {
4135                 struct file *file = io_file_from_index(ctx, i + offset);
4136
4137                 if (!file)
4138                         continue;
4139                 fpl->fp[nr_files] = get_file(file);
4140                 unix_inflight(fpl->user, fpl->fp[nr_files]);
4141                 nr_files++;
4142         }
4143
4144         if (nr_files) {
4145                 fpl->max = SCM_MAX_FD;
4146                 fpl->count = nr_files;
4147                 UNIXCB(skb).fp = fpl;
4148                 skb->destructor = io_destruct_skb;
4149                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
4150                 skb_queue_head(&sk->sk_receive_queue, skb);
4151
4152                 for (i = 0; i < nr_files; i++)
4153                         fput(fpl->fp[i]);
4154         } else {
4155                 kfree_skb(skb);
4156                 kfree(fpl);
4157         }
4158
4159         return 0;
4160 }
4161
4162 /*
4163  * If UNIX sockets are enabled, fd passing can cause a reference cycle which
4164  * causes regular reference counting to break down. We rely on the UNIX
4165  * garbage collection to take care of this problem for us.
4166  */
4167 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4168 {
4169         unsigned left, total;
4170         int ret = 0;
4171
4172         total = 0;
4173         left = ctx->nr_user_files;
4174         while (left) {
4175                 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
4176
4177                 ret = __io_sqe_files_scm(ctx, this_files, total);
4178                 if (ret)
4179                         break;
4180                 left -= this_files;
4181                 total += this_files;
4182         }
4183
4184         if (!ret)
4185                 return 0;
4186
4187         while (total < ctx->nr_user_files) {
4188                 struct file *file = io_file_from_index(ctx, total);
4189
4190                 if (file)
4191                         fput(file);
4192                 total++;
4193         }
4194
4195         return ret;
4196 }
4197 #else
4198 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4199 {
4200         return 0;
4201 }
4202 #endif
4203
4204 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
4205                                     unsigned nr_files)
4206 {
4207         int i;
4208
4209         for (i = 0; i < nr_tables; i++) {
4210                 struct fixed_file_table *table = &ctx->file_table[i];
4211                 unsigned this_files;
4212
4213                 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
4214                 table->files = kcalloc(this_files, sizeof(struct file *),
4215                                         GFP_KERNEL);
4216                 if (!table->files)
4217                         break;
4218                 nr_files -= this_files;
4219         }
4220
4221         if (i == nr_tables)
4222                 return 0;
4223
4224         for (i = 0; i < nr_tables; i++) {
4225                 struct fixed_file_table *table = &ctx->file_table[i];
4226                 kfree(table->files);
4227         }
4228         return 1;
4229 }
4230
4231 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
4232                                  unsigned nr_args)
4233 {
4234         __s32 __user *fds = (__s32 __user *) arg;
4235         unsigned nr_tables;
4236         int fd, ret = 0;
4237         unsigned i;
4238
4239         if (ctx->file_table)
4240                 return -EBUSY;
4241         if (!nr_args)
4242                 return -EINVAL;
4243         if (nr_args > IORING_MAX_FIXED_FILES)
4244                 return -EMFILE;
4245
4246         nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
4247         ctx->file_table = kcalloc(nr_tables, sizeof(struct fixed_file_table),
4248                                         GFP_KERNEL);
4249         if (!ctx->file_table)
4250                 return -ENOMEM;
4251
4252         if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
4253                 kfree(ctx->file_table);
4254                 ctx->file_table = NULL;
4255                 return -ENOMEM;
4256         }
4257
4258         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
4259                 struct fixed_file_table *table;
4260                 unsigned index;
4261
4262                 ret = -EFAULT;
4263                 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
4264                         break;
4265                 /* allow sparse sets */
4266                 if (fd == -1) {
4267                         ret = 0;
4268                         continue;
4269                 }
4270
4271                 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
4272                 index = i & IORING_FILE_TABLE_MASK;
4273                 table->files[index] = fget(fd);
4274
4275                 ret = -EBADF;
4276                 if (!table->files[index])
4277                         break;
4278                 /*
4279                  * Don't allow io_uring instances to be registered. If UNIX
4280                  * isn't enabled, then this causes a reference cycle and this
4281                  * instance can never get freed. If UNIX is enabled we'll
4282                  * handle it just fine, but there's still no point in allowing
4283                  * a ring fd as it doesn't support regular read/write anyway.
4284                  */
4285                 if (table->files[index]->f_op == &io_uring_fops) {
4286                         fput(table->files[index]);
4287                         break;
4288                 }
4289                 ret = 0;
4290         }
4291
4292         if (ret) {
4293                 for (i = 0; i < ctx->nr_user_files; i++) {
4294                         struct file *file;
4295
4296                         file = io_file_from_index(ctx, i);
4297                         if (file)
4298                                 fput(file);
4299                 }
4300                 for (i = 0; i < nr_tables; i++)
4301                         kfree(ctx->file_table[i].files);
4302
4303                 kfree(ctx->file_table);
4304                 ctx->file_table = NULL;
4305                 ctx->nr_user_files = 0;
4306                 return ret;
4307         }
4308
4309         ret = io_sqe_files_scm(ctx);
4310         if (ret)
4311                 io_sqe_files_unregister(ctx);
4312
4313         return ret;
4314 }
4315
4316 static void io_sqe_file_unregister(struct io_ring_ctx *ctx, int index)
4317 {
4318 #if defined(CONFIG_UNIX)
4319         struct file *file = io_file_from_index(ctx, index);
4320         struct sock *sock = ctx->ring_sock->sk;
4321         struct sk_buff_head list, *head = &sock->sk_receive_queue;
4322         struct sk_buff *skb;
4323         int i;
4324
4325         __skb_queue_head_init(&list);
4326
4327         /*
4328          * Find the skb that holds this file in its SCM_RIGHTS. When found,
4329          * remove this entry and rearrange the file array.
4330          */
4331         skb = skb_dequeue(head);
4332         while (skb) {
4333                 struct scm_fp_list *fp;
4334
4335                 fp = UNIXCB(skb).fp;
4336                 for (i = 0; i < fp->count; i++) {
4337                         int left;
4338
4339                         if (fp->fp[i] != file)
4340                                 continue;
4341
4342                         unix_notinflight(fp->user, fp->fp[i]);
4343                         left = fp->count - 1 - i;
4344                         if (left) {
4345                                 memmove(&fp->fp[i], &fp->fp[i + 1],
4346                                                 left * sizeof(struct file *));
4347                         }
4348                         fp->count--;
4349                         if (!fp->count) {
4350                                 kfree_skb(skb);
4351                                 skb = NULL;
4352                         } else {
4353                                 __skb_queue_tail(&list, skb);
4354                         }
4355                         fput(file);
4356                         file = NULL;
4357                         break;
4358                 }
4359
4360                 if (!file)
4361                         break;
4362
4363                 __skb_queue_tail(&list, skb);
4364
4365                 skb = skb_dequeue(head);
4366         }
4367
4368         if (skb_peek(&list)) {
4369                 spin_lock_irq(&head->lock);
4370                 while ((skb = __skb_dequeue(&list)) != NULL)
4371                         __skb_queue_tail(head, skb);
4372                 spin_unlock_irq(&head->lock);
4373         }
4374 #else
4375         fput(io_file_from_index(ctx, index));
4376 #endif
4377 }
4378
4379 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
4380                                 int index)
4381 {
4382 #if defined(CONFIG_UNIX)
4383         struct sock *sock = ctx->ring_sock->sk;
4384         struct sk_buff_head *head = &sock->sk_receive_queue;
4385         struct sk_buff *skb;
4386
4387         /*
4388          * See if we can merge this file into an existing skb SCM_RIGHTS
4389          * file set. If there's no room, fall back to allocating a new skb
4390          * and filling it in.
4391          */
4392         spin_lock_irq(&head->lock);
4393         skb = skb_peek(head);
4394         if (skb) {
4395                 struct scm_fp_list *fpl = UNIXCB(skb).fp;
4396
4397                 if (fpl->count < SCM_MAX_FD) {
4398                         __skb_unlink(skb, head);
4399                         spin_unlock_irq(&head->lock);
4400                         fpl->fp[fpl->count] = get_file(file);
4401                         unix_inflight(fpl->user, fpl->fp[fpl->count]);
4402                         fpl->count++;
4403                         spin_lock_irq(&head->lock);
4404                         __skb_queue_head(head, skb);
4405                 } else {
4406                         skb = NULL;
4407                 }
4408         }
4409         spin_unlock_irq(&head->lock);
4410
4411         if (skb) {
4412                 fput(file);
4413                 return 0;
4414         }
4415
4416         return __io_sqe_files_scm(ctx, 1, index);
4417 #else
4418         return 0;
4419 #endif
4420 }
4421
4422 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
4423                                unsigned nr_args)
4424 {
4425         struct io_uring_files_update up;
4426         __s32 __user *fds;
4427         int fd, i, err;
4428         __u32 done;
4429
4430         if (!ctx->file_table)
4431                 return -ENXIO;
4432         if (!nr_args)
4433                 return -EINVAL;
4434         if (copy_from_user(&up, arg, sizeof(up)))
4435                 return -EFAULT;
4436         if (check_add_overflow(up.offset, nr_args, &done))
4437                 return -EOVERFLOW;
4438         if (done > ctx->nr_user_files)
4439                 return -EINVAL;
4440
4441         done = 0;
4442         fds = (__s32 __user *) up.fds;
4443         while (nr_args) {
4444                 struct fixed_file_table *table;
4445                 unsigned index;
4446
4447                 err = 0;
4448                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
4449                         err = -EFAULT;
4450                         break;
4451                 }
4452                 i = array_index_nospec(up.offset, ctx->nr_user_files);
4453                 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
4454                 index = i & IORING_FILE_TABLE_MASK;
4455                 if (table->files[index]) {
4456                         io_sqe_file_unregister(ctx, i);
4457                         table->files[index] = NULL;
4458                 }
4459                 if (fd != -1) {
4460                         struct file *file;
4461
4462                         file = fget(fd);
4463                         if (!file) {
4464                                 err = -EBADF;
4465                                 break;
4466                         }
4467                         /*
4468                          * Don't allow io_uring instances to be registered. If
4469                          * UNIX isn't enabled, then this causes a reference
4470                          * cycle and this instance can never get freed. If UNIX
4471                          * is enabled we'll handle it just fine, but there's
4472                          * still no point in allowing a ring fd as it doesn't
4473                          * support regular read/write anyway.
4474                          */
4475                         if (file->f_op == &io_uring_fops) {
4476                                 fput(file);
4477                                 err = -EBADF;
4478                                 break;
4479                         }
4480                         table->files[index] = file;
4481                         err = io_sqe_file_register(ctx, file, i);
4482                         if (err)
4483                                 break;
4484                 }
4485                 nr_args--;
4486                 done++;
4487                 up.offset++;
4488         }
4489
4490         return done ? done : err;
4491 }
4492
4493 static void io_put_work(struct io_wq_work *work)
4494 {
4495         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4496
4497         io_put_req(req);
4498 }
4499
4500 static void io_get_work(struct io_wq_work *work)
4501 {
4502         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4503
4504         refcount_inc(&req->refs);
4505 }
4506
4507 static int io_sq_offload_start(struct io_ring_ctx *ctx,
4508                                struct io_uring_params *p)
4509 {
4510         struct io_wq_data data;
4511         unsigned concurrency;
4512         int ret;
4513
4514         init_waitqueue_head(&ctx->sqo_wait);
4515         mmgrab(current->mm);
4516         ctx->sqo_mm = current->mm;
4517
4518         if (ctx->flags & IORING_SETUP_SQPOLL) {
4519                 ret = -EPERM;
4520                 if (!capable(CAP_SYS_ADMIN))
4521                         goto err;
4522
4523                 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
4524                 if (!ctx->sq_thread_idle)
4525                         ctx->sq_thread_idle = HZ;
4526
4527                 if (p->flags & IORING_SETUP_SQ_AFF) {
4528                         int cpu = p->sq_thread_cpu;
4529
4530                         ret = -EINVAL;
4531                         if (cpu >= nr_cpu_ids)
4532                                 goto err;
4533                         if (!cpu_online(cpu))
4534                                 goto err;
4535
4536                         ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
4537                                                         ctx, cpu,
4538                                                         "io_uring-sq");
4539                 } else {
4540                         ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
4541                                                         "io_uring-sq");
4542                 }
4543                 if (IS_ERR(ctx->sqo_thread)) {
4544                         ret = PTR_ERR(ctx->sqo_thread);
4545                         ctx->sqo_thread = NULL;
4546                         goto err;
4547                 }
4548                 wake_up_process(ctx->sqo_thread);
4549         } else if (p->flags & IORING_SETUP_SQ_AFF) {
4550                 /* Can't have SQ_AFF without SQPOLL */
4551                 ret = -EINVAL;
4552                 goto err;
4553         }
4554
4555         data.mm = ctx->sqo_mm;
4556         data.user = ctx->user;
4557         data.creds = ctx->creds;
4558         data.get_work = io_get_work;
4559         data.put_work = io_put_work;
4560
4561         /* Do QD, or 4 * CPUS, whatever is smallest */
4562         concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
4563         ctx->io_wq = io_wq_create(concurrency, &data);
4564         if (IS_ERR(ctx->io_wq)) {
4565                 ret = PTR_ERR(ctx->io_wq);
4566                 ctx->io_wq = NULL;
4567                 goto err;
4568         }
4569
4570         return 0;
4571 err:
4572         io_finish_async(ctx);
4573         mmdrop(ctx->sqo_mm);
4574         ctx->sqo_mm = NULL;
4575         return ret;
4576 }
4577
4578 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
4579 {
4580         atomic_long_sub(nr_pages, &user->locked_vm);
4581 }
4582
4583 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
4584 {
4585         unsigned long page_limit, cur_pages, new_pages;
4586
4587         /* Don't allow more pages than we can safely lock */
4588         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
4589
4590         do {
4591                 cur_pages = atomic_long_read(&user->locked_vm);
4592                 new_pages = cur_pages + nr_pages;
4593                 if (new_pages > page_limit)
4594                         return -ENOMEM;
4595         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
4596                                         new_pages) != cur_pages);
4597
4598         return 0;
4599 }
4600
4601 static void io_mem_free(void *ptr)
4602 {
4603         struct page *page;
4604
4605         if (!ptr)
4606                 return;
4607
4608         page = virt_to_head_page(ptr);
4609         if (put_page_testzero(page))
4610                 free_compound_page(page);
4611 }
4612
4613 static void *io_mem_alloc(size_t size)
4614 {
4615         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
4616                                 __GFP_NORETRY;
4617
4618         return (void *) __get_free_pages(gfp_flags, get_order(size));
4619 }
4620
4621 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
4622                                 size_t *sq_offset)
4623 {
4624         struct io_rings *rings;
4625         size_t off, sq_array_size;
4626
4627         off = struct_size(rings, cqes, cq_entries);
4628         if (off == SIZE_MAX)
4629                 return SIZE_MAX;
4630
4631 #ifdef CONFIG_SMP
4632         off = ALIGN(off, SMP_CACHE_BYTES);
4633         if (off == 0)
4634                 return SIZE_MAX;
4635 #endif
4636
4637         sq_array_size = array_size(sizeof(u32), sq_entries);
4638         if (sq_array_size == SIZE_MAX)
4639                 return SIZE_MAX;
4640
4641         if (check_add_overflow(off, sq_array_size, &off))
4642                 return SIZE_MAX;
4643
4644         if (sq_offset)
4645                 *sq_offset = off;
4646
4647         return off;
4648 }
4649
4650 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
4651 {
4652         size_t pages;
4653
4654         pages = (size_t)1 << get_order(
4655                 rings_size(sq_entries, cq_entries, NULL));
4656         pages += (size_t)1 << get_order(
4657                 array_size(sizeof(struct io_uring_sqe), sq_entries));
4658
4659         return pages;
4660 }
4661
4662 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
4663 {
4664         int i, j;
4665
4666         if (!ctx->user_bufs)
4667                 return -ENXIO;
4668
4669         for (i = 0; i < ctx->nr_user_bufs; i++) {
4670                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4671
4672                 for (j = 0; j < imu->nr_bvecs; j++)
4673                         put_user_page(imu->bvec[j].bv_page);
4674
4675                 if (ctx->account_mem)
4676                         io_unaccount_mem(ctx->user, imu->nr_bvecs);
4677                 kvfree(imu->bvec);
4678                 imu->nr_bvecs = 0;
4679         }
4680
4681         kfree(ctx->user_bufs);
4682         ctx->user_bufs = NULL;
4683         ctx->nr_user_bufs = 0;
4684         return 0;
4685 }
4686
4687 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
4688                        void __user *arg, unsigned index)
4689 {
4690         struct iovec __user *src;
4691
4692 #ifdef CONFIG_COMPAT
4693         if (ctx->compat) {
4694                 struct compat_iovec __user *ciovs;
4695                 struct compat_iovec ciov;
4696
4697                 ciovs = (struct compat_iovec __user *) arg;
4698                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
4699                         return -EFAULT;
4700
4701                 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
4702                 dst->iov_len = ciov.iov_len;
4703                 return 0;
4704         }
4705 #endif
4706         src = (struct iovec __user *) arg;
4707         if (copy_from_user(dst, &src[index], sizeof(*dst)))
4708                 return -EFAULT;
4709         return 0;
4710 }
4711
4712 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
4713                                   unsigned nr_args)
4714 {
4715         struct vm_area_struct **vmas = NULL;
4716         struct page **pages = NULL;
4717         int i, j, got_pages = 0;
4718         int ret = -EINVAL;
4719
4720         if (ctx->user_bufs)
4721                 return -EBUSY;
4722         if (!nr_args || nr_args > UIO_MAXIOV)
4723                 return -EINVAL;
4724
4725         ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
4726                                         GFP_KERNEL);
4727         if (!ctx->user_bufs)
4728                 return -ENOMEM;
4729
4730         for (i = 0; i < nr_args; i++) {
4731                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4732                 unsigned long off, start, end, ubuf;
4733                 int pret, nr_pages;
4734                 struct iovec iov;
4735                 size_t size;
4736
4737                 ret = io_copy_iov(ctx, &iov, arg, i);
4738                 if (ret)
4739                         goto err;
4740
4741                 /*
4742                  * Don't impose further limits on the size and buffer
4743                  * constraints here, we'll -EINVAL later when IO is
4744                  * submitted if they are wrong.
4745                  */
4746                 ret = -EFAULT;
4747                 if (!iov.iov_base || !iov.iov_len)
4748                         goto err;
4749
4750                 /* arbitrary limit, but we need something */
4751                 if (iov.iov_len > SZ_1G)
4752                         goto err;
4753
4754                 ubuf = (unsigned long) iov.iov_base;
4755                 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
4756                 start = ubuf >> PAGE_SHIFT;
4757                 nr_pages = end - start;
4758
4759                 if (ctx->account_mem) {
4760                         ret = io_account_mem(ctx->user, nr_pages);
4761                         if (ret)
4762                                 goto err;
4763                 }
4764
4765                 ret = 0;
4766                 if (!pages || nr_pages > got_pages) {
4767                         kfree(vmas);
4768                         kfree(pages);
4769                         pages = kvmalloc_array(nr_pages, sizeof(struct page *),
4770                                                 GFP_KERNEL);
4771                         vmas = kvmalloc_array(nr_pages,
4772                                         sizeof(struct vm_area_struct *),
4773                                         GFP_KERNEL);
4774                         if (!pages || !vmas) {
4775                                 ret = -ENOMEM;
4776                                 if (ctx->account_mem)
4777                                         io_unaccount_mem(ctx->user, nr_pages);
4778                                 goto err;
4779                         }
4780                         got_pages = nr_pages;
4781                 }
4782
4783                 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
4784                                                 GFP_KERNEL);
4785                 ret = -ENOMEM;
4786                 if (!imu->bvec) {
4787                         if (ctx->account_mem)
4788                                 io_unaccount_mem(ctx->user, nr_pages);
4789                         goto err;
4790                 }
4791
4792                 ret = 0;
4793                 down_read(&current->mm->mmap_sem);
4794                 pret = get_user_pages(ubuf, nr_pages,
4795                                       FOLL_WRITE | FOLL_LONGTERM,
4796                                       pages, vmas);
4797                 if (pret == nr_pages) {
4798                         /* don't support file backed memory */
4799                         for (j = 0; j < nr_pages; j++) {
4800                                 struct vm_area_struct *vma = vmas[j];
4801
4802                                 if (vma->vm_file &&
4803                                     !is_file_hugepages(vma->vm_file)) {
4804                                         ret = -EOPNOTSUPP;
4805                                         break;
4806                                 }
4807                         }
4808                 } else {
4809                         ret = pret < 0 ? pret : -EFAULT;
4810                 }
4811                 up_read(&current->mm->mmap_sem);
4812                 if (ret) {
4813                         /*
4814                          * if we did partial map, or found file backed vmas,
4815                          * release any pages we did get
4816                          */
4817                         if (pret > 0)
4818                                 put_user_pages(pages, pret);
4819                         if (ctx->account_mem)
4820                                 io_unaccount_mem(ctx->user, nr_pages);
4821                         kvfree(imu->bvec);
4822                         goto err;
4823                 }
4824
4825                 off = ubuf & ~PAGE_MASK;
4826                 size = iov.iov_len;
4827                 for (j = 0; j < nr_pages; j++) {
4828                         size_t vec_len;
4829
4830                         vec_len = min_t(size_t, size, PAGE_SIZE - off);
4831                         imu->bvec[j].bv_page = pages[j];
4832                         imu->bvec[j].bv_len = vec_len;
4833                         imu->bvec[j].bv_offset = off;
4834                         off = 0;
4835                         size -= vec_len;
4836                 }
4837                 /* store original address for later verification */
4838                 imu->ubuf = ubuf;
4839                 imu->len = iov.iov_len;
4840                 imu->nr_bvecs = nr_pages;
4841
4842                 ctx->nr_user_bufs++;
4843         }
4844         kvfree(pages);
4845         kvfree(vmas);
4846         return 0;
4847 err:
4848         kvfree(pages);
4849         kvfree(vmas);
4850         io_sqe_buffer_unregister(ctx);
4851         return ret;
4852 }
4853
4854 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
4855 {
4856         __s32 __user *fds = arg;
4857         int fd;
4858
4859         if (ctx->cq_ev_fd)
4860                 return -EBUSY;
4861
4862         if (copy_from_user(&fd, fds, sizeof(*fds)))
4863                 return -EFAULT;
4864
4865         ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
4866         if (IS_ERR(ctx->cq_ev_fd)) {
4867                 int ret = PTR_ERR(ctx->cq_ev_fd);
4868                 ctx->cq_ev_fd = NULL;
4869                 return ret;
4870         }
4871
4872         return 0;
4873 }
4874
4875 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
4876 {
4877         if (ctx->cq_ev_fd) {
4878                 eventfd_ctx_put(ctx->cq_ev_fd);
4879                 ctx->cq_ev_fd = NULL;
4880                 return 0;
4881         }
4882
4883         return -ENXIO;
4884 }
4885
4886 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
4887 {
4888         io_finish_async(ctx);
4889         if (ctx->sqo_mm)
4890                 mmdrop(ctx->sqo_mm);
4891
4892         io_iopoll_reap_events(ctx);
4893         io_sqe_buffer_unregister(ctx);
4894         io_sqe_files_unregister(ctx);
4895         io_eventfd_unregister(ctx);
4896
4897 #if defined(CONFIG_UNIX)
4898         if (ctx->ring_sock) {
4899                 ctx->ring_sock->file = NULL; /* so that iput() is called */
4900                 sock_release(ctx->ring_sock);
4901         }
4902 #endif
4903
4904         io_mem_free(ctx->rings);
4905         io_mem_free(ctx->sq_sqes);
4906
4907         percpu_ref_exit(&ctx->refs);
4908         if (ctx->account_mem)
4909                 io_unaccount_mem(ctx->user,
4910                                 ring_pages(ctx->sq_entries, ctx->cq_entries));
4911         free_uid(ctx->user);
4912         put_cred(ctx->creds);
4913         kfree(ctx->completions);
4914         kfree(ctx->cancel_hash);
4915         kmem_cache_free(req_cachep, ctx->fallback_req);
4916         kfree(ctx);
4917 }
4918
4919 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
4920 {
4921         struct io_ring_ctx *ctx = file->private_data;
4922         __poll_t mask = 0;
4923
4924         poll_wait(file, &ctx->cq_wait, wait);
4925         /*
4926          * synchronizes with barrier from wq_has_sleeper call in
4927          * io_commit_cqring
4928          */
4929         smp_rmb();
4930         if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
4931             ctx->rings->sq_ring_entries)
4932                 mask |= EPOLLOUT | EPOLLWRNORM;
4933         if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
4934                 mask |= EPOLLIN | EPOLLRDNORM;
4935
4936         return mask;
4937 }
4938
4939 static int io_uring_fasync(int fd, struct file *file, int on)
4940 {
4941         struct io_ring_ctx *ctx = file->private_data;
4942
4943         return fasync_helper(fd, file, on, &ctx->cq_fasync);
4944 }
4945
4946 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
4947 {
4948         mutex_lock(&ctx->uring_lock);
4949         percpu_ref_kill(&ctx->refs);
4950         mutex_unlock(&ctx->uring_lock);
4951
4952         io_kill_timeouts(ctx);
4953         io_poll_remove_all(ctx);
4954
4955         if (ctx->io_wq)
4956                 io_wq_cancel_all(ctx->io_wq);
4957
4958         io_iopoll_reap_events(ctx);
4959         /* if we failed setting up the ctx, we might not have any rings */
4960         if (ctx->rings)
4961                 io_cqring_overflow_flush(ctx, true);
4962         wait_for_completion(&ctx->completions[0]);
4963         io_ring_ctx_free(ctx);
4964 }
4965
4966 static int io_uring_release(struct inode *inode, struct file *file)
4967 {
4968         struct io_ring_ctx *ctx = file->private_data;
4969
4970         file->private_data = NULL;
4971         io_ring_ctx_wait_and_kill(ctx);
4972         return 0;
4973 }
4974
4975 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
4976                                   struct files_struct *files)
4977 {
4978         struct io_kiocb *req;
4979         DEFINE_WAIT(wait);
4980
4981         while (!list_empty_careful(&ctx->inflight_list)) {
4982                 struct io_kiocb *cancel_req = NULL;
4983
4984                 spin_lock_irq(&ctx->inflight_lock);
4985                 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
4986                         if (req->work.files != files)
4987                                 continue;
4988                         /* req is being completed, ignore */
4989                         if (!refcount_inc_not_zero(&req->refs))
4990                                 continue;
4991                         cancel_req = req;
4992                         break;
4993                 }
4994                 if (cancel_req)
4995                         prepare_to_wait(&ctx->inflight_wait, &wait,
4996                                                 TASK_UNINTERRUPTIBLE);
4997                 spin_unlock_irq(&ctx->inflight_lock);
4998
4999                 /* We need to keep going until we don't find a matching req */
5000                 if (!cancel_req)
5001                         break;
5002
5003                 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
5004                 io_put_req(cancel_req);
5005                 schedule();
5006         }
5007         finish_wait(&ctx->inflight_wait, &wait);
5008 }
5009
5010 static int io_uring_flush(struct file *file, void *data)
5011 {
5012         struct io_ring_ctx *ctx = file->private_data;
5013
5014         io_uring_cancel_files(ctx, data);
5015         if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
5016                 io_cqring_overflow_flush(ctx, true);
5017                 io_wq_cancel_all(ctx->io_wq);
5018         }
5019         return 0;
5020 }
5021
5022 static void *io_uring_validate_mmap_request(struct file *file,
5023                                             loff_t pgoff, size_t sz)
5024 {
5025         struct io_ring_ctx *ctx = file->private_data;
5026         loff_t offset = pgoff << PAGE_SHIFT;
5027         struct page *page;
5028         void *ptr;
5029
5030         switch (offset) {
5031         case IORING_OFF_SQ_RING:
5032         case IORING_OFF_CQ_RING:
5033                 ptr = ctx->rings;
5034                 break;
5035         case IORING_OFF_SQES:
5036                 ptr = ctx->sq_sqes;
5037                 break;
5038         default:
5039                 return ERR_PTR(-EINVAL);
5040         }
5041
5042         page = virt_to_head_page(ptr);
5043         if (sz > page_size(page))
5044                 return ERR_PTR(-EINVAL);
5045
5046         return ptr;
5047 }
5048
5049 #ifdef CONFIG_MMU
5050
5051 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5052 {
5053         size_t sz = vma->vm_end - vma->vm_start;
5054         unsigned long pfn;
5055         void *ptr;
5056
5057         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
5058         if (IS_ERR(ptr))
5059                 return PTR_ERR(ptr);
5060
5061         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
5062         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
5063 }
5064
5065 #else /* !CONFIG_MMU */
5066
5067 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5068 {
5069         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
5070 }
5071
5072 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
5073 {
5074         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
5075 }
5076
5077 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
5078         unsigned long addr, unsigned long len,
5079         unsigned long pgoff, unsigned long flags)
5080 {
5081         void *ptr;
5082
5083         ptr = io_uring_validate_mmap_request(file, pgoff, len);
5084         if (IS_ERR(ptr))
5085                 return PTR_ERR(ptr);
5086
5087         return (unsigned long) ptr;
5088 }
5089
5090 #endif /* !CONFIG_MMU */
5091
5092 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
5093                 u32, min_complete, u32, flags, const sigset_t __user *, sig,
5094                 size_t, sigsz)
5095 {
5096         struct io_ring_ctx *ctx;
5097         long ret = -EBADF;
5098         int submitted = 0;
5099         struct fd f;
5100
5101         if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
5102                 return -EINVAL;
5103
5104         f = fdget(fd);
5105         if (!f.file)
5106                 return -EBADF;
5107
5108         ret = -EOPNOTSUPP;
5109         if (f.file->f_op != &io_uring_fops)
5110                 goto out_fput;
5111
5112         ret = -ENXIO;
5113         ctx = f.file->private_data;
5114         if (!percpu_ref_tryget(&ctx->refs))
5115                 goto out_fput;
5116
5117         /*
5118          * For SQ polling, the thread will do all submissions and completions.
5119          * Just return the requested submit count, and wake the thread if
5120          * we were asked to.
5121          */
5122         ret = 0;
5123         if (ctx->flags & IORING_SETUP_SQPOLL) {
5124                 if (!list_empty_careful(&ctx->cq_overflow_list))
5125                         io_cqring_overflow_flush(ctx, false);
5126                 if (flags & IORING_ENTER_SQ_WAKEUP)
5127                         wake_up(&ctx->sqo_wait);
5128                 submitted = to_submit;
5129         } else if (to_submit) {
5130                 struct mm_struct *cur_mm;
5131
5132                 to_submit = min(to_submit, ctx->sq_entries);
5133                 mutex_lock(&ctx->uring_lock);
5134                 /* already have mm, so io_submit_sqes() won't try to grab it */
5135                 cur_mm = ctx->sqo_mm;
5136                 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
5137                                            &cur_mm, false);
5138                 mutex_unlock(&ctx->uring_lock);
5139         }
5140         if (flags & IORING_ENTER_GETEVENTS) {
5141                 unsigned nr_events = 0;
5142
5143                 min_complete = min(min_complete, ctx->cq_entries);
5144
5145                 if (ctx->flags & IORING_SETUP_IOPOLL) {
5146                         ret = io_iopoll_check(ctx, &nr_events, min_complete);
5147                 } else {
5148                         ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
5149                 }
5150         }
5151
5152         percpu_ref_put(&ctx->refs);
5153 out_fput:
5154         fdput(f);
5155         return submitted ? submitted : ret;
5156 }
5157
5158 static const struct file_operations io_uring_fops = {
5159         .release        = io_uring_release,
5160         .flush          = io_uring_flush,
5161         .mmap           = io_uring_mmap,
5162 #ifndef CONFIG_MMU
5163         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
5164         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
5165 #endif
5166         .poll           = io_uring_poll,
5167         .fasync         = io_uring_fasync,
5168 };
5169
5170 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
5171                                   struct io_uring_params *p)
5172 {
5173         struct io_rings *rings;
5174         size_t size, sq_array_offset;
5175
5176         size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
5177         if (size == SIZE_MAX)
5178                 return -EOVERFLOW;
5179
5180         rings = io_mem_alloc(size);
5181         if (!rings)
5182                 return -ENOMEM;
5183
5184         ctx->rings = rings;
5185         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
5186         rings->sq_ring_mask = p->sq_entries - 1;
5187         rings->cq_ring_mask = p->cq_entries - 1;
5188         rings->sq_ring_entries = p->sq_entries;
5189         rings->cq_ring_entries = p->cq_entries;
5190         ctx->sq_mask = rings->sq_ring_mask;
5191         ctx->cq_mask = rings->cq_ring_mask;
5192         ctx->sq_entries = rings->sq_ring_entries;
5193         ctx->cq_entries = rings->cq_ring_entries;
5194
5195         size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
5196         if (size == SIZE_MAX) {
5197                 io_mem_free(ctx->rings);
5198                 ctx->rings = NULL;
5199                 return -EOVERFLOW;
5200         }
5201
5202         ctx->sq_sqes = io_mem_alloc(size);
5203         if (!ctx->sq_sqes) {
5204                 io_mem_free(ctx->rings);
5205                 ctx->rings = NULL;
5206                 return -ENOMEM;
5207         }
5208
5209         return 0;
5210 }
5211
5212 /*
5213  * Allocate an anonymous fd, this is what constitutes the application
5214  * visible backing of an io_uring instance. The application mmaps this
5215  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
5216  * we have to tie this fd to a socket for file garbage collection purposes.
5217  */
5218 static int io_uring_get_fd(struct io_ring_ctx *ctx)
5219 {
5220         struct file *file;
5221         int ret;
5222
5223 #if defined(CONFIG_UNIX)
5224         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
5225                                 &ctx->ring_sock);
5226         if (ret)
5227                 return ret;
5228 #endif
5229
5230         ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
5231         if (ret < 0)
5232                 goto err;
5233
5234         file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
5235                                         O_RDWR | O_CLOEXEC);
5236         if (IS_ERR(file)) {
5237                 put_unused_fd(ret);
5238                 ret = PTR_ERR(file);
5239                 goto err;
5240         }
5241
5242 #if defined(CONFIG_UNIX)
5243         ctx->ring_sock->file = file;
5244         ctx->ring_sock->sk->sk_user_data = ctx;
5245 #endif
5246         fd_install(ret, file);
5247         return ret;
5248 err:
5249 #if defined(CONFIG_UNIX)
5250         sock_release(ctx->ring_sock);
5251         ctx->ring_sock = NULL;
5252 #endif
5253         return ret;
5254 }
5255
5256 static int io_uring_create(unsigned entries, struct io_uring_params *p)
5257 {
5258         struct user_struct *user = NULL;
5259         struct io_ring_ctx *ctx;
5260         bool account_mem;
5261         int ret;
5262
5263         if (!entries || entries > IORING_MAX_ENTRIES)
5264                 return -EINVAL;
5265
5266         /*
5267          * Use twice as many entries for the CQ ring. It's possible for the
5268          * application to drive a higher depth than the size of the SQ ring,
5269          * since the sqes are only used at submission time. This allows for
5270          * some flexibility in overcommitting a bit. If the application has
5271          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
5272          * of CQ ring entries manually.
5273          */
5274         p->sq_entries = roundup_pow_of_two(entries);
5275         if (p->flags & IORING_SETUP_CQSIZE) {
5276                 /*
5277                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
5278                  * to a power-of-two, if it isn't already. We do NOT impose
5279                  * any cq vs sq ring sizing.
5280                  */
5281                 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
5282                         return -EINVAL;
5283                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
5284         } else {
5285                 p->cq_entries = 2 * p->sq_entries;
5286         }
5287
5288         user = get_uid(current_user());
5289         account_mem = !capable(CAP_IPC_LOCK);
5290
5291         if (account_mem) {
5292                 ret = io_account_mem(user,
5293                                 ring_pages(p->sq_entries, p->cq_entries));
5294                 if (ret) {
5295                         free_uid(user);
5296                         return ret;
5297                 }
5298         }
5299
5300         ctx = io_ring_ctx_alloc(p);
5301         if (!ctx) {
5302                 if (account_mem)
5303                         io_unaccount_mem(user, ring_pages(p->sq_entries,
5304                                                                 p->cq_entries));
5305                 free_uid(user);
5306                 return -ENOMEM;
5307         }
5308         ctx->compat = in_compat_syscall();
5309         ctx->account_mem = account_mem;
5310         ctx->user = user;
5311         ctx->creds = get_current_cred();
5312
5313         ret = io_allocate_scq_urings(ctx, p);
5314         if (ret)
5315                 goto err;
5316
5317         ret = io_sq_offload_start(ctx, p);
5318         if (ret)
5319                 goto err;
5320
5321         memset(&p->sq_off, 0, sizeof(p->sq_off));
5322         p->sq_off.head = offsetof(struct io_rings, sq.head);
5323         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
5324         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
5325         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
5326         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
5327         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
5328         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
5329
5330         memset(&p->cq_off, 0, sizeof(p->cq_off));
5331         p->cq_off.head = offsetof(struct io_rings, cq.head);
5332         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
5333         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
5334         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
5335         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
5336         p->cq_off.cqes = offsetof(struct io_rings, cqes);
5337
5338         /*
5339          * Install ring fd as the very last thing, so we don't risk someone
5340          * having closed it before we finish setup
5341          */
5342         ret = io_uring_get_fd(ctx);
5343         if (ret < 0)
5344                 goto err;
5345
5346         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
5347                         IORING_FEAT_SUBMIT_STABLE;
5348         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
5349         return ret;
5350 err:
5351         io_ring_ctx_wait_and_kill(ctx);
5352         return ret;
5353 }
5354
5355 /*
5356  * Sets up an aio uring context, and returns the fd. Applications asks for a
5357  * ring size, we return the actual sq/cq ring sizes (among other things) in the
5358  * params structure passed in.
5359  */
5360 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
5361 {
5362         struct io_uring_params p;
5363         long ret;
5364         int i;
5365
5366         if (copy_from_user(&p, params, sizeof(p)))
5367                 return -EFAULT;
5368         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
5369                 if (p.resv[i])
5370                         return -EINVAL;
5371         }
5372
5373         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
5374                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
5375                 return -EINVAL;
5376
5377         ret = io_uring_create(entries, &p);
5378         if (ret < 0)
5379                 return ret;
5380
5381         if (copy_to_user(params, &p, sizeof(p)))
5382                 return -EFAULT;
5383
5384         return ret;
5385 }
5386
5387 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
5388                 struct io_uring_params __user *, params)
5389 {
5390         return io_uring_setup(entries, params);
5391 }
5392
5393 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
5394                                void __user *arg, unsigned nr_args)
5395         __releases(ctx->uring_lock)
5396         __acquires(ctx->uring_lock)
5397 {
5398         int ret;
5399
5400         /*
5401          * We're inside the ring mutex, if the ref is already dying, then
5402          * someone else killed the ctx or is already going through
5403          * io_uring_register().
5404          */
5405         if (percpu_ref_is_dying(&ctx->refs))
5406                 return -ENXIO;
5407
5408         percpu_ref_kill(&ctx->refs);
5409
5410         /*
5411          * Drop uring mutex before waiting for references to exit. If another
5412          * thread is currently inside io_uring_enter() it might need to grab
5413          * the uring_lock to make progress. If we hold it here across the drain
5414          * wait, then we can deadlock. It's safe to drop the mutex here, since
5415          * no new references will come in after we've killed the percpu ref.
5416          */
5417         mutex_unlock(&ctx->uring_lock);
5418         wait_for_completion(&ctx->completions[0]);
5419         mutex_lock(&ctx->uring_lock);
5420
5421         switch (opcode) {
5422         case IORING_REGISTER_BUFFERS:
5423                 ret = io_sqe_buffer_register(ctx, arg, nr_args);
5424                 break;
5425         case IORING_UNREGISTER_BUFFERS:
5426                 ret = -EINVAL;
5427                 if (arg || nr_args)
5428                         break;
5429                 ret = io_sqe_buffer_unregister(ctx);
5430                 break;
5431         case IORING_REGISTER_FILES:
5432                 ret = io_sqe_files_register(ctx, arg, nr_args);
5433                 break;
5434         case IORING_UNREGISTER_FILES:
5435                 ret = -EINVAL;
5436                 if (arg || nr_args)
5437                         break;
5438                 ret = io_sqe_files_unregister(ctx);
5439                 break;
5440         case IORING_REGISTER_FILES_UPDATE:
5441                 ret = io_sqe_files_update(ctx, arg, nr_args);
5442                 break;
5443         case IORING_REGISTER_EVENTFD:
5444                 ret = -EINVAL;
5445                 if (nr_args != 1)
5446                         break;
5447                 ret = io_eventfd_register(ctx, arg);
5448                 break;
5449         case IORING_UNREGISTER_EVENTFD:
5450                 ret = -EINVAL;
5451                 if (arg || nr_args)
5452                         break;
5453                 ret = io_eventfd_unregister(ctx);
5454                 break;
5455         default:
5456                 ret = -EINVAL;
5457                 break;
5458         }
5459
5460         /* bring the ctx back to life */
5461         reinit_completion(&ctx->completions[0]);
5462         percpu_ref_reinit(&ctx->refs);
5463         return ret;
5464 }
5465
5466 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
5467                 void __user *, arg, unsigned int, nr_args)
5468 {
5469         struct io_ring_ctx *ctx;
5470         long ret = -EBADF;
5471         struct fd f;
5472
5473         f = fdget(fd);
5474         if (!f.file)
5475                 return -EBADF;
5476
5477         ret = -EOPNOTSUPP;
5478         if (f.file->f_op != &io_uring_fops)
5479                 goto out_fput;
5480
5481         ctx = f.file->private_data;
5482
5483         mutex_lock(&ctx->uring_lock);
5484         ret = __io_uring_register(ctx, opcode, arg, nr_args);
5485         mutex_unlock(&ctx->uring_lock);
5486         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
5487                                                         ctx->cq_ev_fd != NULL, ret);
5488 out_fput:
5489         fdput(f);
5490         return ret;
5491 }
5492
5493 static int __init io_uring_init(void)
5494 {
5495         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
5496         return 0;
5497 };
5498 __initcall(io_uring_init);