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