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