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