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