io_uring: fix possible poll event lost in multi shot mode
[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         return !(flags & IORING_CQE_F_MORE);
5124 }
5125
5126 static inline bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
5127         __must_hold(&req->ctx->completion_lock)
5128 {
5129         bool done;
5130
5131         done = __io_poll_complete(req, mask);
5132         io_commit_cqring(req->ctx);
5133         return done;
5134 }
5135
5136 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5137 {
5138         struct io_ring_ctx *ctx = req->ctx;
5139         struct io_kiocb *nxt;
5140
5141         if (io_poll_rewait(req, &req->poll)) {
5142                 spin_unlock(&ctx->completion_lock);
5143         } else {
5144                 bool done;
5145
5146                 done = __io_poll_complete(req, req->result);
5147                 if (done) {
5148                         io_poll_remove_double(req);
5149                         hash_del(&req->hash_node);
5150                 } else {
5151                         req->result = 0;
5152                         add_wait_queue(req->poll.head, &req->poll.wait);
5153                 }
5154                 io_commit_cqring(ctx);
5155                 spin_unlock(&ctx->completion_lock);
5156                 io_cqring_ev_posted(ctx);
5157
5158                 if (done) {
5159                         nxt = io_put_req_find_next(req);
5160                         if (nxt)
5161                                 io_req_task_submit(nxt, locked);
5162                 }
5163         }
5164 }
5165
5166 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5167                                int sync, void *key)
5168 {
5169         struct io_kiocb *req = wait->private;
5170         struct io_poll_iocb *poll = io_poll_get_single(req);
5171         __poll_t mask = key_to_poll(key);
5172         unsigned long flags;
5173
5174         /* for instances that support it check for an event match first: */
5175         if (mask && !(mask & poll->events))
5176                 return 0;
5177         if (!(poll->events & EPOLLONESHOT))
5178                 return poll->wait.func(&poll->wait, mode, sync, key);
5179
5180         list_del_init(&wait->entry);
5181
5182         if (poll->head) {
5183                 bool done;
5184
5185                 spin_lock_irqsave(&poll->head->lock, flags);
5186                 done = list_empty(&poll->wait.entry);
5187                 if (!done)
5188                         list_del_init(&poll->wait.entry);
5189                 /* make sure double remove sees this as being gone */
5190                 wait->private = NULL;
5191                 spin_unlock_irqrestore(&poll->head->lock, flags);
5192                 if (!done) {
5193                         /* use wait func handler, so it matches the rq type */
5194                         poll->wait.func(&poll->wait, mode, sync, key);
5195                 }
5196         }
5197         req_ref_put(req);
5198         return 1;
5199 }
5200
5201 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5202                               wait_queue_func_t wake_func)
5203 {
5204         poll->head = NULL;
5205         poll->done = false;
5206         poll->canceled = false;
5207 #define IO_POLL_UNMASK  (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5208         /* mask in events that we always want/need */
5209         poll->events = events | IO_POLL_UNMASK;
5210         INIT_LIST_HEAD(&poll->wait.entry);
5211         init_waitqueue_func_entry(&poll->wait, wake_func);
5212 }
5213
5214 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5215                             struct wait_queue_head *head,
5216                             struct io_poll_iocb **poll_ptr)
5217 {
5218         struct io_kiocb *req = pt->req;
5219
5220         /*
5221          * The file being polled uses multiple waitqueues for poll handling
5222          * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5223          * if this happens.
5224          */
5225         if (unlikely(pt->nr_entries)) {
5226                 struct io_poll_iocb *poll_one = poll;
5227
5228                 /* double add on the same waitqueue head, ignore */
5229                 if (poll_one->head == head)
5230                         return;
5231                 /* already have a 2nd entry, fail a third attempt */
5232                 if (*poll_ptr) {
5233                         if ((*poll_ptr)->head == head)
5234                                 return;
5235                         pt->error = -EINVAL;
5236                         return;
5237                 }
5238                 /*
5239                  * Can't handle multishot for double wait for now, turn it
5240                  * into one-shot mode.
5241                  */
5242                 if (!(poll_one->events & EPOLLONESHOT))
5243                         poll_one->events |= EPOLLONESHOT;
5244                 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5245                 if (!poll) {
5246                         pt->error = -ENOMEM;
5247                         return;
5248                 }
5249                 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5250                 req_ref_get(req);
5251                 poll->wait.private = req;
5252                 *poll_ptr = poll;
5253         }
5254
5255         pt->nr_entries++;
5256         poll->head = head;
5257
5258         if (poll->events & EPOLLEXCLUSIVE)
5259                 add_wait_queue_exclusive(head, &poll->wait);
5260         else
5261                 add_wait_queue(head, &poll->wait);
5262 }
5263
5264 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5265                                struct poll_table_struct *p)
5266 {
5267         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5268         struct async_poll *apoll = pt->req->apoll;
5269
5270         __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5271 }
5272
5273 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5274 {
5275         struct async_poll *apoll = req->apoll;
5276         struct io_ring_ctx *ctx = req->ctx;
5277
5278         trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5279
5280         if (io_poll_rewait(req, &apoll->poll)) {
5281                 spin_unlock(&ctx->completion_lock);
5282                 return;
5283         }
5284
5285         hash_del(&req->hash_node);
5286         io_poll_remove_double(req);
5287         spin_unlock(&ctx->completion_lock);
5288
5289         if (!READ_ONCE(apoll->poll.canceled))
5290                 io_req_task_submit(req, locked);
5291         else
5292                 io_req_complete_failed(req, -ECANCELED);
5293 }
5294
5295 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5296                         void *key)
5297 {
5298         struct io_kiocb *req = wait->private;
5299         struct io_poll_iocb *poll = &req->apoll->poll;
5300
5301         trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5302                                         key_to_poll(key));
5303
5304         return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5305 }
5306
5307 static void io_poll_req_insert(struct io_kiocb *req)
5308 {
5309         struct io_ring_ctx *ctx = req->ctx;
5310         struct hlist_head *list;
5311
5312         list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5313         hlist_add_head(&req->hash_node, list);
5314 }
5315
5316 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5317                                       struct io_poll_iocb *poll,
5318                                       struct io_poll_table *ipt, __poll_t mask,
5319                                       wait_queue_func_t wake_func)
5320         __acquires(&ctx->completion_lock)
5321 {
5322         struct io_ring_ctx *ctx = req->ctx;
5323         bool cancel = false;
5324
5325         INIT_HLIST_NODE(&req->hash_node);
5326         io_init_poll_iocb(poll, mask, wake_func);
5327         poll->file = req->file;
5328         poll->wait.private = req;
5329
5330         ipt->pt._key = mask;
5331         ipt->req = req;
5332         ipt->error = 0;
5333         ipt->nr_entries = 0;
5334
5335         mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5336         if (unlikely(!ipt->nr_entries) && !ipt->error)
5337                 ipt->error = -EINVAL;
5338
5339         spin_lock(&ctx->completion_lock);
5340         if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5341                 io_poll_remove_double(req);
5342         if (likely(poll->head)) {
5343                 spin_lock_irq(&poll->head->lock);
5344                 if (unlikely(list_empty(&poll->wait.entry))) {
5345                         if (ipt->error)
5346                                 cancel = true;
5347                         ipt->error = 0;
5348                         mask = 0;
5349                 }
5350                 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5351                         list_del_init(&poll->wait.entry);
5352                 else if (cancel)
5353                         WRITE_ONCE(poll->canceled, true);
5354                 else if (!poll->done) /* actually waiting for an event */
5355                         io_poll_req_insert(req);
5356                 spin_unlock_irq(&poll->head->lock);
5357         }
5358
5359         return mask;
5360 }
5361
5362 enum {
5363         IO_APOLL_OK,
5364         IO_APOLL_ABORTED,
5365         IO_APOLL_READY
5366 };
5367
5368 static int io_arm_poll_handler(struct io_kiocb *req)
5369 {
5370         const struct io_op_def *def = &io_op_defs[req->opcode];
5371         struct io_ring_ctx *ctx = req->ctx;
5372         struct async_poll *apoll;
5373         struct io_poll_table ipt;
5374         __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5375         int rw;
5376
5377         if (!req->file || !file_can_poll(req->file))
5378                 return IO_APOLL_ABORTED;
5379         if (req->flags & REQ_F_POLLED)
5380                 return IO_APOLL_ABORTED;
5381         if (!def->pollin && !def->pollout)
5382                 return IO_APOLL_ABORTED;
5383
5384         if (def->pollin) {
5385                 rw = READ;
5386                 mask |= POLLIN | POLLRDNORM;
5387
5388                 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5389                 if ((req->opcode == IORING_OP_RECVMSG) &&
5390                     (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5391                         mask &= ~POLLIN;
5392         } else {
5393                 rw = WRITE;
5394                 mask |= POLLOUT | POLLWRNORM;
5395         }
5396
5397         /* if we can't nonblock try, then no point in arming a poll handler */
5398         if (!io_file_supports_nowait(req, rw))
5399                 return IO_APOLL_ABORTED;
5400
5401         apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5402         if (unlikely(!apoll))
5403                 return IO_APOLL_ABORTED;
5404         apoll->double_poll = NULL;
5405         req->apoll = apoll;
5406         req->flags |= REQ_F_POLLED;
5407         ipt.pt._qproc = io_async_queue_proc;
5408         io_req_set_refcount(req);
5409
5410         ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5411                                         io_async_wake);
5412         spin_unlock(&ctx->completion_lock);
5413         if (ret || ipt.error)
5414                 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5415
5416         trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5417                                 mask, apoll->poll.events);
5418         return IO_APOLL_OK;
5419 }
5420
5421 static bool __io_poll_remove_one(struct io_kiocb *req,
5422                                  struct io_poll_iocb *poll, bool do_cancel)
5423         __must_hold(&req->ctx->completion_lock)
5424 {
5425         bool do_complete = false;
5426
5427         if (!poll->head)
5428                 return false;
5429         spin_lock_irq(&poll->head->lock);
5430         if (do_cancel)
5431                 WRITE_ONCE(poll->canceled, true);
5432         if (!list_empty(&poll->wait.entry)) {
5433                 list_del_init(&poll->wait.entry);
5434                 do_complete = true;
5435         }
5436         spin_unlock_irq(&poll->head->lock);
5437         hash_del(&req->hash_node);
5438         return do_complete;
5439 }
5440
5441 static bool io_poll_remove_one(struct io_kiocb *req)
5442         __must_hold(&req->ctx->completion_lock)
5443 {
5444         bool do_complete;
5445
5446         io_poll_remove_double(req);
5447         do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5448
5449         if (do_complete) {
5450                 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5451                 io_commit_cqring(req->ctx);
5452                 req_set_fail(req);
5453                 io_put_req_deferred(req);
5454         }
5455         return do_complete;
5456 }
5457
5458 /*
5459  * Returns true if we found and killed one or more poll requests
5460  */
5461 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5462                                bool cancel_all)
5463 {
5464         struct hlist_node *tmp;
5465         struct io_kiocb *req;
5466         int posted = 0, i;
5467
5468         spin_lock(&ctx->completion_lock);
5469         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5470                 struct hlist_head *list;
5471
5472                 list = &ctx->cancel_hash[i];
5473                 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5474                         if (io_match_task(req, tsk, cancel_all))
5475                                 posted += io_poll_remove_one(req);
5476                 }
5477         }
5478         spin_unlock(&ctx->completion_lock);
5479
5480         if (posted)
5481                 io_cqring_ev_posted(ctx);
5482
5483         return posted != 0;
5484 }
5485
5486 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5487                                      bool poll_only)
5488         __must_hold(&ctx->completion_lock)
5489 {
5490         struct hlist_head *list;
5491         struct io_kiocb *req;
5492
5493         list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5494         hlist_for_each_entry(req, list, hash_node) {
5495                 if (sqe_addr != req->user_data)
5496                         continue;
5497                 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5498                         continue;
5499                 return req;
5500         }
5501         return NULL;
5502 }
5503
5504 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5505                           bool poll_only)
5506         __must_hold(&ctx->completion_lock)
5507 {
5508         struct io_kiocb *req;
5509
5510         req = io_poll_find(ctx, sqe_addr, poll_only);
5511         if (!req)
5512                 return -ENOENT;
5513         if (io_poll_remove_one(req))
5514                 return 0;
5515
5516         return -EALREADY;
5517 }
5518
5519 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5520                                      unsigned int flags)
5521 {
5522         u32 events;
5523
5524         events = READ_ONCE(sqe->poll32_events);
5525 #ifdef __BIG_ENDIAN
5526         events = swahw32(events);
5527 #endif
5528         if (!(flags & IORING_POLL_ADD_MULTI))
5529                 events |= EPOLLONESHOT;
5530         return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5531 }
5532
5533 static int io_poll_update_prep(struct io_kiocb *req,
5534                                const struct io_uring_sqe *sqe)
5535 {
5536         struct io_poll_update *upd = &req->poll_update;
5537         u32 flags;
5538
5539         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5540                 return -EINVAL;
5541         if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5542                 return -EINVAL;
5543         flags = READ_ONCE(sqe->len);
5544         if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5545                       IORING_POLL_ADD_MULTI))
5546                 return -EINVAL;
5547         /* meaningless without update */
5548         if (flags == IORING_POLL_ADD_MULTI)
5549                 return -EINVAL;
5550
5551         upd->old_user_data = READ_ONCE(sqe->addr);
5552         upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5553         upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5554
5555         upd->new_user_data = READ_ONCE(sqe->off);
5556         if (!upd->update_user_data && upd->new_user_data)
5557                 return -EINVAL;
5558         if (upd->update_events)
5559                 upd->events = io_poll_parse_events(sqe, flags);
5560         else if (sqe->poll32_events)
5561                 return -EINVAL;
5562
5563         return 0;
5564 }
5565
5566 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5567                         void *key)
5568 {
5569         struct io_kiocb *req = wait->private;
5570         struct io_poll_iocb *poll = &req->poll;
5571
5572         return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5573 }
5574
5575 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5576                                struct poll_table_struct *p)
5577 {
5578         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5579
5580         __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5581 }
5582
5583 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5584 {
5585         struct io_poll_iocb *poll = &req->poll;
5586         u32 flags;
5587
5588         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5589                 return -EINVAL;
5590         if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5591                 return -EINVAL;
5592         flags = READ_ONCE(sqe->len);
5593         if (flags & ~IORING_POLL_ADD_MULTI)
5594                 return -EINVAL;
5595
5596         io_req_set_refcount(req);
5597         poll->events = io_poll_parse_events(sqe, flags);
5598         return 0;
5599 }
5600
5601 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5602 {
5603         struct io_poll_iocb *poll = &req->poll;
5604         struct io_ring_ctx *ctx = req->ctx;
5605         struct io_poll_table ipt;
5606         __poll_t mask;
5607
5608         ipt.pt._qproc = io_poll_queue_proc;
5609
5610         mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5611                                         io_poll_wake);
5612
5613         if (mask) { /* no async, we'd stolen it */
5614                 ipt.error = 0;
5615                 io_poll_complete(req, mask);
5616         }
5617         spin_unlock(&ctx->completion_lock);
5618
5619         if (mask) {
5620                 io_cqring_ev_posted(ctx);
5621                 if (poll->events & EPOLLONESHOT)
5622                         io_put_req(req);
5623         }
5624         return ipt.error;
5625 }
5626
5627 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5628 {
5629         struct io_ring_ctx *ctx = req->ctx;
5630         struct io_kiocb *preq;
5631         bool completing;
5632         int ret;
5633
5634         spin_lock(&ctx->completion_lock);
5635         preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5636         if (!preq) {
5637                 ret = -ENOENT;
5638                 goto err;
5639         }
5640
5641         if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5642                 completing = true;
5643                 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5644                 goto err;
5645         }
5646
5647         /*
5648          * Don't allow racy completion with singleshot, as we cannot safely
5649          * update those. For multishot, if we're racing with completion, just
5650          * let completion re-add it.
5651          */
5652         completing = !__io_poll_remove_one(preq, &preq->poll, false);
5653         if (completing && (preq->poll.events & EPOLLONESHOT)) {
5654                 ret = -EALREADY;
5655                 goto err;
5656         }
5657         /* we now have a detached poll request. reissue. */
5658         ret = 0;
5659 err:
5660         if (ret < 0) {
5661                 spin_unlock(&ctx->completion_lock);
5662                 req_set_fail(req);
5663                 io_req_complete(req, ret);
5664                 return 0;
5665         }
5666         /* only mask one event flags, keep behavior flags */
5667         if (req->poll_update.update_events) {
5668                 preq->poll.events &= ~0xffff;
5669                 preq->poll.events |= req->poll_update.events & 0xffff;
5670                 preq->poll.events |= IO_POLL_UNMASK;
5671         }
5672         if (req->poll_update.update_user_data)
5673                 preq->user_data = req->poll_update.new_user_data;
5674         spin_unlock(&ctx->completion_lock);
5675
5676         /* complete update request, we're done with it */
5677         io_req_complete(req, ret);
5678
5679         if (!completing) {
5680                 ret = io_poll_add(preq, issue_flags);
5681                 if (ret < 0) {
5682                         req_set_fail(preq);
5683                         io_req_complete(preq, ret);
5684                 }
5685         }
5686         return 0;
5687 }
5688
5689 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5690 {
5691         req_set_fail(req);
5692         io_req_complete_post(req, -ETIME, 0);
5693 }
5694
5695 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5696 {
5697         struct io_timeout_data *data = container_of(timer,
5698                                                 struct io_timeout_data, timer);
5699         struct io_kiocb *req = data->req;
5700         struct io_ring_ctx *ctx = req->ctx;
5701         unsigned long flags;
5702
5703         spin_lock_irqsave(&ctx->timeout_lock, flags);
5704         list_del_init(&req->timeout.list);
5705         atomic_set(&req->ctx->cq_timeouts,
5706                 atomic_read(&req->ctx->cq_timeouts) + 1);
5707         spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5708
5709         req->io_task_work.func = io_req_task_timeout;
5710         io_req_task_work_add(req);
5711         return HRTIMER_NORESTART;
5712 }
5713
5714 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5715                                            __u64 user_data)
5716         __must_hold(&ctx->timeout_lock)
5717 {
5718         struct io_timeout_data *io;
5719         struct io_kiocb *req;
5720         bool found = false;
5721
5722         list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5723                 found = user_data == req->user_data;
5724                 if (found)
5725                         break;
5726         }
5727         if (!found)
5728                 return ERR_PTR(-ENOENT);
5729
5730         io = req->async_data;
5731         if (hrtimer_try_to_cancel(&io->timer) == -1)
5732                 return ERR_PTR(-EALREADY);
5733         list_del_init(&req->timeout.list);
5734         return req;
5735 }
5736
5737 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5738         __must_hold(&ctx->completion_lock)
5739         __must_hold(&ctx->timeout_lock)
5740 {
5741         struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5742
5743         if (IS_ERR(req))
5744                 return PTR_ERR(req);
5745
5746         req_set_fail(req);
5747         io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5748         io_put_req_deferred(req);
5749         return 0;
5750 }
5751
5752 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
5753 {
5754         switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
5755         case IORING_TIMEOUT_BOOTTIME:
5756                 return CLOCK_BOOTTIME;
5757         case IORING_TIMEOUT_REALTIME:
5758                 return CLOCK_REALTIME;
5759         default:
5760                 /* can't happen, vetted at prep time */
5761                 WARN_ON_ONCE(1);
5762                 fallthrough;
5763         case 0:
5764                 return CLOCK_MONOTONIC;
5765         }
5766 }
5767
5768 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5769                                     struct timespec64 *ts, enum hrtimer_mode mode)
5770         __must_hold(&ctx->timeout_lock)
5771 {
5772         struct io_timeout_data *io;
5773         struct io_kiocb *req;
5774         bool found = false;
5775
5776         list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
5777                 found = user_data == req->user_data;
5778                 if (found)
5779                         break;
5780         }
5781         if (!found)
5782                 return -ENOENT;
5783
5784         io = req->async_data;
5785         if (hrtimer_try_to_cancel(&io->timer) == -1)
5786                 return -EALREADY;
5787         hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
5788         io->timer.function = io_link_timeout_fn;
5789         hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
5790         return 0;
5791 }
5792
5793 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5794                              struct timespec64 *ts, enum hrtimer_mode mode)
5795         __must_hold(&ctx->timeout_lock)
5796 {
5797         struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5798         struct io_timeout_data *data;
5799
5800         if (IS_ERR(req))
5801                 return PTR_ERR(req);
5802
5803         req->timeout.off = 0; /* noseq */
5804         data = req->async_data;
5805         list_add_tail(&req->timeout.list, &ctx->timeout_list);
5806         hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
5807         data->timer.function = io_timeout_fn;
5808         hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5809         return 0;
5810 }
5811
5812 static int io_timeout_remove_prep(struct io_kiocb *req,
5813                                   const struct io_uring_sqe *sqe)
5814 {
5815         struct io_timeout_rem *tr = &req->timeout_rem;
5816
5817         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5818                 return -EINVAL;
5819         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5820                 return -EINVAL;
5821         if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
5822                 return -EINVAL;
5823
5824         tr->ltimeout = false;
5825         tr->addr = READ_ONCE(sqe->addr);
5826         tr->flags = READ_ONCE(sqe->timeout_flags);
5827         if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
5828                 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5829                         return -EINVAL;
5830                 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
5831                         tr->ltimeout = true;
5832                 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
5833                         return -EINVAL;
5834                 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5835                         return -EFAULT;
5836         } else if (tr->flags) {
5837                 /* timeout removal doesn't support flags */
5838                 return -EINVAL;
5839         }
5840
5841         return 0;
5842 }
5843
5844 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5845 {
5846         return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5847                                             : HRTIMER_MODE_REL;
5848 }
5849
5850 /*
5851  * Remove or update an existing timeout command
5852  */
5853 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5854 {
5855         struct io_timeout_rem *tr = &req->timeout_rem;
5856         struct io_ring_ctx *ctx = req->ctx;
5857         int ret;
5858
5859         if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
5860                 spin_lock(&ctx->completion_lock);
5861                 spin_lock_irq(&ctx->timeout_lock);
5862                 ret = io_timeout_cancel(ctx, tr->addr);
5863                 spin_unlock_irq(&ctx->timeout_lock);
5864                 spin_unlock(&ctx->completion_lock);
5865         } else {
5866                 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
5867
5868                 spin_lock_irq(&ctx->timeout_lock);
5869                 if (tr->ltimeout)
5870                         ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
5871                 else
5872                         ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5873                 spin_unlock_irq(&ctx->timeout_lock);
5874         }
5875
5876         if (ret < 0)
5877                 req_set_fail(req);
5878         io_req_complete_post(req, ret, 0);
5879         return 0;
5880 }
5881
5882 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5883                            bool is_timeout_link)
5884 {
5885         struct io_timeout_data *data;
5886         unsigned flags;
5887         u32 off = READ_ONCE(sqe->off);
5888
5889         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5890                 return -EINVAL;
5891         if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
5892             sqe->splice_fd_in)
5893                 return -EINVAL;
5894         if (off && is_timeout_link)
5895                 return -EINVAL;
5896         flags = READ_ONCE(sqe->timeout_flags);
5897         if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
5898                 return -EINVAL;
5899         /* more than one clock specified is invalid, obviously */
5900         if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5901                 return -EINVAL;
5902
5903         INIT_LIST_HEAD(&req->timeout.list);
5904         req->timeout.off = off;
5905         if (unlikely(off && !req->ctx->off_timeout_used))
5906                 req->ctx->off_timeout_used = true;
5907
5908         if (!req->async_data && io_alloc_async_data(req))
5909                 return -ENOMEM;
5910
5911         data = req->async_data;
5912         data->req = req;
5913         data->flags = flags;
5914
5915         if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5916                 return -EFAULT;
5917
5918         data->mode = io_translate_timeout_mode(flags);
5919         hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
5920
5921         if (is_timeout_link) {
5922                 struct io_submit_link *link = &req->ctx->submit_state.link;
5923
5924                 if (!link->head)
5925                         return -EINVAL;
5926                 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
5927                         return -EINVAL;
5928                 req->timeout.head = link->last;
5929                 link->last->flags |= REQ_F_ARM_LTIMEOUT;
5930         }
5931         return 0;
5932 }
5933
5934 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5935 {
5936         struct io_ring_ctx *ctx = req->ctx;
5937         struct io_timeout_data *data = req->async_data;
5938         struct list_head *entry;
5939         u32 tail, off = req->timeout.off;
5940
5941         spin_lock_irq(&ctx->timeout_lock);
5942
5943         /*
5944          * sqe->off holds how many events that need to occur for this
5945          * timeout event to be satisfied. If it isn't set, then this is
5946          * a pure timeout request, sequence isn't used.
5947          */
5948         if (io_is_timeout_noseq(req)) {
5949                 entry = ctx->timeout_list.prev;
5950                 goto add;
5951         }
5952
5953         tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5954         req->timeout.target_seq = tail + off;
5955
5956         /* Update the last seq here in case io_flush_timeouts() hasn't.
5957          * This is safe because ->completion_lock is held, and submissions
5958          * and completions are never mixed in the same ->completion_lock section.
5959          */
5960         ctx->cq_last_tm_flush = tail;
5961
5962         /*
5963          * Insertion sort, ensuring the first entry in the list is always
5964          * the one we need first.
5965          */
5966         list_for_each_prev(entry, &ctx->timeout_list) {
5967                 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5968                                                   timeout.list);
5969
5970                 if (io_is_timeout_noseq(nxt))
5971                         continue;
5972                 /* nxt.seq is behind @tail, otherwise would've been completed */
5973                 if (off >= nxt->timeout.target_seq - tail)
5974                         break;
5975         }
5976 add:
5977         list_add(&req->timeout.list, entry);
5978         data->timer.function = io_timeout_fn;
5979         hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5980         spin_unlock_irq(&ctx->timeout_lock);
5981         return 0;
5982 }
5983
5984 struct io_cancel_data {
5985         struct io_ring_ctx *ctx;
5986         u64 user_data;
5987 };
5988
5989 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5990 {
5991         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5992         struct io_cancel_data *cd = data;
5993
5994         return req->ctx == cd->ctx && req->user_data == cd->user_data;
5995 }
5996
5997 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5998                                struct io_ring_ctx *ctx)
5999 {
6000         struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6001         enum io_wq_cancel cancel_ret;
6002         int ret = 0;
6003
6004         if (!tctx || !tctx->io_wq)
6005                 return -ENOENT;
6006
6007         cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6008         switch (cancel_ret) {
6009         case IO_WQ_CANCEL_OK:
6010                 ret = 0;
6011                 break;
6012         case IO_WQ_CANCEL_RUNNING:
6013                 ret = -EALREADY;
6014                 break;
6015         case IO_WQ_CANCEL_NOTFOUND:
6016                 ret = -ENOENT;
6017                 break;
6018         }
6019
6020         return ret;
6021 }
6022
6023 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6024 {
6025         struct io_ring_ctx *ctx = req->ctx;
6026         int ret;
6027
6028         WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6029
6030         ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6031         if (ret != -ENOENT)
6032                 return ret;
6033
6034         spin_lock(&ctx->completion_lock);
6035         spin_lock_irq(&ctx->timeout_lock);
6036         ret = io_timeout_cancel(ctx, sqe_addr);
6037         spin_unlock_irq(&ctx->timeout_lock);
6038         if (ret != -ENOENT)
6039                 goto out;
6040         ret = io_poll_cancel(ctx, sqe_addr, false);
6041 out:
6042         spin_unlock(&ctx->completion_lock);
6043         return ret;
6044 }
6045
6046 static int io_async_cancel_prep(struct io_kiocb *req,
6047                                 const struct io_uring_sqe *sqe)
6048 {
6049         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6050                 return -EINVAL;
6051         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6052                 return -EINVAL;
6053         if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6054             sqe->splice_fd_in)
6055                 return -EINVAL;
6056
6057         req->cancel.addr = READ_ONCE(sqe->addr);
6058         return 0;
6059 }
6060
6061 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6062 {
6063         struct io_ring_ctx *ctx = req->ctx;
6064         u64 sqe_addr = req->cancel.addr;
6065         struct io_tctx_node *node;
6066         int ret;
6067
6068         ret = io_try_cancel_userdata(req, sqe_addr);
6069         if (ret != -ENOENT)
6070                 goto done;
6071
6072         /* slow path, try all io-wq's */
6073         io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6074         ret = -ENOENT;
6075         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6076                 struct io_uring_task *tctx = node->task->io_uring;
6077
6078                 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6079                 if (ret != -ENOENT)
6080                         break;
6081         }
6082         io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6083 done:
6084         if (ret < 0)
6085                 req_set_fail(req);
6086         io_req_complete_post(req, ret, 0);
6087         return 0;
6088 }
6089
6090 static int io_rsrc_update_prep(struct io_kiocb *req,
6091                                 const struct io_uring_sqe *sqe)
6092 {
6093         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6094                 return -EINVAL;
6095         if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6096                 return -EINVAL;
6097
6098         req->rsrc_update.offset = READ_ONCE(sqe->off);
6099         req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6100         if (!req->rsrc_update.nr_args)
6101                 return -EINVAL;
6102         req->rsrc_update.arg = READ_ONCE(sqe->addr);
6103         return 0;
6104 }
6105
6106 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6107 {
6108         struct io_ring_ctx *ctx = req->ctx;
6109         struct io_uring_rsrc_update2 up;
6110         int ret;
6111
6112         if (issue_flags & IO_URING_F_NONBLOCK)
6113                 return -EAGAIN;
6114
6115         up.offset = req->rsrc_update.offset;
6116         up.data = req->rsrc_update.arg;
6117         up.nr = 0;
6118         up.tags = 0;
6119         up.resv = 0;
6120
6121         mutex_lock(&ctx->uring_lock);
6122         ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6123                                         &up, req->rsrc_update.nr_args);
6124         mutex_unlock(&ctx->uring_lock);
6125
6126         if (ret < 0)
6127                 req_set_fail(req);
6128         __io_req_complete(req, issue_flags, ret, 0);
6129         return 0;
6130 }
6131
6132 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6133 {
6134         switch (req->opcode) {
6135         case IORING_OP_NOP:
6136                 return 0;
6137         case IORING_OP_READV:
6138         case IORING_OP_READ_FIXED:
6139         case IORING_OP_READ:
6140                 return io_read_prep(req, sqe);
6141         case IORING_OP_WRITEV:
6142         case IORING_OP_WRITE_FIXED:
6143         case IORING_OP_WRITE:
6144                 return io_write_prep(req, sqe);
6145         case IORING_OP_POLL_ADD:
6146                 return io_poll_add_prep(req, sqe);
6147         case IORING_OP_POLL_REMOVE:
6148                 return io_poll_update_prep(req, sqe);
6149         case IORING_OP_FSYNC:
6150                 return io_fsync_prep(req, sqe);
6151         case IORING_OP_SYNC_FILE_RANGE:
6152                 return io_sfr_prep(req, sqe);
6153         case IORING_OP_SENDMSG:
6154         case IORING_OP_SEND:
6155                 return io_sendmsg_prep(req, sqe);
6156         case IORING_OP_RECVMSG:
6157         case IORING_OP_RECV:
6158                 return io_recvmsg_prep(req, sqe);
6159         case IORING_OP_CONNECT:
6160                 return io_connect_prep(req, sqe);
6161         case IORING_OP_TIMEOUT:
6162                 return io_timeout_prep(req, sqe, false);
6163         case IORING_OP_TIMEOUT_REMOVE:
6164                 return io_timeout_remove_prep(req, sqe);
6165         case IORING_OP_ASYNC_CANCEL:
6166                 return io_async_cancel_prep(req, sqe);
6167         case IORING_OP_LINK_TIMEOUT:
6168                 return io_timeout_prep(req, sqe, true);
6169         case IORING_OP_ACCEPT:
6170                 return io_accept_prep(req, sqe);
6171         case IORING_OP_FALLOCATE:
6172                 return io_fallocate_prep(req, sqe);
6173         case IORING_OP_OPENAT:
6174                 return io_openat_prep(req, sqe);
6175         case IORING_OP_CLOSE:
6176                 return io_close_prep(req, sqe);
6177         case IORING_OP_FILES_UPDATE:
6178                 return io_rsrc_update_prep(req, sqe);
6179         case IORING_OP_STATX:
6180                 return io_statx_prep(req, sqe);
6181         case IORING_OP_FADVISE:
6182                 return io_fadvise_prep(req, sqe);
6183         case IORING_OP_MADVISE:
6184                 return io_madvise_prep(req, sqe);
6185         case IORING_OP_OPENAT2:
6186                 return io_openat2_prep(req, sqe);
6187         case IORING_OP_EPOLL_CTL:
6188                 return io_epoll_ctl_prep(req, sqe);
6189         case IORING_OP_SPLICE:
6190                 return io_splice_prep(req, sqe);
6191         case IORING_OP_PROVIDE_BUFFERS:
6192                 return io_provide_buffers_prep(req, sqe);
6193         case IORING_OP_REMOVE_BUFFERS:
6194                 return io_remove_buffers_prep(req, sqe);
6195         case IORING_OP_TEE:
6196                 return io_tee_prep(req, sqe);
6197         case IORING_OP_SHUTDOWN:
6198                 return io_shutdown_prep(req, sqe);
6199         case IORING_OP_RENAMEAT:
6200                 return io_renameat_prep(req, sqe);
6201         case IORING_OP_UNLINKAT:
6202                 return io_unlinkat_prep(req, sqe);
6203         }
6204
6205         printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6206                         req->opcode);
6207         return -EINVAL;
6208 }
6209
6210 static int io_req_prep_async(struct io_kiocb *req)
6211 {
6212         if (!io_op_defs[req->opcode].needs_async_setup)
6213                 return 0;
6214         if (WARN_ON_ONCE(req->async_data))
6215                 return -EFAULT;
6216         if (io_alloc_async_data(req))
6217                 return -EAGAIN;
6218
6219         switch (req->opcode) {
6220         case IORING_OP_READV:
6221                 return io_rw_prep_async(req, READ);
6222         case IORING_OP_WRITEV:
6223                 return io_rw_prep_async(req, WRITE);
6224         case IORING_OP_SENDMSG:
6225                 return io_sendmsg_prep_async(req);
6226         case IORING_OP_RECVMSG:
6227                 return io_recvmsg_prep_async(req);
6228         case IORING_OP_CONNECT:
6229                 return io_connect_prep_async(req);
6230         }
6231         printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6232                     req->opcode);
6233         return -EFAULT;
6234 }
6235
6236 static u32 io_get_sequence(struct io_kiocb *req)
6237 {
6238         u32 seq = req->ctx->cached_sq_head;
6239
6240         /* need original cached_sq_head, but it was increased for each req */
6241         io_for_each_link(req, req)
6242                 seq--;
6243         return seq;
6244 }
6245
6246 static bool io_drain_req(struct io_kiocb *req)
6247 {
6248         struct io_kiocb *pos;
6249         struct io_ring_ctx *ctx = req->ctx;
6250         struct io_defer_entry *de;
6251         int ret;
6252         u32 seq;
6253
6254         if (req->flags & REQ_F_FAIL) {
6255                 io_req_complete_fail_submit(req);
6256                 return true;
6257         }
6258
6259         /*
6260          * If we need to drain a request in the middle of a link, drain the
6261          * head request and the next request/link after the current link.
6262          * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6263          * maintained for every request of our link.
6264          */
6265         if (ctx->drain_next) {
6266                 req->flags |= REQ_F_IO_DRAIN;
6267                 ctx->drain_next = false;
6268         }
6269         /* not interested in head, start from the first linked */
6270         io_for_each_link(pos, req->link) {
6271                 if (pos->flags & REQ_F_IO_DRAIN) {
6272                         ctx->drain_next = true;
6273                         req->flags |= REQ_F_IO_DRAIN;
6274                         break;
6275                 }
6276         }
6277
6278         /* Still need defer if there is pending req in defer list. */
6279         if (likely(list_empty_careful(&ctx->defer_list) &&
6280                 !(req->flags & REQ_F_IO_DRAIN))) {
6281                 ctx->drain_active = false;
6282                 return false;
6283         }
6284
6285         seq = io_get_sequence(req);
6286         /* Still a chance to pass the sequence check */
6287         if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6288                 return false;
6289
6290         ret = io_req_prep_async(req);
6291         if (ret)
6292                 goto fail;
6293         io_prep_async_link(req);
6294         de = kmalloc(sizeof(*de), GFP_KERNEL);
6295         if (!de) {
6296                 ret = -ENOMEM;
6297 fail:
6298                 io_req_complete_failed(req, ret);
6299                 return true;
6300         }
6301
6302         spin_lock(&ctx->completion_lock);
6303         if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6304                 spin_unlock(&ctx->completion_lock);
6305                 kfree(de);
6306                 io_queue_async_work(req, NULL);
6307                 return true;
6308         }
6309
6310         trace_io_uring_defer(ctx, req, req->user_data);
6311         de->req = req;
6312         de->seq = seq;
6313         list_add_tail(&de->list, &ctx->defer_list);
6314         spin_unlock(&ctx->completion_lock);
6315         return true;
6316 }
6317
6318 static void io_clean_op(struct io_kiocb *req)
6319 {
6320         if (req->flags & REQ_F_BUFFER_SELECTED) {
6321                 switch (req->opcode) {
6322                 case IORING_OP_READV:
6323                 case IORING_OP_READ_FIXED:
6324                 case IORING_OP_READ:
6325                         kfree((void *)(unsigned long)req->rw.addr);
6326                         break;
6327                 case IORING_OP_RECVMSG:
6328                 case IORING_OP_RECV:
6329                         kfree(req->sr_msg.kbuf);
6330                         break;
6331                 }
6332         }
6333
6334         if (req->flags & REQ_F_NEED_CLEANUP) {
6335                 switch (req->opcode) {
6336                 case IORING_OP_READV:
6337                 case IORING_OP_READ_FIXED:
6338                 case IORING_OP_READ:
6339                 case IORING_OP_WRITEV:
6340                 case IORING_OP_WRITE_FIXED:
6341                 case IORING_OP_WRITE: {
6342                         struct io_async_rw *io = req->async_data;
6343
6344                         kfree(io->free_iovec);
6345                         break;
6346                         }
6347                 case IORING_OP_RECVMSG:
6348                 case IORING_OP_SENDMSG: {
6349                         struct io_async_msghdr *io = req->async_data;
6350
6351                         kfree(io->free_iov);
6352                         break;
6353                         }
6354                 case IORING_OP_SPLICE:
6355                 case IORING_OP_TEE:
6356                         if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6357                                 io_put_file(req->splice.file_in);
6358                         break;
6359                 case IORING_OP_OPENAT:
6360                 case IORING_OP_OPENAT2:
6361                         if (req->open.filename)
6362                                 putname(req->open.filename);
6363                         break;
6364                 case IORING_OP_RENAMEAT:
6365                         putname(req->rename.oldpath);
6366                         putname(req->rename.newpath);
6367                         break;
6368                 case IORING_OP_UNLINKAT:
6369                         putname(req->unlink.filename);
6370                         break;
6371                 }
6372         }
6373         if ((req->flags & REQ_F_POLLED) && req->apoll) {
6374                 kfree(req->apoll->double_poll);
6375                 kfree(req->apoll);
6376                 req->apoll = NULL;
6377         }
6378         if (req->flags & REQ_F_INFLIGHT) {
6379                 struct io_uring_task *tctx = req->task->io_uring;
6380
6381                 atomic_dec(&tctx->inflight_tracked);
6382         }
6383         if (req->flags & REQ_F_CREDS)
6384                 put_cred(req->creds);
6385
6386         req->flags &= ~IO_REQ_CLEAN_FLAGS;
6387 }
6388
6389 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6390 {
6391         struct io_ring_ctx *ctx = req->ctx;
6392         const struct cred *creds = NULL;
6393         int ret;
6394
6395         if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6396                 creds = override_creds(req->creds);
6397
6398         switch (req->opcode) {
6399         case IORING_OP_NOP:
6400                 ret = io_nop(req, issue_flags);
6401                 break;
6402         case IORING_OP_READV:
6403         case IORING_OP_READ_FIXED:
6404         case IORING_OP_READ:
6405                 ret = io_read(req, issue_flags);
6406                 break;
6407         case IORING_OP_WRITEV:
6408         case IORING_OP_WRITE_FIXED:
6409         case IORING_OP_WRITE:
6410                 ret = io_write(req, issue_flags);
6411                 break;
6412         case IORING_OP_FSYNC:
6413                 ret = io_fsync(req, issue_flags);
6414                 break;
6415         case IORING_OP_POLL_ADD:
6416                 ret = io_poll_add(req, issue_flags);
6417                 break;
6418         case IORING_OP_POLL_REMOVE:
6419                 ret = io_poll_update(req, issue_flags);
6420                 break;
6421         case IORING_OP_SYNC_FILE_RANGE:
6422                 ret = io_sync_file_range(req, issue_flags);
6423                 break;
6424         case IORING_OP_SENDMSG:
6425                 ret = io_sendmsg(req, issue_flags);
6426                 break;
6427         case IORING_OP_SEND:
6428                 ret = io_send(req, issue_flags);
6429                 break;
6430         case IORING_OP_RECVMSG:
6431                 ret = io_recvmsg(req, issue_flags);
6432                 break;
6433         case IORING_OP_RECV:
6434                 ret = io_recv(req, issue_flags);
6435                 break;
6436         case IORING_OP_TIMEOUT:
6437                 ret = io_timeout(req, issue_flags);
6438                 break;
6439         case IORING_OP_TIMEOUT_REMOVE:
6440                 ret = io_timeout_remove(req, issue_flags);
6441                 break;
6442         case IORING_OP_ACCEPT:
6443                 ret = io_accept(req, issue_flags);
6444                 break;
6445         case IORING_OP_CONNECT:
6446                 ret = io_connect(req, issue_flags);
6447                 break;
6448         case IORING_OP_ASYNC_CANCEL:
6449                 ret = io_async_cancel(req, issue_flags);
6450                 break;
6451         case IORING_OP_FALLOCATE:
6452                 ret = io_fallocate(req, issue_flags);
6453                 break;
6454         case IORING_OP_OPENAT:
6455                 ret = io_openat(req, issue_flags);
6456                 break;
6457         case IORING_OP_CLOSE:
6458                 ret = io_close(req, issue_flags);
6459                 break;
6460         case IORING_OP_FILES_UPDATE:
6461                 ret = io_files_update(req, issue_flags);
6462                 break;
6463         case IORING_OP_STATX:
6464                 ret = io_statx(req, issue_flags);
6465                 break;
6466         case IORING_OP_FADVISE:
6467                 ret = io_fadvise(req, issue_flags);
6468                 break;
6469         case IORING_OP_MADVISE:
6470                 ret = io_madvise(req, issue_flags);
6471                 break;
6472         case IORING_OP_OPENAT2:
6473                 ret = io_openat2(req, issue_flags);
6474                 break;
6475         case IORING_OP_EPOLL_CTL:
6476                 ret = io_epoll_ctl(req, issue_flags);
6477                 break;
6478         case IORING_OP_SPLICE:
6479                 ret = io_splice(req, issue_flags);
6480                 break;
6481         case IORING_OP_PROVIDE_BUFFERS:
6482                 ret = io_provide_buffers(req, issue_flags);
6483                 break;
6484         case IORING_OP_REMOVE_BUFFERS:
6485                 ret = io_remove_buffers(req, issue_flags);
6486                 break;
6487         case IORING_OP_TEE:
6488                 ret = io_tee(req, issue_flags);
6489                 break;
6490         case IORING_OP_SHUTDOWN:
6491                 ret = io_shutdown(req, issue_flags);
6492                 break;
6493         case IORING_OP_RENAMEAT:
6494                 ret = io_renameat(req, issue_flags);
6495                 break;
6496         case IORING_OP_UNLINKAT:
6497                 ret = io_unlinkat(req, issue_flags);
6498                 break;
6499         default:
6500                 ret = -EINVAL;
6501                 break;
6502         }
6503
6504         if (creds)
6505                 revert_creds(creds);
6506         if (ret)
6507                 return ret;
6508         /* If the op doesn't have a file, we're not polling for it */
6509         if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6510                 io_iopoll_req_issued(req);
6511
6512         return 0;
6513 }
6514
6515 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6516 {
6517         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6518
6519         req = io_put_req_find_next(req);
6520         return req ? &req->work : NULL;
6521 }
6522
6523 static void io_wq_submit_work(struct io_wq_work *work)
6524 {
6525         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6526         struct io_kiocb *timeout;
6527         int ret = 0;
6528
6529         /* one will be dropped by ->io_free_work() after returning to io-wq */
6530         if (!(req->flags & REQ_F_REFCOUNT))
6531                 __io_req_set_refcount(req, 2);
6532         else
6533                 req_ref_get(req);
6534
6535         timeout = io_prep_linked_timeout(req);
6536         if (timeout)
6537                 io_queue_linked_timeout(timeout);
6538
6539         /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6540         if (work->flags & IO_WQ_WORK_CANCEL)
6541                 ret = -ECANCELED;
6542
6543         if (!ret) {
6544                 do {
6545                         ret = io_issue_sqe(req, 0);
6546                         /*
6547                          * We can get EAGAIN for polled IO even though we're
6548                          * forcing a sync submission from here, since we can't
6549                          * wait for request slots on the block side.
6550                          */
6551                         if (ret != -EAGAIN)
6552                                 break;
6553                         cond_resched();
6554                 } while (1);
6555         }
6556
6557         /* avoid locking problems by failing it from a clean context */
6558         if (ret)
6559                 io_req_task_queue_fail(req, ret);
6560 }
6561
6562 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6563                                                        unsigned i)
6564 {
6565         return &table->files[i];
6566 }
6567
6568 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6569                                               int index)
6570 {
6571         struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6572
6573         return (struct file *) (slot->file_ptr & FFS_MASK);
6574 }
6575
6576 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6577 {
6578         unsigned long file_ptr = (unsigned long) file;
6579
6580         if (__io_file_supports_nowait(file, READ))
6581                 file_ptr |= FFS_ASYNC_READ;
6582         if (__io_file_supports_nowait(file, WRITE))
6583                 file_ptr |= FFS_ASYNC_WRITE;
6584         if (S_ISREG(file_inode(file)->i_mode))
6585                 file_ptr |= FFS_ISREG;
6586         file_slot->file_ptr = file_ptr;
6587 }
6588
6589 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6590                                              struct io_kiocb *req, int fd)
6591 {
6592         struct file *file;
6593         unsigned long file_ptr;
6594
6595         if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6596                 return NULL;
6597         fd = array_index_nospec(fd, ctx->nr_user_files);
6598         file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6599         file = (struct file *) (file_ptr & FFS_MASK);
6600         file_ptr &= ~FFS_MASK;
6601         /* mask in overlapping REQ_F and FFS bits */
6602         req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6603         io_req_set_rsrc_node(req);
6604         return file;
6605 }
6606
6607 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6608                                        struct io_kiocb *req, int fd)
6609 {
6610         struct file *file = fget(fd);
6611
6612         trace_io_uring_file_get(ctx, fd);
6613
6614         /* we don't allow fixed io_uring files */
6615         if (file && unlikely(file->f_op == &io_uring_fops))
6616                 io_req_track_inflight(req);
6617         return file;
6618 }
6619
6620 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6621                                        struct io_kiocb *req, int fd, bool fixed)
6622 {
6623         if (fixed)
6624                 return io_file_get_fixed(ctx, req, fd);
6625         else
6626                 return io_file_get_normal(ctx, req, fd);
6627 }
6628
6629 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6630 {
6631         struct io_kiocb *prev = req->timeout.prev;
6632         int ret;
6633
6634         if (prev) {
6635                 ret = io_try_cancel_userdata(req, prev->user_data);
6636                 io_req_complete_post(req, ret ?: -ETIME, 0);
6637                 io_put_req(prev);
6638         } else {
6639                 io_req_complete_post(req, -ETIME, 0);
6640         }
6641 }
6642
6643 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6644 {
6645         struct io_timeout_data *data = container_of(timer,
6646                                                 struct io_timeout_data, timer);
6647         struct io_kiocb *prev, *req = data->req;
6648         struct io_ring_ctx *ctx = req->ctx;
6649         unsigned long flags;
6650
6651         spin_lock_irqsave(&ctx->timeout_lock, flags);
6652         prev = req->timeout.head;
6653         req->timeout.head = NULL;
6654
6655         /*
6656          * We don't expect the list to be empty, that will only happen if we
6657          * race with the completion of the linked work.
6658          */
6659         if (prev) {
6660                 io_remove_next_linked(prev);
6661                 if (!req_ref_inc_not_zero(prev))
6662                         prev = NULL;
6663         }
6664         list_del(&req->timeout.list);
6665         req->timeout.prev = prev;
6666         spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6667
6668         req->io_task_work.func = io_req_task_link_timeout;
6669         io_req_task_work_add(req);
6670         return HRTIMER_NORESTART;
6671 }
6672
6673 static void io_queue_linked_timeout(struct io_kiocb *req)
6674 {
6675         struct io_ring_ctx *ctx = req->ctx;
6676
6677         spin_lock_irq(&ctx->timeout_lock);
6678         /*
6679          * If the back reference is NULL, then our linked request finished
6680          * before we got a chance to setup the timer
6681          */
6682         if (req->timeout.head) {
6683                 struct io_timeout_data *data = req->async_data;
6684
6685                 data->timer.function = io_link_timeout_fn;
6686                 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6687                                 data->mode);
6688                 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
6689         }
6690         spin_unlock_irq(&ctx->timeout_lock);
6691         /* drop submission reference */
6692         io_put_req(req);
6693 }
6694
6695 static void __io_queue_sqe(struct io_kiocb *req)
6696         __must_hold(&req->ctx->uring_lock)
6697 {
6698         struct io_kiocb *linked_timeout;
6699         int ret;
6700
6701 issue_sqe:
6702         ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6703
6704         /*
6705          * We async punt it if the file wasn't marked NOWAIT, or if the file
6706          * doesn't support non-blocking read/write attempts
6707          */
6708         if (likely(!ret)) {
6709                 if (req->flags & REQ_F_COMPLETE_INLINE) {
6710                         struct io_ring_ctx *ctx = req->ctx;
6711                         struct io_submit_state *state = &ctx->submit_state;
6712
6713                         state->compl_reqs[state->compl_nr++] = req;
6714                         if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6715                                 io_submit_flush_completions(ctx);
6716                         return;
6717                 }
6718
6719                 linked_timeout = io_prep_linked_timeout(req);
6720                 if (linked_timeout)
6721                         io_queue_linked_timeout(linked_timeout);
6722         } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6723                 linked_timeout = io_prep_linked_timeout(req);
6724
6725                 switch (io_arm_poll_handler(req)) {
6726                 case IO_APOLL_READY:
6727                         if (linked_timeout)
6728                                 io_unprep_linked_timeout(req);
6729                         goto issue_sqe;
6730                 case IO_APOLL_ABORTED:
6731                         /*
6732                          * Queued up for async execution, worker will release
6733                          * submit reference when the iocb is actually submitted.
6734                          */
6735                         io_queue_async_work(req, NULL);
6736                         break;
6737                 }
6738
6739                 if (linked_timeout)
6740                         io_queue_linked_timeout(linked_timeout);
6741         } else {
6742                 io_req_complete_failed(req, ret);
6743         }
6744 }
6745
6746 static inline void io_queue_sqe(struct io_kiocb *req)
6747         __must_hold(&req->ctx->uring_lock)
6748 {
6749         if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6750                 return;
6751
6752         if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
6753                 __io_queue_sqe(req);
6754         } else if (req->flags & REQ_F_FAIL) {
6755                 io_req_complete_fail_submit(req);
6756         } else {
6757                 int ret = io_req_prep_async(req);
6758
6759                 if (unlikely(ret))
6760                         io_req_complete_failed(req, ret);
6761                 else
6762                         io_queue_async_work(req, NULL);
6763         }
6764 }
6765
6766 /*
6767  * Check SQE restrictions (opcode and flags).
6768  *
6769  * Returns 'true' if SQE is allowed, 'false' otherwise.
6770  */
6771 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6772                                         struct io_kiocb *req,
6773                                         unsigned int sqe_flags)
6774 {
6775         if (likely(!ctx->restricted))
6776                 return true;
6777
6778         if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6779                 return false;
6780
6781         if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6782             ctx->restrictions.sqe_flags_required)
6783                 return false;
6784
6785         if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6786                           ctx->restrictions.sqe_flags_required))
6787                 return false;
6788
6789         return true;
6790 }
6791
6792 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6793                        const struct io_uring_sqe *sqe)
6794         __must_hold(&ctx->uring_lock)
6795 {
6796         struct io_submit_state *state;
6797         unsigned int sqe_flags;
6798         int personality, ret = 0;
6799
6800         /* req is partially pre-initialised, see io_preinit_req() */
6801         req->opcode = READ_ONCE(sqe->opcode);
6802         /* same numerical values with corresponding REQ_F_*, safe to copy */
6803         req->flags = sqe_flags = READ_ONCE(sqe->flags);
6804         req->user_data = READ_ONCE(sqe->user_data);
6805         req->file = NULL;
6806         req->fixed_rsrc_refs = NULL;
6807         req->task = current;
6808
6809         /* enforce forwards compatibility on users */
6810         if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6811                 return -EINVAL;
6812         if (unlikely(req->opcode >= IORING_OP_LAST))
6813                 return -EINVAL;
6814         if (!io_check_restriction(ctx, req, sqe_flags))
6815                 return -EACCES;
6816
6817         if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6818             !io_op_defs[req->opcode].buffer_select)
6819                 return -EOPNOTSUPP;
6820         if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6821                 ctx->drain_active = true;
6822
6823         personality = READ_ONCE(sqe->personality);
6824         if (personality) {
6825                 req->creds = xa_load(&ctx->personalities, personality);
6826                 if (!req->creds)
6827                         return -EINVAL;
6828                 get_cred(req->creds);
6829                 req->flags |= REQ_F_CREDS;
6830         }
6831         state = &ctx->submit_state;
6832
6833         /*
6834          * Plug now if we have more than 1 IO left after this, and the target
6835          * is potentially a read/write to block based storage.
6836          */
6837         if (!state->plug_started && state->ios_left > 1 &&
6838             io_op_defs[req->opcode].plug) {
6839                 blk_start_plug(&state->plug);
6840                 state->plug_started = true;
6841         }
6842
6843         if (io_op_defs[req->opcode].needs_file) {
6844                 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
6845                                         (sqe_flags & IOSQE_FIXED_FILE));
6846                 if (unlikely(!req->file))
6847                         ret = -EBADF;
6848         }
6849
6850         state->ios_left--;
6851         return ret;
6852 }
6853
6854 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6855                          const struct io_uring_sqe *sqe)
6856         __must_hold(&ctx->uring_lock)
6857 {
6858         struct io_submit_link *link = &ctx->submit_state.link;
6859         int ret;
6860
6861         ret = io_init_req(ctx, req, sqe);
6862         if (unlikely(ret)) {
6863 fail_req:
6864                 /* fail even hard links since we don't submit */
6865                 if (link->head) {
6866                         /*
6867                          * we can judge a link req is failed or cancelled by if
6868                          * REQ_F_FAIL is set, but the head is an exception since
6869                          * it may be set REQ_F_FAIL because of other req's failure
6870                          * so let's leverage req->result to distinguish if a head
6871                          * is set REQ_F_FAIL because of its failure or other req's
6872                          * failure so that we can set the correct ret code for it.
6873                          * init result here to avoid affecting the normal path.
6874                          */
6875                         if (!(link->head->flags & REQ_F_FAIL))
6876                                 req_fail_link_node(link->head, -ECANCELED);
6877                 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6878                         /*
6879                          * the current req is a normal req, we should return
6880                          * error and thus break the submittion loop.
6881                          */
6882                         io_req_complete_failed(req, ret);
6883                         return ret;
6884                 }
6885                 req_fail_link_node(req, ret);
6886         } else {
6887                 ret = io_req_prep(req, sqe);
6888                 if (unlikely(ret))
6889                         goto fail_req;
6890         }
6891
6892         /* don't need @sqe from now on */
6893         trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6894                                   req->flags, true,
6895                                   ctx->flags & IORING_SETUP_SQPOLL);
6896
6897         /*
6898          * If we already have a head request, queue this one for async
6899          * submittal once the head completes. If we don't have a head but
6900          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6901          * submitted sync once the chain is complete. If none of those
6902          * conditions are true (normal request), then just queue it.
6903          */
6904         if (link->head) {
6905                 struct io_kiocb *head = link->head;
6906
6907                 if (!(req->flags & REQ_F_FAIL)) {
6908                         ret = io_req_prep_async(req);
6909                         if (unlikely(ret)) {
6910                                 req_fail_link_node(req, ret);
6911                                 if (!(head->flags & REQ_F_FAIL))
6912                                         req_fail_link_node(head, -ECANCELED);
6913                         }
6914                 }
6915                 trace_io_uring_link(ctx, req, head);
6916                 link->last->link = req;
6917                 link->last = req;
6918
6919                 /* last request of a link, enqueue the link */
6920                 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6921                         link->head = NULL;
6922                         io_queue_sqe(head);
6923                 }
6924         } else {
6925                 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6926                         link->head = req;
6927                         link->last = req;
6928                 } else {
6929                         io_queue_sqe(req);
6930                 }
6931         }
6932
6933         return 0;
6934 }
6935
6936 /*
6937  * Batched submission is done, ensure local IO is flushed out.
6938  */
6939 static void io_submit_state_end(struct io_submit_state *state,
6940                                 struct io_ring_ctx *ctx)
6941 {
6942         if (state->link.head)
6943                 io_queue_sqe(state->link.head);
6944         if (state->compl_nr)
6945                 io_submit_flush_completions(ctx);
6946         if (state->plug_started)
6947                 blk_finish_plug(&state->plug);
6948 }
6949
6950 /*
6951  * Start submission side cache.
6952  */
6953 static void io_submit_state_start(struct io_submit_state *state,
6954                                   unsigned int max_ios)
6955 {
6956         state->plug_started = false;
6957         state->ios_left = max_ios;
6958         /* set only head, no need to init link_last in advance */
6959         state->link.head = NULL;
6960 }
6961
6962 static void io_commit_sqring(struct io_ring_ctx *ctx)
6963 {
6964         struct io_rings *rings = ctx->rings;
6965
6966         /*
6967          * Ensure any loads from the SQEs are done at this point,
6968          * since once we write the new head, the application could
6969          * write new data to them.
6970          */
6971         smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6972 }
6973
6974 /*
6975  * Fetch an sqe, if one is available. Note this returns a pointer to memory
6976  * that is mapped by userspace. This means that care needs to be taken to
6977  * ensure that reads are stable, as we cannot rely on userspace always
6978  * being a good citizen. If members of the sqe are validated and then later
6979  * used, it's important that those reads are done through READ_ONCE() to
6980  * prevent a re-load down the line.
6981  */
6982 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6983 {
6984         unsigned head, mask = ctx->sq_entries - 1;
6985         unsigned sq_idx = ctx->cached_sq_head++ & mask;
6986
6987         /*
6988          * The cached sq head (or cq tail) serves two purposes:
6989          *
6990          * 1) allows us to batch the cost of updating the user visible
6991          *    head updates.
6992          * 2) allows the kernel side to track the head on its own, even
6993          *    though the application is the one updating it.
6994          */
6995         head = READ_ONCE(ctx->sq_array[sq_idx]);
6996         if (likely(head < ctx->sq_entries))
6997                 return &ctx->sq_sqes[head];
6998
6999         /* drop invalid entries */
7000         ctx->cq_extra--;
7001         WRITE_ONCE(ctx->rings->sq_dropped,
7002                    READ_ONCE(ctx->rings->sq_dropped) + 1);
7003         return NULL;
7004 }
7005
7006 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7007         __must_hold(&ctx->uring_lock)
7008 {
7009         int submitted = 0;
7010
7011         /* make sure SQ entry isn't read before tail */
7012         nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7013         if (!percpu_ref_tryget_many(&ctx->refs, nr))
7014                 return -EAGAIN;
7015         io_get_task_refs(nr);
7016
7017         io_submit_state_start(&ctx->submit_state, nr);
7018         while (submitted < nr) {
7019                 const struct io_uring_sqe *sqe;
7020                 struct io_kiocb *req;
7021
7022                 req = io_alloc_req(ctx);
7023                 if (unlikely(!req)) {
7024                         if (!submitted)
7025                                 submitted = -EAGAIN;
7026                         break;
7027                 }
7028                 sqe = io_get_sqe(ctx);
7029                 if (unlikely(!sqe)) {
7030                         list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7031                         break;
7032                 }
7033                 /* will complete beyond this point, count as submitted */
7034                 submitted++;
7035                 if (io_submit_sqe(ctx, req, sqe))
7036                         break;
7037         }
7038
7039         if (unlikely(submitted != nr)) {
7040                 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7041                 int unused = nr - ref_used;
7042
7043                 current->io_uring->cached_refs += unused;
7044                 percpu_ref_put_many(&ctx->refs, unused);
7045         }
7046
7047         io_submit_state_end(&ctx->submit_state, ctx);
7048          /* Commit SQ ring head once we've consumed and submitted all SQEs */
7049         io_commit_sqring(ctx);
7050
7051         return submitted;
7052 }
7053
7054 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7055 {
7056         return READ_ONCE(sqd->state);
7057 }
7058
7059 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7060 {
7061         /* Tell userspace we may need a wakeup call */
7062         spin_lock(&ctx->completion_lock);
7063         WRITE_ONCE(ctx->rings->sq_flags,
7064                    ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7065         spin_unlock(&ctx->completion_lock);
7066 }
7067
7068 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7069 {
7070         spin_lock(&ctx->completion_lock);
7071         WRITE_ONCE(ctx->rings->sq_flags,
7072                    ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7073         spin_unlock(&ctx->completion_lock);
7074 }
7075
7076 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7077 {
7078         unsigned int to_submit;
7079         int ret = 0;
7080
7081         to_submit = io_sqring_entries(ctx);
7082         /* if we're handling multiple rings, cap submit size for fairness */
7083         if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7084                 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7085
7086         if (!list_empty(&ctx->iopoll_list) || to_submit) {
7087                 unsigned nr_events = 0;
7088                 const struct cred *creds = NULL;
7089
7090                 if (ctx->sq_creds != current_cred())
7091                         creds = override_creds(ctx->sq_creds);
7092
7093                 mutex_lock(&ctx->uring_lock);
7094                 if (!list_empty(&ctx->iopoll_list))
7095                         io_do_iopoll(ctx, &nr_events, 0);
7096
7097                 /*
7098                  * Don't submit if refs are dying, good for io_uring_register(),
7099                  * but also it is relied upon by io_ring_exit_work()
7100                  */
7101                 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7102                     !(ctx->flags & IORING_SETUP_R_DISABLED))
7103                         ret = io_submit_sqes(ctx, to_submit);
7104                 mutex_unlock(&ctx->uring_lock);
7105
7106                 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7107                         wake_up(&ctx->sqo_sq_wait);
7108                 if (creds)
7109                         revert_creds(creds);
7110         }
7111
7112         return ret;
7113 }
7114
7115 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7116 {
7117         struct io_ring_ctx *ctx;
7118         unsigned sq_thread_idle = 0;
7119
7120         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7121                 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7122         sqd->sq_thread_idle = sq_thread_idle;
7123 }
7124
7125 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7126 {
7127         bool did_sig = false;
7128         struct ksignal ksig;
7129
7130         if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7131             signal_pending(current)) {
7132                 mutex_unlock(&sqd->lock);
7133                 if (signal_pending(current))
7134                         did_sig = get_signal(&ksig);
7135                 cond_resched();
7136                 mutex_lock(&sqd->lock);
7137         }
7138         return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7139 }
7140
7141 static int io_sq_thread(void *data)
7142 {
7143         struct io_sq_data *sqd = data;
7144         struct io_ring_ctx *ctx;
7145         unsigned long timeout = 0;
7146         char buf[TASK_COMM_LEN];
7147         DEFINE_WAIT(wait);
7148
7149         snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7150         set_task_comm(current, buf);
7151
7152         if (sqd->sq_cpu != -1)
7153                 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7154         else
7155                 set_cpus_allowed_ptr(current, cpu_online_mask);
7156         current->flags |= PF_NO_SETAFFINITY;
7157
7158         mutex_lock(&sqd->lock);
7159         while (1) {
7160                 bool cap_entries, sqt_spin = false;
7161
7162                 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7163                         if (io_sqd_handle_event(sqd))
7164                                 break;
7165                         timeout = jiffies + sqd->sq_thread_idle;
7166                 }
7167
7168                 cap_entries = !list_is_singular(&sqd->ctx_list);
7169                 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7170                         int ret = __io_sq_thread(ctx, cap_entries);
7171
7172                         if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7173                                 sqt_spin = true;
7174                 }
7175                 if (io_run_task_work())
7176                         sqt_spin = true;
7177
7178                 if (sqt_spin || !time_after(jiffies, timeout)) {
7179                         cond_resched();
7180                         if (sqt_spin)
7181                                 timeout = jiffies + sqd->sq_thread_idle;
7182                         continue;
7183                 }
7184
7185                 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7186                 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7187                         bool needs_sched = true;
7188
7189                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7190                                 io_ring_set_wakeup_flag(ctx);
7191
7192                                 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7193                                     !list_empty_careful(&ctx->iopoll_list)) {
7194                                         needs_sched = false;
7195                                         break;
7196                                 }
7197                                 if (io_sqring_entries(ctx)) {
7198                                         needs_sched = false;
7199                                         break;
7200                                 }
7201                         }
7202
7203                         if (needs_sched) {
7204                                 mutex_unlock(&sqd->lock);
7205                                 schedule();
7206                                 mutex_lock(&sqd->lock);
7207                         }
7208                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7209                                 io_ring_clear_wakeup_flag(ctx);
7210                 }
7211
7212                 finish_wait(&sqd->wait, &wait);
7213                 timeout = jiffies + sqd->sq_thread_idle;
7214         }
7215
7216         io_uring_cancel_generic(true, sqd);
7217         sqd->thread = NULL;
7218         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7219                 io_ring_set_wakeup_flag(ctx);
7220         io_run_task_work();
7221         mutex_unlock(&sqd->lock);
7222
7223         complete(&sqd->exited);
7224         do_exit(0);
7225 }
7226
7227 struct io_wait_queue {
7228         struct wait_queue_entry wq;
7229         struct io_ring_ctx *ctx;
7230         unsigned cq_tail;
7231         unsigned nr_timeouts;
7232 };
7233
7234 static inline bool io_should_wake(struct io_wait_queue *iowq)
7235 {
7236         struct io_ring_ctx *ctx = iowq->ctx;
7237         int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7238
7239         /*
7240          * Wake up if we have enough events, or if a timeout occurred since we
7241          * started waiting. For timeouts, we always want to return to userspace,
7242          * regardless of event count.
7243          */
7244         return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7245 }
7246
7247 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7248                             int wake_flags, void *key)
7249 {
7250         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7251                                                         wq);
7252
7253         /*
7254          * Cannot safely flush overflowed CQEs from here, ensure we wake up
7255          * the task, and the next invocation will do it.
7256          */
7257         if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7258                 return autoremove_wake_function(curr, mode, wake_flags, key);
7259         return -1;
7260 }
7261
7262 static int io_run_task_work_sig(void)
7263 {
7264         if (io_run_task_work())
7265                 return 1;
7266         if (!signal_pending(current))
7267                 return 0;
7268         if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7269                 return -ERESTARTSYS;
7270         return -EINTR;
7271 }
7272
7273 /* when returns >0, the caller should retry */
7274 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7275                                           struct io_wait_queue *iowq,
7276                                           signed long *timeout)
7277 {
7278         int ret;
7279
7280         /* make sure we run task_work before checking for signals */
7281         ret = io_run_task_work_sig();
7282         if (ret || io_should_wake(iowq))
7283                 return ret;
7284         /* let the caller flush overflows, retry */
7285         if (test_bit(0, &ctx->check_cq_overflow))
7286                 return 1;
7287
7288         *timeout = schedule_timeout(*timeout);
7289         return !*timeout ? -ETIME : 1;
7290 }
7291
7292 /*
7293  * Wait until events become available, if we don't already have some. The
7294  * application must reap them itself, as they reside on the shared cq ring.
7295  */
7296 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7297                           const sigset_t __user *sig, size_t sigsz,
7298                           struct __kernel_timespec __user *uts)
7299 {
7300         struct io_wait_queue iowq;
7301         struct io_rings *rings = ctx->rings;
7302         signed long timeout = MAX_SCHEDULE_TIMEOUT;
7303         int ret;
7304
7305         do {
7306                 io_cqring_overflow_flush(ctx);
7307                 if (io_cqring_events(ctx) >= min_events)
7308                         return 0;
7309                 if (!io_run_task_work())
7310                         break;
7311         } while (1);
7312
7313         if (sig) {
7314 #ifdef CONFIG_COMPAT
7315                 if (in_compat_syscall())
7316                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7317                                                       sigsz);
7318                 else
7319 #endif
7320                         ret = set_user_sigmask(sig, sigsz);
7321
7322                 if (ret)
7323                         return ret;
7324         }
7325
7326         if (uts) {
7327                 struct timespec64 ts;
7328
7329                 if (get_timespec64(&ts, uts))
7330                         return -EFAULT;
7331                 timeout = timespec64_to_jiffies(&ts);
7332         }
7333
7334         init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7335         iowq.wq.private = current;
7336         INIT_LIST_HEAD(&iowq.wq.entry);
7337         iowq.ctx = ctx;
7338         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7339         iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7340
7341         trace_io_uring_cqring_wait(ctx, min_events);
7342         do {
7343                 /* if we can't even flush overflow, don't wait for more */
7344                 if (!io_cqring_overflow_flush(ctx)) {
7345                         ret = -EBUSY;
7346                         break;
7347                 }
7348                 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7349                                                 TASK_INTERRUPTIBLE);
7350                 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7351                 finish_wait(&ctx->cq_wait, &iowq.wq);
7352                 cond_resched();
7353         } while (ret > 0);
7354
7355         restore_saved_sigmask_unless(ret == -EINTR);
7356
7357         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7358 }
7359
7360 static void io_free_page_table(void **table, size_t size)
7361 {
7362         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7363
7364         for (i = 0; i < nr_tables; i++)
7365                 kfree(table[i]);
7366         kfree(table);
7367 }
7368
7369 static void **io_alloc_page_table(size_t size)
7370 {
7371         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7372         size_t init_size = size;
7373         void **table;
7374
7375         table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7376         if (!table)
7377                 return NULL;
7378
7379         for (i = 0; i < nr_tables; i++) {
7380                 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7381
7382                 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7383                 if (!table[i]) {
7384                         io_free_page_table(table, init_size);
7385                         return NULL;
7386                 }
7387                 size -= this_size;
7388         }
7389         return table;
7390 }
7391
7392 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7393 {
7394         percpu_ref_exit(&ref_node->refs);
7395         kfree(ref_node);
7396 }
7397
7398 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7399 {
7400         struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7401         struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7402         unsigned long flags;
7403         bool first_add = false;
7404
7405         spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7406         node->done = true;
7407
7408         while (!list_empty(&ctx->rsrc_ref_list)) {
7409                 node = list_first_entry(&ctx->rsrc_ref_list,
7410                                             struct io_rsrc_node, node);
7411                 /* recycle ref nodes in order */
7412                 if (!node->done)
7413                         break;
7414                 list_del(&node->node);
7415                 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7416         }
7417         spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7418
7419         if (first_add)
7420                 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7421 }
7422
7423 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7424 {
7425         struct io_rsrc_node *ref_node;
7426
7427         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7428         if (!ref_node)
7429                 return NULL;
7430
7431         if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7432                             0, GFP_KERNEL)) {
7433                 kfree(ref_node);
7434                 return NULL;
7435         }
7436         INIT_LIST_HEAD(&ref_node->node);
7437         INIT_LIST_HEAD(&ref_node->rsrc_list);
7438         ref_node->done = false;
7439         return ref_node;
7440 }
7441
7442 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7443                                 struct io_rsrc_data *data_to_kill)
7444 {
7445         WARN_ON_ONCE(!ctx->rsrc_backup_node);
7446         WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7447
7448         if (data_to_kill) {
7449                 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7450
7451                 rsrc_node->rsrc_data = data_to_kill;
7452                 spin_lock_irq(&ctx->rsrc_ref_lock);
7453                 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7454                 spin_unlock_irq(&ctx->rsrc_ref_lock);
7455
7456                 atomic_inc(&data_to_kill->refs);
7457                 percpu_ref_kill(&rsrc_node->refs);
7458                 ctx->rsrc_node = NULL;
7459         }
7460
7461         if (!ctx->rsrc_node) {
7462                 ctx->rsrc_node = ctx->rsrc_backup_node;
7463                 ctx->rsrc_backup_node = NULL;
7464         }
7465 }
7466
7467 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7468 {
7469         if (ctx->rsrc_backup_node)
7470                 return 0;
7471         ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7472         return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7473 }
7474
7475 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7476 {
7477         int ret;
7478
7479         /* As we may drop ->uring_lock, other task may have started quiesce */
7480         if (data->quiesce)
7481                 return -ENXIO;
7482
7483         data->quiesce = true;
7484         do {
7485                 ret = io_rsrc_node_switch_start(ctx);
7486                 if (ret)
7487                         break;
7488                 io_rsrc_node_switch(ctx, data);
7489
7490                 /* kill initial ref, already quiesced if zero */
7491                 if (atomic_dec_and_test(&data->refs))
7492                         break;
7493                 mutex_unlock(&ctx->uring_lock);
7494                 flush_delayed_work(&ctx->rsrc_put_work);
7495                 ret = wait_for_completion_interruptible(&data->done);
7496                 if (!ret) {
7497                         mutex_lock(&ctx->uring_lock);
7498                         break;
7499                 }
7500
7501                 atomic_inc(&data->refs);
7502                 /* wait for all works potentially completing data->done */
7503                 flush_delayed_work(&ctx->rsrc_put_work);
7504                 reinit_completion(&data->done);
7505
7506                 ret = io_run_task_work_sig();
7507                 mutex_lock(&ctx->uring_lock);
7508         } while (ret >= 0);
7509         data->quiesce = false;
7510
7511         return ret;
7512 }
7513
7514 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7515 {
7516         unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7517         unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7518
7519         return &data->tags[table_idx][off];
7520 }
7521
7522 static void io_rsrc_data_free(struct io_rsrc_data *data)
7523 {
7524         size_t size = data->nr * sizeof(data->tags[0][0]);
7525
7526         if (data->tags)
7527                 io_free_page_table((void **)data->tags, size);
7528         kfree(data);
7529 }
7530
7531 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7532                               u64 __user *utags, unsigned nr,
7533                               struct io_rsrc_data **pdata)
7534 {
7535         struct io_rsrc_data *data;
7536         int ret = -ENOMEM;
7537         unsigned i;
7538
7539         data = kzalloc(sizeof(*data), GFP_KERNEL);
7540         if (!data)
7541                 return -ENOMEM;
7542         data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7543         if (!data->tags) {
7544                 kfree(data);
7545                 return -ENOMEM;
7546         }
7547
7548         data->nr = nr;
7549         data->ctx = ctx;
7550         data->do_put = do_put;
7551         if (utags) {
7552                 ret = -EFAULT;
7553                 for (i = 0; i < nr; i++) {
7554                         u64 *tag_slot = io_get_tag_slot(data, i);
7555
7556                         if (copy_from_user(tag_slot, &utags[i],
7557                                            sizeof(*tag_slot)))
7558                                 goto fail;
7559                 }
7560         }
7561
7562         atomic_set(&data->refs, 1);
7563         init_completion(&data->done);
7564         *pdata = data;
7565         return 0;
7566 fail:
7567         io_rsrc_data_free(data);
7568         return ret;
7569 }
7570
7571 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7572 {
7573         table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7574                                 GFP_KERNEL_ACCOUNT);
7575         return !!table->files;
7576 }
7577
7578 static void io_free_file_tables(struct io_file_table *table)
7579 {
7580         kvfree(table->files);
7581         table->files = NULL;
7582 }
7583
7584 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7585 {
7586 #if defined(CONFIG_UNIX)
7587         if (ctx->ring_sock) {
7588                 struct sock *sock = ctx->ring_sock->sk;
7589                 struct sk_buff *skb;
7590
7591                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7592                         kfree_skb(skb);
7593         }
7594 #else
7595         int i;
7596
7597         for (i = 0; i < ctx->nr_user_files; i++) {
7598                 struct file *file;
7599
7600                 file = io_file_from_index(ctx, i);
7601                 if (file)
7602                         fput(file);
7603         }
7604 #endif
7605         io_free_file_tables(&ctx->file_table);
7606         io_rsrc_data_free(ctx->file_data);
7607         ctx->file_data = NULL;
7608         ctx->nr_user_files = 0;
7609 }
7610
7611 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7612 {
7613         int ret;
7614
7615         if (!ctx->file_data)
7616                 return -ENXIO;
7617         ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7618         if (!ret)
7619                 __io_sqe_files_unregister(ctx);
7620         return ret;
7621 }
7622
7623 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7624         __releases(&sqd->lock)
7625 {
7626         WARN_ON_ONCE(sqd->thread == current);
7627
7628         /*
7629          * Do the dance but not conditional clear_bit() because it'd race with
7630          * other threads incrementing park_pending and setting the bit.
7631          */
7632         clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7633         if (atomic_dec_return(&sqd->park_pending))
7634                 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7635         mutex_unlock(&sqd->lock);
7636 }
7637
7638 static void io_sq_thread_park(struct io_sq_data *sqd)
7639         __acquires(&sqd->lock)
7640 {
7641         WARN_ON_ONCE(sqd->thread == current);
7642
7643         atomic_inc(&sqd->park_pending);
7644         set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7645         mutex_lock(&sqd->lock);
7646         if (sqd->thread)
7647                 wake_up_process(sqd->thread);
7648 }
7649
7650 static void io_sq_thread_stop(struct io_sq_data *sqd)
7651 {
7652         WARN_ON_ONCE(sqd->thread == current);
7653         WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7654
7655         set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7656         mutex_lock(&sqd->lock);
7657         if (sqd->thread)
7658                 wake_up_process(sqd->thread);
7659         mutex_unlock(&sqd->lock);
7660         wait_for_completion(&sqd->exited);
7661 }
7662
7663 static void io_put_sq_data(struct io_sq_data *sqd)
7664 {
7665         if (refcount_dec_and_test(&sqd->refs)) {
7666                 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7667
7668                 io_sq_thread_stop(sqd);
7669                 kfree(sqd);
7670         }
7671 }
7672
7673 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7674 {
7675         struct io_sq_data *sqd = ctx->sq_data;
7676
7677         if (sqd) {
7678                 io_sq_thread_park(sqd);
7679                 list_del_init(&ctx->sqd_list);
7680                 io_sqd_update_thread_idle(sqd);
7681                 io_sq_thread_unpark(sqd);
7682
7683                 io_put_sq_data(sqd);
7684                 ctx->sq_data = NULL;
7685         }
7686 }
7687
7688 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7689 {
7690         struct io_ring_ctx *ctx_attach;
7691         struct io_sq_data *sqd;
7692         struct fd f;
7693
7694         f = fdget(p->wq_fd);
7695         if (!f.file)
7696                 return ERR_PTR(-ENXIO);
7697         if (f.file->f_op != &io_uring_fops) {
7698                 fdput(f);
7699                 return ERR_PTR(-EINVAL);
7700         }
7701
7702         ctx_attach = f.file->private_data;
7703         sqd = ctx_attach->sq_data;
7704         if (!sqd) {
7705                 fdput(f);
7706                 return ERR_PTR(-EINVAL);
7707         }
7708         if (sqd->task_tgid != current->tgid) {
7709                 fdput(f);
7710                 return ERR_PTR(-EPERM);
7711         }
7712
7713         refcount_inc(&sqd->refs);
7714         fdput(f);
7715         return sqd;
7716 }
7717
7718 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7719                                          bool *attached)
7720 {
7721         struct io_sq_data *sqd;
7722
7723         *attached = false;
7724         if (p->flags & IORING_SETUP_ATTACH_WQ) {
7725                 sqd = io_attach_sq_data(p);
7726                 if (!IS_ERR(sqd)) {
7727                         *attached = true;
7728                         return sqd;
7729                 }
7730                 /* fall through for EPERM case, setup new sqd/task */
7731                 if (PTR_ERR(sqd) != -EPERM)
7732                         return sqd;
7733         }
7734
7735         sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7736         if (!sqd)
7737                 return ERR_PTR(-ENOMEM);
7738
7739         atomic_set(&sqd->park_pending, 0);
7740         refcount_set(&sqd->refs, 1);
7741         INIT_LIST_HEAD(&sqd->ctx_list);
7742         mutex_init(&sqd->lock);
7743         init_waitqueue_head(&sqd->wait);
7744         init_completion(&sqd->exited);
7745         return sqd;
7746 }
7747
7748 #if defined(CONFIG_UNIX)
7749 /*
7750  * Ensure the UNIX gc is aware of our file set, so we are certain that
7751  * the io_uring can be safely unregistered on process exit, even if we have
7752  * loops in the file referencing.
7753  */
7754 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7755 {
7756         struct sock *sk = ctx->ring_sock->sk;
7757         struct scm_fp_list *fpl;
7758         struct sk_buff *skb;
7759         int i, nr_files;
7760
7761         fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7762         if (!fpl)
7763                 return -ENOMEM;
7764
7765         skb = alloc_skb(0, GFP_KERNEL);
7766         if (!skb) {
7767                 kfree(fpl);
7768                 return -ENOMEM;
7769         }
7770
7771         skb->sk = sk;
7772
7773         nr_files = 0;
7774         fpl->user = get_uid(current_user());
7775         for (i = 0; i < nr; i++) {
7776                 struct file *file = io_file_from_index(ctx, i + offset);
7777
7778                 if (!file)
7779                         continue;
7780                 fpl->fp[nr_files] = get_file(file);
7781                 unix_inflight(fpl->user, fpl->fp[nr_files]);
7782                 nr_files++;
7783         }
7784
7785         if (nr_files) {
7786                 fpl->max = SCM_MAX_FD;
7787                 fpl->count = nr_files;
7788                 UNIXCB(skb).fp = fpl;
7789                 skb->destructor = unix_destruct_scm;
7790                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7791                 skb_queue_head(&sk->sk_receive_queue, skb);
7792
7793                 for (i = 0; i < nr_files; i++)
7794                         fput(fpl->fp[i]);
7795         } else {
7796                 kfree_skb(skb);
7797                 kfree(fpl);
7798         }
7799
7800         return 0;
7801 }
7802
7803 /*
7804  * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7805  * causes regular reference counting to break down. We rely on the UNIX
7806  * garbage collection to take care of this problem for us.
7807  */
7808 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7809 {
7810         unsigned left, total;
7811         int ret = 0;
7812
7813         total = 0;
7814         left = ctx->nr_user_files;
7815         while (left) {
7816                 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7817
7818                 ret = __io_sqe_files_scm(ctx, this_files, total);
7819                 if (ret)
7820                         break;
7821                 left -= this_files;
7822                 total += this_files;
7823         }
7824
7825         if (!ret)
7826                 return 0;
7827
7828         while (total < ctx->nr_user_files) {
7829                 struct file *file = io_file_from_index(ctx, total);
7830
7831                 if (file)
7832                         fput(file);
7833                 total++;
7834         }
7835
7836         return ret;
7837 }
7838 #else
7839 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7840 {
7841         return 0;
7842 }
7843 #endif
7844
7845 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7846 {
7847         struct file *file = prsrc->file;
7848 #if defined(CONFIG_UNIX)
7849         struct sock *sock = ctx->ring_sock->sk;
7850         struct sk_buff_head list, *head = &sock->sk_receive_queue;
7851         struct sk_buff *skb;
7852         int i;
7853
7854         __skb_queue_head_init(&list);
7855
7856         /*
7857          * Find the skb that holds this file in its SCM_RIGHTS. When found,
7858          * remove this entry and rearrange the file array.
7859          */
7860         skb = skb_dequeue(head);
7861         while (skb) {
7862                 struct scm_fp_list *fp;
7863
7864                 fp = UNIXCB(skb).fp;
7865                 for (i = 0; i < fp->count; i++) {
7866                         int left;
7867
7868                         if (fp->fp[i] != file)
7869                                 continue;
7870
7871                         unix_notinflight(fp->user, fp->fp[i]);
7872                         left = fp->count - 1 - i;
7873                         if (left) {
7874                                 memmove(&fp->fp[i], &fp->fp[i + 1],
7875                                                 left * sizeof(struct file *));
7876                         }
7877                         fp->count--;
7878                         if (!fp->count) {
7879                                 kfree_skb(skb);
7880                                 skb = NULL;
7881                         } else {
7882                                 __skb_queue_tail(&list, skb);
7883                         }
7884                         fput(file);
7885                         file = NULL;
7886                         break;
7887                 }
7888
7889                 if (!file)
7890                         break;
7891
7892                 __skb_queue_tail(&list, skb);
7893
7894                 skb = skb_dequeue(head);
7895         }
7896
7897         if (skb_peek(&list)) {
7898                 spin_lock_irq(&head->lock);
7899                 while ((skb = __skb_dequeue(&list)) != NULL)
7900                         __skb_queue_tail(head, skb);
7901                 spin_unlock_irq(&head->lock);
7902         }
7903 #else
7904         fput(file);
7905 #endif
7906 }
7907
7908 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7909 {
7910         struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7911         struct io_ring_ctx *ctx = rsrc_data->ctx;
7912         struct io_rsrc_put *prsrc, *tmp;
7913
7914         list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7915                 list_del(&prsrc->list);
7916
7917                 if (prsrc->tag) {
7918                         bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7919
7920                         io_ring_submit_lock(ctx, lock_ring);
7921                         spin_lock(&ctx->completion_lock);
7922                         io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7923                         ctx->cq_extra++;
7924                         io_commit_cqring(ctx);
7925                         spin_unlock(&ctx->completion_lock);
7926                         io_cqring_ev_posted(ctx);
7927                         io_ring_submit_unlock(ctx, lock_ring);
7928                 }
7929
7930                 rsrc_data->do_put(ctx, prsrc);
7931                 kfree(prsrc);
7932         }
7933
7934         io_rsrc_node_destroy(ref_node);
7935         if (atomic_dec_and_test(&rsrc_data->refs))
7936                 complete(&rsrc_data->done);
7937 }
7938
7939 static void io_rsrc_put_work(struct work_struct *work)
7940 {
7941         struct io_ring_ctx *ctx;
7942         struct llist_node *node;
7943
7944         ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7945         node = llist_del_all(&ctx->rsrc_put_llist);
7946
7947         while (node) {
7948                 struct io_rsrc_node *ref_node;
7949                 struct llist_node *next = node->next;
7950
7951                 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7952                 __io_rsrc_put_work(ref_node);
7953                 node = next;
7954         }
7955 }
7956
7957 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7958                                  unsigned nr_args, u64 __user *tags)
7959 {
7960         __s32 __user *fds = (__s32 __user *) arg;
7961         struct file *file;
7962         int fd, ret;
7963         unsigned i;
7964
7965         if (ctx->file_data)
7966                 return -EBUSY;
7967         if (!nr_args)
7968                 return -EINVAL;
7969         if (nr_args > IORING_MAX_FIXED_FILES)
7970                 return -EMFILE;
7971         if (nr_args > rlimit(RLIMIT_NOFILE))
7972                 return -EMFILE;
7973         ret = io_rsrc_node_switch_start(ctx);
7974         if (ret)
7975                 return ret;
7976         ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7977                                  &ctx->file_data);
7978         if (ret)
7979                 return ret;
7980
7981         ret = -ENOMEM;
7982         if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7983                 goto out_free;
7984
7985         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7986                 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7987                         ret = -EFAULT;
7988                         goto out_fput;
7989                 }
7990                 /* allow sparse sets */
7991                 if (fd == -1) {
7992                         ret = -EINVAL;
7993                         if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7994                                 goto out_fput;
7995                         continue;
7996                 }
7997
7998                 file = fget(fd);
7999                 ret = -EBADF;
8000                 if (unlikely(!file))
8001                         goto out_fput;
8002
8003                 /*
8004                  * Don't allow io_uring instances to be registered. If UNIX
8005                  * isn't enabled, then this causes a reference cycle and this
8006                  * instance can never get freed. If UNIX is enabled we'll
8007                  * handle it just fine, but there's still no point in allowing
8008                  * a ring fd as it doesn't support regular read/write anyway.
8009                  */
8010                 if (file->f_op == &io_uring_fops) {
8011                         fput(file);
8012                         goto out_fput;
8013                 }
8014                 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8015         }
8016
8017         ret = io_sqe_files_scm(ctx);
8018         if (ret) {
8019                 __io_sqe_files_unregister(ctx);
8020                 return ret;
8021         }
8022
8023         io_rsrc_node_switch(ctx, NULL);
8024         return ret;
8025 out_fput:
8026         for (i = 0; i < ctx->nr_user_files; i++) {
8027                 file = io_file_from_index(ctx, i);
8028                 if (file)
8029                         fput(file);
8030         }
8031         io_free_file_tables(&ctx->file_table);
8032         ctx->nr_user_files = 0;
8033 out_free:
8034         io_rsrc_data_free(ctx->file_data);
8035         ctx->file_data = NULL;
8036         return ret;
8037 }
8038
8039 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8040                                 int index)
8041 {
8042 #if defined(CONFIG_UNIX)
8043         struct sock *sock = ctx->ring_sock->sk;
8044         struct sk_buff_head *head = &sock->sk_receive_queue;
8045         struct sk_buff *skb;
8046
8047         /*
8048          * See if we can merge this file into an existing skb SCM_RIGHTS
8049          * file set. If there's no room, fall back to allocating a new skb
8050          * and filling it in.
8051          */
8052         spin_lock_irq(&head->lock);
8053         skb = skb_peek(head);
8054         if (skb) {
8055                 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8056
8057                 if (fpl->count < SCM_MAX_FD) {
8058                         __skb_unlink(skb, head);
8059                         spin_unlock_irq(&head->lock);
8060                         fpl->fp[fpl->count] = get_file(file);
8061                         unix_inflight(fpl->user, fpl->fp[fpl->count]);
8062                         fpl->count++;
8063                         spin_lock_irq(&head->lock);
8064                         __skb_queue_head(head, skb);
8065                 } else {
8066                         skb = NULL;
8067                 }
8068         }
8069         spin_unlock_irq(&head->lock);
8070
8071         if (skb) {
8072                 fput(file);
8073                 return 0;
8074         }
8075
8076         return __io_sqe_files_scm(ctx, 1, index);
8077 #else
8078         return 0;
8079 #endif
8080 }
8081
8082 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8083                                  unsigned int issue_flags, u32 slot_index)
8084 {
8085         struct io_ring_ctx *ctx = req->ctx;
8086         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8087         struct io_fixed_file *file_slot;
8088         int ret = -EBADF;
8089
8090         io_ring_submit_lock(ctx, !force_nonblock);
8091         if (file->f_op == &io_uring_fops)
8092                 goto err;
8093         ret = -ENXIO;
8094         if (!ctx->file_data)
8095                 goto err;
8096         ret = -EINVAL;
8097         if (slot_index >= ctx->nr_user_files)
8098                 goto err;
8099
8100         slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8101         file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8102         ret = -EBADF;
8103         if (file_slot->file_ptr)
8104                 goto err;
8105
8106         *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8107         io_fixed_file_set(file_slot, file);
8108         ret = io_sqe_file_register(ctx, file, slot_index);
8109         if (ret) {
8110                 file_slot->file_ptr = 0;
8111                 goto err;
8112         }
8113
8114         ret = 0;
8115 err:
8116         io_ring_submit_unlock(ctx, !force_nonblock);
8117         if (ret)
8118                 fput(file);
8119         return ret;
8120 }
8121
8122 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8123                                  struct io_rsrc_node *node, void *rsrc)
8124 {
8125         struct io_rsrc_put *prsrc;
8126
8127         prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8128         if (!prsrc)
8129                 return -ENOMEM;
8130
8131         prsrc->tag = *io_get_tag_slot(data, idx);
8132         prsrc->rsrc = rsrc;
8133         list_add(&prsrc->list, &node->rsrc_list);
8134         return 0;
8135 }
8136
8137 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8138                                  struct io_uring_rsrc_update2 *up,
8139                                  unsigned nr_args)
8140 {
8141         u64 __user *tags = u64_to_user_ptr(up->tags);
8142         __s32 __user *fds = u64_to_user_ptr(up->data);
8143         struct io_rsrc_data *data = ctx->file_data;
8144         struct io_fixed_file *file_slot;
8145         struct file *file;
8146         int fd, i, err = 0;
8147         unsigned int done;
8148         bool needs_switch = false;
8149
8150         if (!ctx->file_data)
8151                 return -ENXIO;
8152         if (up->offset + nr_args > ctx->nr_user_files)
8153                 return -EINVAL;
8154
8155         for (done = 0; done < nr_args; done++) {
8156                 u64 tag = 0;
8157
8158                 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8159                     copy_from_user(&fd, &fds[done], sizeof(fd))) {
8160                         err = -EFAULT;
8161                         break;
8162                 }
8163                 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8164                         err = -EINVAL;
8165                         break;
8166                 }
8167                 if (fd == IORING_REGISTER_FILES_SKIP)
8168                         continue;
8169
8170                 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8171                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8172
8173                 if (file_slot->file_ptr) {
8174                         file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8175                         err = io_queue_rsrc_removal(data, up->offset + done,
8176                                                     ctx->rsrc_node, file);
8177                         if (err)
8178                                 break;
8179                         file_slot->file_ptr = 0;
8180                         needs_switch = true;
8181                 }
8182                 if (fd != -1) {
8183                         file = fget(fd);
8184                         if (!file) {
8185                                 err = -EBADF;
8186                                 break;
8187                         }
8188                         /*
8189                          * Don't allow io_uring instances to be registered. If
8190                          * UNIX isn't enabled, then this causes a reference
8191                          * cycle and this instance can never get freed. If UNIX
8192                          * is enabled we'll handle it just fine, but there's
8193                          * still no point in allowing a ring fd as it doesn't
8194                          * support regular read/write anyway.
8195                          */
8196                         if (file->f_op == &io_uring_fops) {
8197                                 fput(file);
8198                                 err = -EBADF;
8199                                 break;
8200                         }
8201                         *io_get_tag_slot(data, up->offset + done) = tag;
8202                         io_fixed_file_set(file_slot, file);
8203                         err = io_sqe_file_register(ctx, file, i);
8204                         if (err) {
8205                                 file_slot->file_ptr = 0;
8206                                 fput(file);
8207                                 break;
8208                         }
8209                 }
8210         }
8211
8212         if (needs_switch)
8213                 io_rsrc_node_switch(ctx, data);
8214         return done ? done : err;
8215 }
8216
8217 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8218                                         struct task_struct *task)
8219 {
8220         struct io_wq_hash *hash;
8221         struct io_wq_data data;
8222         unsigned int concurrency;
8223
8224         mutex_lock(&ctx->uring_lock);
8225         hash = ctx->hash_map;
8226         if (!hash) {
8227                 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8228                 if (!hash) {
8229                         mutex_unlock(&ctx->uring_lock);
8230                         return ERR_PTR(-ENOMEM);
8231                 }
8232                 refcount_set(&hash->refs, 1);
8233                 init_waitqueue_head(&hash->wait);
8234                 ctx->hash_map = hash;
8235         }
8236         mutex_unlock(&ctx->uring_lock);
8237
8238         data.hash = hash;
8239         data.task = task;
8240         data.free_work = io_wq_free_work;
8241         data.do_work = io_wq_submit_work;
8242
8243         /* Do QD, or 4 * CPUS, whatever is smallest */
8244         concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8245
8246         return io_wq_create(concurrency, &data);
8247 }
8248
8249 static int io_uring_alloc_task_context(struct task_struct *task,
8250                                        struct io_ring_ctx *ctx)
8251 {
8252         struct io_uring_task *tctx;
8253         int ret;
8254
8255         tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8256         if (unlikely(!tctx))
8257                 return -ENOMEM;
8258
8259         ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8260         if (unlikely(ret)) {
8261                 kfree(tctx);
8262                 return ret;
8263         }
8264
8265         tctx->io_wq = io_init_wq_offload(ctx, task);
8266         if (IS_ERR(tctx->io_wq)) {
8267                 ret = PTR_ERR(tctx->io_wq);
8268                 percpu_counter_destroy(&tctx->inflight);
8269                 kfree(tctx);
8270                 return ret;
8271         }
8272
8273         xa_init(&tctx->xa);
8274         init_waitqueue_head(&tctx->wait);
8275         atomic_set(&tctx->in_idle, 0);
8276         atomic_set(&tctx->inflight_tracked, 0);
8277         task->io_uring = tctx;
8278         spin_lock_init(&tctx->task_lock);
8279         INIT_WQ_LIST(&tctx->task_list);
8280         init_task_work(&tctx->task_work, tctx_task_work);
8281         return 0;
8282 }
8283
8284 void __io_uring_free(struct task_struct *tsk)
8285 {
8286         struct io_uring_task *tctx = tsk->io_uring;
8287
8288         WARN_ON_ONCE(!xa_empty(&tctx->xa));
8289         WARN_ON_ONCE(tctx->io_wq);
8290         WARN_ON_ONCE(tctx->cached_refs);
8291
8292         percpu_counter_destroy(&tctx->inflight);
8293         kfree(tctx);
8294         tsk->io_uring = NULL;
8295 }
8296
8297 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8298                                 struct io_uring_params *p)
8299 {
8300         int ret;
8301
8302         /* Retain compatibility with failing for an invalid attach attempt */
8303         if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8304                                 IORING_SETUP_ATTACH_WQ) {
8305                 struct fd f;
8306
8307                 f = fdget(p->wq_fd);
8308                 if (!f.file)
8309                         return -ENXIO;
8310                 if (f.file->f_op != &io_uring_fops) {
8311                         fdput(f);
8312                         return -EINVAL;
8313                 }
8314                 fdput(f);
8315         }
8316         if (ctx->flags & IORING_SETUP_SQPOLL) {
8317                 struct task_struct *tsk;
8318                 struct io_sq_data *sqd;
8319                 bool attached;
8320
8321                 sqd = io_get_sq_data(p, &attached);
8322                 if (IS_ERR(sqd)) {
8323                         ret = PTR_ERR(sqd);
8324                         goto err;
8325                 }
8326
8327                 ctx->sq_creds = get_current_cred();
8328                 ctx->sq_data = sqd;
8329                 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8330                 if (!ctx->sq_thread_idle)
8331                         ctx->sq_thread_idle = HZ;
8332
8333                 io_sq_thread_park(sqd);
8334                 list_add(&ctx->sqd_list, &sqd->ctx_list);
8335                 io_sqd_update_thread_idle(sqd);
8336                 /* don't attach to a dying SQPOLL thread, would be racy */
8337                 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8338                 io_sq_thread_unpark(sqd);
8339
8340                 if (ret < 0)
8341                         goto err;
8342                 if (attached)
8343                         return 0;
8344
8345                 if (p->flags & IORING_SETUP_SQ_AFF) {
8346                         int cpu = p->sq_thread_cpu;
8347
8348                         ret = -EINVAL;
8349                         if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8350                                 goto err_sqpoll;
8351                         sqd->sq_cpu = cpu;
8352                 } else {
8353                         sqd->sq_cpu = -1;
8354                 }
8355
8356                 sqd->task_pid = current->pid;
8357                 sqd->task_tgid = current->tgid;
8358                 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8359                 if (IS_ERR(tsk)) {
8360                         ret = PTR_ERR(tsk);
8361                         goto err_sqpoll;
8362                 }
8363
8364                 sqd->thread = tsk;
8365                 ret = io_uring_alloc_task_context(tsk, ctx);
8366                 wake_up_new_task(tsk);
8367                 if (ret)
8368                         goto err;
8369         } else if (p->flags & IORING_SETUP_SQ_AFF) {
8370                 /* Can't have SQ_AFF without SQPOLL */
8371                 ret = -EINVAL;
8372                 goto err;
8373         }
8374
8375         return 0;
8376 err_sqpoll:
8377         complete(&ctx->sq_data->exited);
8378 err:
8379         io_sq_thread_finish(ctx);
8380         return ret;
8381 }
8382
8383 static inline void __io_unaccount_mem(struct user_struct *user,
8384                                       unsigned long nr_pages)
8385 {
8386         atomic_long_sub(nr_pages, &user->locked_vm);
8387 }
8388
8389 static inline int __io_account_mem(struct user_struct *user,
8390                                    unsigned long nr_pages)
8391 {
8392         unsigned long page_limit, cur_pages, new_pages;
8393
8394         /* Don't allow more pages than we can safely lock */
8395         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8396
8397         do {
8398                 cur_pages = atomic_long_read(&user->locked_vm);
8399                 new_pages = cur_pages + nr_pages;
8400                 if (new_pages > page_limit)
8401                         return -ENOMEM;
8402         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8403                                         new_pages) != cur_pages);
8404
8405         return 0;
8406 }
8407
8408 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8409 {
8410         if (ctx->user)
8411                 __io_unaccount_mem(ctx->user, nr_pages);
8412
8413         if (ctx->mm_account)
8414                 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8415 }
8416
8417 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8418 {
8419         int ret;
8420
8421         if (ctx->user) {
8422                 ret = __io_account_mem(ctx->user, nr_pages);
8423                 if (ret)
8424                         return ret;
8425         }
8426
8427         if (ctx->mm_account)
8428                 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8429
8430         return 0;
8431 }
8432
8433 static void io_mem_free(void *ptr)
8434 {
8435         struct page *page;
8436
8437         if (!ptr)
8438                 return;
8439
8440         page = virt_to_head_page(ptr);
8441         if (put_page_testzero(page))
8442                 free_compound_page(page);
8443 }
8444
8445 static void *io_mem_alloc(size_t size)
8446 {
8447         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8448                                 __GFP_NORETRY | __GFP_ACCOUNT;
8449
8450         return (void *) __get_free_pages(gfp_flags, get_order(size));
8451 }
8452
8453 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8454                                 size_t *sq_offset)
8455 {
8456         struct io_rings *rings;
8457         size_t off, sq_array_size;
8458
8459         off = struct_size(rings, cqes, cq_entries);
8460         if (off == SIZE_MAX)
8461                 return SIZE_MAX;
8462
8463 #ifdef CONFIG_SMP
8464         off = ALIGN(off, SMP_CACHE_BYTES);
8465         if (off == 0)
8466                 return SIZE_MAX;
8467 #endif
8468
8469         if (sq_offset)
8470                 *sq_offset = off;
8471
8472         sq_array_size = array_size(sizeof(u32), sq_entries);
8473         if (sq_array_size == SIZE_MAX)
8474                 return SIZE_MAX;
8475
8476         if (check_add_overflow(off, sq_array_size, &off))
8477                 return SIZE_MAX;
8478
8479         return off;
8480 }
8481
8482 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8483 {
8484         struct io_mapped_ubuf *imu = *slot;
8485         unsigned int i;
8486
8487         if (imu != ctx->dummy_ubuf) {
8488                 for (i = 0; i < imu->nr_bvecs; i++)
8489                         unpin_user_page(imu->bvec[i].bv_page);
8490                 if (imu->acct_pages)
8491                         io_unaccount_mem(ctx, imu->acct_pages);
8492                 kvfree(imu);
8493         }
8494         *slot = NULL;
8495 }
8496
8497 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8498 {
8499         io_buffer_unmap(ctx, &prsrc->buf);
8500         prsrc->buf = NULL;
8501 }
8502
8503 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8504 {
8505         unsigned int i;
8506
8507         for (i = 0; i < ctx->nr_user_bufs; i++)
8508                 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8509         kfree(ctx->user_bufs);
8510         io_rsrc_data_free(ctx->buf_data);
8511         ctx->user_bufs = NULL;
8512         ctx->buf_data = NULL;
8513         ctx->nr_user_bufs = 0;
8514 }
8515
8516 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8517 {
8518         int ret;
8519
8520         if (!ctx->buf_data)
8521                 return -ENXIO;
8522
8523         ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8524         if (!ret)
8525                 __io_sqe_buffers_unregister(ctx);
8526         return ret;
8527 }
8528
8529 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8530                        void __user *arg, unsigned index)
8531 {
8532         struct iovec __user *src;
8533
8534 #ifdef CONFIG_COMPAT
8535         if (ctx->compat) {
8536                 struct compat_iovec __user *ciovs;
8537                 struct compat_iovec ciov;
8538
8539                 ciovs = (struct compat_iovec __user *) arg;
8540                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8541                         return -EFAULT;
8542
8543                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8544                 dst->iov_len = ciov.iov_len;
8545                 return 0;
8546         }
8547 #endif
8548         src = (struct iovec __user *) arg;
8549         if (copy_from_user(dst, &src[index], sizeof(*dst)))
8550                 return -EFAULT;
8551         return 0;
8552 }
8553
8554 /*
8555  * Not super efficient, but this is just a registration time. And we do cache
8556  * the last compound head, so generally we'll only do a full search if we don't
8557  * match that one.
8558  *
8559  * We check if the given compound head page has already been accounted, to
8560  * avoid double accounting it. This allows us to account the full size of the
8561  * page, not just the constituent pages of a huge page.
8562  */
8563 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8564                                   int nr_pages, struct page *hpage)
8565 {
8566         int i, j;
8567
8568         /* check current page array */
8569         for (i = 0; i < nr_pages; i++) {
8570                 if (!PageCompound(pages[i]))
8571                         continue;
8572                 if (compound_head(pages[i]) == hpage)
8573                         return true;
8574         }
8575
8576         /* check previously registered pages */
8577         for (i = 0; i < ctx->nr_user_bufs; i++) {
8578                 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8579
8580                 for (j = 0; j < imu->nr_bvecs; j++) {
8581                         if (!PageCompound(imu->bvec[j].bv_page))
8582                                 continue;
8583                         if (compound_head(imu->bvec[j].bv_page) == hpage)
8584                                 return true;
8585                 }
8586         }
8587
8588         return false;
8589 }
8590
8591 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8592                                  int nr_pages, struct io_mapped_ubuf *imu,
8593                                  struct page **last_hpage)
8594 {
8595         int i, ret;
8596
8597         imu->acct_pages = 0;
8598         for (i = 0; i < nr_pages; i++) {
8599                 if (!PageCompound(pages[i])) {
8600                         imu->acct_pages++;
8601                 } else {
8602                         struct page *hpage;
8603
8604                         hpage = compound_head(pages[i]);
8605                         if (hpage == *last_hpage)
8606                                 continue;
8607                         *last_hpage = hpage;
8608                         if (headpage_already_acct(ctx, pages, i, hpage))
8609                                 continue;
8610                         imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8611                 }
8612         }
8613
8614         if (!imu->acct_pages)
8615                 return 0;
8616
8617         ret = io_account_mem(ctx, imu->acct_pages);
8618         if (ret)
8619                 imu->acct_pages = 0;
8620         return ret;
8621 }
8622
8623 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8624                                   struct io_mapped_ubuf **pimu,
8625                                   struct page **last_hpage)
8626 {
8627         struct io_mapped_ubuf *imu = NULL;
8628         struct vm_area_struct **vmas = NULL;
8629         struct page **pages = NULL;
8630         unsigned long off, start, end, ubuf;
8631         size_t size;
8632         int ret, pret, nr_pages, i;
8633
8634         if (!iov->iov_base) {
8635                 *pimu = ctx->dummy_ubuf;
8636                 return 0;
8637         }
8638
8639         ubuf = (unsigned long) iov->iov_base;
8640         end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8641         start = ubuf >> PAGE_SHIFT;
8642         nr_pages = end - start;
8643
8644         *pimu = NULL;
8645         ret = -ENOMEM;
8646
8647         pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8648         if (!pages)
8649                 goto done;
8650
8651         vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8652                               GFP_KERNEL);
8653         if (!vmas)
8654                 goto done;
8655
8656         imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8657         if (!imu)
8658                 goto done;
8659
8660         ret = 0;
8661         mmap_read_lock(current->mm);
8662         pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8663                               pages, vmas);
8664         if (pret == nr_pages) {
8665                 /* don't support file backed memory */
8666                 for (i = 0; i < nr_pages; i++) {
8667                         struct vm_area_struct *vma = vmas[i];
8668
8669                         if (vma_is_shmem(vma))
8670                                 continue;
8671                         if (vma->vm_file &&
8672                             !is_file_hugepages(vma->vm_file)) {
8673                                 ret = -EOPNOTSUPP;
8674                                 break;
8675                         }
8676                 }
8677         } else {
8678                 ret = pret < 0 ? pret : -EFAULT;
8679         }
8680         mmap_read_unlock(current->mm);
8681         if (ret) {
8682                 /*
8683                  * if we did partial map, or found file backed vmas,
8684                  * release any pages we did get
8685                  */
8686                 if (pret > 0)
8687                         unpin_user_pages(pages, pret);
8688                 goto done;
8689         }
8690
8691         ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8692         if (ret) {
8693                 unpin_user_pages(pages, pret);
8694                 goto done;
8695         }
8696
8697         off = ubuf & ~PAGE_MASK;
8698         size = iov->iov_len;
8699         for (i = 0; i < nr_pages; i++) {
8700                 size_t vec_len;
8701
8702                 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8703                 imu->bvec[i].bv_page = pages[i];
8704                 imu->bvec[i].bv_len = vec_len;
8705                 imu->bvec[i].bv_offset = off;
8706                 off = 0;
8707                 size -= vec_len;
8708         }
8709         /* store original address for later verification */
8710         imu->ubuf = ubuf;
8711         imu->ubuf_end = ubuf + iov->iov_len;
8712         imu->nr_bvecs = nr_pages;
8713         *pimu = imu;
8714         ret = 0;
8715 done:
8716         if (ret)
8717                 kvfree(imu);
8718         kvfree(pages);
8719         kvfree(vmas);
8720         return ret;
8721 }
8722
8723 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8724 {
8725         ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8726         return ctx->user_bufs ? 0 : -ENOMEM;
8727 }
8728
8729 static int io_buffer_validate(struct iovec *iov)
8730 {
8731         unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8732
8733         /*
8734          * Don't impose further limits on the size and buffer
8735          * constraints here, we'll -EINVAL later when IO is
8736          * submitted if they are wrong.
8737          */
8738         if (!iov->iov_base)
8739                 return iov->iov_len ? -EFAULT : 0;
8740         if (!iov->iov_len)
8741                 return -EFAULT;
8742
8743         /* arbitrary limit, but we need something */
8744         if (iov->iov_len > SZ_1G)
8745                 return -EFAULT;
8746
8747         if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8748                 return -EOVERFLOW;
8749
8750         return 0;
8751 }
8752
8753 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8754                                    unsigned int nr_args, u64 __user *tags)
8755 {
8756         struct page *last_hpage = NULL;
8757         struct io_rsrc_data *data;
8758         int i, ret;
8759         struct iovec iov;
8760
8761         if (ctx->user_bufs)
8762                 return -EBUSY;
8763         if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8764                 return -EINVAL;
8765         ret = io_rsrc_node_switch_start(ctx);
8766         if (ret)
8767                 return ret;
8768         ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8769         if (ret)
8770                 return ret;
8771         ret = io_buffers_map_alloc(ctx, nr_args);
8772         if (ret) {
8773                 io_rsrc_data_free(data);
8774                 return ret;
8775         }
8776
8777         for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8778                 ret = io_copy_iov(ctx, &iov, arg, i);
8779                 if (ret)
8780                         break;
8781                 ret = io_buffer_validate(&iov);
8782                 if (ret)
8783                         break;
8784                 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8785                         ret = -EINVAL;
8786                         break;
8787                 }
8788
8789                 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8790                                              &last_hpage);
8791                 if (ret)
8792                         break;
8793         }
8794
8795         WARN_ON_ONCE(ctx->buf_data);
8796
8797         ctx->buf_data = data;
8798         if (ret)
8799                 __io_sqe_buffers_unregister(ctx);
8800         else
8801                 io_rsrc_node_switch(ctx, NULL);
8802         return ret;
8803 }
8804
8805 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8806                                    struct io_uring_rsrc_update2 *up,
8807                                    unsigned int nr_args)
8808 {
8809         u64 __user *tags = u64_to_user_ptr(up->tags);
8810         struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8811         struct page *last_hpage = NULL;
8812         bool needs_switch = false;
8813         __u32 done;
8814         int i, err;
8815
8816         if (!ctx->buf_data)
8817                 return -ENXIO;
8818         if (up->offset + nr_args > ctx->nr_user_bufs)
8819                 return -EINVAL;
8820
8821         for (done = 0; done < nr_args; done++) {
8822                 struct io_mapped_ubuf *imu;
8823                 int offset = up->offset + done;
8824                 u64 tag = 0;
8825
8826                 err = io_copy_iov(ctx, &iov, iovs, done);
8827                 if (err)
8828                         break;
8829                 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8830                         err = -EFAULT;
8831                         break;
8832                 }
8833                 err = io_buffer_validate(&iov);
8834                 if (err)
8835                         break;
8836                 if (!iov.iov_base && tag) {
8837                         err = -EINVAL;
8838                         break;
8839                 }
8840                 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8841                 if (err)
8842                         break;
8843
8844                 i = array_index_nospec(offset, ctx->nr_user_bufs);
8845                 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8846                         err = io_queue_rsrc_removal(ctx->buf_data, offset,
8847                                                     ctx->rsrc_node, ctx->user_bufs[i]);
8848                         if (unlikely(err)) {
8849                                 io_buffer_unmap(ctx, &imu);
8850                                 break;
8851                         }
8852                         ctx->user_bufs[i] = NULL;
8853                         needs_switch = true;
8854                 }
8855
8856                 ctx->user_bufs[i] = imu;
8857                 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8858         }
8859
8860         if (needs_switch)
8861                 io_rsrc_node_switch(ctx, ctx->buf_data);
8862         return done ? done : err;
8863 }
8864
8865 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8866 {
8867         __s32 __user *fds = arg;
8868         int fd;
8869
8870         if (ctx->cq_ev_fd)
8871                 return -EBUSY;
8872
8873         if (copy_from_user(&fd, fds, sizeof(*fds)))
8874                 return -EFAULT;
8875
8876         ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8877         if (IS_ERR(ctx->cq_ev_fd)) {
8878                 int ret = PTR_ERR(ctx->cq_ev_fd);
8879
8880                 ctx->cq_ev_fd = NULL;
8881                 return ret;
8882         }
8883
8884         return 0;
8885 }
8886
8887 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8888 {
8889         if (ctx->cq_ev_fd) {
8890                 eventfd_ctx_put(ctx->cq_ev_fd);
8891                 ctx->cq_ev_fd = NULL;
8892                 return 0;
8893         }
8894
8895         return -ENXIO;
8896 }
8897
8898 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8899 {
8900         struct io_buffer *buf;
8901         unsigned long index;
8902
8903         xa_for_each(&ctx->io_buffers, index, buf)
8904                 __io_remove_buffers(ctx, buf, index, -1U);
8905 }
8906
8907 static void io_req_cache_free(struct list_head *list)
8908 {
8909         struct io_kiocb *req, *nxt;
8910
8911         list_for_each_entry_safe(req, nxt, list, inflight_entry) {
8912                 list_del(&req->inflight_entry);
8913                 kmem_cache_free(req_cachep, req);
8914         }
8915 }
8916
8917 static void io_req_caches_free(struct io_ring_ctx *ctx)
8918 {
8919         struct io_submit_state *state = &ctx->submit_state;
8920
8921         mutex_lock(&ctx->uring_lock);
8922
8923         if (state->free_reqs) {
8924                 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
8925                 state->free_reqs = 0;
8926         }
8927
8928         io_flush_cached_locked_reqs(ctx, state);
8929         io_req_cache_free(&state->free_list);
8930         mutex_unlock(&ctx->uring_lock);
8931 }
8932
8933 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8934 {
8935         if (data && !atomic_dec_and_test(&data->refs))
8936                 wait_for_completion(&data->done);
8937 }
8938
8939 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8940 {
8941         io_sq_thread_finish(ctx);
8942
8943         if (ctx->mm_account) {
8944                 mmdrop(ctx->mm_account);
8945                 ctx->mm_account = NULL;
8946         }
8947
8948         /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8949         io_wait_rsrc_data(ctx->buf_data);
8950         io_wait_rsrc_data(ctx->file_data);
8951
8952         mutex_lock(&ctx->uring_lock);
8953         if (ctx->buf_data)
8954                 __io_sqe_buffers_unregister(ctx);
8955         if (ctx->file_data)
8956                 __io_sqe_files_unregister(ctx);
8957         if (ctx->rings)
8958                 __io_cqring_overflow_flush(ctx, true);
8959         mutex_unlock(&ctx->uring_lock);
8960         io_eventfd_unregister(ctx);
8961         io_destroy_buffers(ctx);
8962         if (ctx->sq_creds)
8963                 put_cred(ctx->sq_creds);
8964
8965         /* there are no registered resources left, nobody uses it */
8966         if (ctx->rsrc_node)
8967                 io_rsrc_node_destroy(ctx->rsrc_node);
8968         if (ctx->rsrc_backup_node)
8969                 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8970         flush_delayed_work(&ctx->rsrc_put_work);
8971
8972         WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8973         WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8974
8975 #if defined(CONFIG_UNIX)
8976         if (ctx->ring_sock) {
8977                 ctx->ring_sock->file = NULL; /* so that iput() is called */
8978                 sock_release(ctx->ring_sock);
8979         }
8980 #endif
8981         WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
8982
8983         io_mem_free(ctx->rings);
8984         io_mem_free(ctx->sq_sqes);
8985
8986         percpu_ref_exit(&ctx->refs);
8987         free_uid(ctx->user);
8988         io_req_caches_free(ctx);
8989         if (ctx->hash_map)
8990                 io_wq_put_hash(ctx->hash_map);
8991         kfree(ctx->cancel_hash);
8992         kfree(ctx->dummy_ubuf);
8993         kfree(ctx);
8994 }
8995
8996 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8997 {
8998         struct io_ring_ctx *ctx = file->private_data;
8999         __poll_t mask = 0;
9000
9001         poll_wait(file, &ctx->poll_wait, wait);
9002         /*
9003          * synchronizes with barrier from wq_has_sleeper call in
9004          * io_commit_cqring
9005          */
9006         smp_rmb();
9007         if (!io_sqring_full(ctx))
9008                 mask |= EPOLLOUT | EPOLLWRNORM;
9009
9010         /*
9011          * Don't flush cqring overflow list here, just do a simple check.
9012          * Otherwise there could possible be ABBA deadlock:
9013          *      CPU0                    CPU1
9014          *      ----                    ----
9015          * lock(&ctx->uring_lock);
9016          *                              lock(&ep->mtx);
9017          *                              lock(&ctx->uring_lock);
9018          * lock(&ep->mtx);
9019          *
9020          * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9021          * pushs them to do the flush.
9022          */
9023         if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9024                 mask |= EPOLLIN | EPOLLRDNORM;
9025
9026         return mask;
9027 }
9028
9029 static int io_uring_fasync(int fd, struct file *file, int on)
9030 {
9031         struct io_ring_ctx *ctx = file->private_data;
9032
9033         return fasync_helper(fd, file, on, &ctx->cq_fasync);
9034 }
9035
9036 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9037 {
9038         const struct cred *creds;
9039
9040         creds = xa_erase(&ctx->personalities, id);
9041         if (creds) {
9042                 put_cred(creds);
9043                 return 0;
9044         }
9045
9046         return -EINVAL;
9047 }
9048
9049 struct io_tctx_exit {
9050         struct callback_head            task_work;
9051         struct completion               completion;
9052         struct io_ring_ctx              *ctx;
9053 };
9054
9055 static void io_tctx_exit_cb(struct callback_head *cb)
9056 {
9057         struct io_uring_task *tctx = current->io_uring;
9058         struct io_tctx_exit *work;
9059
9060         work = container_of(cb, struct io_tctx_exit, task_work);
9061         /*
9062          * When @in_idle, we're in cancellation and it's racy to remove the
9063          * node. It'll be removed by the end of cancellation, just ignore it.
9064          */
9065         if (!atomic_read(&tctx->in_idle))
9066                 io_uring_del_tctx_node((unsigned long)work->ctx);
9067         complete(&work->completion);
9068 }
9069
9070 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9071 {
9072         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9073
9074         return req->ctx == data;
9075 }
9076
9077 static void io_ring_exit_work(struct work_struct *work)
9078 {
9079         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9080         unsigned long timeout = jiffies + HZ * 60 * 5;
9081         unsigned long interval = HZ / 20;
9082         struct io_tctx_exit exit;
9083         struct io_tctx_node *node;
9084         int ret;
9085
9086         /*
9087          * If we're doing polled IO and end up having requests being
9088          * submitted async (out-of-line), then completions can come in while
9089          * we're waiting for refs to drop. We need to reap these manually,
9090          * as nobody else will be looking for them.
9091          */
9092         do {
9093                 io_uring_try_cancel_requests(ctx, NULL, true);
9094                 if (ctx->sq_data) {
9095                         struct io_sq_data *sqd = ctx->sq_data;
9096                         struct task_struct *tsk;
9097
9098                         io_sq_thread_park(sqd);
9099                         tsk = sqd->thread;
9100                         if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9101                                 io_wq_cancel_cb(tsk->io_uring->io_wq,
9102                                                 io_cancel_ctx_cb, ctx, true);
9103                         io_sq_thread_unpark(sqd);
9104                 }
9105
9106                 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9107                         /* there is little hope left, don't run it too often */
9108                         interval = HZ * 60;
9109                 }
9110         } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9111
9112         init_completion(&exit.completion);
9113         init_task_work(&exit.task_work, io_tctx_exit_cb);
9114         exit.ctx = ctx;
9115         /*
9116          * Some may use context even when all refs and requests have been put,
9117          * and they are free to do so while still holding uring_lock or
9118          * completion_lock, see io_req_task_submit(). Apart from other work,
9119          * this lock/unlock section also waits them to finish.
9120          */
9121         mutex_lock(&ctx->uring_lock);
9122         while (!list_empty(&ctx->tctx_list)) {
9123                 WARN_ON_ONCE(time_after(jiffies, timeout));
9124
9125                 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9126                                         ctx_node);
9127                 /* don't spin on a single task if cancellation failed */
9128                 list_rotate_left(&ctx->tctx_list);
9129                 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9130                 if (WARN_ON_ONCE(ret))
9131                         continue;
9132                 wake_up_process(node->task);
9133
9134                 mutex_unlock(&ctx->uring_lock);
9135                 wait_for_completion(&exit.completion);
9136                 mutex_lock(&ctx->uring_lock);
9137         }
9138         mutex_unlock(&ctx->uring_lock);
9139         spin_lock(&ctx->completion_lock);
9140         spin_unlock(&ctx->completion_lock);
9141
9142         io_ring_ctx_free(ctx);
9143 }
9144
9145 /* Returns true if we found and killed one or more timeouts */
9146 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9147                              bool cancel_all)
9148 {
9149         struct io_kiocb *req, *tmp;
9150         int canceled = 0;
9151
9152         spin_lock(&ctx->completion_lock);
9153         spin_lock_irq(&ctx->timeout_lock);
9154         list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9155                 if (io_match_task(req, tsk, cancel_all)) {
9156                         io_kill_timeout(req, -ECANCELED);
9157                         canceled++;
9158                 }
9159         }
9160         spin_unlock_irq(&ctx->timeout_lock);
9161         if (canceled != 0)
9162                 io_commit_cqring(ctx);
9163         spin_unlock(&ctx->completion_lock);
9164         if (canceled != 0)
9165                 io_cqring_ev_posted(ctx);
9166         return canceled != 0;
9167 }
9168
9169 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9170 {
9171         unsigned long index;
9172         struct creds *creds;
9173
9174         mutex_lock(&ctx->uring_lock);
9175         percpu_ref_kill(&ctx->refs);
9176         if (ctx->rings)
9177                 __io_cqring_overflow_flush(ctx, true);
9178         xa_for_each(&ctx->personalities, index, creds)
9179                 io_unregister_personality(ctx, index);
9180         mutex_unlock(&ctx->uring_lock);
9181
9182         io_kill_timeouts(ctx, NULL, true);
9183         io_poll_remove_all(ctx, NULL, true);
9184
9185         /* if we failed setting up the ctx, we might not have any rings */
9186         io_iopoll_try_reap_events(ctx);
9187
9188         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9189         /*
9190          * Use system_unbound_wq to avoid spawning tons of event kworkers
9191          * if we're exiting a ton of rings at the same time. It just adds
9192          * noise and overhead, there's no discernable change in runtime
9193          * over using system_wq.
9194          */
9195         queue_work(system_unbound_wq, &ctx->exit_work);
9196 }
9197
9198 static int io_uring_release(struct inode *inode, struct file *file)
9199 {
9200         struct io_ring_ctx *ctx = file->private_data;
9201
9202         file->private_data = NULL;
9203         io_ring_ctx_wait_and_kill(ctx);
9204         return 0;
9205 }
9206
9207 struct io_task_cancel {
9208         struct task_struct *task;
9209         bool all;
9210 };
9211
9212 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9213 {
9214         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9215         struct io_task_cancel *cancel = data;
9216         bool ret;
9217
9218         if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
9219                 struct io_ring_ctx *ctx = req->ctx;
9220
9221                 /* protect against races with linked timeouts */
9222                 spin_lock(&ctx->completion_lock);
9223                 ret = io_match_task(req, cancel->task, cancel->all);
9224                 spin_unlock(&ctx->completion_lock);
9225         } else {
9226                 ret = io_match_task(req, cancel->task, cancel->all);
9227         }
9228         return ret;
9229 }
9230
9231 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9232                                   struct task_struct *task, bool cancel_all)
9233 {
9234         struct io_defer_entry *de;
9235         LIST_HEAD(list);
9236
9237         spin_lock(&ctx->completion_lock);
9238         list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9239                 if (io_match_task(de->req, task, cancel_all)) {
9240                         list_cut_position(&list, &ctx->defer_list, &de->list);
9241                         break;
9242                 }
9243         }
9244         spin_unlock(&ctx->completion_lock);
9245         if (list_empty(&list))
9246                 return false;
9247
9248         while (!list_empty(&list)) {
9249                 de = list_first_entry(&list, struct io_defer_entry, list);
9250                 list_del_init(&de->list);
9251                 io_req_complete_failed(de->req, -ECANCELED);
9252                 kfree(de);
9253         }
9254         return true;
9255 }
9256
9257 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9258 {
9259         struct io_tctx_node *node;
9260         enum io_wq_cancel cret;
9261         bool ret = false;
9262
9263         mutex_lock(&ctx->uring_lock);
9264         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9265                 struct io_uring_task *tctx = node->task->io_uring;
9266
9267                 /*
9268                  * io_wq will stay alive while we hold uring_lock, because it's
9269                  * killed after ctx nodes, which requires to take the lock.
9270                  */
9271                 if (!tctx || !tctx->io_wq)
9272                         continue;
9273                 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9274                 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9275         }
9276         mutex_unlock(&ctx->uring_lock);
9277
9278         return ret;
9279 }
9280
9281 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9282                                          struct task_struct *task,
9283                                          bool cancel_all)
9284 {
9285         struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9286         struct io_uring_task *tctx = task ? task->io_uring : NULL;
9287
9288         while (1) {
9289                 enum io_wq_cancel cret;
9290                 bool ret = false;
9291
9292                 if (!task) {
9293                         ret |= io_uring_try_cancel_iowq(ctx);
9294                 } else if (tctx && tctx->io_wq) {
9295                         /*
9296                          * Cancels requests of all rings, not only @ctx, but
9297                          * it's fine as the task is in exit/exec.
9298                          */
9299                         cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9300                                                &cancel, true);
9301                         ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9302                 }
9303
9304                 /* SQPOLL thread does its own polling */
9305                 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9306                     (ctx->sq_data && ctx->sq_data->thread == current)) {
9307                         while (!list_empty_careful(&ctx->iopoll_list)) {
9308                                 io_iopoll_try_reap_events(ctx);
9309                                 ret = true;
9310                         }
9311                 }
9312
9313                 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9314                 ret |= io_poll_remove_all(ctx, task, cancel_all);
9315                 ret |= io_kill_timeouts(ctx, task, cancel_all);
9316                 if (task)
9317                         ret |= io_run_task_work();
9318                 if (!ret)
9319                         break;
9320                 cond_resched();
9321         }
9322 }
9323
9324 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9325 {
9326         struct io_uring_task *tctx = current->io_uring;
9327         struct io_tctx_node *node;
9328         int ret;
9329
9330         if (unlikely(!tctx)) {
9331                 ret = io_uring_alloc_task_context(current, ctx);
9332                 if (unlikely(ret))
9333                         return ret;
9334                 tctx = current->io_uring;
9335         }
9336         if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9337                 node = kmalloc(sizeof(*node), GFP_KERNEL);
9338                 if (!node)
9339                         return -ENOMEM;
9340                 node->ctx = ctx;
9341                 node->task = current;
9342
9343                 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9344                                         node, GFP_KERNEL));
9345                 if (ret) {
9346                         kfree(node);
9347                         return ret;
9348                 }
9349
9350                 mutex_lock(&ctx->uring_lock);
9351                 list_add(&node->ctx_node, &ctx->tctx_list);
9352                 mutex_unlock(&ctx->uring_lock);
9353         }
9354         tctx->last = ctx;
9355         return 0;
9356 }
9357
9358 /*
9359  * Note that this task has used io_uring. We use it for cancelation purposes.
9360  */
9361 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9362 {
9363         struct io_uring_task *tctx = current->io_uring;
9364
9365         if (likely(tctx && tctx->last == ctx))
9366                 return 0;
9367         return __io_uring_add_tctx_node(ctx);
9368 }
9369
9370 /*
9371  * Remove this io_uring_file -> task mapping.
9372  */
9373 static void io_uring_del_tctx_node(unsigned long index)
9374 {
9375         struct io_uring_task *tctx = current->io_uring;
9376         struct io_tctx_node *node;
9377
9378         if (!tctx)
9379                 return;
9380         node = xa_erase(&tctx->xa, index);
9381         if (!node)
9382                 return;
9383
9384         WARN_ON_ONCE(current != node->task);
9385         WARN_ON_ONCE(list_empty(&node->ctx_node));
9386
9387         mutex_lock(&node->ctx->uring_lock);
9388         list_del(&node->ctx_node);
9389         mutex_unlock(&node->ctx->uring_lock);
9390
9391         if (tctx->last == node->ctx)
9392                 tctx->last = NULL;
9393         kfree(node);
9394 }
9395
9396 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9397 {
9398         struct io_wq *wq = tctx->io_wq;
9399         struct io_tctx_node *node;
9400         unsigned long index;
9401
9402         xa_for_each(&tctx->xa, index, node)
9403                 io_uring_del_tctx_node(index);
9404         if (wq) {
9405                 /*
9406                  * Must be after io_uring_del_task_file() (removes nodes under
9407                  * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9408                  */
9409                 io_wq_put_and_exit(wq);
9410                 tctx->io_wq = NULL;
9411         }
9412 }
9413
9414 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9415 {
9416         if (tracked)
9417                 return atomic_read(&tctx->inflight_tracked);
9418         return percpu_counter_sum(&tctx->inflight);
9419 }
9420
9421 static void io_uring_drop_tctx_refs(struct task_struct *task)
9422 {
9423         struct io_uring_task *tctx = task->io_uring;
9424         unsigned int refs = tctx->cached_refs;
9425
9426         if (refs) {
9427                 tctx->cached_refs = 0;
9428                 percpu_counter_sub(&tctx->inflight, refs);
9429                 put_task_struct_many(task, refs);
9430         }
9431 }
9432
9433 /*
9434  * Find any io_uring ctx that this task has registered or done IO on, and cancel
9435  * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9436  */
9437 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9438 {
9439         struct io_uring_task *tctx = current->io_uring;
9440         struct io_ring_ctx *ctx;
9441         s64 inflight;
9442         DEFINE_WAIT(wait);
9443
9444         WARN_ON_ONCE(sqd && sqd->thread != current);
9445
9446         if (!current->io_uring)
9447                 return;
9448         if (tctx->io_wq)
9449                 io_wq_exit_start(tctx->io_wq);
9450
9451         atomic_inc(&tctx->in_idle);
9452         do {
9453                 io_uring_drop_tctx_refs(current);
9454                 /* read completions before cancelations */
9455                 inflight = tctx_inflight(tctx, !cancel_all);
9456                 if (!inflight)
9457                         break;
9458
9459                 if (!sqd) {
9460                         struct io_tctx_node *node;
9461                         unsigned long index;
9462
9463                         xa_for_each(&tctx->xa, index, node) {
9464                                 /* sqpoll task will cancel all its requests */
9465                                 if (node->ctx->sq_data)
9466                                         continue;
9467                                 io_uring_try_cancel_requests(node->ctx, current,
9468                                                              cancel_all);
9469                         }
9470                 } else {
9471                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9472                                 io_uring_try_cancel_requests(ctx, current,
9473                                                              cancel_all);
9474                 }
9475
9476                 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9477                 io_uring_drop_tctx_refs(current);
9478                 /*
9479                  * If we've seen completions, retry without waiting. This
9480                  * avoids a race where a completion comes in before we did
9481                  * prepare_to_wait().
9482                  */
9483                 if (inflight == tctx_inflight(tctx, !cancel_all))
9484                         schedule();
9485                 finish_wait(&tctx->wait, &wait);
9486         } while (1);
9487         atomic_dec(&tctx->in_idle);
9488
9489         io_uring_clean_tctx(tctx);
9490         if (cancel_all) {
9491                 /* for exec all current's requests should be gone, kill tctx */
9492                 __io_uring_free(current);
9493         }
9494 }
9495
9496 void __io_uring_cancel(bool cancel_all)
9497 {
9498         io_uring_cancel_generic(cancel_all, NULL);
9499 }
9500
9501 static void *io_uring_validate_mmap_request(struct file *file,
9502                                             loff_t pgoff, size_t sz)
9503 {
9504         struct io_ring_ctx *ctx = file->private_data;
9505         loff_t offset = pgoff << PAGE_SHIFT;
9506         struct page *page;
9507         void *ptr;
9508
9509         switch (offset) {
9510         case IORING_OFF_SQ_RING:
9511         case IORING_OFF_CQ_RING:
9512                 ptr = ctx->rings;
9513                 break;
9514         case IORING_OFF_SQES:
9515                 ptr = ctx->sq_sqes;
9516                 break;
9517         default:
9518                 return ERR_PTR(-EINVAL);
9519         }
9520
9521         page = virt_to_head_page(ptr);
9522         if (sz > page_size(page))
9523                 return ERR_PTR(-EINVAL);
9524
9525         return ptr;
9526 }
9527
9528 #ifdef CONFIG_MMU
9529
9530 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9531 {
9532         size_t sz = vma->vm_end - vma->vm_start;
9533         unsigned long pfn;
9534         void *ptr;
9535
9536         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9537         if (IS_ERR(ptr))
9538                 return PTR_ERR(ptr);
9539
9540         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9541         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9542 }
9543
9544 #else /* !CONFIG_MMU */
9545
9546 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9547 {
9548         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9549 }
9550
9551 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9552 {
9553         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9554 }
9555
9556 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9557         unsigned long addr, unsigned long len,
9558         unsigned long pgoff, unsigned long flags)
9559 {
9560         void *ptr;
9561
9562         ptr = io_uring_validate_mmap_request(file, pgoff, len);
9563         if (IS_ERR(ptr))
9564                 return PTR_ERR(ptr);
9565
9566         return (unsigned long) ptr;
9567 }
9568
9569 #endif /* !CONFIG_MMU */
9570
9571 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9572 {
9573         DEFINE_WAIT(wait);
9574
9575         do {
9576                 if (!io_sqring_full(ctx))
9577                         break;
9578                 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9579
9580                 if (!io_sqring_full(ctx))
9581                         break;
9582                 schedule();
9583         } while (!signal_pending(current));
9584
9585         finish_wait(&ctx->sqo_sq_wait, &wait);
9586         return 0;
9587 }
9588
9589 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9590                           struct __kernel_timespec __user **ts,
9591                           const sigset_t __user **sig)
9592 {
9593         struct io_uring_getevents_arg arg;
9594
9595         /*
9596          * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9597          * is just a pointer to the sigset_t.
9598          */
9599         if (!(flags & IORING_ENTER_EXT_ARG)) {
9600                 *sig = (const sigset_t __user *) argp;
9601                 *ts = NULL;
9602                 return 0;
9603         }
9604
9605         /*
9606          * EXT_ARG is set - ensure we agree on the size of it and copy in our
9607          * timespec and sigset_t pointers if good.
9608          */
9609         if (*argsz != sizeof(arg))
9610                 return -EINVAL;
9611         if (copy_from_user(&arg, argp, sizeof(arg)))
9612                 return -EFAULT;
9613         *sig = u64_to_user_ptr(arg.sigmask);
9614         *argsz = arg.sigmask_sz;
9615         *ts = u64_to_user_ptr(arg.ts);
9616         return 0;
9617 }
9618
9619 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9620                 u32, min_complete, u32, flags, const void __user *, argp,
9621                 size_t, argsz)
9622 {
9623         struct io_ring_ctx *ctx;
9624         int submitted = 0;
9625         struct fd f;
9626         long ret;
9627
9628         io_run_task_work();
9629
9630         if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9631                                IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9632                 return -EINVAL;
9633
9634         f = fdget(fd);
9635         if (unlikely(!f.file))
9636                 return -EBADF;
9637
9638         ret = -EOPNOTSUPP;
9639         if (unlikely(f.file->f_op != &io_uring_fops))
9640                 goto out_fput;
9641
9642         ret = -ENXIO;
9643         ctx = f.file->private_data;
9644         if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9645                 goto out_fput;
9646
9647         ret = -EBADFD;
9648         if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9649                 goto out;
9650
9651         /*
9652          * For SQ polling, the thread will do all submissions and completions.
9653          * Just return the requested submit count, and wake the thread if
9654          * we were asked to.
9655          */
9656         ret = 0;
9657         if (ctx->flags & IORING_SETUP_SQPOLL) {
9658                 io_cqring_overflow_flush(ctx);
9659
9660                 if (unlikely(ctx->sq_data->thread == NULL)) {
9661                         ret = -EOWNERDEAD;
9662                         goto out;
9663                 }
9664                 if (flags & IORING_ENTER_SQ_WAKEUP)
9665                         wake_up(&ctx->sq_data->wait);
9666                 if (flags & IORING_ENTER_SQ_WAIT) {
9667                         ret = io_sqpoll_wait_sq(ctx);
9668                         if (ret)
9669                                 goto out;
9670                 }
9671                 submitted = to_submit;
9672         } else if (to_submit) {
9673                 ret = io_uring_add_tctx_node(ctx);
9674                 if (unlikely(ret))
9675                         goto out;
9676                 mutex_lock(&ctx->uring_lock);
9677                 submitted = io_submit_sqes(ctx, to_submit);
9678                 mutex_unlock(&ctx->uring_lock);
9679
9680                 if (submitted != to_submit)
9681                         goto out;
9682         }
9683         if (flags & IORING_ENTER_GETEVENTS) {
9684                 const sigset_t __user *sig;
9685                 struct __kernel_timespec __user *ts;
9686
9687                 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9688                 if (unlikely(ret))
9689                         goto out;
9690
9691                 min_complete = min(min_complete, ctx->cq_entries);
9692
9693                 /*
9694                  * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9695                  * space applications don't need to do io completion events
9696                  * polling again, they can rely on io_sq_thread to do polling
9697                  * work, which can reduce cpu usage and uring_lock contention.
9698                  */
9699                 if (ctx->flags & IORING_SETUP_IOPOLL &&
9700                     !(ctx->flags & IORING_SETUP_SQPOLL)) {
9701                         ret = io_iopoll_check(ctx, min_complete);
9702                 } else {
9703                         ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9704                 }
9705         }
9706
9707 out:
9708         percpu_ref_put(&ctx->refs);
9709 out_fput:
9710         fdput(f);
9711         return submitted ? submitted : ret;
9712 }
9713
9714 #ifdef CONFIG_PROC_FS
9715 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9716                 const struct cred *cred)
9717 {
9718         struct user_namespace *uns = seq_user_ns(m);
9719         struct group_info *gi;
9720         kernel_cap_t cap;
9721         unsigned __capi;
9722         int g;
9723
9724         seq_printf(m, "%5d\n", id);
9725         seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9726         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9727         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9728         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9729         seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9730         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9731         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9732         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9733         seq_puts(m, "\n\tGroups:\t");
9734         gi = cred->group_info;
9735         for (g = 0; g < gi->ngroups; g++) {
9736                 seq_put_decimal_ull(m, g ? " " : "",
9737                                         from_kgid_munged(uns, gi->gid[g]));
9738         }
9739         seq_puts(m, "\n\tCapEff:\t");
9740         cap = cred->cap_effective;
9741         CAP_FOR_EACH_U32(__capi)
9742                 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9743         seq_putc(m, '\n');
9744         return 0;
9745 }
9746
9747 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9748 {
9749         struct io_sq_data *sq = NULL;
9750         bool has_lock;
9751         int i;
9752
9753         /*
9754          * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9755          * since fdinfo case grabs it in the opposite direction of normal use
9756          * cases. If we fail to get the lock, we just don't iterate any
9757          * structures that could be going away outside the io_uring mutex.
9758          */
9759         has_lock = mutex_trylock(&ctx->uring_lock);
9760
9761         if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9762                 sq = ctx->sq_data;
9763                 if (!sq->thread)
9764                         sq = NULL;
9765         }
9766
9767         seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9768         seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9769         seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9770         for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9771                 struct file *f = io_file_from_index(ctx, i);
9772
9773                 if (f)
9774                         seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9775                 else
9776                         seq_printf(m, "%5u: <none>\n", i);
9777         }
9778         seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9779         for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9780                 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9781                 unsigned int len = buf->ubuf_end - buf->ubuf;
9782
9783                 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9784         }
9785         if (has_lock && !xa_empty(&ctx->personalities)) {
9786                 unsigned long index;
9787                 const struct cred *cred;
9788
9789                 seq_printf(m, "Personalities:\n");
9790                 xa_for_each(&ctx->personalities, index, cred)
9791                         io_uring_show_cred(m, index, cred);
9792         }
9793         seq_printf(m, "PollList:\n");
9794         spin_lock(&ctx->completion_lock);
9795         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9796                 struct hlist_head *list = &ctx->cancel_hash[i];
9797                 struct io_kiocb *req;
9798
9799                 hlist_for_each_entry(req, list, hash_node)
9800                         seq_printf(m, "  op=%d, task_works=%d\n", req->opcode,
9801                                         req->task->task_works != NULL);
9802         }
9803         spin_unlock(&ctx->completion_lock);
9804         if (has_lock)
9805                 mutex_unlock(&ctx->uring_lock);
9806 }
9807
9808 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9809 {
9810         struct io_ring_ctx *ctx = f->private_data;
9811
9812         if (percpu_ref_tryget(&ctx->refs)) {
9813                 __io_uring_show_fdinfo(ctx, m);
9814                 percpu_ref_put(&ctx->refs);
9815         }
9816 }
9817 #endif
9818
9819 static const struct file_operations io_uring_fops = {
9820         .release        = io_uring_release,
9821         .mmap           = io_uring_mmap,
9822 #ifndef CONFIG_MMU
9823         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9824         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9825 #endif
9826         .poll           = io_uring_poll,
9827         .fasync         = io_uring_fasync,
9828 #ifdef CONFIG_PROC_FS
9829         .show_fdinfo    = io_uring_show_fdinfo,
9830 #endif
9831 };
9832
9833 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9834                                   struct io_uring_params *p)
9835 {
9836         struct io_rings *rings;
9837         size_t size, sq_array_offset;
9838
9839         /* make sure these are sane, as we already accounted them */
9840         ctx->sq_entries = p->sq_entries;
9841         ctx->cq_entries = p->cq_entries;
9842
9843         size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9844         if (size == SIZE_MAX)
9845                 return -EOVERFLOW;
9846
9847         rings = io_mem_alloc(size);
9848         if (!rings)
9849                 return -ENOMEM;
9850
9851         ctx->rings = rings;
9852         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9853         rings->sq_ring_mask = p->sq_entries - 1;
9854         rings->cq_ring_mask = p->cq_entries - 1;
9855         rings->sq_ring_entries = p->sq_entries;
9856         rings->cq_ring_entries = p->cq_entries;
9857
9858         size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9859         if (size == SIZE_MAX) {
9860                 io_mem_free(ctx->rings);
9861                 ctx->rings = NULL;
9862                 return -EOVERFLOW;
9863         }
9864
9865         ctx->sq_sqes = io_mem_alloc(size);
9866         if (!ctx->sq_sqes) {
9867                 io_mem_free(ctx->rings);
9868                 ctx->rings = NULL;
9869                 return -ENOMEM;
9870         }
9871
9872         return 0;
9873 }
9874
9875 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9876 {
9877         int ret, fd;
9878
9879         fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9880         if (fd < 0)
9881                 return fd;
9882
9883         ret = io_uring_add_tctx_node(ctx);
9884         if (ret) {
9885                 put_unused_fd(fd);
9886                 return ret;
9887         }
9888         fd_install(fd, file);
9889         return fd;
9890 }
9891
9892 /*
9893  * Allocate an anonymous fd, this is what constitutes the application
9894  * visible backing of an io_uring instance. The application mmaps this
9895  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9896  * we have to tie this fd to a socket for file garbage collection purposes.
9897  */
9898 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9899 {
9900         struct file *file;
9901 #if defined(CONFIG_UNIX)
9902         int ret;
9903
9904         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9905                                 &ctx->ring_sock);
9906         if (ret)
9907                 return ERR_PTR(ret);
9908 #endif
9909
9910         file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9911                                         O_RDWR | O_CLOEXEC);
9912 #if defined(CONFIG_UNIX)
9913         if (IS_ERR(file)) {
9914                 sock_release(ctx->ring_sock);
9915                 ctx->ring_sock = NULL;
9916         } else {
9917                 ctx->ring_sock->file = file;
9918         }
9919 #endif
9920         return file;
9921 }
9922
9923 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9924                            struct io_uring_params __user *params)
9925 {
9926         struct io_ring_ctx *ctx;
9927         struct file *file;
9928         int ret;
9929
9930         if (!entries)
9931                 return -EINVAL;
9932         if (entries > IORING_MAX_ENTRIES) {
9933                 if (!(p->flags & IORING_SETUP_CLAMP))
9934                         return -EINVAL;
9935                 entries = IORING_MAX_ENTRIES;
9936         }
9937
9938         /*
9939          * Use twice as many entries for the CQ ring. It's possible for the
9940          * application to drive a higher depth than the size of the SQ ring,
9941          * since the sqes are only used at submission time. This allows for
9942          * some flexibility in overcommitting a bit. If the application has
9943          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9944          * of CQ ring entries manually.
9945          */
9946         p->sq_entries = roundup_pow_of_two(entries);
9947         if (p->flags & IORING_SETUP_CQSIZE) {
9948                 /*
9949                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
9950                  * to a power-of-two, if it isn't already. We do NOT impose
9951                  * any cq vs sq ring sizing.
9952                  */
9953                 if (!p->cq_entries)
9954                         return -EINVAL;
9955                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9956                         if (!(p->flags & IORING_SETUP_CLAMP))
9957                                 return -EINVAL;
9958                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
9959                 }
9960                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9961                 if (p->cq_entries < p->sq_entries)
9962                         return -EINVAL;
9963         } else {
9964                 p->cq_entries = 2 * p->sq_entries;
9965         }
9966
9967         ctx = io_ring_ctx_alloc(p);
9968         if (!ctx)
9969                 return -ENOMEM;
9970         ctx->compat = in_compat_syscall();
9971         if (!capable(CAP_IPC_LOCK))
9972                 ctx->user = get_uid(current_user());
9973
9974         /*
9975          * This is just grabbed for accounting purposes. When a process exits,
9976          * the mm is exited and dropped before the files, hence we need to hang
9977          * on to this mm purely for the purposes of being able to unaccount
9978          * memory (locked/pinned vm). It's not used for anything else.
9979          */
9980         mmgrab(current->mm);
9981         ctx->mm_account = current->mm;
9982
9983         ret = io_allocate_scq_urings(ctx, p);
9984         if (ret)
9985                 goto err;
9986
9987         ret = io_sq_offload_create(ctx, p);
9988         if (ret)
9989                 goto err;
9990         /* always set a rsrc node */
9991         ret = io_rsrc_node_switch_start(ctx);
9992         if (ret)
9993                 goto err;
9994         io_rsrc_node_switch(ctx, NULL);
9995
9996         memset(&p->sq_off, 0, sizeof(p->sq_off));
9997         p->sq_off.head = offsetof(struct io_rings, sq.head);
9998         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9999         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10000         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10001         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10002         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10003         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10004
10005         memset(&p->cq_off, 0, sizeof(p->cq_off));
10006         p->cq_off.head = offsetof(struct io_rings, cq.head);
10007         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10008         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10009         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10010         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10011         p->cq_off.cqes = offsetof(struct io_rings, cqes);
10012         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10013
10014         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10015                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10016                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10017                         IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10018                         IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10019                         IORING_FEAT_RSRC_TAGS;
10020
10021         if (copy_to_user(params, p, sizeof(*p))) {
10022                 ret = -EFAULT;
10023                 goto err;
10024         }
10025
10026         file = io_uring_get_file(ctx);
10027         if (IS_ERR(file)) {
10028                 ret = PTR_ERR(file);
10029                 goto err;
10030         }
10031
10032         /*
10033          * Install ring fd as the very last thing, so we don't risk someone
10034          * having closed it before we finish setup
10035          */
10036         ret = io_uring_install_fd(ctx, file);
10037         if (ret < 0) {
10038                 /* fput will clean it up */
10039                 fput(file);
10040                 return ret;
10041         }
10042
10043         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10044         return ret;
10045 err:
10046         io_ring_ctx_wait_and_kill(ctx);
10047         return ret;
10048 }
10049
10050 /*
10051  * Sets up an aio uring context, and returns the fd. Applications asks for a
10052  * ring size, we return the actual sq/cq ring sizes (among other things) in the
10053  * params structure passed in.
10054  */
10055 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10056 {
10057         struct io_uring_params p;
10058         int i;
10059
10060         if (copy_from_user(&p, params, sizeof(p)))
10061                 return -EFAULT;
10062         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10063                 if (p.resv[i])
10064                         return -EINVAL;
10065         }
10066
10067         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10068                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10069                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10070                         IORING_SETUP_R_DISABLED))
10071                 return -EINVAL;
10072
10073         return  io_uring_create(entries, &p, params);
10074 }
10075
10076 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10077                 struct io_uring_params __user *, params)
10078 {
10079         return io_uring_setup(entries, params);
10080 }
10081
10082 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10083 {
10084         struct io_uring_probe *p;
10085         size_t size;
10086         int i, ret;
10087
10088         size = struct_size(p, ops, nr_args);
10089         if (size == SIZE_MAX)
10090                 return -EOVERFLOW;
10091         p = kzalloc(size, GFP_KERNEL);
10092         if (!p)
10093                 return -ENOMEM;
10094
10095         ret = -EFAULT;
10096         if (copy_from_user(p, arg, size))
10097                 goto out;
10098         ret = -EINVAL;
10099         if (memchr_inv(p, 0, size))
10100                 goto out;
10101
10102         p->last_op = IORING_OP_LAST - 1;
10103         if (nr_args > IORING_OP_LAST)
10104                 nr_args = IORING_OP_LAST;
10105
10106         for (i = 0; i < nr_args; i++) {
10107                 p->ops[i].op = i;
10108                 if (!io_op_defs[i].not_supported)
10109                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
10110         }
10111         p->ops_len = i;
10112
10113         ret = 0;
10114         if (copy_to_user(arg, p, size))
10115                 ret = -EFAULT;
10116 out:
10117         kfree(p);
10118         return ret;
10119 }
10120
10121 static int io_register_personality(struct io_ring_ctx *ctx)
10122 {
10123         const struct cred *creds;
10124         u32 id;
10125         int ret;
10126
10127         creds = get_current_cred();
10128
10129         ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10130                         XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10131         if (ret < 0) {
10132                 put_cred(creds);
10133                 return ret;
10134         }
10135         return id;
10136 }
10137
10138 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10139                                     unsigned int nr_args)
10140 {
10141         struct io_uring_restriction *res;
10142         size_t size;
10143         int i, ret;
10144
10145         /* Restrictions allowed only if rings started disabled */
10146         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10147                 return -EBADFD;
10148
10149         /* We allow only a single restrictions registration */
10150         if (ctx->restrictions.registered)
10151                 return -EBUSY;
10152
10153         if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10154                 return -EINVAL;
10155
10156         size = array_size(nr_args, sizeof(*res));
10157         if (size == SIZE_MAX)
10158                 return -EOVERFLOW;
10159
10160         res = memdup_user(arg, size);
10161         if (IS_ERR(res))
10162                 return PTR_ERR(res);
10163
10164         ret = 0;
10165
10166         for (i = 0; i < nr_args; i++) {
10167                 switch (res[i].opcode) {
10168                 case IORING_RESTRICTION_REGISTER_OP:
10169                         if (res[i].register_op >= IORING_REGISTER_LAST) {
10170                                 ret = -EINVAL;
10171                                 goto out;
10172                         }
10173
10174                         __set_bit(res[i].register_op,
10175                                   ctx->restrictions.register_op);
10176                         break;
10177                 case IORING_RESTRICTION_SQE_OP:
10178                         if (res[i].sqe_op >= IORING_OP_LAST) {
10179                                 ret = -EINVAL;
10180                                 goto out;
10181                         }
10182
10183                         __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10184                         break;
10185                 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10186                         ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10187                         break;
10188                 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10189                         ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10190                         break;
10191                 default:
10192                         ret = -EINVAL;
10193                         goto out;
10194                 }
10195         }
10196
10197 out:
10198         /* Reset all restrictions if an error happened */
10199         if (ret != 0)
10200                 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10201         else
10202                 ctx->restrictions.registered = true;
10203
10204         kfree(res);
10205         return ret;
10206 }
10207
10208 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10209 {
10210         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10211                 return -EBADFD;
10212
10213         if (ctx->restrictions.registered)
10214                 ctx->restricted = 1;
10215
10216         ctx->flags &= ~IORING_SETUP_R_DISABLED;
10217         if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10218                 wake_up(&ctx->sq_data->wait);
10219         return 0;
10220 }
10221
10222 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10223                                      struct io_uring_rsrc_update2 *up,
10224                                      unsigned nr_args)
10225 {
10226         __u32 tmp;
10227         int err;
10228
10229         if (up->resv)
10230                 return -EINVAL;
10231         if (check_add_overflow(up->offset, nr_args, &tmp))
10232                 return -EOVERFLOW;
10233         err = io_rsrc_node_switch_start(ctx);
10234         if (err)
10235                 return err;
10236
10237         switch (type) {
10238         case IORING_RSRC_FILE:
10239                 return __io_sqe_files_update(ctx, up, nr_args);
10240         case IORING_RSRC_BUFFER:
10241                 return __io_sqe_buffers_update(ctx, up, nr_args);
10242         }
10243         return -EINVAL;
10244 }
10245
10246 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10247                                     unsigned nr_args)
10248 {
10249         struct io_uring_rsrc_update2 up;
10250
10251         if (!nr_args)
10252                 return -EINVAL;
10253         memset(&up, 0, sizeof(up));
10254         if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10255                 return -EFAULT;
10256         return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10257 }
10258
10259 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10260                                    unsigned size, unsigned type)
10261 {
10262         struct io_uring_rsrc_update2 up;
10263
10264         if (size != sizeof(up))
10265                 return -EINVAL;
10266         if (copy_from_user(&up, arg, sizeof(up)))
10267                 return -EFAULT;
10268         if (!up.nr || up.resv)
10269                 return -EINVAL;
10270         return __io_register_rsrc_update(ctx, type, &up, up.nr);
10271 }
10272
10273 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10274                             unsigned int size, unsigned int type)
10275 {
10276         struct io_uring_rsrc_register rr;
10277
10278         /* keep it extendible */
10279         if (size != sizeof(rr))
10280                 return -EINVAL;
10281
10282         memset(&rr, 0, sizeof(rr));
10283         if (copy_from_user(&rr, arg, size))
10284                 return -EFAULT;
10285         if (!rr.nr || rr.resv || rr.resv2)
10286                 return -EINVAL;
10287
10288         switch (type) {
10289         case IORING_RSRC_FILE:
10290                 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10291                                              rr.nr, u64_to_user_ptr(rr.tags));
10292         case IORING_RSRC_BUFFER:
10293                 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10294                                                rr.nr, u64_to_user_ptr(rr.tags));
10295         }
10296         return -EINVAL;
10297 }
10298
10299 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10300                                 unsigned len)
10301 {
10302         struct io_uring_task *tctx = current->io_uring;
10303         cpumask_var_t new_mask;
10304         int ret;
10305
10306         if (!tctx || !tctx->io_wq)
10307                 return -EINVAL;
10308
10309         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10310                 return -ENOMEM;
10311
10312         cpumask_clear(new_mask);
10313         if (len > cpumask_size())
10314                 len = cpumask_size();
10315
10316         if (copy_from_user(new_mask, arg, len)) {
10317                 free_cpumask_var(new_mask);
10318                 return -EFAULT;
10319         }
10320
10321         ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10322         free_cpumask_var(new_mask);
10323         return ret;
10324 }
10325
10326 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10327 {
10328         struct io_uring_task *tctx = current->io_uring;
10329
10330         if (!tctx || !tctx->io_wq)
10331                 return -EINVAL;
10332
10333         return io_wq_cpu_affinity(tctx->io_wq, NULL);
10334 }
10335
10336 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10337                                         void __user *arg)
10338 {
10339         struct io_uring_task *tctx = NULL;
10340         struct io_sq_data *sqd = NULL;
10341         __u32 new_count[2];
10342         int i, ret;
10343
10344         if (copy_from_user(new_count, arg, sizeof(new_count)))
10345                 return -EFAULT;
10346         for (i = 0; i < ARRAY_SIZE(new_count); i++)
10347                 if (new_count[i] > INT_MAX)
10348                         return -EINVAL;
10349
10350         if (ctx->flags & IORING_SETUP_SQPOLL) {
10351                 sqd = ctx->sq_data;
10352                 if (sqd) {
10353                         mutex_lock(&sqd->lock);
10354                         tctx = sqd->thread->io_uring;
10355                 }
10356         } else {
10357                 tctx = current->io_uring;
10358         }
10359
10360         ret = -EINVAL;
10361         if (!tctx || !tctx->io_wq)
10362                 goto err;
10363
10364         ret = io_wq_max_workers(tctx->io_wq, new_count);
10365         if (ret)
10366                 goto err;
10367
10368         if (sqd)
10369                 mutex_unlock(&sqd->lock);
10370
10371         if (copy_to_user(arg, new_count, sizeof(new_count)))
10372                 return -EFAULT;
10373
10374         return 0;
10375 err:
10376         if (sqd)
10377                 mutex_unlock(&sqd->lock);
10378         return ret;
10379 }
10380
10381 static bool io_register_op_must_quiesce(int op)
10382 {
10383         switch (op) {
10384         case IORING_REGISTER_BUFFERS:
10385         case IORING_UNREGISTER_BUFFERS:
10386         case IORING_REGISTER_FILES:
10387         case IORING_UNREGISTER_FILES:
10388         case IORING_REGISTER_FILES_UPDATE:
10389         case IORING_REGISTER_PROBE:
10390         case IORING_REGISTER_PERSONALITY:
10391         case IORING_UNREGISTER_PERSONALITY:
10392         case IORING_REGISTER_FILES2:
10393         case IORING_REGISTER_FILES_UPDATE2:
10394         case IORING_REGISTER_BUFFERS2:
10395         case IORING_REGISTER_BUFFERS_UPDATE:
10396         case IORING_REGISTER_IOWQ_AFF:
10397         case IORING_UNREGISTER_IOWQ_AFF:
10398         case IORING_REGISTER_IOWQ_MAX_WORKERS:
10399                 return false;
10400         default:
10401                 return true;
10402         }
10403 }
10404
10405 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10406 {
10407         long ret;
10408
10409         percpu_ref_kill(&ctx->refs);
10410
10411         /*
10412          * Drop uring mutex before waiting for references to exit. If another
10413          * thread is currently inside io_uring_enter() it might need to grab the
10414          * uring_lock to make progress. If we hold it here across the drain
10415          * wait, then we can deadlock. It's safe to drop the mutex here, since
10416          * no new references will come in after we've killed the percpu ref.
10417          */
10418         mutex_unlock(&ctx->uring_lock);
10419         do {
10420                 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10421                 if (!ret)
10422                         break;
10423                 ret = io_run_task_work_sig();
10424         } while (ret >= 0);
10425         mutex_lock(&ctx->uring_lock);
10426
10427         if (ret)
10428                 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10429         return ret;
10430 }
10431
10432 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10433                                void __user *arg, unsigned nr_args)
10434         __releases(ctx->uring_lock)
10435         __acquires(ctx->uring_lock)
10436 {
10437         int ret;
10438
10439         /*
10440          * We're inside the ring mutex, if the ref is already dying, then
10441          * someone else killed the ctx or is already going through
10442          * io_uring_register().
10443          */
10444         if (percpu_ref_is_dying(&ctx->refs))
10445                 return -ENXIO;
10446
10447         if (ctx->restricted) {
10448                 if (opcode >= IORING_REGISTER_LAST)
10449                         return -EINVAL;
10450                 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10451                 if (!test_bit(opcode, ctx->restrictions.register_op))
10452                         return -EACCES;
10453         }
10454
10455         if (io_register_op_must_quiesce(opcode)) {
10456                 ret = io_ctx_quiesce(ctx);
10457                 if (ret)
10458                         return ret;
10459         }
10460
10461         switch (opcode) {
10462         case IORING_REGISTER_BUFFERS:
10463                 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10464                 break;
10465         case IORING_UNREGISTER_BUFFERS:
10466                 ret = -EINVAL;
10467                 if (arg || nr_args)
10468                         break;
10469                 ret = io_sqe_buffers_unregister(ctx);
10470                 break;
10471         case IORING_REGISTER_FILES:
10472                 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10473                 break;
10474         case IORING_UNREGISTER_FILES:
10475                 ret = -EINVAL;
10476                 if (arg || nr_args)
10477                         break;
10478                 ret = io_sqe_files_unregister(ctx);
10479                 break;
10480         case IORING_REGISTER_FILES_UPDATE:
10481                 ret = io_register_files_update(ctx, arg, nr_args);
10482                 break;
10483         case IORING_REGISTER_EVENTFD:
10484         case IORING_REGISTER_EVENTFD_ASYNC:
10485                 ret = -EINVAL;
10486                 if (nr_args != 1)
10487                         break;
10488                 ret = io_eventfd_register(ctx, arg);
10489                 if (ret)
10490                         break;
10491                 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10492                         ctx->eventfd_async = 1;
10493                 else
10494                         ctx->eventfd_async = 0;
10495                 break;
10496         case IORING_UNREGISTER_EVENTFD:
10497                 ret = -EINVAL;
10498                 if (arg || nr_args)
10499                         break;
10500                 ret = io_eventfd_unregister(ctx);
10501                 break;
10502         case IORING_REGISTER_PROBE:
10503                 ret = -EINVAL;
10504                 if (!arg || nr_args > 256)
10505                         break;
10506                 ret = io_probe(ctx, arg, nr_args);
10507                 break;
10508         case IORING_REGISTER_PERSONALITY:
10509                 ret = -EINVAL;
10510                 if (arg || nr_args)
10511                         break;
10512                 ret = io_register_personality(ctx);
10513                 break;
10514         case IORING_UNREGISTER_PERSONALITY:
10515                 ret = -EINVAL;
10516                 if (arg)
10517                         break;
10518                 ret = io_unregister_personality(ctx, nr_args);
10519                 break;
10520         case IORING_REGISTER_ENABLE_RINGS:
10521                 ret = -EINVAL;
10522                 if (arg || nr_args)
10523                         break;
10524                 ret = io_register_enable_rings(ctx);
10525                 break;
10526         case IORING_REGISTER_RESTRICTIONS:
10527                 ret = io_register_restrictions(ctx, arg, nr_args);
10528                 break;
10529         case IORING_REGISTER_FILES2:
10530                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10531                 break;
10532         case IORING_REGISTER_FILES_UPDATE2:
10533                 ret = io_register_rsrc_update(ctx, arg, nr_args,
10534                                               IORING_RSRC_FILE);
10535                 break;
10536         case IORING_REGISTER_BUFFERS2:
10537                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10538                 break;
10539         case IORING_REGISTER_BUFFERS_UPDATE:
10540                 ret = io_register_rsrc_update(ctx, arg, nr_args,
10541                                               IORING_RSRC_BUFFER);
10542                 break;
10543         case IORING_REGISTER_IOWQ_AFF:
10544                 ret = -EINVAL;
10545                 if (!arg || !nr_args)
10546                         break;
10547                 ret = io_register_iowq_aff(ctx, arg, nr_args);
10548                 break;
10549         case IORING_UNREGISTER_IOWQ_AFF:
10550                 ret = -EINVAL;
10551                 if (arg || nr_args)
10552                         break;
10553                 ret = io_unregister_iowq_aff(ctx);
10554                 break;
10555         case IORING_REGISTER_IOWQ_MAX_WORKERS:
10556                 ret = -EINVAL;
10557                 if (!arg || nr_args != 2)
10558                         break;
10559                 ret = io_register_iowq_max_workers(ctx, arg);
10560                 break;
10561         default:
10562                 ret = -EINVAL;
10563                 break;
10564         }
10565
10566         if (io_register_op_must_quiesce(opcode)) {
10567                 /* bring the ctx back to life */
10568                 percpu_ref_reinit(&ctx->refs);
10569                 reinit_completion(&ctx->ref_comp);
10570         }
10571         return ret;
10572 }
10573
10574 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10575                 void __user *, arg, unsigned int, nr_args)
10576 {
10577         struct io_ring_ctx *ctx;
10578         long ret = -EBADF;
10579         struct fd f;
10580
10581         f = fdget(fd);
10582         if (!f.file)
10583                 return -EBADF;
10584
10585         ret = -EOPNOTSUPP;
10586         if (f.file->f_op != &io_uring_fops)
10587                 goto out_fput;
10588
10589         ctx = f.file->private_data;
10590
10591         io_run_task_work();
10592
10593         mutex_lock(&ctx->uring_lock);
10594         ret = __io_uring_register(ctx, opcode, arg, nr_args);
10595         mutex_unlock(&ctx->uring_lock);
10596         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10597                                                         ctx->cq_ev_fd != NULL, ret);
10598 out_fput:
10599         fdput(f);
10600         return ret;
10601 }
10602
10603 static int __init io_uring_init(void)
10604 {
10605 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10606         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10607         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10608 } while (0)
10609
10610 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10611         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10612         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10613         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
10614         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
10615         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
10616         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
10617         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
10618         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
10619         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
10620         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
10621         BUILD_BUG_SQE_ELEM(24, __u32,  len);
10622         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
10623         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
10624         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10625         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
10626         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
10627         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
10628         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
10629         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
10630         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
10631         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
10632         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
10633         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
10634         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
10635         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
10636         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
10637         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
10638         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
10639         BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
10640         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
10641         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
10642         BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
10643
10644         BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10645                      sizeof(struct io_uring_rsrc_update));
10646         BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10647                      sizeof(struct io_uring_rsrc_update2));
10648
10649         /* ->buf_index is u16 */
10650         BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
10651
10652         /* should fit into one byte */
10653         BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10654
10655         BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10656         BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10657
10658         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10659                                 SLAB_ACCOUNT);
10660         return 0;
10661 };
10662 __initcall(io_uring_init);