Merge tag 'cxl-for-5.15' of git://git.kernel.org/pub/scm/linux/kernel/git/cxl/cxl
[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                 .hash_reg_file          = 1,
1025                 .unbound_nonreg_file    = 1,
1026                 .pollout                = 1,
1027                 .plug                   = 1,
1028                 .async_size             = sizeof(struct io_async_rw),
1029         },
1030         [IORING_OP_FADVISE] = {
1031                 .needs_file             = 1,
1032         },
1033         [IORING_OP_MADVISE] = {},
1034         [IORING_OP_SEND] = {
1035                 .needs_file             = 1,
1036                 .unbound_nonreg_file    = 1,
1037                 .pollout                = 1,
1038         },
1039         [IORING_OP_RECV] = {
1040                 .needs_file             = 1,
1041                 .unbound_nonreg_file    = 1,
1042                 .pollin                 = 1,
1043                 .buffer_select          = 1,
1044         },
1045         [IORING_OP_OPENAT2] = {
1046         },
1047         [IORING_OP_EPOLL_CTL] = {
1048                 .unbound_nonreg_file    = 1,
1049         },
1050         [IORING_OP_SPLICE] = {
1051                 .needs_file             = 1,
1052                 .hash_reg_file          = 1,
1053                 .unbound_nonreg_file    = 1,
1054         },
1055         [IORING_OP_PROVIDE_BUFFERS] = {},
1056         [IORING_OP_REMOVE_BUFFERS] = {},
1057         [IORING_OP_TEE] = {
1058                 .needs_file             = 1,
1059                 .hash_reg_file          = 1,
1060                 .unbound_nonreg_file    = 1,
1061         },
1062         [IORING_OP_SHUTDOWN] = {
1063                 .needs_file             = 1,
1064         },
1065         [IORING_OP_RENAMEAT] = {},
1066         [IORING_OP_UNLINKAT] = {},
1067         [IORING_OP_MKDIRAT] = {},
1068         [IORING_OP_SYMLINKAT] = {},
1069         [IORING_OP_LINKAT] = {},
1070 };
1071
1072 /* requests with any of those set should undergo io_disarm_next() */
1073 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1074
1075 static bool io_disarm_next(struct io_kiocb *req);
1076 static void io_uring_del_tctx_node(unsigned long index);
1077 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1078                                          struct task_struct *task,
1079                                          bool cancel_all);
1080 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1081
1082 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1083                                  long res, unsigned int cflags);
1084 static void io_put_req(struct io_kiocb *req);
1085 static void io_put_req_deferred(struct io_kiocb *req);
1086 static void io_dismantle_req(struct io_kiocb *req);
1087 static void io_queue_linked_timeout(struct io_kiocb *req);
1088 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1089                                      struct io_uring_rsrc_update2 *up,
1090                                      unsigned nr_args);
1091 static void io_clean_op(struct io_kiocb *req);
1092 static struct file *io_file_get(struct io_ring_ctx *ctx,
1093                                 struct io_kiocb *req, int fd, bool fixed);
1094 static void __io_queue_sqe(struct io_kiocb *req);
1095 static void io_rsrc_put_work(struct work_struct *work);
1096
1097 static void io_req_task_queue(struct io_kiocb *req);
1098 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1099 static int io_req_prep_async(struct io_kiocb *req);
1100
1101 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1102                                  unsigned int issue_flags, u32 slot_index);
1103 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1104
1105 static struct kmem_cache *req_cachep;
1106
1107 static const struct file_operations io_uring_fops;
1108
1109 struct sock *io_uring_get_socket(struct file *file)
1110 {
1111 #if defined(CONFIG_UNIX)
1112         if (file->f_op == &io_uring_fops) {
1113                 struct io_ring_ctx *ctx = file->private_data;
1114
1115                 return ctx->ring_sock->sk;
1116         }
1117 #endif
1118         return NULL;
1119 }
1120 EXPORT_SYMBOL(io_uring_get_socket);
1121
1122 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1123 {
1124         if (!*locked) {
1125                 mutex_lock(&ctx->uring_lock);
1126                 *locked = true;
1127         }
1128 }
1129
1130 #define io_for_each_link(pos, head) \
1131         for (pos = (head); pos; pos = pos->link)
1132
1133 /*
1134  * Shamelessly stolen from the mm implementation of page reference checking,
1135  * see commit f958d7b528b1 for details.
1136  */
1137 #define req_ref_zero_or_close_to_overflow(req)  \
1138         ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1139
1140 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1141 {
1142         WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1143         return atomic_inc_not_zero(&req->refs);
1144 }
1145
1146 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1147 {
1148         if (likely(!(req->flags & REQ_F_REFCOUNT)))
1149                 return true;
1150
1151         WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1152         return atomic_dec_and_test(&req->refs);
1153 }
1154
1155 static inline void req_ref_put(struct io_kiocb *req)
1156 {
1157         WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1158         WARN_ON_ONCE(req_ref_put_and_test(req));
1159 }
1160
1161 static inline void req_ref_get(struct io_kiocb *req)
1162 {
1163         WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1164         WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1165         atomic_inc(&req->refs);
1166 }
1167
1168 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1169 {
1170         if (!(req->flags & REQ_F_REFCOUNT)) {
1171                 req->flags |= REQ_F_REFCOUNT;
1172                 atomic_set(&req->refs, nr);
1173         }
1174 }
1175
1176 static inline void io_req_set_refcount(struct io_kiocb *req)
1177 {
1178         __io_req_set_refcount(req, 1);
1179 }
1180
1181 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1182 {
1183         struct io_ring_ctx *ctx = req->ctx;
1184
1185         if (!req->fixed_rsrc_refs) {
1186                 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1187                 percpu_ref_get(req->fixed_rsrc_refs);
1188         }
1189 }
1190
1191 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1192 {
1193         bool got = percpu_ref_tryget(ref);
1194
1195         /* already at zero, wait for ->release() */
1196         if (!got)
1197                 wait_for_completion(compl);
1198         percpu_ref_resurrect(ref);
1199         if (got)
1200                 percpu_ref_put(ref);
1201 }
1202
1203 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1204                           bool cancel_all)
1205 {
1206         struct io_kiocb *req;
1207
1208         if (task && head->task != task)
1209                 return false;
1210         if (cancel_all)
1211                 return true;
1212
1213         io_for_each_link(req, head) {
1214                 if (req->flags & REQ_F_INFLIGHT)
1215                         return true;
1216         }
1217         return false;
1218 }
1219
1220 static inline void req_set_fail(struct io_kiocb *req)
1221 {
1222         req->flags |= REQ_F_FAIL;
1223 }
1224
1225 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1226 {
1227         req_set_fail(req);
1228         req->result = res;
1229 }
1230
1231 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1232 {
1233         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1234
1235         complete(&ctx->ref_comp);
1236 }
1237
1238 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1239 {
1240         return !req->timeout.off;
1241 }
1242
1243 static void io_fallback_req_func(struct work_struct *work)
1244 {
1245         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1246                                                 fallback_work.work);
1247         struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1248         struct io_kiocb *req, *tmp;
1249         bool locked = false;
1250
1251         percpu_ref_get(&ctx->refs);
1252         llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1253                 req->io_task_work.func(req, &locked);
1254
1255         if (locked) {
1256                 if (ctx->submit_state.compl_nr)
1257                         io_submit_flush_completions(ctx);
1258                 mutex_unlock(&ctx->uring_lock);
1259         }
1260         percpu_ref_put(&ctx->refs);
1261
1262 }
1263
1264 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1265 {
1266         struct io_ring_ctx *ctx;
1267         int hash_bits;
1268
1269         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1270         if (!ctx)
1271                 return NULL;
1272
1273         /*
1274          * Use 5 bits less than the max cq entries, that should give us around
1275          * 32 entries per hash list if totally full and uniformly spread.
1276          */
1277         hash_bits = ilog2(p->cq_entries);
1278         hash_bits -= 5;
1279         if (hash_bits <= 0)
1280                 hash_bits = 1;
1281         ctx->cancel_hash_bits = hash_bits;
1282         ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1283                                         GFP_KERNEL);
1284         if (!ctx->cancel_hash)
1285                 goto err;
1286         __hash_init(ctx->cancel_hash, 1U << hash_bits);
1287
1288         ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1289         if (!ctx->dummy_ubuf)
1290                 goto err;
1291         /* set invalid range, so io_import_fixed() fails meeting it */
1292         ctx->dummy_ubuf->ubuf = -1UL;
1293
1294         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1295                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1296                 goto err;
1297
1298         ctx->flags = p->flags;
1299         init_waitqueue_head(&ctx->sqo_sq_wait);
1300         INIT_LIST_HEAD(&ctx->sqd_list);
1301         init_waitqueue_head(&ctx->poll_wait);
1302         INIT_LIST_HEAD(&ctx->cq_overflow_list);
1303         init_completion(&ctx->ref_comp);
1304         xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1305         xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1306         mutex_init(&ctx->uring_lock);
1307         init_waitqueue_head(&ctx->cq_wait);
1308         spin_lock_init(&ctx->completion_lock);
1309         spin_lock_init(&ctx->timeout_lock);
1310         INIT_LIST_HEAD(&ctx->iopoll_list);
1311         INIT_LIST_HEAD(&ctx->defer_list);
1312         INIT_LIST_HEAD(&ctx->timeout_list);
1313         INIT_LIST_HEAD(&ctx->ltimeout_list);
1314         spin_lock_init(&ctx->rsrc_ref_lock);
1315         INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1316         INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1317         init_llist_head(&ctx->rsrc_put_llist);
1318         INIT_LIST_HEAD(&ctx->tctx_list);
1319         INIT_LIST_HEAD(&ctx->submit_state.free_list);
1320         INIT_LIST_HEAD(&ctx->locked_free_list);
1321         INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1322         return ctx;
1323 err:
1324         kfree(ctx->dummy_ubuf);
1325         kfree(ctx->cancel_hash);
1326         kfree(ctx);
1327         return NULL;
1328 }
1329
1330 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1331 {
1332         struct io_rings *r = ctx->rings;
1333
1334         WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1335         ctx->cq_extra--;
1336 }
1337
1338 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1339 {
1340         if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1341                 struct io_ring_ctx *ctx = req->ctx;
1342
1343                 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1344         }
1345
1346         return false;
1347 }
1348
1349 #define FFS_ASYNC_READ          0x1UL
1350 #define FFS_ASYNC_WRITE         0x2UL
1351 #ifdef CONFIG_64BIT
1352 #define FFS_ISREG               0x4UL
1353 #else
1354 #define FFS_ISREG               0x0UL
1355 #endif
1356 #define FFS_MASK                ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1357
1358 static inline bool io_req_ffs_set(struct io_kiocb *req)
1359 {
1360         return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1361 }
1362
1363 static void io_req_track_inflight(struct io_kiocb *req)
1364 {
1365         if (!(req->flags & REQ_F_INFLIGHT)) {
1366                 req->flags |= REQ_F_INFLIGHT;
1367                 atomic_inc(&current->io_uring->inflight_tracked);
1368         }
1369 }
1370
1371 static inline void io_unprep_linked_timeout(struct io_kiocb *req)
1372 {
1373         req->flags &= ~REQ_F_LINK_TIMEOUT;
1374 }
1375
1376 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1377 {
1378         if (WARN_ON_ONCE(!req->link))
1379                 return NULL;
1380
1381         req->flags &= ~REQ_F_ARM_LTIMEOUT;
1382         req->flags |= REQ_F_LINK_TIMEOUT;
1383
1384         /* linked timeouts should have two refs once prep'ed */
1385         io_req_set_refcount(req);
1386         __io_req_set_refcount(req->link, 2);
1387         return req->link;
1388 }
1389
1390 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1391 {
1392         if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1393                 return NULL;
1394         return __io_prep_linked_timeout(req);
1395 }
1396
1397 static void io_prep_async_work(struct io_kiocb *req)
1398 {
1399         const struct io_op_def *def = &io_op_defs[req->opcode];
1400         struct io_ring_ctx *ctx = req->ctx;
1401
1402         if (!(req->flags & REQ_F_CREDS)) {
1403                 req->flags |= REQ_F_CREDS;
1404                 req->creds = get_current_cred();
1405         }
1406
1407         req->work.list.next = NULL;
1408         req->work.flags = 0;
1409         if (req->flags & REQ_F_FORCE_ASYNC)
1410                 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1411
1412         if (req->flags & REQ_F_ISREG) {
1413                 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1414                         io_wq_hash_work(&req->work, file_inode(req->file));
1415         } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1416                 if (def->unbound_nonreg_file)
1417                         req->work.flags |= IO_WQ_WORK_UNBOUND;
1418         }
1419
1420         switch (req->opcode) {
1421         case IORING_OP_SPLICE:
1422         case IORING_OP_TEE:
1423                 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1424                         req->work.flags |= IO_WQ_WORK_UNBOUND;
1425                 break;
1426         }
1427 }
1428
1429 static void io_prep_async_link(struct io_kiocb *req)
1430 {
1431         struct io_kiocb *cur;
1432
1433         if (req->flags & REQ_F_LINK_TIMEOUT) {
1434                 struct io_ring_ctx *ctx = req->ctx;
1435
1436                 spin_lock(&ctx->completion_lock);
1437                 io_for_each_link(cur, req)
1438                         io_prep_async_work(cur);
1439                 spin_unlock(&ctx->completion_lock);
1440         } else {
1441                 io_for_each_link(cur, req)
1442                         io_prep_async_work(cur);
1443         }
1444 }
1445
1446 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1447 {
1448         struct io_ring_ctx *ctx = req->ctx;
1449         struct io_kiocb *link = io_prep_linked_timeout(req);
1450         struct io_uring_task *tctx = req->task->io_uring;
1451
1452         /* must not take the lock, NULL it as a precaution */
1453         locked = NULL;
1454
1455         BUG_ON(!tctx);
1456         BUG_ON(!tctx->io_wq);
1457
1458         /* init ->work of the whole link before punting */
1459         io_prep_async_link(req);
1460
1461         /*
1462          * Not expected to happen, but if we do have a bug where this _can_
1463          * happen, catch it here and ensure the request is marked as
1464          * canceled. That will make io-wq go through the usual work cancel
1465          * procedure rather than attempt to run this request (or create a new
1466          * worker for it).
1467          */
1468         if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1469                 req->work.flags |= IO_WQ_WORK_CANCEL;
1470
1471         trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1472                                         &req->work, req->flags);
1473         io_wq_enqueue(tctx->io_wq, &req->work);
1474         if (link)
1475                 io_queue_linked_timeout(link);
1476 }
1477
1478 static void io_kill_timeout(struct io_kiocb *req, int status)
1479         __must_hold(&req->ctx->completion_lock)
1480         __must_hold(&req->ctx->timeout_lock)
1481 {
1482         struct io_timeout_data *io = req->async_data;
1483
1484         if (hrtimer_try_to_cancel(&io->timer) != -1) {
1485                 atomic_set(&req->ctx->cq_timeouts,
1486                         atomic_read(&req->ctx->cq_timeouts) + 1);
1487                 list_del_init(&req->timeout.list);
1488                 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1489                 io_put_req_deferred(req);
1490         }
1491 }
1492
1493 static void io_queue_deferred(struct io_ring_ctx *ctx)
1494 {
1495         while (!list_empty(&ctx->defer_list)) {
1496                 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1497                                                 struct io_defer_entry, list);
1498
1499                 if (req_need_defer(de->req, de->seq))
1500                         break;
1501                 list_del_init(&de->list);
1502                 io_req_task_queue(de->req);
1503                 kfree(de);
1504         }
1505 }
1506
1507 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1508         __must_hold(&ctx->completion_lock)
1509 {
1510         u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1511
1512         spin_lock_irq(&ctx->timeout_lock);
1513         while (!list_empty(&ctx->timeout_list)) {
1514                 u32 events_needed, events_got;
1515                 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1516                                                 struct io_kiocb, timeout.list);
1517
1518                 if (io_is_timeout_noseq(req))
1519                         break;
1520
1521                 /*
1522                  * Since seq can easily wrap around over time, subtract
1523                  * the last seq at which timeouts were flushed before comparing.
1524                  * Assuming not more than 2^31-1 events have happened since,
1525                  * these subtractions won't have wrapped, so we can check if
1526                  * target is in [last_seq, current_seq] by comparing the two.
1527                  */
1528                 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1529                 events_got = seq - ctx->cq_last_tm_flush;
1530                 if (events_got < events_needed)
1531                         break;
1532
1533                 list_del_init(&req->timeout.list);
1534                 io_kill_timeout(req, 0);
1535         }
1536         ctx->cq_last_tm_flush = seq;
1537         spin_unlock_irq(&ctx->timeout_lock);
1538 }
1539
1540 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1541 {
1542         if (ctx->off_timeout_used)
1543                 io_flush_timeouts(ctx);
1544         if (ctx->drain_active)
1545                 io_queue_deferred(ctx);
1546 }
1547
1548 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1549 {
1550         if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1551                 __io_commit_cqring_flush(ctx);
1552         /* order cqe stores with ring update */
1553         smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1554 }
1555
1556 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1557 {
1558         struct io_rings *r = ctx->rings;
1559
1560         return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1561 }
1562
1563 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1564 {
1565         return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1566 }
1567
1568 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1569 {
1570         struct io_rings *rings = ctx->rings;
1571         unsigned tail, mask = ctx->cq_entries - 1;
1572
1573         /*
1574          * writes to the cq entry need to come after reading head; the
1575          * control dependency is enough as we're using WRITE_ONCE to
1576          * fill the cq entry
1577          */
1578         if (__io_cqring_events(ctx) == ctx->cq_entries)
1579                 return NULL;
1580
1581         tail = ctx->cached_cq_tail++;
1582         return &rings->cqes[tail & mask];
1583 }
1584
1585 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1586 {
1587         if (likely(!ctx->cq_ev_fd))
1588                 return false;
1589         if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1590                 return false;
1591         return !ctx->eventfd_async || io_wq_current_is_worker();
1592 }
1593
1594 /*
1595  * This should only get called when at least one event has been posted.
1596  * Some applications rely on the eventfd notification count only changing
1597  * IFF a new CQE has been added to the CQ ring. There's no depedency on
1598  * 1:1 relationship between how many times this function is called (and
1599  * hence the eventfd count) and number of CQEs posted to the CQ ring.
1600  */
1601 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1602 {
1603         /*
1604          * wake_up_all() may seem excessive, but io_wake_function() and
1605          * io_should_wake() handle the termination of the loop and only
1606          * wake as many waiters as we need to.
1607          */
1608         if (wq_has_sleeper(&ctx->cq_wait))
1609                 wake_up_all(&ctx->cq_wait);
1610         if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1611                 wake_up(&ctx->sq_data->wait);
1612         if (io_should_trigger_evfd(ctx))
1613                 eventfd_signal(ctx->cq_ev_fd, 1);
1614         if (waitqueue_active(&ctx->poll_wait)) {
1615                 wake_up_interruptible(&ctx->poll_wait);
1616                 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1617         }
1618 }
1619
1620 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1621 {
1622         if (ctx->flags & IORING_SETUP_SQPOLL) {
1623                 if (wq_has_sleeper(&ctx->cq_wait))
1624                         wake_up_all(&ctx->cq_wait);
1625         }
1626         if (io_should_trigger_evfd(ctx))
1627                 eventfd_signal(ctx->cq_ev_fd, 1);
1628         if (waitqueue_active(&ctx->poll_wait)) {
1629                 wake_up_interruptible(&ctx->poll_wait);
1630                 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1631         }
1632 }
1633
1634 /* Returns true if there are no backlogged entries after the flush */
1635 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1636 {
1637         bool all_flushed, posted;
1638
1639         if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1640                 return false;
1641
1642         posted = false;
1643         spin_lock(&ctx->completion_lock);
1644         while (!list_empty(&ctx->cq_overflow_list)) {
1645                 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1646                 struct io_overflow_cqe *ocqe;
1647
1648                 if (!cqe && !force)
1649                         break;
1650                 ocqe = list_first_entry(&ctx->cq_overflow_list,
1651                                         struct io_overflow_cqe, list);
1652                 if (cqe)
1653                         memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1654                 else
1655                         io_account_cq_overflow(ctx);
1656
1657                 posted = true;
1658                 list_del(&ocqe->list);
1659                 kfree(ocqe);
1660         }
1661
1662         all_flushed = list_empty(&ctx->cq_overflow_list);
1663         if (all_flushed) {
1664                 clear_bit(0, &ctx->check_cq_overflow);
1665                 WRITE_ONCE(ctx->rings->sq_flags,
1666                            ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1667         }
1668
1669         if (posted)
1670                 io_commit_cqring(ctx);
1671         spin_unlock(&ctx->completion_lock);
1672         if (posted)
1673                 io_cqring_ev_posted(ctx);
1674         return all_flushed;
1675 }
1676
1677 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1678 {
1679         bool ret = true;
1680
1681         if (test_bit(0, &ctx->check_cq_overflow)) {
1682                 /* iopoll syncs against uring_lock, not completion_lock */
1683                 if (ctx->flags & IORING_SETUP_IOPOLL)
1684                         mutex_lock(&ctx->uring_lock);
1685                 ret = __io_cqring_overflow_flush(ctx, false);
1686                 if (ctx->flags & IORING_SETUP_IOPOLL)
1687                         mutex_unlock(&ctx->uring_lock);
1688         }
1689
1690         return ret;
1691 }
1692
1693 /* must to be called somewhat shortly after putting a request */
1694 static inline void io_put_task(struct task_struct *task, int nr)
1695 {
1696         struct io_uring_task *tctx = task->io_uring;
1697
1698         if (likely(task == current)) {
1699                 tctx->cached_refs += nr;
1700         } else {
1701                 percpu_counter_sub(&tctx->inflight, nr);
1702                 if (unlikely(atomic_read(&tctx->in_idle)))
1703                         wake_up(&tctx->wait);
1704                 put_task_struct_many(task, nr);
1705         }
1706 }
1707
1708 static void io_task_refs_refill(struct io_uring_task *tctx)
1709 {
1710         unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1711
1712         percpu_counter_add(&tctx->inflight, refill);
1713         refcount_add(refill, &current->usage);
1714         tctx->cached_refs += refill;
1715 }
1716
1717 static inline void io_get_task_refs(int nr)
1718 {
1719         struct io_uring_task *tctx = current->io_uring;
1720
1721         tctx->cached_refs -= nr;
1722         if (unlikely(tctx->cached_refs < 0))
1723                 io_task_refs_refill(tctx);
1724 }
1725
1726 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1727                                      long res, unsigned int cflags)
1728 {
1729         struct io_overflow_cqe *ocqe;
1730
1731         ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1732         if (!ocqe) {
1733                 /*
1734                  * If we're in ring overflow flush mode, or in task cancel mode,
1735                  * or cannot allocate an overflow entry, then we need to drop it
1736                  * on the floor.
1737                  */
1738                 io_account_cq_overflow(ctx);
1739                 return false;
1740         }
1741         if (list_empty(&ctx->cq_overflow_list)) {
1742                 set_bit(0, &ctx->check_cq_overflow);
1743                 WRITE_ONCE(ctx->rings->sq_flags,
1744                            ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1745
1746         }
1747         ocqe->cqe.user_data = user_data;
1748         ocqe->cqe.res = res;
1749         ocqe->cqe.flags = cflags;
1750         list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1751         return true;
1752 }
1753
1754 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1755                                           long res, unsigned int cflags)
1756 {
1757         struct io_uring_cqe *cqe;
1758
1759         trace_io_uring_complete(ctx, user_data, res, cflags);
1760
1761         /*
1762          * If we can't get a cq entry, userspace overflowed the
1763          * submission (by quite a lot). Increment the overflow count in
1764          * the ring.
1765          */
1766         cqe = io_get_cqe(ctx);
1767         if (likely(cqe)) {
1768                 WRITE_ONCE(cqe->user_data, user_data);
1769                 WRITE_ONCE(cqe->res, res);
1770                 WRITE_ONCE(cqe->flags, cflags);
1771                 return true;
1772         }
1773         return io_cqring_event_overflow(ctx, user_data, res, cflags);
1774 }
1775
1776 /* not as hot to bloat with inlining */
1777 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1778                                           long res, unsigned int cflags)
1779 {
1780         return __io_cqring_fill_event(ctx, user_data, res, cflags);
1781 }
1782
1783 static void io_req_complete_post(struct io_kiocb *req, long res,
1784                                  unsigned int cflags)
1785 {
1786         struct io_ring_ctx *ctx = req->ctx;
1787
1788         spin_lock(&ctx->completion_lock);
1789         __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1790         /*
1791          * If we're the last reference to this request, add to our locked
1792          * free_list cache.
1793          */
1794         if (req_ref_put_and_test(req)) {
1795                 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1796                         if (req->flags & IO_DISARM_MASK)
1797                                 io_disarm_next(req);
1798                         if (req->link) {
1799                                 io_req_task_queue(req->link);
1800                                 req->link = NULL;
1801                         }
1802                 }
1803                 io_dismantle_req(req);
1804                 io_put_task(req->task, 1);
1805                 list_add(&req->inflight_entry, &ctx->locked_free_list);
1806                 ctx->locked_free_nr++;
1807         } else {
1808                 if (!percpu_ref_tryget(&ctx->refs))
1809                         req = NULL;
1810         }
1811         io_commit_cqring(ctx);
1812         spin_unlock(&ctx->completion_lock);
1813
1814         if (req) {
1815                 io_cqring_ev_posted(ctx);
1816                 percpu_ref_put(&ctx->refs);
1817         }
1818 }
1819
1820 static inline bool io_req_needs_clean(struct io_kiocb *req)
1821 {
1822         return req->flags & IO_REQ_CLEAN_FLAGS;
1823 }
1824
1825 static void io_req_complete_state(struct io_kiocb *req, long res,
1826                                   unsigned int cflags)
1827 {
1828         if (io_req_needs_clean(req))
1829                 io_clean_op(req);
1830         req->result = res;
1831         req->compl.cflags = cflags;
1832         req->flags |= REQ_F_COMPLETE_INLINE;
1833 }
1834
1835 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1836                                      long res, unsigned cflags)
1837 {
1838         if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1839                 io_req_complete_state(req, res, cflags);
1840         else
1841                 io_req_complete_post(req, res, cflags);
1842 }
1843
1844 static inline void io_req_complete(struct io_kiocb *req, long res)
1845 {
1846         __io_req_complete(req, 0, res, 0);
1847 }
1848
1849 static void io_req_complete_failed(struct io_kiocb *req, long res)
1850 {
1851         req_set_fail(req);
1852         io_req_complete_post(req, res, 0);
1853 }
1854
1855 static void io_req_complete_fail_submit(struct io_kiocb *req)
1856 {
1857         /*
1858          * We don't submit, fail them all, for that replace hardlinks with
1859          * normal links. Extra REQ_F_LINK is tolerated.
1860          */
1861         req->flags &= ~REQ_F_HARDLINK;
1862         req->flags |= REQ_F_LINK;
1863         io_req_complete_failed(req, req->result);
1864 }
1865
1866 /*
1867  * Don't initialise the fields below on every allocation, but do that in
1868  * advance and keep them valid across allocations.
1869  */
1870 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1871 {
1872         req->ctx = ctx;
1873         req->link = NULL;
1874         req->async_data = NULL;
1875         /* not necessary, but safer to zero */
1876         req->result = 0;
1877 }
1878
1879 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1880                                         struct io_submit_state *state)
1881 {
1882         spin_lock(&ctx->completion_lock);
1883         list_splice_init(&ctx->locked_free_list, &state->free_list);
1884         ctx->locked_free_nr = 0;
1885         spin_unlock(&ctx->completion_lock);
1886 }
1887
1888 /* Returns true IFF there are requests in the cache */
1889 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1890 {
1891         struct io_submit_state *state = &ctx->submit_state;
1892         int nr;
1893
1894         /*
1895          * If we have more than a batch's worth of requests in our IRQ side
1896          * locked cache, grab the lock and move them over to our submission
1897          * side cache.
1898          */
1899         if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1900                 io_flush_cached_locked_reqs(ctx, state);
1901
1902         nr = state->free_reqs;
1903         while (!list_empty(&state->free_list)) {
1904                 struct io_kiocb *req = list_first_entry(&state->free_list,
1905                                         struct io_kiocb, inflight_entry);
1906
1907                 list_del(&req->inflight_entry);
1908                 state->reqs[nr++] = req;
1909                 if (nr == ARRAY_SIZE(state->reqs))
1910                         break;
1911         }
1912
1913         state->free_reqs = nr;
1914         return nr != 0;
1915 }
1916
1917 /*
1918  * A request might get retired back into the request caches even before opcode
1919  * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1920  * Because of that, io_alloc_req() should be called only under ->uring_lock
1921  * and with extra caution to not get a request that is still worked on.
1922  */
1923 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1924         __must_hold(&ctx->uring_lock)
1925 {
1926         struct io_submit_state *state = &ctx->submit_state;
1927         gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1928         int ret, i;
1929
1930         BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1931
1932         if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1933                 goto got_req;
1934
1935         ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1936                                     state->reqs);
1937
1938         /*
1939          * Bulk alloc is all-or-nothing. If we fail to get a batch,
1940          * retry single alloc to be on the safe side.
1941          */
1942         if (unlikely(ret <= 0)) {
1943                 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1944                 if (!state->reqs[0])
1945                         return NULL;
1946                 ret = 1;
1947         }
1948
1949         for (i = 0; i < ret; i++)
1950                 io_preinit_req(state->reqs[i], ctx);
1951         state->free_reqs = ret;
1952 got_req:
1953         state->free_reqs--;
1954         return state->reqs[state->free_reqs];
1955 }
1956
1957 static inline void io_put_file(struct file *file)
1958 {
1959         if (file)
1960                 fput(file);
1961 }
1962
1963 static void io_dismantle_req(struct io_kiocb *req)
1964 {
1965         unsigned int flags = req->flags;
1966
1967         if (io_req_needs_clean(req))
1968                 io_clean_op(req);
1969         if (!(flags & REQ_F_FIXED_FILE))
1970                 io_put_file(req->file);
1971         if (req->fixed_rsrc_refs)
1972                 percpu_ref_put(req->fixed_rsrc_refs);
1973         if (req->async_data) {
1974                 kfree(req->async_data);
1975                 req->async_data = NULL;
1976         }
1977 }
1978
1979 static void __io_free_req(struct io_kiocb *req)
1980 {
1981         struct io_ring_ctx *ctx = req->ctx;
1982
1983         io_dismantle_req(req);
1984         io_put_task(req->task, 1);
1985
1986         spin_lock(&ctx->completion_lock);
1987         list_add(&req->inflight_entry, &ctx->locked_free_list);
1988         ctx->locked_free_nr++;
1989         spin_unlock(&ctx->completion_lock);
1990
1991         percpu_ref_put(&ctx->refs);
1992 }
1993
1994 static inline void io_remove_next_linked(struct io_kiocb *req)
1995 {
1996         struct io_kiocb *nxt = req->link;
1997
1998         req->link = nxt->link;
1999         nxt->link = NULL;
2000 }
2001
2002 static bool io_kill_linked_timeout(struct io_kiocb *req)
2003         __must_hold(&req->ctx->completion_lock)
2004         __must_hold(&req->ctx->timeout_lock)
2005 {
2006         struct io_kiocb *link = req->link;
2007
2008         if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2009                 struct io_timeout_data *io = link->async_data;
2010
2011                 io_remove_next_linked(req);
2012                 link->timeout.head = NULL;
2013                 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2014                         list_del(&link->timeout.list);
2015                         io_cqring_fill_event(link->ctx, link->user_data,
2016                                              -ECANCELED, 0);
2017                         io_put_req_deferred(link);
2018                         return true;
2019                 }
2020         }
2021         return false;
2022 }
2023
2024 static void io_fail_links(struct io_kiocb *req)
2025         __must_hold(&req->ctx->completion_lock)
2026 {
2027         struct io_kiocb *nxt, *link = req->link;
2028
2029         req->link = NULL;
2030         while (link) {
2031                 long res = -ECANCELED;
2032
2033                 if (link->flags & REQ_F_FAIL)
2034                         res = link->result;
2035
2036                 nxt = link->link;
2037                 link->link = NULL;
2038
2039                 trace_io_uring_fail_link(req, link);
2040                 io_cqring_fill_event(link->ctx, link->user_data, res, 0);
2041                 io_put_req_deferred(link);
2042                 link = nxt;
2043         }
2044 }
2045
2046 static bool io_disarm_next(struct io_kiocb *req)
2047         __must_hold(&req->ctx->completion_lock)
2048 {
2049         bool posted = false;
2050
2051         if (req->flags & REQ_F_ARM_LTIMEOUT) {
2052                 struct io_kiocb *link = req->link;
2053
2054                 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2055                 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2056                         io_remove_next_linked(req);
2057                         io_cqring_fill_event(link->ctx, link->user_data,
2058                                              -ECANCELED, 0);
2059                         io_put_req_deferred(link);
2060                         posted = true;
2061                 }
2062         } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2063                 struct io_ring_ctx *ctx = req->ctx;
2064
2065                 spin_lock_irq(&ctx->timeout_lock);
2066                 posted = io_kill_linked_timeout(req);
2067                 spin_unlock_irq(&ctx->timeout_lock);
2068         }
2069         if (unlikely((req->flags & REQ_F_FAIL) &&
2070                      !(req->flags & REQ_F_HARDLINK))) {
2071                 posted |= (req->link != NULL);
2072                 io_fail_links(req);
2073         }
2074         return posted;
2075 }
2076
2077 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2078 {
2079         struct io_kiocb *nxt;
2080
2081         /*
2082          * If LINK is set, we have dependent requests in this chain. If we
2083          * didn't fail this request, queue the first one up, moving any other
2084          * dependencies to the next request. In case of failure, fail the rest
2085          * of the chain.
2086          */
2087         if (req->flags & IO_DISARM_MASK) {
2088                 struct io_ring_ctx *ctx = req->ctx;
2089                 bool posted;
2090
2091                 spin_lock(&ctx->completion_lock);
2092                 posted = io_disarm_next(req);
2093                 if (posted)
2094                         io_commit_cqring(req->ctx);
2095                 spin_unlock(&ctx->completion_lock);
2096                 if (posted)
2097                         io_cqring_ev_posted(ctx);
2098         }
2099         nxt = req->link;
2100         req->link = NULL;
2101         return nxt;
2102 }
2103
2104 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2105 {
2106         if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2107                 return NULL;
2108         return __io_req_find_next(req);
2109 }
2110
2111 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2112 {
2113         if (!ctx)
2114                 return;
2115         if (*locked) {
2116                 if (ctx->submit_state.compl_nr)
2117                         io_submit_flush_completions(ctx);
2118                 mutex_unlock(&ctx->uring_lock);
2119                 *locked = false;
2120         }
2121         percpu_ref_put(&ctx->refs);
2122 }
2123
2124 static void tctx_task_work(struct callback_head *cb)
2125 {
2126         bool locked = false;
2127         struct io_ring_ctx *ctx = NULL;
2128         struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2129                                                   task_work);
2130
2131         while (1) {
2132                 struct io_wq_work_node *node;
2133
2134                 if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
2135                         io_submit_flush_completions(ctx);
2136
2137                 spin_lock_irq(&tctx->task_lock);
2138                 node = tctx->task_list.first;
2139                 INIT_WQ_LIST(&tctx->task_list);
2140                 if (!node)
2141                         tctx->task_running = false;
2142                 spin_unlock_irq(&tctx->task_lock);
2143                 if (!node)
2144                         break;
2145
2146                 do {
2147                         struct io_wq_work_node *next = node->next;
2148                         struct io_kiocb *req = container_of(node, struct io_kiocb,
2149                                                             io_task_work.node);
2150
2151                         if (req->ctx != ctx) {
2152                                 ctx_flush_and_put(ctx, &locked);
2153                                 ctx = req->ctx;
2154                                 /* if not contended, grab and improve batching */
2155                                 locked = mutex_trylock(&ctx->uring_lock);
2156                                 percpu_ref_get(&ctx->refs);
2157                         }
2158                         req->io_task_work.func(req, &locked);
2159                         node = next;
2160                 } while (node);
2161
2162                 cond_resched();
2163         }
2164
2165         ctx_flush_and_put(ctx, &locked);
2166 }
2167
2168 static void io_req_task_work_add(struct io_kiocb *req)
2169 {
2170         struct task_struct *tsk = req->task;
2171         struct io_uring_task *tctx = tsk->io_uring;
2172         enum task_work_notify_mode notify;
2173         struct io_wq_work_node *node;
2174         unsigned long flags;
2175         bool running;
2176
2177         WARN_ON_ONCE(!tctx);
2178
2179         spin_lock_irqsave(&tctx->task_lock, flags);
2180         wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2181         running = tctx->task_running;
2182         if (!running)
2183                 tctx->task_running = true;
2184         spin_unlock_irqrestore(&tctx->task_lock, flags);
2185
2186         /* task_work already pending, we're done */
2187         if (running)
2188                 return;
2189
2190         /*
2191          * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2192          * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2193          * processing task_work. There's no reliable way to tell if TWA_RESUME
2194          * will do the job.
2195          */
2196         notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2197         if (!task_work_add(tsk, &tctx->task_work, notify)) {
2198                 wake_up_process(tsk);
2199                 return;
2200         }
2201
2202         spin_lock_irqsave(&tctx->task_lock, flags);
2203         tctx->task_running = false;
2204         node = tctx->task_list.first;
2205         INIT_WQ_LIST(&tctx->task_list);
2206         spin_unlock_irqrestore(&tctx->task_lock, flags);
2207
2208         while (node) {
2209                 req = container_of(node, struct io_kiocb, io_task_work.node);
2210                 node = node->next;
2211                 if (llist_add(&req->io_task_work.fallback_node,
2212                               &req->ctx->fallback_llist))
2213                         schedule_delayed_work(&req->ctx->fallback_work, 1);
2214         }
2215 }
2216
2217 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2218 {
2219         struct io_ring_ctx *ctx = req->ctx;
2220
2221         /* not needed for normal modes, but SQPOLL depends on it */
2222         io_tw_lock(ctx, locked);
2223         io_req_complete_failed(req, req->result);
2224 }
2225
2226 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2227 {
2228         struct io_ring_ctx *ctx = req->ctx;
2229
2230         io_tw_lock(ctx, locked);
2231         /* req->task == current here, checking PF_EXITING is safe */
2232         if (likely(!(req->task->flags & PF_EXITING)))
2233                 __io_queue_sqe(req);
2234         else
2235                 io_req_complete_failed(req, -EFAULT);
2236 }
2237
2238 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2239 {
2240         req->result = ret;
2241         req->io_task_work.func = io_req_task_cancel;
2242         io_req_task_work_add(req);
2243 }
2244
2245 static void io_req_task_queue(struct io_kiocb *req)
2246 {
2247         req->io_task_work.func = io_req_task_submit;
2248         io_req_task_work_add(req);
2249 }
2250
2251 static void io_req_task_queue_reissue(struct io_kiocb *req)
2252 {
2253         req->io_task_work.func = io_queue_async_work;
2254         io_req_task_work_add(req);
2255 }
2256
2257 static inline void io_queue_next(struct io_kiocb *req)
2258 {
2259         struct io_kiocb *nxt = io_req_find_next(req);
2260
2261         if (nxt)
2262                 io_req_task_queue(nxt);
2263 }
2264
2265 static void io_free_req(struct io_kiocb *req)
2266 {
2267         io_queue_next(req);
2268         __io_free_req(req);
2269 }
2270
2271 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2272 {
2273         io_free_req(req);
2274 }
2275
2276 struct req_batch {
2277         struct task_struct      *task;
2278         int                     task_refs;
2279         int                     ctx_refs;
2280 };
2281
2282 static inline void io_init_req_batch(struct req_batch *rb)
2283 {
2284         rb->task_refs = 0;
2285         rb->ctx_refs = 0;
2286         rb->task = NULL;
2287 }
2288
2289 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2290                                      struct req_batch *rb)
2291 {
2292         if (rb->ctx_refs)
2293                 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2294         if (rb->task)
2295                 io_put_task(rb->task, rb->task_refs);
2296 }
2297
2298 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2299                               struct io_submit_state *state)
2300 {
2301         io_queue_next(req);
2302         io_dismantle_req(req);
2303
2304         if (req->task != rb->task) {
2305                 if (rb->task)
2306                         io_put_task(rb->task, rb->task_refs);
2307                 rb->task = req->task;
2308                 rb->task_refs = 0;
2309         }
2310         rb->task_refs++;
2311         rb->ctx_refs++;
2312
2313         if (state->free_reqs != ARRAY_SIZE(state->reqs))
2314                 state->reqs[state->free_reqs++] = req;
2315         else
2316                 list_add(&req->inflight_entry, &state->free_list);
2317 }
2318
2319 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2320         __must_hold(&ctx->uring_lock)
2321 {
2322         struct io_submit_state *state = &ctx->submit_state;
2323         int i, nr = state->compl_nr;
2324         struct req_batch rb;
2325
2326         spin_lock(&ctx->completion_lock);
2327         for (i = 0; i < nr; i++) {
2328                 struct io_kiocb *req = state->compl_reqs[i];
2329
2330                 __io_cqring_fill_event(ctx, req->user_data, req->result,
2331                                         req->compl.cflags);
2332         }
2333         io_commit_cqring(ctx);
2334         spin_unlock(&ctx->completion_lock);
2335         io_cqring_ev_posted(ctx);
2336
2337         io_init_req_batch(&rb);
2338         for (i = 0; i < nr; i++) {
2339                 struct io_kiocb *req = state->compl_reqs[i];
2340
2341                 if (req_ref_put_and_test(req))
2342                         io_req_free_batch(&rb, req, &ctx->submit_state);
2343         }
2344
2345         io_req_free_batch_finish(ctx, &rb);
2346         state->compl_nr = 0;
2347 }
2348
2349 /*
2350  * Drop reference to request, return next in chain (if there is one) if this
2351  * was the last reference to this request.
2352  */
2353 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2354 {
2355         struct io_kiocb *nxt = NULL;
2356
2357         if (req_ref_put_and_test(req)) {
2358                 nxt = io_req_find_next(req);
2359                 __io_free_req(req);
2360         }
2361         return nxt;
2362 }
2363
2364 static inline void io_put_req(struct io_kiocb *req)
2365 {
2366         if (req_ref_put_and_test(req))
2367                 io_free_req(req);
2368 }
2369
2370 static inline void io_put_req_deferred(struct io_kiocb *req)
2371 {
2372         if (req_ref_put_and_test(req)) {
2373                 req->io_task_work.func = io_free_req_work;
2374                 io_req_task_work_add(req);
2375         }
2376 }
2377
2378 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2379 {
2380         /* See comment at the top of this file */
2381         smp_rmb();
2382         return __io_cqring_events(ctx);
2383 }
2384
2385 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2386 {
2387         struct io_rings *rings = ctx->rings;
2388
2389         /* make sure SQ entry isn't read before tail */
2390         return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2391 }
2392
2393 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2394 {
2395         unsigned int cflags;
2396
2397         cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2398         cflags |= IORING_CQE_F_BUFFER;
2399         req->flags &= ~REQ_F_BUFFER_SELECTED;
2400         kfree(kbuf);
2401         return cflags;
2402 }
2403
2404 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2405 {
2406         struct io_buffer *kbuf;
2407
2408         if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2409                 return 0;
2410         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2411         return io_put_kbuf(req, kbuf);
2412 }
2413
2414 static inline bool io_run_task_work(void)
2415 {
2416         if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2417                 __set_current_state(TASK_RUNNING);
2418                 tracehook_notify_signal();
2419                 return true;
2420         }
2421
2422         return false;
2423 }
2424
2425 /*
2426  * Find and free completed poll iocbs
2427  */
2428 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2429                                struct list_head *done)
2430 {
2431         struct req_batch rb;
2432         struct io_kiocb *req;
2433
2434         /* order with ->result store in io_complete_rw_iopoll() */
2435         smp_rmb();
2436
2437         io_init_req_batch(&rb);
2438         while (!list_empty(done)) {
2439                 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2440                 list_del(&req->inflight_entry);
2441
2442                 if (READ_ONCE(req->result) == -EAGAIN &&
2443                     !(req->flags & REQ_F_DONT_REISSUE)) {
2444                         req->iopoll_completed = 0;
2445                         io_req_task_queue_reissue(req);
2446                         continue;
2447                 }
2448
2449                 __io_cqring_fill_event(ctx, req->user_data, req->result,
2450                                         io_put_rw_kbuf(req));
2451                 (*nr_events)++;
2452
2453                 if (req_ref_put_and_test(req))
2454                         io_req_free_batch(&rb, req, &ctx->submit_state);
2455         }
2456
2457         io_commit_cqring(ctx);
2458         io_cqring_ev_posted_iopoll(ctx);
2459         io_req_free_batch_finish(ctx, &rb);
2460 }
2461
2462 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2463                         long min)
2464 {
2465         struct io_kiocb *req, *tmp;
2466         LIST_HEAD(done);
2467         bool spin;
2468
2469         /*
2470          * Only spin for completions if we don't have multiple devices hanging
2471          * off our complete list, and we're under the requested amount.
2472          */
2473         spin = !ctx->poll_multi_queue && *nr_events < min;
2474
2475         list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2476                 struct kiocb *kiocb = &req->rw.kiocb;
2477                 int ret;
2478
2479                 /*
2480                  * Move completed and retryable entries to our local lists.
2481                  * If we find a request that requires polling, break out
2482                  * and complete those lists first, if we have entries there.
2483                  */
2484                 if (READ_ONCE(req->iopoll_completed)) {
2485                         list_move_tail(&req->inflight_entry, &done);
2486                         continue;
2487                 }
2488                 if (!list_empty(&done))
2489                         break;
2490
2491                 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2492                 if (unlikely(ret < 0))
2493                         return ret;
2494                 else if (ret)
2495                         spin = false;
2496
2497                 /* iopoll may have completed current req */
2498                 if (READ_ONCE(req->iopoll_completed))
2499                         list_move_tail(&req->inflight_entry, &done);
2500         }
2501
2502         if (!list_empty(&done))
2503                 io_iopoll_complete(ctx, nr_events, &done);
2504
2505         return 0;
2506 }
2507
2508 /*
2509  * We can't just wait for polled events to come to us, we have to actively
2510  * find and complete them.
2511  */
2512 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2513 {
2514         if (!(ctx->flags & IORING_SETUP_IOPOLL))
2515                 return;
2516
2517         mutex_lock(&ctx->uring_lock);
2518         while (!list_empty(&ctx->iopoll_list)) {
2519                 unsigned int nr_events = 0;
2520
2521                 io_do_iopoll(ctx, &nr_events, 0);
2522
2523                 /* let it sleep and repeat later if can't complete a request */
2524                 if (nr_events == 0)
2525                         break;
2526                 /*
2527                  * Ensure we allow local-to-the-cpu processing to take place,
2528                  * in this case we need to ensure that we reap all events.
2529                  * Also let task_work, etc. to progress by releasing the mutex
2530                  */
2531                 if (need_resched()) {
2532                         mutex_unlock(&ctx->uring_lock);
2533                         cond_resched();
2534                         mutex_lock(&ctx->uring_lock);
2535                 }
2536         }
2537         mutex_unlock(&ctx->uring_lock);
2538 }
2539
2540 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2541 {
2542         unsigned int nr_events = 0;
2543         int ret = 0;
2544
2545         /*
2546          * We disallow the app entering submit/complete with polling, but we
2547          * still need to lock the ring to prevent racing with polled issue
2548          * that got punted to a workqueue.
2549          */
2550         mutex_lock(&ctx->uring_lock);
2551         /*
2552          * Don't enter poll loop if we already have events pending.
2553          * If we do, we can potentially be spinning for commands that
2554          * already triggered a CQE (eg in error).
2555          */
2556         if (test_bit(0, &ctx->check_cq_overflow))
2557                 __io_cqring_overflow_flush(ctx, false);
2558         if (io_cqring_events(ctx))
2559                 goto out;
2560         do {
2561                 /*
2562                  * If a submit got punted to a workqueue, we can have the
2563                  * application entering polling for a command before it gets
2564                  * issued. That app will hold the uring_lock for the duration
2565                  * of the poll right here, so we need to take a breather every
2566                  * now and then to ensure that the issue has a chance to add
2567                  * the poll to the issued list. Otherwise we can spin here
2568                  * forever, while the workqueue is stuck trying to acquire the
2569                  * very same mutex.
2570                  */
2571                 if (list_empty(&ctx->iopoll_list)) {
2572                         u32 tail = ctx->cached_cq_tail;
2573
2574                         mutex_unlock(&ctx->uring_lock);
2575                         io_run_task_work();
2576                         mutex_lock(&ctx->uring_lock);
2577
2578                         /* some requests don't go through iopoll_list */
2579                         if (tail != ctx->cached_cq_tail ||
2580                             list_empty(&ctx->iopoll_list))
2581                                 break;
2582                 }
2583                 ret = io_do_iopoll(ctx, &nr_events, min);
2584         } while (!ret && nr_events < min && !need_resched());
2585 out:
2586         mutex_unlock(&ctx->uring_lock);
2587         return ret;
2588 }
2589
2590 static void kiocb_end_write(struct io_kiocb *req)
2591 {
2592         /*
2593          * Tell lockdep we inherited freeze protection from submission
2594          * thread.
2595          */
2596         if (req->flags & REQ_F_ISREG) {
2597                 struct super_block *sb = file_inode(req->file)->i_sb;
2598
2599                 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2600                 sb_end_write(sb);
2601         }
2602 }
2603
2604 #ifdef CONFIG_BLOCK
2605 static bool io_resubmit_prep(struct io_kiocb *req)
2606 {
2607         struct io_async_rw *rw = req->async_data;
2608
2609         if (!rw)
2610                 return !io_req_prep_async(req);
2611         /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2612         iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2613         return true;
2614 }
2615
2616 static bool io_rw_should_reissue(struct io_kiocb *req)
2617 {
2618         umode_t mode = file_inode(req->file)->i_mode;
2619         struct io_ring_ctx *ctx = req->ctx;
2620
2621         if (!S_ISBLK(mode) && !S_ISREG(mode))
2622                 return false;
2623         if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2624             !(ctx->flags & IORING_SETUP_IOPOLL)))
2625                 return false;
2626         /*
2627          * If ref is dying, we might be running poll reap from the exit work.
2628          * Don't attempt to reissue from that path, just let it fail with
2629          * -EAGAIN.
2630          */
2631         if (percpu_ref_is_dying(&ctx->refs))
2632                 return false;
2633         /*
2634          * Play it safe and assume not safe to re-import and reissue if we're
2635          * not in the original thread group (or in task context).
2636          */
2637         if (!same_thread_group(req->task, current) || !in_task())
2638                 return false;
2639         return true;
2640 }
2641 #else
2642 static bool io_resubmit_prep(struct io_kiocb *req)
2643 {
2644         return false;
2645 }
2646 static bool io_rw_should_reissue(struct io_kiocb *req)
2647 {
2648         return false;
2649 }
2650 #endif
2651
2652 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2653 {
2654         if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2655                 kiocb_end_write(req);
2656         if (res != req->result) {
2657                 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2658                     io_rw_should_reissue(req)) {
2659                         req->flags |= REQ_F_REISSUE;
2660                         return true;
2661                 }
2662                 req_set_fail(req);
2663                 req->result = res;
2664         }
2665         return false;
2666 }
2667
2668 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2669 {
2670         unsigned int cflags = io_put_rw_kbuf(req);
2671         long res = req->result;
2672
2673         if (*locked) {
2674                 struct io_ring_ctx *ctx = req->ctx;
2675                 struct io_submit_state *state = &ctx->submit_state;
2676
2677                 io_req_complete_state(req, res, cflags);
2678                 state->compl_reqs[state->compl_nr++] = req;
2679                 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2680                         io_submit_flush_completions(ctx);
2681         } else {
2682                 io_req_complete_post(req, res, cflags);
2683         }
2684 }
2685
2686 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2687                              unsigned int issue_flags)
2688 {
2689         if (__io_complete_rw_common(req, res))
2690                 return;
2691         __io_req_complete(req, issue_flags, req->result, io_put_rw_kbuf(req));
2692 }
2693
2694 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2695 {
2696         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2697
2698         if (__io_complete_rw_common(req, res))
2699                 return;
2700         req->result = res;
2701         req->io_task_work.func = io_req_task_complete;
2702         io_req_task_work_add(req);
2703 }
2704
2705 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2706 {
2707         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2708
2709         if (kiocb->ki_flags & IOCB_WRITE)
2710                 kiocb_end_write(req);
2711         if (unlikely(res != req->result)) {
2712                 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2713                     io_resubmit_prep(req))) {
2714                         req_set_fail(req);
2715                         req->flags |= REQ_F_DONT_REISSUE;
2716                 }
2717         }
2718
2719         WRITE_ONCE(req->result, res);
2720         /* order with io_iopoll_complete() checking ->result */
2721         smp_wmb();
2722         WRITE_ONCE(req->iopoll_completed, 1);
2723 }
2724
2725 /*
2726  * After the iocb has been issued, it's safe to be found on the poll list.
2727  * Adding the kiocb to the list AFTER submission ensures that we don't
2728  * find it from a io_do_iopoll() thread before the issuer is done
2729  * accessing the kiocb cookie.
2730  */
2731 static void io_iopoll_req_issued(struct io_kiocb *req)
2732 {
2733         struct io_ring_ctx *ctx = req->ctx;
2734         const bool in_async = io_wq_current_is_worker();
2735
2736         /* workqueue context doesn't hold uring_lock, grab it now */
2737         if (unlikely(in_async))
2738                 mutex_lock(&ctx->uring_lock);
2739
2740         /*
2741          * Track whether we have multiple files in our lists. This will impact
2742          * how we do polling eventually, not spinning if we're on potentially
2743          * different devices.
2744          */
2745         if (list_empty(&ctx->iopoll_list)) {
2746                 ctx->poll_multi_queue = false;
2747         } else if (!ctx->poll_multi_queue) {
2748                 struct io_kiocb *list_req;
2749                 unsigned int queue_num0, queue_num1;
2750
2751                 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2752                                                 inflight_entry);
2753
2754                 if (list_req->file != req->file) {
2755                         ctx->poll_multi_queue = true;
2756                 } else {
2757                         queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2758                         queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2759                         if (queue_num0 != queue_num1)
2760                                 ctx->poll_multi_queue = true;
2761                 }
2762         }
2763
2764         /*
2765          * For fast devices, IO may have already completed. If it has, add
2766          * it to the front so we find it first.
2767          */
2768         if (READ_ONCE(req->iopoll_completed))
2769                 list_add(&req->inflight_entry, &ctx->iopoll_list);
2770         else
2771                 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2772
2773         if (unlikely(in_async)) {
2774                 /*
2775                  * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2776                  * in sq thread task context or in io worker task context. If
2777                  * current task context is sq thread, we don't need to check
2778                  * whether should wake up sq thread.
2779                  */
2780                 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2781                     wq_has_sleeper(&ctx->sq_data->wait))
2782                         wake_up(&ctx->sq_data->wait);
2783
2784                 mutex_unlock(&ctx->uring_lock);
2785         }
2786 }
2787
2788 static bool io_bdev_nowait(struct block_device *bdev)
2789 {
2790         return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2791 }
2792
2793 /*
2794  * If we tracked the file through the SCM inflight mechanism, we could support
2795  * any file. For now, just ensure that anything potentially problematic is done
2796  * inline.
2797  */
2798 static bool __io_file_supports_nowait(struct file *file, int rw)
2799 {
2800         umode_t mode = file_inode(file)->i_mode;
2801
2802         if (S_ISBLK(mode)) {
2803                 if (IS_ENABLED(CONFIG_BLOCK) &&
2804                     io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2805                         return true;
2806                 return false;
2807         }
2808         if (S_ISSOCK(mode))
2809                 return true;
2810         if (S_ISREG(mode)) {
2811                 if (IS_ENABLED(CONFIG_BLOCK) &&
2812                     io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2813                     file->f_op != &io_uring_fops)
2814                         return true;
2815                 return false;
2816         }
2817
2818         /* any ->read/write should understand O_NONBLOCK */
2819         if (file->f_flags & O_NONBLOCK)
2820                 return true;
2821
2822         if (!(file->f_mode & FMODE_NOWAIT))
2823                 return false;
2824
2825         if (rw == READ)
2826                 return file->f_op->read_iter != NULL;
2827
2828         return file->f_op->write_iter != NULL;
2829 }
2830
2831 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2832 {
2833         if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2834                 return true;
2835         else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2836                 return true;
2837
2838         return __io_file_supports_nowait(req->file, rw);
2839 }
2840
2841 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2842 {
2843         struct io_ring_ctx *ctx = req->ctx;
2844         struct kiocb *kiocb = &req->rw.kiocb;
2845         struct file *file = req->file;
2846         unsigned ioprio;
2847         int ret;
2848
2849         if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2850                 req->flags |= REQ_F_ISREG;
2851
2852         kiocb->ki_pos = READ_ONCE(sqe->off);
2853         if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2854                 req->flags |= REQ_F_CUR_POS;
2855                 kiocb->ki_pos = file->f_pos;
2856         }
2857         kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2858         kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2859         ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2860         if (unlikely(ret))
2861                 return ret;
2862
2863         /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2864         if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2865                 req->flags |= REQ_F_NOWAIT;
2866
2867         ioprio = READ_ONCE(sqe->ioprio);
2868         if (ioprio) {
2869                 ret = ioprio_check_cap(ioprio);
2870                 if (ret)
2871                         return ret;
2872
2873                 kiocb->ki_ioprio = ioprio;
2874         } else
2875                 kiocb->ki_ioprio = get_current_ioprio();
2876
2877         if (ctx->flags & IORING_SETUP_IOPOLL) {
2878                 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2879                     !kiocb->ki_filp->f_op->iopoll)
2880                         return -EOPNOTSUPP;
2881
2882                 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2883                 kiocb->ki_complete = io_complete_rw_iopoll;
2884                 req->iopoll_completed = 0;
2885         } else {
2886                 if (kiocb->ki_flags & IOCB_HIPRI)
2887                         return -EINVAL;
2888                 kiocb->ki_complete = io_complete_rw;
2889         }
2890
2891         if (req->opcode == IORING_OP_READ_FIXED ||
2892             req->opcode == IORING_OP_WRITE_FIXED) {
2893                 req->imu = NULL;
2894                 io_req_set_rsrc_node(req);
2895         }
2896
2897         req->rw.addr = READ_ONCE(sqe->addr);
2898         req->rw.len = READ_ONCE(sqe->len);
2899         req->buf_index = READ_ONCE(sqe->buf_index);
2900         return 0;
2901 }
2902
2903 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2904 {
2905         switch (ret) {
2906         case -EIOCBQUEUED:
2907                 break;
2908         case -ERESTARTSYS:
2909         case -ERESTARTNOINTR:
2910         case -ERESTARTNOHAND:
2911         case -ERESTART_RESTARTBLOCK:
2912                 /*
2913                  * We can't just restart the syscall, since previously
2914                  * submitted sqes may already be in progress. Just fail this
2915                  * IO with EINTR.
2916                  */
2917                 ret = -EINTR;
2918                 fallthrough;
2919         default:
2920                 kiocb->ki_complete(kiocb, ret, 0);
2921         }
2922 }
2923
2924 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2925                        unsigned int issue_flags)
2926 {
2927         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2928         struct io_async_rw *io = req->async_data;
2929         bool check_reissue = kiocb->ki_complete == io_complete_rw;
2930
2931         /* add previously done IO, if any */
2932         if (io && io->bytes_done > 0) {
2933                 if (ret < 0)
2934                         ret = io->bytes_done;
2935                 else
2936                         ret += io->bytes_done;
2937         }
2938
2939         if (req->flags & REQ_F_CUR_POS)
2940                 req->file->f_pos = kiocb->ki_pos;
2941         if (ret >= 0 && check_reissue)
2942                 __io_complete_rw(req, ret, 0, issue_flags);
2943         else
2944                 io_rw_done(kiocb, ret);
2945
2946         if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2947                 req->flags &= ~REQ_F_REISSUE;
2948                 if (io_resubmit_prep(req)) {
2949                         io_req_task_queue_reissue(req);
2950                 } else {
2951                         req_set_fail(req);
2952                         __io_req_complete(req, issue_flags, ret,
2953                                           io_put_rw_kbuf(req));
2954                 }
2955         }
2956 }
2957
2958 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2959                              struct io_mapped_ubuf *imu)
2960 {
2961         size_t len = req->rw.len;
2962         u64 buf_end, buf_addr = req->rw.addr;
2963         size_t offset;
2964
2965         if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2966                 return -EFAULT;
2967         /* not inside the mapped region */
2968         if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2969                 return -EFAULT;
2970
2971         /*
2972          * May not be a start of buffer, set size appropriately
2973          * and advance us to the beginning.
2974          */
2975         offset = buf_addr - imu->ubuf;
2976         iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2977
2978         if (offset) {
2979                 /*
2980                  * Don't use iov_iter_advance() here, as it's really slow for
2981                  * using the latter parts of a big fixed buffer - it iterates
2982                  * over each segment manually. We can cheat a bit here, because
2983                  * we know that:
2984                  *
2985                  * 1) it's a BVEC iter, we set it up
2986                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
2987                  *    first and last bvec
2988                  *
2989                  * So just find our index, and adjust the iterator afterwards.
2990                  * If the offset is within the first bvec (or the whole first
2991                  * bvec, just use iov_iter_advance(). This makes it easier
2992                  * since we can just skip the first segment, which may not
2993                  * be PAGE_SIZE aligned.
2994                  */
2995                 const struct bio_vec *bvec = imu->bvec;
2996
2997                 if (offset <= bvec->bv_len) {
2998                         iov_iter_advance(iter, offset);
2999                 } else {
3000                         unsigned long seg_skip;
3001
3002                         /* skip first vec */
3003                         offset -= bvec->bv_len;
3004                         seg_skip = 1 + (offset >> PAGE_SHIFT);
3005
3006                         iter->bvec = bvec + seg_skip;
3007                         iter->nr_segs -= seg_skip;
3008                         iter->count -= bvec->bv_len + offset;
3009                         iter->iov_offset = offset & ~PAGE_MASK;
3010                 }
3011         }
3012
3013         return 0;
3014 }
3015
3016 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3017 {
3018         struct io_ring_ctx *ctx = req->ctx;
3019         struct io_mapped_ubuf *imu = req->imu;
3020         u16 index, buf_index = req->buf_index;
3021
3022         if (likely(!imu)) {
3023                 if (unlikely(buf_index >= ctx->nr_user_bufs))
3024                         return -EFAULT;
3025                 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3026                 imu = READ_ONCE(ctx->user_bufs[index]);
3027                 req->imu = imu;
3028         }
3029         return __io_import_fixed(req, rw, iter, imu);
3030 }
3031
3032 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3033 {
3034         if (needs_lock)
3035                 mutex_unlock(&ctx->uring_lock);
3036 }
3037
3038 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3039 {
3040         /*
3041          * "Normal" inline submissions always hold the uring_lock, since we
3042          * grab it from the system call. Same is true for the SQPOLL offload.
3043          * The only exception is when we've detached the request and issue it
3044          * from an async worker thread, grab the lock for that case.
3045          */
3046         if (needs_lock)
3047                 mutex_lock(&ctx->uring_lock);
3048 }
3049
3050 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3051                                           int bgid, struct io_buffer *kbuf,
3052                                           bool needs_lock)
3053 {
3054         struct io_buffer *head;
3055
3056         if (req->flags & REQ_F_BUFFER_SELECTED)
3057                 return kbuf;
3058
3059         io_ring_submit_lock(req->ctx, needs_lock);
3060
3061         lockdep_assert_held(&req->ctx->uring_lock);
3062
3063         head = xa_load(&req->ctx->io_buffers, bgid);
3064         if (head) {
3065                 if (!list_empty(&head->list)) {
3066                         kbuf = list_last_entry(&head->list, struct io_buffer,
3067                                                         list);
3068                         list_del(&kbuf->list);
3069                 } else {
3070                         kbuf = head;
3071                         xa_erase(&req->ctx->io_buffers, bgid);
3072                 }
3073                 if (*len > kbuf->len)
3074                         *len = kbuf->len;
3075         } else {
3076                 kbuf = ERR_PTR(-ENOBUFS);
3077         }
3078
3079         io_ring_submit_unlock(req->ctx, needs_lock);
3080
3081         return kbuf;
3082 }
3083
3084 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3085                                         bool needs_lock)
3086 {
3087         struct io_buffer *kbuf;
3088         u16 bgid;
3089
3090         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3091         bgid = req->buf_index;
3092         kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3093         if (IS_ERR(kbuf))
3094                 return kbuf;
3095         req->rw.addr = (u64) (unsigned long) kbuf;
3096         req->flags |= REQ_F_BUFFER_SELECTED;
3097         return u64_to_user_ptr(kbuf->addr);
3098 }
3099
3100 #ifdef CONFIG_COMPAT
3101 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3102                                 bool needs_lock)
3103 {
3104         struct compat_iovec __user *uiov;
3105         compat_ssize_t clen;
3106         void __user *buf;
3107         ssize_t len;
3108
3109         uiov = u64_to_user_ptr(req->rw.addr);
3110         if (!access_ok(uiov, sizeof(*uiov)))
3111                 return -EFAULT;
3112         if (__get_user(clen, &uiov->iov_len))
3113                 return -EFAULT;
3114         if (clen < 0)
3115                 return -EINVAL;
3116
3117         len = clen;
3118         buf = io_rw_buffer_select(req, &len, needs_lock);
3119         if (IS_ERR(buf))
3120                 return PTR_ERR(buf);
3121         iov[0].iov_base = buf;
3122         iov[0].iov_len = (compat_size_t) len;
3123         return 0;
3124 }
3125 #endif
3126
3127 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3128                                       bool needs_lock)
3129 {
3130         struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3131         void __user *buf;
3132         ssize_t len;
3133
3134         if (copy_from_user(iov, uiov, sizeof(*uiov)))
3135                 return -EFAULT;
3136
3137         len = iov[0].iov_len;
3138         if (len < 0)
3139                 return -EINVAL;
3140         buf = io_rw_buffer_select(req, &len, needs_lock);
3141         if (IS_ERR(buf))
3142                 return PTR_ERR(buf);
3143         iov[0].iov_base = buf;
3144         iov[0].iov_len = len;
3145         return 0;
3146 }
3147
3148 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3149                                     bool needs_lock)
3150 {
3151         if (req->flags & REQ_F_BUFFER_SELECTED) {
3152                 struct io_buffer *kbuf;
3153
3154                 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3155                 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3156                 iov[0].iov_len = kbuf->len;
3157                 return 0;
3158         }
3159         if (req->rw.len != 1)
3160                 return -EINVAL;
3161
3162 #ifdef CONFIG_COMPAT
3163         if (req->ctx->compat)
3164                 return io_compat_import(req, iov, needs_lock);
3165 #endif
3166
3167         return __io_iov_buffer_select(req, iov, needs_lock);
3168 }
3169
3170 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3171                            struct iov_iter *iter, bool needs_lock)
3172 {
3173         void __user *buf = u64_to_user_ptr(req->rw.addr);
3174         size_t sqe_len = req->rw.len;
3175         u8 opcode = req->opcode;
3176         ssize_t ret;
3177
3178         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3179                 *iovec = NULL;
3180                 return io_import_fixed(req, rw, iter);
3181         }
3182
3183         /* buffer index only valid with fixed read/write, or buffer select  */
3184         if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3185                 return -EINVAL;
3186
3187         if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3188                 if (req->flags & REQ_F_BUFFER_SELECT) {
3189                         buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3190                         if (IS_ERR(buf))
3191                                 return PTR_ERR(buf);
3192                         req->rw.len = sqe_len;
3193                 }
3194
3195                 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3196                 *iovec = NULL;
3197                 return ret;
3198         }
3199
3200         if (req->flags & REQ_F_BUFFER_SELECT) {
3201                 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3202                 if (!ret)
3203                         iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3204                 *iovec = NULL;
3205                 return ret;
3206         }
3207
3208         return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3209                               req->ctx->compat);
3210 }
3211
3212 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3213 {
3214         return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3215 }
3216
3217 /*
3218  * For files that don't have ->read_iter() and ->write_iter(), handle them
3219  * by looping over ->read() or ->write() manually.
3220  */
3221 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3222 {
3223         struct kiocb *kiocb = &req->rw.kiocb;
3224         struct file *file = req->file;
3225         ssize_t ret = 0;
3226
3227         /*
3228          * Don't support polled IO through this interface, and we can't
3229          * support non-blocking either. For the latter, this just causes
3230          * the kiocb to be handled from an async context.
3231          */
3232         if (kiocb->ki_flags & IOCB_HIPRI)
3233                 return -EOPNOTSUPP;
3234         if (kiocb->ki_flags & IOCB_NOWAIT)
3235                 return -EAGAIN;
3236
3237         while (iov_iter_count(iter)) {
3238                 struct iovec iovec;
3239                 ssize_t nr;
3240
3241                 if (!iov_iter_is_bvec(iter)) {
3242                         iovec = iov_iter_iovec(iter);
3243                 } else {
3244                         iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3245                         iovec.iov_len = req->rw.len;
3246                 }
3247
3248                 if (rw == READ) {
3249                         nr = file->f_op->read(file, iovec.iov_base,
3250                                               iovec.iov_len, io_kiocb_ppos(kiocb));
3251                 } else {
3252                         nr = file->f_op->write(file, iovec.iov_base,
3253                                                iovec.iov_len, io_kiocb_ppos(kiocb));
3254                 }
3255
3256                 if (nr < 0) {
3257                         if (!ret)
3258                                 ret = nr;
3259                         break;
3260                 }
3261                 ret += nr;
3262                 if (nr != iovec.iov_len)
3263                         break;
3264                 req->rw.len -= nr;
3265                 req->rw.addr += nr;
3266                 iov_iter_advance(iter, nr);
3267         }
3268
3269         return ret;
3270 }
3271
3272 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3273                           const struct iovec *fast_iov, struct iov_iter *iter)
3274 {
3275         struct io_async_rw *rw = req->async_data;
3276
3277         memcpy(&rw->iter, iter, sizeof(*iter));
3278         rw->free_iovec = iovec;
3279         rw->bytes_done = 0;
3280         /* can only be fixed buffers, no need to do anything */
3281         if (iov_iter_is_bvec(iter))
3282                 return;
3283         if (!iovec) {
3284                 unsigned iov_off = 0;
3285
3286                 rw->iter.iov = rw->fast_iov;
3287                 if (iter->iov != fast_iov) {
3288                         iov_off = iter->iov - fast_iov;
3289                         rw->iter.iov += iov_off;
3290                 }
3291                 if (rw->fast_iov != fast_iov)
3292                         memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3293                                sizeof(struct iovec) * iter->nr_segs);
3294         } else {
3295                 req->flags |= REQ_F_NEED_CLEANUP;
3296         }
3297 }
3298
3299 static inline int io_alloc_async_data(struct io_kiocb *req)
3300 {
3301         WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3302         req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3303         return req->async_data == NULL;
3304 }
3305
3306 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3307                              const struct iovec *fast_iov,
3308                              struct iov_iter *iter, bool force)
3309 {
3310         if (!force && !io_op_defs[req->opcode].needs_async_setup)
3311                 return 0;
3312         if (!req->async_data) {
3313                 if (io_alloc_async_data(req)) {
3314                         kfree(iovec);
3315                         return -ENOMEM;
3316                 }
3317
3318                 io_req_map_rw(req, iovec, fast_iov, iter);
3319         }
3320         return 0;
3321 }
3322
3323 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3324 {
3325         struct io_async_rw *iorw = req->async_data;
3326         struct iovec *iov = iorw->fast_iov;
3327         int ret;
3328
3329         ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3330         if (unlikely(ret < 0))
3331                 return ret;
3332
3333         iorw->bytes_done = 0;
3334         iorw->free_iovec = iov;
3335         if (iov)
3336                 req->flags |= REQ_F_NEED_CLEANUP;
3337         return 0;
3338 }
3339
3340 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3341 {
3342         if (unlikely(!(req->file->f_mode & FMODE_READ)))
3343                 return -EBADF;
3344         return io_prep_rw(req, sqe);
3345 }
3346
3347 /*
3348  * This is our waitqueue callback handler, registered through lock_page_async()
3349  * when we initially tried to do the IO with the iocb armed our waitqueue.
3350  * This gets called when the page is unlocked, and we generally expect that to
3351  * happen when the page IO is completed and the page is now uptodate. This will
3352  * queue a task_work based retry of the operation, attempting to copy the data
3353  * again. If the latter fails because the page was NOT uptodate, then we will
3354  * do a thread based blocking retry of the operation. That's the unexpected
3355  * slow path.
3356  */
3357 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3358                              int sync, void *arg)
3359 {
3360         struct wait_page_queue *wpq;
3361         struct io_kiocb *req = wait->private;
3362         struct wait_page_key *key = arg;
3363
3364         wpq = container_of(wait, struct wait_page_queue, wait);
3365
3366         if (!wake_page_match(wpq, key))
3367                 return 0;
3368
3369         req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3370         list_del_init(&wait->entry);
3371         io_req_task_queue(req);
3372         return 1;
3373 }
3374
3375 /*
3376  * This controls whether a given IO request should be armed for async page
3377  * based retry. If we return false here, the request is handed to the async
3378  * worker threads for retry. If we're doing buffered reads on a regular file,
3379  * we prepare a private wait_page_queue entry and retry the operation. This
3380  * will either succeed because the page is now uptodate and unlocked, or it
3381  * will register a callback when the page is unlocked at IO completion. Through
3382  * that callback, io_uring uses task_work to setup a retry of the operation.
3383  * That retry will attempt the buffered read again. The retry will generally
3384  * succeed, or in rare cases where it fails, we then fall back to using the
3385  * async worker threads for a blocking retry.
3386  */
3387 static bool io_rw_should_retry(struct io_kiocb *req)
3388 {
3389         struct io_async_rw *rw = req->async_data;
3390         struct wait_page_queue *wait = &rw->wpq;