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