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