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 struct file_operations kvm_chardev_ops;
112 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
114 #ifdef CONFIG_KVM_COMPAT
115 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
118 static int hardware_enable_all(void);
119 static void hardware_disable_all(void);
121 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
123 static void kvm_release_pfn_dirty(kvm_pfn_t pfn);
124 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
126 __visible bool kvm_rebooting;
127 EXPORT_SYMBOL_GPL(kvm_rebooting);
129 static bool largepages_enabled = true;
131 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
132 unsigned long start, unsigned long end)
136 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
139 * The metadata used by is_zone_device_page() to determine whether or
140 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
141 * the device has been pinned, e.g. by get_user_pages(). WARN if the
142 * page_count() is zero to help detect bad usage of this helper.
144 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
147 return is_zone_device_page(pfn_to_page(pfn));
150 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
153 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
154 * perspective they are "normal" pages, albeit with slightly different
158 return PageReserved(pfn_to_page(pfn)) &&
160 !kvm_is_zone_device_pfn(pfn);
166 * Switches to specified vcpu, until a matching vcpu_put()
168 int vcpu_load(struct kvm_vcpu *vcpu)
172 if (mutex_lock_killable(&vcpu->mutex))
175 preempt_notifier_register(&vcpu->preempt_notifier);
176 kvm_arch_vcpu_load(vcpu, cpu);
180 EXPORT_SYMBOL_GPL(vcpu_load);
182 void vcpu_put(struct kvm_vcpu *vcpu)
185 kvm_arch_vcpu_put(vcpu);
186 preempt_notifier_unregister(&vcpu->preempt_notifier);
188 mutex_unlock(&vcpu->mutex);
190 EXPORT_SYMBOL_GPL(vcpu_put);
192 static void ack_flush(void *_completed)
196 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
201 struct kvm_vcpu *vcpu;
203 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
206 kvm_for_each_vcpu(i, vcpu, kvm) {
207 kvm_make_request(req, vcpu);
210 /* Set ->requests bit before we read ->mode. */
211 smp_mb__after_atomic();
213 if (cpus != NULL && cpu != -1 && cpu != me &&
214 kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
215 cpumask_set_cpu(cpu, cpus);
217 if (unlikely(cpus == NULL))
218 smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
219 else if (!cpumask_empty(cpus))
220 smp_call_function_many(cpus, ack_flush, NULL, 1);
224 free_cpumask_var(cpus);
228 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
229 void kvm_flush_remote_tlbs(struct kvm *kvm)
232 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
233 * kvm_make_all_cpus_request.
235 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
238 * We want to publish modifications to the page tables before reading
239 * mode. Pairs with a memory barrier in arch-specific code.
240 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
241 * and smp_mb in walk_shadow_page_lockless_begin/end.
242 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
244 * There is already an smp_mb__after_atomic() before
245 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
248 if (kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
249 ++kvm->stat.remote_tlb_flush;
250 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
252 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
255 void kvm_reload_remote_mmus(struct kvm *kvm)
257 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
260 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
265 mutex_init(&vcpu->mutex);
270 init_swait_queue_head(&vcpu->wq);
271 kvm_async_pf_vcpu_init(vcpu);
274 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
276 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
281 vcpu->run = page_address(page);
283 kvm_vcpu_set_in_spin_loop(vcpu, false);
284 kvm_vcpu_set_dy_eligible(vcpu, false);
285 vcpu->preempted = false;
287 r = kvm_arch_vcpu_init(vcpu);
293 free_page((unsigned long)vcpu->run);
297 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
299 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
302 kvm_arch_vcpu_uninit(vcpu);
303 free_page((unsigned long)vcpu->run);
305 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
307 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
308 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
310 return container_of(mn, struct kvm, mmu_notifier);
313 static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
314 struct mm_struct *mm,
315 unsigned long address)
317 struct kvm *kvm = mmu_notifier_to_kvm(mn);
318 int need_tlb_flush, idx;
321 * When ->invalidate_page runs, the linux pte has been zapped
322 * already but the page is still allocated until
323 * ->invalidate_page returns. So if we increase the sequence
324 * here the kvm page fault will notice if the spte can't be
325 * established because the page is going to be freed. If
326 * instead the kvm page fault establishes the spte before
327 * ->invalidate_page runs, kvm_unmap_hva will release it
330 * The sequence increase only need to be seen at spin_unlock
331 * time, and not at spin_lock time.
333 * Increasing the sequence after the spin_unlock would be
334 * unsafe because the kvm page fault could then establish the
335 * pte after kvm_unmap_hva returned, without noticing the page
336 * is going to be freed.
338 idx = srcu_read_lock(&kvm->srcu);
339 spin_lock(&kvm->mmu_lock);
341 kvm->mmu_notifier_seq++;
342 need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
343 /* we've to flush the tlb before the pages can be freed */
345 kvm_flush_remote_tlbs(kvm);
347 spin_unlock(&kvm->mmu_lock);
349 kvm_arch_mmu_notifier_invalidate_page(kvm, address);
351 srcu_read_unlock(&kvm->srcu, idx);
354 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
355 struct mm_struct *mm,
356 unsigned long address,
359 struct kvm *kvm = mmu_notifier_to_kvm(mn);
362 idx = srcu_read_lock(&kvm->srcu);
363 spin_lock(&kvm->mmu_lock);
364 kvm->mmu_notifier_seq++;
365 kvm_set_spte_hva(kvm, address, pte);
366 spin_unlock(&kvm->mmu_lock);
367 srcu_read_unlock(&kvm->srcu, idx);
370 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
371 struct mm_struct *mm,
375 struct kvm *kvm = mmu_notifier_to_kvm(mn);
376 int need_tlb_flush = 0, idx;
378 idx = srcu_read_lock(&kvm->srcu);
379 spin_lock(&kvm->mmu_lock);
381 * The count increase must become visible at unlock time as no
382 * spte can be established without taking the mmu_lock and
383 * count is also read inside the mmu_lock critical section.
385 kvm->mmu_notifier_count++;
386 need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
387 /* we've to flush the tlb before the pages can be freed */
388 if (need_tlb_flush || kvm->tlbs_dirty)
389 kvm_flush_remote_tlbs(kvm);
391 spin_unlock(&kvm->mmu_lock);
393 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
395 srcu_read_unlock(&kvm->srcu, idx);
398 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
399 struct mm_struct *mm,
403 struct kvm *kvm = mmu_notifier_to_kvm(mn);
405 spin_lock(&kvm->mmu_lock);
407 * This sequence increase will notify the kvm page fault that
408 * the page that is going to be mapped in the spte could have
411 kvm->mmu_notifier_seq++;
414 * The above sequence increase must be visible before the
415 * below count decrease, which is ensured by the smp_wmb above
416 * in conjunction with the smp_rmb in mmu_notifier_retry().
418 kvm->mmu_notifier_count--;
419 spin_unlock(&kvm->mmu_lock);
421 BUG_ON(kvm->mmu_notifier_count < 0);
424 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
425 struct mm_struct *mm,
429 struct kvm *kvm = mmu_notifier_to_kvm(mn);
432 idx = srcu_read_lock(&kvm->srcu);
433 spin_lock(&kvm->mmu_lock);
435 young = kvm_age_hva(kvm, start, end);
437 kvm_flush_remote_tlbs(kvm);
439 spin_unlock(&kvm->mmu_lock);
440 srcu_read_unlock(&kvm->srcu, idx);
445 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
446 struct mm_struct *mm,
450 struct kvm *kvm = mmu_notifier_to_kvm(mn);
453 idx = srcu_read_lock(&kvm->srcu);
454 spin_lock(&kvm->mmu_lock);
456 * Even though we do not flush TLB, this will still adversely
457 * affect performance on pre-Haswell Intel EPT, where there is
458 * no EPT Access Bit to clear so that we have to tear down EPT
459 * tables instead. If we find this unacceptable, we can always
460 * add a parameter to kvm_age_hva so that it effectively doesn't
461 * do anything on clear_young.
463 * Also note that currently we never issue secondary TLB flushes
464 * from clear_young, leaving this job up to the regular system
465 * cadence. If we find this inaccurate, we might come up with a
466 * more sophisticated heuristic later.
468 young = kvm_age_hva(kvm, start, end);
469 spin_unlock(&kvm->mmu_lock);
470 srcu_read_unlock(&kvm->srcu, idx);
475 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
476 struct mm_struct *mm,
477 unsigned long address)
479 struct kvm *kvm = mmu_notifier_to_kvm(mn);
482 idx = srcu_read_lock(&kvm->srcu);
483 spin_lock(&kvm->mmu_lock);
484 young = kvm_test_age_hva(kvm, address);
485 spin_unlock(&kvm->mmu_lock);
486 srcu_read_unlock(&kvm->srcu, idx);
491 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
492 struct mm_struct *mm)
494 struct kvm *kvm = mmu_notifier_to_kvm(mn);
497 idx = srcu_read_lock(&kvm->srcu);
498 kvm_arch_flush_shadow_all(kvm);
499 srcu_read_unlock(&kvm->srcu, idx);
502 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
503 .invalidate_page = kvm_mmu_notifier_invalidate_page,
504 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
505 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
506 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
507 .clear_young = kvm_mmu_notifier_clear_young,
508 .test_young = kvm_mmu_notifier_test_young,
509 .change_pte = kvm_mmu_notifier_change_pte,
510 .release = kvm_mmu_notifier_release,
513 static int kvm_init_mmu_notifier(struct kvm *kvm)
515 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
516 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
519 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
521 static int kvm_init_mmu_notifier(struct kvm *kvm)
526 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
528 static struct kvm_memslots *kvm_alloc_memslots(void)
531 struct kvm_memslots *slots;
533 slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
538 * Init kvm generation close to the maximum to easily test the
539 * code of handling generation number wrap-around.
541 slots->generation = -150;
542 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
543 slots->id_to_index[i] = slots->memslots[i].id = i;
548 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
550 if (!memslot->dirty_bitmap)
553 kvfree(memslot->dirty_bitmap);
554 memslot->dirty_bitmap = NULL;
558 * Free any memory in @free but not in @dont.
560 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
561 struct kvm_memory_slot *dont)
563 if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
564 kvm_destroy_dirty_bitmap(free);
566 kvm_arch_free_memslot(kvm, free, dont);
571 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
573 struct kvm_memory_slot *memslot;
578 kvm_for_each_memslot(memslot, slots)
579 kvm_free_memslot(kvm, memslot, NULL);
584 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
588 if (!kvm->debugfs_dentry)
591 debugfs_remove_recursive(kvm->debugfs_dentry);
593 if (kvm->debugfs_stat_data) {
594 for (i = 0; i < kvm_debugfs_num_entries; i++)
595 kfree(kvm->debugfs_stat_data[i]);
596 kfree(kvm->debugfs_stat_data);
600 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
602 char dir_name[ITOA_MAX_LEN * 2];
603 struct kvm_stat_data *stat_data;
604 struct kvm_stats_debugfs_item *p;
606 if (!debugfs_initialized())
609 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
610 kvm->debugfs_dentry = debugfs_create_dir(dir_name,
612 if (!kvm->debugfs_dentry)
615 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
616 sizeof(*kvm->debugfs_stat_data),
618 if (!kvm->debugfs_stat_data)
621 for (p = debugfs_entries; p->name; p++) {
622 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
626 stat_data->kvm = kvm;
627 stat_data->offset = p->offset;
628 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
629 if (!debugfs_create_file(p->name, 0444,
632 stat_fops_per_vm[p->kind]))
639 * Called after the VM is otherwise initialized, but just before adding it to
642 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
648 * Called just after removing the VM from the vm_list, but before doing any
651 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
655 static struct kvm *kvm_create_vm(unsigned long type)
658 struct kvm *kvm = kvm_arch_alloc_vm();
661 return ERR_PTR(-ENOMEM);
663 spin_lock_init(&kvm->mmu_lock);
664 atomic_inc(¤t->mm->mm_count);
665 kvm->mm = current->mm;
666 kvm_eventfd_init(kvm);
667 mutex_init(&kvm->lock);
668 mutex_init(&kvm->irq_lock);
669 mutex_init(&kvm->slots_lock);
670 atomic_set(&kvm->users_count, 1);
671 INIT_LIST_HEAD(&kvm->devices);
673 r = kvm_arch_init_vm(kvm, type);
675 goto out_err_no_disable;
677 r = hardware_enable_all();
679 goto out_err_no_disable;
681 #ifdef CONFIG_HAVE_KVM_IRQFD
682 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
685 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
688 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
689 kvm->memslots[i] = kvm_alloc_memslots();
690 if (!kvm->memslots[i])
691 goto out_err_no_srcu;
694 if (init_srcu_struct(&kvm->srcu))
695 goto out_err_no_srcu;
696 if (init_srcu_struct(&kvm->irq_srcu))
697 goto out_err_no_irq_srcu;
698 for (i = 0; i < KVM_NR_BUSES; i++) {
699 kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
702 goto out_err_no_mmu_notifier;
705 r = kvm_init_mmu_notifier(kvm);
707 goto out_err_no_mmu_notifier;
709 r = kvm_arch_post_init_vm(kvm);
713 mutex_lock(&kvm_lock);
714 list_add(&kvm->vm_list, &vm_list);
715 mutex_unlock(&kvm_lock);
717 preempt_notifier_inc();
720 * When the fd passed to this ioctl() is opened it pins the module,
721 * but try_module_get() also prevents getting a reference if the module
722 * is in MODULE_STATE_GOING (e.g. if someone ran "rmmod --wait").
724 if (!try_module_get(kvm_chardev_ops.owner)) {
732 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
733 if (kvm->mmu_notifier.ops)
734 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
736 out_err_no_mmu_notifier:
737 cleanup_srcu_struct(&kvm->irq_srcu);
739 cleanup_srcu_struct(&kvm->srcu);
741 hardware_disable_all();
743 for (i = 0; i < KVM_NR_BUSES; i++)
744 kfree(kvm->buses[i]);
745 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
746 kvm_free_memslots(kvm, kvm->memslots[i]);
747 kvm_arch_free_vm(kvm);
753 * Avoid using vmalloc for a small buffer.
754 * Should not be used when the size is statically known.
756 void *kvm_kvzalloc(unsigned long size)
758 if (size > PAGE_SIZE)
759 return vzalloc(size);
761 return kzalloc(size, GFP_KERNEL);
764 static void kvm_destroy_devices(struct kvm *kvm)
766 struct kvm_device *dev, *tmp;
769 * We do not need to take the kvm->lock here, because nobody else
770 * has a reference to the struct kvm at this point and therefore
771 * cannot access the devices list anyhow.
773 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
774 list_del(&dev->vm_node);
775 dev->ops->destroy(dev);
779 static void kvm_destroy_vm(struct kvm *kvm)
782 struct mm_struct *mm = kvm->mm;
784 kvm_destroy_vm_debugfs(kvm);
785 kvm_arch_sync_events(kvm);
786 mutex_lock(&kvm_lock);
787 list_del(&kvm->vm_list);
788 mutex_unlock(&kvm_lock);
789 kvm_arch_pre_destroy_vm(kvm);
791 kvm_free_irq_routing(kvm);
792 for (i = 0; i < KVM_NR_BUSES; i++) {
794 kvm_io_bus_destroy(kvm->buses[i]);
795 kvm->buses[i] = NULL;
797 kvm_coalesced_mmio_free(kvm);
798 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
799 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
801 kvm_arch_flush_shadow_all(kvm);
803 kvm_arch_destroy_vm(kvm);
804 kvm_destroy_devices(kvm);
805 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
806 kvm_free_memslots(kvm, kvm->memslots[i]);
807 cleanup_srcu_struct(&kvm->irq_srcu);
808 cleanup_srcu_struct(&kvm->srcu);
809 kvm_arch_free_vm(kvm);
810 preempt_notifier_dec();
811 hardware_disable_all();
813 module_put(kvm_chardev_ops.owner);
816 void kvm_get_kvm(struct kvm *kvm)
818 atomic_inc(&kvm->users_count);
820 EXPORT_SYMBOL_GPL(kvm_get_kvm);
822 void kvm_put_kvm(struct kvm *kvm)
824 if (atomic_dec_and_test(&kvm->users_count))
827 EXPORT_SYMBOL_GPL(kvm_put_kvm);
830 static int kvm_vm_release(struct inode *inode, struct file *filp)
832 struct kvm *kvm = filp->private_data;
834 kvm_irqfd_release(kvm);
841 * Allocation size is twice as large as the actual dirty bitmap size.
842 * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
844 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
846 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
848 memslot->dirty_bitmap = kvm_kvzalloc(dirty_bytes);
849 if (!memslot->dirty_bitmap)
856 * Insert memslot and re-sort memslots based on their GFN,
857 * so binary search could be used to lookup GFN.
858 * Sorting algorithm takes advantage of having initially
859 * sorted array and known changed memslot position.
861 static void update_memslots(struct kvm_memslots *slots,
862 struct kvm_memory_slot *new)
865 int i = slots->id_to_index[id];
866 struct kvm_memory_slot *mslots = slots->memslots;
868 WARN_ON(mslots[i].id != id);
870 WARN_ON(!mslots[i].npages);
871 if (mslots[i].npages)
874 if (!mslots[i].npages)
878 while (i < KVM_MEM_SLOTS_NUM - 1 &&
879 new->base_gfn <= mslots[i + 1].base_gfn) {
880 if (!mslots[i + 1].npages)
882 mslots[i] = mslots[i + 1];
883 slots->id_to_index[mslots[i].id] = i;
888 * The ">=" is needed when creating a slot with base_gfn == 0,
889 * so that it moves before all those with base_gfn == npages == 0.
891 * On the other hand, if new->npages is zero, the above loop has
892 * already left i pointing to the beginning of the empty part of
893 * mslots, and the ">=" would move the hole backwards in this
894 * case---which is wrong. So skip the loop when deleting a slot.
898 new->base_gfn >= mslots[i - 1].base_gfn) {
899 mslots[i] = mslots[i - 1];
900 slots->id_to_index[mslots[i].id] = i;
904 WARN_ON_ONCE(i != slots->used_slots);
907 slots->id_to_index[mslots[i].id] = i;
910 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
912 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
914 #ifdef __KVM_HAVE_READONLY_MEM
915 valid_flags |= KVM_MEM_READONLY;
918 if (mem->flags & ~valid_flags)
924 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
925 int as_id, struct kvm_memslots *slots)
927 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
930 * Set the low bit in the generation, which disables SPTE caching
931 * until the end of synchronize_srcu_expedited.
933 WARN_ON(old_memslots->generation & 1);
934 slots->generation = old_memslots->generation + 1;
936 rcu_assign_pointer(kvm->memslots[as_id], slots);
937 synchronize_srcu_expedited(&kvm->srcu);
940 * Increment the new memslot generation a second time. This prevents
941 * vm exits that race with memslot updates from caching a memslot
942 * generation that will (potentially) be valid forever.
946 kvm_arch_memslots_updated(kvm, slots);
952 * Allocate some memory and give it an address in the guest physical address
955 * Discontiguous memory is allowed, mostly for framebuffers.
957 * Must be called holding kvm->slots_lock for write.
959 int __kvm_set_memory_region(struct kvm *kvm,
960 const struct kvm_userspace_memory_region *mem)
964 unsigned long npages;
965 struct kvm_memory_slot *slot;
966 struct kvm_memory_slot old, new;
967 struct kvm_memslots *slots = NULL, *old_memslots;
969 enum kvm_mr_change change;
971 r = check_memory_region_flags(mem);
976 as_id = mem->slot >> 16;
979 /* General sanity checks */
980 if (mem->memory_size & (PAGE_SIZE - 1))
982 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
984 /* We can read the guest memory with __xxx_user() later on. */
985 if ((id < KVM_USER_MEM_SLOTS) &&
986 ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
987 !access_ok(VERIFY_WRITE,
988 (void __user *)(unsigned long)mem->userspace_addr,
991 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
993 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
996 slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
997 base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
998 npages = mem->memory_size >> PAGE_SHIFT;
1000 if (npages > KVM_MEM_MAX_NR_PAGES)
1006 new.base_gfn = base_gfn;
1007 new.npages = npages;
1008 new.flags = mem->flags;
1012 change = KVM_MR_CREATE;
1013 else { /* Modify an existing slot. */
1014 if ((mem->userspace_addr != old.userspace_addr) ||
1015 (npages != old.npages) ||
1016 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1019 if (base_gfn != old.base_gfn)
1020 change = KVM_MR_MOVE;
1021 else if (new.flags != old.flags)
1022 change = KVM_MR_FLAGS_ONLY;
1023 else { /* Nothing to change. */
1032 change = KVM_MR_DELETE;
1037 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1038 /* Check for overlaps */
1040 kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
1043 if (!((base_gfn + npages <= slot->base_gfn) ||
1044 (base_gfn >= slot->base_gfn + slot->npages)))
1049 /* Free page dirty bitmap if unneeded */
1050 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1051 new.dirty_bitmap = NULL;
1054 if (change == KVM_MR_CREATE) {
1055 new.userspace_addr = mem->userspace_addr;
1057 if (kvm_arch_create_memslot(kvm, &new, npages))
1061 /* Allocate page dirty bitmap if needed */
1062 if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1063 if (kvm_create_dirty_bitmap(&new) < 0)
1067 slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
1070 memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
1072 if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
1073 slot = id_to_memslot(slots, id);
1074 slot->flags |= KVM_MEMSLOT_INVALID;
1076 old_memslots = install_new_memslots(kvm, as_id, slots);
1078 /* slot was deleted or moved, clear iommu mapping */
1079 kvm_iommu_unmap_pages(kvm, &old);
1080 /* From this point no new shadow pages pointing to a deleted,
1081 * or moved, memslot will be created.
1083 * validation of sp->gfn happens in:
1084 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1085 * - kvm_is_visible_gfn (mmu_check_roots)
1087 kvm_arch_flush_shadow_memslot(kvm, slot);
1090 * We can re-use the old_memslots from above, the only difference
1091 * from the currently installed memslots is the invalid flag. This
1092 * will get overwritten by update_memslots anyway.
1094 slots = old_memslots;
1097 r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
1101 /* actual memory is freed via old in kvm_free_memslot below */
1102 if (change == KVM_MR_DELETE) {
1103 new.dirty_bitmap = NULL;
1104 memset(&new.arch, 0, sizeof(new.arch));
1107 update_memslots(slots, &new);
1108 old_memslots = install_new_memslots(kvm, as_id, slots);
1110 kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
1112 kvm_free_memslot(kvm, &old, &new);
1113 kvfree(old_memslots);
1116 * IOMMU mapping: New slots need to be mapped. Old slots need to be
1117 * un-mapped and re-mapped if their base changes. Since base change
1118 * unmapping is handled above with slot deletion, mapping alone is
1119 * needed here. Anything else the iommu might care about for existing
1120 * slots (size changes, userspace addr changes and read-only flag
1121 * changes) is disallowed above, so any other attribute changes getting
1122 * here can be skipped.
1124 if (as_id == 0 && (change == KVM_MR_CREATE || change == KVM_MR_MOVE)) {
1125 r = kvm_iommu_map_pages(kvm, &new);
1134 kvm_free_memslot(kvm, &new, &old);
1138 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1140 int kvm_set_memory_region(struct kvm *kvm,
1141 const struct kvm_userspace_memory_region *mem)
1145 mutex_lock(&kvm->slots_lock);
1146 r = __kvm_set_memory_region(kvm, mem);
1147 mutex_unlock(&kvm->slots_lock);
1150 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1152 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1153 struct kvm_userspace_memory_region *mem)
1155 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1158 return kvm_set_memory_region(kvm, mem);
1161 int kvm_get_dirty_log(struct kvm *kvm,
1162 struct kvm_dirty_log *log, int *is_dirty)
1164 struct kvm_memslots *slots;
1165 struct kvm_memory_slot *memslot;
1166 int r, i, as_id, id;
1168 unsigned long any = 0;
1171 as_id = log->slot >> 16;
1172 id = (u16)log->slot;
1173 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1176 slots = __kvm_memslots(kvm, as_id);
1177 memslot = id_to_memslot(slots, id);
1179 if (!memslot->dirty_bitmap)
1182 n = kvm_dirty_bitmap_bytes(memslot);
1184 for (i = 0; !any && i < n/sizeof(long); ++i)
1185 any = memslot->dirty_bitmap[i];
1188 if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1198 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1200 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1202 * kvm_get_dirty_log_protect - get a snapshot of dirty pages, and if any pages
1203 * are dirty write protect them for next write.
1204 * @kvm: pointer to kvm instance
1205 * @log: slot id and address to which we copy the log
1206 * @is_dirty: flag set if any page is dirty
1208 * We need to keep it in mind that VCPU threads can write to the bitmap
1209 * concurrently. So, to avoid losing track of dirty pages we keep the
1212 * 1. Take a snapshot of the bit and clear it if needed.
1213 * 2. Write protect the corresponding page.
1214 * 3. Copy the snapshot to the userspace.
1215 * 4. Upon return caller flushes TLB's if needed.
1217 * Between 2 and 4, the guest may write to the page using the remaining TLB
1218 * entry. This is not a problem because the page is reported dirty using
1219 * the snapshot taken before and step 4 ensures that writes done after
1220 * exiting to userspace will be logged for the next call.
1223 int kvm_get_dirty_log_protect(struct kvm *kvm,
1224 struct kvm_dirty_log *log, bool *is_dirty)
1226 struct kvm_memslots *slots;
1227 struct kvm_memory_slot *memslot;
1228 int r, i, as_id, id;
1230 unsigned long *dirty_bitmap;
1231 unsigned long *dirty_bitmap_buffer;
1234 as_id = log->slot >> 16;
1235 id = (u16)log->slot;
1236 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1239 slots = __kvm_memslots(kvm, as_id);
1240 memslot = id_to_memslot(slots, id);
1242 dirty_bitmap = memslot->dirty_bitmap;
1247 n = kvm_dirty_bitmap_bytes(memslot);
1249 dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
1250 memset(dirty_bitmap_buffer, 0, n);
1252 spin_lock(&kvm->mmu_lock);
1254 for (i = 0; i < n / sizeof(long); i++) {
1258 if (!dirty_bitmap[i])
1263 mask = xchg(&dirty_bitmap[i], 0);
1264 dirty_bitmap_buffer[i] = mask;
1267 offset = i * BITS_PER_LONG;
1268 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1273 spin_unlock(&kvm->mmu_lock);
1276 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1283 EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
1286 bool kvm_largepages_enabled(void)
1288 return largepages_enabled;
1291 void kvm_disable_largepages(void)
1293 largepages_enabled = false;
1295 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1297 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1299 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1301 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1303 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1305 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1308 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1310 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1312 if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1313 memslot->flags & KVM_MEMSLOT_INVALID)
1318 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1320 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
1322 struct vm_area_struct *vma;
1323 unsigned long addr, size;
1327 addr = gfn_to_hva(kvm, gfn);
1328 if (kvm_is_error_hva(addr))
1331 down_read(¤t->mm->mmap_sem);
1332 vma = find_vma(current->mm, addr);
1336 size = vma_kernel_pagesize(vma);
1339 up_read(¤t->mm->mmap_sem);
1344 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1346 return slot->flags & KVM_MEM_READONLY;
1349 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1350 gfn_t *nr_pages, bool write)
1352 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1353 return KVM_HVA_ERR_BAD;
1355 if (memslot_is_readonly(slot) && write)
1356 return KVM_HVA_ERR_RO_BAD;
1359 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1361 return __gfn_to_hva_memslot(slot, gfn);
1364 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1367 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1370 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1373 return gfn_to_hva_many(slot, gfn, NULL);
1375 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1377 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1379 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1381 EXPORT_SYMBOL_GPL(gfn_to_hva);
1383 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1385 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1387 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1390 * If writable is set to false, the hva returned by this function is only
1391 * allowed to be read.
1393 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1394 gfn_t gfn, bool *writable)
1396 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1398 if (!kvm_is_error_hva(hva) && writable)
1399 *writable = !memslot_is_readonly(slot);
1404 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1406 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1408 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1411 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1413 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1415 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1418 static int get_user_page_nowait(unsigned long start, int write,
1421 int flags = FOLL_NOWAIT | FOLL_HWPOISON;
1424 flags |= FOLL_WRITE;
1426 return get_user_pages(start, 1, flags, page, NULL);
1429 static inline int check_user_page_hwpoison(unsigned long addr)
1431 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1433 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1434 return rc == -EHWPOISON;
1438 * The atomic path to get the writable pfn which will be stored in @pfn,
1439 * true indicates success, otherwise false is returned.
1441 static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
1442 bool write_fault, bool *writable, kvm_pfn_t *pfn)
1444 struct page *page[1];
1447 if (!(async || atomic))
1451 * Fast pin a writable pfn only if it is a write fault request
1452 * or the caller allows to map a writable pfn for a read fault
1455 if (!(write_fault || writable))
1458 npages = __get_user_pages_fast(addr, 1, 1, page);
1460 *pfn = page_to_pfn(page[0]);
1471 * The slow path to get the pfn of the specified host virtual address,
1472 * 1 indicates success, -errno is returned if error is detected.
1474 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1475 bool *writable, kvm_pfn_t *pfn)
1477 struct page *page[1];
1483 *writable = write_fault;
1486 down_read(¤t->mm->mmap_sem);
1487 npages = get_user_page_nowait(addr, write_fault, page);
1488 up_read(¤t->mm->mmap_sem);
1490 unsigned int flags = FOLL_TOUCH | FOLL_HWPOISON;
1493 flags |= FOLL_WRITE;
1495 npages = __get_user_pages_unlocked(current, current->mm, addr, 1,
1501 /* map read fault as writable if possible */
1502 if (unlikely(!write_fault) && writable) {
1503 struct page *wpage[1];
1505 npages = __get_user_pages_fast(addr, 1, 1, wpage);
1514 *pfn = page_to_pfn(page[0]);
1518 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1520 if (unlikely(!(vma->vm_flags & VM_READ)))
1523 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1529 static int kvm_try_get_pfn(kvm_pfn_t pfn)
1531 if (kvm_is_reserved_pfn(pfn))
1533 return get_page_unless_zero(pfn_to_page(pfn));
1536 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1537 unsigned long addr, bool *async,
1538 bool write_fault, bool *writable,
1546 r = follow_pte_pmd(vma->vm_mm, addr, &ptep, NULL, &ptl);
1549 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1550 * not call the fault handler, so do it here.
1552 bool unlocked = false;
1553 r = fixup_user_fault(current, current->mm, addr,
1554 (write_fault ? FAULT_FLAG_WRITE : 0),
1561 r = follow_pte_pmd(vma->vm_mm, addr, &ptep, NULL, &ptl);
1566 if (write_fault && !pte_write(*ptep)) {
1567 pfn = KVM_PFN_ERR_RO_FAULT;
1572 *writable = pte_write(*ptep);
1573 pfn = pte_pfn(*ptep);
1576 * Get a reference here because callers of *hva_to_pfn* and
1577 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1578 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1579 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1580 * simply do nothing for reserved pfns.
1582 * Whoever called remap_pfn_range is also going to call e.g.
1583 * unmap_mapping_range before the underlying pages are freed,
1584 * causing a call to our MMU notifier.
1586 * Certain IO or PFNMAP mappings can be backed with valid
1587 * struct pages, but be allocated without refcounting e.g.,
1588 * tail pages of non-compound higher order allocations, which
1589 * would then underflow the refcount when the caller does the
1590 * required put_page. Don't allow those pages here.
1592 if (!kvm_try_get_pfn(pfn))
1596 pte_unmap_unlock(ptep, ptl);
1603 * Pin guest page in memory and return its pfn.
1604 * @addr: host virtual address which maps memory to the guest
1605 * @atomic: whether this function can sleep
1606 * @async: whether this function need to wait IO complete if the
1607 * host page is not in the memory
1608 * @write_fault: whether we should get a writable host page
1609 * @writable: whether it allows to map a writable host page for !@write_fault
1611 * The function will map a writable host page for these two cases:
1612 * 1): @write_fault = true
1613 * 2): @write_fault = false && @writable, @writable will tell the caller
1614 * whether the mapping is writable.
1616 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1617 bool write_fault, bool *writable)
1619 struct vm_area_struct *vma;
1623 /* we can do it either atomically or asynchronously, not both */
1624 BUG_ON(atomic && async);
1626 if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
1630 return KVM_PFN_ERR_FAULT;
1632 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1636 down_read(¤t->mm->mmap_sem);
1637 if (npages == -EHWPOISON ||
1638 (!async && check_user_page_hwpoison(addr))) {
1639 pfn = KVM_PFN_ERR_HWPOISON;
1644 vma = find_vma_intersection(current->mm, addr, addr + 1);
1647 pfn = KVM_PFN_ERR_FAULT;
1648 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1649 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1653 pfn = KVM_PFN_ERR_FAULT;
1655 if (async && vma_is_valid(vma, write_fault))
1657 pfn = KVM_PFN_ERR_FAULT;
1660 up_read(¤t->mm->mmap_sem);
1664 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1665 bool atomic, bool *async, bool write_fault,
1668 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1670 if (addr == KVM_HVA_ERR_RO_BAD) {
1673 return KVM_PFN_ERR_RO_FAULT;
1676 if (kvm_is_error_hva(addr)) {
1679 return KVM_PFN_NOSLOT;
1682 /* Do not map writable pfn in the readonly memslot. */
1683 if (writable && memslot_is_readonly(slot)) {
1688 return hva_to_pfn(addr, atomic, async, write_fault,
1691 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1693 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1696 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1697 write_fault, writable);
1699 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1701 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1703 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1705 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1707 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1709 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1711 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1713 kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1715 return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1717 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1719 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1721 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1723 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1725 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1727 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1729 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1731 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1733 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1735 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1737 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1738 struct page **pages, int nr_pages)
1743 addr = gfn_to_hva_many(slot, gfn, &entry);
1744 if (kvm_is_error_hva(addr))
1747 if (entry < nr_pages)
1750 return __get_user_pages_fast(addr, nr_pages, 1, pages);
1752 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1754 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
1756 if (is_error_noslot_pfn(pfn))
1757 return KVM_ERR_PTR_BAD_PAGE;
1759 if (kvm_is_reserved_pfn(pfn)) {
1761 return KVM_ERR_PTR_BAD_PAGE;
1764 return pfn_to_page(pfn);
1767 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1771 pfn = gfn_to_pfn(kvm, gfn);
1773 return kvm_pfn_to_page(pfn);
1775 EXPORT_SYMBOL_GPL(gfn_to_page);
1777 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
1781 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
1783 return kvm_pfn_to_page(pfn);
1785 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
1787 void kvm_release_page_clean(struct page *page)
1789 WARN_ON(is_error_page(page));
1791 kvm_release_pfn_clean(page_to_pfn(page));
1793 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1795 void kvm_release_pfn_clean(kvm_pfn_t pfn)
1797 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
1798 put_page(pfn_to_page(pfn));
1800 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1802 void kvm_release_page_dirty(struct page *page)
1804 WARN_ON(is_error_page(page));
1806 kvm_release_pfn_dirty(page_to_pfn(page));
1808 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1810 static void kvm_release_pfn_dirty(kvm_pfn_t pfn)
1812 kvm_set_pfn_dirty(pfn);
1813 kvm_release_pfn_clean(pfn);
1816 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
1818 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn)) {
1819 struct page *page = pfn_to_page(pfn);
1821 if (!PageReserved(page))
1825 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1827 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
1829 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
1830 mark_page_accessed(pfn_to_page(pfn));
1832 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1834 void kvm_get_pfn(kvm_pfn_t pfn)
1836 if (!kvm_is_reserved_pfn(pfn))
1837 get_page(pfn_to_page(pfn));
1839 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1841 static int next_segment(unsigned long len, int offset)
1843 if (len > PAGE_SIZE - offset)
1844 return PAGE_SIZE - offset;
1849 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
1850 void *data, int offset, int len)
1855 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1856 if (kvm_is_error_hva(addr))
1858 r = __copy_from_user(data, (void __user *)addr + offset, len);
1864 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1867 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1869 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1871 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1873 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
1874 int offset, int len)
1876 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1878 return __kvm_read_guest_page(slot, gfn, data, offset, len);
1880 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
1882 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1884 gfn_t gfn = gpa >> PAGE_SHIFT;
1886 int offset = offset_in_page(gpa);
1889 while ((seg = next_segment(len, offset)) != 0) {
1890 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1900 EXPORT_SYMBOL_GPL(kvm_read_guest);
1902 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
1904 gfn_t gfn = gpa >> PAGE_SHIFT;
1906 int offset = offset_in_page(gpa);
1909 while ((seg = next_segment(len, offset)) != 0) {
1910 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
1920 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
1922 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1923 void *data, int offset, unsigned long len)
1928 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1929 if (kvm_is_error_hva(addr))
1931 pagefault_disable();
1932 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1939 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1942 gfn_t gfn = gpa >> PAGE_SHIFT;
1943 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1944 int offset = offset_in_page(gpa);
1946 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1948 EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
1950 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
1951 void *data, unsigned long len)
1953 gfn_t gfn = gpa >> PAGE_SHIFT;
1954 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1955 int offset = offset_in_page(gpa);
1957 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1959 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
1961 static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
1962 const void *data, int offset, int len)
1967 addr = gfn_to_hva_memslot(memslot, gfn);
1968 if (kvm_is_error_hva(addr))
1970 r = __copy_to_user((void __user *)addr + offset, data, len);
1973 mark_page_dirty_in_slot(memslot, gfn);
1977 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
1978 const void *data, int offset, int len)
1980 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1982 return __kvm_write_guest_page(slot, gfn, data, offset, len);
1984 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1986 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
1987 const void *data, int offset, int len)
1989 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1991 return __kvm_write_guest_page(slot, gfn, data, offset, len);
1993 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
1995 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1998 gfn_t gfn = gpa >> PAGE_SHIFT;
2000 int offset = offset_in_page(gpa);
2003 while ((seg = next_segment(len, offset)) != 0) {
2004 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2014 EXPORT_SYMBOL_GPL(kvm_write_guest);
2016 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2019 gfn_t gfn = gpa >> PAGE_SHIFT;
2021 int offset = offset_in_page(gpa);
2024 while ((seg = next_segment(len, offset)) != 0) {
2025 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2035 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2037 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2038 gpa_t gpa, unsigned long len)
2040 struct kvm_memslots *slots = kvm_memslots(kvm);
2041 int offset = offset_in_page(gpa);
2042 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2043 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2044 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2045 gfn_t nr_pages_avail;
2048 ghc->generation = slots->generation;
2050 ghc->memslot = gfn_to_memslot(kvm, start_gfn);
2051 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, NULL);
2052 if (!kvm_is_error_hva(ghc->hva) && nr_pages_needed <= 1) {
2056 * If the requested region crosses two memslots, we still
2057 * verify that the entire region is valid here.
2059 while (start_gfn <= end_gfn) {
2060 ghc->memslot = gfn_to_memslot(kvm, start_gfn);
2061 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2063 if (kvm_is_error_hva(ghc->hva))
2065 start_gfn += nr_pages_avail;
2067 /* Use the slow path for cross page reads and writes. */
2068 ghc->memslot = NULL;
2072 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2074 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2075 void *data, unsigned long len)
2077 struct kvm_memslots *slots = kvm_memslots(kvm);
2080 BUG_ON(len > ghc->len);
2082 if (slots->generation != ghc->generation)
2083 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
2085 if (kvm_is_error_hva(ghc->hva))
2088 if (unlikely(!ghc->memslot))
2089 return kvm_write_guest(kvm, ghc->gpa, data, len);
2091 r = __copy_to_user((void __user *)ghc->hva, data, len);
2094 mark_page_dirty_in_slot(ghc->memslot, ghc->gpa >> PAGE_SHIFT);
2098 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2100 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2101 void *data, unsigned long len)
2103 struct kvm_memslots *slots = kvm_memslots(kvm);
2106 BUG_ON(len > ghc->len);
2108 if (slots->generation != ghc->generation)
2109 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
2111 if (kvm_is_error_hva(ghc->hva))
2114 if (unlikely(!ghc->memslot))
2115 return kvm_read_guest(kvm, ghc->gpa, data, len);
2117 r = __copy_from_user(data, (void __user *)ghc->hva, len);
2123 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2125 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2127 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2129 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2131 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2133 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2135 gfn_t gfn = gpa >> PAGE_SHIFT;
2137 int offset = offset_in_page(gpa);
2140 while ((seg = next_segment(len, offset)) != 0) {
2141 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2150 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2152 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2155 if (memslot && memslot->dirty_bitmap) {
2156 unsigned long rel_gfn = gfn - memslot->base_gfn;
2158 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2162 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2164 struct kvm_memory_slot *memslot;
2166 memslot = gfn_to_memslot(kvm, gfn);
2167 mark_page_dirty_in_slot(memslot, gfn);
2169 EXPORT_SYMBOL_GPL(mark_page_dirty);
2171 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2173 struct kvm_memory_slot *memslot;
2175 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2176 mark_page_dirty_in_slot(memslot, gfn);
2178 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2180 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2182 unsigned int old, val, grow;
2184 old = val = vcpu->halt_poll_ns;
2185 grow = READ_ONCE(halt_poll_ns_grow);
2187 if (val == 0 && grow)
2192 if (val > halt_poll_ns)
2195 vcpu->halt_poll_ns = val;
2196 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2199 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2201 unsigned int old, val, shrink;
2203 old = val = vcpu->halt_poll_ns;
2204 shrink = READ_ONCE(halt_poll_ns_shrink);
2210 vcpu->halt_poll_ns = val;
2211 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2214 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2216 if (kvm_arch_vcpu_runnable(vcpu)) {
2217 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2220 if (kvm_cpu_has_pending_timer(vcpu))
2222 if (signal_pending(current))
2229 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2231 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2234 DECLARE_SWAITQUEUE(wait);
2235 bool waited = false;
2238 start = cur = ktime_get();
2239 if (vcpu->halt_poll_ns) {
2240 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2242 ++vcpu->stat.halt_attempted_poll;
2245 * This sets KVM_REQ_UNHALT if an interrupt
2248 if (kvm_vcpu_check_block(vcpu) < 0) {
2249 ++vcpu->stat.halt_successful_poll;
2250 if (!vcpu_valid_wakeup(vcpu))
2251 ++vcpu->stat.halt_poll_invalid;
2255 } while (single_task_running() && ktime_before(cur, stop));
2258 kvm_arch_vcpu_blocking(vcpu);
2261 prepare_to_swait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2263 if (kvm_vcpu_check_block(vcpu) < 0)
2270 finish_swait(&vcpu->wq, &wait);
2273 kvm_arch_vcpu_unblocking(vcpu);
2275 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2277 if (!vcpu_valid_wakeup(vcpu))
2278 shrink_halt_poll_ns(vcpu);
2279 else if (halt_poll_ns) {
2280 if (block_ns <= vcpu->halt_poll_ns)
2282 /* we had a long block, shrink polling */
2283 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2284 shrink_halt_poll_ns(vcpu);
2285 /* we had a short halt and our poll time is too small */
2286 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2287 block_ns < halt_poll_ns)
2288 grow_halt_poll_ns(vcpu);
2290 vcpu->halt_poll_ns = 0;
2292 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2293 kvm_arch_vcpu_block_finish(vcpu);
2295 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2298 void kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2300 struct swait_queue_head *wqp;
2302 wqp = kvm_arch_vcpu_wq(vcpu);
2303 if (swait_active(wqp)) {
2305 ++vcpu->stat.halt_wakeup;
2309 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2312 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2314 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2317 int cpu = vcpu->cpu;
2319 kvm_vcpu_wake_up(vcpu);
2321 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2322 if (kvm_arch_vcpu_should_kick(vcpu))
2323 smp_send_reschedule(cpu);
2326 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2327 #endif /* !CONFIG_S390 */
2329 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2332 struct task_struct *task = NULL;
2336 pid = rcu_dereference(target->pid);
2338 task = get_pid_task(pid, PIDTYPE_PID);
2342 ret = yield_to(task, 1);
2343 put_task_struct(task);
2347 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2350 * Helper that checks whether a VCPU is eligible for directed yield.
2351 * Most eligible candidate to yield is decided by following heuristics:
2353 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2354 * (preempted lock holder), indicated by @in_spin_loop.
2355 * Set at the beiginning and cleared at the end of interception/PLE handler.
2357 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2358 * chance last time (mostly it has become eligible now since we have probably
2359 * yielded to lockholder in last iteration. This is done by toggling
2360 * @dy_eligible each time a VCPU checked for eligibility.)
2362 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2363 * to preempted lock-holder could result in wrong VCPU selection and CPU
2364 * burning. Giving priority for a potential lock-holder increases lock
2367 * Since algorithm is based on heuristics, accessing another VCPU data without
2368 * locking does not harm. It may result in trying to yield to same VCPU, fail
2369 * and continue with next VCPU and so on.
2371 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2373 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2376 eligible = !vcpu->spin_loop.in_spin_loop ||
2377 vcpu->spin_loop.dy_eligible;
2379 if (vcpu->spin_loop.in_spin_loop)
2380 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2388 void kvm_vcpu_on_spin(struct kvm_vcpu *me)
2390 struct kvm *kvm = me->kvm;
2391 struct kvm_vcpu *vcpu;
2392 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2398 kvm_vcpu_set_in_spin_loop(me, true);
2400 * We boost the priority of a VCPU that is runnable but not
2401 * currently running, because it got preempted by something
2402 * else and called schedule in __vcpu_run. Hopefully that
2403 * VCPU is holding the lock that we need and will release it.
2404 * We approximate round-robin by starting at the last boosted VCPU.
2406 for (pass = 0; pass < 2 && !yielded && try; pass++) {
2407 kvm_for_each_vcpu(i, vcpu, kvm) {
2408 if (!pass && i <= last_boosted_vcpu) {
2409 i = last_boosted_vcpu;
2411 } else if (pass && i > last_boosted_vcpu)
2413 if (!ACCESS_ONCE(vcpu->preempted))
2417 if (swait_active(&vcpu->wq) && !kvm_arch_vcpu_runnable(vcpu))
2419 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2422 yielded = kvm_vcpu_yield_to(vcpu);
2424 kvm->last_boosted_vcpu = i;
2426 } else if (yielded < 0) {
2433 kvm_vcpu_set_in_spin_loop(me, false);
2435 /* Ensure vcpu is not eligible during next spinloop */
2436 kvm_vcpu_set_dy_eligible(me, false);
2438 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2440 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2442 struct kvm_vcpu *vcpu = vma->vm_file->private_data;
2445 if (vmf->pgoff == 0)
2446 page = virt_to_page(vcpu->run);
2448 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2449 page = virt_to_page(vcpu->arch.pio_data);
2451 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2452 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2453 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2456 return kvm_arch_vcpu_fault(vcpu, vmf);
2462 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2463 .fault = kvm_vcpu_fault,
2466 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2468 vma->vm_ops = &kvm_vcpu_vm_ops;
2472 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2474 struct kvm_vcpu *vcpu = filp->private_data;
2476 debugfs_remove_recursive(vcpu->debugfs_dentry);
2477 kvm_put_kvm(vcpu->kvm);
2481 static struct file_operations kvm_vcpu_fops = {
2482 .release = kvm_vcpu_release,
2483 .unlocked_ioctl = kvm_vcpu_ioctl,
2484 #ifdef CONFIG_KVM_COMPAT
2485 .compat_ioctl = kvm_vcpu_compat_ioctl,
2487 .mmap = kvm_vcpu_mmap,
2488 .llseek = noop_llseek,
2492 * Allocates an inode for the vcpu.
2494 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2496 return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2499 static int kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2501 char dir_name[ITOA_MAX_LEN * 2];
2504 if (!kvm_arch_has_vcpu_debugfs())
2507 if (!debugfs_initialized())
2510 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2511 vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2512 vcpu->kvm->debugfs_dentry);
2513 if (!vcpu->debugfs_dentry)
2516 ret = kvm_arch_create_vcpu_debugfs(vcpu);
2518 debugfs_remove_recursive(vcpu->debugfs_dentry);
2526 * Creates some virtual cpus. Good luck creating more than one.
2528 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
2531 struct kvm_vcpu *vcpu;
2533 if (id >= KVM_MAX_VCPU_ID)
2536 mutex_lock(&kvm->lock);
2537 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2538 mutex_unlock(&kvm->lock);
2542 kvm->created_vcpus++;
2543 mutex_unlock(&kvm->lock);
2545 vcpu = kvm_arch_vcpu_create(kvm, id);
2548 goto vcpu_decrement;
2551 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2553 r = kvm_arch_vcpu_setup(vcpu);
2557 r = kvm_create_vcpu_debugfs(vcpu);
2561 mutex_lock(&kvm->lock);
2562 if (kvm_get_vcpu_by_id(kvm, id)) {
2564 goto unlock_vcpu_destroy;
2567 BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2569 /* Now it's all set up, let userspace reach it */
2571 r = create_vcpu_fd(vcpu);
2574 goto unlock_vcpu_destroy;
2577 kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2580 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
2581 * before kvm->online_vcpu's incremented value.
2584 atomic_inc(&kvm->online_vcpus);
2586 mutex_unlock(&kvm->lock);
2587 kvm_arch_vcpu_postcreate(vcpu);
2590 unlock_vcpu_destroy:
2591 mutex_unlock(&kvm->lock);
2592 debugfs_remove_recursive(vcpu->debugfs_dentry);
2594 kvm_arch_vcpu_destroy(vcpu);
2596 mutex_lock(&kvm->lock);
2597 kvm->created_vcpus--;
2598 mutex_unlock(&kvm->lock);
2602 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2605 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2606 vcpu->sigset_active = 1;
2607 vcpu->sigset = *sigset;
2609 vcpu->sigset_active = 0;
2613 static long kvm_vcpu_ioctl(struct file *filp,
2614 unsigned int ioctl, unsigned long arg)
2616 struct kvm_vcpu *vcpu = filp->private_data;
2617 void __user *argp = (void __user *)arg;
2619 struct kvm_fpu *fpu = NULL;
2620 struct kvm_sregs *kvm_sregs = NULL;
2622 if (vcpu->kvm->mm != current->mm)
2625 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2628 #if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS)
2630 * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
2631 * so vcpu_load() would break it.
2633 if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_S390_IRQ || ioctl == KVM_INTERRUPT)
2634 return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2638 r = vcpu_load(vcpu);
2646 if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
2647 /* The thread running this VCPU changed. */
2648 struct pid *oldpid = vcpu->pid;
2649 struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
2651 rcu_assign_pointer(vcpu->pid, newpid);
2656 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2657 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2659 case KVM_GET_REGS: {
2660 struct kvm_regs *kvm_regs;
2663 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
2666 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2670 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2677 case KVM_SET_REGS: {
2678 struct kvm_regs *kvm_regs;
2681 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2682 if (IS_ERR(kvm_regs)) {
2683 r = PTR_ERR(kvm_regs);
2686 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2690 case KVM_GET_SREGS: {
2691 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
2695 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
2699 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
2704 case KVM_SET_SREGS: {
2705 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2706 if (IS_ERR(kvm_sregs)) {
2707 r = PTR_ERR(kvm_sregs);
2711 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
2714 case KVM_GET_MP_STATE: {
2715 struct kvm_mp_state mp_state;
2717 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2721 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
2726 case KVM_SET_MP_STATE: {
2727 struct kvm_mp_state mp_state;
2730 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
2732 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
2735 case KVM_TRANSLATE: {
2736 struct kvm_translation tr;
2739 if (copy_from_user(&tr, argp, sizeof(tr)))
2741 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
2745 if (copy_to_user(argp, &tr, sizeof(tr)))
2750 case KVM_SET_GUEST_DEBUG: {
2751 struct kvm_guest_debug dbg;
2754 if (copy_from_user(&dbg, argp, sizeof(dbg)))
2756 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2759 case KVM_SET_SIGNAL_MASK: {
2760 struct kvm_signal_mask __user *sigmask_arg = argp;
2761 struct kvm_signal_mask kvm_sigmask;
2762 sigset_t sigset, *p;
2767 if (copy_from_user(&kvm_sigmask, argp,
2768 sizeof(kvm_sigmask)))
2771 if (kvm_sigmask.len != sizeof(sigset))
2774 if (copy_from_user(&sigset, sigmask_arg->sigset,
2779 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2783 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2787 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2791 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2797 fpu = memdup_user(argp, sizeof(*fpu));
2803 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2807 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2816 #ifdef CONFIG_KVM_COMPAT
2817 static long kvm_vcpu_compat_ioctl(struct file *filp,
2818 unsigned int ioctl, unsigned long arg)
2820 struct kvm_vcpu *vcpu = filp->private_data;
2821 void __user *argp = compat_ptr(arg);
2824 if (vcpu->kvm->mm != current->mm)
2828 case KVM_SET_SIGNAL_MASK: {
2829 struct kvm_signal_mask __user *sigmask_arg = argp;
2830 struct kvm_signal_mask kvm_sigmask;
2831 compat_sigset_t csigset;
2836 if (copy_from_user(&kvm_sigmask, argp,
2837 sizeof(kvm_sigmask)))
2840 if (kvm_sigmask.len != sizeof(csigset))
2843 if (copy_from_user(&csigset, sigmask_arg->sigset,
2846 sigset_from_compat(&sigset, &csigset);
2847 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2849 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
2853 r = kvm_vcpu_ioctl(filp, ioctl, arg);
2861 static int kvm_device_ioctl_attr(struct kvm_device *dev,
2862 int (*accessor)(struct kvm_device *dev,
2863 struct kvm_device_attr *attr),
2866 struct kvm_device_attr attr;
2871 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2874 return accessor(dev, &attr);
2877 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
2880 struct kvm_device *dev = filp->private_data;
2882 if (dev->kvm->mm != current->mm)
2886 case KVM_SET_DEVICE_ATTR:
2887 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
2888 case KVM_GET_DEVICE_ATTR:
2889 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
2890 case KVM_HAS_DEVICE_ATTR:
2891 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
2893 if (dev->ops->ioctl)
2894 return dev->ops->ioctl(dev, ioctl, arg);
2900 static int kvm_device_release(struct inode *inode, struct file *filp)
2902 struct kvm_device *dev = filp->private_data;
2903 struct kvm *kvm = dev->kvm;
2909 static const struct file_operations kvm_device_fops = {
2910 .unlocked_ioctl = kvm_device_ioctl,
2911 #ifdef CONFIG_KVM_COMPAT
2912 .compat_ioctl = kvm_device_ioctl,
2914 .release = kvm_device_release,
2917 struct kvm_device *kvm_device_from_filp(struct file *filp)
2919 if (filp->f_op != &kvm_device_fops)
2922 return filp->private_data;
2925 static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
2926 #ifdef CONFIG_KVM_MPIC
2927 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
2928 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
2931 #ifdef CONFIG_KVM_XICS
2932 [KVM_DEV_TYPE_XICS] = &kvm_xics_ops,
2936 int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
2938 if (type >= ARRAY_SIZE(kvm_device_ops_table))
2941 if (kvm_device_ops_table[type] != NULL)
2944 kvm_device_ops_table[type] = ops;
2948 void kvm_unregister_device_ops(u32 type)
2950 if (kvm_device_ops_table[type] != NULL)
2951 kvm_device_ops_table[type] = NULL;
2954 static int kvm_ioctl_create_device(struct kvm *kvm,
2955 struct kvm_create_device *cd)
2957 struct kvm_device_ops *ops = NULL;
2958 struct kvm_device *dev;
2959 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
2962 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
2965 ops = kvm_device_ops_table[cd->type];
2972 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2979 mutex_lock(&kvm->lock);
2980 ret = ops->create(dev, cd->type);
2982 mutex_unlock(&kvm->lock);
2986 list_add(&dev->vm_node, &kvm->devices);
2987 mutex_unlock(&kvm->lock);
2993 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
2996 mutex_lock(&kvm->lock);
2997 list_del(&dev->vm_node);
2998 mutex_unlock(&kvm->lock);
3007 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3010 case KVM_CAP_USER_MEMORY:
3011 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3012 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3013 case KVM_CAP_INTERNAL_ERROR_DATA:
3014 #ifdef CONFIG_HAVE_KVM_MSI
3015 case KVM_CAP_SIGNAL_MSI:
3017 #ifdef CONFIG_HAVE_KVM_IRQFD
3019 case KVM_CAP_IRQFD_RESAMPLE:
3021 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3022 case KVM_CAP_CHECK_EXTENSION_VM:
3024 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3025 case KVM_CAP_IRQ_ROUTING:
3026 return KVM_MAX_IRQ_ROUTES;
3028 #if KVM_ADDRESS_SPACE_NUM > 1
3029 case KVM_CAP_MULTI_ADDRESS_SPACE:
3030 return KVM_ADDRESS_SPACE_NUM;
3032 case KVM_CAP_MAX_VCPU_ID:
3033 return KVM_MAX_VCPU_ID;
3037 return kvm_vm_ioctl_check_extension(kvm, arg);
3040 static long kvm_vm_ioctl(struct file *filp,
3041 unsigned int ioctl, unsigned long arg)
3043 struct kvm *kvm = filp->private_data;
3044 void __user *argp = (void __user *)arg;
3047 if (kvm->mm != current->mm)
3050 case KVM_CREATE_VCPU:
3051 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3053 case KVM_SET_USER_MEMORY_REGION: {
3054 struct kvm_userspace_memory_region kvm_userspace_mem;
3057 if (copy_from_user(&kvm_userspace_mem, argp,
3058 sizeof(kvm_userspace_mem)))
3061 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3064 case KVM_GET_DIRTY_LOG: {
3065 struct kvm_dirty_log log;
3068 if (copy_from_user(&log, argp, sizeof(log)))
3070 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3073 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3074 case KVM_REGISTER_COALESCED_MMIO: {
3075 struct kvm_coalesced_mmio_zone zone;
3078 if (copy_from_user(&zone, argp, sizeof(zone)))
3080 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3083 case KVM_UNREGISTER_COALESCED_MMIO: {
3084 struct kvm_coalesced_mmio_zone zone;
3087 if (copy_from_user(&zone, argp, sizeof(zone)))
3089 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3094 struct kvm_irqfd data;
3097 if (copy_from_user(&data, argp, sizeof(data)))
3099 r = kvm_irqfd(kvm, &data);
3102 case KVM_IOEVENTFD: {
3103 struct kvm_ioeventfd data;
3106 if (copy_from_user(&data, argp, sizeof(data)))
3108 r = kvm_ioeventfd(kvm, &data);
3111 #ifdef CONFIG_HAVE_KVM_MSI
3112 case KVM_SIGNAL_MSI: {
3116 if (copy_from_user(&msi, argp, sizeof(msi)))
3118 r = kvm_send_userspace_msi(kvm, &msi);
3122 #ifdef __KVM_HAVE_IRQ_LINE
3123 case KVM_IRQ_LINE_STATUS:
3124 case KVM_IRQ_LINE: {
3125 struct kvm_irq_level irq_event;
3128 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3131 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3132 ioctl == KVM_IRQ_LINE_STATUS);
3137 if (ioctl == KVM_IRQ_LINE_STATUS) {
3138 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3146 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3147 case KVM_SET_GSI_ROUTING: {
3148 struct kvm_irq_routing routing;
3149 struct kvm_irq_routing __user *urouting;
3150 struct kvm_irq_routing_entry *entries = NULL;
3153 if (copy_from_user(&routing, argp, sizeof(routing)))
3156 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3162 entries = vmalloc(routing.nr * sizeof(*entries));
3167 if (copy_from_user(entries, urouting->entries,
3168 routing.nr * sizeof(*entries)))
3169 goto out_free_irq_routing;
3171 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3173 out_free_irq_routing:
3177 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3178 case KVM_CREATE_DEVICE: {
3179 struct kvm_create_device cd;
3182 if (copy_from_user(&cd, argp, sizeof(cd)))
3185 r = kvm_ioctl_create_device(kvm, &cd);
3190 if (copy_to_user(argp, &cd, sizeof(cd)))
3196 case KVM_CHECK_EXTENSION:
3197 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3200 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3206 #ifdef CONFIG_KVM_COMPAT
3207 struct compat_kvm_dirty_log {
3211 compat_uptr_t dirty_bitmap; /* one bit per page */
3216 static long kvm_vm_compat_ioctl(struct file *filp,
3217 unsigned int ioctl, unsigned long arg)
3219 struct kvm *kvm = filp->private_data;
3222 if (kvm->mm != current->mm)
3225 case KVM_GET_DIRTY_LOG: {
3226 struct compat_kvm_dirty_log compat_log;
3227 struct kvm_dirty_log log;
3230 if (copy_from_user(&compat_log, (void __user *)arg,
3231 sizeof(compat_log)))
3233 log.slot = compat_log.slot;
3234 log.padding1 = compat_log.padding1;
3235 log.padding2 = compat_log.padding2;
3236 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3238 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3242 r = kvm_vm_ioctl(filp, ioctl, arg);
3250 static struct file_operations kvm_vm_fops = {
3251 .release = kvm_vm_release,
3252 .unlocked_ioctl = kvm_vm_ioctl,
3253 #ifdef CONFIG_KVM_COMPAT
3254 .compat_ioctl = kvm_vm_compat_ioctl,
3256 .llseek = noop_llseek,
3259 static int kvm_dev_ioctl_create_vm(unsigned long type)
3265 kvm = kvm_create_vm(type);
3267 return PTR_ERR(kvm);
3268 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3269 r = kvm_coalesced_mmio_init(kvm);
3275 r = get_unused_fd_flags(O_CLOEXEC);
3280 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3284 return PTR_ERR(file);
3287 if (kvm_create_vm_debugfs(kvm, r) < 0) {
3293 fd_install(r, file);
3297 static long kvm_dev_ioctl(struct file *filp,
3298 unsigned int ioctl, unsigned long arg)
3303 case KVM_GET_API_VERSION:
3306 r = KVM_API_VERSION;
3309 r = kvm_dev_ioctl_create_vm(arg);
3311 case KVM_CHECK_EXTENSION:
3312 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3314 case KVM_GET_VCPU_MMAP_SIZE:
3317 r = PAGE_SIZE; /* struct kvm_run */
3319 r += PAGE_SIZE; /* pio data page */
3321 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3322 r += PAGE_SIZE; /* coalesced mmio ring page */
3325 case KVM_TRACE_ENABLE:
3326 case KVM_TRACE_PAUSE:
3327 case KVM_TRACE_DISABLE:
3331 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3337 static struct file_operations kvm_chardev_ops = {
3338 .unlocked_ioctl = kvm_dev_ioctl,
3339 .compat_ioctl = kvm_dev_ioctl,
3340 .llseek = noop_llseek,
3343 static struct miscdevice kvm_dev = {
3349 static void hardware_enable_nolock(void *junk)
3351 int cpu = raw_smp_processor_id();
3354 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3357 cpumask_set_cpu(cpu, cpus_hardware_enabled);
3359 r = kvm_arch_hardware_enable();
3362 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3363 atomic_inc(&hardware_enable_failed);
3364 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3368 static int kvm_starting_cpu(unsigned int cpu)
3370 raw_spin_lock(&kvm_count_lock);
3371 if (kvm_usage_count)
3372 hardware_enable_nolock(NULL);
3373 raw_spin_unlock(&kvm_count_lock);
3377 static void hardware_disable_nolock(void *junk)
3379 int cpu = raw_smp_processor_id();
3381 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3383 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3384 kvm_arch_hardware_disable();
3387 static int kvm_dying_cpu(unsigned int cpu)
3389 raw_spin_lock(&kvm_count_lock);
3390 if (kvm_usage_count)
3391 hardware_disable_nolock(NULL);
3392 raw_spin_unlock(&kvm_count_lock);
3396 static void hardware_disable_all_nolock(void)
3398 BUG_ON(!kvm_usage_count);
3401 if (!kvm_usage_count)
3402 on_each_cpu(hardware_disable_nolock, NULL, 1);
3405 static void hardware_disable_all(void)
3407 raw_spin_lock(&kvm_count_lock);
3408 hardware_disable_all_nolock();
3409 raw_spin_unlock(&kvm_count_lock);
3412 static int hardware_enable_all(void)
3416 raw_spin_lock(&kvm_count_lock);
3419 if (kvm_usage_count == 1) {
3420 atomic_set(&hardware_enable_failed, 0);
3421 on_each_cpu(hardware_enable_nolock, NULL, 1);
3423 if (atomic_read(&hardware_enable_failed)) {
3424 hardware_disable_all_nolock();
3429 raw_spin_unlock(&kvm_count_lock);
3434 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3438 * Some (well, at least mine) BIOSes hang on reboot if
3441 * And Intel TXT required VMX off for all cpu when system shutdown.
3443 pr_info("kvm: exiting hardware virtualization\n");
3444 kvm_rebooting = true;
3445 on_each_cpu(hardware_disable_nolock, NULL, 1);
3449 static struct notifier_block kvm_reboot_notifier = {
3450 .notifier_call = kvm_reboot,
3454 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3458 for (i = 0; i < bus->dev_count; i++) {
3459 struct kvm_io_device *pos = bus->range[i].dev;
3461 kvm_iodevice_destructor(pos);
3466 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3467 const struct kvm_io_range *r2)
3469 gpa_t addr1 = r1->addr;
3470 gpa_t addr2 = r2->addr;
3475 /* If r2->len == 0, match the exact address. If r2->len != 0,
3476 * accept any overlapping write. Any order is acceptable for
3477 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3478 * we process all of them.
3491 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3493 return kvm_io_bus_cmp(p1, p2);
3496 static int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
3497 gpa_t addr, int len)
3499 bus->range[bus->dev_count++] = (struct kvm_io_range) {
3505 sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
3506 kvm_io_bus_sort_cmp, NULL);
3511 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3512 gpa_t addr, int len)
3514 struct kvm_io_range *range, key;
3517 key = (struct kvm_io_range) {
3522 range = bsearch(&key, bus->range, bus->dev_count,
3523 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3527 off = range - bus->range;
3529 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3535 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3536 struct kvm_io_range *range, const void *val)
3540 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3544 while (idx < bus->dev_count &&
3545 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3546 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
3555 /* kvm_io_bus_write - called under kvm->slots_lock */
3556 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3557 int len, const void *val)
3559 struct kvm_io_bus *bus;
3560 struct kvm_io_range range;
3563 range = (struct kvm_io_range) {
3568 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3571 r = __kvm_io_bus_write(vcpu, bus, &range, val);
3572 return r < 0 ? r : 0;
3575 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3576 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3577 gpa_t addr, int len, const void *val, long cookie)
3579 struct kvm_io_bus *bus;
3580 struct kvm_io_range range;
3582 range = (struct kvm_io_range) {
3587 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3591 /* First try the device referenced by cookie. */
3592 if ((cookie >= 0) && (cookie < bus->dev_count) &&
3593 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3594 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
3599 * cookie contained garbage; fall back to search and return the
3600 * correct cookie value.
3602 return __kvm_io_bus_write(vcpu, bus, &range, val);
3605 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3606 struct kvm_io_range *range, void *val)
3610 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3614 while (idx < bus->dev_count &&
3615 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3616 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
3624 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
3626 /* kvm_io_bus_read - called under kvm->slots_lock */
3627 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3630 struct kvm_io_bus *bus;
3631 struct kvm_io_range range;
3634 range = (struct kvm_io_range) {
3639 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3642 r = __kvm_io_bus_read(vcpu, bus, &range, val);
3643 return r < 0 ? r : 0;
3647 /* Caller must hold slots_lock. */
3648 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3649 int len, struct kvm_io_device *dev)
3651 struct kvm_io_bus *new_bus, *bus;
3653 bus = kvm->buses[bus_idx];
3657 /* exclude ioeventfd which is limited by maximum fd */
3658 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
3661 new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
3662 sizeof(struct kvm_io_range)), GFP_KERNEL);
3665 memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
3666 sizeof(struct kvm_io_range)));
3667 kvm_io_bus_insert_dev(new_bus, dev, addr, len);
3668 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3669 synchronize_srcu_expedited(&kvm->srcu);
3675 /* Caller must hold slots_lock. */
3676 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3677 struct kvm_io_device *dev)
3680 struct kvm_io_bus *new_bus, *bus;
3682 bus = kvm->buses[bus_idx];
3686 for (i = 0; i < bus->dev_count; i++)
3687 if (bus->range[i].dev == dev) {
3691 if (i == bus->dev_count)
3694 new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
3695 sizeof(struct kvm_io_range)), GFP_KERNEL);
3697 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3698 new_bus->dev_count--;
3699 memcpy(new_bus->range + i, bus->range + i + 1,
3700 (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
3702 pr_err("kvm: failed to shrink bus, removing it completely\n");
3703 for (j = 0; j < bus->dev_count; j++) {
3706 kvm_iodevice_destructor(bus->range[j].dev);
3710 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3711 synchronize_srcu_expedited(&kvm->srcu);
3716 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3719 struct kvm_io_bus *bus;
3720 int dev_idx, srcu_idx;
3721 struct kvm_io_device *iodev = NULL;
3723 srcu_idx = srcu_read_lock(&kvm->srcu);
3725 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3729 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
3733 iodev = bus->range[dev_idx].dev;
3736 srcu_read_unlock(&kvm->srcu, srcu_idx);
3740 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
3742 static int kvm_debugfs_open(struct inode *inode, struct file *file,
3743 int (*get)(void *, u64 *), int (*set)(void *, u64),
3746 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3749 /* The debugfs files are a reference to the kvm struct which
3750 * is still valid when kvm_destroy_vm is called.
3751 * To avoid the race between open and the removal of the debugfs
3752 * directory we test against the users count.
3754 if (!atomic_add_unless(&stat_data->kvm->users_count, 1, 0))
3757 if (simple_attr_open(inode, file, get, set, fmt)) {
3758 kvm_put_kvm(stat_data->kvm);
3765 static int kvm_debugfs_release(struct inode *inode, struct file *file)
3767 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3770 simple_attr_release(inode, file);
3771 kvm_put_kvm(stat_data->kvm);
3776 static int vm_stat_get_per_vm(void *data, u64 *val)
3778 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3780 *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
3785 static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
3787 __simple_attr_check_format("%llu\n", 0ull);
3788 return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
3792 static const struct file_operations vm_stat_get_per_vm_fops = {
3793 .owner = THIS_MODULE,
3794 .open = vm_stat_get_per_vm_open,
3795 .release = kvm_debugfs_release,
3796 .read = simple_attr_read,
3797 .write = simple_attr_write,
3798 .llseek = generic_file_llseek,
3801 static int vcpu_stat_get_per_vm(void *data, u64 *val)
3804 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3805 struct kvm_vcpu *vcpu;
3809 kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3810 *val += *(u64 *)((void *)vcpu + stat_data->offset);
3815 static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
3817 __simple_attr_check_format("%llu\n", 0ull);
3818 return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
3822 static const struct file_operations vcpu_stat_get_per_vm_fops = {
3823 .owner = THIS_MODULE,
3824 .open = vcpu_stat_get_per_vm_open,
3825 .release = kvm_debugfs_release,
3826 .read = simple_attr_read,
3827 .write = simple_attr_write,
3828 .llseek = generic_file_llseek,
3831 static const struct file_operations *stat_fops_per_vm[] = {
3832 [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
3833 [KVM_STAT_VM] = &vm_stat_get_per_vm_fops,
3836 static int vm_stat_get(void *_offset, u64 *val)
3838 unsigned offset = (long)_offset;
3840 struct kvm_stat_data stat_tmp = {.offset = offset};
3844 mutex_lock(&kvm_lock);
3845 list_for_each_entry(kvm, &vm_list, vm_list) {
3847 vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3850 mutex_unlock(&kvm_lock);
3854 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
3856 static int vcpu_stat_get(void *_offset, u64 *val)
3858 unsigned offset = (long)_offset;
3860 struct kvm_stat_data stat_tmp = {.offset = offset};
3864 mutex_lock(&kvm_lock);
3865 list_for_each_entry(kvm, &vm_list, vm_list) {
3867 vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3870 mutex_unlock(&kvm_lock);
3874 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
3876 static const struct file_operations *stat_fops[] = {
3877 [KVM_STAT_VCPU] = &vcpu_stat_fops,
3878 [KVM_STAT_VM] = &vm_stat_fops,
3881 static int kvm_init_debug(void)
3884 struct kvm_stats_debugfs_item *p;
3886 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
3887 if (kvm_debugfs_dir == NULL)
3890 kvm_debugfs_num_entries = 0;
3891 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
3892 if (!debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
3893 (void *)(long)p->offset,
3894 stat_fops[p->kind]))
3901 debugfs_remove_recursive(kvm_debugfs_dir);
3906 static int kvm_suspend(void)
3908 if (kvm_usage_count)
3909 hardware_disable_nolock(NULL);
3913 static void kvm_resume(void)
3915 if (kvm_usage_count) {
3916 WARN_ON(raw_spin_is_locked(&kvm_count_lock));
3917 hardware_enable_nolock(NULL);
3921 static struct syscore_ops kvm_syscore_ops = {
3922 .suspend = kvm_suspend,
3923 .resume = kvm_resume,
3927 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
3929 return container_of(pn, struct kvm_vcpu, preempt_notifier);
3932 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
3934 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3936 if (vcpu->preempted)
3937 vcpu->preempted = false;
3939 kvm_arch_sched_in(vcpu, cpu);
3941 kvm_arch_vcpu_load(vcpu, cpu);
3944 static void kvm_sched_out(struct preempt_notifier *pn,
3945 struct task_struct *next)
3947 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3949 if (current->state == TASK_RUNNING)
3950 vcpu->preempted = true;
3951 kvm_arch_vcpu_put(vcpu);
3954 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
3955 struct module *module)
3960 r = kvm_arch_init(opaque);
3965 * kvm_arch_init makes sure there's at most one caller
3966 * for architectures that support multiple implementations,
3967 * like intel and amd on x86.
3968 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
3969 * conflicts in case kvm is already setup for another implementation.
3971 r = kvm_irqfd_init();
3975 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
3980 r = kvm_arch_hardware_setup();
3984 for_each_online_cpu(cpu) {
3985 smp_call_function_single(cpu,
3986 kvm_arch_check_processor_compat,
3992 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "AP_KVM_STARTING",
3993 kvm_starting_cpu, kvm_dying_cpu);
3996 register_reboot_notifier(&kvm_reboot_notifier);
3998 /* A kmem cache lets us meet the alignment requirements of fx_save. */
4000 vcpu_align = __alignof__(struct kvm_vcpu);
4001 kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
4002 SLAB_ACCOUNT, NULL);
4003 if (!kvm_vcpu_cache) {
4008 r = kvm_async_pf_init();
4012 kvm_chardev_ops.owner = module;
4013 kvm_vm_fops.owner = module;
4014 kvm_vcpu_fops.owner = module;
4016 r = misc_register(&kvm_dev);
4018 pr_err("kvm: misc device register failed\n");
4022 register_syscore_ops(&kvm_syscore_ops);
4024 kvm_preempt_ops.sched_in = kvm_sched_in;
4025 kvm_preempt_ops.sched_out = kvm_sched_out;
4027 r = kvm_init_debug();
4029 pr_err("kvm: create debugfs files failed\n");
4033 r = kvm_vfio_ops_init();
4039 unregister_syscore_ops(&kvm_syscore_ops);
4040 misc_deregister(&kvm_dev);
4042 kvm_async_pf_deinit();
4044 kmem_cache_destroy(kvm_vcpu_cache);
4046 unregister_reboot_notifier(&kvm_reboot_notifier);
4047 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4050 kvm_arch_hardware_unsetup();
4052 free_cpumask_var(cpus_hardware_enabled);
4060 EXPORT_SYMBOL_GPL(kvm_init);
4064 debugfs_remove_recursive(kvm_debugfs_dir);
4065 misc_deregister(&kvm_dev);
4066 kmem_cache_destroy(kvm_vcpu_cache);
4067 kvm_async_pf_deinit();
4068 unregister_syscore_ops(&kvm_syscore_ops);
4069 unregister_reboot_notifier(&kvm_reboot_notifier);
4070 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4071 on_each_cpu(hardware_disable_nolock, NULL, 1);
4072 kvm_arch_hardware_unsetup();
4075 free_cpumask_var(cpus_hardware_enabled);
4076 kvm_vfio_ops_exit();
4078 EXPORT_SYMBOL_GPL(kvm_exit);
4080 struct kvm_vm_worker_thread_context {
4082 struct task_struct *parent;
4083 struct completion init_done;
4084 kvm_vm_thread_fn_t thread_fn;
4089 static int kvm_vm_worker_thread(void *context)
4092 * The init_context is allocated on the stack of the parent thread, so
4093 * we have to locally copy anything that is needed beyond initialization
4095 struct kvm_vm_worker_thread_context *init_context = context;
4096 struct kvm *kvm = init_context->kvm;
4097 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4098 uintptr_t data = init_context->data;
4101 err = kthread_park(current);
4102 /* kthread_park(current) is never supposed to return an error */
4107 err = cgroup_attach_task_all(init_context->parent, current);
4109 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4114 set_user_nice(current, task_nice(init_context->parent));
4117 init_context->err = err;
4118 complete(&init_context->init_done);
4119 init_context = NULL;
4124 /* Wait to be woken up by the spawner before proceeding. */
4127 if (!kthread_should_stop())
4128 err = thread_fn(kvm, data);
4133 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4134 uintptr_t data, const char *name,
4135 struct task_struct **thread_ptr)
4137 struct kvm_vm_worker_thread_context init_context = {};
4138 struct task_struct *thread;
4141 init_context.kvm = kvm;
4142 init_context.parent = current;
4143 init_context.thread_fn = thread_fn;
4144 init_context.data = data;
4145 init_completion(&init_context.init_done);
4147 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4148 "%s-%d", name, task_pid_nr(current));
4150 return PTR_ERR(thread);
4152 /* kthread_run is never supposed to return NULL */
4153 WARN_ON(thread == NULL);
4155 wait_for_completion(&init_context.init_done);
4157 if (!init_context.err)
4158 *thread_ptr = thread;
4160 return init_context.err;