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