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