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