2 * Kernel-based Virtual Machine driver for Linux
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 * Avi Kivity <avi@qumranet.com>
12 * Yaniv Kamay <yaniv@qumranet.com>
14 * This work is licensed under the terms of the GNU GPL, version 2. See
15 * the COPYING file in the top-level directory.
19 #include <kvm/iodev.h>
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>
27 #include <linux/miscdevice.h>
28 #include <linux/vmalloc.h>
29 #include <linux/reboot.h>
30 #include <linux/debugfs.h>
31 #include <linux/highmem.h>
32 #include <linux/file.h>
33 #include <linux/syscore_ops.h>
34 #include <linux/cpu.h>
35 #include <linux/sched.h>
36 #include <linux/cpumask.h>
37 #include <linux/smp.h>
38 #include <linux/anon_inodes.h>
39 #include <linux/profile.h>
40 #include <linux/kvm_para.h>
41 #include <linux/pagemap.h>
42 #include <linux/mman.h>
43 #include <linux/swap.h>
44 #include <linux/bitops.h>
45 #include <linux/spinlock.h>
46 #include <linux/compat.h>
47 #include <linux/srcu.h>
48 #include <linux/hugetlb.h>
49 #include <linux/slab.h>
50 #include <linux/sort.h>
51 #include <linux/bsearch.h>
52 #include <linux/kthread.h>
54 #include <asm/processor.h>
56 #include <asm/ioctl.h>
57 #include <asm/uaccess.h>
58 #include <asm/pgtable.h>
60 #include "coalesced_mmio.h"
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/kvm.h>
67 /* Worst case buffer size needed for holding an integer. */
68 #define ITOA_MAX_LEN 12
70 MODULE_AUTHOR("Qumranet");
71 MODULE_LICENSE("GPL");
73 /* Architectures should define their poll value according to the halt latency */
74 static unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
75 module_param(halt_poll_ns, uint, S_IRUGO | S_IWUSR);
77 /* Default doubles per-vcpu halt_poll_ns. */
78 static unsigned int halt_poll_ns_grow = 2;
79 module_param(halt_poll_ns_grow, uint, S_IRUGO | S_IWUSR);
81 /* Default resets per-vcpu halt_poll_ns . */
82 static unsigned int halt_poll_ns_shrink;
83 module_param(halt_poll_ns_shrink, uint, S_IRUGO | S_IWUSR);
88 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
91 DEFINE_MUTEX(kvm_lock);
92 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
95 static cpumask_var_t cpus_hardware_enabled;
96 static int kvm_usage_count;
97 static atomic_t hardware_enable_failed;
99 struct kmem_cache *kvm_vcpu_cache;
100 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
102 static __read_mostly struct preempt_ops kvm_preempt_ops;
104 struct dentry *kvm_debugfs_dir;
105 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
107 static int kvm_debugfs_num_entries;
108 static const struct file_operations *stat_fops_per_vm[];
110 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
112 #ifdef CONFIG_KVM_COMPAT
113 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
116 static int hardware_enable_all(void);
117 static void hardware_disable_all(void);
119 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
121 static void kvm_release_pfn_dirty(kvm_pfn_t pfn);
122 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
124 __visible bool kvm_rebooting;
125 EXPORT_SYMBOL_GPL(kvm_rebooting);
127 static bool largepages_enabled = true;
129 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
130 unsigned long start, unsigned long end)
134 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
137 * The metadata used by is_zone_device_page() to determine whether or
138 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
139 * the device has been pinned, e.g. by get_user_pages(). WARN if the
140 * page_count() is zero to help detect bad usage of this helper.
142 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
145 return is_zone_device_page(pfn_to_page(pfn));
148 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
151 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
152 * perspective they are "normal" pages, albeit with slightly different
156 return PageReserved(pfn_to_page(pfn)) &&
158 !kvm_is_zone_device_pfn(pfn);
164 * Switches to specified vcpu, until a matching vcpu_put()
166 int vcpu_load(struct kvm_vcpu *vcpu)
170 if (mutex_lock_killable(&vcpu->mutex))
173 preempt_notifier_register(&vcpu->preempt_notifier);
174 kvm_arch_vcpu_load(vcpu, cpu);
178 EXPORT_SYMBOL_GPL(vcpu_load);
180 void vcpu_put(struct kvm_vcpu *vcpu)
183 kvm_arch_vcpu_put(vcpu);
184 preempt_notifier_unregister(&vcpu->preempt_notifier);
186 mutex_unlock(&vcpu->mutex);
188 EXPORT_SYMBOL_GPL(vcpu_put);
190 static void ack_flush(void *_completed)
194 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
199 struct kvm_vcpu *vcpu;
201 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
204 kvm_for_each_vcpu(i, vcpu, kvm) {
205 kvm_make_request(req, vcpu);
208 /* Set ->requests bit before we read ->mode. */
209 smp_mb__after_atomic();
211 if (cpus != NULL && cpu != -1 && cpu != me &&
212 kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
213 cpumask_set_cpu(cpu, cpus);
215 if (unlikely(cpus == NULL))
216 smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
217 else if (!cpumask_empty(cpus))
218 smp_call_function_many(cpus, ack_flush, NULL, 1);
222 free_cpumask_var(cpus);
226 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
227 void kvm_flush_remote_tlbs(struct kvm *kvm)
230 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
231 * kvm_make_all_cpus_request.
233 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
236 * We want to publish modifications to the page tables before reading
237 * mode. Pairs with a memory barrier in arch-specific code.
238 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
239 * and smp_mb in walk_shadow_page_lockless_begin/end.
240 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
242 * There is already an smp_mb__after_atomic() before
243 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
246 if (kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
247 ++kvm->stat.remote_tlb_flush;
248 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
250 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
253 void kvm_reload_remote_mmus(struct kvm *kvm)
255 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
258 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
263 mutex_init(&vcpu->mutex);
268 init_swait_queue_head(&vcpu->wq);
269 kvm_async_pf_vcpu_init(vcpu);
272 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
274 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
279 vcpu->run = page_address(page);
281 kvm_vcpu_set_in_spin_loop(vcpu, false);
282 kvm_vcpu_set_dy_eligible(vcpu, false);
283 vcpu->preempted = false;
285 r = kvm_arch_vcpu_init(vcpu);
291 free_page((unsigned long)vcpu->run);
295 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
297 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
300 kvm_arch_vcpu_uninit(vcpu);
301 free_page((unsigned long)vcpu->run);
303 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
305 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
306 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
308 return container_of(mn, struct kvm, mmu_notifier);
311 static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
312 struct mm_struct *mm,
313 unsigned long address)
315 struct kvm *kvm = mmu_notifier_to_kvm(mn);
316 int need_tlb_flush, idx;
319 * When ->invalidate_page runs, the linux pte has been zapped
320 * already but the page is still allocated until
321 * ->invalidate_page returns. So if we increase the sequence
322 * here the kvm page fault will notice if the spte can't be
323 * established because the page is going to be freed. If
324 * instead the kvm page fault establishes the spte before
325 * ->invalidate_page runs, kvm_unmap_hva will release it
328 * The sequence increase only need to be seen at spin_unlock
329 * time, and not at spin_lock time.
331 * Increasing the sequence after the spin_unlock would be
332 * unsafe because the kvm page fault could then establish the
333 * pte after kvm_unmap_hva returned, without noticing the page
334 * is going to be freed.
336 idx = srcu_read_lock(&kvm->srcu);
337 spin_lock(&kvm->mmu_lock);
339 kvm->mmu_notifier_seq++;
340 need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
341 /* we've to flush the tlb before the pages can be freed */
343 kvm_flush_remote_tlbs(kvm);
345 spin_unlock(&kvm->mmu_lock);
347 kvm_arch_mmu_notifier_invalidate_page(kvm, address);
349 srcu_read_unlock(&kvm->srcu, idx);
352 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
353 struct mm_struct *mm,
354 unsigned long address,
357 struct kvm *kvm = mmu_notifier_to_kvm(mn);
360 idx = srcu_read_lock(&kvm->srcu);
361 spin_lock(&kvm->mmu_lock);
362 kvm->mmu_notifier_seq++;
363 kvm_set_spte_hva(kvm, address, pte);
364 spin_unlock(&kvm->mmu_lock);
365 srcu_read_unlock(&kvm->srcu, idx);
368 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
369 struct mm_struct *mm,
373 struct kvm *kvm = mmu_notifier_to_kvm(mn);
374 int need_tlb_flush = 0, idx;
376 idx = srcu_read_lock(&kvm->srcu);
377 spin_lock(&kvm->mmu_lock);
379 * The count increase must become visible at unlock time as no
380 * spte can be established without taking the mmu_lock and
381 * count is also read inside the mmu_lock critical section.
383 kvm->mmu_notifier_count++;
384 need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
385 /* we've to flush the tlb before the pages can be freed */
386 if (need_tlb_flush || kvm->tlbs_dirty)
387 kvm_flush_remote_tlbs(kvm);
389 spin_unlock(&kvm->mmu_lock);
391 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
393 srcu_read_unlock(&kvm->srcu, idx);
396 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
397 struct mm_struct *mm,
401 struct kvm *kvm = mmu_notifier_to_kvm(mn);
403 spin_lock(&kvm->mmu_lock);
405 * This sequence increase will notify the kvm page fault that
406 * the page that is going to be mapped in the spte could have
409 kvm->mmu_notifier_seq++;
412 * The above sequence increase must be visible before the
413 * below count decrease, which is ensured by the smp_wmb above
414 * in conjunction with the smp_rmb in mmu_notifier_retry().
416 kvm->mmu_notifier_count--;
417 spin_unlock(&kvm->mmu_lock);
419 BUG_ON(kvm->mmu_notifier_count < 0);
422 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
423 struct mm_struct *mm,
427 struct kvm *kvm = mmu_notifier_to_kvm(mn);
430 idx = srcu_read_lock(&kvm->srcu);
431 spin_lock(&kvm->mmu_lock);
433 young = kvm_age_hva(kvm, start, end);
435 kvm_flush_remote_tlbs(kvm);
437 spin_unlock(&kvm->mmu_lock);
438 srcu_read_unlock(&kvm->srcu, idx);
443 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
444 struct mm_struct *mm,
448 struct kvm *kvm = mmu_notifier_to_kvm(mn);
451 idx = srcu_read_lock(&kvm->srcu);
452 spin_lock(&kvm->mmu_lock);
454 * Even though we do not flush TLB, this will still adversely
455 * affect performance on pre-Haswell Intel EPT, where there is
456 * no EPT Access Bit to clear so that we have to tear down EPT
457 * tables instead. If we find this unacceptable, we can always
458 * add a parameter to kvm_age_hva so that it effectively doesn't
459 * do anything on clear_young.
461 * Also note that currently we never issue secondary TLB flushes
462 * from clear_young, leaving this job up to the regular system
463 * cadence. If we find this inaccurate, we might come up with a
464 * more sophisticated heuristic later.
466 young = kvm_age_hva(kvm, start, end);
467 spin_unlock(&kvm->mmu_lock);
468 srcu_read_unlock(&kvm->srcu, idx);
473 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
474 struct mm_struct *mm,
475 unsigned long address)
477 struct kvm *kvm = mmu_notifier_to_kvm(mn);
480 idx = srcu_read_lock(&kvm->srcu);
481 spin_lock(&kvm->mmu_lock);
482 young = kvm_test_age_hva(kvm, address);
483 spin_unlock(&kvm->mmu_lock);
484 srcu_read_unlock(&kvm->srcu, idx);
489 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
490 struct mm_struct *mm)
492 struct kvm *kvm = mmu_notifier_to_kvm(mn);
495 idx = srcu_read_lock(&kvm->srcu);
496 kvm_arch_flush_shadow_all(kvm);
497 srcu_read_unlock(&kvm->srcu, idx);
500 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
501 .invalidate_page = kvm_mmu_notifier_invalidate_page,
502 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
503 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
504 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
505 .clear_young = kvm_mmu_notifier_clear_young,
506 .test_young = kvm_mmu_notifier_test_young,
507 .change_pte = kvm_mmu_notifier_change_pte,
508 .release = kvm_mmu_notifier_release,
511 static int kvm_init_mmu_notifier(struct kvm *kvm)
513 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
514 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
517 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
519 static int kvm_init_mmu_notifier(struct kvm *kvm)
524 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
526 static struct kvm_memslots *kvm_alloc_memslots(void)
529 struct kvm_memslots *slots;
531 slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
536 * Init kvm generation close to the maximum to easily test the
537 * code of handling generation number wrap-around.
539 slots->generation = -150;
540 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
541 slots->id_to_index[i] = slots->memslots[i].id = i;
546 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
548 if (!memslot->dirty_bitmap)
551 kvfree(memslot->dirty_bitmap);
552 memslot->dirty_bitmap = NULL;
556 * Free any memory in @free but not in @dont.
558 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
559 struct kvm_memory_slot *dont)
561 if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
562 kvm_destroy_dirty_bitmap(free);
564 kvm_arch_free_memslot(kvm, free, dont);
569 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
571 struct kvm_memory_slot *memslot;
576 kvm_for_each_memslot(memslot, slots)
577 kvm_free_memslot(kvm, memslot, NULL);
582 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
586 if (!kvm->debugfs_dentry)
589 debugfs_remove_recursive(kvm->debugfs_dentry);
591 if (kvm->debugfs_stat_data) {
592 for (i = 0; i < kvm_debugfs_num_entries; i++)
593 kfree(kvm->debugfs_stat_data[i]);
594 kfree(kvm->debugfs_stat_data);
598 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
600 char dir_name[ITOA_MAX_LEN * 2];
601 struct kvm_stat_data *stat_data;
602 struct kvm_stats_debugfs_item *p;
604 if (!debugfs_initialized())
607 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
608 kvm->debugfs_dentry = debugfs_create_dir(dir_name,
610 if (!kvm->debugfs_dentry)
613 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
614 sizeof(*kvm->debugfs_stat_data),
616 if (!kvm->debugfs_stat_data)
619 for (p = debugfs_entries; p->name; p++) {
620 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
624 stat_data->kvm = kvm;
625 stat_data->offset = p->offset;
626 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
627 if (!debugfs_create_file(p->name, 0444,
630 stat_fops_per_vm[p->kind]))
637 * Called after the VM is otherwise initialized, but just before adding it to
640 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
646 * Called just after removing the VM from the vm_list, but before doing any
649 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
653 static struct kvm *kvm_create_vm(unsigned long type)
656 struct kvm *kvm = kvm_arch_alloc_vm();
659 return ERR_PTR(-ENOMEM);
661 spin_lock_init(&kvm->mmu_lock);
662 atomic_inc(¤t->mm->mm_count);
663 kvm->mm = current->mm;
664 kvm_eventfd_init(kvm);
665 mutex_init(&kvm->lock);
666 mutex_init(&kvm->irq_lock);
667 mutex_init(&kvm->slots_lock);
668 atomic_set(&kvm->users_count, 1);
669 INIT_LIST_HEAD(&kvm->devices);
671 r = kvm_arch_init_vm(kvm, type);
673 goto out_err_no_disable;
675 r = hardware_enable_all();
677 goto out_err_no_disable;
679 #ifdef CONFIG_HAVE_KVM_IRQFD
680 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
683 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
686 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
687 kvm->memslots[i] = kvm_alloc_memslots();
688 if (!kvm->memslots[i])
689 goto out_err_no_srcu;
692 if (init_srcu_struct(&kvm->srcu))
693 goto out_err_no_srcu;
694 if (init_srcu_struct(&kvm->irq_srcu))
695 goto out_err_no_irq_srcu;
696 for (i = 0; i < KVM_NR_BUSES; i++) {
697 kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
700 goto out_err_no_mmu_notifier;
703 r = kvm_init_mmu_notifier(kvm);
705 goto out_err_no_mmu_notifier;
707 r = kvm_arch_post_init_vm(kvm);
711 mutex_lock(&kvm_lock);
712 list_add(&kvm->vm_list, &vm_list);
713 mutex_unlock(&kvm_lock);
715 preempt_notifier_inc();
720 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
721 if (kvm->mmu_notifier.ops)
722 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
724 out_err_no_mmu_notifier:
725 cleanup_srcu_struct(&kvm->irq_srcu);
727 cleanup_srcu_struct(&kvm->srcu);
729 hardware_disable_all();
731 for (i = 0; i < KVM_NR_BUSES; i++)
732 kfree(kvm->buses[i]);
733 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
734 kvm_free_memslots(kvm, kvm->memslots[i]);
735 kvm_arch_free_vm(kvm);
741 * Avoid using vmalloc for a small buffer.
742 * Should not be used when the size is statically known.
744 void *kvm_kvzalloc(unsigned long size)
746 if (size > PAGE_SIZE)
747 return vzalloc(size);
749 return kzalloc(size, GFP_KERNEL);
752 static void kvm_destroy_devices(struct kvm *kvm)
754 struct kvm_device *dev, *tmp;
757 * We do not need to take the kvm->lock here, because nobody else
758 * has a reference to the struct kvm at this point and therefore
759 * cannot access the devices list anyhow.
761 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
762 list_del(&dev->vm_node);
763 dev->ops->destroy(dev);
767 static void kvm_destroy_vm(struct kvm *kvm)
770 struct mm_struct *mm = kvm->mm;
772 kvm_destroy_vm_debugfs(kvm);
773 kvm_arch_sync_events(kvm);
774 mutex_lock(&kvm_lock);
775 list_del(&kvm->vm_list);
776 mutex_unlock(&kvm_lock);
777 kvm_arch_pre_destroy_vm(kvm);
779 kvm_free_irq_routing(kvm);
780 for (i = 0; i < KVM_NR_BUSES; i++) {
782 kvm_io_bus_destroy(kvm->buses[i]);
783 kvm->buses[i] = NULL;
785 kvm_coalesced_mmio_free(kvm);
786 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
787 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
789 kvm_arch_flush_shadow_all(kvm);
791 kvm_arch_destroy_vm(kvm);
792 kvm_destroy_devices(kvm);
793 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
794 kvm_free_memslots(kvm, kvm->memslots[i]);
795 cleanup_srcu_struct(&kvm->irq_srcu);
796 cleanup_srcu_struct(&kvm->srcu);
797 kvm_arch_free_vm(kvm);
798 preempt_notifier_dec();
799 hardware_disable_all();
803 void kvm_get_kvm(struct kvm *kvm)
805 atomic_inc(&kvm->users_count);
807 EXPORT_SYMBOL_GPL(kvm_get_kvm);
809 void kvm_put_kvm(struct kvm *kvm)
811 if (atomic_dec_and_test(&kvm->users_count))
814 EXPORT_SYMBOL_GPL(kvm_put_kvm);
817 static int kvm_vm_release(struct inode *inode, struct file *filp)
819 struct kvm *kvm = filp->private_data;
821 kvm_irqfd_release(kvm);
828 * Allocation size is twice as large as the actual dirty bitmap size.
829 * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
831 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
833 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
835 memslot->dirty_bitmap = kvm_kvzalloc(dirty_bytes);
836 if (!memslot->dirty_bitmap)
843 * Insert memslot and re-sort memslots based on their GFN,
844 * so binary search could be used to lookup GFN.
845 * Sorting algorithm takes advantage of having initially
846 * sorted array and known changed memslot position.
848 static void update_memslots(struct kvm_memslots *slots,
849 struct kvm_memory_slot *new)
852 int i = slots->id_to_index[id];
853 struct kvm_memory_slot *mslots = slots->memslots;
855 WARN_ON(mslots[i].id != id);
857 WARN_ON(!mslots[i].npages);
858 if (mslots[i].npages)
861 if (!mslots[i].npages)
865 while (i < KVM_MEM_SLOTS_NUM - 1 &&
866 new->base_gfn <= mslots[i + 1].base_gfn) {
867 if (!mslots[i + 1].npages)
869 mslots[i] = mslots[i + 1];
870 slots->id_to_index[mslots[i].id] = i;
875 * The ">=" is needed when creating a slot with base_gfn == 0,
876 * so that it moves before all those with base_gfn == npages == 0.
878 * On the other hand, if new->npages is zero, the above loop has
879 * already left i pointing to the beginning of the empty part of
880 * mslots, and the ">=" would move the hole backwards in this
881 * case---which is wrong. So skip the loop when deleting a slot.
885 new->base_gfn >= mslots[i - 1].base_gfn) {
886 mslots[i] = mslots[i - 1];
887 slots->id_to_index[mslots[i].id] = i;
891 WARN_ON_ONCE(i != slots->used_slots);
894 slots->id_to_index[mslots[i].id] = i;
897 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
899 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
901 #ifdef __KVM_HAVE_READONLY_MEM
902 valid_flags |= KVM_MEM_READONLY;
905 if (mem->flags & ~valid_flags)
911 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
912 int as_id, struct kvm_memslots *slots)
914 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
917 * Set the low bit in the generation, which disables SPTE caching
918 * until the end of synchronize_srcu_expedited.
920 WARN_ON(old_memslots->generation & 1);
921 slots->generation = old_memslots->generation + 1;
923 rcu_assign_pointer(kvm->memslots[as_id], slots);
924 synchronize_srcu_expedited(&kvm->srcu);
927 * Increment the new memslot generation a second time. This prevents
928 * vm exits that race with memslot updates from caching a memslot
929 * generation that will (potentially) be valid forever.
933 kvm_arch_memslots_updated(kvm, slots);
939 * Allocate some memory and give it an address in the guest physical address
942 * Discontiguous memory is allowed, mostly for framebuffers.
944 * Must be called holding kvm->slots_lock for write.
946 int __kvm_set_memory_region(struct kvm *kvm,
947 const struct kvm_userspace_memory_region *mem)
951 unsigned long npages;
952 struct kvm_memory_slot *slot;
953 struct kvm_memory_slot old, new;
954 struct kvm_memslots *slots = NULL, *old_memslots;
956 enum kvm_mr_change change;
958 r = check_memory_region_flags(mem);
963 as_id = mem->slot >> 16;
966 /* General sanity checks */
967 if (mem->memory_size & (PAGE_SIZE - 1))
969 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
971 /* We can read the guest memory with __xxx_user() later on. */
972 if ((id < KVM_USER_MEM_SLOTS) &&
973 ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
974 !access_ok(VERIFY_WRITE,
975 (void __user *)(unsigned long)mem->userspace_addr,
978 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
980 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
983 slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
984 base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
985 npages = mem->memory_size >> PAGE_SHIFT;
987 if (npages > KVM_MEM_MAX_NR_PAGES)
993 new.base_gfn = base_gfn;
995 new.flags = mem->flags;
999 change = KVM_MR_CREATE;
1000 else { /* Modify an existing slot. */
1001 if ((mem->userspace_addr != old.userspace_addr) ||
1002 (npages != old.npages) ||
1003 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1006 if (base_gfn != old.base_gfn)
1007 change = KVM_MR_MOVE;
1008 else if (new.flags != old.flags)
1009 change = KVM_MR_FLAGS_ONLY;
1010 else { /* Nothing to change. */
1019 change = KVM_MR_DELETE;
1024 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1025 /* Check for overlaps */
1027 kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
1030 if (!((base_gfn + npages <= slot->base_gfn) ||
1031 (base_gfn >= slot->base_gfn + slot->npages)))
1036 /* Free page dirty bitmap if unneeded */
1037 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1038 new.dirty_bitmap = NULL;
1041 if (change == KVM_MR_CREATE) {
1042 new.userspace_addr = mem->userspace_addr;
1044 if (kvm_arch_create_memslot(kvm, &new, npages))
1048 /* Allocate page dirty bitmap if needed */
1049 if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1050 if (kvm_create_dirty_bitmap(&new) < 0)
1054 slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
1057 memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
1059 if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
1060 slot = id_to_memslot(slots, id);
1061 slot->flags |= KVM_MEMSLOT_INVALID;
1063 old_memslots = install_new_memslots(kvm, as_id, slots);
1065 /* slot was deleted or moved, clear iommu mapping */
1066 kvm_iommu_unmap_pages(kvm, &old);
1067 /* From this point no new shadow pages pointing to a deleted,
1068 * or moved, memslot will be created.
1070 * validation of sp->gfn happens in:
1071 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1072 * - kvm_is_visible_gfn (mmu_check_roots)
1074 kvm_arch_flush_shadow_memslot(kvm, slot);
1077 * We can re-use the old_memslots from above, the only difference
1078 * from the currently installed memslots is the invalid flag. This
1079 * will get overwritten by update_memslots anyway.
1081 slots = old_memslots;
1084 r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
1088 /* actual memory is freed via old in kvm_free_memslot below */
1089 if (change == KVM_MR_DELETE) {
1090 new.dirty_bitmap = NULL;
1091 memset(&new.arch, 0, sizeof(new.arch));
1094 update_memslots(slots, &new);
1095 old_memslots = install_new_memslots(kvm, as_id, slots);
1097 kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
1099 kvm_free_memslot(kvm, &old, &new);
1100 kvfree(old_memslots);
1103 * IOMMU mapping: New slots need to be mapped. Old slots need to be
1104 * un-mapped and re-mapped if their base changes. Since base change
1105 * unmapping is handled above with slot deletion, mapping alone is
1106 * needed here. Anything else the iommu might care about for existing
1107 * slots (size changes, userspace addr changes and read-only flag
1108 * changes) is disallowed above, so any other attribute changes getting
1109 * here can be skipped.
1111 if (as_id == 0 && (change == KVM_MR_CREATE || change == KVM_MR_MOVE)) {
1112 r = kvm_iommu_map_pages(kvm, &new);
1121 kvm_free_memslot(kvm, &new, &old);
1125 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1127 int kvm_set_memory_region(struct kvm *kvm,
1128 const struct kvm_userspace_memory_region *mem)
1132 mutex_lock(&kvm->slots_lock);
1133 r = __kvm_set_memory_region(kvm, mem);
1134 mutex_unlock(&kvm->slots_lock);
1137 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1139 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1140 struct kvm_userspace_memory_region *mem)
1142 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1145 return kvm_set_memory_region(kvm, mem);
1148 int kvm_get_dirty_log(struct kvm *kvm,
1149 struct kvm_dirty_log *log, int *is_dirty)
1151 struct kvm_memslots *slots;
1152 struct kvm_memory_slot *memslot;
1153 int r, i, as_id, id;
1155 unsigned long any = 0;
1158 as_id = log->slot >> 16;
1159 id = (u16)log->slot;
1160 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1163 slots = __kvm_memslots(kvm, as_id);
1164 memslot = id_to_memslot(slots, id);
1166 if (!memslot->dirty_bitmap)
1169 n = kvm_dirty_bitmap_bytes(memslot);
1171 for (i = 0; !any && i < n/sizeof(long); ++i)
1172 any = memslot->dirty_bitmap[i];
1175 if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1185 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1187 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1189 * kvm_get_dirty_log_protect - get a snapshot of dirty pages, and if any pages
1190 * are dirty write protect them for next write.
1191 * @kvm: pointer to kvm instance
1192 * @log: slot id and address to which we copy the log
1193 * @is_dirty: flag set if any page is dirty
1195 * We need to keep it in mind that VCPU threads can write to the bitmap
1196 * concurrently. So, to avoid losing track of dirty pages we keep the
1199 * 1. Take a snapshot of the bit and clear it if needed.
1200 * 2. Write protect the corresponding page.
1201 * 3. Copy the snapshot to the userspace.
1202 * 4. Upon return caller flushes TLB's if needed.
1204 * Between 2 and 4, the guest may write to the page using the remaining TLB
1205 * entry. This is not a problem because the page is reported dirty using
1206 * the snapshot taken before and step 4 ensures that writes done after
1207 * exiting to userspace will be logged for the next call.
1210 int kvm_get_dirty_log_protect(struct kvm *kvm,
1211 struct kvm_dirty_log *log, bool *is_dirty)
1213 struct kvm_memslots *slots;
1214 struct kvm_memory_slot *memslot;
1215 int r, i, as_id, id;
1217 unsigned long *dirty_bitmap;
1218 unsigned long *dirty_bitmap_buffer;
1221 as_id = log->slot >> 16;
1222 id = (u16)log->slot;
1223 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1226 slots = __kvm_memslots(kvm, as_id);
1227 memslot = id_to_memslot(slots, id);
1229 dirty_bitmap = memslot->dirty_bitmap;
1234 n = kvm_dirty_bitmap_bytes(memslot);
1236 dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
1237 memset(dirty_bitmap_buffer, 0, n);
1239 spin_lock(&kvm->mmu_lock);
1241 for (i = 0; i < n / sizeof(long); i++) {
1245 if (!dirty_bitmap[i])
1250 mask = xchg(&dirty_bitmap[i], 0);
1251 dirty_bitmap_buffer[i] = mask;
1254 offset = i * BITS_PER_LONG;
1255 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1260 spin_unlock(&kvm->mmu_lock);
1263 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1270 EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
1273 bool kvm_largepages_enabled(void)
1275 return largepages_enabled;
1278 void kvm_disable_largepages(void)
1280 largepages_enabled = false;
1282 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1284 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1286 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1288 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1290 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1292 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1295 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1297 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1299 if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1300 memslot->flags & KVM_MEMSLOT_INVALID)
1305 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1307 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
1309 struct vm_area_struct *vma;
1310 unsigned long addr, size;
1314 addr = gfn_to_hva(kvm, gfn);
1315 if (kvm_is_error_hva(addr))
1318 down_read(¤t->mm->mmap_sem);
1319 vma = find_vma(current->mm, addr);
1323 size = vma_kernel_pagesize(vma);
1326 up_read(¤t->mm->mmap_sem);
1331 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1333 return slot->flags & KVM_MEM_READONLY;
1336 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1337 gfn_t *nr_pages, bool write)
1339 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1340 return KVM_HVA_ERR_BAD;
1342 if (memslot_is_readonly(slot) && write)
1343 return KVM_HVA_ERR_RO_BAD;
1346 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1348 return __gfn_to_hva_memslot(slot, gfn);
1351 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1354 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1357 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1360 return gfn_to_hva_many(slot, gfn, NULL);
1362 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1364 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1366 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1368 EXPORT_SYMBOL_GPL(gfn_to_hva);
1370 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1372 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1374 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1377 * If writable is set to false, the hva returned by this function is only
1378 * allowed to be read.
1380 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1381 gfn_t gfn, bool *writable)
1383 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1385 if (!kvm_is_error_hva(hva) && writable)
1386 *writable = !memslot_is_readonly(slot);
1391 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1393 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1395 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1398 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1400 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1402 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1405 static int get_user_page_nowait(unsigned long start, int write,
1408 int flags = FOLL_NOWAIT | FOLL_HWPOISON;
1411 flags |= FOLL_WRITE;
1413 return get_user_pages(start, 1, flags, page, NULL);
1416 static inline int check_user_page_hwpoison(unsigned long addr)
1418 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1420 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1421 return rc == -EHWPOISON;
1425 * The atomic path to get the writable pfn which will be stored in @pfn,
1426 * true indicates success, otherwise false is returned.
1428 static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
1429 bool write_fault, bool *writable, kvm_pfn_t *pfn)
1431 struct page *page[1];
1434 if (!(async || atomic))
1438 * Fast pin a writable pfn only if it is a write fault request
1439 * or the caller allows to map a writable pfn for a read fault
1442 if (!(write_fault || writable))
1445 npages = __get_user_pages_fast(addr, 1, 1, page);
1447 *pfn = page_to_pfn(page[0]);
1458 * The slow path to get the pfn of the specified host virtual address,
1459 * 1 indicates success, -errno is returned if error is detected.
1461 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1462 bool *writable, kvm_pfn_t *pfn)
1464 struct page *page[1];
1470 *writable = write_fault;
1473 down_read(¤t->mm->mmap_sem);
1474 npages = get_user_page_nowait(addr, write_fault, page);
1475 up_read(¤t->mm->mmap_sem);
1477 unsigned int flags = FOLL_TOUCH | FOLL_HWPOISON;
1480 flags |= FOLL_WRITE;
1482 npages = __get_user_pages_unlocked(current, current->mm, addr, 1,
1488 /* map read fault as writable if possible */
1489 if (unlikely(!write_fault) && writable) {
1490 struct page *wpage[1];
1492 npages = __get_user_pages_fast(addr, 1, 1, wpage);
1501 *pfn = page_to_pfn(page[0]);
1505 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1507 if (unlikely(!(vma->vm_flags & VM_READ)))
1510 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1516 static int kvm_try_get_pfn(kvm_pfn_t pfn)
1518 if (kvm_is_reserved_pfn(pfn))
1520 return get_page_unless_zero(pfn_to_page(pfn));
1523 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1524 unsigned long addr, bool *async,
1525 bool write_fault, bool *writable,
1533 r = follow_pte_pmd(vma->vm_mm, addr, &ptep, NULL, &ptl);
1536 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1537 * not call the fault handler, so do it here.
1539 bool unlocked = false;
1540 r = fixup_user_fault(current, current->mm, addr,
1541 (write_fault ? FAULT_FLAG_WRITE : 0),
1548 r = follow_pte_pmd(vma->vm_mm, addr, &ptep, NULL, &ptl);
1553 if (write_fault && !pte_write(*ptep)) {
1554 pfn = KVM_PFN_ERR_RO_FAULT;
1559 *writable = pte_write(*ptep);
1560 pfn = pte_pfn(*ptep);
1563 * Get a reference here because callers of *hva_to_pfn* and
1564 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1565 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1566 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1567 * simply do nothing for reserved pfns.
1569 * Whoever called remap_pfn_range is also going to call e.g.
1570 * unmap_mapping_range before the underlying pages are freed,
1571 * causing a call to our MMU notifier.
1573 * Certain IO or PFNMAP mappings can be backed with valid
1574 * struct pages, but be allocated without refcounting e.g.,
1575 * tail pages of non-compound higher order allocations, which
1576 * would then underflow the refcount when the caller does the
1577 * required put_page. Don't allow those pages here.
1579 if (!kvm_try_get_pfn(pfn))
1583 pte_unmap_unlock(ptep, ptl);
1590 * Pin guest page in memory and return its pfn.
1591 * @addr: host virtual address which maps memory to the guest
1592 * @atomic: whether this function can sleep
1593 * @async: whether this function need to wait IO complete if the
1594 * host page is not in the memory
1595 * @write_fault: whether we should get a writable host page
1596 * @writable: whether it allows to map a writable host page for !@write_fault
1598 * The function will map a writable host page for these two cases:
1599 * 1): @write_fault = true
1600 * 2): @write_fault = false && @writable, @writable will tell the caller
1601 * whether the mapping is writable.
1603 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1604 bool write_fault, bool *writable)
1606 struct vm_area_struct *vma;
1610 /* we can do it either atomically or asynchronously, not both */
1611 BUG_ON(atomic && async);
1613 if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
1617 return KVM_PFN_ERR_FAULT;
1619 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1623 down_read(¤t->mm->mmap_sem);
1624 if (npages == -EHWPOISON ||
1625 (!async && check_user_page_hwpoison(addr))) {
1626 pfn = KVM_PFN_ERR_HWPOISON;
1631 vma = find_vma_intersection(current->mm, addr, addr + 1);
1634 pfn = KVM_PFN_ERR_FAULT;
1635 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1636 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1640 pfn = KVM_PFN_ERR_FAULT;
1642 if (async && vma_is_valid(vma, write_fault))
1644 pfn = KVM_PFN_ERR_FAULT;
1647 up_read(¤t->mm->mmap_sem);
1651 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1652 bool atomic, bool *async, bool write_fault,
1655 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1657 if (addr == KVM_HVA_ERR_RO_BAD) {
1660 return KVM_PFN_ERR_RO_FAULT;
1663 if (kvm_is_error_hva(addr)) {
1666 return KVM_PFN_NOSLOT;
1669 /* Do not map writable pfn in the readonly memslot. */
1670 if (writable && memslot_is_readonly(slot)) {
1675 return hva_to_pfn(addr, atomic, async, write_fault,
1678 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1680 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1683 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1684 write_fault, writable);
1686 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1688 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1690 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1692 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1694 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1696 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1698 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1700 kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1702 return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1704 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1706 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1708 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1710 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1712 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1714 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1716 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1718 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1720 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1722 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1724 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1725 struct page **pages, int nr_pages)
1730 addr = gfn_to_hva_many(slot, gfn, &entry);
1731 if (kvm_is_error_hva(addr))
1734 if (entry < nr_pages)
1737 return __get_user_pages_fast(addr, nr_pages, 1, pages);
1739 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1741 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
1743 if (is_error_noslot_pfn(pfn))
1744 return KVM_ERR_PTR_BAD_PAGE;
1746 if (kvm_is_reserved_pfn(pfn)) {
1748 return KVM_ERR_PTR_BAD_PAGE;
1751 return pfn_to_page(pfn);
1754 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1758 pfn = gfn_to_pfn(kvm, gfn);
1760 return kvm_pfn_to_page(pfn);
1762 EXPORT_SYMBOL_GPL(gfn_to_page);
1764 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
1768 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
1770 return kvm_pfn_to_page(pfn);
1772 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
1774 void kvm_release_page_clean(struct page *page)
1776 WARN_ON(is_error_page(page));
1778 kvm_release_pfn_clean(page_to_pfn(page));
1780 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1782 void kvm_release_pfn_clean(kvm_pfn_t pfn)
1784 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
1785 put_page(pfn_to_page(pfn));
1787 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1789 void kvm_release_page_dirty(struct page *page)
1791 WARN_ON(is_error_page(page));
1793 kvm_release_pfn_dirty(page_to_pfn(page));
1795 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1797 static void kvm_release_pfn_dirty(kvm_pfn_t pfn)
1799 kvm_set_pfn_dirty(pfn);
1800 kvm_release_pfn_clean(pfn);
1803 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
1805 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn)) {
1806 struct page *page = pfn_to_page(pfn);
1808 if (!PageReserved(page))
1812 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1814 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
1816 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
1817 mark_page_accessed(pfn_to_page(pfn));
1819 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1821 void kvm_get_pfn(kvm_pfn_t pfn)
1823 if (!kvm_is_reserved_pfn(pfn))
1824 get_page(pfn_to_page(pfn));
1826 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1828 static int next_segment(unsigned long len, int offset)
1830 if (len > PAGE_SIZE - offset)
1831 return PAGE_SIZE - offset;
1836 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
1837 void *data, int offset, int len)
1842 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1843 if (kvm_is_error_hva(addr))
1845 r = __copy_from_user(data, (void __user *)addr + offset, len);
1851 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1854 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1856 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1858 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1860 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
1861 int offset, int len)
1863 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1865 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1867 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
1869 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1871 gfn_t gfn = gpa >> PAGE_SHIFT;
1873 int offset = offset_in_page(gpa);
1876 while ((seg = next_segment(len, offset)) != 0) {
1877 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1887 EXPORT_SYMBOL_GPL(kvm_read_guest);
1889 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
1891 gfn_t gfn = gpa >> PAGE_SHIFT;
1893 int offset = offset_in_page(gpa);
1896 while ((seg = next_segment(len, offset)) != 0) {
1897 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
1907 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
1909 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1910 void *data, int offset, unsigned long len)
1915 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1916 if (kvm_is_error_hva(addr))
1918 pagefault_disable();
1919 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1926 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1929 gfn_t gfn = gpa >> PAGE_SHIFT;
1930 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1931 int offset = offset_in_page(gpa);
1933 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1935 EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
1937 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
1938 void *data, unsigned long len)
1940 gfn_t gfn = gpa >> PAGE_SHIFT;
1941 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1942 int offset = offset_in_page(gpa);
1944 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1946 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
1948 static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
1949 const void *data, int offset, int len)
1954 addr = gfn_to_hva_memslot(memslot, gfn);
1955 if (kvm_is_error_hva(addr))
1957 r = __copy_to_user((void __user *)addr + offset, data, len);
1960 mark_page_dirty_in_slot(memslot, gfn);
1964 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
1965 const void *data, int offset, int len)
1967 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1969 return __kvm_write_guest_page(slot, gfn, data, offset, len);
1971 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1973 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
1974 const void *data, int offset, int len)
1976 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1978 return __kvm_write_guest_page(slot, gfn, data, offset, len);
1980 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
1982 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1985 gfn_t gfn = gpa >> PAGE_SHIFT;
1987 int offset = offset_in_page(gpa);
1990 while ((seg = next_segment(len, offset)) != 0) {
1991 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2001 EXPORT_SYMBOL_GPL(kvm_write_guest);
2003 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2006 gfn_t gfn = gpa >> PAGE_SHIFT;
2008 int offset = offset_in_page(gpa);
2011 while ((seg = next_segment(len, offset)) != 0) {
2012 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2022 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2024 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2025 gpa_t gpa, unsigned long len)
2027 struct kvm_memslots *slots = kvm_memslots(kvm);
2028 int offset = offset_in_page(gpa);
2029 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2030 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2031 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2032 gfn_t nr_pages_avail;
2035 ghc->generation = slots->generation;
2037 ghc->memslot = gfn_to_memslot(kvm, start_gfn);
2038 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, NULL);
2039 if (!kvm_is_error_hva(ghc->hva) && nr_pages_needed <= 1) {
2043 * If the requested region crosses two memslots, we still
2044 * verify that the entire region is valid here.
2046 while (start_gfn <= end_gfn) {
2047 ghc->memslot = gfn_to_memslot(kvm, start_gfn);
2048 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2050 if (kvm_is_error_hva(ghc->hva))
2052 start_gfn += nr_pages_avail;
2054 /* Use the slow path for cross page reads and writes. */
2055 ghc->memslot = NULL;
2059 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2061 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2062 void *data, unsigned long len)
2064 struct kvm_memslots *slots = kvm_memslots(kvm);
2067 BUG_ON(len > ghc->len);
2069 if (slots->generation != ghc->generation)
2070 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
2072 if (kvm_is_error_hva(ghc->hva))
2075 if (unlikely(!ghc->memslot))
2076 return kvm_write_guest(kvm, ghc->gpa, data, len);
2078 r = __copy_to_user((void __user *)ghc->hva, data, len);
2081 mark_page_dirty_in_slot(ghc->memslot, ghc->gpa >> PAGE_SHIFT);
2085 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2087 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2088 void *data, unsigned long len)
2090 struct kvm_memslots *slots = kvm_memslots(kvm);
2093 BUG_ON(len > ghc->len);
2095 if (slots->generation != ghc->generation)
2096 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
2098 if (kvm_is_error_hva(ghc->hva))
2101 if (unlikely(!ghc->memslot))
2102 return kvm_read_guest(kvm, ghc->gpa, data, len);
2104 r = __copy_from_user(data, (void __user *)ghc->hva, len);
2110 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2112 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2114 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2116 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2118 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2120 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2122 gfn_t gfn = gpa >> PAGE_SHIFT;
2124 int offset = offset_in_page(gpa);
2127 while ((seg = next_segment(len, offset)) != 0) {
2128 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2137 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2139 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2142 if (memslot && memslot->dirty_bitmap) {
2143 unsigned long rel_gfn = gfn - memslot->base_gfn;
2145 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2149 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2151 struct kvm_memory_slot *memslot;
2153 memslot = gfn_to_memslot(kvm, gfn);
2154 mark_page_dirty_in_slot(memslot, gfn);
2156 EXPORT_SYMBOL_GPL(mark_page_dirty);
2158 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2160 struct kvm_memory_slot *memslot;
2162 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2163 mark_page_dirty_in_slot(memslot, gfn);
2165 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2167 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2169 unsigned int old, val, grow;
2171 old = val = vcpu->halt_poll_ns;
2172 grow = READ_ONCE(halt_poll_ns_grow);
2174 if (val == 0 && grow)
2179 if (val > halt_poll_ns)
2182 vcpu->halt_poll_ns = val;
2183 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2186 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2188 unsigned int old, val, shrink;
2190 old = val = vcpu->halt_poll_ns;
2191 shrink = READ_ONCE(halt_poll_ns_shrink);
2197 vcpu->halt_poll_ns = val;
2198 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2201 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2203 if (kvm_arch_vcpu_runnable(vcpu)) {
2204 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2207 if (kvm_cpu_has_pending_timer(vcpu))
2209 if (signal_pending(current))
2216 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2218 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2221 DECLARE_SWAITQUEUE(wait);
2222 bool waited = false;
2225 start = cur = ktime_get();
2226 if (vcpu->halt_poll_ns) {
2227 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2229 ++vcpu->stat.halt_attempted_poll;
2232 * This sets KVM_REQ_UNHALT if an interrupt
2235 if (kvm_vcpu_check_block(vcpu) < 0) {
2236 ++vcpu->stat.halt_successful_poll;
2237 if (!vcpu_valid_wakeup(vcpu))
2238 ++vcpu->stat.halt_poll_invalid;
2242 } while (single_task_running() && ktime_before(cur, stop));
2245 kvm_arch_vcpu_blocking(vcpu);
2248 prepare_to_swait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2250 if (kvm_vcpu_check_block(vcpu) < 0)
2257 finish_swait(&vcpu->wq, &wait);
2260 kvm_arch_vcpu_unblocking(vcpu);
2262 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2264 if (!vcpu_valid_wakeup(vcpu))
2265 shrink_halt_poll_ns(vcpu);
2266 else if (halt_poll_ns) {
2267 if (block_ns <= vcpu->halt_poll_ns)
2269 /* we had a long block, shrink polling */
2270 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2271 shrink_halt_poll_ns(vcpu);
2272 /* we had a short halt and our poll time is too small */
2273 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2274 block_ns < halt_poll_ns)
2275 grow_halt_poll_ns(vcpu);
2277 vcpu->halt_poll_ns = 0;
2279 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2280 kvm_arch_vcpu_block_finish(vcpu);
2282 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2285 void kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2287 struct swait_queue_head *wqp;
2289 wqp = kvm_arch_vcpu_wq(vcpu);
2290 if (swait_active(wqp)) {
2292 ++vcpu->stat.halt_wakeup;
2296 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2299 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2301 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2304 int cpu = vcpu->cpu;
2306 kvm_vcpu_wake_up(vcpu);
2308 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2309 if (kvm_arch_vcpu_should_kick(vcpu))
2310 smp_send_reschedule(cpu);
2313 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2314 #endif /* !CONFIG_S390 */
2316 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2319 struct task_struct *task = NULL;
2323 pid = rcu_dereference(target->pid);
2325 task = get_pid_task(pid, PIDTYPE_PID);
2329 ret = yield_to(task, 1);
2330 put_task_struct(task);
2334 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2337 * Helper that checks whether a VCPU is eligible for directed yield.
2338 * Most eligible candidate to yield is decided by following heuristics:
2340 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2341 * (preempted lock holder), indicated by @in_spin_loop.
2342 * Set at the beiginning and cleared at the end of interception/PLE handler.
2344 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2345 * chance last time (mostly it has become eligible now since we have probably
2346 * yielded to lockholder in last iteration. This is done by toggling
2347 * @dy_eligible each time a VCPU checked for eligibility.)
2349 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2350 * to preempted lock-holder could result in wrong VCPU selection and CPU
2351 * burning. Giving priority for a potential lock-holder increases lock
2354 * Since algorithm is based on heuristics, accessing another VCPU data without
2355 * locking does not harm. It may result in trying to yield to same VCPU, fail
2356 * and continue with next VCPU and so on.
2358 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2360 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2363 eligible = !vcpu->spin_loop.in_spin_loop ||
2364 vcpu->spin_loop.dy_eligible;
2366 if (vcpu->spin_loop.in_spin_loop)
2367 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2375 void kvm_vcpu_on_spin(struct kvm_vcpu *me)
2377 struct kvm *kvm = me->kvm;
2378 struct kvm_vcpu *vcpu;
2379 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2385 kvm_vcpu_set_in_spin_loop(me, true);
2387 * We boost the priority of a VCPU that is runnable but not
2388 * currently running, because it got preempted by something
2389 * else and called schedule in __vcpu_run. Hopefully that
2390 * VCPU is holding the lock that we need and will release it.
2391 * We approximate round-robin by starting at the last boosted VCPU.
2393 for (pass = 0; pass < 2 && !yielded && try; pass++) {
2394 kvm_for_each_vcpu(i, vcpu, kvm) {
2395 if (!pass && i <= last_boosted_vcpu) {
2396 i = last_boosted_vcpu;
2398 } else if (pass && i > last_boosted_vcpu)
2400 if (!ACCESS_ONCE(vcpu->preempted))
2404 if (swait_active(&vcpu->wq) && !kvm_arch_vcpu_runnable(vcpu))
2406 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2409 yielded = kvm_vcpu_yield_to(vcpu);
2411 kvm->last_boosted_vcpu = i;
2413 } else if (yielded < 0) {
2420 kvm_vcpu_set_in_spin_loop(me, false);
2422 /* Ensure vcpu is not eligible during next spinloop */
2423 kvm_vcpu_set_dy_eligible(me, false);
2425 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2427 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2429 struct kvm_vcpu *vcpu = vma->vm_file->private_data;
2432 if (vmf->pgoff == 0)
2433 page = virt_to_page(vcpu->run);
2435 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2436 page = virt_to_page(vcpu->arch.pio_data);
2438 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2439 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2440 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2443 return kvm_arch_vcpu_fault(vcpu, vmf);
2449 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2450 .fault = kvm_vcpu_fault,
2453 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2455 vma->vm_ops = &kvm_vcpu_vm_ops;
2459 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2461 struct kvm_vcpu *vcpu = filp->private_data;
2463 debugfs_remove_recursive(vcpu->debugfs_dentry);
2464 kvm_put_kvm(vcpu->kvm);
2468 static struct file_operations kvm_vcpu_fops = {
2469 .release = kvm_vcpu_release,
2470 .unlocked_ioctl = kvm_vcpu_ioctl,
2471 #ifdef CONFIG_KVM_COMPAT
2472 .compat_ioctl = kvm_vcpu_compat_ioctl,
2474 .mmap = kvm_vcpu_mmap,
2475 .llseek = noop_llseek,
2479 * Allocates an inode for the vcpu.
2481 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2483 return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2486 static int kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2488 char dir_name[ITOA_MAX_LEN * 2];
2491 if (!kvm_arch_has_vcpu_debugfs())
2494 if (!debugfs_initialized())
2497 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2498 vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2499 vcpu->kvm->debugfs_dentry);
2500 if (!vcpu->debugfs_dentry)
2503 ret = kvm_arch_create_vcpu_debugfs(vcpu);
2505 debugfs_remove_recursive(vcpu->debugfs_dentry);
2513 * Creates some virtual cpus. Good luck creating more than one.
2515 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
2518 struct kvm_vcpu *vcpu;
2520 if (id >= KVM_MAX_VCPU_ID)
2523 mutex_lock(&kvm->lock);
2524 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2525 mutex_unlock(&kvm->lock);
2529 kvm->created_vcpus++;
2530 mutex_unlock(&kvm->lock);
2532 vcpu = kvm_arch_vcpu_create(kvm, id);
2535 goto vcpu_decrement;
2538 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2540 r = kvm_arch_vcpu_setup(vcpu);
2544 r = kvm_create_vcpu_debugfs(vcpu);
2548 mutex_lock(&kvm->lock);
2549 if (kvm_get_vcpu_by_id(kvm, id)) {
2551 goto unlock_vcpu_destroy;
2554 BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2556 /* Now it's all set up, let userspace reach it */
2558 r = create_vcpu_fd(vcpu);
2561 goto unlock_vcpu_destroy;
2564 kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2567 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
2568 * before kvm->online_vcpu's incremented value.
2571 atomic_inc(&kvm->online_vcpus);
2573 mutex_unlock(&kvm->lock);
2574 kvm_arch_vcpu_postcreate(vcpu);
2577 unlock_vcpu_destroy:
2578 mutex_unlock(&kvm->lock);
2579 debugfs_remove_recursive(vcpu->debugfs_dentry);
2581 kvm_arch_vcpu_destroy(vcpu);
2583 mutex_lock(&kvm->lock);
2584 kvm->created_vcpus--;
2585 mutex_unlock(&kvm->lock);
2589 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2592 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2593 vcpu->sigset_active = 1;
2594 vcpu->sigset = *sigset;
2596 vcpu->sigset_active = 0;
2600 static long kvm_vcpu_ioctl(struct file *filp,
2601 unsigned int ioctl, unsigned long arg)
2603 struct kvm_vcpu *vcpu = filp->private_data;
2604 void __user *argp = (void __user *)arg;
2606 struct kvm_fpu *fpu = NULL;
2607 struct kvm_sregs *kvm_sregs = NULL;
2609 if (vcpu->kvm->mm != current->mm)
2612 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2615 #if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS)
2617 * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
2618 * so vcpu_load() would break it.
2620 if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_S390_IRQ || ioctl == KVM_INTERRUPT)
2621 return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2625 r = vcpu_load(vcpu);
2633 if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
2634 /* The thread running this VCPU changed. */
2635 struct pid *oldpid = vcpu->pid;
2636 struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
2638 rcu_assign_pointer(vcpu->pid, newpid);
2643 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2644 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2646 case KVM_GET_REGS: {
2647 struct kvm_regs *kvm_regs;
2650 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
2653 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2657 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2664 case KVM_SET_REGS: {
2665 struct kvm_regs *kvm_regs;
2668 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2669 if (IS_ERR(kvm_regs)) {
2670 r = PTR_ERR(kvm_regs);
2673 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2677 case KVM_GET_SREGS: {
2678 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
2682 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
2686 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
2691 case KVM_SET_SREGS: {
2692 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2693 if (IS_ERR(kvm_sregs)) {
2694 r = PTR_ERR(kvm_sregs);
2698 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
2701 case KVM_GET_MP_STATE: {
2702 struct kvm_mp_state mp_state;
2704 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2708 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
2713 case KVM_SET_MP_STATE: {
2714 struct kvm_mp_state mp_state;
2717 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
2719 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
2722 case KVM_TRANSLATE: {
2723 struct kvm_translation tr;
2726 if (copy_from_user(&tr, argp, sizeof(tr)))
2728 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
2732 if (copy_to_user(argp, &tr, sizeof(tr)))
2737 case KVM_SET_GUEST_DEBUG: {
2738 struct kvm_guest_debug dbg;
2741 if (copy_from_user(&dbg, argp, sizeof(dbg)))
2743 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2746 case KVM_SET_SIGNAL_MASK: {
2747 struct kvm_signal_mask __user *sigmask_arg = argp;
2748 struct kvm_signal_mask kvm_sigmask;
2749 sigset_t sigset, *p;
2754 if (copy_from_user(&kvm_sigmask, argp,
2755 sizeof(kvm_sigmask)))
2758 if (kvm_sigmask.len != sizeof(sigset))
2761 if (copy_from_user(&sigset, sigmask_arg->sigset,
2766 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2770 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2774 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2778 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2784 fpu = memdup_user(argp, sizeof(*fpu));
2790 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2794 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2803 #ifdef CONFIG_KVM_COMPAT
2804 static long kvm_vcpu_compat_ioctl(struct file *filp,
2805 unsigned int ioctl, unsigned long arg)
2807 struct kvm_vcpu *vcpu = filp->private_data;
2808 void __user *argp = compat_ptr(arg);
2811 if (vcpu->kvm->mm != current->mm)
2815 case KVM_SET_SIGNAL_MASK: {
2816 struct kvm_signal_mask __user *sigmask_arg = argp;
2817 struct kvm_signal_mask kvm_sigmask;
2818 compat_sigset_t csigset;
2823 if (copy_from_user(&kvm_sigmask, argp,
2824 sizeof(kvm_sigmask)))
2827 if (kvm_sigmask.len != sizeof(csigset))
2830 if (copy_from_user(&csigset, sigmask_arg->sigset,
2833 sigset_from_compat(&sigset, &csigset);
2834 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2836 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
2840 r = kvm_vcpu_ioctl(filp, ioctl, arg);
2848 static int kvm_device_ioctl_attr(struct kvm_device *dev,
2849 int (*accessor)(struct kvm_device *dev,
2850 struct kvm_device_attr *attr),
2853 struct kvm_device_attr attr;
2858 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2861 return accessor(dev, &attr);
2864 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
2867 struct kvm_device *dev = filp->private_data;
2869 if (dev->kvm->mm != current->mm)
2873 case KVM_SET_DEVICE_ATTR:
2874 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
2875 case KVM_GET_DEVICE_ATTR:
2876 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
2877 case KVM_HAS_DEVICE_ATTR:
2878 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
2880 if (dev->ops->ioctl)
2881 return dev->ops->ioctl(dev, ioctl, arg);
2887 static int kvm_device_release(struct inode *inode, struct file *filp)
2889 struct kvm_device *dev = filp->private_data;
2890 struct kvm *kvm = dev->kvm;
2896 static const struct file_operations kvm_device_fops = {
2897 .unlocked_ioctl = kvm_device_ioctl,
2898 #ifdef CONFIG_KVM_COMPAT
2899 .compat_ioctl = kvm_device_ioctl,
2901 .release = kvm_device_release,
2904 struct kvm_device *kvm_device_from_filp(struct file *filp)
2906 if (filp->f_op != &kvm_device_fops)
2909 return filp->private_data;
2912 static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
2913 #ifdef CONFIG_KVM_MPIC
2914 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
2915 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
2918 #ifdef CONFIG_KVM_XICS
2919 [KVM_DEV_TYPE_XICS] = &kvm_xics_ops,
2923 int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
2925 if (type >= ARRAY_SIZE(kvm_device_ops_table))
2928 if (kvm_device_ops_table[type] != NULL)
2931 kvm_device_ops_table[type] = ops;
2935 void kvm_unregister_device_ops(u32 type)
2937 if (kvm_device_ops_table[type] != NULL)
2938 kvm_device_ops_table[type] = NULL;
2941 static int kvm_ioctl_create_device(struct kvm *kvm,
2942 struct kvm_create_device *cd)
2944 struct kvm_device_ops *ops = NULL;
2945 struct kvm_device *dev;
2946 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
2949 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
2952 ops = kvm_device_ops_table[cd->type];
2959 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2966 mutex_lock(&kvm->lock);
2967 ret = ops->create(dev, cd->type);
2969 mutex_unlock(&kvm->lock);
2973 list_add(&dev->vm_node, &kvm->devices);
2974 mutex_unlock(&kvm->lock);
2980 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
2983 mutex_lock(&kvm->lock);
2984 list_del(&dev->vm_node);
2985 mutex_unlock(&kvm->lock);
2994 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
2997 case KVM_CAP_USER_MEMORY:
2998 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2999 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3000 case KVM_CAP_INTERNAL_ERROR_DATA:
3001 #ifdef CONFIG_HAVE_KVM_MSI
3002 case KVM_CAP_SIGNAL_MSI:
3004 #ifdef CONFIG_HAVE_KVM_IRQFD
3006 case KVM_CAP_IRQFD_RESAMPLE:
3008 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3009 case KVM_CAP_CHECK_EXTENSION_VM:
3011 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3012 case KVM_CAP_IRQ_ROUTING:
3013 return KVM_MAX_IRQ_ROUTES;
3015 #if KVM_ADDRESS_SPACE_NUM > 1
3016 case KVM_CAP_MULTI_ADDRESS_SPACE:
3017 return KVM_ADDRESS_SPACE_NUM;
3019 case KVM_CAP_MAX_VCPU_ID:
3020 return KVM_MAX_VCPU_ID;
3024 return kvm_vm_ioctl_check_extension(kvm, arg);
3027 static long kvm_vm_ioctl(struct file *filp,
3028 unsigned int ioctl, unsigned long arg)
3030 struct kvm *kvm = filp->private_data;
3031 void __user *argp = (void __user *)arg;
3034 if (kvm->mm != current->mm)
3037 case KVM_CREATE_VCPU:
3038 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3040 case KVM_SET_USER_MEMORY_REGION: {
3041 struct kvm_userspace_memory_region kvm_userspace_mem;
3044 if (copy_from_user(&kvm_userspace_mem, argp,
3045 sizeof(kvm_userspace_mem)))
3048 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3051 case KVM_GET_DIRTY_LOG: {
3052 struct kvm_dirty_log log;
3055 if (copy_from_user(&log, argp, sizeof(log)))
3057 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3060 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3061 case KVM_REGISTER_COALESCED_MMIO: {
3062 struct kvm_coalesced_mmio_zone zone;
3065 if (copy_from_user(&zone, argp, sizeof(zone)))
3067 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3070 case KVM_UNREGISTER_COALESCED_MMIO: {
3071 struct kvm_coalesced_mmio_zone zone;
3074 if (copy_from_user(&zone, argp, sizeof(zone)))
3076 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3081 struct kvm_irqfd data;
3084 if (copy_from_user(&data, argp, sizeof(data)))
3086 r = kvm_irqfd(kvm, &data);
3089 case KVM_IOEVENTFD: {
3090 struct kvm_ioeventfd data;
3093 if (copy_from_user(&data, argp, sizeof(data)))
3095 r = kvm_ioeventfd(kvm, &data);
3098 #ifdef CONFIG_HAVE_KVM_MSI
3099 case KVM_SIGNAL_MSI: {
3103 if (copy_from_user(&msi, argp, sizeof(msi)))
3105 r = kvm_send_userspace_msi(kvm, &msi);
3109 #ifdef __KVM_HAVE_IRQ_LINE
3110 case KVM_IRQ_LINE_STATUS:
3111 case KVM_IRQ_LINE: {
3112 struct kvm_irq_level irq_event;
3115 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3118 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3119 ioctl == KVM_IRQ_LINE_STATUS);
3124 if (ioctl == KVM_IRQ_LINE_STATUS) {
3125 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3133 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3134 case KVM_SET_GSI_ROUTING: {
3135 struct kvm_irq_routing routing;
3136 struct kvm_irq_routing __user *urouting;
3137 struct kvm_irq_routing_entry *entries = NULL;
3140 if (copy_from_user(&routing, argp, sizeof(routing)))
3143 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3149 entries = vmalloc(routing.nr * sizeof(*entries));
3154 if (copy_from_user(entries, urouting->entries,
3155 routing.nr * sizeof(*entries)))
3156 goto out_free_irq_routing;
3158 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3160 out_free_irq_routing:
3164 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3165 case KVM_CREATE_DEVICE: {
3166 struct kvm_create_device cd;
3169 if (copy_from_user(&cd, argp, sizeof(cd)))
3172 r = kvm_ioctl_create_device(kvm, &cd);
3177 if (copy_to_user(argp, &cd, sizeof(cd)))
3183 case KVM_CHECK_EXTENSION:
3184 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3187 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3193 #ifdef CONFIG_KVM_COMPAT
3194 struct compat_kvm_dirty_log {
3198 compat_uptr_t dirty_bitmap; /* one bit per page */
3203 static long kvm_vm_compat_ioctl(struct file *filp,
3204 unsigned int ioctl, unsigned long arg)
3206 struct kvm *kvm = filp->private_data;
3209 if (kvm->mm != current->mm)
3212 case KVM_GET_DIRTY_LOG: {
3213 struct compat_kvm_dirty_log compat_log;
3214 struct kvm_dirty_log log;
3217 if (copy_from_user(&compat_log, (void __user *)arg,
3218 sizeof(compat_log)))
3220 log.slot = compat_log.slot;
3221 log.padding1 = compat_log.padding1;
3222 log.padding2 = compat_log.padding2;
3223 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3225 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3229 r = kvm_vm_ioctl(filp, ioctl, arg);
3237 static struct file_operations kvm_vm_fops = {
3238 .release = kvm_vm_release,
3239 .unlocked_ioctl = kvm_vm_ioctl,
3240 #ifdef CONFIG_KVM_COMPAT
3241 .compat_ioctl = kvm_vm_compat_ioctl,
3243 .llseek = noop_llseek,
3246 static int kvm_dev_ioctl_create_vm(unsigned long type)
3252 kvm = kvm_create_vm(type);
3254 return PTR_ERR(kvm);
3255 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3256 r = kvm_coalesced_mmio_init(kvm);
3262 r = get_unused_fd_flags(O_CLOEXEC);
3267 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3271 return PTR_ERR(file);
3274 if (kvm_create_vm_debugfs(kvm, r) < 0) {
3280 fd_install(r, file);
3284 static long kvm_dev_ioctl(struct file *filp,
3285 unsigned int ioctl, unsigned long arg)
3290 case KVM_GET_API_VERSION:
3293 r = KVM_API_VERSION;
3296 r = kvm_dev_ioctl_create_vm(arg);
3298 case KVM_CHECK_EXTENSION:
3299 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3301 case KVM_GET_VCPU_MMAP_SIZE:
3304 r = PAGE_SIZE; /* struct kvm_run */
3306 r += PAGE_SIZE; /* pio data page */
3308 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3309 r += PAGE_SIZE; /* coalesced mmio ring page */
3312 case KVM_TRACE_ENABLE:
3313 case KVM_TRACE_PAUSE:
3314 case KVM_TRACE_DISABLE:
3318 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3324 static struct file_operations kvm_chardev_ops = {
3325 .unlocked_ioctl = kvm_dev_ioctl,
3326 .compat_ioctl = kvm_dev_ioctl,
3327 .llseek = noop_llseek,
3330 static struct miscdevice kvm_dev = {
3336 static void hardware_enable_nolock(void *junk)
3338 int cpu = raw_smp_processor_id();
3341 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3344 cpumask_set_cpu(cpu, cpus_hardware_enabled);
3346 r = kvm_arch_hardware_enable();
3349 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3350 atomic_inc(&hardware_enable_failed);
3351 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3355 static int kvm_starting_cpu(unsigned int cpu)
3357 raw_spin_lock(&kvm_count_lock);
3358 if (kvm_usage_count)
3359 hardware_enable_nolock(NULL);
3360 raw_spin_unlock(&kvm_count_lock);
3364 static void hardware_disable_nolock(void *junk)
3366 int cpu = raw_smp_processor_id();
3368 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3370 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3371 kvm_arch_hardware_disable();
3374 static int kvm_dying_cpu(unsigned int cpu)
3376 raw_spin_lock(&kvm_count_lock);
3377 if (kvm_usage_count)
3378 hardware_disable_nolock(NULL);
3379 raw_spin_unlock(&kvm_count_lock);
3383 static void hardware_disable_all_nolock(void)
3385 BUG_ON(!kvm_usage_count);
3388 if (!kvm_usage_count)
3389 on_each_cpu(hardware_disable_nolock, NULL, 1);
3392 static void hardware_disable_all(void)
3394 raw_spin_lock(&kvm_count_lock);
3395 hardware_disable_all_nolock();
3396 raw_spin_unlock(&kvm_count_lock);
3399 static int hardware_enable_all(void)
3403 raw_spin_lock(&kvm_count_lock);
3406 if (kvm_usage_count == 1) {
3407 atomic_set(&hardware_enable_failed, 0);
3408 on_each_cpu(hardware_enable_nolock, NULL, 1);
3410 if (atomic_read(&hardware_enable_failed)) {
3411 hardware_disable_all_nolock();
3416 raw_spin_unlock(&kvm_count_lock);
3421 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3425 * Some (well, at least mine) BIOSes hang on reboot if
3428 * And Intel TXT required VMX off for all cpu when system shutdown.
3430 pr_info("kvm: exiting hardware virtualization\n");
3431 kvm_rebooting = true;
3432 on_each_cpu(hardware_disable_nolock, NULL, 1);
3436 static struct notifier_block kvm_reboot_notifier = {
3437 .notifier_call = kvm_reboot,
3441 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3445 for (i = 0; i < bus->dev_count; i++) {
3446 struct kvm_io_device *pos = bus->range[i].dev;
3448 kvm_iodevice_destructor(pos);
3453 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3454 const struct kvm_io_range *r2)
3456 gpa_t addr1 = r1->addr;
3457 gpa_t addr2 = r2->addr;
3462 /* If r2->len == 0, match the exact address. If r2->len != 0,
3463 * accept any overlapping write. Any order is acceptable for
3464 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3465 * we process all of them.
3478 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3480 return kvm_io_bus_cmp(p1, p2);
3483 static int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
3484 gpa_t addr, int len)
3486 bus->range[bus->dev_count++] = (struct kvm_io_range) {
3492 sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
3493 kvm_io_bus_sort_cmp, NULL);
3498 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3499 gpa_t addr, int len)
3501 struct kvm_io_range *range, key;
3504 key = (struct kvm_io_range) {
3509 range = bsearch(&key, bus->range, bus->dev_count,
3510 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3514 off = range - bus->range;
3516 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3522 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3523 struct kvm_io_range *range, const void *val)
3527 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3531 while (idx < bus->dev_count &&
3532 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3533 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
3542 /* kvm_io_bus_write - called under kvm->slots_lock */
3543 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3544 int len, const void *val)
3546 struct kvm_io_bus *bus;
3547 struct kvm_io_range range;
3550 range = (struct kvm_io_range) {
3555 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3558 r = __kvm_io_bus_write(vcpu, bus, &range, val);
3559 return r < 0 ? r : 0;
3562 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3563 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3564 gpa_t addr, int len, const void *val, long cookie)
3566 struct kvm_io_bus *bus;
3567 struct kvm_io_range range;
3569 range = (struct kvm_io_range) {
3574 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3578 /* First try the device referenced by cookie. */
3579 if ((cookie >= 0) && (cookie < bus->dev_count) &&
3580 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3581 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
3586 * cookie contained garbage; fall back to search and return the
3587 * correct cookie value.
3589 return __kvm_io_bus_write(vcpu, bus, &range, val);
3592 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3593 struct kvm_io_range *range, void *val)
3597 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3601 while (idx < bus->dev_count &&
3602 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3603 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
3611 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
3613 /* kvm_io_bus_read - called under kvm->slots_lock */
3614 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3617 struct kvm_io_bus *bus;
3618 struct kvm_io_range range;
3621 range = (struct kvm_io_range) {
3626 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3629 r = __kvm_io_bus_read(vcpu, bus, &range, val);
3630 return r < 0 ? r : 0;
3634 /* Caller must hold slots_lock. */
3635 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3636 int len, struct kvm_io_device *dev)
3638 struct kvm_io_bus *new_bus, *bus;
3640 bus = kvm->buses[bus_idx];
3644 /* exclude ioeventfd which is limited by maximum fd */
3645 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
3648 new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
3649 sizeof(struct kvm_io_range)), GFP_KERNEL);
3652 memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
3653 sizeof(struct kvm_io_range)));
3654 kvm_io_bus_insert_dev(new_bus, dev, addr, len);
3655 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3656 synchronize_srcu_expedited(&kvm->srcu);
3662 /* Caller must hold slots_lock. */
3663 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3664 struct kvm_io_device *dev)
3667 struct kvm_io_bus *new_bus, *bus;
3669 bus = kvm->buses[bus_idx];
3673 for (i = 0; i < bus->dev_count; i++)
3674 if (bus->range[i].dev == dev) {
3678 if (i == bus->dev_count)
3681 new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
3682 sizeof(struct kvm_io_range)), GFP_KERNEL);
3684 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3685 new_bus->dev_count--;
3686 memcpy(new_bus->range + i, bus->range + i + 1,
3687 (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
3689 pr_err("kvm: failed to shrink bus, removing it completely\n");
3690 for (j = 0; j < bus->dev_count; j++) {
3693 kvm_iodevice_destructor(bus->range[j].dev);
3697 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3698 synchronize_srcu_expedited(&kvm->srcu);
3703 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3706 struct kvm_io_bus *bus;
3707 int dev_idx, srcu_idx;
3708 struct kvm_io_device *iodev = NULL;
3710 srcu_idx = srcu_read_lock(&kvm->srcu);
3712 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3716 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
3720 iodev = bus->range[dev_idx].dev;
3723 srcu_read_unlock(&kvm->srcu, srcu_idx);
3727 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
3729 static int kvm_debugfs_open(struct inode *inode, struct file *file,
3730 int (*get)(void *, u64 *), int (*set)(void *, u64),
3733 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3736 /* The debugfs files are a reference to the kvm struct which
3737 * is still valid when kvm_destroy_vm is called.
3738 * To avoid the race between open and the removal of the debugfs
3739 * directory we test against the users count.
3741 if (!atomic_add_unless(&stat_data->kvm->users_count, 1, 0))
3744 if (simple_attr_open(inode, file, get, set, fmt)) {
3745 kvm_put_kvm(stat_data->kvm);
3752 static int kvm_debugfs_release(struct inode *inode, struct file *file)
3754 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3757 simple_attr_release(inode, file);
3758 kvm_put_kvm(stat_data->kvm);
3763 static int vm_stat_get_per_vm(void *data, u64 *val)
3765 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3767 *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
3772 static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
3774 __simple_attr_check_format("%llu\n", 0ull);
3775 return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
3779 static const struct file_operations vm_stat_get_per_vm_fops = {
3780 .owner = THIS_MODULE,
3781 .open = vm_stat_get_per_vm_open,
3782 .release = kvm_debugfs_release,
3783 .read = simple_attr_read,
3784 .write = simple_attr_write,
3785 .llseek = generic_file_llseek,
3788 static int vcpu_stat_get_per_vm(void *data, u64 *val)
3791 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3792 struct kvm_vcpu *vcpu;
3796 kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3797 *val += *(u64 *)((void *)vcpu + stat_data->offset);
3802 static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
3804 __simple_attr_check_format("%llu\n", 0ull);
3805 return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
3809 static const struct file_operations vcpu_stat_get_per_vm_fops = {
3810 .owner = THIS_MODULE,
3811 .open = vcpu_stat_get_per_vm_open,
3812 .release = kvm_debugfs_release,
3813 .read = simple_attr_read,
3814 .write = simple_attr_write,
3815 .llseek = generic_file_llseek,
3818 static const struct file_operations *stat_fops_per_vm[] = {
3819 [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
3820 [KVM_STAT_VM] = &vm_stat_get_per_vm_fops,
3823 static int vm_stat_get(void *_offset, u64 *val)
3825 unsigned offset = (long)_offset;
3827 struct kvm_stat_data stat_tmp = {.offset = offset};
3831 mutex_lock(&kvm_lock);
3832 list_for_each_entry(kvm, &vm_list, vm_list) {
3834 vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3837 mutex_unlock(&kvm_lock);
3841 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
3843 static int vcpu_stat_get(void *_offset, u64 *val)
3845 unsigned offset = (long)_offset;
3847 struct kvm_stat_data stat_tmp = {.offset = offset};
3851 mutex_lock(&kvm_lock);
3852 list_for_each_entry(kvm, &vm_list, vm_list) {
3854 vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3857 mutex_unlock(&kvm_lock);
3861 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
3863 static const struct file_operations *stat_fops[] = {
3864 [KVM_STAT_VCPU] = &vcpu_stat_fops,
3865 [KVM_STAT_VM] = &vm_stat_fops,
3868 static int kvm_init_debug(void)
3871 struct kvm_stats_debugfs_item *p;
3873 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
3874 if (kvm_debugfs_dir == NULL)
3877 kvm_debugfs_num_entries = 0;
3878 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
3879 if (!debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
3880 (void *)(long)p->offset,
3881 stat_fops[p->kind]))
3888 debugfs_remove_recursive(kvm_debugfs_dir);
3893 static int kvm_suspend(void)
3895 if (kvm_usage_count)
3896 hardware_disable_nolock(NULL);
3900 static void kvm_resume(void)
3902 if (kvm_usage_count) {
3903 WARN_ON(raw_spin_is_locked(&kvm_count_lock));
3904 hardware_enable_nolock(NULL);
3908 static struct syscore_ops kvm_syscore_ops = {
3909 .suspend = kvm_suspend,
3910 .resume = kvm_resume,
3914 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
3916 return container_of(pn, struct kvm_vcpu, preempt_notifier);
3919 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
3921 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3923 if (vcpu->preempted)
3924 vcpu->preempted = false;
3926 kvm_arch_sched_in(vcpu, cpu);
3928 kvm_arch_vcpu_load(vcpu, cpu);
3931 static void kvm_sched_out(struct preempt_notifier *pn,
3932 struct task_struct *next)
3934 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3936 if (current->state == TASK_RUNNING)
3937 vcpu->preempted = true;
3938 kvm_arch_vcpu_put(vcpu);
3941 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
3942 struct module *module)
3947 r = kvm_arch_init(opaque);
3952 * kvm_arch_init makes sure there's at most one caller
3953 * for architectures that support multiple implementations,
3954 * like intel and amd on x86.
3955 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
3956 * conflicts in case kvm is already setup for another implementation.
3958 r = kvm_irqfd_init();
3962 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
3967 r = kvm_arch_hardware_setup();
3971 for_each_online_cpu(cpu) {
3972 smp_call_function_single(cpu,
3973 kvm_arch_check_processor_compat,
3979 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "AP_KVM_STARTING",
3980 kvm_starting_cpu, kvm_dying_cpu);
3983 register_reboot_notifier(&kvm_reboot_notifier);
3985 /* A kmem cache lets us meet the alignment requirements of fx_save. */
3987 vcpu_align = __alignof__(struct kvm_vcpu);
3988 kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
3989 SLAB_ACCOUNT, NULL);
3990 if (!kvm_vcpu_cache) {
3995 r = kvm_async_pf_init();
3999 kvm_chardev_ops.owner = module;
4000 kvm_vm_fops.owner = module;
4001 kvm_vcpu_fops.owner = module;
4003 r = misc_register(&kvm_dev);
4005 pr_err("kvm: misc device register failed\n");
4009 register_syscore_ops(&kvm_syscore_ops);
4011 kvm_preempt_ops.sched_in = kvm_sched_in;
4012 kvm_preempt_ops.sched_out = kvm_sched_out;
4014 r = kvm_init_debug();
4016 pr_err("kvm: create debugfs files failed\n");
4020 r = kvm_vfio_ops_init();
4026 unregister_syscore_ops(&kvm_syscore_ops);
4027 misc_deregister(&kvm_dev);
4029 kvm_async_pf_deinit();
4031 kmem_cache_destroy(kvm_vcpu_cache);
4033 unregister_reboot_notifier(&kvm_reboot_notifier);
4034 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4037 kvm_arch_hardware_unsetup();
4039 free_cpumask_var(cpus_hardware_enabled);
4047 EXPORT_SYMBOL_GPL(kvm_init);
4051 debugfs_remove_recursive(kvm_debugfs_dir);
4052 misc_deregister(&kvm_dev);
4053 kmem_cache_destroy(kvm_vcpu_cache);
4054 kvm_async_pf_deinit();
4055 unregister_syscore_ops(&kvm_syscore_ops);
4056 unregister_reboot_notifier(&kvm_reboot_notifier);
4057 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4058 on_each_cpu(hardware_disable_nolock, NULL, 1);
4059 kvm_arch_hardware_unsetup();
4062 free_cpumask_var(cpus_hardware_enabled);
4063 kvm_vfio_ops_exit();
4065 EXPORT_SYMBOL_GPL(kvm_exit);
4067 struct kvm_vm_worker_thread_context {
4069 struct task_struct *parent;
4070 struct completion init_done;
4071 kvm_vm_thread_fn_t thread_fn;
4076 static int kvm_vm_worker_thread(void *context)
4079 * The init_context is allocated on the stack of the parent thread, so
4080 * we have to locally copy anything that is needed beyond initialization
4082 struct kvm_vm_worker_thread_context *init_context = context;
4083 struct kvm *kvm = init_context->kvm;
4084 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4085 uintptr_t data = init_context->data;
4088 err = kthread_park(current);
4089 /* kthread_park(current) is never supposed to return an error */
4094 err = cgroup_attach_task_all(init_context->parent, current);
4096 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4101 set_user_nice(current, task_nice(init_context->parent));
4104 init_context->err = err;
4105 complete(&init_context->init_done);
4106 init_context = NULL;
4111 /* Wait to be woken up by the spawner before proceeding. */
4114 if (!kthread_should_stop())
4115 err = thread_fn(kvm, data);
4120 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4121 uintptr_t data, const char *name,
4122 struct task_struct **thread_ptr)
4124 struct kvm_vm_worker_thread_context init_context = {};
4125 struct task_struct *thread;
4128 init_context.kvm = kvm;
4129 init_context.parent = current;
4130 init_context.thread_fn = thread_fn;
4131 init_context.data = data;
4132 init_completion(&init_context.init_done);
4134 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4135 "%s-%d", name, task_pid_nr(current));
4137 return PTR_ERR(thread);
4139 /* kthread_run is never supposed to return NULL */
4140 WARN_ON(thread == NULL);
4142 wait_for_completion(&init_context.init_done);
4144 if (!init_context.err)
4145 *thread_ptr = thread;
4147 return init_context.err;