e395167999edfb150a9eb85cd11d402471b4b725
[platform/kernel/linux-starfive.git] / io_uring / io_uring.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Shared application/kernel submission and completion ring pairs, for
4  * supporting fast/efficient IO.
5  *
6  * A note on the read/write ordering memory barriers that are matched between
7  * the application and kernel side.
8  *
9  * After the application reads the CQ ring tail, it must use an
10  * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11  * before writing the tail (using smp_load_acquire to read the tail will
12  * do). It also needs a smp_mb() before updating CQ head (ordering the
13  * entry load(s) with the head store), pairing with an implicit barrier
14  * through a control-dependency in io_get_cqe (smp_store_release to
15  * store head will do). Failure to do so could lead to reading invalid
16  * CQ entries.
17  *
18  * Likewise, the application must use an appropriate smp_wmb() before
19  * writing the SQ tail (ordering SQ entry stores with the tail store),
20  * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21  * to store the tail will do). And it needs a barrier ordering the SQ
22  * head load before writing new SQ entries (smp_load_acquire to read
23  * head will do).
24  *
25  * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26  * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27  * updating the SQ tail; a full memory barrier smp_mb() is needed
28  * between.
29  *
30  * Also see the examples in the liburing library:
31  *
32  *      git://git.kernel.dk/liburing
33  *
34  * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35  * from data shared between the kernel and application. This is done both
36  * for ordering purposes, but also to ensure that once a value is loaded from
37  * data that the application could potentially modify, it remains stable.
38  *
39  * Copyright (C) 2018-2019 Jens Axboe
40  * Copyright (c) 2018-2019 Christoph Hellwig
41  */
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
51
52 #include <linux/sched/signal.h>
53 #include <linux/fs.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
56 #include <linux/mm.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
63 #include <net/sock.h>
64 #include <net/af_unix.h>
65 #include <net/scm.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/fsnotify.h>
74 #include <linux/fadvise.h>
75 #include <linux/eventpoll.h>
76 #include <linux/task_work.h>
77 #include <linux/pagemap.h>
78 #include <linux/io_uring.h>
79 #include <linux/audit.h>
80 #include <linux/security.h>
81
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
84
85 #include <uapi/linux/io_uring.h>
86
87 #include "io-wq.h"
88
89 #include "io_uring_types.h"
90 #include "io_uring.h"
91 #include "opdef.h"
92 #include "refs.h"
93 #include "tctx.h"
94 #include "sqpoll.h"
95 #include "fdinfo.h"
96 #include "kbuf.h"
97
98 #include "xattr.h"
99 #include "nop.h"
100 #include "fs.h"
101 #include "splice.h"
102 #include "sync.h"
103 #include "advise.h"
104 #include "openclose.h"
105 #include "uring_cmd.h"
106 #include "epoll.h"
107 #include "statx.h"
108 #include "net.h"
109 #include "msg_ring.h"
110 #include "timeout.h"
111 #include "poll.h"
112 #include "cancel.h"
113
114 #define IORING_MAX_ENTRIES      32768
115 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
116
117 /* only define max */
118 #define IORING_MAX_FIXED_FILES  (1U << 20)
119 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
120                                  IORING_REGISTER_LAST + IORING_OP_LAST)
121
122 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
123 #define IO_RSRC_TAG_TABLE_MAX   (1U << IO_RSRC_TAG_TABLE_SHIFT)
124 #define IO_RSRC_TAG_TABLE_MASK  (IO_RSRC_TAG_TABLE_MAX - 1)
125
126 #define IORING_MAX_REG_BUFFERS  (1U << 14)
127
128 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
129                           IOSQE_IO_HARDLINK | IOSQE_ASYNC)
130
131 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
132                         IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
133
134 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
135                                 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
136                                 REQ_F_ASYNC_DATA)
137
138 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
139                                  IO_REQ_CLEAN_FLAGS)
140
141 #define IO_TCTX_REFS_CACHE_NR   (1U << 10)
142
143 struct io_rsrc_put {
144         struct list_head list;
145         u64 tag;
146         union {
147                 void *rsrc;
148                 struct file *file;
149                 struct io_mapped_ubuf *buf;
150         };
151 };
152
153 struct io_rsrc_node {
154         struct percpu_ref               refs;
155         struct list_head                node;
156         struct list_head                rsrc_list;
157         struct io_rsrc_data             *rsrc_data;
158         struct llist_node               llist;
159         bool                            done;
160 };
161
162 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
163
164 struct io_rsrc_data {
165         struct io_ring_ctx              *ctx;
166
167         u64                             **tags;
168         unsigned int                    nr;
169         rsrc_put_fn                     *do_put;
170         atomic_t                        refs;
171         struct completion               done;
172         bool                            quiesce;
173 };
174
175 #define IO_COMPL_BATCH                  32
176 #define IO_REQ_CACHE_SIZE               32
177 #define IO_REQ_ALLOC_BATCH              8
178
179 /*
180  * First field must be the file pointer in all the
181  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
182  */
183 struct io_rw {
184         /* NOTE: kiocb has the file as the first member, so don't do it here */
185         struct kiocb                    kiocb;
186         u64                             addr;
187         u32                             len;
188         rwf_t                           flags;
189 };
190
191 struct io_rsrc_update {
192         struct file                     *file;
193         u64                             arg;
194         u32                             nr_args;
195         u32                             offset;
196 };
197
198 struct io_rw_state {
199         struct iov_iter                 iter;
200         struct iov_iter_state           iter_state;
201         struct iovec                    fast_iov[UIO_FASTIOV];
202 };
203
204 struct io_async_rw {
205         struct io_rw_state              s;
206         const struct iovec              *free_iovec;
207         size_t                          bytes_done;
208         struct wait_page_queue          wpq;
209 };
210
211 enum {
212         IORING_RSRC_FILE                = 0,
213         IORING_RSRC_BUFFER              = 1,
214 };
215
216 enum {
217         IO_CHECK_CQ_OVERFLOW_BIT,
218         IO_CHECK_CQ_DROPPED_BIT,
219 };
220
221 struct io_defer_entry {
222         struct list_head        list;
223         struct io_kiocb         *req;
224         u32                     seq;
225 };
226
227 /* requests with any of those set should undergo io_disarm_next() */
228 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
229 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
230
231 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
232                                          struct task_struct *task,
233                                          bool cancel_all);
234
235 static void io_dismantle_req(struct io_kiocb *req);
236 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
237                                      struct io_uring_rsrc_update2 *up,
238                                      unsigned nr_args);
239 static void io_clean_op(struct io_kiocb *req);
240 static void io_queue_sqe(struct io_kiocb *req);
241 static void io_rsrc_put_work(struct work_struct *work);
242
243 static void io_req_task_queue(struct io_kiocb *req);
244 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
245 static int io_req_prep_async(struct io_kiocb *req);
246
247 static void io_eventfd_signal(struct io_ring_ctx *ctx);
248
249 static struct kmem_cache *req_cachep;
250
251 const char *io_uring_get_opcode(u8 opcode)
252 {
253         if (opcode < IORING_OP_LAST)
254                 return io_op_defs[opcode].name;
255         return "INVALID";
256 }
257
258 struct sock *io_uring_get_socket(struct file *file)
259 {
260 #if defined(CONFIG_UNIX)
261         if (io_is_uring_fops(file)) {
262                 struct io_ring_ctx *ctx = file->private_data;
263
264                 return ctx->ring_sock->sk;
265         }
266 #endif
267         return NULL;
268 }
269 EXPORT_SYMBOL(io_uring_get_socket);
270
271 #if defined(CONFIG_UNIX)
272 static inline bool io_file_need_scm(struct file *filp)
273 {
274 #if defined(IO_URING_SCM_ALL)
275         return true;
276 #else
277         return !!unix_get_socket(filp);
278 #endif
279 }
280 #else
281 static inline bool io_file_need_scm(struct file *filp)
282 {
283         return false;
284 }
285 #endif
286
287 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
288 {
289         if (!*locked) {
290                 mutex_lock(&ctx->uring_lock);
291                 *locked = true;
292         }
293 }
294
295 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
296 {
297         if (!wq_list_empty(&ctx->submit_state.compl_reqs))
298                 __io_submit_flush_completions(ctx);
299 }
300
301 #define IO_RSRC_REF_BATCH       100
302
303 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
304 {
305         percpu_ref_put_many(&node->refs, nr);
306 }
307
308 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
309                                           struct io_ring_ctx *ctx)
310         __must_hold(&ctx->uring_lock)
311 {
312         struct io_rsrc_node *node = req->rsrc_node;
313
314         if (node) {
315                 if (node == ctx->rsrc_node)
316                         ctx->rsrc_cached_refs++;
317                 else
318                         io_rsrc_put_node(node, 1);
319         }
320 }
321
322 static inline void io_req_put_rsrc(struct io_kiocb *req)
323 {
324         if (req->rsrc_node)
325                 io_rsrc_put_node(req->rsrc_node, 1);
326 }
327
328 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
329         __must_hold(&ctx->uring_lock)
330 {
331         if (ctx->rsrc_cached_refs) {
332                 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
333                 ctx->rsrc_cached_refs = 0;
334         }
335 }
336
337 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
338         __must_hold(&ctx->uring_lock)
339 {
340         ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
341         percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
342 }
343
344 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
345                                         struct io_ring_ctx *ctx,
346                                         unsigned int issue_flags)
347 {
348         if (!req->rsrc_node) {
349                 req->rsrc_node = ctx->rsrc_node;
350
351                 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
352                         lockdep_assert_held(&ctx->uring_lock);
353                         ctx->rsrc_cached_refs--;
354                         if (unlikely(ctx->rsrc_cached_refs < 0))
355                                 io_rsrc_refs_refill(ctx);
356                 } else {
357                         percpu_ref_get(&req->rsrc_node->refs);
358                 }
359         }
360 }
361
362 static bool io_match_linked(struct io_kiocb *head)
363 {
364         struct io_kiocb *req;
365
366         io_for_each_link(req, head) {
367                 if (req->flags & REQ_F_INFLIGHT)
368                         return true;
369         }
370         return false;
371 }
372
373 /*
374  * As io_match_task() but protected against racing with linked timeouts.
375  * User must not hold timeout_lock.
376  */
377 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
378                         bool cancel_all)
379 {
380         bool matched;
381
382         if (task && head->task != task)
383                 return false;
384         if (cancel_all)
385                 return true;
386
387         if (head->flags & REQ_F_LINK_TIMEOUT) {
388                 struct io_ring_ctx *ctx = head->ctx;
389
390                 /* protect against races with linked timeouts */
391                 spin_lock_irq(&ctx->timeout_lock);
392                 matched = io_match_linked(head);
393                 spin_unlock_irq(&ctx->timeout_lock);
394         } else {
395                 matched = io_match_linked(head);
396         }
397         return matched;
398 }
399
400 static inline void req_fail_link_node(struct io_kiocb *req, int res)
401 {
402         req_set_fail(req);
403         io_req_set_res(req, res, 0);
404 }
405
406 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
407 {
408         wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
409 }
410
411 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
412 {
413         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
414
415         complete(&ctx->ref_comp);
416 }
417
418 static __cold void io_fallback_req_func(struct work_struct *work)
419 {
420         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
421                                                 fallback_work.work);
422         struct llist_node *node = llist_del_all(&ctx->fallback_llist);
423         struct io_kiocb *req, *tmp;
424         bool locked = false;
425
426         percpu_ref_get(&ctx->refs);
427         llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
428                 req->io_task_work.func(req, &locked);
429
430         if (locked) {
431                 io_submit_flush_completions(ctx);
432                 mutex_unlock(&ctx->uring_lock);
433         }
434         percpu_ref_put(&ctx->refs);
435 }
436
437 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
438 {
439         struct io_ring_ctx *ctx;
440         int hash_bits;
441
442         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
443         if (!ctx)
444                 return NULL;
445
446         xa_init(&ctx->io_bl_xa);
447
448         /*
449          * Use 5 bits less than the max cq entries, that should give us around
450          * 32 entries per hash list if totally full and uniformly spread.
451          */
452         hash_bits = ilog2(p->cq_entries);
453         hash_bits -= 5;
454         if (hash_bits <= 0)
455                 hash_bits = 1;
456         ctx->cancel_hash_bits = hash_bits;
457         ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
458                                         GFP_KERNEL);
459         if (!ctx->cancel_hash)
460                 goto err;
461         __hash_init(ctx->cancel_hash, 1U << hash_bits);
462
463         ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
464         if (!ctx->dummy_ubuf)
465                 goto err;
466         /* set invalid range, so io_import_fixed() fails meeting it */
467         ctx->dummy_ubuf->ubuf = -1UL;
468
469         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
470                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
471                 goto err;
472
473         ctx->flags = p->flags;
474         init_waitqueue_head(&ctx->sqo_sq_wait);
475         INIT_LIST_HEAD(&ctx->sqd_list);
476         INIT_LIST_HEAD(&ctx->cq_overflow_list);
477         INIT_LIST_HEAD(&ctx->io_buffers_cache);
478         INIT_LIST_HEAD(&ctx->apoll_cache);
479         init_completion(&ctx->ref_comp);
480         xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
481         mutex_init(&ctx->uring_lock);
482         init_waitqueue_head(&ctx->cq_wait);
483         spin_lock_init(&ctx->completion_lock);
484         spin_lock_init(&ctx->timeout_lock);
485         INIT_WQ_LIST(&ctx->iopoll_list);
486         INIT_LIST_HEAD(&ctx->io_buffers_pages);
487         INIT_LIST_HEAD(&ctx->io_buffers_comp);
488         INIT_LIST_HEAD(&ctx->defer_list);
489         INIT_LIST_HEAD(&ctx->timeout_list);
490         INIT_LIST_HEAD(&ctx->ltimeout_list);
491         spin_lock_init(&ctx->rsrc_ref_lock);
492         INIT_LIST_HEAD(&ctx->rsrc_ref_list);
493         INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
494         init_llist_head(&ctx->rsrc_put_llist);
495         INIT_LIST_HEAD(&ctx->tctx_list);
496         ctx->submit_state.free_list.next = NULL;
497         INIT_WQ_LIST(&ctx->locked_free_list);
498         INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
499         INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
500         return ctx;
501 err:
502         kfree(ctx->dummy_ubuf);
503         kfree(ctx->cancel_hash);
504         kfree(ctx->io_bl);
505         xa_destroy(&ctx->io_bl_xa);
506         kfree(ctx);
507         return NULL;
508 }
509
510 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
511 {
512         struct io_rings *r = ctx->rings;
513
514         WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
515         ctx->cq_extra--;
516 }
517
518 static bool req_need_defer(struct io_kiocb *req, u32 seq)
519 {
520         if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
521                 struct io_ring_ctx *ctx = req->ctx;
522
523                 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
524         }
525
526         return false;
527 }
528
529 static inline bool io_req_ffs_set(struct io_kiocb *req)
530 {
531         return req->flags & REQ_F_FIXED_FILE;
532 }
533
534 static inline void io_req_track_inflight(struct io_kiocb *req)
535 {
536         if (!(req->flags & REQ_F_INFLIGHT)) {
537                 req->flags |= REQ_F_INFLIGHT;
538                 atomic_inc(&req->task->io_uring->inflight_tracked);
539         }
540 }
541
542 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
543 {
544         if (WARN_ON_ONCE(!req->link))
545                 return NULL;
546
547         req->flags &= ~REQ_F_ARM_LTIMEOUT;
548         req->flags |= REQ_F_LINK_TIMEOUT;
549
550         /* linked timeouts should have two refs once prep'ed */
551         io_req_set_refcount(req);
552         __io_req_set_refcount(req->link, 2);
553         return req->link;
554 }
555
556 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
557 {
558         if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
559                 return NULL;
560         return __io_prep_linked_timeout(req);
561 }
562
563 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
564 {
565         io_queue_linked_timeout(__io_prep_linked_timeout(req));
566 }
567
568 static inline void io_arm_ltimeout(struct io_kiocb *req)
569 {
570         if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
571                 __io_arm_ltimeout(req);
572 }
573
574 static void io_prep_async_work(struct io_kiocb *req)
575 {
576         const struct io_op_def *def = &io_op_defs[req->opcode];
577         struct io_ring_ctx *ctx = req->ctx;
578
579         if (!(req->flags & REQ_F_CREDS)) {
580                 req->flags |= REQ_F_CREDS;
581                 req->creds = get_current_cred();
582         }
583
584         req->work.list.next = NULL;
585         req->work.flags = 0;
586         req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
587         if (req->flags & REQ_F_FORCE_ASYNC)
588                 req->work.flags |= IO_WQ_WORK_CONCURRENT;
589
590         if (req->flags & REQ_F_ISREG) {
591                 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
592                         io_wq_hash_work(&req->work, file_inode(req->file));
593         } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
594                 if (def->unbound_nonreg_file)
595                         req->work.flags |= IO_WQ_WORK_UNBOUND;
596         }
597 }
598
599 static void io_prep_async_link(struct io_kiocb *req)
600 {
601         struct io_kiocb *cur;
602
603         if (req->flags & REQ_F_LINK_TIMEOUT) {
604                 struct io_ring_ctx *ctx = req->ctx;
605
606                 spin_lock_irq(&ctx->timeout_lock);
607                 io_for_each_link(cur, req)
608                         io_prep_async_work(cur);
609                 spin_unlock_irq(&ctx->timeout_lock);
610         } else {
611                 io_for_each_link(cur, req)
612                         io_prep_async_work(cur);
613         }
614 }
615
616 static inline void io_req_add_compl_list(struct io_kiocb *req)
617 {
618         struct io_submit_state *state = &req->ctx->submit_state;
619
620         if (!(req->flags & REQ_F_CQE_SKIP))
621                 state->flush_cqes = true;
622         wq_list_add_tail(&req->comp_list, &state->compl_reqs);
623 }
624
625 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
626 {
627         struct io_kiocb *link = io_prep_linked_timeout(req);
628         struct io_uring_task *tctx = req->task->io_uring;
629
630         BUG_ON(!tctx);
631         BUG_ON(!tctx->io_wq);
632
633         /* init ->work of the whole link before punting */
634         io_prep_async_link(req);
635
636         /*
637          * Not expected to happen, but if we do have a bug where this _can_
638          * happen, catch it here and ensure the request is marked as
639          * canceled. That will make io-wq go through the usual work cancel
640          * procedure rather than attempt to run this request (or create a new
641          * worker for it).
642          */
643         if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
644                 req->work.flags |= IO_WQ_WORK_CANCEL;
645
646         trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
647                                         req->opcode, req->flags, &req->work,
648                                         io_wq_is_hashed(&req->work));
649         io_wq_enqueue(tctx->io_wq, &req->work);
650         if (link)
651                 io_queue_linked_timeout(link);
652 }
653
654 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
655 {
656         while (!list_empty(&ctx->defer_list)) {
657                 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
658                                                 struct io_defer_entry, list);
659
660                 if (req_need_defer(de->req, de->seq))
661                         break;
662                 list_del_init(&de->list);
663                 io_req_task_queue(de->req);
664                 kfree(de);
665         }
666 }
667
668 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
669 {
670         if (ctx->off_timeout_used || ctx->drain_active) {
671                 spin_lock(&ctx->completion_lock);
672                 if (ctx->off_timeout_used)
673                         io_flush_timeouts(ctx);
674                 if (ctx->drain_active)
675                         io_queue_deferred(ctx);
676                 io_commit_cqring(ctx);
677                 spin_unlock(&ctx->completion_lock);
678         }
679         if (ctx->has_evfd)
680                 io_eventfd_signal(ctx);
681 }
682
683 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
684 {
685         return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
686 }
687
688 /*
689  * writes to the cq entry need to come after reading head; the
690  * control dependency is enough as we're using WRITE_ONCE to
691  * fill the cq entry
692  */
693 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
694 {
695         struct io_rings *rings = ctx->rings;
696         unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
697         unsigned int shift = 0;
698         unsigned int free, queued, len;
699
700         if (ctx->flags & IORING_SETUP_CQE32)
701                 shift = 1;
702
703         /* userspace may cheat modifying the tail, be safe and do min */
704         queued = min(__io_cqring_events(ctx), ctx->cq_entries);
705         free = ctx->cq_entries - queued;
706         /* we need a contiguous range, limit based on the current array offset */
707         len = min(free, ctx->cq_entries - off);
708         if (!len)
709                 return NULL;
710
711         ctx->cached_cq_tail++;
712         ctx->cqe_cached = &rings->cqes[off];
713         ctx->cqe_sentinel = ctx->cqe_cached + len;
714         ctx->cqe_cached++;
715         return &rings->cqes[off << shift];
716 }
717
718 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
719 {
720         if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
721                 struct io_uring_cqe *cqe = ctx->cqe_cached;
722
723                 if (ctx->flags & IORING_SETUP_CQE32) {
724                         unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
725
726                         cqe += off;
727                 }
728
729                 ctx->cached_cq_tail++;
730                 ctx->cqe_cached++;
731                 return cqe;
732         }
733
734         return __io_get_cqe(ctx);
735 }
736
737 static void io_eventfd_signal(struct io_ring_ctx *ctx)
738 {
739         struct io_ev_fd *ev_fd;
740
741         rcu_read_lock();
742         /*
743          * rcu_dereference ctx->io_ev_fd once and use it for both for checking
744          * and eventfd_signal
745          */
746         ev_fd = rcu_dereference(ctx->io_ev_fd);
747
748         /*
749          * Check again if ev_fd exists incase an io_eventfd_unregister call
750          * completed between the NULL check of ctx->io_ev_fd at the start of
751          * the function and rcu_read_lock.
752          */
753         if (unlikely(!ev_fd))
754                 goto out;
755         if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
756                 goto out;
757
758         if (!ev_fd->eventfd_async || io_wq_current_is_worker())
759                 eventfd_signal(ev_fd->cq_ev_fd, 1);
760 out:
761         rcu_read_unlock();
762 }
763
764 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
765 {
766         /*
767          * wake_up_all() may seem excessive, but io_wake_function() and
768          * io_should_wake() handle the termination of the loop and only
769          * wake as many waiters as we need to.
770          */
771         if (wq_has_sleeper(&ctx->cq_wait))
772                 wake_up_all(&ctx->cq_wait);
773 }
774
775 /*
776  * This should only get called when at least one event has been posted.
777  * Some applications rely on the eventfd notification count only changing
778  * IFF a new CQE has been added to the CQ ring. There's no depedency on
779  * 1:1 relationship between how many times this function is called (and
780  * hence the eventfd count) and number of CQEs posted to the CQ ring.
781  */
782 void io_cqring_ev_posted(struct io_ring_ctx *ctx)
783 {
784         if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
785                      ctx->has_evfd))
786                 __io_commit_cqring_flush(ctx);
787
788         io_cqring_wake(ctx);
789 }
790
791 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
792 {
793         if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
794                      ctx->has_evfd))
795                 __io_commit_cqring_flush(ctx);
796
797         if (ctx->flags & IORING_SETUP_SQPOLL)
798                 io_cqring_wake(ctx);
799 }
800
801 /* Returns true if there are no backlogged entries after the flush */
802 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
803 {
804         bool all_flushed, posted;
805         size_t cqe_size = sizeof(struct io_uring_cqe);
806
807         if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
808                 return false;
809
810         if (ctx->flags & IORING_SETUP_CQE32)
811                 cqe_size <<= 1;
812
813         posted = false;
814         spin_lock(&ctx->completion_lock);
815         while (!list_empty(&ctx->cq_overflow_list)) {
816                 struct io_uring_cqe *cqe = io_get_cqe(ctx);
817                 struct io_overflow_cqe *ocqe;
818
819                 if (!cqe && !force)
820                         break;
821                 ocqe = list_first_entry(&ctx->cq_overflow_list,
822                                         struct io_overflow_cqe, list);
823                 if (cqe)
824                         memcpy(cqe, &ocqe->cqe, cqe_size);
825                 else
826                         io_account_cq_overflow(ctx);
827
828                 posted = true;
829                 list_del(&ocqe->list);
830                 kfree(ocqe);
831         }
832
833         all_flushed = list_empty(&ctx->cq_overflow_list);
834         if (all_flushed) {
835                 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
836                 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
837         }
838
839         io_commit_cqring(ctx);
840         spin_unlock(&ctx->completion_lock);
841         if (posted)
842                 io_cqring_ev_posted(ctx);
843         return all_flushed;
844 }
845
846 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
847 {
848         bool ret = true;
849
850         if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
851                 /* iopoll syncs against uring_lock, not completion_lock */
852                 if (ctx->flags & IORING_SETUP_IOPOLL)
853                         mutex_lock(&ctx->uring_lock);
854                 ret = __io_cqring_overflow_flush(ctx, false);
855                 if (ctx->flags & IORING_SETUP_IOPOLL)
856                         mutex_unlock(&ctx->uring_lock);
857         }
858
859         return ret;
860 }
861
862 static void __io_put_task(struct task_struct *task, int nr)
863 {
864         struct io_uring_task *tctx = task->io_uring;
865
866         percpu_counter_sub(&tctx->inflight, nr);
867         if (unlikely(atomic_read(&tctx->in_idle)))
868                 wake_up(&tctx->wait);
869         put_task_struct_many(task, nr);
870 }
871
872 /* must to be called somewhat shortly after putting a request */
873 static inline void io_put_task(struct task_struct *task, int nr)
874 {
875         if (likely(task == current))
876                 task->io_uring->cached_refs += nr;
877         else
878                 __io_put_task(task, nr);
879 }
880
881 static void io_task_refs_refill(struct io_uring_task *tctx)
882 {
883         unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
884
885         percpu_counter_add(&tctx->inflight, refill);
886         refcount_add(refill, &current->usage);
887         tctx->cached_refs += refill;
888 }
889
890 static inline void io_get_task_refs(int nr)
891 {
892         struct io_uring_task *tctx = current->io_uring;
893
894         tctx->cached_refs -= nr;
895         if (unlikely(tctx->cached_refs < 0))
896                 io_task_refs_refill(tctx);
897 }
898
899 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
900 {
901         struct io_uring_task *tctx = task->io_uring;
902         unsigned int refs = tctx->cached_refs;
903
904         if (refs) {
905                 tctx->cached_refs = 0;
906                 percpu_counter_sub(&tctx->inflight, refs);
907                 put_task_struct_many(task, refs);
908         }
909 }
910
911 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
912                                      s32 res, u32 cflags, u64 extra1,
913                                      u64 extra2)
914 {
915         struct io_overflow_cqe *ocqe;
916         size_t ocq_size = sizeof(struct io_overflow_cqe);
917         bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
918
919         if (is_cqe32)
920                 ocq_size += sizeof(struct io_uring_cqe);
921
922         ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
923         trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
924         if (!ocqe) {
925                 /*
926                  * If we're in ring overflow flush mode, or in task cancel mode,
927                  * or cannot allocate an overflow entry, then we need to drop it
928                  * on the floor.
929                  */
930                 io_account_cq_overflow(ctx);
931                 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
932                 return false;
933         }
934         if (list_empty(&ctx->cq_overflow_list)) {
935                 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
936                 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
937
938         }
939         ocqe->cqe.user_data = user_data;
940         ocqe->cqe.res = res;
941         ocqe->cqe.flags = cflags;
942         if (is_cqe32) {
943                 ocqe->cqe.big_cqe[0] = extra1;
944                 ocqe->cqe.big_cqe[1] = extra2;
945         }
946         list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
947         return true;
948 }
949
950 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
951                                      struct io_kiocb *req)
952 {
953         struct io_uring_cqe *cqe;
954
955         if (!(ctx->flags & IORING_SETUP_CQE32)) {
956                 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
957                                         req->cqe.res, req->cqe.flags, 0, 0);
958
959                 /*
960                  * If we can't get a cq entry, userspace overflowed the
961                  * submission (by quite a lot). Increment the overflow count in
962                  * the ring.
963                  */
964                 cqe = io_get_cqe(ctx);
965                 if (likely(cqe)) {
966                         memcpy(cqe, &req->cqe, sizeof(*cqe));
967                         return true;
968                 }
969
970                 return io_cqring_event_overflow(ctx, req->cqe.user_data,
971                                                 req->cqe.res, req->cqe.flags,
972                                                 0, 0);
973         } else {
974                 u64 extra1 = 0, extra2 = 0;
975
976                 if (req->flags & REQ_F_CQE32_INIT) {
977                         extra1 = req->extra1;
978                         extra2 = req->extra2;
979                 }
980
981                 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
982                                         req->cqe.res, req->cqe.flags, extra1, extra2);
983
984                 /*
985                  * If we can't get a cq entry, userspace overflowed the
986                  * submission (by quite a lot). Increment the overflow count in
987                  * the ring.
988                  */
989                 cqe = io_get_cqe(ctx);
990                 if (likely(cqe)) {
991                         memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
992                         WRITE_ONCE(cqe->big_cqe[0], extra1);
993                         WRITE_ONCE(cqe->big_cqe[1], extra2);
994                         return true;
995                 }
996
997                 return io_cqring_event_overflow(ctx, req->cqe.user_data,
998                                 req->cqe.res, req->cqe.flags,
999                                 extra1, extra2);
1000         }
1001 }
1002
1003 bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
1004                      u32 cflags)
1005 {
1006         struct io_uring_cqe *cqe;
1007
1008         ctx->cq_extra++;
1009         trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
1010
1011         /*
1012          * If we can't get a cq entry, userspace overflowed the
1013          * submission (by quite a lot). Increment the overflow count in
1014          * the ring.
1015          */
1016         cqe = io_get_cqe(ctx);
1017         if (likely(cqe)) {
1018                 WRITE_ONCE(cqe->user_data, user_data);
1019                 WRITE_ONCE(cqe->res, res);
1020                 WRITE_ONCE(cqe->flags, cflags);
1021
1022                 if (ctx->flags & IORING_SETUP_CQE32) {
1023                         WRITE_ONCE(cqe->big_cqe[0], 0);
1024                         WRITE_ONCE(cqe->big_cqe[1], 0);
1025                 }
1026                 return true;
1027         }
1028         return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
1029 }
1030
1031 static void __io_req_complete_put(struct io_kiocb *req)
1032 {
1033         /*
1034          * If we're the last reference to this request, add to our locked
1035          * free_list cache.
1036          */
1037         if (req_ref_put_and_test(req)) {
1038                 struct io_ring_ctx *ctx = req->ctx;
1039
1040                 if (req->flags & IO_REQ_LINK_FLAGS) {
1041                         if (req->flags & IO_DISARM_MASK)
1042                                 io_disarm_next(req);
1043                         if (req->link) {
1044                                 io_req_task_queue(req->link);
1045                                 req->link = NULL;
1046                         }
1047                 }
1048                 io_req_put_rsrc(req);
1049                 /*
1050                  * Selected buffer deallocation in io_clean_op() assumes that
1051                  * we don't hold ->completion_lock. Clean them here to avoid
1052                  * deadlocks.
1053                  */
1054                 io_put_kbuf_comp(req);
1055                 io_dismantle_req(req);
1056                 io_put_task(req->task, 1);
1057                 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1058                 ctx->locked_free_nr++;
1059         }
1060 }
1061
1062 void __io_req_complete_post(struct io_kiocb *req)
1063 {
1064         if (!(req->flags & REQ_F_CQE_SKIP))
1065                 __io_fill_cqe_req(req->ctx, req);
1066         __io_req_complete_put(req);
1067 }
1068
1069 void io_req_complete_post(struct io_kiocb *req)
1070 {
1071         struct io_ring_ctx *ctx = req->ctx;
1072
1073         spin_lock(&ctx->completion_lock);
1074         __io_req_complete_post(req);
1075         io_commit_cqring(ctx);
1076         spin_unlock(&ctx->completion_lock);
1077         io_cqring_ev_posted(ctx);
1078 }
1079
1080 inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags)
1081 {
1082         if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1083                 req->flags |= REQ_F_COMPLETE_INLINE;
1084         else
1085                 io_req_complete_post(req);
1086 }
1087
1088 void io_req_complete_failed(struct io_kiocb *req, s32 res)
1089 {
1090         req_set_fail(req);
1091         io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1092         io_req_complete_post(req);
1093 }
1094
1095 /*
1096  * Don't initialise the fields below on every allocation, but do that in
1097  * advance and keep them valid across allocations.
1098  */
1099 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1100 {
1101         req->ctx = ctx;
1102         req->link = NULL;
1103         req->async_data = NULL;
1104         /* not necessary, but safer to zero */
1105         req->cqe.res = 0;
1106 }
1107
1108 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1109                                         struct io_submit_state *state)
1110 {
1111         spin_lock(&ctx->completion_lock);
1112         wq_list_splice(&ctx->locked_free_list, &state->free_list);
1113         ctx->locked_free_nr = 0;
1114         spin_unlock(&ctx->completion_lock);
1115 }
1116
1117 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
1118 {
1119         return !ctx->submit_state.free_list.next;
1120 }
1121
1122 /*
1123  * A request might get retired back into the request caches even before opcode
1124  * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1125  * Because of that, io_alloc_req() should be called only under ->uring_lock
1126  * and with extra caution to not get a request that is still worked on.
1127  */
1128 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1129         __must_hold(&ctx->uring_lock)
1130 {
1131         gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1132         void *reqs[IO_REQ_ALLOC_BATCH];
1133         int ret, i;
1134
1135         /*
1136          * If we have more than a batch's worth of requests in our IRQ side
1137          * locked cache, grab the lock and move them over to our submission
1138          * side cache.
1139          */
1140         if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1141                 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1142                 if (!io_req_cache_empty(ctx))
1143                         return true;
1144         }
1145
1146         ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1147
1148         /*
1149          * Bulk alloc is all-or-nothing. If we fail to get a batch,
1150          * retry single alloc to be on the safe side.
1151          */
1152         if (unlikely(ret <= 0)) {
1153                 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1154                 if (!reqs[0])
1155                         return false;
1156                 ret = 1;
1157         }
1158
1159         percpu_ref_get_many(&ctx->refs, ret);
1160         for (i = 0; i < ret; i++) {
1161                 struct io_kiocb *req = reqs[i];
1162
1163                 io_preinit_req(req, ctx);
1164                 io_req_add_to_cache(req, ctx);
1165         }
1166         return true;
1167 }
1168
1169 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
1170 {
1171         if (unlikely(io_req_cache_empty(ctx)))
1172                 return __io_alloc_req_refill(ctx);
1173         return true;
1174 }
1175
1176 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1177 {
1178         struct io_wq_work_node *node;
1179
1180         node = wq_stack_extract(&ctx->submit_state.free_list);
1181         return container_of(node, struct io_kiocb, comp_list);
1182 }
1183
1184 static inline void io_dismantle_req(struct io_kiocb *req)
1185 {
1186         unsigned int flags = req->flags;
1187
1188         if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
1189                 io_clean_op(req);
1190         if (!(flags & REQ_F_FIXED_FILE))
1191                 io_put_file(req->file);
1192 }
1193
1194 __cold void io_free_req(struct io_kiocb *req)
1195 {
1196         struct io_ring_ctx *ctx = req->ctx;
1197
1198         io_req_put_rsrc(req);
1199         io_dismantle_req(req);
1200         io_put_task(req->task, 1);
1201
1202         spin_lock(&ctx->completion_lock);
1203         wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1204         ctx->locked_free_nr++;
1205         spin_unlock(&ctx->completion_lock);
1206 }
1207
1208 static void __io_req_find_next_prep(struct io_kiocb *req)
1209 {
1210         struct io_ring_ctx *ctx = req->ctx;
1211         bool posted;
1212
1213         spin_lock(&ctx->completion_lock);
1214         posted = io_disarm_next(req);
1215         io_commit_cqring(ctx);
1216         spin_unlock(&ctx->completion_lock);
1217         if (posted)
1218                 io_cqring_ev_posted(ctx);
1219 }
1220
1221 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1222 {
1223         struct io_kiocb *nxt;
1224
1225         /*
1226          * If LINK is set, we have dependent requests in this chain. If we
1227          * didn't fail this request, queue the first one up, moving any other
1228          * dependencies to the next request. In case of failure, fail the rest
1229          * of the chain.
1230          */
1231         if (unlikely(req->flags & IO_DISARM_MASK))
1232                 __io_req_find_next_prep(req);
1233         nxt = req->link;
1234         req->link = NULL;
1235         return nxt;
1236 }
1237
1238 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
1239 {
1240         if (!ctx)
1241                 return;
1242         if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1243                 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1244         if (*locked) {
1245                 io_submit_flush_completions(ctx);
1246                 mutex_unlock(&ctx->uring_lock);
1247                 *locked = false;
1248         }
1249         percpu_ref_put(&ctx->refs);
1250 }
1251
1252 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
1253 {
1254         io_commit_cqring(ctx);
1255         spin_unlock(&ctx->completion_lock);
1256         io_cqring_ev_posted(ctx);
1257 }
1258
1259 static void handle_prev_tw_list(struct io_wq_work_node *node,
1260                                 struct io_ring_ctx **ctx, bool *uring_locked)
1261 {
1262         if (*ctx && !*uring_locked)
1263                 spin_lock(&(*ctx)->completion_lock);
1264
1265         do {
1266                 struct io_wq_work_node *next = node->next;
1267                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1268                                                     io_task_work.node);
1269
1270                 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1271
1272                 if (req->ctx != *ctx) {
1273                         if (unlikely(!*uring_locked && *ctx))
1274                                 ctx_commit_and_unlock(*ctx);
1275
1276                         ctx_flush_and_put(*ctx, uring_locked);
1277                         *ctx = req->ctx;
1278                         /* if not contended, grab and improve batching */
1279                         *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
1280                         percpu_ref_get(&(*ctx)->refs);
1281                         if (unlikely(!*uring_locked))
1282                                 spin_lock(&(*ctx)->completion_lock);
1283                 }
1284                 if (likely(*uring_locked)) {
1285                         req->io_task_work.func(req, uring_locked);
1286                 } else {
1287                         req->cqe.flags = io_put_kbuf_comp(req);
1288                         __io_req_complete_post(req);
1289                 }
1290                 node = next;
1291         } while (node);
1292
1293         if (unlikely(!*uring_locked))
1294                 ctx_commit_and_unlock(*ctx);
1295 }
1296
1297 static void handle_tw_list(struct io_wq_work_node *node,
1298                            struct io_ring_ctx **ctx, bool *locked)
1299 {
1300         do {
1301                 struct io_wq_work_node *next = node->next;
1302                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1303                                                     io_task_work.node);
1304
1305                 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1306
1307                 if (req->ctx != *ctx) {
1308                         ctx_flush_and_put(*ctx, locked);
1309                         *ctx = req->ctx;
1310                         /* if not contended, grab and improve batching */
1311                         *locked = mutex_trylock(&(*ctx)->uring_lock);
1312                         percpu_ref_get(&(*ctx)->refs);
1313                 }
1314                 req->io_task_work.func(req, locked);
1315                 node = next;
1316         } while (node);
1317 }
1318
1319 void tctx_task_work(struct callback_head *cb)
1320 {
1321         bool uring_locked = false;
1322         struct io_ring_ctx *ctx = NULL;
1323         struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1324                                                   task_work);
1325
1326         while (1) {
1327                 struct io_wq_work_node *node1, *node2;
1328
1329                 spin_lock_irq(&tctx->task_lock);
1330                 node1 = tctx->prio_task_list.first;
1331                 node2 = tctx->task_list.first;
1332                 INIT_WQ_LIST(&tctx->task_list);
1333                 INIT_WQ_LIST(&tctx->prio_task_list);
1334                 if (!node2 && !node1)
1335                         tctx->task_running = false;
1336                 spin_unlock_irq(&tctx->task_lock);
1337                 if (!node2 && !node1)
1338                         break;
1339
1340                 if (node1)
1341                         handle_prev_tw_list(node1, &ctx, &uring_locked);
1342                 if (node2)
1343                         handle_tw_list(node2, &ctx, &uring_locked);
1344                 cond_resched();
1345
1346                 if (data_race(!tctx->task_list.first) &&
1347                     data_race(!tctx->prio_task_list.first) && uring_locked)
1348                         io_submit_flush_completions(ctx);
1349         }
1350
1351         ctx_flush_and_put(ctx, &uring_locked);
1352
1353         /* relaxed read is enough as only the task itself sets ->in_idle */
1354         if (unlikely(atomic_read(&tctx->in_idle)))
1355                 io_uring_drop_tctx_refs(current);
1356 }
1357
1358 static void __io_req_task_work_add(struct io_kiocb *req,
1359                                    struct io_uring_task *tctx,
1360                                    struct io_wq_work_list *list)
1361 {
1362         struct io_ring_ctx *ctx = req->ctx;
1363         struct io_wq_work_node *node;
1364         unsigned long flags;
1365         bool running;
1366
1367         spin_lock_irqsave(&tctx->task_lock, flags);
1368         wq_list_add_tail(&req->io_task_work.node, list);
1369         running = tctx->task_running;
1370         if (!running)
1371                 tctx->task_running = true;
1372         spin_unlock_irqrestore(&tctx->task_lock, flags);
1373
1374         /* task_work already pending, we're done */
1375         if (running)
1376                 return;
1377
1378         if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1379                 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1380
1381         if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1382                 return;
1383
1384         spin_lock_irqsave(&tctx->task_lock, flags);
1385         tctx->task_running = false;
1386         node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
1387         spin_unlock_irqrestore(&tctx->task_lock, flags);
1388
1389         while (node) {
1390                 req = container_of(node, struct io_kiocb, io_task_work.node);
1391                 node = node->next;
1392                 if (llist_add(&req->io_task_work.fallback_node,
1393                               &req->ctx->fallback_llist))
1394                         schedule_delayed_work(&req->ctx->fallback_work, 1);
1395         }
1396 }
1397
1398 void io_req_task_work_add(struct io_kiocb *req)
1399 {
1400         struct io_uring_task *tctx = req->task->io_uring;
1401
1402         __io_req_task_work_add(req, tctx, &tctx->task_list);
1403 }
1404
1405 static void io_req_task_prio_work_add(struct io_kiocb *req)
1406 {
1407         struct io_uring_task *tctx = req->task->io_uring;
1408
1409         if (req->ctx->flags & IORING_SETUP_SQPOLL)
1410                 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
1411         else
1412                 __io_req_task_work_add(req, tctx, &tctx->task_list);
1413 }
1414
1415 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
1416 {
1417         io_req_complete_post(req);
1418 }
1419
1420 void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
1421 {
1422         io_req_set_res(req, res, cflags);
1423         req->io_task_work.func = io_req_tw_post;
1424         io_req_task_work_add(req);
1425 }
1426
1427 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
1428 {
1429         /* not needed for normal modes, but SQPOLL depends on it */
1430         io_tw_lock(req->ctx, locked);
1431         io_req_complete_failed(req, req->cqe.res);
1432 }
1433
1434 void io_req_task_submit(struct io_kiocb *req, bool *locked)
1435 {
1436         io_tw_lock(req->ctx, locked);
1437         /* req->task == current here, checking PF_EXITING is safe */
1438         if (likely(!(req->task->flags & PF_EXITING)))
1439                 io_queue_sqe(req);
1440         else
1441                 io_req_complete_failed(req, -EFAULT);
1442 }
1443
1444 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1445 {
1446         io_req_set_res(req, ret, 0);
1447         req->io_task_work.func = io_req_task_cancel;
1448         io_req_task_work_add(req);
1449 }
1450
1451 static void io_req_task_queue(struct io_kiocb *req)
1452 {
1453         req->io_task_work.func = io_req_task_submit;
1454         io_req_task_work_add(req);
1455 }
1456
1457 static void io_req_task_queue_reissue(struct io_kiocb *req)
1458 {
1459         req->io_task_work.func = io_queue_iowq;
1460         io_req_task_work_add(req);
1461 }
1462
1463 void io_queue_next(struct io_kiocb *req)
1464 {
1465         struct io_kiocb *nxt = io_req_find_next(req);
1466
1467         if (nxt)
1468                 io_req_task_queue(nxt);
1469 }
1470
1471 static void io_free_batch_list(struct io_ring_ctx *ctx,
1472                                 struct io_wq_work_node *node)
1473         __must_hold(&ctx->uring_lock)
1474 {
1475         struct task_struct *task = NULL;
1476         int task_refs = 0;
1477
1478         do {
1479                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1480                                                     comp_list);
1481
1482                 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1483                         if (req->flags & REQ_F_REFCOUNT) {
1484                                 node = req->comp_list.next;
1485                                 if (!req_ref_put_and_test(req))
1486                                         continue;
1487                         }
1488                         if ((req->flags & REQ_F_POLLED) && req->apoll) {
1489                                 struct async_poll *apoll = req->apoll;
1490
1491                                 if (apoll->double_poll)
1492                                         kfree(apoll->double_poll);
1493                                 list_add(&apoll->poll.wait.entry,
1494                                                 &ctx->apoll_cache);
1495                                 req->flags &= ~REQ_F_POLLED;
1496                         }
1497                         if (req->flags & IO_REQ_LINK_FLAGS)
1498                                 io_queue_next(req);
1499                         if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1500                                 io_clean_op(req);
1501                 }
1502                 if (!(req->flags & REQ_F_FIXED_FILE))
1503                         io_put_file(req->file);
1504
1505                 io_req_put_rsrc_locked(req, ctx);
1506
1507                 if (req->task != task) {
1508                         if (task)
1509                                 io_put_task(task, task_refs);
1510                         task = req->task;
1511                         task_refs = 0;
1512                 }
1513                 task_refs++;
1514                 node = req->comp_list.next;
1515                 io_req_add_to_cache(req, ctx);
1516         } while (node);
1517
1518         if (task)
1519                 io_put_task(task, task_refs);
1520 }
1521
1522 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1523         __must_hold(&ctx->uring_lock)
1524 {
1525         struct io_wq_work_node *node, *prev;
1526         struct io_submit_state *state = &ctx->submit_state;
1527
1528         if (state->flush_cqes) {
1529                 spin_lock(&ctx->completion_lock);
1530                 wq_list_for_each(node, prev, &state->compl_reqs) {
1531                         struct io_kiocb *req = container_of(node, struct io_kiocb,
1532                                                     comp_list);
1533
1534                         if (!(req->flags & REQ_F_CQE_SKIP))
1535                                 __io_fill_cqe_req(ctx, req);
1536                 }
1537
1538                 io_commit_cqring(ctx);
1539                 spin_unlock(&ctx->completion_lock);
1540                 io_cqring_ev_posted(ctx);
1541                 state->flush_cqes = false;
1542         }
1543
1544         io_free_batch_list(ctx, state->compl_reqs.first);
1545         INIT_WQ_LIST(&state->compl_reqs);
1546 }
1547
1548 /*
1549  * Drop reference to request, return next in chain (if there is one) if this
1550  * was the last reference to this request.
1551  */
1552 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
1553 {
1554         struct io_kiocb *nxt = NULL;
1555
1556         if (req_ref_put_and_test(req)) {
1557                 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
1558                         nxt = io_req_find_next(req);
1559                 io_free_req(req);
1560         }
1561         return nxt;
1562 }
1563
1564 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1565 {
1566         /* See comment at the top of this file */
1567         smp_rmb();
1568         return __io_cqring_events(ctx);
1569 }
1570
1571 int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
1572 {
1573         struct io_wq_work_node *pos, *start, *prev;
1574         unsigned int poll_flags = BLK_POLL_NOSLEEP;
1575         DEFINE_IO_COMP_BATCH(iob);
1576         int nr_events = 0;
1577
1578         /*
1579          * Only spin for completions if we don't have multiple devices hanging
1580          * off our complete list.
1581          */
1582         if (ctx->poll_multi_queue || force_nonspin)
1583                 poll_flags |= BLK_POLL_ONESHOT;
1584
1585         wq_list_for_each(pos, start, &ctx->iopoll_list) {
1586                 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
1587                 struct io_rw *rw = io_kiocb_to_cmd(req);
1588                 int ret;
1589
1590                 /*
1591                  * Move completed and retryable entries to our local lists.
1592                  * If we find a request that requires polling, break out
1593                  * and complete those lists first, if we have entries there.
1594                  */
1595                 if (READ_ONCE(req->iopoll_completed))
1596                         break;
1597
1598                 ret = rw->kiocb.ki_filp->f_op->iopoll(&rw->kiocb, &iob, poll_flags);
1599                 if (unlikely(ret < 0))
1600                         return ret;
1601                 else if (ret)
1602                         poll_flags |= BLK_POLL_ONESHOT;
1603
1604                 /* iopoll may have completed current req */
1605                 if (!rq_list_empty(iob.req_list) ||
1606                     READ_ONCE(req->iopoll_completed))
1607                         break;
1608         }
1609
1610         if (!rq_list_empty(iob.req_list))
1611                 iob.complete(&iob);
1612         else if (!pos)
1613                 return 0;
1614
1615         prev = start;
1616         wq_list_for_each_resume(pos, prev) {
1617                 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
1618
1619                 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
1620                 if (!smp_load_acquire(&req->iopoll_completed))
1621                         break;
1622                 nr_events++;
1623                 if (unlikely(req->flags & REQ_F_CQE_SKIP))
1624                         continue;
1625
1626                 req->cqe.flags = io_put_kbuf(req, 0);
1627                 __io_fill_cqe_req(req->ctx, req);
1628         }
1629
1630         if (unlikely(!nr_events))
1631                 return 0;
1632
1633         io_commit_cqring(ctx);
1634         io_cqring_ev_posted_iopoll(ctx);
1635         pos = start ? start->next : ctx->iopoll_list.first;
1636         wq_list_cut(&ctx->iopoll_list, prev, start);
1637         io_free_batch_list(ctx, pos);
1638         return nr_events;
1639 }
1640
1641 /*
1642  * We can't just wait for polled events to come to us, we have to actively
1643  * find and complete them.
1644  */
1645 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1646 {
1647         if (!(ctx->flags & IORING_SETUP_IOPOLL))
1648                 return;
1649
1650         mutex_lock(&ctx->uring_lock);
1651         while (!wq_list_empty(&ctx->iopoll_list)) {
1652                 /* let it sleep and repeat later if can't complete a request */
1653                 if (io_do_iopoll(ctx, true) == 0)
1654                         break;
1655                 /*
1656                  * Ensure we allow local-to-the-cpu processing to take place,
1657                  * in this case we need to ensure that we reap all events.
1658                  * Also let task_work, etc. to progress by releasing the mutex
1659                  */
1660                 if (need_resched()) {
1661                         mutex_unlock(&ctx->uring_lock);
1662                         cond_resched();
1663                         mutex_lock(&ctx->uring_lock);
1664                 }
1665         }
1666         mutex_unlock(&ctx->uring_lock);
1667 }
1668
1669 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1670 {
1671         unsigned int nr_events = 0;
1672         int ret = 0;
1673         unsigned long check_cq;
1674
1675         /*
1676          * Don't enter poll loop if we already have events pending.
1677          * If we do, we can potentially be spinning for commands that
1678          * already triggered a CQE (eg in error).
1679          */
1680         check_cq = READ_ONCE(ctx->check_cq);
1681         if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1682                 __io_cqring_overflow_flush(ctx, false);
1683         if (io_cqring_events(ctx))
1684                 return 0;
1685
1686         /*
1687          * Similarly do not spin if we have not informed the user of any
1688          * dropped CQE.
1689          */
1690         if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
1691                 return -EBADR;
1692
1693         do {
1694                 /*
1695                  * If a submit got punted to a workqueue, we can have the
1696                  * application entering polling for a command before it gets
1697                  * issued. That app will hold the uring_lock for the duration
1698                  * of the poll right here, so we need to take a breather every
1699                  * now and then to ensure that the issue has a chance to add
1700                  * the poll to the issued list. Otherwise we can spin here
1701                  * forever, while the workqueue is stuck trying to acquire the
1702                  * very same mutex.
1703                  */
1704                 if (wq_list_empty(&ctx->iopoll_list)) {
1705                         u32 tail = ctx->cached_cq_tail;
1706
1707                         mutex_unlock(&ctx->uring_lock);
1708                         io_run_task_work();
1709                         mutex_lock(&ctx->uring_lock);
1710
1711                         /* some requests don't go through iopoll_list */
1712                         if (tail != ctx->cached_cq_tail ||
1713                             wq_list_empty(&ctx->iopoll_list))
1714                                 break;
1715                 }
1716                 ret = io_do_iopoll(ctx, !min);
1717                 if (ret < 0)
1718                         break;
1719                 nr_events += ret;
1720                 ret = 0;
1721         } while (nr_events < min && !need_resched());
1722
1723         return ret;
1724 }
1725
1726 static void kiocb_end_write(struct io_kiocb *req)
1727 {
1728         /*
1729          * Tell lockdep we inherited freeze protection from submission
1730          * thread.
1731          */
1732         if (req->flags & REQ_F_ISREG) {
1733                 struct super_block *sb = file_inode(req->file)->i_sb;
1734
1735                 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
1736                 sb_end_write(sb);
1737         }
1738 }
1739
1740 #ifdef CONFIG_BLOCK
1741 static bool io_resubmit_prep(struct io_kiocb *req)
1742 {
1743         struct io_async_rw *io = req->async_data;
1744
1745         if (!req_has_async_data(req))
1746                 return !io_req_prep_async(req);
1747         iov_iter_restore(&io->s.iter, &io->s.iter_state);
1748         return true;
1749 }
1750
1751 static bool io_rw_should_reissue(struct io_kiocb *req)
1752 {
1753         umode_t mode = file_inode(req->file)->i_mode;
1754         struct io_ring_ctx *ctx = req->ctx;
1755
1756         if (!S_ISBLK(mode) && !S_ISREG(mode))
1757                 return false;
1758         if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
1759             !(ctx->flags & IORING_SETUP_IOPOLL)))
1760                 return false;
1761         /*
1762          * If ref is dying, we might be running poll reap from the exit work.
1763          * Don't attempt to reissue from that path, just let it fail with
1764          * -EAGAIN.
1765          */
1766         if (percpu_ref_is_dying(&ctx->refs))
1767                 return false;
1768         /*
1769          * Play it safe and assume not safe to re-import and reissue if we're
1770          * not in the original thread group (or in task context).
1771          */
1772         if (!same_thread_group(req->task, current) || !in_task())
1773                 return false;
1774         return true;
1775 }
1776 #else
1777 static bool io_resubmit_prep(struct io_kiocb *req)
1778 {
1779         return false;
1780 }
1781 static bool io_rw_should_reissue(struct io_kiocb *req)
1782 {
1783         return false;
1784 }
1785 #endif
1786
1787 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
1788 {
1789         struct io_rw *rw = io_kiocb_to_cmd(req);
1790
1791         if (rw->kiocb.ki_flags & IOCB_WRITE) {
1792                 kiocb_end_write(req);
1793                 fsnotify_modify(req->file);
1794         } else {
1795                 fsnotify_access(req->file);
1796         }
1797         if (unlikely(res != req->cqe.res)) {
1798                 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
1799                     io_rw_should_reissue(req)) {
1800                         req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
1801                         return true;
1802                 }
1803                 req_set_fail(req);
1804                 req->cqe.res = res;
1805         }
1806         return false;
1807 }
1808
1809 inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
1810 {
1811         if (*locked) {
1812                 req->cqe.flags |= io_put_kbuf(req, 0);
1813                 req->flags |= REQ_F_COMPLETE_INLINE;
1814                 io_req_add_compl_list(req);
1815         } else {
1816                 req->cqe.flags |= io_put_kbuf(req, IO_URING_F_UNLOCKED);
1817                 io_req_complete_post(req);
1818         }
1819 }
1820
1821 static void __io_complete_rw(struct io_kiocb *req, long res,
1822                              unsigned int issue_flags)
1823 {
1824         if (__io_complete_rw_common(req, res))
1825                 return;
1826         io_req_set_res(req, req->cqe.res, io_put_kbuf(req, issue_flags));
1827         __io_req_complete(req, issue_flags);
1828 }
1829
1830 static void io_complete_rw(struct kiocb *kiocb, long res)
1831 {
1832         struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
1833         struct io_kiocb *req = cmd_to_io_kiocb(rw);
1834
1835         if (__io_complete_rw_common(req, res))
1836                 return;
1837         io_req_set_res(req, res, 0);
1838         req->io_task_work.func = io_req_task_complete;
1839         io_req_task_prio_work_add(req);
1840 }
1841
1842 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
1843 {
1844         struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
1845         struct io_kiocb *req = cmd_to_io_kiocb(rw);
1846
1847         if (kiocb->ki_flags & IOCB_WRITE)
1848                 kiocb_end_write(req);
1849         if (unlikely(res != req->cqe.res)) {
1850                 if (res == -EAGAIN && io_rw_should_reissue(req)) {
1851                         req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
1852                         return;
1853                 }
1854                 req->cqe.res = res;
1855         }
1856
1857         /* order with io_iopoll_complete() checking ->iopoll_completed */
1858         smp_store_release(&req->iopoll_completed, 1);
1859 }
1860
1861 /*
1862  * After the iocb has been issued, it's safe to be found on the poll list.
1863  * Adding the kiocb to the list AFTER submission ensures that we don't
1864  * find it from a io_do_iopoll() thread before the issuer is done
1865  * accessing the kiocb cookie.
1866  */
1867 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1868 {
1869         struct io_ring_ctx *ctx = req->ctx;
1870         const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1871
1872         /* workqueue context doesn't hold uring_lock, grab it now */
1873         if (unlikely(needs_lock))
1874                 mutex_lock(&ctx->uring_lock);
1875
1876         /*
1877          * Track whether we have multiple files in our lists. This will impact
1878          * how we do polling eventually, not spinning if we're on potentially
1879          * different devices.
1880          */
1881         if (wq_list_empty(&ctx->iopoll_list)) {
1882                 ctx->poll_multi_queue = false;
1883         } else if (!ctx->poll_multi_queue) {
1884                 struct io_kiocb *list_req;
1885
1886                 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1887                                         comp_list);
1888                 if (list_req->file != req->file)
1889                         ctx->poll_multi_queue = true;
1890         }
1891
1892         /*
1893          * For fast devices, IO may have already completed. If it has, add
1894          * it to the front so we find it first.
1895          */
1896         if (READ_ONCE(req->iopoll_completed))
1897                 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1898         else
1899                 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1900
1901         if (unlikely(needs_lock)) {
1902                 /*
1903                  * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1904                  * in sq thread task context or in io worker task context. If
1905                  * current task context is sq thread, we don't need to check
1906                  * whether should wake up sq thread.
1907                  */
1908                 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1909                     wq_has_sleeper(&ctx->sq_data->wait))
1910                         wake_up(&ctx->sq_data->wait);
1911
1912                 mutex_unlock(&ctx->uring_lock);
1913         }
1914 }
1915
1916 static bool io_bdev_nowait(struct block_device *bdev)
1917 {
1918         return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
1919 }
1920
1921 /*
1922  * If we tracked the file through the SCM inflight mechanism, we could support
1923  * any file. For now, just ensure that anything potentially problematic is done
1924  * inline.
1925  */
1926 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
1927 {
1928         if (S_ISBLK(mode)) {
1929                 if (IS_ENABLED(CONFIG_BLOCK) &&
1930                     io_bdev_nowait(I_BDEV(file->f_mapping->host)))
1931                         return true;
1932                 return false;
1933         }
1934         if (S_ISSOCK(mode))
1935                 return true;
1936         if (S_ISREG(mode)) {
1937                 if (IS_ENABLED(CONFIG_BLOCK) &&
1938                     io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
1939                     !io_is_uring_fops(file))
1940                         return true;
1941                 return false;
1942         }
1943
1944         /* any ->read/write should understand O_NONBLOCK */
1945         if (file->f_flags & O_NONBLOCK)
1946                 return true;
1947         return file->f_mode & FMODE_NOWAIT;
1948 }
1949
1950 /*
1951  * If we tracked the file through the SCM inflight mechanism, we could support
1952  * any file. For now, just ensure that anything potentially problematic is done
1953  * inline.
1954  */
1955 unsigned int io_file_get_flags(struct file *file)
1956 {
1957         umode_t mode = file_inode(file)->i_mode;
1958         unsigned int res = 0;
1959
1960         if (S_ISREG(mode))
1961                 res |= FFS_ISREG;
1962         if (__io_file_supports_nowait(file, mode))
1963                 res |= FFS_NOWAIT;
1964         if (io_file_need_scm(file))
1965                 res |= FFS_SCM;
1966         return res;
1967 }
1968
1969 static inline bool io_file_supports_nowait(struct io_kiocb *req)
1970 {
1971         return req->flags & REQ_F_SUPPORT_NOWAIT;
1972 }
1973
1974 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1975 {
1976         struct io_rw *rw = io_kiocb_to_cmd(req);
1977         unsigned ioprio;
1978         int ret;
1979
1980         rw->kiocb.ki_pos = READ_ONCE(sqe->off);
1981         /* used for fixed read/write too - just read unconditionally */
1982         req->buf_index = READ_ONCE(sqe->buf_index);
1983
1984         if (req->opcode == IORING_OP_READ_FIXED ||
1985             req->opcode == IORING_OP_WRITE_FIXED) {
1986                 struct io_ring_ctx *ctx = req->ctx;
1987                 u16 index;
1988
1989                 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
1990                         return -EFAULT;
1991                 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
1992                 req->imu = ctx->user_bufs[index];
1993                 io_req_set_rsrc_node(req, ctx, 0);
1994         }
1995
1996         ioprio = READ_ONCE(sqe->ioprio);
1997         if (ioprio) {
1998                 ret = ioprio_check_cap(ioprio);
1999                 if (ret)
2000                         return ret;
2001
2002                 rw->kiocb.ki_ioprio = ioprio;
2003         } else {
2004                 rw->kiocb.ki_ioprio = get_current_ioprio();
2005         }
2006
2007         rw->addr = READ_ONCE(sqe->addr);
2008         rw->len = READ_ONCE(sqe->len);
2009         rw->flags = READ_ONCE(sqe->rw_flags);
2010         return 0;
2011 }
2012
2013 static void io_readv_writev_cleanup(struct io_kiocb *req)
2014 {
2015         struct io_async_rw *io = req->async_data;
2016
2017         kfree(io->free_iovec);
2018 }
2019
2020 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2021 {
2022         switch (ret) {
2023         case -EIOCBQUEUED:
2024                 break;
2025         case -ERESTARTSYS:
2026         case -ERESTARTNOINTR:
2027         case -ERESTARTNOHAND:
2028         case -ERESTART_RESTARTBLOCK:
2029                 /*
2030                  * We can't just restart the syscall, since previously
2031                  * submitted sqes may already be in progress. Just fail this
2032                  * IO with EINTR.
2033                  */
2034                 ret = -EINTR;
2035                 fallthrough;
2036         default:
2037                 kiocb->ki_complete(kiocb, ret);
2038         }
2039 }
2040
2041 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
2042 {
2043         struct io_rw *rw = io_kiocb_to_cmd(req);
2044
2045         if (rw->kiocb.ki_pos != -1)
2046                 return &rw->kiocb.ki_pos;
2047
2048         if (!(req->file->f_mode & FMODE_STREAM)) {
2049                 req->flags |= REQ_F_CUR_POS;
2050                 rw->kiocb.ki_pos = req->file->f_pos;
2051                 return &rw->kiocb.ki_pos;
2052         }
2053
2054         rw->kiocb.ki_pos = 0;
2055         return NULL;
2056 }
2057
2058 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
2059                        unsigned int issue_flags)
2060 {
2061         struct io_async_rw *io = req->async_data;
2062         struct io_rw *rw = io_kiocb_to_cmd(req);
2063
2064         /* add previously done IO, if any */
2065         if (req_has_async_data(req) && io->bytes_done > 0) {
2066                 if (ret < 0)
2067                         ret = io->bytes_done;
2068                 else
2069                         ret += io->bytes_done;
2070         }
2071
2072         if (req->flags & REQ_F_CUR_POS)
2073                 req->file->f_pos = rw->kiocb.ki_pos;
2074         if (ret >= 0 && (rw->kiocb.ki_complete == io_complete_rw))
2075                 __io_complete_rw(req, ret, issue_flags);
2076         else
2077                 io_rw_done(&rw->kiocb, ret);
2078
2079         if (req->flags & REQ_F_REISSUE) {
2080                 req->flags &= ~REQ_F_REISSUE;
2081                 if (io_resubmit_prep(req))
2082                         io_req_task_queue_reissue(req);
2083                 else
2084                         io_req_task_queue_fail(req, ret);
2085         }
2086 }
2087
2088 static int __io_import_fixed(struct io_kiocb *req, int ddir,
2089                              struct iov_iter *iter, struct io_mapped_ubuf *imu)
2090 {
2091         struct io_rw *rw = io_kiocb_to_cmd(req);
2092         size_t len = rw->len;
2093         u64 buf_end, buf_addr = rw->addr;
2094         size_t offset;
2095
2096         if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2097                 return -EFAULT;
2098         /* not inside the mapped region */
2099         if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2100                 return -EFAULT;
2101
2102         /*
2103          * May not be a start of buffer, set size appropriately
2104          * and advance us to the beginning.
2105          */
2106         offset = buf_addr - imu->ubuf;
2107         iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
2108
2109         if (offset) {
2110                 /*
2111                  * Don't use iov_iter_advance() here, as it's really slow for
2112                  * using the latter parts of a big fixed buffer - it iterates
2113                  * over each segment manually. We can cheat a bit here, because
2114                  * we know that:
2115                  *
2116                  * 1) it's a BVEC iter, we set it up
2117                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
2118                  *    first and last bvec
2119                  *
2120                  * So just find our index, and adjust the iterator afterwards.
2121                  * If the offset is within the first bvec (or the whole first
2122                  * bvec, just use iov_iter_advance(). This makes it easier
2123                  * since we can just skip the first segment, which may not
2124                  * be PAGE_SIZE aligned.
2125                  */
2126                 const struct bio_vec *bvec = imu->bvec;
2127
2128                 if (offset <= bvec->bv_len) {
2129                         iov_iter_advance(iter, offset);
2130                 } else {
2131                         unsigned long seg_skip;
2132
2133                         /* skip first vec */
2134                         offset -= bvec->bv_len;
2135                         seg_skip = 1 + (offset >> PAGE_SHIFT);
2136
2137                         iter->bvec = bvec + seg_skip;
2138                         iter->nr_segs -= seg_skip;
2139                         iter->count -= bvec->bv_len + offset;
2140                         iter->iov_offset = offset & ~PAGE_MASK;
2141                 }
2142         }
2143
2144         return 0;
2145 }
2146
2147 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2148                            unsigned int issue_flags)
2149 {
2150         if (WARN_ON_ONCE(!req->imu))
2151                 return -EFAULT;
2152         return __io_import_fixed(req, rw, iter, req->imu);
2153 }
2154
2155 #ifdef CONFIG_COMPAT
2156 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2157                                 unsigned int issue_flags)
2158 {
2159         struct io_rw *rw = io_kiocb_to_cmd(req);
2160         struct compat_iovec __user *uiov;
2161         compat_ssize_t clen;
2162         void __user *buf;
2163         size_t len;
2164
2165         uiov = u64_to_user_ptr(rw->addr);
2166         if (!access_ok(uiov, sizeof(*uiov)))
2167                 return -EFAULT;
2168         if (__get_user(clen, &uiov->iov_len))
2169                 return -EFAULT;
2170         if (clen < 0)
2171                 return -EINVAL;
2172
2173         len = clen;
2174         buf = io_buffer_select(req, &len, issue_flags);
2175         if (!buf)
2176                 return -ENOBUFS;
2177         rw->addr = (unsigned long) buf;
2178         iov[0].iov_base = buf;
2179         rw->len = iov[0].iov_len = (compat_size_t) len;
2180         return 0;
2181 }
2182 #endif
2183
2184 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2185                                       unsigned int issue_flags)
2186 {
2187         struct io_rw *rw = io_kiocb_to_cmd(req);
2188         struct iovec __user *uiov = u64_to_user_ptr(rw->addr);
2189         void __user *buf;
2190         ssize_t len;
2191
2192         if (copy_from_user(iov, uiov, sizeof(*uiov)))
2193                 return -EFAULT;
2194
2195         len = iov[0].iov_len;
2196         if (len < 0)
2197                 return -EINVAL;
2198         buf = io_buffer_select(req, &len, issue_flags);
2199         if (!buf)
2200                 return -ENOBUFS;
2201         rw->addr = (unsigned long) buf;
2202         iov[0].iov_base = buf;
2203         rw->len = iov[0].iov_len = len;
2204         return 0;
2205 }
2206
2207 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2208                                     unsigned int issue_flags)
2209 {
2210         struct io_rw *rw = io_kiocb_to_cmd(req);
2211
2212         if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
2213                 iov[0].iov_base = u64_to_user_ptr(rw->addr);
2214                 iov[0].iov_len = rw->len;
2215                 return 0;
2216         }
2217         if (rw->len != 1)
2218                 return -EINVAL;
2219
2220 #ifdef CONFIG_COMPAT
2221         if (req->ctx->compat)
2222                 return io_compat_import(req, iov, issue_flags);
2223 #endif
2224
2225         return __io_iov_buffer_select(req, iov, issue_flags);
2226 }
2227
2228 static struct iovec *__io_import_iovec(int ddir, struct io_kiocb *req,
2229                                        struct io_rw_state *s,
2230                                        unsigned int issue_flags)
2231 {
2232         struct io_rw *rw = io_kiocb_to_cmd(req);
2233         struct iov_iter *iter = &s->iter;
2234         u8 opcode = req->opcode;
2235         struct iovec *iovec;
2236         void __user *buf;
2237         size_t sqe_len;
2238         ssize_t ret;
2239
2240         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2241                 ret = io_import_fixed(req, ddir, iter, issue_flags);
2242                 if (ret)
2243                         return ERR_PTR(ret);
2244                 return NULL;
2245         }
2246
2247         buf = u64_to_user_ptr(rw->addr);
2248         sqe_len = rw->len;
2249
2250         if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2251                 if (io_do_buffer_select(req)) {
2252                         buf = io_buffer_select(req, &sqe_len, issue_flags);
2253                         if (!buf)
2254                                 return ERR_PTR(-ENOBUFS);
2255                         rw->addr = (unsigned long) buf;
2256                         rw->len = sqe_len;
2257                 }
2258
2259                 ret = import_single_range(ddir, buf, sqe_len, s->fast_iov, iter);
2260                 if (ret)
2261                         return ERR_PTR(ret);
2262                 return NULL;
2263         }
2264
2265         iovec = s->fast_iov;
2266         if (req->flags & REQ_F_BUFFER_SELECT) {
2267                 ret = io_iov_buffer_select(req, iovec, issue_flags);
2268                 if (ret)
2269                         return ERR_PTR(ret);
2270                 iov_iter_init(iter, ddir, iovec, 1, iovec->iov_len);
2271                 return NULL;
2272         }
2273
2274         ret = __import_iovec(ddir, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
2275                               req->ctx->compat);
2276         if (unlikely(ret < 0))
2277                 return ERR_PTR(ret);
2278         return iovec;
2279 }
2280
2281 static inline int io_import_iovec(int rw, struct io_kiocb *req,
2282                                   struct iovec **iovec, struct io_rw_state *s,
2283                                   unsigned int issue_flags)
2284 {
2285         *iovec = __io_import_iovec(rw, req, s, issue_flags);
2286         if (unlikely(IS_ERR(*iovec)))
2287                 return PTR_ERR(*iovec);
2288
2289         iov_iter_save_state(&s->iter, &s->iter_state);
2290         return 0;
2291 }
2292
2293 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2294 {
2295         return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
2296 }
2297
2298 /*
2299  * For files that don't have ->read_iter() and ->write_iter(), handle them
2300  * by looping over ->read() or ->write() manually.
2301  */
2302 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
2303 {
2304         struct kiocb *kiocb = &rw->kiocb;
2305         struct file *file = kiocb->ki_filp;
2306         ssize_t ret = 0;
2307         loff_t *ppos;
2308
2309         /*
2310          * Don't support polled IO through this interface, and we can't
2311          * support non-blocking either. For the latter, this just causes
2312          * the kiocb to be handled from an async context.
2313          */
2314         if (kiocb->ki_flags & IOCB_HIPRI)
2315                 return -EOPNOTSUPP;
2316         if ((kiocb->ki_flags & IOCB_NOWAIT) &&
2317             !(kiocb->ki_filp->f_flags & O_NONBLOCK))
2318                 return -EAGAIN;
2319
2320         ppos = io_kiocb_ppos(kiocb);
2321
2322         while (iov_iter_count(iter)) {
2323                 struct iovec iovec;
2324                 ssize_t nr;
2325
2326                 if (!iov_iter_is_bvec(iter)) {
2327                         iovec = iov_iter_iovec(iter);
2328                 } else {
2329                         iovec.iov_base = u64_to_user_ptr(rw->addr);
2330                         iovec.iov_len = rw->len;
2331                 }
2332
2333                 if (ddir == READ) {
2334                         nr = file->f_op->read(file, iovec.iov_base,
2335                                               iovec.iov_len, ppos);
2336                 } else {
2337                         nr = file->f_op->write(file, iovec.iov_base,
2338                                                iovec.iov_len, ppos);
2339                 }
2340
2341                 if (nr < 0) {
2342                         if (!ret)
2343                                 ret = nr;
2344                         break;
2345                 }
2346                 ret += nr;
2347                 if (!iov_iter_is_bvec(iter)) {
2348                         iov_iter_advance(iter, nr);
2349                 } else {
2350                         rw->addr += nr;
2351                         rw->len -= nr;
2352                         if (!rw->len)
2353                                 break;
2354                 }
2355                 if (nr != iovec.iov_len)
2356                         break;
2357         }
2358
2359         return ret;
2360 }
2361
2362 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
2363                           const struct iovec *fast_iov, struct iov_iter *iter)
2364 {
2365         struct io_async_rw *io = req->async_data;
2366
2367         memcpy(&io->s.iter, iter, sizeof(*iter));
2368         io->free_iovec = iovec;
2369         io->bytes_done = 0;
2370         /* can only be fixed buffers, no need to do anything */
2371         if (iov_iter_is_bvec(iter))
2372                 return;
2373         if (!iovec) {
2374                 unsigned iov_off = 0;
2375
2376                 io->s.iter.iov = io->s.fast_iov;
2377                 if (iter->iov != fast_iov) {
2378                         iov_off = iter->iov - fast_iov;
2379                         io->s.iter.iov += iov_off;
2380                 }
2381                 if (io->s.fast_iov != fast_iov)
2382                         memcpy(io->s.fast_iov + iov_off, fast_iov + iov_off,
2383                                sizeof(struct iovec) * iter->nr_segs);
2384         } else {
2385                 req->flags |= REQ_F_NEED_CLEANUP;
2386         }
2387 }
2388
2389 bool io_alloc_async_data(struct io_kiocb *req)
2390 {
2391         WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
2392         req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
2393         if (req->async_data) {
2394                 req->flags |= REQ_F_ASYNC_DATA;
2395                 return false;
2396         }
2397         return true;
2398 }
2399
2400 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
2401                              struct io_rw_state *s, bool force)
2402 {
2403         if (!force && !io_op_defs[req->opcode].prep_async)
2404                 return 0;
2405         if (!req_has_async_data(req)) {
2406                 struct io_async_rw *iorw;
2407
2408                 if (io_alloc_async_data(req)) {
2409                         kfree(iovec);
2410                         return -ENOMEM;
2411                 }
2412
2413                 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
2414                 iorw = req->async_data;
2415                 /* we've copied and mapped the iter, ensure state is saved */
2416                 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
2417         }
2418         return 0;
2419 }
2420
2421 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
2422 {
2423         struct io_async_rw *iorw = req->async_data;
2424         struct iovec *iov;
2425         int ret;
2426
2427         /* submission path, ->uring_lock should already be taken */
2428         ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
2429         if (unlikely(ret < 0))
2430                 return ret;
2431
2432         iorw->bytes_done = 0;
2433         iorw->free_iovec = iov;
2434         if (iov)
2435                 req->flags |= REQ_F_NEED_CLEANUP;
2436         return 0;
2437 }
2438
2439 static int io_readv_prep_async(struct io_kiocb *req)
2440 {
2441         return io_rw_prep_async(req, READ);
2442 }
2443
2444 static int io_writev_prep_async(struct io_kiocb *req)
2445 {
2446         return io_rw_prep_async(req, WRITE);
2447 }
2448
2449 /*
2450  * This is our waitqueue callback handler, registered through __folio_lock_async()
2451  * when we initially tried to do the IO with the iocb armed our waitqueue.
2452  * This gets called when the page is unlocked, and we generally expect that to
2453  * happen when the page IO is completed and the page is now uptodate. This will
2454  * queue a task_work based retry of the operation, attempting to copy the data
2455  * again. If the latter fails because the page was NOT uptodate, then we will
2456  * do a thread based blocking retry of the operation. That's the unexpected
2457  * slow path.
2458  */
2459 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2460                              int sync, void *arg)
2461 {
2462         struct wait_page_queue *wpq;
2463         struct io_kiocb *req = wait->private;
2464         struct io_rw *rw = io_kiocb_to_cmd(req);
2465         struct wait_page_key *key = arg;
2466
2467         wpq = container_of(wait, struct wait_page_queue, wait);
2468
2469         if (!wake_page_match(wpq, key))
2470                 return 0;
2471
2472         rw->kiocb.ki_flags &= ~IOCB_WAITQ;
2473         list_del_init(&wait->entry);
2474         io_req_task_queue(req);
2475         return 1;
2476 }
2477
2478 /*
2479  * This controls whether a given IO request should be armed for async page
2480  * based retry. If we return false here, the request is handed to the async
2481  * worker threads for retry. If we're doing buffered reads on a regular file,
2482  * we prepare a private wait_page_queue entry and retry the operation. This
2483  * will either succeed because the page is now uptodate and unlocked, or it
2484  * will register a callback when the page is unlocked at IO completion. Through
2485  * that callback, io_uring uses task_work to setup a retry of the operation.
2486  * That retry will attempt the buffered read again. The retry will generally
2487  * succeed, or in rare cases where it fails, we then fall back to using the
2488  * async worker threads for a blocking retry.
2489  */
2490 static bool io_rw_should_retry(struct io_kiocb *req)
2491 {
2492         struct io_async_rw *io = req->async_data;
2493         struct wait_page_queue *wait = &io->wpq;
2494         struct io_rw *rw = io_kiocb_to_cmd(req);
2495         struct kiocb *kiocb = &rw->kiocb;
2496
2497         /* never retry for NOWAIT, we just complete with -EAGAIN */
2498         if (req->flags & REQ_F_NOWAIT)
2499                 return false;
2500
2501         /* Only for buffered IO */
2502         if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
2503                 return false;
2504
2505         /*
2506          * just use poll if we can, and don't attempt if the fs doesn't
2507          * support callback based unlocks
2508          */
2509         if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
2510                 return false;
2511
2512         wait->wait.func = io_async_buf_func;
2513         wait->wait.private = req;
2514         wait->wait.flags = 0;
2515         INIT_LIST_HEAD(&wait->wait.entry);
2516         kiocb->ki_flags |= IOCB_WAITQ;
2517         kiocb->ki_flags &= ~IOCB_NOWAIT;
2518         kiocb->ki_waitq = wait;
2519         return true;
2520 }
2521
2522 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
2523 {
2524         struct file *file = rw->kiocb.ki_filp;
2525
2526         if (likely(file->f_op->read_iter))
2527                 return call_read_iter(file, &rw->kiocb, iter);
2528         else if (file->f_op->read)
2529                 return loop_rw_iter(READ, rw, iter);
2530         else
2531                 return -EINVAL;
2532 }
2533
2534 static bool need_read_all(struct io_kiocb *req)
2535 {
2536         return req->flags & REQ_F_ISREG ||
2537                 S_ISBLK(file_inode(req->file)->i_mode);
2538 }
2539
2540 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
2541 {
2542         struct io_rw *rw = io_kiocb_to_cmd(req);
2543         struct kiocb *kiocb = &rw->kiocb;
2544         struct io_ring_ctx *ctx = req->ctx;
2545         struct file *file = req->file;
2546         int ret;
2547
2548         if (unlikely(!file || !(file->f_mode & mode)))
2549                 return -EBADF;
2550
2551         if (!io_req_ffs_set(req))
2552                 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
2553
2554         kiocb->ki_flags = iocb_flags(file);
2555         ret = kiocb_set_rw_flags(kiocb, rw->flags);
2556         if (unlikely(ret))
2557                 return ret;
2558
2559         /*
2560          * If the file is marked O_NONBLOCK, still allow retry for it if it
2561          * supports async. Otherwise it's impossible to use O_NONBLOCK files
2562          * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2563          */
2564         if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2565             ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
2566                 req->flags |= REQ_F_NOWAIT;
2567
2568         if (ctx->flags & IORING_SETUP_IOPOLL) {
2569                 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
2570                         return -EOPNOTSUPP;
2571
2572                 kiocb->private = NULL;
2573                 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2574                 kiocb->ki_complete = io_complete_rw_iopoll;
2575                 req->iopoll_completed = 0;
2576         } else {
2577                 if (kiocb->ki_flags & IOCB_HIPRI)
2578                         return -EINVAL;
2579                 kiocb->ki_complete = io_complete_rw;
2580         }
2581
2582         return 0;
2583 }
2584
2585 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
2586 {
2587         struct io_rw *rw = io_kiocb_to_cmd(req);
2588         struct io_rw_state __s, *s = &__s;
2589         struct iovec *iovec;
2590         struct kiocb *kiocb = &rw->kiocb;
2591         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
2592         struct io_async_rw *io;
2593         ssize_t ret, ret2;
2594         loff_t *ppos;
2595
2596         if (!req_has_async_data(req)) {
2597                 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
2598                 if (unlikely(ret < 0))
2599                         return ret;
2600         } else {
2601                 io = req->async_data;
2602                 s = &io->s;
2603
2604                 /*
2605                  * Safe and required to re-import if we're using provided
2606                  * buffers, as we dropped the selected one before retry.
2607                  */
2608                 if (io_do_buffer_select(req)) {
2609                         ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
2610                         if (unlikely(ret < 0))
2611                                 return ret;
2612                 }
2613
2614                 /*
2615                  * We come here from an earlier attempt, restore our state to
2616                  * match in case it doesn't. It's cheap enough that we don't
2617                  * need to make this conditional.
2618                  */
2619                 iov_iter_restore(&s->iter, &s->iter_state);
2620                 iovec = NULL;
2621         }
2622         ret = io_rw_init_file(req, FMODE_READ);
2623         if (unlikely(ret)) {
2624                 kfree(iovec);
2625                 return ret;
2626         }
2627         req->cqe.res = iov_iter_count(&s->iter);
2628
2629         if (force_nonblock) {
2630                 /* If the file doesn't support async, just async punt */
2631                 if (unlikely(!io_file_supports_nowait(req))) {
2632                         ret = io_setup_async_rw(req, iovec, s, true);
2633                         return ret ?: -EAGAIN;
2634                 }
2635                 kiocb->ki_flags |= IOCB_NOWAIT;
2636         } else {
2637                 /* Ensure we clear previously set non-block flag */
2638                 kiocb->ki_flags &= ~IOCB_NOWAIT;
2639         }
2640
2641         ppos = io_kiocb_update_pos(req);
2642
2643         ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
2644         if (unlikely(ret)) {
2645                 kfree(iovec);
2646                 return ret;
2647         }
2648
2649         ret = io_iter_do_read(rw, &s->iter);
2650
2651         if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
2652                 req->flags &= ~REQ_F_REISSUE;
2653                 /* if we can poll, just do that */
2654                 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
2655                         return -EAGAIN;
2656                 /* IOPOLL retry should happen for io-wq threads */
2657                 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
2658                         goto done;
2659                 /* no retry on NONBLOCK nor RWF_NOWAIT */
2660                 if (req->flags & REQ_F_NOWAIT)
2661                         goto done;
2662                 ret = 0;
2663         } else if (ret == -EIOCBQUEUED) {
2664                 goto out_free;
2665         } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
2666                    (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
2667                 /* read all, failed, already did sync or don't want to retry */
2668                 goto done;
2669         }
2670
2671         /*
2672          * Don't depend on the iter state matching what was consumed, or being
2673          * untouched in case of error. Restore it and we'll advance it
2674          * manually if we need to.
2675          */
2676         iov_iter_restore(&s->iter, &s->iter_state);
2677
2678         ret2 = io_setup_async_rw(req, iovec, s, true);
2679         if (ret2)
2680                 return ret2;
2681
2682         iovec = NULL;
2683         io = req->async_data;
2684         s = &io->s;
2685         /*
2686          * Now use our persistent iterator and state, if we aren't already.
2687          * We've restored and mapped the iter to match.
2688          */
2689
2690         do {
2691                 /*
2692                  * We end up here because of a partial read, either from
2693                  * above or inside this loop. Advance the iter by the bytes
2694                  * that were consumed.
2695                  */
2696                 iov_iter_advance(&s->iter, ret);
2697                 if (!iov_iter_count(&s->iter))
2698                         break;
2699                 io->bytes_done += ret;
2700                 iov_iter_save_state(&s->iter, &s->iter_state);
2701
2702                 /* if we can retry, do so with the callbacks armed */
2703                 if (!io_rw_should_retry(req)) {
2704                         kiocb->ki_flags &= ~IOCB_WAITQ;
2705                         return -EAGAIN;
2706                 }
2707
2708                 /*
2709                  * Now retry read with the IOCB_WAITQ parts set in the iocb. If
2710                  * we get -EIOCBQUEUED, then we'll get a notification when the
2711                  * desired page gets unlocked. We can also get a partial read
2712                  * here, and if we do, then just retry at the new offset.
2713                  */
2714                 ret = io_iter_do_read(rw, &s->iter);
2715                 if (ret == -EIOCBQUEUED)
2716                         return IOU_ISSUE_SKIP_COMPLETE;
2717                 /* we got some bytes, but not all. retry. */
2718                 kiocb->ki_flags &= ~IOCB_WAITQ;
2719                 iov_iter_restore(&s->iter, &s->iter_state);
2720         } while (ret > 0);
2721 done:
2722         kiocb_done(req, ret, issue_flags);
2723 out_free:
2724         /* it's faster to check here then delegate to kfree */
2725         if (iovec)
2726                 kfree(iovec);
2727         return IOU_ISSUE_SKIP_COMPLETE;
2728 }
2729
2730 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
2731 {
2732         struct io_rw *rw = io_kiocb_to_cmd(req);
2733         struct io_rw_state __s, *s = &__s;
2734         struct iovec *iovec;
2735         struct kiocb *kiocb = &rw->kiocb;
2736         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
2737         ssize_t ret, ret2;
2738         loff_t *ppos;
2739
2740         if (!req_has_async_data(req)) {
2741                 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
2742                 if (unlikely(ret < 0))
2743                         return ret;
2744         } else {
2745                 struct io_async_rw *io = req->async_data;
2746
2747                 s = &io->s;
2748                 iov_iter_restore(&s->iter, &s->iter_state);
2749                 iovec = NULL;
2750         }
2751         ret = io_rw_init_file(req, FMODE_WRITE);
2752         if (unlikely(ret)) {
2753                 kfree(iovec);
2754                 return ret;
2755         }
2756         req->cqe.res = iov_iter_count(&s->iter);
2757
2758         if (force_nonblock) {
2759                 /* If the file doesn't support async, just async punt */
2760                 if (unlikely(!io_file_supports_nowait(req)))
2761                         goto copy_iov;
2762
2763                 /* file path doesn't support NOWAIT for non-direct_IO */
2764                 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2765                     (req->flags & REQ_F_ISREG))
2766                         goto copy_iov;
2767
2768                 kiocb->ki_flags |= IOCB_NOWAIT;
2769         } else {
2770                 /* Ensure we clear previously set non-block flag */
2771                 kiocb->ki_flags &= ~IOCB_NOWAIT;
2772         }
2773
2774         ppos = io_kiocb_update_pos(req);
2775
2776         ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
2777         if (unlikely(ret))
2778                 goto out_free;
2779
2780         /*
2781          * Open-code file_start_write here to grab freeze protection,
2782          * which will be released by another thread in
2783          * io_complete_rw().  Fool lockdep by telling it the lock got
2784          * released so that it doesn't complain about the held lock when
2785          * we return to userspace.
2786          */
2787         if (req->flags & REQ_F_ISREG) {
2788                 sb_start_write(file_inode(req->file)->i_sb);
2789                 __sb_writers_release(file_inode(req->file)->i_sb,
2790                                         SB_FREEZE_WRITE);
2791         }
2792         kiocb->ki_flags |= IOCB_WRITE;
2793
2794         if (likely(req->file->f_op->write_iter))
2795                 ret2 = call_write_iter(req->file, kiocb, &s->iter);
2796         else if (req->file->f_op->write)
2797                 ret2 = loop_rw_iter(WRITE, rw, &s->iter);
2798         else
2799                 ret2 = -EINVAL;
2800
2801         if (req->flags & REQ_F_REISSUE) {
2802                 req->flags &= ~REQ_F_REISSUE;
2803                 ret2 = -EAGAIN;
2804         }
2805
2806         /*
2807          * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
2808          * retry them without IOCB_NOWAIT.
2809          */
2810         if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2811                 ret2 = -EAGAIN;
2812         /* no retry on NONBLOCK nor RWF_NOWAIT */
2813         if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
2814                 goto done;
2815         if (!force_nonblock || ret2 != -EAGAIN) {
2816                 /* IOPOLL retry should happen for io-wq threads */
2817                 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
2818                         goto copy_iov;
2819 done:
2820                 kiocb_done(req, ret2, issue_flags);
2821                 ret = IOU_ISSUE_SKIP_COMPLETE;
2822         } else {
2823 copy_iov:
2824                 iov_iter_restore(&s->iter, &s->iter_state);
2825                 ret = io_setup_async_rw(req, iovec, s, false);
2826                 return ret ?: -EAGAIN;
2827         }
2828 out_free:
2829         /* it's reportedly faster than delegating the null check to kfree() */
2830         if (iovec)
2831                 kfree(iovec);
2832         return ret;
2833 }
2834
2835 /*
2836  * Note when io_fixed_fd_install() returns error value, it will ensure
2837  * fput() is called correspondingly.
2838  */
2839 int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
2840                         struct file *file, unsigned int file_slot)
2841 {
2842         bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
2843         struct io_ring_ctx *ctx = req->ctx;
2844         int ret;
2845
2846         io_ring_submit_lock(ctx, issue_flags);
2847
2848         if (alloc_slot) {
2849                 ret = io_file_bitmap_get(ctx);
2850                 if (unlikely(ret < 0))
2851                         goto err;
2852                 file_slot = ret;
2853         } else {
2854                 file_slot--;
2855         }
2856
2857         ret = io_install_fixed_file(req, file, issue_flags, file_slot);
2858         if (!ret && alloc_slot)
2859                 ret = file_slot;
2860 err:
2861         io_ring_submit_unlock(ctx, issue_flags);
2862         if (unlikely(ret < 0))
2863                 fput(file);
2864         return ret;
2865 }
2866
2867 static __maybe_unused int io_eopnotsupp_prep(struct io_kiocb *kiocb,
2868                                              const struct io_uring_sqe *sqe)
2869 {
2870         return -EOPNOTSUPP;
2871 }
2872
2873 static int io_files_update_prep(struct io_kiocb *req,
2874                                 const struct io_uring_sqe *sqe)
2875 {
2876         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
2877
2878         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
2879                 return -EINVAL;
2880         if (sqe->rw_flags || sqe->splice_fd_in)
2881                 return -EINVAL;
2882
2883         up->offset = READ_ONCE(sqe->off);
2884         up->nr_args = READ_ONCE(sqe->len);
2885         if (!up->nr_args)
2886                 return -EINVAL;
2887         up->arg = READ_ONCE(sqe->addr);
2888         return 0;
2889 }
2890
2891 static int io_files_update_with_index_alloc(struct io_kiocb *req,
2892                                             unsigned int issue_flags)
2893 {
2894         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
2895         __s32 __user *fds = u64_to_user_ptr(up->arg);
2896         unsigned int done;
2897         struct file *file;
2898         int ret, fd;
2899
2900         if (!req->ctx->file_data)
2901                 return -ENXIO;
2902
2903         for (done = 0; done < up->nr_args; done++) {
2904                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
2905                         ret = -EFAULT;
2906                         break;
2907                 }
2908
2909                 file = fget(fd);
2910                 if (!file) {
2911                         ret = -EBADF;
2912                         break;
2913                 }
2914                 ret = io_fixed_fd_install(req, issue_flags, file,
2915                                           IORING_FILE_INDEX_ALLOC);
2916                 if (ret < 0)
2917                         break;
2918                 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
2919                         __io_close_fixed(req, issue_flags, ret);
2920                         ret = -EFAULT;
2921                         break;
2922                 }
2923         }
2924
2925         if (done)
2926                 return done;
2927         return ret;
2928 }
2929
2930 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
2931 {
2932         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
2933         struct io_ring_ctx *ctx = req->ctx;
2934         struct io_uring_rsrc_update2 up2;
2935         int ret;
2936
2937         up2.offset = up->offset;
2938         up2.data = up->arg;
2939         up2.nr = 0;
2940         up2.tags = 0;
2941         up2.resv = 0;
2942         up2.resv2 = 0;
2943
2944         if (up->offset == IORING_FILE_INDEX_ALLOC) {
2945                 ret = io_files_update_with_index_alloc(req, issue_flags);
2946         } else {
2947                 io_ring_submit_lock(ctx, issue_flags);
2948                 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
2949                                                 &up2, up->nr_args);
2950                 io_ring_submit_unlock(ctx, issue_flags);
2951         }
2952
2953         if (ret < 0)
2954                 req_set_fail(req);
2955         io_req_set_res(req, ret, 0);
2956         return IOU_OK;
2957 }
2958
2959 static int io_req_prep_async(struct io_kiocb *req)
2960 {
2961         const struct io_op_def *def = &io_op_defs[req->opcode];
2962
2963         /* assign early for deferred execution for non-fixed file */
2964         if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
2965                 req->file = io_file_get_normal(req, req->cqe.fd);
2966         if (!def->prep_async)
2967                 return 0;
2968         if (WARN_ON_ONCE(req_has_async_data(req)))
2969                 return -EFAULT;
2970         if (io_alloc_async_data(req))
2971                 return -EAGAIN;
2972
2973         return def->prep_async(req);
2974 }
2975
2976 static u32 io_get_sequence(struct io_kiocb *req)
2977 {
2978         u32 seq = req->ctx->cached_sq_head;
2979         struct io_kiocb *cur;
2980
2981         /* need original cached_sq_head, but it was increased for each req */
2982         io_for_each_link(cur, req)
2983                 seq--;
2984         return seq;
2985 }
2986
2987 static __cold void io_drain_req(struct io_kiocb *req)
2988 {
2989         struct io_ring_ctx *ctx = req->ctx;
2990         struct io_defer_entry *de;
2991         int ret;
2992         u32 seq = io_get_sequence(req);
2993
2994         /* Still need defer if there is pending req in defer list. */
2995         spin_lock(&ctx->completion_lock);
2996         if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
2997                 spin_unlock(&ctx->completion_lock);
2998 queue:
2999                 ctx->drain_active = false;
3000                 io_req_task_queue(req);
3001                 return;
3002         }
3003         spin_unlock(&ctx->completion_lock);
3004
3005         ret = io_req_prep_async(req);
3006         if (ret) {
3007 fail:
3008                 io_req_complete_failed(req, ret);
3009                 return;
3010         }
3011         io_prep_async_link(req);
3012         de = kmalloc(sizeof(*de), GFP_KERNEL);
3013         if (!de) {
3014                 ret = -ENOMEM;
3015                 goto fail;
3016         }
3017
3018         spin_lock(&ctx->completion_lock);
3019         if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
3020                 spin_unlock(&ctx->completion_lock);
3021                 kfree(de);
3022                 goto queue;
3023         }
3024
3025         trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
3026         de->req = req;
3027         de->seq = seq;
3028         list_add_tail(&de->list, &ctx->defer_list);
3029         spin_unlock(&ctx->completion_lock);
3030 }
3031
3032 static void io_clean_op(struct io_kiocb *req)
3033 {
3034         if (req->flags & REQ_F_BUFFER_SELECTED) {
3035                 spin_lock(&req->ctx->completion_lock);
3036                 io_put_kbuf_comp(req);
3037                 spin_unlock(&req->ctx->completion_lock);
3038         }
3039
3040         if (req->flags & REQ_F_NEED_CLEANUP) {
3041                 const struct io_op_def *def = &io_op_defs[req->opcode];
3042
3043                 if (def->cleanup)
3044                         def->cleanup(req);
3045         }
3046         if ((req->flags & REQ_F_POLLED) && req->apoll) {
3047                 kfree(req->apoll->double_poll);
3048                 kfree(req->apoll);
3049                 req->apoll = NULL;
3050         }
3051         if (req->flags & REQ_F_INFLIGHT) {
3052                 struct io_uring_task *tctx = req->task->io_uring;
3053
3054                 atomic_dec(&tctx->inflight_tracked);
3055         }
3056         if (req->flags & REQ_F_CREDS)
3057                 put_cred(req->creds);
3058         if (req->flags & REQ_F_ASYNC_DATA) {
3059                 kfree(req->async_data);
3060                 req->async_data = NULL;
3061         }
3062         req->flags &= ~IO_REQ_CLEAN_FLAGS;
3063 }
3064
3065 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
3066 {
3067         if (req->file || !io_op_defs[req->opcode].needs_file)
3068                 return true;
3069
3070         if (req->flags & REQ_F_FIXED_FILE)
3071                 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
3072         else
3073                 req->file = io_file_get_normal(req, req->cqe.fd);
3074
3075         return !!req->file;
3076 }
3077
3078 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
3079 {
3080         const struct io_op_def *def = &io_op_defs[req->opcode];
3081         const struct cred *creds = NULL;
3082         int ret;
3083
3084         if (unlikely(!io_assign_file(req, issue_flags)))
3085                 return -EBADF;
3086
3087         if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
3088                 creds = override_creds(req->creds);
3089
3090         if (!def->audit_skip)
3091                 audit_uring_entry(req->opcode);
3092
3093         ret = def->issue(req, issue_flags);
3094
3095         if (!def->audit_skip)
3096                 audit_uring_exit(!ret, ret);
3097
3098         if (creds)
3099                 revert_creds(creds);
3100
3101         if (ret == IOU_OK)
3102                 __io_req_complete(req, issue_flags);
3103         else if (ret != IOU_ISSUE_SKIP_COMPLETE)
3104                 return ret;
3105
3106         /* If the op doesn't have a file, we're not polling for it */
3107         if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
3108                 io_iopoll_req_issued(req, issue_flags);
3109
3110         return 0;
3111 }
3112
3113 int io_poll_issue(struct io_kiocb *req, bool *locked)
3114 {
3115         io_tw_lock(req->ctx, locked);
3116         if (unlikely(req->task->flags & PF_EXITING))
3117                 return -EFAULT;
3118         return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
3119 }
3120
3121 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
3122 {
3123         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3124
3125         req = io_put_req_find_next(req);
3126         return req ? &req->work : NULL;
3127 }
3128
3129 void io_wq_submit_work(struct io_wq_work *work)
3130 {
3131         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3132         const struct io_op_def *def = &io_op_defs[req->opcode];
3133         unsigned int issue_flags = IO_URING_F_UNLOCKED;
3134         bool needs_poll = false;
3135         int ret = 0, err = -ECANCELED;
3136
3137         /* one will be dropped by ->io_free_work() after returning to io-wq */
3138         if (!(req->flags & REQ_F_REFCOUNT))
3139                 __io_req_set_refcount(req, 2);
3140         else
3141                 req_ref_get(req);
3142
3143         io_arm_ltimeout(req);
3144
3145         /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
3146         if (work->flags & IO_WQ_WORK_CANCEL) {
3147 fail:
3148                 io_req_task_queue_fail(req, err);
3149                 return;
3150         }
3151         if (!io_assign_file(req, issue_flags)) {
3152                 err = -EBADF;
3153                 work->flags |= IO_WQ_WORK_CANCEL;
3154                 goto fail;
3155         }
3156
3157         if (req->flags & REQ_F_FORCE_ASYNC) {
3158                 bool opcode_poll = def->pollin || def->pollout;
3159
3160                 if (opcode_poll && file_can_poll(req->file)) {
3161                         needs_poll = true;
3162                         issue_flags |= IO_URING_F_NONBLOCK;
3163                 }
3164         }
3165
3166         do {
3167                 ret = io_issue_sqe(req, issue_flags);
3168                 if (ret != -EAGAIN)
3169                         break;
3170                 /*
3171                  * We can get EAGAIN for iopolled IO even though we're
3172                  * forcing a sync submission from here, since we can't
3173                  * wait for request slots on the block side.
3174                  */
3175                 if (!needs_poll) {
3176                         if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
3177                                 break;
3178                         cond_resched();
3179                         continue;
3180                 }
3181
3182                 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
3183                         return;
3184                 /* aborted or ready, in either case retry blocking */
3185                 needs_poll = false;
3186                 issue_flags &= ~IO_URING_F_NONBLOCK;
3187         } while (1);
3188
3189         /* avoid locking problems by failing it from a clean context */
3190         if (ret < 0)
3191                 io_req_task_queue_fail(req, ret);
3192 }
3193
3194 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
3195                                       unsigned int issue_flags)
3196 {
3197         struct io_ring_ctx *ctx = req->ctx;
3198         struct file *file = NULL;
3199         unsigned long file_ptr;
3200
3201         io_ring_submit_lock(ctx, issue_flags);
3202
3203         if (unlikely((unsigned int)fd >= ctx->nr_user_files))
3204                 goto out;
3205         fd = array_index_nospec(fd, ctx->nr_user_files);
3206         file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
3207         file = (struct file *) (file_ptr & FFS_MASK);
3208         file_ptr &= ~FFS_MASK;
3209         /* mask in overlapping REQ_F and FFS bits */
3210         req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
3211         io_req_set_rsrc_node(req, ctx, 0);
3212         WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
3213 out:
3214         io_ring_submit_unlock(ctx, issue_flags);
3215         return file;
3216 }
3217
3218 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
3219 {
3220         struct file *file = fget(fd);
3221
3222         trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
3223
3224         /* we don't allow fixed io_uring files */
3225         if (file && io_is_uring_fops(file))
3226                 io_req_track_inflight(req);
3227         return file;
3228 }
3229
3230 static void io_queue_async(struct io_kiocb *req, int ret)
3231         __must_hold(&req->ctx->uring_lock)
3232 {
3233         struct io_kiocb *linked_timeout;
3234
3235         if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
3236                 io_req_complete_failed(req, ret);
3237                 return;
3238         }
3239
3240         linked_timeout = io_prep_linked_timeout(req);
3241
3242         switch (io_arm_poll_handler(req, 0)) {
3243         case IO_APOLL_READY:
3244                 io_req_task_queue(req);
3245                 break;
3246         case IO_APOLL_ABORTED:
3247                 /*
3248                  * Queued up for async execution, worker will release
3249                  * submit reference when the iocb is actually submitted.
3250                  */
3251                 io_kbuf_recycle(req, 0);
3252                 io_queue_iowq(req, NULL);
3253                 break;
3254         case IO_APOLL_OK:
3255                 break;
3256         }
3257
3258         if (linked_timeout)
3259                 io_queue_linked_timeout(linked_timeout);
3260 }
3261
3262 static inline void io_queue_sqe(struct io_kiocb *req)
3263         __must_hold(&req->ctx->uring_lock)
3264 {
3265         int ret;
3266
3267         ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
3268
3269         if (req->flags & REQ_F_COMPLETE_INLINE) {
3270                 io_req_add_compl_list(req);
3271                 return;
3272         }
3273         /*
3274          * We async punt it if the file wasn't marked NOWAIT, or if the file
3275          * doesn't support non-blocking read/write attempts
3276          */
3277         if (likely(!ret))
3278                 io_arm_ltimeout(req);
3279         else
3280                 io_queue_async(req, ret);
3281 }
3282
3283 static void io_queue_sqe_fallback(struct io_kiocb *req)
3284         __must_hold(&req->ctx->uring_lock)
3285 {
3286         if (unlikely(req->flags & REQ_F_FAIL)) {
3287                 /*
3288                  * We don't submit, fail them all, for that replace hardlinks
3289                  * with normal links. Extra REQ_F_LINK is tolerated.
3290                  */
3291                 req->flags &= ~REQ_F_HARDLINK;
3292                 req->flags |= REQ_F_LINK;
3293                 io_req_complete_failed(req, req->cqe.res);
3294         } else if (unlikely(req->ctx->drain_active)) {
3295                 io_drain_req(req);
3296         } else {
3297                 int ret = io_req_prep_async(req);
3298
3299                 if (unlikely(ret))
3300                         io_req_complete_failed(req, ret);
3301                 else
3302                         io_queue_iowq(req, NULL);
3303         }
3304 }
3305
3306 /*
3307  * Check SQE restrictions (opcode and flags).
3308  *
3309  * Returns 'true' if SQE is allowed, 'false' otherwise.
3310  */
3311 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
3312                                         struct io_kiocb *req,
3313                                         unsigned int sqe_flags)
3314 {
3315         if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
3316                 return false;
3317
3318         if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
3319             ctx->restrictions.sqe_flags_required)
3320                 return false;
3321
3322         if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
3323                           ctx->restrictions.sqe_flags_required))
3324                 return false;
3325
3326         return true;
3327 }
3328
3329 static void io_init_req_drain(struct io_kiocb *req)
3330 {
3331         struct io_ring_ctx *ctx = req->ctx;
3332         struct io_kiocb *head = ctx->submit_state.link.head;
3333
3334         ctx->drain_active = true;
3335         if (head) {
3336                 /*
3337                  * If we need to drain a request in the middle of a link, drain
3338                  * the head request and the next request/link after the current
3339                  * link. Considering sequential execution of links,
3340                  * REQ_F_IO_DRAIN will be maintained for every request of our
3341                  * link.
3342                  */
3343                 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
3344                 ctx->drain_next = true;
3345         }
3346 }
3347
3348 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
3349                        const struct io_uring_sqe *sqe)
3350         __must_hold(&ctx->uring_lock)
3351 {
3352         const struct io_op_def *def;
3353         unsigned int sqe_flags;
3354         int personality;
3355         u8 opcode;
3356
3357         /* req is partially pre-initialised, see io_preinit_req() */
3358         req->opcode = opcode = READ_ONCE(sqe->opcode);
3359         /* same numerical values with corresponding REQ_F_*, safe to copy */
3360         req->flags = sqe_flags = READ_ONCE(sqe->flags);
3361         req->cqe.user_data = READ_ONCE(sqe->user_data);
3362         req->file = NULL;
3363         req->rsrc_node = NULL;
3364         req->task = current;
3365
3366         if (unlikely(opcode >= IORING_OP_LAST)) {
3367                 req->opcode = 0;
3368                 return -EINVAL;
3369         }
3370         def = &io_op_defs[opcode];
3371         if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
3372                 /* enforce forwards compatibility on users */
3373                 if (sqe_flags & ~SQE_VALID_FLAGS)
3374                         return -EINVAL;
3375                 if (sqe_flags & IOSQE_BUFFER_SELECT) {
3376                         if (!def->buffer_select)
3377                                 return -EOPNOTSUPP;
3378                         req->buf_index = READ_ONCE(sqe->buf_group);
3379                 }
3380                 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
3381                         ctx->drain_disabled = true;
3382                 if (sqe_flags & IOSQE_IO_DRAIN) {
3383                         if (ctx->drain_disabled)
3384                                 return -EOPNOTSUPP;
3385                         io_init_req_drain(req);
3386                 }
3387         }
3388         if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
3389                 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
3390                         return -EACCES;
3391                 /* knock it to the slow queue path, will be drained there */
3392                 if (ctx->drain_active)
3393                         req->flags |= REQ_F_FORCE_ASYNC;
3394                 /* if there is no link, we're at "next" request and need to drain */
3395                 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
3396                         ctx->drain_next = false;
3397                         ctx->drain_active = true;
3398                         req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
3399                 }
3400         }
3401
3402         if (!def->ioprio && sqe->ioprio)
3403                 return -EINVAL;
3404         if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
3405                 return -EINVAL;
3406
3407         if (def->needs_file) {
3408                 struct io_submit_state *state = &ctx->submit_state;
3409
3410                 req->cqe.fd = READ_ONCE(sqe->fd);
3411
3412                 /*
3413                  * Plug now if we have more than 2 IO left after this, and the
3414                  * target is potentially a read/write to block based storage.
3415                  */
3416                 if (state->need_plug && def->plug) {
3417                         state->plug_started = true;
3418                         state->need_plug = false;
3419                         blk_start_plug_nr_ios(&state->plug, state->submit_nr);
3420                 }
3421         }
3422
3423         personality = READ_ONCE(sqe->personality);
3424         if (personality) {
3425                 int ret;
3426
3427                 req->creds = xa_load(&ctx->personalities, personality);
3428                 if (!req->creds)
3429                         return -EINVAL;
3430                 get_cred(req->creds);
3431                 ret = security_uring_override_creds(req->creds);
3432                 if (ret) {
3433                         put_cred(req->creds);
3434                         return ret;
3435                 }
3436                 req->flags |= REQ_F_CREDS;
3437         }
3438
3439         return def->prep(req, sqe);
3440 }
3441
3442 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
3443                                       struct io_kiocb *req, int ret)
3444 {
3445         struct io_ring_ctx *ctx = req->ctx;
3446         struct io_submit_link *link = &ctx->submit_state.link;
3447         struct io_kiocb *head = link->head;
3448
3449         trace_io_uring_req_failed(sqe, ctx, req, ret);
3450
3451         /*
3452          * Avoid breaking links in the middle as it renders links with SQPOLL
3453          * unusable. Instead of failing eagerly, continue assembling the link if
3454          * applicable and mark the head with REQ_F_FAIL. The link flushing code
3455          * should find the flag and handle the rest.
3456          */
3457         req_fail_link_node(req, ret);
3458         if (head && !(head->flags & REQ_F_FAIL))
3459                 req_fail_link_node(head, -ECANCELED);
3460
3461         if (!(req->flags & IO_REQ_LINK_FLAGS)) {
3462                 if (head) {
3463                         link->last->link = req;
3464                         link->head = NULL;
3465                         req = head;
3466                 }
3467                 io_queue_sqe_fallback(req);
3468                 return ret;
3469         }
3470
3471         if (head)
3472                 link->last->link = req;
3473         else
3474                 link->head = req;
3475         link->last = req;
3476         return 0;
3477 }
3478
3479 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
3480                          const struct io_uring_sqe *sqe)
3481         __must_hold(&ctx->uring_lock)
3482 {
3483         struct io_submit_link *link = &ctx->submit_state.link;
3484         int ret;
3485
3486         ret = io_init_req(ctx, req, sqe);
3487         if (unlikely(ret))
3488                 return io_submit_fail_init(sqe, req, ret);
3489
3490         /* don't need @sqe from now on */
3491         trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
3492                                   req->flags, true,
3493                                   ctx->flags & IORING_SETUP_SQPOLL);
3494
3495         /*
3496          * If we already have a head request, queue this one for async
3497          * submittal once the head completes. If we don't have a head but
3498          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
3499          * submitted sync once the chain is complete. If none of those
3500          * conditions are true (normal request), then just queue it.
3501          */
3502         if (unlikely(link->head)) {
3503                 ret = io_req_prep_async(req);
3504                 if (unlikely(ret))
3505                         return io_submit_fail_init(sqe, req, ret);
3506
3507                 trace_io_uring_link(ctx, req, link->head);
3508                 link->last->link = req;
3509                 link->last = req;
3510
3511                 if (req->flags & IO_REQ_LINK_FLAGS)
3512                         return 0;
3513                 /* last request of the link, flush it */
3514                 req = link->head;
3515                 link->head = NULL;
3516                 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
3517                         goto fallback;
3518
3519         } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
3520                                           REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
3521                 if (req->flags & IO_REQ_LINK_FLAGS) {
3522                         link->head = req;
3523                         link->last = req;
3524                 } else {
3525 fallback:
3526                         io_queue_sqe_fallback(req);
3527                 }
3528                 return 0;
3529         }
3530
3531         io_queue_sqe(req);
3532         return 0;
3533 }
3534
3535 /*
3536  * Batched submission is done, ensure local IO is flushed out.
3537  */
3538 static void io_submit_state_end(struct io_ring_ctx *ctx)
3539 {
3540         struct io_submit_state *state = &ctx->submit_state;
3541
3542         if (unlikely(state->link.head))
3543                 io_queue_sqe_fallback(state->link.head);
3544         /* flush only after queuing links as they can generate completions */
3545         io_submit_flush_completions(ctx);
3546         if (state->plug_started)
3547                 blk_finish_plug(&state->plug);
3548 }
3549
3550 /*
3551  * Start submission side cache.
3552  */
3553 static void io_submit_state_start(struct io_submit_state *state,
3554                                   unsigned int max_ios)
3555 {
3556         state->plug_started = false;
3557         state->need_plug = max_ios > 2;
3558         state->submit_nr = max_ios;
3559         /* set only head, no need to init link_last in advance */
3560         state->link.head = NULL;
3561 }
3562
3563 static void io_commit_sqring(struct io_ring_ctx *ctx)
3564 {
3565         struct io_rings *rings = ctx->rings;
3566
3567         /*
3568          * Ensure any loads from the SQEs are done at this point,
3569          * since once we write the new head, the application could
3570          * write new data to them.
3571          */
3572         smp_store_release(&rings->sq.head, ctx->cached_sq_head);
3573 }
3574
3575 /*
3576  * Fetch an sqe, if one is available. Note this returns a pointer to memory
3577  * that is mapped by userspace. This means that care needs to be taken to
3578  * ensure that reads are stable, as we cannot rely on userspace always
3579  * being a good citizen. If members of the sqe are validated and then later
3580  * used, it's important that those reads are done through READ_ONCE() to
3581  * prevent a re-load down the line.
3582  */
3583 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
3584 {
3585         unsigned head, mask = ctx->sq_entries - 1;
3586         unsigned sq_idx = ctx->cached_sq_head++ & mask;
3587
3588         /*
3589          * The cached sq head (or cq tail) serves two purposes:
3590          *
3591          * 1) allows us to batch the cost of updating the user visible
3592          *    head updates.
3593          * 2) allows the kernel side to track the head on its own, even
3594          *    though the application is the one updating it.
3595          */
3596         head = READ_ONCE(ctx->sq_array[sq_idx]);
3597         if (likely(head < ctx->sq_entries)) {
3598                 /* double index for 128-byte SQEs, twice as long */
3599                 if (ctx->flags & IORING_SETUP_SQE128)
3600                         head <<= 1;
3601                 return &ctx->sq_sqes[head];
3602         }
3603
3604         /* drop invalid entries */
3605         ctx->cq_extra--;
3606         WRITE_ONCE(ctx->rings->sq_dropped,
3607                    READ_ONCE(ctx->rings->sq_dropped) + 1);
3608         return NULL;
3609 }
3610
3611 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
3612         __must_hold(&ctx->uring_lock)
3613 {
3614         unsigned int entries = io_sqring_entries(ctx);
3615         unsigned int left;
3616         int ret;
3617
3618         if (unlikely(!entries))
3619                 return 0;
3620         /* make sure SQ entry isn't read before tail */
3621         ret = left = min3(nr, ctx->sq_entries, entries);
3622         io_get_task_refs(left);
3623         io_submit_state_start(&ctx->submit_state, left);
3624
3625         do {
3626                 const struct io_uring_sqe *sqe;
3627                 struct io_kiocb *req;
3628
3629                 if (unlikely(!io_alloc_req_refill(ctx)))
3630                         break;
3631                 req = io_alloc_req(ctx);
3632                 sqe = io_get_sqe(ctx);
3633                 if (unlikely(!sqe)) {
3634                         io_req_add_to_cache(req, ctx);
3635                         break;
3636                 }
3637
3638                 /*
3639                  * Continue submitting even for sqe failure if the
3640                  * ring was setup with IORING_SETUP_SUBMIT_ALL
3641                  */
3642                 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
3643                     !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
3644                         left--;
3645                         break;
3646                 }
3647         } while (--left);
3648
3649         if (unlikely(left)) {
3650                 ret -= left;
3651                 /* try again if it submitted nothing and can't allocate a req */
3652                 if (!ret && io_req_cache_empty(ctx))
3653                         ret = -EAGAIN;
3654                 current->io_uring->cached_refs += left;
3655         }
3656
3657         io_submit_state_end(ctx);
3658          /* Commit SQ ring head once we've consumed and submitted all SQEs */
3659         io_commit_sqring(ctx);
3660         return ret;
3661 }
3662
3663 struct io_wait_queue {
3664         struct wait_queue_entry wq;
3665         struct io_ring_ctx *ctx;
3666         unsigned cq_tail;
3667         unsigned nr_timeouts;
3668 };
3669
3670 static inline bool io_should_wake(struct io_wait_queue *iowq)
3671 {
3672         struct io_ring_ctx *ctx = iowq->ctx;
3673         int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
3674
3675         /*
3676          * Wake up if we have enough events, or if a timeout occurred since we
3677          * started waiting. For timeouts, we always want to return to userspace,
3678          * regardless of event count.
3679          */
3680         return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
3681 }
3682
3683 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
3684                             int wake_flags, void *key)
3685 {
3686         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3687                                                         wq);
3688
3689         /*
3690          * Cannot safely flush overflowed CQEs from here, ensure we wake up
3691          * the task, and the next invocation will do it.
3692          */
3693         if (io_should_wake(iowq) ||
3694             test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
3695                 return autoremove_wake_function(curr, mode, wake_flags, key);
3696         return -1;
3697 }
3698
3699 static int io_run_task_work_sig(void)
3700 {
3701         if (io_run_task_work())
3702                 return 1;
3703         if (test_thread_flag(TIF_NOTIFY_SIGNAL))
3704                 return -ERESTARTSYS;
3705         if (task_sigpending(current))
3706                 return -EINTR;
3707         return 0;
3708 }
3709
3710 /* when returns >0, the caller should retry */
3711 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
3712                                           struct io_wait_queue *iowq,
3713                                           ktime_t timeout)
3714 {
3715         int ret;
3716         unsigned long check_cq;
3717
3718         /* make sure we run task_work before checking for signals */
3719         ret = io_run_task_work_sig();
3720         if (ret || io_should_wake(iowq))
3721                 return ret;
3722         check_cq = READ_ONCE(ctx->check_cq);
3723         /* let the caller flush overflows, retry */
3724         if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3725                 return 1;
3726         if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3727                 return -EBADR;
3728         if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
3729                 return -ETIME;
3730         return 1;
3731 }
3732
3733 /*
3734  * Wait until events become available, if we don't already have some. The
3735  * application must reap them itself, as they reside on the shared cq ring.
3736  */
3737 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3738                           const sigset_t __user *sig, size_t sigsz,
3739                           struct __kernel_timespec __user *uts)
3740 {
3741         struct io_wait_queue iowq;
3742         struct io_rings *rings = ctx->rings;
3743         ktime_t timeout = KTIME_MAX;
3744         int ret;
3745
3746         do {
3747                 io_cqring_overflow_flush(ctx);
3748                 if (io_cqring_events(ctx) >= min_events)
3749                         return 0;
3750                 if (!io_run_task_work())
3751                         break;
3752         } while (1);
3753
3754         if (sig) {
3755 #ifdef CONFIG_COMPAT
3756                 if (in_compat_syscall())
3757                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
3758                                                       sigsz);
3759                 else
3760 #endif
3761                         ret = set_user_sigmask(sig, sigsz);
3762
3763                 if (ret)
3764                         return ret;
3765         }
3766
3767         if (uts) {
3768                 struct timespec64 ts;
3769
3770                 if (get_timespec64(&ts, uts))
3771                         return -EFAULT;
3772                 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
3773         }
3774
3775         init_waitqueue_func_entry(&iowq.wq, io_wake_function);
3776         iowq.wq.private = current;
3777         INIT_LIST_HEAD(&iowq.wq.entry);
3778         iowq.ctx = ctx;
3779         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
3780         iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
3781
3782         trace_io_uring_cqring_wait(ctx, min_events);
3783         do {
3784                 /* if we can't even flush overflow, don't wait for more */
3785                 if (!io_cqring_overflow_flush(ctx)) {
3786                         ret = -EBUSY;
3787                         break;
3788                 }
3789                 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
3790                                                 TASK_INTERRUPTIBLE);
3791                 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
3792                 cond_resched();
3793         } while (ret > 0);
3794
3795         finish_wait(&ctx->cq_wait, &iowq.wq);
3796         restore_saved_sigmask_unless(ret == -EINTR);
3797
3798         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
3799 }
3800
3801 static void io_free_page_table(void **table, size_t size)
3802 {
3803         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
3804
3805         for (i = 0; i < nr_tables; i++)
3806                 kfree(table[i]);
3807         kfree(table);
3808 }
3809
3810 static __cold void **io_alloc_page_table(size_t size)
3811 {
3812         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
3813         size_t init_size = size;
3814         void **table;
3815
3816         table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
3817         if (!table)
3818                 return NULL;
3819
3820         for (i = 0; i < nr_tables; i++) {
3821                 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
3822
3823                 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
3824                 if (!table[i]) {
3825                         io_free_page_table(table, init_size);
3826                         return NULL;
3827                 }
3828                 size -= this_size;
3829         }
3830         return table;
3831 }
3832
3833 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
3834 {
3835         percpu_ref_exit(&ref_node->refs);
3836         kfree(ref_node);
3837 }
3838
3839 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
3840 {
3841         struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
3842         struct io_ring_ctx *ctx = node->rsrc_data->ctx;
3843         unsigned long flags;
3844         bool first_add = false;
3845         unsigned long delay = HZ;
3846
3847         spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
3848         node->done = true;
3849
3850         /* if we are mid-quiesce then do not delay */
3851         if (node->rsrc_data->quiesce)
3852                 delay = 0;
3853
3854         while (!list_empty(&ctx->rsrc_ref_list)) {
3855                 node = list_first_entry(&ctx->rsrc_ref_list,
3856                                             struct io_rsrc_node, node);
3857                 /* recycle ref nodes in order */
3858                 if (!node->done)
3859                         break;
3860                 list_del(&node->node);
3861                 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
3862         }
3863         spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
3864
3865         if (first_add)
3866                 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
3867 }
3868
3869 static struct io_rsrc_node *io_rsrc_node_alloc(void)
3870 {
3871         struct io_rsrc_node *ref_node;
3872
3873         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
3874         if (!ref_node)
3875                 return NULL;
3876
3877         if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
3878                             0, GFP_KERNEL)) {
3879                 kfree(ref_node);
3880                 return NULL;
3881         }
3882         INIT_LIST_HEAD(&ref_node->node);
3883         INIT_LIST_HEAD(&ref_node->rsrc_list);
3884         ref_node->done = false;
3885         return ref_node;
3886 }
3887
3888 void io_rsrc_node_switch(struct io_ring_ctx *ctx,
3889                          struct io_rsrc_data *data_to_kill)
3890         __must_hold(&ctx->uring_lock)
3891 {
3892         WARN_ON_ONCE(!ctx->rsrc_backup_node);
3893         WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
3894
3895         io_rsrc_refs_drop(ctx);
3896
3897         if (data_to_kill) {
3898                 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
3899
3900                 rsrc_node->rsrc_data = data_to_kill;
3901                 spin_lock_irq(&ctx->rsrc_ref_lock);
3902                 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
3903                 spin_unlock_irq(&ctx->rsrc_ref_lock);
3904
3905                 atomic_inc(&data_to_kill->refs);
3906                 percpu_ref_kill(&rsrc_node->refs);
3907                 ctx->rsrc_node = NULL;
3908         }
3909
3910         if (!ctx->rsrc_node) {
3911                 ctx->rsrc_node = ctx->rsrc_backup_node;
3912                 ctx->rsrc_backup_node = NULL;
3913         }
3914 }
3915
3916 int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
3917 {
3918         if (ctx->rsrc_backup_node)
3919                 return 0;
3920         ctx->rsrc_backup_node = io_rsrc_node_alloc();
3921         return ctx->rsrc_backup_node ? 0 : -ENOMEM;
3922 }
3923
3924 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
3925                                       struct io_ring_ctx *ctx)
3926 {
3927         int ret;
3928
3929         /* As we may drop ->uring_lock, other task may have started quiesce */
3930         if (data->quiesce)
3931                 return -ENXIO;
3932
3933         data->quiesce = true;
3934         do {
3935                 ret = io_rsrc_node_switch_start(ctx);
3936                 if (ret)
3937                         break;
3938                 io_rsrc_node_switch(ctx, data);
3939
3940                 /* kill initial ref, already quiesced if zero */
3941                 if (atomic_dec_and_test(&data->refs))
3942                         break;
3943                 mutex_unlock(&ctx->uring_lock);
3944                 flush_delayed_work(&ctx->rsrc_put_work);
3945                 ret = wait_for_completion_interruptible(&data->done);
3946                 if (!ret) {
3947                         mutex_lock(&ctx->uring_lock);
3948                         if (atomic_read(&data->refs) > 0) {
3949                                 /*
3950                                  * it has been revived by another thread while
3951                                  * we were unlocked
3952                                  */
3953                                 mutex_unlock(&ctx->uring_lock);
3954                         } else {
3955                                 break;
3956                         }
3957                 }
3958
3959                 atomic_inc(&data->refs);
3960                 /* wait for all works potentially completing data->done */
3961                 flush_delayed_work(&ctx->rsrc_put_work);
3962                 reinit_completion(&data->done);
3963
3964                 ret = io_run_task_work_sig();
3965                 mutex_lock(&ctx->uring_lock);
3966         } while (ret >= 0);
3967         data->quiesce = false;
3968
3969         return ret;
3970 }
3971
3972 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
3973 {
3974         unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
3975         unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
3976
3977         return &data->tags[table_idx][off];
3978 }
3979
3980 static void io_rsrc_data_free(struct io_rsrc_data *data)
3981 {
3982         size_t size = data->nr * sizeof(data->tags[0][0]);
3983
3984         if (data->tags)
3985                 io_free_page_table((void **)data->tags, size);
3986         kfree(data);
3987 }
3988
3989 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
3990                                      u64 __user *utags, unsigned nr,
3991                                      struct io_rsrc_data **pdata)
3992 {
3993         struct io_rsrc_data *data;
3994         int ret = -ENOMEM;
3995         unsigned i;
3996
3997         data = kzalloc(sizeof(*data), GFP_KERNEL);
3998         if (!data)
3999                 return -ENOMEM;
4000         data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
4001         if (!data->tags) {
4002                 kfree(data);
4003                 return -ENOMEM;
4004         }
4005
4006         data->nr = nr;
4007         data->ctx = ctx;
4008         data->do_put = do_put;
4009         if (utags) {
4010                 ret = -EFAULT;
4011                 for (i = 0; i < nr; i++) {
4012                         u64 *tag_slot = io_get_tag_slot(data, i);
4013
4014                         if (copy_from_user(tag_slot, &utags[i],
4015                                            sizeof(*tag_slot)))
4016                                 goto fail;
4017                 }
4018         }
4019
4020         atomic_set(&data->refs, 1);
4021         init_completion(&data->done);
4022         *pdata = data;
4023         return 0;
4024 fail:
4025         io_rsrc_data_free(data);
4026         return ret;
4027 }
4028
4029 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
4030 {
4031 #if !defined(IO_URING_SCM_ALL)
4032         int i;
4033
4034         for (i = 0; i < ctx->nr_user_files; i++) {
4035                 struct file *file = io_file_from_index(&ctx->file_table, i);
4036
4037                 if (!file)
4038                         continue;
4039                 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
4040                         continue;
4041                 io_file_bitmap_clear(&ctx->file_table, i);
4042                 fput(file);
4043         }
4044 #endif
4045
4046 #if defined(CONFIG_UNIX)
4047         if (ctx->ring_sock) {
4048                 struct sock *sock = ctx->ring_sock->sk;
4049                 struct sk_buff *skb;
4050
4051                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
4052                         kfree_skb(skb);
4053         }
4054 #endif
4055         io_free_file_tables(&ctx->file_table);
4056         io_rsrc_data_free(ctx->file_data);
4057         ctx->file_data = NULL;
4058         ctx->nr_user_files = 0;
4059 }
4060
4061 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
4062 {
4063         unsigned nr = ctx->nr_user_files;
4064         int ret;
4065
4066         if (!ctx->file_data)
4067                 return -ENXIO;
4068
4069         /*
4070          * Quiesce may unlock ->uring_lock, and while it's not held
4071          * prevent new requests using the table.
4072          */
4073         ctx->nr_user_files = 0;
4074         ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
4075         ctx->nr_user_files = nr;
4076         if (!ret)
4077                 __io_sqe_files_unregister(ctx);
4078         return ret;
4079 }
4080
4081 /*
4082  * Ensure the UNIX gc is aware of our file set, so we are certain that
4083  * the io_uring can be safely unregistered on process exit, even if we have
4084  * loops in the file referencing. We account only files that can hold other
4085  * files because otherwise they can't form a loop and so are not interesting
4086  * for GC.
4087  */
4088 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
4089 {
4090 #if defined(CONFIG_UNIX)
4091         struct sock *sk = ctx->ring_sock->sk;
4092         struct sk_buff_head *head = &sk->sk_receive_queue;
4093         struct scm_fp_list *fpl;
4094         struct sk_buff *skb;
4095
4096         if (likely(!io_file_need_scm(file)))
4097                 return 0;
4098
4099         /*
4100          * See if we can merge this file into an existing skb SCM_RIGHTS
4101          * file set. If there's no room, fall back to allocating a new skb
4102          * and filling it in.
4103          */
4104         spin_lock_irq(&head->lock);
4105         skb = skb_peek(head);
4106         if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
4107                 __skb_unlink(skb, head);
4108         else
4109                 skb = NULL;
4110         spin_unlock_irq(&head->lock);
4111
4112         if (!skb) {
4113                 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
4114                 if (!fpl)
4115                         return -ENOMEM;
4116
4117                 skb = alloc_skb(0, GFP_KERNEL);
4118                 if (!skb) {
4119                         kfree(fpl);
4120                         return -ENOMEM;
4121                 }
4122
4123                 fpl->user = get_uid(current_user());
4124                 fpl->max = SCM_MAX_FD;
4125                 fpl->count = 0;
4126
4127                 UNIXCB(skb).fp = fpl;
4128                 skb->sk = sk;
4129                 skb->destructor = unix_destruct_scm;
4130                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
4131         }
4132
4133         fpl = UNIXCB(skb).fp;
4134         fpl->fp[fpl->count++] = get_file(file);
4135         unix_inflight(fpl->user, file);
4136         skb_queue_head(head, skb);
4137         fput(file);
4138 #endif
4139         return 0;
4140 }
4141
4142 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
4143 {
4144         struct file *file = prsrc->file;
4145 #if defined(CONFIG_UNIX)
4146         struct sock *sock = ctx->ring_sock->sk;
4147         struct sk_buff_head list, *head = &sock->sk_receive_queue;
4148         struct sk_buff *skb;
4149         int i;
4150
4151         if (!io_file_need_scm(file)) {
4152                 fput(file);
4153                 return;
4154         }
4155
4156         __skb_queue_head_init(&list);
4157
4158         /*
4159          * Find the skb that holds this file in its SCM_RIGHTS. When found,
4160          * remove this entry and rearrange the file array.
4161          */
4162         skb = skb_dequeue(head);
4163         while (skb) {
4164                 struct scm_fp_list *fp;
4165
4166                 fp = UNIXCB(skb).fp;
4167                 for (i = 0; i < fp->count; i++) {
4168                         int left;
4169
4170                         if (fp->fp[i] != file)
4171                                 continue;
4172
4173                         unix_notinflight(fp->user, fp->fp[i]);
4174                         left = fp->count - 1 - i;
4175                         if (left) {
4176                                 memmove(&fp->fp[i], &fp->fp[i + 1],
4177                                                 left * sizeof(struct file *));
4178                         }
4179                         fp->count--;
4180                         if (!fp->count) {
4181                                 kfree_skb(skb);
4182                                 skb = NULL;
4183                         } else {
4184                                 __skb_queue_tail(&list, skb);
4185                         }
4186                         fput(file);
4187                         file = NULL;
4188                         break;
4189                 }
4190
4191                 if (!file)
4192                         break;
4193
4194                 __skb_queue_tail(&list, skb);
4195
4196                 skb = skb_dequeue(head);
4197         }
4198
4199         if (skb_peek(&list)) {
4200                 spin_lock_irq(&head->lock);
4201                 while ((skb = __skb_dequeue(&list)) != NULL)
4202                         __skb_queue_tail(head, skb);
4203                 spin_unlock_irq(&head->lock);
4204         }
4205 #else
4206         fput(file);
4207 #endif
4208 }
4209
4210 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
4211 {
4212         struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
4213         struct io_ring_ctx *ctx = rsrc_data->ctx;
4214         struct io_rsrc_put *prsrc, *tmp;
4215
4216         list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
4217                 list_del(&prsrc->list);
4218
4219                 if (prsrc->tag) {
4220                         if (ctx->flags & IORING_SETUP_IOPOLL)
4221                                 mutex_lock(&ctx->uring_lock);
4222
4223                         spin_lock(&ctx->completion_lock);
4224                         io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
4225                         io_commit_cqring(ctx);
4226                         spin_unlock(&ctx->completion_lock);
4227                         io_cqring_ev_posted(ctx);
4228
4229                         if (ctx->flags & IORING_SETUP_IOPOLL)
4230                                 mutex_unlock(&ctx->uring_lock);
4231                 }
4232
4233                 rsrc_data->do_put(ctx, prsrc);
4234                 kfree(prsrc);
4235         }
4236
4237         io_rsrc_node_destroy(ref_node);
4238         if (atomic_dec_and_test(&rsrc_data->refs))
4239                 complete(&rsrc_data->done);
4240 }
4241
4242 static void io_rsrc_put_work(struct work_struct *work)
4243 {
4244         struct io_ring_ctx *ctx;
4245         struct llist_node *node;
4246
4247         ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
4248         node = llist_del_all(&ctx->rsrc_put_llist);
4249
4250         while (node) {
4251                 struct io_rsrc_node *ref_node;
4252                 struct llist_node *next = node->next;
4253
4254                 ref_node = llist_entry(node, struct io_rsrc_node, llist);
4255                 __io_rsrc_put_work(ref_node);
4256                 node = next;
4257         }
4258 }
4259
4260 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
4261                                  unsigned nr_args, u64 __user *tags)
4262 {
4263         __s32 __user *fds = (__s32 __user *) arg;
4264         struct file *file;
4265         int fd, ret;
4266         unsigned i;
4267
4268         if (ctx->file_data)
4269                 return -EBUSY;
4270         if (!nr_args)
4271                 return -EINVAL;
4272         if (nr_args > IORING_MAX_FIXED_FILES)
4273                 return -EMFILE;
4274         if (nr_args > rlimit(RLIMIT_NOFILE))
4275                 return -EMFILE;
4276         ret = io_rsrc_node_switch_start(ctx);
4277         if (ret)
4278                 return ret;
4279         ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
4280                                  &ctx->file_data);
4281         if (ret)
4282                 return ret;
4283
4284         if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
4285                 io_rsrc_data_free(ctx->file_data);
4286                 ctx->file_data = NULL;
4287                 return -ENOMEM;
4288         }
4289
4290         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
4291                 struct io_fixed_file *file_slot;
4292
4293                 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
4294                         ret = -EFAULT;
4295                         goto fail;
4296                 }
4297                 /* allow sparse sets */
4298                 if (!fds || fd == -1) {
4299                         ret = -EINVAL;
4300                         if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
4301                                 goto fail;
4302                         continue;
4303                 }
4304
4305                 file = fget(fd);
4306                 ret = -EBADF;
4307                 if (unlikely(!file))
4308                         goto fail;
4309
4310                 /*
4311                  * Don't allow io_uring instances to be registered. If UNIX
4312                  * isn't enabled, then this causes a reference cycle and this
4313                  * instance can never get freed. If UNIX is enabled we'll
4314                  * handle it just fine, but there's still no point in allowing
4315                  * a ring fd as it doesn't support regular read/write anyway.
4316                  */
4317                 if (io_is_uring_fops(file)) {
4318                         fput(file);
4319                         goto fail;
4320                 }
4321                 ret = io_scm_file_account(ctx, file);
4322                 if (ret) {
4323                         fput(file);
4324                         goto fail;
4325                 }
4326                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
4327                 io_fixed_file_set(file_slot, file);
4328                 io_file_bitmap_set(&ctx->file_table, i);
4329         }
4330
4331         io_rsrc_node_switch(ctx, NULL);
4332         return 0;
4333 fail:
4334         __io_sqe_files_unregister(ctx);
4335         return ret;
4336 }
4337
4338 int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
4339                           struct io_rsrc_node *node, void *rsrc)
4340 {
4341         u64 *tag_slot = io_get_tag_slot(data, idx);
4342         struct io_rsrc_put *prsrc;
4343
4344         prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
4345         if (!prsrc)
4346                 return -ENOMEM;
4347
4348         prsrc->tag = *tag_slot;
4349         *tag_slot = 0;
4350         prsrc->rsrc = rsrc;
4351         list_add(&prsrc->list, &node->rsrc_list);
4352         return 0;
4353 }
4354
4355 int io_install_fixed_file(struct io_kiocb *req, struct file *file,
4356                           unsigned int issue_flags, u32 slot_index)
4357         __must_hold(&req->ctx->uring_lock)
4358 {
4359         struct io_ring_ctx *ctx = req->ctx;
4360         bool needs_switch = false;
4361         struct io_fixed_file *file_slot;
4362         int ret;
4363
4364         if (io_is_uring_fops(file))
4365                 return -EBADF;
4366         if (!ctx->file_data)
4367                 return -ENXIO;
4368         if (slot_index >= ctx->nr_user_files)
4369                 return -EINVAL;
4370
4371         slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
4372         file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
4373
4374         if (file_slot->file_ptr) {
4375                 struct file *old_file;
4376
4377                 ret = io_rsrc_node_switch_start(ctx);
4378                 if (ret)
4379                         goto err;
4380
4381                 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
4382                 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
4383                                             ctx->rsrc_node, old_file);
4384                 if (ret)
4385                         goto err;
4386                 file_slot->file_ptr = 0;
4387                 io_file_bitmap_clear(&ctx->file_table, slot_index);
4388                 needs_switch = true;
4389         }
4390
4391         ret = io_scm_file_account(ctx, file);
4392         if (!ret) {
4393                 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
4394                 io_fixed_file_set(file_slot, file);
4395                 io_file_bitmap_set(&ctx->file_table, slot_index);
4396         }
4397 err:
4398         if (needs_switch)
4399                 io_rsrc_node_switch(ctx, ctx->file_data);
4400         if (ret)
4401                 fput(file);
4402         return ret;
4403 }
4404
4405 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
4406                                  struct io_uring_rsrc_update2 *up,
4407                                  unsigned nr_args)
4408 {
4409         u64 __user *tags = u64_to_user_ptr(up->tags);
4410         __s32 __user *fds = u64_to_user_ptr(up->data);
4411         struct io_rsrc_data *data = ctx->file_data;
4412         struct io_fixed_file *file_slot;
4413         struct file *file;
4414         int fd, i, err = 0;
4415         unsigned int done;
4416         bool needs_switch = false;
4417
4418         if (!ctx->file_data)
4419                 return -ENXIO;
4420         if (up->offset + nr_args > ctx->nr_user_files)
4421                 return -EINVAL;
4422
4423         for (done = 0; done < nr_args; done++) {
4424                 u64 tag = 0;
4425
4426                 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
4427                     copy_from_user(&fd, &fds[done], sizeof(fd))) {
4428                         err = -EFAULT;
4429                         break;
4430                 }
4431                 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
4432                         err = -EINVAL;
4433                         break;
4434                 }
4435                 if (fd == IORING_REGISTER_FILES_SKIP)
4436                         continue;
4437
4438                 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
4439                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
4440
4441                 if (file_slot->file_ptr) {
4442                         file = (struct file *)(file_slot->file_ptr & FFS_MASK);
4443                         err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
4444                         if (err)
4445                                 break;
4446                         file_slot->file_ptr = 0;
4447                         io_file_bitmap_clear(&ctx->file_table, i);
4448                         needs_switch = true;
4449                 }
4450                 if (fd != -1) {
4451                         file = fget(fd);
4452                         if (!file) {
4453                                 err = -EBADF;
4454                                 break;
4455                         }
4456                         /*
4457                          * Don't allow io_uring instances to be registered. If
4458                          * UNIX isn't enabled, then this causes a reference
4459                          * cycle and this instance can never get freed. If UNIX
4460                          * is enabled we'll handle it just fine, but there's
4461                          * still no point in allowing a ring fd as it doesn't
4462                          * support regular read/write anyway.
4463                          */
4464                         if (io_is_uring_fops(file)) {
4465                                 fput(file);
4466                                 err = -EBADF;
4467                                 break;
4468                         }
4469                         err = io_scm_file_account(ctx, file);
4470                         if (err) {
4471                                 fput(file);
4472                                 break;
4473                         }
4474                         *io_get_tag_slot(data, i) = tag;
4475                         io_fixed_file_set(file_slot, file);
4476                         io_file_bitmap_set(&ctx->file_table, i);
4477                 }
4478         }
4479
4480         if (needs_switch)
4481                 io_rsrc_node_switch(ctx, data);
4482         return done ? done : err;
4483 }
4484
4485 static inline void __io_unaccount_mem(struct user_struct *user,
4486                                       unsigned long nr_pages)
4487 {
4488         atomic_long_sub(nr_pages, &user->locked_vm);
4489 }
4490
4491 static inline int __io_account_mem(struct user_struct *user,
4492                                    unsigned long nr_pages)
4493 {
4494         unsigned long page_limit, cur_pages, new_pages;
4495
4496         /* Don't allow more pages than we can safely lock */
4497         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
4498
4499         do {
4500                 cur_pages = atomic_long_read(&user->locked_vm);
4501                 new_pages = cur_pages + nr_pages;
4502                 if (new_pages > page_limit)
4503                         return -ENOMEM;
4504         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
4505                                         new_pages) != cur_pages);
4506
4507         return 0;
4508 }
4509
4510 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
4511 {
4512         if (ctx->user)
4513                 __io_unaccount_mem(ctx->user, nr_pages);
4514
4515         if (ctx->mm_account)
4516                 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
4517 }
4518
4519 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
4520 {
4521         int ret;
4522
4523         if (ctx->user) {
4524                 ret = __io_account_mem(ctx->user, nr_pages);
4525                 if (ret)
4526                         return ret;
4527         }
4528
4529         if (ctx->mm_account)
4530                 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
4531
4532         return 0;
4533 }
4534
4535 static void io_mem_free(void *ptr)
4536 {
4537         struct page *page;
4538
4539         if (!ptr)
4540                 return;
4541
4542         page = virt_to_head_page(ptr);
4543         if (put_page_testzero(page))
4544                 free_compound_page(page);
4545 }
4546
4547 static void *io_mem_alloc(size_t size)
4548 {
4549         gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
4550
4551         return (void *) __get_free_pages(gfp, get_order(size));
4552 }
4553
4554 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
4555                                 unsigned int cq_entries, size_t *sq_offset)
4556 {
4557         struct io_rings *rings;
4558         size_t off, sq_array_size;
4559
4560         off = struct_size(rings, cqes, cq_entries);
4561         if (off == SIZE_MAX)
4562                 return SIZE_MAX;
4563         if (ctx->flags & IORING_SETUP_CQE32) {
4564                 if (check_shl_overflow(off, 1, &off))
4565                         return SIZE_MAX;
4566         }
4567
4568 #ifdef CONFIG_SMP
4569         off = ALIGN(off, SMP_CACHE_BYTES);
4570         if (off == 0)
4571                 return SIZE_MAX;
4572 #endif
4573
4574         if (sq_offset)
4575                 *sq_offset = off;
4576
4577         sq_array_size = array_size(sizeof(u32), sq_entries);
4578         if (sq_array_size == SIZE_MAX)
4579                 return SIZE_MAX;
4580
4581         if (check_add_overflow(off, sq_array_size, &off))
4582                 return SIZE_MAX;
4583
4584         return off;
4585 }
4586
4587 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
4588 {
4589         struct io_mapped_ubuf *imu = *slot;
4590         unsigned int i;
4591
4592         if (imu != ctx->dummy_ubuf) {
4593                 for (i = 0; i < imu->nr_bvecs; i++)
4594                         unpin_user_page(imu->bvec[i].bv_page);
4595                 if (imu->acct_pages)
4596                         io_unaccount_mem(ctx, imu->acct_pages);
4597                 kvfree(imu);
4598         }
4599         *slot = NULL;
4600 }
4601
4602 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
4603 {
4604         io_buffer_unmap(ctx, &prsrc->buf);
4605         prsrc->buf = NULL;
4606 }
4607
4608 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
4609 {
4610         unsigned int i;
4611
4612         for (i = 0; i < ctx->nr_user_bufs; i++)
4613                 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
4614         kfree(ctx->user_bufs);
4615         io_rsrc_data_free(ctx->buf_data);
4616         ctx->user_bufs = NULL;
4617         ctx->buf_data = NULL;
4618         ctx->nr_user_bufs = 0;
4619 }
4620
4621 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
4622 {
4623         unsigned nr = ctx->nr_user_bufs;
4624         int ret;
4625
4626         if (!ctx->buf_data)
4627                 return -ENXIO;
4628
4629         /*
4630          * Quiesce may unlock ->uring_lock, and while it's not held
4631          * prevent new requests using the table.
4632          */
4633         ctx->nr_user_bufs = 0;
4634         ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
4635         ctx->nr_user_bufs = nr;
4636         if (!ret)
4637                 __io_sqe_buffers_unregister(ctx);
4638         return ret;
4639 }
4640
4641 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
4642                        void __user *arg, unsigned index)
4643 {
4644         struct iovec __user *src;
4645
4646 #ifdef CONFIG_COMPAT
4647         if (ctx->compat) {
4648                 struct compat_iovec __user *ciovs;
4649                 struct compat_iovec ciov;
4650
4651                 ciovs = (struct compat_iovec __user *) arg;
4652                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
4653                         return -EFAULT;
4654
4655                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
4656                 dst->iov_len = ciov.iov_len;
4657                 return 0;
4658         }
4659 #endif
4660         src = (struct iovec __user *) arg;
4661         if (copy_from_user(dst, &src[index], sizeof(*dst)))
4662                 return -EFAULT;
4663         return 0;
4664 }
4665
4666 /*
4667  * Not super efficient, but this is just a registration time. And we do cache
4668  * the last compound head, so generally we'll only do a full search if we don't
4669  * match that one.
4670  *
4671  * We check if the given compound head page has already been accounted, to
4672  * avoid double accounting it. This allows us to account the full size of the
4673  * page, not just the constituent pages of a huge page.
4674  */
4675 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
4676                                   int nr_pages, struct page *hpage)
4677 {
4678         int i, j;
4679
4680         /* check current page array */
4681         for (i = 0; i < nr_pages; i++) {
4682                 if (!PageCompound(pages[i]))
4683                         continue;
4684                 if (compound_head(pages[i]) == hpage)
4685                         return true;
4686         }
4687
4688         /* check previously registered pages */
4689         for (i = 0; i < ctx->nr_user_bufs; i++) {
4690                 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
4691
4692                 for (j = 0; j < imu->nr_bvecs; j++) {
4693                         if (!PageCompound(imu->bvec[j].bv_page))
4694                                 continue;
4695                         if (compound_head(imu->bvec[j].bv_page) == hpage)
4696                                 return true;
4697                 }
4698         }
4699
4700         return false;
4701 }
4702
4703 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
4704                                  int nr_pages, struct io_mapped_ubuf *imu,
4705                                  struct page **last_hpage)
4706 {
4707         int i, ret;
4708
4709         imu->acct_pages = 0;
4710         for (i = 0; i < nr_pages; i++) {
4711                 if (!PageCompound(pages[i])) {
4712                         imu->acct_pages++;
4713                 } else {
4714                         struct page *hpage;
4715
4716                         hpage = compound_head(pages[i]);
4717                         if (hpage == *last_hpage)
4718                                 continue;
4719                         *last_hpage = hpage;
4720                         if (headpage_already_acct(ctx, pages, i, hpage))
4721                                 continue;
4722                         imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
4723                 }
4724         }
4725
4726         if (!imu->acct_pages)
4727                 return 0;
4728
4729         ret = io_account_mem(ctx, imu->acct_pages);
4730         if (ret)
4731                 imu->acct_pages = 0;
4732         return ret;
4733 }
4734
4735 struct page **io_pin_pages(unsigned long ubuf, unsigned long len, int *npages)
4736 {
4737         unsigned long start, end, nr_pages;
4738         struct vm_area_struct **vmas = NULL;
4739         struct page **pages = NULL;
4740         int i, pret, ret = -ENOMEM;
4741
4742         end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
4743         start = ubuf >> PAGE_SHIFT;
4744         nr_pages = end - start;
4745
4746         pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
4747         if (!pages)
4748                 goto done;
4749
4750         vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
4751                               GFP_KERNEL);
4752         if (!vmas)
4753                 goto done;
4754
4755         ret = 0;
4756         mmap_read_lock(current->mm);
4757         pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
4758                               pages, vmas);
4759         if (pret == nr_pages) {
4760                 /* don't support file backed memory */
4761                 for (i = 0; i < nr_pages; i++) {
4762                         struct vm_area_struct *vma = vmas[i];
4763
4764                         if (vma_is_shmem(vma))
4765                                 continue;
4766                         if (vma->vm_file &&
4767                             !is_file_hugepages(vma->vm_file)) {
4768                                 ret = -EOPNOTSUPP;
4769                                 break;
4770                         }
4771                 }
4772                 *npages = nr_pages;
4773         } else {
4774                 ret = pret < 0 ? pret : -EFAULT;
4775         }
4776         mmap_read_unlock(current->mm);
4777         if (ret) {
4778                 /*
4779                  * if we did partial map, or found file backed vmas,
4780                  * release any pages we did get
4781                  */
4782                 if (pret > 0)
4783                         unpin_user_pages(pages, pret);
4784                 goto done;
4785         }
4786         ret = 0;
4787 done:
4788         kvfree(vmas);
4789         if (ret < 0) {
4790                 kvfree(pages);
4791                 pages = ERR_PTR(ret);
4792         }
4793         return pages;
4794 }
4795
4796 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
4797                                   struct io_mapped_ubuf **pimu,
4798                                   struct page **last_hpage)
4799 {
4800         struct io_mapped_ubuf *imu = NULL;
4801         struct page **pages = NULL;
4802         unsigned long off;
4803         size_t size;
4804         int ret, nr_pages, i;
4805
4806         if (!iov->iov_base) {
4807                 *pimu = ctx->dummy_ubuf;
4808                 return 0;
4809         }
4810
4811         *pimu = NULL;
4812         ret = -ENOMEM;
4813
4814         pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
4815                                 &nr_pages);
4816         if (IS_ERR(pages)) {
4817                 ret = PTR_ERR(pages);
4818                 pages = NULL;
4819                 goto done;
4820         }
4821
4822         imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
4823         if (!imu)
4824                 goto done;
4825
4826         ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
4827         if (ret) {
4828                 unpin_user_pages(pages, nr_pages);
4829                 goto done;
4830         }
4831
4832         off = (unsigned long) iov->iov_base & ~PAGE_MASK;
4833         size = iov->iov_len;
4834         for (i = 0; i < nr_pages; i++) {
4835                 size_t vec_len;
4836
4837                 vec_len = min_t(size_t, size, PAGE_SIZE - off);
4838                 imu->bvec[i].bv_page = pages[i];
4839                 imu->bvec[i].bv_len = vec_len;
4840                 imu->bvec[i].bv_offset = off;
4841                 off = 0;
4842                 size -= vec_len;
4843         }
4844         /* store original address for later verification */
4845         imu->ubuf = (unsigned long) iov->iov_base;
4846         imu->ubuf_end = imu->ubuf + iov->iov_len;
4847         imu->nr_bvecs = nr_pages;
4848         *pimu = imu;
4849         ret = 0;
4850 done:
4851         if (ret)
4852                 kvfree(imu);
4853         kvfree(pages);
4854         return ret;
4855 }
4856
4857 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
4858 {
4859         ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
4860         return ctx->user_bufs ? 0 : -ENOMEM;
4861 }
4862
4863 static int io_buffer_validate(struct iovec *iov)
4864 {
4865         unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
4866
4867         /*
4868          * Don't impose further limits on the size and buffer
4869          * constraints here, we'll -EINVAL later when IO is
4870          * submitted if they are wrong.
4871          */
4872         if (!iov->iov_base)
4873                 return iov->iov_len ? -EFAULT : 0;
4874         if (!iov->iov_len)
4875                 return -EFAULT;
4876
4877         /* arbitrary limit, but we need something */
4878         if (iov->iov_len > SZ_1G)
4879                 return -EFAULT;
4880
4881         if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
4882                 return -EOVERFLOW;
4883
4884         return 0;
4885 }
4886
4887 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
4888                                    unsigned int nr_args, u64 __user *tags)
4889 {
4890         struct page *last_hpage = NULL;
4891         struct io_rsrc_data *data;
4892         int i, ret;
4893         struct iovec iov;
4894
4895         if (ctx->user_bufs)
4896                 return -EBUSY;
4897         if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
4898                 return -EINVAL;
4899         ret = io_rsrc_node_switch_start(ctx);
4900         if (ret)
4901                 return ret;
4902         ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
4903         if (ret)
4904                 return ret;
4905         ret = io_buffers_map_alloc(ctx, nr_args);
4906         if (ret) {
4907                 io_rsrc_data_free(data);
4908                 return ret;
4909         }
4910
4911         for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
4912                 if (arg) {
4913                         ret = io_copy_iov(ctx, &iov, arg, i);
4914                         if (ret)
4915                                 break;
4916                         ret = io_buffer_validate(&iov);
4917                         if (ret)
4918                                 break;
4919                 } else {
4920                         memset(&iov, 0, sizeof(iov));
4921                 }
4922
4923                 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
4924                         ret = -EINVAL;
4925                         break;
4926                 }
4927
4928                 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
4929                                              &last_hpage);
4930                 if (ret)
4931                         break;
4932         }
4933
4934         WARN_ON_ONCE(ctx->buf_data);
4935
4936         ctx->buf_data = data;
4937         if (ret)
4938                 __io_sqe_buffers_unregister(ctx);
4939         else
4940                 io_rsrc_node_switch(ctx, NULL);
4941         return ret;
4942 }
4943
4944 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
4945                                    struct io_uring_rsrc_update2 *up,
4946                                    unsigned int nr_args)
4947 {
4948         u64 __user *tags = u64_to_user_ptr(up->tags);
4949         struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
4950         struct page *last_hpage = NULL;
4951         bool needs_switch = false;
4952         __u32 done;
4953         int i, err;
4954
4955         if (!ctx->buf_data)
4956                 return -ENXIO;
4957         if (up->offset + nr_args > ctx->nr_user_bufs)
4958                 return -EINVAL;
4959
4960         for (done = 0; done < nr_args; done++) {
4961                 struct io_mapped_ubuf *imu;
4962                 int offset = up->offset + done;
4963                 u64 tag = 0;
4964
4965                 err = io_copy_iov(ctx, &iov, iovs, done);
4966                 if (err)
4967                         break;
4968                 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
4969                         err = -EFAULT;
4970                         break;
4971                 }
4972                 err = io_buffer_validate(&iov);
4973                 if (err)
4974                         break;
4975                 if (!iov.iov_base && tag) {
4976                         err = -EINVAL;
4977                         break;
4978                 }
4979                 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
4980                 if (err)
4981                         break;
4982
4983                 i = array_index_nospec(offset, ctx->nr_user_bufs);
4984                 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
4985                         err = io_queue_rsrc_removal(ctx->buf_data, i,
4986                                                     ctx->rsrc_node, ctx->user_bufs[i]);
4987                         if (unlikely(err)) {
4988                                 io_buffer_unmap(ctx, &imu);
4989                                 break;
4990                         }
4991                         ctx->user_bufs[i] = NULL;
4992                         needs_switch = true;
4993                 }
4994
4995                 ctx->user_bufs[i] = imu;
4996                 *io_get_tag_slot(ctx->buf_data, offset) = tag;
4997         }
4998
4999         if (needs_switch)
5000                 io_rsrc_node_switch(ctx, ctx->buf_data);
5001         return done ? done : err;
5002 }
5003
5004 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
5005                                unsigned int eventfd_async)
5006 {
5007         struct io_ev_fd *ev_fd;
5008         __s32 __user *fds = arg;
5009         int fd;
5010
5011         ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
5012                                         lockdep_is_held(&ctx->uring_lock));
5013         if (ev_fd)
5014                 return -EBUSY;
5015
5016         if (copy_from_user(&fd, fds, sizeof(*fds)))
5017                 return -EFAULT;
5018
5019         ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
5020         if (!ev_fd)
5021                 return -ENOMEM;
5022
5023         ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
5024         if (IS_ERR(ev_fd->cq_ev_fd)) {
5025                 int ret = PTR_ERR(ev_fd->cq_ev_fd);
5026                 kfree(ev_fd);
5027                 return ret;
5028         }
5029         ev_fd->eventfd_async = eventfd_async;
5030         ctx->has_evfd = true;
5031         rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
5032         return 0;
5033 }
5034
5035 static void io_eventfd_put(struct rcu_head *rcu)
5036 {
5037         struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
5038
5039         eventfd_ctx_put(ev_fd->cq_ev_fd);
5040         kfree(ev_fd);
5041 }
5042
5043 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
5044 {
5045         struct io_ev_fd *ev_fd;
5046
5047         ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
5048                                         lockdep_is_held(&ctx->uring_lock));
5049         if (ev_fd) {
5050                 ctx->has_evfd = false;
5051                 rcu_assign_pointer(ctx->io_ev_fd, NULL);
5052                 call_rcu(&ev_fd->rcu, io_eventfd_put);
5053                 return 0;
5054         }
5055
5056         return -ENXIO;
5057 }
5058
5059 static void io_req_caches_free(struct io_ring_ctx *ctx)
5060 {
5061         struct io_submit_state *state = &ctx->submit_state;
5062         int nr = 0;
5063
5064         mutex_lock(&ctx->uring_lock);
5065         io_flush_cached_locked_reqs(ctx, state);
5066
5067         while (!io_req_cache_empty(ctx)) {
5068                 struct io_wq_work_node *node;
5069                 struct io_kiocb *req;
5070
5071                 node = wq_stack_extract(&state->free_list);
5072                 req = container_of(node, struct io_kiocb, comp_list);
5073                 kmem_cache_free(req_cachep, req);
5074                 nr++;
5075         }
5076         if (nr)
5077                 percpu_ref_put_many(&ctx->refs, nr);
5078         mutex_unlock(&ctx->uring_lock);
5079 }
5080
5081 static void io_wait_rsrc_data(struct io_rsrc_data *data)
5082 {
5083         if (data && !atomic_dec_and_test(&data->refs))
5084                 wait_for_completion(&data->done);
5085 }
5086
5087 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
5088 {
5089         struct async_poll *apoll;
5090
5091         while (!list_empty(&ctx->apoll_cache)) {
5092                 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
5093                                                 poll.wait.entry);
5094                 list_del(&apoll->poll.wait.entry);
5095                 kfree(apoll);
5096         }
5097 }
5098
5099 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
5100 {
5101         io_sq_thread_finish(ctx);
5102
5103         if (ctx->mm_account) {
5104                 mmdrop(ctx->mm_account);
5105                 ctx->mm_account = NULL;
5106         }
5107
5108         io_rsrc_refs_drop(ctx);
5109         /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
5110         io_wait_rsrc_data(ctx->buf_data);
5111         io_wait_rsrc_data(ctx->file_data);
5112
5113         mutex_lock(&ctx->uring_lock);
5114         if (ctx->buf_data)
5115                 __io_sqe_buffers_unregister(ctx);
5116         if (ctx->file_data)
5117                 __io_sqe_files_unregister(ctx);
5118         if (ctx->rings)
5119                 __io_cqring_overflow_flush(ctx, true);
5120         io_eventfd_unregister(ctx);
5121         io_flush_apoll_cache(ctx);
5122         mutex_unlock(&ctx->uring_lock);
5123         io_destroy_buffers(ctx);
5124         if (ctx->sq_creds)
5125                 put_cred(ctx->sq_creds);
5126
5127         /* there are no registered resources left, nobody uses it */
5128         if (ctx->rsrc_node)
5129                 io_rsrc_node_destroy(ctx->rsrc_node);
5130         if (ctx->rsrc_backup_node)
5131                 io_rsrc_node_destroy(ctx->rsrc_backup_node);
5132         flush_delayed_work(&ctx->rsrc_put_work);
5133         flush_delayed_work(&ctx->fallback_work);
5134
5135         WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
5136         WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
5137
5138 #if defined(CONFIG_UNIX)
5139         if (ctx->ring_sock) {
5140                 ctx->ring_sock->file = NULL; /* so that iput() is called */
5141                 sock_release(ctx->ring_sock);
5142         }
5143 #endif
5144         WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
5145
5146         io_mem_free(ctx->rings);
5147         io_mem_free(ctx->sq_sqes);
5148
5149         percpu_ref_exit(&ctx->refs);
5150         free_uid(ctx->user);
5151         io_req_caches_free(ctx);
5152         if (ctx->hash_map)
5153                 io_wq_put_hash(ctx->hash_map);
5154         kfree(ctx->cancel_hash);
5155         kfree(ctx->dummy_ubuf);
5156         kfree(ctx->io_bl);
5157         xa_destroy(&ctx->io_bl_xa);
5158         kfree(ctx);
5159 }
5160
5161 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
5162 {
5163         struct io_ring_ctx *ctx = file->private_data;
5164         __poll_t mask = 0;
5165
5166         poll_wait(file, &ctx->cq_wait, wait);
5167         /*
5168          * synchronizes with barrier from wq_has_sleeper call in
5169          * io_commit_cqring
5170          */
5171         smp_rmb();
5172         if (!io_sqring_full(ctx))
5173                 mask |= EPOLLOUT | EPOLLWRNORM;
5174
5175         /*
5176          * Don't flush cqring overflow list here, just do a simple check.
5177          * Otherwise there could possible be ABBA deadlock:
5178          *      CPU0                    CPU1
5179          *      ----                    ----
5180          * lock(&ctx->uring_lock);
5181          *                              lock(&ep->mtx);
5182          *                              lock(&ctx->uring_lock);
5183          * lock(&ep->mtx);
5184          *
5185          * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
5186          * pushs them to do the flush.
5187          */
5188         if (io_cqring_events(ctx) ||
5189             test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
5190                 mask |= EPOLLIN | EPOLLRDNORM;
5191
5192         return mask;
5193 }
5194
5195 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
5196 {
5197         const struct cred *creds;
5198
5199         creds = xa_erase(&ctx->personalities, id);
5200         if (creds) {
5201                 put_cred(creds);
5202                 return 0;
5203         }
5204
5205         return -EINVAL;
5206 }
5207
5208 struct io_tctx_exit {
5209         struct callback_head            task_work;
5210         struct completion               completion;
5211         struct io_ring_ctx              *ctx;
5212 };
5213
5214 static __cold void io_tctx_exit_cb(struct callback_head *cb)
5215 {
5216         struct io_uring_task *tctx = current->io_uring;
5217         struct io_tctx_exit *work;
5218
5219         work = container_of(cb, struct io_tctx_exit, task_work);
5220         /*
5221          * When @in_idle, we're in cancellation and it's racy to remove the
5222          * node. It'll be removed by the end of cancellation, just ignore it.
5223          */
5224         if (!atomic_read(&tctx->in_idle))
5225                 io_uring_del_tctx_node((unsigned long)work->ctx);
5226         complete(&work->completion);
5227 }
5228
5229 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
5230 {
5231         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5232
5233         return req->ctx == data;
5234 }
5235
5236 static __cold void io_ring_exit_work(struct work_struct *work)
5237 {
5238         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
5239         unsigned long timeout = jiffies + HZ * 60 * 5;
5240         unsigned long interval = HZ / 20;
5241         struct io_tctx_exit exit;
5242         struct io_tctx_node *node;
5243         int ret;
5244
5245         /*
5246          * If we're doing polled IO and end up having requests being
5247          * submitted async (out-of-line), then completions can come in while
5248          * we're waiting for refs to drop. We need to reap these manually,
5249          * as nobody else will be looking for them.
5250          */
5251         do {
5252                 io_uring_try_cancel_requests(ctx, NULL, true);
5253                 if (ctx->sq_data) {
5254                         struct io_sq_data *sqd = ctx->sq_data;
5255                         struct task_struct *tsk;
5256
5257                         io_sq_thread_park(sqd);
5258                         tsk = sqd->thread;
5259                         if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
5260                                 io_wq_cancel_cb(tsk->io_uring->io_wq,
5261                                                 io_cancel_ctx_cb, ctx, true);
5262                         io_sq_thread_unpark(sqd);
5263                 }
5264
5265                 io_req_caches_free(ctx);
5266
5267                 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
5268                         /* there is little hope left, don't run it too often */
5269                         interval = HZ * 60;
5270                 }
5271         } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
5272
5273         init_completion(&exit.completion);
5274         init_task_work(&exit.task_work, io_tctx_exit_cb);
5275         exit.ctx = ctx;
5276         /*
5277          * Some may use context even when all refs and requests have been put,
5278          * and they are free to do so while still holding uring_lock or
5279          * completion_lock, see io_req_task_submit(). Apart from other work,
5280          * this lock/unlock section also waits them to finish.
5281          */
5282         mutex_lock(&ctx->uring_lock);
5283         while (!list_empty(&ctx->tctx_list)) {
5284                 WARN_ON_ONCE(time_after(jiffies, timeout));
5285
5286                 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
5287                                         ctx_node);
5288                 /* don't spin on a single task if cancellation failed */
5289                 list_rotate_left(&ctx->tctx_list);
5290                 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
5291                 if (WARN_ON_ONCE(ret))
5292                         continue;
5293
5294                 mutex_unlock(&ctx->uring_lock);
5295                 wait_for_completion(&exit.completion);
5296                 mutex_lock(&ctx->uring_lock);
5297         }
5298         mutex_unlock(&ctx->uring_lock);
5299         spin_lock(&ctx->completion_lock);
5300         spin_unlock(&ctx->completion_lock);
5301
5302         io_ring_ctx_free(ctx);
5303 }
5304
5305 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
5306 {
5307         unsigned long index;
5308         struct creds *creds;
5309
5310         mutex_lock(&ctx->uring_lock);
5311         percpu_ref_kill(&ctx->refs);
5312         if (ctx->rings)
5313                 __io_cqring_overflow_flush(ctx, true);
5314         xa_for_each(&ctx->personalities, index, creds)
5315                 io_unregister_personality(ctx, index);
5316         mutex_unlock(&ctx->uring_lock);
5317
5318         /* failed during ring init, it couldn't have issued any requests */
5319         if (ctx->rings) {
5320                 io_kill_timeouts(ctx, NULL, true);
5321                 io_poll_remove_all(ctx, NULL, true);
5322                 /* if we failed setting up the ctx, we might not have any rings */
5323                 io_iopoll_try_reap_events(ctx);
5324         }
5325
5326         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
5327         /*
5328          * Use system_unbound_wq to avoid spawning tons of event kworkers
5329          * if we're exiting a ton of rings at the same time. It just adds
5330          * noise and overhead, there's no discernable change in runtime
5331          * over using system_wq.
5332          */
5333         queue_work(system_unbound_wq, &ctx->exit_work);
5334 }
5335
5336 static int io_uring_release(struct inode *inode, struct file *file)
5337 {
5338         struct io_ring_ctx *ctx = file->private_data;
5339
5340         file->private_data = NULL;
5341         io_ring_ctx_wait_and_kill(ctx);
5342         return 0;
5343 }
5344
5345 struct io_task_cancel {
5346         struct task_struct *task;
5347         bool all;
5348 };
5349
5350 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
5351 {
5352         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5353         struct io_task_cancel *cancel = data;
5354
5355         return io_match_task_safe(req, cancel->task, cancel->all);
5356 }
5357
5358 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
5359                                          struct task_struct *task,
5360                                          bool cancel_all)
5361 {
5362         struct io_defer_entry *de;
5363         LIST_HEAD(list);
5364
5365         spin_lock(&ctx->completion_lock);
5366         list_for_each_entry_reverse(de, &ctx->defer_list, list) {
5367                 if (io_match_task_safe(de->req, task, cancel_all)) {
5368                         list_cut_position(&list, &ctx->defer_list, &de->list);
5369                         break;
5370                 }
5371         }
5372         spin_unlock(&ctx->completion_lock);
5373         if (list_empty(&list))
5374                 return false;
5375
5376         while (!list_empty(&list)) {
5377                 de = list_first_entry(&list, struct io_defer_entry, list);
5378                 list_del_init(&de->list);
5379                 io_req_complete_failed(de->req, -ECANCELED);
5380                 kfree(de);
5381         }
5382         return true;
5383 }
5384
5385 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
5386 {
5387         struct io_tctx_node *node;
5388         enum io_wq_cancel cret;
5389         bool ret = false;
5390
5391         mutex_lock(&ctx->uring_lock);
5392         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5393                 struct io_uring_task *tctx = node->task->io_uring;
5394
5395                 /*
5396                  * io_wq will stay alive while we hold uring_lock, because it's
5397                  * killed after ctx nodes, which requires to take the lock.
5398                  */
5399                 if (!tctx || !tctx->io_wq)
5400                         continue;
5401                 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
5402                 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
5403         }
5404         mutex_unlock(&ctx->uring_lock);
5405
5406         return ret;
5407 }
5408
5409 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
5410                                                 struct task_struct *task,
5411                                                 bool cancel_all)
5412 {
5413         struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
5414         struct io_uring_task *tctx = task ? task->io_uring : NULL;
5415
5416         /* failed during ring init, it couldn't have issued any requests */
5417         if (!ctx->rings)
5418                 return;
5419
5420         while (1) {
5421                 enum io_wq_cancel cret;
5422                 bool ret = false;
5423
5424                 if (!task) {
5425                         ret |= io_uring_try_cancel_iowq(ctx);
5426                 } else if (tctx && tctx->io_wq) {
5427                         /*
5428                          * Cancels requests of all rings, not only @ctx, but
5429                          * it's fine as the task is in exit/exec.
5430                          */
5431                         cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
5432                                                &cancel, true);
5433                         ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
5434                 }
5435
5436                 /* SQPOLL thread does its own polling */
5437                 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
5438                     (ctx->sq_data && ctx->sq_data->thread == current)) {
5439                         while (!wq_list_empty(&ctx->iopoll_list)) {
5440                                 io_iopoll_try_reap_events(ctx);
5441                                 ret = true;
5442                         }
5443                 }
5444
5445                 ret |= io_cancel_defer_files(ctx, task, cancel_all);
5446                 ret |= io_poll_remove_all(ctx, task, cancel_all);
5447                 ret |= io_kill_timeouts(ctx, task, cancel_all);
5448                 if (task)
5449                         ret |= io_run_task_work();
5450                 if (!ret)
5451                         break;
5452                 cond_resched();
5453         }
5454 }
5455
5456 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
5457 {
5458         if (tracked)
5459                 return atomic_read(&tctx->inflight_tracked);
5460         return percpu_counter_sum(&tctx->inflight);
5461 }
5462
5463 /*
5464  * Find any io_uring ctx that this task has registered or done IO on, and cancel
5465  * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
5466  */
5467 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
5468 {
5469         struct io_uring_task *tctx = current->io_uring;
5470         struct io_ring_ctx *ctx;
5471         s64 inflight;
5472         DEFINE_WAIT(wait);
5473
5474         WARN_ON_ONCE(sqd && sqd->thread != current);
5475
5476         if (!current->io_uring)
5477                 return;
5478         if (tctx->io_wq)
5479                 io_wq_exit_start(tctx->io_wq);
5480
5481         atomic_inc(&tctx->in_idle);
5482         do {
5483                 io_uring_drop_tctx_refs(current);
5484                 /* read completions before cancelations */
5485                 inflight = tctx_inflight(tctx, !cancel_all);
5486                 if (!inflight)
5487                         break;
5488
5489                 if (!sqd) {
5490                         struct io_tctx_node *node;
5491                         unsigned long index;
5492
5493                         xa_for_each(&tctx->xa, index, node) {
5494                                 /* sqpoll task will cancel all its requests */
5495                                 if (node->ctx->sq_data)
5496                                         continue;
5497                                 io_uring_try_cancel_requests(node->ctx, current,
5498                                                              cancel_all);
5499                         }
5500                 } else {
5501                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
5502                                 io_uring_try_cancel_requests(ctx, current,
5503                                                              cancel_all);
5504                 }
5505
5506                 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
5507                 io_run_task_work();
5508                 io_uring_drop_tctx_refs(current);
5509
5510                 /*
5511                  * If we've seen completions, retry without waiting. This
5512                  * avoids a race where a completion comes in before we did
5513                  * prepare_to_wait().
5514                  */
5515                 if (inflight == tctx_inflight(tctx, !cancel_all))
5516                         schedule();
5517                 finish_wait(&tctx->wait, &wait);
5518         } while (1);
5519
5520         io_uring_clean_tctx(tctx);
5521         if (cancel_all) {
5522                 /*
5523                  * We shouldn't run task_works after cancel, so just leave
5524                  * ->in_idle set for normal exit.
5525                  */
5526                 atomic_dec(&tctx->in_idle);
5527                 /* for exec all current's requests should be gone, kill tctx */
5528                 __io_uring_free(current);
5529         }
5530 }
5531
5532 void __io_uring_cancel(bool cancel_all)
5533 {
5534         io_uring_cancel_generic(cancel_all, NULL);
5535 }
5536
5537 static void *io_uring_validate_mmap_request(struct file *file,
5538                                             loff_t pgoff, size_t sz)
5539 {
5540         struct io_ring_ctx *ctx = file->private_data;
5541         loff_t offset = pgoff << PAGE_SHIFT;
5542         struct page *page;
5543         void *ptr;
5544
5545         switch (offset) {
5546         case IORING_OFF_SQ_RING:
5547         case IORING_OFF_CQ_RING:
5548                 ptr = ctx->rings;
5549                 break;
5550         case IORING_OFF_SQES:
5551                 ptr = ctx->sq_sqes;
5552                 break;
5553         default:
5554                 return ERR_PTR(-EINVAL);
5555         }
5556
5557         page = virt_to_head_page(ptr);
5558         if (sz > page_size(page))
5559                 return ERR_PTR(-EINVAL);
5560
5561         return ptr;
5562 }
5563
5564 #ifdef CONFIG_MMU
5565
5566 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5567 {
5568         size_t sz = vma->vm_end - vma->vm_start;
5569         unsigned long pfn;
5570         void *ptr;
5571
5572         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
5573         if (IS_ERR(ptr))
5574                 return PTR_ERR(ptr);
5575
5576         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
5577         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
5578 }
5579
5580 #else /* !CONFIG_MMU */
5581
5582 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5583 {
5584         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
5585 }
5586
5587 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
5588 {
5589         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
5590 }
5591
5592 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
5593         unsigned long addr, unsigned long len,
5594         unsigned long pgoff, unsigned long flags)
5595 {
5596         void *ptr;
5597
5598         ptr = io_uring_validate_mmap_request(file, pgoff, len);
5599         if (IS_ERR(ptr))
5600                 return PTR_ERR(ptr);
5601
5602         return (unsigned long) ptr;
5603 }
5604
5605 #endif /* !CONFIG_MMU */
5606
5607 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
5608 {
5609         if (flags & IORING_ENTER_EXT_ARG) {
5610                 struct io_uring_getevents_arg arg;
5611
5612                 if (argsz != sizeof(arg))
5613                         return -EINVAL;
5614                 if (copy_from_user(&arg, argp, sizeof(arg)))
5615                         return -EFAULT;
5616         }
5617         return 0;
5618 }
5619
5620 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
5621                           struct __kernel_timespec __user **ts,
5622                           const sigset_t __user **sig)
5623 {
5624         struct io_uring_getevents_arg arg;
5625
5626         /*
5627          * If EXT_ARG isn't set, then we have no timespec and the argp pointer
5628          * is just a pointer to the sigset_t.
5629          */
5630         if (!(flags & IORING_ENTER_EXT_ARG)) {
5631                 *sig = (const sigset_t __user *) argp;
5632                 *ts = NULL;
5633                 return 0;
5634         }
5635
5636         /*
5637          * EXT_ARG is set - ensure we agree on the size of it and copy in our
5638          * timespec and sigset_t pointers if good.
5639          */
5640         if (*argsz != sizeof(arg))
5641                 return -EINVAL;
5642         if (copy_from_user(&arg, argp, sizeof(arg)))
5643                 return -EFAULT;
5644         if (arg.pad)
5645                 return -EINVAL;
5646         *sig = u64_to_user_ptr(arg.sigmask);
5647         *argsz = arg.sigmask_sz;
5648         *ts = u64_to_user_ptr(arg.ts);
5649         return 0;
5650 }
5651
5652 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
5653                 u32, min_complete, u32, flags, const void __user *, argp,
5654                 size_t, argsz)
5655 {
5656         struct io_ring_ctx *ctx;
5657         struct fd f;
5658         long ret;
5659
5660         io_run_task_work();
5661
5662         if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
5663                                IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
5664                                IORING_ENTER_REGISTERED_RING)))
5665                 return -EINVAL;
5666
5667         /*
5668          * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
5669          * need only dereference our task private array to find it.
5670          */
5671         if (flags & IORING_ENTER_REGISTERED_RING) {
5672                 struct io_uring_task *tctx = current->io_uring;
5673
5674                 if (!tctx || fd >= IO_RINGFD_REG_MAX)
5675                         return -EINVAL;
5676                 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
5677                 f.file = tctx->registered_rings[fd];
5678                 f.flags = 0;
5679         } else {
5680                 f = fdget(fd);
5681         }
5682
5683         if (unlikely(!f.file))
5684                 return -EBADF;
5685
5686         ret = -EOPNOTSUPP;
5687         if (unlikely(!io_is_uring_fops(f.file)))
5688                 goto out_fput;
5689
5690         ret = -ENXIO;
5691         ctx = f.file->private_data;
5692         if (unlikely(!percpu_ref_tryget(&ctx->refs)))
5693                 goto out_fput;
5694
5695         ret = -EBADFD;
5696         if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
5697                 goto out;
5698
5699         /*
5700          * For SQ polling, the thread will do all submissions and completions.
5701          * Just return the requested submit count, and wake the thread if
5702          * we were asked to.
5703          */
5704         ret = 0;
5705         if (ctx->flags & IORING_SETUP_SQPOLL) {
5706                 io_cqring_overflow_flush(ctx);
5707
5708                 if (unlikely(ctx->sq_data->thread == NULL)) {
5709                         ret = -EOWNERDEAD;
5710                         goto out;
5711                 }
5712                 if (flags & IORING_ENTER_SQ_WAKEUP)
5713                         wake_up(&ctx->sq_data->wait);
5714                 if (flags & IORING_ENTER_SQ_WAIT) {
5715                         ret = io_sqpoll_wait_sq(ctx);
5716                         if (ret)
5717                                 goto out;
5718                 }
5719                 ret = to_submit;
5720         } else if (to_submit) {
5721                 ret = io_uring_add_tctx_node(ctx);
5722                 if (unlikely(ret))
5723                         goto out;
5724
5725                 mutex_lock(&ctx->uring_lock);
5726                 ret = io_submit_sqes(ctx, to_submit);
5727                 if (ret != to_submit) {
5728                         mutex_unlock(&ctx->uring_lock);
5729                         goto out;
5730                 }
5731                 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
5732                         goto iopoll_locked;
5733                 mutex_unlock(&ctx->uring_lock);
5734         }
5735         if (flags & IORING_ENTER_GETEVENTS) {
5736                 int ret2;
5737                 if (ctx->syscall_iopoll) {
5738                         /*
5739                          * We disallow the app entering submit/complete with
5740                          * polling, but we still need to lock the ring to
5741                          * prevent racing with polled issue that got punted to
5742                          * a workqueue.
5743                          */
5744                         mutex_lock(&ctx->uring_lock);
5745 iopoll_locked:
5746                         ret2 = io_validate_ext_arg(flags, argp, argsz);
5747                         if (likely(!ret2)) {
5748                                 min_complete = min(min_complete,
5749                                                    ctx->cq_entries);
5750                                 ret2 = io_iopoll_check(ctx, min_complete);
5751                         }
5752                         mutex_unlock(&ctx->uring_lock);
5753                 } else {
5754                         const sigset_t __user *sig;
5755                         struct __kernel_timespec __user *ts;
5756
5757                         ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
5758                         if (likely(!ret2)) {
5759                                 min_complete = min(min_complete,
5760                                                    ctx->cq_entries);
5761                                 ret2 = io_cqring_wait(ctx, min_complete, sig,
5762                                                       argsz, ts);
5763                         }
5764                 }
5765
5766                 if (!ret) {
5767                         ret = ret2;
5768
5769                         /*
5770                          * EBADR indicates that one or more CQE were dropped.
5771                          * Once the user has been informed we can clear the bit
5772                          * as they are obviously ok with those drops.
5773                          */
5774                         if (unlikely(ret2 == -EBADR))
5775                                 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
5776                                           &ctx->check_cq);
5777                 }
5778         }
5779
5780 out:
5781         percpu_ref_put(&ctx->refs);
5782 out_fput:
5783         fdput(f);
5784         return ret;
5785 }
5786
5787 static const struct file_operations io_uring_fops = {
5788         .release        = io_uring_release,
5789         .mmap           = io_uring_mmap,
5790 #ifndef CONFIG_MMU
5791         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
5792         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
5793 #endif
5794         .poll           = io_uring_poll,
5795 #ifdef CONFIG_PROC_FS
5796         .show_fdinfo    = io_uring_show_fdinfo,
5797 #endif
5798 };
5799
5800 bool io_is_uring_fops(struct file *file)
5801 {
5802         return file->f_op == &io_uring_fops;
5803 }
5804
5805 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
5806                                          struct io_uring_params *p)
5807 {
5808         struct io_rings *rings;
5809         size_t size, sq_array_offset;
5810
5811         /* make sure these are sane, as we already accounted them */
5812         ctx->sq_entries = p->sq_entries;
5813         ctx->cq_entries = p->cq_entries;
5814
5815         size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
5816         if (size == SIZE_MAX)
5817                 return -EOVERFLOW;
5818
5819         rings = io_mem_alloc(size);
5820         if (!rings)
5821                 return -ENOMEM;
5822
5823         ctx->rings = rings;
5824         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
5825         rings->sq_ring_mask = p->sq_entries - 1;
5826         rings->cq_ring_mask = p->cq_entries - 1;
5827         rings->sq_ring_entries = p->sq_entries;
5828         rings->cq_ring_entries = p->cq_entries;
5829
5830         if (p->flags & IORING_SETUP_SQE128)
5831                 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
5832         else
5833                 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
5834         if (size == SIZE_MAX) {
5835                 io_mem_free(ctx->rings);
5836                 ctx->rings = NULL;
5837                 return -EOVERFLOW;
5838         }
5839
5840         ctx->sq_sqes = io_mem_alloc(size);
5841         if (!ctx->sq_sqes) {
5842                 io_mem_free(ctx->rings);
5843                 ctx->rings = NULL;
5844                 return -ENOMEM;
5845         }
5846
5847         return 0;
5848 }
5849
5850 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
5851 {
5852         int ret, fd;
5853
5854         fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
5855         if (fd < 0)
5856                 return fd;
5857
5858         ret = io_uring_add_tctx_node(ctx);
5859         if (ret) {
5860                 put_unused_fd(fd);
5861                 return ret;
5862         }
5863         fd_install(fd, file);
5864         return fd;
5865 }
5866
5867 /*
5868  * Allocate an anonymous fd, this is what constitutes the application
5869  * visible backing of an io_uring instance. The application mmaps this
5870  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
5871  * we have to tie this fd to a socket for file garbage collection purposes.
5872  */
5873 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
5874 {
5875         struct file *file;
5876 #if defined(CONFIG_UNIX)
5877         int ret;
5878
5879         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
5880                                 &ctx->ring_sock);
5881         if (ret)
5882                 return ERR_PTR(ret);
5883 #endif
5884
5885         file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
5886                                          O_RDWR | O_CLOEXEC, NULL);
5887 #if defined(CONFIG_UNIX)
5888         if (IS_ERR(file)) {
5889                 sock_release(ctx->ring_sock);
5890                 ctx->ring_sock = NULL;
5891         } else {
5892                 ctx->ring_sock->file = file;
5893         }
5894 #endif
5895         return file;
5896 }
5897
5898 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
5899                                   struct io_uring_params __user *params)
5900 {
5901         struct io_ring_ctx *ctx;
5902         struct file *file;
5903         int ret;
5904
5905         if (!entries)
5906                 return -EINVAL;
5907         if (entries > IORING_MAX_ENTRIES) {
5908                 if (!(p->flags & IORING_SETUP_CLAMP))
5909                         return -EINVAL;
5910                 entries = IORING_MAX_ENTRIES;
5911         }
5912
5913         /*
5914          * Use twice as many entries for the CQ ring. It's possible for the
5915          * application to drive a higher depth than the size of the SQ ring,
5916          * since the sqes are only used at submission time. This allows for
5917          * some flexibility in overcommitting a bit. If the application has
5918          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
5919          * of CQ ring entries manually.
5920          */
5921         p->sq_entries = roundup_pow_of_two(entries);
5922         if (p->flags & IORING_SETUP_CQSIZE) {
5923                 /*
5924                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
5925                  * to a power-of-two, if it isn't already. We do NOT impose
5926                  * any cq vs sq ring sizing.
5927                  */
5928                 if (!p->cq_entries)
5929                         return -EINVAL;
5930                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
5931                         if (!(p->flags & IORING_SETUP_CLAMP))
5932                                 return -EINVAL;
5933                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
5934                 }
5935                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
5936                 if (p->cq_entries < p->sq_entries)
5937                         return -EINVAL;
5938         } else {
5939                 p->cq_entries = 2 * p->sq_entries;
5940         }
5941
5942         ctx = io_ring_ctx_alloc(p);
5943         if (!ctx)
5944                 return -ENOMEM;
5945
5946         /*
5947          * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
5948          * space applications don't need to do io completion events
5949          * polling again, they can rely on io_sq_thread to do polling
5950          * work, which can reduce cpu usage and uring_lock contention.
5951          */
5952         if (ctx->flags & IORING_SETUP_IOPOLL &&
5953             !(ctx->flags & IORING_SETUP_SQPOLL))
5954                 ctx->syscall_iopoll = 1;
5955
5956         ctx->compat = in_compat_syscall();
5957         if (!capable(CAP_IPC_LOCK))
5958                 ctx->user = get_uid(current_user());
5959
5960         /*
5961          * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
5962          * COOP_TASKRUN is set, then IPIs are never needed by the app.
5963          */
5964         ret = -EINVAL;
5965         if (ctx->flags & IORING_SETUP_SQPOLL) {
5966                 /* IPI related flags don't make sense with SQPOLL */
5967                 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
5968                                   IORING_SETUP_TASKRUN_FLAG))
5969                         goto err;
5970                 ctx->notify_method = TWA_SIGNAL_NO_IPI;
5971         } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
5972                 ctx->notify_method = TWA_SIGNAL_NO_IPI;
5973         } else {
5974                 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
5975                         goto err;
5976                 ctx->notify_method = TWA_SIGNAL;
5977         }
5978
5979         /*
5980          * This is just grabbed for accounting purposes. When a process exits,
5981          * the mm is exited and dropped before the files, hence we need to hang
5982          * on to this mm purely for the purposes of being able to unaccount
5983          * memory (locked/pinned vm). It's not used for anything else.
5984          */
5985         mmgrab(current->mm);
5986         ctx->mm_account = current->mm;
5987
5988         ret = io_allocate_scq_urings(ctx, p);
5989         if (ret)
5990                 goto err;
5991
5992         ret = io_sq_offload_create(ctx, p);
5993         if (ret)
5994                 goto err;
5995         /* always set a rsrc node */
5996         ret = io_rsrc_node_switch_start(ctx);
5997         if (ret)
5998                 goto err;
5999         io_rsrc_node_switch(ctx, NULL);
6000
6001         memset(&p->sq_off, 0, sizeof(p->sq_off));
6002         p->sq_off.head = offsetof(struct io_rings, sq.head);
6003         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6004         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6005         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6006         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6007         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6008         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6009
6010         memset(&p->cq_off, 0, sizeof(p->cq_off));
6011         p->cq_off.head = offsetof(struct io_rings, cq.head);
6012         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6013         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6014         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6015         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6016         p->cq_off.cqes = offsetof(struct io_rings, cqes);
6017         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
6018
6019         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6020                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6021                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
6022                         IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
6023                         IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
6024                         IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
6025                         IORING_FEAT_LINKED_FILE;
6026
6027         if (copy_to_user(params, p, sizeof(*p))) {
6028                 ret = -EFAULT;
6029                 goto err;
6030         }
6031
6032         file = io_uring_get_file(ctx);
6033         if (IS_ERR(file)) {
6034                 ret = PTR_ERR(file);
6035                 goto err;
6036         }
6037
6038         /*
6039          * Install ring fd as the very last thing, so we don't risk someone
6040          * having closed it before we finish setup
6041          */
6042         ret = io_uring_install_fd(ctx, file);
6043         if (ret < 0) {
6044                 /* fput will clean it up */
6045                 fput(file);
6046                 return ret;
6047         }
6048
6049         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6050         return ret;
6051 err:
6052         io_ring_ctx_wait_and_kill(ctx);
6053         return ret;
6054 }
6055
6056 /*
6057  * Sets up an aio uring context, and returns the fd. Applications asks for a
6058  * ring size, we return the actual sq/cq ring sizes (among other things) in the
6059  * params structure passed in.
6060  */
6061 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6062 {
6063         struct io_uring_params p;
6064         int i;
6065
6066         if (copy_from_user(&p, params, sizeof(p)))
6067                 return -EFAULT;
6068         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6069                 if (p.resv[i])
6070                         return -EINVAL;
6071         }
6072
6073         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6074                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6075                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
6076                         IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
6077                         IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
6078                         IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
6079                 return -EINVAL;
6080
6081         return io_uring_create(entries, &p, params);
6082 }
6083
6084 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6085                 struct io_uring_params __user *, params)
6086 {
6087         return io_uring_setup(entries, params);
6088 }
6089
6090 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
6091                            unsigned nr_args)
6092 {
6093         struct io_uring_probe *p;
6094         size_t size;
6095         int i, ret;
6096
6097         size = struct_size(p, ops, nr_args);
6098         if (size == SIZE_MAX)
6099                 return -EOVERFLOW;
6100         p = kzalloc(size, GFP_KERNEL);
6101         if (!p)
6102                 return -ENOMEM;
6103
6104         ret = -EFAULT;
6105         if (copy_from_user(p, arg, size))
6106                 goto out;
6107         ret = -EINVAL;
6108         if (memchr_inv(p, 0, size))
6109                 goto out;
6110
6111         p->last_op = IORING_OP_LAST - 1;
6112         if (nr_args > IORING_OP_LAST)
6113                 nr_args = IORING_OP_LAST;
6114
6115         for (i = 0; i < nr_args; i++) {
6116                 p->ops[i].op = i;
6117                 if (!io_op_defs[i].not_supported)
6118                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
6119         }
6120         p->ops_len = i;
6121
6122         ret = 0;
6123         if (copy_to_user(arg, p, size))
6124                 ret = -EFAULT;
6125 out:
6126         kfree(p);
6127         return ret;
6128 }
6129
6130 static int io_register_personality(struct io_ring_ctx *ctx)
6131 {
6132         const struct cred *creds;
6133         u32 id;
6134         int ret;
6135
6136         creds = get_current_cred();
6137
6138         ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
6139                         XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
6140         if (ret < 0) {
6141                 put_cred(creds);
6142                 return ret;
6143         }
6144         return id;
6145 }
6146
6147 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
6148                                            void __user *arg, unsigned int nr_args)
6149 {
6150         struct io_uring_restriction *res;
6151         size_t size;
6152         int i, ret;
6153
6154         /* Restrictions allowed only if rings started disabled */
6155         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
6156                 return -EBADFD;
6157
6158         /* We allow only a single restrictions registration */
6159         if (ctx->restrictions.registered)
6160                 return -EBUSY;
6161
6162         if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
6163                 return -EINVAL;
6164
6165         size = array_size(nr_args, sizeof(*res));
6166         if (size == SIZE_MAX)
6167                 return -EOVERFLOW;
6168
6169         res = memdup_user(arg, size);
6170         if (IS_ERR(res))
6171                 return PTR_ERR(res);
6172
6173         ret = 0;
6174
6175         for (i = 0; i < nr_args; i++) {
6176                 switch (res[i].opcode) {
6177                 case IORING_RESTRICTION_REGISTER_OP:
6178                         if (res[i].register_op >= IORING_REGISTER_LAST) {
6179                                 ret = -EINVAL;
6180                                 goto out;
6181                         }
6182
6183                         __set_bit(res[i].register_op,
6184                                   ctx->restrictions.register_op);
6185                         break;
6186                 case IORING_RESTRICTION_SQE_OP:
6187                         if (res[i].sqe_op >= IORING_OP_LAST) {
6188                                 ret = -EINVAL;
6189                                 goto out;
6190                         }
6191
6192                         __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
6193                         break;
6194                 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
6195                         ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
6196                         break;
6197                 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
6198                         ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
6199                         break;
6200                 default:
6201                         ret = -EINVAL;
6202                         goto out;
6203                 }
6204         }
6205
6206 out:
6207         /* Reset all restrictions if an error happened */
6208         if (ret != 0)
6209                 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
6210         else
6211                 ctx->restrictions.registered = true;
6212
6213         kfree(res);
6214         return ret;
6215 }
6216
6217 static int io_register_enable_rings(struct io_ring_ctx *ctx)
6218 {
6219         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
6220                 return -EBADFD;
6221
6222         if (ctx->restrictions.registered)
6223                 ctx->restricted = 1;
6224
6225         ctx->flags &= ~IORING_SETUP_R_DISABLED;
6226         if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
6227                 wake_up(&ctx->sq_data->wait);
6228         return 0;
6229 }
6230
6231 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
6232                                      struct io_uring_rsrc_update2 *up,
6233                                      unsigned nr_args)
6234 {
6235         __u32 tmp;
6236         int err;
6237
6238         if (check_add_overflow(up->offset, nr_args, &tmp))
6239                 return -EOVERFLOW;
6240         err = io_rsrc_node_switch_start(ctx);
6241         if (err)
6242                 return err;
6243
6244         switch (type) {
6245         case IORING_RSRC_FILE:
6246                 return __io_sqe_files_update(ctx, up, nr_args);
6247         case IORING_RSRC_BUFFER:
6248                 return __io_sqe_buffers_update(ctx, up, nr_args);
6249         }
6250         return -EINVAL;
6251 }
6252
6253 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
6254                                     unsigned nr_args)
6255 {
6256         struct io_uring_rsrc_update2 up;
6257
6258         if (!nr_args)
6259                 return -EINVAL;
6260         memset(&up, 0, sizeof(up));
6261         if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
6262                 return -EFAULT;
6263         if (up.resv || up.resv2)
6264                 return -EINVAL;
6265         return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
6266 }
6267
6268 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
6269                                    unsigned size, unsigned type)
6270 {
6271         struct io_uring_rsrc_update2 up;
6272
6273         if (size != sizeof(up))
6274                 return -EINVAL;
6275         if (copy_from_user(&up, arg, sizeof(up)))
6276                 return -EFAULT;
6277         if (!up.nr || up.resv || up.resv2)
6278                 return -EINVAL;
6279         return __io_register_rsrc_update(ctx, type, &up, up.nr);
6280 }
6281
6282 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
6283                             unsigned int size, unsigned int type)
6284 {
6285         struct io_uring_rsrc_register rr;
6286
6287         /* keep it extendible */
6288         if (size != sizeof(rr))
6289                 return -EINVAL;
6290
6291         memset(&rr, 0, sizeof(rr));
6292         if (copy_from_user(&rr, arg, size))
6293                 return -EFAULT;
6294         if (!rr.nr || rr.resv2)
6295                 return -EINVAL;
6296         if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
6297                 return -EINVAL;
6298
6299         switch (type) {
6300         case IORING_RSRC_FILE:
6301                 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
6302                         break;
6303                 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
6304                                              rr.nr, u64_to_user_ptr(rr.tags));
6305         case IORING_RSRC_BUFFER:
6306                 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
6307                         break;
6308                 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
6309                                                rr.nr, u64_to_user_ptr(rr.tags));
6310         }
6311         return -EINVAL;
6312 }
6313
6314 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
6315                                        void __user *arg, unsigned len)
6316 {
6317         struct io_uring_task *tctx = current->io_uring;
6318         cpumask_var_t new_mask;
6319         int ret;
6320
6321         if (!tctx || !tctx->io_wq)
6322                 return -EINVAL;
6323
6324         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6325                 return -ENOMEM;
6326
6327         cpumask_clear(new_mask);
6328         if (len > cpumask_size())
6329                 len = cpumask_size();
6330
6331         if (in_compat_syscall()) {
6332                 ret = compat_get_bitmap(cpumask_bits(new_mask),
6333                                         (const compat_ulong_t __user *)arg,
6334                                         len * 8 /* CHAR_BIT */);
6335         } else {
6336                 ret = copy_from_user(new_mask, arg, len);
6337         }
6338
6339         if (ret) {
6340                 free_cpumask_var(new_mask);
6341                 return -EFAULT;
6342         }
6343
6344         ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
6345         free_cpumask_var(new_mask);
6346         return ret;
6347 }
6348
6349 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
6350 {
6351         struct io_uring_task *tctx = current->io_uring;
6352
6353         if (!tctx || !tctx->io_wq)
6354                 return -EINVAL;
6355
6356         return io_wq_cpu_affinity(tctx->io_wq, NULL);
6357 }
6358
6359 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
6360                                                void __user *arg)
6361         __must_hold(&ctx->uring_lock)
6362 {
6363         struct io_tctx_node *node;
6364         struct io_uring_task *tctx = NULL;
6365         struct io_sq_data *sqd = NULL;
6366         __u32 new_count[2];
6367         int i, ret;
6368
6369         if (copy_from_user(new_count, arg, sizeof(new_count)))
6370                 return -EFAULT;
6371         for (i = 0; i < ARRAY_SIZE(new_count); i++)
6372                 if (new_count[i] > INT_MAX)
6373                         return -EINVAL;
6374
6375         if (ctx->flags & IORING_SETUP_SQPOLL) {
6376                 sqd = ctx->sq_data;
6377                 if (sqd) {
6378                         /*
6379                          * Observe the correct sqd->lock -> ctx->uring_lock
6380                          * ordering. Fine to drop uring_lock here, we hold
6381                          * a ref to the ctx.
6382                          */
6383                         refcount_inc(&sqd->refs);
6384                         mutex_unlock(&ctx->uring_lock);
6385                         mutex_lock(&sqd->lock);
6386                         mutex_lock(&ctx->uring_lock);
6387                         if (sqd->thread)
6388                                 tctx = sqd->thread->io_uring;
6389                 }
6390         } else {
6391                 tctx = current->io_uring;
6392         }
6393
6394         BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
6395
6396         for (i = 0; i < ARRAY_SIZE(new_count); i++)
6397                 if (new_count[i])
6398                         ctx->iowq_limits[i] = new_count[i];
6399         ctx->iowq_limits_set = true;
6400
6401         if (tctx && tctx->io_wq) {
6402                 ret = io_wq_max_workers(tctx->io_wq, new_count);
6403                 if (ret)
6404                         goto err;
6405         } else {
6406                 memset(new_count, 0, sizeof(new_count));
6407         }
6408
6409         if (sqd) {
6410                 mutex_unlock(&sqd->lock);
6411                 io_put_sq_data(sqd);
6412         }
6413
6414         if (copy_to_user(arg, new_count, sizeof(new_count)))
6415                 return -EFAULT;
6416
6417         /* that's it for SQPOLL, only the SQPOLL task creates requests */
6418         if (sqd)
6419                 return 0;
6420
6421         /* now propagate the restriction to all registered users */
6422         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6423                 struct io_uring_task *tctx = node->task->io_uring;
6424
6425                 if (WARN_ON_ONCE(!tctx->io_wq))
6426                         continue;
6427
6428                 for (i = 0; i < ARRAY_SIZE(new_count); i++)
6429                         new_count[i] = ctx->iowq_limits[i];
6430                 /* ignore errors, it always returns zero anyway */
6431                 (void)io_wq_max_workers(tctx->io_wq, new_count);
6432         }
6433         return 0;
6434 err:
6435         if (sqd) {
6436                 mutex_unlock(&sqd->lock);
6437                 io_put_sq_data(sqd);
6438         }
6439         return ret;
6440 }
6441
6442 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
6443                                void __user *arg, unsigned nr_args)
6444         __releases(ctx->uring_lock)
6445         __acquires(ctx->uring_lock)
6446 {
6447         int ret;
6448
6449         /*
6450          * We're inside the ring mutex, if the ref is already dying, then
6451          * someone else killed the ctx or is already going through
6452          * io_uring_register().
6453          */
6454         if (percpu_ref_is_dying(&ctx->refs))
6455                 return -ENXIO;
6456
6457         if (ctx->restricted) {
6458                 if (opcode >= IORING_REGISTER_LAST)
6459                         return -EINVAL;
6460                 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
6461                 if (!test_bit(opcode, ctx->restrictions.register_op))
6462                         return -EACCES;
6463         }
6464
6465         switch (opcode) {
6466         case IORING_REGISTER_BUFFERS:
6467                 ret = -EFAULT;
6468                 if (!arg)
6469                         break;
6470                 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
6471                 break;
6472         case IORING_UNREGISTER_BUFFERS:
6473                 ret = -EINVAL;
6474                 if (arg || nr_args)
6475                         break;
6476                 ret = io_sqe_buffers_unregister(ctx);
6477                 break;
6478         case IORING_REGISTER_FILES:
6479                 ret = -EFAULT;
6480                 if (!arg)
6481                         break;
6482                 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
6483                 break;
6484         case IORING_UNREGISTER_FILES:
6485                 ret = -EINVAL;
6486                 if (arg || nr_args)
6487                         break;
6488                 ret = io_sqe_files_unregister(ctx);
6489                 break;
6490         case IORING_REGISTER_FILES_UPDATE:
6491                 ret = io_register_files_update(ctx, arg, nr_args);
6492                 break;
6493         case IORING_REGISTER_EVENTFD:
6494                 ret = -EINVAL;
6495                 if (nr_args != 1)
6496                         break;
6497                 ret = io_eventfd_register(ctx, arg, 0);
6498                 break;
6499         case IORING_REGISTER_EVENTFD_ASYNC:
6500                 ret = -EINVAL;
6501                 if (nr_args != 1)
6502                         break;
6503                 ret = io_eventfd_register(ctx, arg, 1);
6504                 break;
6505         case IORING_UNREGISTER_EVENTFD:
6506                 ret = -EINVAL;
6507                 if (arg || nr_args)
6508                         break;
6509                 ret = io_eventfd_unregister(ctx);
6510                 break;
6511         case IORING_REGISTER_PROBE:
6512                 ret = -EINVAL;
6513                 if (!arg || nr_args > 256)
6514                         break;
6515                 ret = io_probe(ctx, arg, nr_args);
6516                 break;
6517         case IORING_REGISTER_PERSONALITY:
6518                 ret = -EINVAL;
6519                 if (arg || nr_args)
6520                         break;
6521                 ret = io_register_personality(ctx);
6522                 break;
6523         case IORING_UNREGISTER_PERSONALITY:
6524                 ret = -EINVAL;
6525                 if (arg)
6526                         break;
6527                 ret = io_unregister_personality(ctx, nr_args);
6528                 break;
6529         case IORING_REGISTER_ENABLE_RINGS:
6530                 ret = -EINVAL;
6531                 if (arg || nr_args)
6532                         break;
6533                 ret = io_register_enable_rings(ctx);
6534                 break;
6535         case IORING_REGISTER_RESTRICTIONS:
6536                 ret = io_register_restrictions(ctx, arg, nr_args);
6537                 break;
6538         case IORING_REGISTER_FILES2:
6539                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
6540                 break;
6541         case IORING_REGISTER_FILES_UPDATE2:
6542                 ret = io_register_rsrc_update(ctx, arg, nr_args,
6543                                               IORING_RSRC_FILE);
6544                 break;
6545         case IORING_REGISTER_BUFFERS2:
6546                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
6547                 break;
6548         case IORING_REGISTER_BUFFERS_UPDATE:
6549                 ret = io_register_rsrc_update(ctx, arg, nr_args,
6550                                               IORING_RSRC_BUFFER);
6551                 break;
6552         case IORING_REGISTER_IOWQ_AFF:
6553                 ret = -EINVAL;
6554                 if (!arg || !nr_args)
6555                         break;
6556                 ret = io_register_iowq_aff(ctx, arg, nr_args);
6557                 break;
6558         case IORING_UNREGISTER_IOWQ_AFF:
6559                 ret = -EINVAL;
6560                 if (arg || nr_args)
6561                         break;
6562                 ret = io_unregister_iowq_aff(ctx);
6563                 break;
6564         case IORING_REGISTER_IOWQ_MAX_WORKERS:
6565                 ret = -EINVAL;
6566                 if (!arg || nr_args != 2)
6567                         break;
6568                 ret = io_register_iowq_max_workers(ctx, arg);
6569                 break;
6570         case IORING_REGISTER_RING_FDS:
6571                 ret = io_ringfd_register(ctx, arg, nr_args);
6572                 break;
6573         case IORING_UNREGISTER_RING_FDS:
6574                 ret = io_ringfd_unregister(ctx, arg, nr_args);
6575                 break;
6576         case IORING_REGISTER_PBUF_RING:
6577                 ret = -EINVAL;
6578                 if (!arg || nr_args != 1)
6579                         break;
6580                 ret = io_register_pbuf_ring(ctx, arg);
6581                 break;
6582         case IORING_UNREGISTER_PBUF_RING:
6583                 ret = -EINVAL;
6584                 if (!arg || nr_args != 1)
6585                         break;
6586                 ret = io_unregister_pbuf_ring(ctx, arg);
6587                 break;
6588         default:
6589                 ret = -EINVAL;
6590                 break;
6591         }
6592
6593         return ret;
6594 }
6595
6596 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
6597                 void __user *, arg, unsigned int, nr_args)
6598 {
6599         struct io_ring_ctx *ctx;
6600         long ret = -EBADF;
6601         struct fd f;
6602
6603         f = fdget(fd);
6604         if (!f.file)
6605                 return -EBADF;
6606
6607         ret = -EOPNOTSUPP;
6608         if (!io_is_uring_fops(f.file))
6609                 goto out_fput;
6610
6611         ctx = f.file->private_data;
6612
6613         io_run_task_work();
6614
6615         mutex_lock(&ctx->uring_lock);
6616         ret = __io_uring_register(ctx, opcode, arg, nr_args);
6617         mutex_unlock(&ctx->uring_lock);
6618         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
6619 out_fput:
6620         fdput(f);
6621         return ret;
6622 }
6623
6624 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
6625 {
6626         WARN_ON_ONCE(1);
6627         return -ECANCELED;
6628 }
6629
6630 const struct io_op_def io_op_defs[] = {
6631         [IORING_OP_NOP] = {
6632                 .audit_skip             = 1,
6633                 .iopoll                 = 1,
6634                 .name                   = "NOP",
6635                 .prep                   = io_nop_prep,
6636                 .issue                  = io_nop,
6637         },
6638         [IORING_OP_READV] = {
6639                 .needs_file             = 1,
6640                 .unbound_nonreg_file    = 1,
6641                 .pollin                 = 1,
6642                 .buffer_select          = 1,
6643                 .plug                   = 1,
6644                 .audit_skip             = 1,
6645                 .ioprio                 = 1,
6646                 .iopoll                 = 1,
6647                 .async_size             = sizeof(struct io_async_rw),
6648                 .name                   = "READV",
6649                 .prep                   = io_prep_rw,
6650                 .issue                  = io_read,
6651                 .prep_async             = io_readv_prep_async,
6652                 .cleanup                = io_readv_writev_cleanup,
6653         },
6654         [IORING_OP_WRITEV] = {
6655                 .needs_file             = 1,
6656                 .hash_reg_file          = 1,
6657                 .unbound_nonreg_file    = 1,
6658                 .pollout                = 1,
6659                 .plug                   = 1,
6660                 .audit_skip             = 1,
6661                 .ioprio                 = 1,
6662                 .iopoll                 = 1,
6663                 .async_size             = sizeof(struct io_async_rw),
6664                 .name                   = "WRITEV",
6665                 .prep                   = io_prep_rw,
6666                 .issue                  = io_write,
6667                 .prep_async             = io_writev_prep_async,
6668                 .cleanup                = io_readv_writev_cleanup,
6669         },
6670         [IORING_OP_FSYNC] = {
6671                 .needs_file             = 1,
6672                 .audit_skip             = 1,
6673                 .name                   = "FSYNC",
6674                 .prep                   = io_fsync_prep,
6675                 .issue                  = io_fsync,
6676         },
6677         [IORING_OP_READ_FIXED] = {
6678                 .needs_file             = 1,
6679                 .unbound_nonreg_file    = 1,
6680                 .pollin                 = 1,
6681                 .plug                   = 1,
6682                 .audit_skip             = 1,
6683                 .ioprio                 = 1,
6684                 .iopoll                 = 1,
6685                 .async_size             = sizeof(struct io_async_rw),
6686                 .name                   = "READ_FIXED",
6687                 .prep                   = io_prep_rw,
6688                 .issue                  = io_read,
6689         },
6690         [IORING_OP_WRITE_FIXED] = {
6691                 .needs_file             = 1,
6692                 .hash_reg_file          = 1,
6693                 .unbound_nonreg_file    = 1,
6694                 .pollout                = 1,
6695                 .plug                   = 1,
6696                 .audit_skip             = 1,
6697                 .ioprio                 = 1,
6698                 .iopoll                 = 1,
6699                 .async_size             = sizeof(struct io_async_rw),
6700                 .name                   = "WRITE_FIXED",
6701                 .prep                   = io_prep_rw,
6702                 .issue                  = io_write,
6703         },
6704         [IORING_OP_POLL_ADD] = {
6705                 .needs_file             = 1,
6706                 .unbound_nonreg_file    = 1,
6707                 .audit_skip             = 1,
6708                 .name                   = "POLL_ADD",
6709                 .prep                   = io_poll_add_prep,
6710                 .issue                  = io_poll_add,
6711         },
6712         [IORING_OP_POLL_REMOVE] = {
6713                 .audit_skip             = 1,
6714                 .name                   = "POLL_REMOVE",
6715                 .prep                   = io_poll_remove_prep,
6716                 .issue                  = io_poll_remove,
6717         },
6718         [IORING_OP_SYNC_FILE_RANGE] = {
6719                 .needs_file             = 1,
6720                 .audit_skip             = 1,
6721                 .name                   = "SYNC_FILE_RANGE",
6722                 .prep                   = io_sfr_prep,
6723                 .issue                  = io_sync_file_range,
6724         },
6725         [IORING_OP_SENDMSG] = {
6726                 .needs_file             = 1,
6727                 .unbound_nonreg_file    = 1,
6728                 .pollout                = 1,
6729                 .ioprio                 = 1,
6730                 .name                   = "SENDMSG",
6731 #if defined(CONFIG_NET)
6732                 .async_size             = sizeof(struct io_async_msghdr),
6733                 .prep                   = io_sendmsg_prep,
6734                 .issue                  = io_sendmsg,
6735                 .prep_async             = io_sendmsg_prep_async,
6736                 .cleanup                = io_sendmsg_recvmsg_cleanup,
6737 #else
6738                 .prep                   = io_eopnotsupp_prep,
6739 #endif
6740         },
6741         [IORING_OP_RECVMSG] = {
6742                 .needs_file             = 1,
6743                 .unbound_nonreg_file    = 1,
6744                 .pollin                 = 1,
6745                 .buffer_select          = 1,
6746                 .ioprio                 = 1,
6747                 .name                   = "RECVMSG",
6748 #if defined(CONFIG_NET)
6749                 .async_size             = sizeof(struct io_async_msghdr),
6750                 .prep                   = io_recvmsg_prep,
6751                 .issue                  = io_recvmsg,
6752                 .prep_async             = io_recvmsg_prep_async,
6753                 .cleanup                = io_sendmsg_recvmsg_cleanup,
6754 #else
6755                 .prep                   = io_eopnotsupp_prep,
6756 #endif
6757         },
6758         [IORING_OP_TIMEOUT] = {
6759                 .audit_skip             = 1,
6760                 .async_size             = sizeof(struct io_timeout_data),
6761                 .name                   = "TIMEOUT",
6762                 .prep                   = io_timeout_prep,
6763                 .issue                  = io_timeout,
6764         },
6765         [IORING_OP_TIMEOUT_REMOVE] = {
6766                 /* used by timeout updates' prep() */
6767                 .audit_skip             = 1,
6768                 .name                   = "TIMEOUT_REMOVE",
6769                 .prep                   = io_timeout_remove_prep,
6770                 .issue                  = io_timeout_remove,
6771         },
6772         [IORING_OP_ACCEPT] = {
6773                 .needs_file             = 1,
6774                 .unbound_nonreg_file    = 1,
6775                 .pollin                 = 1,
6776                 .poll_exclusive         = 1,
6777                 .ioprio                 = 1,    /* used for flags */
6778                 .name                   = "ACCEPT",
6779 #if defined(CONFIG_NET)
6780                 .prep                   = io_accept_prep,
6781                 .issue                  = io_accept,
6782 #else
6783                 .prep                   = io_eopnotsupp_prep,
6784 #endif
6785         },
6786         [IORING_OP_ASYNC_CANCEL] = {
6787                 .audit_skip             = 1,
6788                 .name                   = "ASYNC_CANCEL",
6789                 .prep                   = io_async_cancel_prep,
6790                 .issue                  = io_async_cancel,
6791         },
6792         [IORING_OP_LINK_TIMEOUT] = {
6793                 .audit_skip             = 1,
6794                 .async_size             = sizeof(struct io_timeout_data),
6795                 .name                   = "LINK_TIMEOUT",
6796                 .prep                   = io_link_timeout_prep,
6797                 .issue                  = io_no_issue,
6798         },
6799         [IORING_OP_CONNECT] = {
6800                 .needs_file             = 1,
6801                 .unbound_nonreg_file    = 1,
6802                 .pollout                = 1,
6803                 .name                   = "CONNECT",
6804 #if defined(CONFIG_NET)
6805                 .async_size             = sizeof(struct io_async_connect),
6806                 .prep                   = io_connect_prep,
6807                 .issue                  = io_connect,
6808                 .prep_async             = io_connect_prep_async,
6809 #else
6810                 .prep                   = io_eopnotsupp_prep,
6811 #endif
6812         },
6813         [IORING_OP_FALLOCATE] = {
6814                 .needs_file             = 1,
6815                 .name                   = "FALLOCATE",
6816                 .prep                   = io_fallocate_prep,
6817                 .issue                  = io_fallocate,
6818         },
6819         [IORING_OP_OPENAT] = {
6820                 .name                   = "OPENAT",
6821                 .prep                   = io_openat_prep,
6822                 .issue                  = io_openat,
6823                 .cleanup                = io_open_cleanup,
6824         },
6825         [IORING_OP_CLOSE] = {
6826                 .name                   = "CLOSE",
6827                 .prep                   = io_close_prep,
6828                 .issue                  = io_close,
6829         },
6830         [IORING_OP_FILES_UPDATE] = {
6831                 .audit_skip             = 1,
6832                 .iopoll                 = 1,
6833                 .name                   = "FILES_UPDATE",
6834                 .prep                   = io_files_update_prep,
6835                 .issue                  = io_files_update,
6836         },
6837         [IORING_OP_STATX] = {
6838                 .audit_skip             = 1,
6839                 .name                   = "STATX",
6840                 .prep                   = io_statx_prep,
6841                 .issue                  = io_statx,
6842                 .cleanup                = io_statx_cleanup,
6843         },
6844         [IORING_OP_READ] = {
6845                 .needs_file             = 1,
6846                 .unbound_nonreg_file    = 1,
6847                 .pollin                 = 1,
6848                 .buffer_select          = 1,
6849                 .plug                   = 1,
6850                 .audit_skip             = 1,
6851                 .ioprio                 = 1,
6852                 .iopoll                 = 1,
6853                 .async_size             = sizeof(struct io_async_rw),
6854                 .name                   = "READ",
6855                 .prep                   = io_prep_rw,
6856                 .issue                  = io_read,
6857         },
6858         [IORING_OP_WRITE] = {
6859                 .needs_file             = 1,
6860                 .hash_reg_file          = 1,
6861                 .unbound_nonreg_file    = 1,
6862                 .pollout                = 1,
6863                 .plug                   = 1,
6864                 .audit_skip             = 1,
6865                 .ioprio                 = 1,
6866                 .iopoll                 = 1,
6867                 .async_size             = sizeof(struct io_async_rw),
6868                 .name                   = "WRITE",
6869                 .prep                   = io_prep_rw,
6870                 .issue                  = io_write,
6871         },
6872         [IORING_OP_FADVISE] = {
6873                 .needs_file             = 1,
6874                 .audit_skip             = 1,
6875                 .name                   = "FADVISE",
6876                 .prep                   = io_fadvise_prep,
6877                 .issue                  = io_fadvise,
6878         },
6879         [IORING_OP_MADVISE] = {
6880                 .name                   = "MADVISE",
6881                 .prep                   = io_madvise_prep,
6882                 .issue                  = io_madvise,
6883         },
6884         [IORING_OP_SEND] = {
6885                 .needs_file             = 1,
6886                 .unbound_nonreg_file    = 1,
6887                 .pollout                = 1,
6888                 .audit_skip             = 1,
6889                 .ioprio                 = 1,
6890                 .name                   = "SEND",
6891 #if defined(CONFIG_NET)
6892                 .prep                   = io_sendmsg_prep,
6893                 .issue                  = io_send,
6894 #else
6895                 .prep                   = io_eopnotsupp_prep,
6896 #endif
6897         },
6898         [IORING_OP_RECV] = {
6899                 .needs_file             = 1,
6900                 .unbound_nonreg_file    = 1,
6901                 .pollin                 = 1,
6902                 .buffer_select          = 1,
6903                 .audit_skip             = 1,
6904                 .ioprio                 = 1,
6905                 .name                   = "RECV",
6906 #if defined(CONFIG_NET)
6907                 .prep                   = io_recvmsg_prep,
6908                 .issue                  = io_recv,
6909 #else
6910                 .prep                   = io_eopnotsupp_prep,
6911 #endif
6912         },
6913         [IORING_OP_OPENAT2] = {
6914                 .name                   = "OPENAT2",
6915                 .prep                   = io_openat2_prep,
6916                 .issue                  = io_openat2,
6917                 .cleanup                = io_open_cleanup,
6918         },
6919         [IORING_OP_EPOLL_CTL] = {
6920                 .unbound_nonreg_file    = 1,
6921                 .audit_skip             = 1,
6922                 .name                   = "EPOLL",
6923 #if defined(CONFIG_EPOLL)
6924                 .prep                   = io_epoll_ctl_prep,
6925                 .issue                  = io_epoll_ctl,
6926 #else
6927                 .prep                   = io_eopnotsupp_prep,
6928 #endif
6929         },
6930         [IORING_OP_SPLICE] = {
6931                 .needs_file             = 1,
6932                 .hash_reg_file          = 1,
6933                 .unbound_nonreg_file    = 1,
6934                 .audit_skip             = 1,
6935                 .name                   = "SPLICE",
6936                 .prep                   = io_splice_prep,
6937                 .issue                  = io_splice,
6938         },
6939         [IORING_OP_PROVIDE_BUFFERS] = {
6940                 .audit_skip             = 1,
6941                 .iopoll                 = 1,
6942                 .name                   = "PROVIDE_BUFFERS",
6943                 .prep                   = io_provide_buffers_prep,
6944                 .issue                  = io_provide_buffers,
6945         },
6946         [IORING_OP_REMOVE_BUFFERS] = {
6947                 .audit_skip             = 1,
6948                 .iopoll                 = 1,
6949                 .name                   = "REMOVE_BUFFERS",
6950                 .prep                   = io_remove_buffers_prep,
6951                 .issue                  = io_remove_buffers,
6952         },
6953         [IORING_OP_TEE] = {
6954                 .needs_file             = 1,
6955                 .hash_reg_file          = 1,
6956                 .unbound_nonreg_file    = 1,
6957                 .audit_skip             = 1,
6958                 .name                   = "TEE",
6959                 .prep                   = io_tee_prep,
6960                 .issue                  = io_tee,
6961         },
6962         [IORING_OP_SHUTDOWN] = {
6963                 .needs_file             = 1,
6964                 .name                   = "SHUTDOWN",
6965 #if defined(CONFIG_NET)
6966                 .prep                   = io_shutdown_prep,
6967                 .issue                  = io_shutdown,
6968 #else
6969                 .prep                   = io_eopnotsupp_prep,
6970 #endif
6971         },
6972         [IORING_OP_RENAMEAT] = {
6973                 .name                   = "RENAMEAT",
6974                 .prep                   = io_renameat_prep,
6975                 .issue                  = io_renameat,
6976                 .cleanup                = io_renameat_cleanup,
6977         },
6978         [IORING_OP_UNLINKAT] = {
6979                 .name                   = "UNLINKAT",
6980                 .prep                   = io_unlinkat_prep,
6981                 .issue                  = io_unlinkat,
6982                 .cleanup                = io_unlinkat_cleanup,
6983         },
6984         [IORING_OP_MKDIRAT] = {
6985                 .name                   = "MKDIRAT",
6986                 .prep                   = io_mkdirat_prep,
6987                 .issue                  = io_mkdirat,
6988                 .cleanup                = io_mkdirat_cleanup,
6989         },
6990         [IORING_OP_SYMLINKAT] = {
6991                 .name                   = "SYMLINKAT",
6992                 .prep                   = io_symlinkat_prep,
6993                 .issue                  = io_symlinkat,
6994                 .cleanup                = io_link_cleanup,
6995         },
6996         [IORING_OP_LINKAT] = {
6997                 .name                   = "LINKAT",
6998                 .prep                   = io_linkat_prep,
6999                 .issue                  = io_linkat,
7000                 .cleanup                = io_link_cleanup,
7001         },
7002         [IORING_OP_MSG_RING] = {
7003                 .needs_file             = 1,
7004                 .iopoll                 = 1,
7005                 .name                   = "MSG_RING",
7006                 .prep                   = io_msg_ring_prep,
7007                 .issue                  = io_msg_ring,
7008         },
7009         [IORING_OP_FSETXATTR] = {
7010                 .needs_file = 1,
7011                 .name                   = "FSETXATTR",
7012                 .prep                   = io_fsetxattr_prep,
7013                 .issue                  = io_fsetxattr,
7014                 .cleanup                = io_xattr_cleanup,
7015         },
7016         [IORING_OP_SETXATTR] = {
7017                 .name                   = "SETXATTR",
7018                 .prep                   = io_setxattr_prep,
7019                 .issue                  = io_setxattr,
7020                 .cleanup                = io_xattr_cleanup,
7021         },
7022         [IORING_OP_FGETXATTR] = {
7023                 .needs_file = 1,
7024                 .name                   = "FGETXATTR",
7025                 .prep                   = io_fgetxattr_prep,
7026                 .issue                  = io_fgetxattr,
7027                 .cleanup                = io_xattr_cleanup,
7028         },
7029         [IORING_OP_GETXATTR] = {
7030                 .name                   = "GETXATTR",
7031                 .prep                   = io_getxattr_prep,
7032                 .issue                  = io_getxattr,
7033                 .cleanup                = io_xattr_cleanup,
7034         },
7035         [IORING_OP_SOCKET] = {
7036                 .audit_skip             = 1,
7037                 .name                   = "SOCKET",
7038 #if defined(CONFIG_NET)
7039                 .prep                   = io_socket_prep,
7040                 .issue                  = io_socket,
7041 #else
7042                 .prep                   = io_eopnotsupp_prep,
7043 #endif
7044         },
7045         [IORING_OP_URING_CMD] = {
7046                 .needs_file             = 1,
7047                 .plug                   = 1,
7048                 .name                   = "URING_CMD",
7049                 .async_size             = uring_cmd_pdu_size(1),
7050                 .prep                   = io_uring_cmd_prep,
7051                 .issue                  = io_uring_cmd,
7052                 .prep_async             = io_uring_cmd_prep_async,
7053         },
7054 };
7055
7056 static int __init io_uring_init(void)
7057 {
7058         int i;
7059
7060 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7061         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7062         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7063 } while (0)
7064
7065 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7066         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7067         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7068         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
7069         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
7070         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
7071         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
7072         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
7073         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
7074         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
7075         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
7076         BUILD_BUG_SQE_ELEM(24, __u32,  len);
7077         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
7078         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
7079         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7080         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
7081         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
7082         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
7083         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
7084         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
7085         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
7086         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
7087         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
7088         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
7089         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
7090         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
7091         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
7092         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
7093         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
7094         BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
7095         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
7096         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
7097         BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
7098         BUILD_BUG_SQE_ELEM(48, __u64,  addr3);
7099
7100         BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
7101                      sizeof(struct io_uring_rsrc_update));
7102         BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
7103                      sizeof(struct io_uring_rsrc_update2));
7104
7105         /* ->buf_index is u16 */
7106         BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
7107         BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
7108         BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
7109                      offsetof(struct io_uring_buf_ring, tail));
7110
7111         /* should fit into one byte */
7112         BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
7113         BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
7114         BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
7115
7116         BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
7117         BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
7118
7119         BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
7120
7121         for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
7122                 BUG_ON(!io_op_defs[i].prep);
7123                 if (io_op_defs[i].prep != io_eopnotsupp_prep)
7124                         BUG_ON(!io_op_defs[i].issue);
7125                 WARN_ON_ONCE(!io_op_defs[i].name);
7126         }
7127
7128         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
7129                                 SLAB_ACCOUNT);
7130         return 0;
7131 };
7132 __initcall(io_uring_init);