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