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