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