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