OSDN Git Service

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