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