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