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