OSDN Git Service

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