GNU Linux-libre 4.9.337-gnu1
[releases.git] / virt / kvm / kvm_main.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  */
18
19 #include <kvm/iodev.h>
20
21 #include <linux/kvm_host.h>
22 #include <linux/kvm.h>
23 #include <linux/module.h>
24 #include <linux/errno.h>
25 #include <linux/percpu.h>
26 #include <linux/mm.h>
27 #include <linux/miscdevice.h>
28 #include <linux/vmalloc.h>
29 #include <linux/reboot.h>
30 #include <linux/debugfs.h>
31 #include <linux/highmem.h>
32 #include <linux/file.h>
33 #include <linux/syscore_ops.h>
34 #include <linux/cpu.h>
35 #include <linux/sched.h>
36 #include <linux/cpumask.h>
37 #include <linux/smp.h>
38 #include <linux/anon_inodes.h>
39 #include <linux/profile.h>
40 #include <linux/kvm_para.h>
41 #include <linux/pagemap.h>
42 #include <linux/mman.h>
43 #include <linux/swap.h>
44 #include <linux/bitops.h>
45 #include <linux/spinlock.h>
46 #include <linux/compat.h>
47 #include <linux/srcu.h>
48 #include <linux/hugetlb.h>
49 #include <linux/slab.h>
50 #include <linux/sort.h>
51 #include <linux/bsearch.h>
52 #include <linux/kthread.h>
53
54 #include <asm/processor.h>
55 #include <asm/io.h>
56 #include <asm/ioctl.h>
57 #include <asm/uaccess.h>
58 #include <asm/pgtable.h>
59
60 #include "coalesced_mmio.h"
61 #include "async_pf.h"
62 #include "vfio.h"
63
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/kvm.h>
66
67 /* Worst case buffer size needed for holding an integer. */
68 #define ITOA_MAX_LEN 12
69
70 MODULE_AUTHOR("Qumranet");
71 MODULE_LICENSE("GPL");
72
73 /* Architectures should define their poll value according to the halt latency */
74 static unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
75 module_param(halt_poll_ns, uint, S_IRUGO | S_IWUSR);
76
77 /* Default doubles per-vcpu halt_poll_ns. */
78 static unsigned int halt_poll_ns_grow = 2;
79 module_param(halt_poll_ns_grow, uint, S_IRUGO | S_IWUSR);
80
81 /* Default resets per-vcpu halt_poll_ns . */
82 static unsigned int halt_poll_ns_shrink;
83 module_param(halt_poll_ns_shrink, uint, S_IRUGO | S_IWUSR);
84
85 /*
86  * Ordering of locks:
87  *
88  *      kvm->lock --> kvm->slots_lock --> kvm->irq_lock
89  */
90
91 DEFINE_MUTEX(kvm_lock);
92 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
93 LIST_HEAD(vm_list);
94
95 static cpumask_var_t cpus_hardware_enabled;
96 static int kvm_usage_count;
97 static atomic_t hardware_enable_failed;
98
99 struct kmem_cache *kvm_vcpu_cache;
100 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
101
102 static __read_mostly struct preempt_ops kvm_preempt_ops;
103
104 struct dentry *kvm_debugfs_dir;
105 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
106
107 static int kvm_debugfs_num_entries;
108 static const struct file_operations *stat_fops_per_vm[];
109
110 static struct file_operations kvm_chardev_ops;
111
112 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
113                            unsigned long arg);
114 #ifdef CONFIG_KVM_COMPAT
115 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
116                                   unsigned long arg);
117 #endif
118 static int hardware_enable_all(void);
119 static void hardware_disable_all(void);
120
121 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
122
123 static void kvm_release_pfn_dirty(kvm_pfn_t pfn);
124 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
125
126 __visible bool kvm_rebooting;
127 EXPORT_SYMBOL_GPL(kvm_rebooting);
128
129 static bool largepages_enabled = true;
130
131 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
132                 unsigned long start, unsigned long end)
133 {
134 }
135
136 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
137 {
138         /*
139          * The metadata used by is_zone_device_page() to determine whether or
140          * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
141          * the device has been pinned, e.g. by get_user_pages().  WARN if the
142          * page_count() is zero to help detect bad usage of this helper.
143          */
144         if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
145                 return false;
146
147         return is_zone_device_page(pfn_to_page(pfn));
148 }
149
150 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
151 {
152         /*
153          * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
154          * perspective they are "normal" pages, albeit with slightly different
155          * usage rules.
156          */
157         if (pfn_valid(pfn))
158                 return PageReserved(pfn_to_page(pfn)) &&
159                        !is_zero_pfn(pfn) &&
160                        !kvm_is_zone_device_pfn(pfn);
161
162         return true;
163 }
164
165 /*
166  * Switches to specified vcpu, until a matching vcpu_put()
167  */
168 int vcpu_load(struct kvm_vcpu *vcpu)
169 {
170         int cpu;
171
172         if (mutex_lock_killable(&vcpu->mutex))
173                 return -EINTR;
174         cpu = get_cpu();
175         preempt_notifier_register(&vcpu->preempt_notifier);
176         kvm_arch_vcpu_load(vcpu, cpu);
177         put_cpu();
178         return 0;
179 }
180 EXPORT_SYMBOL_GPL(vcpu_load);
181
182 void vcpu_put(struct kvm_vcpu *vcpu)
183 {
184         preempt_disable();
185         kvm_arch_vcpu_put(vcpu);
186         preempt_notifier_unregister(&vcpu->preempt_notifier);
187         preempt_enable();
188         mutex_unlock(&vcpu->mutex);
189 }
190 EXPORT_SYMBOL_GPL(vcpu_put);
191
192 static void ack_flush(void *_completed)
193 {
194 }
195
196 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
197 {
198         int i, cpu, me;
199         cpumask_var_t cpus;
200         bool called = true;
201         struct kvm_vcpu *vcpu;
202
203         zalloc_cpumask_var(&cpus, GFP_ATOMIC);
204
205         me = get_cpu();
206         kvm_for_each_vcpu(i, vcpu, kvm) {
207                 kvm_make_request(req, vcpu);
208                 cpu = vcpu->cpu;
209
210                 /* Set ->requests bit before we read ->mode. */
211                 smp_mb__after_atomic();
212
213                 if (cpus != NULL && cpu != -1 && cpu != me &&
214                       kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
215                         cpumask_set_cpu(cpu, cpus);
216         }
217         if (unlikely(cpus == NULL))
218                 smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
219         else if (!cpumask_empty(cpus))
220                 smp_call_function_many(cpus, ack_flush, NULL, 1);
221         else
222                 called = false;
223         put_cpu();
224         free_cpumask_var(cpus);
225         return called;
226 }
227
228 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
229 void kvm_flush_remote_tlbs(struct kvm *kvm)
230 {
231         /*
232          * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
233          * kvm_make_all_cpus_request.
234          */
235         long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
236
237         /*
238          * We want to publish modifications to the page tables before reading
239          * mode. Pairs with a memory barrier in arch-specific code.
240          * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
241          * and smp_mb in walk_shadow_page_lockless_begin/end.
242          * - powerpc: smp_mb in kvmppc_prepare_to_enter.
243          *
244          * There is already an smp_mb__after_atomic() before
245          * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
246          * barrier here.
247          */
248         if (kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
249                 ++kvm->stat.remote_tlb_flush;
250         cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
251 }
252 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
253 #endif
254
255 void kvm_reload_remote_mmus(struct kvm *kvm)
256 {
257         kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
258 }
259
260 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
261 {
262         struct page *page;
263         int r;
264
265         mutex_init(&vcpu->mutex);
266         vcpu->cpu = -1;
267         vcpu->kvm = kvm;
268         vcpu->vcpu_id = id;
269         vcpu->pid = NULL;
270         init_swait_queue_head(&vcpu->wq);
271         kvm_async_pf_vcpu_init(vcpu);
272
273         vcpu->pre_pcpu = -1;
274         INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
275
276         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
277         if (!page) {
278                 r = -ENOMEM;
279                 goto fail;
280         }
281         vcpu->run = page_address(page);
282
283         kvm_vcpu_set_in_spin_loop(vcpu, false);
284         kvm_vcpu_set_dy_eligible(vcpu, false);
285         vcpu->preempted = false;
286
287         r = kvm_arch_vcpu_init(vcpu);
288         if (r < 0)
289                 goto fail_free_run;
290         return 0;
291
292 fail_free_run:
293         free_page((unsigned long)vcpu->run);
294 fail:
295         return r;
296 }
297 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
298
299 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
300 {
301         put_pid(vcpu->pid);
302         kvm_arch_vcpu_uninit(vcpu);
303         free_page((unsigned long)vcpu->run);
304 }
305 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
306
307 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
308 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
309 {
310         return container_of(mn, struct kvm, mmu_notifier);
311 }
312
313 static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
314                                              struct mm_struct *mm,
315                                              unsigned long address)
316 {
317         struct kvm *kvm = mmu_notifier_to_kvm(mn);
318         int need_tlb_flush, idx;
319
320         /*
321          * When ->invalidate_page runs, the linux pte has been zapped
322          * already but the page is still allocated until
323          * ->invalidate_page returns. So if we increase the sequence
324          * here the kvm page fault will notice if the spte can't be
325          * established because the page is going to be freed. If
326          * instead the kvm page fault establishes the spte before
327          * ->invalidate_page runs, kvm_unmap_hva will release it
328          * before returning.
329          *
330          * The sequence increase only need to be seen at spin_unlock
331          * time, and not at spin_lock time.
332          *
333          * Increasing the sequence after the spin_unlock would be
334          * unsafe because the kvm page fault could then establish the
335          * pte after kvm_unmap_hva returned, without noticing the page
336          * is going to be freed.
337          */
338         idx = srcu_read_lock(&kvm->srcu);
339         spin_lock(&kvm->mmu_lock);
340
341         kvm->mmu_notifier_seq++;
342         need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
343         /* we've to flush the tlb before the pages can be freed */
344         if (need_tlb_flush)
345                 kvm_flush_remote_tlbs(kvm);
346
347         spin_unlock(&kvm->mmu_lock);
348
349         kvm_arch_mmu_notifier_invalidate_page(kvm, address);
350
351         srcu_read_unlock(&kvm->srcu, idx);
352 }
353
354 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
355                                         struct mm_struct *mm,
356                                         unsigned long address,
357                                         pte_t pte)
358 {
359         struct kvm *kvm = mmu_notifier_to_kvm(mn);
360         int idx;
361
362         idx = srcu_read_lock(&kvm->srcu);
363         spin_lock(&kvm->mmu_lock);
364         kvm->mmu_notifier_seq++;
365         kvm_set_spte_hva(kvm, address, pte);
366         spin_unlock(&kvm->mmu_lock);
367         srcu_read_unlock(&kvm->srcu, idx);
368 }
369
370 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
371                                                     struct mm_struct *mm,
372                                                     unsigned long start,
373                                                     unsigned long end)
374 {
375         struct kvm *kvm = mmu_notifier_to_kvm(mn);
376         int need_tlb_flush = 0, idx;
377
378         idx = srcu_read_lock(&kvm->srcu);
379         spin_lock(&kvm->mmu_lock);
380         /*
381          * The count increase must become visible at unlock time as no
382          * spte can be established without taking the mmu_lock and
383          * count is also read inside the mmu_lock critical section.
384          */
385         kvm->mmu_notifier_count++;
386         need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
387         /* we've to flush the tlb before the pages can be freed */
388         if (need_tlb_flush || kvm->tlbs_dirty)
389                 kvm_flush_remote_tlbs(kvm);
390
391         spin_unlock(&kvm->mmu_lock);
392
393         kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
394
395         srcu_read_unlock(&kvm->srcu, idx);
396 }
397
398 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
399                                                   struct mm_struct *mm,
400                                                   unsigned long start,
401                                                   unsigned long end)
402 {
403         struct kvm *kvm = mmu_notifier_to_kvm(mn);
404
405         spin_lock(&kvm->mmu_lock);
406         /*
407          * This sequence increase will notify the kvm page fault that
408          * the page that is going to be mapped in the spte could have
409          * been freed.
410          */
411         kvm->mmu_notifier_seq++;
412         smp_wmb();
413         /*
414          * The above sequence increase must be visible before the
415          * below count decrease, which is ensured by the smp_wmb above
416          * in conjunction with the smp_rmb in mmu_notifier_retry().
417          */
418         kvm->mmu_notifier_count--;
419         spin_unlock(&kvm->mmu_lock);
420
421         BUG_ON(kvm->mmu_notifier_count < 0);
422 }
423
424 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
425                                               struct mm_struct *mm,
426                                               unsigned long start,
427                                               unsigned long end)
428 {
429         struct kvm *kvm = mmu_notifier_to_kvm(mn);
430         int young, idx;
431
432         idx = srcu_read_lock(&kvm->srcu);
433         spin_lock(&kvm->mmu_lock);
434
435         young = kvm_age_hva(kvm, start, end);
436         if (young)
437                 kvm_flush_remote_tlbs(kvm);
438
439         spin_unlock(&kvm->mmu_lock);
440         srcu_read_unlock(&kvm->srcu, idx);
441
442         return young;
443 }
444
445 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
446                                         struct mm_struct *mm,
447                                         unsigned long start,
448                                         unsigned long end)
449 {
450         struct kvm *kvm = mmu_notifier_to_kvm(mn);
451         int young, idx;
452
453         idx = srcu_read_lock(&kvm->srcu);
454         spin_lock(&kvm->mmu_lock);
455         /*
456          * Even though we do not flush TLB, this will still adversely
457          * affect performance on pre-Haswell Intel EPT, where there is
458          * no EPT Access Bit to clear so that we have to tear down EPT
459          * tables instead. If we find this unacceptable, we can always
460          * add a parameter to kvm_age_hva so that it effectively doesn't
461          * do anything on clear_young.
462          *
463          * Also note that currently we never issue secondary TLB flushes
464          * from clear_young, leaving this job up to the regular system
465          * cadence. If we find this inaccurate, we might come up with a
466          * more sophisticated heuristic later.
467          */
468         young = kvm_age_hva(kvm, start, end);
469         spin_unlock(&kvm->mmu_lock);
470         srcu_read_unlock(&kvm->srcu, idx);
471
472         return young;
473 }
474
475 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
476                                        struct mm_struct *mm,
477                                        unsigned long address)
478 {
479         struct kvm *kvm = mmu_notifier_to_kvm(mn);
480         int young, idx;
481
482         idx = srcu_read_lock(&kvm->srcu);
483         spin_lock(&kvm->mmu_lock);
484         young = kvm_test_age_hva(kvm, address);
485         spin_unlock(&kvm->mmu_lock);
486         srcu_read_unlock(&kvm->srcu, idx);
487
488         return young;
489 }
490
491 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
492                                      struct mm_struct *mm)
493 {
494         struct kvm *kvm = mmu_notifier_to_kvm(mn);
495         int idx;
496
497         idx = srcu_read_lock(&kvm->srcu);
498         kvm_arch_flush_shadow_all(kvm);
499         srcu_read_unlock(&kvm->srcu, idx);
500 }
501
502 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
503         .invalidate_page        = kvm_mmu_notifier_invalidate_page,
504         .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
505         .invalidate_range_end   = kvm_mmu_notifier_invalidate_range_end,
506         .clear_flush_young      = kvm_mmu_notifier_clear_flush_young,
507         .clear_young            = kvm_mmu_notifier_clear_young,
508         .test_young             = kvm_mmu_notifier_test_young,
509         .change_pte             = kvm_mmu_notifier_change_pte,
510         .release                = kvm_mmu_notifier_release,
511 };
512
513 static int kvm_init_mmu_notifier(struct kvm *kvm)
514 {
515         kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
516         return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
517 }
518
519 #else  /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
520
521 static int kvm_init_mmu_notifier(struct kvm *kvm)
522 {
523         return 0;
524 }
525
526 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
527
528 static struct kvm_memslots *kvm_alloc_memslots(void)
529 {
530         int i;
531         struct kvm_memslots *slots;
532
533         slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
534         if (!slots)
535                 return NULL;
536
537         /*
538          * Init kvm generation close to the maximum to easily test the
539          * code of handling generation number wrap-around.
540          */
541         slots->generation = -150;
542         for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
543                 slots->id_to_index[i] = slots->memslots[i].id = i;
544
545         return slots;
546 }
547
548 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
549 {
550         if (!memslot->dirty_bitmap)
551                 return;
552
553         kvfree(memslot->dirty_bitmap);
554         memslot->dirty_bitmap = NULL;
555 }
556
557 /*
558  * Free any memory in @free but not in @dont.
559  */
560 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
561                               struct kvm_memory_slot *dont)
562 {
563         if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
564                 kvm_destroy_dirty_bitmap(free);
565
566         kvm_arch_free_memslot(kvm, free, dont);
567
568         free->npages = 0;
569 }
570
571 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
572 {
573         struct kvm_memory_slot *memslot;
574
575         if (!slots)
576                 return;
577
578         kvm_for_each_memslot(memslot, slots)
579                 kvm_free_memslot(kvm, memslot, NULL);
580
581         kvfree(slots);
582 }
583
584 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
585 {
586         int i;
587
588         if (!kvm->debugfs_dentry)
589                 return;
590
591         debugfs_remove_recursive(kvm->debugfs_dentry);
592
593         if (kvm->debugfs_stat_data) {
594                 for (i = 0; i < kvm_debugfs_num_entries; i++)
595                         kfree(kvm->debugfs_stat_data[i]);
596                 kfree(kvm->debugfs_stat_data);
597         }
598 }
599
600 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
601 {
602         char dir_name[ITOA_MAX_LEN * 2];
603         struct kvm_stat_data *stat_data;
604         struct kvm_stats_debugfs_item *p;
605
606         if (!debugfs_initialized())
607                 return 0;
608
609         snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
610         kvm->debugfs_dentry = debugfs_create_dir(dir_name,
611                                                  kvm_debugfs_dir);
612         if (!kvm->debugfs_dentry)
613                 return -ENOMEM;
614
615         kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
616                                          sizeof(*kvm->debugfs_stat_data),
617                                          GFP_KERNEL);
618         if (!kvm->debugfs_stat_data)
619                 return -ENOMEM;
620
621         for (p = debugfs_entries; p->name; p++) {
622                 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
623                 if (!stat_data)
624                         return -ENOMEM;
625
626                 stat_data->kvm = kvm;
627                 stat_data->offset = p->offset;
628                 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
629                 if (!debugfs_create_file(p->name, 0444,
630                                          kvm->debugfs_dentry,
631                                          stat_data,
632                                          stat_fops_per_vm[p->kind]))
633                         return -ENOMEM;
634         }
635         return 0;
636 }
637
638 /*
639  * Called after the VM is otherwise initialized, but just before adding it to
640  * the vm_list.
641  */
642 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
643 {
644         return 0;
645 }
646
647 /*
648  * Called just after removing the VM from the vm_list, but before doing any
649  * other destruction.
650  */
651 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
652 {
653 }
654
655 static struct kvm *kvm_create_vm(unsigned long type)
656 {
657         int r, i;
658         struct kvm *kvm = kvm_arch_alloc_vm();
659
660         if (!kvm)
661                 return ERR_PTR(-ENOMEM);
662
663         spin_lock_init(&kvm->mmu_lock);
664         atomic_inc(&current->mm->mm_count);
665         kvm->mm = current->mm;
666         kvm_eventfd_init(kvm);
667         mutex_init(&kvm->lock);
668         mutex_init(&kvm->irq_lock);
669         mutex_init(&kvm->slots_lock);
670         atomic_set(&kvm->users_count, 1);
671         INIT_LIST_HEAD(&kvm->devices);
672
673         r = kvm_arch_init_vm(kvm, type);
674         if (r)
675                 goto out_err_no_disable;
676
677         r = hardware_enable_all();
678         if (r)
679                 goto out_err_no_disable;
680
681 #ifdef CONFIG_HAVE_KVM_IRQFD
682         INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
683 #endif
684
685         BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
686
687         r = -ENOMEM;
688         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
689                 kvm->memslots[i] = kvm_alloc_memslots();
690                 if (!kvm->memslots[i])
691                         goto out_err_no_srcu;
692         }
693
694         if (init_srcu_struct(&kvm->srcu))
695                 goto out_err_no_srcu;
696         if (init_srcu_struct(&kvm->irq_srcu))
697                 goto out_err_no_irq_srcu;
698         for (i = 0; i < KVM_NR_BUSES; i++) {
699                 kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
700                                         GFP_KERNEL);
701                 if (!kvm->buses[i])
702                         goto out_err_no_mmu_notifier;
703         }
704
705         r = kvm_init_mmu_notifier(kvm);
706         if (r)
707                 goto out_err_no_mmu_notifier;
708
709         r = kvm_arch_post_init_vm(kvm);
710         if (r)
711                 goto out_err;
712
713         mutex_lock(&kvm_lock);
714         list_add(&kvm->vm_list, &vm_list);
715         mutex_unlock(&kvm_lock);
716
717         preempt_notifier_inc();
718
719         /*
720          * When the fd passed to this ioctl() is opened it pins the module,
721          * but try_module_get() also prevents getting a reference if the module
722          * is in MODULE_STATE_GOING (e.g. if someone ran "rmmod --wait").
723          */
724         if (!try_module_get(kvm_chardev_ops.owner)) {
725                 r = -ENODEV;
726                 goto out_err;
727         }
728
729         return kvm;
730
731 out_err:
732 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
733         if (kvm->mmu_notifier.ops)
734                 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
735 #endif
736 out_err_no_mmu_notifier:
737         cleanup_srcu_struct(&kvm->irq_srcu);
738 out_err_no_irq_srcu:
739         cleanup_srcu_struct(&kvm->srcu);
740 out_err_no_srcu:
741         hardware_disable_all();
742 out_err_no_disable:
743         for (i = 0; i < KVM_NR_BUSES; i++)
744                 kfree(kvm->buses[i]);
745         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
746                 kvm_free_memslots(kvm, kvm->memslots[i]);
747         kvm_arch_free_vm(kvm);
748         mmdrop(current->mm);
749         return ERR_PTR(r);
750 }
751
752 /*
753  * Avoid using vmalloc for a small buffer.
754  * Should not be used when the size is statically known.
755  */
756 void *kvm_kvzalloc(unsigned long size)
757 {
758         if (size > PAGE_SIZE)
759                 return vzalloc(size);
760         else
761                 return kzalloc(size, GFP_KERNEL);
762 }
763
764 static void kvm_destroy_devices(struct kvm *kvm)
765 {
766         struct kvm_device *dev, *tmp;
767
768         /*
769          * We do not need to take the kvm->lock here, because nobody else
770          * has a reference to the struct kvm at this point and therefore
771          * cannot access the devices list anyhow.
772          */
773         list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
774                 list_del(&dev->vm_node);
775                 dev->ops->destroy(dev);
776         }
777 }
778
779 static void kvm_destroy_vm(struct kvm *kvm)
780 {
781         int i;
782         struct mm_struct *mm = kvm->mm;
783
784         kvm_destroy_vm_debugfs(kvm);
785         kvm_arch_sync_events(kvm);
786         mutex_lock(&kvm_lock);
787         list_del(&kvm->vm_list);
788         mutex_unlock(&kvm_lock);
789         kvm_arch_pre_destroy_vm(kvm);
790
791         kvm_free_irq_routing(kvm);
792         for (i = 0; i < KVM_NR_BUSES; i++) {
793                 if (kvm->buses[i])
794                         kvm_io_bus_destroy(kvm->buses[i]);
795                 kvm->buses[i] = NULL;
796         }
797         kvm_coalesced_mmio_free(kvm);
798 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
799         mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
800 #else
801         kvm_arch_flush_shadow_all(kvm);
802 #endif
803         kvm_arch_destroy_vm(kvm);
804         kvm_destroy_devices(kvm);
805         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
806                 kvm_free_memslots(kvm, kvm->memslots[i]);
807         cleanup_srcu_struct(&kvm->irq_srcu);
808         cleanup_srcu_struct(&kvm->srcu);
809         kvm_arch_free_vm(kvm);
810         preempt_notifier_dec();
811         hardware_disable_all();
812         mmdrop(mm);
813         module_put(kvm_chardev_ops.owner);
814 }
815
816 void kvm_get_kvm(struct kvm *kvm)
817 {
818         atomic_inc(&kvm->users_count);
819 }
820 EXPORT_SYMBOL_GPL(kvm_get_kvm);
821
822 void kvm_put_kvm(struct kvm *kvm)
823 {
824         if (atomic_dec_and_test(&kvm->users_count))
825                 kvm_destroy_vm(kvm);
826 }
827 EXPORT_SYMBOL_GPL(kvm_put_kvm);
828
829
830 static int kvm_vm_release(struct inode *inode, struct file *filp)
831 {
832         struct kvm *kvm = filp->private_data;
833
834         kvm_irqfd_release(kvm);
835
836         kvm_put_kvm(kvm);
837         return 0;
838 }
839
840 /*
841  * Allocation size is twice as large as the actual dirty bitmap size.
842  * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
843  */
844 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
845 {
846         unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
847
848         memslot->dirty_bitmap = kvm_kvzalloc(dirty_bytes);
849         if (!memslot->dirty_bitmap)
850                 return -ENOMEM;
851
852         return 0;
853 }
854
855 /*
856  * Insert memslot and re-sort memslots based on their GFN,
857  * so binary search could be used to lookup GFN.
858  * Sorting algorithm takes advantage of having initially
859  * sorted array and known changed memslot position.
860  */
861 static void update_memslots(struct kvm_memslots *slots,
862                             struct kvm_memory_slot *new)
863 {
864         int id = new->id;
865         int i = slots->id_to_index[id];
866         struct kvm_memory_slot *mslots = slots->memslots;
867
868         WARN_ON(mslots[i].id != id);
869         if (!new->npages) {
870                 WARN_ON(!mslots[i].npages);
871                 if (mslots[i].npages)
872                         slots->used_slots--;
873         } else {
874                 if (!mslots[i].npages)
875                         slots->used_slots++;
876         }
877
878         while (i < KVM_MEM_SLOTS_NUM - 1 &&
879                new->base_gfn <= mslots[i + 1].base_gfn) {
880                 if (!mslots[i + 1].npages)
881                         break;
882                 mslots[i] = mslots[i + 1];
883                 slots->id_to_index[mslots[i].id] = i;
884                 i++;
885         }
886
887         /*
888          * The ">=" is needed when creating a slot with base_gfn == 0,
889          * so that it moves before all those with base_gfn == npages == 0.
890          *
891          * On the other hand, if new->npages is zero, the above loop has
892          * already left i pointing to the beginning of the empty part of
893          * mslots, and the ">=" would move the hole backwards in this
894          * case---which is wrong.  So skip the loop when deleting a slot.
895          */
896         if (new->npages) {
897                 while (i > 0 &&
898                        new->base_gfn >= mslots[i - 1].base_gfn) {
899                         mslots[i] = mslots[i - 1];
900                         slots->id_to_index[mslots[i].id] = i;
901                         i--;
902                 }
903         } else
904                 WARN_ON_ONCE(i != slots->used_slots);
905
906         mslots[i] = *new;
907         slots->id_to_index[mslots[i].id] = i;
908 }
909
910 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
911 {
912         u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
913
914 #ifdef __KVM_HAVE_READONLY_MEM
915         valid_flags |= KVM_MEM_READONLY;
916 #endif
917
918         if (mem->flags & ~valid_flags)
919                 return -EINVAL;
920
921         return 0;
922 }
923
924 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
925                 int as_id, struct kvm_memslots *slots)
926 {
927         struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
928
929         /*
930          * Set the low bit in the generation, which disables SPTE caching
931          * until the end of synchronize_srcu_expedited.
932          */
933         WARN_ON(old_memslots->generation & 1);
934         slots->generation = old_memslots->generation + 1;
935
936         rcu_assign_pointer(kvm->memslots[as_id], slots);
937         synchronize_srcu_expedited(&kvm->srcu);
938
939         /*
940          * Increment the new memslot generation a second time. This prevents
941          * vm exits that race with memslot updates from caching a memslot
942          * generation that will (potentially) be valid forever.
943          */
944         slots->generation++;
945
946         kvm_arch_memslots_updated(kvm, slots);
947
948         return old_memslots;
949 }
950
951 /*
952  * Allocate some memory and give it an address in the guest physical address
953  * space.
954  *
955  * Discontiguous memory is allowed, mostly for framebuffers.
956  *
957  * Must be called holding kvm->slots_lock for write.
958  */
959 int __kvm_set_memory_region(struct kvm *kvm,
960                             const struct kvm_userspace_memory_region *mem)
961 {
962         int r;
963         gfn_t base_gfn;
964         unsigned long npages;
965         struct kvm_memory_slot *slot;
966         struct kvm_memory_slot old, new;
967         struct kvm_memslots *slots = NULL, *old_memslots;
968         int as_id, id;
969         enum kvm_mr_change change;
970
971         r = check_memory_region_flags(mem);
972         if (r)
973                 goto out;
974
975         r = -EINVAL;
976         as_id = mem->slot >> 16;
977         id = (u16)mem->slot;
978
979         /* General sanity checks */
980         if (mem->memory_size & (PAGE_SIZE - 1))
981                 goto out;
982         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
983                 goto out;
984         /* We can read the guest memory with __xxx_user() later on. */
985         if ((id < KVM_USER_MEM_SLOTS) &&
986             ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
987              !access_ok(VERIFY_WRITE,
988                         (void __user *)(unsigned long)mem->userspace_addr,
989                         mem->memory_size)))
990                 goto out;
991         if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
992                 goto out;
993         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
994                 goto out;
995
996         slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
997         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
998         npages = mem->memory_size >> PAGE_SHIFT;
999
1000         if (npages > KVM_MEM_MAX_NR_PAGES)
1001                 goto out;
1002
1003         new = old = *slot;
1004
1005         new.id = id;
1006         new.base_gfn = base_gfn;
1007         new.npages = npages;
1008         new.flags = mem->flags;
1009
1010         if (npages) {
1011                 if (!old.npages)
1012                         change = KVM_MR_CREATE;
1013                 else { /* Modify an existing slot. */
1014                         if ((mem->userspace_addr != old.userspace_addr) ||
1015                             (npages != old.npages) ||
1016                             ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1017                                 goto out;
1018
1019                         if (base_gfn != old.base_gfn)
1020                                 change = KVM_MR_MOVE;
1021                         else if (new.flags != old.flags)
1022                                 change = KVM_MR_FLAGS_ONLY;
1023                         else { /* Nothing to change. */
1024                                 r = 0;
1025                                 goto out;
1026                         }
1027                 }
1028         } else {
1029                 if (!old.npages)
1030                         goto out;
1031
1032                 change = KVM_MR_DELETE;
1033                 new.base_gfn = 0;
1034                 new.flags = 0;
1035         }
1036
1037         if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1038                 /* Check for overlaps */
1039                 r = -EEXIST;
1040                 kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
1041                         if (slot->id == id)
1042                                 continue;
1043                         if (!((base_gfn + npages <= slot->base_gfn) ||
1044                               (base_gfn >= slot->base_gfn + slot->npages)))
1045                                 goto out;
1046                 }
1047         }
1048
1049         /* Free page dirty bitmap if unneeded */
1050         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1051                 new.dirty_bitmap = NULL;
1052
1053         r = -ENOMEM;
1054         if (change == KVM_MR_CREATE) {
1055                 new.userspace_addr = mem->userspace_addr;
1056
1057                 if (kvm_arch_create_memslot(kvm, &new, npages))
1058                         goto out_free;
1059         }
1060
1061         /* Allocate page dirty bitmap if needed */
1062         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1063                 if (kvm_create_dirty_bitmap(&new) < 0)
1064                         goto out_free;
1065         }
1066
1067         slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
1068         if (!slots)
1069                 goto out_free;
1070         memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
1071
1072         if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
1073                 slot = id_to_memslot(slots, id);
1074                 slot->flags |= KVM_MEMSLOT_INVALID;
1075
1076                 old_memslots = install_new_memslots(kvm, as_id, slots);
1077
1078                 /* slot was deleted or moved, clear iommu mapping */
1079                 kvm_iommu_unmap_pages(kvm, &old);
1080                 /* From this point no new shadow pages pointing to a deleted,
1081                  * or moved, memslot will be created.
1082                  *
1083                  * validation of sp->gfn happens in:
1084                  *      - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1085                  *      - kvm_is_visible_gfn (mmu_check_roots)
1086                  */
1087                 kvm_arch_flush_shadow_memslot(kvm, slot);
1088
1089                 /*
1090                  * We can re-use the old_memslots from above, the only difference
1091                  * from the currently installed memslots is the invalid flag.  This
1092                  * will get overwritten by update_memslots anyway.
1093                  */
1094                 slots = old_memslots;
1095         }
1096
1097         r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
1098         if (r)
1099                 goto out_slots;
1100
1101         /* actual memory is freed via old in kvm_free_memslot below */
1102         if (change == KVM_MR_DELETE) {
1103                 new.dirty_bitmap = NULL;
1104                 memset(&new.arch, 0, sizeof(new.arch));
1105         }
1106
1107         update_memslots(slots, &new);
1108         old_memslots = install_new_memslots(kvm, as_id, slots);
1109
1110         kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
1111
1112         kvm_free_memslot(kvm, &old, &new);
1113         kvfree(old_memslots);
1114
1115         /*
1116          * IOMMU mapping:  New slots need to be mapped.  Old slots need to be
1117          * un-mapped and re-mapped if their base changes.  Since base change
1118          * unmapping is handled above with slot deletion, mapping alone is
1119          * needed here.  Anything else the iommu might care about for existing
1120          * slots (size changes, userspace addr changes and read-only flag
1121          * changes) is disallowed above, so any other attribute changes getting
1122          * here can be skipped.
1123          */
1124         if (as_id == 0 && (change == KVM_MR_CREATE || change == KVM_MR_MOVE)) {
1125                 r = kvm_iommu_map_pages(kvm, &new);
1126                 return r;
1127         }
1128
1129         return 0;
1130
1131 out_slots:
1132         kvfree(slots);
1133 out_free:
1134         kvm_free_memslot(kvm, &new, &old);
1135 out:
1136         return r;
1137 }
1138 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1139
1140 int kvm_set_memory_region(struct kvm *kvm,
1141                           const struct kvm_userspace_memory_region *mem)
1142 {
1143         int r;
1144
1145         mutex_lock(&kvm->slots_lock);
1146         r = __kvm_set_memory_region(kvm, mem);
1147         mutex_unlock(&kvm->slots_lock);
1148         return r;
1149 }
1150 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1151
1152 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1153                                           struct kvm_userspace_memory_region *mem)
1154 {
1155         if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1156                 return -EINVAL;
1157
1158         return kvm_set_memory_region(kvm, mem);
1159 }
1160
1161 int kvm_get_dirty_log(struct kvm *kvm,
1162                         struct kvm_dirty_log *log, int *is_dirty)
1163 {
1164         struct kvm_memslots *slots;
1165         struct kvm_memory_slot *memslot;
1166         int r, i, as_id, id;
1167         unsigned long n;
1168         unsigned long any = 0;
1169
1170         r = -EINVAL;
1171         as_id = log->slot >> 16;
1172         id = (u16)log->slot;
1173         if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1174                 goto out;
1175
1176         slots = __kvm_memslots(kvm, as_id);
1177         memslot = id_to_memslot(slots, id);
1178         r = -ENOENT;
1179         if (!memslot->dirty_bitmap)
1180                 goto out;
1181
1182         n = kvm_dirty_bitmap_bytes(memslot);
1183
1184         for (i = 0; !any && i < n/sizeof(long); ++i)
1185                 any = memslot->dirty_bitmap[i];
1186
1187         r = -EFAULT;
1188         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1189                 goto out;
1190
1191         if (any)
1192                 *is_dirty = 1;
1193
1194         r = 0;
1195 out:
1196         return r;
1197 }
1198 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1199
1200 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1201 /**
1202  * kvm_get_dirty_log_protect - get a snapshot of dirty pages, and if any pages
1203  *      are dirty write protect them for next write.
1204  * @kvm:        pointer to kvm instance
1205  * @log:        slot id and address to which we copy the log
1206  * @is_dirty:   flag set if any page is dirty
1207  *
1208  * We need to keep it in mind that VCPU threads can write to the bitmap
1209  * concurrently. So, to avoid losing track of dirty pages we keep the
1210  * following order:
1211  *
1212  *    1. Take a snapshot of the bit and clear it if needed.
1213  *    2. Write protect the corresponding page.
1214  *    3. Copy the snapshot to the userspace.
1215  *    4. Upon return caller flushes TLB's if needed.
1216  *
1217  * Between 2 and 4, the guest may write to the page using the remaining TLB
1218  * entry.  This is not a problem because the page is reported dirty using
1219  * the snapshot taken before and step 4 ensures that writes done after
1220  * exiting to userspace will be logged for the next call.
1221  *
1222  */
1223 int kvm_get_dirty_log_protect(struct kvm *kvm,
1224                         struct kvm_dirty_log *log, bool *is_dirty)
1225 {
1226         struct kvm_memslots *slots;
1227         struct kvm_memory_slot *memslot;
1228         int r, i, as_id, id;
1229         unsigned long n;
1230         unsigned long *dirty_bitmap;
1231         unsigned long *dirty_bitmap_buffer;
1232
1233         r = -EINVAL;
1234         as_id = log->slot >> 16;
1235         id = (u16)log->slot;
1236         if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1237                 goto out;
1238
1239         slots = __kvm_memslots(kvm, as_id);
1240         memslot = id_to_memslot(slots, id);
1241
1242         dirty_bitmap = memslot->dirty_bitmap;
1243         r = -ENOENT;
1244         if (!dirty_bitmap)
1245                 goto out;
1246
1247         n = kvm_dirty_bitmap_bytes(memslot);
1248
1249         dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
1250         memset(dirty_bitmap_buffer, 0, n);
1251
1252         spin_lock(&kvm->mmu_lock);
1253         *is_dirty = false;
1254         for (i = 0; i < n / sizeof(long); i++) {
1255                 unsigned long mask;
1256                 gfn_t offset;
1257
1258                 if (!dirty_bitmap[i])
1259                         continue;
1260
1261                 *is_dirty = true;
1262
1263                 mask = xchg(&dirty_bitmap[i], 0);
1264                 dirty_bitmap_buffer[i] = mask;
1265
1266                 if (mask) {
1267                         offset = i * BITS_PER_LONG;
1268                         kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1269                                                                 offset, mask);
1270                 }
1271         }
1272
1273         spin_unlock(&kvm->mmu_lock);
1274
1275         r = -EFAULT;
1276         if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1277                 goto out;
1278
1279         r = 0;
1280 out:
1281         return r;
1282 }
1283 EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
1284 #endif
1285
1286 bool kvm_largepages_enabled(void)
1287 {
1288         return largepages_enabled;
1289 }
1290
1291 void kvm_disable_largepages(void)
1292 {
1293         largepages_enabled = false;
1294 }
1295 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1296
1297 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1298 {
1299         return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1300 }
1301 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1302
1303 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1304 {
1305         return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1306 }
1307
1308 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1309 {
1310         struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1311
1312         if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1313               memslot->flags & KVM_MEMSLOT_INVALID)
1314                 return false;
1315
1316         return true;
1317 }
1318 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1319
1320 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
1321 {
1322         struct vm_area_struct *vma;
1323         unsigned long addr, size;
1324
1325         size = PAGE_SIZE;
1326
1327         addr = gfn_to_hva(kvm, gfn);
1328         if (kvm_is_error_hva(addr))
1329                 return PAGE_SIZE;
1330
1331         down_read(&current->mm->mmap_sem);
1332         vma = find_vma(current->mm, addr);
1333         if (!vma)
1334                 goto out;
1335
1336         size = vma_kernel_pagesize(vma);
1337
1338 out:
1339         up_read(&current->mm->mmap_sem);
1340
1341         return size;
1342 }
1343
1344 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1345 {
1346         return slot->flags & KVM_MEM_READONLY;
1347 }
1348
1349 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1350                                        gfn_t *nr_pages, bool write)
1351 {
1352         if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1353                 return KVM_HVA_ERR_BAD;
1354
1355         if (memslot_is_readonly(slot) && write)
1356                 return KVM_HVA_ERR_RO_BAD;
1357
1358         if (nr_pages)
1359                 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1360
1361         return __gfn_to_hva_memslot(slot, gfn);
1362 }
1363
1364 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1365                                      gfn_t *nr_pages)
1366 {
1367         return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1368 }
1369
1370 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1371                                         gfn_t gfn)
1372 {
1373         return gfn_to_hva_many(slot, gfn, NULL);
1374 }
1375 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1376
1377 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1378 {
1379         return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1380 }
1381 EXPORT_SYMBOL_GPL(gfn_to_hva);
1382
1383 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1384 {
1385         return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1386 }
1387 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1388
1389 /*
1390  * If writable is set to false, the hva returned by this function is only
1391  * allowed to be read.
1392  */
1393 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1394                                       gfn_t gfn, bool *writable)
1395 {
1396         unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1397
1398         if (!kvm_is_error_hva(hva) && writable)
1399                 *writable = !memslot_is_readonly(slot);
1400
1401         return hva;
1402 }
1403
1404 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1405 {
1406         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1407
1408         return gfn_to_hva_memslot_prot(slot, gfn, writable);
1409 }
1410
1411 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1412 {
1413         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1414
1415         return gfn_to_hva_memslot_prot(slot, gfn, writable);
1416 }
1417
1418 static int get_user_page_nowait(unsigned long start, int write,
1419                 struct page **page)
1420 {
1421         int flags = FOLL_NOWAIT | FOLL_HWPOISON;
1422
1423         if (write)
1424                 flags |= FOLL_WRITE;
1425
1426         return get_user_pages(start, 1, flags, page, NULL);
1427 }
1428
1429 static inline int check_user_page_hwpoison(unsigned long addr)
1430 {
1431         int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1432
1433         rc = get_user_pages(addr, 1, flags, NULL, NULL);
1434         return rc == -EHWPOISON;
1435 }
1436
1437 /*
1438  * The atomic path to get the writable pfn which will be stored in @pfn,
1439  * true indicates success, otherwise false is returned.
1440  */
1441 static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
1442                             bool write_fault, bool *writable, kvm_pfn_t *pfn)
1443 {
1444         struct page *page[1];
1445         int npages;
1446
1447         if (!(async || atomic))
1448                 return false;
1449
1450         /*
1451          * Fast pin a writable pfn only if it is a write fault request
1452          * or the caller allows to map a writable pfn for a read fault
1453          * request.
1454          */
1455         if (!(write_fault || writable))
1456                 return false;
1457
1458         npages = __get_user_pages_fast(addr, 1, 1, page);
1459         if (npages == 1) {
1460                 *pfn = page_to_pfn(page[0]);
1461
1462                 if (writable)
1463                         *writable = true;
1464                 return true;
1465         }
1466
1467         return false;
1468 }
1469
1470 /*
1471  * The slow path to get the pfn of the specified host virtual address,
1472  * 1 indicates success, -errno is returned if error is detected.
1473  */
1474 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1475                            bool *writable, kvm_pfn_t *pfn)
1476 {
1477         struct page *page[1];
1478         int npages = 0;
1479
1480         might_sleep();
1481
1482         if (writable)
1483                 *writable = write_fault;
1484
1485         if (async) {
1486                 down_read(&current->mm->mmap_sem);
1487                 npages = get_user_page_nowait(addr, write_fault, page);
1488                 up_read(&current->mm->mmap_sem);
1489         } else {
1490                 unsigned int flags = FOLL_TOUCH | FOLL_HWPOISON;
1491
1492                 if (write_fault)
1493                         flags |= FOLL_WRITE;
1494
1495                 npages = __get_user_pages_unlocked(current, current->mm, addr, 1,
1496                                                    page, flags);
1497         }
1498         if (npages != 1)
1499                 return npages;
1500
1501         /* map read fault as writable if possible */
1502         if (unlikely(!write_fault) && writable) {
1503                 struct page *wpage[1];
1504
1505                 npages = __get_user_pages_fast(addr, 1, 1, wpage);
1506                 if (npages == 1) {
1507                         *writable = true;
1508                         put_page(page[0]);
1509                         page[0] = wpage[0];
1510                 }
1511
1512                 npages = 1;
1513         }
1514         *pfn = page_to_pfn(page[0]);
1515         return npages;
1516 }
1517
1518 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1519 {
1520         if (unlikely(!(vma->vm_flags & VM_READ)))
1521                 return false;
1522
1523         if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1524                 return false;
1525
1526         return true;
1527 }
1528
1529 static int kvm_try_get_pfn(kvm_pfn_t pfn)
1530 {
1531         if (kvm_is_reserved_pfn(pfn))
1532                 return 1;
1533         return get_page_unless_zero(pfn_to_page(pfn));
1534 }
1535
1536 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1537                                unsigned long addr, bool *async,
1538                                bool write_fault, bool *writable,
1539                                kvm_pfn_t *p_pfn)
1540 {
1541         kvm_pfn_t pfn;
1542         pte_t *ptep;
1543         spinlock_t *ptl;
1544         int r;
1545
1546         r = follow_pte_pmd(vma->vm_mm, addr, &ptep, NULL, &ptl);
1547         if (r) {
1548                 /*
1549                  * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1550                  * not call the fault handler, so do it here.
1551                  */
1552                 bool unlocked = false;
1553                 r = fixup_user_fault(current, current->mm, addr,
1554                                      (write_fault ? FAULT_FLAG_WRITE : 0),
1555                                      &unlocked);
1556                 if (unlocked)
1557                         return -EAGAIN;
1558                 if (r)
1559                         return r;
1560
1561                 r = follow_pte_pmd(vma->vm_mm, addr, &ptep, NULL, &ptl);
1562                 if (r)
1563                         return r;
1564         }
1565
1566         if (write_fault && !pte_write(*ptep)) {
1567                 pfn = KVM_PFN_ERR_RO_FAULT;
1568                 goto out;
1569         }
1570
1571         if (writable)
1572                 *writable = pte_write(*ptep);
1573         pfn = pte_pfn(*ptep);
1574
1575         /*
1576          * Get a reference here because callers of *hva_to_pfn* and
1577          * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1578          * returned pfn.  This is only needed if the VMA has VM_MIXEDMAP
1579          * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1580          * simply do nothing for reserved pfns.
1581          *
1582          * Whoever called remap_pfn_range is also going to call e.g.
1583          * unmap_mapping_range before the underlying pages are freed,
1584          * causing a call to our MMU notifier.
1585          *
1586          * Certain IO or PFNMAP mappings can be backed with valid
1587          * struct pages, but be allocated without refcounting e.g.,
1588          * tail pages of non-compound higher order allocations, which
1589          * would then underflow the refcount when the caller does the
1590          * required put_page. Don't allow those pages here.
1591          */ 
1592         if (!kvm_try_get_pfn(pfn))
1593                 r = -EFAULT;
1594
1595 out:
1596         pte_unmap_unlock(ptep, ptl);
1597         *p_pfn = pfn;
1598
1599         return r;
1600 }
1601
1602 /*
1603  * Pin guest page in memory and return its pfn.
1604  * @addr: host virtual address which maps memory to the guest
1605  * @atomic: whether this function can sleep
1606  * @async: whether this function need to wait IO complete if the
1607  *         host page is not in the memory
1608  * @write_fault: whether we should get a writable host page
1609  * @writable: whether it allows to map a writable host page for !@write_fault
1610  *
1611  * The function will map a writable host page for these two cases:
1612  * 1): @write_fault = true
1613  * 2): @write_fault = false && @writable, @writable will tell the caller
1614  *     whether the mapping is writable.
1615  */
1616 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1617                         bool write_fault, bool *writable)
1618 {
1619         struct vm_area_struct *vma;
1620         kvm_pfn_t pfn = 0;
1621         int npages, r;
1622
1623         /* we can do it either atomically or asynchronously, not both */
1624         BUG_ON(atomic && async);
1625
1626         if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
1627                 return pfn;
1628
1629         if (atomic)
1630                 return KVM_PFN_ERR_FAULT;
1631
1632         npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1633         if (npages == 1)
1634                 return pfn;
1635
1636         down_read(&current->mm->mmap_sem);
1637         if (npages == -EHWPOISON ||
1638               (!async && check_user_page_hwpoison(addr))) {
1639                 pfn = KVM_PFN_ERR_HWPOISON;
1640                 goto exit;
1641         }
1642
1643 retry:
1644         vma = find_vma_intersection(current->mm, addr, addr + 1);
1645
1646         if (vma == NULL)
1647                 pfn = KVM_PFN_ERR_FAULT;
1648         else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1649                 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1650                 if (r == -EAGAIN)
1651                         goto retry;
1652                 if (r < 0)
1653                         pfn = KVM_PFN_ERR_FAULT;
1654         } else {
1655                 if (async && vma_is_valid(vma, write_fault))
1656                         *async = true;
1657                 pfn = KVM_PFN_ERR_FAULT;
1658         }
1659 exit:
1660         up_read(&current->mm->mmap_sem);
1661         return pfn;
1662 }
1663
1664 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1665                                bool atomic, bool *async, bool write_fault,
1666                                bool *writable)
1667 {
1668         unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1669
1670         if (addr == KVM_HVA_ERR_RO_BAD) {
1671                 if (writable)
1672                         *writable = false;
1673                 return KVM_PFN_ERR_RO_FAULT;
1674         }
1675
1676         if (kvm_is_error_hva(addr)) {
1677                 if (writable)
1678                         *writable = false;
1679                 return KVM_PFN_NOSLOT;
1680         }
1681
1682         /* Do not map writable pfn in the readonly memslot. */
1683         if (writable && memslot_is_readonly(slot)) {
1684                 *writable = false;
1685                 writable = NULL;
1686         }
1687
1688         return hva_to_pfn(addr, atomic, async, write_fault,
1689                           writable);
1690 }
1691 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1692
1693 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1694                       bool *writable)
1695 {
1696         return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1697                                     write_fault, writable);
1698 }
1699 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1700
1701 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1702 {
1703         return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1704 }
1705 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1706
1707 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1708 {
1709         return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1710 }
1711 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1712
1713 kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1714 {
1715         return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1716 }
1717 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1718
1719 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1720 {
1721         return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1722 }
1723 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1724
1725 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1726 {
1727         return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1728 }
1729 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1730
1731 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1732 {
1733         return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1734 }
1735 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1736
1737 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1738                             struct page **pages, int nr_pages)
1739 {
1740         unsigned long addr;
1741         gfn_t entry;
1742
1743         addr = gfn_to_hva_many(slot, gfn, &entry);
1744         if (kvm_is_error_hva(addr))
1745                 return -1;
1746
1747         if (entry < nr_pages)
1748                 return 0;
1749
1750         return __get_user_pages_fast(addr, nr_pages, 1, pages);
1751 }
1752 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1753
1754 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
1755 {
1756         if (is_error_noslot_pfn(pfn))
1757                 return KVM_ERR_PTR_BAD_PAGE;
1758
1759         if (kvm_is_reserved_pfn(pfn)) {
1760                 WARN_ON(1);
1761                 return KVM_ERR_PTR_BAD_PAGE;
1762         }
1763
1764         return pfn_to_page(pfn);
1765 }
1766
1767 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1768 {
1769         kvm_pfn_t pfn;
1770
1771         pfn = gfn_to_pfn(kvm, gfn);
1772
1773         return kvm_pfn_to_page(pfn);
1774 }
1775 EXPORT_SYMBOL_GPL(gfn_to_page);
1776
1777 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
1778 {
1779         kvm_pfn_t pfn;
1780
1781         pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
1782
1783         return kvm_pfn_to_page(pfn);
1784 }
1785 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
1786
1787 void kvm_release_page_clean(struct page *page)
1788 {
1789         WARN_ON(is_error_page(page));
1790
1791         kvm_release_pfn_clean(page_to_pfn(page));
1792 }
1793 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1794
1795 void kvm_release_pfn_clean(kvm_pfn_t pfn)
1796 {
1797         if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
1798                 put_page(pfn_to_page(pfn));
1799 }
1800 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1801
1802 void kvm_release_page_dirty(struct page *page)
1803 {
1804         WARN_ON(is_error_page(page));
1805
1806         kvm_release_pfn_dirty(page_to_pfn(page));
1807 }
1808 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1809
1810 static void kvm_release_pfn_dirty(kvm_pfn_t pfn)
1811 {
1812         kvm_set_pfn_dirty(pfn);
1813         kvm_release_pfn_clean(pfn);
1814 }
1815
1816 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
1817 {
1818         if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn)) {
1819                 struct page *page = pfn_to_page(pfn);
1820
1821                 if (!PageReserved(page))
1822                         SetPageDirty(page);
1823         }
1824 }
1825 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1826
1827 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
1828 {
1829         if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
1830                 mark_page_accessed(pfn_to_page(pfn));
1831 }
1832 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1833
1834 void kvm_get_pfn(kvm_pfn_t pfn)
1835 {
1836         if (!kvm_is_reserved_pfn(pfn))
1837                 get_page(pfn_to_page(pfn));
1838 }
1839 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1840
1841 static int next_segment(unsigned long len, int offset)
1842 {
1843         if (len > PAGE_SIZE - offset)
1844                 return PAGE_SIZE - offset;
1845         else
1846                 return len;
1847 }
1848
1849 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
1850                                  void *data, int offset, int len)
1851 {
1852         int r;
1853         unsigned long addr;
1854
1855         addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1856         if (kvm_is_error_hva(addr))
1857                 return -EFAULT;
1858         r = __copy_from_user(data, (void __user *)addr + offset, len);
1859         if (r)
1860                 return -EFAULT;
1861         return 0;
1862 }
1863
1864 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1865                         int len)
1866 {
1867         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1868
1869         return __kvm_read_guest_page(slot, gfn, data, offset, len);
1870 }
1871 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1872
1873 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
1874                              int offset, int len)
1875 {
1876         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1877
1878         return __kvm_read_guest_page(slot, gfn, data, offset, len);
1879 }
1880 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
1881
1882 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1883 {
1884         gfn_t gfn = gpa >> PAGE_SHIFT;
1885         int seg;
1886         int offset = offset_in_page(gpa);
1887         int ret;
1888
1889         while ((seg = next_segment(len, offset)) != 0) {
1890                 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1891                 if (ret < 0)
1892                         return ret;
1893                 offset = 0;
1894                 len -= seg;
1895                 data += seg;
1896                 ++gfn;
1897         }
1898         return 0;
1899 }
1900 EXPORT_SYMBOL_GPL(kvm_read_guest);
1901
1902 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
1903 {
1904         gfn_t gfn = gpa >> PAGE_SHIFT;
1905         int seg;
1906         int offset = offset_in_page(gpa);
1907         int ret;
1908
1909         while ((seg = next_segment(len, offset)) != 0) {
1910                 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
1911                 if (ret < 0)
1912                         return ret;
1913                 offset = 0;
1914                 len -= seg;
1915                 data += seg;
1916                 ++gfn;
1917         }
1918         return 0;
1919 }
1920 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
1921
1922 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1923                                    void *data, int offset, unsigned long len)
1924 {
1925         int r;
1926         unsigned long addr;
1927
1928         addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1929         if (kvm_is_error_hva(addr))
1930                 return -EFAULT;
1931         pagefault_disable();
1932         r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1933         pagefault_enable();
1934         if (r)
1935                 return -EFAULT;
1936         return 0;
1937 }
1938
1939 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1940                           unsigned long len)
1941 {
1942         gfn_t gfn = gpa >> PAGE_SHIFT;
1943         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1944         int offset = offset_in_page(gpa);
1945
1946         return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1947 }
1948 EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
1949
1950 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
1951                                void *data, unsigned long len)
1952 {
1953         gfn_t gfn = gpa >> PAGE_SHIFT;
1954         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1955         int offset = offset_in_page(gpa);
1956
1957         return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1958 }
1959 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
1960
1961 static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
1962                                   const void *data, int offset, int len)
1963 {
1964         int r;
1965         unsigned long addr;
1966
1967         addr = gfn_to_hva_memslot(memslot, gfn);
1968         if (kvm_is_error_hva(addr))
1969                 return -EFAULT;
1970         r = __copy_to_user((void __user *)addr + offset, data, len);
1971         if (r)
1972                 return -EFAULT;
1973         mark_page_dirty_in_slot(memslot, gfn);
1974         return 0;
1975 }
1976
1977 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
1978                          const void *data, int offset, int len)
1979 {
1980         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1981
1982         return __kvm_write_guest_page(slot, gfn, data, offset, len);
1983 }
1984 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1985
1986 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
1987                               const void *data, int offset, int len)
1988 {
1989         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1990
1991         return __kvm_write_guest_page(slot, gfn, data, offset, len);
1992 }
1993 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
1994
1995 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1996                     unsigned long len)
1997 {
1998         gfn_t gfn = gpa >> PAGE_SHIFT;
1999         int seg;
2000         int offset = offset_in_page(gpa);
2001         int ret;
2002
2003         while ((seg = next_segment(len, offset)) != 0) {
2004                 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2005                 if (ret < 0)
2006                         return ret;
2007                 offset = 0;
2008                 len -= seg;
2009                 data += seg;
2010                 ++gfn;
2011         }
2012         return 0;
2013 }
2014 EXPORT_SYMBOL_GPL(kvm_write_guest);
2015
2016 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2017                          unsigned long len)
2018 {
2019         gfn_t gfn = gpa >> PAGE_SHIFT;
2020         int seg;
2021         int offset = offset_in_page(gpa);
2022         int ret;
2023
2024         while ((seg = next_segment(len, offset)) != 0) {
2025                 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2026                 if (ret < 0)
2027                         return ret;
2028                 offset = 0;
2029                 len -= seg;
2030                 data += seg;
2031                 ++gfn;
2032         }
2033         return 0;
2034 }
2035 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2036
2037 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2038                               gpa_t gpa, unsigned long len)
2039 {
2040         struct kvm_memslots *slots = kvm_memslots(kvm);
2041         int offset = offset_in_page(gpa);
2042         gfn_t start_gfn = gpa >> PAGE_SHIFT;
2043         gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2044         gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2045         gfn_t nr_pages_avail;
2046
2047         ghc->gpa = gpa;
2048         ghc->generation = slots->generation;
2049         ghc->len = len;
2050         ghc->memslot = gfn_to_memslot(kvm, start_gfn);
2051         ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, NULL);
2052         if (!kvm_is_error_hva(ghc->hva) && nr_pages_needed <= 1) {
2053                 ghc->hva += offset;
2054         } else {
2055                 /*
2056                  * If the requested region crosses two memslots, we still
2057                  * verify that the entire region is valid here.
2058                  */
2059                 while (start_gfn <= end_gfn) {
2060                         ghc->memslot = gfn_to_memslot(kvm, start_gfn);
2061                         ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2062                                                    &nr_pages_avail);
2063                         if (kvm_is_error_hva(ghc->hva))
2064                                 return -EFAULT;
2065                         start_gfn += nr_pages_avail;
2066                 }
2067                 /* Use the slow path for cross page reads and writes. */
2068                 ghc->memslot = NULL;
2069         }
2070         return 0;
2071 }
2072 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2073
2074 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2075                            void *data, unsigned long len)
2076 {
2077         struct kvm_memslots *slots = kvm_memslots(kvm);
2078         int r;
2079
2080         BUG_ON(len > ghc->len);
2081
2082         if (slots->generation != ghc->generation)
2083                 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
2084
2085         if (kvm_is_error_hva(ghc->hva))
2086                 return -EFAULT;
2087
2088         if (unlikely(!ghc->memslot))
2089                 return kvm_write_guest(kvm, ghc->gpa, data, len);
2090
2091         r = __copy_to_user((void __user *)ghc->hva, data, len);
2092         if (r)
2093                 return -EFAULT;
2094         mark_page_dirty_in_slot(ghc->memslot, ghc->gpa >> PAGE_SHIFT);
2095
2096         return 0;
2097 }
2098 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2099
2100 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2101                            void *data, unsigned long len)
2102 {
2103         struct kvm_memslots *slots = kvm_memslots(kvm);
2104         int r;
2105
2106         BUG_ON(len > ghc->len);
2107
2108         if (slots->generation != ghc->generation)
2109                 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
2110
2111         if (kvm_is_error_hva(ghc->hva))
2112                 return -EFAULT;
2113
2114         if (unlikely(!ghc->memslot))
2115                 return kvm_read_guest(kvm, ghc->gpa, data, len);
2116
2117         r = __copy_from_user(data, (void __user *)ghc->hva, len);
2118         if (r)
2119                 return -EFAULT;
2120
2121         return 0;
2122 }
2123 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2124
2125 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2126 {
2127         const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2128
2129         return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2130 }
2131 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2132
2133 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2134 {
2135         gfn_t gfn = gpa >> PAGE_SHIFT;
2136         int seg;
2137         int offset = offset_in_page(gpa);
2138         int ret;
2139
2140         while ((seg = next_segment(len, offset)) != 0) {
2141                 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2142                 if (ret < 0)
2143                         return ret;
2144                 offset = 0;
2145                 len -= seg;
2146                 ++gfn;
2147         }
2148         return 0;
2149 }
2150 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2151
2152 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2153                                     gfn_t gfn)
2154 {
2155         if (memslot && memslot->dirty_bitmap) {
2156                 unsigned long rel_gfn = gfn - memslot->base_gfn;
2157
2158                 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2159         }
2160 }
2161
2162 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2163 {
2164         struct kvm_memory_slot *memslot;
2165
2166         memslot = gfn_to_memslot(kvm, gfn);
2167         mark_page_dirty_in_slot(memslot, gfn);
2168 }
2169 EXPORT_SYMBOL_GPL(mark_page_dirty);
2170
2171 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2172 {
2173         struct kvm_memory_slot *memslot;
2174
2175         memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2176         mark_page_dirty_in_slot(memslot, gfn);
2177 }
2178 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2179
2180 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2181 {
2182         unsigned int old, val, grow;
2183
2184         old = val = vcpu->halt_poll_ns;
2185         grow = READ_ONCE(halt_poll_ns_grow);
2186         /* 10us base */
2187         if (val == 0 && grow)
2188                 val = 10000;
2189         else
2190                 val *= grow;
2191
2192         if (val > halt_poll_ns)
2193                 val = halt_poll_ns;
2194
2195         vcpu->halt_poll_ns = val;
2196         trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2197 }
2198
2199 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2200 {
2201         unsigned int old, val, shrink;
2202
2203         old = val = vcpu->halt_poll_ns;
2204         shrink = READ_ONCE(halt_poll_ns_shrink);
2205         if (shrink == 0)
2206                 val = 0;
2207         else
2208                 val /= shrink;
2209
2210         vcpu->halt_poll_ns = val;
2211         trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2212 }
2213
2214 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2215 {
2216         if (kvm_arch_vcpu_runnable(vcpu)) {
2217                 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2218                 return -EINTR;
2219         }
2220         if (kvm_cpu_has_pending_timer(vcpu))
2221                 return -EINTR;
2222         if (signal_pending(current))
2223                 return -EINTR;
2224
2225         return 0;
2226 }
2227
2228 /*
2229  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2230  */
2231 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2232 {
2233         ktime_t start, cur;
2234         DECLARE_SWAITQUEUE(wait);
2235         bool waited = false;
2236         u64 block_ns;
2237
2238         start = cur = ktime_get();
2239         if (vcpu->halt_poll_ns) {
2240                 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2241
2242                 ++vcpu->stat.halt_attempted_poll;
2243                 do {
2244                         /*
2245                          * This sets KVM_REQ_UNHALT if an interrupt
2246                          * arrives.
2247                          */
2248                         if (kvm_vcpu_check_block(vcpu) < 0) {
2249                                 ++vcpu->stat.halt_successful_poll;
2250                                 if (!vcpu_valid_wakeup(vcpu))
2251                                         ++vcpu->stat.halt_poll_invalid;
2252                                 goto out;
2253                         }
2254                         cur = ktime_get();
2255                 } while (single_task_running() && ktime_before(cur, stop));
2256         }
2257
2258         kvm_arch_vcpu_blocking(vcpu);
2259
2260         for (;;) {
2261                 prepare_to_swait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2262
2263                 if (kvm_vcpu_check_block(vcpu) < 0)
2264                         break;
2265
2266                 waited = true;
2267                 schedule();
2268         }
2269
2270         finish_swait(&vcpu->wq, &wait);
2271         cur = ktime_get();
2272
2273         kvm_arch_vcpu_unblocking(vcpu);
2274 out:
2275         block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2276
2277         if (!vcpu_valid_wakeup(vcpu))
2278                 shrink_halt_poll_ns(vcpu);
2279         else if (halt_poll_ns) {
2280                 if (block_ns <= vcpu->halt_poll_ns)
2281                         ;
2282                 /* we had a long block, shrink polling */
2283                 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2284                         shrink_halt_poll_ns(vcpu);
2285                 /* we had a short halt and our poll time is too small */
2286                 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2287                         block_ns < halt_poll_ns)
2288                         grow_halt_poll_ns(vcpu);
2289         } else
2290                 vcpu->halt_poll_ns = 0;
2291
2292         trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2293         kvm_arch_vcpu_block_finish(vcpu);
2294 }
2295 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2296
2297 #ifndef CONFIG_S390
2298 void kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2299 {
2300         struct swait_queue_head *wqp;
2301
2302         wqp = kvm_arch_vcpu_wq(vcpu);
2303         if (swait_active(wqp)) {
2304                 swake_up(wqp);
2305                 ++vcpu->stat.halt_wakeup;
2306         }
2307
2308 }
2309 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2310
2311 /*
2312  * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2313  */
2314 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2315 {
2316         int me;
2317         int cpu = vcpu->cpu;
2318
2319         kvm_vcpu_wake_up(vcpu);
2320         me = get_cpu();
2321         if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2322                 if (kvm_arch_vcpu_should_kick(vcpu))
2323                         smp_send_reschedule(cpu);
2324         put_cpu();
2325 }
2326 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2327 #endif /* !CONFIG_S390 */
2328
2329 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2330 {
2331         struct pid *pid;
2332         struct task_struct *task = NULL;
2333         int ret = 0;
2334
2335         rcu_read_lock();
2336         pid = rcu_dereference(target->pid);
2337         if (pid)
2338                 task = get_pid_task(pid, PIDTYPE_PID);
2339         rcu_read_unlock();
2340         if (!task)
2341                 return ret;
2342         ret = yield_to(task, 1);
2343         put_task_struct(task);
2344
2345         return ret;
2346 }
2347 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2348
2349 /*
2350  * Helper that checks whether a VCPU is eligible for directed yield.
2351  * Most eligible candidate to yield is decided by following heuristics:
2352  *
2353  *  (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2354  *  (preempted lock holder), indicated by @in_spin_loop.
2355  *  Set at the beiginning and cleared at the end of interception/PLE handler.
2356  *
2357  *  (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2358  *  chance last time (mostly it has become eligible now since we have probably
2359  *  yielded to lockholder in last iteration. This is done by toggling
2360  *  @dy_eligible each time a VCPU checked for eligibility.)
2361  *
2362  *  Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2363  *  to preempted lock-holder could result in wrong VCPU selection and CPU
2364  *  burning. Giving priority for a potential lock-holder increases lock
2365  *  progress.
2366  *
2367  *  Since algorithm is based on heuristics, accessing another VCPU data without
2368  *  locking does not harm. It may result in trying to yield to  same VCPU, fail
2369  *  and continue with next VCPU and so on.
2370  */
2371 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2372 {
2373 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2374         bool eligible;
2375
2376         eligible = !vcpu->spin_loop.in_spin_loop ||
2377                     vcpu->spin_loop.dy_eligible;
2378
2379         if (vcpu->spin_loop.in_spin_loop)
2380                 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2381
2382         return eligible;
2383 #else
2384         return true;
2385 #endif
2386 }
2387
2388 void kvm_vcpu_on_spin(struct kvm_vcpu *me)
2389 {
2390         struct kvm *kvm = me->kvm;
2391         struct kvm_vcpu *vcpu;
2392         int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2393         int yielded = 0;
2394         int try = 3;
2395         int pass;
2396         int i;
2397
2398         kvm_vcpu_set_in_spin_loop(me, true);
2399         /*
2400          * We boost the priority of a VCPU that is runnable but not
2401          * currently running, because it got preempted by something
2402          * else and called schedule in __vcpu_run.  Hopefully that
2403          * VCPU is holding the lock that we need and will release it.
2404          * We approximate round-robin by starting at the last boosted VCPU.
2405          */
2406         for (pass = 0; pass < 2 && !yielded && try; pass++) {
2407                 kvm_for_each_vcpu(i, vcpu, kvm) {
2408                         if (!pass && i <= last_boosted_vcpu) {
2409                                 i = last_boosted_vcpu;
2410                                 continue;
2411                         } else if (pass && i > last_boosted_vcpu)
2412                                 break;
2413                         if (!ACCESS_ONCE(vcpu->preempted))
2414                                 continue;
2415                         if (vcpu == me)
2416                                 continue;
2417                         if (swait_active(&vcpu->wq) && !kvm_arch_vcpu_runnable(vcpu))
2418                                 continue;
2419                         if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2420                                 continue;
2421
2422                         yielded = kvm_vcpu_yield_to(vcpu);
2423                         if (yielded > 0) {
2424                                 kvm->last_boosted_vcpu = i;
2425                                 break;
2426                         } else if (yielded < 0) {
2427                                 try--;
2428                                 if (!try)
2429                                         break;
2430                         }
2431                 }
2432         }
2433         kvm_vcpu_set_in_spin_loop(me, false);
2434
2435         /* Ensure vcpu is not eligible during next spinloop */
2436         kvm_vcpu_set_dy_eligible(me, false);
2437 }
2438 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2439
2440 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2441 {
2442         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
2443         struct page *page;
2444
2445         if (vmf->pgoff == 0)
2446                 page = virt_to_page(vcpu->run);
2447 #ifdef CONFIG_X86
2448         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2449                 page = virt_to_page(vcpu->arch.pio_data);
2450 #endif
2451 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2452         else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2453                 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2454 #endif
2455         else
2456                 return kvm_arch_vcpu_fault(vcpu, vmf);
2457         get_page(page);
2458         vmf->page = page;
2459         return 0;
2460 }
2461
2462 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2463         .fault = kvm_vcpu_fault,
2464 };
2465
2466 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2467 {
2468         vma->vm_ops = &kvm_vcpu_vm_ops;
2469         return 0;
2470 }
2471
2472 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2473 {
2474         struct kvm_vcpu *vcpu = filp->private_data;
2475
2476         debugfs_remove_recursive(vcpu->debugfs_dentry);
2477         kvm_put_kvm(vcpu->kvm);
2478         return 0;
2479 }
2480
2481 static struct file_operations kvm_vcpu_fops = {
2482         .release        = kvm_vcpu_release,
2483         .unlocked_ioctl = kvm_vcpu_ioctl,
2484 #ifdef CONFIG_KVM_COMPAT
2485         .compat_ioctl   = kvm_vcpu_compat_ioctl,
2486 #endif
2487         .mmap           = kvm_vcpu_mmap,
2488         .llseek         = noop_llseek,
2489 };
2490
2491 /*
2492  * Allocates an inode for the vcpu.
2493  */
2494 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2495 {
2496         return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2497 }
2498
2499 static int kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2500 {
2501         char dir_name[ITOA_MAX_LEN * 2];
2502         int ret;
2503
2504         if (!kvm_arch_has_vcpu_debugfs())
2505                 return 0;
2506
2507         if (!debugfs_initialized())
2508                 return 0;
2509
2510         snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2511         vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2512                                                                 vcpu->kvm->debugfs_dentry);
2513         if (!vcpu->debugfs_dentry)
2514                 return -ENOMEM;
2515
2516         ret = kvm_arch_create_vcpu_debugfs(vcpu);
2517         if (ret < 0) {
2518                 debugfs_remove_recursive(vcpu->debugfs_dentry);
2519                 return ret;
2520         }
2521
2522         return 0;
2523 }
2524
2525 /*
2526  * Creates some virtual cpus.  Good luck creating more than one.
2527  */
2528 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
2529 {
2530         int r;
2531         struct kvm_vcpu *vcpu;
2532
2533         if (id >= KVM_MAX_VCPU_ID)
2534                 return -EINVAL;
2535
2536         mutex_lock(&kvm->lock);
2537         if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2538                 mutex_unlock(&kvm->lock);
2539                 return -EINVAL;
2540         }
2541
2542         kvm->created_vcpus++;
2543         mutex_unlock(&kvm->lock);
2544
2545         vcpu = kvm_arch_vcpu_create(kvm, id);
2546         if (IS_ERR(vcpu)) {
2547                 r = PTR_ERR(vcpu);
2548                 goto vcpu_decrement;
2549         }
2550
2551         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2552
2553         r = kvm_arch_vcpu_setup(vcpu);
2554         if (r)
2555                 goto vcpu_destroy;
2556
2557         r = kvm_create_vcpu_debugfs(vcpu);
2558         if (r)
2559                 goto vcpu_destroy;
2560
2561         mutex_lock(&kvm->lock);
2562         if (kvm_get_vcpu_by_id(kvm, id)) {
2563                 r = -EEXIST;
2564                 goto unlock_vcpu_destroy;
2565         }
2566
2567         BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2568
2569         /* Now it's all set up, let userspace reach it */
2570         kvm_get_kvm(kvm);
2571         r = create_vcpu_fd(vcpu);
2572         if (r < 0) {
2573                 kvm_put_kvm(kvm);
2574                 goto unlock_vcpu_destroy;
2575         }
2576
2577         kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2578
2579         /*
2580          * Pairs with smp_rmb() in kvm_get_vcpu.  Write kvm->vcpus
2581          * before kvm->online_vcpu's incremented value.
2582          */
2583         smp_wmb();
2584         atomic_inc(&kvm->online_vcpus);
2585
2586         mutex_unlock(&kvm->lock);
2587         kvm_arch_vcpu_postcreate(vcpu);
2588         return r;
2589
2590 unlock_vcpu_destroy:
2591         mutex_unlock(&kvm->lock);
2592         debugfs_remove_recursive(vcpu->debugfs_dentry);
2593 vcpu_destroy:
2594         kvm_arch_vcpu_destroy(vcpu);
2595 vcpu_decrement:
2596         mutex_lock(&kvm->lock);
2597         kvm->created_vcpus--;
2598         mutex_unlock(&kvm->lock);
2599         return r;
2600 }
2601
2602 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2603 {
2604         if (sigset) {
2605                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2606                 vcpu->sigset_active = 1;
2607                 vcpu->sigset = *sigset;
2608         } else
2609                 vcpu->sigset_active = 0;
2610         return 0;
2611 }
2612
2613 static long kvm_vcpu_ioctl(struct file *filp,
2614                            unsigned int ioctl, unsigned long arg)
2615 {
2616         struct kvm_vcpu *vcpu = filp->private_data;
2617         void __user *argp = (void __user *)arg;
2618         int r;
2619         struct kvm_fpu *fpu = NULL;
2620         struct kvm_sregs *kvm_sregs = NULL;
2621
2622         if (vcpu->kvm->mm != current->mm)
2623                 return -EIO;
2624
2625         if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2626                 return -EINVAL;
2627
2628 #if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS)
2629         /*
2630          * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
2631          * so vcpu_load() would break it.
2632          */
2633         if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_S390_IRQ || ioctl == KVM_INTERRUPT)
2634                 return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2635 #endif
2636
2637
2638         r = vcpu_load(vcpu);
2639         if (r)
2640                 return r;
2641         switch (ioctl) {
2642         case KVM_RUN:
2643                 r = -EINVAL;
2644                 if (arg)
2645                         goto out;
2646                 if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
2647                         /* The thread running this VCPU changed. */
2648                         struct pid *oldpid = vcpu->pid;
2649                         struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
2650
2651                         rcu_assign_pointer(vcpu->pid, newpid);
2652                         if (oldpid)
2653                                 synchronize_rcu();
2654                         put_pid(oldpid);
2655                 }
2656                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2657                 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2658                 break;
2659         case KVM_GET_REGS: {
2660                 struct kvm_regs *kvm_regs;
2661
2662                 r = -ENOMEM;
2663                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
2664                 if (!kvm_regs)
2665                         goto out;
2666                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2667                 if (r)
2668                         goto out_free1;
2669                 r = -EFAULT;
2670                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2671                         goto out_free1;
2672                 r = 0;
2673 out_free1:
2674                 kfree(kvm_regs);
2675                 break;
2676         }
2677         case KVM_SET_REGS: {
2678                 struct kvm_regs *kvm_regs;
2679
2680                 r = -ENOMEM;
2681                 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2682                 if (IS_ERR(kvm_regs)) {
2683                         r = PTR_ERR(kvm_regs);
2684                         goto out;
2685                 }
2686                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2687                 kfree(kvm_regs);
2688                 break;
2689         }
2690         case KVM_GET_SREGS: {
2691                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
2692                 r = -ENOMEM;
2693                 if (!kvm_sregs)
2694                         goto out;
2695                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
2696                 if (r)
2697                         goto out;
2698                 r = -EFAULT;
2699                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
2700                         goto out;
2701                 r = 0;
2702                 break;
2703         }
2704         case KVM_SET_SREGS: {
2705                 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2706                 if (IS_ERR(kvm_sregs)) {
2707                         r = PTR_ERR(kvm_sregs);
2708                         kvm_sregs = NULL;
2709                         goto out;
2710                 }
2711                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
2712                 break;
2713         }
2714         case KVM_GET_MP_STATE: {
2715                 struct kvm_mp_state mp_state;
2716
2717                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2718                 if (r)
2719                         goto out;
2720                 r = -EFAULT;
2721                 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
2722                         goto out;
2723                 r = 0;
2724                 break;
2725         }
2726         case KVM_SET_MP_STATE: {
2727                 struct kvm_mp_state mp_state;
2728
2729                 r = -EFAULT;
2730                 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
2731                         goto out;
2732                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
2733                 break;
2734         }
2735         case KVM_TRANSLATE: {
2736                 struct kvm_translation tr;
2737
2738                 r = -EFAULT;
2739                 if (copy_from_user(&tr, argp, sizeof(tr)))
2740                         goto out;
2741                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
2742                 if (r)
2743                         goto out;
2744                 r = -EFAULT;
2745                 if (copy_to_user(argp, &tr, sizeof(tr)))
2746                         goto out;
2747                 r = 0;
2748                 break;
2749         }
2750         case KVM_SET_GUEST_DEBUG: {
2751                 struct kvm_guest_debug dbg;
2752
2753                 r = -EFAULT;
2754                 if (copy_from_user(&dbg, argp, sizeof(dbg)))
2755                         goto out;
2756                 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2757                 break;
2758         }
2759         case KVM_SET_SIGNAL_MASK: {
2760                 struct kvm_signal_mask __user *sigmask_arg = argp;
2761                 struct kvm_signal_mask kvm_sigmask;
2762                 sigset_t sigset, *p;
2763
2764                 p = NULL;
2765                 if (argp) {
2766                         r = -EFAULT;
2767                         if (copy_from_user(&kvm_sigmask, argp,
2768                                            sizeof(kvm_sigmask)))
2769                                 goto out;
2770                         r = -EINVAL;
2771                         if (kvm_sigmask.len != sizeof(sigset))
2772                                 goto out;
2773                         r = -EFAULT;
2774                         if (copy_from_user(&sigset, sigmask_arg->sigset,
2775                                            sizeof(sigset)))
2776                                 goto out;
2777                         p = &sigset;
2778                 }
2779                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2780                 break;
2781         }
2782         case KVM_GET_FPU: {
2783                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2784                 r = -ENOMEM;
2785                 if (!fpu)
2786                         goto out;
2787                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2788                 if (r)
2789                         goto out;
2790                 r = -EFAULT;
2791                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2792                         goto out;
2793                 r = 0;
2794                 break;
2795         }
2796         case KVM_SET_FPU: {
2797                 fpu = memdup_user(argp, sizeof(*fpu));
2798                 if (IS_ERR(fpu)) {
2799                         r = PTR_ERR(fpu);
2800                         fpu = NULL;
2801                         goto out;
2802                 }
2803                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2804                 break;
2805         }
2806         default:
2807                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2808         }
2809 out:
2810         vcpu_put(vcpu);
2811         kfree(fpu);
2812         kfree(kvm_sregs);
2813         return r;
2814 }
2815
2816 #ifdef CONFIG_KVM_COMPAT
2817 static long kvm_vcpu_compat_ioctl(struct file *filp,
2818                                   unsigned int ioctl, unsigned long arg)
2819 {
2820         struct kvm_vcpu *vcpu = filp->private_data;
2821         void __user *argp = compat_ptr(arg);
2822         int r;
2823
2824         if (vcpu->kvm->mm != current->mm)
2825                 return -EIO;
2826
2827         switch (ioctl) {
2828         case KVM_SET_SIGNAL_MASK: {
2829                 struct kvm_signal_mask __user *sigmask_arg = argp;
2830                 struct kvm_signal_mask kvm_sigmask;
2831                 compat_sigset_t csigset;
2832                 sigset_t sigset;
2833
2834                 if (argp) {
2835                         r = -EFAULT;
2836                         if (copy_from_user(&kvm_sigmask, argp,
2837                                            sizeof(kvm_sigmask)))
2838                                 goto out;
2839                         r = -EINVAL;
2840                         if (kvm_sigmask.len != sizeof(csigset))
2841                                 goto out;
2842                         r = -EFAULT;
2843                         if (copy_from_user(&csigset, sigmask_arg->sigset,
2844                                            sizeof(csigset)))
2845                                 goto out;
2846                         sigset_from_compat(&sigset, &csigset);
2847                         r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2848                 } else
2849                         r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
2850                 break;
2851         }
2852         default:
2853                 r = kvm_vcpu_ioctl(filp, ioctl, arg);
2854         }
2855
2856 out:
2857         return r;
2858 }
2859 #endif
2860
2861 static int kvm_device_ioctl_attr(struct kvm_device *dev,
2862                                  int (*accessor)(struct kvm_device *dev,
2863                                                  struct kvm_device_attr *attr),
2864                                  unsigned long arg)
2865 {
2866         struct kvm_device_attr attr;
2867
2868         if (!accessor)
2869                 return -EPERM;
2870
2871         if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2872                 return -EFAULT;
2873
2874         return accessor(dev, &attr);
2875 }
2876
2877 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
2878                              unsigned long arg)
2879 {
2880         struct kvm_device *dev = filp->private_data;
2881
2882         if (dev->kvm->mm != current->mm)
2883                 return -EIO;
2884
2885         switch (ioctl) {
2886         case KVM_SET_DEVICE_ATTR:
2887                 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
2888         case KVM_GET_DEVICE_ATTR:
2889                 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
2890         case KVM_HAS_DEVICE_ATTR:
2891                 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
2892         default:
2893                 if (dev->ops->ioctl)
2894                         return dev->ops->ioctl(dev, ioctl, arg);
2895
2896                 return -ENOTTY;
2897         }
2898 }
2899
2900 static int kvm_device_release(struct inode *inode, struct file *filp)
2901 {
2902         struct kvm_device *dev = filp->private_data;
2903         struct kvm *kvm = dev->kvm;
2904
2905         kvm_put_kvm(kvm);
2906         return 0;
2907 }
2908
2909 static const struct file_operations kvm_device_fops = {
2910         .unlocked_ioctl = kvm_device_ioctl,
2911 #ifdef CONFIG_KVM_COMPAT
2912         .compat_ioctl = kvm_device_ioctl,
2913 #endif
2914         .release = kvm_device_release,
2915 };
2916
2917 struct kvm_device *kvm_device_from_filp(struct file *filp)
2918 {
2919         if (filp->f_op != &kvm_device_fops)
2920                 return NULL;
2921
2922         return filp->private_data;
2923 }
2924
2925 static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
2926 #ifdef CONFIG_KVM_MPIC
2927         [KVM_DEV_TYPE_FSL_MPIC_20]      = &kvm_mpic_ops,
2928         [KVM_DEV_TYPE_FSL_MPIC_42]      = &kvm_mpic_ops,
2929 #endif
2930
2931 #ifdef CONFIG_KVM_XICS
2932         [KVM_DEV_TYPE_XICS]             = &kvm_xics_ops,
2933 #endif
2934 };
2935
2936 int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
2937 {
2938         if (type >= ARRAY_SIZE(kvm_device_ops_table))
2939                 return -ENOSPC;
2940
2941         if (kvm_device_ops_table[type] != NULL)
2942                 return -EEXIST;
2943
2944         kvm_device_ops_table[type] = ops;
2945         return 0;
2946 }
2947
2948 void kvm_unregister_device_ops(u32 type)
2949 {
2950         if (kvm_device_ops_table[type] != NULL)
2951                 kvm_device_ops_table[type] = NULL;
2952 }
2953
2954 static int kvm_ioctl_create_device(struct kvm *kvm,
2955                                    struct kvm_create_device *cd)
2956 {
2957         struct kvm_device_ops *ops = NULL;
2958         struct kvm_device *dev;
2959         bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
2960         int ret;
2961
2962         if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
2963                 return -ENODEV;
2964
2965         ops = kvm_device_ops_table[cd->type];
2966         if (ops == NULL)
2967                 return -ENODEV;
2968
2969         if (test)
2970                 return 0;
2971
2972         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2973         if (!dev)
2974                 return -ENOMEM;
2975
2976         dev->ops = ops;
2977         dev->kvm = kvm;
2978
2979         mutex_lock(&kvm->lock);
2980         ret = ops->create(dev, cd->type);
2981         if (ret < 0) {
2982                 mutex_unlock(&kvm->lock);
2983                 kfree(dev);
2984                 return ret;
2985         }
2986         list_add(&dev->vm_node, &kvm->devices);
2987         mutex_unlock(&kvm->lock);
2988
2989         if (ops->init)
2990                 ops->init(dev);
2991
2992         kvm_get_kvm(kvm);
2993         ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
2994         if (ret < 0) {
2995                 kvm_put_kvm(kvm);
2996                 mutex_lock(&kvm->lock);
2997                 list_del(&dev->vm_node);
2998                 mutex_unlock(&kvm->lock);
2999                 ops->destroy(dev);
3000                 return ret;
3001         }
3002
3003         cd->fd = ret;
3004         return 0;
3005 }
3006
3007 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3008 {
3009         switch (arg) {
3010         case KVM_CAP_USER_MEMORY:
3011         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3012         case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3013         case KVM_CAP_INTERNAL_ERROR_DATA:
3014 #ifdef CONFIG_HAVE_KVM_MSI
3015         case KVM_CAP_SIGNAL_MSI:
3016 #endif
3017 #ifdef CONFIG_HAVE_KVM_IRQFD
3018         case KVM_CAP_IRQFD:
3019         case KVM_CAP_IRQFD_RESAMPLE:
3020 #endif
3021         case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3022         case KVM_CAP_CHECK_EXTENSION_VM:
3023                 return 1;
3024 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3025         case KVM_CAP_IRQ_ROUTING:
3026                 return KVM_MAX_IRQ_ROUTES;
3027 #endif
3028 #if KVM_ADDRESS_SPACE_NUM > 1
3029         case KVM_CAP_MULTI_ADDRESS_SPACE:
3030                 return KVM_ADDRESS_SPACE_NUM;
3031 #endif
3032         case KVM_CAP_MAX_VCPU_ID:
3033                 return KVM_MAX_VCPU_ID;
3034         default:
3035                 break;
3036         }
3037         return kvm_vm_ioctl_check_extension(kvm, arg);
3038 }
3039
3040 static long kvm_vm_ioctl(struct file *filp,
3041                            unsigned int ioctl, unsigned long arg)
3042 {
3043         struct kvm *kvm = filp->private_data;
3044         void __user *argp = (void __user *)arg;
3045         int r;
3046
3047         if (kvm->mm != current->mm)
3048                 return -EIO;
3049         switch (ioctl) {
3050         case KVM_CREATE_VCPU:
3051                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3052                 break;
3053         case KVM_SET_USER_MEMORY_REGION: {
3054                 struct kvm_userspace_memory_region kvm_userspace_mem;
3055
3056                 r = -EFAULT;
3057                 if (copy_from_user(&kvm_userspace_mem, argp,
3058                                                 sizeof(kvm_userspace_mem)))
3059                         goto out;
3060
3061                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3062                 break;
3063         }
3064         case KVM_GET_DIRTY_LOG: {
3065                 struct kvm_dirty_log log;
3066
3067                 r = -EFAULT;
3068                 if (copy_from_user(&log, argp, sizeof(log)))
3069                         goto out;
3070                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3071                 break;
3072         }
3073 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3074         case KVM_REGISTER_COALESCED_MMIO: {
3075                 struct kvm_coalesced_mmio_zone zone;
3076
3077                 r = -EFAULT;
3078                 if (copy_from_user(&zone, argp, sizeof(zone)))
3079                         goto out;
3080                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3081                 break;
3082         }
3083         case KVM_UNREGISTER_COALESCED_MMIO: {
3084                 struct kvm_coalesced_mmio_zone zone;
3085
3086                 r = -EFAULT;
3087                 if (copy_from_user(&zone, argp, sizeof(zone)))
3088                         goto out;
3089                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3090                 break;
3091         }
3092 #endif
3093         case KVM_IRQFD: {
3094                 struct kvm_irqfd data;
3095
3096                 r = -EFAULT;
3097                 if (copy_from_user(&data, argp, sizeof(data)))
3098                         goto out;
3099                 r = kvm_irqfd(kvm, &data);
3100                 break;
3101         }
3102         case KVM_IOEVENTFD: {
3103                 struct kvm_ioeventfd data;
3104
3105                 r = -EFAULT;
3106                 if (copy_from_user(&data, argp, sizeof(data)))
3107                         goto out;
3108                 r = kvm_ioeventfd(kvm, &data);
3109                 break;
3110         }
3111 #ifdef CONFIG_HAVE_KVM_MSI
3112         case KVM_SIGNAL_MSI: {
3113                 struct kvm_msi msi;
3114
3115                 r = -EFAULT;
3116                 if (copy_from_user(&msi, argp, sizeof(msi)))
3117                         goto out;
3118                 r = kvm_send_userspace_msi(kvm, &msi);
3119                 break;
3120         }
3121 #endif
3122 #ifdef __KVM_HAVE_IRQ_LINE
3123         case KVM_IRQ_LINE_STATUS:
3124         case KVM_IRQ_LINE: {
3125                 struct kvm_irq_level irq_event;
3126
3127                 r = -EFAULT;
3128                 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3129                         goto out;
3130
3131                 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3132                                         ioctl == KVM_IRQ_LINE_STATUS);
3133                 if (r)
3134                         goto out;
3135
3136                 r = -EFAULT;
3137                 if (ioctl == KVM_IRQ_LINE_STATUS) {
3138                         if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3139                                 goto out;
3140                 }
3141
3142                 r = 0;
3143                 break;
3144         }
3145 #endif
3146 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3147         case KVM_SET_GSI_ROUTING: {
3148                 struct kvm_irq_routing routing;
3149                 struct kvm_irq_routing __user *urouting;
3150                 struct kvm_irq_routing_entry *entries = NULL;
3151
3152                 r = -EFAULT;
3153                 if (copy_from_user(&routing, argp, sizeof(routing)))
3154                         goto out;
3155                 r = -EINVAL;
3156                 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3157                         goto out;
3158                 if (routing.flags)
3159                         goto out;
3160                 if (routing.nr) {
3161                         r = -ENOMEM;
3162                         entries = vmalloc(routing.nr * sizeof(*entries));
3163                         if (!entries)
3164                                 goto out;
3165                         r = -EFAULT;
3166                         urouting = argp;
3167                         if (copy_from_user(entries, urouting->entries,
3168                                            routing.nr * sizeof(*entries)))
3169                                 goto out_free_irq_routing;
3170                 }
3171                 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3172                                         routing.flags);
3173 out_free_irq_routing:
3174                 vfree(entries);
3175                 break;
3176         }
3177 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3178         case KVM_CREATE_DEVICE: {
3179                 struct kvm_create_device cd;
3180
3181                 r = -EFAULT;
3182                 if (copy_from_user(&cd, argp, sizeof(cd)))
3183                         goto out;
3184
3185                 r = kvm_ioctl_create_device(kvm, &cd);
3186                 if (r)
3187                         goto out;
3188
3189                 r = -EFAULT;
3190                 if (copy_to_user(argp, &cd, sizeof(cd)))
3191                         goto out;
3192
3193                 r = 0;
3194                 break;
3195         }
3196         case KVM_CHECK_EXTENSION:
3197                 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3198                 break;
3199         default:
3200                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3201         }
3202 out:
3203         return r;
3204 }
3205
3206 #ifdef CONFIG_KVM_COMPAT
3207 struct compat_kvm_dirty_log {
3208         __u32 slot;
3209         __u32 padding1;
3210         union {
3211                 compat_uptr_t dirty_bitmap; /* one bit per page */
3212                 __u64 padding2;
3213         };
3214 };
3215
3216 static long kvm_vm_compat_ioctl(struct file *filp,
3217                            unsigned int ioctl, unsigned long arg)
3218 {
3219         struct kvm *kvm = filp->private_data;
3220         int r;
3221
3222         if (kvm->mm != current->mm)
3223                 return -EIO;
3224         switch (ioctl) {
3225         case KVM_GET_DIRTY_LOG: {
3226                 struct compat_kvm_dirty_log compat_log;
3227                 struct kvm_dirty_log log;
3228
3229                 r = -EFAULT;
3230                 if (copy_from_user(&compat_log, (void __user *)arg,
3231                                    sizeof(compat_log)))
3232                         goto out;
3233                 log.slot         = compat_log.slot;
3234                 log.padding1     = compat_log.padding1;
3235                 log.padding2     = compat_log.padding2;
3236                 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3237
3238                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3239                 break;
3240         }
3241         default:
3242                 r = kvm_vm_ioctl(filp, ioctl, arg);
3243         }
3244
3245 out:
3246         return r;
3247 }
3248 #endif
3249
3250 static struct file_operations kvm_vm_fops = {
3251         .release        = kvm_vm_release,
3252         .unlocked_ioctl = kvm_vm_ioctl,
3253 #ifdef CONFIG_KVM_COMPAT
3254         .compat_ioctl   = kvm_vm_compat_ioctl,
3255 #endif
3256         .llseek         = noop_llseek,
3257 };
3258
3259 static int kvm_dev_ioctl_create_vm(unsigned long type)
3260 {
3261         int r;
3262         struct kvm *kvm;
3263         struct file *file;
3264
3265         kvm = kvm_create_vm(type);
3266         if (IS_ERR(kvm))
3267                 return PTR_ERR(kvm);
3268 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3269         r = kvm_coalesced_mmio_init(kvm);
3270         if (r < 0) {
3271                 kvm_put_kvm(kvm);
3272                 return r;
3273         }
3274 #endif
3275         r = get_unused_fd_flags(O_CLOEXEC);
3276         if (r < 0) {
3277                 kvm_put_kvm(kvm);
3278                 return r;
3279         }
3280         file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3281         if (IS_ERR(file)) {
3282                 put_unused_fd(r);
3283                 kvm_put_kvm(kvm);
3284                 return PTR_ERR(file);
3285         }
3286
3287         if (kvm_create_vm_debugfs(kvm, r) < 0) {
3288                 put_unused_fd(r);
3289                 fput(file);
3290                 return -ENOMEM;
3291         }
3292
3293         fd_install(r, file);
3294         return r;
3295 }
3296
3297 static long kvm_dev_ioctl(struct file *filp,
3298                           unsigned int ioctl, unsigned long arg)
3299 {
3300         long r = -EINVAL;
3301
3302         switch (ioctl) {
3303         case KVM_GET_API_VERSION:
3304                 if (arg)
3305                         goto out;
3306                 r = KVM_API_VERSION;
3307                 break;
3308         case KVM_CREATE_VM:
3309                 r = kvm_dev_ioctl_create_vm(arg);
3310                 break;
3311         case KVM_CHECK_EXTENSION:
3312                 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3313                 break;
3314         case KVM_GET_VCPU_MMAP_SIZE:
3315                 if (arg)
3316                         goto out;
3317                 r = PAGE_SIZE;     /* struct kvm_run */
3318 #ifdef CONFIG_X86
3319                 r += PAGE_SIZE;    /* pio data page */
3320 #endif
3321 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3322                 r += PAGE_SIZE;    /* coalesced mmio ring page */
3323 #endif
3324                 break;
3325         case KVM_TRACE_ENABLE:
3326         case KVM_TRACE_PAUSE:
3327         case KVM_TRACE_DISABLE:
3328                 r = -EOPNOTSUPP;
3329                 break;
3330         default:
3331                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3332         }
3333 out:
3334         return r;
3335 }
3336
3337 static struct file_operations kvm_chardev_ops = {
3338         .unlocked_ioctl = kvm_dev_ioctl,
3339         .compat_ioctl   = kvm_dev_ioctl,
3340         .llseek         = noop_llseek,
3341 };
3342
3343 static struct miscdevice kvm_dev = {
3344         KVM_MINOR,
3345         "kvm",
3346         &kvm_chardev_ops,
3347 };
3348
3349 static void hardware_enable_nolock(void *junk)
3350 {
3351         int cpu = raw_smp_processor_id();
3352         int r;
3353
3354         if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3355                 return;
3356
3357         cpumask_set_cpu(cpu, cpus_hardware_enabled);
3358
3359         r = kvm_arch_hardware_enable();
3360
3361         if (r) {
3362                 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3363                 atomic_inc(&hardware_enable_failed);
3364                 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3365         }
3366 }
3367
3368 static int kvm_starting_cpu(unsigned int cpu)
3369 {
3370         raw_spin_lock(&kvm_count_lock);
3371         if (kvm_usage_count)
3372                 hardware_enable_nolock(NULL);
3373         raw_spin_unlock(&kvm_count_lock);
3374         return 0;
3375 }
3376
3377 static void hardware_disable_nolock(void *junk)
3378 {
3379         int cpu = raw_smp_processor_id();
3380
3381         if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3382                 return;
3383         cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3384         kvm_arch_hardware_disable();
3385 }
3386
3387 static int kvm_dying_cpu(unsigned int cpu)
3388 {
3389         raw_spin_lock(&kvm_count_lock);
3390         if (kvm_usage_count)
3391                 hardware_disable_nolock(NULL);
3392         raw_spin_unlock(&kvm_count_lock);
3393         return 0;
3394 }
3395
3396 static void hardware_disable_all_nolock(void)
3397 {
3398         BUG_ON(!kvm_usage_count);
3399
3400         kvm_usage_count--;
3401         if (!kvm_usage_count)
3402                 on_each_cpu(hardware_disable_nolock, NULL, 1);
3403 }
3404
3405 static void hardware_disable_all(void)
3406 {
3407         raw_spin_lock(&kvm_count_lock);
3408         hardware_disable_all_nolock();
3409         raw_spin_unlock(&kvm_count_lock);
3410 }
3411
3412 static int hardware_enable_all(void)
3413 {
3414         int r = 0;
3415
3416         raw_spin_lock(&kvm_count_lock);
3417
3418         kvm_usage_count++;
3419         if (kvm_usage_count == 1) {
3420                 atomic_set(&hardware_enable_failed, 0);
3421                 on_each_cpu(hardware_enable_nolock, NULL, 1);
3422
3423                 if (atomic_read(&hardware_enable_failed)) {
3424                         hardware_disable_all_nolock();
3425                         r = -EBUSY;
3426                 }
3427         }
3428
3429         raw_spin_unlock(&kvm_count_lock);
3430
3431         return r;
3432 }
3433
3434 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3435                       void *v)
3436 {
3437         /*
3438          * Some (well, at least mine) BIOSes hang on reboot if
3439          * in vmx root mode.
3440          *
3441          * And Intel TXT required VMX off for all cpu when system shutdown.
3442          */
3443         pr_info("kvm: exiting hardware virtualization\n");
3444         kvm_rebooting = true;
3445         on_each_cpu(hardware_disable_nolock, NULL, 1);
3446         return NOTIFY_OK;
3447 }
3448
3449 static struct notifier_block kvm_reboot_notifier = {
3450         .notifier_call = kvm_reboot,
3451         .priority = 0,
3452 };
3453
3454 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3455 {
3456         int i;
3457
3458         for (i = 0; i < bus->dev_count; i++) {
3459                 struct kvm_io_device *pos = bus->range[i].dev;
3460
3461                 kvm_iodevice_destructor(pos);
3462         }
3463         kfree(bus);
3464 }
3465
3466 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3467                                  const struct kvm_io_range *r2)
3468 {
3469         gpa_t addr1 = r1->addr;
3470         gpa_t addr2 = r2->addr;
3471
3472         if (addr1 < addr2)
3473                 return -1;
3474
3475         /* If r2->len == 0, match the exact address.  If r2->len != 0,
3476          * accept any overlapping write.  Any order is acceptable for
3477          * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3478          * we process all of them.
3479          */
3480         if (r2->len) {
3481                 addr1 += r1->len;
3482                 addr2 += r2->len;
3483         }
3484
3485         if (addr1 > addr2)
3486                 return 1;
3487
3488         return 0;
3489 }
3490
3491 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3492 {
3493         return kvm_io_bus_cmp(p1, p2);
3494 }
3495
3496 static int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
3497                           gpa_t addr, int len)
3498 {
3499         bus->range[bus->dev_count++] = (struct kvm_io_range) {
3500                 .addr = addr,
3501                 .len = len,
3502                 .dev = dev,
3503         };
3504
3505         sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
3506                 kvm_io_bus_sort_cmp, NULL);
3507
3508         return 0;
3509 }
3510
3511 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3512                              gpa_t addr, int len)
3513 {
3514         struct kvm_io_range *range, key;
3515         int off;
3516
3517         key = (struct kvm_io_range) {
3518                 .addr = addr,
3519                 .len = len,
3520         };
3521
3522         range = bsearch(&key, bus->range, bus->dev_count,
3523                         sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3524         if (range == NULL)
3525                 return -ENOENT;
3526
3527         off = range - bus->range;
3528
3529         while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3530                 off--;
3531
3532         return off;
3533 }
3534
3535 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3536                               struct kvm_io_range *range, const void *val)
3537 {
3538         int idx;
3539
3540         idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3541         if (idx < 0)
3542                 return -EOPNOTSUPP;
3543
3544         while (idx < bus->dev_count &&
3545                 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3546                 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
3547                                         range->len, val))
3548                         return idx;
3549                 idx++;
3550         }
3551
3552         return -EOPNOTSUPP;
3553 }
3554
3555 /* kvm_io_bus_write - called under kvm->slots_lock */
3556 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3557                      int len, const void *val)
3558 {
3559         struct kvm_io_bus *bus;
3560         struct kvm_io_range range;
3561         int r;
3562
3563         range = (struct kvm_io_range) {
3564                 .addr = addr,
3565                 .len = len,
3566         };
3567
3568         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3569         if (!bus)
3570                 return -ENOMEM;
3571         r = __kvm_io_bus_write(vcpu, bus, &range, val);
3572         return r < 0 ? r : 0;
3573 }
3574
3575 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3576 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3577                             gpa_t addr, int len, const void *val, long cookie)
3578 {
3579         struct kvm_io_bus *bus;
3580         struct kvm_io_range range;
3581
3582         range = (struct kvm_io_range) {
3583                 .addr = addr,
3584                 .len = len,
3585         };
3586
3587         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3588         if (!bus)
3589                 return -ENOMEM;
3590
3591         /* First try the device referenced by cookie. */
3592         if ((cookie >= 0) && (cookie < bus->dev_count) &&
3593             (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3594                 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
3595                                         val))
3596                         return cookie;
3597
3598         /*
3599          * cookie contained garbage; fall back to search and return the
3600          * correct cookie value.
3601          */
3602         return __kvm_io_bus_write(vcpu, bus, &range, val);
3603 }
3604
3605 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3606                              struct kvm_io_range *range, void *val)
3607 {
3608         int idx;
3609
3610         idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3611         if (idx < 0)
3612                 return -EOPNOTSUPP;
3613
3614         while (idx < bus->dev_count &&
3615                 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3616                 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
3617                                        range->len, val))
3618                         return idx;
3619                 idx++;
3620         }
3621
3622         return -EOPNOTSUPP;
3623 }
3624 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
3625
3626 /* kvm_io_bus_read - called under kvm->slots_lock */
3627 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3628                     int len, void *val)
3629 {
3630         struct kvm_io_bus *bus;
3631         struct kvm_io_range range;
3632         int r;
3633
3634         range = (struct kvm_io_range) {
3635                 .addr = addr,
3636                 .len = len,
3637         };
3638
3639         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3640         if (!bus)
3641                 return -ENOMEM;
3642         r = __kvm_io_bus_read(vcpu, bus, &range, val);
3643         return r < 0 ? r : 0;
3644 }
3645
3646
3647 /* Caller must hold slots_lock. */
3648 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3649                             int len, struct kvm_io_device *dev)
3650 {
3651         struct kvm_io_bus *new_bus, *bus;
3652
3653         bus = kvm->buses[bus_idx];
3654         if (!bus)
3655                 return -ENOMEM;
3656
3657         /* exclude ioeventfd which is limited by maximum fd */
3658         if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
3659                 return -ENOSPC;
3660
3661         new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
3662                           sizeof(struct kvm_io_range)), GFP_KERNEL);
3663         if (!new_bus)
3664                 return -ENOMEM;
3665         memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
3666                sizeof(struct kvm_io_range)));
3667         kvm_io_bus_insert_dev(new_bus, dev, addr, len);
3668         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3669         synchronize_srcu_expedited(&kvm->srcu);
3670         kfree(bus);
3671
3672         return 0;
3673 }
3674
3675 /* Caller must hold slots_lock. */
3676 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3677                                struct kvm_io_device *dev)
3678 {
3679         int i, j;
3680         struct kvm_io_bus *new_bus, *bus;
3681
3682         bus = kvm->buses[bus_idx];
3683         if (!bus)
3684                 return;
3685
3686         for (i = 0; i < bus->dev_count; i++)
3687                 if (bus->range[i].dev == dev) {
3688                         break;
3689                 }
3690
3691         if (i == bus->dev_count)
3692                 return;
3693
3694         new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
3695                           sizeof(struct kvm_io_range)), GFP_KERNEL);
3696         if (new_bus) {
3697                 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3698                 new_bus->dev_count--;
3699                 memcpy(new_bus->range + i, bus->range + i + 1,
3700                        (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
3701         } else {
3702                 pr_err("kvm: failed to shrink bus, removing it completely\n");
3703                 for (j = 0; j < bus->dev_count; j++) {
3704                         if (j == i)
3705                                 continue;
3706                         kvm_iodevice_destructor(bus->range[j].dev);
3707                 }
3708         }
3709
3710         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3711         synchronize_srcu_expedited(&kvm->srcu);
3712         kfree(bus);
3713         return;
3714 }
3715
3716 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3717                                          gpa_t addr)
3718 {
3719         struct kvm_io_bus *bus;
3720         int dev_idx, srcu_idx;
3721         struct kvm_io_device *iodev = NULL;
3722
3723         srcu_idx = srcu_read_lock(&kvm->srcu);
3724
3725         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3726         if (!bus)
3727                 goto out_unlock;
3728
3729         dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
3730         if (dev_idx < 0)
3731                 goto out_unlock;
3732
3733         iodev = bus->range[dev_idx].dev;
3734
3735 out_unlock:
3736         srcu_read_unlock(&kvm->srcu, srcu_idx);
3737
3738         return iodev;
3739 }
3740 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
3741
3742 static int kvm_debugfs_open(struct inode *inode, struct file *file,
3743                            int (*get)(void *, u64 *), int (*set)(void *, u64),
3744                            const char *fmt)
3745 {
3746         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3747                                           inode->i_private;
3748
3749         /* The debugfs files are a reference to the kvm struct which
3750          * is still valid when kvm_destroy_vm is called.
3751          * To avoid the race between open and the removal of the debugfs
3752          * directory we test against the users count.
3753          */
3754         if (!atomic_add_unless(&stat_data->kvm->users_count, 1, 0))
3755                 return -ENOENT;
3756
3757         if (simple_attr_open(inode, file, get, set, fmt)) {
3758                 kvm_put_kvm(stat_data->kvm);
3759                 return -ENOMEM;
3760         }
3761
3762         return 0;
3763 }
3764
3765 static int kvm_debugfs_release(struct inode *inode, struct file *file)
3766 {
3767         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3768                                           inode->i_private;
3769
3770         simple_attr_release(inode, file);
3771         kvm_put_kvm(stat_data->kvm);
3772
3773         return 0;
3774 }
3775
3776 static int vm_stat_get_per_vm(void *data, u64 *val)
3777 {
3778         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3779
3780         *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
3781
3782         return 0;
3783 }
3784
3785 static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
3786 {
3787         __simple_attr_check_format("%llu\n", 0ull);
3788         return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
3789                                 NULL, "%llu\n");
3790 }
3791
3792 static const struct file_operations vm_stat_get_per_vm_fops = {
3793         .owner   = THIS_MODULE,
3794         .open    = vm_stat_get_per_vm_open,
3795         .release = kvm_debugfs_release,
3796         .read    = simple_attr_read,
3797         .write   = simple_attr_write,
3798         .llseek  = generic_file_llseek,
3799 };
3800
3801 static int vcpu_stat_get_per_vm(void *data, u64 *val)
3802 {
3803         int i;
3804         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3805         struct kvm_vcpu *vcpu;
3806
3807         *val = 0;
3808
3809         kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3810                 *val += *(u64 *)((void *)vcpu + stat_data->offset);
3811
3812         return 0;
3813 }
3814
3815 static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
3816 {
3817         __simple_attr_check_format("%llu\n", 0ull);
3818         return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
3819                                  NULL, "%llu\n");
3820 }
3821
3822 static const struct file_operations vcpu_stat_get_per_vm_fops = {
3823         .owner   = THIS_MODULE,
3824         .open    = vcpu_stat_get_per_vm_open,
3825         .release = kvm_debugfs_release,
3826         .read    = simple_attr_read,
3827         .write   = simple_attr_write,
3828         .llseek  = generic_file_llseek,
3829 };
3830
3831 static const struct file_operations *stat_fops_per_vm[] = {
3832         [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
3833         [KVM_STAT_VM]   = &vm_stat_get_per_vm_fops,
3834 };
3835
3836 static int vm_stat_get(void *_offset, u64 *val)
3837 {
3838         unsigned offset = (long)_offset;
3839         struct kvm *kvm;
3840         struct kvm_stat_data stat_tmp = {.offset = offset};
3841         u64 tmp_val;
3842
3843         *val = 0;
3844         mutex_lock(&kvm_lock);
3845         list_for_each_entry(kvm, &vm_list, vm_list) {
3846                 stat_tmp.kvm = kvm;
3847                 vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3848                 *val += tmp_val;
3849         }
3850         mutex_unlock(&kvm_lock);
3851         return 0;
3852 }
3853
3854 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
3855
3856 static int vcpu_stat_get(void *_offset, u64 *val)
3857 {
3858         unsigned offset = (long)_offset;
3859         struct kvm *kvm;
3860         struct kvm_stat_data stat_tmp = {.offset = offset};
3861         u64 tmp_val;
3862
3863         *val = 0;
3864         mutex_lock(&kvm_lock);
3865         list_for_each_entry(kvm, &vm_list, vm_list) {
3866                 stat_tmp.kvm = kvm;
3867                 vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3868                 *val += tmp_val;
3869         }
3870         mutex_unlock(&kvm_lock);
3871         return 0;
3872 }
3873
3874 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
3875
3876 static const struct file_operations *stat_fops[] = {
3877         [KVM_STAT_VCPU] = &vcpu_stat_fops,
3878         [KVM_STAT_VM]   = &vm_stat_fops,
3879 };
3880
3881 static int kvm_init_debug(void)
3882 {
3883         int r = -EEXIST;
3884         struct kvm_stats_debugfs_item *p;
3885
3886         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
3887         if (kvm_debugfs_dir == NULL)
3888                 goto out;
3889
3890         kvm_debugfs_num_entries = 0;
3891         for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
3892                 if (!debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
3893                                          (void *)(long)p->offset,
3894                                          stat_fops[p->kind]))
3895                         goto out_dir;
3896         }
3897
3898         return 0;
3899
3900 out_dir:
3901         debugfs_remove_recursive(kvm_debugfs_dir);
3902 out:
3903         return r;
3904 }
3905
3906 static int kvm_suspend(void)
3907 {
3908         if (kvm_usage_count)
3909                 hardware_disable_nolock(NULL);
3910         return 0;
3911 }
3912
3913 static void kvm_resume(void)
3914 {
3915         if (kvm_usage_count) {
3916                 WARN_ON(raw_spin_is_locked(&kvm_count_lock));
3917                 hardware_enable_nolock(NULL);
3918         }
3919 }
3920
3921 static struct syscore_ops kvm_syscore_ops = {
3922         .suspend = kvm_suspend,
3923         .resume = kvm_resume,
3924 };
3925
3926 static inline
3927 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
3928 {
3929         return container_of(pn, struct kvm_vcpu, preempt_notifier);
3930 }
3931
3932 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
3933 {
3934         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3935
3936         if (vcpu->preempted)
3937                 vcpu->preempted = false;
3938
3939         kvm_arch_sched_in(vcpu, cpu);
3940
3941         kvm_arch_vcpu_load(vcpu, cpu);
3942 }
3943
3944 static void kvm_sched_out(struct preempt_notifier *pn,
3945                           struct task_struct *next)
3946 {
3947         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3948
3949         if (current->state == TASK_RUNNING)
3950                 vcpu->preempted = true;
3951         kvm_arch_vcpu_put(vcpu);
3952 }
3953
3954 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
3955                   struct module *module)
3956 {
3957         int r;
3958         int cpu;
3959
3960         r = kvm_arch_init(opaque);
3961         if (r)
3962                 goto out_fail;
3963
3964         /*
3965          * kvm_arch_init makes sure there's at most one caller
3966          * for architectures that support multiple implementations,
3967          * like intel and amd on x86.
3968          * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
3969          * conflicts in case kvm is already setup for another implementation.
3970          */
3971         r = kvm_irqfd_init();
3972         if (r)
3973                 goto out_irqfd;
3974
3975         if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
3976                 r = -ENOMEM;
3977                 goto out_free_0;
3978         }
3979
3980         r = kvm_arch_hardware_setup();
3981         if (r < 0)
3982                 goto out_free_0a;
3983
3984         for_each_online_cpu(cpu) {
3985                 smp_call_function_single(cpu,
3986                                 kvm_arch_check_processor_compat,
3987                                 &r, 1);
3988                 if (r < 0)
3989                         goto out_free_1;
3990         }
3991
3992         r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "AP_KVM_STARTING",
3993                                       kvm_starting_cpu, kvm_dying_cpu);
3994         if (r)
3995                 goto out_free_2;
3996         register_reboot_notifier(&kvm_reboot_notifier);
3997
3998         /* A kmem cache lets us meet the alignment requirements of fx_save. */
3999         if (!vcpu_align)
4000                 vcpu_align = __alignof__(struct kvm_vcpu);
4001         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
4002                                            SLAB_ACCOUNT, NULL);
4003         if (!kvm_vcpu_cache) {
4004                 r = -ENOMEM;
4005                 goto out_free_3;
4006         }
4007
4008         r = kvm_async_pf_init();
4009         if (r)
4010                 goto out_free;
4011
4012         kvm_chardev_ops.owner = module;
4013         kvm_vm_fops.owner = module;
4014         kvm_vcpu_fops.owner = module;
4015
4016         r = misc_register(&kvm_dev);
4017         if (r) {
4018                 pr_err("kvm: misc device register failed\n");
4019                 goto out_unreg;
4020         }
4021
4022         register_syscore_ops(&kvm_syscore_ops);
4023
4024         kvm_preempt_ops.sched_in = kvm_sched_in;
4025         kvm_preempt_ops.sched_out = kvm_sched_out;
4026
4027         r = kvm_init_debug();
4028         if (r) {
4029                 pr_err("kvm: create debugfs files failed\n");
4030                 goto out_undebugfs;
4031         }
4032
4033         r = kvm_vfio_ops_init();
4034         WARN_ON(r);
4035
4036         return 0;
4037
4038 out_undebugfs:
4039         unregister_syscore_ops(&kvm_syscore_ops);
4040         misc_deregister(&kvm_dev);
4041 out_unreg:
4042         kvm_async_pf_deinit();
4043 out_free:
4044         kmem_cache_destroy(kvm_vcpu_cache);
4045 out_free_3:
4046         unregister_reboot_notifier(&kvm_reboot_notifier);
4047         cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4048 out_free_2:
4049 out_free_1:
4050         kvm_arch_hardware_unsetup();
4051 out_free_0a:
4052         free_cpumask_var(cpus_hardware_enabled);
4053 out_free_0:
4054         kvm_irqfd_exit();
4055 out_irqfd:
4056         kvm_arch_exit();
4057 out_fail:
4058         return r;
4059 }
4060 EXPORT_SYMBOL_GPL(kvm_init);
4061
4062 void kvm_exit(void)
4063 {
4064         debugfs_remove_recursive(kvm_debugfs_dir);
4065         misc_deregister(&kvm_dev);
4066         kmem_cache_destroy(kvm_vcpu_cache);
4067         kvm_async_pf_deinit();
4068         unregister_syscore_ops(&kvm_syscore_ops);
4069         unregister_reboot_notifier(&kvm_reboot_notifier);
4070         cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4071         on_each_cpu(hardware_disable_nolock, NULL, 1);
4072         kvm_arch_hardware_unsetup();
4073         kvm_arch_exit();
4074         kvm_irqfd_exit();
4075         free_cpumask_var(cpus_hardware_enabled);
4076         kvm_vfio_ops_exit();
4077 }
4078 EXPORT_SYMBOL_GPL(kvm_exit);
4079
4080 struct kvm_vm_worker_thread_context {
4081         struct kvm *kvm;
4082         struct task_struct *parent;
4083         struct completion init_done;
4084         kvm_vm_thread_fn_t thread_fn;
4085         uintptr_t data;
4086         int err;
4087 };
4088
4089 static int kvm_vm_worker_thread(void *context)
4090 {
4091         /*
4092          * The init_context is allocated on the stack of the parent thread, so
4093          * we have to locally copy anything that is needed beyond initialization
4094          */
4095         struct kvm_vm_worker_thread_context *init_context = context;
4096         struct kvm *kvm = init_context->kvm;
4097         kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4098         uintptr_t data = init_context->data;
4099         int err;
4100
4101         err = kthread_park(current);
4102         /* kthread_park(current) is never supposed to return an error */
4103         WARN_ON(err != 0);
4104         if (err)
4105                 goto init_complete;
4106
4107         err = cgroup_attach_task_all(init_context->parent, current);
4108         if (err) {
4109                 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4110                         __func__, err);
4111                 goto init_complete;
4112         }
4113
4114         set_user_nice(current, task_nice(init_context->parent));
4115
4116 init_complete:
4117         init_context->err = err;
4118         complete(&init_context->init_done);
4119         init_context = NULL;
4120
4121         if (err)
4122                 return err;
4123
4124         /* Wait to be woken up by the spawner before proceeding. */
4125         kthread_parkme();
4126
4127         if (!kthread_should_stop())
4128                 err = thread_fn(kvm, data);
4129
4130         return err;
4131 }
4132
4133 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4134                                 uintptr_t data, const char *name,
4135                                 struct task_struct **thread_ptr)
4136 {
4137         struct kvm_vm_worker_thread_context init_context = {};
4138         struct task_struct *thread;
4139
4140         *thread_ptr = NULL;
4141         init_context.kvm = kvm;
4142         init_context.parent = current;
4143         init_context.thread_fn = thread_fn;
4144         init_context.data = data;
4145         init_completion(&init_context.init_done);
4146
4147         thread = kthread_run(kvm_vm_worker_thread, &init_context,
4148                              "%s-%d", name, task_pid_nr(current));
4149         if (IS_ERR(thread))
4150                 return PTR_ERR(thread);
4151
4152         /* kthread_run is never supposed to return NULL */
4153         WARN_ON(thread == NULL);
4154
4155         wait_for_completion(&init_context.init_done);
4156
4157         if (!init_context.err)
4158                 *thread_ptr = thread;
4159
4160         return init_context.err;
4161 }