Merge tag 'drm-vmwgfx-coherent-2019-11-29' of git://anongit.freedesktop.org/drm/drm
[linux-2.6-microblaze.git] / fs / 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_cqring (smp_store_release to
15  * store head will do). Failure to do so could lead to reading invalid
16  * CQ entries.
17  *
18  * Likewise, the application must use an appropriate smp_wmb() before
19  * writing the SQ tail (ordering SQ entry stores with the tail store),
20  * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21  * to store the tail will do). And it needs a barrier ordering the SQ
22  * head load before writing new SQ entries (smp_load_acquire to read
23  * head will do).
24  *
25  * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26  * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27  * updating the SQ tail; a full memory barrier smp_mb() is needed
28  * between.
29  *
30  * Also see the examples in the liburing library:
31  *
32  *      git://git.kernel.dk/liburing
33  *
34  * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35  * from data shared between the kernel and application. This is done both
36  * for ordering purposes, but also to ensure that once a value is loaded from
37  * data that the application could potentially modify, it remains stable.
38  *
39  * Copyright (C) 2018-2019 Jens Axboe
40  * Copyright (c) 2018-2019 Christoph Hellwig
41  */
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <linux/refcount.h>
48 #include <linux/uio.h>
49
50 #include <linux/sched/signal.h>
51 #include <linux/fs.h>
52 #include <linux/file.h>
53 #include <linux/fdtable.h>
54 #include <linux/mm.h>
55 #include <linux/mman.h>
56 #include <linux/mmu_context.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/kthread.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
63 #include <net/sock.h>
64 #include <net/af_unix.h>
65 #include <net/scm.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72
73 #define CREATE_TRACE_POINTS
74 #include <trace/events/io_uring.h>
75
76 #include <uapi/linux/io_uring.h>
77
78 #include "internal.h"
79 #include "io-wq.h"
80
81 #define IORING_MAX_ENTRIES      32768
82 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
83
84 /*
85  * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
86  */
87 #define IORING_FILE_TABLE_SHIFT 9
88 #define IORING_MAX_FILES_TABLE  (1U << IORING_FILE_TABLE_SHIFT)
89 #define IORING_FILE_TABLE_MASK  (IORING_MAX_FILES_TABLE - 1)
90 #define IORING_MAX_FIXED_FILES  (64 * IORING_MAX_FILES_TABLE)
91
92 struct io_uring {
93         u32 head ____cacheline_aligned_in_smp;
94         u32 tail ____cacheline_aligned_in_smp;
95 };
96
97 /*
98  * This data is shared with the application through the mmap at offsets
99  * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
100  *
101  * The offsets to the member fields are published through struct
102  * io_sqring_offsets when calling io_uring_setup.
103  */
104 struct io_rings {
105         /*
106          * Head and tail offsets into the ring; the offsets need to be
107          * masked to get valid indices.
108          *
109          * The kernel controls head of the sq ring and the tail of the cq ring,
110          * and the application controls tail of the sq ring and the head of the
111          * cq ring.
112          */
113         struct io_uring         sq, cq;
114         /*
115          * Bitmasks to apply to head and tail offsets (constant, equals
116          * ring_entries - 1)
117          */
118         u32                     sq_ring_mask, cq_ring_mask;
119         /* Ring sizes (constant, power of 2) */
120         u32                     sq_ring_entries, cq_ring_entries;
121         /*
122          * Number of invalid entries dropped by the kernel due to
123          * invalid index stored in array
124          *
125          * Written by the kernel, shouldn't be modified by the
126          * application (i.e. get number of "new events" by comparing to
127          * cached value).
128          *
129          * After a new SQ head value was read by the application this
130          * counter includes all submissions that were dropped reaching
131          * the new SQ head (and possibly more).
132          */
133         u32                     sq_dropped;
134         /*
135          * Runtime flags
136          *
137          * Written by the kernel, shouldn't be modified by the
138          * application.
139          *
140          * The application needs a full memory barrier before checking
141          * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
142          */
143         u32                     sq_flags;
144         /*
145          * Number of completion events lost because the queue was full;
146          * this should be avoided by the application by making sure
147          * there are not more requests pending thatn there is space in
148          * the completion queue.
149          *
150          * Written by the kernel, shouldn't be modified by the
151          * application (i.e. get number of "new events" by comparing to
152          * cached value).
153          *
154          * As completion events come in out of order this counter is not
155          * ordered with any other data.
156          */
157         u32                     cq_overflow;
158         /*
159          * Ring buffer of completion events.
160          *
161          * The kernel writes completion events fresh every time they are
162          * produced, so the application is allowed to modify pending
163          * entries.
164          */
165         struct io_uring_cqe     cqes[] ____cacheline_aligned_in_smp;
166 };
167
168 struct io_mapped_ubuf {
169         u64             ubuf;
170         size_t          len;
171         struct          bio_vec *bvec;
172         unsigned int    nr_bvecs;
173 };
174
175 struct fixed_file_table {
176         struct file             **files;
177 };
178
179 struct io_ring_ctx {
180         struct {
181                 struct percpu_ref       refs;
182         } ____cacheline_aligned_in_smp;
183
184         struct {
185                 unsigned int            flags;
186                 bool                    compat;
187                 bool                    account_mem;
188                 bool                    cq_overflow_flushed;
189                 bool                    drain_next;
190
191                 /*
192                  * Ring buffer of indices into array of io_uring_sqe, which is
193                  * mmapped by the application using the IORING_OFF_SQES offset.
194                  *
195                  * This indirection could e.g. be used to assign fixed
196                  * io_uring_sqe entries to operations and only submit them to
197                  * the queue when needed.
198                  *
199                  * The kernel modifies neither the indices array nor the entries
200                  * array.
201                  */
202                 u32                     *sq_array;
203                 unsigned                cached_sq_head;
204                 unsigned                sq_entries;
205                 unsigned                sq_mask;
206                 unsigned                sq_thread_idle;
207                 unsigned                cached_sq_dropped;
208                 atomic_t                cached_cq_overflow;
209                 struct io_uring_sqe     *sq_sqes;
210
211                 struct list_head        defer_list;
212                 struct list_head        timeout_list;
213                 struct list_head        cq_overflow_list;
214
215                 wait_queue_head_t       inflight_wait;
216         } ____cacheline_aligned_in_smp;
217
218         struct io_rings *rings;
219
220         /* IO offload */
221         struct io_wq            *io_wq;
222         struct task_struct      *sqo_thread;    /* if using sq thread polling */
223         struct mm_struct        *sqo_mm;
224         wait_queue_head_t       sqo_wait;
225
226         /*
227          * If used, fixed file set. Writers must ensure that ->refs is dead,
228          * readers must ensure that ->refs is alive as long as the file* is
229          * used. Only updated through io_uring_register(2).
230          */
231         struct fixed_file_table *file_table;
232         unsigned                nr_user_files;
233
234         /* if used, fixed mapped user buffers */
235         unsigned                nr_user_bufs;
236         struct io_mapped_ubuf   *user_bufs;
237
238         struct user_struct      *user;
239
240         struct cred             *creds;
241
242         /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
243         struct completion       *completions;
244
245         /* if all else fails... */
246         struct io_kiocb         *fallback_req;
247
248 #if defined(CONFIG_UNIX)
249         struct socket           *ring_sock;
250 #endif
251
252         struct {
253                 unsigned                cached_cq_tail;
254                 unsigned                cq_entries;
255                 unsigned                cq_mask;
256                 atomic_t                cq_timeouts;
257                 struct wait_queue_head  cq_wait;
258                 struct fasync_struct    *cq_fasync;
259                 struct eventfd_ctx      *cq_ev_fd;
260         } ____cacheline_aligned_in_smp;
261
262         struct {
263                 struct mutex            uring_lock;
264                 wait_queue_head_t       wait;
265         } ____cacheline_aligned_in_smp;
266
267         struct {
268                 spinlock_t              completion_lock;
269                 bool                    poll_multi_file;
270                 /*
271                  * ->poll_list is protected by the ctx->uring_lock for
272                  * io_uring instances that don't use IORING_SETUP_SQPOLL.
273                  * For SQPOLL, only the single threaded io_sq_thread() will
274                  * manipulate the list, hence no extra locking is needed there.
275                  */
276                 struct list_head        poll_list;
277                 struct rb_root          cancel_tree;
278
279                 spinlock_t              inflight_lock;
280                 struct list_head        inflight_list;
281         } ____cacheline_aligned_in_smp;
282 };
283
284 /*
285  * First field must be the file pointer in all the
286  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
287  */
288 struct io_poll_iocb {
289         struct file                     *file;
290         struct wait_queue_head          *head;
291         __poll_t                        events;
292         bool                            done;
293         bool                            canceled;
294         struct wait_queue_entry         *wait;
295 };
296
297 struct io_timeout_data {
298         struct io_kiocb                 *req;
299         struct hrtimer                  timer;
300         struct timespec64               ts;
301         enum hrtimer_mode               mode;
302         u32                             seq_offset;
303 };
304
305 struct io_timeout {
306         struct file                     *file;
307         struct io_timeout_data          *data;
308 };
309
310 /*
311  * NOTE! Each of the iocb union members has the file pointer
312  * as the first entry in their struct definition. So you can
313  * access the file pointer through any of the sub-structs,
314  * or directly as just 'ki_filp' in this struct.
315  */
316 struct io_kiocb {
317         union {
318                 struct file             *file;
319                 struct kiocb            rw;
320                 struct io_poll_iocb     poll;
321                 struct io_timeout       timeout;
322         };
323
324         const struct io_uring_sqe       *sqe;
325         struct file                     *ring_file;
326         int                             ring_fd;
327         bool                            has_user;
328         bool                            in_async;
329         bool                            needs_fixed_file;
330
331         struct io_ring_ctx      *ctx;
332         union {
333                 struct list_head        list;
334                 struct rb_node          rb_node;
335         };
336         struct list_head        link_list;
337         unsigned int            flags;
338         refcount_t              refs;
339 #define REQ_F_NOWAIT            1       /* must not punt to workers */
340 #define REQ_F_IOPOLL_COMPLETED  2       /* polled IO has completed */
341 #define REQ_F_FIXED_FILE        4       /* ctx owns file */
342 #define REQ_F_LINK_NEXT         8       /* already grabbed next link */
343 #define REQ_F_IO_DRAIN          16      /* drain existing IO first */
344 #define REQ_F_IO_DRAINED        32      /* drain done */
345 #define REQ_F_LINK              64      /* linked sqes */
346 #define REQ_F_LINK_TIMEOUT      128     /* has linked timeout */
347 #define REQ_F_FAIL_LINK         256     /* fail rest of links */
348 #define REQ_F_DRAIN_LINK        512     /* link should be fully drained */
349 #define REQ_F_TIMEOUT           1024    /* timeout request */
350 #define REQ_F_ISREG             2048    /* regular file */
351 #define REQ_F_MUST_PUNT         4096    /* must be punted even for NONBLOCK */
352 #define REQ_F_TIMEOUT_NOSEQ     8192    /* no timeout sequence */
353 #define REQ_F_INFLIGHT          16384   /* on inflight list */
354 #define REQ_F_COMP_LOCKED       32768   /* completion under lock */
355 #define REQ_F_FREE_SQE          65536   /* free sqe if not async queued */
356         u64                     user_data;
357         u32                     result;
358         u32                     sequence;
359
360         struct list_head        inflight_entry;
361
362         struct io_wq_work       work;
363 };
364
365 #define IO_PLUG_THRESHOLD               2
366 #define IO_IOPOLL_BATCH                 8
367
368 struct io_submit_state {
369         struct blk_plug         plug;
370
371         /*
372          * io_kiocb alloc cache
373          */
374         void                    *reqs[IO_IOPOLL_BATCH];
375         unsigned                int free_reqs;
376         unsigned                int cur_req;
377
378         /*
379          * File reference cache
380          */
381         struct file             *file;
382         unsigned int            fd;
383         unsigned int            has_refs;
384         unsigned int            used_refs;
385         unsigned int            ios_left;
386 };
387
388 static void io_wq_submit_work(struct io_wq_work **workptr);
389 static void io_cqring_fill_event(struct io_kiocb *req, long res);
390 static void __io_free_req(struct io_kiocb *req);
391 static void io_put_req(struct io_kiocb *req);
392 static void io_double_put_req(struct io_kiocb *req);
393 static void __io_double_put_req(struct io_kiocb *req);
394 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
395 static void io_queue_linked_timeout(struct io_kiocb *req);
396
397 static struct kmem_cache *req_cachep;
398
399 static const struct file_operations io_uring_fops;
400
401 struct sock *io_uring_get_socket(struct file *file)
402 {
403 #if defined(CONFIG_UNIX)
404         if (file->f_op == &io_uring_fops) {
405                 struct io_ring_ctx *ctx = file->private_data;
406
407                 return ctx->ring_sock->sk;
408         }
409 #endif
410         return NULL;
411 }
412 EXPORT_SYMBOL(io_uring_get_socket);
413
414 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
415 {
416         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
417
418         complete(&ctx->completions[0]);
419 }
420
421 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
422 {
423         struct io_ring_ctx *ctx;
424
425         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
426         if (!ctx)
427                 return NULL;
428
429         ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
430         if (!ctx->fallback_req)
431                 goto err;
432
433         ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
434         if (!ctx->completions)
435                 goto err;
436
437         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
438                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
439                 goto err;
440
441         ctx->flags = p->flags;
442         init_waitqueue_head(&ctx->cq_wait);
443         INIT_LIST_HEAD(&ctx->cq_overflow_list);
444         init_completion(&ctx->completions[0]);
445         init_completion(&ctx->completions[1]);
446         mutex_init(&ctx->uring_lock);
447         init_waitqueue_head(&ctx->wait);
448         spin_lock_init(&ctx->completion_lock);
449         INIT_LIST_HEAD(&ctx->poll_list);
450         ctx->cancel_tree = RB_ROOT;
451         INIT_LIST_HEAD(&ctx->defer_list);
452         INIT_LIST_HEAD(&ctx->timeout_list);
453         init_waitqueue_head(&ctx->inflight_wait);
454         spin_lock_init(&ctx->inflight_lock);
455         INIT_LIST_HEAD(&ctx->inflight_list);
456         return ctx;
457 err:
458         if (ctx->fallback_req)
459                 kmem_cache_free(req_cachep, ctx->fallback_req);
460         kfree(ctx->completions);
461         kfree(ctx);
462         return NULL;
463 }
464
465 static inline bool __req_need_defer(struct io_kiocb *req)
466 {
467         struct io_ring_ctx *ctx = req->ctx;
468
469         return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
470                                         + atomic_read(&ctx->cached_cq_overflow);
471 }
472
473 static inline bool req_need_defer(struct io_kiocb *req)
474 {
475         if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) == REQ_F_IO_DRAIN)
476                 return __req_need_defer(req);
477
478         return false;
479 }
480
481 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
482 {
483         struct io_kiocb *req;
484
485         req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
486         if (req && !req_need_defer(req)) {
487                 list_del_init(&req->list);
488                 return req;
489         }
490
491         return NULL;
492 }
493
494 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
495 {
496         struct io_kiocb *req;
497
498         req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
499         if (req) {
500                 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
501                         return NULL;
502                 if (!__req_need_defer(req)) {
503                         list_del_init(&req->list);
504                         return req;
505                 }
506         }
507
508         return NULL;
509 }
510
511 static void __io_commit_cqring(struct io_ring_ctx *ctx)
512 {
513         struct io_rings *rings = ctx->rings;
514
515         if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
516                 /* order cqe stores with ring update */
517                 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
518
519                 if (wq_has_sleeper(&ctx->cq_wait)) {
520                         wake_up_interruptible(&ctx->cq_wait);
521                         kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
522                 }
523         }
524 }
525
526 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
527 {
528         u8 opcode = READ_ONCE(sqe->opcode);
529
530         return !(opcode == IORING_OP_READ_FIXED ||
531                  opcode == IORING_OP_WRITE_FIXED);
532 }
533
534 static inline bool io_prep_async_work(struct io_kiocb *req,
535                                       struct io_kiocb **link)
536 {
537         bool do_hashed = false;
538
539         if (req->sqe) {
540                 switch (req->sqe->opcode) {
541                 case IORING_OP_WRITEV:
542                 case IORING_OP_WRITE_FIXED:
543                         do_hashed = true;
544                         /* fall-through */
545                 case IORING_OP_READV:
546                 case IORING_OP_READ_FIXED:
547                 case IORING_OP_SENDMSG:
548                 case IORING_OP_RECVMSG:
549                 case IORING_OP_ACCEPT:
550                 case IORING_OP_POLL_ADD:
551                 case IORING_OP_CONNECT:
552                         /*
553                          * We know REQ_F_ISREG is not set on some of these
554                          * opcodes, but this enables us to keep the check in
555                          * just one place.
556                          */
557                         if (!(req->flags & REQ_F_ISREG))
558                                 req->work.flags |= IO_WQ_WORK_UNBOUND;
559                         break;
560                 }
561                 if (io_sqe_needs_user(req->sqe))
562                         req->work.flags |= IO_WQ_WORK_NEEDS_USER;
563         }
564
565         *link = io_prep_linked_timeout(req);
566         return do_hashed;
567 }
568
569 static inline void io_queue_async_work(struct io_kiocb *req)
570 {
571         struct io_ring_ctx *ctx = req->ctx;
572         struct io_kiocb *link;
573         bool do_hashed;
574
575         do_hashed = io_prep_async_work(req, &link);
576
577         trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
578                                         req->flags);
579         if (!do_hashed) {
580                 io_wq_enqueue(ctx->io_wq, &req->work);
581         } else {
582                 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
583                                         file_inode(req->file));
584         }
585
586         if (link)
587                 io_queue_linked_timeout(link);
588 }
589
590 static void io_kill_timeout(struct io_kiocb *req)
591 {
592         int ret;
593
594         ret = hrtimer_try_to_cancel(&req->timeout.data->timer);
595         if (ret != -1) {
596                 atomic_inc(&req->ctx->cq_timeouts);
597                 list_del_init(&req->list);
598                 io_cqring_fill_event(req, 0);
599                 io_put_req(req);
600         }
601 }
602
603 static void io_kill_timeouts(struct io_ring_ctx *ctx)
604 {
605         struct io_kiocb *req, *tmp;
606
607         spin_lock_irq(&ctx->completion_lock);
608         list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
609                 io_kill_timeout(req);
610         spin_unlock_irq(&ctx->completion_lock);
611 }
612
613 static void io_commit_cqring(struct io_ring_ctx *ctx)
614 {
615         struct io_kiocb *req;
616
617         while ((req = io_get_timeout_req(ctx)) != NULL)
618                 io_kill_timeout(req);
619
620         __io_commit_cqring(ctx);
621
622         while ((req = io_get_deferred_req(ctx)) != NULL) {
623                 req->flags |= REQ_F_IO_DRAINED;
624                 io_queue_async_work(req);
625         }
626 }
627
628 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
629 {
630         struct io_rings *rings = ctx->rings;
631         unsigned tail;
632
633         tail = ctx->cached_cq_tail;
634         /*
635          * writes to the cq entry need to come after reading head; the
636          * control dependency is enough as we're using WRITE_ONCE to
637          * fill the cq entry
638          */
639         if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
640                 return NULL;
641
642         ctx->cached_cq_tail++;
643         return &rings->cqes[tail & ctx->cq_mask];
644 }
645
646 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
647 {
648         if (waitqueue_active(&ctx->wait))
649                 wake_up(&ctx->wait);
650         if (waitqueue_active(&ctx->sqo_wait))
651                 wake_up(&ctx->sqo_wait);
652         if (ctx->cq_ev_fd)
653                 eventfd_signal(ctx->cq_ev_fd, 1);
654 }
655
656 /* Returns true if there are no backlogged entries after the flush */
657 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
658 {
659         struct io_rings *rings = ctx->rings;
660         struct io_uring_cqe *cqe;
661         struct io_kiocb *req;
662         unsigned long flags;
663         LIST_HEAD(list);
664
665         if (!force) {
666                 if (list_empty_careful(&ctx->cq_overflow_list))
667                         return true;
668                 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
669                     rings->cq_ring_entries))
670                         return false;
671         }
672
673         spin_lock_irqsave(&ctx->completion_lock, flags);
674
675         /* if force is set, the ring is going away. always drop after that */
676         if (force)
677                 ctx->cq_overflow_flushed = true;
678
679         cqe = NULL;
680         while (!list_empty(&ctx->cq_overflow_list)) {
681                 cqe = io_get_cqring(ctx);
682                 if (!cqe && !force)
683                         break;
684
685                 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
686                                                 list);
687                 list_move(&req->list, &list);
688                 if (cqe) {
689                         WRITE_ONCE(cqe->user_data, req->user_data);
690                         WRITE_ONCE(cqe->res, req->result);
691                         WRITE_ONCE(cqe->flags, 0);
692                 } else {
693                         WRITE_ONCE(ctx->rings->cq_overflow,
694                                 atomic_inc_return(&ctx->cached_cq_overflow));
695                 }
696         }
697
698         io_commit_cqring(ctx);
699         spin_unlock_irqrestore(&ctx->completion_lock, flags);
700         io_cqring_ev_posted(ctx);
701
702         while (!list_empty(&list)) {
703                 req = list_first_entry(&list, struct io_kiocb, list);
704                 list_del(&req->list);
705                 io_put_req(req);
706         }
707
708         return cqe != NULL;
709 }
710
711 static void io_cqring_fill_event(struct io_kiocb *req, long res)
712 {
713         struct io_ring_ctx *ctx = req->ctx;
714         struct io_uring_cqe *cqe;
715
716         trace_io_uring_complete(ctx, req->user_data, res);
717
718         /*
719          * If we can't get a cq entry, userspace overflowed the
720          * submission (by quite a lot). Increment the overflow count in
721          * the ring.
722          */
723         cqe = io_get_cqring(ctx);
724         if (likely(cqe)) {
725                 WRITE_ONCE(cqe->user_data, req->user_data);
726                 WRITE_ONCE(cqe->res, res);
727                 WRITE_ONCE(cqe->flags, 0);
728         } else if (ctx->cq_overflow_flushed) {
729                 WRITE_ONCE(ctx->rings->cq_overflow,
730                                 atomic_inc_return(&ctx->cached_cq_overflow));
731         } else {
732                 refcount_inc(&req->refs);
733                 req->result = res;
734                 list_add_tail(&req->list, &ctx->cq_overflow_list);
735         }
736 }
737
738 static void io_cqring_add_event(struct io_kiocb *req, long res)
739 {
740         struct io_ring_ctx *ctx = req->ctx;
741         unsigned long flags;
742
743         spin_lock_irqsave(&ctx->completion_lock, flags);
744         io_cqring_fill_event(req, res);
745         io_commit_cqring(ctx);
746         spin_unlock_irqrestore(&ctx->completion_lock, flags);
747
748         io_cqring_ev_posted(ctx);
749 }
750
751 static inline bool io_is_fallback_req(struct io_kiocb *req)
752 {
753         return req == (struct io_kiocb *)
754                         ((unsigned long) req->ctx->fallback_req & ~1UL);
755 }
756
757 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
758 {
759         struct io_kiocb *req;
760
761         req = ctx->fallback_req;
762         if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
763                 return req;
764
765         return NULL;
766 }
767
768 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
769                                    struct io_submit_state *state)
770 {
771         gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
772         struct io_kiocb *req;
773
774         if (!percpu_ref_tryget(&ctx->refs))
775                 return NULL;
776
777         if (!state) {
778                 req = kmem_cache_alloc(req_cachep, gfp);
779                 if (unlikely(!req))
780                         goto fallback;
781         } else if (!state->free_reqs) {
782                 size_t sz;
783                 int ret;
784
785                 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
786                 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
787
788                 /*
789                  * Bulk alloc is all-or-nothing. If we fail to get a batch,
790                  * retry single alloc to be on the safe side.
791                  */
792                 if (unlikely(ret <= 0)) {
793                         state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
794                         if (!state->reqs[0])
795                                 goto fallback;
796                         ret = 1;
797                 }
798                 state->free_reqs = ret - 1;
799                 state->cur_req = 1;
800                 req = state->reqs[0];
801         } else {
802                 req = state->reqs[state->cur_req];
803                 state->free_reqs--;
804                 state->cur_req++;
805         }
806
807 got_it:
808         req->ring_file = NULL;
809         req->file = NULL;
810         req->ctx = ctx;
811         req->flags = 0;
812         /* one is dropped after submission, the other at completion */
813         refcount_set(&req->refs, 2);
814         req->result = 0;
815         INIT_IO_WORK(&req->work, io_wq_submit_work);
816         return req;
817 fallback:
818         req = io_get_fallback_req(ctx);
819         if (req)
820                 goto got_it;
821         percpu_ref_put(&ctx->refs);
822         return NULL;
823 }
824
825 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
826 {
827         if (*nr) {
828                 kmem_cache_free_bulk(req_cachep, *nr, reqs);
829                 percpu_ref_put_many(&ctx->refs, *nr);
830                 *nr = 0;
831         }
832 }
833
834 static void __io_free_req(struct io_kiocb *req)
835 {
836         struct io_ring_ctx *ctx = req->ctx;
837
838         if (req->flags & REQ_F_FREE_SQE)
839                 kfree(req->sqe);
840         if (req->file && !(req->flags & REQ_F_FIXED_FILE))
841                 fput(req->file);
842         if (req->flags & REQ_F_INFLIGHT) {
843                 unsigned long flags;
844
845                 spin_lock_irqsave(&ctx->inflight_lock, flags);
846                 list_del(&req->inflight_entry);
847                 if (waitqueue_active(&ctx->inflight_wait))
848                         wake_up(&ctx->inflight_wait);
849                 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
850         }
851         if (req->flags & REQ_F_TIMEOUT)
852                 kfree(req->timeout.data);
853         percpu_ref_put(&ctx->refs);
854         if (likely(!io_is_fallback_req(req)))
855                 kmem_cache_free(req_cachep, req);
856         else
857                 clear_bit_unlock(0, (unsigned long *) ctx->fallback_req);
858 }
859
860 static bool io_link_cancel_timeout(struct io_kiocb *req)
861 {
862         struct io_ring_ctx *ctx = req->ctx;
863         int ret;
864
865         ret = hrtimer_try_to_cancel(&req->timeout.data->timer);
866         if (ret != -1) {
867                 io_cqring_fill_event(req, -ECANCELED);
868                 io_commit_cqring(ctx);
869                 req->flags &= ~REQ_F_LINK;
870                 io_put_req(req);
871                 return true;
872         }
873
874         return false;
875 }
876
877 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
878 {
879         struct io_ring_ctx *ctx = req->ctx;
880         struct io_kiocb *nxt;
881         bool wake_ev = false;
882
883         /* Already got next link */
884         if (req->flags & REQ_F_LINK_NEXT)
885                 return;
886
887         /*
888          * The list should never be empty when we are called here. But could
889          * potentially happen if the chain is messed up, check to be on the
890          * safe side.
891          */
892         nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
893         while (nxt) {
894                 list_del_init(&nxt->list);
895
896                 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
897                     (nxt->flags & REQ_F_TIMEOUT)) {
898                         wake_ev |= io_link_cancel_timeout(nxt);
899                         nxt = list_first_entry_or_null(&req->link_list,
900                                                         struct io_kiocb, list);
901                         req->flags &= ~REQ_F_LINK_TIMEOUT;
902                         continue;
903                 }
904                 if (!list_empty(&req->link_list)) {
905                         INIT_LIST_HEAD(&nxt->link_list);
906                         list_splice(&req->link_list, &nxt->link_list);
907                         nxt->flags |= REQ_F_LINK;
908                 }
909
910                 *nxtptr = nxt;
911                 break;
912         }
913
914         req->flags |= REQ_F_LINK_NEXT;
915         if (wake_ev)
916                 io_cqring_ev_posted(ctx);
917 }
918
919 /*
920  * Called if REQ_F_LINK is set, and we fail the head request
921  */
922 static void io_fail_links(struct io_kiocb *req)
923 {
924         struct io_ring_ctx *ctx = req->ctx;
925         struct io_kiocb *link;
926         unsigned long flags;
927
928         spin_lock_irqsave(&ctx->completion_lock, flags);
929
930         while (!list_empty(&req->link_list)) {
931                 link = list_first_entry(&req->link_list, struct io_kiocb, list);
932                 list_del_init(&link->list);
933
934                 trace_io_uring_fail_link(req, link);
935
936                 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
937                     link->sqe->opcode == IORING_OP_LINK_TIMEOUT) {
938                         io_link_cancel_timeout(link);
939                 } else {
940                         io_cqring_fill_event(link, -ECANCELED);
941                         __io_double_put_req(link);
942                 }
943                 req->flags &= ~REQ_F_LINK_TIMEOUT;
944         }
945
946         io_commit_cqring(ctx);
947         spin_unlock_irqrestore(&ctx->completion_lock, flags);
948         io_cqring_ev_posted(ctx);
949 }
950
951 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
952 {
953         if (likely(!(req->flags & REQ_F_LINK)))
954                 return;
955
956         /*
957          * If LINK is set, we have dependent requests in this chain. If we
958          * didn't fail this request, queue the first one up, moving any other
959          * dependencies to the next request. In case of failure, fail the rest
960          * of the chain.
961          */
962         if (req->flags & REQ_F_FAIL_LINK) {
963                 io_fail_links(req);
964         } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
965                         REQ_F_LINK_TIMEOUT) {
966                 struct io_ring_ctx *ctx = req->ctx;
967                 unsigned long flags;
968
969                 /*
970                  * If this is a timeout link, we could be racing with the
971                  * timeout timer. Grab the completion lock for this case to
972                  * protect against that.
973                  */
974                 spin_lock_irqsave(&ctx->completion_lock, flags);
975                 io_req_link_next(req, nxt);
976                 spin_unlock_irqrestore(&ctx->completion_lock, flags);
977         } else {
978                 io_req_link_next(req, nxt);
979         }
980 }
981
982 static void io_free_req(struct io_kiocb *req)
983 {
984         struct io_kiocb *nxt = NULL;
985
986         io_req_find_next(req, &nxt);
987         __io_free_req(req);
988
989         if (nxt)
990                 io_queue_async_work(nxt);
991 }
992
993 /*
994  * Drop reference to request, return next in chain (if there is one) if this
995  * was the last reference to this request.
996  */
997 __attribute__((nonnull))
998 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
999 {
1000         io_req_find_next(req, nxtptr);
1001
1002         if (refcount_dec_and_test(&req->refs))
1003                 __io_free_req(req);
1004 }
1005
1006 static void io_put_req(struct io_kiocb *req)
1007 {
1008         if (refcount_dec_and_test(&req->refs))
1009                 io_free_req(req);
1010 }
1011
1012 /*
1013  * Must only be used if we don't need to care about links, usually from
1014  * within the completion handling itself.
1015  */
1016 static void __io_double_put_req(struct io_kiocb *req)
1017 {
1018         /* drop both submit and complete references */
1019         if (refcount_sub_and_test(2, &req->refs))
1020                 __io_free_req(req);
1021 }
1022
1023 static void io_double_put_req(struct io_kiocb *req)
1024 {
1025         /* drop both submit and complete references */
1026         if (refcount_sub_and_test(2, &req->refs))
1027                 io_free_req(req);
1028 }
1029
1030 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1031 {
1032         struct io_rings *rings = ctx->rings;
1033
1034         /*
1035          * noflush == true is from the waitqueue handler, just ensure we wake
1036          * up the task, and the next invocation will flush the entries. We
1037          * cannot safely to it from here.
1038          */
1039         if (noflush && !list_empty(&ctx->cq_overflow_list))
1040                 return -1U;
1041
1042         io_cqring_overflow_flush(ctx, false);
1043
1044         /* See comment at the top of this file */
1045         smp_rmb();
1046         return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
1047 }
1048
1049 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1050 {
1051         struct io_rings *rings = ctx->rings;
1052
1053         /* make sure SQ entry isn't read before tail */
1054         return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1055 }
1056
1057 /*
1058  * Find and free completed poll iocbs
1059  */
1060 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1061                                struct list_head *done)
1062 {
1063         void *reqs[IO_IOPOLL_BATCH];
1064         struct io_kiocb *req;
1065         int to_free;
1066
1067         to_free = 0;
1068         while (!list_empty(done)) {
1069                 req = list_first_entry(done, struct io_kiocb, list);
1070                 list_del(&req->list);
1071
1072                 io_cqring_fill_event(req, req->result);
1073                 (*nr_events)++;
1074
1075                 if (refcount_dec_and_test(&req->refs)) {
1076                         /* If we're not using fixed files, we have to pair the
1077                          * completion part with the file put. Use regular
1078                          * completions for those, only batch free for fixed
1079                          * file and non-linked commands.
1080                          */
1081                         if (((req->flags &
1082                                 (REQ_F_FIXED_FILE|REQ_F_LINK|REQ_F_FREE_SQE)) ==
1083                             REQ_F_FIXED_FILE) && !io_is_fallback_req(req)) {
1084                                 reqs[to_free++] = req;
1085                                 if (to_free == ARRAY_SIZE(reqs))
1086                                         io_free_req_many(ctx, reqs, &to_free);
1087                         } else {
1088                                 io_free_req(req);
1089                         }
1090                 }
1091         }
1092
1093         io_commit_cqring(ctx);
1094         io_free_req_many(ctx, reqs, &to_free);
1095 }
1096
1097 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1098                         long min)
1099 {
1100         struct io_kiocb *req, *tmp;
1101         LIST_HEAD(done);
1102         bool spin;
1103         int ret;
1104
1105         /*
1106          * Only spin for completions if we don't have multiple devices hanging
1107          * off our complete list, and we're under the requested amount.
1108          */
1109         spin = !ctx->poll_multi_file && *nr_events < min;
1110
1111         ret = 0;
1112         list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1113                 struct kiocb *kiocb = &req->rw;
1114
1115                 /*
1116                  * Move completed entries to our local list. If we find a
1117                  * request that requires polling, break out and complete
1118                  * the done list first, if we have entries there.
1119                  */
1120                 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1121                         list_move_tail(&req->list, &done);
1122                         continue;
1123                 }
1124                 if (!list_empty(&done))
1125                         break;
1126
1127                 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1128                 if (ret < 0)
1129                         break;
1130
1131                 if (ret && spin)
1132                         spin = false;
1133                 ret = 0;
1134         }
1135
1136         if (!list_empty(&done))
1137                 io_iopoll_complete(ctx, nr_events, &done);
1138
1139         return ret;
1140 }
1141
1142 /*
1143  * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
1144  * non-spinning poll check - we'll still enter the driver poll loop, but only
1145  * as a non-spinning completion check.
1146  */
1147 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1148                                 long min)
1149 {
1150         while (!list_empty(&ctx->poll_list) && !need_resched()) {
1151                 int ret;
1152
1153                 ret = io_do_iopoll(ctx, nr_events, min);
1154                 if (ret < 0)
1155                         return ret;
1156                 if (!min || *nr_events >= min)
1157                         return 0;
1158         }
1159
1160         return 1;
1161 }
1162
1163 /*
1164  * We can't just wait for polled events to come to us, we have to actively
1165  * find and complete them.
1166  */
1167 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1168 {
1169         if (!(ctx->flags & IORING_SETUP_IOPOLL))
1170                 return;
1171
1172         mutex_lock(&ctx->uring_lock);
1173         while (!list_empty(&ctx->poll_list)) {
1174                 unsigned int nr_events = 0;
1175
1176                 io_iopoll_getevents(ctx, &nr_events, 1);
1177
1178                 /*
1179                  * Ensure we allow local-to-the-cpu processing to take place,
1180                  * in this case we need to ensure that we reap all events.
1181                  */
1182                 cond_resched();
1183         }
1184         mutex_unlock(&ctx->uring_lock);
1185 }
1186
1187 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1188                             long min)
1189 {
1190         int iters = 0, ret = 0;
1191
1192         do {
1193                 int tmin = 0;
1194
1195                 /*
1196                  * Don't enter poll loop if we already have events pending.
1197                  * If we do, we can potentially be spinning for commands that
1198                  * already triggered a CQE (eg in error).
1199                  */
1200                 if (io_cqring_events(ctx, false))
1201                         break;
1202
1203                 /*
1204                  * If a submit got punted to a workqueue, we can have the
1205                  * application entering polling for a command before it gets
1206                  * issued. That app will hold the uring_lock for the duration
1207                  * of the poll right here, so we need to take a breather every
1208                  * now and then to ensure that the issue has a chance to add
1209                  * the poll to the issued list. Otherwise we can spin here
1210                  * forever, while the workqueue is stuck trying to acquire the
1211                  * very same mutex.
1212                  */
1213                 if (!(++iters & 7)) {
1214                         mutex_unlock(&ctx->uring_lock);
1215                         mutex_lock(&ctx->uring_lock);
1216                 }
1217
1218                 if (*nr_events < min)
1219                         tmin = min - *nr_events;
1220
1221                 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1222                 if (ret <= 0)
1223                         break;
1224                 ret = 0;
1225         } while (min && !*nr_events && !need_resched());
1226
1227         return ret;
1228 }
1229
1230 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1231                            long min)
1232 {
1233         int ret;
1234
1235         /*
1236          * We disallow the app entering submit/complete with polling, but we
1237          * still need to lock the ring to prevent racing with polled issue
1238          * that got punted to a workqueue.
1239          */
1240         mutex_lock(&ctx->uring_lock);
1241         ret = __io_iopoll_check(ctx, nr_events, min);
1242         mutex_unlock(&ctx->uring_lock);
1243         return ret;
1244 }
1245
1246 static void kiocb_end_write(struct io_kiocb *req)
1247 {
1248         /*
1249          * Tell lockdep we inherited freeze protection from submission
1250          * thread.
1251          */
1252         if (req->flags & REQ_F_ISREG) {
1253                 struct inode *inode = file_inode(req->file);
1254
1255                 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1256         }
1257         file_end_write(req->file);
1258 }
1259
1260 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1261 {
1262         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1263
1264         if (kiocb->ki_flags & IOCB_WRITE)
1265                 kiocb_end_write(req);
1266
1267         if ((req->flags & REQ_F_LINK) && res != req->result)
1268                 req->flags |= REQ_F_FAIL_LINK;
1269         io_cqring_add_event(req, res);
1270 }
1271
1272 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1273 {
1274         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1275
1276         io_complete_rw_common(kiocb, res);
1277         io_put_req(req);
1278 }
1279
1280 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1281 {
1282         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1283         struct io_kiocb *nxt = NULL;
1284
1285         io_complete_rw_common(kiocb, res);
1286         io_put_req_find_next(req, &nxt);
1287
1288         return nxt;
1289 }
1290
1291 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1292 {
1293         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1294
1295         if (kiocb->ki_flags & IOCB_WRITE)
1296                 kiocb_end_write(req);
1297
1298         if ((req->flags & REQ_F_LINK) && res != req->result)
1299                 req->flags |= REQ_F_FAIL_LINK;
1300         req->result = res;
1301         if (res != -EAGAIN)
1302                 req->flags |= REQ_F_IOPOLL_COMPLETED;
1303 }
1304
1305 /*
1306  * After the iocb has been issued, it's safe to be found on the poll list.
1307  * Adding the kiocb to the list AFTER submission ensures that we don't
1308  * find it from a io_iopoll_getevents() thread before the issuer is done
1309  * accessing the kiocb cookie.
1310  */
1311 static void io_iopoll_req_issued(struct io_kiocb *req)
1312 {
1313         struct io_ring_ctx *ctx = req->ctx;
1314
1315         /*
1316          * Track whether we have multiple files in our lists. This will impact
1317          * how we do polling eventually, not spinning if we're on potentially
1318          * different devices.
1319          */
1320         if (list_empty(&ctx->poll_list)) {
1321                 ctx->poll_multi_file = false;
1322         } else if (!ctx->poll_multi_file) {
1323                 struct io_kiocb *list_req;
1324
1325                 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1326                                                 list);
1327                 if (list_req->rw.ki_filp != req->rw.ki_filp)
1328                         ctx->poll_multi_file = true;
1329         }
1330
1331         /*
1332          * For fast devices, IO may have already completed. If it has, add
1333          * it to the front so we find it first.
1334          */
1335         if (req->flags & REQ_F_IOPOLL_COMPLETED)
1336                 list_add(&req->list, &ctx->poll_list);
1337         else
1338                 list_add_tail(&req->list, &ctx->poll_list);
1339 }
1340
1341 static void io_file_put(struct io_submit_state *state)
1342 {
1343         if (state->file) {
1344                 int diff = state->has_refs - state->used_refs;
1345
1346                 if (diff)
1347                         fput_many(state->file, diff);
1348                 state->file = NULL;
1349         }
1350 }
1351
1352 /*
1353  * Get as many references to a file as we have IOs left in this submission,
1354  * assuming most submissions are for one file, or at least that each file
1355  * has more than one submission.
1356  */
1357 static struct file *io_file_get(struct io_submit_state *state, int fd)
1358 {
1359         if (!state)
1360                 return fget(fd);
1361
1362         if (state->file) {
1363                 if (state->fd == fd) {
1364                         state->used_refs++;
1365                         state->ios_left--;
1366                         return state->file;
1367                 }
1368                 io_file_put(state);
1369         }
1370         state->file = fget_many(fd, state->ios_left);
1371         if (!state->file)
1372                 return NULL;
1373
1374         state->fd = fd;
1375         state->has_refs = state->ios_left;
1376         state->used_refs = 1;
1377         state->ios_left--;
1378         return state->file;
1379 }
1380
1381 /*
1382  * If we tracked the file through the SCM inflight mechanism, we could support
1383  * any file. For now, just ensure that anything potentially problematic is done
1384  * inline.
1385  */
1386 static bool io_file_supports_async(struct file *file)
1387 {
1388         umode_t mode = file_inode(file)->i_mode;
1389
1390         if (S_ISBLK(mode) || S_ISCHR(mode))
1391                 return true;
1392         if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1393                 return true;
1394
1395         return false;
1396 }
1397
1398 static int io_prep_rw(struct io_kiocb *req, bool force_nonblock)
1399 {
1400         const struct io_uring_sqe *sqe = req->sqe;
1401         struct io_ring_ctx *ctx = req->ctx;
1402         struct kiocb *kiocb = &req->rw;
1403         unsigned ioprio;
1404         int ret;
1405
1406         if (!req->file)
1407                 return -EBADF;
1408
1409         if (S_ISREG(file_inode(req->file)->i_mode))
1410                 req->flags |= REQ_F_ISREG;
1411
1412         /*
1413          * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1414          * we know to async punt it even if it was opened O_NONBLOCK
1415          */
1416         if (force_nonblock && !io_file_supports_async(req->file)) {
1417                 req->flags |= REQ_F_MUST_PUNT;
1418                 return -EAGAIN;
1419         }
1420
1421         kiocb->ki_pos = READ_ONCE(sqe->off);
1422         kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1423         kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1424
1425         ioprio = READ_ONCE(sqe->ioprio);
1426         if (ioprio) {
1427                 ret = ioprio_check_cap(ioprio);
1428                 if (ret)
1429                         return ret;
1430
1431                 kiocb->ki_ioprio = ioprio;
1432         } else
1433                 kiocb->ki_ioprio = get_current_ioprio();
1434
1435         ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1436         if (unlikely(ret))
1437                 return ret;
1438
1439         /* don't allow async punt if RWF_NOWAIT was requested */
1440         if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1441             (req->file->f_flags & O_NONBLOCK))
1442                 req->flags |= REQ_F_NOWAIT;
1443
1444         if (force_nonblock)
1445                 kiocb->ki_flags |= IOCB_NOWAIT;
1446
1447         if (ctx->flags & IORING_SETUP_IOPOLL) {
1448                 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1449                     !kiocb->ki_filp->f_op->iopoll)
1450                         return -EOPNOTSUPP;
1451
1452                 kiocb->ki_flags |= IOCB_HIPRI;
1453                 kiocb->ki_complete = io_complete_rw_iopoll;
1454                 req->result = 0;
1455         } else {
1456                 if (kiocb->ki_flags & IOCB_HIPRI)
1457                         return -EINVAL;
1458                 kiocb->ki_complete = io_complete_rw;
1459         }
1460         return 0;
1461 }
1462
1463 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1464 {
1465         switch (ret) {
1466         case -EIOCBQUEUED:
1467                 break;
1468         case -ERESTARTSYS:
1469         case -ERESTARTNOINTR:
1470         case -ERESTARTNOHAND:
1471         case -ERESTART_RESTARTBLOCK:
1472                 /*
1473                  * We can't just restart the syscall, since previously
1474                  * submitted sqes may already be in progress. Just fail this
1475                  * IO with EINTR.
1476                  */
1477                 ret = -EINTR;
1478                 /* fall through */
1479         default:
1480                 kiocb->ki_complete(kiocb, ret, 0);
1481         }
1482 }
1483
1484 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1485                        bool in_async)
1486 {
1487         if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1488                 *nxt = __io_complete_rw(kiocb, ret);
1489         else
1490                 io_rw_done(kiocb, ret);
1491 }
1492
1493 static ssize_t io_import_fixed(struct io_ring_ctx *ctx, int rw,
1494                                const struct io_uring_sqe *sqe,
1495                                struct iov_iter *iter)
1496 {
1497         size_t len = READ_ONCE(sqe->len);
1498         struct io_mapped_ubuf *imu;
1499         unsigned index, buf_index;
1500         size_t offset;
1501         u64 buf_addr;
1502
1503         /* attempt to use fixed buffers without having provided iovecs */
1504         if (unlikely(!ctx->user_bufs))
1505                 return -EFAULT;
1506
1507         buf_index = READ_ONCE(sqe->buf_index);
1508         if (unlikely(buf_index >= ctx->nr_user_bufs))
1509                 return -EFAULT;
1510
1511         index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1512         imu = &ctx->user_bufs[index];
1513         buf_addr = READ_ONCE(sqe->addr);
1514
1515         /* overflow */
1516         if (buf_addr + len < buf_addr)
1517                 return -EFAULT;
1518         /* not inside the mapped region */
1519         if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1520                 return -EFAULT;
1521
1522         /*
1523          * May not be a start of buffer, set size appropriately
1524          * and advance us to the beginning.
1525          */
1526         offset = buf_addr - imu->ubuf;
1527         iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1528
1529         if (offset) {
1530                 /*
1531                  * Don't use iov_iter_advance() here, as it's really slow for
1532                  * using the latter parts of a big fixed buffer - it iterates
1533                  * over each segment manually. We can cheat a bit here, because
1534                  * we know that:
1535                  *
1536                  * 1) it's a BVEC iter, we set it up
1537                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
1538                  *    first and last bvec
1539                  *
1540                  * So just find our index, and adjust the iterator afterwards.
1541                  * If the offset is within the first bvec (or the whole first
1542                  * bvec, just use iov_iter_advance(). This makes it easier
1543                  * since we can just skip the first segment, which may not
1544                  * be PAGE_SIZE aligned.
1545                  */
1546                 const struct bio_vec *bvec = imu->bvec;
1547
1548                 if (offset <= bvec->bv_len) {
1549                         iov_iter_advance(iter, offset);
1550                 } else {
1551                         unsigned long seg_skip;
1552
1553                         /* skip first vec */
1554                         offset -= bvec->bv_len;
1555                         seg_skip = 1 + (offset >> PAGE_SHIFT);
1556
1557                         iter->bvec = bvec + seg_skip;
1558                         iter->nr_segs -= seg_skip;
1559                         iter->count -= bvec->bv_len + offset;
1560                         iter->iov_offset = offset & ~PAGE_MASK;
1561                 }
1562         }
1563
1564         return len;
1565 }
1566
1567 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1568                                struct iovec **iovec, struct iov_iter *iter)
1569 {
1570         const struct io_uring_sqe *sqe = req->sqe;
1571         void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1572         size_t sqe_len = READ_ONCE(sqe->len);
1573         u8 opcode;
1574
1575         /*
1576          * We're reading ->opcode for the second time, but the first read
1577          * doesn't care whether it's _FIXED or not, so it doesn't matter
1578          * whether ->opcode changes concurrently. The first read does care
1579          * about whether it is a READ or a WRITE, so we don't trust this read
1580          * for that purpose and instead let the caller pass in the read/write
1581          * flag.
1582          */
1583         opcode = READ_ONCE(sqe->opcode);
1584         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1585                 *iovec = NULL;
1586                 return io_import_fixed(req->ctx, rw, sqe, iter);
1587         }
1588
1589         if (!req->has_user)
1590                 return -EFAULT;
1591
1592 #ifdef CONFIG_COMPAT
1593         if (req->ctx->compat)
1594                 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1595                                                 iovec, iter);
1596 #endif
1597
1598         return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1599 }
1600
1601 /*
1602  * For files that don't have ->read_iter() and ->write_iter(), handle them
1603  * by looping over ->read() or ->write() manually.
1604  */
1605 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1606                            struct iov_iter *iter)
1607 {
1608         ssize_t ret = 0;
1609
1610         /*
1611          * Don't support polled IO through this interface, and we can't
1612          * support non-blocking either. For the latter, this just causes
1613          * the kiocb to be handled from an async context.
1614          */
1615         if (kiocb->ki_flags & IOCB_HIPRI)
1616                 return -EOPNOTSUPP;
1617         if (kiocb->ki_flags & IOCB_NOWAIT)
1618                 return -EAGAIN;
1619
1620         while (iov_iter_count(iter)) {
1621                 struct iovec iovec;
1622                 ssize_t nr;
1623
1624                 if (!iov_iter_is_bvec(iter)) {
1625                         iovec = iov_iter_iovec(iter);
1626                 } else {
1627                         /* fixed buffers import bvec */
1628                         iovec.iov_base = kmap(iter->bvec->bv_page)
1629                                                 + iter->iov_offset;
1630                         iovec.iov_len = min(iter->count,
1631                                         iter->bvec->bv_len - iter->iov_offset);
1632                 }
1633
1634                 if (rw == READ) {
1635                         nr = file->f_op->read(file, iovec.iov_base,
1636                                               iovec.iov_len, &kiocb->ki_pos);
1637                 } else {
1638                         nr = file->f_op->write(file, iovec.iov_base,
1639                                                iovec.iov_len, &kiocb->ki_pos);
1640                 }
1641
1642                 if (iov_iter_is_bvec(iter))
1643                         kunmap(iter->bvec->bv_page);
1644
1645                 if (nr < 0) {
1646                         if (!ret)
1647                                 ret = nr;
1648                         break;
1649                 }
1650                 ret += nr;
1651                 if (nr != iovec.iov_len)
1652                         break;
1653                 iov_iter_advance(iter, nr);
1654         }
1655
1656         return ret;
1657 }
1658
1659 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
1660                    bool force_nonblock)
1661 {
1662         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1663         struct kiocb *kiocb = &req->rw;
1664         struct iov_iter iter;
1665         struct file *file;
1666         size_t iov_count;
1667         ssize_t read_size, ret;
1668
1669         ret = io_prep_rw(req, force_nonblock);
1670         if (ret)
1671                 return ret;
1672         file = kiocb->ki_filp;
1673
1674         if (unlikely(!(file->f_mode & FMODE_READ)))
1675                 return -EBADF;
1676
1677         ret = io_import_iovec(READ, req, &iovec, &iter);
1678         if (ret < 0)
1679                 return ret;
1680
1681         read_size = ret;
1682         if (req->flags & REQ_F_LINK)
1683                 req->result = read_size;
1684
1685         iov_count = iov_iter_count(&iter);
1686         ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1687         if (!ret) {
1688                 ssize_t ret2;
1689
1690                 if (file->f_op->read_iter)
1691                         ret2 = call_read_iter(file, kiocb, &iter);
1692                 else
1693                         ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1694
1695                 /*
1696                  * In case of a short read, punt to async. This can happen
1697                  * if we have data partially cached. Alternatively we can
1698                  * return the short read, in which case the application will
1699                  * need to issue another SQE and wait for it. That SQE will
1700                  * need async punt anyway, so it's more efficient to do it
1701                  * here.
1702                  */
1703                 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1704                     (req->flags & REQ_F_ISREG) &&
1705                     ret2 > 0 && ret2 < read_size)
1706                         ret2 = -EAGAIN;
1707                 /* Catch -EAGAIN return for forced non-blocking submission */
1708                 if (!force_nonblock || ret2 != -EAGAIN)
1709                         kiocb_done(kiocb, ret2, nxt, req->in_async);
1710                 else
1711                         ret = -EAGAIN;
1712         }
1713         kfree(iovec);
1714         return ret;
1715 }
1716
1717 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
1718                     bool force_nonblock)
1719 {
1720         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1721         struct kiocb *kiocb = &req->rw;
1722         struct iov_iter iter;
1723         struct file *file;
1724         size_t iov_count;
1725         ssize_t ret;
1726
1727         ret = io_prep_rw(req, force_nonblock);
1728         if (ret)
1729                 return ret;
1730
1731         file = kiocb->ki_filp;
1732         if (unlikely(!(file->f_mode & FMODE_WRITE)))
1733                 return -EBADF;
1734
1735         ret = io_import_iovec(WRITE, req, &iovec, &iter);
1736         if (ret < 0)
1737                 return ret;
1738
1739         if (req->flags & REQ_F_LINK)
1740                 req->result = ret;
1741
1742         iov_count = iov_iter_count(&iter);
1743
1744         ret = -EAGAIN;
1745         if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT))
1746                 goto out_free;
1747
1748         ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1749         if (!ret) {
1750                 ssize_t ret2;
1751
1752                 /*
1753                  * Open-code file_start_write here to grab freeze protection,
1754                  * which will be released by another thread in
1755                  * io_complete_rw().  Fool lockdep by telling it the lock got
1756                  * released so that it doesn't complain about the held lock when
1757                  * we return to userspace.
1758                  */
1759                 if (req->flags & REQ_F_ISREG) {
1760                         __sb_start_write(file_inode(file)->i_sb,
1761                                                 SB_FREEZE_WRITE, true);
1762                         __sb_writers_release(file_inode(file)->i_sb,
1763                                                 SB_FREEZE_WRITE);
1764                 }
1765                 kiocb->ki_flags |= IOCB_WRITE;
1766
1767                 if (file->f_op->write_iter)
1768                         ret2 = call_write_iter(file, kiocb, &iter);
1769                 else
1770                         ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1771                 if (!force_nonblock || ret2 != -EAGAIN)
1772                         kiocb_done(kiocb, ret2, nxt, req->in_async);
1773                 else
1774                         ret = -EAGAIN;
1775         }
1776 out_free:
1777         kfree(iovec);
1778         return ret;
1779 }
1780
1781 /*
1782  * IORING_OP_NOP just posts a completion event, nothing else.
1783  */
1784 static int io_nop(struct io_kiocb *req)
1785 {
1786         struct io_ring_ctx *ctx = req->ctx;
1787
1788         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1789                 return -EINVAL;
1790
1791         io_cqring_add_event(req, 0);
1792         io_put_req(req);
1793         return 0;
1794 }
1795
1796 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1797 {
1798         struct io_ring_ctx *ctx = req->ctx;
1799
1800         if (!req->file)
1801                 return -EBADF;
1802
1803         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1804                 return -EINVAL;
1805         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1806                 return -EINVAL;
1807
1808         return 0;
1809 }
1810
1811 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1812                     struct io_kiocb **nxt, bool force_nonblock)
1813 {
1814         loff_t sqe_off = READ_ONCE(sqe->off);
1815         loff_t sqe_len = READ_ONCE(sqe->len);
1816         loff_t end = sqe_off + sqe_len;
1817         unsigned fsync_flags;
1818         int ret;
1819
1820         fsync_flags = READ_ONCE(sqe->fsync_flags);
1821         if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1822                 return -EINVAL;
1823
1824         ret = io_prep_fsync(req, sqe);
1825         if (ret)
1826                 return ret;
1827
1828         /* fsync always requires a blocking context */
1829         if (force_nonblock)
1830                 return -EAGAIN;
1831
1832         ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1833                                 end > 0 ? end : LLONG_MAX,
1834                                 fsync_flags & IORING_FSYNC_DATASYNC);
1835
1836         if (ret < 0 && (req->flags & REQ_F_LINK))
1837                 req->flags |= REQ_F_FAIL_LINK;
1838         io_cqring_add_event(req, ret);
1839         io_put_req_find_next(req, nxt);
1840         return 0;
1841 }
1842
1843 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1844 {
1845         struct io_ring_ctx *ctx = req->ctx;
1846         int ret = 0;
1847
1848         if (!req->file)
1849                 return -EBADF;
1850
1851         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1852                 return -EINVAL;
1853         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1854                 return -EINVAL;
1855
1856         return ret;
1857 }
1858
1859 static int io_sync_file_range(struct io_kiocb *req,
1860                               const struct io_uring_sqe *sqe,
1861                               struct io_kiocb **nxt,
1862                               bool force_nonblock)
1863 {
1864         loff_t sqe_off;
1865         loff_t sqe_len;
1866         unsigned flags;
1867         int ret;
1868
1869         ret = io_prep_sfr(req, sqe);
1870         if (ret)
1871                 return ret;
1872
1873         /* sync_file_range always requires a blocking context */
1874         if (force_nonblock)
1875                 return -EAGAIN;
1876
1877         sqe_off = READ_ONCE(sqe->off);
1878         sqe_len = READ_ONCE(sqe->len);
1879         flags = READ_ONCE(sqe->sync_range_flags);
1880
1881         ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1882
1883         if (ret < 0 && (req->flags & REQ_F_LINK))
1884                 req->flags |= REQ_F_FAIL_LINK;
1885         io_cqring_add_event(req, ret);
1886         io_put_req_find_next(req, nxt);
1887         return 0;
1888 }
1889
1890 #if defined(CONFIG_NET)
1891 static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1892                            struct io_kiocb **nxt, bool force_nonblock,
1893                    long (*fn)(struct socket *, struct user_msghdr __user *,
1894                                 unsigned int))
1895 {
1896         struct socket *sock;
1897         int ret;
1898
1899         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1900                 return -EINVAL;
1901
1902         sock = sock_from_file(req->file, &ret);
1903         if (sock) {
1904                 struct user_msghdr __user *msg;
1905                 unsigned flags;
1906
1907                 flags = READ_ONCE(sqe->msg_flags);
1908                 if (flags & MSG_DONTWAIT)
1909                         req->flags |= REQ_F_NOWAIT;
1910                 else if (force_nonblock)
1911                         flags |= MSG_DONTWAIT;
1912
1913                 msg = (struct user_msghdr __user *) (unsigned long)
1914                         READ_ONCE(sqe->addr);
1915
1916                 ret = fn(sock, msg, flags);
1917                 if (force_nonblock && ret == -EAGAIN)
1918                         return ret;
1919         }
1920
1921         io_cqring_add_event(req, ret);
1922         if (ret < 0 && (req->flags & REQ_F_LINK))
1923                 req->flags |= REQ_F_FAIL_LINK;
1924         io_put_req_find_next(req, nxt);
1925         return 0;
1926 }
1927 #endif
1928
1929 static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1930                       struct io_kiocb **nxt, bool force_nonblock)
1931 {
1932 #if defined(CONFIG_NET)
1933         return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1934                                 __sys_sendmsg_sock);
1935 #else
1936         return -EOPNOTSUPP;
1937 #endif
1938 }
1939
1940 static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1941                       struct io_kiocb **nxt, bool force_nonblock)
1942 {
1943 #if defined(CONFIG_NET)
1944         return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1945                                 __sys_recvmsg_sock);
1946 #else
1947         return -EOPNOTSUPP;
1948 #endif
1949 }
1950
1951 static int io_accept(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1952                      struct io_kiocb **nxt, bool force_nonblock)
1953 {
1954 #if defined(CONFIG_NET)
1955         struct sockaddr __user *addr;
1956         int __user *addr_len;
1957         unsigned file_flags;
1958         int flags, ret;
1959
1960         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
1961                 return -EINVAL;
1962         if (sqe->ioprio || sqe->len || sqe->buf_index)
1963                 return -EINVAL;
1964
1965         addr = (struct sockaddr __user *) (unsigned long) READ_ONCE(sqe->addr);
1966         addr_len = (int __user *) (unsigned long) READ_ONCE(sqe->addr2);
1967         flags = READ_ONCE(sqe->accept_flags);
1968         file_flags = force_nonblock ? O_NONBLOCK : 0;
1969
1970         ret = __sys_accept4_file(req->file, file_flags, addr, addr_len, flags);
1971         if (ret == -EAGAIN && force_nonblock) {
1972                 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
1973                 return -EAGAIN;
1974         }
1975         if (ret == -ERESTARTSYS)
1976                 ret = -EINTR;
1977         if (ret < 0 && (req->flags & REQ_F_LINK))
1978                 req->flags |= REQ_F_FAIL_LINK;
1979         io_cqring_add_event(req, ret);
1980         io_put_req_find_next(req, nxt);
1981         return 0;
1982 #else
1983         return -EOPNOTSUPP;
1984 #endif
1985 }
1986
1987 static int io_connect(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1988                       struct io_kiocb **nxt, bool force_nonblock)
1989 {
1990 #if defined(CONFIG_NET)
1991         struct sockaddr __user *addr;
1992         unsigned file_flags;
1993         int addr_len, ret;
1994
1995         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
1996                 return -EINVAL;
1997         if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
1998                 return -EINVAL;
1999
2000         addr = (struct sockaddr __user *) (unsigned long) READ_ONCE(sqe->addr);
2001         addr_len = READ_ONCE(sqe->addr2);
2002         file_flags = force_nonblock ? O_NONBLOCK : 0;
2003
2004         ret = __sys_connect_file(req->file, addr, addr_len, file_flags);
2005         if (ret == -EAGAIN && force_nonblock)
2006                 return -EAGAIN;
2007         if (ret == -ERESTARTSYS)
2008                 ret = -EINTR;
2009         if (ret < 0 && (req->flags & REQ_F_LINK))
2010                 req->flags |= REQ_F_FAIL_LINK;
2011         io_cqring_add_event(req, ret);
2012         io_put_req_find_next(req, nxt);
2013         return 0;
2014 #else
2015         return -EOPNOTSUPP;
2016 #endif
2017 }
2018
2019 static inline void io_poll_remove_req(struct io_kiocb *req)
2020 {
2021         if (!RB_EMPTY_NODE(&req->rb_node)) {
2022                 rb_erase(&req->rb_node, &req->ctx->cancel_tree);
2023                 RB_CLEAR_NODE(&req->rb_node);
2024         }
2025 }
2026
2027 static void io_poll_remove_one(struct io_kiocb *req)
2028 {
2029         struct io_poll_iocb *poll = &req->poll;
2030
2031         spin_lock(&poll->head->lock);
2032         WRITE_ONCE(poll->canceled, true);
2033         if (!list_empty(&poll->wait->entry)) {
2034                 list_del_init(&poll->wait->entry);
2035                 io_queue_async_work(req);
2036         }
2037         spin_unlock(&poll->head->lock);
2038         io_poll_remove_req(req);
2039 }
2040
2041 static void io_poll_remove_all(struct io_ring_ctx *ctx)
2042 {
2043         struct rb_node *node;
2044         struct io_kiocb *req;
2045
2046         spin_lock_irq(&ctx->completion_lock);
2047         while ((node = rb_first(&ctx->cancel_tree)) != NULL) {
2048                 req = rb_entry(node, struct io_kiocb, rb_node);
2049                 io_poll_remove_one(req);
2050         }
2051         spin_unlock_irq(&ctx->completion_lock);
2052 }
2053
2054 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
2055 {
2056         struct rb_node *p, *parent = NULL;
2057         struct io_kiocb *req;
2058
2059         p = ctx->cancel_tree.rb_node;
2060         while (p) {
2061                 parent = p;
2062                 req = rb_entry(parent, struct io_kiocb, rb_node);
2063                 if (sqe_addr < req->user_data) {
2064                         p = p->rb_left;
2065                 } else if (sqe_addr > req->user_data) {
2066                         p = p->rb_right;
2067                 } else {
2068                         io_poll_remove_one(req);
2069                         return 0;
2070                 }
2071         }
2072
2073         return -ENOENT;
2074 }
2075
2076 /*
2077  * Find a running poll command that matches one specified in sqe->addr,
2078  * and remove it if found.
2079  */
2080 static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2081 {
2082         struct io_ring_ctx *ctx = req->ctx;
2083         int ret;
2084
2085         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2086                 return -EINVAL;
2087         if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
2088             sqe->poll_events)
2089                 return -EINVAL;
2090
2091         spin_lock_irq(&ctx->completion_lock);
2092         ret = io_poll_cancel(ctx, READ_ONCE(sqe->addr));
2093         spin_unlock_irq(&ctx->completion_lock);
2094
2095         io_cqring_add_event(req, ret);
2096         if (ret < 0 && (req->flags & REQ_F_LINK))
2097                 req->flags |= REQ_F_FAIL_LINK;
2098         io_put_req(req);
2099         return 0;
2100 }
2101
2102 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
2103 {
2104         struct io_ring_ctx *ctx = req->ctx;
2105
2106         req->poll.done = true;
2107         kfree(req->poll.wait);
2108         if (error)
2109                 io_cqring_fill_event(req, error);
2110         else
2111                 io_cqring_fill_event(req, mangle_poll(mask));
2112         io_commit_cqring(ctx);
2113 }
2114
2115 static void io_poll_complete_work(struct io_wq_work **workptr)
2116 {
2117         struct io_wq_work *work = *workptr;
2118         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2119         struct io_poll_iocb *poll = &req->poll;
2120         struct poll_table_struct pt = { ._key = poll->events };
2121         struct io_ring_ctx *ctx = req->ctx;
2122         struct io_kiocb *nxt = NULL;
2123         __poll_t mask = 0;
2124         int ret = 0;
2125
2126         if (work->flags & IO_WQ_WORK_CANCEL) {
2127                 WRITE_ONCE(poll->canceled, true);
2128                 ret = -ECANCELED;
2129         } else if (READ_ONCE(poll->canceled)) {
2130                 ret = -ECANCELED;
2131         }
2132
2133         if (ret != -ECANCELED)
2134                 mask = vfs_poll(poll->file, &pt) & poll->events;
2135
2136         /*
2137          * Note that ->ki_cancel callers also delete iocb from active_reqs after
2138          * calling ->ki_cancel.  We need the ctx_lock roundtrip here to
2139          * synchronize with them.  In the cancellation case the list_del_init
2140          * itself is not actually needed, but harmless so we keep it in to
2141          * avoid further branches in the fast path.
2142          */
2143         spin_lock_irq(&ctx->completion_lock);
2144         if (!mask && ret != -ECANCELED) {
2145                 add_wait_queue(poll->head, poll->wait);
2146                 spin_unlock_irq(&ctx->completion_lock);
2147                 return;
2148         }
2149         io_poll_remove_req(req);
2150         io_poll_complete(req, mask, ret);
2151         spin_unlock_irq(&ctx->completion_lock);
2152
2153         io_cqring_ev_posted(ctx);
2154
2155         if (ret < 0 && req->flags & REQ_F_LINK)
2156                 req->flags |= REQ_F_FAIL_LINK;
2157         io_put_req_find_next(req, &nxt);
2158         if (nxt)
2159                 *workptr = &nxt->work;
2160 }
2161
2162 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
2163                         void *key)
2164 {
2165         struct io_poll_iocb *poll = wait->private;
2166         struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
2167         struct io_ring_ctx *ctx = req->ctx;
2168         __poll_t mask = key_to_poll(key);
2169         unsigned long flags;
2170
2171         /* for instances that support it check for an event match first: */
2172         if (mask && !(mask & poll->events))
2173                 return 0;
2174
2175         list_del_init(&poll->wait->entry);
2176
2177         /*
2178          * Run completion inline if we can. We're using trylock here because
2179          * we are violating the completion_lock -> poll wq lock ordering.
2180          * If we have a link timeout we're going to need the completion_lock
2181          * for finalizing the request, mark us as having grabbed that already.
2182          */
2183         if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
2184                 io_poll_remove_req(req);
2185                 io_poll_complete(req, mask, 0);
2186                 req->flags |= REQ_F_COMP_LOCKED;
2187                 io_put_req(req);
2188                 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2189
2190                 io_cqring_ev_posted(ctx);
2191         } else {
2192                 io_queue_async_work(req);
2193         }
2194
2195         return 1;
2196 }
2197
2198 struct io_poll_table {
2199         struct poll_table_struct pt;
2200         struct io_kiocb *req;
2201         int error;
2202 };
2203
2204 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
2205                                struct poll_table_struct *p)
2206 {
2207         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
2208
2209         if (unlikely(pt->req->poll.head)) {
2210                 pt->error = -EINVAL;
2211                 return;
2212         }
2213
2214         pt->error = 0;
2215         pt->req->poll.head = head;
2216         add_wait_queue(head, pt->req->poll.wait);
2217 }
2218
2219 static void io_poll_req_insert(struct io_kiocb *req)
2220 {
2221         struct io_ring_ctx *ctx = req->ctx;
2222         struct rb_node **p = &ctx->cancel_tree.rb_node;
2223         struct rb_node *parent = NULL;
2224         struct io_kiocb *tmp;
2225
2226         while (*p) {
2227                 parent = *p;
2228                 tmp = rb_entry(parent, struct io_kiocb, rb_node);
2229                 if (req->user_data < tmp->user_data)
2230                         p = &(*p)->rb_left;
2231                 else
2232                         p = &(*p)->rb_right;
2233         }
2234         rb_link_node(&req->rb_node, parent, p);
2235         rb_insert_color(&req->rb_node, &ctx->cancel_tree);
2236 }
2237
2238 static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2239                        struct io_kiocb **nxt)
2240 {
2241         struct io_poll_iocb *poll = &req->poll;
2242         struct io_ring_ctx *ctx = req->ctx;
2243         struct io_poll_table ipt;
2244         bool cancel = false;
2245         __poll_t mask;
2246         u16 events;
2247
2248         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2249                 return -EINVAL;
2250         if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
2251                 return -EINVAL;
2252         if (!poll->file)
2253                 return -EBADF;
2254
2255         poll->wait = kmalloc(sizeof(*poll->wait), GFP_KERNEL);
2256         if (!poll->wait)
2257                 return -ENOMEM;
2258
2259         req->sqe = NULL;
2260         INIT_IO_WORK(&req->work, io_poll_complete_work);
2261         events = READ_ONCE(sqe->poll_events);
2262         poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
2263         RB_CLEAR_NODE(&req->rb_node);
2264
2265         poll->head = NULL;
2266         poll->done = false;
2267         poll->canceled = false;
2268
2269         ipt.pt._qproc = io_poll_queue_proc;
2270         ipt.pt._key = poll->events;
2271         ipt.req = req;
2272         ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
2273
2274         /* initialized the list so that we can do list_empty checks */
2275         INIT_LIST_HEAD(&poll->wait->entry);
2276         init_waitqueue_func_entry(poll->wait, io_poll_wake);
2277         poll->wait->private = poll;
2278
2279         INIT_LIST_HEAD(&req->list);
2280
2281         mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
2282
2283         spin_lock_irq(&ctx->completion_lock);
2284         if (likely(poll->head)) {
2285                 spin_lock(&poll->head->lock);
2286                 if (unlikely(list_empty(&poll->wait->entry))) {
2287                         if (ipt.error)
2288                                 cancel = true;
2289                         ipt.error = 0;
2290                         mask = 0;
2291                 }
2292                 if (mask || ipt.error)
2293                         list_del_init(&poll->wait->entry);
2294                 else if (cancel)
2295                         WRITE_ONCE(poll->canceled, true);
2296                 else if (!poll->done) /* actually waiting for an event */
2297                         io_poll_req_insert(req);
2298                 spin_unlock(&poll->head->lock);
2299         }
2300         if (mask) { /* no async, we'd stolen it */
2301                 ipt.error = 0;
2302                 io_poll_complete(req, mask, 0);
2303         }
2304         spin_unlock_irq(&ctx->completion_lock);
2305
2306         if (mask) {
2307                 io_cqring_ev_posted(ctx);
2308                 io_put_req_find_next(req, nxt);
2309         }
2310         return ipt.error;
2311 }
2312
2313 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
2314 {
2315         struct io_timeout_data *data = container_of(timer,
2316                                                 struct io_timeout_data, timer);
2317         struct io_kiocb *req = data->req;
2318         struct io_ring_ctx *ctx = req->ctx;
2319         unsigned long flags;
2320
2321         atomic_inc(&ctx->cq_timeouts);
2322
2323         spin_lock_irqsave(&ctx->completion_lock, flags);
2324         /*
2325          * We could be racing with timeout deletion. If the list is empty,
2326          * then timeout lookup already found it and will be handling it.
2327          */
2328         if (!list_empty(&req->list)) {
2329                 struct io_kiocb *prev;
2330
2331                 /*
2332                  * Adjust the reqs sequence before the current one because it
2333                  * will consume a slot in the cq_ring and the the cq_tail
2334                  * pointer will be increased, otherwise other timeout reqs may
2335                  * return in advance without waiting for enough wait_nr.
2336                  */
2337                 prev = req;
2338                 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
2339                         prev->sequence++;
2340                 list_del_init(&req->list);
2341         }
2342
2343         io_cqring_fill_event(req, -ETIME);
2344         io_commit_cqring(ctx);
2345         spin_unlock_irqrestore(&ctx->completion_lock, flags);
2346
2347         io_cqring_ev_posted(ctx);
2348         if (req->flags & REQ_F_LINK)
2349                 req->flags |= REQ_F_FAIL_LINK;
2350         io_put_req(req);
2351         return HRTIMER_NORESTART;
2352 }
2353
2354 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
2355 {
2356         struct io_kiocb *req;
2357         int ret = -ENOENT;
2358
2359         list_for_each_entry(req, &ctx->timeout_list, list) {
2360                 if (user_data == req->user_data) {
2361                         list_del_init(&req->list);
2362                         ret = 0;
2363                         break;
2364                 }
2365         }
2366
2367         if (ret == -ENOENT)
2368                 return ret;
2369
2370         ret = hrtimer_try_to_cancel(&req->timeout.data->timer);
2371         if (ret == -1)
2372                 return -EALREADY;
2373
2374         if (req->flags & REQ_F_LINK)
2375                 req->flags |= REQ_F_FAIL_LINK;
2376         io_cqring_fill_event(req, -ECANCELED);
2377         io_put_req(req);
2378         return 0;
2379 }
2380
2381 /*
2382  * Remove or update an existing timeout command
2383  */
2384 static int io_timeout_remove(struct io_kiocb *req,
2385                              const struct io_uring_sqe *sqe)
2386 {
2387         struct io_ring_ctx *ctx = req->ctx;
2388         unsigned flags;
2389         int ret;
2390
2391         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2392                 return -EINVAL;
2393         if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
2394                 return -EINVAL;
2395         flags = READ_ONCE(sqe->timeout_flags);
2396         if (flags)
2397                 return -EINVAL;
2398
2399         spin_lock_irq(&ctx->completion_lock);
2400         ret = io_timeout_cancel(ctx, READ_ONCE(sqe->addr));
2401
2402         io_cqring_fill_event(req, ret);
2403         io_commit_cqring(ctx);
2404         spin_unlock_irq(&ctx->completion_lock);
2405         io_cqring_ev_posted(ctx);
2406         if (ret < 0 && req->flags & REQ_F_LINK)
2407                 req->flags |= REQ_F_FAIL_LINK;
2408         io_put_req(req);
2409         return 0;
2410 }
2411
2412 static int io_timeout_setup(struct io_kiocb *req)
2413 {
2414         const struct io_uring_sqe *sqe = req->sqe;
2415         struct io_timeout_data *data;
2416         unsigned flags;
2417
2418         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2419                 return -EINVAL;
2420         if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
2421                 return -EINVAL;
2422         flags = READ_ONCE(sqe->timeout_flags);
2423         if (flags & ~IORING_TIMEOUT_ABS)
2424                 return -EINVAL;
2425
2426         data = kzalloc(sizeof(struct io_timeout_data), GFP_KERNEL);
2427         if (!data)
2428                 return -ENOMEM;
2429         data->req = req;
2430         req->timeout.data = data;
2431         req->flags |= REQ_F_TIMEOUT;
2432
2433         if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
2434                 return -EFAULT;
2435
2436         if (flags & IORING_TIMEOUT_ABS)
2437                 data->mode = HRTIMER_MODE_ABS;
2438         else
2439                 data->mode = HRTIMER_MODE_REL;
2440
2441         hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
2442         return 0;
2443 }
2444
2445 static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2446 {
2447         unsigned count;
2448         struct io_ring_ctx *ctx = req->ctx;
2449         struct io_timeout_data *data;
2450         struct list_head *entry;
2451         unsigned span = 0;
2452         int ret;
2453
2454         ret = io_timeout_setup(req);
2455         /* common setup allows flags (like links) set, we don't */
2456         if (!ret && sqe->flags)
2457                 ret = -EINVAL;
2458         if (ret)
2459                 return ret;
2460
2461         /*
2462          * sqe->off holds how many events that need to occur for this
2463          * timeout event to be satisfied. If it isn't set, then this is
2464          * a pure timeout request, sequence isn't used.
2465          */
2466         count = READ_ONCE(sqe->off);
2467         if (!count) {
2468                 req->flags |= REQ_F_TIMEOUT_NOSEQ;
2469                 spin_lock_irq(&ctx->completion_lock);
2470                 entry = ctx->timeout_list.prev;
2471                 goto add;
2472         }
2473
2474         req->sequence = ctx->cached_sq_head + count - 1;
2475         req->timeout.data->seq_offset = count;
2476
2477         /*
2478          * Insertion sort, ensuring the first entry in the list is always
2479          * the one we need first.
2480          */
2481         spin_lock_irq(&ctx->completion_lock);
2482         list_for_each_prev(entry, &ctx->timeout_list) {
2483                 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
2484                 unsigned nxt_sq_head;
2485                 long long tmp, tmp_nxt;
2486                 u32 nxt_offset = nxt->timeout.data->seq_offset;
2487
2488                 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
2489                         continue;
2490
2491                 /*
2492                  * Since cached_sq_head + count - 1 can overflow, use type long
2493                  * long to store it.
2494                  */
2495                 tmp = (long long)ctx->cached_sq_head + count - 1;
2496                 nxt_sq_head = nxt->sequence - nxt_offset + 1;
2497                 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
2498
2499                 /*
2500                  * cached_sq_head may overflow, and it will never overflow twice
2501                  * once there is some timeout req still be valid.
2502                  */
2503                 if (ctx->cached_sq_head < nxt_sq_head)
2504                         tmp += UINT_MAX;
2505
2506                 if (tmp > tmp_nxt)
2507                         break;
2508
2509                 /*
2510                  * Sequence of reqs after the insert one and itself should
2511                  * be adjusted because each timeout req consumes a slot.
2512                  */
2513                 span++;
2514                 nxt->sequence++;
2515         }
2516         req->sequence -= span;
2517 add:
2518         list_add(&req->list, entry);
2519         data = req->timeout.data;
2520         data->timer.function = io_timeout_fn;
2521         hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
2522         spin_unlock_irq(&ctx->completion_lock);
2523         return 0;
2524 }
2525
2526 static bool io_cancel_cb(struct io_wq_work *work, void *data)
2527 {
2528         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2529
2530         return req->user_data == (unsigned long) data;
2531 }
2532
2533 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
2534 {
2535         enum io_wq_cancel cancel_ret;
2536         int ret = 0;
2537
2538         cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
2539         switch (cancel_ret) {
2540         case IO_WQ_CANCEL_OK:
2541                 ret = 0;
2542                 break;
2543         case IO_WQ_CANCEL_RUNNING:
2544                 ret = -EALREADY;
2545                 break;
2546         case IO_WQ_CANCEL_NOTFOUND:
2547                 ret = -ENOENT;
2548                 break;
2549         }
2550
2551         return ret;
2552 }
2553
2554 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
2555                                      struct io_kiocb *req, __u64 sqe_addr,
2556                                      struct io_kiocb **nxt, int success_ret)
2557 {
2558         unsigned long flags;
2559         int ret;
2560
2561         ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
2562         if (ret != -ENOENT) {
2563                 spin_lock_irqsave(&ctx->completion_lock, flags);
2564                 goto done;
2565         }
2566
2567         spin_lock_irqsave(&ctx->completion_lock, flags);
2568         ret = io_timeout_cancel(ctx, sqe_addr);
2569         if (ret != -ENOENT)
2570                 goto done;
2571         ret = io_poll_cancel(ctx, sqe_addr);
2572 done:
2573         if (!ret)
2574                 ret = success_ret;
2575         io_cqring_fill_event(req, ret);
2576         io_commit_cqring(ctx);
2577         spin_unlock_irqrestore(&ctx->completion_lock, flags);
2578         io_cqring_ev_posted(ctx);
2579
2580         if (ret < 0 && (req->flags & REQ_F_LINK))
2581                 req->flags |= REQ_F_FAIL_LINK;
2582         io_put_req_find_next(req, nxt);
2583 }
2584
2585 static int io_async_cancel(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2586                            struct io_kiocb **nxt)
2587 {
2588         struct io_ring_ctx *ctx = req->ctx;
2589
2590         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2591                 return -EINVAL;
2592         if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
2593             sqe->cancel_flags)
2594                 return -EINVAL;
2595
2596         io_async_find_and_cancel(ctx, req, READ_ONCE(sqe->addr), nxt, 0);
2597         return 0;
2598 }
2599
2600 static int io_req_defer(struct io_kiocb *req)
2601 {
2602         struct io_uring_sqe *sqe_copy;
2603         struct io_ring_ctx *ctx = req->ctx;
2604
2605         /* Still need defer if there is pending req in defer list. */
2606         if (!req_need_defer(req) && list_empty(&ctx->defer_list))
2607                 return 0;
2608
2609         sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
2610         if (!sqe_copy)
2611                 return -EAGAIN;
2612
2613         spin_lock_irq(&ctx->completion_lock);
2614         if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
2615                 spin_unlock_irq(&ctx->completion_lock);
2616                 kfree(sqe_copy);
2617                 return 0;
2618         }
2619
2620         memcpy(sqe_copy, req->sqe, sizeof(*sqe_copy));
2621         req->flags |= REQ_F_FREE_SQE;
2622         req->sqe = sqe_copy;
2623
2624         trace_io_uring_defer(ctx, req, req->user_data);
2625         list_add_tail(&req->list, &ctx->defer_list);
2626         spin_unlock_irq(&ctx->completion_lock);
2627         return -EIOCBQUEUED;
2628 }
2629
2630 __attribute__((nonnull))
2631 static int io_issue_sqe(struct io_kiocb *req, struct io_kiocb **nxt,
2632                         bool force_nonblock)
2633 {
2634         int ret, opcode;
2635         struct io_ring_ctx *ctx = req->ctx;
2636
2637         opcode = READ_ONCE(req->sqe->opcode);
2638         switch (opcode) {
2639         case IORING_OP_NOP:
2640                 ret = io_nop(req);
2641                 break;
2642         case IORING_OP_READV:
2643                 if (unlikely(req->sqe->buf_index))
2644                         return -EINVAL;
2645                 ret = io_read(req, nxt, force_nonblock);
2646                 break;
2647         case IORING_OP_WRITEV:
2648                 if (unlikely(req->sqe->buf_index))
2649                         return -EINVAL;
2650                 ret = io_write(req, nxt, force_nonblock);
2651                 break;
2652         case IORING_OP_READ_FIXED:
2653                 ret = io_read(req, nxt, force_nonblock);
2654                 break;
2655         case IORING_OP_WRITE_FIXED:
2656                 ret = io_write(req, nxt, force_nonblock);
2657                 break;
2658         case IORING_OP_FSYNC:
2659                 ret = io_fsync(req, req->sqe, nxt, force_nonblock);
2660                 break;
2661         case IORING_OP_POLL_ADD:
2662                 ret = io_poll_add(req, req->sqe, nxt);
2663                 break;
2664         case IORING_OP_POLL_REMOVE:
2665                 ret = io_poll_remove(req, req->sqe);
2666                 break;
2667         case IORING_OP_SYNC_FILE_RANGE:
2668                 ret = io_sync_file_range(req, req->sqe, nxt, force_nonblock);
2669                 break;
2670         case IORING_OP_SENDMSG:
2671                 ret = io_sendmsg(req, req->sqe, nxt, force_nonblock);
2672                 break;
2673         case IORING_OP_RECVMSG:
2674                 ret = io_recvmsg(req, req->sqe, nxt, force_nonblock);
2675                 break;
2676         case IORING_OP_TIMEOUT:
2677                 ret = io_timeout(req, req->sqe);
2678                 break;
2679         case IORING_OP_TIMEOUT_REMOVE:
2680                 ret = io_timeout_remove(req, req->sqe);
2681                 break;
2682         case IORING_OP_ACCEPT:
2683                 ret = io_accept(req, req->sqe, nxt, force_nonblock);
2684                 break;
2685         case IORING_OP_CONNECT:
2686                 ret = io_connect(req, req->sqe, nxt, force_nonblock);
2687                 break;
2688         case IORING_OP_ASYNC_CANCEL:
2689                 ret = io_async_cancel(req, req->sqe, nxt);
2690                 break;
2691         default:
2692                 ret = -EINVAL;
2693                 break;
2694         }
2695
2696         if (ret)
2697                 return ret;
2698
2699         if (ctx->flags & IORING_SETUP_IOPOLL) {
2700                 if (req->result == -EAGAIN)
2701                         return -EAGAIN;
2702
2703                 /* workqueue context doesn't hold uring_lock, grab it now */
2704                 if (req->in_async)
2705                         mutex_lock(&ctx->uring_lock);
2706                 io_iopoll_req_issued(req);
2707                 if (req->in_async)
2708                         mutex_unlock(&ctx->uring_lock);
2709         }
2710
2711         return 0;
2712 }
2713
2714 static void io_link_work_cb(struct io_wq_work **workptr)
2715 {
2716         struct io_wq_work *work = *workptr;
2717         struct io_kiocb *link = work->data;
2718
2719         io_queue_linked_timeout(link);
2720         work->func = io_wq_submit_work;
2721 }
2722
2723 static void io_wq_submit_work(struct io_wq_work **workptr)
2724 {
2725         struct io_wq_work *work = *workptr;
2726         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2727         struct io_kiocb *nxt = NULL;
2728         int ret = 0;
2729
2730         /* Ensure we clear previously set non-block flag */
2731         req->rw.ki_flags &= ~IOCB_NOWAIT;
2732
2733         if (work->flags & IO_WQ_WORK_CANCEL)
2734                 ret = -ECANCELED;
2735
2736         if (!ret) {
2737                 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
2738                 req->in_async = true;
2739                 do {
2740                         ret = io_issue_sqe(req, &nxt, false);
2741                         /*
2742                          * We can get EAGAIN for polled IO even though we're
2743                          * forcing a sync submission from here, since we can't
2744                          * wait for request slots on the block side.
2745                          */
2746                         if (ret != -EAGAIN)
2747                                 break;
2748                         cond_resched();
2749                 } while (1);
2750         }
2751
2752         /* drop submission reference */
2753         io_put_req(req);
2754
2755         if (ret) {
2756                 if (req->flags & REQ_F_LINK)
2757                         req->flags |= REQ_F_FAIL_LINK;
2758                 io_cqring_add_event(req, ret);
2759                 io_put_req(req);
2760         }
2761
2762         /* if a dependent link is ready, pass it back */
2763         if (!ret && nxt) {
2764                 struct io_kiocb *link;
2765
2766                 io_prep_async_work(nxt, &link);
2767                 *workptr = &nxt->work;
2768                 if (link) {
2769                         nxt->work.flags |= IO_WQ_WORK_CB;
2770                         nxt->work.func = io_link_work_cb;
2771                         nxt->work.data = link;
2772                 }
2773         }
2774 }
2775
2776 static bool io_op_needs_file(const struct io_uring_sqe *sqe)
2777 {
2778         int op = READ_ONCE(sqe->opcode);
2779
2780         switch (op) {
2781         case IORING_OP_NOP:
2782         case IORING_OP_POLL_REMOVE:
2783         case IORING_OP_TIMEOUT:
2784         case IORING_OP_TIMEOUT_REMOVE:
2785         case IORING_OP_ASYNC_CANCEL:
2786         case IORING_OP_LINK_TIMEOUT:
2787                 return false;
2788         default:
2789                 return true;
2790         }
2791 }
2792
2793 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
2794                                               int index)
2795 {
2796         struct fixed_file_table *table;
2797
2798         table = &ctx->file_table[index >> IORING_FILE_TABLE_SHIFT];
2799         return table->files[index & IORING_FILE_TABLE_MASK];
2800 }
2801
2802 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req)
2803 {
2804         struct io_ring_ctx *ctx = req->ctx;
2805         unsigned flags;
2806         int fd;
2807
2808         flags = READ_ONCE(req->sqe->flags);
2809         fd = READ_ONCE(req->sqe->fd);
2810
2811         if (flags & IOSQE_IO_DRAIN)
2812                 req->flags |= REQ_F_IO_DRAIN;
2813
2814         if (!io_op_needs_file(req->sqe))
2815                 return 0;
2816
2817         if (flags & IOSQE_FIXED_FILE) {
2818                 if (unlikely(!ctx->file_table ||
2819                     (unsigned) fd >= ctx->nr_user_files))
2820                         return -EBADF;
2821                 fd = array_index_nospec(fd, ctx->nr_user_files);
2822                 req->file = io_file_from_index(ctx, fd);
2823                 if (!req->file)
2824                         return -EBADF;
2825                 req->flags |= REQ_F_FIXED_FILE;
2826         } else {
2827                 if (req->needs_fixed_file)
2828                         return -EBADF;
2829                 trace_io_uring_file_get(ctx, fd);
2830                 req->file = io_file_get(state, fd);
2831                 if (unlikely(!req->file))
2832                         return -EBADF;
2833         }
2834
2835         return 0;
2836 }
2837
2838 static int io_grab_files(struct io_kiocb *req)
2839 {
2840         int ret = -EBADF;
2841         struct io_ring_ctx *ctx = req->ctx;
2842
2843         rcu_read_lock();
2844         spin_lock_irq(&ctx->inflight_lock);
2845         /*
2846          * We use the f_ops->flush() handler to ensure that we can flush
2847          * out work accessing these files if the fd is closed. Check if
2848          * the fd has changed since we started down this path, and disallow
2849          * this operation if it has.
2850          */
2851         if (fcheck(req->ring_fd) == req->ring_file) {
2852                 list_add(&req->inflight_entry, &ctx->inflight_list);
2853                 req->flags |= REQ_F_INFLIGHT;
2854                 req->work.files = current->files;
2855                 ret = 0;
2856         }
2857         spin_unlock_irq(&ctx->inflight_lock);
2858         rcu_read_unlock();
2859
2860         return ret;
2861 }
2862
2863 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
2864 {
2865         struct io_timeout_data *data = container_of(timer,
2866                                                 struct io_timeout_data, timer);
2867         struct io_kiocb *req = data->req;
2868         struct io_ring_ctx *ctx = req->ctx;
2869         struct io_kiocb *prev = NULL;
2870         unsigned long flags;
2871
2872         spin_lock_irqsave(&ctx->completion_lock, flags);
2873
2874         /*
2875          * We don't expect the list to be empty, that will only happen if we
2876          * race with the completion of the linked work.
2877          */
2878         if (!list_empty(&req->list)) {
2879                 prev = list_entry(req->list.prev, struct io_kiocb, link_list);
2880                 if (refcount_inc_not_zero(&prev->refs)) {
2881                         list_del_init(&req->list);
2882                         prev->flags &= ~REQ_F_LINK_TIMEOUT;
2883                 } else
2884                         prev = NULL;
2885         }
2886
2887         spin_unlock_irqrestore(&ctx->completion_lock, flags);
2888
2889         if (prev) {
2890                 if (prev->flags & REQ_F_LINK)
2891                         prev->flags |= REQ_F_FAIL_LINK;
2892                 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
2893                                                 -ETIME);
2894                 io_put_req(prev);
2895         } else {
2896                 io_cqring_add_event(req, -ETIME);
2897                 io_put_req(req);
2898         }
2899         return HRTIMER_NORESTART;
2900 }
2901
2902 static void io_queue_linked_timeout(struct io_kiocb *req)
2903 {
2904         struct io_ring_ctx *ctx = req->ctx;
2905
2906         /*
2907          * If the list is now empty, then our linked request finished before
2908          * we got a chance to setup the timer
2909          */
2910         spin_lock_irq(&ctx->completion_lock);
2911         if (!list_empty(&req->list)) {
2912                 struct io_timeout_data *data = req->timeout.data;
2913
2914                 data->timer.function = io_link_timeout_fn;
2915                 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
2916                                 data->mode);
2917         }
2918         spin_unlock_irq(&ctx->completion_lock);
2919
2920         /* drop submission reference */
2921         io_put_req(req);
2922 }
2923
2924 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
2925 {
2926         struct io_kiocb *nxt;
2927
2928         if (!(req->flags & REQ_F_LINK))
2929                 return NULL;
2930
2931         nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
2932         if (!nxt || nxt->sqe->opcode != IORING_OP_LINK_TIMEOUT)
2933                 return NULL;
2934
2935         req->flags |= REQ_F_LINK_TIMEOUT;
2936         return nxt;
2937 }
2938
2939 static void __io_queue_sqe(struct io_kiocb *req)
2940 {
2941         struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
2942         struct io_kiocb *nxt = NULL;
2943         int ret;
2944
2945         ret = io_issue_sqe(req, &nxt, true);
2946         if (nxt)
2947                 io_queue_async_work(nxt);
2948
2949         /*
2950          * We async punt it if the file wasn't marked NOWAIT, or if the file
2951          * doesn't support non-blocking read/write attempts
2952          */
2953         if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
2954             (req->flags & REQ_F_MUST_PUNT))) {
2955                 struct io_uring_sqe *sqe_copy;
2956
2957                 sqe_copy = kmemdup(req->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2958                 if (!sqe_copy)
2959                         goto err;
2960
2961                 req->sqe = sqe_copy;
2962                 req->flags |= REQ_F_FREE_SQE;
2963
2964                 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
2965                         ret = io_grab_files(req);
2966                         if (ret)
2967                                 goto err;
2968                 }
2969
2970                 /*
2971                  * Queued up for async execution, worker will release
2972                  * submit reference when the iocb is actually submitted.
2973                  */
2974                 io_queue_async_work(req);
2975                 return;
2976         }
2977
2978 err:
2979         /* drop submission reference */
2980         io_put_req(req);
2981
2982         if (linked_timeout) {
2983                 if (!ret)
2984                         io_queue_linked_timeout(linked_timeout);
2985                 else
2986                         io_put_req(linked_timeout);
2987         }
2988
2989         /* and drop final reference, if we failed */
2990         if (ret) {
2991                 io_cqring_add_event(req, ret);
2992                 if (req->flags & REQ_F_LINK)
2993                         req->flags |= REQ_F_FAIL_LINK;
2994                 io_put_req(req);
2995         }
2996 }
2997
2998 static void io_queue_sqe(struct io_kiocb *req)
2999 {
3000         int ret;
3001
3002         if (unlikely(req->ctx->drain_next)) {
3003                 req->flags |= REQ_F_IO_DRAIN;
3004                 req->ctx->drain_next = false;
3005         }
3006         req->ctx->drain_next = (req->flags & REQ_F_DRAIN_LINK);
3007
3008         ret = io_req_defer(req);
3009         if (ret) {
3010                 if (ret != -EIOCBQUEUED) {
3011                         io_cqring_add_event(req, ret);
3012                         if (req->flags & REQ_F_LINK)
3013                                 req->flags |= REQ_F_FAIL_LINK;
3014                         io_double_put_req(req);
3015                 }
3016         } else
3017                 __io_queue_sqe(req);
3018 }
3019
3020 static inline void io_queue_link_head(struct io_kiocb *req)
3021 {
3022         if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
3023                 io_cqring_add_event(req, -ECANCELED);
3024                 io_double_put_req(req);
3025         } else
3026                 io_queue_sqe(req);
3027 }
3028
3029
3030 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
3031
3032 static void io_submit_sqe(struct io_kiocb *req, struct io_submit_state *state,
3033                           struct io_kiocb **link)
3034 {
3035         struct io_ring_ctx *ctx = req->ctx;
3036         int ret;
3037
3038         req->user_data = req->sqe->user_data;
3039
3040         /* enforce forwards compatibility on users */
3041         if (unlikely(req->sqe->flags & ~SQE_VALID_FLAGS)) {
3042                 ret = -EINVAL;
3043                 goto err_req;
3044         }
3045
3046         ret = io_req_set_file(state, req);
3047         if (unlikely(ret)) {
3048 err_req:
3049                 io_cqring_add_event(req, ret);
3050                 io_double_put_req(req);
3051                 return;
3052         }
3053
3054         /*
3055          * If we already have a head request, queue this one for async
3056          * submittal once the head completes. If we don't have a head but
3057          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
3058          * submitted sync once the chain is complete. If none of those
3059          * conditions are true (normal request), then just queue it.
3060          */
3061         if (*link) {
3062                 struct io_kiocb *prev = *link;
3063                 struct io_uring_sqe *sqe_copy;
3064
3065                 if (req->sqe->flags & IOSQE_IO_DRAIN)
3066                         (*link)->flags |= REQ_F_DRAIN_LINK | REQ_F_IO_DRAIN;
3067
3068                 if (READ_ONCE(req->sqe->opcode) == IORING_OP_LINK_TIMEOUT) {
3069                         ret = io_timeout_setup(req);
3070                         /* common setup allows offset being set, we don't */
3071                         if (!ret && req->sqe->off)
3072                                 ret = -EINVAL;
3073                         if (ret) {
3074                                 prev->flags |= REQ_F_FAIL_LINK;
3075                                 goto err_req;
3076                         }
3077                 }
3078
3079                 sqe_copy = kmemdup(req->sqe, sizeof(*sqe_copy), GFP_KERNEL);
3080                 if (!sqe_copy) {
3081                         ret = -EAGAIN;
3082                         goto err_req;
3083                 }
3084
3085                 req->sqe = sqe_copy;
3086                 req->flags |= REQ_F_FREE_SQE;
3087                 trace_io_uring_link(ctx, req, prev);
3088                 list_add_tail(&req->list, &prev->link_list);
3089         } else if (req->sqe->flags & IOSQE_IO_LINK) {
3090                 req->flags |= REQ_F_LINK;
3091
3092                 INIT_LIST_HEAD(&req->link_list);
3093                 *link = req;
3094         } else {
3095                 io_queue_sqe(req);
3096         }
3097 }
3098
3099 /*
3100  * Batched submission is done, ensure local IO is flushed out.
3101  */
3102 static void io_submit_state_end(struct io_submit_state *state)
3103 {
3104         blk_finish_plug(&state->plug);
3105         io_file_put(state);
3106         if (state->free_reqs)
3107                 kmem_cache_free_bulk(req_cachep, state->free_reqs,
3108                                         &state->reqs[state->cur_req]);
3109 }
3110
3111 /*
3112  * Start submission side cache.
3113  */
3114 static void io_submit_state_start(struct io_submit_state *state,
3115                                   struct io_ring_ctx *ctx, unsigned max_ios)
3116 {
3117         blk_start_plug(&state->plug);
3118         state->free_reqs = 0;
3119         state->file = NULL;
3120         state->ios_left = max_ios;
3121 }
3122
3123 static void io_commit_sqring(struct io_ring_ctx *ctx)
3124 {
3125         struct io_rings *rings = ctx->rings;
3126
3127         if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
3128                 /*
3129                  * Ensure any loads from the SQEs are done at this point,
3130                  * since once we write the new head, the application could
3131                  * write new data to them.
3132                  */
3133                 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
3134         }
3135 }
3136
3137 /*
3138  * Fetch an sqe, if one is available. Note that s->sqe will point to memory
3139  * that is mapped by userspace. This means that care needs to be taken to
3140  * ensure that reads are stable, as we cannot rely on userspace always
3141  * being a good citizen. If members of the sqe are validated and then later
3142  * used, it's important that those reads are done through READ_ONCE() to
3143  * prevent a re-load down the line.
3144  */
3145 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req)
3146 {
3147         struct io_rings *rings = ctx->rings;
3148         u32 *sq_array = ctx->sq_array;
3149         unsigned head;
3150
3151         /*
3152          * The cached sq head (or cq tail) serves two purposes:
3153          *
3154          * 1) allows us to batch the cost of updating the user visible
3155          *    head updates.
3156          * 2) allows the kernel side to track the head on its own, even
3157          *    though the application is the one updating it.
3158          */
3159         head = ctx->cached_sq_head;
3160         /* make sure SQ entry isn't read before tail */
3161         if (unlikely(head == smp_load_acquire(&rings->sq.tail)))
3162                 return false;
3163
3164         head = READ_ONCE(sq_array[head & ctx->sq_mask]);
3165         if (likely(head < ctx->sq_entries)) {
3166                 /*
3167                  * All io need record the previous position, if LINK vs DARIN,
3168                  * it can be used to mark the position of the first IO in the
3169                  * link list.
3170                  */
3171                 req->sequence = ctx->cached_sq_head;
3172                 req->sqe = &ctx->sq_sqes[head];
3173                 ctx->cached_sq_head++;
3174                 return true;
3175         }
3176
3177         /* drop invalid entries */
3178         ctx->cached_sq_head++;
3179         ctx->cached_sq_dropped++;
3180         WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
3181         return false;
3182 }
3183
3184 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
3185                           struct file *ring_file, int ring_fd,
3186                           struct mm_struct **mm, bool async)
3187 {
3188         struct io_submit_state state, *statep = NULL;
3189         struct io_kiocb *link = NULL;
3190         int i, submitted = 0;
3191         bool mm_fault = false;
3192
3193         /* if we have a backlog and couldn't flush it all, return BUSY */
3194         if (!list_empty(&ctx->cq_overflow_list) &&
3195             !io_cqring_overflow_flush(ctx, false))
3196                 return -EBUSY;
3197
3198         if (nr > IO_PLUG_THRESHOLD) {
3199                 io_submit_state_start(&state, ctx, nr);
3200                 statep = &state;
3201         }
3202
3203         for (i = 0; i < nr; i++) {
3204                 struct io_kiocb *req;
3205                 unsigned int sqe_flags;
3206
3207                 req = io_get_req(ctx, statep);
3208                 if (unlikely(!req)) {
3209                         if (!submitted)
3210                                 submitted = -EAGAIN;
3211                         break;
3212                 }
3213                 if (!io_get_sqring(ctx, req)) {
3214                         __io_free_req(req);
3215                         break;
3216                 }
3217
3218                 if (io_sqe_needs_user(req->sqe) && !*mm) {
3219                         mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
3220                         if (!mm_fault) {
3221                                 use_mm(ctx->sqo_mm);
3222                                 *mm = ctx->sqo_mm;
3223                         }
3224                 }
3225
3226                 sqe_flags = req->sqe->flags;
3227
3228                 req->ring_file = ring_file;
3229                 req->ring_fd = ring_fd;
3230                 req->has_user = *mm != NULL;
3231                 req->in_async = async;
3232                 req->needs_fixed_file = async;
3233                 trace_io_uring_submit_sqe(ctx, req->sqe->user_data,
3234                                           true, async);
3235                 io_submit_sqe(req, statep, &link);
3236                 submitted++;
3237
3238                 /*
3239                  * If previous wasn't linked and we have a linked command,
3240                  * that's the end of the chain. Submit the previous link.
3241                  */
3242                 if (!(sqe_flags & IOSQE_IO_LINK) && link) {
3243                         io_queue_link_head(link);
3244                         link = NULL;
3245                 }
3246         }
3247
3248         if (link)
3249                 io_queue_link_head(link);
3250         if (statep)
3251                 io_submit_state_end(&state);
3252
3253          /* Commit SQ ring head once we've consumed and submitted all SQEs */
3254         io_commit_sqring(ctx);
3255
3256         return submitted;
3257 }
3258
3259 static int io_sq_thread(void *data)
3260 {
3261         struct io_ring_ctx *ctx = data;
3262         struct mm_struct *cur_mm = NULL;
3263         const struct cred *old_cred;
3264         mm_segment_t old_fs;
3265         DEFINE_WAIT(wait);
3266         unsigned inflight;
3267         unsigned long timeout;
3268         int ret;
3269
3270         complete(&ctx->completions[1]);
3271
3272         old_fs = get_fs();
3273         set_fs(USER_DS);
3274         old_cred = override_creds(ctx->creds);
3275
3276         ret = timeout = inflight = 0;
3277         while (!kthread_should_park()) {
3278                 unsigned int to_submit;
3279
3280                 if (inflight) {
3281                         unsigned nr_events = 0;
3282
3283                         if (ctx->flags & IORING_SETUP_IOPOLL) {
3284                                 /*
3285                                  * inflight is the count of the maximum possible
3286                                  * entries we submitted, but it can be smaller
3287                                  * if we dropped some of them. If we don't have
3288                                  * poll entries available, then we know that we
3289                                  * have nothing left to poll for. Reset the
3290                                  * inflight count to zero in that case.
3291                                  */
3292                                 mutex_lock(&ctx->uring_lock);
3293                                 if (!list_empty(&ctx->poll_list))
3294                                         __io_iopoll_check(ctx, &nr_events, 0);
3295                                 else
3296                                         inflight = 0;
3297                                 mutex_unlock(&ctx->uring_lock);
3298                         } else {
3299                                 /*
3300                                  * Normal IO, just pretend everything completed.
3301                                  * We don't have to poll completions for that.
3302                                  */
3303                                 nr_events = inflight;
3304                         }
3305
3306                         inflight -= nr_events;
3307                         if (!inflight)
3308                                 timeout = jiffies + ctx->sq_thread_idle;
3309                 }
3310
3311                 to_submit = io_sqring_entries(ctx);
3312
3313                 /*
3314                  * If submit got -EBUSY, flag us as needing the application
3315                  * to enter the kernel to reap and flush events.
3316                  */
3317                 if (!to_submit || ret == -EBUSY) {
3318                         /*
3319                          * We're polling. If we're within the defined idle
3320                          * period, then let us spin without work before going
3321                          * to sleep. The exception is if we got EBUSY doing
3322                          * more IO, we should wait for the application to
3323                          * reap events and wake us up.
3324                          */
3325                         if (inflight ||
3326                             (!time_after(jiffies, timeout) && ret != -EBUSY)) {
3327                                 cond_resched();
3328                                 continue;
3329                         }
3330
3331                         /*
3332                          * Drop cur_mm before scheduling, we can't hold it for
3333                          * long periods (or over schedule()). Do this before
3334                          * adding ourselves to the waitqueue, as the unuse/drop
3335                          * may sleep.
3336                          */
3337                         if (cur_mm) {
3338                                 unuse_mm(cur_mm);
3339                                 mmput(cur_mm);
3340                                 cur_mm = NULL;
3341                         }
3342
3343                         prepare_to_wait(&ctx->sqo_wait, &wait,
3344                                                 TASK_INTERRUPTIBLE);
3345
3346                         /* Tell userspace we may need a wakeup call */
3347                         ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
3348                         /* make sure to read SQ tail after writing flags */
3349                         smp_mb();
3350
3351                         to_submit = io_sqring_entries(ctx);
3352                         if (!to_submit || ret == -EBUSY) {
3353                                 if (kthread_should_park()) {
3354                                         finish_wait(&ctx->sqo_wait, &wait);
3355                                         break;
3356                                 }
3357                                 if (signal_pending(current))
3358                                         flush_signals(current);
3359                                 schedule();
3360                                 finish_wait(&ctx->sqo_wait, &wait);
3361
3362                                 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3363                                 continue;
3364                         }
3365                         finish_wait(&ctx->sqo_wait, &wait);
3366
3367                         ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3368                 }
3369
3370                 to_submit = min(to_submit, ctx->sq_entries);
3371                 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
3372                 if (ret > 0)
3373                         inflight += ret;
3374         }
3375
3376         set_fs(old_fs);
3377         if (cur_mm) {
3378                 unuse_mm(cur_mm);
3379                 mmput(cur_mm);
3380         }
3381         revert_creds(old_cred);
3382
3383         kthread_parkme();
3384
3385         return 0;
3386 }
3387
3388 struct io_wait_queue {
3389         struct wait_queue_entry wq;
3390         struct io_ring_ctx *ctx;
3391         unsigned to_wait;
3392         unsigned nr_timeouts;
3393 };
3394
3395 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
3396 {
3397         struct io_ring_ctx *ctx = iowq->ctx;
3398
3399         /*
3400          * Wake up if we have enough events, or if a timeout occured since we
3401          * started waiting. For timeouts, we always want to return to userspace,
3402          * regardless of event count.
3403          */
3404         return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
3405                         atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
3406 }
3407
3408 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
3409                             int wake_flags, void *key)
3410 {
3411         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3412                                                         wq);
3413
3414         /* use noflush == true, as we can't safely rely on locking context */
3415         if (!io_should_wake(iowq, true))
3416                 return -1;
3417
3418         return autoremove_wake_function(curr, mode, wake_flags, key);
3419 }
3420
3421 /*
3422  * Wait until events become available, if we don't already have some. The
3423  * application must reap them itself, as they reside on the shared cq ring.
3424  */
3425 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3426                           const sigset_t __user *sig, size_t sigsz)
3427 {
3428         struct io_wait_queue iowq = {
3429                 .wq = {
3430                         .private        = current,
3431                         .func           = io_wake_function,
3432                         .entry          = LIST_HEAD_INIT(iowq.wq.entry),
3433                 },
3434                 .ctx            = ctx,
3435                 .to_wait        = min_events,
3436         };
3437         struct io_rings *rings = ctx->rings;
3438         int ret = 0;
3439
3440         if (io_cqring_events(ctx, false) >= min_events)
3441                 return 0;
3442
3443         if (sig) {
3444 #ifdef CONFIG_COMPAT
3445                 if (in_compat_syscall())
3446                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
3447                                                       sigsz);
3448                 else
3449 #endif
3450                         ret = set_user_sigmask(sig, sigsz);
3451
3452                 if (ret)
3453                         return ret;
3454         }
3455
3456         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
3457         trace_io_uring_cqring_wait(ctx, min_events);
3458         do {
3459                 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
3460                                                 TASK_INTERRUPTIBLE);
3461                 if (io_should_wake(&iowq, false))
3462                         break;
3463                 schedule();
3464                 if (signal_pending(current)) {
3465                         ret = -EINTR;
3466                         break;
3467                 }
3468         } while (1);
3469         finish_wait(&ctx->wait, &iowq.wq);
3470
3471         restore_saved_sigmask_unless(ret == -EINTR);
3472
3473         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
3474 }
3475
3476 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
3477 {
3478 #if defined(CONFIG_UNIX)
3479         if (ctx->ring_sock) {
3480                 struct sock *sock = ctx->ring_sock->sk;
3481                 struct sk_buff *skb;
3482
3483                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
3484                         kfree_skb(skb);
3485         }
3486 #else
3487         int i;
3488
3489         for (i = 0; i < ctx->nr_user_files; i++) {
3490                 struct file *file;
3491
3492                 file = io_file_from_index(ctx, i);
3493                 if (file)
3494                         fput(file);
3495         }
3496 #endif
3497 }
3498
3499 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
3500 {
3501         unsigned nr_tables, i;
3502
3503         if (!ctx->file_table)
3504                 return -ENXIO;
3505
3506         __io_sqe_files_unregister(ctx);
3507         nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
3508         for (i = 0; i < nr_tables; i++)
3509                 kfree(ctx->file_table[i].files);
3510         kfree(ctx->file_table);
3511         ctx->file_table = NULL;
3512         ctx->nr_user_files = 0;
3513         return 0;
3514 }
3515
3516 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
3517 {
3518         if (ctx->sqo_thread) {
3519                 wait_for_completion(&ctx->completions[1]);
3520                 /*
3521                  * The park is a bit of a work-around, without it we get
3522                  * warning spews on shutdown with SQPOLL set and affinity
3523                  * set to a single CPU.
3524                  */
3525                 kthread_park(ctx->sqo_thread);
3526                 kthread_stop(ctx->sqo_thread);
3527                 ctx->sqo_thread = NULL;
3528         }
3529 }
3530
3531 static void io_finish_async(struct io_ring_ctx *ctx)
3532 {
3533         io_sq_thread_stop(ctx);
3534
3535         if (ctx->io_wq) {
3536                 io_wq_destroy(ctx->io_wq);
3537                 ctx->io_wq = NULL;
3538         }
3539 }
3540
3541 #if defined(CONFIG_UNIX)
3542 static void io_destruct_skb(struct sk_buff *skb)
3543 {
3544         struct io_ring_ctx *ctx = skb->sk->sk_user_data;
3545
3546         if (ctx->io_wq)
3547                 io_wq_flush(ctx->io_wq);
3548
3549         unix_destruct_scm(skb);
3550 }
3551
3552 /*
3553  * Ensure the UNIX gc is aware of our file set, so we are certain that
3554  * the io_uring can be safely unregistered on process exit, even if we have
3555  * loops in the file referencing.
3556  */
3557 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
3558 {
3559         struct sock *sk = ctx->ring_sock->sk;
3560         struct scm_fp_list *fpl;
3561         struct sk_buff *skb;
3562         int i, nr_files;
3563
3564         if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
3565                 unsigned long inflight = ctx->user->unix_inflight + nr;
3566
3567                 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
3568                         return -EMFILE;
3569         }
3570
3571         fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
3572         if (!fpl)
3573                 return -ENOMEM;
3574
3575         skb = alloc_skb(0, GFP_KERNEL);
3576         if (!skb) {
3577                 kfree(fpl);
3578                 return -ENOMEM;
3579         }
3580
3581         skb->sk = sk;
3582
3583         nr_files = 0;
3584         fpl->user = get_uid(ctx->user);
3585         for (i = 0; i < nr; i++) {
3586                 struct file *file = io_file_from_index(ctx, i + offset);
3587
3588                 if (!file)
3589                         continue;
3590                 fpl->fp[nr_files] = get_file(file);
3591                 unix_inflight(fpl->user, fpl->fp[nr_files]);
3592                 nr_files++;
3593         }
3594
3595         if (nr_files) {
3596                 fpl->max = SCM_MAX_FD;
3597                 fpl->count = nr_files;
3598                 UNIXCB(skb).fp = fpl;
3599                 skb->destructor = io_destruct_skb;
3600                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
3601                 skb_queue_head(&sk->sk_receive_queue, skb);
3602
3603                 for (i = 0; i < nr_files; i++)
3604                         fput(fpl->fp[i]);
3605         } else {
3606                 kfree_skb(skb);
3607                 kfree(fpl);
3608         }
3609
3610         return 0;
3611 }
3612
3613 /*
3614  * If UNIX sockets are enabled, fd passing can cause a reference cycle which
3615  * causes regular reference counting to break down. We rely on the UNIX
3616  * garbage collection to take care of this problem for us.
3617  */
3618 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3619 {
3620         unsigned left, total;
3621         int ret = 0;
3622
3623         total = 0;
3624         left = ctx->nr_user_files;
3625         while (left) {
3626                 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
3627
3628                 ret = __io_sqe_files_scm(ctx, this_files, total);
3629                 if (ret)
3630                         break;
3631                 left -= this_files;
3632                 total += this_files;
3633         }
3634
3635         if (!ret)
3636                 return 0;
3637
3638         while (total < ctx->nr_user_files) {
3639                 struct file *file = io_file_from_index(ctx, total);
3640
3641                 if (file)
3642                         fput(file);
3643                 total++;
3644         }
3645
3646         return ret;
3647 }
3648 #else
3649 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3650 {
3651         return 0;
3652 }
3653 #endif
3654
3655 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
3656                                     unsigned nr_files)
3657 {
3658         int i;
3659
3660         for (i = 0; i < nr_tables; i++) {
3661                 struct fixed_file_table *table = &ctx->file_table[i];
3662                 unsigned this_files;
3663
3664                 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
3665                 table->files = kcalloc(this_files, sizeof(struct file *),
3666                                         GFP_KERNEL);
3667                 if (!table->files)
3668                         break;
3669                 nr_files -= this_files;
3670         }
3671
3672         if (i == nr_tables)
3673                 return 0;
3674
3675         for (i = 0; i < nr_tables; i++) {
3676                 struct fixed_file_table *table = &ctx->file_table[i];
3677                 kfree(table->files);
3678         }
3679         return 1;
3680 }
3681
3682 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3683                                  unsigned nr_args)
3684 {
3685         __s32 __user *fds = (__s32 __user *) arg;
3686         unsigned nr_tables;
3687         int fd, ret = 0;
3688         unsigned i;
3689
3690         if (ctx->file_table)
3691                 return -EBUSY;
3692         if (!nr_args)
3693                 return -EINVAL;
3694         if (nr_args > IORING_MAX_FIXED_FILES)
3695                 return -EMFILE;
3696
3697         nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
3698         ctx->file_table = kcalloc(nr_tables, sizeof(struct fixed_file_table),
3699                                         GFP_KERNEL);
3700         if (!ctx->file_table)
3701                 return -ENOMEM;
3702
3703         if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
3704                 kfree(ctx->file_table);
3705                 ctx->file_table = NULL;
3706                 return -ENOMEM;
3707         }
3708
3709         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
3710                 struct fixed_file_table *table;
3711                 unsigned index;
3712
3713                 ret = -EFAULT;
3714                 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3715                         break;
3716                 /* allow sparse sets */
3717                 if (fd == -1) {
3718                         ret = 0;
3719                         continue;
3720                 }
3721
3722                 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3723                 index = i & IORING_FILE_TABLE_MASK;
3724                 table->files[index] = fget(fd);
3725
3726                 ret = -EBADF;
3727                 if (!table->files[index])
3728                         break;
3729                 /*
3730                  * Don't allow io_uring instances to be registered. If UNIX
3731                  * isn't enabled, then this causes a reference cycle and this
3732                  * instance can never get freed. If UNIX is enabled we'll
3733                  * handle it just fine, but there's still no point in allowing
3734                  * a ring fd as it doesn't support regular read/write anyway.
3735                  */
3736                 if (table->files[index]->f_op == &io_uring_fops) {
3737                         fput(table->files[index]);
3738                         break;
3739                 }
3740                 ret = 0;
3741         }
3742
3743         if (ret) {
3744                 for (i = 0; i < ctx->nr_user_files; i++) {
3745                         struct file *file;
3746
3747                         file = io_file_from_index(ctx, i);
3748                         if (file)
3749                                 fput(file);
3750                 }
3751                 for (i = 0; i < nr_tables; i++)
3752                         kfree(ctx->file_table[i].files);
3753
3754                 kfree(ctx->file_table);
3755                 ctx->file_table = NULL;
3756                 ctx->nr_user_files = 0;
3757                 return ret;
3758         }
3759
3760         ret = io_sqe_files_scm(ctx);
3761         if (ret)
3762                 io_sqe_files_unregister(ctx);
3763
3764         return ret;
3765 }
3766
3767 static void io_sqe_file_unregister(struct io_ring_ctx *ctx, int index)
3768 {
3769 #if defined(CONFIG_UNIX)
3770         struct file *file = io_file_from_index(ctx, index);
3771         struct sock *sock = ctx->ring_sock->sk;
3772         struct sk_buff_head list, *head = &sock->sk_receive_queue;
3773         struct sk_buff *skb;
3774         int i;
3775
3776         __skb_queue_head_init(&list);
3777
3778         /*
3779          * Find the skb that holds this file in its SCM_RIGHTS. When found,
3780          * remove this entry and rearrange the file array.
3781          */
3782         skb = skb_dequeue(head);
3783         while (skb) {
3784                 struct scm_fp_list *fp;
3785
3786                 fp = UNIXCB(skb).fp;
3787                 for (i = 0; i < fp->count; i++) {
3788                         int left;
3789
3790                         if (fp->fp[i] != file)
3791                                 continue;
3792
3793                         unix_notinflight(fp->user, fp->fp[i]);
3794                         left = fp->count - 1 - i;
3795                         if (left) {
3796                                 memmove(&fp->fp[i], &fp->fp[i + 1],
3797                                                 left * sizeof(struct file *));
3798                         }
3799                         fp->count--;
3800                         if (!fp->count) {
3801                                 kfree_skb(skb);
3802                                 skb = NULL;
3803                         } else {
3804                                 __skb_queue_tail(&list, skb);
3805                         }
3806                         fput(file);
3807                         file = NULL;
3808                         break;
3809                 }
3810
3811                 if (!file)
3812                         break;
3813
3814                 __skb_queue_tail(&list, skb);
3815
3816                 skb = skb_dequeue(head);
3817         }
3818
3819         if (skb_peek(&list)) {
3820                 spin_lock_irq(&head->lock);
3821                 while ((skb = __skb_dequeue(&list)) != NULL)
3822                         __skb_queue_tail(head, skb);
3823                 spin_unlock_irq(&head->lock);
3824         }
3825 #else
3826         fput(io_file_from_index(ctx, index));
3827 #endif
3828 }
3829
3830 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
3831                                 int index)
3832 {
3833 #if defined(CONFIG_UNIX)
3834         struct sock *sock = ctx->ring_sock->sk;
3835         struct sk_buff_head *head = &sock->sk_receive_queue;
3836         struct sk_buff *skb;
3837
3838         /*
3839          * See if we can merge this file into an existing skb SCM_RIGHTS
3840          * file set. If there's no room, fall back to allocating a new skb
3841          * and filling it in.
3842          */
3843         spin_lock_irq(&head->lock);
3844         skb = skb_peek(head);
3845         if (skb) {
3846                 struct scm_fp_list *fpl = UNIXCB(skb).fp;
3847
3848                 if (fpl->count < SCM_MAX_FD) {
3849                         __skb_unlink(skb, head);
3850                         spin_unlock_irq(&head->lock);
3851                         fpl->fp[fpl->count] = get_file(file);
3852                         unix_inflight(fpl->user, fpl->fp[fpl->count]);
3853                         fpl->count++;
3854                         spin_lock_irq(&head->lock);
3855                         __skb_queue_head(head, skb);
3856                 } else {
3857                         skb = NULL;
3858                 }
3859         }
3860         spin_unlock_irq(&head->lock);
3861
3862         if (skb) {
3863                 fput(file);
3864                 return 0;
3865         }
3866
3867         return __io_sqe_files_scm(ctx, 1, index);
3868 #else
3869         return 0;
3870 #endif
3871 }
3872
3873 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
3874                                unsigned nr_args)
3875 {
3876         struct io_uring_files_update up;
3877         __s32 __user *fds;
3878         int fd, i, err;
3879         __u32 done;
3880
3881         if (!ctx->file_table)
3882                 return -ENXIO;
3883         if (!nr_args)
3884                 return -EINVAL;
3885         if (copy_from_user(&up, arg, sizeof(up)))
3886                 return -EFAULT;
3887         if (check_add_overflow(up.offset, nr_args, &done))
3888                 return -EOVERFLOW;
3889         if (done > ctx->nr_user_files)
3890                 return -EINVAL;
3891
3892         done = 0;
3893         fds = (__s32 __user *) up.fds;
3894         while (nr_args) {
3895                 struct fixed_file_table *table;
3896                 unsigned index;
3897
3898                 err = 0;
3899                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
3900                         err = -EFAULT;
3901                         break;
3902                 }
3903                 i = array_index_nospec(up.offset, ctx->nr_user_files);
3904                 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3905                 index = i & IORING_FILE_TABLE_MASK;
3906                 if (table->files[index]) {
3907                         io_sqe_file_unregister(ctx, i);
3908                         table->files[index] = NULL;
3909                 }
3910                 if (fd != -1) {
3911                         struct file *file;
3912
3913                         file = fget(fd);
3914                         if (!file) {
3915                                 err = -EBADF;
3916                                 break;
3917                         }
3918                         /*
3919                          * Don't allow io_uring instances to be registered. If
3920                          * UNIX isn't enabled, then this causes a reference
3921                          * cycle and this instance can never get freed. If UNIX
3922                          * is enabled we'll handle it just fine, but there's
3923                          * still no point in allowing a ring fd as it doesn't
3924                          * support regular read/write anyway.
3925                          */
3926                         if (file->f_op == &io_uring_fops) {
3927                                 fput(file);
3928                                 err = -EBADF;
3929                                 break;
3930                         }
3931                         table->files[index] = file;
3932                         err = io_sqe_file_register(ctx, file, i);
3933                         if (err)
3934                                 break;
3935                 }
3936                 nr_args--;
3937                 done++;
3938                 up.offset++;
3939         }
3940
3941         return done ? done : err;
3942 }
3943
3944 static void io_put_work(struct io_wq_work *work)
3945 {
3946         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3947
3948         io_put_req(req);
3949 }
3950
3951 static void io_get_work(struct io_wq_work *work)
3952 {
3953         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3954
3955         refcount_inc(&req->refs);
3956 }
3957
3958 static int io_sq_offload_start(struct io_ring_ctx *ctx,
3959                                struct io_uring_params *p)
3960 {
3961         struct io_wq_data data;
3962         unsigned concurrency;
3963         int ret;
3964
3965         init_waitqueue_head(&ctx->sqo_wait);
3966         mmgrab(current->mm);
3967         ctx->sqo_mm = current->mm;
3968
3969         if (ctx->flags & IORING_SETUP_SQPOLL) {
3970                 ret = -EPERM;
3971                 if (!capable(CAP_SYS_ADMIN))
3972                         goto err;
3973
3974                 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3975                 if (!ctx->sq_thread_idle)
3976                         ctx->sq_thread_idle = HZ;
3977
3978                 if (p->flags & IORING_SETUP_SQ_AFF) {
3979                         int cpu = p->sq_thread_cpu;
3980
3981                         ret = -EINVAL;
3982                         if (cpu >= nr_cpu_ids)
3983                                 goto err;
3984                         if (!cpu_online(cpu))
3985                                 goto err;
3986
3987                         ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3988                                                         ctx, cpu,
3989                                                         "io_uring-sq");
3990                 } else {
3991                         ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3992                                                         "io_uring-sq");
3993                 }
3994                 if (IS_ERR(ctx->sqo_thread)) {
3995                         ret = PTR_ERR(ctx->sqo_thread);
3996                         ctx->sqo_thread = NULL;
3997                         goto err;
3998                 }
3999                 wake_up_process(ctx->sqo_thread);
4000         } else if (p->flags & IORING_SETUP_SQ_AFF) {
4001                 /* Can't have SQ_AFF without SQPOLL */
4002                 ret = -EINVAL;
4003                 goto err;
4004         }
4005
4006         data.mm = ctx->sqo_mm;
4007         data.user = ctx->user;
4008         data.creds = ctx->creds;
4009         data.get_work = io_get_work;
4010         data.put_work = io_put_work;
4011
4012         /* Do QD, or 4 * CPUS, whatever is smallest */
4013         concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
4014         ctx->io_wq = io_wq_create(concurrency, &data);
4015         if (IS_ERR(ctx->io_wq)) {
4016                 ret = PTR_ERR(ctx->io_wq);
4017                 ctx->io_wq = NULL;
4018                 goto err;
4019         }
4020
4021         return 0;
4022 err:
4023         io_finish_async(ctx);
4024         mmdrop(ctx->sqo_mm);
4025         ctx->sqo_mm = NULL;
4026         return ret;
4027 }
4028
4029 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
4030 {
4031         atomic_long_sub(nr_pages, &user->locked_vm);
4032 }
4033
4034 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
4035 {
4036         unsigned long page_limit, cur_pages, new_pages;
4037
4038         /* Don't allow more pages than we can safely lock */
4039         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
4040
4041         do {
4042                 cur_pages = atomic_long_read(&user->locked_vm);
4043                 new_pages = cur_pages + nr_pages;
4044                 if (new_pages > page_limit)
4045                         return -ENOMEM;
4046         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
4047                                         new_pages) != cur_pages);
4048
4049         return 0;
4050 }
4051
4052 static void io_mem_free(void *ptr)
4053 {
4054         struct page *page;
4055
4056         if (!ptr)
4057                 return;
4058
4059         page = virt_to_head_page(ptr);
4060         if (put_page_testzero(page))
4061                 free_compound_page(page);
4062 }
4063
4064 static void *io_mem_alloc(size_t size)
4065 {
4066         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
4067                                 __GFP_NORETRY;
4068
4069         return (void *) __get_free_pages(gfp_flags, get_order(size));
4070 }
4071
4072 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
4073                                 size_t *sq_offset)
4074 {
4075         struct io_rings *rings;
4076         size_t off, sq_array_size;
4077
4078         off = struct_size(rings, cqes, cq_entries);
4079         if (off == SIZE_MAX)
4080                 return SIZE_MAX;
4081
4082 #ifdef CONFIG_SMP
4083         off = ALIGN(off, SMP_CACHE_BYTES);
4084         if (off == 0)
4085                 return SIZE_MAX;
4086 #endif
4087
4088         sq_array_size = array_size(sizeof(u32), sq_entries);
4089         if (sq_array_size == SIZE_MAX)
4090                 return SIZE_MAX;
4091
4092         if (check_add_overflow(off, sq_array_size, &off))
4093                 return SIZE_MAX;
4094
4095         if (sq_offset)
4096                 *sq_offset = off;
4097
4098         return off;
4099 }
4100
4101 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
4102 {
4103         size_t pages;
4104
4105         pages = (size_t)1 << get_order(
4106                 rings_size(sq_entries, cq_entries, NULL));
4107         pages += (size_t)1 << get_order(
4108                 array_size(sizeof(struct io_uring_sqe), sq_entries));
4109
4110         return pages;
4111 }
4112
4113 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
4114 {
4115         int i, j;
4116
4117         if (!ctx->user_bufs)
4118                 return -ENXIO;
4119
4120         for (i = 0; i < ctx->nr_user_bufs; i++) {
4121                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4122
4123                 for (j = 0; j < imu->nr_bvecs; j++)
4124                         put_user_page(imu->bvec[j].bv_page);
4125
4126                 if (ctx->account_mem)
4127                         io_unaccount_mem(ctx->user, imu->nr_bvecs);
4128                 kvfree(imu->bvec);
4129                 imu->nr_bvecs = 0;
4130         }
4131
4132         kfree(ctx->user_bufs);
4133         ctx->user_bufs = NULL;
4134         ctx->nr_user_bufs = 0;
4135         return 0;
4136 }
4137
4138 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
4139                        void __user *arg, unsigned index)
4140 {
4141         struct iovec __user *src;
4142
4143 #ifdef CONFIG_COMPAT
4144         if (ctx->compat) {
4145                 struct compat_iovec __user *ciovs;
4146                 struct compat_iovec ciov;
4147
4148                 ciovs = (struct compat_iovec __user *) arg;
4149                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
4150                         return -EFAULT;
4151
4152                 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
4153                 dst->iov_len = ciov.iov_len;
4154                 return 0;
4155         }
4156 #endif
4157         src = (struct iovec __user *) arg;
4158         if (copy_from_user(dst, &src[index], sizeof(*dst)))
4159                 return -EFAULT;
4160         return 0;
4161 }
4162
4163 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
4164                                   unsigned nr_args)
4165 {
4166         struct vm_area_struct **vmas = NULL;
4167         struct page **pages = NULL;
4168         int i, j, got_pages = 0;
4169         int ret = -EINVAL;
4170
4171         if (ctx->user_bufs)
4172                 return -EBUSY;
4173         if (!nr_args || nr_args > UIO_MAXIOV)
4174                 return -EINVAL;
4175
4176         ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
4177                                         GFP_KERNEL);
4178         if (!ctx->user_bufs)
4179                 return -ENOMEM;
4180
4181         for (i = 0; i < nr_args; i++) {
4182                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4183                 unsigned long off, start, end, ubuf;
4184                 int pret, nr_pages;
4185                 struct iovec iov;
4186                 size_t size;
4187
4188                 ret = io_copy_iov(ctx, &iov, arg, i);
4189                 if (ret)
4190                         goto err;
4191
4192                 /*
4193                  * Don't impose further limits on the size and buffer
4194                  * constraints here, we'll -EINVAL later when IO is
4195                  * submitted if they are wrong.
4196                  */
4197                 ret = -EFAULT;
4198                 if (!iov.iov_base || !iov.iov_len)
4199                         goto err;
4200
4201                 /* arbitrary limit, but we need something */
4202                 if (iov.iov_len > SZ_1G)
4203                         goto err;
4204
4205                 ubuf = (unsigned long) iov.iov_base;
4206                 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
4207                 start = ubuf >> PAGE_SHIFT;
4208                 nr_pages = end - start;
4209
4210                 if (ctx->account_mem) {
4211                         ret = io_account_mem(ctx->user, nr_pages);
4212                         if (ret)
4213                                 goto err;
4214                 }
4215
4216                 ret = 0;
4217                 if (!pages || nr_pages > got_pages) {
4218                         kfree(vmas);
4219                         kfree(pages);
4220                         pages = kvmalloc_array(nr_pages, sizeof(struct page *),
4221                                                 GFP_KERNEL);
4222                         vmas = kvmalloc_array(nr_pages,
4223                                         sizeof(struct vm_area_struct *),
4224                                         GFP_KERNEL);
4225                         if (!pages || !vmas) {
4226                                 ret = -ENOMEM;
4227                                 if (ctx->account_mem)
4228                                         io_unaccount_mem(ctx->user, nr_pages);
4229                                 goto err;
4230                         }
4231                         got_pages = nr_pages;
4232                 }
4233
4234                 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
4235                                                 GFP_KERNEL);
4236                 ret = -ENOMEM;
4237                 if (!imu->bvec) {
4238                         if (ctx->account_mem)
4239                                 io_unaccount_mem(ctx->user, nr_pages);
4240                         goto err;
4241                 }
4242
4243                 ret = 0;
4244                 down_read(&current->mm->mmap_sem);
4245                 pret = get_user_pages(ubuf, nr_pages,
4246                                       FOLL_WRITE | FOLL_LONGTERM,
4247                                       pages, vmas);
4248                 if (pret == nr_pages) {
4249                         /* don't support file backed memory */
4250                         for (j = 0; j < nr_pages; j++) {
4251                                 struct vm_area_struct *vma = vmas[j];
4252
4253                                 if (vma->vm_file &&
4254                                     !is_file_hugepages(vma->vm_file)) {
4255                                         ret = -EOPNOTSUPP;
4256                                         break;
4257                                 }
4258                         }
4259                 } else {
4260                         ret = pret < 0 ? pret : -EFAULT;
4261                 }
4262                 up_read(&current->mm->mmap_sem);
4263                 if (ret) {
4264                         /*
4265                          * if we did partial map, or found file backed vmas,
4266                          * release any pages we did get
4267                          */
4268                         if (pret > 0)
4269                                 put_user_pages(pages, pret);
4270                         if (ctx->account_mem)
4271                                 io_unaccount_mem(ctx->user, nr_pages);
4272                         kvfree(imu->bvec);
4273                         goto err;
4274                 }
4275
4276                 off = ubuf & ~PAGE_MASK;
4277                 size = iov.iov_len;
4278                 for (j = 0; j < nr_pages; j++) {
4279                         size_t vec_len;
4280
4281                         vec_len = min_t(size_t, size, PAGE_SIZE - off);
4282                         imu->bvec[j].bv_page = pages[j];
4283                         imu->bvec[j].bv_len = vec_len;
4284                         imu->bvec[j].bv_offset = off;
4285                         off = 0;
4286                         size -= vec_len;
4287                 }
4288                 /* store original address for later verification */
4289                 imu->ubuf = ubuf;
4290                 imu->len = iov.iov_len;
4291                 imu->nr_bvecs = nr_pages;
4292
4293                 ctx->nr_user_bufs++;
4294         }
4295         kvfree(pages);
4296         kvfree(vmas);
4297         return 0;
4298 err:
4299         kvfree(pages);
4300         kvfree(vmas);
4301         io_sqe_buffer_unregister(ctx);
4302         return ret;
4303 }
4304
4305 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
4306 {
4307         __s32 __user *fds = arg;
4308         int fd;
4309
4310         if (ctx->cq_ev_fd)
4311                 return -EBUSY;
4312
4313         if (copy_from_user(&fd, fds, sizeof(*fds)))
4314                 return -EFAULT;
4315
4316         ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
4317         if (IS_ERR(ctx->cq_ev_fd)) {
4318                 int ret = PTR_ERR(ctx->cq_ev_fd);
4319                 ctx->cq_ev_fd = NULL;
4320                 return ret;
4321         }
4322
4323         return 0;
4324 }
4325
4326 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
4327 {
4328         if (ctx->cq_ev_fd) {
4329                 eventfd_ctx_put(ctx->cq_ev_fd);
4330                 ctx->cq_ev_fd = NULL;
4331                 return 0;
4332         }
4333
4334         return -ENXIO;
4335 }
4336
4337 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
4338 {
4339         io_finish_async(ctx);
4340         if (ctx->sqo_mm)
4341                 mmdrop(ctx->sqo_mm);
4342
4343         io_iopoll_reap_events(ctx);
4344         io_sqe_buffer_unregister(ctx);
4345         io_sqe_files_unregister(ctx);
4346         io_eventfd_unregister(ctx);
4347
4348 #if defined(CONFIG_UNIX)
4349         if (ctx->ring_sock) {
4350                 ctx->ring_sock->file = NULL; /* so that iput() is called */
4351                 sock_release(ctx->ring_sock);
4352         }
4353 #endif
4354
4355         io_mem_free(ctx->rings);
4356         io_mem_free(ctx->sq_sqes);
4357
4358         percpu_ref_exit(&ctx->refs);
4359         if (ctx->account_mem)
4360                 io_unaccount_mem(ctx->user,
4361                                 ring_pages(ctx->sq_entries, ctx->cq_entries));
4362         free_uid(ctx->user);
4363         put_cred(ctx->creds);
4364         kfree(ctx->completions);
4365         kmem_cache_free(req_cachep, ctx->fallback_req);
4366         kfree(ctx);
4367 }
4368
4369 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
4370 {
4371         struct io_ring_ctx *ctx = file->private_data;
4372         __poll_t mask = 0;
4373
4374         poll_wait(file, &ctx->cq_wait, wait);
4375         /*
4376          * synchronizes with barrier from wq_has_sleeper call in
4377          * io_commit_cqring
4378          */
4379         smp_rmb();
4380         if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
4381             ctx->rings->sq_ring_entries)
4382                 mask |= EPOLLOUT | EPOLLWRNORM;
4383         if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
4384                 mask |= EPOLLIN | EPOLLRDNORM;
4385
4386         return mask;
4387 }
4388
4389 static int io_uring_fasync(int fd, struct file *file, int on)
4390 {
4391         struct io_ring_ctx *ctx = file->private_data;
4392
4393         return fasync_helper(fd, file, on, &ctx->cq_fasync);
4394 }
4395
4396 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
4397 {
4398         mutex_lock(&ctx->uring_lock);
4399         percpu_ref_kill(&ctx->refs);
4400         mutex_unlock(&ctx->uring_lock);
4401
4402         io_kill_timeouts(ctx);
4403         io_poll_remove_all(ctx);
4404
4405         if (ctx->io_wq)
4406                 io_wq_cancel_all(ctx->io_wq);
4407
4408         io_iopoll_reap_events(ctx);
4409         /* if we failed setting up the ctx, we might not have any rings */
4410         if (ctx->rings)
4411                 io_cqring_overflow_flush(ctx, true);
4412         wait_for_completion(&ctx->completions[0]);
4413         io_ring_ctx_free(ctx);
4414 }
4415
4416 static int io_uring_release(struct inode *inode, struct file *file)
4417 {
4418         struct io_ring_ctx *ctx = file->private_data;
4419
4420         file->private_data = NULL;
4421         io_ring_ctx_wait_and_kill(ctx);
4422         return 0;
4423 }
4424
4425 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
4426                                   struct files_struct *files)
4427 {
4428         struct io_kiocb *req;
4429         DEFINE_WAIT(wait);
4430
4431         while (!list_empty_careful(&ctx->inflight_list)) {
4432                 struct io_kiocb *cancel_req = NULL;
4433
4434                 spin_lock_irq(&ctx->inflight_lock);
4435                 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
4436                         if (req->work.files != files)
4437                                 continue;
4438                         /* req is being completed, ignore */
4439                         if (!refcount_inc_not_zero(&req->refs))
4440                                 continue;
4441                         cancel_req = req;
4442                         break;
4443                 }
4444                 if (cancel_req)
4445                         prepare_to_wait(&ctx->inflight_wait, &wait,
4446                                                 TASK_UNINTERRUPTIBLE);
4447                 spin_unlock_irq(&ctx->inflight_lock);
4448
4449                 /* We need to keep going until we don't find a matching req */
4450                 if (!cancel_req)
4451                         break;
4452
4453                 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
4454                 io_put_req(cancel_req);
4455                 schedule();
4456         }
4457         finish_wait(&ctx->inflight_wait, &wait);
4458 }
4459
4460 static int io_uring_flush(struct file *file, void *data)
4461 {
4462         struct io_ring_ctx *ctx = file->private_data;
4463
4464         io_uring_cancel_files(ctx, data);
4465         if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
4466                 io_cqring_overflow_flush(ctx, true);
4467                 io_wq_cancel_all(ctx->io_wq);
4468         }
4469         return 0;
4470 }
4471
4472 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
4473 {
4474         loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
4475         unsigned long sz = vma->vm_end - vma->vm_start;
4476         struct io_ring_ctx *ctx = file->private_data;
4477         unsigned long pfn;
4478         struct page *page;
4479         void *ptr;
4480
4481         switch (offset) {
4482         case IORING_OFF_SQ_RING:
4483         case IORING_OFF_CQ_RING:
4484                 ptr = ctx->rings;
4485                 break;
4486         case IORING_OFF_SQES:
4487                 ptr = ctx->sq_sqes;
4488                 break;
4489         default:
4490                 return -EINVAL;
4491         }
4492
4493         page = virt_to_head_page(ptr);
4494         if (sz > page_size(page))
4495                 return -EINVAL;
4496
4497         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
4498         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
4499 }
4500
4501 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
4502                 u32, min_complete, u32, flags, const sigset_t __user *, sig,
4503                 size_t, sigsz)
4504 {
4505         struct io_ring_ctx *ctx;
4506         long ret = -EBADF;
4507         int submitted = 0;
4508         struct fd f;
4509
4510         if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
4511                 return -EINVAL;
4512
4513         f = fdget(fd);
4514         if (!f.file)
4515                 return -EBADF;
4516
4517         ret = -EOPNOTSUPP;
4518         if (f.file->f_op != &io_uring_fops)
4519                 goto out_fput;
4520
4521         ret = -ENXIO;
4522         ctx = f.file->private_data;
4523         if (!percpu_ref_tryget(&ctx->refs))
4524                 goto out_fput;
4525
4526         /*
4527          * For SQ polling, the thread will do all submissions and completions.
4528          * Just return the requested submit count, and wake the thread if
4529          * we were asked to.
4530          */
4531         ret = 0;
4532         if (ctx->flags & IORING_SETUP_SQPOLL) {
4533                 if (!list_empty_careful(&ctx->cq_overflow_list))
4534                         io_cqring_overflow_flush(ctx, false);
4535                 if (flags & IORING_ENTER_SQ_WAKEUP)
4536                         wake_up(&ctx->sqo_wait);
4537                 submitted = to_submit;
4538         } else if (to_submit) {
4539                 struct mm_struct *cur_mm;
4540
4541                 to_submit = min(to_submit, ctx->sq_entries);
4542                 mutex_lock(&ctx->uring_lock);
4543                 /* already have mm, so io_submit_sqes() won't try to grab it */
4544                 cur_mm = ctx->sqo_mm;
4545                 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
4546                                            &cur_mm, false);
4547                 mutex_unlock(&ctx->uring_lock);
4548         }
4549         if (flags & IORING_ENTER_GETEVENTS) {
4550                 unsigned nr_events = 0;
4551
4552                 min_complete = min(min_complete, ctx->cq_entries);
4553
4554                 if (ctx->flags & IORING_SETUP_IOPOLL) {
4555                         ret = io_iopoll_check(ctx, &nr_events, min_complete);
4556                 } else {
4557                         ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
4558                 }
4559         }
4560
4561         percpu_ref_put(&ctx->refs);
4562 out_fput:
4563         fdput(f);
4564         return submitted ? submitted : ret;
4565 }
4566
4567 static const struct file_operations io_uring_fops = {
4568         .release        = io_uring_release,
4569         .flush          = io_uring_flush,
4570         .mmap           = io_uring_mmap,
4571         .poll           = io_uring_poll,
4572         .fasync         = io_uring_fasync,
4573 };
4574
4575 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
4576                                   struct io_uring_params *p)
4577 {
4578         struct io_rings *rings;
4579         size_t size, sq_array_offset;
4580
4581         size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
4582         if (size == SIZE_MAX)
4583                 return -EOVERFLOW;
4584
4585         rings = io_mem_alloc(size);
4586         if (!rings)
4587                 return -ENOMEM;
4588
4589         ctx->rings = rings;
4590         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
4591         rings->sq_ring_mask = p->sq_entries - 1;
4592         rings->cq_ring_mask = p->cq_entries - 1;
4593         rings->sq_ring_entries = p->sq_entries;
4594         rings->cq_ring_entries = p->cq_entries;
4595         ctx->sq_mask = rings->sq_ring_mask;
4596         ctx->cq_mask = rings->cq_ring_mask;
4597         ctx->sq_entries = rings->sq_ring_entries;
4598         ctx->cq_entries = rings->cq_ring_entries;
4599
4600         size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
4601         if (size == SIZE_MAX) {
4602                 io_mem_free(ctx->rings);
4603                 ctx->rings = NULL;
4604                 return -EOVERFLOW;
4605         }
4606
4607         ctx->sq_sqes = io_mem_alloc(size);
4608         if (!ctx->sq_sqes) {
4609                 io_mem_free(ctx->rings);
4610                 ctx->rings = NULL;
4611                 return -ENOMEM;
4612         }
4613
4614         return 0;
4615 }
4616
4617 /*
4618  * Allocate an anonymous fd, this is what constitutes the application
4619  * visible backing of an io_uring instance. The application mmaps this
4620  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
4621  * we have to tie this fd to a socket for file garbage collection purposes.
4622  */
4623 static int io_uring_get_fd(struct io_ring_ctx *ctx)
4624 {
4625         struct file *file;
4626         int ret;
4627
4628 #if defined(CONFIG_UNIX)
4629         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
4630                                 &ctx->ring_sock);
4631         if (ret)
4632                 return ret;
4633 #endif
4634
4635         ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
4636         if (ret < 0)
4637                 goto err;
4638
4639         file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
4640                                         O_RDWR | O_CLOEXEC);
4641         if (IS_ERR(file)) {
4642                 put_unused_fd(ret);
4643                 ret = PTR_ERR(file);
4644                 goto err;
4645         }
4646
4647 #if defined(CONFIG_UNIX)
4648         ctx->ring_sock->file = file;
4649         ctx->ring_sock->sk->sk_user_data = ctx;
4650 #endif
4651         fd_install(ret, file);
4652         return ret;
4653 err:
4654 #if defined(CONFIG_UNIX)
4655         sock_release(ctx->ring_sock);
4656         ctx->ring_sock = NULL;
4657 #endif
4658         return ret;
4659 }
4660
4661 static int io_uring_create(unsigned entries, struct io_uring_params *p)
4662 {
4663         struct user_struct *user = NULL;
4664         struct io_ring_ctx *ctx;
4665         bool account_mem;
4666         int ret;
4667
4668         if (!entries || entries > IORING_MAX_ENTRIES)
4669                 return -EINVAL;
4670
4671         /*
4672          * Use twice as many entries for the CQ ring. It's possible for the
4673          * application to drive a higher depth than the size of the SQ ring,
4674          * since the sqes are only used at submission time. This allows for
4675          * some flexibility in overcommitting a bit. If the application has
4676          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
4677          * of CQ ring entries manually.
4678          */
4679         p->sq_entries = roundup_pow_of_two(entries);
4680         if (p->flags & IORING_SETUP_CQSIZE) {
4681                 /*
4682                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
4683                  * to a power-of-two, if it isn't already. We do NOT impose
4684                  * any cq vs sq ring sizing.
4685                  */
4686                 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
4687                         return -EINVAL;
4688                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
4689         } else {
4690                 p->cq_entries = 2 * p->sq_entries;
4691         }
4692
4693         user = get_uid(current_user());
4694         account_mem = !capable(CAP_IPC_LOCK);
4695
4696         if (account_mem) {
4697                 ret = io_account_mem(user,
4698                                 ring_pages(p->sq_entries, p->cq_entries));
4699                 if (ret) {
4700                         free_uid(user);
4701                         return ret;
4702                 }
4703         }
4704
4705         ctx = io_ring_ctx_alloc(p);
4706         if (!ctx) {
4707                 if (account_mem)
4708                         io_unaccount_mem(user, ring_pages(p->sq_entries,
4709                                                                 p->cq_entries));
4710                 free_uid(user);
4711                 return -ENOMEM;
4712         }
4713         ctx->compat = in_compat_syscall();
4714         ctx->account_mem = account_mem;
4715         ctx->user = user;
4716         ctx->creds = prepare_creds();
4717
4718         ret = io_allocate_scq_urings(ctx, p);
4719         if (ret)
4720                 goto err;
4721
4722         ret = io_sq_offload_start(ctx, p);
4723         if (ret)
4724                 goto err;
4725
4726         memset(&p->sq_off, 0, sizeof(p->sq_off));
4727         p->sq_off.head = offsetof(struct io_rings, sq.head);
4728         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
4729         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
4730         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
4731         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
4732         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
4733         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
4734
4735         memset(&p->cq_off, 0, sizeof(p->cq_off));
4736         p->cq_off.head = offsetof(struct io_rings, cq.head);
4737         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
4738         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
4739         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
4740         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
4741         p->cq_off.cqes = offsetof(struct io_rings, cqes);
4742
4743         /*
4744          * Install ring fd as the very last thing, so we don't risk someone
4745          * having closed it before we finish setup
4746          */
4747         ret = io_uring_get_fd(ctx);
4748         if (ret < 0)
4749                 goto err;
4750
4751         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP;
4752         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
4753         return ret;
4754 err:
4755         io_ring_ctx_wait_and_kill(ctx);
4756         return ret;
4757 }
4758
4759 /*
4760  * Sets up an aio uring context, and returns the fd. Applications asks for a
4761  * ring size, we return the actual sq/cq ring sizes (among other things) in the
4762  * params structure passed in.
4763  */
4764 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4765 {
4766         struct io_uring_params p;
4767         long ret;
4768         int i;
4769
4770         if (copy_from_user(&p, params, sizeof(p)))
4771                 return -EFAULT;
4772         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4773                 if (p.resv[i])
4774                         return -EINVAL;
4775         }
4776
4777         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
4778                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
4779                 return -EINVAL;
4780
4781         ret = io_uring_create(entries, &p);
4782         if (ret < 0)
4783                 return ret;
4784
4785         if (copy_to_user(params, &p, sizeof(p)))
4786                 return -EFAULT;
4787
4788         return ret;
4789 }
4790
4791 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4792                 struct io_uring_params __user *, params)
4793 {
4794         return io_uring_setup(entries, params);
4795 }
4796
4797 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4798                                void __user *arg, unsigned nr_args)
4799         __releases(ctx->uring_lock)
4800         __acquires(ctx->uring_lock)
4801 {
4802         int ret;
4803
4804         /*
4805          * We're inside the ring mutex, if the ref is already dying, then
4806          * someone else killed the ctx or is already going through
4807          * io_uring_register().
4808          */
4809         if (percpu_ref_is_dying(&ctx->refs))
4810                 return -ENXIO;
4811
4812         percpu_ref_kill(&ctx->refs);
4813
4814         /*
4815          * Drop uring mutex before waiting for references to exit. If another
4816          * thread is currently inside io_uring_enter() it might need to grab
4817          * the uring_lock to make progress. If we hold it here across the drain
4818          * wait, then we can deadlock. It's safe to drop the mutex here, since
4819          * no new references will come in after we've killed the percpu ref.
4820          */
4821         mutex_unlock(&ctx->uring_lock);
4822         wait_for_completion(&ctx->completions[0]);
4823         mutex_lock(&ctx->uring_lock);
4824
4825         switch (opcode) {
4826         case IORING_REGISTER_BUFFERS:
4827                 ret = io_sqe_buffer_register(ctx, arg, nr_args);
4828                 break;
4829         case IORING_UNREGISTER_BUFFERS:
4830                 ret = -EINVAL;
4831                 if (arg || nr_args)
4832                         break;
4833                 ret = io_sqe_buffer_unregister(ctx);
4834                 break;
4835         case IORING_REGISTER_FILES:
4836                 ret = io_sqe_files_register(ctx, arg, nr_args);
4837                 break;
4838         case IORING_UNREGISTER_FILES:
4839                 ret = -EINVAL;
4840                 if (arg || nr_args)
4841                         break;
4842                 ret = io_sqe_files_unregister(ctx);
4843                 break;
4844         case IORING_REGISTER_FILES_UPDATE:
4845                 ret = io_sqe_files_update(ctx, arg, nr_args);
4846                 break;
4847         case IORING_REGISTER_EVENTFD:
4848                 ret = -EINVAL;
4849                 if (nr_args != 1)
4850                         break;
4851                 ret = io_eventfd_register(ctx, arg);
4852                 break;
4853         case IORING_UNREGISTER_EVENTFD:
4854                 ret = -EINVAL;
4855                 if (arg || nr_args)
4856                         break;
4857                 ret = io_eventfd_unregister(ctx);
4858                 break;
4859         default:
4860                 ret = -EINVAL;
4861                 break;
4862         }
4863
4864         /* bring the ctx back to life */
4865         reinit_completion(&ctx->completions[0]);
4866         percpu_ref_reinit(&ctx->refs);
4867         return ret;
4868 }
4869
4870 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4871                 void __user *, arg, unsigned int, nr_args)
4872 {
4873         struct io_ring_ctx *ctx;
4874         long ret = -EBADF;
4875         struct fd f;
4876
4877         f = fdget(fd);
4878         if (!f.file)
4879                 return -EBADF;
4880
4881         ret = -EOPNOTSUPP;
4882         if (f.file->f_op != &io_uring_fops)
4883                 goto out_fput;
4884
4885         ctx = f.file->private_data;
4886
4887         mutex_lock(&ctx->uring_lock);
4888         ret = __io_uring_register(ctx, opcode, arg, nr_args);
4889         mutex_unlock(&ctx->uring_lock);
4890         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
4891                                                         ctx->cq_ev_fd != NULL, ret);
4892 out_fput:
4893         fdput(f);
4894         return ret;
4895 }
4896
4897 static int __init io_uring_init(void)
4898 {
4899         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
4900         return 0;
4901 };
4902 __initcall(io_uring_init);