Merge tag 'io_uring-5.15-2021-09-11' of git://git.kernel.dk/linux-block
[linux-2.6-microblaze.git] / fs / io_uring.c
index fa8794c..16fb743 100644 (file)
@@ -11,7 +11,7 @@
  * before writing the tail (using smp_load_acquire to read the tail will
  * do). It also needs a smp_mb() before updating CQ head (ordering the
  * entry load(s) with the head store), pairing with an implicit barrier
- * through a control-dependency in io_get_cqring (smp_store_release to
+ * through a control-dependency in io_get_cqe (smp_store_release to
  * store head will do). Failure to do so could lead to reading invalid
  * CQ entries.
  *
@@ -78,6 +78,7 @@
 #include <linux/task_work.h>
 #include <linux/pagemap.h>
 #include <linux/io_uring.h>
+#include <linux/tracehook.h>
 
 #define CREATE_TRACE_POINTS
 #include <trace/events/io_uring.h>
 
 #define IORING_MAX_ENTRIES     32768
 #define IORING_MAX_CQ_ENTRIES  (2 * IORING_MAX_ENTRIES)
+#define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
 
-/*
- * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
- */
-#define IORING_FILE_TABLE_SHIFT        9
-#define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
-#define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
-#define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
+/* only define max */
+#define IORING_MAX_FIXED_FILES (1U << 15)
 #define IORING_MAX_RESTRICTIONS        (IORING_RESTRICTION_LAST + \
                                 IORING_REGISTER_LAST + IORING_OP_LAST)
 
+#define IO_RSRC_TAG_TABLE_SHIFT        (PAGE_SHIFT - 3)
+#define IO_RSRC_TAG_TABLE_MAX  (1U << IO_RSRC_TAG_TABLE_SHIFT)
+#define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
+
 #define IORING_MAX_REG_BUFFERS (1U << 14)
 
 #define SQE_VALID_FLAGS        (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
                                IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
                                IOSQE_BUFFER_SELECT)
+#define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
+                               REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS)
+
+#define IO_TCTX_REFS_CACHE_NR  (1U << 10)
 
 struct io_uring {
        u32 head ____cacheline_aligned_in_smp;
@@ -164,7 +169,7 @@ struct io_rings {
         * Written by the application, shouldn't be modified by the
         * kernel.
         */
-       u32                     cq_flags;
+       u32                     cq_flags;
        /*
         * Number of completion events lost because the queue was full;
         * this should be avoided by the application by making sure
@@ -225,8 +230,7 @@ struct io_rsrc_put {
 };
 
 struct io_file_table {
-       /* two level table */
-       struct io_fixed_file **files;
+       struct io_fixed_file *files;
 };
 
 struct io_rsrc_node {
@@ -243,7 +247,8 @@ typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
 struct io_rsrc_data {
        struct io_ring_ctx              *ctx;
 
-       u64                             *tags;
+       u64                             **tags;
+       unsigned int                    nr;
        rsrc_put_fn                     *do_put;
        atomic_t                        refs;
        struct completion               done;
@@ -288,24 +293,12 @@ struct io_sq_data {
 
        unsigned long           state;
        struct completion       exited;
-       struct callback_head    *park_task_work;
 };
 
-#define IO_IOPOLL_BATCH                        8
 #define IO_COMPL_BATCH                 32
 #define IO_REQ_CACHE_SIZE              32
 #define IO_REQ_ALLOC_BATCH             8
 
-struct io_comp_state {
-       struct io_kiocb         *reqs[IO_COMPL_BATCH];
-       unsigned int            nr;
-       unsigned int            locked_free_nr;
-       /* inline/task_work completion list, under ->uring_lock */
-       struct list_head        free_list;
-       /* IRQ completion list, under ->completion_lock */
-       struct list_head        locked_free_list;
-};
-
 struct io_submit_link {
        struct io_kiocb         *head;
        struct io_kiocb         *last;
@@ -326,28 +319,32 @@ struct io_submit_state {
        /*
         * Batch completion logic
         */
-       struct io_comp_state    comp;
+       struct io_kiocb         *compl_reqs[IO_COMPL_BATCH];
+       unsigned int            compl_nr;
+       /* inline/task_work completion list, under ->uring_lock */
+       struct list_head        free_list;
 
-       /*
-        * File reference cache
-        */
-       struct file             *file;
-       unsigned int            fd;
-       unsigned int            file_refs;
        unsigned int            ios_left;
 };
 
 struct io_ring_ctx {
+       /* const or read-mostly hot data */
        struct {
                struct percpu_ref       refs;
-       } ____cacheline_aligned_in_smp;
 
-       struct {
+               struct io_rings         *rings;
                unsigned int            flags;
                unsigned int            compat: 1;
                unsigned int            drain_next: 1;
                unsigned int            eventfd_async: 1;
                unsigned int            restricted: 1;
+               unsigned int            off_timeout_used: 1;
+               unsigned int            drain_active: 1;
+       } ____cacheline_aligned_in_smp;
+
+       /* submission data */
+       struct {
+               struct mutex            uring_lock;
 
                /*
                 * Ring buffer of indices into array of io_uring_sqe, which is
@@ -361,35 +358,34 @@ struct io_ring_ctx {
                 * array.
                 */
                u32                     *sq_array;
+               struct io_uring_sqe     *sq_sqes;
                unsigned                cached_sq_head;
                unsigned                sq_entries;
-               unsigned                sq_mask;
-               unsigned                sq_thread_idle;
-               unsigned                cached_sq_dropped;
-               unsigned                cached_cq_overflow;
-               unsigned long           sq_check_overflow;
+               struct list_head        defer_list;
 
-               /* hashed buffered write serialization */
-               struct io_wq_hash       *hash_map;
+               /*
+                * Fixed resources fast path, should be accessed only under
+                * uring_lock, and updated through io_uring_register(2)
+                */
+               struct io_rsrc_node     *rsrc_node;
+               struct io_file_table    file_table;
+               unsigned                nr_user_files;
+               unsigned                nr_user_bufs;
+               struct io_mapped_ubuf   **user_bufs;
 
-               struct list_head        defer_list;
+               struct io_submit_state  submit_state;
                struct list_head        timeout_list;
+               struct list_head        ltimeout_list;
                struct list_head        cq_overflow_list;
-
-               struct io_uring_sqe     *sq_sqes;
-       } ____cacheline_aligned_in_smp;
-
-       struct {
-               struct mutex            uring_lock;
-               wait_queue_head_t       wait;
+               struct xarray           io_buffers;
+               struct xarray           personalities;
+               u32                     pers_next;
+               unsigned                sq_thread_idle;
        } ____cacheline_aligned_in_smp;
 
-       struct io_submit_state          submit_state;
-
-       struct io_rings *rings;
-
-       /* Only used for accounting purposes */
-       struct mm_struct        *mm_account;
+       /* IRQ completion list, under ->completion_lock */
+       struct list_head        locked_free_list;
+       unsigned int            locked_free_nr;
 
        const struct cred       *sq_creds;      /* cred used for __io_sq_thread() */
        struct io_sq_data       *sq_data;       /* if using sq thread polling */
@@ -397,49 +393,25 @@ struct io_ring_ctx {
        struct wait_queue_head  sqo_sq_wait;
        struct list_head        sqd_list;
 
-       /*
-        * If used, fixed file set. Writers must ensure that ->refs is dead,
-        * readers must ensure that ->refs is alive as long as the file* is
-        * used. Only updated through io_uring_register(2).
-        */
-       struct io_rsrc_data     *file_data;
-       struct io_file_table    file_table;
-       unsigned                nr_user_files;
-
-       /* if used, fixed mapped user buffers */
-       struct io_rsrc_data     *buf_data;
-       unsigned                nr_user_bufs;
-       struct io_mapped_ubuf   **user_bufs;
-
-       struct user_struct      *user;
-
-       struct completion       ref_comp;
-
-#if defined(CONFIG_UNIX)
-       struct socket           *ring_sock;
-#endif
-
-       struct xarray           io_buffers;
-
-       struct xarray           personalities;
-       u32                     pers_next;
+       unsigned long           check_cq_overflow;
 
        struct {
                unsigned                cached_cq_tail;
                unsigned                cq_entries;
-               unsigned                cq_mask;
-               atomic_t                cq_timeouts;
-               unsigned                cq_last_tm_flush;
-               unsigned                cq_extra;
-               unsigned long           cq_check_overflow;
+               struct eventfd_ctx      *cq_ev_fd;
+               struct wait_queue_head  poll_wait;
                struct wait_queue_head  cq_wait;
+               unsigned                cq_extra;
+               atomic_t                cq_timeouts;
                struct fasync_struct    *cq_fasync;
-               struct eventfd_ctx      *cq_ev_fd;
+               unsigned                cq_last_tm_flush;
        } ____cacheline_aligned_in_smp;
 
        struct {
                spinlock_t              completion_lock;
 
+               spinlock_t              timeout_lock;
+
                /*
                 * ->iopoll_list is protected by the ctx->uring_lock for
                 * io_uring instances that don't use IORING_SETUP_SQPOLL.
@@ -449,29 +421,48 @@ struct io_ring_ctx {
                struct list_head        iopoll_list;
                struct hlist_head       *cancel_hash;
                unsigned                cancel_hash_bits;
-               bool                    poll_multi_file;
+               bool                    poll_multi_queue;
        } ____cacheline_aligned_in_smp;
 
-       struct delayed_work             rsrc_put_work;
-       struct llist_head               rsrc_put_llist;
-       struct list_head                rsrc_ref_list;
-       spinlock_t                      rsrc_ref_lock;
-       struct io_rsrc_node             *rsrc_node;
-       struct io_rsrc_node             *rsrc_backup_node;
-       struct io_mapped_ubuf           *dummy_ubuf;
-
        struct io_restriction           restrictions;
 
-       /* exit task_work */
-       struct callback_head            *exit_task_work;
+       /* slow path rsrc auxilary data, used by update/register */
+       struct {
+               struct io_rsrc_node             *rsrc_backup_node;
+               struct io_mapped_ubuf           *dummy_ubuf;
+               struct io_rsrc_data             *file_data;
+               struct io_rsrc_data             *buf_data;
+
+               struct delayed_work             rsrc_put_work;
+               struct llist_head               rsrc_put_llist;
+               struct list_head                rsrc_ref_list;
+               spinlock_t                      rsrc_ref_lock;
+       };
 
        /* Keep this last, we don't need it for the fast path */
-       struct work_struct              exit_work;
-       struct list_head                tctx_list;
+       struct {
+               #if defined(CONFIG_UNIX)
+                       struct socket           *ring_sock;
+               #endif
+               /* hashed buffered write serialization */
+               struct io_wq_hash               *hash_map;
+
+               /* Only used for accounting purposes */
+               struct user_struct              *user;
+               struct mm_struct                *mm_account;
+
+               /* ctx exit and cancelation */
+               struct llist_head               fallback_llist;
+               struct delayed_work             fallback_work;
+               struct work_struct              exit_work;
+               struct list_head                tctx_list;
+               struct completion               ref_comp;
+       };
 };
 
 struct io_uring_task {
        /* submission side */
+       int                     cached_refs;
        struct xarray           xa;
        struct wait_queue_head  wait;
        const struct io_ring_ctx *last;
@@ -482,8 +473,8 @@ struct io_uring_task {
 
        spinlock_t              task_lock;
        struct io_wq_work_list  task_list;
-       unsigned long           task_state;
        struct callback_head    task_work;
+       bool                    task_running;
 };
 
 /*
@@ -518,6 +509,7 @@ struct io_timeout_data {
        struct hrtimer                  timer;
        struct timespec64               ts;
        enum hrtimer_mode               mode;
+       u32                             flags;
 };
 
 struct io_accept {
@@ -525,6 +517,7 @@ struct io_accept {
        struct sockaddr __user          *addr;
        int __user                      *addr_len;
        int                             flags;
+       u32                             file_slot;
        unsigned long                   nofile;
 };
 
@@ -548,6 +541,8 @@ struct io_timeout {
        struct list_head                list;
        /* head of the link, used by linked timeouts only */
        struct io_kiocb                 *head;
+       /* for linked completions */
+       struct io_kiocb                 *prev;
 };
 
 struct io_timeout_rem {
@@ -557,6 +552,7 @@ struct io_timeout_rem {
        /* timeout update */
        struct timespec64               ts;
        u32                             flags;
+       bool                            ltimeout;
 };
 
 struct io_rw {
@@ -588,6 +584,7 @@ struct io_sr_msg {
 struct io_open {
        struct file                     *file;
        int                             dfd;
+       u32                             file_slot;
        struct filename                 *filename;
        struct open_how                 how;
        unsigned long                   nofile;
@@ -670,9 +667,31 @@ struct io_unlink {
        struct filename                 *filename;
 };
 
+struct io_mkdir {
+       struct file                     *file;
+       int                             dfd;
+       umode_t                         mode;
+       struct filename                 *filename;
+};
+
+struct io_symlink {
+       struct file                     *file;
+       int                             new_dfd;
+       struct filename                 *oldpath;
+       struct filename                 *newpath;
+};
+
+struct io_hardlink {
+       struct file                     *file;
+       int                             old_dfd;
+       int                             new_dfd;
+       struct filename                 *oldpath;
+       struct filename                 *newpath;
+       int                             flags;
+};
+
 struct io_completion {
        struct file                     *file;
-       struct list_head                list;
        u32                             cflags;
 };
 
@@ -706,7 +725,7 @@ enum {
        REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
 
        /* first byte is taken by user flags, shift it to not overlap */
-       REQ_F_FAIL_LINK_BIT     = 8,
+       REQ_F_FAIL_BIT          = 8,
        REQ_F_INFLIGHT_BIT,
        REQ_F_CUR_POS_BIT,
        REQ_F_NOWAIT_BIT,
@@ -714,13 +733,15 @@ enum {
        REQ_F_NEED_CLEANUP_BIT,
        REQ_F_POLLED_BIT,
        REQ_F_BUFFER_SELECTED_BIT,
-       REQ_F_LTIMEOUT_ACTIVE_BIT,
        REQ_F_COMPLETE_INLINE_BIT,
        REQ_F_REISSUE_BIT,
        REQ_F_DONT_REISSUE_BIT,
+       REQ_F_CREDS_BIT,
+       REQ_F_REFCOUNT_BIT,
+       REQ_F_ARM_LTIMEOUT_BIT,
        /* keep async read/write and isreg together and in order */
-       REQ_F_ASYNC_READ_BIT,
-       REQ_F_ASYNC_WRITE_BIT,
+       REQ_F_NOWAIT_READ_BIT,
+       REQ_F_NOWAIT_WRITE_BIT,
        REQ_F_ISREG_BIT,
 
        /* not a real bit, just to check we're not overflowing the space */
@@ -742,7 +763,7 @@ enum {
        REQ_F_BUFFER_SELECT     = BIT(REQ_F_BUFFER_SELECT_BIT),
 
        /* fail rest of links */
-       REQ_F_FAIL_LINK         = BIT(REQ_F_FAIL_LINK_BIT),
+       REQ_F_FAIL              = BIT(REQ_F_FAIL_BIT),
        /* on inflight list, should be cancelled and waited on exit reliably */
        REQ_F_INFLIGHT          = BIT(REQ_F_INFLIGHT_BIT),
        /* read/write uses file position */
@@ -757,8 +778,6 @@ enum {
        REQ_F_POLLED            = BIT(REQ_F_POLLED_BIT),
        /* buffer already selected */
        REQ_F_BUFFER_SELECTED   = BIT(REQ_F_BUFFER_SELECTED_BIT),
-       /* linked timeout is active, i.e. prepared by link's head */
-       REQ_F_LTIMEOUT_ACTIVE   = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
        /* completion is deferred through io_comp_state */
        REQ_F_COMPLETE_INLINE   = BIT(REQ_F_COMPLETE_INLINE_BIT),
        /* caller should reissue async */
@@ -766,11 +785,17 @@ enum {
        /* don't attempt request reissue, see io_rw_reissue() */
        REQ_F_DONT_REISSUE      = BIT(REQ_F_DONT_REISSUE_BIT),
        /* supports async reads */
-       REQ_F_ASYNC_READ        = BIT(REQ_F_ASYNC_READ_BIT),
+       REQ_F_NOWAIT_READ       = BIT(REQ_F_NOWAIT_READ_BIT),
        /* supports async writes */
-       REQ_F_ASYNC_WRITE       = BIT(REQ_F_ASYNC_WRITE_BIT),
+       REQ_F_NOWAIT_WRITE      = BIT(REQ_F_NOWAIT_WRITE_BIT),
        /* regular file */
        REQ_F_ISREG             = BIT(REQ_F_ISREG_BIT),
+       /* has creds assigned */
+       REQ_F_CREDS             = BIT(REQ_F_CREDS_BIT),
+       /* skip refcounting if not set */
+       REQ_F_REFCOUNT          = BIT(REQ_F_REFCOUNT_BIT),
+       /* there is a linked timeout that has to be armed */
+       REQ_F_ARM_LTIMEOUT      = BIT(REQ_F_ARM_LTIMEOUT_BIT),
 };
 
 struct async_poll {
@@ -778,9 +803,14 @@ struct async_poll {
        struct io_poll_iocb     *double_poll;
 };
 
+typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
+
 struct io_task_work {
-       struct io_wq_work_node  node;
-       task_work_func_t        func;
+       union {
+               struct io_wq_work_node  node;
+               struct llist_node       fallback_node;
+       };
+       io_req_tw_func_t                func;
 };
 
 enum {
@@ -819,6 +849,9 @@ struct io_kiocb {
                struct io_shutdown      shutdown;
                struct io_rename        rename;
                struct io_unlink        unlink;
+               struct io_mkdir         mkdir;
+               struct io_symlink       symlink;
+               struct io_hardlink      hardlink;
                /* use only after cleaning per-op data, see io_clean_op() */
                struct io_completion    compl;
        };
@@ -843,14 +876,13 @@ struct io_kiocb {
 
        /* used with ctx->iopoll_list with reads/writes */
        struct list_head                inflight_entry;
-       union {
-               struct io_task_work     io_task_work;
-               struct callback_head    task_work;
-       };
+       struct io_task_work             io_task_work;
        /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
        struct hlist_node               hash_node;
        struct async_poll               *apoll;
        struct io_wq_work               work;
+       const struct cred               *creds;
+
        /* store used ubuf, so we can prevent reloading */
        struct io_mapped_ubuf           *imu;
 };
@@ -989,6 +1021,7 @@ static const struct io_op_def io_op_defs[] = {
        },
        [IORING_OP_WRITE] = {
                .needs_file             = 1,
+               .hash_reg_file          = 1,
                .unbound_nonreg_file    = 1,
                .pollout                = 1,
                .plug                   = 1,
@@ -1031,39 +1064,44 @@ static const struct io_op_def io_op_defs[] = {
        },
        [IORING_OP_RENAMEAT] = {},
        [IORING_OP_UNLINKAT] = {},
+       [IORING_OP_MKDIRAT] = {},
+       [IORING_OP_SYMLINKAT] = {},
+       [IORING_OP_LINKAT] = {},
 };
 
+/* requests with any of those set should undergo io_disarm_next() */
+#define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
+
 static bool io_disarm_next(struct io_kiocb *req);
-static void io_uring_del_task_file(unsigned long index);
+static void io_uring_del_tctx_node(unsigned long index);
 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
                                         struct task_struct *task,
-                                        struct files_struct *files);
-static void io_uring_cancel_sqpoll(struct io_sq_data *sqd);
-static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
+                                        bool cancel_all);
+static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
 
 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
                                 long res, unsigned int cflags);
 static void io_put_req(struct io_kiocb *req);
-static void io_put_req_deferred(struct io_kiocb *req, int nr);
+static void io_put_req_deferred(struct io_kiocb *req);
 static void io_dismantle_req(struct io_kiocb *req);
-static void io_put_task(struct task_struct *task, int nr);
-static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
 static void io_queue_linked_timeout(struct io_kiocb *req);
 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
                                     struct io_uring_rsrc_update2 *up,
                                     unsigned nr_args);
 static void io_clean_op(struct io_kiocb *req);
-static struct file *io_file_get(struct io_submit_state *state,
+static struct file *io_file_get(struct io_ring_ctx *ctx,
                                struct io_kiocb *req, int fd, bool fixed);
 static void __io_queue_sqe(struct io_kiocb *req);
 static void io_rsrc_put_work(struct work_struct *work);
 
 static void io_req_task_queue(struct io_kiocb *req);
-static void io_submit_flush_completions(struct io_comp_state *cs,
-                                       struct io_ring_ctx *ctx);
-static bool io_poll_remove_waitqs(struct io_kiocb *req);
+static void io_submit_flush_completions(struct io_ring_ctx *ctx);
 static int io_req_prep_async(struct io_kiocb *req);
 
+static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
+                                unsigned int issue_flags, u32 slot_index);
+static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
+
 static struct kmem_cache *req_cachep;
 
 static const struct file_operations io_uring_fops;
@@ -1081,9 +1119,65 @@ struct sock *io_uring_get_socket(struct file *file)
 }
 EXPORT_SYMBOL(io_uring_get_socket);
 
+static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
+{
+       if (!*locked) {
+               mutex_lock(&ctx->uring_lock);
+               *locked = true;
+       }
+}
+
 #define io_for_each_link(pos, head) \
        for (pos = (head); pos; pos = pos->link)
 
+/*
+ * Shamelessly stolen from the mm implementation of page reference checking,
+ * see commit f958d7b528b1 for details.
+ */
+#define req_ref_zero_or_close_to_overflow(req) \
+       ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
+
+static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
+{
+       WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
+       return atomic_inc_not_zero(&req->refs);
+}
+
+static inline bool req_ref_put_and_test(struct io_kiocb *req)
+{
+       if (likely(!(req->flags & REQ_F_REFCOUNT)))
+               return true;
+
+       WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
+       return atomic_dec_and_test(&req->refs);
+}
+
+static inline void req_ref_put(struct io_kiocb *req)
+{
+       WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
+       WARN_ON_ONCE(req_ref_put_and_test(req));
+}
+
+static inline void req_ref_get(struct io_kiocb *req)
+{
+       WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
+       WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
+       atomic_inc(&req->refs);
+}
+
+static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
+{
+       if (!(req->flags & REQ_F_REFCOUNT)) {
+               req->flags |= REQ_F_REFCOUNT;
+               atomic_set(&req->refs, nr);
+       }
+}
+
+static inline void io_req_set_refcount(struct io_kiocb *req)
+{
+       __io_req_set_refcount(req, 1);
+}
+
 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
 {
        struct io_ring_ctx *ctx = req->ctx;
@@ -1106,15 +1200,14 @@ static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
                percpu_ref_put(ref);
 }
 
-static bool io_match_task(struct io_kiocb *head,
-                         struct task_struct *task,
-                         struct files_struct *files)
+static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
+                         bool cancel_all)
 {
        struct io_kiocb *req;
 
        if (task && head->task != task)
                return false;
-       if (!files)
+       if (cancel_all)
                return true;
 
        io_for_each_link(req, head) {
@@ -1124,10 +1217,15 @@ static bool io_match_task(struct io_kiocb *head,
        return false;
 }
 
-static inline void req_set_fail_links(struct io_kiocb *req)
+static inline void req_set_fail(struct io_kiocb *req)
+{
+       req->flags |= REQ_F_FAIL;
+}
+
+static inline void req_fail_link_node(struct io_kiocb *req, int res)
 {
-       if (req->flags & REQ_F_LINK)
-               req->flags |= REQ_F_FAIL_LINK;
+       req_set_fail(req);
+       req->result = res;
 }
 
 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
@@ -1142,6 +1240,27 @@ static inline bool io_is_timeout_noseq(struct io_kiocb *req)
        return !req->timeout.off;
 }
 
+static void io_fallback_req_func(struct work_struct *work)
+{
+       struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
+                                               fallback_work.work);
+       struct llist_node *node = llist_del_all(&ctx->fallback_llist);
+       struct io_kiocb *req, *tmp;
+       bool locked = false;
+
+       percpu_ref_get(&ctx->refs);
+       llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
+               req->io_task_work.func(req, &locked);
+
+       if (locked) {
+               if (ctx->submit_state.compl_nr)
+                       io_submit_flush_completions(ctx);
+               mutex_unlock(&ctx->uring_lock);
+       }
+       percpu_ref_put(&ctx->refs);
+
+}
+
 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
 {
        struct io_ring_ctx *ctx;
@@ -1179,24 +1298,27 @@ static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
        ctx->flags = p->flags;
        init_waitqueue_head(&ctx->sqo_sq_wait);
        INIT_LIST_HEAD(&ctx->sqd_list);
-       init_waitqueue_head(&ctx->cq_wait);
+       init_waitqueue_head(&ctx->poll_wait);
        INIT_LIST_HEAD(&ctx->cq_overflow_list);
        init_completion(&ctx->ref_comp);
        xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
        xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
        mutex_init(&ctx->uring_lock);
-       init_waitqueue_head(&ctx->wait);
+       init_waitqueue_head(&ctx->cq_wait);
        spin_lock_init(&ctx->completion_lock);
+       spin_lock_init(&ctx->timeout_lock);
        INIT_LIST_HEAD(&ctx->iopoll_list);
        INIT_LIST_HEAD(&ctx->defer_list);
        INIT_LIST_HEAD(&ctx->timeout_list);
+       INIT_LIST_HEAD(&ctx->ltimeout_list);
        spin_lock_init(&ctx->rsrc_ref_lock);
        INIT_LIST_HEAD(&ctx->rsrc_ref_list);
        INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
        init_llist_head(&ctx->rsrc_put_llist);
        INIT_LIST_HEAD(&ctx->tctx_list);
-       INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
-       INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
+       INIT_LIST_HEAD(&ctx->submit_state.free_list);
+       INIT_LIST_HEAD(&ctx->locked_free_list);
+       INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
        return ctx;
 err:
        kfree(ctx->dummy_ubuf);
@@ -1205,18 +1327,39 @@ err:
        return NULL;
 }
 
+static void io_account_cq_overflow(struct io_ring_ctx *ctx)
+{
+       struct io_rings *r = ctx->rings;
+
+       WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
+       ctx->cq_extra--;
+}
+
 static bool req_need_defer(struct io_kiocb *req, u32 seq)
 {
        if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
                struct io_ring_ctx *ctx = req->ctx;
 
-               return seq + ctx->cq_extra != ctx->cached_cq_tail
-                               + READ_ONCE(ctx->cached_cq_overflow);
+               return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
        }
 
        return false;
 }
 
+#define FFS_ASYNC_READ         0x1UL
+#define FFS_ASYNC_WRITE                0x2UL
+#ifdef CONFIG_64BIT
+#define FFS_ISREG              0x4UL
+#else
+#define FFS_ISREG              0x0UL
+#endif
+#define FFS_MASK               ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
+
+static inline bool io_req_ffs_set(struct io_kiocb *req)
+{
+       return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
+}
+
 static void io_req_track_inflight(struct io_kiocb *req)
 {
        if (!(req->flags & REQ_F_INFLIGHT)) {
@@ -1225,13 +1368,41 @@ static void io_req_track_inflight(struct io_kiocb *req)
        }
 }
 
+static inline void io_unprep_linked_timeout(struct io_kiocb *req)
+{
+       req->flags &= ~REQ_F_LINK_TIMEOUT;
+}
+
+static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
+{
+       if (WARN_ON_ONCE(!req->link))
+               return NULL;
+
+       req->flags &= ~REQ_F_ARM_LTIMEOUT;
+       req->flags |= REQ_F_LINK_TIMEOUT;
+
+       /* linked timeouts should have two refs once prep'ed */
+       io_req_set_refcount(req);
+       __io_req_set_refcount(req->link, 2);
+       return req->link;
+}
+
+static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
+{
+       if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
+               return NULL;
+       return __io_prep_linked_timeout(req);
+}
+
 static void io_prep_async_work(struct io_kiocb *req)
 {
        const struct io_op_def *def = &io_op_defs[req->opcode];
        struct io_ring_ctx *ctx = req->ctx;
 
-       if (!req->work.creds)
-               req->work.creds = get_current_cred();
+       if (!(req->flags & REQ_F_CREDS)) {
+               req->flags |= REQ_F_CREDS;
+               req->creds = get_current_cred();
+       }
 
        req->work.list.next = NULL;
        req->work.flags = 0;
@@ -1259,21 +1430,44 @@ static void io_prep_async_link(struct io_kiocb *req)
 {
        struct io_kiocb *cur;
 
-       io_for_each_link(cur, req)
-               io_prep_async_work(cur);
+       if (req->flags & REQ_F_LINK_TIMEOUT) {
+               struct io_ring_ctx *ctx = req->ctx;
+
+               spin_lock(&ctx->completion_lock);
+               io_for_each_link(cur, req)
+                       io_prep_async_work(cur);
+               spin_unlock(&ctx->completion_lock);
+       } else {
+               io_for_each_link(cur, req)
+                       io_prep_async_work(cur);
+       }
 }
 
-static void io_queue_async_work(struct io_kiocb *req)
+static void io_queue_async_work(struct io_kiocb *req, bool *locked)
 {
        struct io_ring_ctx *ctx = req->ctx;
        struct io_kiocb *link = io_prep_linked_timeout(req);
        struct io_uring_task *tctx = req->task->io_uring;
 
+       /* must not take the lock, NULL it as a precaution */
+       locked = NULL;
+
        BUG_ON(!tctx);
        BUG_ON(!tctx->io_wq);
 
        /* init ->work of the whole link before punting */
        io_prep_async_link(req);
+
+       /*
+        * Not expected to happen, but if we do have a bug where this _can_
+        * happen, catch it here and ensure the request is marked as
+        * canceled. That will make io-wq go through the usual work cancel
+        * procedure rather than attempt to run this request (or create a new
+        * worker for it).
+        */
+       if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
+               req->work.flags |= IO_WQ_WORK_CANCEL;
+
        trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
                                        &req->work, req->flags);
        io_wq_enqueue(tctx->io_wq, &req->work);
@@ -1283,21 +1477,24 @@ static void io_queue_async_work(struct io_kiocb *req)
 
 static void io_kill_timeout(struct io_kiocb *req, int status)
        __must_hold(&req->ctx->completion_lock)
+       __must_hold(&req->ctx->timeout_lock)
 {
        struct io_timeout_data *io = req->async_data;
 
        if (hrtimer_try_to_cancel(&io->timer) != -1) {
+               if (status)
+                       req_set_fail(req);
                atomic_set(&req->ctx->cq_timeouts,
                        atomic_read(&req->ctx->cq_timeouts) + 1);
                list_del_init(&req->timeout.list);
                io_cqring_fill_event(req->ctx, req->user_data, status, 0);
-               io_put_req_deferred(req, 1);
+               io_put_req_deferred(req);
        }
 }
 
-static void __io_queue_deferred(struct io_ring_ctx *ctx)
+static void io_queue_deferred(struct io_ring_ctx *ctx)
 {
-       do {
+       while (!list_empty(&ctx->defer_list)) {
                struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
                                                struct io_defer_entry, list);
 
@@ -1306,19 +1503,16 @@ static void __io_queue_deferred(struct io_ring_ctx *ctx)
                list_del_init(&de->list);
                io_req_task_queue(de->req);
                kfree(de);
-       } while (!list_empty(&ctx->defer_list));
+       }
 }
 
 static void io_flush_timeouts(struct io_ring_ctx *ctx)
+       __must_hold(&ctx->completion_lock)
 {
-       u32 seq;
-
-       if (list_empty(&ctx->timeout_list))
-               return;
-
-       seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
+       u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
 
-       do {
+       spin_lock_irq(&ctx->timeout_lock);
+       while (!list_empty(&ctx->timeout_list)) {
                u32 events_needed, events_got;
                struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
                                                struct io_kiocb, timeout.list);
@@ -1340,27 +1534,32 @@ static void io_flush_timeouts(struct io_ring_ctx *ctx)
 
                list_del_init(&req->timeout.list);
                io_kill_timeout(req, 0);
-       } while (!list_empty(&ctx->timeout_list));
-
+       }
        ctx->cq_last_tm_flush = seq;
+       spin_unlock_irq(&ctx->timeout_lock);
 }
 
-static void io_commit_cqring(struct io_ring_ctx *ctx)
+static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
 {
-       io_flush_timeouts(ctx);
+       if (ctx->off_timeout_used)
+               io_flush_timeouts(ctx);
+       if (ctx->drain_active)
+               io_queue_deferred(ctx);
+}
 
+static inline void io_commit_cqring(struct io_ring_ctx *ctx)
+{
+       if (unlikely(ctx->off_timeout_used || ctx->drain_active))
+               __io_commit_cqring_flush(ctx);
        /* order cqe stores with ring update */
        smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
-
-       if (unlikely(!list_empty(&ctx->defer_list)))
-               __io_queue_deferred(ctx);
 }
 
 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
 {
        struct io_rings *r = ctx->rings;
 
-       return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
+       return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
 }
 
 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
@@ -1368,21 +1567,21 @@ static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
        return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
 }
 
-static inline struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
+static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
 {
        struct io_rings *rings = ctx->rings;
-       unsigned tail;
+       unsigned tail, mask = ctx->cq_entries - 1;
 
        /*
         * writes to the cq entry need to come after reading head; the
         * control dependency is enough as we're using WRITE_ONCE to
         * fill the cq entry
         */
-       if (__io_cqring_events(ctx) == rings->cq_ring_entries)
+       if (__io_cqring_events(ctx) == ctx->cq_entries)
                return NULL;
 
        tail = ctx->cached_cq_tail++;
-       return &rings->cqes[tail & ctx->cq_mask];
+       return &rings->cqes[tail & mask];
 }
 
 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
@@ -1394,19 +1593,28 @@ static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
        return !ctx->eventfd_async || io_wq_current_is_worker();
 }
 
+/*
+ * This should only get called when at least one event has been posted.
+ * Some applications rely on the eventfd notification count only changing
+ * IFF a new CQE has been added to the CQ ring. There's no depedency on
+ * 1:1 relationship between how many times this function is called (and
+ * hence the eventfd count) and number of CQEs posted to the CQ ring.
+ */
 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
 {
-       /* see waitqueue_active() comment */
-       smp_mb();
-
-       if (waitqueue_active(&ctx->wait))
-               wake_up(&ctx->wait);
+       /*
+        * wake_up_all() may seem excessive, but io_wake_function() and
+        * io_should_wake() handle the termination of the loop and only
+        * wake as many waiters as we need to.
+        */
+       if (wq_has_sleeper(&ctx->cq_wait))
+               wake_up_all(&ctx->cq_wait);
        if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
                wake_up(&ctx->sq_data->wait);
        if (io_should_trigger_evfd(ctx))
                eventfd_signal(ctx->cq_ev_fd, 1);
-       if (waitqueue_active(&ctx->cq_wait)) {
-               wake_up_interruptible(&ctx->cq_wait);
+       if (waitqueue_active(&ctx->poll_wait)) {
+               wake_up_interruptible(&ctx->poll_wait);
                kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
        }
 }
@@ -1417,13 +1625,13 @@ static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
        smp_mb();
 
        if (ctx->flags & IORING_SETUP_SQPOLL) {
-               if (waitqueue_active(&ctx->wait))
-                       wake_up(&ctx->wait);
+               if (waitqueue_active(&ctx->cq_wait))
+                       wake_up_all(&ctx->cq_wait);
        }
        if (io_should_trigger_evfd(ctx))
                eventfd_signal(ctx->cq_ev_fd, 1);
-       if (waitqueue_active(&ctx->cq_wait)) {
-               wake_up_interruptible(&ctx->cq_wait);
+       if (waitqueue_active(&ctx->poll_wait)) {
+               wake_up_interruptible(&ctx->poll_wait);
                kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
        }
 }
@@ -1431,17 +1639,15 @@ static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
 /* Returns true if there are no backlogged entries after the flush */
 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
 {
-       struct io_rings *rings = ctx->rings;
-       unsigned long flags;
        bool all_flushed, posted;
 
-       if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
+       if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
                return false;
 
        posted = false;
-       spin_lock_irqsave(&ctx->completion_lock, flags);
+       spin_lock(&ctx->completion_lock);
        while (!list_empty(&ctx->cq_overflow_list)) {
-               struct io_uring_cqe *cqe = io_get_cqring(ctx);
+               struct io_uring_cqe *cqe = io_get_cqe(ctx);
                struct io_overflow_cqe *ocqe;
 
                if (!cqe && !force)
@@ -1451,8 +1657,8 @@ static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
                if (cqe)
                        memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
                else
-                       WRITE_ONCE(ctx->rings->cq_overflow,
-                                  ++ctx->cached_cq_overflow);
+                       io_account_cq_overflow(ctx);
+
                posted = true;
                list_del(&ocqe->list);
                kfree(ocqe);
@@ -1460,28 +1666,28 @@ static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
 
        all_flushed = list_empty(&ctx->cq_overflow_list);
        if (all_flushed) {
-               clear_bit(0, &ctx->sq_check_overflow);
-               clear_bit(0, &ctx->cq_check_overflow);
-               ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
+               clear_bit(0, &ctx->check_cq_overflow);
+               WRITE_ONCE(ctx->rings->sq_flags,
+                          ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
        }
 
        if (posted)
                io_commit_cqring(ctx);
-       spin_unlock_irqrestore(&ctx->completion_lock, flags);
+       spin_unlock(&ctx->completion_lock);
        if (posted)
                io_cqring_ev_posted(ctx);
        return all_flushed;
 }
 
-static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
+static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
 {
        bool ret = true;
 
-       if (test_bit(0, &ctx->cq_check_overflow)) {
+       if (test_bit(0, &ctx->check_cq_overflow)) {
                /* iopoll syncs against uring_lock, not completion_lock */
                if (ctx->flags & IORING_SETUP_IOPOLL)
                        mutex_lock(&ctx->uring_lock);
-               ret = __io_cqring_overflow_flush(ctx, force);
+               ret = __io_cqring_overflow_flush(ctx, false);
                if (ctx->flags & IORING_SETUP_IOPOLL)
                        mutex_unlock(&ctx->uring_lock);
        }
@@ -1489,39 +1695,37 @@ static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
        return ret;
 }
 
-/*
- * Shamelessly stolen from the mm implementation of page reference checking,
- * see commit f958d7b528b1 for details.
- */
-#define req_ref_zero_or_close_to_overflow(req) \
-       ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
-
-static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
+/* must to be called somewhat shortly after putting a request */
+static inline void io_put_task(struct task_struct *task, int nr)
 {
-       return atomic_inc_not_zero(&req->refs);
-}
+       struct io_uring_task *tctx = task->io_uring;
 
-static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
-{
-       WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
-       return atomic_sub_and_test(refs, &req->refs);
+       if (likely(task == current)) {
+               tctx->cached_refs += nr;
+       } else {
+               percpu_counter_sub(&tctx->inflight, nr);
+               if (unlikely(atomic_read(&tctx->in_idle)))
+                       wake_up(&tctx->wait);
+               put_task_struct_many(task, nr);
+       }
 }
 
-static inline bool req_ref_put_and_test(struct io_kiocb *req)
+static void io_task_refs_refill(struct io_uring_task *tctx)
 {
-       WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
-       return atomic_dec_and_test(&req->refs);
-}
+       unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
 
-static inline void req_ref_put(struct io_kiocb *req)
-{
-       WARN_ON_ONCE(req_ref_put_and_test(req));
+       percpu_counter_add(&tctx->inflight, refill);
+       refcount_add(refill, &current->usage);
+       tctx->cached_refs += refill;
 }
 
-static inline void req_ref_get(struct io_kiocb *req)
+static inline void io_get_task_refs(int nr)
 {
-       WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
-       atomic_inc(&req->refs);
+       struct io_uring_task *tctx = current->io_uring;
+
+       tctx->cached_refs -= nr;
+       if (unlikely(tctx->cached_refs < 0))
+               io_task_refs_refill(tctx);
 }
 
 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
@@ -1536,13 +1740,14 @@ static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
                 * or cannot allocate an overflow entry, then we need to drop it
                 * on the floor.
                 */
-               WRITE_ONCE(ctx->rings->cq_overflow, ++ctx->cached_cq_overflow);
+               io_account_cq_overflow(ctx);
                return false;
        }
        if (list_empty(&ctx->cq_overflow_list)) {
-               set_bit(0, &ctx->sq_check_overflow);
-               set_bit(0, &ctx->cq_check_overflow);
-               ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
+               set_bit(0, &ctx->check_cq_overflow);
+               WRITE_ONCE(ctx->rings->sq_flags,
+                          ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
+
        }
        ocqe->cqe.user_data = user_data;
        ocqe->cqe.res = res;
@@ -1563,7 +1768,7 @@ static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data
         * submission (by quite a lot). Increment the overflow count in
         * the ring.
         */
-       cqe = io_get_cqring(ctx);
+       cqe = io_get_cqe(ctx);
        if (likely(cqe)) {
                WRITE_ONCE(cqe->user_data, user_data);
                WRITE_ONCE(cqe->res, res);
@@ -1584,19 +1789,16 @@ static void io_req_complete_post(struct io_kiocb *req, long res,
                                 unsigned int cflags)
 {
        struct io_ring_ctx *ctx = req->ctx;
-       unsigned long flags;
 
-       spin_lock_irqsave(&ctx->completion_lock, flags);
+       spin_lock(&ctx->completion_lock);
        __io_cqring_fill_event(ctx, req->user_data, res, cflags);
        /*
         * If we're the last reference to this request, add to our locked
         * free_list cache.
         */
        if (req_ref_put_and_test(req)) {
-               struct io_comp_state *cs = &ctx->submit_state.comp;
-
                if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
-                       if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
+                       if (req->flags & IO_DISARM_MASK)
                                io_disarm_next(req);
                        if (req->link) {
                                io_req_task_queue(req->link);
@@ -1605,14 +1807,14 @@ static void io_req_complete_post(struct io_kiocb *req, long res,
                }
                io_dismantle_req(req);
                io_put_task(req->task, 1);
-               list_add(&req->compl.list, &cs->locked_free_list);
-               cs->locked_free_nr++;
+               list_add(&req->inflight_entry, &ctx->locked_free_list);
+               ctx->locked_free_nr++;
        } else {
                if (!percpu_ref_tryget(&ctx->refs))
                        req = NULL;
        }
        io_commit_cqring(ctx);
-       spin_unlock_irqrestore(&ctx->completion_lock, flags);
+       spin_unlock(&ctx->completion_lock);
 
        if (req) {
                io_cqring_ev_posted(ctx);
@@ -1622,8 +1824,7 @@ static void io_req_complete_post(struct io_kiocb *req, long res,
 
 static inline bool io_req_needs_clean(struct io_kiocb *req)
 {
-       return req->flags & (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP |
-                               REQ_F_POLLED | REQ_F_INFLIGHT);
+       return req->flags & IO_REQ_CLEAN_FLAGS;
 }
 
 static void io_req_complete_state(struct io_kiocb *req, long res,
@@ -1652,25 +1853,47 @@ static inline void io_req_complete(struct io_kiocb *req, long res)
 
 static void io_req_complete_failed(struct io_kiocb *req, long res)
 {
-       req_set_fail_links(req);
-       io_put_req(req);
+       req_set_fail(req);
        io_req_complete_post(req, res, 0);
 }
 
-static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
-                                       struct io_comp_state *cs)
+static void io_req_complete_fail_submit(struct io_kiocb *req)
 {
-       spin_lock_irq(&ctx->completion_lock);
-       list_splice_init(&cs->locked_free_list, &cs->free_list);
-       cs->locked_free_nr = 0;
-       spin_unlock_irq(&ctx->completion_lock);
+       /*
+        * We don't submit, fail them all, for that replace hardlinks with
+        * normal links. Extra REQ_F_LINK is tolerated.
+        */
+       req->flags &= ~REQ_F_HARDLINK;
+       req->flags |= REQ_F_LINK;
+       io_req_complete_failed(req, req->result);
 }
 
-/* Returns true IFF there are requests in the cache */
+/*
+ * Don't initialise the fields below on every allocation, but do that in
+ * advance and keep them valid across allocations.
+ */
+static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
+{
+       req->ctx = ctx;
+       req->link = NULL;
+       req->async_data = NULL;
+       /* not necessary, but safer to zero */
+       req->result = 0;
+}
+
+static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
+                                       struct io_submit_state *state)
+{
+       spin_lock(&ctx->completion_lock);
+       list_splice_init(&ctx->locked_free_list, &state->free_list);
+       ctx->locked_free_nr = 0;
+       spin_unlock(&ctx->completion_lock);
+}
+
+/* Returns true IFF there are requests in the cache */
 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
 {
        struct io_submit_state *state = &ctx->submit_state;
-       struct io_comp_state *cs = &state->comp;
        int nr;
 
        /*
@@ -1678,15 +1901,15 @@ static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
         * locked cache, grab the lock and move them over to our submission
         * side cache.
         */
-       if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH)
-               io_flush_cached_locked_reqs(ctx, cs);
+       if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
+               io_flush_cached_locked_reqs(ctx, state);
 
        nr = state->free_reqs;
-       while (!list_empty(&cs->free_list)) {
-               struct io_kiocb *req = list_first_entry(&cs->free_list,
-                                               struct io_kiocb, compl.list);
+       while (!list_empty(&state->free_list)) {
+               struct io_kiocb *req = list_first_entry(&state->free_list,
+                                       struct io_kiocb, inflight_entry);
 
-               list_del(&req->compl.list);
+               list_del(&req->inflight_entry);
                state->reqs[nr++] = req;
                if (nr == ARRAY_SIZE(state->reqs))
                        break;
@@ -1696,34 +1919,41 @@ static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
        return nr != 0;
 }
 
+/*
+ * A request might get retired back into the request caches even before opcode
+ * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
+ * Because of that, io_alloc_req() should be called only under ->uring_lock
+ * and with extra caution to not get a request that is still worked on.
+ */
 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
+       __must_hold(&ctx->uring_lock)
 {
        struct io_submit_state *state = &ctx->submit_state;
+       gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
+       int ret, i;
 
-       BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
-
-       if (!state->free_reqs) {
-               gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
-               int ret;
+       BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
 
-               if (io_flush_cached_reqs(ctx))
-                       goto got_req;
+       if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
+               goto got_req;
 
-               ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
-                                           state->reqs);
+       ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
+                                   state->reqs);
 
-               /*
-                * Bulk alloc is all-or-nothing. If we fail to get a batch,
-                * retry single alloc to be on the safe side.
-                */
-               if (unlikely(ret <= 0)) {
-                       state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
-                       if (!state->reqs[0])
-                               return NULL;
-                       ret = 1;
-               }
-               state->free_reqs = ret;
+       /*
+        * Bulk alloc is all-or-nothing. If we fail to get a batch,
+        * retry single alloc to be on the safe side.
+        */
+       if (unlikely(ret <= 0)) {
+               state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
+               if (!state->reqs[0])
+                       return NULL;
+               ret = 1;
        }
+
+       for (i = 0; i < ret; i++)
+               io_preinit_req(state->reqs[i], ctx);
+       state->free_reqs = ret;
 got_req:
        state->free_reqs--;
        return state->reqs[state->free_reqs];
@@ -1745,25 +1975,12 @@ static void io_dismantle_req(struct io_kiocb *req)
                io_put_file(req->file);
        if (req->fixed_rsrc_refs)
                percpu_ref_put(req->fixed_rsrc_refs);
-       if (req->async_data)
+       if (req->async_data) {
                kfree(req->async_data);
-       if (req->work.creds) {
-               put_cred(req->work.creds);
-               req->work.creds = NULL;
+               req->async_data = NULL;
        }
 }
 
-/* must to be called somewhat shortly after putting a request */
-static inline void io_put_task(struct task_struct *task, int nr)
-{
-       struct io_uring_task *tctx = task->io_uring;
-
-       percpu_counter_sub(&tctx->inflight, nr);
-       if (unlikely(atomic_read(&tctx->in_idle)))
-               wake_up(&tctx->wait);
-       put_task_struct_many(task, nr);
-}
-
 static void __io_free_req(struct io_kiocb *req)
 {
        struct io_ring_ctx *ctx = req->ctx;
@@ -1771,7 +1988,11 @@ static void __io_free_req(struct io_kiocb *req)
        io_dismantle_req(req);
        io_put_task(req->task, 1);
 
-       kmem_cache_free(req_cachep, req);
+       spin_lock(&ctx->completion_lock);
+       list_add(&req->inflight_entry, &ctx->locked_free_list);
+       ctx->locked_free_nr++;
+       spin_unlock(&ctx->completion_lock);
+
        percpu_ref_put(&ctx->refs);
 }
 
@@ -1785,22 +2006,20 @@ static inline void io_remove_next_linked(struct io_kiocb *req)
 
 static bool io_kill_linked_timeout(struct io_kiocb *req)
        __must_hold(&req->ctx->completion_lock)
+       __must_hold(&req->ctx->timeout_lock)
 {
        struct io_kiocb *link = req->link;
 
-       /*
-        * Can happen if a linked timeout fired and link had been like
-        * req -> link t-out -> link t-out [-> ...]
-        */
-       if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
+       if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
                struct io_timeout_data *io = link->async_data;
 
                io_remove_next_linked(req);
                link->timeout.head = NULL;
                if (hrtimer_try_to_cancel(&io->timer) != -1) {
+                       list_del(&link->timeout.list);
                        io_cqring_fill_event(link->ctx, link->user_data,
                                             -ECANCELED, 0);
-                       io_put_req_deferred(link, 1);
+                       io_put_req_deferred(link);
                        return true;
                }
        }
@@ -1814,12 +2033,17 @@ static void io_fail_links(struct io_kiocb *req)
 
        req->link = NULL;
        while (link) {
+               long res = -ECANCELED;
+
+               if (link->flags & REQ_F_FAIL)
+                       res = link->result;
+
                nxt = link->link;
                link->link = NULL;
 
                trace_io_uring_fail_link(req, link);
-               io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
-               io_put_req_deferred(link, 2);
+               io_cqring_fill_event(link->ctx, link->user_data, res, 0);
+               io_put_req_deferred(link);
                link = nxt;
        }
 }
@@ -1829,9 +2053,25 @@ static bool io_disarm_next(struct io_kiocb *req)
 {
        bool posted = false;
 
-       if (likely(req->flags & REQ_F_LINK_TIMEOUT))
+       if (req->flags & REQ_F_ARM_LTIMEOUT) {
+               struct io_kiocb *link = req->link;
+
+               req->flags &= ~REQ_F_ARM_LTIMEOUT;
+               if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
+                       io_remove_next_linked(req);
+                       io_cqring_fill_event(link->ctx, link->user_data,
+                                            -ECANCELED, 0);
+                       io_put_req_deferred(link);
+                       posted = true;
+               }
+       } else if (req->flags & REQ_F_LINK_TIMEOUT) {
+               struct io_ring_ctx *ctx = req->ctx;
+
+               spin_lock_irq(&ctx->timeout_lock);
                posted = io_kill_linked_timeout(req);
-       if (unlikely((req->flags & REQ_F_FAIL_LINK) &&
+               spin_unlock_irq(&ctx->timeout_lock);
+       }
+       if (unlikely((req->flags & REQ_F_FAIL) &&
                     !(req->flags & REQ_F_HARDLINK))) {
                posted |= (req->link != NULL);
                io_fail_links(req);
@@ -1849,16 +2089,15 @@ static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
         * dependencies to the next request. In case of failure, fail the rest
         * of the chain.
         */
-       if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK)) {
+       if (req->flags & IO_DISARM_MASK) {
                struct io_ring_ctx *ctx = req->ctx;
-               unsigned long flags;
                bool posted;
 
-               spin_lock_irqsave(&ctx->completion_lock, flags);
+               spin_lock(&ctx->completion_lock);
                posted = io_disarm_next(req);
                if (posted)
                        io_commit_cqring(req->ctx);
-               spin_unlock_irqrestore(&ctx->completion_lock, flags);
+               spin_unlock(&ctx->completion_lock);
                if (posted)
                        io_cqring_ev_posted(ctx);
        }
@@ -1874,84 +2113,84 @@ static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
        return __io_req_find_next(req);
 }
 
-static void ctx_flush_and_put(struct io_ring_ctx *ctx)
+static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
 {
        if (!ctx)
                return;
-       if (ctx->submit_state.comp.nr) {
-               mutex_lock(&ctx->uring_lock);
-               io_submit_flush_completions(&ctx->submit_state.comp, ctx);
+       if (*locked) {
+               if (ctx->submit_state.compl_nr)
+                       io_submit_flush_completions(ctx);
                mutex_unlock(&ctx->uring_lock);
+               *locked = false;
        }
        percpu_ref_put(&ctx->refs);
 }
 
-static bool __tctx_task_work(struct io_uring_task *tctx)
+static void tctx_task_work(struct callback_head *cb)
 {
+       bool locked = false;
        struct io_ring_ctx *ctx = NULL;
-       struct io_wq_work_list list;
-       struct io_wq_work_node *node;
+       struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
+                                                 task_work);
 
-       if (wq_list_empty(&tctx->task_list))
-               return false;
+       while (1) {
+               struct io_wq_work_node *node;
 
-       spin_lock_irq(&tctx->task_lock);
-       list = tctx->task_list;
-       INIT_WQ_LIST(&tctx->task_list);
-       spin_unlock_irq(&tctx->task_lock);
+               if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
+                       io_submit_flush_completions(ctx);
 
-       node = list.first;
-       while (node) {
-               struct io_wq_work_node *next = node->next;
-               struct io_kiocb *req;
+               spin_lock_irq(&tctx->task_lock);
+               node = tctx->task_list.first;
+               INIT_WQ_LIST(&tctx->task_list);
+               if (!node)
+                       tctx->task_running = false;
+               spin_unlock_irq(&tctx->task_lock);
+               if (!node)
+                       break;
 
-               req = container_of(node, struct io_kiocb, io_task_work.node);
-               if (req->ctx != ctx) {
-                       ctx_flush_and_put(ctx);
-                       ctx = req->ctx;
-                       percpu_ref_get(&ctx->refs);
-               }
+               do {
+                       struct io_wq_work_node *next = node->next;
+                       struct io_kiocb *req = container_of(node, struct io_kiocb,
+                                                           io_task_work.node);
+
+                       if (req->ctx != ctx) {
+                               ctx_flush_and_put(ctx, &locked);
+                               ctx = req->ctx;
+                               /* if not contended, grab and improve batching */
+                               locked = mutex_trylock(&ctx->uring_lock);
+                               percpu_ref_get(&ctx->refs);
+                       }
+                       req->io_task_work.func(req, &locked);
+                       node = next;
+               } while (node);
 
-               req->task_work.func(&req->task_work);
-               node = next;
+               cond_resched();
        }
 
-       ctx_flush_and_put(ctx);
-       return list.first != NULL;
-}
-
-static void tctx_task_work(struct callback_head *cb)
-{
-       struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
-
-       clear_bit(0, &tctx->task_state);
-
-       while (__tctx_task_work(tctx))
-               cond_resched();
+       ctx_flush_and_put(ctx, &locked);
 }
 
-static int io_req_task_work_add(struct io_kiocb *req)
+static void io_req_task_work_add(struct io_kiocb *req)
 {
        struct task_struct *tsk = req->task;
        struct io_uring_task *tctx = tsk->io_uring;
        enum task_work_notify_mode notify;
-       struct io_wq_work_node *node, *prev;
+       struct io_wq_work_node *node;
        unsigned long flags;
-       int ret = 0;
-
-       if (unlikely(tsk->flags & PF_EXITING))
-               return -ESRCH;
+       bool running;
 
        WARN_ON_ONCE(!tctx);
 
        spin_lock_irqsave(&tctx->task_lock, flags);
        wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
+       running = tctx->task_running;
+       if (!running)
+               tctx->task_running = true;
        spin_unlock_irqrestore(&tctx->task_lock, flags);
 
        /* task_work already pending, we're done */
-       if (test_bit(0, &tctx->task_state) ||
-           test_and_set_bit(0, &tctx->task_state))
-               return 0;
+       if (running)
+               return;
 
        /*
         * SQPOLL kernel thread doesn't need notification, just a wakeup. For
@@ -1960,115 +2199,64 @@ static int io_req_task_work_add(struct io_kiocb *req)
         * will do the job.
         */
        notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
-
        if (!task_work_add(tsk, &tctx->task_work, notify)) {
                wake_up_process(tsk);
-               return 0;
+               return;
        }
 
-       /*
-        * Slow path - we failed, find and delete work. if the work is not
-        * in the list, it got run and we're fine.
-        */
        spin_lock_irqsave(&tctx->task_lock, flags);
-       wq_list_for_each(node, prev, &tctx->task_list) {
-               if (&req->io_task_work.node == node) {
-                       wq_list_del(&tctx->task_list, node, prev);
-                       ret = 1;
-                       break;
-               }
-       }
+       tctx->task_running = false;
+       node = tctx->task_list.first;
+       INIT_WQ_LIST(&tctx->task_list);
        spin_unlock_irqrestore(&tctx->task_lock, flags);
-       clear_bit(0, &tctx->task_state);
-       return ret;
-}
-
-static bool io_run_task_work_head(struct callback_head **work_head)
-{
-       struct callback_head *work, *next;
-       bool executed = false;
-
-       do {
-               work = xchg(work_head, NULL);
-               if (!work)
-                       break;
-
-               do {
-                       next = work->next;
-                       work->func(work);
-                       work = next;
-                       cond_resched();
-               } while (work);
-               executed = true;
-       } while (1);
-
-       return executed;
-}
-
-static void io_task_work_add_head(struct callback_head **work_head,
-                                 struct callback_head *task_work)
-{
-       struct callback_head *head;
-
-       do {
-               head = READ_ONCE(*work_head);
-               task_work->next = head;
-       } while (cmpxchg(work_head, head, task_work) != head);
-}
 
-static void io_req_task_work_add_fallback(struct io_kiocb *req,
-                                         task_work_func_t cb)
-{
-       init_task_work(&req->task_work, cb);
-       io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
+       while (node) {
+               req = container_of(node, struct io_kiocb, io_task_work.node);
+               node = node->next;
+               if (llist_add(&req->io_task_work.fallback_node,
+                             &req->ctx->fallback_llist))
+                       schedule_delayed_work(&req->ctx->fallback_work, 1);
+       }
 }
 
-static void io_req_task_cancel(struct callback_head *cb)
+static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
 {
-       struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
        struct io_ring_ctx *ctx = req->ctx;
 
-       /* ctx is guaranteed to stay alive while we hold uring_lock */
-       mutex_lock(&ctx->uring_lock);
+       /* not needed for normal modes, but SQPOLL depends on it */
+       io_tw_lock(ctx, locked);
        io_req_complete_failed(req, req->result);
-       mutex_unlock(&ctx->uring_lock);
 }
 
-static void __io_req_task_submit(struct io_kiocb *req)
+static void io_req_task_submit(struct io_kiocb *req, bool *locked)
 {
        struct io_ring_ctx *ctx = req->ctx;
 
-       /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
-       mutex_lock(&ctx->uring_lock);
-       if (!(current->flags & PF_EXITING) && !current->in_execve)
+       io_tw_lock(ctx, locked);
+       /* req->task == current here, checking PF_EXITING is safe */
+       if (likely(!(req->task->flags & PF_EXITING)))
                __io_queue_sqe(req);
        else
                io_req_complete_failed(req, -EFAULT);
-       mutex_unlock(&ctx->uring_lock);
-}
-
-static void io_req_task_submit(struct callback_head *cb)
-{
-       struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
-
-       __io_req_task_submit(req);
 }
 
 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
 {
        req->result = ret;
-       req->task_work.func = io_req_task_cancel;
-
-       if (unlikely(io_req_task_work_add(req)))
-               io_req_task_work_add_fallback(req, io_req_task_cancel);
+       req->io_task_work.func = io_req_task_cancel;
+       io_req_task_work_add(req);
 }
 
 static void io_req_task_queue(struct io_kiocb *req)
 {
-       req->task_work.func = io_req_task_submit;
+       req->io_task_work.func = io_req_task_submit;
+       io_req_task_work_add(req);
+}
 
-       if (unlikely(io_req_task_work_add(req)))
-               io_req_task_queue_fail(req, -ECANCELED);
+static void io_req_task_queue_reissue(struct io_kiocb *req)
+{
+       req->io_task_work.func = io_queue_async_work;
+       io_req_task_work_add(req);
 }
 
 static inline void io_queue_next(struct io_kiocb *req)
@@ -2085,6 +2273,11 @@ static void io_free_req(struct io_kiocb *req)
        __io_free_req(req);
 }
 
+static void io_free_req_work(struct io_kiocb *req, bool *locked)
+{
+       io_free_req(req);
+}
+
 struct req_batch {
        struct task_struct      *task;
        int                     task_refs;
@@ -2101,10 +2294,10 @@ static inline void io_init_req_batch(struct req_batch *rb)
 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
                                     struct req_batch *rb)
 {
-       if (rb->task)
-               io_put_task(rb->task, rb->task_refs);
        if (rb->ctx_refs)
                percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
+       if (rb->task)
+               io_put_task(rb->task, rb->task_refs);
 }
 
 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
@@ -2125,37 +2318,37 @@ static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
        if (state->free_reqs != ARRAY_SIZE(state->reqs))
                state->reqs[state->free_reqs++] = req;
        else
-               list_add(&req->compl.list, &state->comp.free_list);
+               list_add(&req->inflight_entry, &state->free_list);
 }
 
-static void io_submit_flush_completions(struct io_comp_state *cs,
-                                       struct io_ring_ctx *ctx)
+static void io_submit_flush_completions(struct io_ring_ctx *ctx)
+       __must_hold(&ctx->uring_lock)
 {
-       int i, nr = cs->nr;
-       struct io_kiocb *req;
+       struct io_submit_state *state = &ctx->submit_state;
+       int i, nr = state->compl_nr;
        struct req_batch rb;
 
-       io_init_req_batch(&rb);
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
        for (i = 0; i < nr; i++) {
-               req = cs->reqs[i];
+               struct io_kiocb *req = state->compl_reqs[i];
+
                __io_cqring_fill_event(ctx, req->user_data, req->result,
                                        req->compl.cflags);
        }
        io_commit_cqring(ctx);
-       spin_unlock_irq(&ctx->completion_lock);
-
+       spin_unlock(&ctx->completion_lock);
        io_cqring_ev_posted(ctx);
+
+       io_init_req_batch(&rb);
        for (i = 0; i < nr; i++) {
-               req = cs->reqs[i];
+               struct io_kiocb *req = state->compl_reqs[i];
 
-               /* submission and completion refs */
-               if (req_ref_sub_and_test(req, 2))
+               if (req_ref_put_and_test(req))
                        io_req_free_batch(&rb, req, &ctx->submit_state);
        }
 
        io_req_free_batch_finish(ctx, &rb);
-       cs->nr = 0;
+       state->compl_nr = 0;
 }
 
 /*
@@ -2179,24 +2372,12 @@ static inline void io_put_req(struct io_kiocb *req)
                io_free_req(req);
 }
 
-static void io_put_req_deferred_cb(struct callback_head *cb)
-{
-       struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
-
-       io_free_req(req);
-}
-
-static void io_free_req_deferred(struct io_kiocb *req)
-{
-       req->task_work.func = io_put_req_deferred_cb;
-       if (unlikely(io_req_task_work_add(req)))
-               io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
-}
-
-static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
+static inline void io_put_req_deferred(struct io_kiocb *req)
 {
-       if (req_ref_sub_and_test(req, refs))
-               io_free_req_deferred(req);
+       if (req_ref_put_and_test(req)) {
+               req->io_task_work.func = io_free_req_work;
+               io_req_task_work_add(req);
+       }
 }
 
 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
@@ -2229,21 +2410,17 @@ static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
 {
        struct io_buffer *kbuf;
 
+       if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
+               return 0;
        kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
        return io_put_kbuf(req, kbuf);
 }
 
 static inline bool io_run_task_work(void)
 {
-       /*
-        * Not safe to run on exiting task, and the task_work handling will
-        * not add work to such a task.
-        */
-       if (unlikely(current->flags & PF_EXITING))
-               return false;
-       if (current->task_works) {
+       if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
                __set_current_state(TASK_RUNNING);
-               task_work_run();
+               tracehook_notify_signal();
                return true;
        }
 
@@ -2264,23 +2441,18 @@ static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
 
        io_init_req_batch(&rb);
        while (!list_empty(done)) {
-               int cflags = 0;
-
                req = list_first_entry(done, struct io_kiocb, inflight_entry);
                list_del(&req->inflight_entry);
 
                if (READ_ONCE(req->result) == -EAGAIN &&
                    !(req->flags & REQ_F_DONT_REISSUE)) {
                        req->iopoll_completed = 0;
-                       req_ref_get(req);
-                       io_queue_async_work(req);
+                       io_req_task_queue_reissue(req);
                        continue;
                }
 
-               if (req->flags & REQ_F_BUFFER_SELECTED)
-                       cflags = io_put_rw_kbuf(req);
-
-               __io_cqring_fill_event(ctx, req->user_data, req->result, cflags);
+               __io_cqring_fill_event(ctx, req->user_data, req->result,
+                                       io_put_rw_kbuf(req));
                (*nr_events)++;
 
                if (req_ref_put_and_test(req))
@@ -2298,17 +2470,16 @@ static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
        struct io_kiocb *req, *tmp;
        LIST_HEAD(done);
        bool spin;
-       int ret;
 
        /*
         * Only spin for completions if we don't have multiple devices hanging
         * off our complete list, and we're under the requested amount.
         */
-       spin = !ctx->poll_multi_file && *nr_events < min;
+       spin = !ctx->poll_multi_queue && *nr_events < min;
 
-       ret = 0;
        list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
                struct kiocb *kiocb = &req->rw.kiocb;
+               int ret;
 
                /*
                 * Move completed and retryable entries to our local lists.
@@ -2323,22 +2494,20 @@ static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
                        break;
 
                ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
-               if (ret < 0)
-                       break;
+               if (unlikely(ret < 0))
+                       return ret;
+               else if (ret)
+                       spin = false;
 
                /* iopoll may have completed current req */
                if (READ_ONCE(req->iopoll_completed))
                        list_move_tail(&req->inflight_entry, &done);
-
-               if (ret && spin)
-                       spin = false;
-               ret = 0;
        }
 
        if (!list_empty(&done))
                io_iopoll_complete(ctx, nr_events, &done);
 
-       return ret;
+       return 0;
 }
 
 /*
@@ -2389,7 +2558,7 @@ static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
         * If we do, we can potentially be spinning for commands that
         * already triggered a CQE (eg in error).
         */
-       if (test_bit(0, &ctx->cq_check_overflow))
+       if (test_bit(0, &ctx->check_cq_overflow))
                __io_cqring_overflow_flush(ctx, false);
        if (io_cqring_events(ctx))
                goto out;
@@ -2405,11 +2574,15 @@ static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
                 * very same mutex.
                 */
                if (list_empty(&ctx->iopoll_list)) {
+                       u32 tail = ctx->cached_cq_tail;
+
                        mutex_unlock(&ctx->uring_lock);
                        io_run_task_work();
                        mutex_lock(&ctx->uring_lock);
 
-                       if (list_empty(&ctx->iopoll_list))
+                       /* some requests don't go through iopoll_list */
+                       if (tail != ctx->cached_cq_tail ||
+                           list_empty(&ctx->iopoll_list))
                                break;
                }
                ret = io_do_iopoll(ctx, &nr_events, min);
@@ -2462,6 +2635,12 @@ static bool io_rw_should_reissue(struct io_kiocb *req)
         */
        if (percpu_ref_is_dying(&ctx->refs))
                return false;
+       /*
+        * Play it safe and assume not safe to re-import and reissue if we're
+        * not in the original thread group (or in task context).
+        */
+       if (!same_thread_group(req->task, current) || !in_task())
+               return false;
        return true;
 }
 #else
@@ -2475,31 +2654,57 @@ static bool io_rw_should_reissue(struct io_kiocb *req)
 }
 #endif
 
-static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
-                            unsigned int issue_flags)
+static bool __io_complete_rw_common(struct io_kiocb *req, long res)
 {
-       int cflags = 0;
-
        if (req->rw.kiocb.ki_flags & IOCB_WRITE)
                kiocb_end_write(req);
        if (res != req->result) {
                if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
                    io_rw_should_reissue(req)) {
                        req->flags |= REQ_F_REISSUE;
-                       return;
+                       return true;
                }
-               req_set_fail_links(req);
+               req_set_fail(req);
+               req->result = res;
        }
-       if (req->flags & REQ_F_BUFFER_SELECTED)
-               cflags = io_put_rw_kbuf(req);
-       __io_req_complete(req, issue_flags, res, cflags);
+       return false;
+}
+
+static void io_req_task_complete(struct io_kiocb *req, bool *locked)
+{
+       unsigned int cflags = io_put_rw_kbuf(req);
+       long res = req->result;
+
+       if (*locked) {
+               struct io_ring_ctx *ctx = req->ctx;
+               struct io_submit_state *state = &ctx->submit_state;
+
+               io_req_complete_state(req, res, cflags);
+               state->compl_reqs[state->compl_nr++] = req;
+               if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
+                       io_submit_flush_completions(ctx);
+       } else {
+               io_req_complete_post(req, res, cflags);
+       }
+}
+
+static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
+                            unsigned int issue_flags)
+{
+       if (__io_complete_rw_common(req, res))
+               return;
+       __io_req_complete(req, issue_flags, req->result, io_put_rw_kbuf(req));
 }
 
 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
 {
        struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
 
-       __io_complete_rw(req, res, res2, 0);
+       if (__io_complete_rw_common(req, res))
+               return;
+       req->result = res;
+       req->io_task_work.func = io_req_task_complete;
+       io_req_task_work_add(req);
 }
 
 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
@@ -2511,7 +2716,7 @@ static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
        if (unlikely(res != req->result)) {
                if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
                    io_resubmit_prep(req))) {
-                       req_set_fail_links(req);
+                       req_set_fail(req);
                        req->flags |= REQ_F_DONT_REISSUE;
                }
        }
@@ -2528,9 +2733,14 @@ static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
  * find it from a io_do_iopoll() thread before the issuer is done
  * accessing the kiocb cookie.
  */
-static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
+static void io_iopoll_req_issued(struct io_kiocb *req)
 {
        struct io_ring_ctx *ctx = req->ctx;
+       const bool in_async = io_wq_current_is_worker();
+
+       /* workqueue context doesn't hold uring_lock, grab it now */
+       if (unlikely(in_async))
+               mutex_lock(&ctx->uring_lock);
 
        /*
         * Track whether we have multiple files in our lists. This will impact
@@ -2538,14 +2748,22 @@ static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
         * different devices.
         */
        if (list_empty(&ctx->iopoll_list)) {
-               ctx->poll_multi_file = false;
-       } else if (!ctx->poll_multi_file) {
+               ctx->poll_multi_queue = false;
+       } else if (!ctx->poll_multi_queue) {
                struct io_kiocb *list_req;
+               unsigned int queue_num0, queue_num1;
 
                list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
                                                inflight_entry);
-               if (list_req->file != req->file)
-                       ctx->poll_multi_file = true;
+
+               if (list_req->file != req->file) {
+                       ctx->poll_multi_queue = true;
+               } else {
+                       queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
+                       queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
+                       if (queue_num0 != queue_num1)
+                               ctx->poll_multi_queue = true;
+               }
        }
 
        /*
@@ -2557,48 +2775,19 @@ static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
        else
                list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
 
-       /*
-        * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
-        * task context or in io worker task context. If current task context is
-        * sq thread, we don't need to check whether should wake up sq thread.
-        */
-       if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
-           wq_has_sleeper(&ctx->sq_data->wait))
-               wake_up(&ctx->sq_data->wait);
-}
-
-static inline void io_state_file_put(struct io_submit_state *state)
-{
-       if (state->file_refs) {
-               fput_many(state->file, state->file_refs);
-               state->file_refs = 0;
-       }
-}
-
-/*
- * Get as many references to a file as we have IOs left in this submission,
- * assuming most submissions are for one file, or at least that each file
- * has more than one submission.
- */
-static struct file *__io_file_get(struct io_submit_state *state, int fd)
-{
-       if (!state)
-               return fget(fd);
+       if (unlikely(in_async)) {
+               /*
+                * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
+                * in sq thread task context or in io worker task context. If
+                * current task context is sq thread, we don't need to check
+                * whether should wake up sq thread.
+                */
+               if ((ctx->flags & IORING_SETUP_SQPOLL) &&
+                   wq_has_sleeper(&ctx->sq_data->wait))
+                       wake_up(&ctx->sq_data->wait);
 
-       if (state->file_refs) {
-               if (state->fd == fd) {
-                       state->file_refs--;
-                       return state->file;
-               }
-               io_state_file_put(state);
+               mutex_unlock(&ctx->uring_lock);
        }
-       state->file = fget_many(fd, state->ios_left);
-       if (unlikely(!state->file))
-               return NULL;
-
-       state->fd = fd;
-       state->file_refs = state->ios_left - 1;
-       return state->file;
 }
 
 static bool io_bdev_nowait(struct block_device *bdev)
@@ -2611,7 +2800,7 @@ static bool io_bdev_nowait(struct block_device *bdev)
  * any file. For now, just ensure that anything potentially problematic is done
  * inline.
  */
-static bool __io_file_supports_async(struct file *file, int rw)
+static bool __io_file_supports_nowait(struct file *file, int rw)
 {
        umode_t mode = file_inode(file)->i_mode;
 
@@ -2621,7 +2810,7 @@ static bool __io_file_supports_async(struct file *file, int rw)
                        return true;
                return false;
        }
-       if (S_ISCHR(mode) || S_ISSOCK(mode))
+       if (S_ISSOCK(mode))
                return true;
        if (S_ISREG(mode)) {
                if (IS_ENABLED(CONFIG_BLOCK) &&
@@ -2644,14 +2833,14 @@ static bool __io_file_supports_async(struct file *file, int rw)
        return file->f_op->write_iter != NULL;
 }
 
-static bool io_file_supports_async(struct io_kiocb *req, int rw)
+static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
 {
-       if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
+       if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
                return true;
-       else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
+       else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
                return true;
 
-       return __io_file_supports_async(req->file, rw);
+       return __io_file_supports_nowait(req->file, rw);
 }
 
 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
@@ -2662,7 +2851,7 @@ static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
        unsigned ioprio;
        int ret;
 
-       if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
+       if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
                req->flags |= REQ_F_ISREG;
 
        kiocb->ki_pos = READ_ONCE(sqe->off);
@@ -2695,7 +2884,7 @@ static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
                    !kiocb->ki_filp->f_op->iopoll)
                        return -EOPNOTSUPP;
 
-               kiocb->ki_flags |= IOCB_HIPRI;
+               kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
                kiocb->ki_complete = io_complete_rw_iopoll;
                req->iopoll_completed = 0;
        } else {
@@ -2754,23 +2943,19 @@ static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
 
        if (req->flags & REQ_F_CUR_POS)
                req->file->f_pos = kiocb->ki_pos;
-       if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
+       if (ret >= 0 && check_reissue)
                __io_complete_rw(req, ret, 0, issue_flags);
        else
                io_rw_done(kiocb, ret);
 
-       if (check_reissue && req->flags & REQ_F_REISSUE) {
+       if (check_reissue && (req->flags & REQ_F_REISSUE)) {
                req->flags &= ~REQ_F_REISSUE;
                if (io_resubmit_prep(req)) {
-                       req_ref_get(req);
-                       io_queue_async_work(req);
+                       io_req_task_queue_reissue(req);
                } else {
-                       int cflags = 0;
-
-                       req_set_fail_links(req);
-                       if (req->flags & REQ_F_BUFFER_SELECTED)
-                               cflags = io_put_rw_kbuf(req);
-                       __io_req_complete(req, issue_flags, ret, cflags);
+                       req_set_fail(req);
+                       __io_req_complete(req, issue_flags, ret,
+                                         io_put_rw_kbuf(req));
                }
        }
 }
@@ -3188,9 +3373,6 @@ static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
 
        req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
        list_del_init(&wait->entry);
-
-       /* submit ref gets dropped, acquire a new one */
-       req_ref_get(req);
        io_req_task_queue(req);
        return 1;
 }
@@ -3238,7 +3420,7 @@ static bool io_rw_should_retry(struct io_kiocb *req)
        return true;
 }
 
-static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
+static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
 {
        if (req->file->f_op->read_iter)
                return call_read_iter(req->file, &req->rw.kiocb, iter);
@@ -3248,6 +3430,12 @@ static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
                return -EINVAL;
 }
 
+static bool need_read_all(struct io_kiocb *req)
+{
+       return req->flags & REQ_F_ISREG ||
+               S_ISBLK(file_inode(req->file)->i_mode);
+}
+
 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
 {
        struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
@@ -3275,7 +3463,7 @@ static int io_read(struct io_kiocb *req, unsigned int issue_flags)
                kiocb->ki_flags |= IOCB_NOWAIT;
 
        /* If the file doesn't support async, just async punt */
-       if (force_nonblock && !io_file_supports_async(req, READ)) {
+       if (force_nonblock && !io_file_supports_nowait(req, READ)) {
                ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
                return ret ?: -EAGAIN;
        }
@@ -3297,12 +3485,13 @@ static int io_read(struct io_kiocb *req, unsigned int issue_flags)
                if (req->flags & REQ_F_NOWAIT)
                        goto done;
                /* some cases will consume bytes even on error returns */
+               iov_iter_reexpand(iter, iter->count + iter->truncated);
                iov_iter_revert(iter, io_size - iov_iter_count(iter));
                ret = 0;
        } else if (ret == -EIOCBQUEUED) {
                goto out_free;
        } else if (ret <= 0 || ret == io_size || !force_nonblock ||
-                  (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
+                  (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
                /* read all, failed, already did sync or don't want to retry */
                goto done;
        }
@@ -3380,7 +3569,7 @@ static int io_write(struct io_kiocb *req, unsigned int issue_flags)
                kiocb->ki_flags |= IOCB_NOWAIT;
 
        /* If the file doesn't support async, just async punt */
-       if (force_nonblock && !io_file_supports_async(req, WRITE))
+       if (force_nonblock && !io_file_supports_nowait(req, WRITE))
                goto copy_iov;
 
        /* file path doesn't support NOWAIT for non-direct_IO */
@@ -3436,6 +3625,7 @@ done:
        } else {
 copy_iov:
                /* some cases will consume bytes even on error returns */
+               iov_iter_reexpand(iter, iter->count + iter->truncated);
                iov_iter_revert(iter, io_size - iov_iter_count(iter));
                ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
                return ret ?: -EAGAIN;
@@ -3453,6 +3643,10 @@ static int io_renameat_prep(struct io_kiocb *req,
        struct io_rename *ren = &req->rename;
        const char __user *oldf, *newf;
 
+       if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
+               return -EINVAL;
+       if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
+               return -EINVAL;
        if (unlikely(req->flags & REQ_F_FIXED_FILE))
                return -EBADF;
 
@@ -3489,7 +3683,7 @@ static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
 
        req->flags &= ~REQ_F_NEED_CLEANUP;
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
 }
@@ -3500,6 +3694,11 @@ static int io_unlinkat_prep(struct io_kiocb *req,
        struct io_unlink *un = &req->unlink;
        const char __user *fname;
 
+       if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
+               return -EINVAL;
+       if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
+           sqe->splice_fd_in)
+               return -EINVAL;
        if (unlikely(req->flags & REQ_F_FIXED_FILE))
                return -EBADF;
 
@@ -3533,56 +3732,199 @@ static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
 
        req->flags &= ~REQ_F_NEED_CLEANUP;
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
 }
 
-static int io_shutdown_prep(struct io_kiocb *req,
+static int io_mkdirat_prep(struct io_kiocb *req,
                            const struct io_uring_sqe *sqe)
 {
-#if defined(CONFIG_NET)
+       struct io_mkdir *mkd = &req->mkdir;
+       const char __user *fname;
+
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
-       if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
-           sqe->buf_index)
+       if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
+           sqe->splice_fd_in)
                return -EINVAL;
+       if (unlikely(req->flags & REQ_F_FIXED_FILE))
+               return -EBADF;
 
-       req->shutdown.how = READ_ONCE(sqe->len);
+       mkd->dfd = READ_ONCE(sqe->fd);
+       mkd->mode = READ_ONCE(sqe->len);
+
+       fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
+       mkd->filename = getname(fname);
+       if (IS_ERR(mkd->filename))
+               return PTR_ERR(mkd->filename);
+
+       req->flags |= REQ_F_NEED_CLEANUP;
        return 0;
-#else
-       return -EOPNOTSUPP;
-#endif
 }
 
-static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
+static int io_mkdirat(struct io_kiocb *req, int issue_flags)
 {
-#if defined(CONFIG_NET)
-       struct socket *sock;
+       struct io_mkdir *mkd = &req->mkdir;
        int ret;
 
        if (issue_flags & IO_URING_F_NONBLOCK)
                return -EAGAIN;
 
-       sock = sock_from_file(req->file);
-       if (unlikely(!sock))
-               return -ENOTSOCK;
+       ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
 
-       ret = __sys_shutdown_sock(sock, req->shutdown.how);
+       req->flags &= ~REQ_F_NEED_CLEANUP;
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
-#else
-       return -EOPNOTSUPP;
-#endif
 }
 
-static int __io_splice_prep(struct io_kiocb *req,
+static int io_symlinkat_prep(struct io_kiocb *req,
                            const struct io_uring_sqe *sqe)
 {
-       struct io_splice* sp = &req->splice;
-       unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
+       struct io_symlink *sl = &req->symlink;
+       const char __user *oldpath, *newpath;
+
+       if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
+               return -EINVAL;
+       if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
+           sqe->splice_fd_in)
+               return -EINVAL;
+       if (unlikely(req->flags & REQ_F_FIXED_FILE))
+               return -EBADF;
+
+       sl->new_dfd = READ_ONCE(sqe->fd);
+       oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
+       newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
+
+       sl->oldpath = getname(oldpath);
+       if (IS_ERR(sl->oldpath))
+               return PTR_ERR(sl->oldpath);
+
+       sl->newpath = getname(newpath);
+       if (IS_ERR(sl->newpath)) {
+               putname(sl->oldpath);
+               return PTR_ERR(sl->newpath);
+       }
+
+       req->flags |= REQ_F_NEED_CLEANUP;
+       return 0;
+}
+
+static int io_symlinkat(struct io_kiocb *req, int issue_flags)
+{
+       struct io_symlink *sl = &req->symlink;
+       int ret;
+
+       if (issue_flags & IO_URING_F_NONBLOCK)
+               return -EAGAIN;
+
+       ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
+
+       req->flags &= ~REQ_F_NEED_CLEANUP;
+       if (ret < 0)
+               req_set_fail(req);
+       io_req_complete(req, ret);
+       return 0;
+}
+
+static int io_linkat_prep(struct io_kiocb *req,
+                           const struct io_uring_sqe *sqe)
+{
+       struct io_hardlink *lnk = &req->hardlink;
+       const char __user *oldf, *newf;
+
+       if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
+               return -EINVAL;
+       if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
+               return -EINVAL;
+       if (unlikely(req->flags & REQ_F_FIXED_FILE))
+               return -EBADF;
+
+       lnk->old_dfd = READ_ONCE(sqe->fd);
+       lnk->new_dfd = READ_ONCE(sqe->len);
+       oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
+       newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
+       lnk->flags = READ_ONCE(sqe->hardlink_flags);
+
+       lnk->oldpath = getname(oldf);
+       if (IS_ERR(lnk->oldpath))
+               return PTR_ERR(lnk->oldpath);
+
+       lnk->newpath = getname(newf);
+       if (IS_ERR(lnk->newpath)) {
+               putname(lnk->oldpath);
+               return PTR_ERR(lnk->newpath);
+       }
+
+       req->flags |= REQ_F_NEED_CLEANUP;
+       return 0;
+}
+
+static int io_linkat(struct io_kiocb *req, int issue_flags)
+{
+       struct io_hardlink *lnk = &req->hardlink;
+       int ret;
+
+       if (issue_flags & IO_URING_F_NONBLOCK)
+               return -EAGAIN;
+
+       ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
+                               lnk->newpath, lnk->flags);
+
+       req->flags &= ~REQ_F_NEED_CLEANUP;
+       if (ret < 0)
+               req_set_fail(req);
+       io_req_complete(req, ret);
+       return 0;
+}
+
+static int io_shutdown_prep(struct io_kiocb *req,
+                           const struct io_uring_sqe *sqe)
+{
+#if defined(CONFIG_NET)
+       if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
+               return -EINVAL;
+       if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
+                    sqe->buf_index || sqe->splice_fd_in))
+               return -EINVAL;
+
+       req->shutdown.how = READ_ONCE(sqe->len);
+       return 0;
+#else
+       return -EOPNOTSUPP;
+#endif
+}
+
+static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
+{
+#if defined(CONFIG_NET)
+       struct socket *sock;
+       int ret;
+
+       if (issue_flags & IO_URING_F_NONBLOCK)
+               return -EAGAIN;
+
+       sock = sock_from_file(req->file);
+       if (unlikely(!sock))
+               return -ENOTSOCK;
+
+       ret = __sys_shutdown_sock(sock, req->shutdown.how);
+       if (ret < 0)
+               req_set_fail(req);
+       io_req_complete(req, ret);
+       return 0;
+#else
+       return -EOPNOTSUPP;
+#endif
+}
+
+static int __io_splice_prep(struct io_kiocb *req,
+                           const struct io_uring_sqe *sqe)
+{
+       struct io_splice *sp = &req->splice;
+       unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
 
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
@@ -3594,7 +3936,7 @@ static int __io_splice_prep(struct io_kiocb *req,
        if (unlikely(sp->flags & ~valid_flags))
                return -EINVAL;
 
-       sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
+       sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
                                  (sp->flags & SPLICE_F_FD_IN_FIXED));
        if (!sp->file_in)
                return -EBADF;
@@ -3628,14 +3970,14 @@ static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
        req->flags &= ~REQ_F_NEED_CLEANUP;
 
        if (ret != sp->len)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
 }
 
 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 {
-       struct io_splicesp = &req->splice;
+       struct io_splice *sp = &req->splice;
 
        sp->off_in = READ_ONCE(sqe->splice_off_in);
        sp->off_out = READ_ONCE(sqe->off);
@@ -3665,7 +4007,7 @@ static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
        req->flags &= ~REQ_F_NEED_CLEANUP;
 
        if (ret != sp->len)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
 }
@@ -3693,7 +4035,8 @@ static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 
        if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
-       if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
+       if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
+                    sqe->splice_fd_in))
                return -EINVAL;
 
        req->sync.flags = READ_ONCE(sqe->fsync_flags);
@@ -3718,7 +4061,7 @@ static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
                                end > 0 ? end : LLONG_MAX,
                                req->sync.flags & IORING_FSYNC_DATASYNC);
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
 }
@@ -3726,7 +4069,8 @@ static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
 static int io_fallocate_prep(struct io_kiocb *req,
                             const struct io_uring_sqe *sqe)
 {
-       if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
+       if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
+           sqe->splice_fd_in)
                return -EINVAL;
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
@@ -3747,7 +4091,7 @@ static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
        ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
                                req->sync.len);
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
 }
@@ -3757,6 +4101,8 @@ static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe
        const char __user *fname;
        int ret;
 
+       if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
+               return -EINVAL;
        if (unlikely(sqe->ioprio || sqe->buf_index))
                return -EINVAL;
        if (unlikely(req->flags & REQ_F_FIXED_FILE))
@@ -3774,6 +4120,11 @@ static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe
                req->open.filename = NULL;
                return ret;
        }
+
+       req->open.file_slot = READ_ONCE(sqe->file_index);
+       if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
+               return -EINVAL;
+
        req->open.nofile = rlimit(RLIMIT_NOFILE);
        req->flags |= REQ_F_NEED_CLEANUP;
        return 0;
@@ -3781,12 +4132,9 @@ static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe
 
 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 {
-       u64 flags, mode;
+       u64 mode = READ_ONCE(sqe->len);
+       u64 flags = READ_ONCE(sqe->open_flags);
 
-       if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
-               return -EINVAL;
-       mode = READ_ONCE(sqe->len);
-       flags = READ_ONCE(sqe->open_flags);
        req->open.how = build_open_how(flags, mode);
        return __io_openat_prep(req, sqe);
 }
@@ -3797,8 +4145,6 @@ static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
        size_t len;
        int ret;
 
-       if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
-               return -EINVAL;
        how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
        len = READ_ONCE(sqe->len);
        if (len < OPEN_HOW_SIZE_VER0)
@@ -3816,8 +4162,8 @@ static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
 {
        struct open_flags op;
        struct file *file;
-       bool nonblock_set;
-       bool resolve_nonblock;
+       bool resolve_nonblock, nonblock_set;
+       bool fixed = !!req->open.file_slot;
        int ret;
 
        ret = build_open_flags(&req->open.how, &op);
@@ -3836,37 +4182,44 @@ static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
                op.open_flag |= O_NONBLOCK;
        }
 
-       ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
-       if (ret < 0)
-               goto err;
+       if (!fixed) {
+               ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
+               if (ret < 0)
+                       goto err;
+       }
 
        file = do_filp_open(req->open.dfd, req->open.filename, &op);
-       /* only retry if RESOLVE_CACHED wasn't already set by application */
-       if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
-           file == ERR_PTR(-EAGAIN)) {
+       if (IS_ERR(file)) {
                /*
-                * We could hang on to this 'fd', but seems like marginal
-                * gain for something that is now known to be a slower path.
-                * So just put it, and we'll get a new one when we retry.
+                * We could hang on to this 'fd' on retrying, but seems like
+                * marginal gain for something that is now known to be a slower
+                * path. So just put it, and we'll get a new one when we retry.
                 */
-               put_unused_fd(ret);
-               return -EAGAIN;
-       }
+               if (!fixed)
+                       put_unused_fd(ret);
 
-       if (IS_ERR(file)) {
-               put_unused_fd(ret);
                ret = PTR_ERR(file);
-       } else {
-               if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
-                       file->f_flags &= ~O_NONBLOCK;
-               fsnotify_open(file);
-               fd_install(ret, file);
+               /* only retry if RESOLVE_CACHED wasn't already set by application */
+               if (ret == -EAGAIN &&
+                   (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
+                       return -EAGAIN;
+               goto err;
        }
+
+       if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
+               file->f_flags &= ~O_NONBLOCK;
+       fsnotify_open(file);
+
+       if (!fixed)
+               fd_install(ret, file);
+       else
+               ret = io_install_fixed_file(req, file, issue_flags,
+                                           req->open.file_slot - 1);
 err:
        putname(req->open.filename);
        req->flags &= ~REQ_F_NEED_CLEANUP;
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        __io_req_complete(req, issue_flags, ret, 0);
        return 0;
 }
@@ -3882,7 +4235,8 @@ static int io_remove_buffers_prep(struct io_kiocb *req,
        struct io_provide_buf *p = &req->pbuf;
        u64 tmp;
 
-       if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
+       if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
+           sqe->splice_fd_in)
                return -EINVAL;
 
        tmp = READ_ONCE(sqe->fd);
@@ -3938,7 +4292,7 @@ static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
        if (head)
                ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
 
        /* complete before unlock, IOPOLL may need the lock */
        __io_req_complete(req, issue_flags, ret, 0);
@@ -3953,7 +4307,7 @@ static int io_provide_buffers_prep(struct io_kiocb *req,
        struct io_provide_buf *p = &req->pbuf;
        u64 tmp;
 
-       if (sqe->ioprio || sqe->rw_flags)
+       if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
                return -EINVAL;
 
        tmp = READ_ONCE(sqe->fd);
@@ -4029,7 +4383,7 @@ static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
                        __io_remove_buffers(ctx, head, p->bgid, -1U);
        }
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        /* complete before unlock, IOPOLL may need the lock */
        __io_req_complete(req, issue_flags, ret, 0);
        io_ring_submit_unlock(ctx, !force_nonblock);
@@ -4040,7 +4394,7 @@ static int io_epoll_ctl_prep(struct io_kiocb *req,
                             const struct io_uring_sqe *sqe)
 {
 #if defined(CONFIG_EPOLL)
-       if (sqe->ioprio || sqe->buf_index)
+       if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
                return -EINVAL;
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
@@ -4075,7 +4429,7 @@ static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
                return -EAGAIN;
 
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        __io_req_complete(req, issue_flags, ret, 0);
        return 0;
 #else
@@ -4086,7 +4440,7 @@ static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 {
 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
-       if (sqe->ioprio || sqe->buf_index || sqe->off)
+       if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
                return -EINVAL;
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
@@ -4111,7 +4465,7 @@ static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
 
        ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
 #else
@@ -4121,7 +4475,7 @@ static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
 
 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 {
-       if (sqe->ioprio || sqe->buf_index || sqe->addr)
+       if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
                return -EINVAL;
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
@@ -4150,7 +4504,7 @@ static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
 
        ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        __io_req_complete(req, issue_flags, ret, 0);
        return 0;
 }
@@ -4159,7 +4513,7 @@ static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 {
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
-       if (sqe->ioprio || sqe->buf_index)
+       if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
                return -EINVAL;
        if (req->flags & REQ_F_FIXED_FILE)
                return -EBADF;
@@ -4185,7 +4539,7 @@ static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
                       ctx->buffer);
 
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
 }
@@ -4195,7 +4549,7 @@ static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
        if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
-           sqe->rw_flags || sqe->buf_index)
+           sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
                return -EINVAL;
        if (req->flags & REQ_F_FIXED_FILE)
                return -EBADF;
@@ -4243,7 +4597,7 @@ static int io_close(struct io_kiocb *req, unsigned int issue_flags)
        ret = filp_close(file, current->files);
 err:
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        if (file)
                fput(file);
        __io_req_complete(req, issue_flags, ret, 0);
@@ -4256,7 +4610,8 @@ static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 
        if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
-       if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
+       if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
+                    sqe->splice_fd_in))
                return -EINVAL;
 
        req->sync.off = READ_ONCE(sqe->off);
@@ -4276,7 +4631,7 @@ static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
        ret = sync_file_range(req->file, req->sync.off, req->sync.len,
                                req->sync.flags);
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        io_req_complete(req, ret);
        return 0;
 }
@@ -4380,7 +4735,7 @@ static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
                kfree(kmsg->free_iov);
        req->flags &= ~REQ_F_NEED_CLEANUP;
        if (ret < min_ret)
-               req_set_fail_links(req);
+               req_set_fail(req);
        __io_req_complete(req, issue_flags, ret, 0);
        return 0;
 }
@@ -4422,7 +4777,7 @@ static int io_send(struct io_kiocb *req, unsigned int issue_flags)
                ret = -EINTR;
 
        if (ret < min_ret)
-               req_set_fail_links(req);
+               req_set_fail(req);
        __io_req_complete(req, issue_flags, ret, 0);
        return 0;
 }
@@ -4617,7 +4972,7 @@ static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
                kfree(kmsg->free_iov);
        req->flags &= ~REQ_F_NEED_CLEANUP;
        if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
-               req_set_fail_links(req);
+               req_set_fail(req);
        __io_req_complete(req, issue_flags, ret, cflags);
        return 0;
 }
@@ -4672,7 +5027,7 @@ out_free:
        if (req->flags & REQ_F_BUFFER_SELECTED)
                cflags = io_put_recv_kbuf(req);
        if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
-               req_set_fail_links(req);
+               req_set_fail(req);
        __io_req_complete(req, issue_flags, ret, cflags);
        return 0;
 }
@@ -4690,6 +5045,15 @@ static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
        accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
        accept->flags = READ_ONCE(sqe->accept_flags);
        accept->nofile = rlimit(RLIMIT_NOFILE);
+
+       accept->file_slot = READ_ONCE(sqe->file_index);
+       if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
+                                 (accept->flags & SOCK_CLOEXEC)))
+               return -EINVAL;
+       if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
+               return -EINVAL;
+       if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
+               accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
        return 0;
 }
 
@@ -4698,20 +5062,35 @@ static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
        struct io_accept *accept = &req->accept;
        bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
        unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
-       int ret;
+       bool fixed = !!accept->file_slot;
+       struct file *file;
+       int ret, fd;
 
        if (req->file->f_flags & O_NONBLOCK)
                req->flags |= REQ_F_NOWAIT;
 
-       ret = __sys_accept4_file(req->file, file_flags, accept->addr,
-                                       accept->addr_len, accept->flags,
-                                       accept->nofile);
-       if (ret == -EAGAIN && force_nonblock)
-               return -EAGAIN;
-       if (ret < 0) {
+       if (!fixed) {
+               fd = __get_unused_fd_flags(accept->flags, accept->nofile);
+               if (unlikely(fd < 0))
+                       return fd;
+       }
+       file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
+                        accept->flags);
+       if (IS_ERR(file)) {
+               if (!fixed)
+                       put_unused_fd(fd);
+               ret = PTR_ERR(file);
+               if (ret == -EAGAIN && force_nonblock)
+                       return -EAGAIN;
                if (ret == -ERESTARTSYS)
                        ret = -EINTR;
-               req_set_fail_links(req);
+               req_set_fail(req);
+       } else if (!fixed) {
+               fd_install(fd, file);
+               ret = fd;
+       } else {
+               ret = io_install_fixed_file(req, file, issue_flags,
+                                           accept->file_slot - 1);
        }
        __io_req_complete(req, issue_flags, ret, 0);
        return 0;
@@ -4731,7 +5110,8 @@ static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
-       if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
+       if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
+           sqe->splice_fd_in)
                return -EINVAL;
 
        conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
@@ -4775,7 +5155,7 @@ static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
                ret = -EINTR;
 out:
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        __io_req_complete(req, issue_flags, ret, 0);
        return 0;
 }
@@ -4811,14 +5191,13 @@ IO_NETOP_FN(recv);
 struct io_poll_table {
        struct poll_table_struct pt;
        struct io_kiocb *req;
+       int nr_entries;
        int error;
 };
 
 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
-                          __poll_t mask, task_work_func_t func)
+                          __poll_t mask, io_req_tw_func_t func)
 {
-       int ret;
-
        /* for instances that support it check for an event match first: */
        if (mask && !(mask & poll->events))
                return 0;
@@ -4828,7 +5207,7 @@ static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
        list_del_init(&poll->wait.entry);
 
        req->result = mask;
-       req->task_work.func = func;
+       req->io_task_work.func = func;
 
        /*
         * If this fails, then the task is exiting. When a task exits, the
@@ -4836,11 +5215,7 @@ static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
         * of executing it. We can't safely execute it anyway, as we may not
         * have the needed state needed for it anyway.
         */
-       ret = io_req_task_work_add(req);
-       if (unlikely(ret)) {
-               WRITE_ONCE(poll->canceled, true);
-               io_req_task_work_add_fallback(req, func);
-       }
+       io_req_task_work_add(req);
        return 1;
 }
 
@@ -4849,13 +5224,17 @@ static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
 {
        struct io_ring_ctx *ctx = req->ctx;
 
+       /* req->task == current here, checking PF_EXITING is safe */
+       if (unlikely(req->task->flags & PF_EXITING))
+               WRITE_ONCE(poll->canceled, true);
+
        if (!req->result && !READ_ONCE(poll->canceled)) {
                struct poll_table_struct pt = { ._key = poll->events };
 
                req->result = vfs_poll(req->file, &pt) & poll->events;
        }
 
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
        if (!req->result && !READ_ONCE(poll->canceled)) {
                add_wait_queue(poll->head, &poll->wait);
                return true;
@@ -4889,16 +5268,16 @@ static void io_poll_remove_double(struct io_kiocb *req)
        if (poll && poll->head) {
                struct wait_queue_head *head = poll->head;
 
-               spin_lock(&head->lock);
+               spin_lock_irq(&head->lock);
                list_del_init(&poll->wait.entry);
                if (poll->wait.private)
                        req_ref_put(req);
                poll->head = NULL;
-               spin_unlock(&head->lock);
+               spin_unlock_irq(&head->lock);
        }
 }
 
-static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
+static bool __io_poll_complete(struct io_kiocb *req, __poll_t mask)
        __must_hold(&req->ctx->completion_lock)
 {
        struct io_ring_ctx *ctx = req->ctx;
@@ -4914,42 +5293,51 @@ static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
        if (req->poll.events & EPOLLONESHOT)
                flags = 0;
        if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
-               io_poll_remove_waitqs(req);
                req->poll.done = true;
                flags = 0;
        }
        if (flags & IORING_CQE_F_MORE)
                ctx->cq_extra++;
 
-       io_commit_cqring(ctx);
        return !(flags & IORING_CQE_F_MORE);
 }
 
-static void io_poll_task_func(struct callback_head *cb)
+static inline bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
+       __must_hold(&req->ctx->completion_lock)
+{
+       bool done;
+
+       done = __io_poll_complete(req, mask);
+       io_commit_cqring(req->ctx);
+       return done;
+}
+
+static void io_poll_task_func(struct io_kiocb *req, bool *locked)
 {
-       struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
        struct io_ring_ctx *ctx = req->ctx;
        struct io_kiocb *nxt;
 
        if (io_poll_rewait(req, &req->poll)) {
-               spin_unlock_irq(&ctx->completion_lock);
+               spin_unlock(&ctx->completion_lock);
        } else {
                bool done;
 
-               done = io_poll_complete(req, req->result);
+               done = __io_poll_complete(req, req->result);
                if (done) {
+                       io_poll_remove_double(req);
                        hash_del(&req->hash_node);
                } else {
                        req->result = 0;
                        add_wait_queue(req->poll.head, &req->poll.wait);
                }
-               spin_unlock_irq(&ctx->completion_lock);
+               io_commit_cqring(ctx);
+               spin_unlock(&ctx->completion_lock);
                io_cqring_ev_posted(ctx);
 
                if (done) {
                        nxt = io_put_req_find_next(req);
                        if (nxt)
-                               __io_req_task_submit(nxt);
+                               io_req_task_submit(nxt, locked);
                }
        }
 }
@@ -4960,6 +5348,7 @@ static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
        struct io_kiocb *req = wait->private;
        struct io_poll_iocb *poll = io_poll_get_single(req);
        __poll_t mask = key_to_poll(key);
+       unsigned long flags;
 
        /* for instances that support it check for an event match first: */
        if (mask && !(mask & poll->events))
@@ -4969,16 +5358,16 @@ static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
 
        list_del_init(&wait->entry);
 
-       if (poll && poll->head) {
+       if (poll->head) {
                bool done;
 
-               spin_lock(&poll->head->lock);
+               spin_lock_irqsave(&poll->head->lock, flags);
                done = list_empty(&poll->wait.entry);
                if (!done)
                        list_del_init(&poll->wait.entry);
                /* make sure double remove sees this as being gone */
                wait->private = NULL;
-               spin_unlock(&poll->head->lock);
+               spin_unlock_irqrestore(&poll->head->lock, flags);
                if (!done) {
                        /* use wait func handler, so it matches the rq type */
                        poll->wait.func(&poll->wait, mode, sync, key);
@@ -5008,15 +5397,20 @@ static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
        struct io_kiocb *req = pt->req;
 
        /*
-        * If poll->head is already set, it's because the file being polled
-        * uses multiple waitqueues for poll handling (eg one for read, one
-        * for write). Setup a separate io_poll_iocb if this happens.
+        * The file being polled uses multiple waitqueues for poll handling
+        * (e.g. one for read, one for write). Setup a separate io_poll_iocb
+        * if this happens.
         */
-       if (unlikely(poll->head)) {
+       if (unlikely(pt->nr_entries)) {
                struct io_poll_iocb *poll_one = poll;
 
+               /* double add on the same waitqueue head, ignore */
+               if (poll_one->head == head)
+                       return;
                /* already have a 2nd entry, fail a third attempt */
                if (*poll_ptr) {
+                       if ((*poll_ptr)->head == head)
+                               return;
                        pt->error = -EINVAL;
                        return;
                }
@@ -5026,9 +5420,6 @@ static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
                 */
                if (!(poll_one->events & EPOLLONESHOT))
                        poll_one->events |= EPOLLONESHOT;
-               /* double add on the same waitqueue head, ignore */
-               if (poll_one->head == head)
-                       return;
                poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
                if (!poll) {
                        pt->error = -ENOMEM;
@@ -5040,7 +5431,7 @@ static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
                *poll_ptr = poll;
        }
 
-       pt->error = 0;
+       pt->nr_entries++;
        poll->head = head;
 
        if (poll->events & EPOLLEXCLUSIVE)
@@ -5058,25 +5449,24 @@ static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
        __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
 }
 
-static void io_async_task_func(struct callback_head *cb)
+static void io_async_task_func(struct io_kiocb *req, bool *locked)
 {
-       struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
        struct async_poll *apoll = req->apoll;
        struct io_ring_ctx *ctx = req->ctx;
 
-       trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
+       trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
 
        if (io_poll_rewait(req, &apoll->poll)) {
-               spin_unlock_irq(&ctx->completion_lock);
+               spin_unlock(&ctx->completion_lock);
                return;
        }
 
        hash_del(&req->hash_node);
        io_poll_remove_double(req);
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_unlock(&ctx->completion_lock);
 
        if (!READ_ONCE(apoll->poll.canceled))
-               __io_req_task_submit(req);
+               io_req_task_submit(req, locked);
        else
                io_req_complete_failed(req, -ECANCELED);
 }
@@ -5118,13 +5508,18 @@ static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
 
        ipt->pt._key = mask;
        ipt->req = req;
-       ipt->error = -EINVAL;
+       ipt->error = 0;
+       ipt->nr_entries = 0;
 
        mask = vfs_poll(req->file, &ipt->pt) & poll->events;
+       if (unlikely(!ipt->nr_entries) && !ipt->error)
+               ipt->error = -EINVAL;
 
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
+       if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
+               io_poll_remove_double(req);
        if (likely(poll->head)) {
-               spin_lock(&poll->head->lock);
+               spin_lock_irq(&poll->head->lock);
                if (unlikely(list_empty(&poll->wait.entry))) {
                        if (ipt->error)
                                cancel = true;
@@ -5137,69 +5532,69 @@ static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
                        WRITE_ONCE(poll->canceled, true);
                else if (!poll->done) /* actually waiting for an event */
                        io_poll_req_insert(req);
-               spin_unlock(&poll->head->lock);
+               spin_unlock_irq(&poll->head->lock);
        }
 
        return mask;
 }
 
-static bool io_arm_poll_handler(struct io_kiocb *req)
+enum {
+       IO_APOLL_OK,
+       IO_APOLL_ABORTED,
+       IO_APOLL_READY
+};
+
+static int io_arm_poll_handler(struct io_kiocb *req)
 {
        const struct io_op_def *def = &io_op_defs[req->opcode];
        struct io_ring_ctx *ctx = req->ctx;
        struct async_poll *apoll;
        struct io_poll_table ipt;
-       __poll_t mask, ret;
+       __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
        int rw;
 
        if (!req->file || !file_can_poll(req->file))
-               return false;
+               return IO_APOLL_ABORTED;
        if (req->flags & REQ_F_POLLED)
-               return false;
-       if (def->pollin)
+               return IO_APOLL_ABORTED;
+       if (!def->pollin && !def->pollout)
+               return IO_APOLL_ABORTED;
+
+       if (def->pollin) {
                rw = READ;
-       else if (def->pollout)
+               mask |= POLLIN | POLLRDNORM;
+
+               /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
+               if ((req->opcode == IORING_OP_RECVMSG) &&
+                   (req->sr_msg.msg_flags & MSG_ERRQUEUE))
+                       mask &= ~POLLIN;
+       } else {
                rw = WRITE;
-       else
-               return false;
+               mask |= POLLOUT | POLLWRNORM;
+       }
+
        /* if we can't nonblock try, then no point in arming a poll handler */
-       if (!io_file_supports_async(req, rw))
-               return false;
+       if (!io_file_supports_nowait(req, rw))
+               return IO_APOLL_ABORTED;
 
        apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
        if (unlikely(!apoll))
-               return false;
+               return IO_APOLL_ABORTED;
        apoll->double_poll = NULL;
-
-       req->flags |= REQ_F_POLLED;
        req->apoll = apoll;
-
-       mask = EPOLLONESHOT;
-       if (def->pollin)
-               mask |= POLLIN | POLLRDNORM;
-       if (def->pollout)
-               mask |= POLLOUT | POLLWRNORM;
-
-       /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
-       if ((req->opcode == IORING_OP_RECVMSG) &&
-           (req->sr_msg.msg_flags & MSG_ERRQUEUE))
-               mask &= ~POLLIN;
-
-       mask |= POLLERR | POLLPRI;
-
+       req->flags |= REQ_F_POLLED;
        ipt.pt._qproc = io_async_queue_proc;
+       io_req_set_refcount(req);
 
        ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
                                        io_async_wake);
-       if (ret || ipt.error) {
-               io_poll_remove_double(req);
-               spin_unlock_irq(&ctx->completion_lock);
-               return false;
-       }
-       spin_unlock_irq(&ctx->completion_lock);
-       trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
-                                       apoll->poll.events);
-       return true;
+       spin_unlock(&ctx->completion_lock);
+       if (ret || ipt.error)
+               return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
+
+       trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
+                               mask, apoll->poll.events);
+       return IO_APOLL_OK;
 }
 
 static bool __io_poll_remove_one(struct io_kiocb *req,
@@ -5210,19 +5605,19 @@ static bool __io_poll_remove_one(struct io_kiocb *req,
 
        if (!poll->head)
                return false;
-       spin_lock(&poll->head->lock);
+       spin_lock_irq(&poll->head->lock);
        if (do_cancel)
                WRITE_ONCE(poll->canceled, true);
        if (!list_empty(&poll->wait.entry)) {
                list_del_init(&poll->wait.entry);
                do_complete = true;
        }
-       spin_unlock(&poll->head->lock);
+       spin_unlock_irq(&poll->head->lock);
        hash_del(&req->hash_node);
        return do_complete;
 }
 
-static bool io_poll_remove_waitqs(struct io_kiocb *req)
+static bool io_poll_remove_one(struct io_kiocb *req)
        __must_hold(&req->ctx->completion_lock)
 {
        bool do_complete;
@@ -5230,26 +5625,12 @@ static bool io_poll_remove_waitqs(struct io_kiocb *req)
        io_poll_remove_double(req);
        do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
 
-       if (req->opcode != IORING_OP_POLL_ADD && do_complete) {
-               /* non-poll requests have submit ref still */
-               req_ref_put(req);
-       }
-       return do_complete;
-}
-
-static bool io_poll_remove_one(struct io_kiocb *req)
-       __must_hold(&req->ctx->completion_lock)
-{
-       bool do_complete;
-
-       do_complete = io_poll_remove_waitqs(req);
        if (do_complete) {
                io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
                io_commit_cqring(req->ctx);
-               req_set_fail_links(req);
-               io_put_req_deferred(req, 1);
+               req_set_fail(req);
+               io_put_req_deferred(req);
        }
-
        return do_complete;
 }
 
@@ -5257,23 +5638,23 @@ static bool io_poll_remove_one(struct io_kiocb *req)
  * Returns true if we found and killed one or more poll requests
  */
 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
-                              struct files_struct *files)
+                              bool cancel_all)
 {
        struct hlist_node *tmp;
        struct io_kiocb *req;
        int posted = 0, i;
 
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
        for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
                struct hlist_head *list;
 
                list = &ctx->cancel_hash[i];
                hlist_for_each_entry_safe(req, tmp, list, hash_node) {
-                       if (io_match_task(req, tsk, files))
+                       if (io_match_task(req, tsk, cancel_all))
                                posted += io_poll_remove_one(req);
                }
        }
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_unlock(&ctx->completion_lock);
 
        if (posted)
                io_cqring_ev_posted(ctx);
@@ -5336,7 +5717,7 @@ static int io_poll_update_prep(struct io_kiocb *req,
 
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
-       if (sqe->ioprio || sqe->buf_index)
+       if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
                return -EINVAL;
        flags = READ_ONCE(sqe->len);
        if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
@@ -5391,6 +5772,7 @@ static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe
        if (flags & ~IORING_POLL_ADD_MULTI)
                return -EINVAL;
 
+       io_req_set_refcount(req);
        poll->events = io_poll_parse_events(sqe, flags);
        return 0;
 }
@@ -5411,7 +5793,7 @@ static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
                ipt.error = 0;
                io_poll_complete(req, mask);
        }
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_unlock(&ctx->completion_lock);
 
        if (mask) {
                io_cqring_ev_posted(ctx);
@@ -5428,7 +5810,7 @@ static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
        bool completing;
        int ret;
 
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
        preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
        if (!preq) {
                ret = -ENOENT;
@@ -5455,8 +5837,8 @@ static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
        ret = 0;
 err:
        if (ret < 0) {
-               spin_unlock_irq(&ctx->completion_lock);
-               req_set_fail_links(req);
+               spin_unlock(&ctx->completion_lock);
+               req_set_fail(req);
                io_req_complete(req, ret);
                return 0;
        }
@@ -5468,7 +5850,7 @@ err:
        }
        if (req->poll_update.update_user_data)
                preq->user_data = req->poll_update.new_user_data;
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_unlock(&ctx->completion_lock);
 
        /* complete update request, we're done with it */
        io_req_complete(req, ret);
@@ -5476,13 +5858,19 @@ err:
        if (!completing) {
                ret = io_poll_add(preq, issue_flags);
                if (ret < 0) {
-                       req_set_fail_links(preq);
+                       req_set_fail(preq);
                        io_req_complete(preq, ret);
                }
        }
        return 0;
 }
 
+static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
+{
+       req_set_fail(req);
+       io_req_complete_post(req, -ETIME, 0);
+}
+
 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
 {
        struct io_timeout_data *data = container_of(timer,
@@ -5491,24 +5879,20 @@ static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
        struct io_ring_ctx *ctx = req->ctx;
        unsigned long flags;
 
-       spin_lock_irqsave(&ctx->completion_lock, flags);
+       spin_lock_irqsave(&ctx->timeout_lock, flags);
        list_del_init(&req->timeout.list);
        atomic_set(&req->ctx->cq_timeouts,
                atomic_read(&req->ctx->cq_timeouts) + 1);
+       spin_unlock_irqrestore(&ctx->timeout_lock, flags);
 
-       io_cqring_fill_event(ctx, req->user_data, -ETIME, 0);
-       io_commit_cqring(ctx);
-       spin_unlock_irqrestore(&ctx->completion_lock, flags);
-
-       io_cqring_ev_posted(ctx);
-       req_set_fail_links(req);
-       io_put_req(req);
+       req->io_task_work.func = io_req_task_timeout;
+       io_req_task_work_add(req);
        return HRTIMER_NORESTART;
 }
 
 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
                                           __u64 user_data)
-       __must_hold(&ctx->completion_lock)
+       __must_hold(&ctx->timeout_lock)
 {
        struct io_timeout_data *io;
        struct io_kiocb *req;
@@ -5531,21 +5915,63 @@ static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
 
 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
        __must_hold(&ctx->completion_lock)
+       __must_hold(&ctx->timeout_lock)
 {
        struct io_kiocb *req = io_timeout_extract(ctx, user_data);
 
        if (IS_ERR(req))
                return PTR_ERR(req);
 
-       req_set_fail_links(req);
+       req_set_fail(req);
        io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
-       io_put_req_deferred(req, 1);
+       io_put_req_deferred(req);
+       return 0;
+}
+
+static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
+{
+       switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
+       case IORING_TIMEOUT_BOOTTIME:
+               return CLOCK_BOOTTIME;
+       case IORING_TIMEOUT_REALTIME:
+               return CLOCK_REALTIME;
+       default:
+               /* can't happen, vetted at prep time */
+               WARN_ON_ONCE(1);
+               fallthrough;
+       case 0:
+               return CLOCK_MONOTONIC;
+       }
+}
+
+static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
+                                   struct timespec64 *ts, enum hrtimer_mode mode)
+       __must_hold(&ctx->timeout_lock)
+{
+       struct io_timeout_data *io;
+       struct io_kiocb *req;
+       bool found = false;
+
+       list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
+               found = user_data == req->user_data;
+               if (found)
+                       break;
+       }
+       if (!found)
+               return -ENOENT;
+
+       io = req->async_data;
+       if (hrtimer_try_to_cancel(&io->timer) == -1)
+               return -EALREADY;
+       hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
+       io->timer.function = io_link_timeout_fn;
+       hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
        return 0;
 }
 
 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
                             struct timespec64 *ts, enum hrtimer_mode mode)
-       __must_hold(&ctx->completion_lock)
+       __must_hold(&ctx->timeout_lock)
 {
        struct io_kiocb *req = io_timeout_extract(ctx, user_data);
        struct io_timeout_data *data;
@@ -5556,7 +5982,7 @@ static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
        req->timeout.off = 0; /* noseq */
        data = req->async_data;
        list_add_tail(&req->timeout.list, &ctx->timeout_list);
-       hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
+       hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
        data->timer.function = io_timeout_fn;
        hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
        return 0;
@@ -5571,13 +5997,18 @@ static int io_timeout_remove_prep(struct io_kiocb *req,
                return -EINVAL;
        if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
                return -EINVAL;
-       if (sqe->ioprio || sqe->buf_index || sqe->len)
+       if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
                return -EINVAL;
 
+       tr->ltimeout = false;
        tr->addr = READ_ONCE(sqe->addr);
        tr->flags = READ_ONCE(sqe->timeout_flags);
-       if (tr->flags & IORING_TIMEOUT_UPDATE) {
-               if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
+       if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
+               if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
+                       return -EINVAL;
+               if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
+                       tr->ltimeout = true;
+               if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
                        return -EINVAL;
                if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
                        return -EFAULT;
@@ -5604,20 +6035,26 @@ static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
        struct io_ring_ctx *ctx = req->ctx;
        int ret;
 
-       spin_lock_irq(&ctx->completion_lock);
-       if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
+       if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
+               spin_lock(&ctx->completion_lock);
+               spin_lock_irq(&ctx->timeout_lock);
                ret = io_timeout_cancel(ctx, tr->addr);
-       else
-               ret = io_timeout_update(ctx, tr->addr, &tr->ts,
-                                       io_translate_timeout_mode(tr->flags));
+               spin_unlock_irq(&ctx->timeout_lock);
+               spin_unlock(&ctx->completion_lock);
+       } else {
+               enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
+
+               spin_lock_irq(&ctx->timeout_lock);
+               if (tr->ltimeout)
+                       ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
+               else
+                       ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
+               spin_unlock_irq(&ctx->timeout_lock);
+       }
 
-       io_cqring_fill_event(ctx, req->user_data, ret, 0);
-       io_commit_cqring(ctx);
-       spin_unlock_irq(&ctx->completion_lock);
-       io_cqring_ev_posted(ctx);
        if (ret < 0)
-               req_set_fail_links(req);
-       io_put_req(req);
+               req_set_fail(req);
+       io_req_complete_post(req, ret, 0);
        return 0;
 }
 
@@ -5630,29 +6067,46 @@ static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
 
        if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
                return -EINVAL;
-       if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
+       if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
+           sqe->splice_fd_in)
                return -EINVAL;
        if (off && is_timeout_link)
                return -EINVAL;
        flags = READ_ONCE(sqe->timeout_flags);
-       if (flags & ~IORING_TIMEOUT_ABS)
+       if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
+               return -EINVAL;
+       /* more than one clock specified is invalid, obviously */
+       if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
                return -EINVAL;
 
+       INIT_LIST_HEAD(&req->timeout.list);
        req->timeout.off = off;
+       if (unlikely(off && !req->ctx->off_timeout_used))
+               req->ctx->off_timeout_used = true;
 
        if (!req->async_data && io_alloc_async_data(req))
                return -ENOMEM;
 
        data = req->async_data;
        data->req = req;
+       data->flags = flags;
 
        if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
                return -EFAULT;
 
        data->mode = io_translate_timeout_mode(flags);
-       hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
-       if (is_timeout_link)
-               io_req_track_inflight(req);
+       hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
+
+       if (is_timeout_link) {
+               struct io_submit_link *link = &req->ctx->submit_state.link;
+
+               if (!link->head)
+                       return -EINVAL;
+               if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
+                       return -EINVAL;
+               req->timeout.head = link->last;
+               link->last->flags |= REQ_F_ARM_LTIMEOUT;
+       }
        return 0;
 }
 
@@ -5663,7 +6117,7 @@ static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
        struct list_head *entry;
        u32 tail, off = req->timeout.off;
 
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock_irq(&ctx->timeout_lock);
 
        /*
         * sqe->off holds how many events that need to occur for this
@@ -5702,7 +6156,7 @@ add:
        list_add(&req->timeout.list, entry);
        data->timer.function = io_timeout_fn;
        hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_unlock_irq(&ctx->timeout_lock);
        return 0;
 }
 
@@ -5745,31 +6199,27 @@ static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
        return ret;
 }
 
-static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
-                                    struct io_kiocb *req, __u64 sqe_addr,
-                                    int success_ret)
+static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
 {
-       unsigned long flags;
+       struct io_ring_ctx *ctx = req->ctx;
        int ret;
 
+       WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
+
        ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
-       spin_lock_irqsave(&ctx->completion_lock, flags);
        if (ret != -ENOENT)
-               goto done;
+               return ret;
+
+       spin_lock(&ctx->completion_lock);
+       spin_lock_irq(&ctx->timeout_lock);
        ret = io_timeout_cancel(ctx, sqe_addr);
+       spin_unlock_irq(&ctx->timeout_lock);
        if (ret != -ENOENT)
-               goto done;
+               goto out;
        ret = io_poll_cancel(ctx, sqe_addr, false);
-done:
-       if (!ret)
-               ret = success_ret;
-       io_cqring_fill_event(ctx, req->user_data, ret, 0);
-       io_commit_cqring(ctx);
-       spin_unlock_irqrestore(&ctx->completion_lock, flags);
-       io_cqring_ev_posted(ctx);
-
-       if (ret < 0)
-               req_set_fail_links(req);
+out:
+       spin_unlock(&ctx->completion_lock);
+       return ret;
 }
 
 static int io_async_cancel_prep(struct io_kiocb *req,
@@ -5779,7 +6229,8 @@ static int io_async_cancel_prep(struct io_kiocb *req,
                return -EINVAL;
        if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
                return -EINVAL;
-       if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
+       if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
+           sqe->splice_fd_in)
                return -EINVAL;
 
        req->cancel.addr = READ_ONCE(sqe->addr);
@@ -5793,18 +6244,9 @@ static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
        struct io_tctx_node *node;
        int ret;
 
-       /* tasks should wait for their io-wq threads, so safe w/o sync */
-       ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
-       spin_lock_irq(&ctx->completion_lock);
+       ret = io_try_cancel_userdata(req, sqe_addr);
        if (ret != -ENOENT)
                goto done;
-       ret = io_timeout_cancel(ctx, sqe_addr);
-       if (ret != -ENOENT)
-               goto done;
-       ret = io_poll_cancel(ctx, sqe_addr, false);
-       if (ret != -ENOENT)
-               goto done;
-       spin_unlock_irq(&ctx->completion_lock);
 
        /* slow path, try all io-wq's */
        io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
@@ -5817,17 +6259,10 @@ static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
                        break;
        }
        io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
-
-       spin_lock_irq(&ctx->completion_lock);
 done:
-       io_cqring_fill_event(ctx, req->user_data, ret, 0);
-       io_commit_cqring(ctx);
-       spin_unlock_irq(&ctx->completion_lock);
-       io_cqring_ev_posted(ctx);
-
        if (ret < 0)
-               req_set_fail_links(req);
-       io_put_req(req);
+               req_set_fail(req);
+       io_req_complete_post(req, ret, 0);
        return 0;
 }
 
@@ -5836,7 +6271,7 @@ static int io_rsrc_update_prep(struct io_kiocb *req,
 {
        if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
                return -EINVAL;
-       if (sqe->ioprio || sqe->rw_flags)
+       if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
                return -EINVAL;
 
        req->rsrc_update.offset = READ_ONCE(sqe->off);
@@ -5868,7 +6303,7 @@ static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
        mutex_unlock(&ctx->uring_lock);
 
        if (ret < 0)
-               req_set_fail_links(req);
+               req_set_fail(req);
        __io_req_complete(req, issue_flags, ret, 0);
        return 0;
 }
@@ -5944,6 +6379,12 @@ static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
                return io_renameat_prep(req, sqe);
        case IORING_OP_UNLINKAT:
                return io_unlinkat_prep(req, sqe);
+       case IORING_OP_MKDIRAT:
+               return io_mkdirat_prep(req, sqe);
+       case IORING_OP_SYMLINKAT:
+               return io_symlinkat_prep(req, sqe);
+       case IORING_OP_LINKAT:
+               return io_linkat_prep(req, sqe);
        }
 
        printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
@@ -5979,56 +6420,84 @@ static int io_req_prep_async(struct io_kiocb *req)
 
 static u32 io_get_sequence(struct io_kiocb *req)
 {
-       struct io_kiocb *pos;
-       struct io_ring_ctx *ctx = req->ctx;
-       u32 total_submitted, nr_reqs = 0;
+       u32 seq = req->ctx->cached_sq_head;
 
-       io_for_each_link(pos, req)
-               nr_reqs++;
-
-       total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
-       return total_submitted - nr_reqs;
+       /* need original cached_sq_head, but it was increased for each req */
+       io_for_each_link(req, req)
+               seq--;
+       return seq;
 }
 
-static int io_req_defer(struct io_kiocb *req)
+static bool io_drain_req(struct io_kiocb *req)
 {
+       struct io_kiocb *pos;
        struct io_ring_ctx *ctx = req->ctx;
        struct io_defer_entry *de;
        int ret;
        u32 seq;
 
+       if (req->flags & REQ_F_FAIL) {
+               io_req_complete_fail_submit(req);
+               return true;
+       }
+
+       /*
+        * If we need to drain a request in the middle of a link, drain the
+        * head request and the next request/link after the current link.
+        * Considering sequential execution of links, IOSQE_IO_DRAIN will be
+        * maintained for every request of our link.
+        */
+       if (ctx->drain_next) {
+               req->flags |= REQ_F_IO_DRAIN;
+               ctx->drain_next = false;
+       }
+       /* not interested in head, start from the first linked */
+       io_for_each_link(pos, req->link) {
+               if (pos->flags & REQ_F_IO_DRAIN) {
+                       ctx->drain_next = true;
+                       req->flags |= REQ_F_IO_DRAIN;
+                       break;
+               }
+       }
+
        /* Still need defer if there is pending req in defer list. */
        if (likely(list_empty_careful(&ctx->defer_list) &&
-               !(req->flags & REQ_F_IO_DRAIN)))
-               return 0;
+               !(req->flags & REQ_F_IO_DRAIN))) {
+               ctx->drain_active = false;
+               return false;
+       }
 
        seq = io_get_sequence(req);
        /* Still a chance to pass the sequence check */
        if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
-               return 0;
+               return false;
 
        ret = io_req_prep_async(req);
        if (ret)
-               return ret;
+               goto fail;
        io_prep_async_link(req);
        de = kmalloc(sizeof(*de), GFP_KERNEL);
-       if (!de)
-               return -ENOMEM;
+       if (!de) {
+               ret = -ENOMEM;
+fail:
+               io_req_complete_failed(req, ret);
+               return true;
+       }
 
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
        if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
-               spin_unlock_irq(&ctx->completion_lock);
+               spin_unlock(&ctx->completion_lock);
                kfree(de);
-               io_queue_async_work(req);
-               return -EIOCBQUEUED;
+               io_queue_async_work(req, NULL);
+               return true;
        }
 
        trace_io_uring_defer(ctx, req, req->user_data);
        de->req = req;
        de->seq = seq;
        list_add_tail(&de->list, &ctx->defer_list);
-       spin_unlock_irq(&ctx->completion_lock);
-       return -EIOCBQUEUED;
+       spin_unlock(&ctx->completion_lock);
+       return true;
 }
 
 static void io_clean_op(struct io_kiocb *req)
@@ -6045,7 +6514,6 @@ static void io_clean_op(struct io_kiocb *req)
                        kfree(req->sr_msg.kbuf);
                        break;
                }
-               req->flags &= ~REQ_F_BUFFER_SELECTED;
        }
 
        if (req->flags & REQ_F_NEED_CLEANUP) {
@@ -6057,8 +6525,8 @@ static void io_clean_op(struct io_kiocb *req)
                case IORING_OP_WRITE_FIXED:
                case IORING_OP_WRITE: {
                        struct io_async_rw *io = req->async_data;
-                       if (io->free_iovec)
-                               kfree(io->free_iovec);
+
+                       kfree(io->free_iovec);
                        break;
                        }
                case IORING_OP_RECVMSG:
@@ -6085,8 +6553,18 @@ static void io_clean_op(struct io_kiocb *req)
                case IORING_OP_UNLINKAT:
                        putname(req->unlink.filename);
                        break;
+               case IORING_OP_MKDIRAT:
+                       putname(req->mkdir.filename);
+                       break;
+               case IORING_OP_SYMLINKAT:
+                       putname(req->symlink.oldpath);
+                       putname(req->symlink.newpath);
+                       break;
+               case IORING_OP_LINKAT:
+                       putname(req->hardlink.oldpath);
+                       putname(req->hardlink.newpath);
+                       break;
                }
-               req->flags &= ~REQ_F_NEED_CLEANUP;
        }
        if ((req->flags & REQ_F_POLLED) && req->apoll) {
                kfree(req->apoll->double_poll);
@@ -6097,8 +6575,11 @@ static void io_clean_op(struct io_kiocb *req)
                struct io_uring_task *tctx = req->task->io_uring;
 
                atomic_dec(&tctx->inflight_tracked);
-               req->flags &= ~REQ_F_INFLIGHT;
        }
+       if (req->flags & REQ_F_CREDS)
+               put_cred(req->creds);
+
+       req->flags &= ~IO_REQ_CLEAN_FLAGS;
 }
 
 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
@@ -6107,8 +6588,8 @@ static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
        const struct cred *creds = NULL;
        int ret;
 
-       if (req->work.creds && req->work.creds != current_cred())
-               creds = override_creds(req->work.creds);
+       if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
+               creds = override_creds(req->creds);
 
        switch (req->opcode) {
        case IORING_OP_NOP:
@@ -6211,6 +6692,15 @@ static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
        case IORING_OP_UNLINKAT:
                ret = io_unlinkat(req, issue_flags);
                break;
+       case IORING_OP_MKDIRAT:
+               ret = io_mkdirat(req, issue_flags);
+               break;
+       case IORING_OP_SYMLINKAT:
+               ret = io_symlinkat(req, issue_flags);
+               break;
+       case IORING_OP_LINKAT:
+               ret = io_linkat(req, issue_flags);
+               break;
        default:
                ret = -EINVAL;
                break;
@@ -6218,25 +6708,21 @@ static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
 
        if (creds)
                revert_creds(creds);
-
        if (ret)
                return ret;
-
        /* If the op doesn't have a file, we're not polling for it */
-       if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
-               const bool in_async = io_wq_current_is_worker();
-
-               /* workqueue context doesn't hold uring_lock, grab it now */
-               if (in_async)
-                       mutex_lock(&ctx->uring_lock);
+       if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
+               io_iopoll_req_issued(req);
 
-               io_iopoll_req_issued(req, in_async);
+       return 0;
+}
 
-               if (in_async)
-                       mutex_unlock(&ctx->uring_lock);
-       }
+static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
+{
+       struct io_kiocb *req = container_of(work, struct io_kiocb, work);
 
-       return 0;
+       req = io_put_req_find_next(req);
+       return req ? &req->work : NULL;
 }
 
 static void io_wq_submit_work(struct io_wq_work *work)
@@ -6245,10 +6731,17 @@ static void io_wq_submit_work(struct io_wq_work *work)
        struct io_kiocb *timeout;
        int ret = 0;
 
+       /* one will be dropped by ->io_free_work() after returning to io-wq */
+       if (!(req->flags & REQ_F_REFCOUNT))
+               __io_req_set_refcount(req, 2);
+       else
+               req_ref_get(req);
+
        timeout = io_prep_linked_timeout(req);
        if (timeout)
                io_queue_linked_timeout(timeout);
 
+       /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
        if (work->flags & IO_WQ_WORK_CANCEL)
                ret = -ECANCELED;
 
@@ -6267,29 +6760,14 @@ static void io_wq_submit_work(struct io_wq_work *work)
        }
 
        /* avoid locking problems by failing it from a clean context */
-       if (ret) {
-               /* io-wq is going to take one down */
-               req_ref_get(req);
+       if (ret)
                io_req_task_queue_fail(req, ret);
-       }
 }
 
-#define FFS_ASYNC_READ         0x1UL
-#define FFS_ASYNC_WRITE                0x2UL
-#ifdef CONFIG_64BIT
-#define FFS_ISREG              0x4UL
-#else
-#define FFS_ISREG              0x0UL
-#endif
-#define FFS_MASK               ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
-
 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
-                                                     unsigned i)
+                                                      unsigned i)
 {
-       struct io_fixed_file *table_l2;
-
-       table_l2 = table->files[i >> IORING_FILE_TABLE_SHIFT];
-       return &table_l2[i & IORING_FILE_TABLE_MASK];
+       return &table->files[i];
 }
 
 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
@@ -6304,45 +6782,69 @@ static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file
 {
        unsigned long file_ptr = (unsigned long) file;
 
-       if (__io_file_supports_async(file, READ))
+       if (__io_file_supports_nowait(file, READ))
                file_ptr |= FFS_ASYNC_READ;
-       if (__io_file_supports_async(file, WRITE))
+       if (__io_file_supports_nowait(file, WRITE))
                file_ptr |= FFS_ASYNC_WRITE;
        if (S_ISREG(file_inode(file)->i_mode))
                file_ptr |= FFS_ISREG;
        file_slot->file_ptr = file_ptr;
 }
 
-static struct file *io_file_get(struct io_submit_state *state,
-                               struct io_kiocb *req, int fd, bool fixed)
+static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
+                                            struct io_kiocb *req, int fd)
 {
-       struct io_ring_ctx *ctx = req->ctx;
        struct file *file;
+       unsigned long file_ptr;
 
-       if (fixed) {
-               unsigned long file_ptr;
+       if (unlikely((unsigned int)fd >= ctx->nr_user_files))
+               return NULL;
+       fd = array_index_nospec(fd, ctx->nr_user_files);
+       file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
+       file = (struct file *) (file_ptr & FFS_MASK);
+       file_ptr &= ~FFS_MASK;
+       /* mask in overlapping REQ_F and FFS bits */
+       req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
+       io_req_set_rsrc_node(req);
+       return file;
+}
 
-               if (unlikely((unsigned int)fd >= ctx->nr_user_files))
-                       return NULL;
-               fd = array_index_nospec(fd, ctx->nr_user_files);
-               file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
-               file = (struct file *) (file_ptr & FFS_MASK);
-               file_ptr &= ~FFS_MASK;
-               /* mask in overlapping REQ_F and FFS bits */
-               req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
-               io_req_set_rsrc_node(req);
-       } else {
-               trace_io_uring_file_get(ctx, fd);
-               file = __io_file_get(state, fd);
+static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
+                                      struct io_kiocb *req, int fd)
+{
+       struct file *file = fget(fd);
 
-               /* we don't allow fixed io_uring files */
-               if (file && unlikely(file->f_op == &io_uring_fops))
-                       io_req_track_inflight(req);
-       }
+       trace_io_uring_file_get(ctx, fd);
 
+       /* we don't allow fixed io_uring files */
+       if (file && unlikely(file->f_op == &io_uring_fops))
+               io_req_track_inflight(req);
        return file;
 }
 
+static inline struct file *io_file_get(struct io_ring_ctx *ctx,
+                                      struct io_kiocb *req, int fd, bool fixed)
+{
+       if (fixed)
+               return io_file_get_fixed(ctx, req, fd);
+       else
+               return io_file_get_normal(ctx, req, fd);
+}
+
+static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
+{
+       struct io_kiocb *prev = req->timeout.prev;
+       int ret;
+
+       if (prev) {
+               ret = io_try_cancel_userdata(req, prev->user_data);
+               io_req_complete_post(req, ret ?: -ETIME, 0);
+               io_put_req(prev);
+       } else {
+               io_req_complete_post(req, -ETIME, 0);
+       }
+}
+
 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
 {
        struct io_timeout_data *data = container_of(timer,
@@ -6351,7 +6853,7 @@ static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
        struct io_ring_ctx *ctx = req->ctx;
        unsigned long flags;
 
-       spin_lock_irqsave(&ctx->completion_lock, flags);
+       spin_lock_irqsave(&ctx->timeout_lock, flags);
        prev = req->timeout.head;
        req->timeout.head = NULL;
 
@@ -6364,15 +6866,12 @@ static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
                if (!req_ref_inc_not_zero(prev))
                        prev = NULL;
        }
-       spin_unlock_irqrestore(&ctx->completion_lock, flags);
+       list_del(&req->timeout.list);
+       req->timeout.prev = prev;
+       spin_unlock_irqrestore(&ctx->timeout_lock, flags);
 
-       if (prev) {
-               io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
-               io_put_req_deferred(prev, 1);
-               io_put_req_deferred(req, 1);
-       } else {
-               io_req_complete_post(req, -ETIME, 0);
-       }
+       req->io_task_work.func = io_req_task_link_timeout;
+       io_req_task_work_add(req);
        return HRTIMER_NORESTART;
 }
 
@@ -6380,7 +6879,7 @@ static void io_queue_linked_timeout(struct io_kiocb *req)
 {
        struct io_ring_ctx *ctx = req->ctx;
 
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock_irq(&ctx->timeout_lock);
        /*
         * If the back reference is NULL, then our linked request finished
         * before we got a chance to setup the timer
@@ -6391,31 +6890,20 @@ static void io_queue_linked_timeout(struct io_kiocb *req)
                data->timer.function = io_link_timeout_fn;
                hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
                                data->mode);
+               list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
        }
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_unlock_irq(&ctx->timeout_lock);
        /* drop submission reference */
        io_put_req(req);
 }
 
-static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
-{
-       struct io_kiocb *nxt = req->link;
-
-       if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
-           nxt->opcode != IORING_OP_LINK_TIMEOUT)
-               return NULL;
-
-       nxt->timeout.head = req;
-       nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
-       req->flags |= REQ_F_LINK_TIMEOUT;
-       return nxt;
-}
-
 static void __io_queue_sqe(struct io_kiocb *req)
+       __must_hold(&req->ctx->uring_lock)
 {
-       struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
+       struct io_kiocb *linked_timeout;
        int ret;
 
+issue_sqe:
        ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
 
        /*
@@ -6423,49 +6911,60 @@ static void __io_queue_sqe(struct io_kiocb *req)
         * doesn't support non-blocking read/write attempts
         */
        if (likely(!ret)) {
-               /* drop submission reference */
                if (req->flags & REQ_F_COMPLETE_INLINE) {
                        struct io_ring_ctx *ctx = req->ctx;
-                       struct io_comp_state *cs = &ctx->submit_state.comp;
+                       struct io_submit_state *state = &ctx->submit_state;
 
-                       cs->reqs[cs->nr++] = req;
-                       if (cs->nr == ARRAY_SIZE(cs->reqs))
-                               io_submit_flush_completions(cs, ctx);
-               } else {
-                       io_put_req(req);
+                       state->compl_reqs[state->compl_nr++] = req;
+                       if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
+                               io_submit_flush_completions(ctx);
+                       return;
                }
+
+               linked_timeout = io_prep_linked_timeout(req);
+               if (linked_timeout)
+                       io_queue_linked_timeout(linked_timeout);
        } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
-               if (!io_arm_poll_handler(req)) {
+               linked_timeout = io_prep_linked_timeout(req);
+
+               switch (io_arm_poll_handler(req)) {
+               case IO_APOLL_READY:
+                       if (linked_timeout)
+                               io_unprep_linked_timeout(req);
+                       goto issue_sqe;
+               case IO_APOLL_ABORTED:
                        /*
                         * Queued up for async execution, worker will release
                         * submit reference when the iocb is actually submitted.
                         */
-                       io_queue_async_work(req);
+                       io_queue_async_work(req, NULL);
+                       break;
                }
+
+               if (linked_timeout)
+                       io_queue_linked_timeout(linked_timeout);
        } else {
                io_req_complete_failed(req, ret);
        }
-       if (linked_timeout)
-               io_queue_linked_timeout(linked_timeout);
 }
 
-static void io_queue_sqe(struct io_kiocb *req)
+static inline void io_queue_sqe(struct io_kiocb *req)
+       __must_hold(&req->ctx->uring_lock)
 {
-       int ret;
+       if (unlikely(req->ctx->drain_active) && io_drain_req(req))
+               return;
 
-       ret = io_req_defer(req);
-       if (ret) {
-               if (ret != -EIOCBQUEUED) {
-fail_req:
-                       io_req_complete_failed(req, ret);
-               }
-       } else if (req->flags & REQ_F_FORCE_ASYNC) {
-               ret = io_req_prep_async(req);
-               if (unlikely(ret))
-                       goto fail_req;
-               io_queue_async_work(req);
-       } else {
+       if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
                __io_queue_sqe(req);
+       } else if (req->flags & REQ_F_FAIL) {
+               io_req_complete_fail_submit(req);
+       } else {
+               int ret = io_req_prep_async(req);
+
+               if (unlikely(ret))
+                       io_req_complete_failed(req, ret);
+               else
+                       io_queue_async_work(req, NULL);
        }
 }
 
@@ -6478,7 +6977,7 @@ static inline bool io_check_restriction(struct io_ring_ctx *ctx,
                                        struct io_kiocb *req,
                                        unsigned int sqe_flags)
 {
-       if (!ctx->restricted)
+       if (likely(!ctx->restricted))
                return true;
 
        if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
@@ -6497,44 +6996,42 @@ static inline bool io_check_restriction(struct io_ring_ctx *ctx,
 
 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
                       const struct io_uring_sqe *sqe)
+       __must_hold(&ctx->uring_lock)
 {
        struct io_submit_state *state;
        unsigned int sqe_flags;
        int personality, ret = 0;
 
+       /* req is partially pre-initialised, see io_preinit_req() */
        req->opcode = READ_ONCE(sqe->opcode);
        /* same numerical values with corresponding REQ_F_*, safe to copy */
        req->flags = sqe_flags = READ_ONCE(sqe->flags);
        req->user_data = READ_ONCE(sqe->user_data);
-       req->async_data = NULL;
        req->file = NULL;
-       req->ctx = ctx;
-       req->link = NULL;
        req->fixed_rsrc_refs = NULL;
-       /* one is dropped after submission, the other at completion */
-       atomic_set(&req->refs, 2);
        req->task = current;
-       req->result = 0;
-       req->work.creds = NULL;
 
        /* enforce forwards compatibility on users */
        if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
                return -EINVAL;
        if (unlikely(req->opcode >= IORING_OP_LAST))
                return -EINVAL;
-       if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
+       if (!io_check_restriction(ctx, req, sqe_flags))
                return -EACCES;
 
        if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
            !io_op_defs[req->opcode].buffer_select)
                return -EOPNOTSUPP;
+       if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
+               ctx->drain_active = true;
 
        personality = READ_ONCE(sqe->personality);
        if (personality) {
-               req->work.creds = xa_load(&ctx->personalities, personality);
-               if (!req->work.creds)
+               req->creds = xa_load(&ctx->personalities, personality);
+               if (!req->creds)
                        return -EINVAL;
-               get_cred(req->work.creds);
+               get_cred(req->creds);
+               req->flags |= REQ_F_CREDS;
        }
        state = &ctx->submit_state;
 
@@ -6549,9 +7046,8 @@ static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
        }
 
        if (io_op_defs[req->opcode].needs_file) {
-               bool fixed = req->flags & REQ_F_FIXED_FILE;
-
-               req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
+               req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
+                                       (sqe_flags & IOSQE_FIXED_FILE));
                if (unlikely(!req->file))
                        ret = -EBADF;
        }
@@ -6562,6 +7058,7 @@ static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
 
 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
                         const struct io_uring_sqe *sqe)
+       __must_hold(&ctx->uring_lock)
 {
        struct io_submit_link *link = &ctx->submit_state.link;
        int ret;
@@ -6569,22 +7066,38 @@ static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
        ret = io_init_req(ctx, req, sqe);
        if (unlikely(ret)) {
 fail_req:
+               /* fail even hard links since we don't submit */
                if (link->head) {
-                       /* fail even hard links since we don't submit */
-                       link->head->flags |= REQ_F_FAIL_LINK;
-                       io_req_complete_failed(link->head, -ECANCELED);
-                       link->head = NULL;
+                       /*
+                        * we can judge a link req is failed or cancelled by if
+                        * REQ_F_FAIL is set, but the head is an exception since
+                        * it may be set REQ_F_FAIL because of other req's failure
+                        * so let's leverage req->result to distinguish if a head
+                        * is set REQ_F_FAIL because of its failure or other req's
+                        * failure so that we can set the correct ret code for it.
+                        * init result here to avoid affecting the normal path.
+                        */
+                       if (!(link->head->flags & REQ_F_FAIL))
+                               req_fail_link_node(link->head, -ECANCELED);
+               } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
+                       /*
+                        * the current req is a normal req, we should return
+                        * error and thus break the submittion loop.
+                        */
+                       io_req_complete_failed(req, ret);
+                       return ret;
                }
-               io_req_complete_failed(req, ret);
-               return ret;
+               req_fail_link_node(req, ret);
+       } else {
+               ret = io_req_prep(req, sqe);
+               if (unlikely(ret))
+                       goto fail_req;
        }
-       ret = io_req_prep(req, sqe);
-       if (unlikely(ret))
-               goto fail_req;
 
        /* don't need @sqe from now on */
-       trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
-                               true, ctx->flags & IORING_SETUP_SQPOLL);
+       trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
+                                 req->flags, true,
+                                 ctx->flags & IORING_SETUP_SQPOLL);
 
        /*
         * If we already have a head request, queue this one for async
@@ -6596,34 +7109,24 @@ fail_req:
        if (link->head) {
                struct io_kiocb *head = link->head;
 
-               /*
-                * Taking sequential execution of a link, draining both sides
-                * of the link also fullfils IOSQE_IO_DRAIN semantics for all
-                * requests in the link. So, it drains the head and the
-                * next after the link request. The last one is done via
-                * drain_next flag to persist the effect across calls.
-                */
-               if (req->flags & REQ_F_IO_DRAIN) {
-                       head->flags |= REQ_F_IO_DRAIN;
-                       ctx->drain_next = 1;
+               if (!(req->flags & REQ_F_FAIL)) {
+                       ret = io_req_prep_async(req);
+                       if (unlikely(ret)) {
+                               req_fail_link_node(req, ret);
+                               if (!(head->flags & REQ_F_FAIL))
+                                       req_fail_link_node(head, -ECANCELED);
+                       }
                }
-               ret = io_req_prep_async(req);
-               if (unlikely(ret))
-                       goto fail_req;
                trace_io_uring_link(ctx, req, head);
                link->last->link = req;
                link->last = req;
 
                /* last request of a link, enqueue the link */
                if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
-                       io_queue_sqe(head);
                        link->head = NULL;
+                       io_queue_sqe(head);
                }
        } else {
-               if (unlikely(ctx->drain_next)) {
-                       req->flags |= REQ_F_IO_DRAIN;
-                       ctx->drain_next = 0;
-               }
                if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
                        link->head = req;
                        link->last = req;
@@ -6643,11 +7146,10 @@ static void io_submit_state_end(struct io_submit_state *state,
 {
        if (state->link.head)
                io_queue_sqe(state->link.head);
-       if (state->comp.nr)
-               io_submit_flush_completions(&state->comp, ctx);
+       if (state->compl_nr)
+               io_submit_flush_completions(ctx);
        if (state->plug_started)
                blk_finish_plug(&state->plug);
-       io_state_file_put(state);
 }
 
 /*
@@ -6675,7 +7177,7 @@ static void io_commit_sqring(struct io_ring_ctx *ctx)
 }
 
 /*
- * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
+ * Fetch an sqe, if one is available. Note this returns a pointer to memory
  * that is mapped by userspace. This means that care needs to be taken to
  * ensure that reads are stable, as we cannot rely on userspace always
  * being a good citizen. If members of the sqe are validated and then later
@@ -6684,8 +7186,8 @@ static void io_commit_sqring(struct io_ring_ctx *ctx)
  */
 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
 {
-       u32 *sq_array = ctx->sq_array;
-       unsigned head;
+       unsigned head, mask = ctx->sq_entries - 1;
+       unsigned sq_idx = ctx->cached_sq_head++ & mask;
 
        /*
         * The cached sq head (or cq tail) serves two purposes:
@@ -6695,30 +7197,29 @@ static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
         * 2) allows the kernel side to track the head on its own, even
         *    though the application is the one updating it.
         */
-       head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
+       head = READ_ONCE(ctx->sq_array[sq_idx]);
        if (likely(head < ctx->sq_entries))
                return &ctx->sq_sqes[head];
 
        /* drop invalid entries */
-       ctx->cached_sq_dropped++;
-       WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
+       ctx->cq_extra--;
+       WRITE_ONCE(ctx->rings->sq_dropped,
+                  READ_ONCE(ctx->rings->sq_dropped) + 1);
        return NULL;
 }
 
 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
+       __must_hold(&ctx->uring_lock)
 {
        int submitted = 0;
 
        /* make sure SQ entry isn't read before tail */
        nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
-
        if (!percpu_ref_tryget_many(&ctx->refs, nr))
                return -EAGAIN;
+       io_get_task_refs(nr);
 
-       percpu_counter_add(&current->io_uring->inflight, nr);
-       refcount_add(nr, &current->usage);
        io_submit_state_start(&ctx->submit_state, nr);
-
        while (submitted < nr) {
                const struct io_uring_sqe *sqe;
                struct io_kiocb *req;
@@ -6731,7 +7232,7 @@ static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
                }
                sqe = io_get_sqe(ctx);
                if (unlikely(!sqe)) {
-                       kmem_cache_free(req_cachep, req);
+                       list_add(&req->inflight_entry, &ctx->submit_state.free_list);
                        break;
                }
                /* will complete beyond this point, count as submitted */
@@ -6742,12 +7243,10 @@ static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
 
        if (unlikely(submitted != nr)) {
                int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
-               struct io_uring_task *tctx = current->io_uring;
                int unused = nr - ref_used;
 
+               current->io_uring->cached_refs += unused;
                percpu_ref_put_many(&ctx->refs, unused);
-               percpu_counter_sub(&tctx->inflight, unused);
-               put_task_struct_many(current, unused);
        }
 
        io_submit_state_end(&ctx->submit_state, ctx);
@@ -6757,19 +7256,26 @@ static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
        return submitted;
 }
 
+static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
+{
+       return READ_ONCE(sqd->state);
+}
+
 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
 {
        /* Tell userspace we may need a wakeup call */
-       spin_lock_irq(&ctx->completion_lock);
-       ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
+       WRITE_ONCE(ctx->rings->sq_flags,
+                  ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
+       spin_unlock(&ctx->completion_lock);
 }
 
 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
 {
-       spin_lock_irq(&ctx->completion_lock);
-       ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
+       WRITE_ONCE(ctx->rings->sq_flags,
+                  ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
+       spin_unlock(&ctx->completion_lock);
 }
 
 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
@@ -6779,11 +7285,15 @@ static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
 
        to_submit = io_sqring_entries(ctx);
        /* if we're handling multiple rings, cap submit size for fairness */
-       if (cap_entries && to_submit > 8)
-               to_submit = 8;
+       if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
+               to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
 
        if (!list_empty(&ctx->iopoll_list) || to_submit) {
                unsigned nr_events = 0;
+               const struct cred *creds = NULL;
+
+               if (ctx->sq_creds != current_cred())
+                       creds = override_creds(ctx->sq_creds);
 
                mutex_lock(&ctx->uring_lock);
                if (!list_empty(&ctx->iopoll_list))
@@ -6797,10 +7307,12 @@ static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
                    !(ctx->flags & IORING_SETUP_R_DISABLED))
                        ret = io_submit_sqes(ctx, to_submit);
                mutex_unlock(&ctx->uring_lock);
-       }
 
-       if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
-               wake_up(&ctx->sqo_sq_wait);
+               if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
+                       wake_up(&ctx->sqo_sq_wait);
+               if (creds)
+                       revert_creds(creds);
+       }
 
        return ret;
 }
@@ -6815,6 +7327,22 @@ static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
        sqd->sq_thread_idle = sq_thread_idle;
 }
 
+static bool io_sqd_handle_event(struct io_sq_data *sqd)
+{
+       bool did_sig = false;
+       struct ksignal ksig;
+
+       if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
+           signal_pending(current)) {
+               mutex_unlock(&sqd->lock);
+               if (signal_pending(current))
+                       did_sig = get_signal(&ksig);
+               cond_resched();
+               mutex_lock(&sqd->lock);
+       }
+       return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
+}
+
 static int io_sq_thread(void *data)
 {
        struct io_sq_data *sqd = data;
@@ -6833,48 +7361,26 @@ static int io_sq_thread(void *data)
        current->flags |= PF_NO_SETAFFINITY;
 
        mutex_lock(&sqd->lock);
-       /* a user may had exited before the thread started */
-       io_run_task_work_head(&sqd->park_task_work);
-
-       while (!test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state)) {
-               int ret;
-               bool cap_entries, sqt_spin, needs_sched;
-
-               if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
-                   signal_pending(current)) {
-                       bool did_sig = false;
-
-                       mutex_unlock(&sqd->lock);
-                       if (signal_pending(current)) {
-                               struct ksignal ksig;
+       while (1) {
+               bool cap_entries, sqt_spin = false;
 
-                               did_sig = get_signal(&ksig);
-                       }
-                       cond_resched();
-                       mutex_lock(&sqd->lock);
-                       io_run_task_work();
-                       io_run_task_work_head(&sqd->park_task_work);
-                       if (did_sig)
+               if (io_sqd_events_pending(sqd) || signal_pending(current)) {
+                       if (io_sqd_handle_event(sqd))
                                break;
                        timeout = jiffies + sqd->sq_thread_idle;
-                       continue;
                }
-               sqt_spin = false;
+
                cap_entries = !list_is_singular(&sqd->ctx_list);
                list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
-                       const struct cred *creds = NULL;
+                       int ret = __io_sq_thread(ctx, cap_entries);
 
-                       if (ctx->sq_creds != current_cred())
-                               creds = override_creds(ctx->sq_creds);
-                       ret = __io_sq_thread(ctx, cap_entries);
-                       if (creds)
-                               revert_creds(creds);
                        if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
                                sqt_spin = true;
                }
+               if (io_run_task_work())
+                       sqt_spin = true;
 
                if (sqt_spin || !time_after(jiffies, timeout)) {
-                       io_run_task_work();
                        cond_resched();
                        if (sqt_spin)
                                timeout = jiffies + sqd->sq_thread_idle;
@@ -6882,12 +7388,12 @@ static int io_sq_thread(void *data)
                }
 
                prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
-               if (!test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state)) {
-                       list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
-                               io_ring_set_wakeup_flag(ctx);
+               if (!io_sqd_events_pending(sqd) && !current->task_works) {
+                       bool needs_sched = true;
 
-                       needs_sched = true;
                        list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
+                               io_ring_set_wakeup_flag(ctx);
+
                                if ((ctx->flags & IORING_SETUP_IOPOLL) &&
                                    !list_empty_careful(&ctx->iopoll_list)) {
                                        needs_sched = false;
@@ -6909,16 +7415,14 @@ static int io_sq_thread(void *data)
                }
 
                finish_wait(&sqd->wait, &wait);
-               io_run_task_work_head(&sqd->park_task_work);
                timeout = jiffies + sqd->sq_thread_idle;
        }
 
-       io_uring_cancel_sqpoll(sqd);
+       io_uring_cancel_generic(true, sqd);
        sqd->thread = NULL;
        list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
                io_ring_set_wakeup_flag(ctx);
        io_run_task_work();
-       io_run_task_work_head(&sqd->park_task_work);
        mutex_unlock(&sqd->lock);
 
        complete(&sqd->exited);
@@ -6928,21 +7432,21 @@ static int io_sq_thread(void *data)
 struct io_wait_queue {
        struct wait_queue_entry wq;
        struct io_ring_ctx *ctx;
-       unsigned to_wait;
+       unsigned cq_tail;
        unsigned nr_timeouts;
 };
 
 static inline bool io_should_wake(struct io_wait_queue *iowq)
 {
        struct io_ring_ctx *ctx = iowq->ctx;
+       int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
 
        /*
         * Wake up if we have enough events, or if a timeout occurred since we
         * started waiting. For timeouts, we always want to return to userspace,
         * regardless of event count.
         */
-       return io_cqring_events(ctx) >= iowq->to_wait ||
-                       atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
+       return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
 }
 
 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
@@ -6955,7 +7459,7 @@ static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
         * Cannot safely flush overflowed CQEs from here, ensure we wake up
         * the task, and the next invocation will do it.
         */
-       if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
+       if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
                return autoremove_wake_function(curr, mode, wake_flags, key);
        return -1;
 }
@@ -6983,7 +7487,7 @@ static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
        if (ret || io_should_wake(iowq))
                return ret;
        /* let the caller flush overflows, retry */
-       if (test_bit(0, &ctx->cq_check_overflow))
+       if (test_bit(0, &ctx->check_cq_overflow))
                return 1;
 
        *timeout = schedule_timeout(*timeout);
@@ -6998,21 +7502,13 @@ static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
                          const sigset_t __user *sig, size_t sigsz,
                          struct __kernel_timespec __user *uts)
 {
-       struct io_wait_queue iowq = {
-               .wq = {
-                       .private        = current,
-                       .func           = io_wake_function,
-                       .entry          = LIST_HEAD_INIT(iowq.wq.entry),
-               },
-               .ctx            = ctx,
-               .to_wait        = min_events,
-       };
+       struct io_wait_queue iowq;
        struct io_rings *rings = ctx->rings;
        signed long timeout = MAX_SCHEDULE_TIMEOUT;
        int ret;
 
        do {
-               io_cqring_overflow_flush(ctx, false);
+               io_cqring_overflow_flush(ctx);
                if (io_cqring_events(ctx) >= min_events)
                        return 0;
                if (!io_run_task_work())
@@ -7040,18 +7536,24 @@ static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
                timeout = timespec64_to_jiffies(&ts);
        }
 
+       init_waitqueue_func_entry(&iowq.wq, io_wake_function);
+       iowq.wq.private = current;
+       INIT_LIST_HEAD(&iowq.wq.entry);
+       iowq.ctx = ctx;
        iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
+       iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
+
        trace_io_uring_cqring_wait(ctx, min_events);
        do {
                /* if we can't even flush overflow, don't wait for more */
-               if (!io_cqring_overflow_flush(ctx, false)) {
+               if (!io_cqring_overflow_flush(ctx)) {
                        ret = -EBUSY;
                        break;
                }
-               prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
+               prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
                                                TASK_INTERRUPTIBLE);
                ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
-               finish_wait(&ctx->wait, &iowq.wq);
+               finish_wait(&ctx->cq_wait, &iowq.wq);
                cond_resched();
        } while (ret > 0);
 
@@ -7060,24 +7562,36 @@ static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
        return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
 }
 
-static void io_free_file_tables(struct io_file_table *table, unsigned nr_files)
+static void io_free_page_table(void **table, size_t size)
 {
-       unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
+       unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
 
        for (i = 0; i < nr_tables; i++)
-               kfree(table->files[i]);
-       kfree(table->files);
-       table->files = NULL;
+               kfree(table[i]);
+       kfree(table);
 }
 
-static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
+static void **io_alloc_page_table(size_t size)
 {
-       spin_lock_bh(&ctx->rsrc_ref_lock);
-}
+       unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
+       size_t init_size = size;
+       void **table;
 
-static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
-{
-       spin_unlock_bh(&ctx->rsrc_ref_lock);
+       table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
+       if (!table)
+               return NULL;
+
+       for (i = 0; i < nr_tables; i++) {
+               unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
+
+               table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
+               if (!table[i]) {
+                       io_free_page_table(table, init_size);
+                       return NULL;
+               }
+               size -= this_size;
+       }
+       return table;
 }
 
 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
@@ -7086,6 +7600,50 @@ static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
        kfree(ref_node);
 }
 
+static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
+{
+       struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
+       struct io_ring_ctx *ctx = node->rsrc_data->ctx;
+       unsigned long flags;
+       bool first_add = false;
+
+       spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
+       node->done = true;
+
+       while (!list_empty(&ctx->rsrc_ref_list)) {
+               node = list_first_entry(&ctx->rsrc_ref_list,
+                                           struct io_rsrc_node, node);
+               /* recycle ref nodes in order */
+               if (!node->done)
+                       break;
+               list_del(&node->node);
+               first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
+       }
+       spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
+
+       if (first_add)
+               mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
+}
+
+static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
+{
+       struct io_rsrc_node *ref_node;
+
+       ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
+       if (!ref_node)
+               return NULL;
+
+       if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
+                           0, GFP_KERNEL)) {
+               kfree(ref_node);
+               return NULL;
+       }
+       INIT_LIST_HEAD(&ref_node->node);
+       INIT_LIST_HEAD(&ref_node->rsrc_list);
+       ref_node->done = false;
+       return ref_node;
+}
+
 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
                                struct io_rsrc_data *data_to_kill)
 {
@@ -7096,9 +7654,9 @@ static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
                struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
 
                rsrc_node->rsrc_data = data_to_kill;
-               io_rsrc_ref_lock(ctx);
+               spin_lock_irq(&ctx->rsrc_ref_lock);
                list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
-               io_rsrc_ref_unlock(ctx);
+               spin_unlock_irq(&ctx->rsrc_ref_lock);
 
                atomic_inc(&data_to_kill->refs);
                percpu_ref_kill(&rsrc_node->refs);
@@ -7137,17 +7695,19 @@ static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ct
                /* kill initial ref, already quiesced if zero */
                if (atomic_dec_and_test(&data->refs))
                        break;
+               mutex_unlock(&ctx->uring_lock);
                flush_delayed_work(&ctx->rsrc_put_work);
                ret = wait_for_completion_interruptible(&data->done);
-               if (!ret)
+               if (!ret) {
+                       mutex_lock(&ctx->uring_lock);
                        break;
+               }
 
                atomic_inc(&data->refs);
                /* wait for all works potentially completing data->done */
                flush_delayed_work(&ctx->rsrc_put_work);
                reinit_completion(&data->done);
 
-               mutex_unlock(&ctx->uring_lock);
                ret = io_run_task_work_sig();
                mutex_lock(&ctx->uring_lock);
        } while (ret >= 0);
@@ -7156,33 +7716,74 @@ static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ct
        return ret;
 }
 
+static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
+{
+       unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
+       unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
+
+       return &data->tags[table_idx][off];
+}
+
 static void io_rsrc_data_free(struct io_rsrc_data *data)
 {
-       kvfree(data->tags);
+       size_t size = data->nr * sizeof(data->tags[0][0]);
+
+       if (data->tags)
+               io_free_page_table((void **)data->tags, size);
        kfree(data);
 }
 
-static struct io_rsrc_data *io_rsrc_data_alloc(struct io_ring_ctx *ctx,
-                                              rsrc_put_fn *do_put,
-                                              unsigned nr)
+static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
+                             u64 __user *utags, unsigned nr,
+                             struct io_rsrc_data **pdata)
 {
        struct io_rsrc_data *data;
+       int ret = -ENOMEM;
+       unsigned i;
 
        data = kzalloc(sizeof(*data), GFP_KERNEL);
        if (!data)
-               return NULL;
-
-       data->tags = kvcalloc(nr, sizeof(*data->tags), GFP_KERNEL);
+               return -ENOMEM;
+       data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
        if (!data->tags) {
                kfree(data);
-               return NULL;
+               return -ENOMEM;
        }
 
-       atomic_set(&data->refs, 1);
+       data->nr = nr;
        data->ctx = ctx;
        data->do_put = do_put;
+       if (utags) {
+               ret = -EFAULT;
+               for (i = 0; i < nr; i++) {
+                       u64 *tag_slot = io_get_tag_slot(data, i);
+
+                       if (copy_from_user(tag_slot, &utags[i],
+                                          sizeof(*tag_slot)))
+                               goto fail;
+               }
+       }
+
+       atomic_set(&data->refs, 1);
        init_completion(&data->done);
-       return data;
+       *pdata = data;
+       return 0;
+fail:
+       io_rsrc_data_free(data);
+       return ret;
+}
+
+static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
+{
+       table->files = kvcalloc(nr_files, sizeof(table->files[0]),
+                               GFP_KERNEL_ACCOUNT);
+       return !!table->files;
+}
+
+static void io_free_file_tables(struct io_file_table *table)
+{
+       kvfree(table->files);
+       table->files = NULL;
 }
 
 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
@@ -7206,7 +7807,7 @@ static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
                        fput(file);
        }
 #endif
-       io_free_file_tables(&ctx->file_table, ctx->nr_user_files);
+       io_free_file_tables(&ctx->file_table);
        io_rsrc_data_free(ctx->file_data);
        ctx->file_data = NULL;
        ctx->nr_user_files = 0;
@@ -7446,31 +8047,6 @@ static int io_sqe_files_scm(struct io_ring_ctx *ctx)
 }
 #endif
 
-static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
-{
-       unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
-
-       table->files = kcalloc(nr_tables, sizeof(*table->files), GFP_KERNEL);
-       if (!table->files)
-               return false;
-
-       for (i = 0; i < nr_tables; i++) {
-               unsigned int this_files = min(nr_files, IORING_MAX_FILES_TABLE);
-
-               table->files[i] = kcalloc(this_files, sizeof(*table->files[i]),
-                                       GFP_KERNEL);
-               if (!table->files[i])
-                       break;
-               nr_files -= this_files;
-       }
-
-       if (i == nr_tables)
-               return true;
-
-       io_free_file_tables(table, nr_tables * IORING_MAX_FILES_TABLE);
-       return false;
-}
-
 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
 {
        struct file *file = prsrc->file;
@@ -7545,86 +8121,42 @@ static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
 
                if (prsrc->tag) {
                        bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
-                       unsigned long flags;
 
                        io_ring_submit_lock(ctx, lock_ring);
-                       spin_lock_irqsave(&ctx->completion_lock, flags);
+                       spin_lock(&ctx->completion_lock);
                        io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
                        ctx->cq_extra++;
                        io_commit_cqring(ctx);
-                       spin_unlock_irqrestore(&ctx->completion_lock, flags);
+                       spin_unlock(&ctx->completion_lock);
                        io_cqring_ev_posted(ctx);
                        io_ring_submit_unlock(ctx, lock_ring);
                }
 
                rsrc_data->do_put(ctx, prsrc);
-               kfree(prsrc);
-       }
-
-       io_rsrc_node_destroy(ref_node);
-       if (atomic_dec_and_test(&rsrc_data->refs))
-               complete(&rsrc_data->done);
-}
-
-static void io_rsrc_put_work(struct work_struct *work)
-{
-       struct io_ring_ctx *ctx;
-       struct llist_node *node;
-
-       ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
-       node = llist_del_all(&ctx->rsrc_put_llist);
-
-       while (node) {
-               struct io_rsrc_node *ref_node;
-               struct llist_node *next = node->next;
-
-               ref_node = llist_entry(node, struct io_rsrc_node, llist);
-               __io_rsrc_put_work(ref_node);
-               node = next;
-       }
-}
-
-static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
-{
-       struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
-       struct io_ring_ctx *ctx = node->rsrc_data->ctx;
-       bool first_add = false;
-
-       io_rsrc_ref_lock(ctx);
-       node->done = true;
-
-       while (!list_empty(&ctx->rsrc_ref_list)) {
-               node = list_first_entry(&ctx->rsrc_ref_list,
-                                           struct io_rsrc_node, node);
-               /* recycle ref nodes in order */
-               if (!node->done)
-                       break;
-               list_del(&node->node);
-               first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
+               kfree(prsrc);
        }
-       io_rsrc_ref_unlock(ctx);
 
-       if (first_add)
-               mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
+       io_rsrc_node_destroy(ref_node);
+       if (atomic_dec_and_test(&rsrc_data->refs))
+               complete(&rsrc_data->done);
 }
 
-static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
+static void io_rsrc_put_work(struct work_struct *work)
 {
-       struct io_rsrc_node *ref_node;
+       struct io_ring_ctx *ctx;
+       struct llist_node *node;
 
-       ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
-       if (!ref_node)
-               return NULL;
+       ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
+       node = llist_del_all(&ctx->rsrc_put_llist);
 
-       if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
-                           0, GFP_KERNEL)) {
-               kfree(ref_node);
-               return NULL;
+       while (node) {
+               struct io_rsrc_node *ref_node;
+               struct llist_node *next = node->next;
+
+               ref_node = llist_entry(node, struct io_rsrc_node, llist);
+               __io_rsrc_put_work(ref_node);
+               node = next;
        }
-       INIT_LIST_HEAD(&ref_node->node);
-       INIT_LIST_HEAD(&ref_node->rsrc_list);
-       ref_node->done = false;
-       return ref_node;
 }
 
 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
@@ -7634,7 +8166,6 @@ static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
        struct file *file;
        int fd, ret;
        unsigned i;
-       struct io_rsrc_data *file_data;
 
        if (ctx->file_data)
                return -EBUSY;
@@ -7642,30 +8173,29 @@ static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
                return -EINVAL;
        if (nr_args > IORING_MAX_FIXED_FILES)
                return -EMFILE;
+       if (nr_args > rlimit(RLIMIT_NOFILE))
+               return -EMFILE;
        ret = io_rsrc_node_switch_start(ctx);
        if (ret)
                return ret;
+       ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
+                                &ctx->file_data);
+       if (ret)
+               return ret;
 
-       file_data = io_rsrc_data_alloc(ctx, io_rsrc_file_put, nr_args);
-       if (!file_data)
-               return -ENOMEM;
-       ctx->file_data = file_data;
        ret = -ENOMEM;
        if (!io_alloc_file_tables(&ctx->file_table, nr_args))
                goto out_free;
 
        for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
-               u64 tag = 0;
-
-               if ((tags && copy_from_user(&tag, &tags[i], sizeof(tag))) ||
-                   copy_from_user(&fd, &fds[i], sizeof(fd))) {
+               if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
                        ret = -EFAULT;
                        goto out_fput;
                }
                /* allow sparse sets */
                if (fd == -1) {
                        ret = -EINVAL;
-                       if (unlikely(tag))
+                       if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
                                goto out_fput;
                        continue;
                }
@@ -7686,7 +8216,6 @@ static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
                        fput(file);
                        goto out_fput;
                }
-               ctx->file_data->tags[i] = tag;
                io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
        }
 
@@ -7704,7 +8233,7 @@ out_fput:
                if (file)
                        fput(file);
        }
-       io_free_file_tables(&ctx->file_table, nr_args);
+       io_free_file_tables(&ctx->file_table);
        ctx->nr_user_files = 0;
 out_free:
        io_rsrc_data_free(ctx->file_data);
@@ -7755,6 +8284,46 @@ static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
 #endif
 }
 
+static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
+                                unsigned int issue_flags, u32 slot_index)
+{
+       struct io_ring_ctx *ctx = req->ctx;
+       bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
+       struct io_fixed_file *file_slot;
+       int ret = -EBADF;
+
+       io_ring_submit_lock(ctx, !force_nonblock);
+       if (file->f_op == &io_uring_fops)
+               goto err;
+       ret = -ENXIO;
+       if (!ctx->file_data)
+               goto err;
+       ret = -EINVAL;
+       if (slot_index >= ctx->nr_user_files)
+               goto err;
+
+       slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
+       file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
+       ret = -EBADF;
+       if (file_slot->file_ptr)
+               goto err;
+
+       *io_get_tag_slot(ctx->file_data, slot_index) = 0;
+       io_fixed_file_set(file_slot, file);
+       ret = io_sqe_file_register(ctx, file, slot_index);
+       if (ret) {
+               file_slot->file_ptr = 0;
+               goto err;
+       }
+
+       ret = 0;
+err:
+       io_ring_submit_unlock(ctx, !force_nonblock);
+       if (ret)
+               fput(file);
+       return ret;
+}
+
 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
                                 struct io_rsrc_node *node, void *rsrc)
 {
@@ -7764,7 +8333,7 @@ static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
        if (!prsrc)
                return -ENOMEM;
 
-       prsrc->tag = data->tags[idx];
+       prsrc->tag = *io_get_tag_slot(data, idx);
        prsrc->rsrc = rsrc;
        list_add(&prsrc->list, &node->rsrc_list);
        return 0;
@@ -7834,7 +8403,7 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx,
                                err = -EBADF;
                                break;
                        }
-                       data->tags[up->offset + done] = tag;
+                       *io_get_tag_slot(data, up->offset + done) = tag;
                        io_fixed_file_set(file_slot, file);
                        err = io_sqe_file_register(ctx, file, i);
                        if (err) {
@@ -7850,14 +8419,6 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx,
        return done ? done : err;
 }
 
-static struct io_wq_work *io_free_work(struct io_wq_work *work)
-{
-       struct io_kiocb *req = container_of(work, struct io_kiocb, work);
-
-       req = io_put_req_find_next(req);
-       return req ? &req->work : NULL;
-}
-
 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
                                        struct task_struct *task)
 {
@@ -7865,19 +8426,23 @@ static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
        struct io_wq_data data;
        unsigned int concurrency;
 
+       mutex_lock(&ctx->uring_lock);
        hash = ctx->hash_map;
        if (!hash) {
                hash = kzalloc(sizeof(*hash), GFP_KERNEL);
-               if (!hash)
+               if (!hash) {
+                       mutex_unlock(&ctx->uring_lock);
                        return ERR_PTR(-ENOMEM);
+               }
                refcount_set(&hash->refs, 1);
                init_waitqueue_head(&hash->wait);
                ctx->hash_map = hash;
        }
+       mutex_unlock(&ctx->uring_lock);
 
        data.hash = hash;
        data.task = task;
-       data.free_work = io_free_work;
+       data.free_work = io_wq_free_work;
        data.do_work = io_wq_submit_work;
 
        /* Do QD, or 4 * CPUS, whatever is smallest */
@@ -7892,7 +8457,7 @@ static int io_uring_alloc_task_context(struct task_struct *task,
        struct io_uring_task *tctx;
        int ret;
 
-       tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
+       tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
        if (unlikely(!tctx))
                return -ENOMEM;
 
@@ -7912,13 +8477,11 @@ static int io_uring_alloc_task_context(struct task_struct *task,
 
        xa_init(&tctx->xa);
        init_waitqueue_head(&tctx->wait);
-       tctx->last = NULL;
        atomic_set(&tctx->in_idle, 0);
        atomic_set(&tctx->inflight_tracked, 0);
        task->io_uring = tctx;
        spin_lock_init(&tctx->task_lock);
        INIT_WQ_LIST(&tctx->task_list);
-       tctx->task_state = 0;
        init_task_work(&tctx->task_work, tctx_task_work);
        return 0;
 }
@@ -7929,6 +8492,7 @@ void __io_uring_free(struct task_struct *tsk)
 
        WARN_ON_ONCE(!xa_empty(&tctx->xa));
        WARN_ON_ONCE(tctx->io_wq);
+       WARN_ON_ONCE(tctx->cached_refs);
 
        percpu_counter_destroy(&tctx->inflight);
        kfree(tctx);
@@ -7948,9 +8512,11 @@ static int io_sq_offload_create(struct io_ring_ctx *ctx,
                f = fdget(p->wq_fd);
                if (!f.file)
                        return -ENXIO;
-               fdput(f);
-               if (f.file->f_op != &io_uring_fops)
+               if (f.file->f_op != &io_uring_fops) {
+                       fdput(f);
                        return -EINVAL;
+               }
+               fdput(f);
        }
        if (ctx->flags & IORING_SETUP_SQPOLL) {
                struct task_struct *tsk;
@@ -8305,6 +8871,8 @@ static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
                for (i = 0; i < nr_pages; i++) {
                        struct vm_area_struct *vma = vmas[i];
 
+                       if (vma_is_shmem(vma))
+                               continue;
                        if (vma->vm_file &&
                            !is_file_hugepages(vma->vm_file)) {
                                ret = -EOPNOTSUPP;
@@ -8402,9 +8970,9 @@ static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
        ret = io_rsrc_node_switch_start(ctx);
        if (ret)
                return ret;
-       data = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, nr_args);
-       if (!data)
-               return -ENOMEM;
+       ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
+       if (ret)
+               return ret;
        ret = io_buffers_map_alloc(ctx, nr_args);
        if (ret) {
                io_rsrc_data_free(data);
@@ -8412,19 +8980,13 @@ static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
        }
 
        for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
-               u64 tag = 0;
-
-               if (tags && copy_from_user(&tag, &tags[i], sizeof(tag))) {
-                       ret = -EFAULT;
-                       break;
-               }
                ret = io_copy_iov(ctx, &iov, arg, i);
                if (ret)
                        break;
                ret = io_buffer_validate(&iov);
                if (ret)
                        break;
-               if (!iov.iov_base && tag) {
+               if (!iov.iov_base && *io_get_tag_slot(data, i)) {
                        ret = -EINVAL;
                        break;
                }
@@ -8433,7 +8995,6 @@ static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
                                             &last_hpage);
                if (ret)
                        break;
-               data->tags[i] = tag;
        }
 
        WARN_ON_ONCE(ctx->buf_data);
@@ -8498,7 +9059,7 @@ static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
                }
 
                ctx->user_bufs[i] = imu;
-               ctx->buf_data->tags[offset] = tag;
+               *io_get_tag_slot(ctx->buf_data, offset) = tag;
        }
 
        if (needs_switch)
@@ -8520,6 +9081,7 @@ static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
        ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
        if (IS_ERR(ctx->cq_ev_fd)) {
                int ret = PTR_ERR(ctx->cq_ev_fd);
+
                ctx->cq_ev_fd = NULL;
                return ret;
        }
@@ -8547,43 +9109,36 @@ static void io_destroy_buffers(struct io_ring_ctx *ctx)
                __io_remove_buffers(ctx, buf, index, -1U);
 }
 
-static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
+static void io_req_cache_free(struct list_head *list)
 {
        struct io_kiocb *req, *nxt;
 
-       list_for_each_entry_safe(req, nxt, list, compl.list) {
-               if (tsk && req->task != tsk)
-                       continue;
-               list_del(&req->compl.list);
+       list_for_each_entry_safe(req, nxt, list, inflight_entry) {
+               list_del(&req->inflight_entry);
                kmem_cache_free(req_cachep, req);
        }
 }
 
 static void io_req_caches_free(struct io_ring_ctx *ctx)
 {
-       struct io_submit_state *submit_state = &ctx->submit_state;
-       struct io_comp_state *cs = &ctx->submit_state.comp;
+       struct io_submit_state *state = &ctx->submit_state;
 
        mutex_lock(&ctx->uring_lock);
 
-       if (submit_state->free_reqs) {
-               kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
-                                    submit_state->reqs);
-               submit_state->free_reqs = 0;
+       if (state->free_reqs) {
+               kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
+               state->free_reqs = 0;
        }
 
-       io_flush_cached_locked_reqs(ctx, cs);
-       io_req_cache_free(&cs->free_list, NULL);
+       io_flush_cached_locked_reqs(ctx, state);
+       io_req_cache_free(&state->free_list);
        mutex_unlock(&ctx->uring_lock);
 }
 
-static bool io_wait_rsrc_data(struct io_rsrc_data *data)
+static void io_wait_rsrc_data(struct io_rsrc_data *data)
 {
-       if (!data)
-               return false;
-       if (!atomic_dec_and_test(&data->refs))
+       if (data && !atomic_dec_and_test(&data->refs))
                wait_for_completion(&data->done);
-       return true;
 }
 
 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
@@ -8595,10 +9150,14 @@ static void io_ring_ctx_free(struct io_ring_ctx *ctx)
                ctx->mm_account = NULL;
        }
 
+       /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
+       io_wait_rsrc_data(ctx->buf_data);
+       io_wait_rsrc_data(ctx->file_data);
+
        mutex_lock(&ctx->uring_lock);
-       if (io_wait_rsrc_data(ctx->buf_data))
+       if (ctx->buf_data)
                __io_sqe_buffers_unregister(ctx);
-       if (io_wait_rsrc_data(ctx->file_data))
+       if (ctx->file_data)
                __io_sqe_files_unregister(ctx);
        if (ctx->rings)
                __io_cqring_overflow_flush(ctx, true);
@@ -8624,6 +9183,7 @@ static void io_ring_ctx_free(struct io_ring_ctx *ctx)
                sock_release(ctx->ring_sock);
        }
 #endif
+       WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
 
        io_mem_free(ctx->rings);
        io_mem_free(ctx->sq_sqes);
@@ -8643,7 +9203,7 @@ static __poll_t io_uring_poll(struct file *file, poll_table *wait)
        struct io_ring_ctx *ctx = file->private_data;
        __poll_t mask = 0;
 
-       poll_wait(file, &ctx->cq_wait, wait);
+       poll_wait(file, &ctx->poll_wait, wait);
        /*
         * synchronizes with barrier from wq_has_sleeper call in
         * io_commit_cqring
@@ -8665,7 +9225,7 @@ static __poll_t io_uring_poll(struct file *file, poll_table *wait)
         * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
         * pushs them to do the flush.
         */
-       if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
+       if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
                mask |= EPOLLIN | EPOLLRDNORM;
 
        return mask;
@@ -8691,11 +9251,6 @@ static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
        return -EINVAL;
 }
 
-static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
-{
-       return io_run_task_work_head(&ctx->exit_task_work);
-}
-
 struct io_tctx_exit {
        struct callback_head            task_work;
        struct completion               completion;
@@ -8713,7 +9268,7 @@ static void io_tctx_exit_cb(struct callback_head *cb)
         * node. It'll be removed by the end of cancellation, just ignore it.
         */
        if (!atomic_read(&tctx->in_idle))
-               io_uring_del_task_file((unsigned long)work->ctx);
+               io_uring_del_tctx_node((unsigned long)work->ctx);
        complete(&work->completion);
 }
 
@@ -8728,6 +9283,7 @@ static void io_ring_exit_work(struct work_struct *work)
 {
        struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
        unsigned long timeout = jiffies + HZ * 60 * 5;
+       unsigned long interval = HZ / 20;
        struct io_tctx_exit exit;
        struct io_tctx_node *node;
        int ret;
@@ -8739,7 +9295,7 @@ static void io_ring_exit_work(struct work_struct *work)
         * as nobody else will be looking for them.
         */
        do {
-               io_uring_try_cancel_requests(ctx, NULL, NULL);
+               io_uring_try_cancel_requests(ctx, NULL, true);
                if (ctx->sq_data) {
                        struct io_sq_data *sqd = ctx->sq_data;
                        struct task_struct *tsk;
@@ -8752,8 +9308,11 @@ static void io_ring_exit_work(struct work_struct *work)
                        io_sq_thread_unpark(sqd);
                }
 
-               WARN_ON_ONCE(time_after(jiffies, timeout));
-       } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
+               if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
+                       /* there is little hope left, don't run it too often */
+                       interval = HZ * 60;
+               }
+       } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
 
        init_completion(&exit.completion);
        init_task_work(&exit.task_work, io_tctx_exit_cb);
@@ -8761,7 +9320,7 @@ static void io_ring_exit_work(struct work_struct *work)
        /*
         * Some may use context even when all refs and requests have been put,
         * and they are free to do so while still holding uring_lock or
-        * completion_lock, see __io_req_task_submit(). Apart from other work,
+        * completion_lock, see io_req_task_submit(). Apart from other work,
         * this lock/unlock section also waits them to finish.
         */
        mutex_lock(&ctx->uring_lock);
@@ -8782,29 +9341,31 @@ static void io_ring_exit_work(struct work_struct *work)
                mutex_lock(&ctx->uring_lock);
        }
        mutex_unlock(&ctx->uring_lock);
-       spin_lock_irq(&ctx->completion_lock);
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
+       spin_unlock(&ctx->completion_lock);
 
        io_ring_ctx_free(ctx);
 }
 
 /* Returns true if we found and killed one or more timeouts */
 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
-                            struct files_struct *files)
+                            bool cancel_all)
 {
        struct io_kiocb *req, *tmp;
        int canceled = 0;
 
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
+       spin_lock_irq(&ctx->timeout_lock);
        list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
-               if (io_match_task(req, tsk, files)) {
+               if (io_match_task(req, tsk, cancel_all)) {
                        io_kill_timeout(req, -ECANCELED);
                        canceled++;
                }
        }
+       spin_unlock_irq(&ctx->timeout_lock);
        if (canceled != 0)
                io_commit_cqring(ctx);
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_unlock(&ctx->completion_lock);
        if (canceled != 0)
                io_cqring_ev_posted(ctx);
        return canceled != 0;
@@ -8823,8 +9384,8 @@ static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
                io_unregister_personality(ctx, index);
        mutex_unlock(&ctx->uring_lock);
 
-       io_kill_timeouts(ctx, NULL, NULL);
-       io_poll_remove_all(ctx, NULL, NULL);
+       io_kill_timeouts(ctx, NULL, true);
+       io_poll_remove_all(ctx, NULL, true);
 
        /* if we failed setting up the ctx, we might not have any rings */
        io_iopoll_try_reap_events(ctx);
@@ -8850,7 +9411,7 @@ static int io_uring_release(struct inode *inode, struct file *file)
 
 struct io_task_cancel {
        struct task_struct *task;
-       struct files_struct *files;
+       bool all;
 };
 
 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
@@ -8859,35 +9420,33 @@ static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
        struct io_task_cancel *cancel = data;
        bool ret;
 
-       if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
-               unsigned long flags;
+       if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
                struct io_ring_ctx *ctx = req->ctx;
 
                /* protect against races with linked timeouts */
-               spin_lock_irqsave(&ctx->completion_lock, flags);
-               ret = io_match_task(req, cancel->task, cancel->files);
-               spin_unlock_irqrestore(&ctx->completion_lock, flags);
+               spin_lock(&ctx->completion_lock);
+               ret = io_match_task(req, cancel->task, cancel->all);
+               spin_unlock(&ctx->completion_lock);
        } else {
-               ret = io_match_task(req, cancel->task, cancel->files);
+               ret = io_match_task(req, cancel->task, cancel->all);
        }
        return ret;
 }
 
 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
-                                 struct task_struct *task,
-                                 struct files_struct *files)
+                                 struct task_struct *task, bool cancel_all)
 {
        struct io_defer_entry *de;
        LIST_HEAD(list);
 
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
        list_for_each_entry_reverse(de, &ctx->defer_list, list) {
-               if (io_match_task(de->req, task, files)) {
+               if (io_match_task(de->req, task, cancel_all)) {
                        list_cut_position(&list, &ctx->defer_list, &de->list);
                        break;
                }
        }
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_unlock(&ctx->completion_lock);
        if (list_empty(&list))
                return false;
 
@@ -8926,9 +9485,9 @@ static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
 
 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
                                         struct task_struct *task,
-                                        struct files_struct *files)
+                                        bool cancel_all)
 {
-       struct io_task_cancel cancel = { .task = task, .files = files, };
+       struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
        struct io_uring_task *tctx = task ? task->io_uring : NULL;
 
        while (1) {
@@ -8948,7 +9507,7 @@ static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
                }
 
                /* SQPOLL thread does its own polling */
-               if ((!(ctx->flags & IORING_SETUP_SQPOLL) && !files) ||
+               if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
                    (ctx->sq_data && ctx->sq_data->thread == current)) {
                        while (!list_empty_careful(&ctx->iopoll_list)) {
                                io_iopoll_try_reap_events(ctx);
@@ -8956,18 +9515,18 @@ static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
                        }
                }
 
-               ret |= io_cancel_defer_files(ctx, task, files);
-               ret |= io_poll_remove_all(ctx, task, files);
-               ret |= io_kill_timeouts(ctx, task, files);
-               ret |= io_run_task_work();
-               ret |= io_run_ctx_fallback(ctx);
+               ret |= io_cancel_defer_files(ctx, task, cancel_all);
+               ret |= io_poll_remove_all(ctx, task, cancel_all);
+               ret |= io_kill_timeouts(ctx, task, cancel_all);
+               if (task)
+                       ret |= io_run_task_work();
                if (!ret)
                        break;
                cond_resched();
        }
 }
 
-static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
+static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
 {
        struct io_uring_task *tctx = current->io_uring;
        struct io_tctx_node *node;
@@ -9004,19 +9563,19 @@ static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
 /*
  * Note that this task has used io_uring. We use it for cancelation purposes.
  */
-static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
+static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
 {
        struct io_uring_task *tctx = current->io_uring;
 
        if (likely(tctx && tctx->last == ctx))
                return 0;
-       return __io_uring_add_task_file(ctx);
+       return __io_uring_add_tctx_node(ctx);
 }
 
 /*
  * Remove this io_uring_file -> task mapping.
  */
-static void io_uring_del_task_file(unsigned long index)
+static void io_uring_del_tctx_node(unsigned long index)
 {
        struct io_uring_task *tctx = current->io_uring;
        struct io_tctx_node *node;
@@ -9046,14 +9605,14 @@ static void io_uring_clean_tctx(struct io_uring_task *tctx)
        unsigned long index;
 
        xa_for_each(&tctx->xa, index, node)
-               io_uring_del_task_file(index);
+               io_uring_del_tctx_node(index);
        if (wq) {
                /*
                 * Must be after io_uring_del_task_file() (removes nodes under
                 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
                 */
-               tctx->io_wq = NULL;
                io_wq_put_and_exit(wq);
+               tctx->io_wq = NULL;
        }
 }
 
@@ -9064,99 +9623,86 @@ static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
        return percpu_counter_sum(&tctx->inflight);
 }
 
-static void io_uring_try_cancel(struct files_struct *files)
+static void io_uring_drop_tctx_refs(struct task_struct *task)
 {
-       struct io_uring_task *tctx = current->io_uring;
-       struct io_tctx_node *node;
-       unsigned long index;
-
-       xa_for_each(&tctx->xa, index, node) {
-               struct io_ring_ctx *ctx = node->ctx;
+       struct io_uring_task *tctx = task->io_uring;
+       unsigned int refs = tctx->cached_refs;
 
-               /* sqpoll task will cancel all its requests */
-               if (!ctx->sq_data)
-                       io_uring_try_cancel_requests(ctx, current, files);
+       if (refs) {
+               tctx->cached_refs = 0;
+               percpu_counter_sub(&tctx->inflight, refs);
+               put_task_struct_many(task, refs);
        }
 }
 
-/* should only be called by SQPOLL task */
-static void io_uring_cancel_sqpoll(struct io_sq_data *sqd)
+/*
+ * Find any io_uring ctx that this task has registered or done IO on, and cancel
+ * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
+ */
+static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
 {
        struct io_uring_task *tctx = current->io_uring;
        struct io_ring_ctx *ctx;
        s64 inflight;
        DEFINE_WAIT(wait);
 
+       WARN_ON_ONCE(sqd && sqd->thread != current);
+
        if (!current->io_uring)
                return;
        if (tctx->io_wq)
                io_wq_exit_start(tctx->io_wq);
 
-       WARN_ON_ONCE(!sqd || sqd->thread != current);
-
        atomic_inc(&tctx->in_idle);
        do {
+               io_uring_drop_tctx_refs(current);
                /* read completions before cancelations */
-               inflight = tctx_inflight(tctx, false);
+               inflight = tctx_inflight(tctx, !cancel_all);
                if (!inflight)
                        break;
-               list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
-                       io_uring_try_cancel_requests(ctx, current, NULL);
-
-               prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
-               /*
-                * If we've seen completions, retry without waiting. This
-                * avoids a race where a completion comes in before we did
-                * prepare_to_wait().
-                */
-               if (inflight == tctx_inflight(tctx, false))
-                       schedule();
-               finish_wait(&tctx->wait, &wait);
-       } while (1);
-       atomic_dec(&tctx->in_idle);
-}
 
-/*
- * Find any io_uring fd that this task has registered or done IO on, and cancel
- * requests.
- */
-void __io_uring_cancel(struct files_struct *files)
-{
-       struct io_uring_task *tctx = current->io_uring;
-       DEFINE_WAIT(wait);
-       s64 inflight;
+               if (!sqd) {
+                       struct io_tctx_node *node;
+                       unsigned long index;
 
-       if (tctx->io_wq)
-               io_wq_exit_start(tctx->io_wq);
+                       xa_for_each(&tctx->xa, index, node) {
+                               /* sqpoll task will cancel all its requests */
+                               if (node->ctx->sq_data)
+                                       continue;
+                               io_uring_try_cancel_requests(node->ctx, current,
+                                                            cancel_all);
+                       }
+               } else {
+                       list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
+                               io_uring_try_cancel_requests(ctx, current,
+                                                            cancel_all);
+               }
 
-       /* make sure overflow events are dropped */
-       atomic_inc(&tctx->in_idle);
-       do {
-               /* read completions before cancelations */
-               inflight = tctx_inflight(tctx, !!files);
-               if (!inflight)
-                       break;
-               io_uring_try_cancel(files);
                prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
-
+               io_uring_drop_tctx_refs(current);
                /*
                 * If we've seen completions, retry without waiting. This
                 * avoids a race where a completion comes in before we did
                 * prepare_to_wait().
                 */
-               if (inflight == tctx_inflight(tctx, !!files))
+               if (inflight == tctx_inflight(tctx, !cancel_all))
                        schedule();
                finish_wait(&tctx->wait, &wait);
        } while (1);
        atomic_dec(&tctx->in_idle);
 
        io_uring_clean_tctx(tctx);
-       if (!files) {
+       if (cancel_all) {
                /* for exec all current's requests should be gone, kill tctx */
                __io_uring_free(current);
        }
 }
 
+void __io_uring_cancel(bool cancel_all)
+{
+       io_uring_cancel_generic(cancel_all, NULL);
+}
+
 static void *io_uring_validate_mmap_request(struct file *file,
                                            loff_t pgoff, size_t sz)
 {
@@ -9314,10 +9860,10 @@ SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
         */
        ret = 0;
        if (ctx->flags & IORING_SETUP_SQPOLL) {
-               io_cqring_overflow_flush(ctx, false);
+               io_cqring_overflow_flush(ctx);
 
-               ret = -EOWNERDEAD;
                if (unlikely(ctx->sq_data->thread == NULL)) {
+                       ret = -EOWNERDEAD;
                        goto out;
                }
                if (flags & IORING_ENTER_SQ_WAKEUP)
@@ -9329,7 +9875,7 @@ SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
                }
                submitted = to_submit;
        } else if (to_submit) {
-               ret = io_uring_add_task_file(ctx);
+               ret = io_uring_add_tctx_node(ctx);
                if (unlikely(ret))
                        goto out;
                mutex_lock(&ctx->uring_lock);
@@ -9450,7 +9996,7 @@ static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
                        io_uring_show_cred(m, index, cred);
        }
        seq_printf(m, "PollList:\n");
-       spin_lock_irq(&ctx->completion_lock);
+       spin_lock(&ctx->completion_lock);
        for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
                struct hlist_head *list = &ctx->cancel_hash[i];
                struct io_kiocb *req;
@@ -9459,7 +10005,7 @@ static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
                        seq_printf(m, "  op=%d, task_works=%d\n", req->opcode,
                                        req->task->task_works != NULL);
        }
-       spin_unlock_irq(&ctx->completion_lock);
+       spin_unlock(&ctx->completion_lock);
        if (has_lock)
                mutex_unlock(&ctx->uring_lock);
 }
@@ -9513,8 +10059,6 @@ static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
        rings->cq_ring_mask = p->cq_entries - 1;
        rings->sq_ring_entries = p->sq_entries;
        rings->cq_ring_entries = p->cq_entries;
-       ctx->sq_mask = rings->sq_ring_mask;
-       ctx->cq_mask = rings->cq_ring_mask;
 
        size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
        if (size == SIZE_MAX) {
@@ -9541,7 +10085,7 @@ static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
        if (fd < 0)
                return fd;
 
-       ret = io_uring_add_task_file(ctx);
+       ret = io_uring_add_tctx_node(ctx);
        if (ret) {
                put_unused_fd(fd);
                return ret;
@@ -9789,10 +10333,11 @@ static int io_register_personality(struct io_ring_ctx *ctx)
 
        ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
                        XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
-       if (!ret)
-               return id;
-       put_cred(creds);
-       return ret;
+       if (ret < 0) {
+               put_cred(creds);
+               return ret;
+       }
+       return id;
 }
 
 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
@@ -9956,6 +10501,95 @@ static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
        return -EINVAL;
 }
 
+static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
+                               unsigned len)
+{
+       struct io_uring_task *tctx = current->io_uring;
+       cpumask_var_t new_mask;
+       int ret;
+
+       if (!tctx || !tctx->io_wq)
+               return -EINVAL;
+
+       if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
+               return -ENOMEM;
+
+       cpumask_clear(new_mask);
+       if (len > cpumask_size())
+               len = cpumask_size();
+
+       if (copy_from_user(new_mask, arg, len)) {
+               free_cpumask_var(new_mask);
+               return -EFAULT;
+       }
+
+       ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
+       free_cpumask_var(new_mask);
+       return ret;
+}
+
+static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
+{
+       struct io_uring_task *tctx = current->io_uring;
+
+       if (!tctx || !tctx->io_wq)
+               return -EINVAL;
+
+       return io_wq_cpu_affinity(tctx->io_wq, NULL);
+}
+
+static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
+                                       void __user *arg)
+{
+       struct io_uring_task *tctx = NULL;
+       struct io_sq_data *sqd = NULL;
+       __u32 new_count[2];
+       int i, ret;
+
+       if (copy_from_user(new_count, arg, sizeof(new_count)))
+               return -EFAULT;
+       for (i = 0; i < ARRAY_SIZE(new_count); i++)
+               if (new_count[i] > INT_MAX)
+                       return -EINVAL;
+
+       if (ctx->flags & IORING_SETUP_SQPOLL) {
+               sqd = ctx->sq_data;
+               if (sqd) {
+                       /*
+                        * Observe the correct sqd->lock -> ctx->uring_lock
+                        * ordering. Fine to drop uring_lock here, we hold
+                        * a ref to the ctx.
+                        */
+                       mutex_unlock(&ctx->uring_lock);
+                       mutex_lock(&sqd->lock);
+                       mutex_lock(&ctx->uring_lock);
+                       tctx = sqd->thread->io_uring;
+               }
+       } else {
+               tctx = current->io_uring;
+       }
+
+       ret = -EINVAL;
+       if (!tctx || !tctx->io_wq)
+               goto err;
+
+       ret = io_wq_max_workers(tctx->io_wq, new_count);
+       if (ret)
+               goto err;
+
+       if (sqd)
+               mutex_unlock(&sqd->lock);
+
+       if (copy_to_user(arg, new_count, sizeof(new_count)))
+               return -EFAULT;
+
+       return 0;
+err:
+       if (sqd)
+               mutex_unlock(&sqd->lock);
+       return ret;
+}
+
 static bool io_register_op_must_quiesce(int op)
 {
        switch (op) {
@@ -9971,12 +10605,42 @@ static bool io_register_op_must_quiesce(int op)
        case IORING_REGISTER_FILES_UPDATE2:
        case IORING_REGISTER_BUFFERS2:
        case IORING_REGISTER_BUFFERS_UPDATE:
+       case IORING_REGISTER_IOWQ_AFF:
+       case IORING_UNREGISTER_IOWQ_AFF:
+       case IORING_REGISTER_IOWQ_MAX_WORKERS:
                return false;
        default:
                return true;
        }
 }
 
+static int io_ctx_quiesce(struct io_ring_ctx *ctx)
+{
+       long ret;
+
+       percpu_ref_kill(&ctx->refs);
+
+       /*
+        * Drop uring mutex before waiting for references to exit. If another
+        * thread is currently inside io_uring_enter() it might need to grab the
+        * uring_lock to make progress. If we hold it here across the drain
+        * wait, then we can deadlock. It's safe to drop the mutex here, since
+        * no new references will come in after we've killed the percpu ref.
+        */
+       mutex_unlock(&ctx->uring_lock);
+       do {
+               ret = wait_for_completion_interruptible(&ctx->ref_comp);
+               if (!ret)
+                       break;
+               ret = io_run_task_work_sig();
+       } while (ret >= 0);
+       mutex_lock(&ctx->uring_lock);
+
+       if (ret)
+               io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
+       return ret;
+}
+
 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
                               void __user *arg, unsigned nr_args)
        __releases(ctx->uring_lock)
@@ -10001,31 +10665,9 @@ static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
        }
 
        if (io_register_op_must_quiesce(opcode)) {
-               percpu_ref_kill(&ctx->refs);
-
-               /*
-                * Drop uring mutex before waiting for references to exit. If
-                * another thread is currently inside io_uring_enter() it might
-                * need to grab the uring_lock to make progress. If we hold it
-                * here across the drain wait, then we can deadlock. It's safe
-                * to drop the mutex here, since no new references will come in
-                * after we've killed the percpu ref.
-                */
-               mutex_unlock(&ctx->uring_lock);
-               do {
-                       ret = wait_for_completion_interruptible(&ctx->ref_comp);
-                       if (!ret)
-                               break;
-                       ret = io_run_task_work_sig();
-                       if (ret < 0)
-                               break;
-               } while (1);
-               mutex_lock(&ctx->uring_lock);
-
-               if (ret) {
-                       io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
+               ret = io_ctx_quiesce(ctx);
+               if (ret)
                        return ret;
-               }
        }
 
        switch (opcode) {
@@ -10110,6 +10752,24 @@ static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
                ret = io_register_rsrc_update(ctx, arg, nr_args,
                                              IORING_RSRC_BUFFER);
                break;
+       case IORING_REGISTER_IOWQ_AFF:
+               ret = -EINVAL;
+               if (!arg || !nr_args)
+                       break;
+               ret = io_register_iowq_aff(ctx, arg, nr_args);
+               break;
+       case IORING_UNREGISTER_IOWQ_AFF:
+               ret = -EINVAL;
+               if (arg || nr_args)
+                       break;
+               ret = io_unregister_iowq_aff(ctx);
+               break;
+       case IORING_REGISTER_IOWQ_MAX_WORKERS:
+               ret = -EINVAL;
+               if (!arg || nr_args != 2)
+                       break;
+               ret = io_register_iowq_max_workers(ctx, arg);
+               break;
        default:
                ret = -EINVAL;
                break;
@@ -10188,18 +10848,25 @@ static int __init io_uring_init(void)
        BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
        BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
        BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
+       BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
        BUILD_BUG_SQE_ELEM(42, __u16,  personality);
        BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
+       BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
 
        BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
                     sizeof(struct io_uring_rsrc_update));
        BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
                     sizeof(struct io_uring_rsrc_update2));
+
+       /* ->buf_index is u16 */
+       BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
+
        /* should fit into one byte */
        BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
 
        BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
-       BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
+       BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
+
        req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
                                SLAB_ACCOUNT);
        return 0;