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