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