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