tools headers UAPI: Sync drm/i915_drm.h with the kernel sources
[linux-2.6-microblaze.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 <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
51
52 #include <linux/sched/signal.h>
53 #include <linux/fs.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
56 #include <linux/mm.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
64 #include <net/sock.h>
65 #include <net/af_unix.h>
66 #include <net/scm.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/fs_struct.h>
79 #include <linux/splice.h>
80 #include <linux/task_work.h>
81 #include <linux/pagemap.h>
82 #include <linux/io_uring.h>
83 #include <linux/blk-cgroup.h>
84 #include <linux/audit.h>
85
86 #define CREATE_TRACE_POINTS
87 #include <trace/events/io_uring.h>
88
89 #include <uapi/linux/io_uring.h>
90
91 #include "internal.h"
92 #include "io-wq.h"
93
94 #define IORING_MAX_ENTRIES      32768
95 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
96
97 /*
98  * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
99  */
100 #define IORING_FILE_TABLE_SHIFT 9
101 #define IORING_MAX_FILES_TABLE  (1U << IORING_FILE_TABLE_SHIFT)
102 #define IORING_FILE_TABLE_MASK  (IORING_MAX_FILES_TABLE - 1)
103 #define IORING_MAX_FIXED_FILES  (64 * IORING_MAX_FILES_TABLE)
104 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
105                                  IORING_REGISTER_LAST + IORING_OP_LAST)
106
107 struct io_uring {
108         u32 head ____cacheline_aligned_in_smp;
109         u32 tail ____cacheline_aligned_in_smp;
110 };
111
112 /*
113  * This data is shared with the application through the mmap at offsets
114  * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
115  *
116  * The offsets to the member fields are published through struct
117  * io_sqring_offsets when calling io_uring_setup.
118  */
119 struct io_rings {
120         /*
121          * Head and tail offsets into the ring; the offsets need to be
122          * masked to get valid indices.
123          *
124          * The kernel controls head of the sq ring and the tail of the cq ring,
125          * and the application controls tail of the sq ring and the head of the
126          * cq ring.
127          */
128         struct io_uring         sq, cq;
129         /*
130          * Bitmasks to apply to head and tail offsets (constant, equals
131          * ring_entries - 1)
132          */
133         u32                     sq_ring_mask, cq_ring_mask;
134         /* Ring sizes (constant, power of 2) */
135         u32                     sq_ring_entries, cq_ring_entries;
136         /*
137          * Number of invalid entries dropped by the kernel due to
138          * invalid index stored in array
139          *
140          * Written by the kernel, shouldn't be modified by the
141          * application (i.e. get number of "new events" by comparing to
142          * cached value).
143          *
144          * After a new SQ head value was read by the application this
145          * counter includes all submissions that were dropped reaching
146          * the new SQ head (and possibly more).
147          */
148         u32                     sq_dropped;
149         /*
150          * Runtime SQ flags
151          *
152          * Written by the kernel, shouldn't be modified by the
153          * application.
154          *
155          * The application needs a full memory barrier before checking
156          * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
157          */
158         u32                     sq_flags;
159         /*
160          * Runtime CQ flags
161          *
162          * Written by the application, shouldn't be modified by the
163          * kernel.
164          */
165         u32                     cq_flags;
166         /*
167          * Number of completion events lost because the queue was full;
168          * this should be avoided by the application by making sure
169          * there are not more requests pending than there is space in
170          * the completion queue.
171          *
172          * Written by the kernel, shouldn't be modified by the
173          * application (i.e. get number of "new events" by comparing to
174          * cached value).
175          *
176          * As completion events come in out of order this counter is not
177          * ordered with any other data.
178          */
179         u32                     cq_overflow;
180         /*
181          * Ring buffer of completion events.
182          *
183          * The kernel writes completion events fresh every time they are
184          * produced, so the application is allowed to modify pending
185          * entries.
186          */
187         struct io_uring_cqe     cqes[] ____cacheline_aligned_in_smp;
188 };
189
190 enum io_uring_cmd_flags {
191         IO_URING_F_NONBLOCK             = 1,
192         IO_URING_F_COMPLETE_DEFER       = 2,
193 };
194
195 struct io_mapped_ubuf {
196         u64             ubuf;
197         size_t          len;
198         struct          bio_vec *bvec;
199         unsigned int    nr_bvecs;
200         unsigned long   acct_pages;
201 };
202
203 struct io_ring_ctx;
204
205 struct io_rsrc_put {
206         struct list_head list;
207         union {
208                 void *rsrc;
209                 struct file *file;
210         };
211 };
212
213 struct fixed_rsrc_table {
214         struct file             **files;
215 };
216
217 struct fixed_rsrc_ref_node {
218         struct percpu_ref               refs;
219         struct list_head                node;
220         struct list_head                rsrc_list;
221         struct fixed_rsrc_data          *rsrc_data;
222         void                            (*rsrc_put)(struct io_ring_ctx *ctx,
223                                                     struct io_rsrc_put *prsrc);
224         struct llist_node               llist;
225         bool                            done;
226 };
227
228 struct fixed_rsrc_data {
229         struct fixed_rsrc_table         *table;
230         struct io_ring_ctx              *ctx;
231
232         struct fixed_rsrc_ref_node      *node;
233         struct percpu_ref               refs;
234         struct completion               done;
235 };
236
237 struct io_buffer {
238         struct list_head list;
239         __u64 addr;
240         __s32 len;
241         __u16 bid;
242 };
243
244 struct io_restriction {
245         DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
246         DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
247         u8 sqe_flags_allowed;
248         u8 sqe_flags_required;
249         bool registered;
250 };
251
252 struct io_sq_data {
253         refcount_t              refs;
254         struct mutex            lock;
255
256         /* ctx's that are using this sqd */
257         struct list_head        ctx_list;
258         struct list_head        ctx_new_list;
259         struct mutex            ctx_lock;
260
261         struct task_struct      *thread;
262         struct wait_queue_head  wait;
263
264         unsigned                sq_thread_idle;
265 };
266
267 #define IO_IOPOLL_BATCH                 8
268 #define IO_COMPL_BATCH                  32
269 #define IO_REQ_CACHE_SIZE               32
270 #define IO_REQ_ALLOC_BATCH              8
271
272 struct io_comp_state {
273         struct io_kiocb         *reqs[IO_COMPL_BATCH];
274         unsigned int            nr;
275         unsigned int            locked_free_nr;
276         /* inline/task_work completion list, under ->uring_lock */
277         struct list_head        free_list;
278         /* IRQ completion list, under ->completion_lock */
279         struct list_head        locked_free_list;
280 };
281
282 struct io_submit_state {
283         struct blk_plug         plug;
284
285         /*
286          * io_kiocb alloc cache
287          */
288         void                    *reqs[IO_REQ_CACHE_SIZE];
289         unsigned int            free_reqs;
290
291         bool                    plug_started;
292
293         /*
294          * Batch completion logic
295          */
296         struct io_comp_state    comp;
297
298         /*
299          * File reference cache
300          */
301         struct file             *file;
302         unsigned int            fd;
303         unsigned int            file_refs;
304         unsigned int            ios_left;
305 };
306
307 struct io_ring_ctx {
308         struct {
309                 struct percpu_ref       refs;
310         } ____cacheline_aligned_in_smp;
311
312         struct {
313                 unsigned int            flags;
314                 unsigned int            compat: 1;
315                 unsigned int            limit_mem: 1;
316                 unsigned int            cq_overflow_flushed: 1;
317                 unsigned int            drain_next: 1;
318                 unsigned int            eventfd_async: 1;
319                 unsigned int            restricted: 1;
320                 unsigned int            sqo_dead: 1;
321
322                 /*
323                  * Ring buffer of indices into array of io_uring_sqe, which is
324                  * mmapped by the application using the IORING_OFF_SQES offset.
325                  *
326                  * This indirection could e.g. be used to assign fixed
327                  * io_uring_sqe entries to operations and only submit them to
328                  * the queue when needed.
329                  *
330                  * The kernel modifies neither the indices array nor the entries
331                  * array.
332                  */
333                 u32                     *sq_array;
334                 unsigned                cached_sq_head;
335                 unsigned                sq_entries;
336                 unsigned                sq_mask;
337                 unsigned                sq_thread_idle;
338                 unsigned                cached_sq_dropped;
339                 unsigned                cached_cq_overflow;
340                 unsigned long           sq_check_overflow;
341
342                 struct list_head        defer_list;
343                 struct list_head        timeout_list;
344                 struct list_head        cq_overflow_list;
345
346                 struct io_uring_sqe     *sq_sqes;
347         } ____cacheline_aligned_in_smp;
348
349         struct {
350                 struct mutex            uring_lock;
351                 wait_queue_head_t       wait;
352         } ____cacheline_aligned_in_smp;
353
354         struct io_submit_state          submit_state;
355
356         struct io_rings *rings;
357
358         /* IO offload */
359         struct io_wq            *io_wq;
360
361         /*
362          * For SQPOLL usage - we hold a reference to the parent task, so we
363          * have access to the ->files
364          */
365         struct task_struct      *sqo_task;
366
367         /* Only used for accounting purposes */
368         struct mm_struct        *mm_account;
369
370 #ifdef CONFIG_BLK_CGROUP
371         struct cgroup_subsys_state      *sqo_blkcg_css;
372 #endif
373
374         struct io_sq_data       *sq_data;       /* if using sq thread polling */
375
376         struct wait_queue_head  sqo_sq_wait;
377         struct list_head        sqd_list;
378
379         /*
380          * If used, fixed file set. Writers must ensure that ->refs is dead,
381          * readers must ensure that ->refs is alive as long as the file* is
382          * used. Only updated through io_uring_register(2).
383          */
384         struct fixed_rsrc_data  *file_data;
385         unsigned                nr_user_files;
386
387         /* if used, fixed mapped user buffers */
388         unsigned                nr_user_bufs;
389         struct io_mapped_ubuf   *user_bufs;
390
391         struct user_struct      *user;
392
393         const struct cred       *creds;
394
395 #ifdef CONFIG_AUDIT
396         kuid_t                  loginuid;
397         unsigned int            sessionid;
398 #endif
399
400         struct completion       ref_comp;
401         struct completion       sq_thread_comp;
402
403 #if defined(CONFIG_UNIX)
404         struct socket           *ring_sock;
405 #endif
406
407         struct idr              io_buffer_idr;
408
409         struct idr              personality_idr;
410
411         struct {
412                 unsigned                cached_cq_tail;
413                 unsigned                cq_entries;
414                 unsigned                cq_mask;
415                 atomic_t                cq_timeouts;
416                 unsigned                cq_last_tm_flush;
417                 unsigned long           cq_check_overflow;
418                 struct wait_queue_head  cq_wait;
419                 struct fasync_struct    *cq_fasync;
420                 struct eventfd_ctx      *cq_ev_fd;
421         } ____cacheline_aligned_in_smp;
422
423         struct {
424                 spinlock_t              completion_lock;
425
426                 /*
427                  * ->iopoll_list is protected by the ctx->uring_lock for
428                  * io_uring instances that don't use IORING_SETUP_SQPOLL.
429                  * For SQPOLL, only the single threaded io_sq_thread() will
430                  * manipulate the list, hence no extra locking is needed there.
431                  */
432                 struct list_head        iopoll_list;
433                 struct hlist_head       *cancel_hash;
434                 unsigned                cancel_hash_bits;
435                 bool                    poll_multi_file;
436
437                 spinlock_t              inflight_lock;
438                 struct list_head        inflight_list;
439         } ____cacheline_aligned_in_smp;
440
441         struct delayed_work             rsrc_put_work;
442         struct llist_head               rsrc_put_llist;
443         struct list_head                rsrc_ref_list;
444         spinlock_t                      rsrc_ref_lock;
445
446         struct io_restriction           restrictions;
447
448         /* Keep this last, we don't need it for the fast path */
449         struct work_struct              exit_work;
450 };
451
452 /*
453  * First field must be the file pointer in all the
454  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
455  */
456 struct io_poll_iocb {
457         struct file                     *file;
458         struct wait_queue_head          *head;
459         __poll_t                        events;
460         bool                            done;
461         bool                            canceled;
462         struct wait_queue_entry         wait;
463 };
464
465 struct io_poll_remove {
466         struct file                     *file;
467         u64                             addr;
468 };
469
470 struct io_close {
471         struct file                     *file;
472         int                             fd;
473 };
474
475 struct io_timeout_data {
476         struct io_kiocb                 *req;
477         struct hrtimer                  timer;
478         struct timespec64               ts;
479         enum hrtimer_mode               mode;
480 };
481
482 struct io_accept {
483         struct file                     *file;
484         struct sockaddr __user          *addr;
485         int __user                      *addr_len;
486         int                             flags;
487         unsigned long                   nofile;
488 };
489
490 struct io_sync {
491         struct file                     *file;
492         loff_t                          len;
493         loff_t                          off;
494         int                             flags;
495         int                             mode;
496 };
497
498 struct io_cancel {
499         struct file                     *file;
500         u64                             addr;
501 };
502
503 struct io_timeout {
504         struct file                     *file;
505         u32                             off;
506         u32                             target_seq;
507         struct list_head                list;
508         /* head of the link, used by linked timeouts only */
509         struct io_kiocb                 *head;
510 };
511
512 struct io_timeout_rem {
513         struct file                     *file;
514         u64                             addr;
515
516         /* timeout update */
517         struct timespec64               ts;
518         u32                             flags;
519 };
520
521 struct io_rw {
522         /* NOTE: kiocb has the file as the first member, so don't do it here */
523         struct kiocb                    kiocb;
524         u64                             addr;
525         u64                             len;
526 };
527
528 struct io_connect {
529         struct file                     *file;
530         struct sockaddr __user          *addr;
531         int                             addr_len;
532 };
533
534 struct io_sr_msg {
535         struct file                     *file;
536         union {
537                 struct user_msghdr __user *umsg;
538                 void __user             *buf;
539         };
540         int                             msg_flags;
541         int                             bgid;
542         size_t                          len;
543         struct io_buffer                *kbuf;
544 };
545
546 struct io_open {
547         struct file                     *file;
548         int                             dfd;
549         struct filename                 *filename;
550         struct open_how                 how;
551         unsigned long                   nofile;
552 };
553
554 struct io_rsrc_update {
555         struct file                     *file;
556         u64                             arg;
557         u32                             nr_args;
558         u32                             offset;
559 };
560
561 struct io_fadvise {
562         struct file                     *file;
563         u64                             offset;
564         u32                             len;
565         u32                             advice;
566 };
567
568 struct io_madvise {
569         struct file                     *file;
570         u64                             addr;
571         u32                             len;
572         u32                             advice;
573 };
574
575 struct io_epoll {
576         struct file                     *file;
577         int                             epfd;
578         int                             op;
579         int                             fd;
580         struct epoll_event              event;
581 };
582
583 struct io_splice {
584         struct file                     *file_out;
585         struct file                     *file_in;
586         loff_t                          off_out;
587         loff_t                          off_in;
588         u64                             len;
589         unsigned int                    flags;
590 };
591
592 struct io_provide_buf {
593         struct file                     *file;
594         __u64                           addr;
595         __s32                           len;
596         __u32                           bgid;
597         __u16                           nbufs;
598         __u16                           bid;
599 };
600
601 struct io_statx {
602         struct file                     *file;
603         int                             dfd;
604         unsigned int                    mask;
605         unsigned int                    flags;
606         const char __user               *filename;
607         struct statx __user             *buffer;
608 };
609
610 struct io_shutdown {
611         struct file                     *file;
612         int                             how;
613 };
614
615 struct io_rename {
616         struct file                     *file;
617         int                             old_dfd;
618         int                             new_dfd;
619         struct filename                 *oldpath;
620         struct filename                 *newpath;
621         int                             flags;
622 };
623
624 struct io_unlink {
625         struct file                     *file;
626         int                             dfd;
627         int                             flags;
628         struct filename                 *filename;
629 };
630
631 struct io_completion {
632         struct file                     *file;
633         struct list_head                list;
634         int                             cflags;
635 };
636
637 struct io_async_connect {
638         struct sockaddr_storage         address;
639 };
640
641 struct io_async_msghdr {
642         struct iovec                    fast_iov[UIO_FASTIOV];
643         /* points to an allocated iov, if NULL we use fast_iov instead */
644         struct iovec                    *free_iov;
645         struct sockaddr __user          *uaddr;
646         struct msghdr                   msg;
647         struct sockaddr_storage         addr;
648 };
649
650 struct io_async_rw {
651         struct iovec                    fast_iov[UIO_FASTIOV];
652         const struct iovec              *free_iovec;
653         struct iov_iter                 iter;
654         size_t                          bytes_done;
655         struct wait_page_queue          wpq;
656 };
657
658 enum {
659         REQ_F_FIXED_FILE_BIT    = IOSQE_FIXED_FILE_BIT,
660         REQ_F_IO_DRAIN_BIT      = IOSQE_IO_DRAIN_BIT,
661         REQ_F_LINK_BIT          = IOSQE_IO_LINK_BIT,
662         REQ_F_HARDLINK_BIT      = IOSQE_IO_HARDLINK_BIT,
663         REQ_F_FORCE_ASYNC_BIT   = IOSQE_ASYNC_BIT,
664         REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
665
666         REQ_F_FAIL_LINK_BIT,
667         REQ_F_INFLIGHT_BIT,
668         REQ_F_CUR_POS_BIT,
669         REQ_F_NOWAIT_BIT,
670         REQ_F_LINK_TIMEOUT_BIT,
671         REQ_F_ISREG_BIT,
672         REQ_F_NEED_CLEANUP_BIT,
673         REQ_F_POLLED_BIT,
674         REQ_F_BUFFER_SELECTED_BIT,
675         REQ_F_NO_FILE_TABLE_BIT,
676         REQ_F_WORK_INITIALIZED_BIT,
677         REQ_F_LTIMEOUT_ACTIVE_BIT,
678         REQ_F_COMPLETE_INLINE_BIT,
679
680         /* not a real bit, just to check we're not overflowing the space */
681         __REQ_F_LAST_BIT,
682 };
683
684 enum {
685         /* ctx owns file */
686         REQ_F_FIXED_FILE        = BIT(REQ_F_FIXED_FILE_BIT),
687         /* drain existing IO first */
688         REQ_F_IO_DRAIN          = BIT(REQ_F_IO_DRAIN_BIT),
689         /* linked sqes */
690         REQ_F_LINK              = BIT(REQ_F_LINK_BIT),
691         /* doesn't sever on completion < 0 */
692         REQ_F_HARDLINK          = BIT(REQ_F_HARDLINK_BIT),
693         /* IOSQE_ASYNC */
694         REQ_F_FORCE_ASYNC       = BIT(REQ_F_FORCE_ASYNC_BIT),
695         /* IOSQE_BUFFER_SELECT */
696         REQ_F_BUFFER_SELECT     = BIT(REQ_F_BUFFER_SELECT_BIT),
697
698         /* fail rest of links */
699         REQ_F_FAIL_LINK         = BIT(REQ_F_FAIL_LINK_BIT),
700         /* on inflight list */
701         REQ_F_INFLIGHT          = BIT(REQ_F_INFLIGHT_BIT),
702         /* read/write uses file position */
703         REQ_F_CUR_POS           = BIT(REQ_F_CUR_POS_BIT),
704         /* must not punt to workers */
705         REQ_F_NOWAIT            = BIT(REQ_F_NOWAIT_BIT),
706         /* has or had linked timeout */
707         REQ_F_LINK_TIMEOUT      = BIT(REQ_F_LINK_TIMEOUT_BIT),
708         /* regular file */
709         REQ_F_ISREG             = BIT(REQ_F_ISREG_BIT),
710         /* needs cleanup */
711         REQ_F_NEED_CLEANUP      = BIT(REQ_F_NEED_CLEANUP_BIT),
712         /* already went through poll handler */
713         REQ_F_POLLED            = BIT(REQ_F_POLLED_BIT),
714         /* buffer already selected */
715         REQ_F_BUFFER_SELECTED   = BIT(REQ_F_BUFFER_SELECTED_BIT),
716         /* doesn't need file table for this request */
717         REQ_F_NO_FILE_TABLE     = BIT(REQ_F_NO_FILE_TABLE_BIT),
718         /* io_wq_work is initialized */
719         REQ_F_WORK_INITIALIZED  = BIT(REQ_F_WORK_INITIALIZED_BIT),
720         /* linked timeout is active, i.e. prepared by link's head */
721         REQ_F_LTIMEOUT_ACTIVE   = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
722         /* completion is deferred through io_comp_state */
723         REQ_F_COMPLETE_INLINE   = BIT(REQ_F_COMPLETE_INLINE_BIT),
724 };
725
726 struct async_poll {
727         struct io_poll_iocb     poll;
728         struct io_poll_iocb     *double_poll;
729 };
730
731 struct io_task_work {
732         struct io_wq_work_node  node;
733         task_work_func_t        func;
734 };
735
736 /*
737  * NOTE! Each of the iocb union members has the file pointer
738  * as the first entry in their struct definition. So you can
739  * access the file pointer through any of the sub-structs,
740  * or directly as just 'ki_filp' in this struct.
741  */
742 struct io_kiocb {
743         union {
744                 struct file             *file;
745                 struct io_rw            rw;
746                 struct io_poll_iocb     poll;
747                 struct io_poll_remove   poll_remove;
748                 struct io_accept        accept;
749                 struct io_sync          sync;
750                 struct io_cancel        cancel;
751                 struct io_timeout       timeout;
752                 struct io_timeout_rem   timeout_rem;
753                 struct io_connect       connect;
754                 struct io_sr_msg        sr_msg;
755                 struct io_open          open;
756                 struct io_close         close;
757                 struct io_rsrc_update   rsrc_update;
758                 struct io_fadvise       fadvise;
759                 struct io_madvise       madvise;
760                 struct io_epoll         epoll;
761                 struct io_splice        splice;
762                 struct io_provide_buf   pbuf;
763                 struct io_statx         statx;
764                 struct io_shutdown      shutdown;
765                 struct io_rename        rename;
766                 struct io_unlink        unlink;
767                 /* use only after cleaning per-op data, see io_clean_op() */
768                 struct io_completion    compl;
769         };
770
771         /* opcode allocated if it needs to store data for async defer */
772         void                            *async_data;
773         u8                              opcode;
774         /* polled IO has completed */
775         u8                              iopoll_completed;
776
777         u16                             buf_index;
778         u32                             result;
779
780         struct io_ring_ctx              *ctx;
781         unsigned int                    flags;
782         refcount_t                      refs;
783         struct task_struct              *task;
784         u64                             user_data;
785
786         struct io_kiocb                 *link;
787         struct percpu_ref               *fixed_rsrc_refs;
788
789         /*
790          * 1. used with ctx->iopoll_list with reads/writes
791          * 2. to track reqs with ->files (see io_op_def::file_table)
792          */
793         struct list_head                inflight_entry;
794         union {
795                 struct io_task_work     io_task_work;
796                 struct callback_head    task_work;
797         };
798         /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
799         struct hlist_node               hash_node;
800         struct async_poll               *apoll;
801         struct io_wq_work               work;
802 };
803
804 struct io_defer_entry {
805         struct list_head        list;
806         struct io_kiocb         *req;
807         u32                     seq;
808 };
809
810 struct io_op_def {
811         /* needs req->file assigned */
812         unsigned                needs_file : 1;
813         /* hash wq insertion if file is a regular file */
814         unsigned                hash_reg_file : 1;
815         /* unbound wq insertion if file is a non-regular file */
816         unsigned                unbound_nonreg_file : 1;
817         /* opcode is not supported by this kernel */
818         unsigned                not_supported : 1;
819         /* set if opcode supports polled "wait" */
820         unsigned                pollin : 1;
821         unsigned                pollout : 1;
822         /* op supports buffer selection */
823         unsigned                buffer_select : 1;
824         /* must always have async data allocated */
825         unsigned                needs_async_data : 1;
826         /* should block plug */
827         unsigned                plug : 1;
828         /* size of async data needed, if any */
829         unsigned short          async_size;
830         unsigned                work_flags;
831 };
832
833 static const struct io_op_def io_op_defs[] = {
834         [IORING_OP_NOP] = {},
835         [IORING_OP_READV] = {
836                 .needs_file             = 1,
837                 .unbound_nonreg_file    = 1,
838                 .pollin                 = 1,
839                 .buffer_select          = 1,
840                 .needs_async_data       = 1,
841                 .plug                   = 1,
842                 .async_size             = sizeof(struct io_async_rw),
843                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
844         },
845         [IORING_OP_WRITEV] = {
846                 .needs_file             = 1,
847                 .hash_reg_file          = 1,
848                 .unbound_nonreg_file    = 1,
849                 .pollout                = 1,
850                 .needs_async_data       = 1,
851                 .plug                   = 1,
852                 .async_size             = sizeof(struct io_async_rw),
853                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
854                                                 IO_WQ_WORK_FSIZE,
855         },
856         [IORING_OP_FSYNC] = {
857                 .needs_file             = 1,
858                 .work_flags             = IO_WQ_WORK_BLKCG,
859         },
860         [IORING_OP_READ_FIXED] = {
861                 .needs_file             = 1,
862                 .unbound_nonreg_file    = 1,
863                 .pollin                 = 1,
864                 .plug                   = 1,
865                 .async_size             = sizeof(struct io_async_rw),
866                 .work_flags             = IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
867         },
868         [IORING_OP_WRITE_FIXED] = {
869                 .needs_file             = 1,
870                 .hash_reg_file          = 1,
871                 .unbound_nonreg_file    = 1,
872                 .pollout                = 1,
873                 .plug                   = 1,
874                 .async_size             = sizeof(struct io_async_rw),
875                 .work_flags             = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE |
876                                                 IO_WQ_WORK_MM,
877         },
878         [IORING_OP_POLL_ADD] = {
879                 .needs_file             = 1,
880                 .unbound_nonreg_file    = 1,
881         },
882         [IORING_OP_POLL_REMOVE] = {},
883         [IORING_OP_SYNC_FILE_RANGE] = {
884                 .needs_file             = 1,
885                 .work_flags             = IO_WQ_WORK_BLKCG,
886         },
887         [IORING_OP_SENDMSG] = {
888                 .needs_file             = 1,
889                 .unbound_nonreg_file    = 1,
890                 .pollout                = 1,
891                 .needs_async_data       = 1,
892                 .async_size             = sizeof(struct io_async_msghdr),
893                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
894                                                 IO_WQ_WORK_FS,
895         },
896         [IORING_OP_RECVMSG] = {
897                 .needs_file             = 1,
898                 .unbound_nonreg_file    = 1,
899                 .pollin                 = 1,
900                 .buffer_select          = 1,
901                 .needs_async_data       = 1,
902                 .async_size             = sizeof(struct io_async_msghdr),
903                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
904                                                 IO_WQ_WORK_FS,
905         },
906         [IORING_OP_TIMEOUT] = {
907                 .needs_async_data       = 1,
908                 .async_size             = sizeof(struct io_timeout_data),
909                 .work_flags             = IO_WQ_WORK_MM,
910         },
911         [IORING_OP_TIMEOUT_REMOVE] = {
912                 /* used by timeout updates' prep() */
913                 .work_flags             = IO_WQ_WORK_MM,
914         },
915         [IORING_OP_ACCEPT] = {
916                 .needs_file             = 1,
917                 .unbound_nonreg_file    = 1,
918                 .pollin                 = 1,
919                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_FILES,
920         },
921         [IORING_OP_ASYNC_CANCEL] = {},
922         [IORING_OP_LINK_TIMEOUT] = {
923                 .needs_async_data       = 1,
924                 .async_size             = sizeof(struct io_timeout_data),
925                 .work_flags             = IO_WQ_WORK_MM,
926         },
927         [IORING_OP_CONNECT] = {
928                 .needs_file             = 1,
929                 .unbound_nonreg_file    = 1,
930                 .pollout                = 1,
931                 .needs_async_data       = 1,
932                 .async_size             = sizeof(struct io_async_connect),
933                 .work_flags             = IO_WQ_WORK_MM,
934         },
935         [IORING_OP_FALLOCATE] = {
936                 .needs_file             = 1,
937                 .work_flags             = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE,
938         },
939         [IORING_OP_OPENAT] = {
940                 .work_flags             = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG |
941                                                 IO_WQ_WORK_FS | IO_WQ_WORK_MM,
942         },
943         [IORING_OP_CLOSE] = {
944                 .work_flags             = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG,
945         },
946         [IORING_OP_FILES_UPDATE] = {
947                 .work_flags             = IO_WQ_WORK_FILES | IO_WQ_WORK_MM,
948         },
949         [IORING_OP_STATX] = {
950                 .work_flags             = IO_WQ_WORK_FILES | IO_WQ_WORK_MM |
951                                                 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
952         },
953         [IORING_OP_READ] = {
954                 .needs_file             = 1,
955                 .unbound_nonreg_file    = 1,
956                 .pollin                 = 1,
957                 .buffer_select          = 1,
958                 .plug                   = 1,
959                 .async_size             = sizeof(struct io_async_rw),
960                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
961         },
962         [IORING_OP_WRITE] = {
963                 .needs_file             = 1,
964                 .unbound_nonreg_file    = 1,
965                 .pollout                = 1,
966                 .plug                   = 1,
967                 .async_size             = sizeof(struct io_async_rw),
968                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
969                                                 IO_WQ_WORK_FSIZE,
970         },
971         [IORING_OP_FADVISE] = {
972                 .needs_file             = 1,
973                 .work_flags             = IO_WQ_WORK_BLKCG,
974         },
975         [IORING_OP_MADVISE] = {
976                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
977         },
978         [IORING_OP_SEND] = {
979                 .needs_file             = 1,
980                 .unbound_nonreg_file    = 1,
981                 .pollout                = 1,
982                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
983         },
984         [IORING_OP_RECV] = {
985                 .needs_file             = 1,
986                 .unbound_nonreg_file    = 1,
987                 .pollin                 = 1,
988                 .buffer_select          = 1,
989                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
990         },
991         [IORING_OP_OPENAT2] = {
992                 .work_flags             = IO_WQ_WORK_FILES | IO_WQ_WORK_FS |
993                                                 IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
994         },
995         [IORING_OP_EPOLL_CTL] = {
996                 .unbound_nonreg_file    = 1,
997                 .work_flags             = IO_WQ_WORK_FILES,
998         },
999         [IORING_OP_SPLICE] = {
1000                 .needs_file             = 1,
1001                 .hash_reg_file          = 1,
1002                 .unbound_nonreg_file    = 1,
1003                 .work_flags             = IO_WQ_WORK_BLKCG,
1004         },
1005         [IORING_OP_PROVIDE_BUFFERS] = {},
1006         [IORING_OP_REMOVE_BUFFERS] = {},
1007         [IORING_OP_TEE] = {
1008                 .needs_file             = 1,
1009                 .hash_reg_file          = 1,
1010                 .unbound_nonreg_file    = 1,
1011         },
1012         [IORING_OP_SHUTDOWN] = {
1013                 .needs_file             = 1,
1014         },
1015         [IORING_OP_RENAMEAT] = {
1016                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
1017                                                 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
1018         },
1019         [IORING_OP_UNLINKAT] = {
1020                 .work_flags             = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
1021                                                 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
1022         },
1023 };
1024
1025 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1026                                          struct task_struct *task,
1027                                          struct files_struct *files);
1028 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
1029 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
1030                         struct io_ring_ctx *ctx);
1031 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
1032                                      struct fixed_rsrc_ref_node *ref_node);
1033
1034 static bool io_rw_reissue(struct io_kiocb *req);
1035 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1036 static void io_put_req(struct io_kiocb *req);
1037 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1038 static void io_double_put_req(struct io_kiocb *req);
1039 static void io_dismantle_req(struct io_kiocb *req);
1040 static void io_put_task(struct task_struct *task, int nr);
1041 static void io_queue_next(struct io_kiocb *req);
1042 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1043 static void __io_queue_linked_timeout(struct io_kiocb *req);
1044 static void io_queue_linked_timeout(struct io_kiocb *req);
1045 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1046                                  struct io_uring_rsrc_update *ip,
1047                                  unsigned nr_args);
1048 static void __io_clean_op(struct io_kiocb *req);
1049 static struct file *io_file_get(struct io_submit_state *state,
1050                                 struct io_kiocb *req, int fd, bool fixed);
1051 static void __io_queue_sqe(struct io_kiocb *req);
1052 static void io_rsrc_put_work(struct work_struct *work);
1053
1054 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1055                            struct iov_iter *iter, bool needs_lock);
1056 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1057                              const struct iovec *fast_iov,
1058                              struct iov_iter *iter, bool force);
1059 static void io_req_task_queue(struct io_kiocb *req);
1060 static void io_submit_flush_completions(struct io_comp_state *cs,
1061                                         struct io_ring_ctx *ctx);
1062
1063 static struct kmem_cache *req_cachep;
1064
1065 static const struct file_operations io_uring_fops;
1066
1067 struct sock *io_uring_get_socket(struct file *file)
1068 {
1069 #if defined(CONFIG_UNIX)
1070         if (file->f_op == &io_uring_fops) {
1071                 struct io_ring_ctx *ctx = file->private_data;
1072
1073                 return ctx->ring_sock->sk;
1074         }
1075 #endif
1076         return NULL;
1077 }
1078 EXPORT_SYMBOL(io_uring_get_socket);
1079
1080 #define io_for_each_link(pos, head) \
1081         for (pos = (head); pos; pos = pos->link)
1082
1083 static inline void io_clean_op(struct io_kiocb *req)
1084 {
1085         if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1086                 __io_clean_op(req);
1087 }
1088
1089 static inline void io_set_resource_node(struct io_kiocb *req)
1090 {
1091         struct io_ring_ctx *ctx = req->ctx;
1092
1093         if (!req->fixed_rsrc_refs) {
1094                 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1095                 percpu_ref_get(req->fixed_rsrc_refs);
1096         }
1097 }
1098
1099 static bool io_match_task(struct io_kiocb *head,
1100                           struct task_struct *task,
1101                           struct files_struct *files)
1102 {
1103         struct io_kiocb *req;
1104
1105         if (task && head->task != task) {
1106                 /* in terms of cancelation, always match if req task is dead */
1107                 if (head->task->flags & PF_EXITING)
1108                         return true;
1109                 return false;
1110         }
1111         if (!files)
1112                 return true;
1113
1114         io_for_each_link(req, head) {
1115                 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1116                         continue;
1117                 if (req->file && req->file->f_op == &io_uring_fops)
1118                         return true;
1119                 if ((req->work.flags & IO_WQ_WORK_FILES) &&
1120                     req->work.identity->files == files)
1121                         return true;
1122         }
1123         return false;
1124 }
1125
1126 static void io_sq_thread_drop_mm_files(void)
1127 {
1128         struct files_struct *files = current->files;
1129         struct mm_struct *mm = current->mm;
1130
1131         if (mm) {
1132                 kthread_unuse_mm(mm);
1133                 mmput(mm);
1134                 current->mm = NULL;
1135         }
1136         if (files) {
1137                 struct nsproxy *nsproxy = current->nsproxy;
1138
1139                 task_lock(current);
1140                 current->files = NULL;
1141                 current->nsproxy = NULL;
1142                 task_unlock(current);
1143                 put_files_struct(files);
1144                 put_nsproxy(nsproxy);
1145         }
1146 }
1147
1148 static int __io_sq_thread_acquire_files(struct io_ring_ctx *ctx)
1149 {
1150         if (!current->files) {
1151                 struct files_struct *files;
1152                 struct nsproxy *nsproxy;
1153
1154                 task_lock(ctx->sqo_task);
1155                 files = ctx->sqo_task->files;
1156                 if (!files) {
1157                         task_unlock(ctx->sqo_task);
1158                         return -EOWNERDEAD;
1159                 }
1160                 atomic_inc(&files->count);
1161                 get_nsproxy(ctx->sqo_task->nsproxy);
1162                 nsproxy = ctx->sqo_task->nsproxy;
1163                 task_unlock(ctx->sqo_task);
1164
1165                 task_lock(current);
1166                 current->files = files;
1167                 current->nsproxy = nsproxy;
1168                 task_unlock(current);
1169         }
1170         return 0;
1171 }
1172
1173 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1174 {
1175         struct mm_struct *mm;
1176
1177         if (current->mm)
1178                 return 0;
1179
1180         task_lock(ctx->sqo_task);
1181         mm = ctx->sqo_task->mm;
1182         if (unlikely(!mm || !mmget_not_zero(mm)))
1183                 mm = NULL;
1184         task_unlock(ctx->sqo_task);
1185
1186         if (mm) {
1187                 kthread_use_mm(mm);
1188                 return 0;
1189         }
1190
1191         return -EFAULT;
1192 }
1193
1194 static int __io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1195                                            struct io_kiocb *req)
1196 {
1197         const struct io_op_def *def = &io_op_defs[req->opcode];
1198         int ret;
1199
1200         if (def->work_flags & IO_WQ_WORK_MM) {
1201                 ret = __io_sq_thread_acquire_mm(ctx);
1202                 if (unlikely(ret))
1203                         return ret;
1204         }
1205
1206         if (def->needs_file || (def->work_flags & IO_WQ_WORK_FILES)) {
1207                 ret = __io_sq_thread_acquire_files(ctx);
1208                 if (unlikely(ret))
1209                         return ret;
1210         }
1211
1212         return 0;
1213 }
1214
1215 static inline int io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1216                                                 struct io_kiocb *req)
1217 {
1218         if (!(ctx->flags & IORING_SETUP_SQPOLL))
1219                 return 0;
1220         return __io_sq_thread_acquire_mm_files(ctx, req);
1221 }
1222
1223 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1224                                          struct cgroup_subsys_state **cur_css)
1225
1226 {
1227 #ifdef CONFIG_BLK_CGROUP
1228         /* puts the old one when swapping */
1229         if (*cur_css != ctx->sqo_blkcg_css) {
1230                 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1231                 *cur_css = ctx->sqo_blkcg_css;
1232         }
1233 #endif
1234 }
1235
1236 static void io_sq_thread_unassociate_blkcg(void)
1237 {
1238 #ifdef CONFIG_BLK_CGROUP
1239         kthread_associate_blkcg(NULL);
1240 #endif
1241 }
1242
1243 static inline void req_set_fail_links(struct io_kiocb *req)
1244 {
1245         if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1246                 req->flags |= REQ_F_FAIL_LINK;
1247 }
1248
1249 /*
1250  * None of these are dereferenced, they are simply used to check if any of
1251  * them have changed. If we're under current and check they are still the
1252  * same, we're fine to grab references to them for actual out-of-line use.
1253  */
1254 static void io_init_identity(struct io_identity *id)
1255 {
1256         id->files = current->files;
1257         id->mm = current->mm;
1258 #ifdef CONFIG_BLK_CGROUP
1259         rcu_read_lock();
1260         id->blkcg_css = blkcg_css();
1261         rcu_read_unlock();
1262 #endif
1263         id->creds = current_cred();
1264         id->nsproxy = current->nsproxy;
1265         id->fs = current->fs;
1266         id->fsize = rlimit(RLIMIT_FSIZE);
1267 #ifdef CONFIG_AUDIT
1268         id->loginuid = current->loginuid;
1269         id->sessionid = current->sessionid;
1270 #endif
1271         refcount_set(&id->count, 1);
1272 }
1273
1274 static inline void __io_req_init_async(struct io_kiocb *req)
1275 {
1276         memset(&req->work, 0, sizeof(req->work));
1277         req->flags |= REQ_F_WORK_INITIALIZED;
1278 }
1279
1280 /*
1281  * Note: must call io_req_init_async() for the first time you
1282  * touch any members of io_wq_work.
1283  */
1284 static inline void io_req_init_async(struct io_kiocb *req)
1285 {
1286         struct io_uring_task *tctx = current->io_uring;
1287
1288         if (req->flags & REQ_F_WORK_INITIALIZED)
1289                 return;
1290
1291         __io_req_init_async(req);
1292
1293         /* Grab a ref if this isn't our static identity */
1294         req->work.identity = tctx->identity;
1295         if (tctx->identity != &tctx->__identity)
1296                 refcount_inc(&req->work.identity->count);
1297 }
1298
1299 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1300 {
1301         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1302
1303         complete(&ctx->ref_comp);
1304 }
1305
1306 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1307 {
1308         return !req->timeout.off;
1309 }
1310
1311 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1312 {
1313         struct io_ring_ctx *ctx;
1314         int hash_bits;
1315
1316         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1317         if (!ctx)
1318                 return NULL;
1319
1320         /*
1321          * Use 5 bits less than the max cq entries, that should give us around
1322          * 32 entries per hash list if totally full and uniformly spread.
1323          */
1324         hash_bits = ilog2(p->cq_entries);
1325         hash_bits -= 5;
1326         if (hash_bits <= 0)
1327                 hash_bits = 1;
1328         ctx->cancel_hash_bits = hash_bits;
1329         ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1330                                         GFP_KERNEL);
1331         if (!ctx->cancel_hash)
1332                 goto err;
1333         __hash_init(ctx->cancel_hash, 1U << hash_bits);
1334
1335         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1336                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1337                 goto err;
1338
1339         ctx->flags = p->flags;
1340         init_waitqueue_head(&ctx->sqo_sq_wait);
1341         INIT_LIST_HEAD(&ctx->sqd_list);
1342         init_waitqueue_head(&ctx->cq_wait);
1343         INIT_LIST_HEAD(&ctx->cq_overflow_list);
1344         init_completion(&ctx->ref_comp);
1345         init_completion(&ctx->sq_thread_comp);
1346         idr_init(&ctx->io_buffer_idr);
1347         idr_init(&ctx->personality_idr);
1348         mutex_init(&ctx->uring_lock);
1349         init_waitqueue_head(&ctx->wait);
1350         spin_lock_init(&ctx->completion_lock);
1351         INIT_LIST_HEAD(&ctx->iopoll_list);
1352         INIT_LIST_HEAD(&ctx->defer_list);
1353         INIT_LIST_HEAD(&ctx->timeout_list);
1354         spin_lock_init(&ctx->inflight_lock);
1355         INIT_LIST_HEAD(&ctx->inflight_list);
1356         spin_lock_init(&ctx->rsrc_ref_lock);
1357         INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1358         INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1359         init_llist_head(&ctx->rsrc_put_llist);
1360         INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1361         INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1362         return ctx;
1363 err:
1364         kfree(ctx->cancel_hash);
1365         kfree(ctx);
1366         return NULL;
1367 }
1368
1369 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1370 {
1371         if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1372                 struct io_ring_ctx *ctx = req->ctx;
1373
1374                 return seq != ctx->cached_cq_tail
1375                                 + READ_ONCE(ctx->cached_cq_overflow);
1376         }
1377
1378         return false;
1379 }
1380
1381 static void io_put_identity(struct io_uring_task *tctx, struct io_kiocb *req)
1382 {
1383         if (req->work.identity == &tctx->__identity)
1384                 return;
1385         if (refcount_dec_and_test(&req->work.identity->count))
1386                 kfree(req->work.identity);
1387 }
1388
1389 static void io_req_clean_work(struct io_kiocb *req)
1390 {
1391         if (!(req->flags & REQ_F_WORK_INITIALIZED))
1392                 return;
1393
1394         if (req->work.flags & IO_WQ_WORK_MM)
1395                 mmdrop(req->work.identity->mm);
1396 #ifdef CONFIG_BLK_CGROUP
1397         if (req->work.flags & IO_WQ_WORK_BLKCG)
1398                 css_put(req->work.identity->blkcg_css);
1399 #endif
1400         if (req->work.flags & IO_WQ_WORK_CREDS)
1401                 put_cred(req->work.identity->creds);
1402         if (req->work.flags & IO_WQ_WORK_FS) {
1403                 struct fs_struct *fs = req->work.identity->fs;
1404
1405                 spin_lock(&req->work.identity->fs->lock);
1406                 if (--fs->users)
1407                         fs = NULL;
1408                 spin_unlock(&req->work.identity->fs->lock);
1409                 if (fs)
1410                         free_fs_struct(fs);
1411         }
1412         if (req->work.flags & IO_WQ_WORK_FILES) {
1413                 put_files_struct(req->work.identity->files);
1414                 put_nsproxy(req->work.identity->nsproxy);
1415         }
1416         if (req->flags & REQ_F_INFLIGHT) {
1417                 struct io_ring_ctx *ctx = req->ctx;
1418                 struct io_uring_task *tctx = req->task->io_uring;
1419                 unsigned long flags;
1420
1421                 spin_lock_irqsave(&ctx->inflight_lock, flags);
1422                 list_del(&req->inflight_entry);
1423                 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1424                 req->flags &= ~REQ_F_INFLIGHT;
1425                 if (atomic_read(&tctx->in_idle))
1426                         wake_up(&tctx->wait);
1427         }
1428
1429         req->flags &= ~REQ_F_WORK_INITIALIZED;
1430         req->work.flags &= ~(IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG | IO_WQ_WORK_FS |
1431                              IO_WQ_WORK_CREDS | IO_WQ_WORK_FILES);
1432         io_put_identity(req->task->io_uring, req);
1433 }
1434
1435 /*
1436  * Create a private copy of io_identity, since some fields don't match
1437  * the current context.
1438  */
1439 static bool io_identity_cow(struct io_kiocb *req)
1440 {
1441         struct io_uring_task *tctx = current->io_uring;
1442         const struct cred *creds = NULL;
1443         struct io_identity *id;
1444
1445         if (req->work.flags & IO_WQ_WORK_CREDS)
1446                 creds = req->work.identity->creds;
1447
1448         id = kmemdup(req->work.identity, sizeof(*id), GFP_KERNEL);
1449         if (unlikely(!id)) {
1450                 req->work.flags |= IO_WQ_WORK_CANCEL;
1451                 return false;
1452         }
1453
1454         /*
1455          * We can safely just re-init the creds we copied  Either the field
1456          * matches the current one, or we haven't grabbed it yet. The only
1457          * exception is ->creds, through registered personalities, so handle
1458          * that one separately.
1459          */
1460         io_init_identity(id);
1461         if (creds)
1462                 id->creds = creds;
1463
1464         /* add one for this request */
1465         refcount_inc(&id->count);
1466
1467         /* drop tctx and req identity references, if needed */
1468         if (tctx->identity != &tctx->__identity &&
1469             refcount_dec_and_test(&tctx->identity->count))
1470                 kfree(tctx->identity);
1471         if (req->work.identity != &tctx->__identity &&
1472             refcount_dec_and_test(&req->work.identity->count))
1473                 kfree(req->work.identity);
1474
1475         req->work.identity = id;
1476         tctx->identity = id;
1477         return true;
1478 }
1479
1480 static void io_req_track_inflight(struct io_kiocb *req)
1481 {
1482         struct io_ring_ctx *ctx = req->ctx;
1483
1484         if (!(req->flags & REQ_F_INFLIGHT)) {
1485                 io_req_init_async(req);
1486                 req->flags |= REQ_F_INFLIGHT;
1487
1488                 spin_lock_irq(&ctx->inflight_lock);
1489                 list_add(&req->inflight_entry, &ctx->inflight_list);
1490                 spin_unlock_irq(&ctx->inflight_lock);
1491         }
1492 }
1493
1494 static bool io_grab_identity(struct io_kiocb *req)
1495 {
1496         const struct io_op_def *def = &io_op_defs[req->opcode];
1497         struct io_identity *id = req->work.identity;
1498
1499         if (def->work_flags & IO_WQ_WORK_FSIZE) {
1500                 if (id->fsize != rlimit(RLIMIT_FSIZE))
1501                         return false;
1502                 req->work.flags |= IO_WQ_WORK_FSIZE;
1503         }
1504 #ifdef CONFIG_BLK_CGROUP
1505         if (!(req->work.flags & IO_WQ_WORK_BLKCG) &&
1506             (def->work_flags & IO_WQ_WORK_BLKCG)) {
1507                 rcu_read_lock();
1508                 if (id->blkcg_css != blkcg_css()) {
1509                         rcu_read_unlock();
1510                         return false;
1511                 }
1512                 /*
1513                  * This should be rare, either the cgroup is dying or the task
1514                  * is moving cgroups. Just punt to root for the handful of ios.
1515                  */
1516                 if (css_tryget_online(id->blkcg_css))
1517                         req->work.flags |= IO_WQ_WORK_BLKCG;
1518                 rcu_read_unlock();
1519         }
1520 #endif
1521         if (!(req->work.flags & IO_WQ_WORK_CREDS)) {
1522                 if (id->creds != current_cred())
1523                         return false;
1524                 get_cred(id->creds);
1525                 req->work.flags |= IO_WQ_WORK_CREDS;
1526         }
1527 #ifdef CONFIG_AUDIT
1528         if (!uid_eq(current->loginuid, id->loginuid) ||
1529             current->sessionid != id->sessionid)
1530                 return false;
1531 #endif
1532         if (!(req->work.flags & IO_WQ_WORK_FS) &&
1533             (def->work_flags & IO_WQ_WORK_FS)) {
1534                 if (current->fs != id->fs)
1535                         return false;
1536                 spin_lock(&id->fs->lock);
1537                 if (!id->fs->in_exec) {
1538                         id->fs->users++;
1539                         req->work.flags |= IO_WQ_WORK_FS;
1540                 } else {
1541                         req->work.flags |= IO_WQ_WORK_CANCEL;
1542                 }
1543                 spin_unlock(&current->fs->lock);
1544         }
1545         if (!(req->work.flags & IO_WQ_WORK_FILES) &&
1546             (def->work_flags & IO_WQ_WORK_FILES) &&
1547             !(req->flags & REQ_F_NO_FILE_TABLE)) {
1548                 if (id->files != current->files ||
1549                     id->nsproxy != current->nsproxy)
1550                         return false;
1551                 atomic_inc(&id->files->count);
1552                 get_nsproxy(id->nsproxy);
1553                 req->work.flags |= IO_WQ_WORK_FILES;
1554                 io_req_track_inflight(req);
1555         }
1556         if (!(req->work.flags & IO_WQ_WORK_MM) &&
1557             (def->work_flags & IO_WQ_WORK_MM)) {
1558                 if (id->mm != current->mm)
1559                         return false;
1560                 mmgrab(id->mm);
1561                 req->work.flags |= IO_WQ_WORK_MM;
1562         }
1563
1564         return true;
1565 }
1566
1567 static void io_prep_async_work(struct io_kiocb *req)
1568 {
1569         const struct io_op_def *def = &io_op_defs[req->opcode];
1570         struct io_ring_ctx *ctx = req->ctx;
1571
1572         io_req_init_async(req);
1573
1574         if (req->flags & REQ_F_FORCE_ASYNC)
1575                 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1576
1577         if (req->flags & REQ_F_ISREG) {
1578                 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1579                         io_wq_hash_work(&req->work, file_inode(req->file));
1580         } else {
1581                 if (def->unbound_nonreg_file)
1582                         req->work.flags |= IO_WQ_WORK_UNBOUND;
1583         }
1584
1585         /* if we fail grabbing identity, we must COW, regrab, and retry */
1586         if (io_grab_identity(req))
1587                 return;
1588
1589         if (!io_identity_cow(req))
1590                 return;
1591
1592         /* can't fail at this point */
1593         if (!io_grab_identity(req))
1594                 WARN_ON(1);
1595 }
1596
1597 static void io_prep_async_link(struct io_kiocb *req)
1598 {
1599         struct io_kiocb *cur;
1600
1601         io_for_each_link(cur, req)
1602                 io_prep_async_work(cur);
1603 }
1604
1605 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1606 {
1607         struct io_ring_ctx *ctx = req->ctx;
1608         struct io_kiocb *link = io_prep_linked_timeout(req);
1609
1610         trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1611                                         &req->work, req->flags);
1612         io_wq_enqueue(ctx->io_wq, &req->work);
1613         return link;
1614 }
1615
1616 static void io_queue_async_work(struct io_kiocb *req)
1617 {
1618         struct io_kiocb *link;
1619
1620         /* init ->work of the whole link before punting */
1621         io_prep_async_link(req);
1622         link = __io_queue_async_work(req);
1623
1624         if (link)
1625                 io_queue_linked_timeout(link);
1626 }
1627
1628 static void io_kill_timeout(struct io_kiocb *req)
1629 {
1630         struct io_timeout_data *io = req->async_data;
1631         int ret;
1632
1633         ret = hrtimer_try_to_cancel(&io->timer);
1634         if (ret != -1) {
1635                 atomic_set(&req->ctx->cq_timeouts,
1636                         atomic_read(&req->ctx->cq_timeouts) + 1);
1637                 list_del_init(&req->timeout.list);
1638                 io_cqring_fill_event(req, 0);
1639                 io_put_req_deferred(req, 1);
1640         }
1641 }
1642
1643 /*
1644  * Returns true if we found and killed one or more timeouts
1645  */
1646 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1647                              struct files_struct *files)
1648 {
1649         struct io_kiocb *req, *tmp;
1650         int canceled = 0;
1651
1652         spin_lock_irq(&ctx->completion_lock);
1653         list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1654                 if (io_match_task(req, tsk, files)) {
1655                         io_kill_timeout(req);
1656                         canceled++;
1657                 }
1658         }
1659         spin_unlock_irq(&ctx->completion_lock);
1660         return canceled != 0;
1661 }
1662
1663 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1664 {
1665         do {
1666                 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1667                                                 struct io_defer_entry, list);
1668
1669                 if (req_need_defer(de->req, de->seq))
1670                         break;
1671                 list_del_init(&de->list);
1672                 io_req_task_queue(de->req);
1673                 kfree(de);
1674         } while (!list_empty(&ctx->defer_list));
1675 }
1676
1677 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1678 {
1679         u32 seq;
1680
1681         if (list_empty(&ctx->timeout_list))
1682                 return;
1683
1684         seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1685
1686         do {
1687                 u32 events_needed, events_got;
1688                 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1689                                                 struct io_kiocb, timeout.list);
1690
1691                 if (io_is_timeout_noseq(req))
1692                         break;
1693
1694                 /*
1695                  * Since seq can easily wrap around over time, subtract
1696                  * the last seq at which timeouts were flushed before comparing.
1697                  * Assuming not more than 2^31-1 events have happened since,
1698                  * these subtractions won't have wrapped, so we can check if
1699                  * target is in [last_seq, current_seq] by comparing the two.
1700                  */
1701                 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1702                 events_got = seq - ctx->cq_last_tm_flush;
1703                 if (events_got < events_needed)
1704                         break;
1705
1706                 list_del_init(&req->timeout.list);
1707                 io_kill_timeout(req);
1708         } while (!list_empty(&ctx->timeout_list));
1709
1710         ctx->cq_last_tm_flush = seq;
1711 }
1712
1713 static void io_commit_cqring(struct io_ring_ctx *ctx)
1714 {
1715         io_flush_timeouts(ctx);
1716
1717         /* order cqe stores with ring update */
1718         smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1719
1720         if (unlikely(!list_empty(&ctx->defer_list)))
1721                 __io_queue_deferred(ctx);
1722 }
1723
1724 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1725 {
1726         struct io_rings *r = ctx->rings;
1727
1728         return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1729 }
1730
1731 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1732 {
1733         return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1734 }
1735
1736 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1737 {
1738         struct io_rings *rings = ctx->rings;
1739         unsigned tail;
1740
1741         /*
1742          * writes to the cq entry need to come after reading head; the
1743          * control dependency is enough as we're using WRITE_ONCE to
1744          * fill the cq entry
1745          */
1746         if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1747                 return NULL;
1748
1749         tail = ctx->cached_cq_tail++;
1750         return &rings->cqes[tail & ctx->cq_mask];
1751 }
1752
1753 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1754 {
1755         if (!ctx->cq_ev_fd)
1756                 return false;
1757         if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1758                 return false;
1759         if (!ctx->eventfd_async)
1760                 return true;
1761         return io_wq_current_is_worker();
1762 }
1763
1764 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1765 {
1766         /* see waitqueue_active() comment */
1767         smp_mb();
1768
1769         if (waitqueue_active(&ctx->wait))
1770                 wake_up(&ctx->wait);
1771         if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1772                 wake_up(&ctx->sq_data->wait);
1773         if (io_should_trigger_evfd(ctx))
1774                 eventfd_signal(ctx->cq_ev_fd, 1);
1775         if (waitqueue_active(&ctx->cq_wait)) {
1776                 wake_up_interruptible(&ctx->cq_wait);
1777                 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1778         }
1779 }
1780
1781 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1782 {
1783         /* see waitqueue_active() comment */
1784         smp_mb();
1785
1786         if (ctx->flags & IORING_SETUP_SQPOLL) {
1787                 if (waitqueue_active(&ctx->wait))
1788                         wake_up(&ctx->wait);
1789         }
1790         if (io_should_trigger_evfd(ctx))
1791                 eventfd_signal(ctx->cq_ev_fd, 1);
1792         if (waitqueue_active(&ctx->cq_wait)) {
1793                 wake_up_interruptible(&ctx->cq_wait);
1794                 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1795         }
1796 }
1797
1798 /* Returns true if there are no backlogged entries after the flush */
1799 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1800                                        struct task_struct *tsk,
1801                                        struct files_struct *files)
1802 {
1803         struct io_rings *rings = ctx->rings;
1804         struct io_kiocb *req, *tmp;
1805         struct io_uring_cqe *cqe;
1806         unsigned long flags;
1807         bool all_flushed, posted;
1808         LIST_HEAD(list);
1809
1810         if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1811                 return false;
1812
1813         posted = false;
1814         spin_lock_irqsave(&ctx->completion_lock, flags);
1815         list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1816                 if (!io_match_task(req, tsk, files))
1817                         continue;
1818
1819                 cqe = io_get_cqring(ctx);
1820                 if (!cqe && !force)
1821                         break;
1822
1823                 list_move(&req->compl.list, &list);
1824                 if (cqe) {
1825                         WRITE_ONCE(cqe->user_data, req->user_data);
1826                         WRITE_ONCE(cqe->res, req->result);
1827                         WRITE_ONCE(cqe->flags, req->compl.cflags);
1828                 } else {
1829                         ctx->cached_cq_overflow++;
1830                         WRITE_ONCE(ctx->rings->cq_overflow,
1831                                    ctx->cached_cq_overflow);
1832                 }
1833                 posted = true;
1834         }
1835
1836         all_flushed = list_empty(&ctx->cq_overflow_list);
1837         if (all_flushed) {
1838                 clear_bit(0, &ctx->sq_check_overflow);
1839                 clear_bit(0, &ctx->cq_check_overflow);
1840                 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1841         }
1842
1843         if (posted)
1844                 io_commit_cqring(ctx);
1845         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1846         if (posted)
1847                 io_cqring_ev_posted(ctx);
1848
1849         while (!list_empty(&list)) {
1850                 req = list_first_entry(&list, struct io_kiocb, compl.list);
1851                 list_del(&req->compl.list);
1852                 io_put_req(req);
1853         }
1854
1855         return all_flushed;
1856 }
1857
1858 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1859                                      struct task_struct *tsk,
1860                                      struct files_struct *files)
1861 {
1862         if (test_bit(0, &ctx->cq_check_overflow)) {
1863                 /* iopoll syncs against uring_lock, not completion_lock */
1864                 if (ctx->flags & IORING_SETUP_IOPOLL)
1865                         mutex_lock(&ctx->uring_lock);
1866                 __io_cqring_overflow_flush(ctx, force, tsk, files);
1867                 if (ctx->flags & IORING_SETUP_IOPOLL)
1868                         mutex_unlock(&ctx->uring_lock);
1869         }
1870 }
1871
1872 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1873 {
1874         struct io_ring_ctx *ctx = req->ctx;
1875         struct io_uring_cqe *cqe;
1876
1877         trace_io_uring_complete(ctx, req->user_data, res);
1878
1879         /*
1880          * If we can't get a cq entry, userspace overflowed the
1881          * submission (by quite a lot). Increment the overflow count in
1882          * the ring.
1883          */
1884         cqe = io_get_cqring(ctx);
1885         if (likely(cqe)) {
1886                 WRITE_ONCE(cqe->user_data, req->user_data);
1887                 WRITE_ONCE(cqe->res, res);
1888                 WRITE_ONCE(cqe->flags, cflags);
1889         } else if (ctx->cq_overflow_flushed ||
1890                    atomic_read(&req->task->io_uring->in_idle)) {
1891                 /*
1892                  * If we're in ring overflow flush mode, or in task cancel mode,
1893                  * then we cannot store the request for later flushing, we need
1894                  * to drop it on the floor.
1895                  */
1896                 ctx->cached_cq_overflow++;
1897                 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1898         } else {
1899                 if (list_empty(&ctx->cq_overflow_list)) {
1900                         set_bit(0, &ctx->sq_check_overflow);
1901                         set_bit(0, &ctx->cq_check_overflow);
1902                         ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1903                 }
1904                 io_clean_op(req);
1905                 req->result = res;
1906                 req->compl.cflags = cflags;
1907                 refcount_inc(&req->refs);
1908                 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1909         }
1910 }
1911
1912 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1913 {
1914         __io_cqring_fill_event(req, res, 0);
1915 }
1916
1917 static inline void io_req_complete_post(struct io_kiocb *req, long res,
1918                                         unsigned int cflags)
1919 {
1920         struct io_ring_ctx *ctx = req->ctx;
1921         unsigned long flags;
1922
1923         spin_lock_irqsave(&ctx->completion_lock, flags);
1924         __io_cqring_fill_event(req, res, cflags);
1925         io_commit_cqring(ctx);
1926         /*
1927          * If we're the last reference to this request, add to our locked
1928          * free_list cache.
1929          */
1930         if (refcount_dec_and_test(&req->refs)) {
1931                 struct io_comp_state *cs = &ctx->submit_state.comp;
1932
1933                 io_dismantle_req(req);
1934                 io_put_task(req->task, 1);
1935                 list_add(&req->compl.list, &cs->locked_free_list);
1936                 cs->locked_free_nr++;
1937         } else
1938                 req = NULL;
1939         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1940
1941         io_cqring_ev_posted(ctx);
1942         if (req) {
1943                 io_queue_next(req);
1944                 percpu_ref_put(&ctx->refs);
1945         }
1946 }
1947
1948 static void io_req_complete_state(struct io_kiocb *req, long res,
1949                                   unsigned int cflags)
1950 {
1951         io_clean_op(req);
1952         req->result = res;
1953         req->compl.cflags = cflags;
1954         req->flags |= REQ_F_COMPLETE_INLINE;
1955 }
1956
1957 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1958                                      long res, unsigned cflags)
1959 {
1960         if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1961                 io_req_complete_state(req, res, cflags);
1962         else
1963                 io_req_complete_post(req, res, cflags);
1964 }
1965
1966 static inline void io_req_complete(struct io_kiocb *req, long res)
1967 {
1968         __io_req_complete(req, 0, res, 0);
1969 }
1970
1971 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1972 {
1973         struct io_submit_state *state = &ctx->submit_state;
1974         struct io_comp_state *cs = &state->comp;
1975         struct io_kiocb *req = NULL;
1976
1977         /*
1978          * If we have more than a batch's worth of requests in our IRQ side
1979          * locked cache, grab the lock and move them over to our submission
1980          * side cache.
1981          */
1982         if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1983                 spin_lock_irq(&ctx->completion_lock);
1984                 list_splice_init(&cs->locked_free_list, &cs->free_list);
1985                 cs->locked_free_nr = 0;
1986                 spin_unlock_irq(&ctx->completion_lock);
1987         }
1988
1989         while (!list_empty(&cs->free_list)) {
1990                 req = list_first_entry(&cs->free_list, struct io_kiocb,
1991                                         compl.list);
1992                 list_del(&req->compl.list);
1993                 state->reqs[state->free_reqs++] = req;
1994                 if (state->free_reqs == ARRAY_SIZE(state->reqs))
1995                         break;
1996         }
1997
1998         return req != NULL;
1999 }
2000
2001 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2002 {
2003         struct io_submit_state *state = &ctx->submit_state;
2004
2005         BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
2006
2007         if (!state->free_reqs) {
2008                 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2009                 int ret;
2010
2011                 if (io_flush_cached_reqs(ctx))
2012                         goto got_req;
2013
2014                 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
2015                                             state->reqs);
2016
2017                 /*
2018                  * Bulk alloc is all-or-nothing. If we fail to get a batch,
2019                  * retry single alloc to be on the safe side.
2020                  */
2021                 if (unlikely(ret <= 0)) {
2022                         state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2023                         if (!state->reqs[0])
2024                                 return NULL;
2025                         ret = 1;
2026                 }
2027                 state->free_reqs = ret;
2028         }
2029 got_req:
2030         state->free_reqs--;
2031         return state->reqs[state->free_reqs];
2032 }
2033
2034 static inline void io_put_file(struct io_kiocb *req, struct file *file,
2035                           bool fixed)
2036 {
2037         if (!fixed)
2038                 fput(file);
2039 }
2040
2041 static void io_dismantle_req(struct io_kiocb *req)
2042 {
2043         io_clean_op(req);
2044
2045         if (req->async_data)
2046                 kfree(req->async_data);
2047         if (req->file)
2048                 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
2049         if (req->fixed_rsrc_refs)
2050                 percpu_ref_put(req->fixed_rsrc_refs);
2051         io_req_clean_work(req);
2052 }
2053
2054 static inline void io_put_task(struct task_struct *task, int nr)
2055 {
2056         struct io_uring_task *tctx = task->io_uring;
2057
2058         percpu_counter_sub(&tctx->inflight, nr);
2059         if (unlikely(atomic_read(&tctx->in_idle)))
2060                 wake_up(&tctx->wait);
2061         put_task_struct_many(task, nr);
2062 }
2063
2064 static void __io_free_req(struct io_kiocb *req)
2065 {
2066         struct io_ring_ctx *ctx = req->ctx;
2067
2068         io_dismantle_req(req);
2069         io_put_task(req->task, 1);
2070
2071         kmem_cache_free(req_cachep, req);
2072         percpu_ref_put(&ctx->refs);
2073 }
2074
2075 static inline void io_remove_next_linked(struct io_kiocb *req)
2076 {
2077         struct io_kiocb *nxt = req->link;
2078
2079         req->link = nxt->link;
2080         nxt->link = NULL;
2081 }
2082
2083 static void io_kill_linked_timeout(struct io_kiocb *req)
2084 {
2085         struct io_ring_ctx *ctx = req->ctx;
2086         struct io_kiocb *link;
2087         bool cancelled = false;
2088         unsigned long flags;
2089
2090         spin_lock_irqsave(&ctx->completion_lock, flags);
2091         link = req->link;
2092
2093         /*
2094          * Can happen if a linked timeout fired and link had been like
2095          * req -> link t-out -> link t-out [-> ...]
2096          */
2097         if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
2098                 struct io_timeout_data *io = link->async_data;
2099                 int ret;
2100
2101                 io_remove_next_linked(req);
2102                 link->timeout.head = NULL;
2103                 ret = hrtimer_try_to_cancel(&io->timer);
2104                 if (ret != -1) {
2105                         io_cqring_fill_event(link, -ECANCELED);
2106                         io_commit_cqring(ctx);
2107                         cancelled = true;
2108                 }
2109         }
2110         req->flags &= ~REQ_F_LINK_TIMEOUT;
2111         spin_unlock_irqrestore(&ctx->completion_lock, flags);
2112
2113         if (cancelled) {
2114                 io_cqring_ev_posted(ctx);
2115                 io_put_req(link);
2116         }
2117 }
2118
2119
2120 static void io_fail_links(struct io_kiocb *req)
2121 {
2122         struct io_kiocb *link, *nxt;
2123         struct io_ring_ctx *ctx = req->ctx;
2124         unsigned long flags;
2125
2126         spin_lock_irqsave(&ctx->completion_lock, flags);
2127         link = req->link;
2128         req->link = NULL;
2129
2130         while (link) {
2131                 nxt = link->link;
2132                 link->link = NULL;
2133
2134                 trace_io_uring_fail_link(req, link);
2135                 io_cqring_fill_event(link, -ECANCELED);
2136
2137                 /*
2138                  * It's ok to free under spinlock as they're not linked anymore,
2139                  * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
2140                  * work.fs->lock.
2141                  */
2142                 if (link->flags & REQ_F_WORK_INITIALIZED)
2143                         io_put_req_deferred(link, 2);
2144                 else
2145                         io_double_put_req(link);
2146                 link = nxt;
2147         }
2148         io_commit_cqring(ctx);
2149         spin_unlock_irqrestore(&ctx->completion_lock, flags);
2150
2151         io_cqring_ev_posted(ctx);
2152 }
2153
2154 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2155 {
2156         if (req->flags & REQ_F_LINK_TIMEOUT)
2157                 io_kill_linked_timeout(req);
2158
2159         /*
2160          * If LINK is set, we have dependent requests in this chain. If we
2161          * didn't fail this request, queue the first one up, moving any other
2162          * dependencies to the next request. In case of failure, fail the rest
2163          * of the chain.
2164          */
2165         if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
2166                 struct io_kiocb *nxt = req->link;
2167
2168                 req->link = NULL;
2169                 return nxt;
2170         }
2171         io_fail_links(req);
2172         return NULL;
2173 }
2174
2175 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2176 {
2177         if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2178                 return NULL;
2179         return __io_req_find_next(req);
2180 }
2181
2182 static bool __tctx_task_work(struct io_uring_task *tctx)
2183 {
2184         struct io_ring_ctx *ctx = NULL;
2185         struct io_wq_work_list list;
2186         struct io_wq_work_node *node;
2187
2188         if (wq_list_empty(&tctx->task_list))
2189                 return false;
2190
2191         spin_lock_irq(&tctx->task_lock);
2192         list = tctx->task_list;
2193         INIT_WQ_LIST(&tctx->task_list);
2194         spin_unlock_irq(&tctx->task_lock);
2195
2196         node = list.first;
2197         while (node) {
2198                 struct io_wq_work_node *next = node->next;
2199                 struct io_ring_ctx *this_ctx;
2200                 struct io_kiocb *req;
2201
2202                 req = container_of(node, struct io_kiocb, io_task_work.node);
2203                 this_ctx = req->ctx;
2204                 req->task_work.func(&req->task_work);
2205                 node = next;
2206
2207                 if (!ctx) {
2208                         ctx = this_ctx;
2209                 } else if (ctx != this_ctx) {
2210                         mutex_lock(&ctx->uring_lock);
2211                         io_submit_flush_completions(&ctx->submit_state.comp, ctx);
2212                         mutex_unlock(&ctx->uring_lock);
2213                         ctx = this_ctx;
2214                 }
2215         }
2216
2217         if (ctx && ctx->submit_state.comp.nr) {
2218                 mutex_lock(&ctx->uring_lock);
2219                 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
2220                 mutex_unlock(&ctx->uring_lock);
2221         }
2222
2223         return list.first != NULL;
2224 }
2225
2226 static void tctx_task_work(struct callback_head *cb)
2227 {
2228         struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
2229
2230         while (__tctx_task_work(tctx))
2231                 cond_resched();
2232
2233         clear_bit(0, &tctx->task_state);
2234 }
2235
2236 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
2237                             enum task_work_notify_mode notify)
2238 {
2239         struct io_uring_task *tctx = tsk->io_uring;
2240         struct io_wq_work_node *node, *prev;
2241         unsigned long flags;
2242         int ret;
2243
2244         WARN_ON_ONCE(!tctx);
2245
2246         spin_lock_irqsave(&tctx->task_lock, flags);
2247         wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2248         spin_unlock_irqrestore(&tctx->task_lock, flags);
2249
2250         /* task_work already pending, we're done */
2251         if (test_bit(0, &tctx->task_state) ||
2252             test_and_set_bit(0, &tctx->task_state))
2253                 return 0;
2254
2255         if (!task_work_add(tsk, &tctx->task_work, notify))
2256                 return 0;
2257
2258         /*
2259          * Slow path - we failed, find and delete work. if the work is not
2260          * in the list, it got run and we're fine.
2261          */
2262         ret = 0;
2263         spin_lock_irqsave(&tctx->task_lock, flags);
2264         wq_list_for_each(node, prev, &tctx->task_list) {
2265                 if (&req->io_task_work.node == node) {
2266                         wq_list_del(&tctx->task_list, node, prev);
2267                         ret = 1;
2268                         break;
2269                 }
2270         }
2271         spin_unlock_irqrestore(&tctx->task_lock, flags);
2272         clear_bit(0, &tctx->task_state);
2273         return ret;
2274 }
2275
2276 static int io_req_task_work_add(struct io_kiocb *req)
2277 {
2278         struct task_struct *tsk = req->task;
2279         struct io_ring_ctx *ctx = req->ctx;
2280         enum task_work_notify_mode notify;
2281         int ret;
2282
2283         if (tsk->flags & PF_EXITING)
2284                 return -ESRCH;
2285
2286         /*
2287          * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2288          * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2289          * processing task_work. There's no reliable way to tell if TWA_RESUME
2290          * will do the job.
2291          */
2292         notify = TWA_NONE;
2293         if (!(ctx->flags & IORING_SETUP_SQPOLL))
2294                 notify = TWA_SIGNAL;
2295
2296         ret = io_task_work_add(tsk, req, notify);
2297         if (!ret)
2298                 wake_up_process(tsk);
2299
2300         return ret;
2301 }
2302
2303 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2304                                           task_work_func_t cb)
2305 {
2306         struct task_struct *tsk = io_wq_get_task(req->ctx->io_wq);
2307
2308         init_task_work(&req->task_work, cb);
2309         task_work_add(tsk, &req->task_work, TWA_NONE);
2310         wake_up_process(tsk);
2311 }
2312
2313 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2314 {
2315         struct io_ring_ctx *ctx = req->ctx;
2316
2317         spin_lock_irq(&ctx->completion_lock);
2318         io_cqring_fill_event(req, error);
2319         io_commit_cqring(ctx);
2320         spin_unlock_irq(&ctx->completion_lock);
2321
2322         io_cqring_ev_posted(ctx);
2323         req_set_fail_links(req);
2324         io_double_put_req(req);
2325 }
2326
2327 static void io_req_task_cancel(struct callback_head *cb)
2328 {
2329         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2330         struct io_ring_ctx *ctx = req->ctx;
2331
2332         __io_req_task_cancel(req, -ECANCELED);
2333         percpu_ref_put(&ctx->refs);
2334 }
2335
2336 static void __io_req_task_submit(struct io_kiocb *req)
2337 {
2338         struct io_ring_ctx *ctx = req->ctx;
2339
2340         /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2341         mutex_lock(&ctx->uring_lock);
2342         if (!ctx->sqo_dead && !(current->flags & PF_EXITING) &&
2343             !io_sq_thread_acquire_mm_files(ctx, req))
2344                 __io_queue_sqe(req);
2345         else
2346                 __io_req_task_cancel(req, -EFAULT);
2347         mutex_unlock(&ctx->uring_lock);
2348
2349         if (ctx->flags & IORING_SETUP_SQPOLL)
2350                 io_sq_thread_drop_mm_files();
2351 }
2352
2353 static void io_req_task_submit(struct callback_head *cb)
2354 {
2355         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2356
2357         __io_req_task_submit(req);
2358 }
2359
2360 static void io_req_task_queue(struct io_kiocb *req)
2361 {
2362         int ret;
2363
2364         req->task_work.func = io_req_task_submit;
2365         ret = io_req_task_work_add(req);
2366         if (unlikely(ret)) {
2367                 percpu_ref_get(&req->ctx->refs);
2368                 io_req_task_work_add_fallback(req, io_req_task_cancel);
2369         }
2370 }
2371
2372 static inline void io_queue_next(struct io_kiocb *req)
2373 {
2374         struct io_kiocb *nxt = io_req_find_next(req);
2375
2376         if (nxt)
2377                 io_req_task_queue(nxt);
2378 }
2379
2380 static void io_free_req(struct io_kiocb *req)
2381 {
2382         io_queue_next(req);
2383         __io_free_req(req);
2384 }
2385
2386 struct req_batch {
2387         struct task_struct      *task;
2388         int                     task_refs;
2389         int                     ctx_refs;
2390 };
2391
2392 static inline void io_init_req_batch(struct req_batch *rb)
2393 {
2394         rb->task_refs = 0;
2395         rb->ctx_refs = 0;
2396         rb->task = NULL;
2397 }
2398
2399 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2400                                      struct req_batch *rb)
2401 {
2402         if (rb->task)
2403                 io_put_task(rb->task, rb->task_refs);
2404         if (rb->ctx_refs)
2405                 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2406 }
2407
2408 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2409                               struct io_submit_state *state)
2410 {
2411         io_queue_next(req);
2412
2413         if (req->task != rb->task) {
2414                 if (rb->task)
2415                         io_put_task(rb->task, rb->task_refs);
2416                 rb->task = req->task;
2417                 rb->task_refs = 0;
2418         }
2419         rb->task_refs++;
2420         rb->ctx_refs++;
2421
2422         io_dismantle_req(req);
2423         if (state->free_reqs != ARRAY_SIZE(state->reqs))
2424                 state->reqs[state->free_reqs++] = req;
2425         else
2426                 list_add(&req->compl.list, &state->comp.free_list);
2427 }
2428
2429 static void io_submit_flush_completions(struct io_comp_state *cs,
2430                                         struct io_ring_ctx *ctx)
2431 {
2432         int i, nr = cs->nr;
2433         struct io_kiocb *req;
2434         struct req_batch rb;
2435
2436         io_init_req_batch(&rb);
2437         spin_lock_irq(&ctx->completion_lock);
2438         for (i = 0; i < nr; i++) {
2439                 req = cs->reqs[i];
2440                 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2441         }
2442         io_commit_cqring(ctx);
2443         spin_unlock_irq(&ctx->completion_lock);
2444
2445         io_cqring_ev_posted(ctx);
2446         for (i = 0; i < nr; i++) {
2447                 req = cs->reqs[i];
2448
2449                 /* submission and completion refs */
2450                 if (refcount_sub_and_test(2, &req->refs))
2451                         io_req_free_batch(&rb, req, &ctx->submit_state);
2452         }
2453
2454         io_req_free_batch_finish(ctx, &rb);
2455         cs->nr = 0;
2456 }
2457
2458 /*
2459  * Drop reference to request, return next in chain (if there is one) if this
2460  * was the last reference to this request.
2461  */
2462 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2463 {
2464         struct io_kiocb *nxt = NULL;
2465
2466         if (refcount_dec_and_test(&req->refs)) {
2467                 nxt = io_req_find_next(req);
2468                 __io_free_req(req);
2469         }
2470         return nxt;
2471 }
2472
2473 static void io_put_req(struct io_kiocb *req)
2474 {
2475         if (refcount_dec_and_test(&req->refs))
2476                 io_free_req(req);
2477 }
2478
2479 static void io_put_req_deferred_cb(struct callback_head *cb)
2480 {
2481         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2482
2483         io_free_req(req);
2484 }
2485
2486 static void io_free_req_deferred(struct io_kiocb *req)
2487 {
2488         int ret;
2489
2490         req->task_work.func = io_put_req_deferred_cb;
2491         ret = io_req_task_work_add(req);
2492         if (unlikely(ret))
2493                 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2494 }
2495
2496 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2497 {
2498         if (refcount_sub_and_test(refs, &req->refs))
2499                 io_free_req_deferred(req);
2500 }
2501
2502 static void io_double_put_req(struct io_kiocb *req)
2503 {
2504         /* drop both submit and complete references */
2505         if (refcount_sub_and_test(2, &req->refs))
2506                 io_free_req(req);
2507 }
2508
2509 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2510 {
2511         /* See comment at the top of this file */
2512         smp_rmb();
2513         return __io_cqring_events(ctx);
2514 }
2515
2516 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2517 {
2518         struct io_rings *rings = ctx->rings;
2519
2520         /* make sure SQ entry isn't read before tail */
2521         return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2522 }
2523
2524 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2525 {
2526         unsigned int cflags;
2527
2528         cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2529         cflags |= IORING_CQE_F_BUFFER;
2530         req->flags &= ~REQ_F_BUFFER_SELECTED;
2531         kfree(kbuf);
2532         return cflags;
2533 }
2534
2535 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2536 {
2537         struct io_buffer *kbuf;
2538
2539         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2540         return io_put_kbuf(req, kbuf);
2541 }
2542
2543 static inline bool io_run_task_work(void)
2544 {
2545         /*
2546          * Not safe to run on exiting task, and the task_work handling will
2547          * not add work to such a task.
2548          */
2549         if (unlikely(current->flags & PF_EXITING))
2550                 return false;
2551         if (current->task_works) {
2552                 __set_current_state(TASK_RUNNING);
2553                 task_work_run();
2554                 return true;
2555         }
2556
2557         return false;
2558 }
2559
2560 /*
2561  * Find and free completed poll iocbs
2562  */
2563 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2564                                struct list_head *done)
2565 {
2566         struct req_batch rb;
2567         struct io_kiocb *req;
2568
2569         /* order with ->result store in io_complete_rw_iopoll() */
2570         smp_rmb();
2571
2572         io_init_req_batch(&rb);
2573         while (!list_empty(done)) {
2574                 int cflags = 0;
2575
2576                 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2577                 list_del(&req->inflight_entry);
2578
2579                 if (READ_ONCE(req->result) == -EAGAIN) {
2580                         req->iopoll_completed = 0;
2581                         if (io_rw_reissue(req))
2582                                 continue;
2583                 }
2584
2585                 if (req->flags & REQ_F_BUFFER_SELECTED)
2586                         cflags = io_put_rw_kbuf(req);
2587
2588                 __io_cqring_fill_event(req, req->result, cflags);
2589                 (*nr_events)++;
2590
2591                 if (refcount_dec_and_test(&req->refs))
2592                         io_req_free_batch(&rb, req, &ctx->submit_state);
2593         }
2594
2595         io_commit_cqring(ctx);
2596         io_cqring_ev_posted_iopoll(ctx);
2597         io_req_free_batch_finish(ctx, &rb);
2598 }
2599
2600 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2601                         long min)
2602 {
2603         struct io_kiocb *req, *tmp;
2604         LIST_HEAD(done);
2605         bool spin;
2606         int ret;
2607
2608         /*
2609          * Only spin for completions if we don't have multiple devices hanging
2610          * off our complete list, and we're under the requested amount.
2611          */
2612         spin = !ctx->poll_multi_file && *nr_events < min;
2613
2614         ret = 0;
2615         list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2616                 struct kiocb *kiocb = &req->rw.kiocb;
2617
2618                 /*
2619                  * Move completed and retryable entries to our local lists.
2620                  * If we find a request that requires polling, break out
2621                  * and complete those lists first, if we have entries there.
2622                  */
2623                 if (READ_ONCE(req->iopoll_completed)) {
2624                         list_move_tail(&req->inflight_entry, &done);
2625                         continue;
2626                 }
2627                 if (!list_empty(&done))
2628                         break;
2629
2630                 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2631                 if (ret < 0)
2632                         break;
2633
2634                 /* iopoll may have completed current req */
2635                 if (READ_ONCE(req->iopoll_completed))
2636                         list_move_tail(&req->inflight_entry, &done);
2637
2638                 if (ret && spin)
2639                         spin = false;
2640                 ret = 0;
2641         }
2642
2643         if (!list_empty(&done))
2644                 io_iopoll_complete(ctx, nr_events, &done);
2645
2646         return ret;
2647 }
2648
2649 /*
2650  * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2651  * non-spinning poll check - we'll still enter the driver poll loop, but only
2652  * as a non-spinning completion check.
2653  */
2654 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2655                                 long min)
2656 {
2657         while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2658                 int ret;
2659
2660                 ret = io_do_iopoll(ctx, nr_events, min);
2661                 if (ret < 0)
2662                         return ret;
2663                 if (*nr_events >= min)
2664                         return 0;
2665         }
2666
2667         return 1;
2668 }
2669
2670 /*
2671  * We can't just wait for polled events to come to us, we have to actively
2672  * find and complete them.
2673  */
2674 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2675 {
2676         if (!(ctx->flags & IORING_SETUP_IOPOLL))
2677                 return;
2678
2679         mutex_lock(&ctx->uring_lock);
2680         while (!list_empty(&ctx->iopoll_list)) {
2681                 unsigned int nr_events = 0;
2682
2683                 io_do_iopoll(ctx, &nr_events, 0);
2684
2685                 /* let it sleep and repeat later if can't complete a request */
2686                 if (nr_events == 0)
2687                         break;
2688                 /*
2689                  * Ensure we allow local-to-the-cpu processing to take place,
2690                  * in this case we need to ensure that we reap all events.
2691                  * Also let task_work, etc. to progress by releasing the mutex
2692                  */
2693                 if (need_resched()) {
2694                         mutex_unlock(&ctx->uring_lock);
2695                         cond_resched();
2696                         mutex_lock(&ctx->uring_lock);
2697                 }
2698         }
2699         mutex_unlock(&ctx->uring_lock);
2700 }
2701
2702 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2703 {
2704         unsigned int nr_events = 0;
2705         int iters = 0, ret = 0;
2706
2707         /*
2708          * We disallow the app entering submit/complete with polling, but we
2709          * still need to lock the ring to prevent racing with polled issue
2710          * that got punted to a workqueue.
2711          */
2712         mutex_lock(&ctx->uring_lock);
2713         do {
2714                 /*
2715                  * Don't enter poll loop if we already have events pending.
2716                  * If we do, we can potentially be spinning for commands that
2717                  * already triggered a CQE (eg in error).
2718                  */
2719                 if (test_bit(0, &ctx->cq_check_overflow))
2720                         __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2721                 if (io_cqring_events(ctx))
2722                         break;
2723
2724                 /*
2725                  * If a submit got punted to a workqueue, we can have the
2726                  * application entering polling for a command before it gets
2727                  * issued. That app will hold the uring_lock for the duration
2728                  * of the poll right here, so we need to take a breather every
2729                  * now and then to ensure that the issue has a chance to add
2730                  * the poll to the issued list. Otherwise we can spin here
2731                  * forever, while the workqueue is stuck trying to acquire the
2732                  * very same mutex.
2733                  */
2734                 if (!(++iters & 7)) {
2735                         mutex_unlock(&ctx->uring_lock);
2736                         io_run_task_work();
2737                         mutex_lock(&ctx->uring_lock);
2738                 }
2739
2740                 ret = io_iopoll_getevents(ctx, &nr_events, min);
2741                 if (ret <= 0)
2742                         break;
2743                 ret = 0;
2744         } while (min && !nr_events && !need_resched());
2745
2746         mutex_unlock(&ctx->uring_lock);
2747         return ret;
2748 }
2749
2750 static void kiocb_end_write(struct io_kiocb *req)
2751 {
2752         /*
2753          * Tell lockdep we inherited freeze protection from submission
2754          * thread.
2755          */
2756         if (req->flags & REQ_F_ISREG) {
2757                 struct inode *inode = file_inode(req->file);
2758
2759                 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2760         }
2761         file_end_write(req->file);
2762 }
2763
2764 #ifdef CONFIG_BLOCK
2765 static bool io_resubmit_prep(struct io_kiocb *req)
2766 {
2767         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2768         int rw, ret;
2769         struct iov_iter iter;
2770
2771         /* already prepared */
2772         if (req->async_data)
2773                 return true;
2774
2775         switch (req->opcode) {
2776         case IORING_OP_READV:
2777         case IORING_OP_READ_FIXED:
2778         case IORING_OP_READ:
2779                 rw = READ;
2780                 break;
2781         case IORING_OP_WRITEV:
2782         case IORING_OP_WRITE_FIXED:
2783         case IORING_OP_WRITE:
2784                 rw = WRITE;
2785                 break;
2786         default:
2787                 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2788                                 req->opcode);
2789                 return false;
2790         }
2791
2792         ret = io_import_iovec(rw, req, &iovec, &iter, false);
2793         if (ret < 0)
2794                 return false;
2795         return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2796 }
2797 #endif
2798
2799 static bool io_rw_reissue(struct io_kiocb *req)
2800 {
2801 #ifdef CONFIG_BLOCK
2802         umode_t mode = file_inode(req->file)->i_mode;
2803         int ret;
2804
2805         if (!S_ISBLK(mode) && !S_ISREG(mode))
2806                 return false;
2807         if ((req->flags & REQ_F_NOWAIT) || io_wq_current_is_worker())
2808                 return false;
2809
2810         lockdep_assert_held(&req->ctx->uring_lock);
2811
2812         ret = io_sq_thread_acquire_mm_files(req->ctx, req);
2813
2814         if (!ret && io_resubmit_prep(req)) {
2815                 refcount_inc(&req->refs);
2816                 io_queue_async_work(req);
2817                 return true;
2818         }
2819         req_set_fail_links(req);
2820 #endif
2821         return false;
2822 }
2823
2824 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2825                              unsigned int issue_flags)
2826 {
2827         int cflags = 0;
2828
2829         if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_reissue(req))
2830                 return;
2831         if (res != req->result)
2832                 req_set_fail_links(req);
2833
2834         if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2835                 kiocb_end_write(req);
2836         if (req->flags & REQ_F_BUFFER_SELECTED)
2837                 cflags = io_put_rw_kbuf(req);
2838         __io_req_complete(req, issue_flags, res, cflags);
2839 }
2840
2841 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2842 {
2843         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2844
2845         __io_complete_rw(req, res, res2, 0);
2846 }
2847
2848 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2849 {
2850         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2851
2852         if (kiocb->ki_flags & IOCB_WRITE)
2853                 kiocb_end_write(req);
2854
2855         if (res != -EAGAIN && res != req->result)
2856                 req_set_fail_links(req);
2857
2858         WRITE_ONCE(req->result, res);
2859         /* order with io_poll_complete() checking ->result */
2860         smp_wmb();
2861         WRITE_ONCE(req->iopoll_completed, 1);
2862 }
2863
2864 /*
2865  * After the iocb has been issued, it's safe to be found on the poll list.
2866  * Adding the kiocb to the list AFTER submission ensures that we don't
2867  * find it from a io_iopoll_getevents() thread before the issuer is done
2868  * accessing the kiocb cookie.
2869  */
2870 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2871 {
2872         struct io_ring_ctx *ctx = req->ctx;
2873
2874         /*
2875          * Track whether we have multiple files in our lists. This will impact
2876          * how we do polling eventually, not spinning if we're on potentially
2877          * different devices.
2878          */
2879         if (list_empty(&ctx->iopoll_list)) {
2880                 ctx->poll_multi_file = false;
2881         } else if (!ctx->poll_multi_file) {
2882                 struct io_kiocb *list_req;
2883
2884                 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2885                                                 inflight_entry);
2886                 if (list_req->file != req->file)
2887                         ctx->poll_multi_file = true;
2888         }
2889
2890         /*
2891          * For fast devices, IO may have already completed. If it has, add
2892          * it to the front so we find it first.
2893          */
2894         if (READ_ONCE(req->iopoll_completed))
2895                 list_add(&req->inflight_entry, &ctx->iopoll_list);
2896         else
2897                 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2898
2899         /*
2900          * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2901          * task context or in io worker task context. If current task context is
2902          * sq thread, we don't need to check whether should wake up sq thread.
2903          */
2904         if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2905             wq_has_sleeper(&ctx->sq_data->wait))
2906                 wake_up(&ctx->sq_data->wait);
2907 }
2908
2909 static inline void io_state_file_put(struct io_submit_state *state)
2910 {
2911         if (state->file_refs) {
2912                 fput_many(state->file, state->file_refs);
2913                 state->file_refs = 0;
2914         }
2915 }
2916
2917 /*
2918  * Get as many references to a file as we have IOs left in this submission,
2919  * assuming most submissions are for one file, or at least that each file
2920  * has more than one submission.
2921  */
2922 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2923 {
2924         if (!state)
2925                 return fget(fd);
2926
2927         if (state->file_refs) {
2928                 if (state->fd == fd) {
2929                         state->file_refs--;
2930                         return state->file;
2931                 }
2932                 io_state_file_put(state);
2933         }
2934         state->file = fget_many(fd, state->ios_left);
2935         if (unlikely(!state->file))
2936                 return NULL;
2937
2938         state->fd = fd;
2939         state->file_refs = state->ios_left - 1;
2940         return state->file;
2941 }
2942
2943 static bool io_bdev_nowait(struct block_device *bdev)
2944 {
2945         return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2946 }
2947
2948 /*
2949  * If we tracked the file through the SCM inflight mechanism, we could support
2950  * any file. For now, just ensure that anything potentially problematic is done
2951  * inline.
2952  */
2953 static bool io_file_supports_async(struct file *file, int rw)
2954 {
2955         umode_t mode = file_inode(file)->i_mode;
2956
2957         if (S_ISBLK(mode)) {
2958                 if (IS_ENABLED(CONFIG_BLOCK) &&
2959                     io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2960                         return true;
2961                 return false;
2962         }
2963         if (S_ISCHR(mode) || S_ISSOCK(mode))
2964                 return true;
2965         if (S_ISREG(mode)) {
2966                 if (IS_ENABLED(CONFIG_BLOCK) &&
2967                     io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2968                     file->f_op != &io_uring_fops)
2969                         return true;
2970                 return false;
2971         }
2972
2973         /* any ->read/write should understand O_NONBLOCK */
2974         if (file->f_flags & O_NONBLOCK)
2975                 return true;
2976
2977         if (!(file->f_mode & FMODE_NOWAIT))
2978                 return false;
2979
2980         if (rw == READ)
2981                 return file->f_op->read_iter != NULL;
2982
2983         return file->f_op->write_iter != NULL;
2984 }
2985
2986 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2987 {
2988         struct io_ring_ctx *ctx = req->ctx;
2989         struct kiocb *kiocb = &req->rw.kiocb;
2990         struct file *file = req->file;
2991         unsigned ioprio;
2992         int ret;
2993
2994         if (S_ISREG(file_inode(file)->i_mode))
2995                 req->flags |= REQ_F_ISREG;
2996
2997         kiocb->ki_pos = READ_ONCE(sqe->off);
2998         if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2999                 req->flags |= REQ_F_CUR_POS;
3000                 kiocb->ki_pos = file->f_pos;
3001         }
3002         kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
3003         kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
3004         ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3005         if (unlikely(ret))
3006                 return ret;
3007
3008         /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
3009         if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
3010                 req->flags |= REQ_F_NOWAIT;
3011
3012         ioprio = READ_ONCE(sqe->ioprio);
3013         if (ioprio) {
3014                 ret = ioprio_check_cap(ioprio);
3015                 if (ret)
3016                         return ret;
3017
3018                 kiocb->ki_ioprio = ioprio;
3019         } else
3020                 kiocb->ki_ioprio = get_current_ioprio();
3021
3022         if (ctx->flags & IORING_SETUP_IOPOLL) {
3023                 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
3024                     !kiocb->ki_filp->f_op->iopoll)
3025                         return -EOPNOTSUPP;
3026
3027                 kiocb->ki_flags |= IOCB_HIPRI;
3028                 kiocb->ki_complete = io_complete_rw_iopoll;
3029                 req->iopoll_completed = 0;
3030         } else {
3031                 if (kiocb->ki_flags & IOCB_HIPRI)
3032                         return -EINVAL;
3033                 kiocb->ki_complete = io_complete_rw;
3034         }
3035
3036         req->rw.addr = READ_ONCE(sqe->addr);
3037         req->rw.len = READ_ONCE(sqe->len);
3038         req->buf_index = READ_ONCE(sqe->buf_index);
3039         return 0;
3040 }
3041
3042 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3043 {
3044         switch (ret) {
3045         case -EIOCBQUEUED:
3046                 break;
3047         case -ERESTARTSYS:
3048         case -ERESTARTNOINTR:
3049         case -ERESTARTNOHAND:
3050         case -ERESTART_RESTARTBLOCK:
3051                 /*
3052                  * We can't just restart the syscall, since previously
3053                  * submitted sqes may already be in progress. Just fail this
3054                  * IO with EINTR.
3055                  */
3056                 ret = -EINTR;
3057                 fallthrough;
3058         default:
3059                 kiocb->ki_complete(kiocb, ret, 0);
3060         }
3061 }
3062
3063 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
3064                        unsigned int issue_flags)
3065 {
3066         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3067         struct io_async_rw *io = req->async_data;
3068
3069         /* add previously done IO, if any */
3070         if (io && io->bytes_done > 0) {
3071                 if (ret < 0)
3072                         ret = io->bytes_done;
3073                 else
3074                         ret += io->bytes_done;
3075         }
3076
3077         if (req->flags & REQ_F_CUR_POS)
3078                 req->file->f_pos = kiocb->ki_pos;
3079         if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
3080                 __io_complete_rw(req, ret, 0, issue_flags);
3081         else
3082                 io_rw_done(kiocb, ret);
3083 }
3084
3085 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3086 {
3087         struct io_ring_ctx *ctx = req->ctx;
3088         size_t len = req->rw.len;
3089         struct io_mapped_ubuf *imu;
3090         u16 index, buf_index = req->buf_index;
3091         size_t offset;
3092         u64 buf_addr;
3093
3094         if (unlikely(buf_index >= ctx->nr_user_bufs))
3095                 return -EFAULT;
3096         index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3097         imu = &ctx->user_bufs[index];
3098         buf_addr = req->rw.addr;
3099
3100         /* overflow */
3101         if (buf_addr + len < buf_addr)
3102                 return -EFAULT;
3103         /* not inside the mapped region */
3104         if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
3105                 return -EFAULT;
3106
3107         /*
3108          * May not be a start of buffer, set size appropriately
3109          * and advance us to the beginning.
3110          */
3111         offset = buf_addr - imu->ubuf;
3112         iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3113
3114         if (offset) {
3115                 /*
3116                  * Don't use iov_iter_advance() here, as it's really slow for
3117                  * using the latter parts of a big fixed buffer - it iterates
3118                  * over each segment manually. We can cheat a bit here, because
3119                  * we know that:
3120                  *
3121                  * 1) it's a BVEC iter, we set it up
3122                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
3123                  *    first and last bvec
3124                  *
3125                  * So just find our index, and adjust the iterator afterwards.
3126                  * If the offset is within the first bvec (or the whole first
3127                  * bvec, just use iov_iter_advance(). This makes it easier
3128                  * since we can just skip the first segment, which may not
3129                  * be PAGE_SIZE aligned.
3130                  */
3131                 const struct bio_vec *bvec = imu->bvec;
3132
3133                 if (offset <= bvec->bv_len) {
3134                         iov_iter_advance(iter, offset);
3135                 } else {
3136                         unsigned long seg_skip;
3137
3138                         /* skip first vec */
3139                         offset -= bvec->bv_len;
3140                         seg_skip = 1 + (offset >> PAGE_SHIFT);
3141
3142                         iter->bvec = bvec + seg_skip;
3143                         iter->nr_segs -= seg_skip;
3144                         iter->count -= bvec->bv_len + offset;
3145                         iter->iov_offset = offset & ~PAGE_MASK;
3146                 }
3147         }
3148
3149         return 0;
3150 }
3151
3152 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3153 {
3154         if (needs_lock)
3155                 mutex_unlock(&ctx->uring_lock);
3156 }
3157
3158 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3159 {
3160         /*
3161          * "Normal" inline submissions always hold the uring_lock, since we
3162          * grab it from the system call. Same is true for the SQPOLL offload.
3163          * The only exception is when we've detached the request and issue it
3164          * from an async worker thread, grab the lock for that case.
3165          */
3166         if (needs_lock)
3167                 mutex_lock(&ctx->uring_lock);
3168 }
3169
3170 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3171                                           int bgid, struct io_buffer *kbuf,
3172                                           bool needs_lock)
3173 {
3174         struct io_buffer *head;
3175
3176         if (req->flags & REQ_F_BUFFER_SELECTED)
3177                 return kbuf;
3178
3179         io_ring_submit_lock(req->ctx, needs_lock);
3180
3181         lockdep_assert_held(&req->ctx->uring_lock);
3182
3183         head = idr_find(&req->ctx->io_buffer_idr, bgid);
3184         if (head) {
3185                 if (!list_empty(&head->list)) {
3186                         kbuf = list_last_entry(&head->list, struct io_buffer,
3187                                                         list);
3188                         list_del(&kbuf->list);
3189                 } else {
3190                         kbuf = head;
3191                         idr_remove(&req->ctx->io_buffer_idr, bgid);
3192                 }
3193                 if (*len > kbuf->len)
3194                         *len = kbuf->len;
3195         } else {
3196                 kbuf = ERR_PTR(-ENOBUFS);
3197         }
3198
3199         io_ring_submit_unlock(req->ctx, needs_lock);
3200
3201         return kbuf;
3202 }
3203
3204 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3205                                         bool needs_lock)
3206 {
3207         struct io_buffer *kbuf;
3208         u16 bgid;
3209
3210         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3211         bgid = req->buf_index;
3212         kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3213         if (IS_ERR(kbuf))
3214                 return kbuf;
3215         req->rw.addr = (u64) (unsigned long) kbuf;
3216         req->flags |= REQ_F_BUFFER_SELECTED;
3217         return u64_to_user_ptr(kbuf->addr);
3218 }
3219
3220 #ifdef CONFIG_COMPAT
3221 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3222                                 bool needs_lock)
3223 {
3224         struct compat_iovec __user *uiov;
3225         compat_ssize_t clen;
3226         void __user *buf;
3227         ssize_t len;
3228
3229         uiov = u64_to_user_ptr(req->rw.addr);
3230         if (!access_ok(uiov, sizeof(*uiov)))
3231                 return -EFAULT;
3232         if (__get_user(clen, &uiov->iov_len))
3233                 return -EFAULT;
3234         if (clen < 0)
3235                 return -EINVAL;
3236
3237         len = clen;
3238         buf = io_rw_buffer_select(req, &len, needs_lock);
3239         if (IS_ERR(buf))
3240                 return PTR_ERR(buf);
3241         iov[0].iov_base = buf;
3242         iov[0].iov_len = (compat_size_t) len;
3243         return 0;
3244 }
3245 #endif
3246
3247 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3248                                       bool needs_lock)
3249 {
3250         struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3251         void __user *buf;
3252         ssize_t len;
3253
3254         if (copy_from_user(iov, uiov, sizeof(*uiov)))
3255                 return -EFAULT;
3256
3257         len = iov[0].iov_len;
3258         if (len < 0)
3259                 return -EINVAL;
3260         buf = io_rw_buffer_select(req, &len, needs_lock);
3261         if (IS_ERR(buf))
3262                 return PTR_ERR(buf);
3263         iov[0].iov_base = buf;
3264         iov[0].iov_len = len;
3265         return 0;
3266 }
3267
3268 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3269                                     bool needs_lock)
3270 {
3271         if (req->flags & REQ_F_BUFFER_SELECTED) {
3272                 struct io_buffer *kbuf;
3273
3274                 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3275                 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3276                 iov[0].iov_len = kbuf->len;
3277                 return 0;
3278         }
3279         if (req->rw.len != 1)
3280                 return -EINVAL;
3281
3282 #ifdef CONFIG_COMPAT
3283         if (req->ctx->compat)
3284                 return io_compat_import(req, iov, needs_lock);
3285 #endif
3286
3287         return __io_iov_buffer_select(req, iov, needs_lock);
3288 }
3289
3290 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3291                            struct iov_iter *iter, bool needs_lock)
3292 {
3293         void __user *buf = u64_to_user_ptr(req->rw.addr);
3294         size_t sqe_len = req->rw.len;
3295         u8 opcode = req->opcode;
3296         ssize_t ret;
3297
3298         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3299                 *iovec = NULL;
3300                 return io_import_fixed(req, rw, iter);
3301         }
3302
3303         /* buffer index only valid with fixed read/write, or buffer select  */
3304         if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3305                 return -EINVAL;
3306
3307         if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3308                 if (req->flags & REQ_F_BUFFER_SELECT) {
3309                         buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3310                         if (IS_ERR(buf))
3311                                 return PTR_ERR(buf);
3312                         req->rw.len = sqe_len;
3313                 }
3314
3315                 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3316                 *iovec = NULL;
3317                 return ret;
3318         }
3319
3320         if (req->flags & REQ_F_BUFFER_SELECT) {
3321                 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3322                 if (!ret)
3323                         iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3324                 *iovec = NULL;
3325                 return ret;
3326         }
3327
3328         return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3329                               req->ctx->compat);
3330 }
3331
3332 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3333 {
3334         return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3335 }
3336
3337 /*
3338  * For files that don't have ->read_iter() and ->write_iter(), handle them
3339  * by looping over ->read() or ->write() manually.
3340  */
3341 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3342 {
3343         struct kiocb *kiocb = &req->rw.kiocb;
3344         struct file *file = req->file;
3345         ssize_t ret = 0;
3346
3347         /*
3348          * Don't support polled IO through this interface, and we can't
3349          * support non-blocking either. For the latter, this just causes
3350          * the kiocb to be handled from an async context.
3351          */
3352         if (kiocb->ki_flags & IOCB_HIPRI)
3353                 return -EOPNOTSUPP;
3354         if (kiocb->ki_flags & IOCB_NOWAIT)
3355                 return -EAGAIN;
3356
3357         while (iov_iter_count(iter)) {
3358                 struct iovec iovec;
3359                 ssize_t nr;
3360
3361                 if (!iov_iter_is_bvec(iter)) {
3362                         iovec = iov_iter_iovec(iter);
3363                 } else {
3364                         iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3365                         iovec.iov_len = req->rw.len;
3366                 }
3367
3368                 if (rw == READ) {
3369                         nr = file->f_op->read(file, iovec.iov_base,
3370                                               iovec.iov_len, io_kiocb_ppos(kiocb));
3371                 } else {
3372                         nr = file->f_op->write(file, iovec.iov_base,
3373                                                iovec.iov_len, io_kiocb_ppos(kiocb));
3374                 }
3375
3376                 if (nr < 0) {
3377                         if (!ret)
3378                                 ret = nr;
3379                         break;
3380                 }
3381                 ret += nr;
3382                 if (nr != iovec.iov_len)
3383                         break;
3384                 req->rw.len -= nr;
3385                 req->rw.addr += nr;
3386                 iov_iter_advance(iter, nr);
3387         }
3388
3389         return ret;
3390 }
3391
3392 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3393                           const struct iovec *fast_iov, struct iov_iter *iter)
3394 {
3395         struct io_async_rw *rw = req->async_data;
3396
3397         memcpy(&rw->iter, iter, sizeof(*iter));
3398         rw->free_iovec = iovec;
3399         rw->bytes_done = 0;
3400         /* can only be fixed buffers, no need to do anything */
3401         if (iov_iter_is_bvec(iter))
3402                 return;
3403         if (!iovec) {
3404                 unsigned iov_off = 0;
3405
3406                 rw->iter.iov = rw->fast_iov;
3407                 if (iter->iov != fast_iov) {
3408                         iov_off = iter->iov - fast_iov;
3409                         rw->iter.iov += iov_off;
3410                 }
3411                 if (rw->fast_iov != fast_iov)
3412                         memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3413                                sizeof(struct iovec) * iter->nr_segs);
3414         } else {
3415                 req->flags |= REQ_F_NEED_CLEANUP;
3416         }
3417 }
3418
3419 static inline int __io_alloc_async_data(struct io_kiocb *req)
3420 {
3421         WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3422         req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3423         return req->async_data == NULL;
3424 }
3425
3426 static int io_alloc_async_data(struct io_kiocb *req)
3427 {
3428         if (!io_op_defs[req->opcode].needs_async_data)
3429                 return 0;
3430
3431         return  __io_alloc_async_data(req);
3432 }
3433
3434 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3435                              const struct iovec *fast_iov,
3436                              struct iov_iter *iter, bool force)
3437 {
3438         if (!force && !io_op_defs[req->opcode].needs_async_data)
3439                 return 0;
3440         if (!req->async_data) {
3441                 if (__io_alloc_async_data(req)) {
3442                         kfree(iovec);
3443                         return -ENOMEM;
3444                 }
3445
3446                 io_req_map_rw(req, iovec, fast_iov, iter);
3447         }
3448         return 0;
3449 }
3450
3451 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3452 {
3453         struct io_async_rw *iorw = req->async_data;
3454         struct iovec *iov = iorw->fast_iov;
3455         int ret;
3456
3457         ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3458         if (unlikely(ret < 0))
3459                 return ret;
3460
3461         iorw->bytes_done = 0;
3462         iorw->free_iovec = iov;
3463         if (iov)
3464                 req->flags |= REQ_F_NEED_CLEANUP;
3465         return 0;
3466 }
3467
3468 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3469 {
3470         ssize_t ret;
3471
3472         ret = io_prep_rw(req, sqe);
3473         if (ret)
3474                 return ret;
3475
3476         if (unlikely(!(req->file->f_mode & FMODE_READ)))
3477                 return -EBADF;
3478
3479         /* either don't need iovec imported or already have it */
3480         if (!req->async_data)
3481                 return 0;
3482         return io_rw_prep_async(req, READ);
3483 }
3484
3485 /*
3486  * This is our waitqueue callback handler, registered through lock_page_async()
3487  * when we initially tried to do the IO with the iocb armed our waitqueue.
3488  * This gets called when the page is unlocked, and we generally expect that to
3489  * happen when the page IO is completed and the page is now uptodate. This will
3490  * queue a task_work based retry of the operation, attempting to copy the data
3491  * again. If the latter fails because the page was NOT uptodate, then we will
3492  * do a thread based blocking retry of the operation. That's the unexpected
3493  * slow path.
3494  */
3495 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3496                              int sync, void *arg)
3497 {
3498         struct wait_page_queue *wpq;
3499         struct io_kiocb *req = wait->private;
3500         struct wait_page_key *key = arg;
3501
3502         wpq = container_of(wait, struct wait_page_queue, wait);
3503
3504         if (!wake_page_match(wpq, key))
3505                 return 0;
3506
3507         req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3508         list_del_init(&wait->entry);
3509
3510         /* submit ref gets dropped, acquire a new one */
3511         refcount_inc(&req->refs);
3512         io_req_task_queue(req);
3513         return 1;
3514 }
3515
3516 /*
3517  * This controls whether a given IO request should be armed for async page
3518  * based retry. If we return false here, the request is handed to the async
3519  * worker threads for retry. If we're doing buffered reads on a regular file,
3520  * we prepare a private wait_page_queue entry and retry the operation. This
3521  * will either succeed because the page is now uptodate and unlocked, or it
3522  * will register a callback when the page is unlocked at IO completion. Through
3523  * that callback, io_uring uses task_work to setup a retry of the operation.
3524  * That retry will attempt the buffered read again. The retry will generally
3525  * succeed, or in rare cases where it fails, we then fall back to using the
3526  * async worker threads for a blocking retry.
3527  */
3528 static bool io_rw_should_retry(struct io_kiocb *req)
3529 {
3530         struct io_async_rw *rw = req->async_data;
3531         struct wait_page_queue *wait = &rw->wpq;
3532         struct kiocb *kiocb = &req->rw.kiocb;
3533
3534         /* never retry for NOWAIT, we just complete with -EAGAIN */
3535         if (req->flags & REQ_F_NOWAIT)
3536                 return false;
3537
3538         /* Only for buffered IO */
3539         if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3540                 return false;
3541
3542         /*
3543          * just use poll if we can, and don't attempt if the fs doesn't
3544          * support callback based unlocks
3545          */
3546         if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3547                 return false;
3548
3549         wait->wait.func = io_async_buf_func;
3550         wait->wait.private = req;
3551         wait->wait.flags = 0;
3552         INIT_LIST_HEAD(&wait->wait.entry);
3553         kiocb->ki_flags |= IOCB_WAITQ;
3554         kiocb->ki_flags &= ~IOCB_NOWAIT;
3555         kiocb->ki_waitq = wait;
3556         return true;
3557 }
3558
3559 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3560 {
3561         if (req->file->f_op->read_iter)
3562                 return call_read_iter(req->file, &req->rw.kiocb, iter);
3563         else if (req->file->f_op->read)
3564                 return loop_rw_iter(READ, req, iter);
3565         else
3566                 return -EINVAL;
3567 }
3568
3569 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3570 {
3571         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3572         struct kiocb *kiocb = &req->rw.kiocb;
3573         struct iov_iter __iter, *iter = &__iter;
3574         struct io_async_rw *rw = req->async_data;
3575         ssize_t io_size, ret, ret2;
3576         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3577
3578         if (rw) {
3579                 iter = &rw->iter;
3580                 iovec = NULL;
3581         } else {
3582                 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3583                 if (ret < 0)
3584                         return ret;
3585         }
3586         io_size = iov_iter_count(iter);
3587         req->result = io_size;
3588
3589         /* Ensure we clear previously set non-block flag */
3590         if (!force_nonblock)
3591                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3592         else
3593                 kiocb->ki_flags |= IOCB_NOWAIT;
3594
3595         /* If the file doesn't support async, just async punt */
3596         if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3597                 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3598                 return ret ?: -EAGAIN;
3599         }
3600
3601         ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3602         if (unlikely(ret)) {
3603                 kfree(iovec);
3604                 return ret;
3605         }
3606
3607         ret = io_iter_do_read(req, iter);
3608
3609         if (ret == -EIOCBQUEUED) {
3610                 /* it's faster to check here then delegate to kfree */
3611                 if (iovec)
3612                         kfree(iovec);
3613                 return 0;
3614         } else if (ret == -EAGAIN) {
3615                 /* IOPOLL retry should happen for io-wq threads */
3616                 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3617                         goto done;
3618                 /* no retry on NONBLOCK nor RWF_NOWAIT */
3619                 if (req->flags & REQ_F_NOWAIT)
3620                         goto done;
3621                 /* some cases will consume bytes even on error returns */
3622                 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3623                 ret = 0;
3624         } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3625                    (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3626                 /* read all, failed, already did sync or don't want to retry */
3627                 goto done;
3628         }
3629
3630         ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3631         if (ret2)
3632                 return ret2;
3633
3634         rw = req->async_data;
3635         /* now use our persistent iterator, if we aren't already */
3636         iter = &rw->iter;
3637
3638         do {
3639                 io_size -= ret;
3640                 rw->bytes_done += ret;
3641                 /* if we can retry, do so with the callbacks armed */
3642                 if (!io_rw_should_retry(req)) {
3643                         kiocb->ki_flags &= ~IOCB_WAITQ;
3644                         return -EAGAIN;
3645                 }
3646
3647                 /*
3648                  * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3649                  * we get -EIOCBQUEUED, then we'll get a notification when the
3650                  * desired page gets unlocked. We can also get a partial read
3651                  * here, and if we do, then just retry at the new offset.
3652                  */
3653                 ret = io_iter_do_read(req, iter);
3654                 if (ret == -EIOCBQUEUED)
3655                         return 0;
3656                 /* we got some bytes, but not all. retry. */
3657         } while (ret > 0 && ret < io_size);
3658 done:
3659         kiocb_done(kiocb, ret, issue_flags);
3660         return 0;
3661 }
3662
3663 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3664 {
3665         ssize_t ret;
3666
3667         ret = io_prep_rw(req, sqe);
3668         if (ret)
3669                 return ret;
3670
3671         if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3672                 return -EBADF;
3673
3674         /* either don't need iovec imported or already have it */
3675         if (!req->async_data)
3676                 return 0;
3677         return io_rw_prep_async(req, WRITE);
3678 }
3679
3680 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3681 {
3682         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3683         struct kiocb *kiocb = &req->rw.kiocb;
3684         struct iov_iter __iter, *iter = &__iter;
3685         struct io_async_rw *rw = req->async_data;
3686         ssize_t ret, ret2, io_size;
3687         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3688
3689         if (rw) {
3690                 iter = &rw->iter;
3691                 iovec = NULL;
3692         } else {
3693                 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3694                 if (ret < 0)
3695                         return ret;
3696         }
3697         io_size = iov_iter_count(iter);
3698         req->result = io_size;
3699
3700         /* Ensure we clear previously set non-block flag */
3701         if (!force_nonblock)
3702                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3703         else
3704                 kiocb->ki_flags |= IOCB_NOWAIT;
3705
3706         /* If the file doesn't support async, just async punt */
3707         if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3708                 goto copy_iov;
3709
3710         /* file path doesn't support NOWAIT for non-direct_IO */
3711         if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3712             (req->flags & REQ_F_ISREG))
3713                 goto copy_iov;
3714
3715         ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3716         if (unlikely(ret))
3717                 goto out_free;
3718
3719         /*
3720          * Open-code file_start_write here to grab freeze protection,
3721          * which will be released by another thread in
3722          * io_complete_rw().  Fool lockdep by telling it the lock got
3723          * released so that it doesn't complain about the held lock when
3724          * we return to userspace.
3725          */
3726         if (req->flags & REQ_F_ISREG) {
3727                 sb_start_write(file_inode(req->file)->i_sb);
3728                 __sb_writers_release(file_inode(req->file)->i_sb,
3729                                         SB_FREEZE_WRITE);
3730         }
3731         kiocb->ki_flags |= IOCB_WRITE;
3732
3733         if (req->file->f_op->write_iter)
3734                 ret2 = call_write_iter(req->file, kiocb, iter);
3735         else if (req->file->f_op->write)
3736                 ret2 = loop_rw_iter(WRITE, req, iter);
3737         else
3738                 ret2 = -EINVAL;
3739
3740         /*
3741          * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3742          * retry them without IOCB_NOWAIT.
3743          */
3744         if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3745                 ret2 = -EAGAIN;
3746         /* no retry on NONBLOCK nor RWF_NOWAIT */
3747         if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3748                 goto done;
3749         if (!force_nonblock || ret2 != -EAGAIN) {
3750                 /* IOPOLL retry should happen for io-wq threads */
3751                 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3752                         goto copy_iov;
3753 done:
3754                 kiocb_done(kiocb, ret2, issue_flags);
3755         } else {
3756 copy_iov:
3757                 /* some cases will consume bytes even on error returns */
3758                 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3759                 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3760                 return ret ?: -EAGAIN;
3761         }
3762 out_free:
3763         /* it's reportedly faster than delegating the null check to kfree() */
3764         if (iovec)
3765                 kfree(iovec);
3766         return ret;
3767 }
3768
3769 static int io_renameat_prep(struct io_kiocb *req,
3770                             const struct io_uring_sqe *sqe)
3771 {
3772         struct io_rename *ren = &req->rename;
3773         const char __user *oldf, *newf;
3774
3775         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3776                 return -EBADF;
3777
3778         ren->old_dfd = READ_ONCE(sqe->fd);
3779         oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3780         newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3781         ren->new_dfd = READ_ONCE(sqe->len);
3782         ren->flags = READ_ONCE(sqe->rename_flags);
3783
3784         ren->oldpath = getname(oldf);
3785         if (IS_ERR(ren->oldpath))
3786                 return PTR_ERR(ren->oldpath);
3787
3788         ren->newpath = getname(newf);
3789         if (IS_ERR(ren->newpath)) {
3790                 putname(ren->oldpath);
3791                 return PTR_ERR(ren->newpath);
3792         }
3793
3794         req->flags |= REQ_F_NEED_CLEANUP;
3795         return 0;
3796 }
3797
3798 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3799 {
3800         struct io_rename *ren = &req->rename;
3801         int ret;
3802
3803         if (issue_flags & IO_URING_F_NONBLOCK)
3804                 return -EAGAIN;
3805
3806         ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3807                                 ren->newpath, ren->flags);
3808
3809         req->flags &= ~REQ_F_NEED_CLEANUP;
3810         if (ret < 0)
3811                 req_set_fail_links(req);
3812         io_req_complete(req, ret);
3813         return 0;
3814 }
3815
3816 static int io_unlinkat_prep(struct io_kiocb *req,
3817                             const struct io_uring_sqe *sqe)
3818 {
3819         struct io_unlink *un = &req->unlink;
3820         const char __user *fname;
3821
3822         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3823                 return -EBADF;
3824
3825         un->dfd = READ_ONCE(sqe->fd);
3826
3827         un->flags = READ_ONCE(sqe->unlink_flags);
3828         if (un->flags & ~AT_REMOVEDIR)
3829                 return -EINVAL;
3830
3831         fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3832         un->filename = getname(fname);
3833         if (IS_ERR(un->filename))
3834                 return PTR_ERR(un->filename);
3835
3836         req->flags |= REQ_F_NEED_CLEANUP;
3837         return 0;
3838 }
3839
3840 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3841 {
3842         struct io_unlink *un = &req->unlink;
3843         int ret;
3844
3845         if (issue_flags & IO_URING_F_NONBLOCK)
3846                 return -EAGAIN;
3847
3848         if (un->flags & AT_REMOVEDIR)
3849                 ret = do_rmdir(un->dfd, un->filename);
3850         else
3851                 ret = do_unlinkat(un->dfd, un->filename);
3852
3853         req->flags &= ~REQ_F_NEED_CLEANUP;
3854         if (ret < 0)
3855                 req_set_fail_links(req);
3856         io_req_complete(req, ret);
3857         return 0;
3858 }
3859
3860 static int io_shutdown_prep(struct io_kiocb *req,
3861                             const struct io_uring_sqe *sqe)
3862 {
3863 #if defined(CONFIG_NET)
3864         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3865                 return -EINVAL;
3866         if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3867             sqe->buf_index)
3868                 return -EINVAL;
3869
3870         req->shutdown.how = READ_ONCE(sqe->len);
3871         return 0;
3872 #else
3873         return -EOPNOTSUPP;
3874 #endif
3875 }
3876
3877 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3878 {
3879 #if defined(CONFIG_NET)
3880         struct socket *sock;
3881         int ret;
3882
3883         if (issue_flags & IO_URING_F_NONBLOCK)
3884                 return -EAGAIN;
3885
3886         sock = sock_from_file(req->file);
3887         if (unlikely(!sock))
3888                 return -ENOTSOCK;
3889
3890         ret = __sys_shutdown_sock(sock, req->shutdown.how);
3891         if (ret < 0)
3892                 req_set_fail_links(req);
3893         io_req_complete(req, ret);
3894         return 0;
3895 #else
3896         return -EOPNOTSUPP;
3897 #endif
3898 }
3899
3900 static int __io_splice_prep(struct io_kiocb *req,
3901                             const struct io_uring_sqe *sqe)
3902 {
3903         struct io_splice* sp = &req->splice;
3904         unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3905
3906         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3907                 return -EINVAL;
3908
3909         sp->file_in = NULL;
3910         sp->len = READ_ONCE(sqe->len);
3911         sp->flags = READ_ONCE(sqe->splice_flags);
3912
3913         if (unlikely(sp->flags & ~valid_flags))
3914                 return -EINVAL;
3915
3916         sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3917                                   (sp->flags & SPLICE_F_FD_IN_FIXED));
3918         if (!sp->file_in)
3919                 return -EBADF;
3920         req->flags |= REQ_F_NEED_CLEANUP;
3921
3922         if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3923                 /*
3924                  * Splice operation will be punted aync, and here need to
3925                  * modify io_wq_work.flags, so initialize io_wq_work firstly.
3926                  */
3927                 io_req_init_async(req);
3928                 req->work.flags |= IO_WQ_WORK_UNBOUND;
3929         }
3930
3931         return 0;
3932 }
3933
3934 static int io_tee_prep(struct io_kiocb *req,
3935                        const struct io_uring_sqe *sqe)
3936 {
3937         if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3938                 return -EINVAL;
3939         return __io_splice_prep(req, sqe);
3940 }
3941
3942 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3943 {
3944         struct io_splice *sp = &req->splice;
3945         struct file *in = sp->file_in;
3946         struct file *out = sp->file_out;
3947         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3948         long ret = 0;
3949
3950         if (issue_flags & IO_URING_F_NONBLOCK)
3951                 return -EAGAIN;
3952         if (sp->len)
3953                 ret = do_tee(in, out, sp->len, flags);
3954
3955         io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3956         req->flags &= ~REQ_F_NEED_CLEANUP;
3957
3958         if (ret != sp->len)
3959                 req_set_fail_links(req);
3960         io_req_complete(req, ret);
3961         return 0;
3962 }
3963
3964 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3965 {
3966         struct io_splice* sp = &req->splice;
3967
3968         sp->off_in = READ_ONCE(sqe->splice_off_in);
3969         sp->off_out = READ_ONCE(sqe->off);
3970         return __io_splice_prep(req, sqe);
3971 }
3972
3973 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3974 {
3975         struct io_splice *sp = &req->splice;
3976         struct file *in = sp->file_in;
3977         struct file *out = sp->file_out;
3978         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3979         loff_t *poff_in, *poff_out;
3980         long ret = 0;
3981
3982         if (issue_flags & IO_URING_F_NONBLOCK)
3983                 return -EAGAIN;
3984
3985         poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3986         poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3987
3988         if (sp->len)
3989                 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3990
3991         io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3992         req->flags &= ~REQ_F_NEED_CLEANUP;
3993
3994         if (ret != sp->len)
3995                 req_set_fail_links(req);
3996         io_req_complete(req, ret);
3997         return 0;
3998 }
3999
4000 /*
4001  * IORING_OP_NOP just posts a completion event, nothing else.
4002  */
4003 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4004 {
4005         struct io_ring_ctx *ctx = req->ctx;
4006
4007         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4008                 return -EINVAL;
4009
4010         __io_req_complete(req, issue_flags, 0, 0);
4011         return 0;
4012 }
4013
4014 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4015 {
4016         struct io_ring_ctx *ctx = req->ctx;
4017
4018         if (!req->file)
4019                 return -EBADF;
4020
4021         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4022                 return -EINVAL;
4023         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4024                 return -EINVAL;
4025
4026         req->sync.flags = READ_ONCE(sqe->fsync_flags);
4027         if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4028                 return -EINVAL;
4029
4030         req->sync.off = READ_ONCE(sqe->off);
4031         req->sync.len = READ_ONCE(sqe->len);
4032         return 0;
4033 }
4034
4035 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4036 {
4037         loff_t end = req->sync.off + req->sync.len;
4038         int ret;
4039
4040         /* fsync always requires a blocking context */
4041         if (issue_flags & IO_URING_F_NONBLOCK)
4042                 return -EAGAIN;
4043
4044         ret = vfs_fsync_range(req->file, req->sync.off,
4045                                 end > 0 ? end : LLONG_MAX,
4046                                 req->sync.flags & IORING_FSYNC_DATASYNC);
4047         if (ret < 0)
4048                 req_set_fail_links(req);
4049         io_req_complete(req, ret);
4050         return 0;
4051 }
4052
4053 static int io_fallocate_prep(struct io_kiocb *req,
4054                              const struct io_uring_sqe *sqe)
4055 {
4056         if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
4057                 return -EINVAL;
4058         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4059                 return -EINVAL;
4060
4061         req->sync.off = READ_ONCE(sqe->off);
4062         req->sync.len = READ_ONCE(sqe->addr);
4063         req->sync.mode = READ_ONCE(sqe->len);
4064         return 0;
4065 }
4066
4067 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4068 {
4069         int ret;
4070
4071         /* fallocate always requiring blocking context */
4072         if (issue_flags & IO_URING_F_NONBLOCK)
4073                 return -EAGAIN;
4074         ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4075                                 req->sync.len);
4076         if (ret < 0)
4077                 req_set_fail_links(req);
4078         io_req_complete(req, ret);
4079         return 0;
4080 }
4081
4082 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4083 {
4084         const char __user *fname;
4085         int ret;
4086
4087         if (unlikely(sqe->ioprio || sqe->buf_index))
4088                 return -EINVAL;
4089         if (unlikely(req->flags & REQ_F_FIXED_FILE))
4090                 return -EBADF;
4091
4092         /* open.how should be already initialised */
4093         if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4094                 req->open.how.flags |= O_LARGEFILE;
4095
4096         req->open.dfd = READ_ONCE(sqe->fd);
4097         fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4098         req->open.filename = getname(fname);
4099         if (IS_ERR(req->open.filename)) {
4100                 ret = PTR_ERR(req->open.filename);
4101                 req->open.filename = NULL;
4102                 return ret;
4103         }
4104         req->open.nofile = rlimit(RLIMIT_NOFILE);
4105         req->flags |= REQ_F_NEED_CLEANUP;
4106         return 0;
4107 }
4108
4109 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4110 {
4111         u64 flags, mode;
4112
4113         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4114                 return -EINVAL;
4115         mode = READ_ONCE(sqe->len);
4116         flags = READ_ONCE(sqe->open_flags);
4117         req->open.how = build_open_how(flags, mode);
4118         return __io_openat_prep(req, sqe);
4119 }
4120
4121 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4122 {
4123         struct open_how __user *how;
4124         size_t len;
4125         int ret;
4126
4127         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4128                 return -EINVAL;
4129         how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4130         len = READ_ONCE(sqe->len);
4131         if (len < OPEN_HOW_SIZE_VER0)
4132                 return -EINVAL;
4133
4134         ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4135                                         len);
4136         if (ret)
4137                 return ret;
4138
4139         return __io_openat_prep(req, sqe);
4140 }
4141
4142 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4143 {
4144         struct open_flags op;
4145         struct file *file;
4146         bool nonblock_set;
4147         bool resolve_nonblock;
4148         int ret;
4149
4150         ret = build_open_flags(&req->open.how, &op);
4151         if (ret)
4152                 goto err;
4153         nonblock_set = op.open_flag & O_NONBLOCK;
4154         resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4155         if (issue_flags & IO_URING_F_NONBLOCK) {
4156                 /*
4157                  * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4158                  * it'll always -EAGAIN
4159                  */
4160                 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4161                         return -EAGAIN;
4162                 op.lookup_flags |= LOOKUP_CACHED;
4163                 op.open_flag |= O_NONBLOCK;
4164         }
4165
4166         ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4167         if (ret < 0)
4168                 goto err;
4169
4170         file = do_filp_open(req->open.dfd, req->open.filename, &op);
4171         /* only retry if RESOLVE_CACHED wasn't already set by application */
4172         if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
4173             file == ERR_PTR(-EAGAIN)) {
4174                 /*
4175                  * We could hang on to this 'fd', but seems like marginal
4176                  * gain for something that is now known to be a slower path.
4177                  * So just put it, and we'll get a new one when we retry.
4178                  */
4179                 put_unused_fd(ret);
4180                 return -EAGAIN;
4181         }
4182
4183         if (IS_ERR(file)) {
4184                 put_unused_fd(ret);
4185                 ret = PTR_ERR(file);
4186         } else {
4187                 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4188                         file->f_flags &= ~O_NONBLOCK;
4189                 fsnotify_open(file);
4190                 fd_install(ret, file);
4191         }
4192 err:
4193         putname(req->open.filename);
4194         req->flags &= ~REQ_F_NEED_CLEANUP;
4195         if (ret < 0)
4196                 req_set_fail_links(req);
4197         io_req_complete(req, ret);
4198         return 0;
4199 }
4200
4201 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4202 {
4203         return io_openat2(req, issue_flags & IO_URING_F_NONBLOCK);
4204 }
4205
4206 static int io_remove_buffers_prep(struct io_kiocb *req,
4207                                   const struct io_uring_sqe *sqe)
4208 {
4209         struct io_provide_buf *p = &req->pbuf;
4210         u64 tmp;
4211
4212         if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
4213                 return -EINVAL;
4214
4215         tmp = READ_ONCE(sqe->fd);
4216         if (!tmp || tmp > USHRT_MAX)
4217                 return -EINVAL;
4218
4219         memset(p, 0, sizeof(*p));
4220         p->nbufs = tmp;
4221         p->bgid = READ_ONCE(sqe->buf_group);
4222         return 0;
4223 }
4224
4225 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4226                                int bgid, unsigned nbufs)
4227 {
4228         unsigned i = 0;
4229
4230         /* shouldn't happen */
4231         if (!nbufs)
4232                 return 0;
4233
4234         /* the head kbuf is the list itself */
4235         while (!list_empty(&buf->list)) {
4236                 struct io_buffer *nxt;
4237
4238                 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4239                 list_del(&nxt->list);
4240                 kfree(nxt);
4241                 if (++i == nbufs)
4242                         return i;
4243         }
4244         i++;
4245         kfree(buf);
4246         idr_remove(&ctx->io_buffer_idr, bgid);
4247
4248         return i;
4249 }
4250
4251 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4252 {
4253         struct io_provide_buf *p = &req->pbuf;
4254         struct io_ring_ctx *ctx = req->ctx;
4255         struct io_buffer *head;
4256         int ret = 0;
4257         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4258
4259         io_ring_submit_lock(ctx, !force_nonblock);
4260
4261         lockdep_assert_held(&ctx->uring_lock);
4262
4263         ret = -ENOENT;
4264         head = idr_find(&ctx->io_buffer_idr, p->bgid);
4265         if (head)
4266                 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4267         if (ret < 0)
4268                 req_set_fail_links(req);
4269
4270         /* need to hold the lock to complete IOPOLL requests */
4271         if (ctx->flags & IORING_SETUP_IOPOLL) {
4272                 __io_req_complete(req, issue_flags, ret, 0);
4273                 io_ring_submit_unlock(ctx, !force_nonblock);
4274         } else {
4275                 io_ring_submit_unlock(ctx, !force_nonblock);
4276                 __io_req_complete(req, issue_flags, ret, 0);
4277         }
4278         return 0;
4279 }
4280
4281 static int io_provide_buffers_prep(struct io_kiocb *req,
4282                                    const struct io_uring_sqe *sqe)
4283 {
4284         struct io_provide_buf *p = &req->pbuf;
4285         u64 tmp;
4286
4287         if (sqe->ioprio || sqe->rw_flags)
4288                 return -EINVAL;
4289
4290         tmp = READ_ONCE(sqe->fd);
4291         if (!tmp || tmp > USHRT_MAX)
4292                 return -E2BIG;
4293         p->nbufs = tmp;
4294         p->addr = READ_ONCE(sqe->addr);
4295         p->len = READ_ONCE(sqe->len);
4296
4297         if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
4298                 return -EFAULT;
4299
4300         p->bgid = READ_ONCE(sqe->buf_group);
4301         tmp = READ_ONCE(sqe->off);
4302         if (tmp > USHRT_MAX)
4303                 return -E2BIG;
4304         p->bid = tmp;
4305         return 0;
4306 }
4307
4308 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4309 {
4310         struct io_buffer *buf;
4311         u64 addr = pbuf->addr;
4312         int i, bid = pbuf->bid;
4313
4314         for (i = 0; i < pbuf->nbufs; i++) {
4315                 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4316                 if (!buf)
4317                         break;
4318
4319                 buf->addr = addr;
4320                 buf->len = pbuf->len;
4321                 buf->bid = bid;
4322                 addr += pbuf->len;
4323                 bid++;
4324                 if (!*head) {
4325                         INIT_LIST_HEAD(&buf->list);
4326                         *head = buf;
4327                 } else {
4328                         list_add_tail(&buf->list, &(*head)->list);
4329                 }
4330         }
4331
4332         return i ? i : -ENOMEM;
4333 }
4334
4335 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4336 {
4337         struct io_provide_buf *p = &req->pbuf;
4338         struct io_ring_ctx *ctx = req->ctx;
4339         struct io_buffer *head, *list;
4340         int ret = 0;
4341         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4342
4343         io_ring_submit_lock(ctx, !force_nonblock);
4344
4345         lockdep_assert_held(&ctx->uring_lock);
4346
4347         list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4348
4349         ret = io_add_buffers(p, &head);
4350         if (ret < 0)
4351                 goto out;
4352
4353         if (!list) {
4354                 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4355                                         GFP_KERNEL);
4356                 if (ret < 0) {
4357                         __io_remove_buffers(ctx, head, p->bgid, -1U);
4358                         goto out;
4359                 }
4360         }
4361 out:
4362         if (ret < 0)
4363                 req_set_fail_links(req);
4364
4365         /* need to hold the lock to complete IOPOLL requests */
4366         if (ctx->flags & IORING_SETUP_IOPOLL) {
4367                 __io_req_complete(req, issue_flags, ret, 0);
4368                 io_ring_submit_unlock(ctx, !force_nonblock);
4369         } else {
4370                 io_ring_submit_unlock(ctx, !force_nonblock);
4371                 __io_req_complete(req, issue_flags, ret, 0);
4372         }
4373         return 0;
4374 }
4375
4376 static int io_epoll_ctl_prep(struct io_kiocb *req,
4377                              const struct io_uring_sqe *sqe)
4378 {
4379 #if defined(CONFIG_EPOLL)
4380         if (sqe->ioprio || sqe->buf_index)
4381                 return -EINVAL;
4382         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4383                 return -EINVAL;
4384
4385         req->epoll.epfd = READ_ONCE(sqe->fd);
4386         req->epoll.op = READ_ONCE(sqe->len);
4387         req->epoll.fd = READ_ONCE(sqe->off);
4388
4389         if (ep_op_has_event(req->epoll.op)) {
4390                 struct epoll_event __user *ev;
4391
4392                 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4393                 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4394                         return -EFAULT;
4395         }
4396
4397         return 0;
4398 #else
4399         return -EOPNOTSUPP;
4400 #endif
4401 }
4402
4403 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4404 {
4405 #if defined(CONFIG_EPOLL)
4406         struct io_epoll *ie = &req->epoll;
4407         int ret;
4408         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4409
4410         ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4411         if (force_nonblock && ret == -EAGAIN)
4412                 return -EAGAIN;
4413
4414         if (ret < 0)
4415                 req_set_fail_links(req);
4416         __io_req_complete(req, issue_flags, ret, 0);
4417         return 0;
4418 #else
4419         return -EOPNOTSUPP;
4420 #endif
4421 }
4422
4423 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4424 {
4425 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4426         if (sqe->ioprio || sqe->buf_index || sqe->off)
4427                 return -EINVAL;
4428         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4429                 return -EINVAL;
4430
4431         req->madvise.addr = READ_ONCE(sqe->addr);
4432         req->madvise.len = READ_ONCE(sqe->len);
4433         req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4434         return 0;
4435 #else
4436         return -EOPNOTSUPP;
4437 #endif
4438 }
4439
4440 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4441 {
4442 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4443         struct io_madvise *ma = &req->madvise;
4444         int ret;
4445
4446         if (issue_flags & IO_URING_F_NONBLOCK)
4447                 return -EAGAIN;
4448
4449         ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4450         if (ret < 0)
4451                 req_set_fail_links(req);
4452         io_req_complete(req, ret);
4453         return 0;
4454 #else
4455         return -EOPNOTSUPP;
4456 #endif
4457 }
4458
4459 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4460 {
4461         if (sqe->ioprio || sqe->buf_index || sqe->addr)
4462                 return -EINVAL;
4463         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4464                 return -EINVAL;
4465
4466         req->fadvise.offset = READ_ONCE(sqe->off);
4467         req->fadvise.len = READ_ONCE(sqe->len);
4468         req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4469         return 0;
4470 }
4471
4472 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4473 {
4474         struct io_fadvise *fa = &req->fadvise;
4475         int ret;
4476
4477         if (issue_flags & IO_URING_F_NONBLOCK) {
4478                 switch (fa->advice) {
4479                 case POSIX_FADV_NORMAL:
4480                 case POSIX_FADV_RANDOM:
4481                 case POSIX_FADV_SEQUENTIAL:
4482                         break;
4483                 default:
4484                         return -EAGAIN;
4485                 }
4486         }
4487
4488         ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4489         if (ret < 0)
4490                 req_set_fail_links(req);
4491         io_req_complete(req, ret);
4492         return 0;
4493 }
4494
4495 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4496 {
4497         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4498                 return -EINVAL;
4499         if (sqe->ioprio || sqe->buf_index)
4500                 return -EINVAL;
4501         if (req->flags & REQ_F_FIXED_FILE)
4502                 return -EBADF;
4503
4504         req->statx.dfd = READ_ONCE(sqe->fd);
4505         req->statx.mask = READ_ONCE(sqe->len);
4506         req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4507         req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4508         req->statx.flags = READ_ONCE(sqe->statx_flags);
4509
4510         return 0;
4511 }
4512
4513 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4514 {
4515         struct io_statx *ctx = &req->statx;
4516         int ret;
4517
4518         if (issue_flags & IO_URING_F_NONBLOCK) {
4519                 /* only need file table for an actual valid fd */
4520                 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4521                         req->flags |= REQ_F_NO_FILE_TABLE;
4522                 return -EAGAIN;
4523         }
4524
4525         ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4526                        ctx->buffer);
4527
4528         if (ret < 0)
4529                 req_set_fail_links(req);
4530         io_req_complete(req, ret);
4531         return 0;
4532 }
4533
4534 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4535 {
4536         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4537                 return -EINVAL;
4538         if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4539             sqe->rw_flags || sqe->buf_index)
4540                 return -EINVAL;
4541         if (req->flags & REQ_F_FIXED_FILE)
4542                 return -EBADF;
4543
4544         req->close.fd = READ_ONCE(sqe->fd);
4545         return 0;
4546 }
4547
4548 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4549 {
4550         struct files_struct *files = current->files;
4551         struct io_close *close = &req->close;
4552         struct fdtable *fdt;
4553         struct file *file;
4554         int ret;
4555
4556         file = NULL;
4557         ret = -EBADF;
4558         spin_lock(&files->file_lock);
4559         fdt = files_fdtable(files);
4560         if (close->fd >= fdt->max_fds) {
4561                 spin_unlock(&files->file_lock);
4562                 goto err;
4563         }
4564         file = fdt->fd[close->fd];
4565         if (!file) {
4566                 spin_unlock(&files->file_lock);
4567                 goto err;
4568         }
4569
4570         if (file->f_op == &io_uring_fops) {
4571                 spin_unlock(&files->file_lock);
4572                 file = NULL;
4573                 goto err;
4574         }
4575
4576         /* if the file has a flush method, be safe and punt to async */
4577         if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4578                 spin_unlock(&files->file_lock);
4579                 return -EAGAIN;
4580         }
4581
4582         ret = __close_fd_get_file(close->fd, &file);
4583         spin_unlock(&files->file_lock);
4584         if (ret < 0) {
4585                 if (ret == -ENOENT)
4586                         ret = -EBADF;
4587                 goto err;
4588         }
4589
4590         /* No ->flush() or already async, safely close from here */
4591         ret = filp_close(file, current->files);
4592 err:
4593         if (ret < 0)
4594                 req_set_fail_links(req);
4595         if (file)
4596                 fput(file);
4597         __io_req_complete(req, issue_flags, ret, 0);
4598         return 0;
4599 }
4600
4601 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4602 {
4603         struct io_ring_ctx *ctx = req->ctx;
4604
4605         if (!req->file)
4606                 return -EBADF;
4607
4608         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4609                 return -EINVAL;
4610         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4611                 return -EINVAL;
4612
4613         req->sync.off = READ_ONCE(sqe->off);
4614         req->sync.len = READ_ONCE(sqe->len);
4615         req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4616         return 0;
4617 }
4618
4619 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4620 {
4621         int ret;
4622
4623         /* sync_file_range always requires a blocking context */
4624         if (issue_flags & IO_URING_F_NONBLOCK)
4625                 return -EAGAIN;
4626
4627         ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4628                                 req->sync.flags);
4629         if (ret < 0)
4630                 req_set_fail_links(req);
4631         io_req_complete(req, ret);
4632         return 0;
4633 }
4634
4635 #if defined(CONFIG_NET)
4636 static int io_setup_async_msg(struct io_kiocb *req,
4637                               struct io_async_msghdr *kmsg)
4638 {
4639         struct io_async_msghdr *async_msg = req->async_data;
4640
4641         if (async_msg)
4642                 return -EAGAIN;
4643         if (io_alloc_async_data(req)) {
4644                 kfree(kmsg->free_iov);
4645                 return -ENOMEM;
4646         }
4647         async_msg = req->async_data;
4648         req->flags |= REQ_F_NEED_CLEANUP;
4649         memcpy(async_msg, kmsg, sizeof(*kmsg));
4650         async_msg->msg.msg_name = &async_msg->addr;
4651         /* if were using fast_iov, set it to the new one */
4652         if (!async_msg->free_iov)
4653                 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4654
4655         return -EAGAIN;
4656 }
4657
4658 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4659                                struct io_async_msghdr *iomsg)
4660 {
4661         iomsg->msg.msg_name = &iomsg->addr;
4662         iomsg->free_iov = iomsg->fast_iov;
4663         return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4664                                    req->sr_msg.msg_flags, &iomsg->free_iov);
4665 }
4666
4667 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4668 {
4669         struct io_async_msghdr *async_msg = req->async_data;
4670         struct io_sr_msg *sr = &req->sr_msg;
4671         int ret;
4672
4673         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4674                 return -EINVAL;
4675
4676         sr->msg_flags = READ_ONCE(sqe->msg_flags);
4677         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4678         sr->len = READ_ONCE(sqe->len);
4679
4680 #ifdef CONFIG_COMPAT
4681         if (req->ctx->compat)
4682                 sr->msg_flags |= MSG_CMSG_COMPAT;
4683 #endif
4684
4685         if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4686                 return 0;
4687         ret = io_sendmsg_copy_hdr(req, async_msg);
4688         if (!ret)
4689                 req->flags |= REQ_F_NEED_CLEANUP;
4690         return ret;
4691 }
4692
4693 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4694 {
4695         struct io_async_msghdr iomsg, *kmsg;
4696         struct socket *sock;
4697         unsigned flags;
4698         int ret;
4699
4700         sock = sock_from_file(req->file);
4701         if (unlikely(!sock))
4702                 return -ENOTSOCK;
4703
4704         kmsg = req->async_data;
4705         if (!kmsg) {
4706                 ret = io_sendmsg_copy_hdr(req, &iomsg);
4707                 if (ret)
4708                         return ret;
4709                 kmsg = &iomsg;
4710         }
4711
4712         flags = req->sr_msg.msg_flags;
4713         if (flags & MSG_DONTWAIT)
4714                 req->flags |= REQ_F_NOWAIT;
4715         else if (issue_flags & IO_URING_F_NONBLOCK)
4716                 flags |= MSG_DONTWAIT;
4717
4718         ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4719         if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4720                 return io_setup_async_msg(req, kmsg);
4721         if (ret == -ERESTARTSYS)
4722                 ret = -EINTR;
4723
4724         /* fast path, check for non-NULL to avoid function call */
4725         if (kmsg->free_iov)
4726                 kfree(kmsg->free_iov);
4727         req->flags &= ~REQ_F_NEED_CLEANUP;
4728         if (ret < 0)
4729                 req_set_fail_links(req);
4730         __io_req_complete(req, issue_flags, ret, 0);
4731         return 0;
4732 }
4733
4734 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4735 {
4736         struct io_sr_msg *sr = &req->sr_msg;
4737         struct msghdr msg;
4738         struct iovec iov;
4739         struct socket *sock;
4740         unsigned flags;
4741         int ret;
4742
4743         sock = sock_from_file(req->file);
4744         if (unlikely(!sock))
4745                 return -ENOTSOCK;
4746
4747         ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4748         if (unlikely(ret))
4749                 return ret;
4750
4751         msg.msg_name = NULL;
4752         msg.msg_control = NULL;
4753         msg.msg_controllen = 0;
4754         msg.msg_namelen = 0;
4755
4756         flags = req->sr_msg.msg_flags;
4757         if (flags & MSG_DONTWAIT)
4758                 req->flags |= REQ_F_NOWAIT;
4759         else if (issue_flags & IO_URING_F_NONBLOCK)
4760                 flags |= MSG_DONTWAIT;
4761
4762         msg.msg_flags = flags;
4763         ret = sock_sendmsg(sock, &msg);
4764         if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4765                 return -EAGAIN;
4766         if (ret == -ERESTARTSYS)
4767                 ret = -EINTR;
4768
4769         if (ret < 0)
4770                 req_set_fail_links(req);
4771         __io_req_complete(req, issue_flags, ret, 0);
4772         return 0;
4773 }
4774
4775 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4776                                  struct io_async_msghdr *iomsg)
4777 {
4778         struct io_sr_msg *sr = &req->sr_msg;
4779         struct iovec __user *uiov;
4780         size_t iov_len;
4781         int ret;
4782
4783         ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4784                                         &iomsg->uaddr, &uiov, &iov_len);
4785         if (ret)
4786                 return ret;
4787
4788         if (req->flags & REQ_F_BUFFER_SELECT) {
4789                 if (iov_len > 1)
4790                         return -EINVAL;
4791                 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4792                         return -EFAULT;
4793                 sr->len = iomsg->fast_iov[0].iov_len;
4794                 iomsg->free_iov = NULL;
4795         } else {
4796                 iomsg->free_iov = iomsg->fast_iov;
4797                 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4798                                      &iomsg->free_iov, &iomsg->msg.msg_iter,
4799                                      false);
4800                 if (ret > 0)
4801                         ret = 0;
4802         }
4803
4804         return ret;
4805 }
4806
4807 #ifdef CONFIG_COMPAT
4808 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4809                                         struct io_async_msghdr *iomsg)
4810 {
4811         struct compat_msghdr __user *msg_compat;
4812         struct io_sr_msg *sr = &req->sr_msg;
4813         struct compat_iovec __user *uiov;
4814         compat_uptr_t ptr;
4815         compat_size_t len;
4816         int ret;
4817
4818         msg_compat = (struct compat_msghdr __user *) sr->umsg;
4819         ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4820                                         &ptr, &len);
4821         if (ret)
4822                 return ret;
4823
4824         uiov = compat_ptr(ptr);
4825         if (req->flags & REQ_F_BUFFER_SELECT) {
4826                 compat_ssize_t clen;
4827
4828                 if (len > 1)
4829                         return -EINVAL;
4830                 if (!access_ok(uiov, sizeof(*uiov)))
4831                         return -EFAULT;
4832                 if (__get_user(clen, &uiov->iov_len))
4833                         return -EFAULT;
4834                 if (clen < 0)
4835                         return -EINVAL;
4836                 sr->len = clen;
4837                 iomsg->free_iov = NULL;
4838         } else {
4839                 iomsg->free_iov = iomsg->fast_iov;
4840                 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4841                                    UIO_FASTIOV, &iomsg->free_iov,
4842                                    &iomsg->msg.msg_iter, true);
4843                 if (ret < 0)
4844                         return ret;
4845         }
4846
4847         return 0;
4848 }
4849 #endif
4850
4851 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4852                                struct io_async_msghdr *iomsg)
4853 {
4854         iomsg->msg.msg_name = &iomsg->addr;
4855
4856 #ifdef CONFIG_COMPAT
4857         if (req->ctx->compat)
4858                 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4859 #endif
4860
4861         return __io_recvmsg_copy_hdr(req, iomsg);
4862 }
4863
4864 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4865                                                bool needs_lock)
4866 {
4867         struct io_sr_msg *sr = &req->sr_msg;
4868         struct io_buffer *kbuf;
4869
4870         kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4871         if (IS_ERR(kbuf))
4872                 return kbuf;
4873
4874         sr->kbuf = kbuf;
4875         req->flags |= REQ_F_BUFFER_SELECTED;
4876         return kbuf;
4877 }
4878
4879 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4880 {
4881         return io_put_kbuf(req, req->sr_msg.kbuf);
4882 }
4883
4884 static int io_recvmsg_prep(struct io_kiocb *req,
4885                            const struct io_uring_sqe *sqe)
4886 {
4887         struct io_async_msghdr *async_msg = req->async_data;
4888         struct io_sr_msg *sr = &req->sr_msg;
4889         int ret;
4890
4891         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4892                 return -EINVAL;
4893
4894         sr->msg_flags = READ_ONCE(sqe->msg_flags);
4895         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4896         sr->len = READ_ONCE(sqe->len);
4897         sr->bgid = READ_ONCE(sqe->buf_group);
4898
4899 #ifdef CONFIG_COMPAT
4900         if (req->ctx->compat)
4901                 sr->msg_flags |= MSG_CMSG_COMPAT;
4902 #endif
4903
4904         if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4905                 return 0;
4906         ret = io_recvmsg_copy_hdr(req, async_msg);
4907         if (!ret)
4908                 req->flags |= REQ_F_NEED_CLEANUP;
4909         return ret;
4910 }
4911
4912 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4913 {
4914         struct io_async_msghdr iomsg, *kmsg;
4915         struct socket *sock;
4916         struct io_buffer *kbuf;
4917         unsigned flags;
4918         int ret, cflags = 0;
4919         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4920
4921         sock = sock_from_file(req->file);
4922         if (unlikely(!sock))
4923                 return -ENOTSOCK;
4924
4925         kmsg = req->async_data;
4926         if (!kmsg) {
4927                 ret = io_recvmsg_copy_hdr(req, &iomsg);
4928                 if (ret)
4929                         return ret;
4930                 kmsg = &iomsg;
4931         }
4932
4933         if (req->flags & REQ_F_BUFFER_SELECT) {
4934                 kbuf = io_recv_buffer_select(req, !force_nonblock);
4935                 if (IS_ERR(kbuf))
4936                         return PTR_ERR(kbuf);
4937                 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4938                 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4939                 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4940                                 1, req->sr_msg.len);
4941         }
4942
4943         flags = req->sr_msg.msg_flags;
4944         if (flags & MSG_DONTWAIT)
4945                 req->flags |= REQ_F_NOWAIT;
4946         else if (force_nonblock)
4947                 flags |= MSG_DONTWAIT;
4948
4949         ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4950                                         kmsg->uaddr, flags);
4951         if (force_nonblock && ret == -EAGAIN)
4952                 return io_setup_async_msg(req, kmsg);
4953         if (ret == -ERESTARTSYS)
4954                 ret = -EINTR;
4955
4956         if (req->flags & REQ_F_BUFFER_SELECTED)
4957                 cflags = io_put_recv_kbuf(req);
4958         /* fast path, check for non-NULL to avoid function call */
4959         if (kmsg->free_iov)
4960                 kfree(kmsg->free_iov);
4961         req->flags &= ~REQ_F_NEED_CLEANUP;
4962         if (ret < 0)
4963                 req_set_fail_links(req);
4964         __io_req_complete(req, issue_flags, ret, cflags);
4965         return 0;
4966 }
4967
4968 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4969 {
4970         struct io_buffer *kbuf;
4971         struct io_sr_msg *sr = &req->sr_msg;
4972         struct msghdr msg;
4973         void __user *buf = sr->buf;
4974         struct socket *sock;
4975         struct iovec iov;
4976         unsigned flags;
4977         int ret, cflags = 0;
4978         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4979
4980         sock = sock_from_file(req->file);
4981         if (unlikely(!sock))
4982                 return -ENOTSOCK;
4983
4984         if (req->flags & REQ_F_BUFFER_SELECT) {
4985                 kbuf = io_recv_buffer_select(req, !force_nonblock);
4986                 if (IS_ERR(kbuf))
4987                         return PTR_ERR(kbuf);
4988                 buf = u64_to_user_ptr(kbuf->addr);
4989         }
4990
4991         ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4992         if (unlikely(ret))
4993                 goto out_free;
4994
4995         msg.msg_name = NULL;
4996         msg.msg_control = NULL;
4997         msg.msg_controllen = 0;
4998         msg.msg_namelen = 0;
4999         msg.msg_iocb = NULL;
5000         msg.msg_flags = 0;
5001
5002         flags = req->sr_msg.msg_flags;
5003         if (flags & MSG_DONTWAIT)
5004                 req->flags |= REQ_F_NOWAIT;
5005         else if (force_nonblock)
5006                 flags |= MSG_DONTWAIT;
5007
5008         ret = sock_recvmsg(sock, &msg, flags);
5009         if (force_nonblock && ret == -EAGAIN)
5010                 return -EAGAIN;
5011         if (ret == -ERESTARTSYS)
5012                 ret = -EINTR;
5013 out_free:
5014         if (req->flags & REQ_F_BUFFER_SELECTED)
5015                 cflags = io_put_recv_kbuf(req);
5016         if (ret < 0)
5017                 req_set_fail_links(req);
5018         __io_req_complete(req, issue_flags, ret, cflags);
5019         return 0;
5020 }
5021
5022 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5023 {
5024         struct io_accept *accept = &req->accept;
5025
5026         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5027                 return -EINVAL;
5028         if (sqe->ioprio || sqe->len || sqe->buf_index)
5029                 return -EINVAL;
5030
5031         accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5032         accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5033         accept->flags = READ_ONCE(sqe->accept_flags);
5034         accept->nofile = rlimit(RLIMIT_NOFILE);
5035         return 0;
5036 }
5037
5038 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5039 {
5040         struct io_accept *accept = &req->accept;
5041         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5042         unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5043         int ret;
5044
5045         if (req->file->f_flags & O_NONBLOCK)
5046                 req->flags |= REQ_F_NOWAIT;
5047
5048         ret = __sys_accept4_file(req->file, file_flags, accept->addr,
5049                                         accept->addr_len, accept->flags,
5050                                         accept->nofile);
5051         if (ret == -EAGAIN && force_nonblock)
5052                 return -EAGAIN;
5053         if (ret < 0) {
5054                 if (ret == -ERESTARTSYS)
5055                         ret = -EINTR;
5056                 req_set_fail_links(req);
5057         }
5058         __io_req_complete(req, issue_flags, ret, 0);
5059         return 0;
5060 }
5061
5062 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5063 {
5064         struct io_connect *conn = &req->connect;
5065         struct io_async_connect *io = req->async_data;
5066
5067         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5068                 return -EINVAL;
5069         if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
5070                 return -EINVAL;
5071
5072         conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5073         conn->addr_len =  READ_ONCE(sqe->addr2);
5074
5075         if (!io)
5076                 return 0;
5077
5078         return move_addr_to_kernel(conn->addr, conn->addr_len,
5079                                         &io->address);
5080 }
5081
5082 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5083 {
5084         struct io_async_connect __io, *io;
5085         unsigned file_flags;
5086         int ret;
5087         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5088
5089         if (req->async_data) {
5090                 io = req->async_data;
5091         } else {
5092                 ret = move_addr_to_kernel(req->connect.addr,
5093                                                 req->connect.addr_len,
5094                                                 &__io.address);
5095                 if (ret)
5096                         goto out;
5097                 io = &__io;
5098         }
5099
5100         file_flags = force_nonblock ? O_NONBLOCK : 0;
5101
5102         ret = __sys_connect_file(req->file, &io->address,
5103                                         req->connect.addr_len, file_flags);
5104         if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5105                 if (req->async_data)
5106                         return -EAGAIN;
5107                 if (io_alloc_async_data(req)) {
5108                         ret = -ENOMEM;
5109                         goto out;
5110                 }
5111                 io = req->async_data;
5112                 memcpy(req->async_data, &__io, sizeof(__io));
5113                 return -EAGAIN;
5114         }
5115         if (ret == -ERESTARTSYS)
5116                 ret = -EINTR;
5117 out:
5118         if (ret < 0)
5119                 req_set_fail_links(req);
5120         __io_req_complete(req, issue_flags, ret, 0);
5121         return 0;
5122 }
5123 #else /* !CONFIG_NET */
5124 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5125 {
5126         return -EOPNOTSUPP;
5127 }
5128
5129 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5130 {
5131         return -EOPNOTSUPP;
5132 }
5133
5134 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5135 {
5136         return -EOPNOTSUPP;
5137 }
5138
5139 static int io_recvmsg_prep(struct io_kiocb *req,
5140                            const struct io_uring_sqe *sqe)
5141 {
5142         return -EOPNOTSUPP;
5143 }
5144
5145 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5146 {
5147         return -EOPNOTSUPP;
5148 }
5149
5150 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5151 {
5152         return -EOPNOTSUPP;
5153 }
5154
5155 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5156 {
5157         return -EOPNOTSUPP;
5158 }
5159
5160 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5161 {
5162         return -EOPNOTSUPP;
5163 }
5164
5165 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5166 {
5167         return -EOPNOTSUPP;
5168 }
5169
5170 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5171 {
5172         return -EOPNOTSUPP;
5173 }
5174 #endif /* CONFIG_NET */
5175
5176 struct io_poll_table {
5177         struct poll_table_struct pt;
5178         struct io_kiocb *req;
5179         int error;
5180 };
5181
5182 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5183                            __poll_t mask, task_work_func_t func)
5184 {
5185         int ret;
5186
5187         /* for instances that support it check for an event match first: */
5188         if (mask && !(mask & poll->events))
5189                 return 0;
5190
5191         trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5192
5193         list_del_init(&poll->wait.entry);
5194
5195         req->result = mask;
5196         req->task_work.func = func;
5197         percpu_ref_get(&req->ctx->refs);
5198
5199         /*
5200          * If this fails, then the task is exiting. When a task exits, the
5201          * work gets canceled, so just cancel this request as well instead
5202          * of executing it. We can't safely execute it anyway, as we may not
5203          * have the needed state needed for it anyway.
5204          */
5205         ret = io_req_task_work_add(req);
5206         if (unlikely(ret)) {
5207                 WRITE_ONCE(poll->canceled, true);
5208                 io_req_task_work_add_fallback(req, func);
5209         }
5210         return 1;
5211 }
5212
5213 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5214         __acquires(&req->ctx->completion_lock)
5215 {
5216         struct io_ring_ctx *ctx = req->ctx;
5217
5218         if (!req->result && !READ_ONCE(poll->canceled)) {
5219                 struct poll_table_struct pt = { ._key = poll->events };
5220
5221                 req->result = vfs_poll(req->file, &pt) & poll->events;
5222         }
5223
5224         spin_lock_irq(&ctx->completion_lock);
5225         if (!req->result && !READ_ONCE(poll->canceled)) {
5226                 add_wait_queue(poll->head, &poll->wait);
5227                 return true;
5228         }
5229
5230         return false;
5231 }
5232
5233 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5234 {
5235         /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5236         if (req->opcode == IORING_OP_POLL_ADD)
5237                 return req->async_data;
5238         return req->apoll->double_poll;
5239 }
5240
5241 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5242 {
5243         if (req->opcode == IORING_OP_POLL_ADD)
5244                 return &req->poll;
5245         return &req->apoll->poll;
5246 }
5247
5248 static void io_poll_remove_double(struct io_kiocb *req)
5249 {
5250         struct io_poll_iocb *poll = io_poll_get_double(req);
5251
5252         lockdep_assert_held(&req->ctx->completion_lock);
5253
5254         if (poll && poll->head) {
5255                 struct wait_queue_head *head = poll->head;
5256
5257                 spin_lock(&head->lock);
5258                 list_del_init(&poll->wait.entry);
5259                 if (poll->wait.private)
5260                         refcount_dec(&req->refs);
5261                 poll->head = NULL;
5262                 spin_unlock(&head->lock);
5263         }
5264 }
5265
5266 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
5267 {
5268         struct io_ring_ctx *ctx = req->ctx;
5269
5270         io_poll_remove_double(req);
5271         req->poll.done = true;
5272         io_cqring_fill_event(req, error ? error : mangle_poll(mask));
5273         io_commit_cqring(ctx);
5274 }
5275
5276 static void io_poll_task_func(struct callback_head *cb)
5277 {
5278         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5279         struct io_ring_ctx *ctx = req->ctx;
5280         struct io_kiocb *nxt;
5281
5282         if (io_poll_rewait(req, &req->poll)) {
5283                 spin_unlock_irq(&ctx->completion_lock);
5284         } else {
5285                 hash_del(&req->hash_node);
5286                 io_poll_complete(req, req->result, 0);
5287                 spin_unlock_irq(&ctx->completion_lock);
5288
5289                 nxt = io_put_req_find_next(req);
5290                 io_cqring_ev_posted(ctx);
5291                 if (nxt)
5292                         __io_req_task_submit(nxt);
5293         }
5294
5295         percpu_ref_put(&ctx->refs);
5296 }
5297
5298 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5299                                int sync, void *key)
5300 {
5301         struct io_kiocb *req = wait->private;
5302         struct io_poll_iocb *poll = io_poll_get_single(req);
5303         __poll_t mask = key_to_poll(key);
5304
5305         /* for instances that support it check for an event match first: */
5306         if (mask && !(mask & poll->events))
5307                 return 0;
5308
5309         list_del_init(&wait->entry);
5310
5311         if (poll && poll->head) {
5312                 bool done;
5313
5314                 spin_lock(&poll->head->lock);
5315                 done = list_empty(&poll->wait.entry);
5316                 if (!done)
5317                         list_del_init(&poll->wait.entry);
5318                 /* make sure double remove sees this as being gone */
5319                 wait->private = NULL;
5320                 spin_unlock(&poll->head->lock);
5321                 if (!done) {
5322                         /* use wait func handler, so it matches the rq type */
5323                         poll->wait.func(&poll->wait, mode, sync, key);
5324                 }
5325         }
5326         refcount_dec(&req->refs);
5327         return 1;
5328 }
5329
5330 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5331                               wait_queue_func_t wake_func)
5332 {
5333         poll->head = NULL;
5334         poll->done = false;
5335         poll->canceled = false;
5336         poll->events = events;
5337         INIT_LIST_HEAD(&poll->wait.entry);
5338         init_waitqueue_func_entry(&poll->wait, wake_func);
5339 }
5340
5341 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5342                             struct wait_queue_head *head,
5343                             struct io_poll_iocb **poll_ptr)
5344 {
5345         struct io_kiocb *req = pt->req;
5346
5347         /*
5348          * If poll->head is already set, it's because the file being polled
5349          * uses multiple waitqueues for poll handling (eg one for read, one
5350          * for write). Setup a separate io_poll_iocb if this happens.
5351          */
5352         if (unlikely(poll->head)) {
5353                 struct io_poll_iocb *poll_one = poll;
5354
5355                 /* already have a 2nd entry, fail a third attempt */
5356                 if (*poll_ptr) {
5357                         pt->error = -EINVAL;
5358                         return;
5359                 }
5360                 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5361                 if (!poll) {
5362                         pt->error = -ENOMEM;
5363                         return;
5364                 }
5365                 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5366                 refcount_inc(&req->refs);
5367                 poll->wait.private = req;
5368                 *poll_ptr = poll;
5369         }
5370
5371         pt->error = 0;
5372         poll->head = head;
5373
5374         if (poll->events & EPOLLEXCLUSIVE)
5375                 add_wait_queue_exclusive(head, &poll->wait);
5376         else
5377                 add_wait_queue(head, &poll->wait);
5378 }
5379
5380 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5381                                struct poll_table_struct *p)
5382 {
5383         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5384         struct async_poll *apoll = pt->req->apoll;
5385
5386         __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5387 }
5388
5389 static void io_async_task_func(struct callback_head *cb)
5390 {
5391         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5392         struct async_poll *apoll = req->apoll;
5393         struct io_ring_ctx *ctx = req->ctx;
5394
5395         trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5396
5397         if (io_poll_rewait(req, &apoll->poll)) {
5398                 spin_unlock_irq(&ctx->completion_lock);
5399                 percpu_ref_put(&ctx->refs);
5400                 return;
5401         }
5402
5403         /* If req is still hashed, it cannot have been canceled. Don't check. */
5404         if (hash_hashed(&req->hash_node))
5405                 hash_del(&req->hash_node);
5406
5407         io_poll_remove_double(req);
5408         spin_unlock_irq(&ctx->completion_lock);
5409
5410         if (!READ_ONCE(apoll->poll.canceled))
5411                 __io_req_task_submit(req);
5412         else
5413                 __io_req_task_cancel(req, -ECANCELED);
5414
5415         percpu_ref_put(&ctx->refs);
5416         kfree(apoll->double_poll);
5417         kfree(apoll);
5418 }
5419
5420 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5421                         void *key)
5422 {
5423         struct io_kiocb *req = wait->private;
5424         struct io_poll_iocb *poll = &req->apoll->poll;
5425
5426         trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5427                                         key_to_poll(key));
5428
5429         return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5430 }
5431
5432 static void io_poll_req_insert(struct io_kiocb *req)
5433 {
5434         struct io_ring_ctx *ctx = req->ctx;
5435         struct hlist_head *list;
5436
5437         list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5438         hlist_add_head(&req->hash_node, list);
5439 }
5440
5441 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5442                                       struct io_poll_iocb *poll,
5443                                       struct io_poll_table *ipt, __poll_t mask,
5444                                       wait_queue_func_t wake_func)
5445         __acquires(&ctx->completion_lock)
5446 {
5447         struct io_ring_ctx *ctx = req->ctx;
5448         bool cancel = false;
5449
5450         INIT_HLIST_NODE(&req->hash_node);
5451         io_init_poll_iocb(poll, mask, wake_func);
5452         poll->file = req->file;
5453         poll->wait.private = req;
5454
5455         ipt->pt._key = mask;
5456         ipt->req = req;
5457         ipt->error = -EINVAL;
5458
5459         mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5460
5461         spin_lock_irq(&ctx->completion_lock);
5462         if (likely(poll->head)) {
5463                 spin_lock(&poll->head->lock);
5464                 if (unlikely(list_empty(&poll->wait.entry))) {
5465                         if (ipt->error)
5466                                 cancel = true;
5467                         ipt->error = 0;
5468                         mask = 0;
5469                 }
5470                 if (mask || ipt->error)
5471                         list_del_init(&poll->wait.entry);
5472                 else if (cancel)
5473                         WRITE_ONCE(poll->canceled, true);
5474                 else if (!poll->done) /* actually waiting for an event */
5475                         io_poll_req_insert(req);
5476                 spin_unlock(&poll->head->lock);
5477         }
5478
5479         return mask;
5480 }
5481
5482 static bool io_arm_poll_handler(struct io_kiocb *req)
5483 {
5484         const struct io_op_def *def = &io_op_defs[req->opcode];
5485         struct io_ring_ctx *ctx = req->ctx;
5486         struct async_poll *apoll;
5487         struct io_poll_table ipt;
5488         __poll_t mask, ret;
5489         int rw;
5490
5491         if (!req->file || !file_can_poll(req->file))
5492                 return false;
5493         if (req->flags & REQ_F_POLLED)
5494                 return false;
5495         if (def->pollin)
5496                 rw = READ;
5497         else if (def->pollout)
5498                 rw = WRITE;
5499         else
5500                 return false;
5501         /* if we can't nonblock try, then no point in arming a poll handler */
5502         if (!io_file_supports_async(req->file, rw))
5503                 return false;
5504
5505         apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5506         if (unlikely(!apoll))
5507                 return false;
5508         apoll->double_poll = NULL;
5509
5510         req->flags |= REQ_F_POLLED;
5511         req->apoll = apoll;
5512
5513         mask = 0;
5514         if (def->pollin)
5515                 mask |= POLLIN | POLLRDNORM;
5516         if (def->pollout)
5517                 mask |= POLLOUT | POLLWRNORM;
5518
5519         /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5520         if ((req->opcode == IORING_OP_RECVMSG) &&
5521             (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5522                 mask &= ~POLLIN;
5523
5524         mask |= POLLERR | POLLPRI;
5525
5526         ipt.pt._qproc = io_async_queue_proc;
5527
5528         ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5529                                         io_async_wake);
5530         if (ret || ipt.error) {
5531                 io_poll_remove_double(req);
5532                 spin_unlock_irq(&ctx->completion_lock);
5533                 kfree(apoll->double_poll);
5534                 kfree(apoll);
5535                 return false;
5536         }
5537         spin_unlock_irq(&ctx->completion_lock);
5538         trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5539                                         apoll->poll.events);
5540         return true;
5541 }
5542
5543 static bool __io_poll_remove_one(struct io_kiocb *req,
5544                                  struct io_poll_iocb *poll)
5545 {
5546         bool do_complete = false;
5547
5548         spin_lock(&poll->head->lock);
5549         WRITE_ONCE(poll->canceled, true);
5550         if (!list_empty(&poll->wait.entry)) {
5551                 list_del_init(&poll->wait.entry);
5552                 do_complete = true;
5553         }
5554         spin_unlock(&poll->head->lock);
5555         hash_del(&req->hash_node);
5556         return do_complete;
5557 }
5558
5559 static bool io_poll_remove_one(struct io_kiocb *req)
5560 {
5561         bool do_complete;
5562
5563         io_poll_remove_double(req);
5564
5565         if (req->opcode == IORING_OP_POLL_ADD) {
5566                 do_complete = __io_poll_remove_one(req, &req->poll);
5567         } else {
5568                 struct async_poll *apoll = req->apoll;
5569
5570                 /* non-poll requests have submit ref still */
5571                 do_complete = __io_poll_remove_one(req, &apoll->poll);
5572                 if (do_complete) {
5573                         io_put_req(req);
5574                         kfree(apoll->double_poll);
5575                         kfree(apoll);
5576                 }
5577         }
5578
5579         if (do_complete) {
5580                 io_cqring_fill_event(req, -ECANCELED);
5581                 io_commit_cqring(req->ctx);
5582                 req_set_fail_links(req);
5583                 io_put_req_deferred(req, 1);
5584         }
5585
5586         return do_complete;
5587 }
5588
5589 /*
5590  * Returns true if we found and killed one or more poll requests
5591  */
5592 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5593                                struct files_struct *files)
5594 {
5595         struct hlist_node *tmp;
5596         struct io_kiocb *req;
5597         int posted = 0, i;
5598
5599         spin_lock_irq(&ctx->completion_lock);
5600         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5601                 struct hlist_head *list;
5602
5603                 list = &ctx->cancel_hash[i];
5604                 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5605                         if (io_match_task(req, tsk, files))
5606                                 posted += io_poll_remove_one(req);
5607                 }
5608         }
5609         spin_unlock_irq(&ctx->completion_lock);
5610
5611         if (posted)
5612                 io_cqring_ev_posted(ctx);
5613
5614         return posted != 0;
5615 }
5616
5617 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5618 {
5619         struct hlist_head *list;
5620         struct io_kiocb *req;
5621
5622         list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5623         hlist_for_each_entry(req, list, hash_node) {
5624                 if (sqe_addr != req->user_data)
5625                         continue;
5626                 if (io_poll_remove_one(req))
5627                         return 0;
5628                 return -EALREADY;
5629         }
5630
5631         return -ENOENT;
5632 }
5633
5634 static int io_poll_remove_prep(struct io_kiocb *req,
5635                                const struct io_uring_sqe *sqe)
5636 {
5637         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5638                 return -EINVAL;
5639         if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5640             sqe->poll_events)
5641                 return -EINVAL;
5642
5643         req->poll_remove.addr = READ_ONCE(sqe->addr);
5644         return 0;
5645 }
5646
5647 /*
5648  * Find a running poll command that matches one specified in sqe->addr,
5649  * and remove it if found.
5650  */
5651 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5652 {
5653         struct io_ring_ctx *ctx = req->ctx;
5654         int ret;
5655
5656         spin_lock_irq(&ctx->completion_lock);
5657         ret = io_poll_cancel(ctx, req->poll_remove.addr);
5658         spin_unlock_irq(&ctx->completion_lock);
5659
5660         if (ret < 0)
5661                 req_set_fail_links(req);
5662         io_req_complete(req, ret);
5663         return 0;
5664 }
5665
5666 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5667                         void *key)
5668 {
5669         struct io_kiocb *req = wait->private;
5670         struct io_poll_iocb *poll = &req->poll;
5671
5672         return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5673 }
5674
5675 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5676                                struct poll_table_struct *p)
5677 {
5678         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5679
5680         __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5681 }
5682
5683 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5684 {
5685         struct io_poll_iocb *poll = &req->poll;
5686         u32 events;
5687
5688         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5689                 return -EINVAL;
5690         if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5691                 return -EINVAL;
5692
5693         events = READ_ONCE(sqe->poll32_events);
5694 #ifdef __BIG_ENDIAN
5695         events = swahw32(events);
5696 #endif
5697         poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5698                        (events & EPOLLEXCLUSIVE);
5699         return 0;
5700 }
5701
5702 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5703 {
5704         struct io_poll_iocb *poll = &req->poll;
5705         struct io_ring_ctx *ctx = req->ctx;
5706         struct io_poll_table ipt;
5707         __poll_t mask;
5708
5709         ipt.pt._qproc = io_poll_queue_proc;
5710
5711         mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5712                                         io_poll_wake);
5713
5714         if (mask) { /* no async, we'd stolen it */
5715                 ipt.error = 0;
5716                 io_poll_complete(req, mask, 0);
5717         }
5718         spin_unlock_irq(&ctx->completion_lock);
5719
5720         if (mask) {
5721                 io_cqring_ev_posted(ctx);
5722                 io_put_req(req);
5723         }
5724         return ipt.error;
5725 }
5726
5727 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5728 {
5729         struct io_timeout_data *data = container_of(timer,
5730                                                 struct io_timeout_data, timer);
5731         struct io_kiocb *req = data->req;
5732         struct io_ring_ctx *ctx = req->ctx;
5733         unsigned long flags;
5734
5735         spin_lock_irqsave(&ctx->completion_lock, flags);
5736         list_del_init(&req->timeout.list);
5737         atomic_set(&req->ctx->cq_timeouts,
5738                 atomic_read(&req->ctx->cq_timeouts) + 1);
5739
5740         io_cqring_fill_event(req, -ETIME);
5741         io_commit_cqring(ctx);
5742         spin_unlock_irqrestore(&ctx->completion_lock, flags);
5743
5744         io_cqring_ev_posted(ctx);
5745         req_set_fail_links(req);
5746         io_put_req(req);
5747         return HRTIMER_NORESTART;
5748 }
5749
5750 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5751                                            __u64 user_data)
5752 {
5753         struct io_timeout_data *io;
5754         struct io_kiocb *req;
5755         int ret = -ENOENT;
5756
5757         list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5758                 if (user_data == req->user_data) {
5759                         ret = 0;
5760                         break;
5761                 }
5762         }
5763
5764         if (ret == -ENOENT)
5765                 return ERR_PTR(ret);
5766
5767         io = req->async_data;
5768         ret = hrtimer_try_to_cancel(&io->timer);
5769         if (ret == -1)
5770                 return ERR_PTR(-EALREADY);
5771         list_del_init(&req->timeout.list);
5772         return req;
5773 }
5774
5775 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5776 {
5777         struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5778
5779         if (IS_ERR(req))
5780                 return PTR_ERR(req);
5781
5782         req_set_fail_links(req);
5783         io_cqring_fill_event(req, -ECANCELED);
5784         io_put_req_deferred(req, 1);
5785         return 0;
5786 }
5787
5788 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5789                              struct timespec64 *ts, enum hrtimer_mode mode)
5790 {
5791         struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5792         struct io_timeout_data *data;
5793
5794         if (IS_ERR(req))
5795                 return PTR_ERR(req);
5796
5797         req->timeout.off = 0; /* noseq */
5798         data = req->async_data;
5799         list_add_tail(&req->timeout.list, &ctx->timeout_list);
5800         hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5801         data->timer.function = io_timeout_fn;
5802         hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5803         return 0;
5804 }
5805
5806 static int io_timeout_remove_prep(struct io_kiocb *req,
5807                                   const struct io_uring_sqe *sqe)
5808 {
5809         struct io_timeout_rem *tr = &req->timeout_rem;
5810
5811         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5812                 return -EINVAL;
5813         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5814                 return -EINVAL;
5815         if (sqe->ioprio || sqe->buf_index || sqe->len)
5816                 return -EINVAL;
5817
5818         tr->addr = READ_ONCE(sqe->addr);
5819         tr->flags = READ_ONCE(sqe->timeout_flags);
5820         if (tr->flags & IORING_TIMEOUT_UPDATE) {
5821                 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5822                         return -EINVAL;
5823                 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5824                         return -EFAULT;
5825         } else if (tr->flags) {
5826                 /* timeout removal doesn't support flags */
5827                 return -EINVAL;
5828         }
5829
5830         return 0;
5831 }
5832
5833 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5834 {
5835         return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5836                                             : HRTIMER_MODE_REL;
5837 }
5838
5839 /*
5840  * Remove or update an existing timeout command
5841  */
5842 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5843 {
5844         struct io_timeout_rem *tr = &req->timeout_rem;
5845         struct io_ring_ctx *ctx = req->ctx;
5846         int ret;
5847
5848         spin_lock_irq(&ctx->completion_lock);
5849         if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5850                 ret = io_timeout_cancel(ctx, tr->addr);
5851         else
5852                 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5853                                         io_translate_timeout_mode(tr->flags));
5854
5855         io_cqring_fill_event(req, ret);
5856         io_commit_cqring(ctx);
5857         spin_unlock_irq(&ctx->completion_lock);
5858         io_cqring_ev_posted(ctx);
5859         if (ret < 0)
5860                 req_set_fail_links(req);
5861         io_put_req(req);
5862         return 0;
5863 }
5864
5865 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5866                            bool is_timeout_link)
5867 {
5868         struct io_timeout_data *data;
5869         unsigned flags;
5870         u32 off = READ_ONCE(sqe->off);
5871
5872         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5873                 return -EINVAL;
5874         if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5875                 return -EINVAL;
5876         if (off && is_timeout_link)
5877                 return -EINVAL;
5878         flags = READ_ONCE(sqe->timeout_flags);
5879         if (flags & ~IORING_TIMEOUT_ABS)
5880                 return -EINVAL;
5881
5882         req->timeout.off = off;
5883
5884         if (!req->async_data && io_alloc_async_data(req))
5885                 return -ENOMEM;
5886
5887         data = req->async_data;
5888         data->req = req;
5889
5890         if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5891                 return -EFAULT;
5892
5893         data->mode = io_translate_timeout_mode(flags);
5894         hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5895         return 0;
5896 }
5897
5898 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5899 {
5900         struct io_ring_ctx *ctx = req->ctx;
5901         struct io_timeout_data *data = req->async_data;
5902         struct list_head *entry;
5903         u32 tail, off = req->timeout.off;
5904
5905         spin_lock_irq(&ctx->completion_lock);
5906
5907         /*
5908          * sqe->off holds how many events that need to occur for this
5909          * timeout event to be satisfied. If it isn't set, then this is
5910          * a pure timeout request, sequence isn't used.
5911          */
5912         if (io_is_timeout_noseq(req)) {
5913                 entry = ctx->timeout_list.prev;
5914                 goto add;
5915         }
5916
5917         tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5918         req->timeout.target_seq = tail + off;
5919
5920         /* Update the last seq here in case io_flush_timeouts() hasn't.
5921          * This is safe because ->completion_lock is held, and submissions
5922          * and completions are never mixed in the same ->completion_lock section.
5923          */
5924         ctx->cq_last_tm_flush = tail;
5925
5926         /*
5927          * Insertion sort, ensuring the first entry in the list is always
5928          * the one we need first.
5929          */
5930         list_for_each_prev(entry, &ctx->timeout_list) {
5931                 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5932                                                   timeout.list);
5933
5934                 if (io_is_timeout_noseq(nxt))
5935                         continue;
5936                 /* nxt.seq is behind @tail, otherwise would've been completed */
5937                 if (off >= nxt->timeout.target_seq - tail)
5938                         break;
5939         }
5940 add:
5941         list_add(&req->timeout.list, entry);
5942         data->timer.function = io_timeout_fn;
5943         hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5944         spin_unlock_irq(&ctx->completion_lock);
5945         return 0;
5946 }
5947
5948 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5949 {
5950         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5951
5952         return req->user_data == (unsigned long) data;
5953 }
5954
5955 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5956 {
5957         enum io_wq_cancel cancel_ret;
5958         int ret = 0;
5959
5960         cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5961         switch (cancel_ret) {
5962         case IO_WQ_CANCEL_OK:
5963                 ret = 0;
5964                 break;
5965         case IO_WQ_CANCEL_RUNNING:
5966                 ret = -EALREADY;
5967                 break;
5968         case IO_WQ_CANCEL_NOTFOUND:
5969                 ret = -ENOENT;
5970                 break;
5971         }
5972
5973         return ret;
5974 }
5975
5976 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5977                                      struct io_kiocb *req, __u64 sqe_addr,
5978                                      int success_ret)
5979 {
5980         unsigned long flags;
5981         int ret;
5982
5983         ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5984         if (ret != -ENOENT) {
5985                 spin_lock_irqsave(&ctx->completion_lock, flags);
5986                 goto done;
5987         }
5988
5989         spin_lock_irqsave(&ctx->completion_lock, flags);
5990         ret = io_timeout_cancel(ctx, sqe_addr);
5991         if (ret != -ENOENT)
5992                 goto done;
5993         ret = io_poll_cancel(ctx, sqe_addr);
5994 done:
5995         if (!ret)
5996                 ret = success_ret;
5997         io_cqring_fill_event(req, ret);
5998         io_commit_cqring(ctx);
5999         spin_unlock_irqrestore(&ctx->completion_lock, flags);
6000         io_cqring_ev_posted(ctx);
6001
6002         if (ret < 0)
6003                 req_set_fail_links(req);
6004         io_put_req(req);
6005 }
6006
6007 static int io_async_cancel_prep(struct io_kiocb *req,
6008                                 const struct io_uring_sqe *sqe)
6009 {
6010         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6011                 return -EINVAL;
6012         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6013                 return -EINVAL;
6014         if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
6015                 return -EINVAL;
6016
6017         req->cancel.addr = READ_ONCE(sqe->addr);
6018         return 0;
6019 }
6020
6021 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6022 {
6023         struct io_ring_ctx *ctx = req->ctx;
6024
6025         io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
6026         return 0;
6027 }
6028
6029 static int io_rsrc_update_prep(struct io_kiocb *req,
6030                                 const struct io_uring_sqe *sqe)
6031 {
6032         if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
6033                 return -EINVAL;
6034         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6035                 return -EINVAL;
6036         if (sqe->ioprio || sqe->rw_flags)
6037                 return -EINVAL;
6038
6039         req->rsrc_update.offset = READ_ONCE(sqe->off);
6040         req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6041         if (!req->rsrc_update.nr_args)
6042                 return -EINVAL;
6043         req->rsrc_update.arg = READ_ONCE(sqe->addr);
6044         return 0;
6045 }
6046
6047 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6048 {
6049         struct io_ring_ctx *ctx = req->ctx;
6050         struct io_uring_rsrc_update up;
6051         int ret;
6052
6053         if (issue_flags & IO_URING_F_NONBLOCK)
6054                 return -EAGAIN;
6055
6056         up.offset = req->rsrc_update.offset;
6057         up.data = req->rsrc_update.arg;
6058
6059         mutex_lock(&ctx->uring_lock);
6060         ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
6061         mutex_unlock(&ctx->uring_lock);
6062
6063         if (ret < 0)
6064                 req_set_fail_links(req);
6065         __io_req_complete(req, issue_flags, ret, 0);
6066         return 0;
6067 }
6068
6069 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6070 {
6071         switch (req->opcode) {
6072         case IORING_OP_NOP:
6073                 return 0;
6074         case IORING_OP_READV:
6075         case IORING_OP_READ_FIXED:
6076         case IORING_OP_READ:
6077                 return io_read_prep(req, sqe);
6078         case IORING_OP_WRITEV:
6079         case IORING_OP_WRITE_FIXED:
6080         case IORING_OP_WRITE:
6081                 return io_write_prep(req, sqe);
6082         case IORING_OP_POLL_ADD:
6083                 return io_poll_add_prep(req, sqe);
6084         case IORING_OP_POLL_REMOVE:
6085                 return io_poll_remove_prep(req, sqe);
6086         case IORING_OP_FSYNC:
6087                 return io_prep_fsync(req, sqe);
6088         case IORING_OP_SYNC_FILE_RANGE:
6089                 return io_prep_sfr(req, sqe);
6090         case IORING_OP_SENDMSG:
6091         case IORING_OP_SEND:
6092                 return io_sendmsg_prep(req, sqe);
6093         case IORING_OP_RECVMSG:
6094         case IORING_OP_RECV:
6095                 return io_recvmsg_prep(req, sqe);
6096         case IORING_OP_CONNECT:
6097                 return io_connect_prep(req, sqe);
6098         case IORING_OP_TIMEOUT:
6099                 return io_timeout_prep(req, sqe, false);
6100         case IORING_OP_TIMEOUT_REMOVE:
6101                 return io_timeout_remove_prep(req, sqe);
6102         case IORING_OP_ASYNC_CANCEL:
6103                 return io_async_cancel_prep(req, sqe);
6104         case IORING_OP_LINK_TIMEOUT:
6105                 return io_timeout_prep(req, sqe, true);
6106         case IORING_OP_ACCEPT:
6107                 return io_accept_prep(req, sqe);
6108         case IORING_OP_FALLOCATE:
6109                 return io_fallocate_prep(req, sqe);
6110         case IORING_OP_OPENAT:
6111                 return io_openat_prep(req, sqe);
6112         case IORING_OP_CLOSE:
6113                 return io_close_prep(req, sqe);
6114         case IORING_OP_FILES_UPDATE:
6115                 return io_rsrc_update_prep(req, sqe);
6116         case IORING_OP_STATX:
6117                 return io_statx_prep(req, sqe);
6118         case IORING_OP_FADVISE:
6119                 return io_fadvise_prep(req, sqe);
6120         case IORING_OP_MADVISE:
6121                 return io_madvise_prep(req, sqe);
6122         case IORING_OP_OPENAT2:
6123                 return io_openat2_prep(req, sqe);
6124         case IORING_OP_EPOLL_CTL:
6125                 return io_epoll_ctl_prep(req, sqe);
6126         case IORING_OP_SPLICE:
6127                 return io_splice_prep(req, sqe);
6128         case IORING_OP_PROVIDE_BUFFERS:
6129                 return io_provide_buffers_prep(req, sqe);
6130         case IORING_OP_REMOVE_BUFFERS:
6131                 return io_remove_buffers_prep(req, sqe);
6132         case IORING_OP_TEE:
6133                 return io_tee_prep(req, sqe);
6134         case IORING_OP_SHUTDOWN:
6135                 return io_shutdown_prep(req, sqe);
6136         case IORING_OP_RENAMEAT:
6137                 return io_renameat_prep(req, sqe);
6138         case IORING_OP_UNLINKAT:
6139                 return io_unlinkat_prep(req, sqe);
6140         }
6141
6142         printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6143                         req->opcode);
6144         return-EINVAL;
6145 }
6146
6147 static int io_req_defer_prep(struct io_kiocb *req,
6148                              const struct io_uring_sqe *sqe)
6149 {
6150         if (!sqe)
6151                 return 0;
6152         if (io_alloc_async_data(req))
6153                 return -EAGAIN;
6154         return io_req_prep(req, sqe);
6155 }
6156
6157 static u32 io_get_sequence(struct io_kiocb *req)
6158 {
6159         struct io_kiocb *pos;
6160         struct io_ring_ctx *ctx = req->ctx;
6161         u32 total_submitted, nr_reqs = 0;
6162
6163         io_for_each_link(pos, req)
6164                 nr_reqs++;
6165
6166         total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6167         return total_submitted - nr_reqs;
6168 }
6169
6170 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6171 {
6172         struct io_ring_ctx *ctx = req->ctx;
6173         struct io_defer_entry *de;
6174         int ret;
6175         u32 seq;
6176
6177         /* Still need defer if there is pending req in defer list. */
6178         if (likely(list_empty_careful(&ctx->defer_list) &&
6179                 !(req->flags & REQ_F_IO_DRAIN)))
6180                 return 0;
6181
6182         seq = io_get_sequence(req);
6183         /* Still a chance to pass the sequence check */
6184         if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6185                 return 0;
6186
6187         if (!req->async_data) {
6188                 ret = io_req_defer_prep(req, sqe);
6189                 if (ret)
6190                         return ret;
6191         }
6192         io_prep_async_link(req);
6193         de = kmalloc(sizeof(*de), GFP_KERNEL);
6194         if (!de)
6195                 return -ENOMEM;
6196
6197         spin_lock_irq(&ctx->completion_lock);
6198         if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6199                 spin_unlock_irq(&ctx->completion_lock);
6200                 kfree(de);
6201                 io_queue_async_work(req);
6202                 return -EIOCBQUEUED;
6203         }
6204
6205         trace_io_uring_defer(ctx, req, req->user_data);
6206         de->req = req;
6207         de->seq = seq;
6208         list_add_tail(&de->list, &ctx->defer_list);
6209         spin_unlock_irq(&ctx->completion_lock);
6210         return -EIOCBQUEUED;
6211 }
6212
6213 static void __io_clean_op(struct io_kiocb *req)
6214 {
6215         if (req->flags & REQ_F_BUFFER_SELECTED) {
6216                 switch (req->opcode) {
6217                 case IORING_OP_READV:
6218                 case IORING_OP_READ_FIXED:
6219                 case IORING_OP_READ:
6220                         kfree((void *)(unsigned long)req->rw.addr);
6221                         break;
6222                 case IORING_OP_RECVMSG:
6223                 case IORING_OP_RECV:
6224                         kfree(req->sr_msg.kbuf);
6225                         break;
6226                 }
6227                 req->flags &= ~REQ_F_BUFFER_SELECTED;
6228         }
6229
6230         if (req->flags & REQ_F_NEED_CLEANUP) {
6231                 switch (req->opcode) {
6232                 case IORING_OP_READV:
6233                 case IORING_OP_READ_FIXED:
6234                 case IORING_OP_READ:
6235                 case IORING_OP_WRITEV:
6236                 case IORING_OP_WRITE_FIXED:
6237                 case IORING_OP_WRITE: {
6238                         struct io_async_rw *io = req->async_data;
6239                         if (io->free_iovec)
6240                                 kfree(io->free_iovec);
6241                         break;
6242                         }
6243                 case IORING_OP_RECVMSG:
6244                 case IORING_OP_SENDMSG: {
6245                         struct io_async_msghdr *io = req->async_data;
6246
6247                         kfree(io->free_iov);
6248                         break;
6249                         }
6250                 case IORING_OP_SPLICE:
6251                 case IORING_OP_TEE:
6252                         io_put_file(req, req->splice.file_in,
6253                                     (req->splice.flags & SPLICE_F_FD_IN_FIXED));
6254                         break;
6255                 case IORING_OP_OPENAT:
6256                 case IORING_OP_OPENAT2:
6257                         if (req->open.filename)
6258                                 putname(req->open.filename);
6259                         break;
6260                 case IORING_OP_RENAMEAT:
6261                         putname(req->rename.oldpath);
6262                         putname(req->rename.newpath);
6263                         break;
6264                 case IORING_OP_UNLINKAT:
6265                         putname(req->unlink.filename);
6266                         break;
6267                 }
6268                 req->flags &= ~REQ_F_NEED_CLEANUP;
6269         }
6270 }
6271
6272 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6273 {
6274         struct io_ring_ctx *ctx = req->ctx;
6275         int ret;
6276
6277         switch (req->opcode) {
6278         case IORING_OP_NOP:
6279                 ret = io_nop(req, issue_flags);
6280                 break;
6281         case IORING_OP_READV:
6282         case IORING_OP_READ_FIXED:
6283         case IORING_OP_READ:
6284                 ret = io_read(req, issue_flags);
6285                 break;
6286         case IORING_OP_WRITEV:
6287         case IORING_OP_WRITE_FIXED:
6288         case IORING_OP_WRITE:
6289                 ret = io_write(req, issue_flags);
6290                 break;
6291         case IORING_OP_FSYNC:
6292                 ret = io_fsync(req, issue_flags);
6293                 break;
6294         case IORING_OP_POLL_ADD:
6295                 ret = io_poll_add(req, issue_flags);
6296                 break;
6297         case IORING_OP_POLL_REMOVE:
6298                 ret = io_poll_remove(req, issue_flags);
6299                 break;
6300         case IORING_OP_SYNC_FILE_RANGE:
6301                 ret = io_sync_file_range(req, issue_flags);
6302                 break;
6303         case IORING_OP_SENDMSG:
6304                 ret = io_sendmsg(req, issue_flags);
6305                 break;
6306         case IORING_OP_SEND:
6307                 ret = io_send(req, issue_flags);
6308                 break;
6309         case IORING_OP_RECVMSG:
6310                 ret = io_recvmsg(req, issue_flags);
6311                 break;
6312         case IORING_OP_RECV:
6313                 ret = io_recv(req, issue_flags);
6314                 break;
6315         case IORING_OP_TIMEOUT:
6316                 ret = io_timeout(req, issue_flags);
6317                 break;
6318         case IORING_OP_TIMEOUT_REMOVE:
6319                 ret = io_timeout_remove(req, issue_flags);
6320                 break;
6321         case IORING_OP_ACCEPT:
6322                 ret = io_accept(req, issue_flags);
6323                 break;
6324         case IORING_OP_CONNECT:
6325                 ret = io_connect(req, issue_flags);
6326                 break;
6327         case IORING_OP_ASYNC_CANCEL:
6328                 ret = io_async_cancel(req, issue_flags);
6329                 break;
6330         case IORING_OP_FALLOCATE:
6331                 ret = io_fallocate(req, issue_flags);
6332                 break;
6333         case IORING_OP_OPENAT:
6334                 ret = io_openat(req, issue_flags);
6335                 break;
6336         case IORING_OP_CLOSE:
6337                 ret = io_close(req, issue_flags);
6338                 break;
6339         case IORING_OP_FILES_UPDATE:
6340                 ret = io_files_update(req, issue_flags);
6341                 break;
6342         case IORING_OP_STATX:
6343                 ret = io_statx(req, issue_flags);
6344                 break;
6345         case IORING_OP_FADVISE:
6346                 ret = io_fadvise(req, issue_flags);
6347                 break;
6348         case IORING_OP_MADVISE:
6349                 ret = io_madvise(req, issue_flags);
6350                 break;
6351         case IORING_OP_OPENAT2:
6352                 ret = io_openat2(req, issue_flags);
6353                 break;
6354         case IORING_OP_EPOLL_CTL:
6355                 ret = io_epoll_ctl(req, issue_flags);
6356                 break;
6357         case IORING_OP_SPLICE:
6358                 ret = io_splice(req, issue_flags);
6359                 break;
6360         case IORING_OP_PROVIDE_BUFFERS:
6361                 ret = io_provide_buffers(req, issue_flags);
6362                 break;
6363         case IORING_OP_REMOVE_BUFFERS:
6364                 ret = io_remove_buffers(req, issue_flags);
6365                 break;
6366         case IORING_OP_TEE:
6367                 ret = io_tee(req, issue_flags);
6368                 break;
6369         case IORING_OP_SHUTDOWN:
6370                 ret = io_shutdown(req, issue_flags);
6371                 break;
6372         case IORING_OP_RENAMEAT:
6373                 ret = io_renameat(req, issue_flags);
6374                 break;
6375         case IORING_OP_UNLINKAT:
6376                 ret = io_unlinkat(req, issue_flags);
6377                 break;
6378         default:
6379                 ret = -EINVAL;
6380                 break;
6381         }
6382
6383         if (ret)
6384                 return ret;
6385
6386         /* If the op doesn't have a file, we're not polling for it */
6387         if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6388                 const bool in_async = io_wq_current_is_worker();
6389
6390                 /* workqueue context doesn't hold uring_lock, grab it now */
6391                 if (in_async)
6392                         mutex_lock(&ctx->uring_lock);
6393
6394                 io_iopoll_req_issued(req, in_async);
6395
6396                 if (in_async)
6397                         mutex_unlock(&ctx->uring_lock);
6398         }
6399
6400         return 0;
6401 }
6402
6403 static void io_wq_submit_work(struct io_wq_work *work)
6404 {
6405         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6406         struct io_kiocb *timeout;
6407         int ret = 0;
6408
6409         timeout = io_prep_linked_timeout(req);
6410         if (timeout)
6411                 io_queue_linked_timeout(timeout);
6412
6413         if (work->flags & IO_WQ_WORK_CANCEL)
6414                 ret = -ECANCELED;
6415
6416         if (!ret) {
6417                 do {
6418                         ret = io_issue_sqe(req, 0);
6419                         /*
6420                          * We can get EAGAIN for polled IO even though we're
6421                          * forcing a sync submission from here, since we can't
6422                          * wait for request slots on the block side.
6423                          */
6424                         if (ret != -EAGAIN)
6425                                 break;
6426                         cond_resched();
6427                 } while (1);
6428         }
6429
6430         if (ret) {
6431                 struct io_ring_ctx *lock_ctx = NULL;
6432
6433                 if (req->ctx->flags & IORING_SETUP_IOPOLL)
6434                         lock_ctx = req->ctx;
6435
6436                 /*
6437                  * io_iopoll_complete() does not hold completion_lock to
6438                  * complete polled io, so here for polled io, we can not call
6439                  * io_req_complete() directly, otherwise there maybe concurrent
6440                  * access to cqring, defer_list, etc, which is not safe. Given
6441                  * that io_iopoll_complete() is always called under uring_lock,
6442                  * so here for polled io, we also get uring_lock to complete
6443                  * it.
6444                  */
6445                 if (lock_ctx)
6446                         mutex_lock(&lock_ctx->uring_lock);
6447
6448                 req_set_fail_links(req);
6449                 io_req_complete(req, ret);
6450
6451                 if (lock_ctx)
6452                         mutex_unlock(&lock_ctx->uring_lock);
6453         }
6454 }
6455
6456 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6457                                               int index)
6458 {
6459         struct fixed_rsrc_table *table;
6460
6461         table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6462         return table->files[index & IORING_FILE_TABLE_MASK];
6463 }
6464
6465 static struct file *io_file_get(struct io_submit_state *state,
6466                                 struct io_kiocb *req, int fd, bool fixed)
6467 {
6468         struct io_ring_ctx *ctx = req->ctx;
6469         struct file *file;
6470
6471         if (fixed) {
6472                 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6473                         return NULL;
6474                 fd = array_index_nospec(fd, ctx->nr_user_files);
6475                 file = io_file_from_index(ctx, fd);
6476                 io_set_resource_node(req);
6477         } else {
6478                 trace_io_uring_file_get(ctx, fd);
6479                 file = __io_file_get(state, fd);
6480         }
6481
6482         if (file && unlikely(file->f_op == &io_uring_fops))
6483                 io_req_track_inflight(req);
6484         return file;
6485 }
6486
6487 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6488 {
6489         struct io_timeout_data *data = container_of(timer,
6490                                                 struct io_timeout_data, timer);
6491         struct io_kiocb *prev, *req = data->req;
6492         struct io_ring_ctx *ctx = req->ctx;
6493         unsigned long flags;
6494
6495         spin_lock_irqsave(&ctx->completion_lock, flags);
6496         prev = req->timeout.head;
6497         req->timeout.head = NULL;
6498
6499         /*
6500          * We don't expect the list to be empty, that will only happen if we
6501          * race with the completion of the linked work.
6502          */
6503         if (prev && refcount_inc_not_zero(&prev->refs))
6504                 io_remove_next_linked(prev);
6505         else
6506                 prev = NULL;
6507         spin_unlock_irqrestore(&ctx->completion_lock, flags);
6508
6509         if (prev) {
6510                 req_set_fail_links(prev);
6511                 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6512                 io_put_req_deferred(prev, 1);
6513         } else {
6514                 io_req_complete_post(req, -ETIME, 0);
6515                 io_put_req_deferred(req, 1);
6516         }
6517         return HRTIMER_NORESTART;
6518 }
6519
6520 static void __io_queue_linked_timeout(struct io_kiocb *req)
6521 {
6522         /*
6523          * If the back reference is NULL, then our linked request finished
6524          * before we got a chance to setup the timer
6525          */
6526         if (req->timeout.head) {
6527                 struct io_timeout_data *data = req->async_data;
6528
6529                 data->timer.function = io_link_timeout_fn;
6530                 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6531                                 data->mode);
6532         }
6533 }
6534
6535 static void io_queue_linked_timeout(struct io_kiocb *req)
6536 {
6537         struct io_ring_ctx *ctx = req->ctx;
6538
6539         spin_lock_irq(&ctx->completion_lock);
6540         __io_queue_linked_timeout(req);
6541         spin_unlock_irq(&ctx->completion_lock);
6542
6543         /* drop submission reference */
6544         io_put_req(req);
6545 }
6546
6547 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6548 {
6549         struct io_kiocb *nxt = req->link;
6550
6551         if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6552             nxt->opcode != IORING_OP_LINK_TIMEOUT)
6553                 return NULL;
6554
6555         nxt->timeout.head = req;
6556         nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6557         req->flags |= REQ_F_LINK_TIMEOUT;
6558         return nxt;
6559 }
6560
6561 static void __io_queue_sqe(struct io_kiocb *req)
6562 {
6563         struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6564         const struct cred *old_creds = NULL;
6565         int ret;
6566
6567         if ((req->flags & REQ_F_WORK_INITIALIZED) &&
6568             (req->work.flags & IO_WQ_WORK_CREDS) &&
6569             req->work.identity->creds != current_cred())
6570                 old_creds = override_creds(req->work.identity->creds);
6571
6572         ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6573
6574         if (old_creds)
6575                 revert_creds(old_creds);
6576
6577         /*
6578          * We async punt it if the file wasn't marked NOWAIT, or if the file
6579          * doesn't support non-blocking read/write attempts
6580          */
6581         if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6582                 if (!io_arm_poll_handler(req)) {
6583                         /*
6584                          * Queued up for async execution, worker will release
6585                          * submit reference when the iocb is actually submitted.
6586                          */
6587                         io_queue_async_work(req);
6588                 }
6589         } else if (likely(!ret)) {
6590                 /* drop submission reference */
6591                 if (req->flags & REQ_F_COMPLETE_INLINE) {
6592                         struct io_ring_ctx *ctx = req->ctx;
6593                         struct io_comp_state *cs = &ctx->submit_state.comp;
6594
6595                         cs->reqs[cs->nr++] = req;
6596                         if (cs->nr == ARRAY_SIZE(cs->reqs))
6597                                 io_submit_flush_completions(cs, ctx);
6598                 } else {
6599                         io_put_req(req);
6600                 }
6601         } else {
6602                 req_set_fail_links(req);
6603                 io_put_req(req);
6604                 io_req_complete(req, ret);
6605         }
6606         if (linked_timeout)
6607                 io_queue_linked_timeout(linked_timeout);
6608 }
6609
6610 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6611 {
6612         int ret;
6613
6614         ret = io_req_defer(req, sqe);
6615         if (ret) {
6616                 if (ret != -EIOCBQUEUED) {
6617 fail_req:
6618                         req_set_fail_links(req);
6619                         io_put_req(req);
6620                         io_req_complete(req, ret);
6621                 }
6622         } else if (req->flags & REQ_F_FORCE_ASYNC) {
6623                 if (!req->async_data) {
6624                         ret = io_req_defer_prep(req, sqe);
6625                         if (unlikely(ret))
6626                                 goto fail_req;
6627                 }
6628                 io_queue_async_work(req);
6629         } else {
6630                 if (sqe) {
6631                         ret = io_req_prep(req, sqe);
6632                         if (unlikely(ret))
6633                                 goto fail_req;
6634                 }
6635                 __io_queue_sqe(req);
6636         }
6637 }
6638
6639 static inline void io_queue_link_head(struct io_kiocb *req)
6640 {
6641         if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6642                 io_put_req(req);
6643                 io_req_complete(req, -ECANCELED);
6644         } else
6645                 io_queue_sqe(req, NULL);
6646 }
6647
6648 struct io_submit_link {
6649         struct io_kiocb *head;
6650         struct io_kiocb *last;
6651 };
6652
6653 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6654                          struct io_submit_link *link)
6655 {
6656         struct io_ring_ctx *ctx = req->ctx;
6657         int ret;
6658
6659         /*
6660          * If we already have a head request, queue this one for async
6661          * submittal once the head completes. If we don't have a head but
6662          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6663          * submitted sync once the chain is complete. If none of those
6664          * conditions are true (normal request), then just queue it.
6665          */
6666         if (link->head) {
6667                 struct io_kiocb *head = link->head;
6668
6669                 /*
6670                  * Taking sequential execution of a link, draining both sides
6671                  * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6672                  * requests in the link. So, it drains the head and the
6673                  * next after the link request. The last one is done via
6674                  * drain_next flag to persist the effect across calls.
6675                  */
6676                 if (req->flags & REQ_F_IO_DRAIN) {
6677                         head->flags |= REQ_F_IO_DRAIN;
6678                         ctx->drain_next = 1;
6679                 }
6680                 ret = io_req_defer_prep(req, sqe);
6681                 if (unlikely(ret)) {
6682                         /* fail even hard links since we don't submit */
6683                         head->flags |= REQ_F_FAIL_LINK;
6684                         return ret;
6685                 }
6686                 trace_io_uring_link(ctx, req, head);
6687                 link->last->link = req;
6688                 link->last = req;
6689
6690                 /* last request of a link, enqueue the link */
6691                 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6692                         io_queue_link_head(head);
6693                         link->head = NULL;
6694                 }
6695         } else {
6696                 if (unlikely(ctx->drain_next)) {
6697                         req->flags |= REQ_F_IO_DRAIN;
6698                         ctx->drain_next = 0;
6699                 }
6700                 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6701                         ret = io_req_defer_prep(req, sqe);
6702                         if (unlikely(ret))
6703                                 req->flags |= REQ_F_FAIL_LINK;
6704                         link->head = req;
6705                         link->last = req;
6706                 } else {
6707                         io_queue_sqe(req, sqe);
6708                 }
6709         }
6710
6711         return 0;
6712 }
6713
6714 /*
6715  * Batched submission is done, ensure local IO is flushed out.
6716  */
6717 static void io_submit_state_end(struct io_submit_state *state,
6718                                 struct io_ring_ctx *ctx)
6719 {
6720         if (state->comp.nr)
6721                 io_submit_flush_completions(&state->comp, ctx);
6722         if (state->plug_started)
6723                 blk_finish_plug(&state->plug);
6724         io_state_file_put(state);
6725 }
6726
6727 /*
6728  * Start submission side cache.
6729  */
6730 static void io_submit_state_start(struct io_submit_state *state,
6731                                   unsigned int max_ios)
6732 {
6733         state->plug_started = false;
6734         state->ios_left = max_ios;
6735 }
6736
6737 static void io_commit_sqring(struct io_ring_ctx *ctx)
6738 {
6739         struct io_rings *rings = ctx->rings;
6740
6741         /*
6742          * Ensure any loads from the SQEs are done at this point,
6743          * since once we write the new head, the application could
6744          * write new data to them.
6745          */
6746         smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6747 }
6748
6749 /*
6750  * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6751  * that is mapped by userspace. This means that care needs to be taken to
6752  * ensure that reads are stable, as we cannot rely on userspace always
6753  * being a good citizen. If members of the sqe are validated and then later
6754  * used, it's important that those reads are done through READ_ONCE() to
6755  * prevent a re-load down the line.
6756  */
6757 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6758 {
6759         u32 *sq_array = ctx->sq_array;
6760         unsigned head;
6761
6762         /*
6763          * The cached sq head (or cq tail) serves two purposes:
6764          *
6765          * 1) allows us to batch the cost of updating the user visible
6766          *    head updates.
6767          * 2) allows the kernel side to track the head on its own, even
6768          *    though the application is the one updating it.
6769          */
6770         head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6771         if (likely(head < ctx->sq_entries))
6772                 return &ctx->sq_sqes[head];
6773
6774         /* drop invalid entries */
6775         ctx->cached_sq_dropped++;
6776         WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6777         return NULL;
6778 }
6779
6780 /*
6781  * Check SQE restrictions (opcode and flags).
6782  *
6783  * Returns 'true' if SQE is allowed, 'false' otherwise.
6784  */
6785 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6786                                         struct io_kiocb *req,
6787                                         unsigned int sqe_flags)
6788 {
6789         if (!ctx->restricted)
6790                 return true;
6791
6792         if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6793                 return false;
6794
6795         if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6796             ctx->restrictions.sqe_flags_required)
6797                 return false;
6798
6799         if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6800                           ctx->restrictions.sqe_flags_required))
6801                 return false;
6802
6803         return true;
6804 }
6805
6806 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6807                                 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6808                                 IOSQE_BUFFER_SELECT)
6809
6810 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6811                        const struct io_uring_sqe *sqe)
6812 {
6813         struct io_submit_state *state;
6814         unsigned int sqe_flags;
6815         int id, ret = 0;
6816
6817         req->opcode = READ_ONCE(sqe->opcode);
6818         /* same numerical values with corresponding REQ_F_*, safe to copy */
6819         req->flags = sqe_flags = READ_ONCE(sqe->flags);
6820         req->user_data = READ_ONCE(sqe->user_data);
6821         req->async_data = NULL;
6822         req->file = NULL;
6823         req->ctx = ctx;
6824         req->link = NULL;
6825         req->fixed_rsrc_refs = NULL;
6826         /* one is dropped after submission, the other at completion */
6827         refcount_set(&req->refs, 2);
6828         req->task = current;
6829         req->result = 0;
6830
6831         /* enforce forwards compatibility on users */
6832         if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6833                 return -EINVAL;
6834
6835         if (unlikely(req->opcode >= IORING_OP_LAST))
6836                 return -EINVAL;
6837
6838         if (unlikely(io_sq_thread_acquire_mm_files(ctx, req)))
6839                 return -EFAULT;
6840
6841         if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6842                 return -EACCES;
6843
6844         if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6845             !io_op_defs[req->opcode].buffer_select)
6846                 return -EOPNOTSUPP;
6847
6848         id = READ_ONCE(sqe->personality);
6849         if (id) {
6850                 struct io_identity *iod;
6851
6852                 iod = idr_find(&ctx->personality_idr, id);
6853                 if (unlikely(!iod))
6854                         return -EINVAL;
6855                 refcount_inc(&iod->count);
6856
6857                 __io_req_init_async(req);
6858                 get_cred(iod->creds);
6859                 req->work.identity = iod;
6860                 req->work.flags |= IO_WQ_WORK_CREDS;
6861         }
6862
6863         state = &ctx->submit_state;
6864
6865         /*
6866          * Plug now if we have more than 1 IO left after this, and the target
6867          * is potentially a read/write to block based storage.
6868          */
6869         if (!state->plug_started && state->ios_left > 1 &&
6870             io_op_defs[req->opcode].plug) {
6871                 blk_start_plug(&state->plug);
6872                 state->plug_started = true;
6873         }
6874
6875         if (io_op_defs[req->opcode].needs_file) {
6876                 bool fixed = req->flags & REQ_F_FIXED_FILE;
6877
6878                 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6879                 if (unlikely(!req->file))
6880                         ret = -EBADF;
6881         }
6882
6883         state->ios_left--;
6884         return ret;
6885 }
6886
6887 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6888 {
6889         struct io_submit_link link;
6890         int i, submitted = 0;
6891
6892         /* if we have a backlog and couldn't flush it all, return BUSY */
6893         if (test_bit(0, &ctx->sq_check_overflow)) {
6894                 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6895                         return -EBUSY;
6896         }
6897
6898         /* make sure SQ entry isn't read before tail */
6899         nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6900
6901         if (!percpu_ref_tryget_many(&ctx->refs, nr))
6902                 return -EAGAIN;
6903
6904         percpu_counter_add(&current->io_uring->inflight, nr);
6905         refcount_add(nr, &current->usage);
6906
6907         io_submit_state_start(&ctx->submit_state, nr);
6908         link.head = NULL;
6909
6910         for (i = 0; i < nr; i++) {
6911                 const struct io_uring_sqe *sqe;
6912                 struct io_kiocb *req;
6913                 int err;
6914
6915                 req = io_alloc_req(ctx);
6916                 if (unlikely(!req)) {
6917                         if (!submitted)
6918                                 submitted = -EAGAIN;
6919                         break;
6920                 }
6921                 sqe = io_get_sqe(ctx);
6922                 if (unlikely(!sqe)) {
6923                         kmem_cache_free(req_cachep, req);
6924                         break;
6925                 }
6926                 /* will complete beyond this point, count as submitted */
6927                 submitted++;
6928
6929                 err = io_init_req(ctx, req, sqe);
6930                 if (unlikely(err)) {
6931 fail_req:
6932                         io_put_req(req);
6933                         io_req_complete(req, err);
6934                         break;
6935                 }
6936
6937                 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6938                                         true, ctx->flags & IORING_SETUP_SQPOLL);
6939                 err = io_submit_sqe(req, sqe, &link);
6940                 if (err)
6941                         goto fail_req;
6942         }
6943
6944         if (unlikely(submitted != nr)) {
6945                 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6946                 struct io_uring_task *tctx = current->io_uring;
6947                 int unused = nr - ref_used;
6948
6949                 percpu_ref_put_many(&ctx->refs, unused);
6950                 percpu_counter_sub(&tctx->inflight, unused);
6951                 put_task_struct_many(current, unused);
6952         }
6953         if (link.head)
6954                 io_queue_link_head(link.head);
6955         io_submit_state_end(&ctx->submit_state, ctx);
6956
6957          /* Commit SQ ring head once we've consumed and submitted all SQEs */
6958         io_commit_sqring(ctx);
6959
6960         return submitted;
6961 }
6962
6963 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6964 {
6965         /* Tell userspace we may need a wakeup call */
6966         spin_lock_irq(&ctx->completion_lock);
6967         ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6968         spin_unlock_irq(&ctx->completion_lock);
6969 }
6970
6971 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6972 {
6973         spin_lock_irq(&ctx->completion_lock);
6974         ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6975         spin_unlock_irq(&ctx->completion_lock);
6976 }
6977
6978 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6979 {
6980         unsigned int to_submit;
6981         int ret = 0;
6982
6983         to_submit = io_sqring_entries(ctx);
6984         /* if we're handling multiple rings, cap submit size for fairness */
6985         if (cap_entries && to_submit > 8)
6986                 to_submit = 8;
6987
6988         if (!list_empty(&ctx->iopoll_list) || to_submit) {
6989                 unsigned nr_events = 0;
6990
6991                 mutex_lock(&ctx->uring_lock);
6992                 if (!list_empty(&ctx->iopoll_list))
6993                         io_do_iopoll(ctx, &nr_events, 0);
6994
6995                 if (to_submit && !ctx->sqo_dead &&
6996                     likely(!percpu_ref_is_dying(&ctx->refs)))
6997                         ret = io_submit_sqes(ctx, to_submit);
6998                 mutex_unlock(&ctx->uring_lock);
6999         }
7000
7001         if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
7002                 wake_up(&ctx->sqo_sq_wait);
7003
7004         return ret;
7005 }
7006
7007 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7008 {
7009         struct io_ring_ctx *ctx;
7010         unsigned sq_thread_idle = 0;
7011
7012         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7013                 if (sq_thread_idle < ctx->sq_thread_idle)
7014                         sq_thread_idle = ctx->sq_thread_idle;
7015         }
7016
7017         sqd->sq_thread_idle = sq_thread_idle;
7018 }
7019
7020 static void io_sqd_init_new(struct io_sq_data *sqd)
7021 {
7022         struct io_ring_ctx *ctx;
7023
7024         while (!list_empty(&sqd->ctx_new_list)) {
7025                 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
7026                 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
7027                 complete(&ctx->sq_thread_comp);
7028         }
7029
7030         io_sqd_update_thread_idle(sqd);
7031 }
7032
7033 static int io_sq_thread(void *data)
7034 {
7035         struct cgroup_subsys_state *cur_css = NULL;
7036         struct files_struct *old_files = current->files;
7037         struct nsproxy *old_nsproxy = current->nsproxy;
7038         const struct cred *old_cred = NULL;
7039         struct io_sq_data *sqd = data;
7040         struct io_ring_ctx *ctx;
7041         unsigned long timeout = 0;
7042         DEFINE_WAIT(wait);
7043
7044         task_lock(current);
7045         current->files = NULL;
7046         current->nsproxy = NULL;
7047         task_unlock(current);
7048
7049         while (!kthread_should_stop()) {
7050                 int ret;
7051                 bool cap_entries, sqt_spin, needs_sched;
7052
7053                 /*
7054                  * Any changes to the sqd lists are synchronized through the
7055                  * kthread parking. This synchronizes the thread vs users,
7056                  * the users are synchronized on the sqd->ctx_lock.
7057                  */
7058                 if (kthread_should_park()) {
7059                         kthread_parkme();
7060                         /*
7061                          * When sq thread is unparked, in case the previous park operation
7062                          * comes from io_put_sq_data(), which means that sq thread is going
7063                          * to be stopped, so here needs to have a check.
7064                          */
7065                         if (kthread_should_stop())
7066                                 break;
7067                 }
7068
7069                 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
7070                         io_sqd_init_new(sqd);
7071                         timeout = jiffies + sqd->sq_thread_idle;
7072                 }
7073
7074                 sqt_spin = false;
7075                 cap_entries = !list_is_singular(&sqd->ctx_list);
7076                 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7077                         if (current->cred != ctx->creds) {
7078                                 if (old_cred)
7079                                         revert_creds(old_cred);
7080                                 old_cred = override_creds(ctx->creds);
7081                         }
7082                         io_sq_thread_associate_blkcg(ctx, &cur_css);
7083 #ifdef CONFIG_AUDIT
7084                         current->loginuid = ctx->loginuid;
7085                         current->sessionid = ctx->sessionid;
7086 #endif
7087
7088                         ret = __io_sq_thread(ctx, cap_entries);
7089                         if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7090                                 sqt_spin = true;
7091
7092                         io_sq_thread_drop_mm_files();
7093                 }
7094
7095                 if (sqt_spin || !time_after(jiffies, timeout)) {
7096                         io_run_task_work();
7097                         io_sq_thread_drop_mm_files();
7098                         cond_resched();
7099                         if (sqt_spin)
7100                                 timeout = jiffies + sqd->sq_thread_idle;
7101                         continue;
7102                 }
7103
7104                 needs_sched = true;
7105                 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7106                 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7107                         if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7108                             !list_empty_careful(&ctx->iopoll_list)) {
7109                                 needs_sched = false;
7110                                 break;
7111                         }
7112                         if (io_sqring_entries(ctx)) {
7113                                 needs_sched = false;
7114                                 break;
7115                         }
7116                 }
7117
7118                 if (needs_sched && !kthread_should_park()) {
7119                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7120                                 io_ring_set_wakeup_flag(ctx);
7121
7122                         schedule();
7123                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7124                                 io_ring_clear_wakeup_flag(ctx);
7125                 }
7126
7127                 finish_wait(&sqd->wait, &wait);
7128                 timeout = jiffies + sqd->sq_thread_idle;
7129         }
7130
7131         io_run_task_work();
7132         io_sq_thread_drop_mm_files();
7133
7134         if (cur_css)
7135                 io_sq_thread_unassociate_blkcg();
7136         if (old_cred)
7137                 revert_creds(old_cred);
7138
7139         task_lock(current);
7140         current->files = old_files;
7141         current->nsproxy = old_nsproxy;
7142         task_unlock(current);
7143
7144         kthread_parkme();
7145
7146         return 0;
7147 }
7148
7149 struct io_wait_queue {
7150         struct wait_queue_entry wq;
7151         struct io_ring_ctx *ctx;
7152         unsigned to_wait;
7153         unsigned nr_timeouts;
7154 };
7155
7156 static inline bool io_should_wake(struct io_wait_queue *iowq)
7157 {
7158         struct io_ring_ctx *ctx = iowq->ctx;
7159
7160         /*
7161          * Wake up if we have enough events, or if a timeout occurred since we
7162          * started waiting. For timeouts, we always want to return to userspace,
7163          * regardless of event count.
7164          */
7165         return io_cqring_events(ctx) >= iowq->to_wait ||
7166                         atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7167 }
7168
7169 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7170                             int wake_flags, void *key)
7171 {
7172         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7173                                                         wq);
7174
7175         /*
7176          * Cannot safely flush overflowed CQEs from here, ensure we wake up
7177          * the task, and the next invocation will do it.
7178          */
7179         if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
7180                 return autoremove_wake_function(curr, mode, wake_flags, key);
7181         return -1;
7182 }
7183
7184 static int io_run_task_work_sig(void)
7185 {
7186         if (io_run_task_work())
7187                 return 1;
7188         if (!signal_pending(current))
7189                 return 0;
7190         if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
7191                 return -ERESTARTSYS;
7192         return -EINTR;
7193 }
7194
7195 /* when returns >0, the caller should retry */
7196 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7197                                           struct io_wait_queue *iowq,
7198                                           signed long *timeout)
7199 {
7200         int ret;
7201
7202         /* make sure we run task_work before checking for signals */
7203         ret = io_run_task_work_sig();
7204         if (ret || io_should_wake(iowq))
7205                 return ret;
7206         /* let the caller flush overflows, retry */
7207         if (test_bit(0, &ctx->cq_check_overflow))
7208                 return 1;
7209
7210         *timeout = schedule_timeout(*timeout);
7211         return !*timeout ? -ETIME : 1;
7212 }
7213
7214 /*
7215  * Wait until events become available, if we don't already have some. The
7216  * application must reap them itself, as they reside on the shared cq ring.
7217  */
7218 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7219                           const sigset_t __user *sig, size_t sigsz,
7220                           struct __kernel_timespec __user *uts)
7221 {
7222         struct io_wait_queue iowq = {
7223                 .wq = {
7224                         .private        = current,
7225                         .func           = io_wake_function,
7226                         .entry          = LIST_HEAD_INIT(iowq.wq.entry),
7227                 },
7228                 .ctx            = ctx,
7229                 .to_wait        = min_events,
7230         };
7231         struct io_rings *rings = ctx->rings;
7232         signed long timeout = MAX_SCHEDULE_TIMEOUT;
7233         int ret;
7234
7235         do {
7236                 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7237                 if (io_cqring_events(ctx) >= min_events)
7238                         return 0;
7239                 if (!io_run_task_work())
7240                         break;
7241         } while (1);
7242
7243         if (sig) {
7244 #ifdef CONFIG_COMPAT
7245                 if (in_compat_syscall())
7246                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7247                                                       sigsz);
7248                 else
7249 #endif
7250                         ret = set_user_sigmask(sig, sigsz);
7251
7252                 if (ret)
7253                         return ret;
7254         }
7255
7256         if (uts) {
7257                 struct timespec64 ts;
7258
7259                 if (get_timespec64(&ts, uts))
7260                         return -EFAULT;
7261                 timeout = timespec64_to_jiffies(&ts);
7262         }
7263
7264         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7265         trace_io_uring_cqring_wait(ctx, min_events);
7266         do {
7267                 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7268                 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7269                                                 TASK_INTERRUPTIBLE);
7270                 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7271                 finish_wait(&ctx->wait, &iowq.wq);
7272         } while (ret > 0);
7273
7274         restore_saved_sigmask_unless(ret == -EINTR);
7275
7276         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7277 }
7278
7279 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7280 {
7281 #if defined(CONFIG_UNIX)
7282         if (ctx->ring_sock) {
7283                 struct sock *sock = ctx->ring_sock->sk;
7284                 struct sk_buff *skb;
7285
7286                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7287                         kfree_skb(skb);
7288         }
7289 #else
7290         int i;
7291
7292         for (i = 0; i < ctx->nr_user_files; i++) {
7293                 struct file *file;
7294
7295                 file = io_file_from_index(ctx, i);
7296                 if (file)
7297                         fput(file);
7298         }
7299 #endif
7300 }
7301
7302 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7303 {
7304         struct fixed_rsrc_data *data;
7305
7306         data = container_of(ref, struct fixed_rsrc_data, refs);
7307         complete(&data->done);
7308 }
7309
7310 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7311 {
7312         spin_lock_bh(&ctx->rsrc_ref_lock);
7313 }
7314
7315 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7316 {
7317         spin_unlock_bh(&ctx->rsrc_ref_lock);
7318 }
7319
7320 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
7321                                  struct fixed_rsrc_data *rsrc_data,
7322                                  struct fixed_rsrc_ref_node *ref_node)
7323 {
7324         io_rsrc_ref_lock(ctx);
7325         rsrc_data->node = ref_node;
7326         list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
7327         io_rsrc_ref_unlock(ctx);
7328         percpu_ref_get(&rsrc_data->refs);
7329 }
7330
7331 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
7332                                struct io_ring_ctx *ctx,
7333                                struct fixed_rsrc_ref_node *backup_node)
7334 {
7335         struct fixed_rsrc_ref_node *ref_node;
7336         int ret;
7337
7338         io_rsrc_ref_lock(ctx);
7339         ref_node = data->node;
7340         io_rsrc_ref_unlock(ctx);
7341         if (ref_node)
7342                 percpu_ref_kill(&ref_node->refs);
7343
7344         percpu_ref_kill(&data->refs);
7345
7346         /* wait for all refs nodes to complete */
7347         flush_delayed_work(&ctx->rsrc_put_work);
7348         do {
7349                 ret = wait_for_completion_interruptible(&data->done);
7350                 if (!ret)
7351                         break;
7352                 ret = io_run_task_work_sig();
7353                 if (ret < 0) {
7354                         percpu_ref_resurrect(&data->refs);
7355                         reinit_completion(&data->done);
7356                         io_sqe_rsrc_set_node(ctx, data, backup_node);
7357                         return ret;
7358                 }
7359         } while (1);
7360
7361         destroy_fixed_rsrc_ref_node(backup_node);
7362         return 0;
7363 }
7364
7365 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7366 {
7367         struct fixed_rsrc_data *data;
7368
7369         data = kzalloc(sizeof(*data), GFP_KERNEL);
7370         if (!data)
7371                 return NULL;
7372
7373         if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7374                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7375                 kfree(data);
7376                 return NULL;
7377         }
7378         data->ctx = ctx;
7379         init_completion(&data->done);
7380         return data;
7381 }
7382
7383 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7384 {
7385         percpu_ref_exit(&data->refs);
7386         kfree(data->table);
7387         kfree(data);
7388 }
7389
7390 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7391 {
7392         struct fixed_rsrc_data *data = ctx->file_data;
7393         struct fixed_rsrc_ref_node *backup_node;
7394         unsigned nr_tables, i;
7395         int ret;
7396
7397         if (!data)
7398                 return -ENXIO;
7399         backup_node = alloc_fixed_rsrc_ref_node(ctx);
7400         if (!backup_node)
7401                 return -ENOMEM;
7402         init_fixed_file_ref_node(ctx, backup_node);
7403
7404         ret = io_rsrc_ref_quiesce(data, ctx, backup_node);
7405         if (ret)
7406                 return ret;
7407
7408         __io_sqe_files_unregister(ctx);
7409         nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7410         for (i = 0; i < nr_tables; i++)
7411                 kfree(data->table[i].files);
7412         free_fixed_rsrc_data(data);
7413         ctx->file_data = NULL;
7414         ctx->nr_user_files = 0;
7415         return 0;
7416 }
7417
7418 static void io_put_sq_data(struct io_sq_data *sqd)
7419 {
7420         if (refcount_dec_and_test(&sqd->refs)) {
7421                 /*
7422                  * The park is a bit of a work-around, without it we get
7423                  * warning spews on shutdown with SQPOLL set and affinity
7424                  * set to a single CPU.
7425                  */
7426                 if (sqd->thread) {
7427                         kthread_park(sqd->thread);
7428                         kthread_stop(sqd->thread);
7429                 }
7430
7431                 kfree(sqd);
7432         }
7433 }
7434
7435 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7436 {
7437         struct io_ring_ctx *ctx_attach;
7438         struct io_sq_data *sqd;
7439         struct fd f;
7440
7441         f = fdget(p->wq_fd);
7442         if (!f.file)
7443                 return ERR_PTR(-ENXIO);
7444         if (f.file->f_op != &io_uring_fops) {
7445                 fdput(f);
7446                 return ERR_PTR(-EINVAL);
7447         }
7448
7449         ctx_attach = f.file->private_data;
7450         sqd = ctx_attach->sq_data;
7451         if (!sqd) {
7452                 fdput(f);
7453                 return ERR_PTR(-EINVAL);
7454         }
7455
7456         refcount_inc(&sqd->refs);
7457         fdput(f);
7458         return sqd;
7459 }
7460
7461 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7462 {
7463         struct io_sq_data *sqd;
7464
7465         if (p->flags & IORING_SETUP_ATTACH_WQ)
7466                 return io_attach_sq_data(p);
7467
7468         sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7469         if (!sqd)
7470                 return ERR_PTR(-ENOMEM);
7471
7472         refcount_set(&sqd->refs, 1);
7473         INIT_LIST_HEAD(&sqd->ctx_list);
7474         INIT_LIST_HEAD(&sqd->ctx_new_list);
7475         mutex_init(&sqd->ctx_lock);
7476         mutex_init(&sqd->lock);
7477         init_waitqueue_head(&sqd->wait);
7478         return sqd;
7479 }
7480
7481 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7482         __releases(&sqd->lock)
7483 {
7484         if (!sqd->thread)
7485                 return;
7486         kthread_unpark(sqd->thread);
7487         mutex_unlock(&sqd->lock);
7488 }
7489
7490 static void io_sq_thread_park(struct io_sq_data *sqd)
7491         __acquires(&sqd->lock)
7492 {
7493         if (!sqd->thread)
7494                 return;
7495         mutex_lock(&sqd->lock);
7496         kthread_park(sqd->thread);
7497 }
7498
7499 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7500 {
7501         struct io_sq_data *sqd = ctx->sq_data;
7502
7503         if (sqd) {
7504                 if (sqd->thread) {
7505                         /*
7506                          * We may arrive here from the error branch in
7507                          * io_sq_offload_create() where the kthread is created
7508                          * without being waked up, thus wake it up now to make
7509                          * sure the wait will complete.
7510                          */
7511                         wake_up_process(sqd->thread);
7512                         wait_for_completion(&ctx->sq_thread_comp);
7513
7514                         io_sq_thread_park(sqd);
7515                 }
7516
7517                 mutex_lock(&sqd->ctx_lock);
7518                 list_del(&ctx->sqd_list);
7519                 io_sqd_update_thread_idle(sqd);
7520                 mutex_unlock(&sqd->ctx_lock);
7521
7522                 if (sqd->thread)
7523                         io_sq_thread_unpark(sqd);
7524
7525                 io_put_sq_data(sqd);
7526                 ctx->sq_data = NULL;
7527         }
7528 }
7529
7530 static void io_finish_async(struct io_ring_ctx *ctx)
7531 {
7532         io_sq_thread_stop(ctx);
7533
7534         if (ctx->io_wq) {
7535                 io_wq_destroy(ctx->io_wq);
7536                 ctx->io_wq = NULL;
7537         }
7538 }
7539
7540 #if defined(CONFIG_UNIX)
7541 /*
7542  * Ensure the UNIX gc is aware of our file set, so we are certain that
7543  * the io_uring can be safely unregistered on process exit, even if we have
7544  * loops in the file referencing.
7545  */
7546 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7547 {
7548         struct sock *sk = ctx->ring_sock->sk;
7549         struct scm_fp_list *fpl;
7550         struct sk_buff *skb;
7551         int i, nr_files;
7552
7553         fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7554         if (!fpl)
7555                 return -ENOMEM;
7556
7557         skb = alloc_skb(0, GFP_KERNEL);
7558         if (!skb) {
7559                 kfree(fpl);
7560                 return -ENOMEM;
7561         }
7562
7563         skb->sk = sk;
7564
7565         nr_files = 0;
7566         fpl->user = get_uid(ctx->user);
7567         for (i = 0; i < nr; i++) {
7568                 struct file *file = io_file_from_index(ctx, i + offset);
7569
7570                 if (!file)
7571                         continue;
7572                 fpl->fp[nr_files] = get_file(file);
7573                 unix_inflight(fpl->user, fpl->fp[nr_files]);
7574                 nr_files++;
7575         }
7576
7577         if (nr_files) {
7578                 fpl->max = SCM_MAX_FD;
7579                 fpl->count = nr_files;
7580                 UNIXCB(skb).fp = fpl;
7581                 skb->destructor = unix_destruct_scm;
7582                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7583                 skb_queue_head(&sk->sk_receive_queue, skb);
7584
7585                 for (i = 0; i < nr_files; i++)
7586                         fput(fpl->fp[i]);
7587         } else {
7588                 kfree_skb(skb);
7589                 kfree(fpl);
7590         }
7591
7592         return 0;
7593 }
7594
7595 /*
7596  * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7597  * causes regular reference counting to break down. We rely on the UNIX
7598  * garbage collection to take care of this problem for us.
7599  */
7600 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7601 {
7602         unsigned left, total;
7603         int ret = 0;
7604
7605         total = 0;
7606         left = ctx->nr_user_files;
7607         while (left) {
7608                 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7609
7610                 ret = __io_sqe_files_scm(ctx, this_files, total);
7611                 if (ret)
7612                         break;
7613                 left -= this_files;
7614                 total += this_files;
7615         }
7616
7617         if (!ret)
7618                 return 0;
7619
7620         while (total < ctx->nr_user_files) {
7621                 struct file *file = io_file_from_index(ctx, total);
7622
7623                 if (file)
7624                         fput(file);
7625                 total++;
7626         }
7627
7628         return ret;
7629 }
7630 #else
7631 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7632 {
7633         return 0;
7634 }
7635 #endif
7636
7637 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7638                                     unsigned nr_tables, unsigned nr_files)
7639 {
7640         int i;
7641
7642         for (i = 0; i < nr_tables; i++) {
7643                 struct fixed_rsrc_table *table = &file_data->table[i];
7644                 unsigned this_files;
7645
7646                 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7647                 table->files = kcalloc(this_files, sizeof(struct file *),
7648                                         GFP_KERNEL);
7649                 if (!table->files)
7650                         break;
7651                 nr_files -= this_files;
7652         }
7653
7654         if (i == nr_tables)
7655                 return 0;
7656
7657         for (i = 0; i < nr_tables; i++) {
7658                 struct fixed_rsrc_table *table = &file_data->table[i];
7659                 kfree(table->files);
7660         }
7661         return 1;
7662 }
7663
7664 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7665 {
7666         struct file *file = prsrc->file;
7667 #if defined(CONFIG_UNIX)
7668         struct sock *sock = ctx->ring_sock->sk;
7669         struct sk_buff_head list, *head = &sock->sk_receive_queue;
7670         struct sk_buff *skb;
7671         int i;
7672
7673         __skb_queue_head_init(&list);
7674
7675         /*
7676          * Find the skb that holds this file in its SCM_RIGHTS. When found,
7677          * remove this entry and rearrange the file array.
7678          */
7679         skb = skb_dequeue(head);
7680         while (skb) {
7681                 struct scm_fp_list *fp;
7682
7683                 fp = UNIXCB(skb).fp;
7684                 for (i = 0; i < fp->count; i++) {
7685                         int left;
7686
7687                         if (fp->fp[i] != file)
7688                                 continue;
7689
7690                         unix_notinflight(fp->user, fp->fp[i]);
7691                         left = fp->count - 1 - i;
7692                         if (left) {
7693                                 memmove(&fp->fp[i], &fp->fp[i + 1],
7694                                                 left * sizeof(struct file *));
7695                         }
7696                         fp->count--;
7697                         if (!fp->count) {
7698                                 kfree_skb(skb);
7699                                 skb = NULL;
7700                         } else {
7701                                 __skb_queue_tail(&list, skb);
7702                         }
7703                         fput(file);
7704                         file = NULL;
7705                         break;
7706                 }
7707
7708                 if (!file)
7709                         break;
7710
7711                 __skb_queue_tail(&list, skb);
7712
7713                 skb = skb_dequeue(head);
7714         }
7715
7716         if (skb_peek(&list)) {
7717                 spin_lock_irq(&head->lock);
7718                 while ((skb = __skb_dequeue(&list)) != NULL)
7719                         __skb_queue_tail(head, skb);
7720                 spin_unlock_irq(&head->lock);
7721         }
7722 #else
7723         fput(file);
7724 #endif
7725 }
7726
7727 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7728 {
7729         struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7730         struct io_ring_ctx *ctx = rsrc_data->ctx;
7731         struct io_rsrc_put *prsrc, *tmp;
7732
7733         list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7734                 list_del(&prsrc->list);
7735                 ref_node->rsrc_put(ctx, prsrc);
7736                 kfree(prsrc);
7737         }
7738
7739         percpu_ref_exit(&ref_node->refs);
7740         kfree(ref_node);
7741         percpu_ref_put(&rsrc_data->refs);
7742 }
7743
7744 static void io_rsrc_put_work(struct work_struct *work)
7745 {
7746         struct io_ring_ctx *ctx;
7747         struct llist_node *node;
7748
7749         ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7750         node = llist_del_all(&ctx->rsrc_put_llist);
7751
7752         while (node) {
7753                 struct fixed_rsrc_ref_node *ref_node;
7754                 struct llist_node *next = node->next;
7755
7756                 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7757                 __io_rsrc_put_work(ref_node);
7758                 node = next;
7759         }
7760 }
7761
7762 static struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
7763                                         unsigned i)
7764 {
7765         struct fixed_rsrc_table *table;
7766
7767         table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7768         return &table->files[i & IORING_FILE_TABLE_MASK];
7769 }
7770
7771 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7772 {
7773         struct fixed_rsrc_ref_node *ref_node;
7774         struct fixed_rsrc_data *data;
7775         struct io_ring_ctx *ctx;
7776         bool first_add = false;
7777         int delay = HZ;
7778
7779         ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7780         data = ref_node->rsrc_data;
7781         ctx = data->ctx;
7782
7783         io_rsrc_ref_lock(ctx);
7784         ref_node->done = true;
7785
7786         while (!list_empty(&ctx->rsrc_ref_list)) {
7787                 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7788                                         struct fixed_rsrc_ref_node, node);
7789                 /* recycle ref nodes in order */
7790                 if (!ref_node->done)
7791                         break;
7792                 list_del(&ref_node->node);
7793                 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7794         }
7795         io_rsrc_ref_unlock(ctx);
7796
7797         if (percpu_ref_is_dying(&data->refs))
7798                 delay = 0;
7799
7800         if (!delay)
7801                 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7802         else if (first_add)
7803                 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7804 }
7805
7806 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7807                         struct io_ring_ctx *ctx)
7808 {
7809         struct fixed_rsrc_ref_node *ref_node;
7810
7811         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7812         if (!ref_node)
7813                 return NULL;
7814
7815         if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7816                             0, GFP_KERNEL)) {
7817                 kfree(ref_node);
7818                 return NULL;
7819         }
7820         INIT_LIST_HEAD(&ref_node->node);
7821         INIT_LIST_HEAD(&ref_node->rsrc_list);
7822         ref_node->done = false;
7823         return ref_node;
7824 }
7825
7826 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7827                                      struct fixed_rsrc_ref_node *ref_node)
7828 {
7829         ref_node->rsrc_data = ctx->file_data;
7830         ref_node->rsrc_put = io_ring_file_put;
7831 }
7832
7833 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7834 {
7835         percpu_ref_exit(&ref_node->refs);
7836         kfree(ref_node);
7837 }
7838
7839
7840 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7841                                  unsigned nr_args)
7842 {
7843         __s32 __user *fds = (__s32 __user *) arg;
7844         unsigned nr_tables, i;
7845         struct file *file;
7846         int fd, ret = -ENOMEM;
7847         struct fixed_rsrc_ref_node *ref_node;
7848         struct fixed_rsrc_data *file_data;
7849
7850         if (ctx->file_data)
7851                 return -EBUSY;
7852         if (!nr_args)
7853                 return -EINVAL;
7854         if (nr_args > IORING_MAX_FIXED_FILES)
7855                 return -EMFILE;
7856
7857         file_data = alloc_fixed_rsrc_data(ctx);
7858         if (!file_data)
7859                 return -ENOMEM;
7860         ctx->file_data = file_data;
7861
7862         nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7863         file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7864                                    GFP_KERNEL);
7865         if (!file_data->table)
7866                 goto out_free;
7867
7868         if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7869                 goto out_free;
7870
7871         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7872                 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7873                         ret = -EFAULT;
7874                         goto out_fput;
7875                 }
7876                 /* allow sparse sets */
7877                 if (fd == -1)
7878                         continue;
7879
7880                 file = fget(fd);
7881                 ret = -EBADF;
7882                 if (!file)
7883                         goto out_fput;
7884
7885                 /*
7886                  * Don't allow io_uring instances to be registered. If UNIX
7887                  * isn't enabled, then this causes a reference cycle and this
7888                  * instance can never get freed. If UNIX is enabled we'll
7889                  * handle it just fine, but there's still no point in allowing
7890                  * a ring fd as it doesn't support regular read/write anyway.
7891                  */
7892                 if (file->f_op == &io_uring_fops) {
7893                         fput(file);
7894                         goto out_fput;
7895                 }
7896                 *io_fixed_file_slot(file_data, i) = file;
7897         }
7898
7899         ret = io_sqe_files_scm(ctx);
7900         if (ret) {
7901                 io_sqe_files_unregister(ctx);
7902                 return ret;
7903         }
7904
7905         ref_node = alloc_fixed_rsrc_ref_node(ctx);
7906         if (!ref_node) {
7907                 io_sqe_files_unregister(ctx);
7908                 return -ENOMEM;
7909         }
7910         init_fixed_file_ref_node(ctx, ref_node);
7911
7912         io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7913         return ret;
7914 out_fput:
7915         for (i = 0; i < ctx->nr_user_files; i++) {
7916                 file = io_file_from_index(ctx, i);
7917                 if (file)
7918                         fput(file);
7919         }
7920         for (i = 0; i < nr_tables; i++)
7921                 kfree(file_data->table[i].files);
7922         ctx->nr_user_files = 0;
7923 out_free:
7924         free_fixed_rsrc_data(ctx->file_data);
7925         ctx->file_data = NULL;
7926         return ret;
7927 }
7928
7929 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7930                                 int index)
7931 {
7932 #if defined(CONFIG_UNIX)
7933         struct sock *sock = ctx->ring_sock->sk;
7934         struct sk_buff_head *head = &sock->sk_receive_queue;
7935         struct sk_buff *skb;
7936
7937         /*
7938          * See if we can merge this file into an existing skb SCM_RIGHTS
7939          * file set. If there's no room, fall back to allocating a new skb
7940          * and filling it in.
7941          */
7942         spin_lock_irq(&head->lock);
7943         skb = skb_peek(head);
7944         if (skb) {
7945                 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7946
7947                 if (fpl->count < SCM_MAX_FD) {
7948                         __skb_unlink(skb, head);
7949                         spin_unlock_irq(&head->lock);
7950                         fpl->fp[fpl->count] = get_file(file);
7951                         unix_inflight(fpl->user, fpl->fp[fpl->count]);
7952                         fpl->count++;
7953                         spin_lock_irq(&head->lock);
7954                         __skb_queue_head(head, skb);
7955                 } else {
7956                         skb = NULL;
7957                 }
7958         }
7959         spin_unlock_irq(&head->lock);
7960
7961         if (skb) {
7962                 fput(file);
7963                 return 0;
7964         }
7965
7966         return __io_sqe_files_scm(ctx, 1, index);
7967 #else
7968         return 0;
7969 #endif
7970 }
7971
7972 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7973 {
7974         struct io_rsrc_put *prsrc;
7975         struct fixed_rsrc_ref_node *ref_node = data->node;
7976
7977         prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7978         if (!prsrc)
7979                 return -ENOMEM;
7980
7981         prsrc->rsrc = rsrc;
7982         list_add(&prsrc->list, &ref_node->rsrc_list);
7983
7984         return 0;
7985 }
7986
7987 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7988                                         struct file *file)
7989 {
7990         return io_queue_rsrc_removal(data, (void *)file);
7991 }
7992
7993 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7994                                  struct io_uring_rsrc_update *up,
7995                                  unsigned nr_args)
7996 {
7997         struct fixed_rsrc_data *data = ctx->file_data;
7998         struct fixed_rsrc_ref_node *ref_node;
7999         struct file *file, **file_slot;
8000         __s32 __user *fds;
8001         int fd, i, err;
8002         __u32 done;
8003         bool needs_switch = false;
8004
8005         if (check_add_overflow(up->offset, nr_args, &done))
8006                 return -EOVERFLOW;
8007         if (done > ctx->nr_user_files)
8008                 return -EINVAL;
8009
8010         ref_node = alloc_fixed_rsrc_ref_node(ctx);
8011         if (!ref_node)
8012                 return -ENOMEM;
8013         init_fixed_file_ref_node(ctx, ref_node);
8014
8015         fds = u64_to_user_ptr(up->data);
8016         for (done = 0; done < nr_args; done++) {
8017                 err = 0;
8018                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
8019                         err = -EFAULT;
8020                         break;
8021                 }
8022                 if (fd == IORING_REGISTER_FILES_SKIP)
8023                         continue;
8024
8025                 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8026                 file_slot = io_fixed_file_slot(ctx->file_data, i);
8027
8028                 if (*file_slot) {
8029                         err = io_queue_file_removal(data, *file_slot);
8030                         if (err)
8031                                 break;
8032                         *file_slot = NULL;
8033                         needs_switch = true;
8034                 }
8035                 if (fd != -1) {
8036                         file = fget(fd);
8037                         if (!file) {
8038                                 err = -EBADF;
8039                                 break;
8040                         }
8041                         /*
8042                          * Don't allow io_uring instances to be registered. If
8043                          * UNIX isn't enabled, then this causes a reference
8044                          * cycle and this instance can never get freed. If UNIX
8045                          * is enabled we'll handle it just fine, but there's
8046                          * still no point in allowing a ring fd as it doesn't
8047                          * support regular read/write anyway.
8048                          */
8049                         if (file->f_op == &io_uring_fops) {
8050                                 fput(file);
8051                                 err = -EBADF;
8052                                 break;
8053                         }
8054                         *file_slot = file;
8055                         err = io_sqe_file_register(ctx, file, i);
8056                         if (err) {
8057                                 *file_slot = NULL;
8058                                 fput(file);
8059                                 break;
8060                         }
8061                 }
8062         }
8063
8064         if (needs_switch) {
8065                 percpu_ref_kill(&data->node->refs);
8066                 io_sqe_rsrc_set_node(ctx, data, ref_node);
8067         } else
8068                 destroy_fixed_rsrc_ref_node(ref_node);
8069
8070         return done ? done : err;
8071 }
8072
8073 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
8074                                unsigned nr_args)
8075 {
8076         struct io_uring_rsrc_update up;
8077
8078         if (!ctx->file_data)
8079                 return -ENXIO;
8080         if (!nr_args)
8081                 return -EINVAL;
8082         if (copy_from_user(&up, arg, sizeof(up)))
8083                 return -EFAULT;
8084         if (up.resv)
8085                 return -EINVAL;
8086
8087         return __io_sqe_files_update(ctx, &up, nr_args);
8088 }
8089
8090 static struct io_wq_work *io_free_work(struct io_wq_work *work)
8091 {
8092         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8093
8094         req = io_put_req_find_next(req);
8095         return req ? &req->work : NULL;
8096 }
8097
8098 static int io_init_wq_offload(struct io_ring_ctx *ctx,
8099                               struct io_uring_params *p)
8100 {
8101         struct io_wq_data data;
8102         struct fd f;
8103         struct io_ring_ctx *ctx_attach;
8104         unsigned int concurrency;
8105         int ret = 0;
8106
8107         data.user = ctx->user;
8108         data.free_work = io_free_work;
8109         data.do_work = io_wq_submit_work;
8110
8111         if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
8112                 /* Do QD, or 4 * CPUS, whatever is smallest */
8113                 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8114
8115                 ctx->io_wq = io_wq_create(concurrency, &data);
8116                 if (IS_ERR(ctx->io_wq)) {
8117                         ret = PTR_ERR(ctx->io_wq);
8118                         ctx->io_wq = NULL;
8119                 }
8120                 return ret;
8121         }
8122
8123         f = fdget(p->wq_fd);
8124         if (!f.file)
8125                 return -EBADF;
8126
8127         if (f.file->f_op != &io_uring_fops) {
8128                 ret = -EINVAL;
8129                 goto out_fput;
8130         }
8131
8132         ctx_attach = f.file->private_data;
8133         /* @io_wq is protected by holding the fd */
8134         if (!io_wq_get(ctx_attach->io_wq, &data)) {
8135                 ret = -EINVAL;
8136                 goto out_fput;
8137         }
8138
8139         ctx->io_wq = ctx_attach->io_wq;
8140 out_fput:
8141         fdput(f);
8142         return ret;
8143 }
8144
8145 static int io_uring_alloc_task_context(struct task_struct *task)
8146 {
8147         struct io_uring_task *tctx;
8148         int ret;
8149
8150         tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
8151         if (unlikely(!tctx))
8152                 return -ENOMEM;
8153
8154         ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8155         if (unlikely(ret)) {
8156                 kfree(tctx);
8157                 return ret;
8158         }
8159
8160         xa_init(&tctx->xa);
8161         init_waitqueue_head(&tctx->wait);
8162         tctx->last = NULL;
8163         atomic_set(&tctx->in_idle, 0);
8164         tctx->sqpoll = false;
8165         io_init_identity(&tctx->__identity);
8166         tctx->identity = &tctx->__identity;
8167         task->io_uring = tctx;
8168         spin_lock_init(&tctx->task_lock);
8169         INIT_WQ_LIST(&tctx->task_list);
8170         tctx->task_state = 0;
8171         init_task_work(&tctx->task_work, tctx_task_work);
8172         return 0;
8173 }
8174
8175 void __io_uring_free(struct task_struct *tsk)
8176 {
8177         struct io_uring_task *tctx = tsk->io_uring;
8178
8179         WARN_ON_ONCE(!xa_empty(&tctx->xa));
8180         WARN_ON_ONCE(refcount_read(&tctx->identity->count) != 1);
8181         if (tctx->identity != &tctx->__identity)
8182                 kfree(tctx->identity);
8183         percpu_counter_destroy(&tctx->inflight);
8184         kfree(tctx);
8185         tsk->io_uring = NULL;
8186 }
8187
8188 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8189                                 struct io_uring_params *p)
8190 {
8191         int ret;
8192
8193         if (ctx->flags & IORING_SETUP_SQPOLL) {
8194                 struct io_sq_data *sqd;
8195
8196                 ret = -EPERM;
8197                 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
8198                         goto err;
8199
8200                 sqd = io_get_sq_data(p);
8201                 if (IS_ERR(sqd)) {
8202                         ret = PTR_ERR(sqd);
8203                         goto err;
8204                 }
8205
8206                 ctx->sq_data = sqd;
8207                 io_sq_thread_park(sqd);
8208                 mutex_lock(&sqd->ctx_lock);
8209                 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
8210                 mutex_unlock(&sqd->ctx_lock);
8211                 io_sq_thread_unpark(sqd);
8212
8213                 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8214                 if (!ctx->sq_thread_idle)
8215                         ctx->sq_thread_idle = HZ;
8216
8217                 if (sqd->thread)
8218                         goto done;
8219
8220                 if (p->flags & IORING_SETUP_SQ_AFF) {
8221                         int cpu = p->sq_thread_cpu;
8222
8223                         ret = -EINVAL;
8224                         if (cpu >= nr_cpu_ids)
8225                                 goto err;
8226                         if (!cpu_online(cpu))
8227                                 goto err;
8228
8229                         sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
8230                                                         cpu, "io_uring-sq");
8231                 } else {
8232                         sqd->thread = kthread_create(io_sq_thread, sqd,
8233                                                         "io_uring-sq");
8234                 }
8235                 if (IS_ERR(sqd->thread)) {
8236                         ret = PTR_ERR(sqd->thread);
8237                         sqd->thread = NULL;
8238                         goto err;
8239                 }
8240                 ret = io_uring_alloc_task_context(sqd->thread);
8241                 if (ret)
8242                         goto err;
8243         } else if (p->flags & IORING_SETUP_SQ_AFF) {
8244                 /* Can't have SQ_AFF without SQPOLL */
8245                 ret = -EINVAL;
8246                 goto err;
8247         }
8248
8249 done:
8250         ret = io_init_wq_offload(ctx, p);
8251         if (ret)
8252                 goto err;
8253
8254         return 0;
8255 err:
8256         io_finish_async(ctx);
8257         return ret;
8258 }
8259
8260 static void io_sq_offload_start(struct io_ring_ctx *ctx)
8261 {
8262         struct io_sq_data *sqd = ctx->sq_data;
8263
8264         if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
8265                 wake_up_process(sqd->thread);
8266 }
8267
8268 static inline void __io_unaccount_mem(struct user_struct *user,
8269                                       unsigned long nr_pages)
8270 {
8271         atomic_long_sub(nr_pages, &user->locked_vm);
8272 }
8273
8274 static inline int __io_account_mem(struct user_struct *user,
8275                                    unsigned long nr_pages)
8276 {
8277         unsigned long page_limit, cur_pages, new_pages;
8278
8279         /* Don't allow more pages than we can safely lock */
8280         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8281
8282         do {
8283                 cur_pages = atomic_long_read(&user->locked_vm);
8284                 new_pages = cur_pages + nr_pages;
8285                 if (new_pages > page_limit)
8286                         return -ENOMEM;
8287         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8288                                         new_pages) != cur_pages);
8289
8290         return 0;
8291 }
8292
8293 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8294 {
8295         if (ctx->limit_mem)
8296                 __io_unaccount_mem(ctx->user, nr_pages);
8297
8298         if (ctx->mm_account)
8299                 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8300 }
8301
8302 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8303 {
8304         int ret;
8305
8306         if (ctx->limit_mem) {
8307                 ret = __io_account_mem(ctx->user, nr_pages);
8308                 if (ret)
8309                         return ret;
8310         }
8311
8312         if (ctx->mm_account)
8313                 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8314
8315         return 0;
8316 }
8317
8318 static void io_mem_free(void *ptr)
8319 {
8320         struct page *page;
8321
8322         if (!ptr)
8323                 return;
8324
8325         page = virt_to_head_page(ptr);
8326         if (put_page_testzero(page))
8327                 free_compound_page(page);
8328 }
8329
8330 static void *io_mem_alloc(size_t size)
8331 {
8332         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8333                                 __GFP_NORETRY | __GFP_ACCOUNT;
8334
8335         return (void *) __get_free_pages(gfp_flags, get_order(size));
8336 }
8337
8338 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8339                                 size_t *sq_offset)
8340 {
8341         struct io_rings *rings;
8342         size_t off, sq_array_size;
8343
8344         off = struct_size(rings, cqes, cq_entries);
8345         if (off == SIZE_MAX)
8346                 return SIZE_MAX;
8347
8348 #ifdef CONFIG_SMP
8349         off = ALIGN(off, SMP_CACHE_BYTES);
8350         if (off == 0)
8351                 return SIZE_MAX;
8352 #endif
8353
8354         if (sq_offset)
8355                 *sq_offset = off;
8356
8357         sq_array_size = array_size(sizeof(u32), sq_entries);
8358         if (sq_array_size == SIZE_MAX)
8359                 return SIZE_MAX;
8360
8361         if (check_add_overflow(off, sq_array_size, &off))
8362                 return SIZE_MAX;
8363
8364         return off;
8365 }
8366
8367 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8368 {
8369         int i, j;
8370
8371         if (!ctx->user_bufs)
8372                 return -ENXIO;
8373
8374         for (i = 0; i < ctx->nr_user_bufs; i++) {
8375                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8376
8377                 for (j = 0; j < imu->nr_bvecs; j++)
8378                         unpin_user_page(imu->bvec[j].bv_page);
8379
8380                 if (imu->acct_pages)
8381                         io_unaccount_mem(ctx, imu->acct_pages);
8382                 kvfree(imu->bvec);
8383                 imu->nr_bvecs = 0;
8384         }
8385
8386         kfree(ctx->user_bufs);
8387         ctx->user_bufs = NULL;
8388         ctx->nr_user_bufs = 0;
8389         return 0;
8390 }
8391
8392 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8393                        void __user *arg, unsigned index)
8394 {
8395         struct iovec __user *src;
8396
8397 #ifdef CONFIG_COMPAT
8398         if (ctx->compat) {
8399                 struct compat_iovec __user *ciovs;
8400                 struct compat_iovec ciov;
8401
8402                 ciovs = (struct compat_iovec __user *) arg;
8403                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8404                         return -EFAULT;
8405
8406                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8407                 dst->iov_len = ciov.iov_len;
8408                 return 0;
8409         }
8410 #endif
8411         src = (struct iovec __user *) arg;
8412         if (copy_from_user(dst, &src[index], sizeof(*dst)))
8413                 return -EFAULT;
8414         return 0;
8415 }
8416
8417 /*
8418  * Not super efficient, but this is just a registration time. And we do cache
8419  * the last compound head, so generally we'll only do a full search if we don't
8420  * match that one.
8421  *
8422  * We check if the given compound head page has already been accounted, to
8423  * avoid double accounting it. This allows us to account the full size of the
8424  * page, not just the constituent pages of a huge page.
8425  */
8426 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8427                                   int nr_pages, struct page *hpage)
8428 {
8429         int i, j;
8430
8431         /* check current page array */
8432         for (i = 0; i < nr_pages; i++) {
8433                 if (!PageCompound(pages[i]))
8434                         continue;
8435                 if (compound_head(pages[i]) == hpage)
8436                         return true;
8437         }
8438
8439         /* check previously registered pages */
8440         for (i = 0; i < ctx->nr_user_bufs; i++) {
8441                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8442
8443                 for (j = 0; j < imu->nr_bvecs; j++) {
8444                         if (!PageCompound(imu->bvec[j].bv_page))
8445                                 continue;
8446                         if (compound_head(imu->bvec[j].bv_page) == hpage)
8447                                 return true;
8448                 }
8449         }
8450
8451         return false;
8452 }
8453
8454 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8455                                  int nr_pages, struct io_mapped_ubuf *imu,
8456                                  struct page **last_hpage)
8457 {
8458         int i, ret;
8459
8460         for (i = 0; i < nr_pages; i++) {
8461                 if (!PageCompound(pages[i])) {
8462                         imu->acct_pages++;
8463                 } else {
8464                         struct page *hpage;
8465
8466                         hpage = compound_head(pages[i]);
8467                         if (hpage == *last_hpage)
8468                                 continue;
8469                         *last_hpage = hpage;
8470                         if (headpage_already_acct(ctx, pages, i, hpage))
8471                                 continue;
8472                         imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8473                 }
8474         }
8475
8476         if (!imu->acct_pages)
8477                 return 0;
8478
8479         ret = io_account_mem(ctx, imu->acct_pages);
8480         if (ret)
8481                 imu->acct_pages = 0;
8482         return ret;
8483 }
8484
8485 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8486                                   struct io_mapped_ubuf *imu,
8487                                   struct page **last_hpage)
8488 {
8489         struct vm_area_struct **vmas = NULL;
8490         struct page **pages = NULL;
8491         unsigned long off, start, end, ubuf;
8492         size_t size;
8493         int ret, pret, nr_pages, i;
8494
8495         ubuf = (unsigned long) iov->iov_base;
8496         end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8497         start = ubuf >> PAGE_SHIFT;
8498         nr_pages = end - start;
8499
8500         ret = -ENOMEM;
8501
8502         pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8503         if (!pages)
8504                 goto done;
8505
8506         vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8507                               GFP_KERNEL);
8508         if (!vmas)
8509                 goto done;
8510
8511         imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8512                                    GFP_KERNEL);
8513         if (!imu->bvec)
8514                 goto done;
8515
8516         ret = 0;
8517         mmap_read_lock(current->mm);
8518         pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8519                               pages, vmas);
8520         if (pret == nr_pages) {
8521                 /* don't support file backed memory */
8522                 for (i = 0; i < nr_pages; i++) {
8523                         struct vm_area_struct *vma = vmas[i];
8524
8525                         if (vma->vm_file &&
8526                             !is_file_hugepages(vma->vm_file)) {
8527                                 ret = -EOPNOTSUPP;
8528                                 break;
8529                         }
8530                 }
8531         } else {
8532                 ret = pret < 0 ? pret : -EFAULT;
8533         }
8534         mmap_read_unlock(current->mm);
8535         if (ret) {
8536                 /*
8537                  * if we did partial map, or found file backed vmas,
8538                  * release any pages we did get
8539                  */
8540                 if (pret > 0)
8541                         unpin_user_pages(pages, pret);
8542                 kvfree(imu->bvec);
8543                 goto done;
8544         }
8545
8546         ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8547         if (ret) {
8548                 unpin_user_pages(pages, pret);
8549                 kvfree(imu->bvec);
8550                 goto done;
8551         }
8552
8553         off = ubuf & ~PAGE_MASK;
8554         size = iov->iov_len;
8555         for (i = 0; i < nr_pages; i++) {
8556                 size_t vec_len;
8557
8558                 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8559                 imu->bvec[i].bv_page = pages[i];
8560                 imu->bvec[i].bv_len = vec_len;
8561                 imu->bvec[i].bv_offset = off;
8562                 off = 0;
8563                 size -= vec_len;
8564         }
8565         /* store original address for later verification */
8566         imu->ubuf = ubuf;
8567         imu->len = iov->iov_len;
8568         imu->nr_bvecs = nr_pages;
8569         ret = 0;
8570 done:
8571         kvfree(pages);
8572         kvfree(vmas);
8573         return ret;
8574 }
8575
8576 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8577 {
8578         if (ctx->user_bufs)
8579                 return -EBUSY;
8580         if (!nr_args || nr_args > UIO_MAXIOV)
8581                 return -EINVAL;
8582
8583         ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8584                                         GFP_KERNEL);
8585         if (!ctx->user_bufs)
8586                 return -ENOMEM;
8587
8588         return 0;
8589 }
8590
8591 static int io_buffer_validate(struct iovec *iov)
8592 {
8593         /*
8594          * Don't impose further limits on the size and buffer
8595          * constraints here, we'll -EINVAL later when IO is
8596          * submitted if they are wrong.
8597          */
8598         if (!iov->iov_base || !iov->iov_len)
8599                 return -EFAULT;
8600
8601         /* arbitrary limit, but we need something */
8602         if (iov->iov_len > SZ_1G)
8603                 return -EFAULT;
8604
8605         return 0;
8606 }
8607
8608 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8609                                    unsigned int nr_args)
8610 {
8611         int i, ret;
8612         struct iovec iov;
8613         struct page *last_hpage = NULL;
8614
8615         ret = io_buffers_map_alloc(ctx, nr_args);
8616         if (ret)
8617                 return ret;
8618
8619         for (i = 0; i < nr_args; i++) {
8620                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8621
8622                 ret = io_copy_iov(ctx, &iov, arg, i);
8623                 if (ret)
8624                         break;
8625
8626                 ret = io_buffer_validate(&iov);
8627                 if (ret)
8628                         break;
8629
8630                 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8631                 if (ret)
8632                         break;
8633
8634                 ctx->nr_user_bufs++;
8635         }
8636
8637         if (ret)
8638                 io_sqe_buffers_unregister(ctx);
8639
8640         return ret;
8641 }
8642
8643 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8644 {
8645         __s32 __user *fds = arg;
8646         int fd;
8647
8648         if (ctx->cq_ev_fd)
8649                 return -EBUSY;
8650
8651         if (copy_from_user(&fd, fds, sizeof(*fds)))
8652                 return -EFAULT;
8653
8654         ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8655         if (IS_ERR(ctx->cq_ev_fd)) {
8656                 int ret = PTR_ERR(ctx->cq_ev_fd);
8657                 ctx->cq_ev_fd = NULL;
8658                 return ret;
8659         }
8660
8661         return 0;
8662 }
8663
8664 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8665 {
8666         if (ctx->cq_ev_fd) {
8667                 eventfd_ctx_put(ctx->cq_ev_fd);
8668                 ctx->cq_ev_fd = NULL;
8669                 return 0;
8670         }
8671
8672         return -ENXIO;
8673 }
8674
8675 static int __io_destroy_buffers(int id, void *p, void *data)
8676 {
8677         struct io_ring_ctx *ctx = data;
8678         struct io_buffer *buf = p;
8679
8680         __io_remove_buffers(ctx, buf, id, -1U);
8681         return 0;
8682 }
8683
8684 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8685 {
8686         idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8687         idr_destroy(&ctx->io_buffer_idr);
8688 }
8689
8690 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8691 {
8692         struct io_kiocb *req, *nxt;
8693
8694         list_for_each_entry_safe(req, nxt, list, compl.list) {
8695                 if (tsk && req->task != tsk)
8696                         continue;
8697                 list_del(&req->compl.list);
8698                 kmem_cache_free(req_cachep, req);
8699         }
8700 }
8701
8702 static void io_req_caches_free(struct io_ring_ctx *ctx, struct task_struct *tsk)
8703 {
8704         struct io_submit_state *submit_state = &ctx->submit_state;
8705
8706         mutex_lock(&ctx->uring_lock);
8707
8708         if (submit_state->free_reqs)
8709                 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8710                                      submit_state->reqs);
8711
8712         io_req_cache_free(&submit_state->comp.free_list, NULL);
8713
8714         spin_lock_irq(&ctx->completion_lock);
8715         io_req_cache_free(&submit_state->comp.locked_free_list, NULL);
8716         spin_unlock_irq(&ctx->completion_lock);
8717
8718         mutex_unlock(&ctx->uring_lock);
8719 }
8720
8721 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8722 {
8723         /*
8724          * Some may use context even when all refs and requests have been put,
8725          * and they are free to do so while still holding uring_lock, see
8726          * __io_req_task_submit(). Wait for them to finish.
8727          */
8728         mutex_lock(&ctx->uring_lock);
8729         mutex_unlock(&ctx->uring_lock);
8730
8731         io_finish_async(ctx);
8732         io_sqe_buffers_unregister(ctx);
8733
8734         if (ctx->sqo_task) {
8735                 put_task_struct(ctx->sqo_task);
8736                 ctx->sqo_task = NULL;
8737                 mmdrop(ctx->mm_account);
8738                 ctx->mm_account = NULL;
8739         }
8740
8741 #ifdef CONFIG_BLK_CGROUP
8742         if (ctx->sqo_blkcg_css)
8743                 css_put(ctx->sqo_blkcg_css);
8744 #endif
8745
8746         io_sqe_files_unregister(ctx);
8747         io_eventfd_unregister(ctx);
8748         io_destroy_buffers(ctx);
8749         idr_destroy(&ctx->personality_idr);
8750
8751 #if defined(CONFIG_UNIX)
8752         if (ctx->ring_sock) {
8753                 ctx->ring_sock->file = NULL; /* so that iput() is called */
8754                 sock_release(ctx->ring_sock);
8755         }
8756 #endif
8757
8758         io_mem_free(ctx->rings);
8759         io_mem_free(ctx->sq_sqes);
8760
8761         percpu_ref_exit(&ctx->refs);
8762         free_uid(ctx->user);
8763         put_cred(ctx->creds);
8764         io_req_caches_free(ctx, NULL);
8765         kfree(ctx->cancel_hash);
8766         kfree(ctx);
8767 }
8768
8769 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8770 {
8771         struct io_ring_ctx *ctx = file->private_data;
8772         __poll_t mask = 0;
8773
8774         poll_wait(file, &ctx->cq_wait, wait);
8775         /*
8776          * synchronizes with barrier from wq_has_sleeper call in
8777          * io_commit_cqring
8778          */
8779         smp_rmb();
8780         if (!io_sqring_full(ctx))
8781                 mask |= EPOLLOUT | EPOLLWRNORM;
8782
8783         /*
8784          * Don't flush cqring overflow list here, just do a simple check.
8785          * Otherwise there could possible be ABBA deadlock:
8786          *      CPU0                    CPU1
8787          *      ----                    ----
8788          * lock(&ctx->uring_lock);
8789          *                              lock(&ep->mtx);
8790          *                              lock(&ctx->uring_lock);
8791          * lock(&ep->mtx);
8792          *
8793          * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8794          * pushs them to do the flush.
8795          */
8796         if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8797                 mask |= EPOLLIN | EPOLLRDNORM;
8798
8799         return mask;
8800 }
8801
8802 static int io_uring_fasync(int fd, struct file *file, int on)
8803 {
8804         struct io_ring_ctx *ctx = file->private_data;
8805
8806         return fasync_helper(fd, file, on, &ctx->cq_fasync);
8807 }
8808
8809 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8810 {
8811         struct io_identity *iod;
8812
8813         iod = idr_remove(&ctx->personality_idr, id);
8814         if (iod) {
8815                 put_cred(iod->creds);
8816                 if (refcount_dec_and_test(&iod->count))
8817                         kfree(iod);
8818                 return 0;
8819         }
8820
8821         return -EINVAL;
8822 }
8823
8824 static int io_remove_personalities(int id, void *p, void *data)
8825 {
8826         struct io_ring_ctx *ctx = data;
8827
8828         io_unregister_personality(ctx, id);
8829         return 0;
8830 }
8831
8832 static void io_ring_exit_work(struct work_struct *work)
8833 {
8834         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8835                                                exit_work);
8836
8837         /*
8838          * If we're doing polled IO and end up having requests being
8839          * submitted async (out-of-line), then completions can come in while
8840          * we're waiting for refs to drop. We need to reap these manually,
8841          * as nobody else will be looking for them.
8842          */
8843         do {
8844                 io_uring_try_cancel_requests(ctx, NULL, NULL);
8845         } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8846         io_ring_ctx_free(ctx);
8847 }
8848
8849 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8850 {
8851         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8852
8853         return req->ctx == data;
8854 }
8855
8856 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8857 {
8858         mutex_lock(&ctx->uring_lock);
8859         percpu_ref_kill(&ctx->refs);
8860
8861         if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8862                 ctx->sqo_dead = 1;
8863
8864         /* if force is set, the ring is going away. always drop after that */
8865         ctx->cq_overflow_flushed = 1;
8866         if (ctx->rings)
8867                 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8868         idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8869         mutex_unlock(&ctx->uring_lock);
8870
8871         io_kill_timeouts(ctx, NULL, NULL);
8872         io_poll_remove_all(ctx, NULL, NULL);
8873
8874         if (ctx->io_wq)
8875                 io_wq_cancel_cb(ctx->io_wq, io_cancel_ctx_cb, ctx, true);
8876
8877         /* if we failed setting up the ctx, we might not have any rings */
8878         io_iopoll_try_reap_events(ctx);
8879
8880         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8881         /*
8882          * Use system_unbound_wq to avoid spawning tons of event kworkers
8883          * if we're exiting a ton of rings at the same time. It just adds
8884          * noise and overhead, there's no discernable change in runtime
8885          * over using system_wq.
8886          */
8887         queue_work(system_unbound_wq, &ctx->exit_work);
8888 }
8889
8890 static int io_uring_release(struct inode *inode, struct file *file)
8891 {
8892         struct io_ring_ctx *ctx = file->private_data;
8893
8894         file->private_data = NULL;
8895         io_ring_ctx_wait_and_kill(ctx);
8896         return 0;
8897 }
8898
8899 struct io_task_cancel {
8900         struct task_struct *task;
8901         struct files_struct *files;
8902 };
8903
8904 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8905 {
8906         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8907         struct io_task_cancel *cancel = data;
8908         bool ret;
8909
8910         if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8911                 unsigned long flags;
8912                 struct io_ring_ctx *ctx = req->ctx;
8913
8914                 /* protect against races with linked timeouts */
8915                 spin_lock_irqsave(&ctx->completion_lock, flags);
8916                 ret = io_match_task(req, cancel->task, cancel->files);
8917                 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8918         } else {
8919                 ret = io_match_task(req, cancel->task, cancel->files);
8920         }
8921         return ret;
8922 }
8923
8924 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8925                                   struct task_struct *task,
8926                                   struct files_struct *files)
8927 {
8928         struct io_defer_entry *de = NULL;
8929         LIST_HEAD(list);
8930
8931         spin_lock_irq(&ctx->completion_lock);
8932         list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8933                 if (io_match_task(de->req, task, files)) {
8934                         list_cut_position(&list, &ctx->defer_list, &de->list);
8935                         break;
8936                 }
8937         }
8938         spin_unlock_irq(&ctx->completion_lock);
8939
8940         while (!list_empty(&list)) {
8941                 de = list_first_entry(&list, struct io_defer_entry, list);
8942                 list_del_init(&de->list);
8943                 req_set_fail_links(de->req);
8944                 io_put_req(de->req);
8945                 io_req_complete(de->req, -ECANCELED);
8946                 kfree(de);
8947         }
8948 }
8949
8950 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8951                                          struct task_struct *task,
8952                                          struct files_struct *files)
8953 {
8954         struct io_task_cancel cancel = { .task = task, .files = files, };
8955
8956         while (1) {
8957                 enum io_wq_cancel cret;
8958                 bool ret = false;
8959
8960                 if (ctx->io_wq) {
8961                         cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb,
8962                                                &cancel, true);
8963                         ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8964                 }
8965
8966                 /* SQPOLL thread does its own polling */
8967                 if (!(ctx->flags & IORING_SETUP_SQPOLL) && !files) {
8968                         while (!list_empty_careful(&ctx->iopoll_list)) {
8969                                 io_iopoll_try_reap_events(ctx);
8970                                 ret = true;
8971                         }
8972                 }
8973
8974                 ret |= io_poll_remove_all(ctx, task, files);
8975                 ret |= io_kill_timeouts(ctx, task, files);
8976                 ret |= io_run_task_work();
8977                 io_cqring_overflow_flush(ctx, true, task, files);
8978                 if (!ret)
8979                         break;
8980                 cond_resched();
8981         }
8982 }
8983
8984 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8985                                    struct task_struct *task,
8986                                    struct files_struct *files)
8987 {
8988         struct io_kiocb *req;
8989         int cnt = 0;
8990
8991         spin_lock_irq(&ctx->inflight_lock);
8992         list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8993                 cnt += io_match_task(req, task, files);
8994         spin_unlock_irq(&ctx->inflight_lock);
8995         return cnt;
8996 }
8997
8998 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8999                                   struct task_struct *task,
9000                                   struct files_struct *files)
9001 {
9002         while (!list_empty_careful(&ctx->inflight_list)) {
9003                 DEFINE_WAIT(wait);
9004                 int inflight;
9005
9006                 inflight = io_uring_count_inflight(ctx, task, files);
9007                 if (!inflight)
9008                         break;
9009
9010                 io_uring_try_cancel_requests(ctx, task, files);
9011
9012                 if (ctx->sq_data)
9013                         io_sq_thread_unpark(ctx->sq_data);
9014                 prepare_to_wait(&task->io_uring->wait, &wait,
9015                                 TASK_UNINTERRUPTIBLE);
9016                 if (inflight == io_uring_count_inflight(ctx, task, files))
9017                         schedule();
9018                 finish_wait(&task->io_uring->wait, &wait);
9019                 if (ctx->sq_data)
9020                         io_sq_thread_park(ctx->sq_data);
9021         }
9022 }
9023
9024 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
9025 {
9026         mutex_lock(&ctx->uring_lock);
9027         ctx->sqo_dead = 1;
9028         mutex_unlock(&ctx->uring_lock);
9029
9030         /* make sure callers enter the ring to get error */
9031         if (ctx->rings)
9032                 io_ring_set_wakeup_flag(ctx);
9033 }
9034
9035 /*
9036  * We need to iteratively cancel requests, in case a request has dependent
9037  * hard links. These persist even for failure of cancelations, hence keep
9038  * looping until none are found.
9039  */
9040 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
9041                                           struct files_struct *files)
9042 {
9043         struct task_struct *task = current;
9044
9045         if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9046                 io_disable_sqo_submit(ctx);
9047                 task = ctx->sq_data->thread;
9048                 atomic_inc(&task->io_uring->in_idle);
9049                 io_sq_thread_park(ctx->sq_data);
9050         }
9051
9052         io_cancel_defer_files(ctx, task, files);
9053
9054         io_uring_cancel_files(ctx, task, files);
9055         if (!files)
9056                 io_uring_try_cancel_requests(ctx, task, NULL);
9057
9058         if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9059                 atomic_dec(&task->io_uring->in_idle);
9060                 io_sq_thread_unpark(ctx->sq_data);
9061         }
9062 }
9063
9064 /*
9065  * Note that this task has used io_uring. We use it for cancelation purposes.
9066  */
9067 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
9068 {
9069         struct io_uring_task *tctx = current->io_uring;
9070         int ret;
9071
9072         if (unlikely(!tctx)) {
9073                 ret = io_uring_alloc_task_context(current);
9074                 if (unlikely(ret))
9075                         return ret;
9076                 tctx = current->io_uring;
9077         }
9078         if (tctx->last != file) {
9079                 void *old = xa_load(&tctx->xa, (unsigned long)file);
9080
9081                 if (!old) {
9082                         get_file(file);
9083                         ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
9084                                                 file, GFP_KERNEL));
9085                         if (ret) {
9086                                 fput(file);
9087                                 return ret;
9088                         }
9089
9090                         /* one and only SQPOLL file note, held by sqo_task */
9091                         WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) &&
9092                                      current != ctx->sqo_task);
9093                 }
9094                 tctx->last = file;
9095         }
9096
9097         /*
9098          * This is race safe in that the task itself is doing this, hence it
9099          * cannot be going through the exit/cancel paths at the same time.
9100          * This cannot be modified while exit/cancel is running.
9101          */
9102         if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
9103                 tctx->sqpoll = true;
9104
9105         return 0;
9106 }
9107
9108 /*
9109  * Remove this io_uring_file -> task mapping.
9110  */
9111 static void io_uring_del_task_file(struct file *file)
9112 {
9113         struct io_uring_task *tctx = current->io_uring;
9114
9115         if (tctx->last == file)
9116                 tctx->last = NULL;
9117         file = xa_erase(&tctx->xa, (unsigned long)file);
9118         if (file)
9119                 fput(file);
9120 }
9121
9122 static void io_uring_remove_task_files(struct io_uring_task *tctx)
9123 {
9124         struct file *file;
9125         unsigned long index;
9126
9127         xa_for_each(&tctx->xa, index, file)
9128                 io_uring_del_task_file(file);
9129 }
9130
9131 void __io_uring_files_cancel(struct files_struct *files)
9132 {
9133         struct io_uring_task *tctx = current->io_uring;
9134         struct file *file;
9135         unsigned long index;
9136
9137         /* make sure overflow events are dropped */
9138         atomic_inc(&tctx->in_idle);
9139         xa_for_each(&tctx->xa, index, file)
9140                 io_uring_cancel_task_requests(file->private_data, files);
9141         atomic_dec(&tctx->in_idle);
9142
9143         if (files)
9144                 io_uring_remove_task_files(tctx);
9145 }
9146
9147 static s64 tctx_inflight(struct io_uring_task *tctx)
9148 {
9149         return percpu_counter_sum(&tctx->inflight);
9150 }
9151
9152 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
9153 {
9154         struct io_uring_task *tctx;
9155         s64 inflight;
9156         DEFINE_WAIT(wait);
9157
9158         if (!ctx->sq_data)
9159                 return;
9160         tctx = ctx->sq_data->thread->io_uring;
9161         io_disable_sqo_submit(ctx);
9162
9163         atomic_inc(&tctx->in_idle);
9164         do {
9165                 /* read completions before cancelations */
9166                 inflight = tctx_inflight(tctx);
9167                 if (!inflight)
9168                         break;
9169                 io_uring_cancel_task_requests(ctx, NULL);
9170
9171                 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9172                 /*
9173                  * If we've seen completions, retry without waiting. This
9174                  * avoids a race where a completion comes in before we did
9175                  * prepare_to_wait().
9176                  */
9177                 if (inflight == tctx_inflight(tctx))
9178                         schedule();
9179                 finish_wait(&tctx->wait, &wait);
9180         } while (1);
9181         atomic_dec(&tctx->in_idle);
9182 }
9183
9184 /*
9185  * Find any io_uring fd that this task has registered or done IO on, and cancel
9186  * requests.
9187  */
9188 void __io_uring_task_cancel(void)
9189 {
9190         struct io_uring_task *tctx = current->io_uring;
9191         DEFINE_WAIT(wait);
9192         s64 inflight;
9193
9194         /* make sure overflow events are dropped */
9195         atomic_inc(&tctx->in_idle);
9196
9197         /* trigger io_disable_sqo_submit() */
9198         if (tctx->sqpoll) {
9199                 struct file *file;
9200                 unsigned long index;
9201
9202                 xa_for_each(&tctx->xa, index, file)
9203                         io_uring_cancel_sqpoll(file->private_data);
9204         }
9205
9206         do {
9207                 /* read completions before cancelations */
9208                 inflight = tctx_inflight(tctx);
9209                 if (!inflight)
9210                         break;
9211                 __io_uring_files_cancel(NULL);
9212
9213                 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9214
9215                 /*
9216                  * If we've seen completions, retry without waiting. This
9217                  * avoids a race where a completion comes in before we did
9218                  * prepare_to_wait().
9219                  */
9220                 if (inflight == tctx_inflight(tctx))
9221                         schedule();
9222                 finish_wait(&tctx->wait, &wait);
9223         } while (1);
9224
9225         atomic_dec(&tctx->in_idle);
9226
9227         io_uring_remove_task_files(tctx);
9228 }
9229
9230 static int io_uring_flush(struct file *file, void *data)
9231 {
9232         struct io_uring_task *tctx = current->io_uring;
9233         struct io_ring_ctx *ctx = file->private_data;
9234
9235         if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
9236                 io_uring_cancel_task_requests(ctx, NULL);
9237                 io_req_caches_free(ctx, current);
9238         }
9239
9240         if (!tctx)
9241                 return 0;
9242
9243         /* we should have cancelled and erased it before PF_EXITING */
9244         WARN_ON_ONCE((current->flags & PF_EXITING) &&
9245                      xa_load(&tctx->xa, (unsigned long)file));
9246
9247         /*
9248          * fput() is pending, will be 2 if the only other ref is our potential
9249          * task file note. If the task is exiting, drop regardless of count.
9250          */
9251         if (atomic_long_read(&file->f_count) != 2)
9252                 return 0;
9253
9254         if (ctx->flags & IORING_SETUP_SQPOLL) {
9255                 /* there is only one file note, which is owned by sqo_task */
9256                 WARN_ON_ONCE(ctx->sqo_task != current &&
9257                              xa_load(&tctx->xa, (unsigned long)file));
9258                 /* sqo_dead check is for when this happens after cancellation */
9259                 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
9260                              !xa_load(&tctx->xa, (unsigned long)file));
9261
9262                 io_disable_sqo_submit(ctx);
9263         }
9264
9265         if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
9266                 io_uring_del_task_file(file);
9267         return 0;
9268 }
9269
9270 static void *io_uring_validate_mmap_request(struct file *file,
9271                                             loff_t pgoff, size_t sz)
9272 {
9273         struct io_ring_ctx *ctx = file->private_data;
9274         loff_t offset = pgoff << PAGE_SHIFT;
9275         struct page *page;
9276         void *ptr;
9277
9278         switch (offset) {
9279         case IORING_OFF_SQ_RING:
9280         case IORING_OFF_CQ_RING:
9281                 ptr = ctx->rings;
9282                 break;
9283         case IORING_OFF_SQES:
9284                 ptr = ctx->sq_sqes;
9285                 break;
9286         default:
9287                 return ERR_PTR(-EINVAL);
9288         }
9289
9290         page = virt_to_head_page(ptr);
9291         if (sz > page_size(page))
9292                 return ERR_PTR(-EINVAL);
9293
9294         return ptr;
9295 }
9296
9297 #ifdef CONFIG_MMU
9298
9299 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9300 {
9301         size_t sz = vma->vm_end - vma->vm_start;
9302         unsigned long pfn;
9303         void *ptr;
9304
9305         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9306         if (IS_ERR(ptr))
9307                 return PTR_ERR(ptr);
9308
9309         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9310         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9311 }
9312
9313 #else /* !CONFIG_MMU */
9314
9315 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9316 {
9317         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9318 }
9319
9320 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9321 {
9322         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9323 }
9324
9325 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9326         unsigned long addr, unsigned long len,
9327         unsigned long pgoff, unsigned long flags)
9328 {
9329         void *ptr;
9330
9331         ptr = io_uring_validate_mmap_request(file, pgoff, len);
9332         if (IS_ERR(ptr))
9333                 return PTR_ERR(ptr);
9334
9335         return (unsigned long) ptr;
9336 }
9337
9338 #endif /* !CONFIG_MMU */
9339
9340 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9341 {
9342         int ret = 0;
9343         DEFINE_WAIT(wait);
9344
9345         do {
9346                 if (!io_sqring_full(ctx))
9347                         break;
9348
9349                 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9350
9351                 if (unlikely(ctx->sqo_dead)) {
9352                         ret = -EOWNERDEAD;
9353                         goto out;
9354                 }
9355
9356                 if (!io_sqring_full(ctx))
9357                         break;
9358
9359                 schedule();
9360         } while (!signal_pending(current));
9361
9362         finish_wait(&ctx->sqo_sq_wait, &wait);
9363 out:
9364         return ret;
9365 }
9366
9367 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9368                           struct __kernel_timespec __user **ts,
9369                           const sigset_t __user **sig)
9370 {
9371         struct io_uring_getevents_arg arg;
9372
9373         /*
9374          * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9375          * is just a pointer to the sigset_t.
9376          */
9377         if (!(flags & IORING_ENTER_EXT_ARG)) {
9378                 *sig = (const sigset_t __user *) argp;
9379                 *ts = NULL;
9380                 return 0;
9381         }
9382
9383         /*
9384          * EXT_ARG is set - ensure we agree on the size of it and copy in our
9385          * timespec and sigset_t pointers if good.
9386          */
9387         if (*argsz != sizeof(arg))
9388                 return -EINVAL;
9389         if (copy_from_user(&arg, argp, sizeof(arg)))
9390                 return -EFAULT;
9391         *sig = u64_to_user_ptr(arg.sigmask);
9392         *argsz = arg.sigmask_sz;
9393         *ts = u64_to_user_ptr(arg.ts);
9394         return 0;
9395 }
9396
9397 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9398                 u32, min_complete, u32, flags, const void __user *, argp,
9399                 size_t, argsz)
9400 {
9401         struct io_ring_ctx *ctx;
9402         long ret = -EBADF;
9403         int submitted = 0;
9404         struct fd f;
9405
9406         io_run_task_work();
9407
9408         if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9409                         IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9410                 return -EINVAL;
9411
9412         f = fdget(fd);
9413         if (!f.file)
9414                 return -EBADF;
9415
9416         ret = -EOPNOTSUPP;
9417         if (f.file->f_op != &io_uring_fops)
9418                 goto out_fput;
9419
9420         ret = -ENXIO;
9421         ctx = f.file->private_data;
9422         if (!percpu_ref_tryget(&ctx->refs))
9423                 goto out_fput;
9424
9425         ret = -EBADFD;
9426         if (ctx->flags & IORING_SETUP_R_DISABLED)
9427                 goto out;
9428
9429         /*
9430          * For SQ polling, the thread will do all submissions and completions.
9431          * Just return the requested submit count, and wake the thread if
9432          * we were asked to.
9433          */
9434         ret = 0;
9435         if (ctx->flags & IORING_SETUP_SQPOLL) {
9436                 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9437
9438                 ret = -EOWNERDEAD;
9439                 if (unlikely(ctx->sqo_dead))
9440                         goto out;
9441                 if (flags & IORING_ENTER_SQ_WAKEUP)
9442                         wake_up(&ctx->sq_data->wait);
9443                 if (flags & IORING_ENTER_SQ_WAIT) {
9444                         ret = io_sqpoll_wait_sq(ctx);
9445                         if (ret)
9446                                 goto out;
9447                 }
9448                 submitted = to_submit;
9449         } else if (to_submit) {
9450                 ret = io_uring_add_task_file(ctx, f.file);
9451                 if (unlikely(ret))
9452                         goto out;
9453                 mutex_lock(&ctx->uring_lock);
9454                 submitted = io_submit_sqes(ctx, to_submit);
9455                 mutex_unlock(&ctx->uring_lock);
9456
9457                 if (submitted != to_submit)
9458                         goto out;
9459         }
9460         if (flags & IORING_ENTER_GETEVENTS) {
9461                 const sigset_t __user *sig;
9462                 struct __kernel_timespec __user *ts;
9463
9464                 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9465                 if (unlikely(ret))
9466                         goto out;
9467
9468                 min_complete = min(min_complete, ctx->cq_entries);
9469
9470                 /*
9471                  * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9472                  * space applications don't need to do io completion events
9473                  * polling again, they can rely on io_sq_thread to do polling
9474                  * work, which can reduce cpu usage and uring_lock contention.
9475                  */
9476                 if (ctx->flags & IORING_SETUP_IOPOLL &&
9477                     !(ctx->flags & IORING_SETUP_SQPOLL)) {
9478                         ret = io_iopoll_check(ctx, min_complete);
9479                 } else {
9480                         ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9481                 }
9482         }
9483
9484 out:
9485         percpu_ref_put(&ctx->refs);
9486 out_fput:
9487         fdput(f);
9488         return submitted ? submitted : ret;
9489 }
9490
9491 #ifdef CONFIG_PROC_FS
9492 static int io_uring_show_cred(int id, void *p, void *data)
9493 {
9494         struct io_identity *iod = p;
9495         const struct cred *cred = iod->creds;
9496         struct seq_file *m = data;
9497         struct user_namespace *uns = seq_user_ns(m);
9498         struct group_info *gi;
9499         kernel_cap_t cap;
9500         unsigned __capi;
9501         int g;
9502
9503         seq_printf(m, "%5d\n", id);
9504         seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9505         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9506         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9507         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9508         seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9509         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9510         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9511         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9512         seq_puts(m, "\n\tGroups:\t");
9513         gi = cred->group_info;
9514         for (g = 0; g < gi->ngroups; g++) {
9515                 seq_put_decimal_ull(m, g ? " " : "",
9516                                         from_kgid_munged(uns, gi->gid[g]));
9517         }
9518         seq_puts(m, "\n\tCapEff:\t");
9519         cap = cred->cap_effective;
9520         CAP_FOR_EACH_U32(__capi)
9521                 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9522         seq_putc(m, '\n');
9523         return 0;
9524 }
9525
9526 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9527 {
9528         struct io_sq_data *sq = NULL;
9529         bool has_lock;
9530         int i;
9531
9532         /*
9533          * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9534          * since fdinfo case grabs it in the opposite direction of normal use
9535          * cases. If we fail to get the lock, we just don't iterate any
9536          * structures that could be going away outside the io_uring mutex.
9537          */
9538         has_lock = mutex_trylock(&ctx->uring_lock);
9539
9540         if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9541                 sq = ctx->sq_data;
9542
9543         seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9544         seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9545         seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9546         for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9547                 struct file *f = *io_fixed_file_slot(ctx->file_data, i);
9548
9549                 if (f)
9550                         seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9551                 else
9552                         seq_printf(m, "%5u: <none>\n", i);
9553         }
9554         seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9555         for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9556                 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9557
9558                 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9559                                                 (unsigned int) buf->len);
9560         }
9561         if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9562                 seq_printf(m, "Personalities:\n");
9563                 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9564         }
9565         seq_printf(m, "PollList:\n");
9566         spin_lock_irq(&ctx->completion_lock);
9567         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9568                 struct hlist_head *list = &ctx->cancel_hash[i];
9569                 struct io_kiocb *req;
9570
9571                 hlist_for_each_entry(req, list, hash_node)
9572                         seq_printf(m, "  op=%d, task_works=%d\n", req->opcode,
9573                                         req->task->task_works != NULL);
9574         }
9575         spin_unlock_irq(&ctx->completion_lock);
9576         if (has_lock)
9577                 mutex_unlock(&ctx->uring_lock);
9578 }
9579
9580 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9581 {
9582         struct io_ring_ctx *ctx = f->private_data;
9583
9584         if (percpu_ref_tryget(&ctx->refs)) {
9585                 __io_uring_show_fdinfo(ctx, m);
9586                 percpu_ref_put(&ctx->refs);
9587         }
9588 }
9589 #endif
9590
9591 static const struct file_operations io_uring_fops = {
9592         .release        = io_uring_release,
9593         .flush          = io_uring_flush,
9594         .mmap           = io_uring_mmap,
9595 #ifndef CONFIG_MMU
9596         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9597         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9598 #endif
9599         .poll           = io_uring_poll,
9600         .fasync         = io_uring_fasync,
9601 #ifdef CONFIG_PROC_FS
9602         .show_fdinfo    = io_uring_show_fdinfo,
9603 #endif
9604 };
9605
9606 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9607                                   struct io_uring_params *p)
9608 {
9609         struct io_rings *rings;
9610         size_t size, sq_array_offset;
9611
9612         /* make sure these are sane, as we already accounted them */
9613         ctx->sq_entries = p->sq_entries;
9614         ctx->cq_entries = p->cq_entries;
9615
9616         size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9617         if (size == SIZE_MAX)
9618                 return -EOVERFLOW;
9619
9620         rings = io_mem_alloc(size);
9621         if (!rings)
9622                 return -ENOMEM;
9623
9624         ctx->rings = rings;
9625         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9626         rings->sq_ring_mask = p->sq_entries - 1;
9627         rings->cq_ring_mask = p->cq_entries - 1;
9628         rings->sq_ring_entries = p->sq_entries;
9629         rings->cq_ring_entries = p->cq_entries;
9630         ctx->sq_mask = rings->sq_ring_mask;
9631         ctx->cq_mask = rings->cq_ring_mask;
9632
9633         size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9634         if (size == SIZE_MAX) {
9635                 io_mem_free(ctx->rings);
9636                 ctx->rings = NULL;
9637                 return -EOVERFLOW;
9638         }
9639
9640         ctx->sq_sqes = io_mem_alloc(size);
9641         if (!ctx->sq_sqes) {
9642                 io_mem_free(ctx->rings);
9643                 ctx->rings = NULL;
9644                 return -ENOMEM;
9645         }
9646
9647         return 0;
9648 }
9649
9650 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9651 {
9652         int ret, fd;
9653
9654         fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9655         if (fd < 0)
9656                 return fd;
9657
9658         ret = io_uring_add_task_file(ctx, file);
9659         if (ret) {
9660                 put_unused_fd(fd);
9661                 return ret;
9662         }
9663         fd_install(fd, file);
9664         return fd;
9665 }
9666
9667 /*
9668  * Allocate an anonymous fd, this is what constitutes the application
9669  * visible backing of an io_uring instance. The application mmaps this
9670  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9671  * we have to tie this fd to a socket for file garbage collection purposes.
9672  */
9673 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9674 {
9675         struct file *file;
9676 #if defined(CONFIG_UNIX)
9677         int ret;
9678
9679         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9680                                 &ctx->ring_sock);
9681         if (ret)
9682                 return ERR_PTR(ret);
9683 #endif
9684
9685         file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9686                                         O_RDWR | O_CLOEXEC);
9687 #if defined(CONFIG_UNIX)
9688         if (IS_ERR(file)) {
9689                 sock_release(ctx->ring_sock);
9690                 ctx->ring_sock = NULL;
9691         } else {
9692                 ctx->ring_sock->file = file;
9693         }
9694 #endif
9695         return file;
9696 }
9697
9698 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9699                            struct io_uring_params __user *params)
9700 {
9701         struct user_struct *user = NULL;
9702         struct io_ring_ctx *ctx;
9703         struct file *file;
9704         int ret;
9705
9706         if (!entries)
9707                 return -EINVAL;
9708         if (entries > IORING_MAX_ENTRIES) {
9709                 if (!(p->flags & IORING_SETUP_CLAMP))
9710                         return -EINVAL;
9711                 entries = IORING_MAX_ENTRIES;
9712         }
9713
9714         /*
9715          * Use twice as many entries for the CQ ring. It's possible for the
9716          * application to drive a higher depth than the size of the SQ ring,
9717          * since the sqes are only used at submission time. This allows for
9718          * some flexibility in overcommitting a bit. If the application has
9719          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9720          * of CQ ring entries manually.
9721          */
9722         p->sq_entries = roundup_pow_of_two(entries);
9723         if (p->flags & IORING_SETUP_CQSIZE) {
9724                 /*
9725                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
9726                  * to a power-of-two, if it isn't already. We do NOT impose
9727                  * any cq vs sq ring sizing.
9728                  */
9729                 if (!p->cq_entries)
9730                         return -EINVAL;
9731                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9732                         if (!(p->flags & IORING_SETUP_CLAMP))
9733                                 return -EINVAL;
9734                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
9735                 }
9736                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9737                 if (p->cq_entries < p->sq_entries)
9738                         return -EINVAL;
9739         } else {
9740                 p->cq_entries = 2 * p->sq_entries;
9741         }
9742
9743         user = get_uid(current_user());
9744
9745         ctx = io_ring_ctx_alloc(p);
9746         if (!ctx) {
9747                 free_uid(user);
9748                 return -ENOMEM;
9749         }
9750         ctx->compat = in_compat_syscall();
9751         ctx->limit_mem = !capable(CAP_IPC_LOCK);
9752         ctx->user = user;
9753         ctx->creds = get_current_cred();
9754 #ifdef CONFIG_AUDIT
9755         ctx->loginuid = current->loginuid;
9756         ctx->sessionid = current->sessionid;
9757 #endif
9758         ctx->sqo_task = get_task_struct(current);
9759
9760         /*
9761          * This is just grabbed for accounting purposes. When a process exits,
9762          * the mm is exited and dropped before the files, hence we need to hang
9763          * on to this mm purely for the purposes of being able to unaccount
9764          * memory (locked/pinned vm). It's not used for anything else.
9765          */
9766         mmgrab(current->mm);
9767         ctx->mm_account = current->mm;
9768
9769 #ifdef CONFIG_BLK_CGROUP
9770         /*
9771          * The sq thread will belong to the original cgroup it was inited in.
9772          * If the cgroup goes offline (e.g. disabling the io controller), then
9773          * issued bios will be associated with the closest cgroup later in the
9774          * block layer.
9775          */
9776         rcu_read_lock();
9777         ctx->sqo_blkcg_css = blkcg_css();
9778         ret = css_tryget_online(ctx->sqo_blkcg_css);
9779         rcu_read_unlock();
9780         if (!ret) {
9781                 /* don't init against a dying cgroup, have the user try again */
9782                 ctx->sqo_blkcg_css = NULL;
9783                 ret = -ENODEV;
9784                 goto err;
9785         }
9786 #endif
9787         ret = io_allocate_scq_urings(ctx, p);
9788         if (ret)
9789                 goto err;
9790
9791         ret = io_sq_offload_create(ctx, p);
9792         if (ret)
9793                 goto err;
9794
9795         if (!(p->flags & IORING_SETUP_R_DISABLED))
9796                 io_sq_offload_start(ctx);
9797
9798         memset(&p->sq_off, 0, sizeof(p->sq_off));
9799         p->sq_off.head = offsetof(struct io_rings, sq.head);
9800         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9801         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9802         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9803         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9804         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9805         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9806
9807         memset(&p->cq_off, 0, sizeof(p->cq_off));
9808         p->cq_off.head = offsetof(struct io_rings, cq.head);
9809         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9810         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9811         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9812         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9813         p->cq_off.cqes = offsetof(struct io_rings, cqes);
9814         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9815
9816         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9817                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9818                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9819                         IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9820                         IORING_FEAT_EXT_ARG;
9821
9822         if (copy_to_user(params, p, sizeof(*p))) {
9823                 ret = -EFAULT;
9824                 goto err;
9825         }
9826
9827         file = io_uring_get_file(ctx);
9828         if (IS_ERR(file)) {
9829                 ret = PTR_ERR(file);
9830                 goto err;
9831         }
9832
9833         /*
9834          * Install ring fd as the very last thing, so we don't risk someone
9835          * having closed it before we finish setup
9836          */
9837         ret = io_uring_install_fd(ctx, file);
9838         if (ret < 0) {
9839                 io_disable_sqo_submit(ctx);
9840                 /* fput will clean it up */
9841                 fput(file);
9842                 return ret;
9843         }
9844
9845         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9846         return ret;
9847 err:
9848         io_disable_sqo_submit(ctx);
9849         io_ring_ctx_wait_and_kill(ctx);
9850         return ret;
9851 }
9852
9853 /*
9854  * Sets up an aio uring context, and returns the fd. Applications asks for a
9855  * ring size, we return the actual sq/cq ring sizes (among other things) in the
9856  * params structure passed in.
9857  */
9858 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9859 {
9860         struct io_uring_params p;
9861         int i;
9862
9863         if (copy_from_user(&p, params, sizeof(p)))
9864                 return -EFAULT;
9865         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9866                 if (p.resv[i])
9867                         return -EINVAL;
9868         }
9869
9870         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9871                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9872                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9873                         IORING_SETUP_R_DISABLED))
9874                 return -EINVAL;
9875
9876         return  io_uring_create(entries, &p, params);
9877 }
9878
9879 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9880                 struct io_uring_params __user *, params)
9881 {
9882         return io_uring_setup(entries, params);
9883 }
9884
9885 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9886 {
9887         struct io_uring_probe *p;
9888         size_t size;
9889         int i, ret;
9890
9891         size = struct_size(p, ops, nr_args);
9892         if (size == SIZE_MAX)
9893                 return -EOVERFLOW;
9894         p = kzalloc(size, GFP_KERNEL);
9895         if (!p)
9896                 return -ENOMEM;
9897
9898         ret = -EFAULT;
9899         if (copy_from_user(p, arg, size))
9900                 goto out;
9901         ret = -EINVAL;
9902         if (memchr_inv(p, 0, size))
9903                 goto out;
9904
9905         p->last_op = IORING_OP_LAST - 1;
9906         if (nr_args > IORING_OP_LAST)
9907                 nr_args = IORING_OP_LAST;
9908
9909         for (i = 0; i < nr_args; i++) {
9910                 p->ops[i].op = i;
9911                 if (!io_op_defs[i].not_supported)
9912                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
9913         }
9914         p->ops_len = i;
9915
9916         ret = 0;
9917         if (copy_to_user(arg, p, size))
9918                 ret = -EFAULT;
9919 out:
9920         kfree(p);
9921         return ret;
9922 }
9923
9924 static int io_register_personality(struct io_ring_ctx *ctx)
9925 {
9926         struct io_identity *id;
9927         int ret;
9928
9929         id = kmalloc(sizeof(*id), GFP_KERNEL);
9930         if (unlikely(!id))
9931                 return -ENOMEM;
9932
9933         io_init_identity(id);
9934         id->creds = get_current_cred();
9935
9936         ret = idr_alloc_cyclic(&ctx->personality_idr, id, 1, USHRT_MAX, GFP_KERNEL);
9937         if (ret < 0) {
9938                 put_cred(id->creds);
9939                 kfree(id);
9940         }
9941         return ret;
9942 }
9943
9944 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9945                                     unsigned int nr_args)
9946 {
9947         struct io_uring_restriction *res;
9948         size_t size;
9949         int i, ret;
9950
9951         /* Restrictions allowed only if rings started disabled */
9952         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9953                 return -EBADFD;
9954
9955         /* We allow only a single restrictions registration */
9956         if (ctx->restrictions.registered)
9957                 return -EBUSY;
9958
9959         if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9960                 return -EINVAL;
9961
9962         size = array_size(nr_args, sizeof(*res));
9963         if (size == SIZE_MAX)
9964                 return -EOVERFLOW;
9965
9966         res = memdup_user(arg, size);
9967         if (IS_ERR(res))
9968                 return PTR_ERR(res);
9969
9970         ret = 0;
9971
9972         for (i = 0; i < nr_args; i++) {
9973                 switch (res[i].opcode) {
9974                 case IORING_RESTRICTION_REGISTER_OP:
9975                         if (res[i].register_op >= IORING_REGISTER_LAST) {
9976                                 ret = -EINVAL;
9977                                 goto out;
9978                         }
9979
9980                         __set_bit(res[i].register_op,
9981                                   ctx->restrictions.register_op);
9982                         break;
9983                 case IORING_RESTRICTION_SQE_OP:
9984                         if (res[i].sqe_op >= IORING_OP_LAST) {
9985                                 ret = -EINVAL;
9986                                 goto out;
9987                         }
9988
9989                         __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9990                         break;
9991                 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9992                         ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9993                         break;
9994                 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9995                         ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9996                         break;
9997                 default:
9998                         ret = -EINVAL;
9999                         goto out;
10000                 }
10001         }
10002
10003 out:
10004         /* Reset all restrictions if an error happened */
10005         if (ret != 0)
10006                 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10007         else
10008                 ctx->restrictions.registered = true;
10009
10010         kfree(res);
10011         return ret;
10012 }
10013
10014 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10015 {
10016         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10017                 return -EBADFD;
10018
10019         if (ctx->restrictions.registered)
10020                 ctx->restricted = 1;
10021
10022         ctx->flags &= ~IORING_SETUP_R_DISABLED;
10023
10024         io_sq_offload_start(ctx);
10025
10026         return 0;
10027 }
10028
10029 static bool io_register_op_must_quiesce(int op)
10030 {
10031         switch (op) {
10032         case IORING_UNREGISTER_FILES:
10033         case IORING_REGISTER_FILES_UPDATE:
10034         case IORING_REGISTER_PROBE:
10035         case IORING_REGISTER_PERSONALITY:
10036         case IORING_UNREGISTER_PERSONALITY:
10037                 return false;
10038         default:
10039                 return true;
10040         }
10041 }
10042
10043 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10044                                void __user *arg, unsigned nr_args)
10045         __releases(ctx->uring_lock)
10046         __acquires(ctx->uring_lock)
10047 {
10048         int ret;
10049
10050         /*
10051          * We're inside the ring mutex, if the ref is already dying, then
10052          * someone else killed the ctx or is already going through
10053          * io_uring_register().
10054          */
10055         if (percpu_ref_is_dying(&ctx->refs))
10056                 return -ENXIO;
10057
10058         if (io_register_op_must_quiesce(opcode)) {
10059                 percpu_ref_kill(&ctx->refs);
10060
10061                 /*
10062                  * Drop uring mutex before waiting for references to exit. If
10063                  * another thread is currently inside io_uring_enter() it might
10064                  * need to grab the uring_lock to make progress. If we hold it
10065                  * here across the drain wait, then we can deadlock. It's safe
10066                  * to drop the mutex here, since no new references will come in
10067                  * after we've killed the percpu ref.
10068                  */
10069                 mutex_unlock(&ctx->uring_lock);
10070                 do {
10071                         ret = wait_for_completion_interruptible(&ctx->ref_comp);
10072                         if (!ret)
10073                                 break;
10074                         ret = io_run_task_work_sig();
10075                         if (ret < 0)
10076                                 break;
10077                 } while (1);
10078
10079                 mutex_lock(&ctx->uring_lock);
10080
10081                 if (ret) {
10082                         percpu_ref_resurrect(&ctx->refs);
10083                         goto out_quiesce;
10084                 }
10085         }
10086
10087         if (ctx->restricted) {
10088                 if (opcode >= IORING_REGISTER_LAST) {
10089                         ret = -EINVAL;
10090                         goto out;
10091                 }
10092
10093                 if (!test_bit(opcode, ctx->restrictions.register_op)) {
10094                         ret = -EACCES;
10095                         goto out;
10096                 }
10097         }
10098
10099         switch (opcode) {
10100         case IORING_REGISTER_BUFFERS:
10101                 ret = io_sqe_buffers_register(ctx, arg, nr_args);
10102                 break;
10103         case IORING_UNREGISTER_BUFFERS:
10104                 ret = -EINVAL;
10105                 if (arg || nr_args)
10106                         break;
10107                 ret = io_sqe_buffers_unregister(ctx);
10108                 break;
10109         case IORING_REGISTER_FILES:
10110                 ret = io_sqe_files_register(ctx, arg, nr_args);
10111                 break;
10112         case IORING_UNREGISTER_FILES:
10113                 ret = -EINVAL;
10114                 if (arg || nr_args)
10115                         break;
10116                 ret = io_sqe_files_unregister(ctx);
10117                 break;
10118         case IORING_REGISTER_FILES_UPDATE:
10119                 ret = io_sqe_files_update(ctx, arg, nr_args);
10120                 break;
10121         case IORING_REGISTER_EVENTFD:
10122         case IORING_REGISTER_EVENTFD_ASYNC:
10123                 ret = -EINVAL;
10124                 if (nr_args != 1)
10125                         break;
10126                 ret = io_eventfd_register(ctx, arg);
10127                 if (ret)
10128                         break;
10129                 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10130                         ctx->eventfd_async = 1;
10131                 else
10132                         ctx->eventfd_async = 0;
10133                 break;
10134         case IORING_UNREGISTER_EVENTFD:
10135                 ret = -EINVAL;
10136                 if (arg || nr_args)
10137                         break;
10138                 ret = io_eventfd_unregister(ctx);
10139                 break;
10140         case IORING_REGISTER_PROBE:
10141                 ret = -EINVAL;
10142                 if (!arg || nr_args > 256)
10143                         break;
10144                 ret = io_probe(ctx, arg, nr_args);
10145                 break;
10146         case IORING_REGISTER_PERSONALITY:
10147                 ret = -EINVAL;
10148                 if (arg || nr_args)
10149                         break;
10150                 ret = io_register_personality(ctx);
10151                 break;
10152         case IORING_UNREGISTER_PERSONALITY:
10153                 ret = -EINVAL;
10154                 if (arg)
10155                         break;
10156                 ret = io_unregister_personality(ctx, nr_args);
10157                 break;
10158         case IORING_REGISTER_ENABLE_RINGS:
10159                 ret = -EINVAL;
10160                 if (arg || nr_args)
10161                         break;
10162                 ret = io_register_enable_rings(ctx);
10163                 break;
10164         case IORING_REGISTER_RESTRICTIONS:
10165                 ret = io_register_restrictions(ctx, arg, nr_args);
10166                 break;
10167         default:
10168                 ret = -EINVAL;
10169                 break;
10170         }
10171
10172 out:
10173         if (io_register_op_must_quiesce(opcode)) {
10174                 /* bring the ctx back to life */
10175                 percpu_ref_reinit(&ctx->refs);
10176 out_quiesce:
10177                 reinit_completion(&ctx->ref_comp);
10178         }
10179         return ret;
10180 }
10181
10182 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10183                 void __user *, arg, unsigned int, nr_args)
10184 {
10185         struct io_ring_ctx *ctx;
10186         long ret = -EBADF;
10187         struct fd f;
10188
10189         f = fdget(fd);
10190         if (!f.file)
10191                 return -EBADF;
10192
10193         ret = -EOPNOTSUPP;
10194         if (f.file->f_op != &io_uring_fops)
10195                 goto out_fput;
10196
10197         ctx = f.file->private_data;
10198
10199         mutex_lock(&ctx->uring_lock);
10200         ret = __io_uring_register(ctx, opcode, arg, nr_args);
10201         mutex_unlock(&ctx->uring_lock);
10202         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10203                                                         ctx->cq_ev_fd != NULL, ret);
10204 out_fput:
10205         fdput(f);
10206         return ret;
10207 }
10208
10209 static int __init io_uring_init(void)
10210 {
10211 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10212         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10213         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10214 } while (0)
10215
10216 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10217         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10218         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10219         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
10220         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
10221         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
10222         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
10223         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
10224         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
10225         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
10226         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
10227         BUILD_BUG_SQE_ELEM(24, __u32,  len);
10228         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
10229         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
10230         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10231         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
10232         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
10233         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
10234         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
10235         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
10236         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
10237         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
10238         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
10239         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
10240         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
10241         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
10242         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
10243         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
10244         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
10245         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
10246         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
10247
10248         BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10249         BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10250         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10251                                 SLAB_ACCOUNT);
10252         return 0;
10253 };
10254 __initcall(io_uring_init);