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