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