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