OSDN Git Service

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