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