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