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