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