~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/io_uring.c

Version: ~ [ linux-6.0-rc6 ] ~ [ linux-5.19.10 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.69 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.144 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.214 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.259 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.294 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.329 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.302 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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_cqring (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 
 82 #define CREATE_TRACE_POINTS
 83 #include <trace/events/io_uring.h>
 84 
 85 #include <uapi/linux/io_uring.h>
 86 
 87 #include "internal.h"
 88 #include "io-wq.h"
 89 
 90 #define IORING_MAX_ENTRIES      32768
 91 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
 92 
 93 /*
 94  * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
 95  */
 96 #define IORING_FILE_TABLE_SHIFT 9
 97 #define IORING_MAX_FILES_TABLE  (1U << IORING_FILE_TABLE_SHIFT)
 98 #define IORING_FILE_TABLE_MASK  (IORING_MAX_FILES_TABLE - 1)
 99 #define IORING_MAX_FIXED_FILES  (64 * IORING_MAX_FILES_TABLE)
100 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
101                                  IORING_REGISTER_LAST + IORING_OP_LAST)
102 
103 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
104                                 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
105                                 IOSQE_BUFFER_SELECT)
106 
107 struct io_uring {
108         u32 head ____cacheline_aligned_in_smp;
109         u32 tail ____cacheline_aligned_in_smp;
110 };
111 
112 /*
113  * This data is shared with the application through the mmap at offsets
114  * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
115  *
116  * The offsets to the member fields are published through struct
117  * io_sqring_offsets when calling io_uring_setup.
118  */
119 struct io_rings {
120         /*
121          * Head and tail offsets into the ring; the offsets need to be
122          * masked to get valid indices.
123          *
124          * The kernel controls head of the sq ring and the tail of the cq ring,
125          * and the application controls tail of the sq ring and the head of the
126          * cq ring.
127          */
128         struct io_uring         sq, cq;
129         /*
130          * Bitmasks to apply to head and tail offsets (constant, equals
131          * ring_entries - 1)
132          */
133         u32                     sq_ring_mask, cq_ring_mask;
134         /* Ring sizes (constant, power of 2) */
135         u32                     sq_ring_entries, cq_ring_entries;
136         /*
137          * Number of invalid entries dropped by the kernel due to
138          * invalid index stored in array
139          *
140          * Written by the kernel, shouldn't be modified by the
141          * application (i.e. get number of "new events" by comparing to
142          * cached value).
143          *
144          * After a new SQ head value was read by the application this
145          * counter includes all submissions that were dropped reaching
146          * the new SQ head (and possibly more).
147          */
148         u32                     sq_dropped;
149         /*
150          * Runtime SQ flags
151          *
152          * Written by the kernel, shouldn't be modified by the
153          * application.
154          *
155          * The application needs a full memory barrier before checking
156          * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
157          */
158         u32                     sq_flags;
159         /*
160          * Runtime CQ flags
161          *
162          * Written by the application, shouldn't be modified by the
163          * kernel.
164          */
165         u32                     cq_flags;
166         /*
167          * Number of completion events lost because the queue was full;
168          * this should be avoided by the application by making sure
169          * there are not more requests pending than there is space in
170          * the completion queue.
171          *
172          * Written by the kernel, shouldn't be modified by the
173          * application (i.e. get number of "new events" by comparing to
174          * cached value).
175          *
176          * As completion events come in out of order this counter is not
177          * ordered with any other data.
178          */
179         u32                     cq_overflow;
180         /*
181          * Ring buffer of completion events.
182          *
183          * The kernel writes completion events fresh every time they are
184          * produced, so the application is allowed to modify pending
185          * entries.
186          */
187         struct io_uring_cqe     cqes[] ____cacheline_aligned_in_smp;
188 };
189 
190 enum io_uring_cmd_flags {
191         IO_URING_F_NONBLOCK             = 1,
192         IO_URING_F_COMPLETE_DEFER       = 2,
193 };
194 
195 struct io_mapped_ubuf {
196         u64             ubuf;
197         size_t          len;
198         struct          bio_vec *bvec;
199         unsigned int    nr_bvecs;
200         unsigned long   acct_pages;
201 };
202 
203 struct io_ring_ctx;
204 
205 struct io_rsrc_put {
206         struct list_head list;
207         union {
208                 void *rsrc;
209                 struct file *file;
210         };
211 };
212 
213 struct fixed_rsrc_table {
214         struct file             **files;
215 };
216 
217 struct fixed_rsrc_ref_node {
218         struct percpu_ref               refs;
219         struct list_head                node;
220         struct list_head                rsrc_list;
221         struct fixed_rsrc_data          *rsrc_data;
222         void                            (*rsrc_put)(struct io_ring_ctx *ctx,
223                                                     struct io_rsrc_put *prsrc);
224         struct llist_node               llist;
225         bool                            done;
226 };
227 
228 struct fixed_rsrc_data {
229         struct fixed_rsrc_table         *table;
230         struct io_ring_ctx              *ctx;
231 
232         struct fixed_rsrc_ref_node      *node;
233         struct percpu_ref               refs;
234         struct completion               done;
235         bool                            quiesce;
236 };
237 
238 struct io_buffer {
239         struct list_head list;
240         __u64 addr;
241         __u32 len;
242         __u16 bid;
243 };
244 
245 struct io_restriction {
246         DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
247         DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
248         u8 sqe_flags_allowed;
249         u8 sqe_flags_required;
250         bool registered;
251 };
252 
253 enum {
254         IO_SQ_THREAD_SHOULD_STOP = 0,
255         IO_SQ_THREAD_SHOULD_PARK,
256 };
257 
258 struct io_sq_data {
259         refcount_t              refs;
260         atomic_t                park_pending;
261         struct mutex            lock;
262 
263         /* ctx's that are using this sqd */
264         struct list_head        ctx_list;
265 
266         struct task_struct      *thread;
267         struct wait_queue_head  wait;
268 
269         unsigned                sq_thread_idle;
270         int                     sq_cpu;
271         pid_t                   task_pid;
272         pid_t                   task_tgid;
273 
274         unsigned long           state;
275         struct completion       exited;
276         struct callback_head    *park_task_work;
277 };
278 
279 #define IO_IOPOLL_BATCH                 8
280 #define IO_COMPL_BATCH                  32
281 #define IO_REQ_CACHE_SIZE               32
282 #define IO_REQ_ALLOC_BATCH              8
283 
284 struct io_comp_state {
285         struct io_kiocb         *reqs[IO_COMPL_BATCH];
286         unsigned int            nr;
287         unsigned int            locked_free_nr;
288         /* inline/task_work completion list, under ->uring_lock */
289         struct list_head        free_list;
290         /* IRQ completion list, under ->completion_lock */
291         struct list_head        locked_free_list;
292 };
293 
294 struct io_submit_link {
295         struct io_kiocb         *head;
296         struct io_kiocb         *last;
297 };
298 
299 struct io_submit_state {
300         struct blk_plug         plug;
301         struct io_submit_link   link;
302 
303         /*
304          * io_kiocb alloc cache
305          */
306         void                    *reqs[IO_REQ_CACHE_SIZE];
307         unsigned int            free_reqs;
308 
309         bool                    plug_started;
310 
311         /*
312          * Batch completion logic
313          */
314         struct io_comp_state    comp;
315 
316         /*
317          * File reference cache
318          */
319         struct file             *file;
320         unsigned int            fd;
321         unsigned int            file_refs;
322         unsigned int            ios_left;
323 };
324 
325 struct io_ring_ctx {
326         struct {
327                 struct percpu_ref       refs;
328         } ____cacheline_aligned_in_smp;
329 
330         struct {
331                 unsigned int            flags;
332                 unsigned int            compat: 1;
333                 unsigned int            cq_overflow_flushed: 1;
334                 unsigned int            drain_next: 1;
335                 unsigned int            eventfd_async: 1;
336                 unsigned int            restricted: 1;
337 
338                 /*
339                  * Ring buffer of indices into array of io_uring_sqe, which is
340                  * mmapped by the application using the IORING_OFF_SQES offset.
341                  *
342                  * This indirection could e.g. be used to assign fixed
343                  * io_uring_sqe entries to operations and only submit them to
344                  * the queue when needed.
345                  *
346                  * The kernel modifies neither the indices array nor the entries
347                  * array.
348                  */
349                 u32                     *sq_array;
350                 unsigned                cached_sq_head;
351                 unsigned                sq_entries;
352                 unsigned                sq_mask;
353                 unsigned                sq_thread_idle;
354                 unsigned                cached_sq_dropped;
355                 unsigned                cached_cq_overflow;
356                 unsigned long           sq_check_overflow;
357 
358                 /* hashed buffered write serialization */
359                 struct io_wq_hash       *hash_map;
360 
361                 struct list_head        defer_list;
362                 struct list_head        timeout_list;
363                 struct list_head        cq_overflow_list;
364 
365                 struct io_uring_sqe     *sq_sqes;
366         } ____cacheline_aligned_in_smp;
367 
368         struct {
369                 struct mutex            uring_lock;
370                 wait_queue_head_t       wait;
371         } ____cacheline_aligned_in_smp;
372 
373         struct io_submit_state          submit_state;
374 
375         struct io_rings *rings;
376 
377         /* Only used for accounting purposes */
378         struct mm_struct        *mm_account;
379 
380         const struct cred       *sq_creds;      /* cred used for __io_sq_thread() */
381         struct io_sq_data       *sq_data;       /* if using sq thread polling */
382 
383         struct wait_queue_head  sqo_sq_wait;
384         struct list_head        sqd_list;
385 
386         /*
387          * If used, fixed file set. Writers must ensure that ->refs is dead,
388          * readers must ensure that ->refs is alive as long as the file* is
389          * used. Only updated through io_uring_register(2).
390          */
391         struct fixed_rsrc_data  *file_data;
392         unsigned                nr_user_files;
393 
394         /* if used, fixed mapped user buffers */
395         unsigned                nr_user_bufs;
396         struct io_mapped_ubuf   *user_bufs;
397 
398         struct user_struct      *user;
399 
400         struct completion       ref_comp;
401 
402 #if defined(CONFIG_UNIX)
403         struct socket           *ring_sock;
404 #endif
405 
406         struct xarray           io_buffers;
407 
408         struct xarray           personalities;
409         u32                     pers_next;
410 
411         struct {
412                 unsigned                cached_cq_tail;
413                 unsigned                cq_entries;
414                 unsigned                cq_mask;
415                 atomic_t                cq_timeouts;
416                 unsigned                cq_last_tm_flush;
417                 unsigned long           cq_check_overflow;
418                 struct wait_queue_head  cq_wait;
419                 struct fasync_struct    *cq_fasync;
420                 struct eventfd_ctx      *cq_ev_fd;
421         } ____cacheline_aligned_in_smp;
422 
423         struct {
424                 spinlock_t              completion_lock;
425 
426                 /*
427                  * ->iopoll_list is protected by the ctx->uring_lock for
428                  * io_uring instances that don't use IORING_SETUP_SQPOLL.
429                  * For SQPOLL, only the single threaded io_sq_thread() will
430                  * manipulate the list, hence no extra locking is needed there.
431                  */
432                 struct list_head        iopoll_list;
433                 struct hlist_head       *cancel_hash;
434                 unsigned                cancel_hash_bits;
435                 bool                    poll_multi_file;
436 
437                 spinlock_t              inflight_lock;
438                 struct list_head        inflight_list;
439         } ____cacheline_aligned_in_smp;
440 
441         struct delayed_work             rsrc_put_work;
442         struct llist_head               rsrc_put_llist;
443         struct list_head                rsrc_ref_list;
444         spinlock_t                      rsrc_ref_lock;
445 
446         struct io_restriction           restrictions;
447 
448         /* exit task_work */
449         struct callback_head            *exit_task_work;
450 
451         struct wait_queue_head          hash_wait;
452 
453         /* Keep this last, we don't need it for the fast path */
454         struct work_struct              exit_work;
455         struct list_head                tctx_list;
456 };
457 
458 struct io_uring_task {
459         /* submission side */
460         struct xarray           xa;
461         struct wait_queue_head  wait;
462         const struct io_ring_ctx *last;
463         struct io_wq            *io_wq;
464         struct percpu_counter   inflight;
465         atomic_t                in_idle;
466         bool                    sqpoll;
467 
468         spinlock_t              task_lock;
469         struct io_wq_work_list  task_list;
470         unsigned long           task_state;
471         struct callback_head    task_work;
472 };
473 
474 /*
475  * First field must be the file pointer in all the
476  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
477  */
478 struct io_poll_iocb {
479         struct file                     *file;
480         struct wait_queue_head          *head;
481         __poll_t                        events;
482         bool                            done;
483         bool                            canceled;
484         struct wait_queue_entry         wait;
485 };
486 
487 struct io_poll_remove {
488         struct file                     *file;
489         u64                             addr;
490 };
491 
492 struct io_close {
493         struct file                     *file;
494         int                             fd;
495 };
496 
497 struct io_timeout_data {
498         struct io_kiocb                 *req;
499         struct hrtimer                  timer;
500         struct timespec64               ts;
501         enum hrtimer_mode               mode;
502 };
503 
504 struct io_accept {
505         struct file                     *file;
506         struct sockaddr __user          *addr;
507         int __user                      *addr_len;
508         int                             flags;
509         unsigned long                   nofile;
510 };
511 
512 struct io_sync {
513         struct file                     *file;
514         loff_t                          len;
515         loff_t                          off;
516         int                             flags;
517         int                             mode;
518 };
519 
520 struct io_cancel {
521         struct file                     *file;
522         u64                             addr;
523 };
524 
525 struct io_timeout {
526         struct file                     *file;
527         u32                             off;
528         u32                             target_seq;
529         struct list_head                list;
530         /* head of the link, used by linked timeouts only */
531         struct io_kiocb                 *head;
532 };
533 
534 struct io_timeout_rem {
535         struct file                     *file;
536         u64                             addr;
537 
538         /* timeout update */
539         struct timespec64               ts;
540         u32                             flags;
541 };
542 
543 struct io_rw {
544         /* NOTE: kiocb has the file as the first member, so don't do it here */
545         struct kiocb                    kiocb;
546         u64                             addr;
547         u64                             len;
548 };
549 
550 struct io_connect {
551         struct file                     *file;
552         struct sockaddr __user          *addr;
553         int                             addr_len;
554 };
555 
556 struct io_sr_msg {
557         struct file                     *file;
558         union {
559                 struct user_msghdr __user *umsg;
560                 void __user             *buf;
561         };
562         int                             msg_flags;
563         int                             bgid;
564         size_t                          len;
565         struct io_buffer                *kbuf;
566 };
567 
568 struct io_open {
569         struct file                     *file;
570         int                             dfd;
571         struct filename                 *filename;
572         struct open_how                 how;
573         unsigned long                   nofile;
574 };
575 
576 struct io_rsrc_update {
577         struct file                     *file;
578         u64                             arg;
579         u32                             nr_args;
580         u32                             offset;
581 };
582 
583 struct io_fadvise {
584         struct file                     *file;
585         u64                             offset;
586         u32                             len;
587         u32                             advice;
588 };
589 
590 struct io_madvise {
591         struct file                     *file;
592         u64                             addr;
593         u32                             len;
594         u32                             advice;
595 };
596 
597 struct io_epoll {
598         struct file                     *file;
599         int                             epfd;
600         int                             op;
601         int                             fd;
602         struct epoll_event              event;
603 };
604 
605 struct io_splice {
606         struct file                     *file_out;
607         struct file                     *file_in;
608         loff_t                          off_out;
609         loff_t                          off_in;
610         u64                             len;
611         unsigned int                    flags;
612 };
613 
614 struct io_provide_buf {
615         struct file                     *file;
616         __u64                           addr;
617         __u32                           len;
618         __u32                           bgid;
619         __u16                           nbufs;
620         __u16                           bid;
621 };
622 
623 struct io_statx {
624         struct file                     *file;
625         int                             dfd;
626         unsigned int                    mask;
627         unsigned int                    flags;
628         const char __user               *filename;
629         struct statx __user             *buffer;
630 };
631 
632 struct io_shutdown {
633         struct file                     *file;
634         int                             how;
635 };
636 
637 struct io_rename {
638         struct file                     *file;
639         int                             old_dfd;
640         int                             new_dfd;
641         struct filename                 *oldpath;
642         struct filename                 *newpath;
643         int                             flags;
644 };
645 
646 struct io_unlink {
647         struct file                     *file;
648         int                             dfd;
649         int                             flags;
650         struct filename                 *filename;
651 };
652 
653 struct io_completion {
654         struct file                     *file;
655         struct list_head                list;
656         u32                             cflags;
657 };
658 
659 struct io_async_connect {
660         struct sockaddr_storage         address;
661 };
662 
663 struct io_async_msghdr {
664         struct iovec                    fast_iov[UIO_FASTIOV];
665         /* points to an allocated iov, if NULL we use fast_iov instead */
666         struct iovec                    *free_iov;
667         struct sockaddr __user          *uaddr;
668         struct msghdr                   msg;
669         struct sockaddr_storage         addr;
670 };
671 
672 struct io_async_rw {
673         struct iovec                    fast_iov[UIO_FASTIOV];
674         const struct iovec              *free_iovec;
675         struct iov_iter                 iter;
676         size_t                          bytes_done;
677         struct wait_page_queue          wpq;
678 };
679 
680 enum {
681         REQ_F_FIXED_FILE_BIT    = IOSQE_FIXED_FILE_BIT,
682         REQ_F_IO_DRAIN_BIT      = IOSQE_IO_DRAIN_BIT,
683         REQ_F_LINK_BIT          = IOSQE_IO_LINK_BIT,
684         REQ_F_HARDLINK_BIT      = IOSQE_IO_HARDLINK_BIT,
685         REQ_F_FORCE_ASYNC_BIT   = IOSQE_ASYNC_BIT,
686         REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
687 
688         REQ_F_FAIL_LINK_BIT,
689         REQ_F_INFLIGHT_BIT,
690         REQ_F_CUR_POS_BIT,
691         REQ_F_NOWAIT_BIT,
692         REQ_F_LINK_TIMEOUT_BIT,
693         REQ_F_ISREG_BIT,
694         REQ_F_NEED_CLEANUP_BIT,
695         REQ_F_POLLED_BIT,
696         REQ_F_BUFFER_SELECTED_BIT,
697         REQ_F_NO_FILE_TABLE_BIT,
698         REQ_F_LTIMEOUT_ACTIVE_BIT,
699         REQ_F_COMPLETE_INLINE_BIT,
700         REQ_F_REISSUE_BIT,
701 
702         /* not a real bit, just to check we're not overflowing the space */
703         __REQ_F_LAST_BIT,
704 };
705 
706 enum {
707         /* ctx owns file */
708         REQ_F_FIXED_FILE        = BIT(REQ_F_FIXED_FILE_BIT),
709         /* drain existing IO first */
710         REQ_F_IO_DRAIN          = BIT(REQ_F_IO_DRAIN_BIT),
711         /* linked sqes */
712         REQ_F_LINK              = BIT(REQ_F_LINK_BIT),
713         /* doesn't sever on completion < 0 */
714         REQ_F_HARDLINK          = BIT(REQ_F_HARDLINK_BIT),
715         /* IOSQE_ASYNC */
716         REQ_F_FORCE_ASYNC       = BIT(REQ_F_FORCE_ASYNC_BIT),
717         /* IOSQE_BUFFER_SELECT */
718         REQ_F_BUFFER_SELECT     = BIT(REQ_F_BUFFER_SELECT_BIT),
719 
720         /* fail rest of links */
721         REQ_F_FAIL_LINK         = BIT(REQ_F_FAIL_LINK_BIT),
722         /* on inflight list, should be cancelled and waited on exit reliably */
723         REQ_F_INFLIGHT          = BIT(REQ_F_INFLIGHT_BIT),
724         /* read/write uses file position */
725         REQ_F_CUR_POS           = BIT(REQ_F_CUR_POS_BIT),
726         /* must not punt to workers */
727         REQ_F_NOWAIT            = BIT(REQ_F_NOWAIT_BIT),
728         /* has or had linked timeout */
729         REQ_F_LINK_TIMEOUT      = BIT(REQ_F_LINK_TIMEOUT_BIT),
730         /* regular file */
731         REQ_F_ISREG             = BIT(REQ_F_ISREG_BIT),
732         /* needs cleanup */
733         REQ_F_NEED_CLEANUP      = BIT(REQ_F_NEED_CLEANUP_BIT),
734         /* already went through poll handler */
735         REQ_F_POLLED            = BIT(REQ_F_POLLED_BIT),
736         /* buffer already selected */
737         REQ_F_BUFFER_SELECTED   = BIT(REQ_F_BUFFER_SELECTED_BIT),
738         /* doesn't need file table for this request */
739         REQ_F_NO_FILE_TABLE     = BIT(REQ_F_NO_FILE_TABLE_BIT),
740         /* linked timeout is active, i.e. prepared by link's head */
741         REQ_F_LTIMEOUT_ACTIVE   = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
742         /* completion is deferred through io_comp_state */
743         REQ_F_COMPLETE_INLINE   = BIT(REQ_F_COMPLETE_INLINE_BIT),
744         /* caller should reissue async */
745         REQ_F_REISSUE           = BIT(REQ_F_REISSUE_BIT),
746 };
747 
748 struct async_poll {
749         struct io_poll_iocb     poll;
750         struct io_poll_iocb     *double_poll;
751 };
752 
753 struct io_task_work {
754         struct io_wq_work_node  node;
755         task_work_func_t        func;
756 };
757 
758 /*
759  * NOTE! Each of the iocb union members has the file pointer
760  * as the first entry in their struct definition. So you can
761  * access the file pointer through any of the sub-structs,
762  * or directly as just 'ki_filp' in this struct.
763  */
764 struct io_kiocb {
765         union {
766                 struct file             *file;
767                 struct io_rw            rw;
768                 struct io_poll_iocb     poll;
769                 struct io_poll_remove   poll_remove;
770                 struct io_accept        accept;
771                 struct io_sync          sync;
772                 struct io_cancel        cancel;
773                 struct io_timeout       timeout;
774                 struct io_timeout_rem   timeout_rem;
775                 struct io_connect       connect;
776                 struct io_sr_msg        sr_msg;
777                 struct io_open          open;
778                 struct io_close         close;
779                 struct io_rsrc_update   rsrc_update;
780                 struct io_fadvise       fadvise;
781                 struct io_madvise       madvise;
782                 struct io_epoll         epoll;
783                 struct io_splice        splice;
784                 struct io_provide_buf   pbuf;
785                 struct io_statx         statx;
786                 struct io_shutdown      shutdown;
787                 struct io_rename        rename;
788                 struct io_unlink        unlink;
789                 /* use only after cleaning per-op data, see io_clean_op() */
790                 struct io_completion    compl;
791         };
792 
793         /* opcode allocated if it needs to store data for async defer */
794         void                            *async_data;
795         u8                              opcode;
796         /* polled IO has completed */
797         u8                              iopoll_completed;
798 
799         u16                             buf_index;
800         u32                             result;
801 
802         struct io_ring_ctx              *ctx;
803         unsigned int                    flags;
804         refcount_t                      refs;
805         struct task_struct              *task;
806         u64                             user_data;
807 
808         struct io_kiocb                 *link;
809         struct percpu_ref               *fixed_rsrc_refs;
810 
811         /*
812          * 1. used with ctx->iopoll_list with reads/writes
813          * 2. to track reqs with ->files (see io_op_def::file_table)
814          */
815         struct list_head                inflight_entry;
816         union {
817                 struct io_task_work     io_task_work;
818                 struct callback_head    task_work;
819         };
820         /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
821         struct hlist_node               hash_node;
822         struct async_poll               *apoll;
823         struct io_wq_work               work;
824 };
825 
826 struct io_tctx_node {
827         struct list_head        ctx_node;
828         struct task_struct      *task;
829         struct io_ring_ctx      *ctx;
830 };
831 
832 struct io_defer_entry {
833         struct list_head        list;
834         struct io_kiocb         *req;
835         u32                     seq;
836 };
837 
838 struct io_op_def {
839         /* needs req->file assigned */
840         unsigned                needs_file : 1;
841         /* hash wq insertion if file is a regular file */
842         unsigned                hash_reg_file : 1;
843         /* unbound wq insertion if file is a non-regular file */
844         unsigned                unbound_nonreg_file : 1;
845         /* opcode is not supported by this kernel */
846         unsigned                not_supported : 1;
847         /* set if opcode supports polled "wait" */
848         unsigned                pollin : 1;
849         unsigned                pollout : 1;
850         /* op supports buffer selection */
851         unsigned                buffer_select : 1;
852         /* must always have async data allocated */
853         unsigned                needs_async_data : 1;
854         /* should block plug */
855         unsigned                plug : 1;
856         /* size of async data needed, if any */
857         unsigned short          async_size;
858 };
859 
860 static const struct io_op_def io_op_defs[] = {
861         [IORING_OP_NOP] = {},
862         [IORING_OP_READV] = {
863                 .needs_file             = 1,
864                 .unbound_nonreg_file    = 1,
865                 .pollin                 = 1,
866                 .buffer_select          = 1,
867                 .needs_async_data       = 1,
868                 .plug                   = 1,
869                 .async_size             = sizeof(struct io_async_rw),
870         },
871         [IORING_OP_WRITEV] = {
872                 .needs_file             = 1,
873                 .hash_reg_file          = 1,
874                 .unbound_nonreg_file    = 1,
875                 .pollout                = 1,
876                 .needs_async_data       = 1,
877                 .plug                   = 1,
878                 .async_size             = sizeof(struct io_async_rw),
879         },
880         [IORING_OP_FSYNC] = {
881                 .needs_file             = 1,
882         },
883         [IORING_OP_READ_FIXED] = {
884                 .needs_file             = 1,
885                 .unbound_nonreg_file    = 1,
886                 .pollin                 = 1,
887                 .plug                   = 1,
888                 .async_size             = sizeof(struct io_async_rw),
889         },
890         [IORING_OP_WRITE_FIXED] = {
891                 .needs_file             = 1,
892                 .hash_reg_file          = 1,
893                 .unbound_nonreg_file    = 1,
894                 .pollout                = 1,
895                 .plug                   = 1,
896                 .async_size             = sizeof(struct io_async_rw),
897         },
898         [IORING_OP_POLL_ADD] = {
899                 .needs_file             = 1,
900                 .unbound_nonreg_file    = 1,
901         },
902         [IORING_OP_POLL_REMOVE] = {},
903         [IORING_OP_SYNC_FILE_RANGE] = {
904                 .needs_file             = 1,
905         },
906         [IORING_OP_SENDMSG] = {
907                 .needs_file             = 1,
908                 .unbound_nonreg_file    = 1,
909                 .pollout                = 1,
910                 .needs_async_data       = 1,
911                 .async_size             = sizeof(struct io_async_msghdr),
912         },
913         [IORING_OP_RECVMSG] = {
914                 .needs_file             = 1,
915                 .unbound_nonreg_file    = 1,
916                 .pollin                 = 1,
917                 .buffer_select          = 1,
918                 .needs_async_data       = 1,
919                 .async_size             = sizeof(struct io_async_msghdr),
920         },
921         [IORING_OP_TIMEOUT] = {
922                 .needs_async_data       = 1,
923                 .async_size             = sizeof(struct io_timeout_data),
924         },
925         [IORING_OP_TIMEOUT_REMOVE] = {
926                 /* used by timeout updates' prep() */
927         },
928         [IORING_OP_ACCEPT] = {
929                 .needs_file             = 1,
930                 .unbound_nonreg_file    = 1,
931                 .pollin                 = 1,
932         },
933         [IORING_OP_ASYNC_CANCEL] = {},
934         [IORING_OP_LINK_TIMEOUT] = {
935                 .needs_async_data       = 1,
936                 .async_size             = sizeof(struct io_timeout_data),
937         },
938         [IORING_OP_CONNECT] = {
939                 .needs_file             = 1,
940                 .unbound_nonreg_file    = 1,
941                 .pollout                = 1,
942                 .needs_async_data       = 1,
943                 .async_size             = sizeof(struct io_async_connect),
944         },
945         [IORING_OP_FALLOCATE] = {
946                 .needs_file             = 1,
947         },
948         [IORING_OP_OPENAT] = {},
949         [IORING_OP_CLOSE] = {},
950         [IORING_OP_FILES_UPDATE] = {},
951         [IORING_OP_STATX] = {},
952         [IORING_OP_READ] = {
953                 .needs_file             = 1,
954                 .unbound_nonreg_file    = 1,
955                 .pollin                 = 1,
956                 .buffer_select          = 1,
957                 .plug                   = 1,
958                 .async_size             = sizeof(struct io_async_rw),
959         },
960         [IORING_OP_WRITE] = {
961                 .needs_file             = 1,
962                 .unbound_nonreg_file    = 1,
963                 .pollout                = 1,
964                 .plug                   = 1,
965                 .async_size             = sizeof(struct io_async_rw),
966         },
967         [IORING_OP_FADVISE] = {
968                 .needs_file             = 1,
969         },
970         [IORING_OP_MADVISE] = {},
971         [IORING_OP_SEND] = {
972                 .needs_file             = 1,
973                 .unbound_nonreg_file    = 1,
974                 .pollout                = 1,
975         },
976         [IORING_OP_RECV] = {
977                 .needs_file             = 1,
978                 .unbound_nonreg_file    = 1,
979                 .pollin                 = 1,
980                 .buffer_select          = 1,
981         },
982         [IORING_OP_OPENAT2] = {
983         },
984         [IORING_OP_EPOLL_CTL] = {
985                 .unbound_nonreg_file    = 1,
986         },
987         [IORING_OP_SPLICE] = {
988                 .needs_file             = 1,
989                 .hash_reg_file          = 1,
990                 .unbound_nonreg_file    = 1,
991         },
992         [IORING_OP_PROVIDE_BUFFERS] = {},
993         [IORING_OP_REMOVE_BUFFERS] = {},
994         [IORING_OP_TEE] = {
995                 .needs_file             = 1,
996                 .hash_reg_file          = 1,
997                 .unbound_nonreg_file    = 1,
998         },
999         [IORING_OP_SHUTDOWN] = {
1000                 .needs_file             = 1,
1001         },
1002         [IORING_OP_RENAMEAT] = {},
1003         [IORING_OP_UNLINKAT] = {},
1004 };
1005 
1006 static bool io_disarm_next(struct io_kiocb *req);
1007 static void io_uring_del_task_file(unsigned long index);
1008 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1009                                          struct task_struct *task,
1010                                          struct files_struct *files);
1011 static void io_uring_cancel_sqpoll(struct io_sq_data *sqd);
1012 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
1013 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
1014                         struct io_ring_ctx *ctx);
1015 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
1016 
1017 static bool io_rw_reissue(struct io_kiocb *req);
1018 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1019 static void io_put_req(struct io_kiocb *req);
1020 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1021 static void io_double_put_req(struct io_kiocb *req);
1022 static void io_dismantle_req(struct io_kiocb *req);
1023 static void io_put_task(struct task_struct *task, int nr);
1024 static void io_queue_next(struct io_kiocb *req);
1025 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1026 static void __io_queue_linked_timeout(struct io_kiocb *req);
1027 static void io_queue_linked_timeout(struct io_kiocb *req);
1028 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1029                                  struct io_uring_rsrc_update *ip,
1030                                  unsigned nr_args);
1031 static void __io_clean_op(struct io_kiocb *req);
1032 static struct file *io_file_get(struct io_submit_state *state,
1033                                 struct io_kiocb *req, int fd, bool fixed);
1034 static void __io_queue_sqe(struct io_kiocb *req);
1035 static void io_rsrc_put_work(struct work_struct *work);
1036 
1037 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1038                            struct iov_iter *iter, bool needs_lock);
1039 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1040                              const struct iovec *fast_iov,
1041                              struct iov_iter *iter, bool force);
1042 static void io_req_task_queue(struct io_kiocb *req);
1043 static void io_submit_flush_completions(struct io_comp_state *cs,
1044                                         struct io_ring_ctx *ctx);
1045 
1046 static struct kmem_cache *req_cachep;
1047 
1048 static const struct file_operations io_uring_fops;
1049 
1050 struct sock *io_uring_get_socket(struct file *file)
1051 {
1052 #if defined(CONFIG_UNIX)
1053         if (file->f_op == &io_uring_fops) {
1054                 struct io_ring_ctx *ctx = file->private_data;
1055 
1056                 return ctx->ring_sock->sk;
1057         }
1058 #endif
1059         return NULL;
1060 }
1061 EXPORT_SYMBOL(io_uring_get_socket);
1062 
1063 #define io_for_each_link(pos, head) \
1064         for (pos = (head); pos; pos = pos->link)
1065 
1066 static inline void io_clean_op(struct io_kiocb *req)
1067 {
1068         if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1069                 __io_clean_op(req);
1070 }
1071 
1072 static inline void io_set_resource_node(struct io_kiocb *req)
1073 {
1074         struct io_ring_ctx *ctx = req->ctx;
1075 
1076         if (!req->fixed_rsrc_refs) {
1077                 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1078                 percpu_ref_get(req->fixed_rsrc_refs);
1079         }
1080 }
1081 
1082 static bool io_match_task(struct io_kiocb *head,
1083                           struct task_struct *task,
1084                           struct files_struct *files)
1085 {
1086         struct io_kiocb *req;
1087 
1088         if (task && head->task != task) {
1089                 /* in terms of cancelation, always match if req task is dead */
1090                 if (head->task->flags & PF_EXITING)
1091                         return true;
1092                 return false;
1093         }
1094         if (!files)
1095                 return true;
1096 
1097         io_for_each_link(req, head) {
1098                 if (req->flags & REQ_F_INFLIGHT)
1099                         return true;
1100         }
1101         return false;
1102 }
1103 
1104 static inline void req_set_fail_links(struct io_kiocb *req)
1105 {
1106         if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1107                 req->flags |= REQ_F_FAIL_LINK;
1108 }
1109 
1110 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1111 {
1112         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1113 
1114         complete(&ctx->ref_comp);
1115 }
1116 
1117 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1118 {
1119         return !req->timeout.off;
1120 }
1121 
1122 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1123 {
1124         struct io_ring_ctx *ctx;
1125         int hash_bits;
1126 
1127         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1128         if (!ctx)
1129                 return NULL;
1130 
1131         /*
1132          * Use 5 bits less than the max cq entries, that should give us around
1133          * 32 entries per hash list if totally full and uniformly spread.
1134          */
1135         hash_bits = ilog2(p->cq_entries);
1136         hash_bits -= 5;
1137         if (hash_bits <= 0)
1138                 hash_bits = 1;
1139         ctx->cancel_hash_bits = hash_bits;
1140         ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1141                                         GFP_KERNEL);
1142         if (!ctx->cancel_hash)
1143                 goto err;
1144         __hash_init(ctx->cancel_hash, 1U << hash_bits);
1145 
1146         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1147                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1148                 goto err;
1149 
1150         ctx->flags = p->flags;
1151         init_waitqueue_head(&ctx->sqo_sq_wait);
1152         INIT_LIST_HEAD(&ctx->sqd_list);
1153         init_waitqueue_head(&ctx->cq_wait);
1154         INIT_LIST_HEAD(&ctx->cq_overflow_list);
1155         init_completion(&ctx->ref_comp);
1156         xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1157         xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1158         mutex_init(&ctx->uring_lock);
1159         init_waitqueue_head(&ctx->wait);
1160         spin_lock_init(&ctx->completion_lock);
1161         INIT_LIST_HEAD(&ctx->iopoll_list);
1162         INIT_LIST_HEAD(&ctx->defer_list);
1163         INIT_LIST_HEAD(&ctx->timeout_list);
1164         spin_lock_init(&ctx->inflight_lock);
1165         INIT_LIST_HEAD(&ctx->inflight_list);
1166         spin_lock_init(&ctx->rsrc_ref_lock);
1167         INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1168         INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1169         init_llist_head(&ctx->rsrc_put_llist);
1170         INIT_LIST_HEAD(&ctx->tctx_list);
1171         INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1172         INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1173         return ctx;
1174 err:
1175         kfree(ctx->cancel_hash);
1176         kfree(ctx);
1177         return NULL;
1178 }
1179 
1180 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1181 {
1182         if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1183                 struct io_ring_ctx *ctx = req->ctx;
1184 
1185                 return seq != ctx->cached_cq_tail
1186                                 + READ_ONCE(ctx->cached_cq_overflow);
1187         }
1188 
1189         return false;
1190 }
1191 
1192 static void io_req_track_inflight(struct io_kiocb *req)
1193 {
1194         struct io_ring_ctx *ctx = req->ctx;
1195 
1196         if (!(req->flags & REQ_F_INFLIGHT)) {
1197                 req->flags |= REQ_F_INFLIGHT;
1198 
1199                 spin_lock_irq(&ctx->inflight_lock);
1200                 list_add(&req->inflight_entry, &ctx->inflight_list);
1201                 spin_unlock_irq(&ctx->inflight_lock);
1202         }
1203 }
1204 
1205 static void io_prep_async_work(struct io_kiocb *req)
1206 {
1207         const struct io_op_def *def = &io_op_defs[req->opcode];
1208         struct io_ring_ctx *ctx = req->ctx;
1209 
1210         if (!req->work.creds)
1211                 req->work.creds = get_current_cred();
1212 
1213         if (req->flags & REQ_F_FORCE_ASYNC)
1214                 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1215 
1216         if (req->flags & REQ_F_ISREG) {
1217                 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1218                         io_wq_hash_work(&req->work, file_inode(req->file));
1219         } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1220                 if (def->unbound_nonreg_file)
1221                         req->work.flags |= IO_WQ_WORK_UNBOUND;
1222         }
1223 }
1224 
1225 static void io_prep_async_link(struct io_kiocb *req)
1226 {
1227         struct io_kiocb *cur;
1228 
1229         io_for_each_link(cur, req)
1230                 io_prep_async_work(cur);
1231 }
1232 
1233 static void io_queue_async_work(struct io_kiocb *req)
1234 {
1235         struct io_ring_ctx *ctx = req->ctx;
1236         struct io_kiocb *link = io_prep_linked_timeout(req);
1237         struct io_uring_task *tctx = req->task->io_uring;
1238 
1239         BUG_ON(!tctx);
1240         BUG_ON(!tctx->io_wq);
1241 
1242         /* init ->work of the whole link before punting */
1243         io_prep_async_link(req);
1244         trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1245                                         &req->work, req->flags);
1246         io_wq_enqueue(tctx->io_wq, &req->work);
1247         if (link)
1248                 io_queue_linked_timeout(link);
1249 }
1250 
1251 static void io_kill_timeout(struct io_kiocb *req, int status)
1252 {
1253         struct io_timeout_data *io = req->async_data;
1254         int ret;
1255 
1256         ret = hrtimer_try_to_cancel(&io->timer);
1257         if (ret != -1) {
1258                 atomic_set(&req->ctx->cq_timeouts,
1259                         atomic_read(&req->ctx->cq_timeouts) + 1);
1260                 list_del_init(&req->timeout.list);
1261                 io_cqring_fill_event(req, status);
1262                 io_put_req_deferred(req, 1);
1263         }
1264 }
1265 
1266 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1267 {
1268         do {
1269                 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1270                                                 struct io_defer_entry, list);
1271 
1272                 if (req_need_defer(de->req, de->seq))
1273                         break;
1274                 list_del_init(&de->list);
1275                 io_req_task_queue(de->req);
1276                 kfree(de);
1277         } while (!list_empty(&ctx->defer_list));
1278 }
1279 
1280 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1281 {
1282         u32 seq;
1283 
1284         if (list_empty(&ctx->timeout_list))
1285                 return;
1286 
1287         seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1288 
1289         do {
1290                 u32 events_needed, events_got;
1291                 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1292                                                 struct io_kiocb, timeout.list);
1293 
1294                 if (io_is_timeout_noseq(req))
1295                         break;
1296 
1297                 /*
1298                  * Since seq can easily wrap around over time, subtract
1299                  * the last seq at which timeouts were flushed before comparing.
1300                  * Assuming not more than 2^31-1 events have happened since,
1301                  * these subtractions won't have wrapped, so we can check if
1302                  * target is in [last_seq, current_seq] by comparing the two.
1303                  */
1304                 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1305                 events_got = seq - ctx->cq_last_tm_flush;
1306                 if (events_got < events_needed)
1307                         break;
1308 
1309                 list_del_init(&req->timeout.list);
1310                 io_kill_timeout(req, 0);
1311         } while (!list_empty(&ctx->timeout_list));
1312 
1313         ctx->cq_last_tm_flush = seq;
1314 }
1315 
1316 static void io_commit_cqring(struct io_ring_ctx *ctx)
1317 {
1318         io_flush_timeouts(ctx);
1319 
1320         /* order cqe stores with ring update */
1321         smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1322 
1323         if (unlikely(!list_empty(&ctx->defer_list)))
1324                 __io_queue_deferred(ctx);
1325 }
1326 
1327 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1328 {
1329         struct io_rings *r = ctx->rings;
1330 
1331         return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1332 }
1333 
1334 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1335 {
1336         return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1337 }
1338 
1339 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1340 {
1341         struct io_rings *rings = ctx->rings;
1342         unsigned tail;
1343 
1344         /*
1345          * writes to the cq entry need to come after reading head; the
1346          * control dependency is enough as we're using WRITE_ONCE to
1347          * fill the cq entry
1348          */
1349         if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1350                 return NULL;
1351 
1352         tail = ctx->cached_cq_tail++;
1353         return &rings->cqes[tail & ctx->cq_mask];
1354 }
1355 
1356 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1357 {
1358         if (!ctx->cq_ev_fd)
1359                 return false;
1360         if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1361                 return false;
1362         if (!ctx->eventfd_async)
1363                 return true;
1364         return io_wq_current_is_worker();
1365 }
1366 
1367 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1368 {
1369         /* see waitqueue_active() comment */
1370         smp_mb();
1371 
1372         if (waitqueue_active(&ctx->wait))
1373                 wake_up(&ctx->wait);
1374         if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1375                 wake_up(&ctx->sq_data->wait);
1376         if (io_should_trigger_evfd(ctx))
1377                 eventfd_signal(ctx->cq_ev_fd, 1);
1378         if (waitqueue_active(&ctx->cq_wait)) {
1379                 wake_up_interruptible(&ctx->cq_wait);
1380                 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1381         }
1382 }
1383 
1384 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1385 {
1386         /* see waitqueue_active() comment */
1387         smp_mb();
1388 
1389         if (ctx->flags & IORING_SETUP_SQPOLL) {
1390                 if (waitqueue_active(&ctx->wait))
1391                         wake_up(&ctx->wait);
1392         }
1393         if (io_should_trigger_evfd(ctx))
1394                 eventfd_signal(ctx->cq_ev_fd, 1);
1395         if (waitqueue_active(&ctx->cq_wait)) {
1396                 wake_up_interruptible(&ctx->cq_wait);
1397                 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1398         }
1399 }
1400 
1401 /* Returns true if there are no backlogged entries after the flush */
1402 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1403                                        struct task_struct *tsk,
1404                                        struct files_struct *files)
1405 {
1406         struct io_rings *rings = ctx->rings;
1407         struct io_kiocb *req, *tmp;
1408         struct io_uring_cqe *cqe;
1409         unsigned long flags;
1410         bool all_flushed, posted;
1411         LIST_HEAD(list);
1412 
1413         if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1414                 return false;
1415 
1416         posted = false;
1417         spin_lock_irqsave(&ctx->completion_lock, flags);
1418         list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1419                 if (!io_match_task(req, tsk, files))
1420                         continue;
1421 
1422                 cqe = io_get_cqring(ctx);
1423                 if (!cqe && !force)
1424                         break;
1425 
1426                 list_move(&req->compl.list, &list);
1427                 if (cqe) {
1428                         WRITE_ONCE(cqe->user_data, req->user_data);
1429                         WRITE_ONCE(cqe->res, req->result);
1430                         WRITE_ONCE(cqe->flags, req->compl.cflags);
1431                 } else {
1432                         ctx->cached_cq_overflow++;
1433                         WRITE_ONCE(ctx->rings->cq_overflow,
1434                                    ctx->cached_cq_overflow);
1435                 }
1436                 posted = true;
1437         }
1438 
1439         all_flushed = list_empty(&ctx->cq_overflow_list);
1440         if (all_flushed) {
1441                 clear_bit(0, &ctx->sq_check_overflow);
1442                 clear_bit(0, &ctx->cq_check_overflow);
1443                 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1444         }
1445 
1446         if (posted)
1447                 io_commit_cqring(ctx);
1448         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1449         if (posted)
1450                 io_cqring_ev_posted(ctx);
1451 
1452         while (!list_empty(&list)) {
1453                 req = list_first_entry(&list, struct io_kiocb, compl.list);
1454                 list_del(&req->compl.list);
1455                 io_put_req(req);
1456         }
1457 
1458         return all_flushed;
1459 }
1460 
1461 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1462                                      struct task_struct *tsk,
1463                                      struct files_struct *files)
1464 {
1465         bool ret = true;
1466 
1467         if (test_bit(0, &ctx->cq_check_overflow)) {
1468                 /* iopoll syncs against uring_lock, not completion_lock */
1469                 if (ctx->flags & IORING_SETUP_IOPOLL)
1470                         mutex_lock(&ctx->uring_lock);
1471                 ret = __io_cqring_overflow_flush(ctx, force, tsk, files);
1472                 if (ctx->flags & IORING_SETUP_IOPOLL)
1473                         mutex_unlock(&ctx->uring_lock);
1474         }
1475 
1476         return ret;
1477 }
1478 
1479 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1480 {
1481         return refcount_inc_not_zero(&req->refs);
1482 }
1483 
1484 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1485 {
1486         return refcount_sub_and_test(refs, &req->refs);
1487 }
1488 
1489 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1490 {
1491         return refcount_dec_and_test(&req->refs);
1492 }
1493 
1494 static inline void req_ref_put(struct io_kiocb *req)
1495 {
1496         refcount_dec(&req->refs);
1497 }
1498 
1499 static inline void req_ref_get(struct io_kiocb *req)
1500 {
1501         refcount_inc(&req->refs);
1502 }
1503 
1504 static void __io_cqring_fill_event(struct io_kiocb *req, long res,
1505                                    unsigned int cflags)
1506 {
1507         struct io_ring_ctx *ctx = req->ctx;
1508         struct io_uring_cqe *cqe;
1509 
1510         trace_io_uring_complete(ctx, req->user_data, res);
1511 
1512         /*
1513          * If we can't get a cq entry, userspace overflowed the
1514          * submission (by quite a lot). Increment the overflow count in
1515          * the ring.
1516          */
1517         cqe = io_get_cqring(ctx);
1518         if (likely(cqe)) {
1519                 WRITE_ONCE(cqe->user_data, req->user_data);
1520                 WRITE_ONCE(cqe->res, res);
1521                 WRITE_ONCE(cqe->flags, cflags);
1522         } else if (ctx->cq_overflow_flushed ||
1523                    atomic_read(&req->task->io_uring->in_idle)) {
1524                 /*
1525                  * If we're in ring overflow flush mode, or in task cancel mode,
1526                  * then we cannot store the request for later flushing, we need
1527                  * to drop it on the floor.
1528                  */
1529                 ctx->cached_cq_overflow++;
1530                 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1531         } else {
1532                 if (list_empty(&ctx->cq_overflow_list)) {
1533                         set_bit(0, &ctx->sq_check_overflow);
1534                         set_bit(0, &ctx->cq_check_overflow);
1535                         ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1536                 }
1537                 io_clean_op(req);
1538                 req->result = res;
1539                 req->compl.cflags = cflags;
1540                 req_ref_get(req);
1541                 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1542         }
1543 }
1544 
1545 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1546 {
1547         __io_cqring_fill_event(req, res, 0);
1548 }
1549 
1550 static void io_req_complete_post(struct io_kiocb *req, long res,
1551                                  unsigned int cflags)
1552 {
1553         struct io_ring_ctx *ctx = req->ctx;
1554         unsigned long flags;
1555 
1556         spin_lock_irqsave(&ctx->completion_lock, flags);
1557         __io_cqring_fill_event(req, res, cflags);
1558         /*
1559          * If we're the last reference to this request, add to our locked
1560          * free_list cache.
1561          */
1562         if (req_ref_put_and_test(req)) {
1563                 struct io_comp_state *cs = &ctx->submit_state.comp;
1564 
1565                 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1566                         if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
1567                                 io_disarm_next(req);
1568                         if (req->link) {
1569                                 io_req_task_queue(req->link);
1570                                 req->link = NULL;
1571                         }
1572                 }
1573                 io_dismantle_req(req);
1574                 io_put_task(req->task, 1);
1575                 list_add(&req->compl.list, &cs->locked_free_list);
1576                 cs->locked_free_nr++;
1577         } else {
1578                 if (!percpu_ref_tryget(&ctx->refs))
1579                         req = NULL;
1580         }
1581         io_commit_cqring(ctx);
1582         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1583 
1584         if (req) {
1585                 io_cqring_ev_posted(ctx);
1586                 percpu_ref_put(&ctx->refs);
1587         }
1588 }
1589 
1590 static void io_req_complete_state(struct io_kiocb *req, long res,
1591                                   unsigned int cflags)
1592 {
1593         io_clean_op(req);
1594         req->result = res;
1595         req->compl.cflags = cflags;
1596         req->flags |= REQ_F_COMPLETE_INLINE;
1597 }
1598 
1599 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1600                                      long res, unsigned cflags)
1601 {
1602         if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1603                 io_req_complete_state(req, res, cflags);
1604         else
1605                 io_req_complete_post(req, res, cflags);
1606 }
1607 
1608 static inline void io_req_complete(struct io_kiocb *req, long res)
1609 {
1610         __io_req_complete(req, 0, res, 0);
1611 }
1612 
1613 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1614 {
1615         struct io_submit_state *state = &ctx->submit_state;
1616         struct io_comp_state *cs = &state->comp;
1617         struct io_kiocb *req = NULL;
1618 
1619         /*
1620          * If we have more than a batch's worth of requests in our IRQ side
1621          * locked cache, grab the lock and move them over to our submission
1622          * side cache.
1623          */
1624         if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1625                 spin_lock_irq(&ctx->completion_lock);
1626                 list_splice_init(&cs->locked_free_list, &cs->free_list);
1627                 cs->locked_free_nr = 0;
1628                 spin_unlock_irq(&ctx->completion_lock);
1629         }
1630 
1631         while (!list_empty(&cs->free_list)) {
1632                 req = list_first_entry(&cs->free_list, struct io_kiocb,
1633                                         compl.list);
1634                 list_del(&req->compl.list);
1635                 state->reqs[state->free_reqs++] = req;
1636                 if (state->free_reqs == ARRAY_SIZE(state->reqs))
1637                         break;
1638         }
1639 
1640         return req != NULL;
1641 }
1642 
1643 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1644 {
1645         struct io_submit_state *state = &ctx->submit_state;
1646 
1647         BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1648 
1649         if (!state->free_reqs) {
1650                 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1651                 int ret;
1652 
1653                 if (io_flush_cached_reqs(ctx))
1654                         goto got_req;
1655 
1656                 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1657                                             state->reqs);
1658 
1659                 /*
1660                  * Bulk alloc is all-or-nothing. If we fail to get a batch,
1661                  * retry single alloc to be on the safe side.
1662                  */
1663                 if (unlikely(ret <= 0)) {
1664                         state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1665                         if (!state->reqs[0])
1666                                 return NULL;
1667                         ret = 1;
1668                 }
1669                 state->free_reqs = ret;
1670         }
1671 got_req:
1672         state->free_reqs--;
1673         return state->reqs[state->free_reqs];
1674 }
1675 
1676 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1677                           bool fixed)
1678 {
1679         if (!fixed)
1680                 fput(file);
1681 }
1682 
1683 static void io_dismantle_req(struct io_kiocb *req)
1684 {
1685         io_clean_op(req);
1686 
1687         if (req->async_data)
1688                 kfree(req->async_data);
1689         if (req->file)
1690                 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1691         if (req->fixed_rsrc_refs)
1692                 percpu_ref_put(req->fixed_rsrc_refs);
1693         if (req->work.creds) {
1694                 put_cred(req->work.creds);
1695                 req->work.creds = NULL;
1696         }
1697 
1698         if (req->flags & REQ_F_INFLIGHT) {
1699                 struct io_ring_ctx *ctx = req->ctx;
1700                 unsigned long flags;
1701 
1702                 spin_lock_irqsave(&ctx->inflight_lock, flags);
1703                 list_del(&req->inflight_entry);
1704                 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1705                 req->flags &= ~REQ_F_INFLIGHT;
1706         }
1707 }
1708 
1709 /* must to be called somewhat shortly after putting a request */
1710 static inline void io_put_task(struct task_struct *task, int nr)
1711 {
1712         struct io_uring_task *tctx = task->io_uring;
1713 
1714         percpu_counter_sub(&tctx->inflight, nr);
1715         if (unlikely(atomic_read(&tctx->in_idle)))
1716                 wake_up(&tctx->wait);
1717         put_task_struct_many(task, nr);
1718 }
1719 
1720 static void __io_free_req(struct io_kiocb *req)
1721 {
1722         struct io_ring_ctx *ctx = req->ctx;
1723 
1724         io_dismantle_req(req);
1725         io_put_task(req->task, 1);
1726 
1727         kmem_cache_free(req_cachep, req);
1728         percpu_ref_put(&ctx->refs);
1729 }
1730 
1731 static inline void io_remove_next_linked(struct io_kiocb *req)
1732 {
1733         struct io_kiocb *nxt = req->link;
1734 
1735         req->link = nxt->link;
1736         nxt->link = NULL;
1737 }
1738 
1739 static bool io_kill_linked_timeout(struct io_kiocb *req)
1740         __must_hold(&req->ctx->completion_lock)
1741 {
1742         struct io_kiocb *link = req->link;
1743         bool cancelled = false;
1744 
1745         /*
1746          * Can happen if a linked timeout fired and link had been like
1747          * req -> link t-out -> link t-out [-> ...]
1748          */
1749         if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1750                 struct io_timeout_data *io = link->async_data;
1751                 int ret;
1752 
1753                 io_remove_next_linked(req);
1754                 link->timeout.head = NULL;
1755                 ret = hrtimer_try_to_cancel(&io->timer);
1756                 if (ret != -1) {
1757                         io_cqring_fill_event(link, -ECANCELED);
1758                         io_put_req_deferred(link, 1);
1759                         cancelled = true;
1760                 }
1761         }
1762         req->flags &= ~REQ_F_LINK_TIMEOUT;
1763         return cancelled;
1764 }
1765 
1766 static void io_fail_links(struct io_kiocb *req)
1767         __must_hold(&req->ctx->completion_lock)
1768 {
1769         struct io_kiocb *nxt, *link = req->link;
1770 
1771         req->link = NULL;
1772         while (link) {
1773                 nxt = link->link;
1774                 link->link = NULL;
1775 
1776                 trace_io_uring_fail_link(req, link);
1777                 io_cqring_fill_event(link, -ECANCELED);
1778                 io_put_req_deferred(link, 2);
1779                 link = nxt;
1780         }
1781 }
1782 
1783 static bool io_disarm_next(struct io_kiocb *req)
1784         __must_hold(&req->ctx->completion_lock)
1785 {
1786         bool posted = false;
1787 
1788         if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1789                 posted = io_kill_linked_timeout(req);
1790         if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
1791                 posted |= (req->link != NULL);
1792                 io_fail_links(req);
1793         }
1794         return posted;
1795 }
1796 
1797 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1798 {
1799         struct io_kiocb *nxt;
1800 
1801         /*
1802          * If LINK is set, we have dependent requests in this chain. If we
1803          * didn't fail this request, queue the first one up, moving any other
1804          * dependencies to the next request. In case of failure, fail the rest
1805          * of the chain.
1806          */
1807         if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK)) {
1808                 struct io_ring_ctx *ctx = req->ctx;
1809                 unsigned long flags;
1810                 bool posted;
1811 
1812                 spin_lock_irqsave(&ctx->completion_lock, flags);
1813                 posted = io_disarm_next(req);
1814                 if (posted)
1815                         io_commit_cqring(req->ctx);
1816                 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1817                 if (posted)
1818                         io_cqring_ev_posted(ctx);
1819         }
1820         nxt = req->link;
1821         req->link = NULL;
1822         return nxt;
1823 }
1824 
1825 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1826 {
1827         if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1828                 return NULL;
1829         return __io_req_find_next(req);
1830 }
1831 
1832 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1833 {
1834         if (!ctx)
1835                 return;
1836         if (ctx->submit_state.comp.nr) {
1837                 mutex_lock(&ctx->uring_lock);
1838                 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1839                 mutex_unlock(&ctx->uring_lock);
1840         }
1841         percpu_ref_put(&ctx->refs);
1842 }
1843 
1844 static bool __tctx_task_work(struct io_uring_task *tctx)
1845 {
1846         struct io_ring_ctx *ctx = NULL;
1847         struct io_wq_work_list list;
1848         struct io_wq_work_node *node;
1849 
1850         if (wq_list_empty(&tctx->task_list))
1851                 return false;
1852 
1853         spin_lock_irq(&tctx->task_lock);
1854         list = tctx->task_list;
1855         INIT_WQ_LIST(&tctx->task_list);
1856         spin_unlock_irq(&tctx->task_lock);
1857 
1858         node = list.first;
1859         while (node) {
1860                 struct io_wq_work_node *next = node->next;
1861                 struct io_kiocb *req;
1862 
1863                 req = container_of(node, struct io_kiocb, io_task_work.node);
1864                 if (req->ctx != ctx) {
1865                         ctx_flush_and_put(ctx);
1866                         ctx = req->ctx;
1867                         percpu_ref_get(&ctx->refs);
1868                 }
1869 
1870                 req->task_work.func(&req->task_work);
1871                 node = next;
1872         }
1873 
1874         ctx_flush_and_put(ctx);
1875         return list.first != NULL;
1876 }
1877 
1878 static void tctx_task_work(struct callback_head *cb)
1879 {
1880         struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1881 
1882         clear_bit(0, &tctx->task_state);
1883 
1884         while (__tctx_task_work(tctx))
1885                 cond_resched();
1886 }
1887 
1888 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
1889                             enum task_work_notify_mode notify)
1890 {
1891         struct io_uring_task *tctx = tsk->io_uring;
1892         struct io_wq_work_node *node, *prev;
1893         unsigned long flags;
1894         int ret;
1895 
1896         WARN_ON_ONCE(!tctx);
1897 
1898         spin_lock_irqsave(&tctx->task_lock, flags);
1899         wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1900         spin_unlock_irqrestore(&tctx->task_lock, flags);
1901 
1902         /* task_work already pending, we're done */
1903         if (test_bit(0, &tctx->task_state) ||
1904             test_and_set_bit(0, &tctx->task_state))
1905                 return 0;
1906 
1907         if (!task_work_add(tsk, &tctx->task_work, notify))
1908                 return 0;
1909 
1910         /*
1911          * Slow path - we failed, find and delete work. if the work is not
1912          * in the list, it got run and we're fine.
1913          */
1914         ret = 0;
1915         spin_lock_irqsave(&tctx->task_lock, flags);
1916         wq_list_for_each(node, prev, &tctx->task_list) {
1917                 if (&req->io_task_work.node == node) {
1918                         wq_list_del(&tctx->task_list, node, prev);
1919                         ret = 1;
1920                         break;
1921                 }
1922         }
1923         spin_unlock_irqrestore(&tctx->task_lock, flags);
1924         clear_bit(0, &tctx->task_state);
1925         return ret;
1926 }
1927 
1928 static int io_req_task_work_add(struct io_kiocb *req)
1929 {
1930         struct task_struct *tsk = req->task;
1931         struct io_ring_ctx *ctx = req->ctx;
1932         enum task_work_notify_mode notify;
1933         int ret;
1934 
1935         if (tsk->flags & PF_EXITING)
1936                 return -ESRCH;
1937 
1938         /*
1939          * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1940          * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1941          * processing task_work. There's no reliable way to tell if TWA_RESUME
1942          * will do the job.
1943          */
1944         notify = TWA_NONE;
1945         if (!(ctx->flags & IORING_SETUP_SQPOLL))
1946                 notify = TWA_SIGNAL;
1947 
1948         ret = io_task_work_add(tsk, req, notify);
1949         if (!ret)
1950                 wake_up_process(tsk);
1951 
1952         return ret;
1953 }
1954 
1955 static bool io_run_task_work_head(struct callback_head **work_head)
1956 {
1957         struct callback_head *work, *next;
1958         bool executed = false;
1959 
1960         do {
1961                 work = xchg(work_head, NULL);
1962                 if (!work)
1963                         break;
1964 
1965                 do {
1966                         next = work->next;
1967                         work->func(work);
1968                         work = next;
1969                         cond_resched();
1970                 } while (work);
1971                 executed = true;
1972         } while (1);
1973 
1974         return executed;
1975 }
1976 
1977 static void io_task_work_add_head(struct callback_head **work_head,
1978                                   struct callback_head *task_work)
1979 {
1980         struct callback_head *head;
1981 
1982         do {
1983                 head = READ_ONCE(*work_head);
1984                 task_work->next = head;
1985         } while (cmpxchg(work_head, head, task_work) != head);
1986 }
1987 
1988 static void io_req_task_work_add_fallback(struct io_kiocb *req,
1989                                           task_work_func_t cb)
1990 {
1991         init_task_work(&req->task_work, cb);
1992         io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
1993 }
1994 
1995 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1996 {
1997         struct io_ring_ctx *ctx = req->ctx;
1998 
1999         spin_lock_irq(&ctx->completion_lock);
2000         io_cqring_fill_event(req, error);
2001         io_commit_cqring(ctx);
2002         spin_unlock_irq(&ctx->completion_lock);
2003 
2004         io_cqring_ev_posted(ctx);
2005         req_set_fail_links(req);
2006         io_double_put_req(req);
2007 }
2008 
2009 static void io_req_task_cancel(struct callback_head *cb)
2010 {
2011         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2012         struct io_ring_ctx *ctx = req->ctx;
2013 
2014         mutex_lock(&ctx->uring_lock);
2015         __io_req_task_cancel(req, req->result);
2016         mutex_unlock(&ctx->uring_lock);
2017         percpu_ref_put(&ctx->refs);
2018 }
2019 
2020 static void __io_req_task_submit(struct io_kiocb *req)
2021 {
2022         struct io_ring_ctx *ctx = req->ctx;
2023 
2024         /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2025         mutex_lock(&ctx->uring_lock);
2026         if (!(req->task->flags & PF_EXITING) && !req->task->in_execve)
2027                 __io_queue_sqe(req);
2028         else
2029                 __io_req_task_cancel(req, -EFAULT);
2030         mutex_unlock(&ctx->uring_lock);
2031 }
2032 
2033 static void io_req_task_submit(struct callback_head *cb)
2034 {
2035         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2036 
2037         __io_req_task_submit(req);
2038 }
2039 
2040 static void io_req_task_queue(struct io_kiocb *req)
2041 {
2042         int ret;
2043 
2044         req->task_work.func = io_req_task_submit;
2045         ret = io_req_task_work_add(req);
2046         if (unlikely(ret)) {
2047                 req->result = -ECANCELED;
2048                 percpu_ref_get(&req->ctx->refs);
2049                 io_req_task_work_add_fallback(req, io_req_task_cancel);
2050         }
2051 }
2052 
2053 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2054 {
2055         percpu_ref_get(&req->ctx->refs);
2056         req->result = ret;
2057         req->task_work.func = io_req_task_cancel;
2058 
2059         if (unlikely(io_req_task_work_add(req)))
2060                 io_req_task_work_add_fallback(req, io_req_task_cancel);
2061 }
2062 
2063 static inline void io_queue_next(struct io_kiocb *req)
2064 {
2065         struct io_kiocb *nxt = io_req_find_next(req);
2066 
2067         if (nxt)
2068                 io_req_task_queue(nxt);
2069 }
2070 
2071 static void io_free_req(struct io_kiocb *req)
2072 {
2073         io_queue_next(req);
2074         __io_free_req(req);
2075 }
2076 
2077 struct req_batch {
2078         struct task_struct      *task;
2079         int                     task_refs;
2080         int                     ctx_refs;
2081 };
2082 
2083 static inline void io_init_req_batch(struct req_batch *rb)
2084 {
2085         rb->task_refs = 0;
2086         rb->ctx_refs = 0;
2087         rb->task = NULL;
2088 }
2089 
2090 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2091                                      struct req_batch *rb)
2092 {
2093         if (rb->task)
2094                 io_put_task(rb->task, rb->task_refs);
2095         if (rb->ctx_refs)
2096                 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2097 }
2098 
2099 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2100                               struct io_submit_state *state)
2101 {
2102         io_queue_next(req);
2103 
2104         if (req->task != rb->task) {
2105                 if (rb->task)
2106                         io_put_task(rb->task, rb->task_refs);
2107                 rb->task = req->task;
2108                 rb->task_refs = 0;
2109         }
2110         rb->task_refs++;
2111         rb->ctx_refs++;
2112 
2113         io_dismantle_req(req);
2114         if (state->free_reqs != ARRAY_SIZE(state->reqs))
2115                 state->reqs[state->free_reqs++] = req;
2116         else
2117                 list_add(&req->compl.list, &state->comp.free_list);
2118 }
2119 
2120 static void io_submit_flush_completions(struct io_comp_state *cs,
2121                                         struct io_ring_ctx *ctx)
2122 {
2123         int i, nr = cs->nr;
2124         struct io_kiocb *req;
2125         struct req_batch rb;
2126 
2127         io_init_req_batch(&rb);
2128         spin_lock_irq(&ctx->completion_lock);
2129         for (i = 0; i < nr; i++) {
2130                 req = cs->reqs[i];
2131                 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2132         }
2133         io_commit_cqring(ctx);
2134         spin_unlock_irq(&ctx->completion_lock);
2135 
2136         io_cqring_ev_posted(ctx);
2137         for (i = 0; i < nr; i++) {
2138                 req = cs->reqs[i];
2139 
2140                 /* submission and completion refs */
2141                 if (req_ref_sub_and_test(req, 2))
2142                         io_req_free_batch(&rb, req, &ctx->submit_state);
2143         }
2144 
2145         io_req_free_batch_finish(ctx, &rb);
2146         cs->nr = 0;
2147 }
2148 
2149 /*
2150  * Drop reference to request, return next in chain (if there is one) if this
2151  * was the last reference to this request.
2152  */
2153 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2154 {
2155         struct io_kiocb *nxt = NULL;
2156 
2157         if (req_ref_put_and_test(req)) {
2158                 nxt = io_req_find_next(req);
2159                 __io_free_req(req);
2160         }
2161         return nxt;
2162 }
2163 
2164 static void io_put_req(struct io_kiocb *req)
2165 {
2166         if (req_ref_put_and_test(req))
2167                 io_free_req(req);
2168 }
2169 
2170 static void io_put_req_deferred_cb(struct callback_head *cb)
2171 {
2172         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2173 
2174         io_free_req(req);
2175 }
2176 
2177 static void io_free_req_deferred(struct io_kiocb *req)
2178 {
2179         int ret;
2180 
2181         req->task_work.func = io_put_req_deferred_cb;
2182         ret = io_req_task_work_add(req);
2183         if (unlikely(ret))
2184                 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2185 }
2186 
2187 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2188 {
2189         if (req_ref_sub_and_test(req, refs))
2190                 io_free_req_deferred(req);
2191 }
2192 
2193 static void io_double_put_req(struct io_kiocb *req)
2194 {
2195         /* drop both submit and complete references */
2196         if (req_ref_sub_and_test(req, 2))
2197                 io_free_req(req);
2198 }
2199 
2200 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2201 {
2202         /* See comment at the top of this file */
2203         smp_rmb();
2204         return __io_cqring_events(ctx);
2205 }
2206 
2207 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2208 {
2209         struct io_rings *rings = ctx->rings;
2210 
2211         /* make sure SQ entry isn't read before tail */
2212         return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2213 }
2214 
2215 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2216 {
2217         unsigned int cflags;
2218 
2219         cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2220         cflags |= IORING_CQE_F_BUFFER;
2221         req->flags &= ~REQ_F_BUFFER_SELECTED;
2222         kfree(kbuf);
2223         return cflags;
2224 }
2225 
2226 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2227 {
2228         struct io_buffer *kbuf;
2229 
2230         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2231         return io_put_kbuf(req, kbuf);
2232 }
2233 
2234 static inline bool io_run_task_work(void)
2235 {
2236         /*
2237          * Not safe to run on exiting task, and the task_work handling will
2238          * not add work to such a task.
2239          */
2240         if (unlikely(current->flags & PF_EXITING))
2241                 return false;
2242         if (current->task_works) {
2243                 __set_current_state(TASK_RUNNING);
2244                 task_work_run();
2245                 return true;
2246         }
2247 
2248         return false;
2249 }
2250 
2251 /*
2252  * Find and free completed poll iocbs
2253  */
2254 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2255                                struct list_head *done)
2256 {
2257         struct req_batch rb;
2258         struct io_kiocb *req;
2259 
2260         /* order with ->result store in io_complete_rw_iopoll() */
2261         smp_rmb();
2262 
2263         io_init_req_batch(&rb);
2264         while (!list_empty(done)) {
2265                 int cflags = 0;
2266 
2267                 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2268                 list_del(&req->inflight_entry);
2269 
2270                 if (READ_ONCE(req->result) == -EAGAIN) {
2271                         req->iopoll_completed = 0;
2272                         if (io_rw_reissue(req))
2273                                 continue;
2274                 }
2275 
2276                 if (req->flags & REQ_F_BUFFER_SELECTED)
2277                         cflags = io_put_rw_kbuf(req);
2278 
2279                 __io_cqring_fill_event(req, req->result, cflags);
2280                 (*nr_events)++;
2281 
2282                 if (req_ref_put_and_test(req))
2283                         io_req_free_batch(&rb, req, &ctx->submit_state);
2284         }
2285 
2286         io_commit_cqring(ctx);
2287         io_cqring_ev_posted_iopoll(ctx);
2288         io_req_free_batch_finish(ctx, &rb);
2289 }
2290 
2291 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2292                         long min)
2293 {
2294         struct io_kiocb *req, *tmp;
2295         LIST_HEAD(done);
2296         bool spin;
2297         int ret;
2298 
2299         /*
2300          * Only spin for completions if we don't have multiple devices hanging
2301          * off our complete list, and we're under the requested amount.
2302          */
2303         spin = !ctx->poll_multi_file && *nr_events < min;
2304 
2305         ret = 0;
2306         list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2307                 struct kiocb *kiocb = &req->rw.kiocb;
2308 
2309                 /*
2310                  * Move completed and retryable entries to our local lists.
2311                  * If we find a request that requires polling, break out
2312                  * and complete those lists first, if we have entries there.
2313                  */
2314                 if (READ_ONCE(req->iopoll_completed)) {
2315                         list_move_tail(&req->inflight_entry, &done);
2316                         continue;
2317                 }
2318                 if (!list_empty(&done))
2319                         break;
2320 
2321                 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2322                 if (ret < 0)
2323                         break;
2324 
2325                 /* iopoll may have completed current req */
2326                 if (READ_ONCE(req->iopoll_completed))
2327                         list_move_tail(&req->inflight_entry, &done);
2328 
2329                 if (ret && spin)
2330                         spin = false;
2331                 ret = 0;
2332         }
2333 
2334         if (!list_empty(&done))
2335                 io_iopoll_complete(ctx, nr_events, &done);
2336 
2337         return ret;
2338 }
2339 
2340 /*
2341  * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2342  * non-spinning poll check - we'll still enter the driver poll loop, but only
2343  * as a non-spinning completion check.
2344  */
2345 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2346                                 long min)
2347 {
2348         while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2349                 int ret;
2350 
2351                 ret = io_do_iopoll(ctx, nr_events, min);
2352                 if (ret < 0)
2353                         return ret;
2354                 if (*nr_events >= min)
2355                         return 0;
2356         }
2357 
2358         return 1;
2359 }
2360 
2361 /*
2362  * We can't just wait for polled events to come to us, we have to actively
2363  * find and complete them.
2364  */
2365 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2366 {
2367         if (!(ctx->flags & IORING_SETUP_IOPOLL))
2368                 return;
2369 
2370         mutex_lock(&ctx->uring_lock);
2371         while (!list_empty(&ctx->iopoll_list)) {
2372                 unsigned int nr_events = 0;
2373 
2374                 io_do_iopoll(ctx, &nr_events, 0);
2375 
2376                 /* let it sleep and repeat later if can't complete a request */
2377                 if (nr_events == 0)
2378                         break;
2379                 /*
2380                  * Ensure we allow local-to-the-cpu processing to take place,
2381                  * in this case we need to ensure that we reap all events.
2382                  * Also let task_work, etc. to progress by releasing the mutex
2383                  */
2384                 if (need_resched()) {
2385                         mutex_unlock(&ctx->uring_lock);
2386                         cond_resched();
2387                         mutex_lock(&ctx->uring_lock);
2388                 }
2389         }
2390         mutex_unlock(&ctx->uring_lock);
2391 }
2392 
2393 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2394 {
2395         unsigned int nr_events = 0;
2396         int iters = 0, ret = 0;
2397 
2398         /*
2399          * We disallow the app entering submit/complete with polling, but we
2400          * still need to lock the ring to prevent racing with polled issue
2401          * that got punted to a workqueue.
2402          */
2403         mutex_lock(&ctx->uring_lock);
2404         do {
2405                 /*
2406                  * Don't enter poll loop if we already have events pending.
2407                  * If we do, we can potentially be spinning for commands that
2408                  * already triggered a CQE (eg in error).
2409                  */
2410                 if (test_bit(0, &ctx->cq_check_overflow))
2411                         __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2412                 if (io_cqring_events(ctx))
2413                         break;
2414 
2415                 /*
2416                  * If a submit got punted to a workqueue, we can have the
2417                  * application entering polling for a command before it gets
2418                  * issued. That app will hold the uring_lock for the duration
2419                  * of the poll right here, so we need to take a breather every
2420                  * now and then to ensure that the issue has a chance to add
2421                  * the poll to the issued list. Otherwise we can spin here
2422                  * forever, while the workqueue is stuck trying to acquire the
2423                  * very same mutex.
2424                  */
2425                 if (!(++iters & 7)) {
2426                         mutex_unlock(&ctx->uring_lock);
2427                         io_run_task_work();
2428                         mutex_lock(&ctx->uring_lock);
2429                 }
2430 
2431                 ret = io_iopoll_getevents(ctx, &nr_events, min);
2432                 if (ret <= 0)
2433                         break;
2434                 ret = 0;
2435         } while (min && !nr_events && !need_resched());
2436 
2437         mutex_unlock(&ctx->uring_lock);
2438         return ret;
2439 }
2440 
2441 static void kiocb_end_write(struct io_kiocb *req)
2442 {
2443         /*
2444          * Tell lockdep we inherited freeze protection from submission
2445          * thread.
2446          */
2447         if (req->flags & REQ_F_ISREG) {
2448                 struct inode *inode = file_inode(req->file);
2449 
2450                 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2451         }
2452         file_end_write(req->file);
2453 }
2454 
2455 #ifdef CONFIG_BLOCK
2456 static bool io_resubmit_prep(struct io_kiocb *req)
2457 {
2458         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2459         int rw, ret;
2460         struct iov_iter iter;
2461 
2462         /* already prepared */
2463         if (req->async_data)
2464                 return true;
2465 
2466         switch (req->opcode) {
2467         case IORING_OP_READV:
2468         case IORING_OP_READ_FIXED:
2469         case IORING_OP_READ:
2470                 rw = READ;
2471                 break;
2472         case IORING_OP_WRITEV:
2473         case IORING_OP_WRITE_FIXED:
2474         case IORING_OP_WRITE:
2475                 rw = WRITE;
2476                 break;
2477         default:
2478                 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2479                                 req->opcode);
2480                 return false;
2481         }
2482 
2483         ret = io_import_iovec(rw, req, &iovec, &iter, false);
2484         if (ret < 0)
2485                 return false;
2486         return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2487 }
2488 
2489 static bool io_rw_should_reissue(struct io_kiocb *req)
2490 {
2491         umode_t mode = file_inode(req->file)->i_mode;
2492         struct io_ring_ctx *ctx = req->ctx;
2493 
2494         if (!S_ISBLK(mode) && !S_ISREG(mode))
2495                 return false;
2496         if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2497             !(ctx->flags & IORING_SETUP_IOPOLL)))
2498                 return false;
2499         /*
2500          * If ref is dying, we might be running poll reap from the exit work.
2501          * Don't attempt to reissue from that path, just let it fail with
2502          * -EAGAIN.
2503          */
2504         if (percpu_ref_is_dying(&ctx->refs))
2505                 return false;
2506         return true;
2507 }
2508 #else
2509 static bool io_rw_should_reissue(struct io_kiocb *req)
2510 {
2511         return false;
2512 }
2513 #endif
2514 
2515 static bool io_rw_reissue(struct io_kiocb *req)
2516 {
2517 #ifdef CONFIG_BLOCK
2518         if (!io_rw_should_reissue(req))
2519                 return false;
2520 
2521         lockdep_assert_held(&req->ctx->uring_lock);
2522 
2523         if (io_resubmit_prep(req)) {
2524                 req_ref_get(req);
2525                 io_queue_async_work(req);
2526                 return true;
2527         }
2528         req_set_fail_links(req);
2529 #endif
2530         return false;
2531 }
2532 
2533 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2534                              unsigned int issue_flags)
2535 {
2536         int cflags = 0;
2537 
2538         if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2539                 kiocb_end_write(req);
2540         if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_should_reissue(req)) {
2541                 req->flags |= REQ_F_REISSUE;
2542                 return;
2543         }
2544         if (res != req->result)
2545                 req_set_fail_links(req);
2546         if (req->flags & REQ_F_BUFFER_SELECTED)
2547                 cflags = io_put_rw_kbuf(req);
2548         __io_req_complete(req, issue_flags, res, cflags);
2549 }
2550 
2551 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2552 {
2553         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2554 
2555         __io_complete_rw(req, res, res2, 0);
2556 }
2557 
2558 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2559 {
2560         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2561 
2562 #ifdef CONFIG_BLOCK
2563         /* Rewind iter, if we have one. iopoll path resubmits as usual */
2564         if (res == -EAGAIN && io_rw_should_reissue(req)) {
2565                 struct io_async_rw *rw = req->async_data;
2566 
2567                 if (rw)
2568                         iov_iter_revert(&rw->iter,
2569                                         req->result - iov_iter_count(&rw->iter));
2570                 else if (!io_resubmit_prep(req))
2571                         res = -EIO;
2572         }
2573 #endif
2574 
2575         if (kiocb->ki_flags & IOCB_WRITE)
2576                 kiocb_end_write(req);
2577 
2578         if (res != -EAGAIN && res != req->result)
2579                 req_set_fail_links(req);
2580 
2581         WRITE_ONCE(req->result, res);
2582         /* order with io_poll_complete() checking ->result */
2583         smp_wmb();
2584         WRITE_ONCE(req->iopoll_completed, 1);
2585 }
2586 
2587 /*
2588  * After the iocb has been issued, it's safe to be found on the poll list.
2589  * Adding the kiocb to the list AFTER submission ensures that we don't
2590  * find it from a io_iopoll_getevents() thread before the issuer is done
2591  * accessing the kiocb cookie.
2592  */
2593 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2594 {
2595         struct io_ring_ctx *ctx = req->ctx;
2596 
2597         /*
2598          * Track whether we have multiple files in our lists. This will impact
2599          * how we do polling eventually, not spinning if we're on potentially
2600          * different devices.
2601          */
2602         if (list_empty(&ctx->iopoll_list)) {
2603                 ctx->poll_multi_file = false;
2604         } else if (!ctx->poll_multi_file) {
2605                 struct io_kiocb *list_req;
2606 
2607                 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2608                                                 inflight_entry);
2609                 if (list_req->file != req->file)
2610                         ctx->poll_multi_file = true;
2611         }
2612 
2613         /*
2614          * For fast devices, IO may have already completed. If it has, add
2615          * it to the front so we find it first.
2616          */
2617         if (READ_ONCE(req->iopoll_completed))
2618                 list_add(&req->inflight_entry, &ctx->iopoll_list);
2619         else
2620                 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2621 
2622         /*
2623          * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2624          * task context or in io worker task context. If current task context is
2625          * sq thread, we don't need to check whether should wake up sq thread.
2626          */
2627         if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2628             wq_has_sleeper(&ctx->sq_data->wait))
2629                 wake_up(&ctx->sq_data->wait);
2630 }
2631 
2632 static inline void io_state_file_put(struct io_submit_state *state)
2633 {
2634         if (state->file_refs) {
2635                 fput_many(state->file, state->file_refs);
2636                 state->file_refs = 0;
2637         }
2638 }
2639 
2640 /*
2641  * Get as many references to a file as we have IOs left in this submission,
2642  * assuming most submissions are for one file, or at least that each file
2643  * has more than one submission.
2644  */
2645 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2646 {
2647         if (!state)
2648                 return fget(fd);
2649 
2650         if (state->file_refs) {
2651                 if (state->fd == fd) {
2652                         state->file_refs--;
2653                         return state->file;
2654                 }
2655                 io_state_file_put(state);
2656         }
2657         state->file = fget_many(fd, state->ios_left);
2658         if (unlikely(!state->file))
2659                 return NULL;
2660 
2661         state->fd = fd;
2662         state->file_refs = state->ios_left - 1;
2663         return state->file;
2664 }
2665 
2666 static bool io_bdev_nowait(struct block_device *bdev)
2667 {
2668         return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2669 }
2670 
2671 /*
2672  * If we tracked the file through the SCM inflight mechanism, we could support
2673  * any file. For now, just ensure that anything potentially problematic is done
2674  * inline.
2675  */
2676 static bool io_file_supports_async(struct file *file, int rw)
2677 {
2678         umode_t mode = file_inode(file)->i_mode;
2679 
2680         if (S_ISBLK(mode)) {
2681                 if (IS_ENABLED(CONFIG_BLOCK) &&
2682                     io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2683                         return true;
2684                 return false;
2685         }
2686         if (S_ISSOCK(mode))
2687                 return true;
2688         if (S_ISREG(mode)) {
2689                 if (IS_ENABLED(CONFIG_BLOCK) &&
2690                     io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2691                     file->f_op != &io_uring_fops)
2692                         return true;
2693                 return false;
2694         }
2695 
2696         /* any ->read/write should understand O_NONBLOCK */
2697         if (file->f_flags & O_NONBLOCK)
2698                 return true;
2699 
2700         if (!(file->f_mode & FMODE_NOWAIT))
2701                 return false;
2702 
2703         if (rw == READ)
2704                 return file->f_op->read_iter != NULL;
2705 
2706         return file->f_op->write_iter != NULL;
2707 }
2708 
2709 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2710 {
2711         struct io_ring_ctx *ctx = req->ctx;
2712         struct kiocb *kiocb = &req->rw.kiocb;
2713         struct file *file = req->file;
2714         unsigned ioprio;
2715         int ret;
2716 
2717         if (S_ISREG(file_inode(file)->i_mode))
2718                 req->flags |= REQ_F_ISREG;
2719 
2720         kiocb->ki_pos = READ_ONCE(sqe->off);
2721         if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2722                 req->flags |= REQ_F_CUR_POS;
2723                 kiocb->ki_pos = file->f_pos;
2724         }
2725         kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2726         kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2727         ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2728         if (unlikely(ret))
2729                 return ret;
2730 
2731         /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2732         if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2733                 req->flags |= REQ_F_NOWAIT;
2734 
2735         ioprio = READ_ONCE(sqe->ioprio);
2736         if (ioprio) {
2737                 ret = ioprio_check_cap(ioprio);
2738                 if (ret)
2739                         return ret;
2740 
2741                 kiocb->ki_ioprio = ioprio;
2742         } else
2743                 kiocb->ki_ioprio = get_current_ioprio();
2744 
2745         if (ctx->flags & IORING_SETUP_IOPOLL) {
2746                 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2747                     !kiocb->ki_filp->f_op->iopoll)
2748                         return -EOPNOTSUPP;
2749 
2750                 kiocb->ki_flags |= IOCB_HIPRI;
2751                 kiocb->ki_complete = io_complete_rw_iopoll;
2752                 req->iopoll_completed = 0;
2753         } else {
2754                 if (kiocb->ki_flags & IOCB_HIPRI)
2755                         return -EINVAL;
2756                 kiocb->ki_complete = io_complete_rw;
2757         }
2758 
2759         req->rw.addr = READ_ONCE(sqe->addr);
2760         req->rw.len = READ_ONCE(sqe->len);
2761         req->buf_index = READ_ONCE(sqe->buf_index);
2762         return 0;
2763 }
2764 
2765 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2766 {
2767         switch (ret) {
2768         case -EIOCBQUEUED:
2769                 break;
2770         case -ERESTARTSYS:
2771         case -ERESTARTNOINTR:
2772         case -ERESTARTNOHAND:
2773         case -ERESTART_RESTARTBLOCK:
2774                 /*
2775                  * We can't just restart the syscall, since previously
2776                  * submitted sqes may already be in progress. Just fail this
2777                  * IO with EINTR.
2778                  */
2779                 ret = -EINTR;
2780                 fallthrough;
2781         default:
2782                 kiocb->ki_complete(kiocb, ret, 0);
2783         }
2784 }
2785 
2786 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2787                        unsigned int issue_flags)
2788 {
2789         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2790         struct io_async_rw *io = req->async_data;
2791         bool check_reissue = kiocb->ki_complete == io_complete_rw;
2792 
2793         /* add previously done IO, if any */
2794         if (io && io->bytes_done > 0) {
2795                 if (ret < 0)
2796                         ret = io->bytes_done;
2797                 else
2798                         ret += io->bytes_done;
2799         }
2800 
2801         if (req->flags & REQ_F_CUR_POS)
2802                 req->file->f_pos = kiocb->ki_pos;
2803         if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2804                 __io_complete_rw(req, ret, 0, issue_flags);
2805         else
2806                 io_rw_done(kiocb, ret);
2807 
2808         if (check_reissue && req->flags & REQ_F_REISSUE) {
2809                 req->flags &= ~REQ_F_REISSUE;
2810                 if (!io_rw_reissue(req)) {
2811                         int cflags = 0;
2812 
2813                         req_set_fail_links(req);
2814                         if (req->flags & REQ_F_BUFFER_SELECTED)
2815                                 cflags = io_put_rw_kbuf(req);
2816                         __io_req_complete(req, issue_flags, ret, cflags);
2817                 }
2818         }
2819 }
2820 
2821 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2822 {
2823         struct io_ring_ctx *ctx = req->ctx;
2824         size_t len = req->rw.len;
2825         struct io_mapped_ubuf *imu;
2826         u16 index, buf_index = req->buf_index;
2827         size_t offset;
2828         u64 buf_addr;
2829 
2830         if (unlikely(buf_index >= ctx->nr_user_bufs))
2831                 return -EFAULT;
2832         index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2833         imu = &ctx->user_bufs[index];
2834         buf_addr = req->rw.addr;
2835 
2836         /* overflow */
2837         if (buf_addr + len < buf_addr)
2838                 return -EFAULT;
2839         /* not inside the mapped region */
2840         if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2841                 return -EFAULT;
2842 
2843         /*
2844          * May not be a start of buffer, set size appropriately
2845          * and advance us to the beginning.
2846          */
2847         offset = buf_addr - imu->ubuf;
2848         iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2849 
2850         if (offset) {
2851                 /*
2852                  * Don't use iov_iter_advance() here, as it's really slow for
2853                  * using the latter parts of a big fixed buffer - it iterates
2854                  * over each segment manually. We can cheat a bit here, because
2855                  * we know that:
2856                  *
2857                  * 1) it's a BVEC iter, we set it up
2858                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
2859                  *    first and last bvec
2860                  *
2861                  * So just find our index, and adjust the iterator afterwards.
2862                  * If the offset is within the first bvec (or the whole first
2863                  * bvec, just use iov_iter_advance(). This makes it easier
2864                  * since we can just skip the first segment, which may not
2865                  * be PAGE_SIZE aligned.
2866                  */
2867                 const struct bio_vec *bvec = imu->bvec;
2868 
2869                 if (offset <= bvec->bv_len) {
2870                         iov_iter_advance(iter, offset);
2871                 } else {
2872                         unsigned long seg_skip;
2873 
2874                         /* skip first vec */
2875                         offset -= bvec->bv_len;
2876                         seg_skip = 1 + (offset >> PAGE_SHIFT);
2877 
2878                         iter->bvec = bvec + seg_skip;
2879                         iter->nr_segs -= seg_skip;
2880                         iter->count -= bvec->bv_len + offset;
2881                         iter->iov_offset = offset & ~PAGE_MASK;
2882                 }
2883         }
2884 
2885         return 0;
2886 }
2887 
2888 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2889 {
2890         if (needs_lock)
2891                 mutex_unlock(&ctx->uring_lock);
2892 }
2893 
2894 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2895 {
2896         /*
2897          * "Normal" inline submissions always hold the uring_lock, since we
2898          * grab it from the system call. Same is true for the SQPOLL offload.
2899          * The only exception is when we've detached the request and issue it
2900          * from an async worker thread, grab the lock for that case.
2901          */
2902         if (needs_lock)
2903                 mutex_lock(&ctx->uring_lock);
2904 }
2905 
2906 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2907                                           int bgid, struct io_buffer *kbuf,
2908                                           bool needs_lock)
2909 {
2910         struct io_buffer *head;
2911 
2912         if (req->flags & REQ_F_BUFFER_SELECTED)
2913                 return kbuf;
2914 
2915         io_ring_submit_lock(req->ctx, needs_lock);
2916 
2917         lockdep_assert_held(&req->ctx->uring_lock);
2918 
2919         head = xa_load(&req->ctx->io_buffers, bgid);
2920         if (head) {
2921                 if (!list_empty(&head->list)) {
2922                         kbuf = list_last_entry(&head->list, struct io_buffer,
2923                                                         list);
2924                         list_del(&kbuf->list);
2925                 } else {
2926                         kbuf = head;
2927                         xa_erase(&req->ctx->io_buffers, bgid);
2928                 }
2929                 if (*len > kbuf->len)
2930                         *len = kbuf->len;
2931         } else {
2932                 kbuf = ERR_PTR(-ENOBUFS);
2933         }
2934 
2935         io_ring_submit_unlock(req->ctx, needs_lock);
2936 
2937         return kbuf;
2938 }
2939 
2940 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2941                                         bool needs_lock)
2942 {
2943         struct io_buffer *kbuf;
2944         u16 bgid;
2945 
2946         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2947         bgid = req->buf_index;
2948         kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2949         if (IS_ERR(kbuf))
2950                 return kbuf;
2951         req->rw.addr = (u64) (unsigned long) kbuf;
2952         req->flags |= REQ_F_BUFFER_SELECTED;
2953         return u64_to_user_ptr(kbuf->addr);
2954 }
2955 
2956 #ifdef CONFIG_COMPAT
2957 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2958                                 bool needs_lock)
2959 {
2960         struct compat_iovec __user *uiov;
2961         compat_ssize_t clen;
2962         void __user *buf;
2963         ssize_t len;
2964 
2965         uiov = u64_to_user_ptr(req->rw.addr);
2966         if (!access_ok(uiov, sizeof(*uiov)))
2967                 return -EFAULT;
2968         if (__get_user(clen, &uiov->iov_len))
2969                 return -EFAULT;
2970         if (clen < 0)
2971                 return -EINVAL;
2972 
2973         len = clen;
2974         buf = io_rw_buffer_select(req, &len, needs_lock);
2975         if (IS_ERR(buf))
2976                 return PTR_ERR(buf);
2977         iov[0].iov_base = buf;
2978         iov[0].iov_len = (compat_size_t) len;
2979         return 0;
2980 }
2981 #endif
2982 
2983 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2984                                       bool needs_lock)
2985 {
2986         struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2987         void __user *buf;
2988         ssize_t len;
2989 
2990         if (copy_from_user(iov, uiov, sizeof(*uiov)))
2991                 return -EFAULT;
2992 
2993         len = iov[0].iov_len;
2994         if (len < 0)
2995                 return -EINVAL;
2996         buf = io_rw_buffer_select(req, &len, needs_lock);
2997         if (IS_ERR(buf))
2998                 return PTR_ERR(buf);
2999         iov[0].iov_base = buf;
3000         iov[0].iov_len = len;
3001         return 0;
3002 }
3003 
3004 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3005                                     bool needs_lock)
3006 {
3007         if (req->flags & REQ_F_BUFFER_SELECTED) {
3008                 struct io_buffer *kbuf;
3009 
3010                 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3011                 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3012                 iov[0].iov_len = kbuf->len;
3013                 return 0;
3014         }
3015         if (req->rw.len != 1)
3016                 return -EINVAL;
3017 
3018 #ifdef CONFIG_COMPAT
3019         if (req->ctx->compat)
3020                 return io_compat_import(req, iov, needs_lock);
3021 #endif
3022 
3023         return __io_iov_buffer_select(req, iov, needs_lock);
3024 }
3025 
3026 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3027                            struct iov_iter *iter, bool needs_lock)
3028 {
3029         void __user *buf = u64_to_user_ptr(req->rw.addr);
3030         size_t sqe_len = req->rw.len;
3031         u8 opcode = req->opcode;
3032         ssize_t ret;
3033 
3034         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3035                 *iovec = NULL;
3036                 return io_import_fixed(req, rw, iter);
3037         }
3038 
3039         /* buffer index only valid with fixed read/write, or buffer select  */
3040         if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3041                 return -EINVAL;
3042 
3043         if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3044                 if (req->flags & REQ_F_BUFFER_SELECT) {
3045                         buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3046                         if (IS_ERR(buf))
3047                                 return PTR_ERR(buf);
3048                         req->rw.len = sqe_len;
3049                 }
3050 
3051                 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3052                 *iovec = NULL;
3053                 return ret;
3054         }
3055 
3056         if (req->flags & REQ_F_BUFFER_SELECT) {
3057                 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3058                 if (!ret)
3059                         iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3060                 *iovec = NULL;
3061                 return ret;
3062         }
3063 
3064         return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3065                               req->ctx->compat);
3066 }
3067 
3068 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3069 {
3070         return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3071 }
3072 
3073 /*
3074  * For files that don't have ->read_iter() and ->write_iter(), handle them
3075  * by looping over ->read() or ->write() manually.
3076  */
3077 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3078 {
3079         struct kiocb *kiocb = &req->rw.kiocb;
3080         struct file *file = req->file;
3081         ssize_t ret = 0;
3082 
3083         /*
3084          * Don't support polled IO through this interface, and we can't
3085          * support non-blocking either. For the latter, this just causes
3086          * the kiocb to be handled from an async context.
3087          */
3088         if (kiocb->ki_flags & IOCB_HIPRI)
3089                 return -EOPNOTSUPP;
3090         if (kiocb->ki_flags & IOCB_NOWAIT)
3091                 return -EAGAIN;
3092 
3093         while (iov_iter_count(iter)) {
3094                 struct iovec iovec;
3095                 ssize_t nr;
3096 
3097                 if (!iov_iter_is_bvec(iter)) {
3098                         iovec = iov_iter_iovec(iter);
3099                 } else {
3100                         iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3101                         iovec.iov_len = req->rw.len;
3102                 }
3103 
3104                 if (rw == READ) {
3105                         nr = file->f_op->read(file, iovec.iov_base,
3106                                               iovec.iov_len, io_kiocb_ppos(kiocb));
3107                 } else {
3108                         nr = file->f_op->write(file, iovec.iov_base,
3109                                                iovec.iov_len, io_kiocb_ppos(kiocb));
3110                 }
3111 
3112                 if (nr < 0) {
3113                         if (!ret)
3114                                 ret = nr;
3115                         break;
3116                 }
3117                 ret += nr;
3118                 if (nr != iovec.iov_len)
3119                         break;
3120                 req->rw.len -= nr;
3121                 req->rw.addr += nr;
3122                 iov_iter_advance(iter, nr);
3123         }
3124 
3125         return ret;
3126 }
3127 
3128 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3129                           const struct iovec *fast_iov, struct iov_iter *iter)
3130 {
3131         struct io_async_rw *rw = req->async_data;
3132 
3133         memcpy(&rw->iter, iter, sizeof(*iter));
3134         rw->free_iovec = iovec;
3135         rw->bytes_done = 0;
3136         /* can only be fixed buffers, no need to do anything */
3137         if (iov_iter_is_bvec(iter))
3138                 return;
3139         if (!iovec) {
3140                 unsigned iov_off = 0;
3141 
3142                 rw->iter.iov = rw->fast_iov;
3143                 if (iter->iov != fast_iov) {
3144                         iov_off = iter->iov - fast_iov;
3145                         rw->iter.iov += iov_off;
3146                 }
3147                 if (rw->fast_iov != fast_iov)
3148                         memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3149                                sizeof(struct iovec) * iter->nr_segs);
3150         } else {
3151                 req->flags |= REQ_F_NEED_CLEANUP;
3152         }
3153 }
3154 
3155 static inline int __io_alloc_async_data(struct io_kiocb *req)
3156 {
3157         WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3158         req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3159         return req->async_data == NULL;
3160 }
3161 
3162 static int io_alloc_async_data(struct io_kiocb *req)
3163 {
3164         if (!io_op_defs[req->opcode].needs_async_data)
3165                 return 0;
3166 
3167         return  __io_alloc_async_data(req);
3168 }
3169 
3170 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3171                              const struct iovec *fast_iov,
3172                              struct iov_iter *iter, bool force)
3173 {
3174         if (!force && !io_op_defs[req->opcode].needs_async_data)
3175                 return 0;
3176         if (!req->async_data) {
3177                 if (__io_alloc_async_data(req)) {
3178                         kfree(iovec);
3179                         return -ENOMEM;
3180                 }
3181 
3182                 io_req_map_rw(req, iovec, fast_iov, iter);
3183         }
3184         return 0;
3185 }
3186 
3187 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3188 {
3189         struct io_async_rw *iorw = req->async_data;
3190         struct iovec *iov = iorw->fast_iov;
3191         int ret;
3192 
3193         ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3194         if (unlikely(ret < 0))
3195                 return ret;
3196 
3197         iorw->bytes_done = 0;
3198         iorw->free_iovec = iov;
3199         if (iov)
3200                 req->flags |= REQ_F_NEED_CLEANUP;
3201         return 0;
3202 }
3203 
3204 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3205 {
3206         if (unlikely(!(req->file->f_mode & FMODE_READ)))
3207                 return -EBADF;
3208         return io_prep_rw(req, sqe);
3209 }
3210 
3211 /*
3212  * This is our waitqueue callback handler, registered through lock_page_async()
3213  * when we initially tried to do the IO with the iocb armed our waitqueue.
3214  * This gets called when the page is unlocked, and we generally expect that to
3215  * happen when the page IO is completed and the page is now uptodate. This will
3216  * queue a task_work based retry of the operation, attempting to copy the data
3217  * again. If the latter fails because the page was NOT uptodate, then we will
3218  * do a thread based blocking retry of the operation. That's the unexpected
3219  * slow path.
3220  */
3221 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3222                              int sync, void *arg)
3223 {
3224         struct wait_page_queue *wpq;
3225         struct io_kiocb *req = wait->private;
3226         struct wait_page_key *key = arg;
3227 
3228         wpq = container_of(wait, struct wait_page_queue, wait);
3229 
3230         if (!wake_page_match(wpq, key))
3231                 return 0;
3232 
3233         req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3234         list_del_init(&wait->entry);
3235 
3236         /* submit ref gets dropped, acquire a new one */
3237         req_ref_get(req);
3238         io_req_task_queue(req);
3239         return 1;
3240 }
3241 
3242 /*
3243  * This controls whether a given IO request should be armed for async page
3244  * based retry. If we return false here, the request is handed to the async
3245  * worker threads for retry. If we're doing buffered reads on a regular file,
3246  * we prepare a private wait_page_queue entry and retry the operation. This
3247  * will either succeed because the page is now uptodate and unlocked, or it
3248  * will register a callback when the page is unlocked at IO completion. Through
3249  * that callback, io_uring uses task_work to setup a retry of the operation.
3250  * That retry will attempt the buffered read again. The retry will generally
3251  * succeed, or in rare cases where it fails, we then fall back to using the
3252  * async worker threads for a blocking retry.
3253  */
3254 static bool io_rw_should_retry(struct io_kiocb *req)
3255 {
3256         struct io_async_rw *rw = req->async_data;
3257         struct wait_page_queue *wait = &rw->wpq;
3258         struct kiocb *kiocb = &req->rw.kiocb;
3259 
3260         /* never retry for NOWAIT, we just complete with -EAGAIN */
3261         if (req->flags & REQ_F_NOWAIT)
3262                 return false;
3263 
3264         /* Only for buffered IO */
3265         if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3266                 return false;
3267 
3268         /*
3269          * just use poll if we can, and don't attempt if the fs doesn't
3270          * support callback based unlocks
3271          */
3272         if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3273                 return false;
3274 
3275         wait->wait.func = io_async_buf_func;
3276         wait->wait.private = req;
3277         wait->wait.flags = 0;
3278         INIT_LIST_HEAD(&wait->wait.entry);
3279         kiocb->ki_flags |= IOCB_WAITQ;
3280         kiocb->ki_flags &= ~IOCB_NOWAIT;
3281         kiocb->ki_waitq = wait;
3282         return true;
3283 }
3284 
3285 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3286 {
3287         if (req->file->f_op->read_iter)
3288                 return call_read_iter(req->file, &req->rw.kiocb, iter);
3289         else if (req->file->f_op->read)
3290                 return loop_rw_iter(READ, req, iter);
3291         else
3292                 return -EINVAL;
3293 }
3294 
3295 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3296 {
3297         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3298         struct kiocb *kiocb = &req->rw.kiocb;
3299         struct iov_iter __iter, *iter = &__iter;
3300         struct io_async_rw *rw = req->async_data;
3301         ssize_t io_size, ret, ret2;
3302         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3303 
3304         if (rw) {
3305                 iter = &rw->iter;
3306                 iovec = NULL;
3307         } else {
3308                 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3309                 if (ret < 0)
3310                         return ret;
3311         }
3312         io_size = iov_iter_count(iter);
3313         req->result = io_size;
3314 
3315         /* Ensure we clear previously set non-block flag */
3316         if (!force_nonblock)
3317                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3318         else
3319                 kiocb->ki_flags |= IOCB_NOWAIT;
3320 
3321         /* If the file doesn't support async, just async punt */
3322         if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3323                 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3324                 return ret ?: -EAGAIN;
3325         }
3326 
3327         ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3328         if (unlikely(ret)) {
3329                 kfree(iovec);
3330                 return ret;
3331         }
3332 
3333         ret = io_iter_do_read(req, iter);
3334 
3335         if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3336                 req->flags &= ~REQ_F_REISSUE;
3337                 /* IOPOLL retry should happen for io-wq threads */
3338                 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3339                         goto done;
3340                 /* no retry on NONBLOCK nor RWF_NOWAIT */
3341                 if (req->flags & REQ_F_NOWAIT)
3342                         goto done;
3343                 /* some cases will consume bytes even on error returns */
3344                 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3345                 ret = 0;
3346         } else if (ret == -EIOCBQUEUED) {
3347                 goto out_free;
3348         } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3349                    (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3350                 /* read all, failed, already did sync or don't want to retry */
3351                 goto done;
3352         }
3353 
3354         ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3355         if (ret2)
3356                 return ret2;
3357 
3358         iovec = NULL;
3359         rw = req->async_data;
3360         /* now use our persistent iterator, if we aren't already */
3361         iter = &rw->iter;
3362 
3363         do {
3364                 io_size -= ret;
3365                 rw->bytes_done += ret;
3366                 /* if we can retry, do so with the callbacks armed */
3367                 if (!io_rw_should_retry(req)) {
3368                         kiocb->ki_flags &= ~IOCB_WAITQ;
3369                         return -EAGAIN;
3370                 }
3371 
3372                 /*
3373                  * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3374                  * we get -EIOCBQUEUED, then we'll get a notification when the
3375                  * desired page gets unlocked. We can also get a partial read
3376                  * here, and if we do, then just retry at the new offset.
3377                  */
3378                 ret = io_iter_do_read(req, iter);
3379                 if (ret == -EIOCBQUEUED)
3380                         return 0;
3381                 /* we got some bytes, but not all. retry. */
3382                 kiocb->ki_flags &= ~IOCB_WAITQ;
3383         } while (ret > 0 && ret < io_size);
3384 done:
3385         kiocb_done(kiocb, ret, issue_flags);
3386 out_free:
3387         /* it's faster to check here then delegate to kfree */
3388         if (iovec)
3389                 kfree(iovec);
3390         return 0;
3391 }
3392 
3393 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3394 {
3395         if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3396                 return -EBADF;
3397         return io_prep_rw(req, sqe);
3398 }
3399 
3400 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3401 {
3402         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3403         struct kiocb *kiocb = &req->rw.kiocb;
3404         struct iov_iter __iter, *iter = &__iter;
3405         struct io_async_rw *rw = req->async_data;
3406         ssize_t ret, ret2, io_size;
3407         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3408 
3409         if (rw) {
3410                 iter = &rw->iter;
3411                 iovec = NULL;
3412         } else {
3413                 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3414                 if (ret < 0)
3415                         return ret;
3416         }
3417         io_size = iov_iter_count(iter);
3418         req->result = io_size;
3419 
3420         /* Ensure we clear previously set non-block flag */
3421         if (!force_nonblock)
3422                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3423         else
3424                 kiocb->ki_flags |= IOCB_NOWAIT;
3425 
3426         /* If the file doesn't support async, just async punt */
3427         if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3428                 goto copy_iov;
3429 
3430         /* file path doesn't support NOWAIT for non-direct_IO */
3431         if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3432             (req->flags & REQ_F_ISREG))
3433                 goto copy_iov;
3434 
3435         ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3436         if (unlikely(ret))
3437                 goto out_free;
3438 
3439         /*
3440          * Open-code file_start_write here to grab freeze protection,
3441          * which will be released by another thread in
3442          * io_complete_rw().  Fool lockdep by telling it the lock got
3443          * released so that it doesn't complain about the held lock when
3444          * we return to userspace.
3445          */
3446         if (req->flags & REQ_F_ISREG) {
3447                 sb_start_write(file_inode(req->file)->i_sb);
3448                 __sb_writers_release(file_inode(req->file)->i_sb,
3449                                         SB_FREEZE_WRITE);
3450         }
3451         kiocb->ki_flags |= IOCB_WRITE;
3452 
3453         if (req->file->f_op->write_iter)
3454                 ret2 = call_write_iter(req->file, kiocb, iter);
3455         else if (req->file->f_op->write)
3456                 ret2 = loop_rw_iter(WRITE, req, iter);
3457         else
3458                 ret2 = -EINVAL;
3459 
3460         if (req->flags & REQ_F_REISSUE) {
3461                 req->flags &= ~REQ_F_REISSUE;
3462                 ret2 = -EAGAIN;
3463         }
3464 
3465         /*
3466          * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3467          * retry them without IOCB_NOWAIT.
3468          */
3469         if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3470                 ret2 = -EAGAIN;
3471         /* no retry on NONBLOCK nor RWF_NOWAIT */
3472         if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3473                 goto done;
3474         if (!force_nonblock || ret2 != -EAGAIN) {
3475                 /* IOPOLL retry should happen for io-wq threads */
3476                 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3477                         goto copy_iov;
3478 done:
3479                 kiocb_done(kiocb, ret2, issue_flags);
3480         } else {
3481 copy_iov:
3482                 /* some cases will consume bytes even on error returns */
3483                 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3484                 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3485                 return ret ?: -EAGAIN;
3486         }
3487 out_free:
3488         /* it's reportedly faster than delegating the null check to kfree() */
3489         if (iovec)
3490                 kfree(iovec);
3491         return ret;
3492 }
3493 
3494 static int io_renameat_prep(struct io_kiocb *req,
3495                             const struct io_uring_sqe *sqe)
3496 {
3497         struct io_rename *ren = &req->rename;
3498         const char __user *oldf, *newf;
3499 
3500         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3501                 return -EINVAL;
3502         if (sqe->ioprio || sqe->buf_index)
3503                 return -EINVAL;
3504         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3505                 return -EBADF;
3506 
3507         ren->old_dfd = READ_ONCE(sqe->fd);
3508         oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3509         newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3510         ren->new_dfd = READ_ONCE(sqe->len);
3511         ren->flags = READ_ONCE(sqe->rename_flags);
3512 
3513         ren->oldpath = getname(oldf);
3514         if (IS_ERR(ren->oldpath))
3515                 return PTR_ERR(ren->oldpath);
3516 
3517         ren->newpath = getname(newf);
3518         if (IS_ERR(ren->newpath)) {
3519                 putname(ren->oldpath);
3520                 return PTR_ERR(ren->newpath);
3521         }
3522 
3523         req->flags |= REQ_F_NEED_CLEANUP;
3524         return 0;
3525 }
3526 
3527 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3528 {
3529         struct io_rename *ren = &req->rename;
3530         int ret;
3531 
3532         if (issue_flags & IO_URING_F_NONBLOCK)
3533                 return -EAGAIN;
3534 
3535         ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3536                                 ren->newpath, ren->flags);
3537 
3538         req->flags &= ~REQ_F_NEED_CLEANUP;
3539         if (ret < 0)
3540                 req_set_fail_links(req);
3541         io_req_complete(req, ret);
3542         return 0;
3543 }
3544 
3545 static int io_unlinkat_prep(struct io_kiocb *req,
3546                             const struct io_uring_sqe *sqe)
3547 {
3548         struct io_unlink *un = &req->unlink;
3549         const char __user *fname;
3550 
3551         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3552                 return -EINVAL;
3553         if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3554                 return -EINVAL;
3555         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3556                 return -EBADF;
3557 
3558         un->dfd = READ_ONCE(sqe->fd);
3559 
3560         un->flags = READ_ONCE(sqe->unlink_flags);
3561         if (un->flags & ~AT_REMOVEDIR)
3562                 return -EINVAL;
3563 
3564         fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3565         un->filename = getname(fname);
3566         if (IS_ERR(un->filename))
3567                 return PTR_ERR(un->filename);
3568 
3569         req->flags |= REQ_F_NEED_CLEANUP;
3570         return 0;
3571 }
3572 
3573 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3574 {
3575         struct io_unlink *un = &req->unlink;
3576         int ret;
3577 
3578         if (issue_flags & IO_URING_F_NONBLOCK)
3579                 return -EAGAIN;
3580 
3581         if (un->flags & AT_REMOVEDIR)
3582                 ret = do_rmdir(un->dfd, un->filename);
3583         else
3584                 ret = do_unlinkat(un->dfd, un->filename);
3585 
3586         req->flags &= ~REQ_F_NEED_CLEANUP;
3587         if (ret < 0)
3588                 req_set_fail_links(req);
3589         io_req_complete(req, ret);
3590         return 0;
3591 }
3592 
3593 static int io_shutdown_prep(struct io_kiocb *req,
3594                             const struct io_uring_sqe *sqe)
3595 {
3596 #if defined(CONFIG_NET)
3597         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3598                 return -EINVAL;
3599         if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3600             sqe->buf_index)
3601                 return -EINVAL;
3602 
3603         req->shutdown.how = READ_ONCE(sqe->len);
3604         return 0;
3605 #else
3606         return -EOPNOTSUPP;
3607 #endif
3608 }
3609 
3610 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3611 {
3612 #if defined(CONFIG_NET)
3613         struct socket *sock;
3614         int ret;
3615 
3616         if (issue_flags & IO_URING_F_NONBLOCK)
3617                 return -EAGAIN;
3618 
3619         sock = sock_from_file(req->file);
3620         if (unlikely(!sock))
3621                 return -ENOTSOCK;
3622 
3623         ret = __sys_shutdown_sock(sock, req->shutdown.how);
3624         if (ret < 0)
3625                 req_set_fail_links(req);
3626         io_req_complete(req, ret);
3627         return 0;
3628 #else
3629         return -EOPNOTSUPP;
3630 #endif
3631 }
3632 
3633 static int __io_splice_prep(struct io_kiocb *req,
3634                             const struct io_uring_sqe *sqe)
3635 {
3636         struct io_splice* sp = &req->splice;
3637         unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3638 
3639         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3640                 return -EINVAL;
3641 
3642         sp->file_in = NULL;
3643         sp->len = READ_ONCE(sqe->len);
3644         sp->flags = READ_ONCE(sqe->splice_flags);
3645 
3646         if (unlikely(sp->flags & ~valid_flags))
3647                 return -EINVAL;
3648 
3649         sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3650                                   (sp->flags & SPLICE_F_FD_IN_FIXED));
3651         if (!sp->file_in)
3652                 return -EBADF;
3653         req->flags |= REQ_F_NEED_CLEANUP;
3654 
3655         if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3656                 /*
3657                  * Splice operation will be punted aync, and here need to
3658                  * modify io_wq_work.flags, so initialize io_wq_work firstly.
3659                  */
3660                 req->work.flags |= IO_WQ_WORK_UNBOUND;
3661         }
3662 
3663         return 0;
3664 }
3665 
3666 static int io_tee_prep(struct io_kiocb *req,
3667                        const struct io_uring_sqe *sqe)
3668 {
3669         if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3670                 return -EINVAL;
3671         return __io_splice_prep(req, sqe);
3672 }
3673 
3674 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3675 {
3676         struct io_splice *sp = &req->splice;
3677         struct file *in = sp->file_in;
3678         struct file *out = sp->file_out;
3679         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3680         long ret = 0;
3681 
3682         if (issue_flags & IO_URING_F_NONBLOCK)
3683                 return -EAGAIN;
3684         if (sp->len)
3685                 ret = do_tee(in, out, sp->len, flags);
3686 
3687         io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3688         req->flags &= ~REQ_F_NEED_CLEANUP;
3689 
3690         if (ret != sp->len)
3691                 req_set_fail_links(req);
3692         io_req_complete(req, ret);
3693         return 0;
3694 }
3695 
3696 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3697 {
3698         struct io_splice* sp = &req->splice;
3699 
3700         sp->off_in = READ_ONCE(sqe->splice_off_in);
3701         sp->off_out = READ_ONCE(sqe->off);
3702         return __io_splice_prep(req, sqe);
3703 }
3704 
3705 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3706 {
3707         struct io_splice *sp = &req->splice;
3708         struct file *in = sp->file_in;
3709         struct file *out = sp->file_out;
3710         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3711         loff_t *poff_in, *poff_out;
3712         long ret = 0;
3713 
3714         if (issue_flags & IO_URING_F_NONBLOCK)
3715                 return -EAGAIN;
3716 
3717         poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3718         poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3719 
3720         if (sp->len)
3721                 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3722 
3723         io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3724         req->flags &= ~REQ_F_NEED_CLEANUP;
3725 
3726         if (ret != sp->len)
3727                 req_set_fail_links(req);
3728         io_req_complete(req, ret);
3729         return 0;
3730 }
3731 
3732 /*
3733  * IORING_OP_NOP just posts a completion event, nothing else.
3734  */
3735 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3736 {
3737         struct io_ring_ctx *ctx = req->ctx;
3738 
3739         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3740                 return -EINVAL;
3741 
3742         __io_req_complete(req, issue_flags, 0, 0);
3743         return 0;
3744 }
3745 
3746 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3747 {
3748         struct io_ring_ctx *ctx = req->ctx;
3749 
3750         if (!req->file)
3751                 return -EBADF;
3752 
3753         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3754                 return -EINVAL;
3755         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3756                 return -EINVAL;
3757 
3758         req->sync.flags = READ_ONCE(sqe->fsync_flags);
3759         if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3760                 return -EINVAL;
3761 
3762         req->sync.off = READ_ONCE(sqe->off);
3763         req->sync.len = READ_ONCE(sqe->len);
3764         return 0;
3765 }
3766 
3767 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3768 {
3769         loff_t end = req->sync.off + req->sync.len;
3770         int ret;
3771 
3772         /* fsync always requires a blocking context */
3773         if (issue_flags & IO_URING_F_NONBLOCK)
3774                 return -EAGAIN;
3775 
3776         ret = vfs_fsync_range(req->file, req->sync.off,
3777                                 end > 0 ? end : LLONG_MAX,
3778                                 req->sync.flags & IORING_FSYNC_DATASYNC);
3779         if (ret < 0)
3780                 req_set_fail_links(req);
3781         io_req_complete(req, ret);
3782         return 0;
3783 }
3784 
3785 static int io_fallocate_prep(struct io_kiocb *req,
3786                              const struct io_uring_sqe *sqe)
3787 {
3788         if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3789                 return -EINVAL;
3790         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3791                 return -EINVAL;
3792 
3793         req->sync.off = READ_ONCE(sqe->off);
3794         req->sync.len = READ_ONCE(sqe->addr);
3795         req->sync.mode = READ_ONCE(sqe->len);
3796         return 0;
3797 }
3798 
3799 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3800 {
3801         int ret;
3802 
3803         /* fallocate always requiring blocking context */
3804         if (issue_flags & IO_URING_F_NONBLOCK)
3805                 return -EAGAIN;
3806         ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3807                                 req->sync.len);
3808         if (ret < 0)
3809                 req_set_fail_links(req);
3810         io_req_complete(req, ret);
3811         return 0;
3812 }
3813 
3814 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3815 {
3816         const char __user *fname;
3817         int ret;
3818 
3819         if (unlikely(sqe->ioprio || sqe->buf_index))
3820                 return -EINVAL;
3821         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3822                 return -EBADF;
3823 
3824         /* open.how should be already initialised */
3825         if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3826                 req->open.how.flags |= O_LARGEFILE;
3827 
3828         req->open.dfd = READ_ONCE(sqe->fd);
3829         fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3830         req->open.filename = getname(fname);
3831         if (IS_ERR(req->open.filename)) {
3832                 ret = PTR_ERR(req->open.filename);
3833                 req->open.filename = NULL;
3834                 return ret;
3835         }
3836         req->open.nofile = rlimit(RLIMIT_NOFILE);
3837         req->flags |= REQ_F_NEED_CLEANUP;
3838         return 0;
3839 }
3840 
3841 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3842 {
3843         u64 flags, mode;
3844 
3845         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3846                 return -EINVAL;
3847         mode = READ_ONCE(sqe->len);
3848         flags = READ_ONCE(sqe->open_flags);
3849         req->open.how = build_open_how(flags, mode);
3850         return __io_openat_prep(req, sqe);
3851 }
3852 
3853 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3854 {
3855         struct open_how __user *how;
3856         size_t len;
3857         int ret;
3858 
3859         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3860                 return -EINVAL;
3861         how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3862         len = READ_ONCE(sqe->len);
3863         if (len < OPEN_HOW_SIZE_VER0)
3864                 return -EINVAL;
3865 
3866         ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3867                                         len);
3868         if (ret)
3869                 return ret;
3870 
3871         return __io_openat_prep(req, sqe);
3872 }
3873 
3874 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3875 {
3876         struct open_flags op;
3877         struct file *file;
3878         bool nonblock_set;
3879         bool resolve_nonblock;
3880         int ret;
3881 
3882         ret = build_open_flags(&req->open.how, &op);
3883         if (ret)
3884                 goto err;
3885         nonblock_set = op.open_flag & O_NONBLOCK;
3886         resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3887         if (issue_flags & IO_URING_F_NONBLOCK) {
3888                 /*
3889                  * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3890                  * it'll always -EAGAIN
3891                  */
3892                 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3893                         return -EAGAIN;
3894                 op.lookup_flags |= LOOKUP_CACHED;
3895                 op.open_flag |= O_NONBLOCK;
3896         }
3897 
3898         ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3899         if (ret < 0)
3900                 goto err;
3901 
3902         file = do_filp_open(req->open.dfd, req->open.filename, &op);
3903         /* only retry if RESOLVE_CACHED wasn't already set by application */
3904         if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3905             file == ERR_PTR(-EAGAIN)) {
3906                 /*
3907                  * We could hang on to this 'fd', but seems like marginal
3908                  * gain for something that is now known to be a slower path.
3909                  * So just put it, and we'll get a new one when we retry.
3910                  */
3911                 put_unused_fd(ret);
3912                 return -EAGAIN;
3913         }
3914 
3915         if (IS_ERR(file)) {
3916                 put_unused_fd(ret);
3917                 ret = PTR_ERR(file);
3918         } else {
3919                 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3920                         file->f_flags &= ~O_NONBLOCK;
3921                 fsnotify_open(file);
3922                 fd_install(ret, file);
3923         }
3924 err:
3925         putname(req->open.filename);
3926         req->flags &= ~REQ_F_NEED_CLEANUP;
3927         if (ret < 0)
3928                 req_set_fail_links(req);
3929         io_req_complete(req, ret);
3930         return 0;
3931 }
3932 
3933 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3934 {
3935         return io_openat2(req, issue_flags);
3936 }
3937 
3938 static int io_remove_buffers_prep(struct io_kiocb *req,
3939                                   const struct io_uring_sqe *sqe)
3940 {
3941         struct io_provide_buf *p = &req->pbuf;
3942         u64 tmp;
3943 
3944         if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3945                 return -EINVAL;
3946 
3947         tmp = READ_ONCE(sqe->fd);
3948         if (!tmp || tmp > USHRT_MAX)
3949                 return -EINVAL;
3950 
3951         memset(p, 0, sizeof(*p));
3952         p->nbufs = tmp;
3953         p->bgid = READ_ONCE(sqe->buf_group);
3954         return 0;
3955 }
3956 
3957 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3958                                int bgid, unsigned nbufs)
3959 {
3960         unsigned i = 0;
3961 
3962         /* shouldn't happen */
3963         if (!nbufs)
3964                 return 0;
3965 
3966         /* the head kbuf is the list itself */
3967         while (!list_empty(&buf->list)) {
3968                 struct io_buffer *nxt;
3969 
3970                 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3971                 list_del(&nxt->list);
3972                 kfree(nxt);
3973                 if (++i == nbufs)
3974                         return i;
3975         }
3976         i++;
3977         kfree(buf);
3978         xa_erase(&ctx->io_buffers, bgid);
3979 
3980         return i;
3981 }
3982 
3983 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3984 {
3985         struct io_provide_buf *p = &req->pbuf;
3986         struct io_ring_ctx *ctx = req->ctx;
3987         struct io_buffer *head;
3988         int ret = 0;
3989         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3990 
3991         io_ring_submit_lock(ctx, !force_nonblock);
3992 
3993         lockdep_assert_held(&ctx->uring_lock);
3994 
3995         ret = -ENOENT;
3996         head = xa_load(&ctx->io_buffers, p->bgid);
3997         if (head)
3998                 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3999         if (ret < 0)
4000                 req_set_fail_links(req);
4001 
4002         /* need to hold the lock to complete IOPOLL requests */
4003         if (ctx->flags & IORING_SETUP_IOPOLL) {
4004                 __io_req_complete(req, issue_flags, ret, 0);
4005                 io_ring_submit_unlock(ctx, !force_nonblock);
4006         } else {
4007                 io_ring_submit_unlock(ctx, !force_nonblock);
4008                 __io_req_complete(req, issue_flags, ret, 0);
4009         }
4010         return 0;
4011 }
4012 
4013 static int io_provide_buffers_prep(struct io_kiocb *req,
4014                                    const struct io_uring_sqe *sqe)
4015 {
4016         unsigned long size, tmp_check;
4017         struct io_provide_buf *p = &req->pbuf;
4018         u64 tmp;
4019 
4020         if (sqe->ioprio || sqe->rw_flags)
4021                 return -EINVAL;
4022 
4023         tmp = READ_ONCE(sqe->fd);
4024         if (!tmp || tmp > USHRT_MAX)
4025                 return -E2BIG;
4026         p->nbufs = tmp;
4027         p->addr = READ_ONCE(sqe->addr);
4028         p->len = READ_ONCE(sqe->len);
4029 
4030         if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4031                                 &size))
4032                 return -EOVERFLOW;
4033         if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4034                 return -EOVERFLOW;
4035 
4036         size = (unsigned long)p->len * p->nbufs;
4037         if (!access_ok(u64_to_user_ptr(p->addr), size))
4038                 return -EFAULT;
4039 
4040         p->bgid = READ_ONCE(sqe->buf_group);
4041         tmp = READ_ONCE(sqe->off);
4042         if (tmp > USHRT_MAX)
4043                 return -E2BIG;
4044         p->bid = tmp;
4045         return 0;
4046 }
4047 
4048 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4049 {
4050         struct io_buffer *buf;
4051         u64 addr = pbuf->addr;
4052         int i, bid = pbuf->bid;
4053 
4054         for (i = 0; i < pbuf->nbufs; i++) {
4055                 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4056                 if (!buf)
4057                         break;
4058 
4059                 buf->addr = addr;
4060                 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4061                 buf->bid = bid;
4062                 addr += pbuf->len;
4063                 bid++;
4064                 if (!*head) {
4065                         INIT_LIST_HEAD(&buf->list);
4066                         *head = buf;
4067                 } else {
4068                         list_add_tail(&buf->list, &(*head)->list);
4069                 }
4070         }
4071 
4072         return i ? i : -ENOMEM;
4073 }
4074 
4075 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4076 {
4077         struct io_provide_buf *p = &req->pbuf;
4078         struct io_ring_ctx *ctx = req->ctx;
4079         struct io_buffer *head, *list;
4080         int ret = 0;
4081         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4082 
4083         io_ring_submit_lock(ctx, !force_nonblock);
4084 
4085         lockdep_assert_held(&ctx->uring_lock);
4086 
4087         list = head = xa_load(&ctx->io_buffers, p->bgid);
4088 
4089         ret = io_add_buffers(p, &head);
4090         if (ret >= 0 && !list) {
4091                 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4092                 if (ret < 0)
4093                         __io_remove_buffers(ctx, head, p->bgid, -1U);
4094         }
4095         if (ret < 0)
4096                 req_set_fail_links(req);
4097 
4098         /* need to hold the lock to complete IOPOLL requests */
4099         if (ctx->flags & IORING_SETUP_IOPOLL) {
4100                 __io_req_complete(req, issue_flags, ret, 0);
4101                 io_ring_submit_unlock(ctx, !force_nonblock);
4102         } else {
4103                 io_ring_submit_unlock(ctx, !force_nonblock);
4104                 __io_req_complete(req, issue_flags, ret, 0);
4105         }
4106         return 0;
4107 }
4108 
4109 static int io_epoll_ctl_prep(struct io_kiocb *req,
4110                              const struct io_uring_sqe *sqe)
4111 {
4112 #if defined(CONFIG_EPOLL)
4113         if (sqe->ioprio || sqe->buf_index)
4114                 return -EINVAL;
4115         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4116                 return -EINVAL;
4117 
4118         req->epoll.epfd = READ_ONCE(sqe->fd);
4119         req->epoll.op = READ_ONCE(sqe->len);
4120         req->epoll.fd = READ_ONCE(sqe->off);
4121 
4122         if (ep_op_has_event(req->epoll.op)) {
4123                 struct epoll_event __user *ev;
4124 
4125                 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4126                 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4127                         return -EFAULT;
4128         }
4129 
4130         return 0;
4131 #else
4132         return -EOPNOTSUPP;
4133 #endif
4134 }
4135 
4136 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4137 {
4138 #if defined(CONFIG_EPOLL)
4139         struct io_epoll *ie = &req->epoll;
4140         int ret;
4141         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4142 
4143         ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4144         if (force_nonblock && ret == -EAGAIN)
4145                 return -EAGAIN;
4146 
4147         if (ret < 0)
4148                 req_set_fail_links(req);
4149         __io_req_complete(req, issue_flags, ret, 0);
4150         return 0;
4151 #else
4152         return -EOPNOTSUPP;
4153 #endif
4154 }
4155 
4156 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4157 {
4158 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4159         if (sqe->ioprio || sqe->buf_index || sqe->off)
4160                 return -EINVAL;
4161         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4162                 return -EINVAL;
4163 
4164         req->madvise.addr = READ_ONCE(sqe->addr);
4165         req->madvise.len = READ_ONCE(sqe->len);
4166         req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4167         return 0;
4168 #else
4169         return -EOPNOTSUPP;
4170 #endif
4171 }
4172 
4173 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4174 {
4175 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4176         struct io_madvise *ma = &req->madvise;
4177         int ret;
4178 
4179         if (issue_flags & IO_URING_F_NONBLOCK)
4180                 return -EAGAIN;
4181 
4182         ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4183         if (ret < 0)
4184                 req_set_fail_links(req);
4185         io_req_complete(req, ret);
4186         return 0;
4187 #else
4188         return -EOPNOTSUPP;
4189 #endif
4190 }
4191 
4192 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4193 {
4194         if (sqe->ioprio || sqe->buf_index || sqe->addr)
4195                 return -EINVAL;
4196         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4197                 return -EINVAL;
4198 
4199         req->fadvise.offset = READ_ONCE(sqe->off);
4200         req->fadvise.len = READ_ONCE(sqe->len);
4201         req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4202         return 0;
4203 }
4204 
4205 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4206 {
4207         struct io_fadvise *fa = &req->fadvise;
4208         int ret;
4209 
4210         if (issue_flags & IO_URING_F_NONBLOCK) {
4211                 switch (fa->advice) {
4212                 case POSIX_FADV_NORMAL:
4213                 case POSIX_FADV_RANDOM:
4214                 case POSIX_FADV_SEQUENTIAL:
4215                         break;
4216                 default:
4217                         return -EAGAIN;
4218                 }
4219         }
4220 
4221         ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4222         if (ret < 0)
4223                 req_set_fail_links(req);
4224         io_req_complete(req, ret);
4225         return 0;
4226 }
4227 
4228 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4229 {
4230         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4231                 return -EINVAL;
4232         if (sqe->ioprio || sqe->buf_index)
4233                 return -EINVAL;
4234         if (req->flags & REQ_F_FIXED_FILE)
4235                 return -EBADF;
4236 
4237         req->statx.dfd = READ_ONCE(sqe->fd);
4238         req->statx.mask = READ_ONCE(sqe->len);
4239         req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4240         req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4241         req->statx.flags = READ_ONCE(sqe->statx_flags);
4242 
4243         return 0;
4244 }
4245 
4246 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4247 {
4248         struct io_statx *ctx = &req->statx;
4249         int ret;
4250 
4251         if (issue_flags & IO_URING_F_NONBLOCK) {
4252                 /* only need file table for an actual valid fd */
4253                 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4254                         req->flags |= REQ_F_NO_FILE_TABLE;
4255                 return -EAGAIN;
4256         }
4257 
4258         ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4259                        ctx->buffer);
4260 
4261         if (ret < 0)
4262                 req_set_fail_links(req);
4263         io_req_complete(req, ret);
4264         return 0;
4265 }
4266 
4267 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4268 {
4269         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4270                 return -EINVAL;
4271         if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4272             sqe->rw_flags || sqe->buf_index)
4273                 return -EINVAL;
4274         if (req->flags & REQ_F_FIXED_FILE)
4275                 return -EBADF;
4276 
4277         req->close.fd = READ_ONCE(sqe->fd);
4278         return 0;
4279 }
4280 
4281 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4282 {
4283         struct files_struct *files = current->files;
4284         struct io_close *close = &req->close;
4285         struct fdtable *fdt;
4286         struct file *file;
4287         int ret;
4288 
4289         file = NULL;
4290         ret = -EBADF;
4291         spin_lock(&files->file_lock);
4292         fdt = files_fdtable(files);
4293         if (close->fd >= fdt->max_fds) {
4294                 spin_unlock(&files->file_lock);
4295                 goto err;
4296         }
4297         file = fdt->fd[close->fd];
4298         if (!file) {
4299                 spin_unlock(&files->file_lock);
4300                 goto err;
4301         }
4302 
4303         if (file->f_op == &io_uring_fops) {
4304                 spin_unlock(&files->file_lock);
4305                 file = NULL;
4306                 goto err;
4307         }
4308 
4309         /* if the file has a flush method, be safe and punt to async */
4310         if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4311                 spin_unlock(&files->file_lock);
4312                 return -EAGAIN;
4313         }
4314 
4315         ret = __close_fd_get_file(close->fd, &file);
4316         spin_unlock(&files->file_lock);
4317         if (ret < 0) {
4318                 if (ret == -ENOENT)
4319                         ret = -EBADF;
4320                 goto err;
4321         }
4322 
4323         /* No ->flush() or already async, safely close from here */
4324         ret = filp_close(file, current->files);
4325 err:
4326         if (ret < 0)
4327                 req_set_fail_links(req);
4328         if (file)
4329                 fput(file);
4330         __io_req_complete(req, issue_flags, ret, 0);
4331         return 0;
4332 }
4333 
4334 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4335 {
4336         struct io_ring_ctx *ctx = req->ctx;
4337 
4338         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4339                 return -EINVAL;
4340         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4341                 return -EINVAL;
4342 
4343         req->sync.off = READ_ONCE(sqe->off);
4344         req->sync.len = READ_ONCE(sqe->len);
4345         req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4346         return 0;
4347 }
4348 
4349 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4350 {
4351         int ret;
4352 
4353         /* sync_file_range always requires a blocking context */
4354         if (issue_flags & IO_URING_F_NONBLOCK)
4355                 return -EAGAIN;
4356 
4357         ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4358                                 req->sync.flags);
4359         if (ret < 0)
4360                 req_set_fail_links(req);
4361         io_req_complete(req, ret);
4362         return 0;
4363 }
4364 
4365 #if defined(CONFIG_NET)
4366 static int io_setup_async_msg(struct io_kiocb *req,
4367                               struct io_async_msghdr *kmsg)
4368 {
4369         struct io_async_msghdr *async_msg = req->async_data;
4370 
4371         if (async_msg)
4372                 return -EAGAIN;
4373         if (io_alloc_async_data(req)) {
4374                 kfree(kmsg->free_iov);
4375                 return -ENOMEM;
4376         }
4377         async_msg = req->async_data;
4378         req->flags |= REQ_F_NEED_CLEANUP;
4379         memcpy(async_msg, kmsg, sizeof(*kmsg));
4380         async_msg->msg.msg_name = &async_msg->addr;
4381         /* if were using fast_iov, set it to the new one */
4382         if (!async_msg->free_iov)
4383                 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4384 
4385         return -EAGAIN;
4386 }
4387 
4388 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4389                                struct io_async_msghdr *iomsg)
4390 {
4391         iomsg->msg.msg_name = &iomsg->addr;
4392         iomsg->free_iov = iomsg->fast_iov;
4393         return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4394                                    req->sr_msg.msg_flags, &iomsg->free_iov);
4395 }
4396 
4397 static int io_sendmsg_prep_async(struct io_kiocb *req)
4398 {
4399         int ret;
4400 
4401         if (!io_op_defs[req->opcode].needs_async_data)
4402                 return 0;
4403         ret = io_sendmsg_copy_hdr(req, req->async_data);
4404         if (!ret)
4405                 req->flags |= REQ_F_NEED_CLEANUP;
4406         return ret;
4407 }
4408 
4409 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4410 {
4411         struct io_sr_msg *sr = &req->sr_msg;
4412 
4413         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4414                 return -EINVAL;
4415 
4416         sr->msg_flags = READ_ONCE(sqe->msg_flags);
4417         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4418         sr->len = READ_ONCE(sqe->len);
4419 
4420 #ifdef CONFIG_COMPAT
4421         if (req->ctx->compat)
4422                 sr->msg_flags |= MSG_CMSG_COMPAT;
4423 #endif
4424         return 0;
4425 }
4426 
4427 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4428 {
4429         struct io_async_msghdr iomsg, *kmsg;
4430         struct socket *sock;
4431         unsigned flags;
4432         int min_ret = 0;
4433         int ret;
4434 
4435         sock = sock_from_file(req->file);
4436         if (unlikely(!sock))
4437                 return -ENOTSOCK;
4438 
4439         kmsg = req->async_data;
4440         if (!kmsg) {
4441                 ret = io_sendmsg_copy_hdr(req, &iomsg);
4442                 if (ret)
4443                         return ret;
4444                 kmsg = &iomsg;
4445         }
4446 
4447         flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4448         if (flags & MSG_DONTWAIT)
4449                 req->flags |= REQ_F_NOWAIT;
4450         else if (issue_flags & IO_URING_F_NONBLOCK)
4451                 flags |= MSG_DONTWAIT;
4452 
4453         if (flags & MSG_WAITALL)
4454                 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4455 
4456         ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4457         if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4458                 return io_setup_async_msg(req, kmsg);
4459         if (ret == -ERESTARTSYS)
4460                 ret = -EINTR;
4461 
4462         /* fast path, check for non-NULL to avoid function call */
4463         if (kmsg->free_iov)
4464                 kfree(kmsg->free_iov);
4465         req->flags &= ~REQ_F_NEED_CLEANUP;
4466         if (ret < min_ret)
4467                 req_set_fail_links(req);
4468         __io_req_complete(req, issue_flags, ret, 0);
4469         return 0;
4470 }
4471 
4472 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4473 {
4474         struct io_sr_msg *sr = &req->sr_msg;
4475         struct msghdr msg;
4476         struct iovec iov;
4477         struct socket *sock;
4478         unsigned flags;
4479         int min_ret = 0;
4480         int ret;
4481 
4482         sock = sock_from_file(req->file);
4483         if (unlikely(!sock))
4484                 return -ENOTSOCK;
4485 
4486         ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4487         if (unlikely(ret))
4488                 return ret;
4489 
4490         msg.msg_name = NULL;
4491         msg.msg_control = NULL;
4492         msg.msg_controllen = 0;
4493         msg.msg_namelen = 0;
4494 
4495         flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4496         if (flags & MSG_DONTWAIT)
4497                 req->flags |= REQ_F_NOWAIT;
4498         else if (issue_flags & IO_URING_F_NONBLOCK)
4499                 flags |= MSG_DONTWAIT;
4500 
4501         if (flags & MSG_WAITALL)
4502                 min_ret = iov_iter_count(&msg.msg_iter);
4503 
4504         msg.msg_flags = flags;
4505         ret = sock_sendmsg(sock, &msg);
4506         if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4507                 return -EAGAIN;
4508         if (ret == -ERESTARTSYS)
4509                 ret = -EINTR;
4510 
4511         if (ret < min_ret)
4512                 req_set_fail_links(req);
4513         __io_req_complete(req, issue_flags, ret, 0);
4514         return 0;
4515 }
4516 
4517 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4518                                  struct io_async_msghdr *iomsg)
4519 {
4520         struct io_sr_msg *sr = &req->sr_msg;
4521         struct iovec __user *uiov;
4522         size_t iov_len;
4523         int ret;
4524 
4525         ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4526                                         &iomsg->uaddr, &uiov, &iov_len);
4527         if (ret)
4528                 return ret;
4529 
4530         if (req->flags & REQ_F_BUFFER_SELECT) {
4531                 if (iov_len > 1)
4532                         return -EINVAL;
4533                 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4534                         return -EFAULT;
4535                 sr->len = iomsg->fast_iov[0].iov_len;
4536                 iomsg->free_iov = NULL;
4537         } else {
4538                 iomsg->free_iov = iomsg->fast_iov;
4539                 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4540                                      &iomsg->free_iov, &iomsg->msg.msg_iter,
4541                                      false);
4542                 if (ret > 0)
4543                         ret = 0;
4544         }
4545 
4546         return ret;
4547 }
4548 
4549 #ifdef CONFIG_COMPAT
4550 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4551                                         struct io_async_msghdr *iomsg)
4552 {
4553         struct compat_msghdr __user *msg_compat;
4554         struct io_sr_msg *sr = &req->sr_msg;
4555         struct compat_iovec __user *uiov;
4556         compat_uptr_t ptr;
4557         compat_size_t len;
4558         int ret;
4559 
4560         msg_compat = (struct compat_msghdr __user *) sr->umsg;
4561         ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4562                                         &ptr, &len);
4563         if (ret)
4564                 return ret;
4565 
4566         uiov = compat_ptr(ptr);
4567         if (req->flags & REQ_F_BUFFER_SELECT) {
4568                 compat_ssize_t clen;
4569 
4570                 if (len > 1)
4571                         return -EINVAL;
4572                 if (!access_ok(uiov, sizeof(*uiov)))
4573                         return -EFAULT;
4574                 if (__get_user(clen, &uiov->iov_len))
4575                         return -EFAULT;
4576                 if (clen < 0)
4577                         return -EINVAL;
4578                 sr->len = clen;
4579                 iomsg->free_iov = NULL;
4580         } else {
4581                 iomsg->free_iov = iomsg->fast_iov;
4582                 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4583                                    UIO_FASTIOV, &iomsg->free_iov,
4584                                    &iomsg->msg.msg_iter, true);
4585                 if (ret < 0)
4586                         return ret;
4587         }
4588 
4589         return 0;
4590 }
4591 #endif
4592 
4593 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4594                                struct io_async_msghdr *iomsg)
4595 {
4596         iomsg->msg.msg_name = &iomsg->addr;
4597 
4598 #ifdef CONFIG_COMPAT
4599         if (req->ctx->compat)
4600                 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4601 #endif
4602 
4603         return __io_recvmsg_copy_hdr(req, iomsg);
4604 }
4605 
4606 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4607                                                bool needs_lock)
4608 {
4609         struct io_sr_msg *sr = &req->sr_msg;
4610         struct io_buffer *kbuf;
4611 
4612         kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4613         if (IS_ERR(kbuf))
4614                 return kbuf;
4615 
4616         sr->kbuf = kbuf;
4617         req->flags |= REQ_F_BUFFER_SELECTED;
4618         return kbuf;
4619 }
4620 
4621 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4622 {
4623         return io_put_kbuf(req, req->sr_msg.kbuf);
4624 }
4625 
4626 static int io_recvmsg_prep_async(struct io_kiocb *req)
4627 {
4628         int ret;
4629 
4630         if (!io_op_defs[req->opcode].needs_async_data)
4631                 return 0;
4632         ret = io_recvmsg_copy_hdr(req, req->async_data);
4633         if (!ret)
4634                 req->flags |= REQ_F_NEED_CLEANUP;
4635         return ret;
4636 }
4637 
4638 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4639 {
4640         struct io_sr_msg *sr = &req->sr_msg;
4641 
4642         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4643                 return -EINVAL;
4644 
4645         sr->msg_flags = READ_ONCE(sqe->msg_flags);
4646         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4647         sr->len = READ_ONCE(sqe->len);
4648         sr->bgid = READ_ONCE(sqe->buf_group);
4649 
4650 #ifdef CONFIG_COMPAT
4651         if (req->ctx->compat)
4652                 sr->msg_flags |= MSG_CMSG_COMPAT;
4653 #endif
4654         return 0;
4655 }
4656 
4657 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4658 {
4659         struct io_async_msghdr iomsg, *kmsg;
4660         struct socket *sock;
4661         struct io_buffer *kbuf;
4662         unsigned flags;
4663         int min_ret = 0;
4664         int ret, cflags = 0;
4665         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4666 
4667         sock = sock_from_file(req->file);
4668         if (unlikely(!sock))
4669                 return -ENOTSOCK;
4670 
4671         kmsg = req->async_data;
4672         if (!kmsg) {
4673                 ret = io_recvmsg_copy_hdr(req, &iomsg);
4674                 if (ret)
4675                         return ret;
4676                 kmsg = &iomsg;
4677         }
4678 
4679         if (req->flags & REQ_F_BUFFER_SELECT) {
4680                 kbuf = io_recv_buffer_select(req, !force_nonblock);
4681                 if (IS_ERR(kbuf))
4682                         return PTR_ERR(kbuf);
4683                 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4684                 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4685                 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4686                                 1, req->sr_msg.len);
4687         }
4688 
4689         flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4690         if (flags & MSG_DONTWAIT)
4691                 req->flags |= REQ_F_NOWAIT;
4692         else if (force_nonblock)
4693                 flags |= MSG_DONTWAIT;
4694 
4695         if (flags & MSG_WAITALL)
4696                 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4697 
4698         ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4699                                         kmsg->uaddr, flags);
4700         if (force_nonblock && ret == -EAGAIN)
4701                 return io_setup_async_msg(req, kmsg);
4702         if (ret == -ERESTARTSYS)
4703                 ret = -EINTR;
4704 
4705         if (req->flags & REQ_F_BUFFER_SELECTED)
4706                 cflags = io_put_recv_kbuf(req);
4707         /* fast path, check for non-NULL to avoid function call */
4708         if (kmsg->free_iov)
4709                 kfree(kmsg->free_iov);
4710         req->flags &= ~REQ_F_NEED_CLEANUP;
4711         if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4712                 req_set_fail_links(req);
4713         __io_req_complete(req, issue_flags, ret, cflags);
4714         return 0;
4715 }
4716 
4717 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4718 {
4719         struct io_buffer *kbuf;
4720         struct io_sr_msg *sr = &req->sr_msg;
4721         struct msghdr msg;
4722         void __user *buf = sr->buf;
4723         struct socket *sock;
4724         struct iovec iov;
4725         unsigned flags;
4726         int min_ret = 0;
4727         int ret, cflags = 0;
4728         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4729 
4730         sock = sock_from_file(req->file);
4731         if (unlikely(!sock))
4732                 return -ENOTSOCK;
4733 
4734         if (req->flags & REQ_F_BUFFER_SELECT) {
4735                 kbuf = io_recv_buffer_select(req, !force_nonblock);
4736                 if (IS_ERR(kbuf))
4737                         return PTR_ERR(kbuf);
4738                 buf = u64_to_user_ptr(kbuf->addr);
4739         }
4740 
4741         ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4742         if (unlikely(ret))
4743                 goto out_free;
4744 
4745         msg.msg_name = NULL;
4746         msg.msg_control = NULL;
4747         msg.msg_controllen = 0;
4748         msg.msg_namelen = 0;
4749         msg.msg_iocb = NULL;
4750         msg.msg_flags = 0;
4751 
4752         flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4753         if (flags & MSG_DONTWAIT)
4754                 req->flags |= REQ_F_NOWAIT;
4755         else if (force_nonblock)
4756                 flags |= MSG_DONTWAIT;
4757 
4758         if (flags & MSG_WAITALL)
4759                 min_ret = iov_iter_count(&msg.msg_iter);
4760 
4761         ret = sock_recvmsg(sock, &msg, flags);
4762         if (force_nonblock && ret == -EAGAIN)
4763                 return -EAGAIN;
4764         if (ret == -ERESTARTSYS)
4765                 ret = -EINTR;
4766 out_free:
4767         if (req->flags & REQ_F_BUFFER_SELECTED)
4768                 cflags = io_put_recv_kbuf(req);
4769         if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4770                 req_set_fail_links(req);
4771         __io_req_complete(req, issue_flags, ret, cflags);
4772         return 0;
4773 }
4774 
4775 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4776 {
4777         struct io_accept *accept = &req->accept;
4778 
4779         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4780                 return -EINVAL;
4781         if (sqe->ioprio || sqe->len || sqe->buf_index)
4782                 return -EINVAL;
4783 
4784         accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4785         accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4786         accept->flags = READ_ONCE(sqe->accept_flags);
4787         accept->nofile = rlimit(RLIMIT_NOFILE);
4788         return 0;
4789 }
4790 
4791 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4792 {
4793         struct io_accept *accept = &req->accept;
4794         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4795         unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4796         int ret;
4797 
4798         if (req->file->f_flags & O_NONBLOCK)
4799                 req->flags |= REQ_F_NOWAIT;
4800 
4801         ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4802                                         accept->addr_len, accept->flags,
4803                                         accept->nofile);
4804         if (ret == -EAGAIN && force_nonblock)
4805                 return -EAGAIN;
4806         if (ret < 0) {
4807                 if (ret == -ERESTARTSYS)
4808                         ret = -EINTR;
4809                 req_set_fail_links(req);
4810         }
4811         __io_req_complete(req, issue_flags, ret, 0);
4812         return 0;
4813 }
4814 
4815 static int io_connect_prep_async(struct io_kiocb *req)
4816 {
4817         struct io_async_connect *io = req->async_data;
4818         struct io_connect *conn = &req->connect;
4819 
4820         return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4821 }
4822 
4823 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4824 {
4825         struct io_connect *conn = &req->connect;
4826 
4827         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4828                 return -EINVAL;
4829         if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4830                 return -EINVAL;
4831 
4832         conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4833         conn->addr_len =  READ_ONCE(sqe->addr2);
4834         return 0;
4835 }
4836 
4837 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4838 {
4839         struct io_async_connect __io, *io;
4840         unsigned file_flags;
4841         int ret;
4842         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4843 
4844         if (req->async_data) {
4845                 io = req->async_data;
4846         } else {
4847                 ret = move_addr_to_kernel(req->connect.addr,
4848                                                 req->connect.addr_len,
4849                                                 &__io.address);
4850                 if (ret)
4851                         goto out;
4852                 io = &__io;
4853         }
4854 
4855         file_flags = force_nonblock ? O_NONBLOCK : 0;
4856 
4857         ret = __sys_connect_file(req->file, &io->address,
4858                                         req->connect.addr_len, file_flags);
4859         if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4860                 if (req->async_data)
4861                         return -EAGAIN;
4862                 if (io_alloc_async_data(req)) {
4863                         ret = -ENOMEM;
4864                         goto out;
4865                 }
4866                 memcpy(req->async_data, &__io, sizeof(__io));
4867                 return -EAGAIN;
4868         }
4869         if (ret == -ERESTARTSYS)
4870                 ret = -EINTR;
4871 out:
4872         if (ret < 0)
4873                 req_set_fail_links(req);
4874         __io_req_complete(req, issue_flags, ret, 0);
4875         return 0;
4876 }
4877 #else /* !CONFIG_NET */
4878 #define IO_NETOP_FN(op)                                                 \
4879 static int io_##op(struct io_kiocb *req, unsigned int issue_flags)      \
4880 {                                                                       \
4881         return -EOPNOTSUPP;                                             \
4882 }
4883 
4884 #define IO_NETOP_PREP(op)                                               \
4885 IO_NETOP_FN(op)                                                         \
4886 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4887 {                                                                       \
4888         return -EOPNOTSUPP;                                             \
4889 }                                                                       \
4890 
4891 #define IO_NETOP_PREP_ASYNC(op)                                         \
4892 IO_NETOP_PREP(op)                                                       \
4893 static int io_##op##_prep_async(struct io_kiocb *req)                   \
4894 {                                                                       \
4895         return -EOPNOTSUPP;                                             \
4896 }
4897 
4898 IO_NETOP_PREP_ASYNC(sendmsg);
4899 IO_NETOP_PREP_ASYNC(recvmsg);
4900 IO_NETOP_PREP_ASYNC(connect);
4901 IO_NETOP_PREP(accept);
4902 IO_NETOP_FN(send);
4903 IO_NETOP_FN(recv);
4904 #endif /* CONFIG_NET */
4905 
4906 struct io_poll_table {
4907         struct poll_table_struct pt;
4908         struct io_kiocb *req;
4909         int error;
4910 };
4911 
4912 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4913                            __poll_t mask, task_work_func_t func)
4914 {
4915         int ret;
4916 
4917         /* for instances that support it check for an event match first: */
4918         if (mask && !(mask & poll->events))
4919                 return 0;
4920 
4921         trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4922 
4923         list_del_init(&poll->wait.entry);
4924 
4925         req->result = mask;
4926         req->task_work.func = func;
4927         percpu_ref_get(&req->ctx->refs);
4928 
4929         /*
4930          * If this fails, then the task is exiting. When a task exits, the
4931          * work gets canceled, so just cancel this request as well instead
4932          * of executing it. We can't safely execute it anyway, as we may not
4933          * have the needed state needed for it anyway.
4934          */
4935         ret = io_req_task_work_add(req);
4936         if (unlikely(ret)) {
4937                 WRITE_ONCE(poll->canceled, true);
4938                 io_req_task_work_add_fallback(req, func);
4939         }
4940         return 1;
4941 }
4942 
4943 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4944         __acquires(&req->ctx->completion_lock)
4945 {
4946         struct io_ring_ctx *ctx = req->ctx;
4947 
4948         if (!req->result && !READ_ONCE(poll->canceled)) {
4949                 struct poll_table_struct pt = { ._key = poll->events };
4950 
4951                 req->result = vfs_poll(req->file, &pt) & poll->events;
4952         }
4953 
4954         spin_lock_irq(&ctx->completion_lock);
4955         if (!req->result && !READ_ONCE(poll->canceled)) {
4956                 add_wait_queue(poll->head, &poll->wait);
4957                 return true;
4958         }
4959 
4960         return false;
4961 }
4962 
4963 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4964 {
4965         /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4966         if (req->opcode == IORING_OP_POLL_ADD)
4967                 return req->async_data;
4968         return req->apoll->double_poll;
4969 }
4970 
4971 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4972 {
4973         if (req->opcode == IORING_OP_POLL_ADD)
4974                 return &req->poll;
4975         return &req->apoll->poll;
4976 }
4977 
4978 static void io_poll_remove_double(struct io_kiocb *req)
4979 {
4980         struct io_poll_iocb *poll = io_poll_get_double(req);
4981 
4982         lockdep_assert_held(&req->ctx->completion_lock);
4983 
4984         if (poll && poll->head) {
4985                 struct wait_queue_head *head = poll->head;
4986 
4987                 spin_lock(&head->lock);
4988                 list_del_init(&poll->wait.entry);
4989                 if (poll->wait.private)
4990                         req_ref_put(req);
4991                 poll->head = NULL;
4992                 spin_unlock(&head->lock);
4993         }
4994 }
4995 
4996 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4997 {
4998         struct io_ring_ctx *ctx = req->ctx;
4999 
5000         io_poll_remove_double(req);
5001         req->poll.done = true;
5002         io_cqring_fill_event(req, error ? error : mangle_poll(mask));
5003         io_commit_cqring(ctx);
5004 }
5005 
5006 static void io_poll_task_func(struct callback_head *cb)
5007 {
5008         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5009         struct io_ring_ctx *ctx = req->ctx;
5010         struct io_kiocb *nxt;
5011 
5012         if (io_poll_rewait(req, &req->poll)) {
5013                 spin_unlock_irq(&ctx->completion_lock);
5014         } else {
5015                 hash_del(&req->hash_node);
5016                 io_poll_complete(req, req->result, 0);
5017                 spin_unlock_irq(&ctx->completion_lock);
5018 
5019                 nxt = io_put_req_find_next(req);
5020                 io_cqring_ev_posted(ctx);
5021                 if (nxt)
5022                         __io_req_task_submit(nxt);
5023         }
5024 
5025         percpu_ref_put(&ctx->refs);
5026 }
5027 
5028 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5029                                int sync, void *key)
5030 {
5031         struct io_kiocb *req = wait->private;
5032         struct io_poll_iocb *poll = io_poll_get_single(req);
5033         __poll_t mask = key_to_poll(key);
5034 
5035         /* for instances that support it check for an event match first: */
5036         if (mask && !(mask & poll->events))
5037                 return 0;
5038 
5039         list_del_init(&wait->entry);
5040 
5041         if (poll && poll->head) {
5042                 bool done;
5043 
5044                 spin_lock(&poll->head->lock);
5045                 done = list_empty(&poll->wait.entry);
5046                 if (!done)
5047                         list_del_init(&poll->wait.entry);
5048                 /* make sure double remove sees this as being gone */
5049                 wait->private = NULL;
5050                 spin_unlock(&poll->head->lock);
5051                 if (!done) {
5052                         /* use wait func handler, so it matches the rq type */
5053                         poll->wait.func(&poll->wait, mode, sync, key);
5054                 }
5055         }
5056         req_ref_put(req);
5057         return 1;
5058 }
5059 
5060 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5061                               wait_queue_func_t wake_func)
5062 {
5063         poll->head = NULL;
5064         poll->done = false;
5065         poll->canceled = false;
5066         poll->events = events;
5067         INIT_LIST_HEAD(&poll->wait.entry);
5068         init_waitqueue_func_entry(&poll->wait, wake_func);
5069 }
5070 
5071 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5072                             struct wait_queue_head *head,
5073                             struct io_poll_iocb **poll_ptr)
5074 {
5075         struct io_kiocb *req = pt->req;
5076 
5077         /*
5078          * If poll->head is already set, it's because the file being polled
5079          * uses multiple waitqueues for poll handling (eg one for read, one
5080          * for write). Setup a separate io_poll_iocb if this happens.
5081          */
5082         if (unlikely(poll->head)) {
5083                 struct io_poll_iocb *poll_one = poll;
5084 
5085                 /* already have a 2nd entry, fail a third attempt */
5086                 if (*poll_ptr) {
5087                         pt->error = -EINVAL;
5088                         return;
5089                 }
5090                 /* double add on the same waitqueue head, ignore */
5091                 if (poll->head == head)
5092                         return;
5093                 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5094                 if (!poll) {
5095                         pt->error = -ENOMEM;
5096                         return;
5097                 }
5098                 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5099                 req_ref_get(req);
5100                 poll->wait.private = req;
5101                 *poll_ptr = poll;
5102         }
5103 
5104         pt->error = 0;
5105         poll->head = head;
5106 
5107         if (poll->events & EPOLLEXCLUSIVE)
5108                 add_wait_queue_exclusive(head, &poll->wait);
5109         else
5110                 add_wait_queue(head, &poll->wait);
5111 }
5112 
5113 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5114                                struct poll_table_struct *p)
5115 {
5116         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5117         struct async_poll *apoll = pt->req->apoll;
5118 
5119         __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5120 }
5121 
5122 static void io_async_task_func(struct callback_head *cb)
5123 {
5124         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5125         struct async_poll *apoll = req->apoll;
5126         struct io_ring_ctx *ctx = req->ctx;
5127 
5128         trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5129 
5130         if (io_poll_rewait(req, &apoll->poll)) {
5131                 spin_unlock_irq(&ctx->completion_lock);
5132                 percpu_ref_put(&ctx->refs);
5133                 return;
5134         }
5135 
5136         /* If req is still hashed, it cannot have been canceled. Don't check. */
5137         if (hash_hashed(&req->hash_node))
5138                 hash_del(&req->hash_node);
5139 
5140         io_poll_remove_double(req);
5141         spin_unlock_irq(&ctx->completion_lock);
5142 
5143         if (!READ_ONCE(apoll->poll.canceled))
5144                 __io_req_task_submit(req);
5145         else
5146                 __io_req_task_cancel(req, -ECANCELED);
5147 
5148         percpu_ref_put(&ctx->refs);
5149         kfree(apoll->double_poll);
5150         kfree(apoll);
5151 }
5152 
5153 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5154                         void *key)
5155 {
5156         struct io_kiocb *req = wait->private;
5157         struct io_poll_iocb *poll = &req->apoll->poll;
5158 
5159         trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5160                                         key_to_poll(key));
5161 
5162         return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5163 }
5164 
5165 static void io_poll_req_insert(struct io_kiocb *req)
5166 {
5167         struct io_ring_ctx *ctx = req->ctx;
5168         struct hlist_head *list;
5169 
5170         list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5171         hlist_add_head(&req->hash_node, list);
5172 }
5173 
5174 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5175                                       struct io_poll_iocb *poll,
5176                                       struct io_poll_table *ipt, __poll_t mask,
5177                                       wait_queue_func_t wake_func)
5178         __acquires(&ctx->completion_lock)
5179 {
5180         struct io_ring_ctx *ctx = req->ctx;
5181         bool cancel = false;
5182 
5183         INIT_HLIST_NODE(&req->hash_node);
5184         io_init_poll_iocb(poll, mask, wake_func);
5185         poll->file = req->file;
5186         poll->wait.private = req;
5187 
5188         ipt->pt._key = mask;
5189         ipt->req = req;
5190         ipt->error = -EINVAL;
5191 
5192         mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5193 
5194         spin_lock_irq(&ctx->completion_lock);
5195         if (likely(poll->head)) {
5196                 spin_lock(&poll->head->lock);
5197                 if (unlikely(list_empty(&poll->wait.entry))) {
5198                         if (ipt->error)
5199                                 cancel = true;
5200                         ipt->error = 0;
5201                         mask = 0;
5202                 }
5203                 if (mask || ipt->error)
5204                         list_del_init(&poll->wait.entry);
5205                 else if (cancel)
5206                         WRITE_ONCE(poll->canceled, true);
5207                 else if (!poll->done) /* actually waiting for an event */
5208                         io_poll_req_insert(req);
5209                 spin_unlock(&poll->head->lock);
5210         }
5211 
5212         return mask;
5213 }
5214 
5215 static bool io_arm_poll_handler(struct io_kiocb *req)
5216 {
5217         const struct io_op_def *def = &io_op_defs[req->opcode];
5218         struct io_ring_ctx *ctx = req->ctx;
5219         struct async_poll *apoll;
5220         struct io_poll_table ipt;
5221         __poll_t mask, ret;
5222         int rw;
5223 
5224         if (!req->file || !file_can_poll(req->file))
5225                 return false;
5226         if (req->flags & REQ_F_POLLED)
5227                 return false;
5228         if (def->pollin)
5229                 rw = READ;
5230         else if (def->pollout)
5231                 rw = WRITE;
5232         else
5233                 return false;
5234         /* if we can't nonblock try, then no point in arming a poll handler */
5235         if (!io_file_supports_async(req->file, rw))
5236                 return false;
5237 
5238         apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5239         if (unlikely(!apoll))
5240                 return false;
5241         apoll->double_poll = NULL;
5242 
5243         req->flags |= REQ_F_POLLED;
5244         req->apoll = apoll;
5245 
5246         mask = 0;
5247         if (def->pollin)
5248                 mask |= POLLIN | POLLRDNORM;
5249         if (def->pollout)
5250                 mask |= POLLOUT | POLLWRNORM;
5251 
5252         /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5253         if ((req->opcode == IORING_OP_RECVMSG) &&
5254             (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5255                 mask &= ~POLLIN;
5256 
5257         mask |= POLLERR | POLLPRI;
5258 
5259         ipt.pt._qproc = io_async_queue_proc;
5260 
5261         ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5262                                         io_async_wake);
5263         if (ret || ipt.error) {
5264                 io_poll_remove_double(req);
5265                 spin_unlock_irq(&ctx->completion_lock);
5266                 kfree(apoll->double_poll);
5267                 kfree(apoll);
5268                 return false;
5269         }
5270         spin_unlock_irq(&ctx->completion_lock);
5271         trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5272                                         apoll->poll.events);
5273         return true;
5274 }
5275 
5276 static bool __io_poll_remove_one(struct io_kiocb *req,
5277                                  struct io_poll_iocb *poll)
5278 {
5279         bool do_complete = false;
5280 
5281         spin_lock(&poll->head->lock);
5282         WRITE_ONCE(poll->canceled, true);
5283         if (!list_empty(&poll->wait.entry)) {
5284                 list_del_init(&poll->wait.entry);
5285                 do_complete = true;
5286         }
5287         spin_unlock(&poll->head->lock);
5288         hash_del(&req->hash_node);
5289         return do_complete;
5290 }
5291 
5292 static bool io_poll_remove_one(struct io_kiocb *req)
5293 {
5294         bool do_complete;
5295 
5296         io_poll_remove_double(req);
5297 
5298         if (req->opcode == IORING_OP_POLL_ADD) {
5299                 do_complete = __io_poll_remove_one(req, &req->poll);
5300         } else {
5301                 struct async_poll *apoll = req->apoll;
5302 
5303                 /* non-poll requests have submit ref still */
5304                 do_complete = __io_poll_remove_one(req, &apoll->poll);
5305                 if (do_complete) {
5306                         io_put_req(req);
5307                         kfree(apoll->double_poll);
5308                         kfree(apoll);
5309                 }
5310         }
5311 
5312         if (do_complete) {
5313                 io_cqring_fill_event(req, -ECANCELED);
5314                 io_commit_cqring(req->ctx);
5315                 req_set_fail_links(req);
5316                 io_put_req_deferred(req, 1);
5317         }
5318 
5319         return do_complete;
5320 }
5321 
5322 /*
5323  * Returns true if we found and killed one or more poll requests
5324  */
5325 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5326                                struct files_struct *files)
5327 {
5328         struct hlist_node *tmp;
5329         struct io_kiocb *req;
5330         int posted = 0, i;
5331 
5332         spin_lock_irq(&ctx->completion_lock);
5333         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5334                 struct hlist_head *list;
5335 
5336                 list = &ctx->cancel_hash[i];
5337                 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5338                         if (io_match_task(req, tsk, files))
5339                                 posted += io_poll_remove_one(req);
5340                 }
5341         }
5342         spin_unlock_irq(&ctx->completion_lock);
5343 
5344         if (posted)
5345                 io_cqring_ev_posted(ctx);
5346 
5347         return posted != 0;
5348 }
5349 
5350 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5351 {
5352         struct hlist_head *list;
5353         struct io_kiocb *req;
5354 
5355         list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5356         hlist_for_each_entry(req, list, hash_node) {
5357                 if (sqe_addr != req->user_data)
5358                         continue;
5359                 if (io_poll_remove_one(req))
5360                         return 0;
5361                 return -EALREADY;
5362         }
5363 
5364         return -ENOENT;
5365 }
5366 
5367 static int io_poll_remove_prep(struct io_kiocb *req,
5368                                const struct io_uring_sqe *sqe)
5369 {
5370         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5371                 return -EINVAL;
5372         if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5373             sqe->poll_events)
5374                 return -EINVAL;
5375 
5376         req->poll_remove.addr = READ_ONCE(sqe->addr);
5377         return 0;
5378 }
5379 
5380 /*
5381  * Find a running poll command that matches one specified in sqe->addr,
5382  * and remove it if found.
5383  */
5384 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5385 {
5386         struct io_ring_ctx *ctx = req->ctx;
5387         int ret;
5388 
5389         spin_lock_irq(&ctx->completion_lock);
5390         ret = io_poll_cancel(ctx, req->poll_remove.addr);
5391         spin_unlock_irq(&ctx->completion_lock);
5392 
5393         if (ret < 0)
5394                 req_set_fail_links(req);
5395         io_req_complete(req, ret);
5396         return 0;
5397 }
5398 
5399 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5400                         void *key)
5401 {
5402         struct io_kiocb *req = wait->private;
5403         struct io_poll_iocb *poll = &req->poll;
5404 
5405         return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5406 }
5407 
5408 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5409                                struct poll_table_struct *p)
5410 {
5411         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5412 
5413         __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5414 }
5415 
5416 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5417 {
5418         struct io_poll_iocb *poll = &req->poll;
5419         u32 events;
5420 
5421         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5422                 return -EINVAL;
5423         if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5424                 return -EINVAL;
5425 
5426         events = READ_ONCE(sqe->poll32_events);
5427 #ifdef __BIG_ENDIAN
5428         events = swahw32(events);
5429 #endif
5430         poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5431                        (events & EPOLLEXCLUSIVE);
5432         return 0;
5433 }
5434 
5435 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5436 {
5437         struct io_poll_iocb *poll = &req->poll;
5438         struct io_ring_ctx *ctx = req->ctx;
5439         struct io_poll_table ipt;
5440         __poll_t mask;
5441 
5442         ipt.pt._qproc = io_poll_queue_proc;
5443 
5444         mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5445                                         io_poll_wake);
5446 
5447         if (mask) { /* no async, we'd stolen it */
5448                 ipt.error = 0;
5449                 io_poll_complete(req, mask, 0);
5450         }
5451         spin_unlock_irq(&ctx->completion_lock);
5452 
5453         if (mask) {
5454                 io_cqring_ev_posted(ctx);
5455                 io_put_req(req);
5456         }
5457         return ipt.error;
5458 }
5459 
5460 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5461 {
5462         struct io_timeout_data *data = container_of(timer,
5463                                                 struct io_timeout_data, timer);
5464         struct io_kiocb *req = data->req;
5465         struct io_ring_ctx *ctx = req->ctx;
5466         unsigned long flags;
5467 
5468         spin_lock_irqsave(&ctx->completion_lock, flags);
5469         list_del_init(&req->timeout.list);
5470         atomic_set(&req->ctx->cq_timeouts,
5471                 atomic_read(&req->ctx->cq_timeouts) + 1);
5472 
5473         io_cqring_fill_event(req, -ETIME);
5474         io_commit_cqring(ctx);
5475         spin_unlock_irqrestore(&ctx->completion_lock, flags);
5476 
5477         io_cqring_ev_posted(ctx);
5478         req_set_fail_links(req);
5479         io_put_req(req);
5480         return HRTIMER_NORESTART;
5481 }
5482 
5483 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5484                                            __u64 user_data)
5485 {
5486         struct io_timeout_data *io;
5487         struct io_kiocb *req;
5488         int ret = -ENOENT;
5489 
5490         list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5491                 if (user_data == req->user_data) {
5492                         ret = 0;
5493                         break;
5494                 }
5495         }
5496 
5497         if (ret == -ENOENT)
5498                 return ERR_PTR(ret);
5499 
5500         io = req->async_data;
5501         ret = hrtimer_try_to_cancel(&io->timer);
5502         if (ret == -1)
5503                 return ERR_PTR(-EALREADY);
5504         list_del_init(&req->timeout.list);
5505         return req;
5506 }
5507 
5508 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5509 {
5510         struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5511 
5512         if (IS_ERR(req))
5513                 return PTR_ERR(req);
5514 
5515         req_set_fail_links(req);
5516         io_cqring_fill_event(req, -ECANCELED);
5517         io_put_req_deferred(req, 1);
5518         return 0;
5519 }
5520 
5521 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5522                              struct timespec64 *ts, enum hrtimer_mode mode)
5523 {
5524         struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5525         struct io_timeout_data *data;
5526 
5527         if (IS_ERR(req))
5528                 return PTR_ERR(req);
5529 
5530         req->timeout.off = 0; /* noseq */
5531         data = req->async_data;
5532         list_add_tail(&req->timeout.list, &ctx->timeout_list);
5533         hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5534         data->timer.function = io_timeout_fn;
5535         hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5536         return 0;
5537 }
5538 
5539 static int io_timeout_remove_prep(struct io_kiocb *req,
5540                                   const struct io_uring_sqe *sqe)
5541 {
5542         struct io_timeout_rem *tr = &req->timeout_rem;
5543 
5544         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5545                 return -EINVAL;
5546         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5547                 return -EINVAL;
5548         if (sqe->ioprio || sqe->buf_index || sqe->len)
5549                 return -EINVAL;
5550 
5551         tr->addr = READ_ONCE(sqe->addr);
5552         tr->flags = READ_ONCE(sqe->timeout_flags);
5553         if (tr->flags & IORING_TIMEOUT_UPDATE) {
5554                 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5555                         return -EINVAL;
5556                 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5557                         return -EFAULT;
5558         } else if (tr->flags) {
5559                 /* timeout removal doesn't support flags */
5560                 return -EINVAL;
5561         }
5562 
5563         return 0;
5564 }
5565 
5566 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5567 {
5568         return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5569                                             : HRTIMER_MODE_REL;
5570 }
5571 
5572 /*
5573  * Remove or update an existing timeout command
5574  */
5575 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5576 {
5577         struct io_timeout_rem *tr = &req->timeout_rem;
5578         struct io_ring_ctx *ctx = req->ctx;
5579         int ret;
5580 
5581         spin_lock_irq(&ctx->completion_lock);
5582         if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5583                 ret = io_timeout_cancel(ctx, tr->addr);
5584         else
5585                 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5586                                         io_translate_timeout_mode(tr->flags));
5587 
5588         io_cqring_fill_event(req, ret);
5589         io_commit_cqring(ctx);
5590         spin_unlock_irq(&ctx->completion_lock);
5591         io_cqring_ev_posted(ctx);
5592         if (ret < 0)
5593                 req_set_fail_links(req);
5594         io_put_req(req);
5595         return 0;
5596 }
5597 
5598 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5599                            bool is_timeout_link)
5600 {
5601         struct io_timeout_data *data;
5602         unsigned flags;
5603         u32 off = READ_ONCE(sqe->off);
5604 
5605         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5606                 return -EINVAL;
5607         if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5608                 return -EINVAL;
5609         if (off && is_timeout_link)
5610                 return -EINVAL;
5611         flags = READ_ONCE(sqe->timeout_flags);
5612         if (flags & ~IORING_TIMEOUT_ABS)
5613                 return -EINVAL;
5614 
5615         req->timeout.off = off;
5616 
5617         if (!req->async_data && io_alloc_async_data(req))
5618                 return -ENOMEM;
5619 
5620         data = req->async_data;
5621         data->req = req;
5622 
5623         if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5624                 return -EFAULT;
5625 
5626         data->mode = io_translate_timeout_mode(flags);
5627         hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5628         if (is_timeout_link)
5629                 io_req_track_inflight(req);
5630         return 0;
5631 }
5632 
5633 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5634 {
5635         struct io_ring_ctx *ctx = req->ctx;
5636         struct io_timeout_data *data = req->async_data;
5637         struct list_head *entry;
5638         u32 tail, off = req->timeout.off;
5639 
5640         spin_lock_irq(&ctx->completion_lock);
5641 
5642         /*
5643          * sqe->off holds how many events that need to occur for this
5644          * timeout event to be satisfied. If it isn't set, then this is
5645          * a pure timeout request, sequence isn't used.
5646          */
5647         if (io_is_timeout_noseq(req)) {
5648                 entry = ctx->timeout_list.prev;
5649                 goto add;
5650         }
5651 
5652         tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5653         req->timeout.target_seq = tail + off;
5654 
5655         /* Update the last seq here in case io_flush_timeouts() hasn't.
5656          * This is safe because ->completion_lock is held, and submissions
5657          * and completions are never mixed in the same ->completion_lock section.
5658          */
5659         ctx->cq_last_tm_flush = tail;
5660 
5661         /*
5662          * Insertion sort, ensuring the first entry in the list is always
5663          * the one we need first.
5664          */
5665         list_for_each_prev(entry, &ctx->timeout_list) {
5666                 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5667                                                   timeout.list);
5668 
5669                 if (io_is_timeout_noseq(nxt))
5670                         continue;
5671                 /* nxt.seq is behind @tail, otherwise would've been completed */
5672                 if (off >= nxt->timeout.target_seq - tail)
5673                         break;
5674         }
5675 add:
5676         list_add(&req->timeout.list, entry);
5677         data->timer.function = io_timeout_fn;
5678         hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5679         spin_unlock_irq(&ctx->completion_lock);
5680         return 0;
5681 }
5682 
5683 struct io_cancel_data {
5684         struct io_ring_ctx *ctx;
5685         u64 user_data;
5686 };
5687 
5688 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5689 {
5690         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5691         struct io_cancel_data *cd = data;
5692 
5693         return req->ctx == cd->ctx && req->user_data == cd->user_data;
5694 }
5695 
5696 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5697                                struct io_ring_ctx *ctx)
5698 {
5699         struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5700         enum io_wq_cancel cancel_ret;
5701         int ret = 0;
5702 
5703         if (!tctx || !tctx->io_wq)
5704                 return -ENOENT;
5705 
5706         cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5707         switch (cancel_ret) {
5708         case IO_WQ_CANCEL_OK:
5709                 ret = 0;
5710                 break;
5711         case IO_WQ_CANCEL_RUNNING:
5712                 ret = -EALREADY;
5713                 break;
5714         case IO_WQ_CANCEL_NOTFOUND:
5715                 ret = -ENOENT;
5716                 break;
5717         }
5718 
5719         return ret;
5720 }
5721 
5722 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5723                                      struct io_kiocb *req, __u64 sqe_addr,
5724                                      int success_ret)
5725 {
5726         unsigned long flags;
5727         int ret;
5728 
5729         ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5730         spin_lock_irqsave(&ctx->completion_lock, flags);
5731         if (ret != -ENOENT)
5732                 goto done;
5733         ret = io_timeout_cancel(ctx, sqe_addr);
5734         if (ret != -ENOENT)
5735                 goto done;
5736         ret = io_poll_cancel(ctx, sqe_addr);
5737 done:
5738         if (!ret)
5739                 ret = success_ret;
5740         io_cqring_fill_event(req, ret);
5741         io_commit_cqring(ctx);
5742         spin_unlock_irqrestore(&ctx->completion_lock, flags);
5743         io_cqring_ev_posted(ctx);
5744 
5745         if (ret < 0)
5746                 req_set_fail_links(req);
5747 }
5748 
5749 static int io_async_cancel_prep(struct io_kiocb *req,
5750                                 const struct io_uring_sqe *sqe)
5751 {
5752         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5753                 return -EINVAL;
5754         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5755                 return -EINVAL;
5756         if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5757                 return -EINVAL;
5758 
5759         req->cancel.addr = READ_ONCE(sqe->addr);
5760         return 0;
5761 }
5762 
5763 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5764 {
5765         struct io_ring_ctx *ctx = req->ctx;
5766         u64 sqe_addr = req->cancel.addr;
5767         struct io_tctx_node *node;
5768         int ret;
5769 
5770         /* tasks should wait for their io-wq threads, so safe w/o sync */
5771         ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5772         spin_lock_irq(&ctx->completion_lock);
5773         if (ret != -ENOENT)
5774                 goto done;
5775         ret = io_timeout_cancel(ctx, sqe_addr);
5776         if (ret != -ENOENT)
5777                 goto done;
5778         ret = io_poll_cancel(ctx, sqe_addr);
5779         if (ret != -ENOENT)
5780                 goto done;
5781         spin_unlock_irq(&ctx->completion_lock);
5782 
5783         /* slow path, try all io-wq's */
5784         io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5785         ret = -ENOENT;
5786         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5787                 struct io_uring_task *tctx = node->task->io_uring;
5788 
5789                 if (!tctx || !tctx->io_wq)
5790                         continue;
5791                 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5792                 if (ret != -ENOENT)
5793                         break;
5794         }
5795         io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5796 
5797         spin_lock_irq(&ctx->completion_lock);
5798 done:
5799         io_cqring_fill_event(req, ret);