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