OSDN Git Service

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