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