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