16a625e854ec33e1904727ae4728df1f09cf053c
[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 <net/compat.h>
47 #include <linux/refcount.h>
48 #include <linux/uio.h>
49 #include <linux/bits.h>
50
51 #include <linux/sched/signal.h>
52 #include <linux/fs.h>
53 #include <linux/file.h>
54 #include <linux/fdtable.h>
55 #include <linux/mm.h>
56 #include <linux/mman.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/bvec.h>
60 #include <linux/net.h>
61 #include <net/sock.h>
62 #include <net/af_unix.h>
63 #include <net/scm.h>
64 #include <linux/anon_inodes.h>
65 #include <linux/sched/mm.h>
66 #include <linux/uaccess.h>
67 #include <linux/nospec.h>
68 #include <linux/highmem.h>
69 #include <linux/fsnotify.h>
70 #include <linux/fadvise.h>
71 #include <linux/task_work.h>
72 #include <linux/io_uring.h>
73 #include <linux/audit.h>
74 #include <linux/security.h>
75
76 #define CREATE_TRACE_POINTS
77 #include <trace/events/io_uring.h>
78
79 #include <uapi/linux/io_uring.h>
80
81 #include "io-wq.h"
82
83 #include "io_uring.h"
84 #include "opdef.h"
85 #include "refs.h"
86 #include "tctx.h"
87 #include "sqpoll.h"
88 #include "fdinfo.h"
89 #include "kbuf.h"
90 #include "rsrc.h"
91 #include "cancel.h"
92
93 #include "timeout.h"
94 #include "poll.h"
95
96 #define IORING_MAX_ENTRIES      32768
97 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
98
99 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
100                                  IORING_REGISTER_LAST + IORING_OP_LAST)
101
102 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
103                           IOSQE_IO_HARDLINK | IOSQE_ASYNC)
104
105 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
106                         IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
107
108 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
109                                 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
110                                 REQ_F_ASYNC_DATA)
111
112 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
113                                  IO_REQ_CLEAN_FLAGS)
114
115 #define IO_TCTX_REFS_CACHE_NR   (1U << 10)
116
117 #define IO_COMPL_BATCH                  32
118 #define IO_REQ_ALLOC_BATCH              8
119
120 enum {
121         IO_CHECK_CQ_OVERFLOW_BIT,
122         IO_CHECK_CQ_DROPPED_BIT,
123 };
124
125 struct io_defer_entry {
126         struct list_head        list;
127         struct io_kiocb         *req;
128         u32                     seq;
129 };
130
131 /* requests with any of those set should undergo io_disarm_next() */
132 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
133 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
134
135 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
136                                          struct task_struct *task,
137                                          bool cancel_all);
138
139 static void io_dismantle_req(struct io_kiocb *req);
140 static void io_clean_op(struct io_kiocb *req);
141 static void io_queue_sqe(struct io_kiocb *req);
142
143 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
144
145 static struct kmem_cache *req_cachep;
146
147 struct sock *io_uring_get_socket(struct file *file)
148 {
149 #if defined(CONFIG_UNIX)
150         if (io_is_uring_fops(file)) {
151                 struct io_ring_ctx *ctx = file->private_data;
152
153                 return ctx->ring_sock->sk;
154         }
155 #endif
156         return NULL;
157 }
158 EXPORT_SYMBOL(io_uring_get_socket);
159
160 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
161 {
162         if (!wq_list_empty(&ctx->submit_state.compl_reqs))
163                 __io_submit_flush_completions(ctx);
164 }
165
166 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
167 {
168         return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
169 }
170
171 static bool io_match_linked(struct io_kiocb *head)
172 {
173         struct io_kiocb *req;
174
175         io_for_each_link(req, head) {
176                 if (req->flags & REQ_F_INFLIGHT)
177                         return true;
178         }
179         return false;
180 }
181
182 /*
183  * As io_match_task() but protected against racing with linked timeouts.
184  * User must not hold timeout_lock.
185  */
186 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
187                         bool cancel_all)
188 {
189         bool matched;
190
191         if (task && head->task != task)
192                 return false;
193         if (cancel_all)
194                 return true;
195
196         if (head->flags & REQ_F_LINK_TIMEOUT) {
197                 struct io_ring_ctx *ctx = head->ctx;
198
199                 /* protect against races with linked timeouts */
200                 spin_lock_irq(&ctx->timeout_lock);
201                 matched = io_match_linked(head);
202                 spin_unlock_irq(&ctx->timeout_lock);
203         } else {
204                 matched = io_match_linked(head);
205         }
206         return matched;
207 }
208
209 static inline void req_fail_link_node(struct io_kiocb *req, int res)
210 {
211         req_set_fail(req);
212         io_req_set_res(req, res, 0);
213 }
214
215 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
216 {
217         wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
218 }
219
220 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
221 {
222         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
223
224         complete(&ctx->ref_comp);
225 }
226
227 static __cold void io_fallback_req_func(struct work_struct *work)
228 {
229         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
230                                                 fallback_work.work);
231         struct llist_node *node = llist_del_all(&ctx->fallback_llist);
232         struct io_kiocb *req, *tmp;
233         bool locked = false;
234
235         percpu_ref_get(&ctx->refs);
236         llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
237                 req->io_task_work.func(req, &locked);
238
239         if (locked) {
240                 io_submit_flush_completions(ctx);
241                 mutex_unlock(&ctx->uring_lock);
242         }
243         percpu_ref_put(&ctx->refs);
244 }
245
246 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
247 {
248         unsigned hash_buckets = 1U << bits;
249         size_t hash_size = hash_buckets * sizeof(table->hbs[0]);
250
251         table->hbs = kmalloc(hash_size, GFP_KERNEL);
252         if (!table->hbs)
253                 return -ENOMEM;
254
255         table->hash_bits = bits;
256         init_hash_table(table, hash_buckets);
257         return 0;
258 }
259
260 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
261 {
262         struct io_ring_ctx *ctx;
263         int hash_bits;
264
265         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
266         if (!ctx)
267                 return NULL;
268
269         xa_init(&ctx->io_bl_xa);
270
271         /*
272          * Use 5 bits less than the max cq entries, that should give us around
273          * 32 entries per hash list if totally full and uniformly spread, but
274          * don't keep too many buckets to not overconsume memory.
275          */
276         hash_bits = ilog2(p->cq_entries) - 5;
277         hash_bits = clamp(hash_bits, 1, 8);
278         if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
279                 goto err;
280         if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits))
281                 goto err;
282
283         ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
284         if (!ctx->dummy_ubuf)
285                 goto err;
286         /* set invalid range, so io_import_fixed() fails meeting it */
287         ctx->dummy_ubuf->ubuf = -1UL;
288
289         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
290                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
291                 goto err;
292
293         ctx->flags = p->flags;
294         init_waitqueue_head(&ctx->sqo_sq_wait);
295         INIT_LIST_HEAD(&ctx->sqd_list);
296         INIT_LIST_HEAD(&ctx->cq_overflow_list);
297         INIT_LIST_HEAD(&ctx->io_buffers_cache);
298         INIT_LIST_HEAD(&ctx->apoll_cache);
299         init_completion(&ctx->ref_comp);
300         xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
301         mutex_init(&ctx->uring_lock);
302         init_waitqueue_head(&ctx->cq_wait);
303         spin_lock_init(&ctx->completion_lock);
304         spin_lock_init(&ctx->timeout_lock);
305         INIT_WQ_LIST(&ctx->iopoll_list);
306         INIT_LIST_HEAD(&ctx->io_buffers_pages);
307         INIT_LIST_HEAD(&ctx->io_buffers_comp);
308         INIT_LIST_HEAD(&ctx->defer_list);
309         INIT_LIST_HEAD(&ctx->timeout_list);
310         INIT_LIST_HEAD(&ctx->ltimeout_list);
311         spin_lock_init(&ctx->rsrc_ref_lock);
312         INIT_LIST_HEAD(&ctx->rsrc_ref_list);
313         INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
314         init_llist_head(&ctx->rsrc_put_llist);
315         INIT_LIST_HEAD(&ctx->tctx_list);
316         ctx->submit_state.free_list.next = NULL;
317         INIT_WQ_LIST(&ctx->locked_free_list);
318         INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
319         INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
320         return ctx;
321 err:
322         kfree(ctx->dummy_ubuf);
323         kfree(ctx->cancel_table.hbs);
324         kfree(ctx->cancel_table_locked.hbs);
325         kfree(ctx->io_bl);
326         xa_destroy(&ctx->io_bl_xa);
327         kfree(ctx);
328         return NULL;
329 }
330
331 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
332 {
333         struct io_rings *r = ctx->rings;
334
335         WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
336         ctx->cq_extra--;
337 }
338
339 static bool req_need_defer(struct io_kiocb *req, u32 seq)
340 {
341         if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
342                 struct io_ring_ctx *ctx = req->ctx;
343
344                 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
345         }
346
347         return false;
348 }
349
350 static inline void io_req_track_inflight(struct io_kiocb *req)
351 {
352         if (!(req->flags & REQ_F_INFLIGHT)) {
353                 req->flags |= REQ_F_INFLIGHT;
354                 atomic_inc(&req->task->io_uring->inflight_tracked);
355         }
356 }
357
358 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
359 {
360         if (WARN_ON_ONCE(!req->link))
361                 return NULL;
362
363         req->flags &= ~REQ_F_ARM_LTIMEOUT;
364         req->flags |= REQ_F_LINK_TIMEOUT;
365
366         /* linked timeouts should have two refs once prep'ed */
367         io_req_set_refcount(req);
368         __io_req_set_refcount(req->link, 2);
369         return req->link;
370 }
371
372 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
373 {
374         if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
375                 return NULL;
376         return __io_prep_linked_timeout(req);
377 }
378
379 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
380 {
381         io_queue_linked_timeout(__io_prep_linked_timeout(req));
382 }
383
384 static inline void io_arm_ltimeout(struct io_kiocb *req)
385 {
386         if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
387                 __io_arm_ltimeout(req);
388 }
389
390 static void io_prep_async_work(struct io_kiocb *req)
391 {
392         const struct io_op_def *def = &io_op_defs[req->opcode];
393         struct io_ring_ctx *ctx = req->ctx;
394
395         if (!(req->flags & REQ_F_CREDS)) {
396                 req->flags |= REQ_F_CREDS;
397                 req->creds = get_current_cred();
398         }
399
400         req->work.list.next = NULL;
401         req->work.flags = 0;
402         req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
403         if (req->flags & REQ_F_FORCE_ASYNC)
404                 req->work.flags |= IO_WQ_WORK_CONCURRENT;
405
406         if (req->flags & REQ_F_ISREG) {
407                 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
408                         io_wq_hash_work(&req->work, file_inode(req->file));
409         } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
410                 if (def->unbound_nonreg_file)
411                         req->work.flags |= IO_WQ_WORK_UNBOUND;
412         }
413 }
414
415 static void io_prep_async_link(struct io_kiocb *req)
416 {
417         struct io_kiocb *cur;
418
419         if (req->flags & REQ_F_LINK_TIMEOUT) {
420                 struct io_ring_ctx *ctx = req->ctx;
421
422                 spin_lock_irq(&ctx->timeout_lock);
423                 io_for_each_link(cur, req)
424                         io_prep_async_work(cur);
425                 spin_unlock_irq(&ctx->timeout_lock);
426         } else {
427                 io_for_each_link(cur, req)
428                         io_prep_async_work(cur);
429         }
430 }
431
432 void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
433 {
434         struct io_kiocb *link = io_prep_linked_timeout(req);
435         struct io_uring_task *tctx = req->task->io_uring;
436
437         BUG_ON(!tctx);
438         BUG_ON(!tctx->io_wq);
439
440         /* init ->work of the whole link before punting */
441         io_prep_async_link(req);
442
443         /*
444          * Not expected to happen, but if we do have a bug where this _can_
445          * happen, catch it here and ensure the request is marked as
446          * canceled. That will make io-wq go through the usual work cancel
447          * procedure rather than attempt to run this request (or create a new
448          * worker for it).
449          */
450         if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
451                 req->work.flags |= IO_WQ_WORK_CANCEL;
452
453         trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
454         io_wq_enqueue(tctx->io_wq, &req->work);
455         if (link)
456                 io_queue_linked_timeout(link);
457 }
458
459 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
460 {
461         while (!list_empty(&ctx->defer_list)) {
462                 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
463                                                 struct io_defer_entry, list);
464
465                 if (req_need_defer(de->req, de->seq))
466                         break;
467                 list_del_init(&de->list);
468                 io_req_task_queue(de->req);
469                 kfree(de);
470         }
471 }
472
473 static void io_eventfd_signal(struct io_ring_ctx *ctx)
474 {
475         struct io_ev_fd *ev_fd;
476
477         rcu_read_lock();
478         /*
479          * rcu_dereference ctx->io_ev_fd once and use it for both for checking
480          * and eventfd_signal
481          */
482         ev_fd = rcu_dereference(ctx->io_ev_fd);
483
484         /*
485          * Check again if ev_fd exists incase an io_eventfd_unregister call
486          * completed between the NULL check of ctx->io_ev_fd at the start of
487          * the function and rcu_read_lock.
488          */
489         if (unlikely(!ev_fd))
490                 goto out;
491         if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
492                 goto out;
493
494         if (!ev_fd->eventfd_async || io_wq_current_is_worker())
495                 eventfd_signal(ev_fd->cq_ev_fd, 1);
496 out:
497         rcu_read_unlock();
498 }
499
500 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
501 {
502         if (ctx->off_timeout_used || ctx->drain_active) {
503                 spin_lock(&ctx->completion_lock);
504                 if (ctx->off_timeout_used)
505                         io_flush_timeouts(ctx);
506                 if (ctx->drain_active)
507                         io_queue_deferred(ctx);
508                 spin_unlock(&ctx->completion_lock);
509         }
510         if (ctx->has_evfd)
511                 io_eventfd_signal(ctx);
512 }
513
514 /*
515  * This should only get called when at least one event has been posted.
516  * Some applications rely on the eventfd notification count only changing
517  * IFF a new CQE has been added to the CQ ring. There's no depedency on
518  * 1:1 relationship between how many times this function is called (and
519  * hence the eventfd count) and number of CQEs posted to the CQ ring.
520  */
521 void io_cqring_ev_posted(struct io_ring_ctx *ctx)
522 {
523         if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
524                      ctx->has_evfd))
525                 __io_commit_cqring_flush(ctx);
526
527         io_cqring_wake(ctx);
528 }
529
530 /* Returns true if there are no backlogged entries after the flush */
531 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
532 {
533         bool all_flushed, posted;
534         size_t cqe_size = sizeof(struct io_uring_cqe);
535
536         if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
537                 return false;
538
539         if (ctx->flags & IORING_SETUP_CQE32)
540                 cqe_size <<= 1;
541
542         posted = false;
543         spin_lock(&ctx->completion_lock);
544         while (!list_empty(&ctx->cq_overflow_list)) {
545                 struct io_uring_cqe *cqe = io_get_cqe(ctx);
546                 struct io_overflow_cqe *ocqe;
547
548                 if (!cqe && !force)
549                         break;
550                 ocqe = list_first_entry(&ctx->cq_overflow_list,
551                                         struct io_overflow_cqe, list);
552                 if (cqe)
553                         memcpy(cqe, &ocqe->cqe, cqe_size);
554                 else
555                         io_account_cq_overflow(ctx);
556
557                 posted = true;
558                 list_del(&ocqe->list);
559                 kfree(ocqe);
560         }
561
562         all_flushed = list_empty(&ctx->cq_overflow_list);
563         if (all_flushed) {
564                 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
565                 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
566         }
567
568         io_commit_cqring(ctx);
569         spin_unlock(&ctx->completion_lock);
570         if (posted)
571                 io_cqring_ev_posted(ctx);
572         return all_flushed;
573 }
574
575 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
576 {
577         bool ret = true;
578
579         if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
580                 /* iopoll syncs against uring_lock, not completion_lock */
581                 if (ctx->flags & IORING_SETUP_IOPOLL)
582                         mutex_lock(&ctx->uring_lock);
583                 ret = __io_cqring_overflow_flush(ctx, false);
584                 if (ctx->flags & IORING_SETUP_IOPOLL)
585                         mutex_unlock(&ctx->uring_lock);
586         }
587
588         return ret;
589 }
590
591 static void __io_put_task(struct task_struct *task, int nr)
592 {
593         struct io_uring_task *tctx = task->io_uring;
594
595         percpu_counter_sub(&tctx->inflight, nr);
596         if (unlikely(atomic_read(&tctx->in_idle)))
597                 wake_up(&tctx->wait);
598         put_task_struct_many(task, nr);
599 }
600
601 /* must to be called somewhat shortly after putting a request */
602 static inline void io_put_task(struct task_struct *task, int nr)
603 {
604         if (likely(task == current))
605                 task->io_uring->cached_refs += nr;
606         else
607                 __io_put_task(task, nr);
608 }
609
610 static void io_task_refs_refill(struct io_uring_task *tctx)
611 {
612         unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
613
614         percpu_counter_add(&tctx->inflight, refill);
615         refcount_add(refill, &current->usage);
616         tctx->cached_refs += refill;
617 }
618
619 static inline void io_get_task_refs(int nr)
620 {
621         struct io_uring_task *tctx = current->io_uring;
622
623         tctx->cached_refs -= nr;
624         if (unlikely(tctx->cached_refs < 0))
625                 io_task_refs_refill(tctx);
626 }
627
628 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
629 {
630         struct io_uring_task *tctx = task->io_uring;
631         unsigned int refs = tctx->cached_refs;
632
633         if (refs) {
634                 tctx->cached_refs = 0;
635                 percpu_counter_sub(&tctx->inflight, refs);
636                 put_task_struct_many(task, refs);
637         }
638 }
639
640 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
641                                      s32 res, u32 cflags, u64 extra1, u64 extra2)
642 {
643         struct io_overflow_cqe *ocqe;
644         size_t ocq_size = sizeof(struct io_overflow_cqe);
645         bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
646
647         if (is_cqe32)
648                 ocq_size += sizeof(struct io_uring_cqe);
649
650         ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
651         trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
652         if (!ocqe) {
653                 /*
654                  * If we're in ring overflow flush mode, or in task cancel mode,
655                  * or cannot allocate an overflow entry, then we need to drop it
656                  * on the floor.
657                  */
658                 io_account_cq_overflow(ctx);
659                 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
660                 return false;
661         }
662         if (list_empty(&ctx->cq_overflow_list)) {
663                 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
664                 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
665
666         }
667         ocqe->cqe.user_data = user_data;
668         ocqe->cqe.res = res;
669         ocqe->cqe.flags = cflags;
670         if (is_cqe32) {
671                 ocqe->cqe.big_cqe[0] = extra1;
672                 ocqe->cqe.big_cqe[1] = extra2;
673         }
674         list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
675         return true;
676 }
677
678 bool io_req_cqe_overflow(struct io_kiocb *req)
679 {
680         if (!(req->flags & REQ_F_CQE32_INIT)) {
681                 req->extra1 = 0;
682                 req->extra2 = 0;
683         }
684         return io_cqring_event_overflow(req->ctx, req->cqe.user_data,
685                                         req->cqe.res, req->cqe.flags,
686                                         req->extra1, req->extra2);
687 }
688
689 /*
690  * writes to the cq entry need to come after reading head; the
691  * control dependency is enough as we're using WRITE_ONCE to
692  * fill the cq entry
693  */
694 struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
695 {
696         struct io_rings *rings = ctx->rings;
697         unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
698         unsigned int free, queued, len;
699
700
701         /* userspace may cheat modifying the tail, be safe and do min */
702         queued = min(__io_cqring_events(ctx), ctx->cq_entries);
703         free = ctx->cq_entries - queued;
704         /* we need a contiguous range, limit based on the current array offset */
705         len = min(free, ctx->cq_entries - off);
706         if (!len)
707                 return NULL;
708
709         if (ctx->flags & IORING_SETUP_CQE32) {
710                 off <<= 1;
711                 len <<= 1;
712         }
713
714         ctx->cqe_cached = &rings->cqes[off];
715         ctx->cqe_sentinel = ctx->cqe_cached + len;
716
717         ctx->cached_cq_tail++;
718         ctx->cqe_cached++;
719         if (ctx->flags & IORING_SETUP_CQE32)
720                 ctx->cqe_cached++;
721         return &rings->cqes[off];
722 }
723
724 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx,
725                             u64 user_data, s32 res, u32 cflags)
726 {
727         struct io_uring_cqe *cqe;
728
729         ctx->cq_extra++;
730         trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
731
732         /*
733          * If we can't get a cq entry, userspace overflowed the
734          * submission (by quite a lot). Increment the overflow count in
735          * the ring.
736          */
737         cqe = io_get_cqe(ctx);
738         if (likely(cqe)) {
739                 WRITE_ONCE(cqe->user_data, user_data);
740                 WRITE_ONCE(cqe->res, res);
741                 WRITE_ONCE(cqe->flags, cflags);
742
743                 if (ctx->flags & IORING_SETUP_CQE32) {
744                         WRITE_ONCE(cqe->big_cqe[0], 0);
745                         WRITE_ONCE(cqe->big_cqe[1], 0);
746                 }
747                 return true;
748         }
749         return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
750 }
751
752 bool io_post_aux_cqe(struct io_ring_ctx *ctx,
753                      u64 user_data, s32 res, u32 cflags)
754 {
755         bool filled;
756
757         spin_lock(&ctx->completion_lock);
758         filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
759         io_commit_cqring(ctx);
760         spin_unlock(&ctx->completion_lock);
761         if (filled)
762                 io_cqring_ev_posted(ctx);
763         return filled;
764 }
765
766 static void __io_req_complete_put(struct io_kiocb *req)
767 {
768         /*
769          * If we're the last reference to this request, add to our locked
770          * free_list cache.
771          */
772         if (req_ref_put_and_test(req)) {
773                 struct io_ring_ctx *ctx = req->ctx;
774
775                 if (req->flags & IO_REQ_LINK_FLAGS) {
776                         if (req->flags & IO_DISARM_MASK)
777                                 io_disarm_next(req);
778                         if (req->link) {
779                                 io_req_task_queue(req->link);
780                                 req->link = NULL;
781                         }
782                 }
783                 io_req_put_rsrc(req);
784                 /*
785                  * Selected buffer deallocation in io_clean_op() assumes that
786                  * we don't hold ->completion_lock. Clean them here to avoid
787                  * deadlocks.
788                  */
789                 io_put_kbuf_comp(req);
790                 io_dismantle_req(req);
791                 io_put_task(req->task, 1);
792                 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
793                 ctx->locked_free_nr++;
794         }
795 }
796
797 void __io_req_complete_post(struct io_kiocb *req)
798 {
799         if (!(req->flags & REQ_F_CQE_SKIP))
800                 __io_fill_cqe_req(req->ctx, req);
801         __io_req_complete_put(req);
802 }
803
804 void io_req_complete_post(struct io_kiocb *req)
805 {
806         struct io_ring_ctx *ctx = req->ctx;
807
808         spin_lock(&ctx->completion_lock);
809         __io_req_complete_post(req);
810         io_commit_cqring(ctx);
811         spin_unlock(&ctx->completion_lock);
812         io_cqring_ev_posted(ctx);
813 }
814
815 inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags)
816 {
817         io_req_complete_post(req);
818 }
819
820 void io_req_complete_failed(struct io_kiocb *req, s32 res)
821 {
822         req_set_fail(req);
823         io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
824         io_req_complete_post(req);
825 }
826
827 /*
828  * Don't initialise the fields below on every allocation, but do that in
829  * advance and keep them valid across allocations.
830  */
831 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
832 {
833         req->ctx = ctx;
834         req->link = NULL;
835         req->async_data = NULL;
836         /* not necessary, but safer to zero */
837         req->cqe.res = 0;
838 }
839
840 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
841                                         struct io_submit_state *state)
842 {
843         spin_lock(&ctx->completion_lock);
844         wq_list_splice(&ctx->locked_free_list, &state->free_list);
845         ctx->locked_free_nr = 0;
846         spin_unlock(&ctx->completion_lock);
847 }
848
849 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
850 {
851         return !ctx->submit_state.free_list.next;
852 }
853
854 /*
855  * A request might get retired back into the request caches even before opcode
856  * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
857  * Because of that, io_alloc_req() should be called only under ->uring_lock
858  * and with extra caution to not get a request that is still worked on.
859  */
860 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
861         __must_hold(&ctx->uring_lock)
862 {
863         gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
864         void *reqs[IO_REQ_ALLOC_BATCH];
865         int ret, i;
866
867         /*
868          * If we have more than a batch's worth of requests in our IRQ side
869          * locked cache, grab the lock and move them over to our submission
870          * side cache.
871          */
872         if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
873                 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
874                 if (!io_req_cache_empty(ctx))
875                         return true;
876         }
877
878         ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
879
880         /*
881          * Bulk alloc is all-or-nothing. If we fail to get a batch,
882          * retry single alloc to be on the safe side.
883          */
884         if (unlikely(ret <= 0)) {
885                 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
886                 if (!reqs[0])
887                         return false;
888                 ret = 1;
889         }
890
891         percpu_ref_get_many(&ctx->refs, ret);
892         for (i = 0; i < ret; i++) {
893                 struct io_kiocb *req = reqs[i];
894
895                 io_preinit_req(req, ctx);
896                 io_req_add_to_cache(req, ctx);
897         }
898         return true;
899 }
900
901 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
902 {
903         if (unlikely(io_req_cache_empty(ctx)))
904                 return __io_alloc_req_refill(ctx);
905         return true;
906 }
907
908 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
909 {
910         struct io_wq_work_node *node;
911
912         node = wq_stack_extract(&ctx->submit_state.free_list);
913         return container_of(node, struct io_kiocb, comp_list);
914 }
915
916 static inline void io_dismantle_req(struct io_kiocb *req)
917 {
918         unsigned int flags = req->flags;
919
920         if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
921                 io_clean_op(req);
922         if (!(flags & REQ_F_FIXED_FILE))
923                 io_put_file(req->file);
924 }
925
926 __cold void io_free_req(struct io_kiocb *req)
927 {
928         struct io_ring_ctx *ctx = req->ctx;
929
930         io_req_put_rsrc(req);
931         io_dismantle_req(req);
932         io_put_task(req->task, 1);
933
934         spin_lock(&ctx->completion_lock);
935         wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
936         ctx->locked_free_nr++;
937         spin_unlock(&ctx->completion_lock);
938 }
939
940 static void __io_req_find_next_prep(struct io_kiocb *req)
941 {
942         struct io_ring_ctx *ctx = req->ctx;
943         bool posted;
944
945         spin_lock(&ctx->completion_lock);
946         posted = io_disarm_next(req);
947         io_commit_cqring(ctx);
948         spin_unlock(&ctx->completion_lock);
949         if (posted)
950                 io_cqring_ev_posted(ctx);
951 }
952
953 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
954 {
955         struct io_kiocb *nxt;
956
957         /*
958          * If LINK is set, we have dependent requests in this chain. If we
959          * didn't fail this request, queue the first one up, moving any other
960          * dependencies to the next request. In case of failure, fail the rest
961          * of the chain.
962          */
963         if (unlikely(req->flags & IO_DISARM_MASK))
964                 __io_req_find_next_prep(req);
965         nxt = req->link;
966         req->link = NULL;
967         return nxt;
968 }
969
970 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
971 {
972         if (!ctx)
973                 return;
974         if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
975                 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
976         if (*locked) {
977                 io_submit_flush_completions(ctx);
978                 mutex_unlock(&ctx->uring_lock);
979                 *locked = false;
980         }
981         percpu_ref_put(&ctx->refs);
982 }
983
984 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
985 {
986         io_commit_cqring(ctx);
987         spin_unlock(&ctx->completion_lock);
988         io_cqring_ev_posted(ctx);
989 }
990
991 static void handle_prev_tw_list(struct io_wq_work_node *node,
992                                 struct io_ring_ctx **ctx, bool *uring_locked)
993 {
994         if (*ctx && !*uring_locked)
995                 spin_lock(&(*ctx)->completion_lock);
996
997         do {
998                 struct io_wq_work_node *next = node->next;
999                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1000                                                     io_task_work.node);
1001
1002                 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1003
1004                 if (req->ctx != *ctx) {
1005                         if (unlikely(!*uring_locked && *ctx))
1006                                 ctx_commit_and_unlock(*ctx);
1007
1008                         ctx_flush_and_put(*ctx, uring_locked);
1009                         *ctx = req->ctx;
1010                         /* if not contended, grab and improve batching */
1011                         *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
1012                         percpu_ref_get(&(*ctx)->refs);
1013                         if (unlikely(!*uring_locked))
1014                                 spin_lock(&(*ctx)->completion_lock);
1015                 }
1016                 if (likely(*uring_locked)) {
1017                         req->io_task_work.func(req, uring_locked);
1018                 } else {
1019                         req->cqe.flags = io_put_kbuf_comp(req);
1020                         __io_req_complete_post(req);
1021                 }
1022                 node = next;
1023         } while (node);
1024
1025         if (unlikely(!*uring_locked))
1026                 ctx_commit_and_unlock(*ctx);
1027 }
1028
1029 static void handle_tw_list(struct io_wq_work_node *node,
1030                            struct io_ring_ctx **ctx, bool *locked)
1031 {
1032         do {
1033                 struct io_wq_work_node *next = node->next;
1034                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1035                                                     io_task_work.node);
1036
1037                 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1038
1039                 if (req->ctx != *ctx) {
1040                         ctx_flush_and_put(*ctx, locked);
1041                         *ctx = req->ctx;
1042                         /* if not contended, grab and improve batching */
1043                         *locked = mutex_trylock(&(*ctx)->uring_lock);
1044                         percpu_ref_get(&(*ctx)->refs);
1045                 }
1046                 req->io_task_work.func(req, locked);
1047                 node = next;
1048         } while (node);
1049 }
1050
1051 void tctx_task_work(struct callback_head *cb)
1052 {
1053         bool uring_locked = false;
1054         struct io_ring_ctx *ctx = NULL;
1055         struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1056                                                   task_work);
1057
1058         while (1) {
1059                 struct io_wq_work_node *node1, *node2;
1060
1061                 spin_lock_irq(&tctx->task_lock);
1062                 node1 = tctx->prio_task_list.first;
1063                 node2 = tctx->task_list.first;
1064                 INIT_WQ_LIST(&tctx->task_list);
1065                 INIT_WQ_LIST(&tctx->prio_task_list);
1066                 if (!node2 && !node1)
1067                         tctx->task_running = false;
1068                 spin_unlock_irq(&tctx->task_lock);
1069                 if (!node2 && !node1)
1070                         break;
1071
1072                 if (node1)
1073                         handle_prev_tw_list(node1, &ctx, &uring_locked);
1074                 if (node2)
1075                         handle_tw_list(node2, &ctx, &uring_locked);
1076                 cond_resched();
1077
1078                 if (data_race(!tctx->task_list.first) &&
1079                     data_race(!tctx->prio_task_list.first) && uring_locked)
1080                         io_submit_flush_completions(ctx);
1081         }
1082
1083         ctx_flush_and_put(ctx, &uring_locked);
1084
1085         /* relaxed read is enough as only the task itself sets ->in_idle */
1086         if (unlikely(atomic_read(&tctx->in_idle)))
1087                 io_uring_drop_tctx_refs(current);
1088 }
1089
1090 static void __io_req_task_work_add(struct io_kiocb *req,
1091                                    struct io_uring_task *tctx,
1092                                    struct io_wq_work_list *list)
1093 {
1094         struct io_ring_ctx *ctx = req->ctx;
1095         struct io_wq_work_node *node;
1096         unsigned long flags;
1097         bool running;
1098
1099         spin_lock_irqsave(&tctx->task_lock, flags);
1100         wq_list_add_tail(&req->io_task_work.node, list);
1101         running = tctx->task_running;
1102         if (!running)
1103                 tctx->task_running = true;
1104         spin_unlock_irqrestore(&tctx->task_lock, flags);
1105
1106         /* task_work already pending, we're done */
1107         if (running)
1108                 return;
1109
1110         if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1111                 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1112
1113         if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1114                 return;
1115
1116         spin_lock_irqsave(&tctx->task_lock, flags);
1117         tctx->task_running = false;
1118         node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
1119         spin_unlock_irqrestore(&tctx->task_lock, flags);
1120
1121         while (node) {
1122                 req = container_of(node, struct io_kiocb, io_task_work.node);
1123                 node = node->next;
1124                 if (llist_add(&req->io_task_work.fallback_node,
1125                               &req->ctx->fallback_llist))
1126                         schedule_delayed_work(&req->ctx->fallback_work, 1);
1127         }
1128 }
1129
1130 void io_req_task_work_add(struct io_kiocb *req)
1131 {
1132         struct io_uring_task *tctx = req->task->io_uring;
1133
1134         __io_req_task_work_add(req, tctx, &tctx->task_list);
1135 }
1136
1137 void io_req_task_prio_work_add(struct io_kiocb *req)
1138 {
1139         struct io_uring_task *tctx = req->task->io_uring;
1140
1141         if (req->ctx->flags & IORING_SETUP_SQPOLL)
1142                 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
1143         else
1144                 __io_req_task_work_add(req, tctx, &tctx->task_list);
1145 }
1146
1147 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
1148 {
1149         io_req_complete_post(req);
1150 }
1151
1152 void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
1153 {
1154         io_req_set_res(req, res, cflags);
1155         req->io_task_work.func = io_req_tw_post;
1156         io_req_task_work_add(req);
1157 }
1158
1159 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
1160 {
1161         /* not needed for normal modes, but SQPOLL depends on it */
1162         io_tw_lock(req->ctx, locked);
1163         io_req_complete_failed(req, req->cqe.res);
1164 }
1165
1166 void io_req_task_submit(struct io_kiocb *req, bool *locked)
1167 {
1168         io_tw_lock(req->ctx, locked);
1169         /* req->task == current here, checking PF_EXITING is safe */
1170         if (likely(!(req->task->flags & PF_EXITING)))
1171                 io_queue_sqe(req);
1172         else
1173                 io_req_complete_failed(req, -EFAULT);
1174 }
1175
1176 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1177 {
1178         io_req_set_res(req, ret, 0);
1179         req->io_task_work.func = io_req_task_cancel;
1180         io_req_task_work_add(req);
1181 }
1182
1183 void io_req_task_queue(struct io_kiocb *req)
1184 {
1185         req->io_task_work.func = io_req_task_submit;
1186         io_req_task_work_add(req);
1187 }
1188
1189 void io_queue_next(struct io_kiocb *req)
1190 {
1191         struct io_kiocb *nxt = io_req_find_next(req);
1192
1193         if (nxt)
1194                 io_req_task_queue(nxt);
1195 }
1196
1197 void io_free_batch_list(struct io_ring_ctx *ctx, struct io_wq_work_node *node)
1198         __must_hold(&ctx->uring_lock)
1199 {
1200         struct task_struct *task = NULL;
1201         int task_refs = 0;
1202
1203         do {
1204                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1205                                                     comp_list);
1206
1207                 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1208                         if (req->flags & REQ_F_REFCOUNT) {
1209                                 node = req->comp_list.next;
1210                                 if (!req_ref_put_and_test(req))
1211                                         continue;
1212                         }
1213                         if ((req->flags & REQ_F_POLLED) && req->apoll) {
1214                                 struct async_poll *apoll = req->apoll;
1215
1216                                 if (apoll->double_poll)
1217                                         kfree(apoll->double_poll);
1218                                 list_add(&apoll->poll.wait.entry,
1219                                                 &ctx->apoll_cache);
1220                                 req->flags &= ~REQ_F_POLLED;
1221                         }
1222                         if (req->flags & IO_REQ_LINK_FLAGS)
1223                                 io_queue_next(req);
1224                         if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1225                                 io_clean_op(req);
1226                 }
1227                 if (!(req->flags & REQ_F_FIXED_FILE))
1228                         io_put_file(req->file);
1229
1230                 io_req_put_rsrc_locked(req, ctx);
1231
1232                 if (req->task != task) {
1233                         if (task)
1234                                 io_put_task(task, task_refs);
1235                         task = req->task;
1236                         task_refs = 0;
1237                 }
1238                 task_refs++;
1239                 node = req->comp_list.next;
1240                 io_req_add_to_cache(req, ctx);
1241         } while (node);
1242
1243         if (task)
1244                 io_put_task(task, task_refs);
1245 }
1246
1247 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1248         __must_hold(&ctx->uring_lock)
1249 {
1250         struct io_wq_work_node *node, *prev;
1251         struct io_submit_state *state = &ctx->submit_state;
1252
1253         spin_lock(&ctx->completion_lock);
1254         wq_list_for_each(node, prev, &state->compl_reqs) {
1255                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1256                                             comp_list);
1257
1258                 if (!(req->flags & REQ_F_CQE_SKIP))
1259                         __io_fill_cqe_req(ctx, req);
1260         }
1261
1262         io_commit_cqring(ctx);
1263         spin_unlock(&ctx->completion_lock);
1264         io_cqring_ev_posted(ctx);
1265
1266         io_free_batch_list(ctx, state->compl_reqs.first);
1267         INIT_WQ_LIST(&state->compl_reqs);
1268 }
1269
1270 /*
1271  * Drop reference to request, return next in chain (if there is one) if this
1272  * was the last reference to this request.
1273  */
1274 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
1275 {
1276         struct io_kiocb *nxt = NULL;
1277
1278         if (req_ref_put_and_test(req)) {
1279                 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
1280                         nxt = io_req_find_next(req);
1281                 io_free_req(req);
1282         }
1283         return nxt;
1284 }
1285
1286 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1287 {
1288         /* See comment at the top of this file */
1289         smp_rmb();
1290         return __io_cqring_events(ctx);
1291 }
1292
1293 /*
1294  * We can't just wait for polled events to come to us, we have to actively
1295  * find and complete them.
1296  */
1297 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1298 {
1299         if (!(ctx->flags & IORING_SETUP_IOPOLL))
1300                 return;
1301
1302         mutex_lock(&ctx->uring_lock);
1303         while (!wq_list_empty(&ctx->iopoll_list)) {
1304                 /* let it sleep and repeat later if can't complete a request */
1305                 if (io_do_iopoll(ctx, true) == 0)
1306                         break;
1307                 /*
1308                  * Ensure we allow local-to-the-cpu processing to take place,
1309                  * in this case we need to ensure that we reap all events.
1310                  * Also let task_work, etc. to progress by releasing the mutex
1311                  */
1312                 if (need_resched()) {
1313                         mutex_unlock(&ctx->uring_lock);
1314                         cond_resched();
1315                         mutex_lock(&ctx->uring_lock);
1316                 }
1317         }
1318         mutex_unlock(&ctx->uring_lock);
1319 }
1320
1321 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1322 {
1323         unsigned int nr_events = 0;
1324         int ret = 0;
1325         unsigned long check_cq;
1326
1327         check_cq = READ_ONCE(ctx->check_cq);
1328         if (unlikely(check_cq)) {
1329                 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1330                         __io_cqring_overflow_flush(ctx, false);
1331                 /*
1332                  * Similarly do not spin if we have not informed the user of any
1333                  * dropped CQE.
1334                  */
1335                 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1336                         return -EBADR;
1337         }
1338         /*
1339          * Don't enter poll loop if we already have events pending.
1340          * If we do, we can potentially be spinning for commands that
1341          * already triggered a CQE (eg in error).
1342          */
1343         if (io_cqring_events(ctx))
1344                 return 0;
1345
1346         do {
1347                 /*
1348                  * If a submit got punted to a workqueue, we can have the
1349                  * application entering polling for a command before it gets
1350                  * issued. That app will hold the uring_lock for the duration
1351                  * of the poll right here, so we need to take a breather every
1352                  * now and then to ensure that the issue has a chance to add
1353                  * the poll to the issued list. Otherwise we can spin here
1354                  * forever, while the workqueue is stuck trying to acquire the
1355                  * very same mutex.
1356                  */
1357                 if (wq_list_empty(&ctx->iopoll_list)) {
1358                         u32 tail = ctx->cached_cq_tail;
1359
1360                         mutex_unlock(&ctx->uring_lock);
1361                         io_run_task_work();
1362                         mutex_lock(&ctx->uring_lock);
1363
1364                         /* some requests don't go through iopoll_list */
1365                         if (tail != ctx->cached_cq_tail ||
1366                             wq_list_empty(&ctx->iopoll_list))
1367                                 break;
1368                 }
1369                 ret = io_do_iopoll(ctx, !min);
1370                 if (ret < 0)
1371                         break;
1372                 nr_events += ret;
1373                 ret = 0;
1374         } while (nr_events < min && !need_resched());
1375
1376         return ret;
1377 }
1378
1379 void io_req_task_complete(struct io_kiocb *req, bool *locked)
1380 {
1381         if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
1382                 unsigned issue_flags = *locked ? 0 : IO_URING_F_UNLOCKED;
1383
1384                 req->cqe.flags |= io_put_kbuf(req, issue_flags);
1385         }
1386
1387         if (*locked)
1388                 io_req_add_compl_list(req);
1389         else
1390                 io_req_complete_post(req);
1391 }
1392
1393 /*
1394  * After the iocb has been issued, it's safe to be found on the poll list.
1395  * Adding the kiocb to the list AFTER submission ensures that we don't
1396  * find it from a io_do_iopoll() thread before the issuer is done
1397  * accessing the kiocb cookie.
1398  */
1399 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1400 {
1401         struct io_ring_ctx *ctx = req->ctx;
1402         const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1403
1404         /* workqueue context doesn't hold uring_lock, grab it now */
1405         if (unlikely(needs_lock))
1406                 mutex_lock(&ctx->uring_lock);
1407
1408         /*
1409          * Track whether we have multiple files in our lists. This will impact
1410          * how we do polling eventually, not spinning if we're on potentially
1411          * different devices.
1412          */
1413         if (wq_list_empty(&ctx->iopoll_list)) {
1414                 ctx->poll_multi_queue = false;
1415         } else if (!ctx->poll_multi_queue) {
1416                 struct io_kiocb *list_req;
1417
1418                 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1419                                         comp_list);
1420                 if (list_req->file != req->file)
1421                         ctx->poll_multi_queue = true;
1422         }
1423
1424         /*
1425          * For fast devices, IO may have already completed. If it has, add
1426          * it to the front so we find it first.
1427          */
1428         if (READ_ONCE(req->iopoll_completed))
1429                 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1430         else
1431                 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1432
1433         if (unlikely(needs_lock)) {
1434                 /*
1435                  * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1436                  * in sq thread task context or in io worker task context. If
1437                  * current task context is sq thread, we don't need to check
1438                  * whether should wake up sq thread.
1439                  */
1440                 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1441                     wq_has_sleeper(&ctx->sq_data->wait))
1442                         wake_up(&ctx->sq_data->wait);
1443
1444                 mutex_unlock(&ctx->uring_lock);
1445         }
1446 }
1447
1448 static bool io_bdev_nowait(struct block_device *bdev)
1449 {
1450         return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
1451 }
1452
1453 /*
1454  * If we tracked the file through the SCM inflight mechanism, we could support
1455  * any file. For now, just ensure that anything potentially problematic is done
1456  * inline.
1457  */
1458 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
1459 {
1460         if (S_ISBLK(mode)) {
1461                 if (IS_ENABLED(CONFIG_BLOCK) &&
1462                     io_bdev_nowait(I_BDEV(file->f_mapping->host)))
1463                         return true;
1464                 return false;
1465         }
1466         if (S_ISSOCK(mode))
1467                 return true;
1468         if (S_ISREG(mode)) {
1469                 if (IS_ENABLED(CONFIG_BLOCK) &&
1470                     io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
1471                     !io_is_uring_fops(file))
1472                         return true;
1473                 return false;
1474         }
1475
1476         /* any ->read/write should understand O_NONBLOCK */
1477         if (file->f_flags & O_NONBLOCK)
1478                 return true;
1479         return file->f_mode & FMODE_NOWAIT;
1480 }
1481
1482 /*
1483  * If we tracked the file through the SCM inflight mechanism, we could support
1484  * any file. For now, just ensure that anything potentially problematic is done
1485  * inline.
1486  */
1487 unsigned int io_file_get_flags(struct file *file)
1488 {
1489         umode_t mode = file_inode(file)->i_mode;
1490         unsigned int res = 0;
1491
1492         if (S_ISREG(mode))
1493                 res |= FFS_ISREG;
1494         if (__io_file_supports_nowait(file, mode))
1495                 res |= FFS_NOWAIT;
1496         if (io_file_need_scm(file))
1497                 res |= FFS_SCM;
1498         return res;
1499 }
1500
1501 bool io_alloc_async_data(struct io_kiocb *req)
1502 {
1503         WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
1504         req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
1505         if (req->async_data) {
1506                 req->flags |= REQ_F_ASYNC_DATA;
1507                 return false;
1508         }
1509         return true;
1510 }
1511
1512 int io_req_prep_async(struct io_kiocb *req)
1513 {
1514         const struct io_op_def *def = &io_op_defs[req->opcode];
1515
1516         /* assign early for deferred execution for non-fixed file */
1517         if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
1518                 req->file = io_file_get_normal(req, req->cqe.fd);
1519         if (!def->prep_async)
1520                 return 0;
1521         if (WARN_ON_ONCE(req_has_async_data(req)))
1522                 return -EFAULT;
1523         if (io_alloc_async_data(req))
1524                 return -EAGAIN;
1525
1526         return def->prep_async(req);
1527 }
1528
1529 static u32 io_get_sequence(struct io_kiocb *req)
1530 {
1531         u32 seq = req->ctx->cached_sq_head;
1532         struct io_kiocb *cur;
1533
1534         /* need original cached_sq_head, but it was increased for each req */
1535         io_for_each_link(cur, req)
1536                 seq--;
1537         return seq;
1538 }
1539
1540 static __cold void io_drain_req(struct io_kiocb *req)
1541 {
1542         struct io_ring_ctx *ctx = req->ctx;
1543         struct io_defer_entry *de;
1544         int ret;
1545         u32 seq = io_get_sequence(req);
1546
1547         /* Still need defer if there is pending req in defer list. */
1548         spin_lock(&ctx->completion_lock);
1549         if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
1550                 spin_unlock(&ctx->completion_lock);
1551 queue:
1552                 ctx->drain_active = false;
1553                 io_req_task_queue(req);
1554                 return;
1555         }
1556         spin_unlock(&ctx->completion_lock);
1557
1558         ret = io_req_prep_async(req);
1559         if (ret) {
1560 fail:
1561                 io_req_complete_failed(req, ret);
1562                 return;
1563         }
1564         io_prep_async_link(req);
1565         de = kmalloc(sizeof(*de), GFP_KERNEL);
1566         if (!de) {
1567                 ret = -ENOMEM;
1568                 goto fail;
1569         }
1570
1571         spin_lock(&ctx->completion_lock);
1572         if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
1573                 spin_unlock(&ctx->completion_lock);
1574                 kfree(de);
1575                 goto queue;
1576         }
1577
1578         trace_io_uring_defer(req);
1579         de->req = req;
1580         de->seq = seq;
1581         list_add_tail(&de->list, &ctx->defer_list);
1582         spin_unlock(&ctx->completion_lock);
1583 }
1584
1585 static void io_clean_op(struct io_kiocb *req)
1586 {
1587         if (req->flags & REQ_F_BUFFER_SELECTED) {
1588                 spin_lock(&req->ctx->completion_lock);
1589                 io_put_kbuf_comp(req);
1590                 spin_unlock(&req->ctx->completion_lock);
1591         }
1592
1593         if (req->flags & REQ_F_NEED_CLEANUP) {
1594                 const struct io_op_def *def = &io_op_defs[req->opcode];
1595
1596                 if (def->cleanup)
1597                         def->cleanup(req);
1598         }
1599         if ((req->flags & REQ_F_POLLED) && req->apoll) {
1600                 kfree(req->apoll->double_poll);
1601                 kfree(req->apoll);
1602                 req->apoll = NULL;
1603         }
1604         if (req->flags & REQ_F_INFLIGHT) {
1605                 struct io_uring_task *tctx = req->task->io_uring;
1606
1607                 atomic_dec(&tctx->inflight_tracked);
1608         }
1609         if (req->flags & REQ_F_CREDS)
1610                 put_cred(req->creds);
1611         if (req->flags & REQ_F_ASYNC_DATA) {
1612                 kfree(req->async_data);
1613                 req->async_data = NULL;
1614         }
1615         req->flags &= ~IO_REQ_CLEAN_FLAGS;
1616 }
1617
1618 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
1619 {
1620         if (req->file || !io_op_defs[req->opcode].needs_file)
1621                 return true;
1622
1623         if (req->flags & REQ_F_FIXED_FILE)
1624                 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1625         else
1626                 req->file = io_file_get_normal(req, req->cqe.fd);
1627
1628         return !!req->file;
1629 }
1630
1631 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1632 {
1633         const struct io_op_def *def = &io_op_defs[req->opcode];
1634         const struct cred *creds = NULL;
1635         int ret;
1636
1637         if (unlikely(!io_assign_file(req, issue_flags)))
1638                 return -EBADF;
1639
1640         if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
1641                 creds = override_creds(req->creds);
1642
1643         if (!def->audit_skip)
1644                 audit_uring_entry(req->opcode);
1645
1646         ret = def->issue(req, issue_flags);
1647
1648         if (!def->audit_skip)
1649                 audit_uring_exit(!ret, ret);
1650
1651         if (creds)
1652                 revert_creds(creds);
1653
1654         if (ret == IOU_OK) {
1655                 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1656                         io_req_add_compl_list(req);
1657                 else
1658                         io_req_complete_post(req);
1659         } else if (ret != IOU_ISSUE_SKIP_COMPLETE)
1660                 return ret;
1661
1662         /* If the op doesn't have a file, we're not polling for it */
1663         if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
1664                 io_iopoll_req_issued(req, issue_flags);
1665
1666         return 0;
1667 }
1668
1669 int io_poll_issue(struct io_kiocb *req, bool *locked)
1670 {
1671         io_tw_lock(req->ctx, locked);
1672         if (unlikely(req->task->flags & PF_EXITING))
1673                 return -EFAULT;
1674         return io_issue_sqe(req, IO_URING_F_NONBLOCK);
1675 }
1676
1677 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1678 {
1679         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1680
1681         req = io_put_req_find_next(req);
1682         return req ? &req->work : NULL;
1683 }
1684
1685 void io_wq_submit_work(struct io_wq_work *work)
1686 {
1687         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1688         const struct io_op_def *def = &io_op_defs[req->opcode];
1689         unsigned int issue_flags = IO_URING_F_UNLOCKED;
1690         bool needs_poll = false;
1691         int ret = 0, err = -ECANCELED;
1692
1693         /* one will be dropped by ->io_free_work() after returning to io-wq */
1694         if (!(req->flags & REQ_F_REFCOUNT))
1695                 __io_req_set_refcount(req, 2);
1696         else
1697                 req_ref_get(req);
1698
1699         io_arm_ltimeout(req);
1700
1701         /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1702         if (work->flags & IO_WQ_WORK_CANCEL) {
1703 fail:
1704                 io_req_task_queue_fail(req, err);
1705                 return;
1706         }
1707         if (!io_assign_file(req, issue_flags)) {
1708                 err = -EBADF;
1709                 work->flags |= IO_WQ_WORK_CANCEL;
1710                 goto fail;
1711         }
1712
1713         if (req->flags & REQ_F_FORCE_ASYNC) {
1714                 bool opcode_poll = def->pollin || def->pollout;
1715
1716                 if (opcode_poll && file_can_poll(req->file)) {
1717                         needs_poll = true;
1718                         issue_flags |= IO_URING_F_NONBLOCK;
1719                 }
1720         }
1721
1722         do {
1723                 ret = io_issue_sqe(req, issue_flags);
1724                 if (ret != -EAGAIN)
1725                         break;
1726                 /*
1727                  * We can get EAGAIN for iopolled IO even though we're
1728                  * forcing a sync submission from here, since we can't
1729                  * wait for request slots on the block side.
1730                  */
1731                 if (!needs_poll) {
1732                         if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1733                                 break;
1734                         cond_resched();
1735                         continue;
1736                 }
1737
1738                 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1739                         return;
1740                 /* aborted or ready, in either case retry blocking */
1741                 needs_poll = false;
1742                 issue_flags &= ~IO_URING_F_NONBLOCK;
1743         } while (1);
1744
1745         /* avoid locking problems by failing it from a clean context */
1746         if (ret < 0)
1747                 io_req_task_queue_fail(req, ret);
1748 }
1749
1750 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1751                                       unsigned int issue_flags)
1752 {
1753         struct io_ring_ctx *ctx = req->ctx;
1754         struct file *file = NULL;
1755         unsigned long file_ptr;
1756
1757         io_ring_submit_lock(ctx, issue_flags);
1758
1759         if (unlikely((unsigned int)fd >= ctx->nr_user_files))
1760                 goto out;
1761         fd = array_index_nospec(fd, ctx->nr_user_files);
1762         file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
1763         file = (struct file *) (file_ptr & FFS_MASK);
1764         file_ptr &= ~FFS_MASK;
1765         /* mask in overlapping REQ_F and FFS bits */
1766         req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
1767         io_req_set_rsrc_node(req, ctx, 0);
1768         WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
1769 out:
1770         io_ring_submit_unlock(ctx, issue_flags);
1771         return file;
1772 }
1773
1774 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
1775 {
1776         struct file *file = fget(fd);
1777
1778         trace_io_uring_file_get(req, fd);
1779
1780         /* we don't allow fixed io_uring files */
1781         if (file && io_is_uring_fops(file))
1782                 io_req_track_inflight(req);
1783         return file;
1784 }
1785
1786 static void io_queue_async(struct io_kiocb *req, int ret)
1787         __must_hold(&req->ctx->uring_lock)
1788 {
1789         struct io_kiocb *linked_timeout;
1790
1791         if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
1792                 io_req_complete_failed(req, ret);
1793                 return;
1794         }
1795
1796         linked_timeout = io_prep_linked_timeout(req);
1797
1798         switch (io_arm_poll_handler(req, 0)) {
1799         case IO_APOLL_READY:
1800                 io_req_task_queue(req);
1801                 break;
1802         case IO_APOLL_ABORTED:
1803                 /*
1804                  * Queued up for async execution, worker will release
1805                  * submit reference when the iocb is actually submitted.
1806                  */
1807                 io_kbuf_recycle(req, 0);
1808                 io_queue_iowq(req, NULL);
1809                 break;
1810         case IO_APOLL_OK:
1811                 break;
1812         }
1813
1814         if (linked_timeout)
1815                 io_queue_linked_timeout(linked_timeout);
1816 }
1817
1818 static inline void io_queue_sqe(struct io_kiocb *req)
1819         __must_hold(&req->ctx->uring_lock)
1820 {
1821         int ret;
1822
1823         ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
1824
1825         /*
1826          * We async punt it if the file wasn't marked NOWAIT, or if the file
1827          * doesn't support non-blocking read/write attempts
1828          */
1829         if (likely(!ret))
1830                 io_arm_ltimeout(req);
1831         else
1832                 io_queue_async(req, ret);
1833 }
1834
1835 static void io_queue_sqe_fallback(struct io_kiocb *req)
1836         __must_hold(&req->ctx->uring_lock)
1837 {
1838         if (unlikely(req->flags & REQ_F_FAIL)) {
1839                 /*
1840                  * We don't submit, fail them all, for that replace hardlinks
1841                  * with normal links. Extra REQ_F_LINK is tolerated.
1842                  */
1843                 req->flags &= ~REQ_F_HARDLINK;
1844                 req->flags |= REQ_F_LINK;
1845                 io_req_complete_failed(req, req->cqe.res);
1846         } else if (unlikely(req->ctx->drain_active)) {
1847                 io_drain_req(req);
1848         } else {
1849                 int ret = io_req_prep_async(req);
1850
1851                 if (unlikely(ret))
1852                         io_req_complete_failed(req, ret);
1853                 else
1854                         io_queue_iowq(req, NULL);
1855         }
1856 }
1857
1858 /*
1859  * Check SQE restrictions (opcode and flags).
1860  *
1861  * Returns 'true' if SQE is allowed, 'false' otherwise.
1862  */
1863 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
1864                                         struct io_kiocb *req,
1865                                         unsigned int sqe_flags)
1866 {
1867         if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
1868                 return false;
1869
1870         if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
1871             ctx->restrictions.sqe_flags_required)
1872                 return false;
1873
1874         if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
1875                           ctx->restrictions.sqe_flags_required))
1876                 return false;
1877
1878         return true;
1879 }
1880
1881 static void io_init_req_drain(struct io_kiocb *req)
1882 {
1883         struct io_ring_ctx *ctx = req->ctx;
1884         struct io_kiocb *head = ctx->submit_state.link.head;
1885
1886         ctx->drain_active = true;
1887         if (head) {
1888                 /*
1889                  * If we need to drain a request in the middle of a link, drain
1890                  * the head request and the next request/link after the current
1891                  * link. Considering sequential execution of links,
1892                  * REQ_F_IO_DRAIN will be maintained for every request of our
1893                  * link.
1894                  */
1895                 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
1896                 ctx->drain_next = true;
1897         }
1898 }
1899
1900 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
1901                        const struct io_uring_sqe *sqe)
1902         __must_hold(&ctx->uring_lock)
1903 {
1904         const struct io_op_def *def;
1905         unsigned int sqe_flags;
1906         int personality;
1907         u8 opcode;
1908
1909         /* req is partially pre-initialised, see io_preinit_req() */
1910         req->opcode = opcode = READ_ONCE(sqe->opcode);
1911         /* same numerical values with corresponding REQ_F_*, safe to copy */
1912         req->flags = sqe_flags = READ_ONCE(sqe->flags);
1913         req->cqe.user_data = READ_ONCE(sqe->user_data);
1914         req->file = NULL;
1915         req->rsrc_node = NULL;
1916         req->task = current;
1917
1918         if (unlikely(opcode >= IORING_OP_LAST)) {
1919                 req->opcode = 0;
1920                 return -EINVAL;
1921         }
1922         def = &io_op_defs[opcode];
1923         if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
1924                 /* enforce forwards compatibility on users */
1925                 if (sqe_flags & ~SQE_VALID_FLAGS)
1926                         return -EINVAL;
1927                 if (sqe_flags & IOSQE_BUFFER_SELECT) {
1928                         if (!def->buffer_select)
1929                                 return -EOPNOTSUPP;
1930                         req->buf_index = READ_ONCE(sqe->buf_group);
1931                 }
1932                 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
1933                         ctx->drain_disabled = true;
1934                 if (sqe_flags & IOSQE_IO_DRAIN) {
1935                         if (ctx->drain_disabled)
1936                                 return -EOPNOTSUPP;
1937                         io_init_req_drain(req);
1938                 }
1939         }
1940         if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
1941                 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
1942                         return -EACCES;
1943                 /* knock it to the slow queue path, will be drained there */
1944                 if (ctx->drain_active)
1945                         req->flags |= REQ_F_FORCE_ASYNC;
1946                 /* if there is no link, we're at "next" request and need to drain */
1947                 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
1948                         ctx->drain_next = false;
1949                         ctx->drain_active = true;
1950                         req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
1951                 }
1952         }
1953
1954         if (!def->ioprio && sqe->ioprio)
1955                 return -EINVAL;
1956         if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
1957                 return -EINVAL;
1958
1959         if (def->needs_file) {
1960                 struct io_submit_state *state = &ctx->submit_state;
1961
1962                 req->cqe.fd = READ_ONCE(sqe->fd);
1963
1964                 /*
1965                  * Plug now if we have more than 2 IO left after this, and the
1966                  * target is potentially a read/write to block based storage.
1967                  */
1968                 if (state->need_plug && def->plug) {
1969                         state->plug_started = true;
1970                         state->need_plug = false;
1971                         blk_start_plug_nr_ios(&state->plug, state->submit_nr);
1972                 }
1973         }
1974
1975         personality = READ_ONCE(sqe->personality);
1976         if (personality) {
1977                 int ret;
1978
1979                 req->creds = xa_load(&ctx->personalities, personality);
1980                 if (!req->creds)
1981                         return -EINVAL;
1982                 get_cred(req->creds);
1983                 ret = security_uring_override_creds(req->creds);
1984                 if (ret) {
1985                         put_cred(req->creds);
1986                         return ret;
1987                 }
1988                 req->flags |= REQ_F_CREDS;
1989         }
1990
1991         return def->prep(req, sqe);
1992 }
1993
1994 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
1995                                       struct io_kiocb *req, int ret)
1996 {
1997         struct io_ring_ctx *ctx = req->ctx;
1998         struct io_submit_link *link = &ctx->submit_state.link;
1999         struct io_kiocb *head = link->head;
2000
2001         trace_io_uring_req_failed(sqe, req, ret);
2002
2003         /*
2004          * Avoid breaking links in the middle as it renders links with SQPOLL
2005          * unusable. Instead of failing eagerly, continue assembling the link if
2006          * applicable and mark the head with REQ_F_FAIL. The link flushing code
2007          * should find the flag and handle the rest.
2008          */
2009         req_fail_link_node(req, ret);
2010         if (head && !(head->flags & REQ_F_FAIL))
2011                 req_fail_link_node(head, -ECANCELED);
2012
2013         if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2014                 if (head) {
2015                         link->last->link = req;
2016                         link->head = NULL;
2017                         req = head;
2018                 }
2019                 io_queue_sqe_fallback(req);
2020                 return ret;
2021         }
2022
2023         if (head)
2024                 link->last->link = req;
2025         else
2026                 link->head = req;
2027         link->last = req;
2028         return 0;
2029 }
2030
2031 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2032                          const struct io_uring_sqe *sqe)
2033         __must_hold(&ctx->uring_lock)
2034 {
2035         struct io_submit_link *link = &ctx->submit_state.link;
2036         int ret;
2037
2038         ret = io_init_req(ctx, req, sqe);
2039         if (unlikely(ret))
2040                 return io_submit_fail_init(sqe, req, ret);
2041
2042         /* don't need @sqe from now on */
2043         trace_io_uring_submit_sqe(req, true);
2044
2045         /*
2046          * If we already have a head request, queue this one for async
2047          * submittal once the head completes. If we don't have a head but
2048          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2049          * submitted sync once the chain is complete. If none of those
2050          * conditions are true (normal request), then just queue it.
2051          */
2052         if (unlikely(link->head)) {
2053                 ret = io_req_prep_async(req);
2054                 if (unlikely(ret))
2055                         return io_submit_fail_init(sqe, req, ret);
2056
2057                 trace_io_uring_link(req, link->head);
2058                 link->last->link = req;
2059                 link->last = req;
2060
2061                 if (req->flags & IO_REQ_LINK_FLAGS)
2062                         return 0;
2063                 /* last request of the link, flush it */
2064                 req = link->head;
2065                 link->head = NULL;
2066                 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2067                         goto fallback;
2068
2069         } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2070                                           REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2071                 if (req->flags & IO_REQ_LINK_FLAGS) {
2072                         link->head = req;
2073                         link->last = req;
2074                 } else {
2075 fallback:
2076                         io_queue_sqe_fallback(req);
2077                 }
2078                 return 0;
2079         }
2080
2081         io_queue_sqe(req);
2082         return 0;
2083 }
2084
2085 /*
2086  * Batched submission is done, ensure local IO is flushed out.
2087  */
2088 static void io_submit_state_end(struct io_ring_ctx *ctx)
2089 {
2090         struct io_submit_state *state = &ctx->submit_state;
2091
2092         if (unlikely(state->link.head))
2093                 io_queue_sqe_fallback(state->link.head);
2094         /* flush only after queuing links as they can generate completions */
2095         io_submit_flush_completions(ctx);
2096         if (state->plug_started)
2097                 blk_finish_plug(&state->plug);
2098 }
2099
2100 /*
2101  * Start submission side cache.
2102  */
2103 static void io_submit_state_start(struct io_submit_state *state,
2104                                   unsigned int max_ios)
2105 {
2106         state->plug_started = false;
2107         state->need_plug = max_ios > 2;
2108         state->submit_nr = max_ios;
2109         /* set only head, no need to init link_last in advance */
2110         state->link.head = NULL;
2111 }
2112
2113 static void io_commit_sqring(struct io_ring_ctx *ctx)
2114 {
2115         struct io_rings *rings = ctx->rings;
2116
2117         /*
2118          * Ensure any loads from the SQEs are done at this point,
2119          * since once we write the new head, the application could
2120          * write new data to them.
2121          */
2122         smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2123 }
2124
2125 /*
2126  * Fetch an sqe, if one is available. Note this returns a pointer to memory
2127  * that is mapped by userspace. This means that care needs to be taken to
2128  * ensure that reads are stable, as we cannot rely on userspace always
2129  * being a good citizen. If members of the sqe are validated and then later
2130  * used, it's important that those reads are done through READ_ONCE() to
2131  * prevent a re-load down the line.
2132  */
2133 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
2134 {
2135         unsigned head, mask = ctx->sq_entries - 1;
2136         unsigned sq_idx = ctx->cached_sq_head++ & mask;
2137
2138         /*
2139          * The cached sq head (or cq tail) serves two purposes:
2140          *
2141          * 1) allows us to batch the cost of updating the user visible
2142          *    head updates.
2143          * 2) allows the kernel side to track the head on its own, even
2144          *    though the application is the one updating it.
2145          */
2146         head = READ_ONCE(ctx->sq_array[sq_idx]);
2147         if (likely(head < ctx->sq_entries)) {
2148                 /* double index for 128-byte SQEs, twice as long */
2149                 if (ctx->flags & IORING_SETUP_SQE128)
2150                         head <<= 1;
2151                 return &ctx->sq_sqes[head];
2152         }
2153
2154         /* drop invalid entries */
2155         ctx->cq_extra--;
2156         WRITE_ONCE(ctx->rings->sq_dropped,
2157                    READ_ONCE(ctx->rings->sq_dropped) + 1);
2158         return NULL;
2159 }
2160
2161 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2162         __must_hold(&ctx->uring_lock)
2163 {
2164         unsigned int entries = io_sqring_entries(ctx);
2165         unsigned int left;
2166         int ret;
2167
2168         if (unlikely(!entries))
2169                 return 0;
2170         /* make sure SQ entry isn't read before tail */
2171         ret = left = min3(nr, ctx->sq_entries, entries);
2172         io_get_task_refs(left);
2173         io_submit_state_start(&ctx->submit_state, left);
2174
2175         do {
2176                 const struct io_uring_sqe *sqe;
2177                 struct io_kiocb *req;
2178
2179                 if (unlikely(!io_alloc_req_refill(ctx)))
2180                         break;
2181                 req = io_alloc_req(ctx);
2182                 sqe = io_get_sqe(ctx);
2183                 if (unlikely(!sqe)) {
2184                         io_req_add_to_cache(req, ctx);
2185                         break;
2186                 }
2187
2188                 /*
2189                  * Continue submitting even for sqe failure if the
2190                  * ring was setup with IORING_SETUP_SUBMIT_ALL
2191                  */
2192                 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2193                     !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2194                         left--;
2195                         break;
2196                 }
2197         } while (--left);
2198
2199         if (unlikely(left)) {
2200                 ret -= left;
2201                 /* try again if it submitted nothing and can't allocate a req */
2202                 if (!ret && io_req_cache_empty(ctx))
2203                         ret = -EAGAIN;
2204                 current->io_uring->cached_refs += left;
2205         }
2206
2207         io_submit_state_end(ctx);
2208          /* Commit SQ ring head once we've consumed and submitted all SQEs */
2209         io_commit_sqring(ctx);
2210         return ret;
2211 }
2212
2213 struct io_wait_queue {
2214         struct wait_queue_entry wq;
2215         struct io_ring_ctx *ctx;
2216         unsigned cq_tail;
2217         unsigned nr_timeouts;
2218 };
2219
2220 static inline bool io_should_wake(struct io_wait_queue *iowq)
2221 {
2222         struct io_ring_ctx *ctx = iowq->ctx;
2223         int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
2224
2225         /*
2226          * Wake up if we have enough events, or if a timeout occurred since we
2227          * started waiting. For timeouts, we always want to return to userspace,
2228          * regardless of event count.
2229          */
2230         return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2231 }
2232
2233 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2234                             int wake_flags, void *key)
2235 {
2236         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
2237                                                         wq);
2238
2239         /*
2240          * Cannot safely flush overflowed CQEs from here, ensure we wake up
2241          * the task, and the next invocation will do it.
2242          */
2243         if (io_should_wake(iowq) ||
2244             test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
2245                 return autoremove_wake_function(curr, mode, wake_flags, key);
2246         return -1;
2247 }
2248
2249 int io_run_task_work_sig(void)
2250 {
2251         if (io_run_task_work())
2252                 return 1;
2253         if (test_thread_flag(TIF_NOTIFY_SIGNAL))
2254                 return -ERESTARTSYS;
2255         if (task_sigpending(current))
2256                 return -EINTR;
2257         return 0;
2258 }
2259
2260 /* when returns >0, the caller should retry */
2261 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2262                                           struct io_wait_queue *iowq,
2263                                           ktime_t timeout)
2264 {
2265         int ret;
2266         unsigned long check_cq;
2267
2268         /* make sure we run task_work before checking for signals */
2269         ret = io_run_task_work_sig();
2270         if (ret || io_should_wake(iowq))
2271                 return ret;
2272
2273         check_cq = READ_ONCE(ctx->check_cq);
2274         if (unlikely(check_cq)) {
2275                 /* let the caller flush overflows, retry */
2276                 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2277                         return 1;
2278                 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
2279                         return -EBADR;
2280         }
2281         if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
2282                 return -ETIME;
2283         return 1;
2284 }
2285
2286 /*
2287  * Wait until events become available, if we don't already have some. The
2288  * application must reap them itself, as they reside on the shared cq ring.
2289  */
2290 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2291                           const sigset_t __user *sig, size_t sigsz,
2292                           struct __kernel_timespec __user *uts)
2293 {
2294         struct io_wait_queue iowq;
2295         struct io_rings *rings = ctx->rings;
2296         ktime_t timeout = KTIME_MAX;
2297         int ret;
2298
2299         do {
2300                 io_cqring_overflow_flush(ctx);
2301                 if (io_cqring_events(ctx) >= min_events)
2302                         return 0;
2303                 if (!io_run_task_work())
2304                         break;
2305         } while (1);
2306
2307         if (sig) {
2308 #ifdef CONFIG_COMPAT
2309                 if (in_compat_syscall())
2310                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2311                                                       sigsz);
2312                 else
2313 #endif
2314                         ret = set_user_sigmask(sig, sigsz);
2315
2316                 if (ret)
2317                         return ret;
2318         }
2319
2320         if (uts) {
2321                 struct timespec64 ts;
2322
2323                 if (get_timespec64(&ts, uts))
2324                         return -EFAULT;
2325                 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
2326         }
2327
2328         init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2329         iowq.wq.private = current;
2330         INIT_LIST_HEAD(&iowq.wq.entry);
2331         iowq.ctx = ctx;
2332         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2333         iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2334
2335         trace_io_uring_cqring_wait(ctx, min_events);
2336         do {
2337                 /* if we can't even flush overflow, don't wait for more */
2338                 if (!io_cqring_overflow_flush(ctx)) {
2339                         ret = -EBUSY;
2340                         break;
2341                 }
2342                 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2343                                                 TASK_INTERRUPTIBLE);
2344                 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
2345                 cond_resched();
2346         } while (ret > 0);
2347
2348         finish_wait(&ctx->cq_wait, &iowq.wq);
2349         restore_saved_sigmask_unless(ret == -EINTR);
2350
2351         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2352 }
2353
2354 static void io_mem_free(void *ptr)
2355 {
2356         struct page *page;
2357
2358         if (!ptr)
2359                 return;
2360
2361         page = virt_to_head_page(ptr);
2362         if (put_page_testzero(page))
2363                 free_compound_page(page);
2364 }
2365
2366 static void *io_mem_alloc(size_t size)
2367 {
2368         gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
2369
2370         return (void *) __get_free_pages(gfp, get_order(size));
2371 }
2372
2373 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
2374                                 unsigned int cq_entries, size_t *sq_offset)
2375 {
2376         struct io_rings *rings;
2377         size_t off, sq_array_size;
2378
2379         off = struct_size(rings, cqes, cq_entries);
2380         if (off == SIZE_MAX)
2381                 return SIZE_MAX;
2382         if (ctx->flags & IORING_SETUP_CQE32) {
2383                 if (check_shl_overflow(off, 1, &off))
2384                         return SIZE_MAX;
2385         }
2386
2387 #ifdef CONFIG_SMP
2388         off = ALIGN(off, SMP_CACHE_BYTES);
2389         if (off == 0)
2390                 return SIZE_MAX;
2391 #endif
2392
2393         if (sq_offset)
2394                 *sq_offset = off;
2395
2396         sq_array_size = array_size(sizeof(u32), sq_entries);
2397         if (sq_array_size == SIZE_MAX)
2398                 return SIZE_MAX;
2399
2400         if (check_add_overflow(off, sq_array_size, &off))
2401                 return SIZE_MAX;
2402
2403         return off;
2404 }
2405
2406 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
2407                                unsigned int eventfd_async)
2408 {
2409         struct io_ev_fd *ev_fd;
2410         __s32 __user *fds = arg;
2411         int fd;
2412
2413         ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2414                                         lockdep_is_held(&ctx->uring_lock));
2415         if (ev_fd)
2416                 return -EBUSY;
2417
2418         if (copy_from_user(&fd, fds, sizeof(*fds)))
2419                 return -EFAULT;
2420
2421         ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
2422         if (!ev_fd)
2423                 return -ENOMEM;
2424
2425         ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
2426         if (IS_ERR(ev_fd->cq_ev_fd)) {
2427                 int ret = PTR_ERR(ev_fd->cq_ev_fd);
2428                 kfree(ev_fd);
2429                 return ret;
2430         }
2431         ev_fd->eventfd_async = eventfd_async;
2432         ctx->has_evfd = true;
2433         rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
2434         return 0;
2435 }
2436
2437 static void io_eventfd_put(struct rcu_head *rcu)
2438 {
2439         struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
2440
2441         eventfd_ctx_put(ev_fd->cq_ev_fd);
2442         kfree(ev_fd);
2443 }
2444
2445 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
2446 {
2447         struct io_ev_fd *ev_fd;
2448
2449         ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2450                                         lockdep_is_held(&ctx->uring_lock));
2451         if (ev_fd) {
2452                 ctx->has_evfd = false;
2453                 rcu_assign_pointer(ctx->io_ev_fd, NULL);
2454                 call_rcu(&ev_fd->rcu, io_eventfd_put);
2455                 return 0;
2456         }
2457
2458         return -ENXIO;
2459 }
2460
2461 static void io_req_caches_free(struct io_ring_ctx *ctx)
2462 {
2463         struct io_submit_state *state = &ctx->submit_state;
2464         int nr = 0;
2465
2466         mutex_lock(&ctx->uring_lock);
2467         io_flush_cached_locked_reqs(ctx, state);
2468
2469         while (!io_req_cache_empty(ctx)) {
2470                 struct io_wq_work_node *node;
2471                 struct io_kiocb *req;
2472
2473                 node = wq_stack_extract(&state->free_list);
2474                 req = container_of(node, struct io_kiocb, comp_list);
2475                 kmem_cache_free(req_cachep, req);
2476                 nr++;
2477         }
2478         if (nr)
2479                 percpu_ref_put_many(&ctx->refs, nr);
2480         mutex_unlock(&ctx->uring_lock);
2481 }
2482
2483 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
2484 {
2485         struct async_poll *apoll;
2486
2487         while (!list_empty(&ctx->apoll_cache)) {
2488                 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
2489                                                 poll.wait.entry);
2490                 list_del(&apoll->poll.wait.entry);
2491                 kfree(apoll);
2492         }
2493 }
2494
2495 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2496 {
2497         io_sq_thread_finish(ctx);
2498
2499         if (ctx->mm_account) {
2500                 mmdrop(ctx->mm_account);
2501                 ctx->mm_account = NULL;
2502         }
2503
2504         io_rsrc_refs_drop(ctx);
2505         /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
2506         io_wait_rsrc_data(ctx->buf_data);
2507         io_wait_rsrc_data(ctx->file_data);
2508
2509         mutex_lock(&ctx->uring_lock);
2510         if (ctx->buf_data)
2511                 __io_sqe_buffers_unregister(ctx);
2512         if (ctx->file_data)
2513                 __io_sqe_files_unregister(ctx);
2514         if (ctx->rings)
2515                 __io_cqring_overflow_flush(ctx, true);
2516         io_eventfd_unregister(ctx);
2517         io_flush_apoll_cache(ctx);
2518         mutex_unlock(&ctx->uring_lock);
2519         io_destroy_buffers(ctx);
2520         if (ctx->sq_creds)
2521                 put_cred(ctx->sq_creds);
2522         if (ctx->submitter_task)
2523                 put_task_struct(ctx->submitter_task);
2524
2525         /* there are no registered resources left, nobody uses it */
2526         if (ctx->rsrc_node)
2527                 io_rsrc_node_destroy(ctx->rsrc_node);
2528         if (ctx->rsrc_backup_node)
2529                 io_rsrc_node_destroy(ctx->rsrc_backup_node);
2530         flush_delayed_work(&ctx->rsrc_put_work);
2531         flush_delayed_work(&ctx->fallback_work);
2532
2533         WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
2534         WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
2535
2536 #if defined(CONFIG_UNIX)
2537         if (ctx->ring_sock) {
2538                 ctx->ring_sock->file = NULL; /* so that iput() is called */
2539                 sock_release(ctx->ring_sock);
2540         }
2541 #endif
2542         WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2543
2544         io_mem_free(ctx->rings);
2545         io_mem_free(ctx->sq_sqes);
2546
2547         percpu_ref_exit(&ctx->refs);
2548         free_uid(ctx->user);
2549         io_req_caches_free(ctx);
2550         if (ctx->hash_map)
2551                 io_wq_put_hash(ctx->hash_map);
2552         kfree(ctx->cancel_table.hbs);
2553         kfree(ctx->cancel_table_locked.hbs);
2554         kfree(ctx->dummy_ubuf);
2555         kfree(ctx->io_bl);
2556         xa_destroy(&ctx->io_bl_xa);
2557         kfree(ctx);
2558 }
2559
2560 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2561 {
2562         struct io_ring_ctx *ctx = file->private_data;
2563         __poll_t mask = 0;
2564
2565         poll_wait(file, &ctx->cq_wait, wait);
2566         /*
2567          * synchronizes with barrier from wq_has_sleeper call in
2568          * io_commit_cqring
2569          */
2570         smp_rmb();
2571         if (!io_sqring_full(ctx))
2572                 mask |= EPOLLOUT | EPOLLWRNORM;
2573
2574         /*
2575          * Don't flush cqring overflow list here, just do a simple check.
2576          * Otherwise there could possible be ABBA deadlock:
2577          *      CPU0                    CPU1
2578          *      ----                    ----
2579          * lock(&ctx->uring_lock);
2580          *                              lock(&ep->mtx);
2581          *                              lock(&ctx->uring_lock);
2582          * lock(&ep->mtx);
2583          *
2584          * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
2585          * pushs them to do the flush.
2586          */
2587         if (io_cqring_events(ctx) ||
2588             test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
2589                 mask |= EPOLLIN | EPOLLRDNORM;
2590
2591         return mask;
2592 }
2593
2594 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
2595 {
2596         const struct cred *creds;
2597
2598         creds = xa_erase(&ctx->personalities, id);
2599         if (creds) {
2600                 put_cred(creds);
2601                 return 0;
2602         }
2603
2604         return -EINVAL;
2605 }
2606
2607 struct io_tctx_exit {
2608         struct callback_head            task_work;
2609         struct completion               completion;
2610         struct io_ring_ctx              *ctx;
2611 };
2612
2613 static __cold void io_tctx_exit_cb(struct callback_head *cb)
2614 {
2615         struct io_uring_task *tctx = current->io_uring;
2616         struct io_tctx_exit *work;
2617
2618         work = container_of(cb, struct io_tctx_exit, task_work);
2619         /*
2620          * When @in_idle, we're in cancellation and it's racy to remove the
2621          * node. It'll be removed by the end of cancellation, just ignore it.
2622          */
2623         if (!atomic_read(&tctx->in_idle))
2624                 io_uring_del_tctx_node((unsigned long)work->ctx);
2625         complete(&work->completion);
2626 }
2627
2628 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
2629 {
2630         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2631
2632         return req->ctx == data;
2633 }
2634
2635 static __cold void io_ring_exit_work(struct work_struct *work)
2636 {
2637         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
2638         unsigned long timeout = jiffies + HZ * 60 * 5;
2639         unsigned long interval = HZ / 20;
2640         struct io_tctx_exit exit;
2641         struct io_tctx_node *node;
2642         int ret;
2643
2644         /*
2645          * If we're doing polled IO and end up having requests being
2646          * submitted async (out-of-line), then completions can come in while
2647          * we're waiting for refs to drop. We need to reap these manually,
2648          * as nobody else will be looking for them.
2649          */
2650         do {
2651                 io_uring_try_cancel_requests(ctx, NULL, true);
2652                 if (ctx->sq_data) {
2653                         struct io_sq_data *sqd = ctx->sq_data;
2654                         struct task_struct *tsk;
2655
2656                         io_sq_thread_park(sqd);
2657                         tsk = sqd->thread;
2658                         if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
2659                                 io_wq_cancel_cb(tsk->io_uring->io_wq,
2660                                                 io_cancel_ctx_cb, ctx, true);
2661                         io_sq_thread_unpark(sqd);
2662                 }
2663
2664                 io_req_caches_free(ctx);
2665
2666                 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
2667                         /* there is little hope left, don't run it too often */
2668                         interval = HZ * 60;
2669                 }
2670         } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
2671
2672         init_completion(&exit.completion);
2673         init_task_work(&exit.task_work, io_tctx_exit_cb);
2674         exit.ctx = ctx;
2675         /*
2676          * Some may use context even when all refs and requests have been put,
2677          * and they are free to do so while still holding uring_lock or
2678          * completion_lock, see io_req_task_submit(). Apart from other work,
2679          * this lock/unlock section also waits them to finish.
2680          */
2681         mutex_lock(&ctx->uring_lock);
2682         while (!list_empty(&ctx->tctx_list)) {
2683                 WARN_ON_ONCE(time_after(jiffies, timeout));
2684
2685                 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
2686                                         ctx_node);
2687                 /* don't spin on a single task if cancellation failed */
2688                 list_rotate_left(&ctx->tctx_list);
2689                 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
2690                 if (WARN_ON_ONCE(ret))
2691                         continue;
2692
2693                 mutex_unlock(&ctx->uring_lock);
2694                 wait_for_completion(&exit.completion);
2695                 mutex_lock(&ctx->uring_lock);
2696         }
2697         mutex_unlock(&ctx->uring_lock);
2698         spin_lock(&ctx->completion_lock);
2699         spin_unlock(&ctx->completion_lock);
2700
2701         io_ring_ctx_free(ctx);
2702 }
2703
2704 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2705 {
2706         unsigned long index;
2707         struct creds *creds;
2708
2709         mutex_lock(&ctx->uring_lock);
2710         percpu_ref_kill(&ctx->refs);
2711         if (ctx->rings)
2712                 __io_cqring_overflow_flush(ctx, true);
2713         xa_for_each(&ctx->personalities, index, creds)
2714                 io_unregister_personality(ctx, index);
2715         if (ctx->rings)
2716                 io_poll_remove_all(ctx, NULL, true);
2717         mutex_unlock(&ctx->uring_lock);
2718
2719         /* failed during ring init, it couldn't have issued any requests */
2720         if (ctx->rings) {
2721                 io_kill_timeouts(ctx, NULL, true);
2722                 /* if we failed setting up the ctx, we might not have any rings */
2723                 io_iopoll_try_reap_events(ctx);
2724         }
2725
2726         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
2727         /*
2728          * Use system_unbound_wq to avoid spawning tons of event kworkers
2729          * if we're exiting a ton of rings at the same time. It just adds
2730          * noise and overhead, there's no discernable change in runtime
2731          * over using system_wq.
2732          */
2733         queue_work(system_unbound_wq, &ctx->exit_work);
2734 }
2735
2736 static int io_uring_release(struct inode *inode, struct file *file)
2737 {
2738         struct io_ring_ctx *ctx = file->private_data;
2739
2740         file->private_data = NULL;
2741         io_ring_ctx_wait_and_kill(ctx);
2742         return 0;
2743 }
2744
2745 struct io_task_cancel {
2746         struct task_struct *task;
2747         bool all;
2748 };
2749
2750 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
2751 {
2752         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2753         struct io_task_cancel *cancel = data;
2754
2755         return io_match_task_safe(req, cancel->task, cancel->all);
2756 }
2757
2758 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
2759                                          struct task_struct *task,
2760                                          bool cancel_all)
2761 {
2762         struct io_defer_entry *de;
2763         LIST_HEAD(list);
2764
2765         spin_lock(&ctx->completion_lock);
2766         list_for_each_entry_reverse(de, &ctx->defer_list, list) {
2767                 if (io_match_task_safe(de->req, task, cancel_all)) {
2768                         list_cut_position(&list, &ctx->defer_list, &de->list);
2769                         break;
2770                 }
2771         }
2772         spin_unlock(&ctx->completion_lock);
2773         if (list_empty(&list))
2774                 return false;
2775
2776         while (!list_empty(&list)) {
2777                 de = list_first_entry(&list, struct io_defer_entry, list);
2778                 list_del_init(&de->list);
2779                 io_req_complete_failed(de->req, -ECANCELED);
2780                 kfree(de);
2781         }
2782         return true;
2783 }
2784
2785 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
2786 {
2787         struct io_tctx_node *node;
2788         enum io_wq_cancel cret;
2789         bool ret = false;
2790
2791         mutex_lock(&ctx->uring_lock);
2792         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
2793                 struct io_uring_task *tctx = node->task->io_uring;
2794
2795                 /*
2796                  * io_wq will stay alive while we hold uring_lock, because it's
2797                  * killed after ctx nodes, which requires to take the lock.
2798                  */
2799                 if (!tctx || !tctx->io_wq)
2800                         continue;
2801                 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
2802                 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
2803         }
2804         mutex_unlock(&ctx->uring_lock);
2805
2806         return ret;
2807 }
2808
2809 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
2810                                                 struct task_struct *task,
2811                                                 bool cancel_all)
2812 {
2813         struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
2814         struct io_uring_task *tctx = task ? task->io_uring : NULL;
2815
2816         /* failed during ring init, it couldn't have issued any requests */
2817         if (!ctx->rings)
2818                 return;
2819
2820         while (1) {
2821                 enum io_wq_cancel cret;
2822                 bool ret = false;
2823
2824                 if (!task) {
2825                         ret |= io_uring_try_cancel_iowq(ctx);
2826                 } else if (tctx && tctx->io_wq) {
2827                         /*
2828                          * Cancels requests of all rings, not only @ctx, but
2829                          * it's fine as the task is in exit/exec.
2830                          */
2831                         cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
2832                                                &cancel, true);
2833                         ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
2834                 }
2835
2836                 /* SQPOLL thread does its own polling */
2837                 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
2838                     (ctx->sq_data && ctx->sq_data->thread == current)) {
2839                         while (!wq_list_empty(&ctx->iopoll_list)) {
2840                                 io_iopoll_try_reap_events(ctx);
2841                                 ret = true;
2842                         }
2843                 }
2844
2845                 ret |= io_cancel_defer_files(ctx, task, cancel_all);
2846                 mutex_lock(&ctx->uring_lock);
2847                 ret |= io_poll_remove_all(ctx, task, cancel_all);
2848                 mutex_unlock(&ctx->uring_lock);
2849                 ret |= io_kill_timeouts(ctx, task, cancel_all);
2850                 if (task)
2851                         ret |= io_run_task_work();
2852                 if (!ret)
2853                         break;
2854                 cond_resched();
2855         }
2856 }
2857
2858 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
2859 {
2860         if (tracked)
2861                 return atomic_read(&tctx->inflight_tracked);
2862         return percpu_counter_sum(&tctx->inflight);
2863 }
2864
2865 /*
2866  * Find any io_uring ctx that this task has registered or done IO on, and cancel
2867  * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
2868  */
2869 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
2870 {
2871         struct io_uring_task *tctx = current->io_uring;
2872         struct io_ring_ctx *ctx;
2873         s64 inflight;
2874         DEFINE_WAIT(wait);
2875
2876         WARN_ON_ONCE(sqd && sqd->thread != current);
2877
2878         if (!current->io_uring)
2879                 return;
2880         if (tctx->io_wq)
2881                 io_wq_exit_start(tctx->io_wq);
2882
2883         atomic_inc(&tctx->in_idle);
2884         do {
2885                 io_uring_drop_tctx_refs(current);
2886                 /* read completions before cancelations */
2887                 inflight = tctx_inflight(tctx, !cancel_all);
2888                 if (!inflight)
2889                         break;
2890
2891                 if (!sqd) {
2892                         struct io_tctx_node *node;
2893                         unsigned long index;
2894
2895                         xa_for_each(&tctx->xa, index, node) {
2896                                 /* sqpoll task will cancel all its requests */
2897                                 if (node->ctx->sq_data)
2898                                         continue;
2899                                 io_uring_try_cancel_requests(node->ctx, current,
2900                                                              cancel_all);
2901                         }
2902                 } else {
2903                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
2904                                 io_uring_try_cancel_requests(ctx, current,
2905                                                              cancel_all);
2906                 }
2907
2908                 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
2909                 io_run_task_work();
2910                 io_uring_drop_tctx_refs(current);
2911
2912                 /*
2913                  * If we've seen completions, retry without waiting. This
2914                  * avoids a race where a completion comes in before we did
2915                  * prepare_to_wait().
2916                  */
2917                 if (inflight == tctx_inflight(tctx, !cancel_all))
2918                         schedule();
2919                 finish_wait(&tctx->wait, &wait);
2920         } while (1);
2921
2922         io_uring_clean_tctx(tctx);
2923         if (cancel_all) {
2924                 /*
2925                  * We shouldn't run task_works after cancel, so just leave
2926                  * ->in_idle set for normal exit.
2927                  */
2928                 atomic_dec(&tctx->in_idle);
2929                 /* for exec all current's requests should be gone, kill tctx */
2930                 __io_uring_free(current);
2931         }
2932 }
2933
2934 void __io_uring_cancel(bool cancel_all)
2935 {
2936         io_uring_cancel_generic(cancel_all, NULL);
2937 }
2938
2939 static void *io_uring_validate_mmap_request(struct file *file,
2940                                             loff_t pgoff, size_t sz)
2941 {
2942         struct io_ring_ctx *ctx = file->private_data;
2943         loff_t offset = pgoff << PAGE_SHIFT;
2944         struct page *page;
2945         void *ptr;
2946
2947         switch (offset) {
2948         case IORING_OFF_SQ_RING:
2949         case IORING_OFF_CQ_RING:
2950                 ptr = ctx->rings;
2951                 break;
2952         case IORING_OFF_SQES:
2953                 ptr = ctx->sq_sqes;
2954                 break;
2955         default:
2956                 return ERR_PTR(-EINVAL);
2957         }
2958
2959         page = virt_to_head_page(ptr);
2960         if (sz > page_size(page))
2961                 return ERR_PTR(-EINVAL);
2962
2963         return ptr;
2964 }
2965
2966 #ifdef CONFIG_MMU
2967
2968 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2969 {
2970         size_t sz = vma->vm_end - vma->vm_start;
2971         unsigned long pfn;
2972         void *ptr;
2973
2974         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
2975         if (IS_ERR(ptr))
2976                 return PTR_ERR(ptr);
2977
2978         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
2979         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2980 }
2981
2982 #else /* !CONFIG_MMU */
2983
2984 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2985 {
2986         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
2987 }
2988
2989 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
2990 {
2991         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
2992 }
2993
2994 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
2995         unsigned long addr, unsigned long len,
2996         unsigned long pgoff, unsigned long flags)
2997 {
2998         void *ptr;
2999
3000         ptr = io_uring_validate_mmap_request(file, pgoff, len);
3001         if (IS_ERR(ptr))
3002                 return PTR_ERR(ptr);
3003
3004         return (unsigned long) ptr;
3005 }
3006
3007 #endif /* !CONFIG_MMU */
3008
3009 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
3010 {
3011         if (flags & IORING_ENTER_EXT_ARG) {
3012                 struct io_uring_getevents_arg arg;
3013
3014                 if (argsz != sizeof(arg))
3015                         return -EINVAL;
3016                 if (copy_from_user(&arg, argp, sizeof(arg)))
3017                         return -EFAULT;
3018         }
3019         return 0;
3020 }
3021
3022 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
3023                           struct __kernel_timespec __user **ts,
3024                           const sigset_t __user **sig)
3025 {
3026         struct io_uring_getevents_arg arg;
3027
3028         /*
3029          * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3030          * is just a pointer to the sigset_t.
3031          */
3032         if (!(flags & IORING_ENTER_EXT_ARG)) {
3033                 *sig = (const sigset_t __user *) argp;
3034                 *ts = NULL;
3035                 return 0;
3036         }
3037
3038         /*
3039          * EXT_ARG is set - ensure we agree on the size of it and copy in our
3040          * timespec and sigset_t pointers if good.
3041          */
3042         if (*argsz != sizeof(arg))
3043                 return -EINVAL;
3044         if (copy_from_user(&arg, argp, sizeof(arg)))
3045                 return -EFAULT;
3046         if (arg.pad)
3047                 return -EINVAL;
3048         *sig = u64_to_user_ptr(arg.sigmask);
3049         *argsz = arg.sigmask_sz;
3050         *ts = u64_to_user_ptr(arg.ts);
3051         return 0;
3052 }
3053
3054 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3055                 u32, min_complete, u32, flags, const void __user *, argp,
3056                 size_t, argsz)
3057 {
3058         struct io_ring_ctx *ctx;
3059         struct fd f;
3060         long ret;
3061
3062         io_run_task_work();
3063
3064         if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
3065                                IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3066                                IORING_ENTER_REGISTERED_RING)))
3067                 return -EINVAL;
3068
3069         /*
3070          * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3071          * need only dereference our task private array to find it.
3072          */
3073         if (flags & IORING_ENTER_REGISTERED_RING) {
3074                 struct io_uring_task *tctx = current->io_uring;
3075
3076                 if (!tctx || fd >= IO_RINGFD_REG_MAX)
3077                         return -EINVAL;
3078                 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
3079                 f.file = tctx->registered_rings[fd];
3080                 f.flags = 0;
3081         } else {
3082                 f = fdget(fd);
3083         }
3084
3085         if (unlikely(!f.file))
3086                 return -EBADF;
3087
3088         ret = -EOPNOTSUPP;
3089         if (unlikely(!io_is_uring_fops(f.file)))
3090                 goto out_fput;
3091
3092         ret = -ENXIO;
3093         ctx = f.file->private_data;
3094         if (unlikely(!percpu_ref_tryget(&ctx->refs)))
3095                 goto out_fput;
3096
3097         ret = -EBADFD;
3098         if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
3099                 goto out;
3100
3101         /*
3102          * For SQ polling, the thread will do all submissions and completions.
3103          * Just return the requested submit count, and wake the thread if
3104          * we were asked to.
3105          */
3106         ret = 0;
3107         if (ctx->flags & IORING_SETUP_SQPOLL) {
3108                 io_cqring_overflow_flush(ctx);
3109
3110                 if (unlikely(ctx->sq_data->thread == NULL)) {
3111                         ret = -EOWNERDEAD;
3112                         goto out;
3113                 }
3114                 if (flags & IORING_ENTER_SQ_WAKEUP)
3115                         wake_up(&ctx->sq_data->wait);
3116                 if (flags & IORING_ENTER_SQ_WAIT) {
3117                         ret = io_sqpoll_wait_sq(ctx);
3118                         if (ret)
3119                                 goto out;
3120                 }
3121                 ret = to_submit;
3122         } else if (to_submit) {
3123                 ret = io_uring_add_tctx_node(ctx);
3124                 if (unlikely(ret))
3125                         goto out;
3126
3127                 mutex_lock(&ctx->uring_lock);
3128                 ret = io_submit_sqes(ctx, to_submit);
3129                 if (ret != to_submit) {
3130                         mutex_unlock(&ctx->uring_lock);
3131                         goto out;
3132                 }
3133                 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
3134                         goto iopoll_locked;
3135                 mutex_unlock(&ctx->uring_lock);
3136         }
3137         if (flags & IORING_ENTER_GETEVENTS) {
3138                 int ret2;
3139                 if (ctx->syscall_iopoll) {
3140                         /*
3141                          * We disallow the app entering submit/complete with
3142                          * polling, but we still need to lock the ring to
3143                          * prevent racing with polled issue that got punted to
3144                          * a workqueue.
3145                          */
3146                         mutex_lock(&ctx->uring_lock);
3147 iopoll_locked:
3148                         ret2 = io_validate_ext_arg(flags, argp, argsz);
3149                         if (likely(!ret2)) {
3150                                 min_complete = min(min_complete,
3151                                                    ctx->cq_entries);
3152                                 ret2 = io_iopoll_check(ctx, min_complete);
3153                         }
3154                         mutex_unlock(&ctx->uring_lock);
3155                 } else {
3156                         const sigset_t __user *sig;
3157                         struct __kernel_timespec __user *ts;
3158
3159                         ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
3160                         if (likely(!ret2)) {
3161                                 min_complete = min(min_complete,
3162                                                    ctx->cq_entries);
3163                                 ret2 = io_cqring_wait(ctx, min_complete, sig,
3164                                                       argsz, ts);
3165                         }
3166                 }
3167
3168                 if (!ret) {
3169                         ret = ret2;
3170
3171                         /*
3172                          * EBADR indicates that one or more CQE were dropped.
3173                          * Once the user has been informed we can clear the bit
3174                          * as they are obviously ok with those drops.
3175                          */
3176                         if (unlikely(ret2 == -EBADR))
3177                                 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3178                                           &ctx->check_cq);
3179                 }
3180         }
3181
3182 out:
3183         percpu_ref_put(&ctx->refs);
3184 out_fput:
3185         fdput(f);
3186         return ret;
3187 }
3188
3189 static const struct file_operations io_uring_fops = {
3190         .release        = io_uring_release,
3191         .mmap           = io_uring_mmap,
3192 #ifndef CONFIG_MMU
3193         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
3194         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
3195 #endif
3196         .poll           = io_uring_poll,
3197 #ifdef CONFIG_PROC_FS
3198         .show_fdinfo    = io_uring_show_fdinfo,
3199 #endif
3200 };
3201
3202 bool io_is_uring_fops(struct file *file)
3203 {
3204         return file->f_op == &io_uring_fops;
3205 }
3206
3207 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3208                                          struct io_uring_params *p)
3209 {
3210         struct io_rings *rings;
3211         size_t size, sq_array_offset;
3212
3213         /* make sure these are sane, as we already accounted them */
3214         ctx->sq_entries = p->sq_entries;
3215         ctx->cq_entries = p->cq_entries;
3216
3217         size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
3218         if (size == SIZE_MAX)
3219                 return -EOVERFLOW;
3220
3221         rings = io_mem_alloc(size);
3222         if (!rings)
3223                 return -ENOMEM;
3224
3225         ctx->rings = rings;
3226         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3227         rings->sq_ring_mask = p->sq_entries - 1;
3228         rings->cq_ring_mask = p->cq_entries - 1;
3229         rings->sq_ring_entries = p->sq_entries;
3230         rings->cq_ring_entries = p->cq_entries;
3231
3232         if (p->flags & IORING_SETUP_SQE128)
3233                 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3234         else
3235                 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3236         if (size == SIZE_MAX) {
3237                 io_mem_free(ctx->rings);
3238                 ctx->rings = NULL;
3239                 return -EOVERFLOW;
3240         }
3241
3242         ctx->sq_sqes = io_mem_alloc(size);
3243         if (!ctx->sq_sqes) {
3244                 io_mem_free(ctx->rings);
3245                 ctx->rings = NULL;
3246                 return -ENOMEM;
3247         }
3248
3249         return 0;
3250 }
3251
3252 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
3253 {
3254         int ret, fd;
3255
3256         fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3257         if (fd < 0)
3258                 return fd;
3259
3260         ret = __io_uring_add_tctx_node(ctx, false);
3261         if (ret) {
3262                 put_unused_fd(fd);
3263                 return ret;
3264         }
3265         fd_install(fd, file);
3266         return fd;
3267 }
3268
3269 /*
3270  * Allocate an anonymous fd, this is what constitutes the application
3271  * visible backing of an io_uring instance. The application mmaps this
3272  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3273  * we have to tie this fd to a socket for file garbage collection purposes.
3274  */
3275 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
3276 {
3277         struct file *file;
3278 #if defined(CONFIG_UNIX)
3279         int ret;
3280
3281         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3282                                 &ctx->ring_sock);
3283         if (ret)
3284                 return ERR_PTR(ret);
3285 #endif
3286
3287         file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
3288                                          O_RDWR | O_CLOEXEC, NULL);
3289 #if defined(CONFIG_UNIX)
3290         if (IS_ERR(file)) {
3291                 sock_release(ctx->ring_sock);
3292                 ctx->ring_sock = NULL;
3293         } else {
3294                 ctx->ring_sock->file = file;
3295         }
3296 #endif
3297         return file;
3298 }
3299
3300 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3301                                   struct io_uring_params __user *params)
3302 {
3303         struct io_ring_ctx *ctx;
3304         struct file *file;
3305         int ret;
3306
3307         if (!entries)
3308                 return -EINVAL;
3309         if (entries > IORING_MAX_ENTRIES) {
3310                 if (!(p->flags & IORING_SETUP_CLAMP))
3311                         return -EINVAL;
3312                 entries = IORING_MAX_ENTRIES;
3313         }
3314
3315         /*
3316          * Use twice as many entries for the CQ ring. It's possible for the
3317          * application to drive a higher depth than the size of the SQ ring,
3318          * since the sqes are only used at submission time. This allows for
3319          * some flexibility in overcommitting a bit. If the application has
3320          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3321          * of CQ ring entries manually.
3322          */
3323         p->sq_entries = roundup_pow_of_two(entries);
3324         if (p->flags & IORING_SETUP_CQSIZE) {
3325                 /*
3326                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
3327                  * to a power-of-two, if it isn't already. We do NOT impose
3328                  * any cq vs sq ring sizing.
3329                  */
3330                 if (!p->cq_entries)
3331                         return -EINVAL;
3332                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3333                         if (!(p->flags & IORING_SETUP_CLAMP))
3334                                 return -EINVAL;
3335                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
3336                 }
3337                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
3338                 if (p->cq_entries < p->sq_entries)
3339                         return -EINVAL;
3340         } else {
3341                 p->cq_entries = 2 * p->sq_entries;
3342         }
3343
3344         ctx = io_ring_ctx_alloc(p);
3345         if (!ctx)
3346                 return -ENOMEM;
3347
3348         /*
3349          * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3350          * space applications don't need to do io completion events
3351          * polling again, they can rely on io_sq_thread to do polling
3352          * work, which can reduce cpu usage and uring_lock contention.
3353          */
3354         if (ctx->flags & IORING_SETUP_IOPOLL &&
3355             !(ctx->flags & IORING_SETUP_SQPOLL))
3356                 ctx->syscall_iopoll = 1;
3357
3358         ctx->compat = in_compat_syscall();
3359         if (!capable(CAP_IPC_LOCK))
3360                 ctx->user = get_uid(current_user());
3361
3362         /*
3363          * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3364          * COOP_TASKRUN is set, then IPIs are never needed by the app.
3365          */
3366         ret = -EINVAL;
3367         if (ctx->flags & IORING_SETUP_SQPOLL) {
3368                 /* IPI related flags don't make sense with SQPOLL */
3369                 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
3370                                   IORING_SETUP_TASKRUN_FLAG))
3371                         goto err;
3372                 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3373         } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
3374                 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3375         } else {
3376                 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
3377                         goto err;
3378                 ctx->notify_method = TWA_SIGNAL;
3379         }
3380
3381         /*
3382          * This is just grabbed for accounting purposes. When a process exits,
3383          * the mm is exited and dropped before the files, hence we need to hang
3384          * on to this mm purely for the purposes of being able to unaccount
3385          * memory (locked/pinned vm). It's not used for anything else.
3386          */
3387         mmgrab(current->mm);
3388         ctx->mm_account = current->mm;
3389
3390         ret = io_allocate_scq_urings(ctx, p);
3391         if (ret)
3392                 goto err;
3393
3394         ret = io_sq_offload_create(ctx, p);
3395         if (ret)
3396                 goto err;
3397         /* always set a rsrc node */
3398         ret = io_rsrc_node_switch_start(ctx);
3399         if (ret)
3400                 goto err;
3401         io_rsrc_node_switch(ctx, NULL);
3402
3403         memset(&p->sq_off, 0, sizeof(p->sq_off));
3404         p->sq_off.head = offsetof(struct io_rings, sq.head);
3405         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3406         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3407         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3408         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3409         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3410         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3411
3412         memset(&p->cq_off, 0, sizeof(p->cq_off));
3413         p->cq_off.head = offsetof(struct io_rings, cq.head);
3414         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3415         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3416         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3417         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3418         p->cq_off.cqes = offsetof(struct io_rings, cqes);
3419         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
3420
3421         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
3422                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
3423                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
3424                         IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
3425                         IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
3426                         IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
3427                         IORING_FEAT_LINKED_FILE;
3428
3429         if (copy_to_user(params, p, sizeof(*p))) {
3430                 ret = -EFAULT;
3431                 goto err;
3432         }
3433
3434         file = io_uring_get_file(ctx);
3435         if (IS_ERR(file)) {
3436                 ret = PTR_ERR(file);
3437                 goto err;
3438         }
3439
3440         /*
3441          * Install ring fd as the very last thing, so we don't risk someone
3442          * having closed it before we finish setup
3443          */
3444         ret = io_uring_install_fd(ctx, file);
3445         if (ret < 0) {
3446                 /* fput will clean it up */
3447                 fput(file);
3448                 return ret;
3449         }
3450
3451         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
3452         return ret;
3453 err:
3454         io_ring_ctx_wait_and_kill(ctx);
3455         return ret;
3456 }
3457
3458 /*
3459  * Sets up an aio uring context, and returns the fd. Applications asks for a
3460  * ring size, we return the actual sq/cq ring sizes (among other things) in the
3461  * params structure passed in.
3462  */
3463 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3464 {
3465         struct io_uring_params p;
3466         int i;
3467
3468         if (copy_from_user(&p, params, sizeof(p)))
3469                 return -EFAULT;
3470         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3471                 if (p.resv[i])
3472                         return -EINVAL;
3473         }
3474
3475         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3476                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
3477                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
3478                         IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
3479                         IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
3480                         IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
3481                         IORING_SETUP_SINGLE_ISSUER))
3482                 return -EINVAL;
3483
3484         return io_uring_create(entries, &p, params);
3485 }
3486
3487 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3488                 struct io_uring_params __user *, params)
3489 {
3490         return io_uring_setup(entries, params);
3491 }
3492
3493 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
3494                            unsigned nr_args)
3495 {
3496         struct io_uring_probe *p;
3497         size_t size;
3498         int i, ret;
3499
3500         size = struct_size(p, ops, nr_args);
3501         if (size == SIZE_MAX)
3502                 return -EOVERFLOW;
3503         p = kzalloc(size, GFP_KERNEL);
3504         if (!p)
3505                 return -ENOMEM;
3506
3507         ret = -EFAULT;
3508         if (copy_from_user(p, arg, size))
3509                 goto out;
3510         ret = -EINVAL;
3511         if (memchr_inv(p, 0, size))
3512                 goto out;
3513
3514         p->last_op = IORING_OP_LAST - 1;
3515         if (nr_args > IORING_OP_LAST)
3516                 nr_args = IORING_OP_LAST;
3517
3518         for (i = 0; i < nr_args; i++) {
3519                 p->ops[i].op = i;
3520                 if (!io_op_defs[i].not_supported)
3521                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
3522         }
3523         p->ops_len = i;
3524
3525         ret = 0;
3526         if (copy_to_user(arg, p, size))
3527                 ret = -EFAULT;
3528 out:
3529         kfree(p);
3530         return ret;
3531 }
3532
3533 static int io_register_personality(struct io_ring_ctx *ctx)
3534 {
3535         const struct cred *creds;
3536         u32 id;
3537         int ret;
3538
3539         creds = get_current_cred();
3540
3541         ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
3542                         XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
3543         if (ret < 0) {
3544                 put_cred(creds);
3545                 return ret;
3546         }
3547         return id;
3548 }
3549
3550 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
3551                                            void __user *arg, unsigned int nr_args)
3552 {
3553         struct io_uring_restriction *res;
3554         size_t size;
3555         int i, ret;
3556
3557         /* Restrictions allowed only if rings started disabled */
3558         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
3559                 return -EBADFD;
3560
3561         /* We allow only a single restrictions registration */
3562         if (ctx->restrictions.registered)
3563                 return -EBUSY;
3564
3565         if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
3566                 return -EINVAL;
3567
3568         size = array_size(nr_args, sizeof(*res));
3569         if (size == SIZE_MAX)
3570                 return -EOVERFLOW;
3571
3572         res = memdup_user(arg, size);
3573         if (IS_ERR(res))
3574                 return PTR_ERR(res);
3575
3576         ret = 0;
3577
3578         for (i = 0; i < nr_args; i++) {
3579                 switch (res[i].opcode) {
3580                 case IORING_RESTRICTION_REGISTER_OP:
3581                         if (res[i].register_op >= IORING_REGISTER_LAST) {
3582                                 ret = -EINVAL;
3583                                 goto out;
3584                         }
3585
3586                         __set_bit(res[i].register_op,
3587                                   ctx->restrictions.register_op);
3588                         break;
3589                 case IORING_RESTRICTION_SQE_OP:
3590                         if (res[i].sqe_op >= IORING_OP_LAST) {
3591                                 ret = -EINVAL;
3592                                 goto out;
3593                         }
3594
3595                         __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
3596                         break;
3597                 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
3598                         ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
3599                         break;
3600                 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
3601                         ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
3602                         break;
3603                 default:
3604                         ret = -EINVAL;
3605                         goto out;
3606                 }
3607         }
3608
3609 out:
3610         /* Reset all restrictions if an error happened */
3611         if (ret != 0)
3612                 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
3613         else
3614                 ctx->restrictions.registered = true;
3615
3616         kfree(res);
3617         return ret;
3618 }
3619
3620 static int io_register_enable_rings(struct io_ring_ctx *ctx)
3621 {
3622         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
3623                 return -EBADFD;
3624
3625         if (ctx->restrictions.registered)
3626                 ctx->restricted = 1;
3627
3628         ctx->flags &= ~IORING_SETUP_R_DISABLED;
3629         if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
3630                 wake_up(&ctx->sq_data->wait);
3631         return 0;
3632 }
3633
3634 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
3635                                        void __user *arg, unsigned len)
3636 {
3637         struct io_uring_task *tctx = current->io_uring;
3638         cpumask_var_t new_mask;
3639         int ret;
3640
3641         if (!tctx || !tctx->io_wq)
3642                 return -EINVAL;
3643
3644         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
3645                 return -ENOMEM;
3646
3647         cpumask_clear(new_mask);
3648         if (len > cpumask_size())
3649                 len = cpumask_size();
3650
3651         if (in_compat_syscall()) {
3652                 ret = compat_get_bitmap(cpumask_bits(new_mask),
3653                                         (const compat_ulong_t __user *)arg,
3654                                         len * 8 /* CHAR_BIT */);
3655         } else {
3656                 ret = copy_from_user(new_mask, arg, len);
3657         }
3658
3659         if (ret) {
3660                 free_cpumask_var(new_mask);
3661                 return -EFAULT;
3662         }
3663
3664         ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
3665         free_cpumask_var(new_mask);
3666         return ret;
3667 }
3668
3669 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
3670 {
3671         struct io_uring_task *tctx = current->io_uring;
3672
3673         if (!tctx || !tctx->io_wq)
3674                 return -EINVAL;
3675
3676         return io_wq_cpu_affinity(tctx->io_wq, NULL);
3677 }
3678
3679 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
3680                                                void __user *arg)
3681         __must_hold(&ctx->uring_lock)
3682 {
3683         struct io_tctx_node *node;
3684         struct io_uring_task *tctx = NULL;
3685         struct io_sq_data *sqd = NULL;
3686         __u32 new_count[2];
3687         int i, ret;
3688
3689         if (copy_from_user(new_count, arg, sizeof(new_count)))
3690                 return -EFAULT;
3691         for (i = 0; i < ARRAY_SIZE(new_count); i++)
3692                 if (new_count[i] > INT_MAX)
3693                         return -EINVAL;
3694
3695         if (ctx->flags & IORING_SETUP_SQPOLL) {
3696                 sqd = ctx->sq_data;
3697                 if (sqd) {
3698                         /*
3699                          * Observe the correct sqd->lock -> ctx->uring_lock
3700                          * ordering. Fine to drop uring_lock here, we hold
3701                          * a ref to the ctx.
3702                          */
3703                         refcount_inc(&sqd->refs);
3704                         mutex_unlock(&ctx->uring_lock);
3705                         mutex_lock(&sqd->lock);
3706                         mutex_lock(&ctx->uring_lock);
3707                         if (sqd->thread)
3708                                 tctx = sqd->thread->io_uring;
3709                 }
3710         } else {
3711                 tctx = current->io_uring;
3712         }
3713
3714         BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
3715
3716         for (i = 0; i < ARRAY_SIZE(new_count); i++)
3717                 if (new_count[i])
3718                         ctx->iowq_limits[i] = new_count[i];
3719         ctx->iowq_limits_set = true;
3720
3721         if (tctx && tctx->io_wq) {
3722                 ret = io_wq_max_workers(tctx->io_wq, new_count);
3723                 if (ret)
3724                         goto err;
3725         } else {
3726                 memset(new_count, 0, sizeof(new_count));
3727         }
3728
3729         if (sqd) {
3730                 mutex_unlock(&sqd->lock);
3731                 io_put_sq_data(sqd);
3732         }
3733
3734         if (copy_to_user(arg, new_count, sizeof(new_count)))
3735                 return -EFAULT;
3736
3737         /* that's it for SQPOLL, only the SQPOLL task creates requests */
3738         if (sqd)
3739                 return 0;
3740
3741         /* now propagate the restriction to all registered users */
3742         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3743                 struct io_uring_task *tctx = node->task->io_uring;
3744
3745                 if (WARN_ON_ONCE(!tctx->io_wq))
3746                         continue;
3747
3748                 for (i = 0; i < ARRAY_SIZE(new_count); i++)
3749                         new_count[i] = ctx->iowq_limits[i];
3750                 /* ignore errors, it always returns zero anyway */
3751                 (void)io_wq_max_workers(tctx->io_wq, new_count);
3752         }
3753         return 0;
3754 err:
3755         if (sqd) {
3756                 mutex_unlock(&sqd->lock);
3757                 io_put_sq_data(sqd);
3758         }
3759         return ret;
3760 }
3761
3762 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3763                                void __user *arg, unsigned nr_args)
3764         __releases(ctx->uring_lock)
3765         __acquires(ctx->uring_lock)
3766 {
3767         int ret;
3768
3769         /*
3770          * We're inside the ring mutex, if the ref is already dying, then
3771          * someone else killed the ctx or is already going through
3772          * io_uring_register().
3773          */
3774         if (percpu_ref_is_dying(&ctx->refs))
3775                 return -ENXIO;
3776
3777         if (ctx->restricted) {
3778                 if (opcode >= IORING_REGISTER_LAST)
3779                         return -EINVAL;
3780                 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
3781                 if (!test_bit(opcode, ctx->restrictions.register_op))
3782                         return -EACCES;
3783         }
3784
3785         switch (opcode) {
3786         case IORING_REGISTER_BUFFERS:
3787                 ret = -EFAULT;
3788                 if (!arg)
3789                         break;
3790                 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
3791                 break;
3792         case IORING_UNREGISTER_BUFFERS:
3793                 ret = -EINVAL;
3794                 if (arg || nr_args)
3795                         break;
3796                 ret = io_sqe_buffers_unregister(ctx);
3797                 break;
3798         case IORING_REGISTER_FILES:
3799                 ret = -EFAULT;
3800                 if (!arg)
3801                         break;
3802                 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
3803                 break;
3804         case IORING_UNREGISTER_FILES:
3805                 ret = -EINVAL;
3806                 if (arg || nr_args)
3807                         break;
3808                 ret = io_sqe_files_unregister(ctx);
3809                 break;
3810         case IORING_REGISTER_FILES_UPDATE:
3811                 ret = io_register_files_update(ctx, arg, nr_args);
3812                 break;
3813         case IORING_REGISTER_EVENTFD:
3814                 ret = -EINVAL;
3815                 if (nr_args != 1)
3816                         break;
3817                 ret = io_eventfd_register(ctx, arg, 0);
3818                 break;
3819         case IORING_REGISTER_EVENTFD_ASYNC:
3820                 ret = -EINVAL;
3821                 if (nr_args != 1)
3822                         break;
3823                 ret = io_eventfd_register(ctx, arg, 1);
3824                 break;
3825         case IORING_UNREGISTER_EVENTFD:
3826                 ret = -EINVAL;
3827                 if (arg || nr_args)
3828                         break;
3829                 ret = io_eventfd_unregister(ctx);
3830                 break;
3831         case IORING_REGISTER_PROBE:
3832                 ret = -EINVAL;
3833                 if (!arg || nr_args > 256)
3834                         break;
3835                 ret = io_probe(ctx, arg, nr_args);
3836                 break;
3837         case IORING_REGISTER_PERSONALITY:
3838                 ret = -EINVAL;
3839                 if (arg || nr_args)
3840                         break;
3841                 ret = io_register_personality(ctx);
3842                 break;
3843         case IORING_UNREGISTER_PERSONALITY:
3844                 ret = -EINVAL;
3845                 if (arg)
3846                         break;
3847                 ret = io_unregister_personality(ctx, nr_args);
3848                 break;
3849         case IORING_REGISTER_ENABLE_RINGS:
3850                 ret = -EINVAL;
3851                 if (arg || nr_args)
3852                         break;
3853                 ret = io_register_enable_rings(ctx);
3854                 break;
3855         case IORING_REGISTER_RESTRICTIONS:
3856                 ret = io_register_restrictions(ctx, arg, nr_args);
3857                 break;
3858         case IORING_REGISTER_FILES2:
3859                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
3860                 break;
3861         case IORING_REGISTER_FILES_UPDATE2:
3862                 ret = io_register_rsrc_update(ctx, arg, nr_args,
3863                                               IORING_RSRC_FILE);
3864                 break;
3865         case IORING_REGISTER_BUFFERS2:
3866                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
3867                 break;
3868         case IORING_REGISTER_BUFFERS_UPDATE:
3869                 ret = io_register_rsrc_update(ctx, arg, nr_args,
3870                                               IORING_RSRC_BUFFER);
3871                 break;
3872         case IORING_REGISTER_IOWQ_AFF:
3873                 ret = -EINVAL;
3874                 if (!arg || !nr_args)
3875                         break;
3876                 ret = io_register_iowq_aff(ctx, arg, nr_args);
3877                 break;
3878         case IORING_UNREGISTER_IOWQ_AFF:
3879                 ret = -EINVAL;
3880                 if (arg || nr_args)
3881                         break;
3882                 ret = io_unregister_iowq_aff(ctx);
3883                 break;
3884         case IORING_REGISTER_IOWQ_MAX_WORKERS:
3885                 ret = -EINVAL;
3886                 if (!arg || nr_args != 2)
3887                         break;
3888                 ret = io_register_iowq_max_workers(ctx, arg);
3889                 break;
3890         case IORING_REGISTER_RING_FDS:
3891                 ret = io_ringfd_register(ctx, arg, nr_args);
3892                 break;
3893         case IORING_UNREGISTER_RING_FDS:
3894                 ret = io_ringfd_unregister(ctx, arg, nr_args);
3895                 break;
3896         case IORING_REGISTER_PBUF_RING:
3897                 ret = -EINVAL;
3898                 if (!arg || nr_args != 1)
3899                         break;
3900                 ret = io_register_pbuf_ring(ctx, arg);
3901                 break;
3902         case IORING_UNREGISTER_PBUF_RING:
3903                 ret = -EINVAL;
3904                 if (!arg || nr_args != 1)
3905                         break;
3906                 ret = io_unregister_pbuf_ring(ctx, arg);
3907                 break;
3908         default:
3909                 ret = -EINVAL;
3910                 break;
3911         }
3912
3913         return ret;
3914 }
3915
3916 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3917                 void __user *, arg, unsigned int, nr_args)
3918 {
3919         struct io_ring_ctx *ctx;
3920         long ret = -EBADF;
3921         struct fd f;
3922
3923         f = fdget(fd);
3924         if (!f.file)
3925                 return -EBADF;
3926
3927         ret = -EOPNOTSUPP;
3928         if (!io_is_uring_fops(f.file))
3929                 goto out_fput;
3930
3931         ctx = f.file->private_data;
3932
3933         io_run_task_work();
3934
3935         mutex_lock(&ctx->uring_lock);
3936         ret = __io_uring_register(ctx, opcode, arg, nr_args);
3937         mutex_unlock(&ctx->uring_lock);
3938         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
3939 out_fput:
3940         fdput(f);
3941         return ret;
3942 }
3943
3944 static int __init io_uring_init(void)
3945 {
3946 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
3947         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
3948         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
3949 } while (0)
3950
3951 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
3952         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
3953         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
3954         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
3955         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
3956         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
3957         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
3958         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
3959         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
3960         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
3961         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
3962         BUILD_BUG_SQE_ELEM(24, __u32,  len);
3963         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
3964         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
3965         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
3966         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
3967         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
3968         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
3969         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
3970         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
3971         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
3972         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
3973         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
3974         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
3975         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
3976         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
3977         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
3978         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
3979         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
3980         BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
3981         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
3982         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
3983         BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
3984         BUILD_BUG_SQE_ELEM(48, __u64,  addr3);
3985
3986         BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
3987                      sizeof(struct io_uring_rsrc_update));
3988         BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
3989                      sizeof(struct io_uring_rsrc_update2));
3990
3991         /* ->buf_index is u16 */
3992         BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
3993         BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
3994                      offsetof(struct io_uring_buf_ring, tail));
3995
3996         /* should fit into one byte */
3997         BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
3998         BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
3999         BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
4000
4001         BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
4002
4003         BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
4004
4005         io_uring_optable_init();
4006
4007         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4008                                 SLAB_ACCOUNT);
4009         return 0;
4010 };
4011 __initcall(io_uring_init);