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