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