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