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