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