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