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