1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <kvm/iodev.h>
18 #include <linux/kvm_host.h>
19 #include <linux/kvm.h>
20 #include <linux/module.h>
21 #include <linux/errno.h>
22 #include <linux/percpu.h>
24 #include <linux/miscdevice.h>
25 #include <linux/vmalloc.h>
26 #include <linux/reboot.h>
27 #include <linux/debugfs.h>
28 #include <linux/highmem.h>
29 #include <linux/file.h>
30 #include <linux/syscore_ops.h>
31 #include <linux/cpu.h>
32 #include <linux/sched/signal.h>
33 #include <linux/sched/mm.h>
34 #include <linux/sched/stat.h>
35 #include <linux/cpumask.h>
36 #include <linux/smp.h>
37 #include <linux/anon_inodes.h>
38 #include <linux/profile.h>
39 #include <linux/kvm_para.h>
40 #include <linux/pagemap.h>
41 #include <linux/mman.h>
42 #include <linux/swap.h>
43 #include <linux/bitops.h>
44 #include <linux/spinlock.h>
45 #include <linux/compat.h>
46 #include <linux/srcu.h>
47 #include <linux/hugetlb.h>
48 #include <linux/slab.h>
49 #include <linux/sort.h>
50 #include <linux/bsearch.h>
52 #include <linux/lockdep.h>
53 #include <linux/kthread.h>
55 #include <asm/processor.h>
56 #include <asm/ioctl.h>
57 #include <linux/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 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
75 module_param(halt_poll_ns, uint, 0644);
76 EXPORT_SYMBOL_GPL(halt_poll_ns);
78 /* Default doubles per-vcpu halt_poll_ns. */
79 unsigned int halt_poll_ns_grow = 2;
80 module_param(halt_poll_ns_grow, uint, 0644);
81 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
83 /* The start value to grow halt_poll_ns from */
84 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
85 module_param(halt_poll_ns_grow_start, uint, 0644);
86 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
88 /* Default resets per-vcpu halt_poll_ns . */
89 unsigned int halt_poll_ns_shrink;
90 module_param(halt_poll_ns_shrink, uint, 0644);
91 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
96 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
99 DEFINE_MUTEX(kvm_lock);
100 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
103 static cpumask_var_t cpus_hardware_enabled;
104 static int kvm_usage_count;
105 static atomic_t hardware_enable_failed;
107 static struct kmem_cache *kvm_vcpu_cache;
109 static __read_mostly struct preempt_ops kvm_preempt_ops;
110 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
112 struct dentry *kvm_debugfs_dir;
113 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
115 static int kvm_debugfs_num_entries;
116 static const struct file_operations stat_fops_per_vm;
118 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
120 #ifdef CONFIG_KVM_COMPAT
121 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
123 #define KVM_COMPAT(c) .compat_ioctl = (c)
126 * For architectures that don't implement a compat infrastructure,
127 * adopt a double line of defense:
128 * - Prevent a compat task from opening /dev/kvm
129 * - If the open has been done by a 64bit task, and the KVM fd
130 * passed to a compat task, let the ioctls fail.
132 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
133 unsigned long arg) { return -EINVAL; }
135 static int kvm_no_compat_open(struct inode *inode, struct file *file)
137 return is_compat_task() ? -ENODEV : 0;
139 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
140 .open = kvm_no_compat_open
142 static int hardware_enable_all(void);
143 static void hardware_disable_all(void);
145 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
147 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
149 __visible bool kvm_rebooting;
150 EXPORT_SYMBOL_GPL(kvm_rebooting);
152 #define KVM_EVENT_CREATE_VM 0
153 #define KVM_EVENT_DESTROY_VM 1
154 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
155 static unsigned long long kvm_createvm_count;
156 static unsigned long long kvm_active_vms;
158 __weak int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
159 unsigned long start, unsigned long end, bool blockable)
164 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
167 * The metadata used by is_zone_device_page() to determine whether or
168 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
169 * the device has been pinned, e.g. by get_user_pages(). WARN if the
170 * page_count() is zero to help detect bad usage of this helper.
172 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
175 return is_zone_device_page(pfn_to_page(pfn));
178 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
181 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
182 * perspective they are "normal" pages, albeit with slightly different
186 return PageReserved(pfn_to_page(pfn)) &&
188 !kvm_is_zone_device_pfn(pfn);
193 bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
195 struct page *page = pfn_to_page(pfn);
197 if (!PageTransCompoundMap(page))
200 return is_transparent_hugepage(compound_head(page));
204 * Switches to specified vcpu, until a matching vcpu_put()
206 void vcpu_load(struct kvm_vcpu *vcpu)
210 __this_cpu_write(kvm_running_vcpu, vcpu);
211 preempt_notifier_register(&vcpu->preempt_notifier);
212 kvm_arch_vcpu_load(vcpu, cpu);
215 EXPORT_SYMBOL_GPL(vcpu_load);
217 void vcpu_put(struct kvm_vcpu *vcpu)
220 kvm_arch_vcpu_put(vcpu);
221 preempt_notifier_unregister(&vcpu->preempt_notifier);
222 __this_cpu_write(kvm_running_vcpu, NULL);
225 EXPORT_SYMBOL_GPL(vcpu_put);
227 /* TODO: merge with kvm_arch_vcpu_should_kick */
228 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
230 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
233 * We need to wait for the VCPU to reenable interrupts and get out of
234 * READING_SHADOW_PAGE_TABLES mode.
236 if (req & KVM_REQUEST_WAIT)
237 return mode != OUTSIDE_GUEST_MODE;
240 * Need to kick a running VCPU, but otherwise there is nothing to do.
242 return mode == IN_GUEST_MODE;
245 static void ack_flush(void *_completed)
249 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
252 cpus = cpu_online_mask;
254 if (cpumask_empty(cpus))
257 smp_call_function_many(cpus, ack_flush, NULL, wait);
261 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
262 struct kvm_vcpu *except,
263 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
266 struct kvm_vcpu *vcpu;
271 kvm_for_each_vcpu(i, vcpu, kvm) {
272 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
276 kvm_make_request(req, vcpu);
279 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
282 if (tmp != NULL && cpu != -1 && cpu != me &&
283 kvm_request_needs_ipi(vcpu, req))
284 __cpumask_set_cpu(cpu, tmp);
287 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
293 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
294 struct kvm_vcpu *except)
299 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
301 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
303 free_cpumask_var(cpus);
307 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
309 return kvm_make_all_cpus_request_except(kvm, req, NULL);
312 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
313 void kvm_flush_remote_tlbs(struct kvm *kvm)
316 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
317 * kvm_make_all_cpus_request.
319 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
322 * We want to publish modifications to the page tables before reading
323 * mode. Pairs with a memory barrier in arch-specific code.
324 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
325 * and smp_mb in walk_shadow_page_lockless_begin/end.
326 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
328 * There is already an smp_mb__after_atomic() before
329 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
332 if (!kvm_arch_flush_remote_tlb(kvm)
333 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
334 ++kvm->stat.remote_tlb_flush;
335 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
337 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
340 void kvm_reload_remote_mmus(struct kvm *kvm)
342 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
345 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
347 mutex_init(&vcpu->mutex);
352 init_swait_queue_head(&vcpu->wq);
353 kvm_async_pf_vcpu_init(vcpu);
356 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
358 kvm_vcpu_set_in_spin_loop(vcpu, false);
359 kvm_vcpu_set_dy_eligible(vcpu, false);
360 vcpu->preempted = false;
362 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
365 void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
367 kvm_arch_vcpu_destroy(vcpu);
370 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
371 * the vcpu->pid pointer, and at destruction time all file descriptors
374 put_pid(rcu_dereference_protected(vcpu->pid, 1));
376 free_page((unsigned long)vcpu->run);
377 kmem_cache_free(kvm_vcpu_cache, vcpu);
379 EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
381 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
382 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
384 return container_of(mn, struct kvm, mmu_notifier);
387 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
388 struct mm_struct *mm,
389 unsigned long address,
392 struct kvm *kvm = mmu_notifier_to_kvm(mn);
395 idx = srcu_read_lock(&kvm->srcu);
396 spin_lock(&kvm->mmu_lock);
397 kvm->mmu_notifier_seq++;
399 if (kvm_set_spte_hva(kvm, address, pte))
400 kvm_flush_remote_tlbs(kvm);
402 spin_unlock(&kvm->mmu_lock);
403 srcu_read_unlock(&kvm->srcu, idx);
406 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
407 const struct mmu_notifier_range *range)
409 struct kvm *kvm = mmu_notifier_to_kvm(mn);
410 int need_tlb_flush = 0, idx;
413 idx = srcu_read_lock(&kvm->srcu);
414 spin_lock(&kvm->mmu_lock);
416 * The count increase must become visible at unlock time as no
417 * spte can be established without taking the mmu_lock and
418 * count is also read inside the mmu_lock critical section.
420 kvm->mmu_notifier_count++;
421 need_tlb_flush = kvm_unmap_hva_range(kvm, range->start, range->end);
422 need_tlb_flush |= kvm->tlbs_dirty;
423 /* we've to flush the tlb before the pages can be freed */
425 kvm_flush_remote_tlbs(kvm);
427 spin_unlock(&kvm->mmu_lock);
429 ret = kvm_arch_mmu_notifier_invalidate_range(kvm, range->start,
431 mmu_notifier_range_blockable(range));
433 srcu_read_unlock(&kvm->srcu, idx);
438 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
439 const struct mmu_notifier_range *range)
441 struct kvm *kvm = mmu_notifier_to_kvm(mn);
443 spin_lock(&kvm->mmu_lock);
445 * This sequence increase will notify the kvm page fault that
446 * the page that is going to be mapped in the spte could have
449 kvm->mmu_notifier_seq++;
452 * The above sequence increase must be visible before the
453 * below count decrease, which is ensured by the smp_wmb above
454 * in conjunction with the smp_rmb in mmu_notifier_retry().
456 kvm->mmu_notifier_count--;
457 spin_unlock(&kvm->mmu_lock);
459 BUG_ON(kvm->mmu_notifier_count < 0);
462 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
463 struct mm_struct *mm,
467 struct kvm *kvm = mmu_notifier_to_kvm(mn);
470 idx = srcu_read_lock(&kvm->srcu);
471 spin_lock(&kvm->mmu_lock);
473 young = kvm_age_hva(kvm, start, end);
475 kvm_flush_remote_tlbs(kvm);
477 spin_unlock(&kvm->mmu_lock);
478 srcu_read_unlock(&kvm->srcu, idx);
483 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
484 struct mm_struct *mm,
488 struct kvm *kvm = mmu_notifier_to_kvm(mn);
491 idx = srcu_read_lock(&kvm->srcu);
492 spin_lock(&kvm->mmu_lock);
494 * Even though we do not flush TLB, this will still adversely
495 * affect performance on pre-Haswell Intel EPT, where there is
496 * no EPT Access Bit to clear so that we have to tear down EPT
497 * tables instead. If we find this unacceptable, we can always
498 * add a parameter to kvm_age_hva so that it effectively doesn't
499 * do anything on clear_young.
501 * Also note that currently we never issue secondary TLB flushes
502 * from clear_young, leaving this job up to the regular system
503 * cadence. If we find this inaccurate, we might come up with a
504 * more sophisticated heuristic later.
506 young = kvm_age_hva(kvm, start, end);
507 spin_unlock(&kvm->mmu_lock);
508 srcu_read_unlock(&kvm->srcu, idx);
513 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
514 struct mm_struct *mm,
515 unsigned long address)
517 struct kvm *kvm = mmu_notifier_to_kvm(mn);
520 idx = srcu_read_lock(&kvm->srcu);
521 spin_lock(&kvm->mmu_lock);
522 young = kvm_test_age_hva(kvm, address);
523 spin_unlock(&kvm->mmu_lock);
524 srcu_read_unlock(&kvm->srcu, idx);
529 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
530 struct mm_struct *mm)
532 struct kvm *kvm = mmu_notifier_to_kvm(mn);
535 idx = srcu_read_lock(&kvm->srcu);
536 kvm_arch_flush_shadow_all(kvm);
537 srcu_read_unlock(&kvm->srcu, idx);
540 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
541 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
542 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
543 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
544 .clear_young = kvm_mmu_notifier_clear_young,
545 .test_young = kvm_mmu_notifier_test_young,
546 .change_pte = kvm_mmu_notifier_change_pte,
547 .release = kvm_mmu_notifier_release,
550 static int kvm_init_mmu_notifier(struct kvm *kvm)
552 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
553 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
556 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
558 static int kvm_init_mmu_notifier(struct kvm *kvm)
563 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
565 static struct kvm_memslots *kvm_alloc_memslots(void)
568 struct kvm_memslots *slots;
570 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
574 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
575 slots->id_to_index[i] = -1;
580 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
582 if (!memslot->dirty_bitmap)
585 kvfree(memslot->dirty_bitmap);
586 memslot->dirty_bitmap = NULL;
589 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
591 kvm_destroy_dirty_bitmap(slot);
593 kvm_arch_free_memslot(kvm, slot);
599 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
601 struct kvm_memory_slot *memslot;
606 kvm_for_each_memslot(memslot, slots)
607 kvm_free_memslot(kvm, memslot);
612 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
616 if (!kvm->debugfs_dentry)
619 debugfs_remove_recursive(kvm->debugfs_dentry);
621 if (kvm->debugfs_stat_data) {
622 for (i = 0; i < kvm_debugfs_num_entries; i++)
623 kfree(kvm->debugfs_stat_data[i]);
624 kfree(kvm->debugfs_stat_data);
628 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
630 char dir_name[ITOA_MAX_LEN * 2];
631 struct kvm_stat_data *stat_data;
632 struct kvm_stats_debugfs_item *p;
634 if (!debugfs_initialized())
637 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
638 kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
640 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
641 sizeof(*kvm->debugfs_stat_data),
643 if (!kvm->debugfs_stat_data)
646 for (p = debugfs_entries; p->name; p++) {
647 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
651 stat_data->kvm = kvm;
652 stat_data->dbgfs_item = p;
653 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
654 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
655 kvm->debugfs_dentry, stat_data,
662 * Called after the VM is otherwise initialized, but just before adding it to
665 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
671 * Called just after removing the VM from the vm_list, but before doing any
674 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
678 static struct kvm *kvm_create_vm(unsigned long type)
680 struct kvm *kvm = kvm_arch_alloc_vm();
685 return ERR_PTR(-ENOMEM);
687 spin_lock_init(&kvm->mmu_lock);
689 kvm->mm = current->mm;
690 kvm_eventfd_init(kvm);
691 mutex_init(&kvm->lock);
692 mutex_init(&kvm->irq_lock);
693 mutex_init(&kvm->slots_lock);
694 INIT_LIST_HEAD(&kvm->devices);
696 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
698 if (init_srcu_struct(&kvm->srcu))
699 goto out_err_no_srcu;
700 if (init_srcu_struct(&kvm->irq_srcu))
701 goto out_err_no_irq_srcu;
703 refcount_set(&kvm->users_count, 1);
704 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
705 struct kvm_memslots *slots = kvm_alloc_memslots();
708 goto out_err_no_arch_destroy_vm;
709 /* Generations must be different for each address space. */
710 slots->generation = i;
711 rcu_assign_pointer(kvm->memslots[i], slots);
714 for (i = 0; i < KVM_NR_BUSES; i++) {
715 rcu_assign_pointer(kvm->buses[i],
716 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
718 goto out_err_no_arch_destroy_vm;
721 r = kvm_arch_init_vm(kvm, type);
723 goto out_err_no_arch_destroy_vm;
725 r = hardware_enable_all();
727 goto out_err_no_disable;
729 #ifdef CONFIG_HAVE_KVM_IRQFD
730 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
733 r = kvm_init_mmu_notifier(kvm);
735 goto out_err_no_mmu_notifier;
737 r = kvm_arch_post_init_vm(kvm);
741 mutex_lock(&kvm_lock);
742 list_add(&kvm->vm_list, &vm_list);
743 mutex_unlock(&kvm_lock);
745 preempt_notifier_inc();
750 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
751 if (kvm->mmu_notifier.ops)
752 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
754 out_err_no_mmu_notifier:
755 hardware_disable_all();
757 kvm_arch_destroy_vm(kvm);
758 out_err_no_arch_destroy_vm:
759 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
760 for (i = 0; i < KVM_NR_BUSES; i++)
761 kfree(kvm_get_bus(kvm, i));
762 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
763 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
764 cleanup_srcu_struct(&kvm->irq_srcu);
766 cleanup_srcu_struct(&kvm->srcu);
768 kvm_arch_free_vm(kvm);
773 static void kvm_destroy_devices(struct kvm *kvm)
775 struct kvm_device *dev, *tmp;
778 * We do not need to take the kvm->lock here, because nobody else
779 * has a reference to the struct kvm at this point and therefore
780 * cannot access the devices list anyhow.
782 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
783 list_del(&dev->vm_node);
784 dev->ops->destroy(dev);
788 static void kvm_destroy_vm(struct kvm *kvm)
791 struct mm_struct *mm = kvm->mm;
793 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
794 kvm_destroy_vm_debugfs(kvm);
795 kvm_arch_sync_events(kvm);
796 mutex_lock(&kvm_lock);
797 list_del(&kvm->vm_list);
798 mutex_unlock(&kvm_lock);
799 kvm_arch_pre_destroy_vm(kvm);
801 kvm_free_irq_routing(kvm);
802 for (i = 0; i < KVM_NR_BUSES; i++) {
803 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
806 kvm_io_bus_destroy(bus);
807 kvm->buses[i] = NULL;
809 kvm_coalesced_mmio_free(kvm);
810 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
811 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
813 kvm_arch_flush_shadow_all(kvm);
815 kvm_arch_destroy_vm(kvm);
816 kvm_destroy_devices(kvm);
817 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
818 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
819 cleanup_srcu_struct(&kvm->irq_srcu);
820 cleanup_srcu_struct(&kvm->srcu);
821 kvm_arch_free_vm(kvm);
822 preempt_notifier_dec();
823 hardware_disable_all();
827 void kvm_get_kvm(struct kvm *kvm)
829 refcount_inc(&kvm->users_count);
831 EXPORT_SYMBOL_GPL(kvm_get_kvm);
833 void kvm_put_kvm(struct kvm *kvm)
835 if (refcount_dec_and_test(&kvm->users_count))
838 EXPORT_SYMBOL_GPL(kvm_put_kvm);
841 * Used to put a reference that was taken on behalf of an object associated
842 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
843 * of the new file descriptor fails and the reference cannot be transferred to
844 * its final owner. In such cases, the caller is still actively using @kvm and
845 * will fail miserably if the refcount unexpectedly hits zero.
847 void kvm_put_kvm_no_destroy(struct kvm *kvm)
849 WARN_ON(refcount_dec_and_test(&kvm->users_count));
851 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
853 static int kvm_vm_release(struct inode *inode, struct file *filp)
855 struct kvm *kvm = filp->private_data;
857 kvm_irqfd_release(kvm);
864 * Allocation size is twice as large as the actual dirty bitmap size.
865 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
867 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
869 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
871 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
872 if (!memslot->dirty_bitmap)
879 * Delete a memslot by decrementing the number of used slots and shifting all
880 * other entries in the array forward one spot.
882 static inline void kvm_memslot_delete(struct kvm_memslots *slots,
883 struct kvm_memory_slot *memslot)
885 struct kvm_memory_slot *mslots = slots->memslots;
888 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
893 if (atomic_read(&slots->lru_slot) >= slots->used_slots)
894 atomic_set(&slots->lru_slot, 0);
896 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
897 mslots[i] = mslots[i + 1];
898 slots->id_to_index[mslots[i].id] = i;
900 mslots[i] = *memslot;
901 slots->id_to_index[memslot->id] = -1;
905 * "Insert" a new memslot by incrementing the number of used slots. Returns
906 * the new slot's initial index into the memslots array.
908 static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
910 return slots->used_slots++;
914 * Move a changed memslot backwards in the array by shifting existing slots
915 * with a higher GFN toward the front of the array. Note, the changed memslot
916 * itself is not preserved in the array, i.e. not swapped at this time, only
917 * its new index into the array is tracked. Returns the changed memslot's
918 * current index into the memslots array.
920 static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
921 struct kvm_memory_slot *memslot)
923 struct kvm_memory_slot *mslots = slots->memslots;
926 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
927 WARN_ON_ONCE(!slots->used_slots))
931 * Move the target memslot backward in the array by shifting existing
932 * memslots with a higher GFN (than the target memslot) towards the
933 * front of the array.
935 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
936 if (memslot->base_gfn > mslots[i + 1].base_gfn)
939 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
941 /* Shift the next memslot forward one and update its index. */
942 mslots[i] = mslots[i + 1];
943 slots->id_to_index[mslots[i].id] = i;
949 * Move a changed memslot forwards in the array by shifting existing slots with
950 * a lower GFN toward the back of the array. Note, the changed memslot itself
951 * is not preserved in the array, i.e. not swapped at this time, only its new
952 * index into the array is tracked. Returns the changed memslot's final index
953 * into the memslots array.
955 static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
956 struct kvm_memory_slot *memslot,
959 struct kvm_memory_slot *mslots = slots->memslots;
962 for (i = start; i > 0; i--) {
963 if (memslot->base_gfn < mslots[i - 1].base_gfn)
966 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
968 /* Shift the next memslot back one and update its index. */
969 mslots[i] = mslots[i - 1];
970 slots->id_to_index[mslots[i].id] = i;
976 * Re-sort memslots based on their GFN to account for an added, deleted, or
977 * moved memslot. Sorting memslots by GFN allows using a binary search during
980 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
981 * at memslots[0] has the highest GFN.
983 * The sorting algorithm takes advantage of having initially sorted memslots
984 * and knowing the position of the changed memslot. Sorting is also optimized
985 * by not swapping the updated memslot and instead only shifting other memslots
986 * and tracking the new index for the update memslot. Only once its final
987 * index is known is the updated memslot copied into its position in the array.
989 * - When deleting a memslot, the deleted memslot simply needs to be moved to
990 * the end of the array.
992 * - When creating a memslot, the algorithm "inserts" the new memslot at the
993 * end of the array and then it forward to its correct location.
995 * - When moving a memslot, the algorithm first moves the updated memslot
996 * backward to handle the scenario where the memslot's GFN was changed to a
997 * lower value. update_memslots() then falls through and runs the same flow
998 * as creating a memslot to move the memslot forward to handle the scenario
999 * where its GFN was changed to a higher value.
1001 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1002 * historical reasons. Originally, invalid memslots where denoted by having
1003 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1004 * to the end of the array. The current algorithm uses dedicated logic to
1005 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1007 * The other historical motiviation for highest->lowest was to improve the
1008 * performance of memslot lookup. KVM originally used a linear search starting
1009 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1010 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1011 * single memslot above the 4gb boundary. As the largest memslot is also the
1012 * most likely to be referenced, sorting it to the front of the array was
1013 * advantageous. The current binary search starts from the middle of the array
1014 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1016 static void update_memslots(struct kvm_memslots *slots,
1017 struct kvm_memory_slot *memslot,
1018 enum kvm_mr_change change)
1022 if (change == KVM_MR_DELETE) {
1023 kvm_memslot_delete(slots, memslot);
1025 if (change == KVM_MR_CREATE)
1026 i = kvm_memslot_insert_back(slots);
1028 i = kvm_memslot_move_backward(slots, memslot);
1029 i = kvm_memslot_move_forward(slots, memslot, i);
1032 * Copy the memslot to its new position in memslots and update
1033 * its index accordingly.
1035 slots->memslots[i] = *memslot;
1036 slots->id_to_index[memslot->id] = i;
1040 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1042 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1044 #ifdef __KVM_HAVE_READONLY_MEM
1045 valid_flags |= KVM_MEM_READONLY;
1048 if (mem->flags & ~valid_flags)
1054 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
1055 int as_id, struct kvm_memslots *slots)
1057 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
1058 u64 gen = old_memslots->generation;
1060 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1061 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1063 rcu_assign_pointer(kvm->memslots[as_id], slots);
1064 synchronize_srcu_expedited(&kvm->srcu);
1067 * Increment the new memslot generation a second time, dropping the
1068 * update in-progress flag and incrementing the generation based on
1069 * the number of address spaces. This provides a unique and easily
1070 * identifiable generation number while the memslots are in flux.
1072 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1075 * Generations must be unique even across address spaces. We do not need
1076 * a global counter for that, instead the generation space is evenly split
1077 * across address spaces. For example, with two address spaces, address
1078 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1079 * use generations 1, 3, 5, ...
1081 gen += KVM_ADDRESS_SPACE_NUM;
1083 kvm_arch_memslots_updated(kvm, gen);
1085 slots->generation = gen;
1087 return old_memslots;
1091 * Note, at a minimum, the current number of used slots must be allocated, even
1092 * when deleting a memslot, as we need a complete duplicate of the memslots for
1093 * use when invalidating a memslot prior to deleting/moving the memslot.
1095 static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1096 enum kvm_mr_change change)
1098 struct kvm_memslots *slots;
1099 size_t old_size, new_size;
1101 old_size = sizeof(struct kvm_memslots) +
1102 (sizeof(struct kvm_memory_slot) * old->used_slots);
1104 if (change == KVM_MR_CREATE)
1105 new_size = old_size + sizeof(struct kvm_memory_slot);
1107 new_size = old_size;
1109 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1111 memcpy(slots, old, old_size);
1116 static int kvm_set_memslot(struct kvm *kvm,
1117 const struct kvm_userspace_memory_region *mem,
1118 struct kvm_memory_slot *old,
1119 struct kvm_memory_slot *new, int as_id,
1120 enum kvm_mr_change change)
1122 struct kvm_memory_slot *slot;
1123 struct kvm_memslots *slots;
1126 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
1130 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1132 * Note, the INVALID flag needs to be in the appropriate entry
1133 * in the freshly allocated memslots, not in @old or @new.
1135 slot = id_to_memslot(slots, old->id);
1136 slot->flags |= KVM_MEMSLOT_INVALID;
1139 * We can re-use the old memslots, the only difference from the
1140 * newly installed memslots is the invalid flag, which will get
1141 * dropped by update_memslots anyway. We'll also revert to the
1142 * old memslots if preparing the new memory region fails.
1144 slots = install_new_memslots(kvm, as_id, slots);
1146 /* From this point no new shadow pages pointing to a deleted,
1147 * or moved, memslot will be created.
1149 * validation of sp->gfn happens in:
1150 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1151 * - kvm_is_visible_gfn (mmu_check_root)
1153 kvm_arch_flush_shadow_memslot(kvm, slot);
1156 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1160 update_memslots(slots, new, change);
1161 slots = install_new_memslots(kvm, as_id, slots);
1163 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1169 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1170 slots = install_new_memslots(kvm, as_id, slots);
1175 static int kvm_delete_memslot(struct kvm *kvm,
1176 const struct kvm_userspace_memory_region *mem,
1177 struct kvm_memory_slot *old, int as_id)
1179 struct kvm_memory_slot new;
1185 memset(&new, 0, sizeof(new));
1188 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1192 kvm_free_memslot(kvm, old);
1197 * Allocate some memory and give it an address in the guest physical address
1200 * Discontiguous memory is allowed, mostly for framebuffers.
1202 * Must be called holding kvm->slots_lock for write.
1204 int __kvm_set_memory_region(struct kvm *kvm,
1205 const struct kvm_userspace_memory_region *mem)
1207 struct kvm_memory_slot old, new;
1208 struct kvm_memory_slot *tmp;
1209 enum kvm_mr_change change;
1213 r = check_memory_region_flags(mem);
1217 as_id = mem->slot >> 16;
1218 id = (u16)mem->slot;
1220 /* General sanity checks */
1221 if (mem->memory_size & (PAGE_SIZE - 1))
1223 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1225 /* We can read the guest memory with __xxx_user() later on. */
1226 if ((id < KVM_USER_MEM_SLOTS) &&
1227 ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1228 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1231 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1233 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1237 * Make a full copy of the old memslot, the pointer will become stale
1238 * when the memslots are re-sorted by update_memslots(), and the old
1239 * memslot needs to be referenced after calling update_memslots(), e.g.
1240 * to free its resources and for arch specific behavior.
1242 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1247 memset(&old, 0, sizeof(old));
1251 if (!mem->memory_size)
1252 return kvm_delete_memslot(kvm, mem, &old, as_id);
1255 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1256 new.npages = mem->memory_size >> PAGE_SHIFT;
1257 new.flags = mem->flags;
1258 new.userspace_addr = mem->userspace_addr;
1260 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1264 change = KVM_MR_CREATE;
1265 new.dirty_bitmap = NULL;
1266 memset(&new.arch, 0, sizeof(new.arch));
1267 } else { /* Modify an existing slot. */
1268 if ((new.userspace_addr != old.userspace_addr) ||
1269 (new.npages != old.npages) ||
1270 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1273 if (new.base_gfn != old.base_gfn)
1274 change = KVM_MR_MOVE;
1275 else if (new.flags != old.flags)
1276 change = KVM_MR_FLAGS_ONLY;
1277 else /* Nothing to change. */
1280 /* Copy dirty_bitmap and arch from the current memslot. */
1281 new.dirty_bitmap = old.dirty_bitmap;
1282 memcpy(&new.arch, &old.arch, sizeof(new.arch));
1285 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1286 /* Check for overlaps */
1287 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1290 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1291 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1296 /* Allocate/free page dirty bitmap as needed */
1297 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1298 new.dirty_bitmap = NULL;
1299 else if (!new.dirty_bitmap) {
1300 r = kvm_alloc_dirty_bitmap(&new);
1304 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1305 bitmap_set(new.dirty_bitmap, 0, new.npages);
1308 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1312 if (old.dirty_bitmap && !new.dirty_bitmap)
1313 kvm_destroy_dirty_bitmap(&old);
1317 if (new.dirty_bitmap && !old.dirty_bitmap)
1318 kvm_destroy_dirty_bitmap(&new);
1321 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1323 int kvm_set_memory_region(struct kvm *kvm,
1324 const struct kvm_userspace_memory_region *mem)
1328 mutex_lock(&kvm->slots_lock);
1329 r = __kvm_set_memory_region(kvm, mem);
1330 mutex_unlock(&kvm->slots_lock);
1333 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1335 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1336 struct kvm_userspace_memory_region *mem)
1338 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1341 return kvm_set_memory_region(kvm, mem);
1344 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1346 * kvm_get_dirty_log - get a snapshot of dirty pages
1347 * @kvm: pointer to kvm instance
1348 * @log: slot id and address to which we copy the log
1349 * @is_dirty: set to '1' if any dirty pages were found
1350 * @memslot: set to the associated memslot, always valid on success
1352 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1353 int *is_dirty, struct kvm_memory_slot **memslot)
1355 struct kvm_memslots *slots;
1358 unsigned long any = 0;
1363 as_id = log->slot >> 16;
1364 id = (u16)log->slot;
1365 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1368 slots = __kvm_memslots(kvm, as_id);
1369 *memslot = id_to_memslot(slots, id);
1370 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1373 kvm_arch_sync_dirty_log(kvm, *memslot);
1375 n = kvm_dirty_bitmap_bytes(*memslot);
1377 for (i = 0; !any && i < n/sizeof(long); ++i)
1378 any = (*memslot)->dirty_bitmap[i];
1380 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1387 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1389 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1391 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1392 * and reenable dirty page tracking for the corresponding pages.
1393 * @kvm: pointer to kvm instance
1394 * @log: slot id and address to which we copy the log
1396 * We need to keep it in mind that VCPU threads can write to the bitmap
1397 * concurrently. So, to avoid losing track of dirty pages we keep the
1400 * 1. Take a snapshot of the bit and clear it if needed.
1401 * 2. Write protect the corresponding page.
1402 * 3. Copy the snapshot to the userspace.
1403 * 4. Upon return caller flushes TLB's if needed.
1405 * Between 2 and 4, the guest may write to the page using the remaining TLB
1406 * entry. This is not a problem because the page is reported dirty using
1407 * the snapshot taken before and step 4 ensures that writes done after
1408 * exiting to userspace will be logged for the next call.
1411 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
1413 struct kvm_memslots *slots;
1414 struct kvm_memory_slot *memslot;
1417 unsigned long *dirty_bitmap;
1418 unsigned long *dirty_bitmap_buffer;
1421 as_id = log->slot >> 16;
1422 id = (u16)log->slot;
1423 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1426 slots = __kvm_memslots(kvm, as_id);
1427 memslot = id_to_memslot(slots, id);
1428 if (!memslot || !memslot->dirty_bitmap)
1431 dirty_bitmap = memslot->dirty_bitmap;
1433 kvm_arch_sync_dirty_log(kvm, memslot);
1435 n = kvm_dirty_bitmap_bytes(memslot);
1437 if (kvm->manual_dirty_log_protect) {
1439 * Unlike kvm_get_dirty_log, we always return false in *flush,
1440 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1441 * is some code duplication between this function and
1442 * kvm_get_dirty_log, but hopefully all architecture
1443 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1444 * can be eliminated.
1446 dirty_bitmap_buffer = dirty_bitmap;
1448 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1449 memset(dirty_bitmap_buffer, 0, n);
1451 spin_lock(&kvm->mmu_lock);
1452 for (i = 0; i < n / sizeof(long); i++) {
1456 if (!dirty_bitmap[i])
1460 mask = xchg(&dirty_bitmap[i], 0);
1461 dirty_bitmap_buffer[i] = mask;
1463 offset = i * BITS_PER_LONG;
1464 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1467 spin_unlock(&kvm->mmu_lock);
1471 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1473 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1480 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1481 * @kvm: kvm instance
1482 * @log: slot id and address to which we copy the log
1484 * Steps 1-4 below provide general overview of dirty page logging. See
1485 * kvm_get_dirty_log_protect() function description for additional details.
1487 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1488 * always flush the TLB (step 4) even if previous step failed and the dirty
1489 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1490 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1491 * writes will be marked dirty for next log read.
1493 * 1. Take a snapshot of the bit and clear it if needed.
1494 * 2. Write protect the corresponding page.
1495 * 3. Copy the snapshot to the userspace.
1496 * 4. Flush TLB's if needed.
1498 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1499 struct kvm_dirty_log *log)
1503 mutex_lock(&kvm->slots_lock);
1505 r = kvm_get_dirty_log_protect(kvm, log);
1507 mutex_unlock(&kvm->slots_lock);
1512 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1513 * and reenable dirty page tracking for the corresponding pages.
1514 * @kvm: pointer to kvm instance
1515 * @log: slot id and address from which to fetch the bitmap of dirty pages
1517 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1518 struct kvm_clear_dirty_log *log)
1520 struct kvm_memslots *slots;
1521 struct kvm_memory_slot *memslot;
1525 unsigned long *dirty_bitmap;
1526 unsigned long *dirty_bitmap_buffer;
1529 as_id = log->slot >> 16;
1530 id = (u16)log->slot;
1531 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1534 if (log->first_page & 63)
1537 slots = __kvm_memslots(kvm, as_id);
1538 memslot = id_to_memslot(slots, id);
1539 if (!memslot || !memslot->dirty_bitmap)
1542 dirty_bitmap = memslot->dirty_bitmap;
1544 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
1546 if (log->first_page > memslot->npages ||
1547 log->num_pages > memslot->npages - log->first_page ||
1548 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1551 kvm_arch_sync_dirty_log(kvm, memslot);
1554 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1555 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1558 spin_lock(&kvm->mmu_lock);
1559 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1560 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
1561 i++, offset += BITS_PER_LONG) {
1562 unsigned long mask = *dirty_bitmap_buffer++;
1563 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1567 mask &= atomic_long_fetch_andnot(mask, p);
1570 * mask contains the bits that really have been cleared. This
1571 * never includes any bits beyond the length of the memslot (if
1572 * the length is not aligned to 64 pages), therefore it is not
1573 * a problem if userspace sets them in log->dirty_bitmap.
1577 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1581 spin_unlock(&kvm->mmu_lock);
1584 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1589 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
1590 struct kvm_clear_dirty_log *log)
1594 mutex_lock(&kvm->slots_lock);
1596 r = kvm_clear_dirty_log_protect(kvm, log);
1598 mutex_unlock(&kvm->slots_lock);
1601 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1603 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1605 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1607 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1609 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1611 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1614 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1616 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1618 if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1619 memslot->flags & KVM_MEMSLOT_INVALID)
1624 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1626 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
1628 struct vm_area_struct *vma;
1629 unsigned long addr, size;
1633 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
1634 if (kvm_is_error_hva(addr))
1637 down_read(¤t->mm->mmap_sem);
1638 vma = find_vma(current->mm, addr);
1642 size = vma_kernel_pagesize(vma);
1645 up_read(¤t->mm->mmap_sem);
1650 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1652 return slot->flags & KVM_MEM_READONLY;
1655 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1656 gfn_t *nr_pages, bool write)
1658 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1659 return KVM_HVA_ERR_BAD;
1661 if (memslot_is_readonly(slot) && write)
1662 return KVM_HVA_ERR_RO_BAD;
1665 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1667 return __gfn_to_hva_memslot(slot, gfn);
1670 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1673 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1676 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1679 return gfn_to_hva_many(slot, gfn, NULL);
1681 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1683 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1685 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1687 EXPORT_SYMBOL_GPL(gfn_to_hva);
1689 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1691 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1693 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1696 * Return the hva of a @gfn and the R/W attribute if possible.
1698 * @slot: the kvm_memory_slot which contains @gfn
1699 * @gfn: the gfn to be translated
1700 * @writable: used to return the read/write attribute of the @slot if the hva
1701 * is valid and @writable is not NULL
1703 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1704 gfn_t gfn, bool *writable)
1706 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1708 if (!kvm_is_error_hva(hva) && writable)
1709 *writable = !memslot_is_readonly(slot);
1714 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1716 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1718 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1721 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1723 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1725 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1728 static inline int check_user_page_hwpoison(unsigned long addr)
1730 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1732 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1733 return rc == -EHWPOISON;
1737 * The fast path to get the writable pfn which will be stored in @pfn,
1738 * true indicates success, otherwise false is returned. It's also the
1739 * only part that runs if we can in atomic context.
1741 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1742 bool *writable, kvm_pfn_t *pfn)
1744 struct page *page[1];
1748 * Fast pin a writable pfn only if it is a write fault request
1749 * or the caller allows to map a writable pfn for a read fault
1752 if (!(write_fault || writable))
1755 npages = __get_user_pages_fast(addr, 1, 1, page);
1757 *pfn = page_to_pfn(page[0]);
1768 * The slow path to get the pfn of the specified host virtual address,
1769 * 1 indicates success, -errno is returned if error is detected.
1771 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1772 bool *writable, kvm_pfn_t *pfn)
1774 unsigned int flags = FOLL_HWPOISON;
1781 *writable = write_fault;
1784 flags |= FOLL_WRITE;
1786 flags |= FOLL_NOWAIT;
1788 npages = get_user_pages_unlocked(addr, 1, &page, flags);
1792 /* map read fault as writable if possible */
1793 if (unlikely(!write_fault) && writable) {
1796 if (__get_user_pages_fast(addr, 1, 1, &wpage) == 1) {
1802 *pfn = page_to_pfn(page);
1806 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1808 if (unlikely(!(vma->vm_flags & VM_READ)))
1811 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1817 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1818 unsigned long addr, bool *async,
1819 bool write_fault, bool *writable,
1825 r = follow_pfn(vma, addr, &pfn);
1828 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1829 * not call the fault handler, so do it here.
1831 bool unlocked = false;
1832 r = fixup_user_fault(current, current->mm, addr,
1833 (write_fault ? FAULT_FLAG_WRITE : 0),
1840 r = follow_pfn(vma, addr, &pfn);
1850 * Get a reference here because callers of *hva_to_pfn* and
1851 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1852 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1853 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1854 * simply do nothing for reserved pfns.
1856 * Whoever called remap_pfn_range is also going to call e.g.
1857 * unmap_mapping_range before the underlying pages are freed,
1858 * causing a call to our MMU notifier.
1867 * Pin guest page in memory and return its pfn.
1868 * @addr: host virtual address which maps memory to the guest
1869 * @atomic: whether this function can sleep
1870 * @async: whether this function need to wait IO complete if the
1871 * host page is not in the memory
1872 * @write_fault: whether we should get a writable host page
1873 * @writable: whether it allows to map a writable host page for !@write_fault
1875 * The function will map a writable host page for these two cases:
1876 * 1): @write_fault = true
1877 * 2): @write_fault = false && @writable, @writable will tell the caller
1878 * whether the mapping is writable.
1880 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1881 bool write_fault, bool *writable)
1883 struct vm_area_struct *vma;
1887 /* we can do it either atomically or asynchronously, not both */
1888 BUG_ON(atomic && async);
1890 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
1894 return KVM_PFN_ERR_FAULT;
1896 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1900 down_read(¤t->mm->mmap_sem);
1901 if (npages == -EHWPOISON ||
1902 (!async && check_user_page_hwpoison(addr))) {
1903 pfn = KVM_PFN_ERR_HWPOISON;
1908 vma = find_vma_intersection(current->mm, addr, addr + 1);
1911 pfn = KVM_PFN_ERR_FAULT;
1912 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1913 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1917 pfn = KVM_PFN_ERR_FAULT;
1919 if (async && vma_is_valid(vma, write_fault))
1921 pfn = KVM_PFN_ERR_FAULT;
1924 up_read(¤t->mm->mmap_sem);
1928 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1929 bool atomic, bool *async, bool write_fault,
1932 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1934 if (addr == KVM_HVA_ERR_RO_BAD) {
1937 return KVM_PFN_ERR_RO_FAULT;
1940 if (kvm_is_error_hva(addr)) {
1943 return KVM_PFN_NOSLOT;
1946 /* Do not map writable pfn in the readonly memslot. */
1947 if (writable && memslot_is_readonly(slot)) {
1952 return hva_to_pfn(addr, atomic, async, write_fault,
1955 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1957 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1960 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1961 write_fault, writable);
1963 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1965 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1967 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1969 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1971 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1973 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1975 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1977 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1979 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1981 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1983 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1985 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1987 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1989 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1991 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1993 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1995 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1996 struct page **pages, int nr_pages)
2001 addr = gfn_to_hva_many(slot, gfn, &entry);
2002 if (kvm_is_error_hva(addr))
2005 if (entry < nr_pages)
2008 return __get_user_pages_fast(addr, nr_pages, 1, pages);
2010 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2012 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2014 if (is_error_noslot_pfn(pfn))
2015 return KVM_ERR_PTR_BAD_PAGE;
2017 if (kvm_is_reserved_pfn(pfn)) {
2019 return KVM_ERR_PTR_BAD_PAGE;
2022 return pfn_to_page(pfn);
2025 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2029 pfn = gfn_to_pfn(kvm, gfn);
2031 return kvm_pfn_to_page(pfn);
2033 EXPORT_SYMBOL_GPL(gfn_to_page);
2035 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2041 cache->pfn = cache->gfn = 0;
2044 kvm_release_pfn_dirty(pfn);
2046 kvm_release_pfn_clean(pfn);
2049 static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2050 struct gfn_to_pfn_cache *cache, u64 gen)
2052 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2054 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2056 cache->dirty = false;
2057 cache->generation = gen;
2060 static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2061 struct kvm_host_map *map,
2062 struct gfn_to_pfn_cache *cache,
2067 struct page *page = KVM_UNMAPPED_PAGE;
2068 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2069 u64 gen = slots->generation;
2075 if (!cache->pfn || cache->gfn != gfn ||
2076 cache->generation != gen) {
2079 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2085 pfn = gfn_to_pfn_memslot(slot, gfn);
2087 if (is_error_noslot_pfn(pfn))
2090 if (pfn_valid(pfn)) {
2091 page = pfn_to_page(pfn);
2093 hva = kmap_atomic(page);
2096 #ifdef CONFIG_HAS_IOMEM
2097 } else if (!atomic) {
2098 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2115 int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2116 struct gfn_to_pfn_cache *cache, bool atomic)
2118 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2121 EXPORT_SYMBOL_GPL(kvm_map_gfn);
2123 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2125 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2128 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2130 static void __kvm_unmap_gfn(struct kvm_memory_slot *memslot,
2131 struct kvm_host_map *map,
2132 struct gfn_to_pfn_cache *cache,
2133 bool dirty, bool atomic)
2141 if (map->page != KVM_UNMAPPED_PAGE) {
2143 kunmap_atomic(map->hva);
2147 #ifdef CONFIG_HAS_IOMEM
2151 WARN_ONCE(1, "Unexpected unmapping in atomic context");
2155 mark_page_dirty_in_slot(memslot, map->gfn);
2158 cache->dirty |= dirty;
2160 kvm_release_pfn(map->pfn, dirty, NULL);
2166 int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2167 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2169 __kvm_unmap_gfn(gfn_to_memslot(vcpu->kvm, map->gfn), map,
2170 cache, dirty, atomic);
2173 EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2175 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2177 __kvm_unmap_gfn(kvm_vcpu_gfn_to_memslot(vcpu, map->gfn), map, NULL,
2180 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2182 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2186 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2188 return kvm_pfn_to_page(pfn);
2190 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2192 void kvm_release_page_clean(struct page *page)
2194 WARN_ON(is_error_page(page));
2196 kvm_release_pfn_clean(page_to_pfn(page));
2198 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2200 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2202 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2203 put_page(pfn_to_page(pfn));
2205 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2207 void kvm_release_page_dirty(struct page *page)
2209 WARN_ON(is_error_page(page));
2211 kvm_release_pfn_dirty(page_to_pfn(page));
2213 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2215 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2217 kvm_set_pfn_dirty(pfn);
2218 kvm_release_pfn_clean(pfn);
2220 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2222 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2224 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2225 SetPageDirty(pfn_to_page(pfn));
2227 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2229 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2231 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2232 mark_page_accessed(pfn_to_page(pfn));
2234 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2236 void kvm_get_pfn(kvm_pfn_t pfn)
2238 if (!kvm_is_reserved_pfn(pfn))
2239 get_page(pfn_to_page(pfn));
2241 EXPORT_SYMBOL_GPL(kvm_get_pfn);
2243 static int next_segment(unsigned long len, int offset)
2245 if (len > PAGE_SIZE - offset)
2246 return PAGE_SIZE - offset;
2251 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2252 void *data, int offset, int len)
2257 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2258 if (kvm_is_error_hva(addr))
2260 r = __copy_from_user(data, (void __user *)addr + offset, len);
2266 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2269 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2271 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2273 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2275 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2276 int offset, int len)
2278 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2280 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2282 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2284 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2286 gfn_t gfn = gpa >> PAGE_SHIFT;
2288 int offset = offset_in_page(gpa);
2291 while ((seg = next_segment(len, offset)) != 0) {
2292 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2302 EXPORT_SYMBOL_GPL(kvm_read_guest);
2304 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2306 gfn_t gfn = gpa >> PAGE_SHIFT;
2308 int offset = offset_in_page(gpa);
2311 while ((seg = next_segment(len, offset)) != 0) {
2312 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2322 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2324 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2325 void *data, int offset, unsigned long len)
2330 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2331 if (kvm_is_error_hva(addr))
2333 pagefault_disable();
2334 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2341 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2342 void *data, unsigned long len)
2344 gfn_t gfn = gpa >> PAGE_SHIFT;
2345 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2346 int offset = offset_in_page(gpa);
2348 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2350 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2352 static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
2353 const void *data, int offset, int len)
2358 addr = gfn_to_hva_memslot(memslot, gfn);
2359 if (kvm_is_error_hva(addr))
2361 r = __copy_to_user((void __user *)addr + offset, data, len);
2364 mark_page_dirty_in_slot(memslot, gfn);
2368 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2369 const void *data, int offset, int len)
2371 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2373 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2375 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2377 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2378 const void *data, int offset, int len)
2380 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2382 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2384 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2386 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2389 gfn_t gfn = gpa >> PAGE_SHIFT;
2391 int offset = offset_in_page(gpa);
2394 while ((seg = next_segment(len, offset)) != 0) {
2395 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2405 EXPORT_SYMBOL_GPL(kvm_write_guest);
2407 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2410 gfn_t gfn = gpa >> PAGE_SHIFT;
2412 int offset = offset_in_page(gpa);
2415 while ((seg = next_segment(len, offset)) != 0) {
2416 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2426 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2428 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2429 struct gfn_to_hva_cache *ghc,
2430 gpa_t gpa, unsigned long len)
2432 int offset = offset_in_page(gpa);
2433 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2434 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2435 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2436 gfn_t nr_pages_avail;
2438 /* Update ghc->generation before performing any error checks. */
2439 ghc->generation = slots->generation;
2441 if (start_gfn > end_gfn) {
2442 ghc->hva = KVM_HVA_ERR_BAD;
2447 * If the requested region crosses two memslots, we still
2448 * verify that the entire region is valid here.
2450 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
2451 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2452 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2454 if (kvm_is_error_hva(ghc->hva))
2458 /* Use the slow path for cross page reads and writes. */
2459 if (nr_pages_needed == 1)
2462 ghc->memslot = NULL;
2469 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2470 gpa_t gpa, unsigned long len)
2472 struct kvm_memslots *slots = kvm_memslots(kvm);
2473 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2475 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2477 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2478 void *data, unsigned int offset,
2481 struct kvm_memslots *slots = kvm_memslots(kvm);
2483 gpa_t gpa = ghc->gpa + offset;
2485 BUG_ON(len + offset > ghc->len);
2487 if (slots->generation != ghc->generation) {
2488 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2492 if (kvm_is_error_hva(ghc->hva))
2495 if (unlikely(!ghc->memslot))
2496 return kvm_write_guest(kvm, gpa, data, len);
2498 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2501 mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
2505 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2507 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2508 void *data, unsigned long len)
2510 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2512 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2514 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2515 void *data, unsigned long len)
2517 struct kvm_memslots *slots = kvm_memslots(kvm);
2520 BUG_ON(len > ghc->len);
2522 if (slots->generation != ghc->generation) {
2523 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2527 if (kvm_is_error_hva(ghc->hva))
2530 if (unlikely(!ghc->memslot))
2531 return kvm_read_guest(kvm, ghc->gpa, data, len);
2533 r = __copy_from_user(data, (void __user *)ghc->hva, len);
2539 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2541 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2543 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2545 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2547 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2549 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2551 gfn_t gfn = gpa >> PAGE_SHIFT;
2553 int offset = offset_in_page(gpa);
2556 while ((seg = next_segment(len, offset)) != 0) {
2557 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2566 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2568 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2571 if (memslot && memslot->dirty_bitmap) {
2572 unsigned long rel_gfn = gfn - memslot->base_gfn;
2574 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2578 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2580 struct kvm_memory_slot *memslot;
2582 memslot = gfn_to_memslot(kvm, gfn);
2583 mark_page_dirty_in_slot(memslot, gfn);
2585 EXPORT_SYMBOL_GPL(mark_page_dirty);
2587 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2589 struct kvm_memory_slot *memslot;
2591 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2592 mark_page_dirty_in_slot(memslot, gfn);
2594 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2596 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2598 if (!vcpu->sigset_active)
2602 * This does a lockless modification of ->real_blocked, which is fine
2603 * because, only current can change ->real_blocked and all readers of
2604 * ->real_blocked don't care as long ->real_blocked is always a subset
2607 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
2610 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2612 if (!vcpu->sigset_active)
2615 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
2616 sigemptyset(¤t->real_blocked);
2619 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2621 unsigned int old, val, grow, grow_start;
2623 old = val = vcpu->halt_poll_ns;
2624 grow_start = READ_ONCE(halt_poll_ns_grow_start);
2625 grow = READ_ONCE(halt_poll_ns_grow);
2630 if (val < grow_start)
2633 if (val > halt_poll_ns)
2636 vcpu->halt_poll_ns = val;
2638 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2641 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2643 unsigned int old, val, shrink;
2645 old = val = vcpu->halt_poll_ns;
2646 shrink = READ_ONCE(halt_poll_ns_shrink);
2652 vcpu->halt_poll_ns = val;
2653 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2656 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2659 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2661 if (kvm_arch_vcpu_runnable(vcpu)) {
2662 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2665 if (kvm_cpu_has_pending_timer(vcpu))
2667 if (signal_pending(current))
2672 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2677 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2679 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2682 DECLARE_SWAITQUEUE(wait);
2683 bool waited = false;
2686 kvm_arch_vcpu_blocking(vcpu);
2688 start = cur = ktime_get();
2689 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
2690 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2692 ++vcpu->stat.halt_attempted_poll;
2695 * This sets KVM_REQ_UNHALT if an interrupt
2698 if (kvm_vcpu_check_block(vcpu) < 0) {
2699 ++vcpu->stat.halt_successful_poll;
2700 if (!vcpu_valid_wakeup(vcpu))
2701 ++vcpu->stat.halt_poll_invalid;
2705 } while (single_task_running() && ktime_before(cur, stop));
2709 prepare_to_swait_exclusive(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2711 if (kvm_vcpu_check_block(vcpu) < 0)
2718 finish_swait(&vcpu->wq, &wait);
2721 kvm_arch_vcpu_unblocking(vcpu);
2722 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2724 if (!kvm_arch_no_poll(vcpu)) {
2725 if (!vcpu_valid_wakeup(vcpu)) {
2726 shrink_halt_poll_ns(vcpu);
2727 } else if (halt_poll_ns) {
2728 if (block_ns <= vcpu->halt_poll_ns)
2730 /* we had a long block, shrink polling */
2731 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2732 shrink_halt_poll_ns(vcpu);
2733 /* we had a short halt and our poll time is too small */
2734 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2735 block_ns < halt_poll_ns)
2736 grow_halt_poll_ns(vcpu);
2738 vcpu->halt_poll_ns = 0;
2742 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2743 kvm_arch_vcpu_block_finish(vcpu);
2745 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2747 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2749 struct swait_queue_head *wqp;
2751 wqp = kvm_arch_vcpu_wq(vcpu);
2752 if (swq_has_sleeper(wqp)) {
2754 WRITE_ONCE(vcpu->ready, true);
2755 ++vcpu->stat.halt_wakeup;
2761 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2765 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2767 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2770 int cpu = vcpu->cpu;
2772 if (kvm_vcpu_wake_up(vcpu))
2776 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2777 if (kvm_arch_vcpu_should_kick(vcpu))
2778 smp_send_reschedule(cpu);
2781 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2782 #endif /* !CONFIG_S390 */
2784 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2787 struct task_struct *task = NULL;
2791 pid = rcu_dereference(target->pid);
2793 task = get_pid_task(pid, PIDTYPE_PID);
2797 ret = yield_to(task, 1);
2798 put_task_struct(task);
2802 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2805 * Helper that checks whether a VCPU is eligible for directed yield.
2806 * Most eligible candidate to yield is decided by following heuristics:
2808 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2809 * (preempted lock holder), indicated by @in_spin_loop.
2810 * Set at the beiginning and cleared at the end of interception/PLE handler.
2812 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2813 * chance last time (mostly it has become eligible now since we have probably
2814 * yielded to lockholder in last iteration. This is done by toggling
2815 * @dy_eligible each time a VCPU checked for eligibility.)
2817 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2818 * to preempted lock-holder could result in wrong VCPU selection and CPU
2819 * burning. Giving priority for a potential lock-holder increases lock
2822 * Since algorithm is based on heuristics, accessing another VCPU data without
2823 * locking does not harm. It may result in trying to yield to same VCPU, fail
2824 * and continue with next VCPU and so on.
2826 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2828 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2831 eligible = !vcpu->spin_loop.in_spin_loop ||
2832 vcpu->spin_loop.dy_eligible;
2834 if (vcpu->spin_loop.in_spin_loop)
2835 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2844 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2845 * a vcpu_load/vcpu_put pair. However, for most architectures
2846 * kvm_arch_vcpu_runnable does not require vcpu_load.
2848 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2850 return kvm_arch_vcpu_runnable(vcpu);
2853 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2855 if (kvm_arch_dy_runnable(vcpu))
2858 #ifdef CONFIG_KVM_ASYNC_PF
2859 if (!list_empty_careful(&vcpu->async_pf.done))
2866 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
2868 struct kvm *kvm = me->kvm;
2869 struct kvm_vcpu *vcpu;
2870 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2876 kvm_vcpu_set_in_spin_loop(me, true);
2878 * We boost the priority of a VCPU that is runnable but not
2879 * currently running, because it got preempted by something
2880 * else and called schedule in __vcpu_run. Hopefully that
2881 * VCPU is holding the lock that we need and will release it.
2882 * We approximate round-robin by starting at the last boosted VCPU.
2884 for (pass = 0; pass < 2 && !yielded && try; pass++) {
2885 kvm_for_each_vcpu(i, vcpu, kvm) {
2886 if (!pass && i <= last_boosted_vcpu) {
2887 i = last_boosted_vcpu;
2889 } else if (pass && i > last_boosted_vcpu)
2891 if (!READ_ONCE(vcpu->ready))
2895 if (swait_active(&vcpu->wq) && !vcpu_dy_runnable(vcpu))
2897 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
2898 !kvm_arch_vcpu_in_kernel(vcpu))
2900 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2903 yielded = kvm_vcpu_yield_to(vcpu);
2905 kvm->last_boosted_vcpu = i;
2907 } else if (yielded < 0) {
2914 kvm_vcpu_set_in_spin_loop(me, false);
2916 /* Ensure vcpu is not eligible during next spinloop */
2917 kvm_vcpu_set_dy_eligible(me, false);
2919 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2921 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
2923 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
2926 if (vmf->pgoff == 0)
2927 page = virt_to_page(vcpu->run);
2929 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2930 page = virt_to_page(vcpu->arch.pio_data);
2932 #ifdef CONFIG_KVM_MMIO
2933 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2934 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2937 return kvm_arch_vcpu_fault(vcpu, vmf);
2943 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2944 .fault = kvm_vcpu_fault,
2947 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2949 vma->vm_ops = &kvm_vcpu_vm_ops;
2953 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2955 struct kvm_vcpu *vcpu = filp->private_data;
2957 debugfs_remove_recursive(vcpu->debugfs_dentry);
2958 kvm_put_kvm(vcpu->kvm);
2962 static struct file_operations kvm_vcpu_fops = {
2963 .release = kvm_vcpu_release,
2964 .unlocked_ioctl = kvm_vcpu_ioctl,
2965 .mmap = kvm_vcpu_mmap,
2966 .llseek = noop_llseek,
2967 KVM_COMPAT(kvm_vcpu_compat_ioctl),
2971 * Allocates an inode for the vcpu.
2973 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2975 char name[8 + 1 + ITOA_MAX_LEN + 1];
2977 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
2978 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2981 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2983 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
2984 char dir_name[ITOA_MAX_LEN * 2];
2986 if (!debugfs_initialized())
2989 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2990 vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2991 vcpu->kvm->debugfs_dentry);
2993 kvm_arch_create_vcpu_debugfs(vcpu);
2998 * Creates some virtual cpus. Good luck creating more than one.
3000 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3003 struct kvm_vcpu *vcpu;
3006 if (id >= KVM_MAX_VCPU_ID)
3009 mutex_lock(&kvm->lock);
3010 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3011 mutex_unlock(&kvm->lock);
3015 kvm->created_vcpus++;
3016 mutex_unlock(&kvm->lock);
3018 r = kvm_arch_vcpu_precreate(kvm, id);
3020 goto vcpu_decrement;
3022 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
3025 goto vcpu_decrement;
3028 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3029 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3034 vcpu->run = page_address(page);
3036 kvm_vcpu_init(vcpu, kvm, id);
3038 r = kvm_arch_vcpu_create(vcpu);
3040 goto vcpu_free_run_page;
3042 kvm_create_vcpu_debugfs(vcpu);
3044 mutex_lock(&kvm->lock);
3045 if (kvm_get_vcpu_by_id(kvm, id)) {
3047 goto unlock_vcpu_destroy;
3050 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3051 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
3053 /* Now it's all set up, let userspace reach it */
3055 r = create_vcpu_fd(vcpu);
3057 kvm_put_kvm_no_destroy(kvm);
3058 goto unlock_vcpu_destroy;
3061 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
3064 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3065 * before kvm->online_vcpu's incremented value.
3068 atomic_inc(&kvm->online_vcpus);
3070 mutex_unlock(&kvm->lock);
3071 kvm_arch_vcpu_postcreate(vcpu);
3074 unlock_vcpu_destroy:
3075 mutex_unlock(&kvm->lock);
3076 debugfs_remove_recursive(vcpu->debugfs_dentry);
3077 kvm_arch_vcpu_destroy(vcpu);
3079 free_page((unsigned long)vcpu->run);
3081 kmem_cache_free(kvm_vcpu_cache, vcpu);
3083 mutex_lock(&kvm->lock);
3084 kvm->created_vcpus--;
3085 mutex_unlock(&kvm->lock);
3089 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3092 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3093 vcpu->sigset_active = 1;
3094 vcpu->sigset = *sigset;
3096 vcpu->sigset_active = 0;
3100 static long kvm_vcpu_ioctl(struct file *filp,
3101 unsigned int ioctl, unsigned long arg)
3103 struct kvm_vcpu *vcpu = filp->private_data;
3104 void __user *argp = (void __user *)arg;
3106 struct kvm_fpu *fpu = NULL;
3107 struct kvm_sregs *kvm_sregs = NULL;
3109 if (vcpu->kvm->mm != current->mm)
3112 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3116 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3117 * execution; mutex_lock() would break them.
3119 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3120 if (r != -ENOIOCTLCMD)
3123 if (mutex_lock_killable(&vcpu->mutex))
3131 oldpid = rcu_access_pointer(vcpu->pid);
3132 if (unlikely(oldpid != task_pid(current))) {
3133 /* The thread running this VCPU changed. */
3136 r = kvm_arch_vcpu_run_pid_change(vcpu);
3140 newpid = get_task_pid(current, PIDTYPE_PID);
3141 rcu_assign_pointer(vcpu->pid, newpid);
3146 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
3147 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3150 case KVM_GET_REGS: {
3151 struct kvm_regs *kvm_regs;
3154 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3157 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3161 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3168 case KVM_SET_REGS: {
3169 struct kvm_regs *kvm_regs;
3172 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3173 if (IS_ERR(kvm_regs)) {
3174 r = PTR_ERR(kvm_regs);
3177 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3181 case KVM_GET_SREGS: {
3182 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3183 GFP_KERNEL_ACCOUNT);
3187 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3191 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3196 case KVM_SET_SREGS: {
3197 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3198 if (IS_ERR(kvm_sregs)) {
3199 r = PTR_ERR(kvm_sregs);
3203 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3206 case KVM_GET_MP_STATE: {
3207 struct kvm_mp_state mp_state;
3209 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3213 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3218 case KVM_SET_MP_STATE: {
3219 struct kvm_mp_state mp_state;
3222 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3224 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3227 case KVM_TRANSLATE: {
3228 struct kvm_translation tr;
3231 if (copy_from_user(&tr, argp, sizeof(tr)))
3233 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3237 if (copy_to_user(argp, &tr, sizeof(tr)))
3242 case KVM_SET_GUEST_DEBUG: {
3243 struct kvm_guest_debug dbg;
3246 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3248 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3251 case KVM_SET_SIGNAL_MASK: {
3252 struct kvm_signal_mask __user *sigmask_arg = argp;
3253 struct kvm_signal_mask kvm_sigmask;
3254 sigset_t sigset, *p;
3259 if (copy_from_user(&kvm_sigmask, argp,
3260 sizeof(kvm_sigmask)))
3263 if (kvm_sigmask.len != sizeof(sigset))
3266 if (copy_from_user(&sigset, sigmask_arg->sigset,
3271 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3275 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
3279 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3283 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3289 fpu = memdup_user(argp, sizeof(*fpu));
3295 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3299 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3302 mutex_unlock(&vcpu->mutex);
3308 #ifdef CONFIG_KVM_COMPAT
3309 static long kvm_vcpu_compat_ioctl(struct file *filp,
3310 unsigned int ioctl, unsigned long arg)
3312 struct kvm_vcpu *vcpu = filp->private_data;
3313 void __user *argp = compat_ptr(arg);
3316 if (vcpu->kvm->mm != current->mm)
3320 case KVM_SET_SIGNAL_MASK: {
3321 struct kvm_signal_mask __user *sigmask_arg = argp;
3322 struct kvm_signal_mask kvm_sigmask;
3327 if (copy_from_user(&kvm_sigmask, argp,
3328 sizeof(kvm_sigmask)))
3331 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3334 if (get_compat_sigset(&sigset, (void *)sigmask_arg->sigset))
3336 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3338 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3342 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3350 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3352 struct kvm_device *dev = filp->private_data;
3355 return dev->ops->mmap(dev, vma);
3360 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3361 int (*accessor)(struct kvm_device *dev,
3362 struct kvm_device_attr *attr),
3365 struct kvm_device_attr attr;
3370 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3373 return accessor(dev, &attr);
3376 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3379 struct kvm_device *dev = filp->private_data;
3381 if (dev->kvm->mm != current->mm)
3385 case KVM_SET_DEVICE_ATTR:
3386 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3387 case KVM_GET_DEVICE_ATTR:
3388 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3389 case KVM_HAS_DEVICE_ATTR:
3390 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3392 if (dev->ops->ioctl)
3393 return dev->ops->ioctl(dev, ioctl, arg);
3399 static int kvm_device_release(struct inode *inode, struct file *filp)
3401 struct kvm_device *dev = filp->private_data;
3402 struct kvm *kvm = dev->kvm;
3404 if (dev->ops->release) {
3405 mutex_lock(&kvm->lock);
3406 list_del(&dev->vm_node);
3407 dev->ops->release(dev);
3408 mutex_unlock(&kvm->lock);
3415 static const struct file_operations kvm_device_fops = {
3416 .unlocked_ioctl = kvm_device_ioctl,
3417 .release = kvm_device_release,
3418 KVM_COMPAT(kvm_device_ioctl),
3419 .mmap = kvm_device_mmap,
3422 struct kvm_device *kvm_device_from_filp(struct file *filp)
3424 if (filp->f_op != &kvm_device_fops)
3427 return filp->private_data;
3430 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
3431 #ifdef CONFIG_KVM_MPIC
3432 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3433 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3437 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
3439 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3442 if (kvm_device_ops_table[type] != NULL)
3445 kvm_device_ops_table[type] = ops;
3449 void kvm_unregister_device_ops(u32 type)
3451 if (kvm_device_ops_table[type] != NULL)
3452 kvm_device_ops_table[type] = NULL;
3455 static int kvm_ioctl_create_device(struct kvm *kvm,
3456 struct kvm_create_device *cd)
3458 const struct kvm_device_ops *ops = NULL;
3459 struct kvm_device *dev;
3460 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
3464 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3467 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3468 ops = kvm_device_ops_table[type];
3475 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
3482 mutex_lock(&kvm->lock);
3483 ret = ops->create(dev, type);
3485 mutex_unlock(&kvm->lock);
3489 list_add(&dev->vm_node, &kvm->devices);
3490 mutex_unlock(&kvm->lock);
3496 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3498 kvm_put_kvm_no_destroy(kvm);
3499 mutex_lock(&kvm->lock);
3500 list_del(&dev->vm_node);
3501 mutex_unlock(&kvm->lock);
3510 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3513 case KVM_CAP_USER_MEMORY:
3514 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3515 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3516 case KVM_CAP_INTERNAL_ERROR_DATA:
3517 #ifdef CONFIG_HAVE_KVM_MSI
3518 case KVM_CAP_SIGNAL_MSI:
3520 #ifdef CONFIG_HAVE_KVM_IRQFD
3522 case KVM_CAP_IRQFD_RESAMPLE:
3524 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3525 case KVM_CAP_CHECK_EXTENSION_VM:
3526 case KVM_CAP_ENABLE_CAP_VM:
3528 #ifdef CONFIG_KVM_MMIO
3529 case KVM_CAP_COALESCED_MMIO:
3530 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3531 case KVM_CAP_COALESCED_PIO:
3534 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3535 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3536 return KVM_DIRTY_LOG_MANUAL_CAPS;
3538 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3539 case KVM_CAP_IRQ_ROUTING:
3540 return KVM_MAX_IRQ_ROUTES;
3542 #if KVM_ADDRESS_SPACE_NUM > 1
3543 case KVM_CAP_MULTI_ADDRESS_SPACE:
3544 return KVM_ADDRESS_SPACE_NUM;
3546 case KVM_CAP_NR_MEMSLOTS:
3547 return KVM_USER_MEM_SLOTS;
3551 return kvm_vm_ioctl_check_extension(kvm, arg);
3554 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3555 struct kvm_enable_cap *cap)
3560 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3561 struct kvm_enable_cap *cap)
3564 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3565 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
3566 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
3568 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
3569 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
3571 if (cap->flags || (cap->args[0] & ~allowed_options))
3573 kvm->manual_dirty_log_protect = cap->args[0];
3578 return kvm_vm_ioctl_enable_cap(kvm, cap);
3582 static long kvm_vm_ioctl(struct file *filp,
3583 unsigned int ioctl, unsigned long arg)
3585 struct kvm *kvm = filp->private_data;
3586 void __user *argp = (void __user *)arg;
3589 if (kvm->mm != current->mm)
3592 case KVM_CREATE_VCPU:
3593 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3595 case KVM_ENABLE_CAP: {
3596 struct kvm_enable_cap cap;
3599 if (copy_from_user(&cap, argp, sizeof(cap)))
3601 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
3604 case KVM_SET_USER_MEMORY_REGION: {
3605 struct kvm_userspace_memory_region kvm_userspace_mem;
3608 if (copy_from_user(&kvm_userspace_mem, argp,
3609 sizeof(kvm_userspace_mem)))
3612 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3615 case KVM_GET_DIRTY_LOG: {
3616 struct kvm_dirty_log log;
3619 if (copy_from_user(&log, argp, sizeof(log)))
3621 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3624 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3625 case KVM_CLEAR_DIRTY_LOG: {
3626 struct kvm_clear_dirty_log log;
3629 if (copy_from_user(&log, argp, sizeof(log)))
3631 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3635 #ifdef CONFIG_KVM_MMIO
3636 case KVM_REGISTER_COALESCED_MMIO: {
3637 struct kvm_coalesced_mmio_zone zone;
3640 if (copy_from_user(&zone, argp, sizeof(zone)))
3642 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3645 case KVM_UNREGISTER_COALESCED_MMIO: {
3646 struct kvm_coalesced_mmio_zone zone;
3649 if (copy_from_user(&zone, argp, sizeof(zone)))
3651 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3656 struct kvm_irqfd data;
3659 if (copy_from_user(&data, argp, sizeof(data)))
3661 r = kvm_irqfd(kvm, &data);
3664 case KVM_IOEVENTFD: {
3665 struct kvm_ioeventfd data;
3668 if (copy_from_user(&data, argp, sizeof(data)))
3670 r = kvm_ioeventfd(kvm, &data);
3673 #ifdef CONFIG_HAVE_KVM_MSI
3674 case KVM_SIGNAL_MSI: {
3678 if (copy_from_user(&msi, argp, sizeof(msi)))
3680 r = kvm_send_userspace_msi(kvm, &msi);
3684 #ifdef __KVM_HAVE_IRQ_LINE
3685 case KVM_IRQ_LINE_STATUS:
3686 case KVM_IRQ_LINE: {
3687 struct kvm_irq_level irq_event;
3690 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3693 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3694 ioctl == KVM_IRQ_LINE_STATUS);
3699 if (ioctl == KVM_IRQ_LINE_STATUS) {
3700 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3708 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3709 case KVM_SET_GSI_ROUTING: {
3710 struct kvm_irq_routing routing;
3711 struct kvm_irq_routing __user *urouting;
3712 struct kvm_irq_routing_entry *entries = NULL;
3715 if (copy_from_user(&routing, argp, sizeof(routing)))
3718 if (!kvm_arch_can_set_irq_routing(kvm))
3720 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3726 entries = vmalloc(array_size(sizeof(*entries),
3732 if (copy_from_user(entries, urouting->entries,
3733 routing.nr * sizeof(*entries)))
3734 goto out_free_irq_routing;
3736 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3738 out_free_irq_routing:
3742 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3743 case KVM_CREATE_DEVICE: {
3744 struct kvm_create_device cd;
3747 if (copy_from_user(&cd, argp, sizeof(cd)))
3750 r = kvm_ioctl_create_device(kvm, &cd);
3755 if (copy_to_user(argp, &cd, sizeof(cd)))
3761 case KVM_CHECK_EXTENSION:
3762 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3765 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3771 #ifdef CONFIG_KVM_COMPAT
3772 struct compat_kvm_dirty_log {
3776 compat_uptr_t dirty_bitmap; /* one bit per page */
3781 static long kvm_vm_compat_ioctl(struct file *filp,
3782 unsigned int ioctl, unsigned long arg)
3784 struct kvm *kvm = filp->private_data;
3787 if (kvm->mm != current->mm)
3790 case KVM_GET_DIRTY_LOG: {
3791 struct compat_kvm_dirty_log compat_log;
3792 struct kvm_dirty_log log;
3794 if (copy_from_user(&compat_log, (void __user *)arg,
3795 sizeof(compat_log)))
3797 log.slot = compat_log.slot;
3798 log.padding1 = compat_log.padding1;
3799 log.padding2 = compat_log.padding2;
3800 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3802 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3806 r = kvm_vm_ioctl(filp, ioctl, arg);
3812 static struct file_operations kvm_vm_fops = {
3813 .release = kvm_vm_release,
3814 .unlocked_ioctl = kvm_vm_ioctl,
3815 .llseek = noop_llseek,
3816 KVM_COMPAT(kvm_vm_compat_ioctl),
3819 static int kvm_dev_ioctl_create_vm(unsigned long type)
3825 kvm = kvm_create_vm(type);
3827 return PTR_ERR(kvm);
3828 #ifdef CONFIG_KVM_MMIO
3829 r = kvm_coalesced_mmio_init(kvm);
3833 r = get_unused_fd_flags(O_CLOEXEC);
3837 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3845 * Don't call kvm_put_kvm anymore at this point; file->f_op is
3846 * already set, with ->release() being kvm_vm_release(). In error
3847 * cases it will be called by the final fput(file) and will take
3848 * care of doing kvm_put_kvm(kvm).
3850 if (kvm_create_vm_debugfs(kvm, r) < 0) {
3855 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
3857 fd_install(r, file);
3865 static long kvm_dev_ioctl(struct file *filp,
3866 unsigned int ioctl, unsigned long arg)
3871 case KVM_GET_API_VERSION:
3874 r = KVM_API_VERSION;
3877 r = kvm_dev_ioctl_create_vm(arg);
3879 case KVM_CHECK_EXTENSION:
3880 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3882 case KVM_GET_VCPU_MMAP_SIZE:
3885 r = PAGE_SIZE; /* struct kvm_run */
3887 r += PAGE_SIZE; /* pio data page */
3889 #ifdef CONFIG_KVM_MMIO
3890 r += PAGE_SIZE; /* coalesced mmio ring page */
3893 case KVM_TRACE_ENABLE:
3894 case KVM_TRACE_PAUSE:
3895 case KVM_TRACE_DISABLE:
3899 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3905 static struct file_operations kvm_chardev_ops = {
3906 .unlocked_ioctl = kvm_dev_ioctl,
3907 .llseek = noop_llseek,
3908 KVM_COMPAT(kvm_dev_ioctl),
3911 static struct miscdevice kvm_dev = {
3917 static void hardware_enable_nolock(void *junk)
3919 int cpu = raw_smp_processor_id();
3922 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3925 cpumask_set_cpu(cpu, cpus_hardware_enabled);
3927 r = kvm_arch_hardware_enable();
3930 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3931 atomic_inc(&hardware_enable_failed);
3932 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3936 static int kvm_starting_cpu(unsigned int cpu)
3938 raw_spin_lock(&kvm_count_lock);
3939 if (kvm_usage_count)
3940 hardware_enable_nolock(NULL);
3941 raw_spin_unlock(&kvm_count_lock);
3945 static void hardware_disable_nolock(void *junk)
3947 int cpu = raw_smp_processor_id();
3949 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3951 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3952 kvm_arch_hardware_disable();
3955 static int kvm_dying_cpu(unsigned int cpu)
3957 raw_spin_lock(&kvm_count_lock);
3958 if (kvm_usage_count)
3959 hardware_disable_nolock(NULL);
3960 raw_spin_unlock(&kvm_count_lock);
3964 static void hardware_disable_all_nolock(void)
3966 BUG_ON(!kvm_usage_count);
3969 if (!kvm_usage_count)
3970 on_each_cpu(hardware_disable_nolock, NULL, 1);
3973 static void hardware_disable_all(void)
3975 raw_spin_lock(&kvm_count_lock);
3976 hardware_disable_all_nolock();
3977 raw_spin_unlock(&kvm_count_lock);
3980 static int hardware_enable_all(void)
3984 raw_spin_lock(&kvm_count_lock);
3987 if (kvm_usage_count == 1) {
3988 atomic_set(&hardware_enable_failed, 0);
3989 on_each_cpu(hardware_enable_nolock, NULL, 1);
3991 if (atomic_read(&hardware_enable_failed)) {
3992 hardware_disable_all_nolock();
3997 raw_spin_unlock(&kvm_count_lock);
4002 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4006 * Some (well, at least mine) BIOSes hang on reboot if
4009 * And Intel TXT required VMX off for all cpu when system shutdown.
4011 pr_info("kvm: exiting hardware virtualization\n");
4012 kvm_rebooting = true;
4013 on_each_cpu(hardware_disable_nolock, NULL, 1);
4017 static struct notifier_block kvm_reboot_notifier = {
4018 .notifier_call = kvm_reboot,
4022 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4026 for (i = 0; i < bus->dev_count; i++) {
4027 struct kvm_io_device *pos = bus->range[i].dev;
4029 kvm_iodevice_destructor(pos);
4034 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4035 const struct kvm_io_range *r2)
4037 gpa_t addr1 = r1->addr;
4038 gpa_t addr2 = r2->addr;
4043 /* If r2->len == 0, match the exact address. If r2->len != 0,
4044 * accept any overlapping write. Any order is acceptable for
4045 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4046 * we process all of them.
4059 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4061 return kvm_io_bus_cmp(p1, p2);
4064 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4065 gpa_t addr, int len)
4067 struct kvm_io_range *range, key;
4070 key = (struct kvm_io_range) {
4075 range = bsearch(&key, bus->range, bus->dev_count,
4076 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4080 off = range - bus->range;
4082 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4088 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4089 struct kvm_io_range *range, const void *val)
4093 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4097 while (idx < bus->dev_count &&
4098 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4099 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4108 /* kvm_io_bus_write - called under kvm->slots_lock */
4109 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4110 int len, const void *val)
4112 struct kvm_io_bus *bus;
4113 struct kvm_io_range range;
4116 range = (struct kvm_io_range) {
4121 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4124 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4125 return r < 0 ? r : 0;
4127 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
4129 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4130 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4131 gpa_t addr, int len, const void *val, long cookie)
4133 struct kvm_io_bus *bus;
4134 struct kvm_io_range range;
4136 range = (struct kvm_io_range) {
4141 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4145 /* First try the device referenced by cookie. */
4146 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4147 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4148 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4153 * cookie contained garbage; fall back to search and return the
4154 * correct cookie value.
4156 return __kvm_io_bus_write(vcpu, bus, &range, val);
4159 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4160 struct kvm_io_range *range, void *val)
4164 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4168 while (idx < bus->dev_count &&
4169 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4170 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4179 /* kvm_io_bus_read - called under kvm->slots_lock */
4180 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4183 struct kvm_io_bus *bus;
4184 struct kvm_io_range range;
4187 range = (struct kvm_io_range) {
4192 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4195 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4196 return r < 0 ? r : 0;
4199 /* Caller must hold slots_lock. */
4200 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4201 int len, struct kvm_io_device *dev)
4204 struct kvm_io_bus *new_bus, *bus;
4205 struct kvm_io_range range;
4207 bus = kvm_get_bus(kvm, bus_idx);
4211 /* exclude ioeventfd which is limited by maximum fd */
4212 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
4215 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
4216 GFP_KERNEL_ACCOUNT);
4220 range = (struct kvm_io_range) {
4226 for (i = 0; i < bus->dev_count; i++)
4227 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4230 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4231 new_bus->dev_count++;
4232 new_bus->range[i] = range;
4233 memcpy(new_bus->range + i + 1, bus->range + i,
4234 (bus->dev_count - i) * sizeof(struct kvm_io_range));
4235 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4236 synchronize_srcu_expedited(&kvm->srcu);
4242 /* Caller must hold slots_lock. */
4243 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4244 struct kvm_io_device *dev)
4247 struct kvm_io_bus *new_bus, *bus;
4249 bus = kvm_get_bus(kvm, bus_idx);
4253 for (i = 0; i < bus->dev_count; i++)
4254 if (bus->range[i].dev == dev) {
4258 if (i == bus->dev_count)
4261 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
4262 GFP_KERNEL_ACCOUNT);
4264 pr_err("kvm: failed to shrink bus, removing it completely\n");
4268 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4269 new_bus->dev_count--;
4270 memcpy(new_bus->range + i, bus->range + i + 1,
4271 (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
4274 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4275 synchronize_srcu_expedited(&kvm->srcu);
4280 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4283 struct kvm_io_bus *bus;
4284 int dev_idx, srcu_idx;
4285 struct kvm_io_device *iodev = NULL;
4287 srcu_idx = srcu_read_lock(&kvm->srcu);
4289 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
4293 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4297 iodev = bus->range[dev_idx].dev;
4300 srcu_read_unlock(&kvm->srcu, srcu_idx);
4304 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4306 static int kvm_debugfs_open(struct inode *inode, struct file *file,
4307 int (*get)(void *, u64 *), int (*set)(void *, u64),
4310 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4313 /* The debugfs files are a reference to the kvm struct which
4314 * is still valid when kvm_destroy_vm is called.
4315 * To avoid the race between open and the removal of the debugfs
4316 * directory we test against the users count.
4318 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
4321 if (simple_attr_open(inode, file, get,
4322 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4325 kvm_put_kvm(stat_data->kvm);
4332 static int kvm_debugfs_release(struct inode *inode, struct file *file)
4334 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4337 simple_attr_release(inode, file);
4338 kvm_put_kvm(stat_data->kvm);
4343 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
4345 *val = *(ulong *)((void *)kvm + offset);
4350 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
4352 *(ulong *)((void *)kvm + offset) = 0;
4357 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
4360 struct kvm_vcpu *vcpu;
4364 kvm_for_each_vcpu(i, vcpu, kvm)
4365 *val += *(u64 *)((void *)vcpu + offset);
4370 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
4373 struct kvm_vcpu *vcpu;
4375 kvm_for_each_vcpu(i, vcpu, kvm)
4376 *(u64 *)((void *)vcpu + offset) = 0;
4381 static int kvm_stat_data_get(void *data, u64 *val)
4384 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4386 switch (stat_data->dbgfs_item->kind) {
4388 r = kvm_get_stat_per_vm(stat_data->kvm,
4389 stat_data->dbgfs_item->offset, val);
4392 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4393 stat_data->dbgfs_item->offset, val);
4400 static int kvm_stat_data_clear(void *data, u64 val)
4403 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4408 switch (stat_data->dbgfs_item->kind) {
4410 r = kvm_clear_stat_per_vm(stat_data->kvm,
4411 stat_data->dbgfs_item->offset);
4414 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4415 stat_data->dbgfs_item->offset);
4422 static int kvm_stat_data_open(struct inode *inode, struct file *file)
4424 __simple_attr_check_format("%llu\n", 0ull);
4425 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
4426 kvm_stat_data_clear, "%llu\n");
4429 static const struct file_operations stat_fops_per_vm = {
4430 .owner = THIS_MODULE,
4431 .open = kvm_stat_data_open,
4432 .release = kvm_debugfs_release,
4433 .read = simple_attr_read,
4434 .write = simple_attr_write,
4435 .llseek = no_llseek,
4438 static int vm_stat_get(void *_offset, u64 *val)
4440 unsigned offset = (long)_offset;
4445 mutex_lock(&kvm_lock);
4446 list_for_each_entry(kvm, &vm_list, vm_list) {
4447 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
4450 mutex_unlock(&kvm_lock);
4454 static int vm_stat_clear(void *_offset, u64 val)
4456 unsigned offset = (long)_offset;
4462 mutex_lock(&kvm_lock);
4463 list_for_each_entry(kvm, &vm_list, vm_list) {
4464 kvm_clear_stat_per_vm(kvm, offset);
4466 mutex_unlock(&kvm_lock);
4471 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
4473 static int vcpu_stat_get(void *_offset, u64 *val)
4475 unsigned offset = (long)_offset;
4480 mutex_lock(&kvm_lock);
4481 list_for_each_entry(kvm, &vm_list, vm_list) {
4482 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
4485 mutex_unlock(&kvm_lock);
4489 static int vcpu_stat_clear(void *_offset, u64 val)
4491 unsigned offset = (long)_offset;
4497 mutex_lock(&kvm_lock);
4498 list_for_each_entry(kvm, &vm_list, vm_list) {
4499 kvm_clear_stat_per_vcpu(kvm, offset);
4501 mutex_unlock(&kvm_lock);
4506 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4509 static const struct file_operations *stat_fops[] = {
4510 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4511 [KVM_STAT_VM] = &vm_stat_fops,
4514 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4516 struct kobj_uevent_env *env;
4517 unsigned long long created, active;
4519 if (!kvm_dev.this_device || !kvm)
4522 mutex_lock(&kvm_lock);
4523 if (type == KVM_EVENT_CREATE_VM) {
4524 kvm_createvm_count++;
4526 } else if (type == KVM_EVENT_DESTROY_VM) {
4529 created = kvm_createvm_count;
4530 active = kvm_active_vms;
4531 mutex_unlock(&kvm_lock);
4533 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
4537 add_uevent_var(env, "CREATED=%llu", created);
4538 add_uevent_var(env, "COUNT=%llu", active);
4540 if (type == KVM_EVENT_CREATE_VM) {
4541 add_uevent_var(env, "EVENT=create");
4542 kvm->userspace_pid = task_pid_nr(current);
4543 } else if (type == KVM_EVENT_DESTROY_VM) {
4544 add_uevent_var(env, "EVENT=destroy");
4546 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4548 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
4549 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
4552 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4554 add_uevent_var(env, "STATS_PATH=%s", tmp);
4558 /* no need for checks, since we are adding at most only 5 keys */
4559 env->envp[env->envp_idx++] = NULL;
4560 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4564 static void kvm_init_debug(void)
4566 struct kvm_stats_debugfs_item *p;
4568 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4570 kvm_debugfs_num_entries = 0;
4571 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
4572 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
4573 kvm_debugfs_dir, (void *)(long)p->offset,
4574 stat_fops[p->kind]);
4578 static int kvm_suspend(void)
4580 if (kvm_usage_count)
4581 hardware_disable_nolock(NULL);
4585 static void kvm_resume(void)
4587 if (kvm_usage_count) {
4588 #ifdef CONFIG_LOCKDEP
4589 WARN_ON(lockdep_is_held(&kvm_count_lock));
4591 hardware_enable_nolock(NULL);
4595 static struct syscore_ops kvm_syscore_ops = {
4596 .suspend = kvm_suspend,
4597 .resume = kvm_resume,
4601 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4603 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4606 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4608 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4610 WRITE_ONCE(vcpu->preempted, false);
4611 WRITE_ONCE(vcpu->ready, false);
4613 __this_cpu_write(kvm_running_vcpu, vcpu);
4614 kvm_arch_sched_in(vcpu, cpu);
4615 kvm_arch_vcpu_load(vcpu, cpu);
4618 static void kvm_sched_out(struct preempt_notifier *pn,
4619 struct task_struct *next)
4621 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4623 if (current->state == TASK_RUNNING) {
4624 WRITE_ONCE(vcpu->preempted, true);
4625 WRITE_ONCE(vcpu->ready, true);
4627 kvm_arch_vcpu_put(vcpu);
4628 __this_cpu_write(kvm_running_vcpu, NULL);
4632 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
4634 * We can disable preemption locally around accessing the per-CPU variable,
4635 * and use the resolved vcpu pointer after enabling preemption again,
4636 * because even if the current thread is migrated to another CPU, reading
4637 * the per-CPU value later will give us the same value as we update the
4638 * per-CPU variable in the preempt notifier handlers.
4640 struct kvm_vcpu *kvm_get_running_vcpu(void)
4642 struct kvm_vcpu *vcpu;
4645 vcpu = __this_cpu_read(kvm_running_vcpu);
4652 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
4654 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
4656 return &kvm_running_vcpu;
4659 struct kvm_cpu_compat_check {
4664 static void check_processor_compat(void *data)
4666 struct kvm_cpu_compat_check *c = data;
4668 *c->ret = kvm_arch_check_processor_compat(c->opaque);
4671 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4672 struct module *module)
4674 struct kvm_cpu_compat_check c;
4678 r = kvm_arch_init(opaque);
4683 * kvm_arch_init makes sure there's at most one caller
4684 * for architectures that support multiple implementations,
4685 * like intel and amd on x86.
4686 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4687 * conflicts in case kvm is already setup for another implementation.
4689 r = kvm_irqfd_init();
4693 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4698 r = kvm_arch_hardware_setup(opaque);
4704 for_each_online_cpu(cpu) {
4705 smp_call_function_single(cpu, check_processor_compat, &c, 1);
4710 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4711 kvm_starting_cpu, kvm_dying_cpu);
4714 register_reboot_notifier(&kvm_reboot_notifier);
4716 /* A kmem cache lets us meet the alignment requirements of fx_save. */
4718 vcpu_align = __alignof__(struct kvm_vcpu);
4720 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4722 offsetof(struct kvm_vcpu, arch),
4723 sizeof_field(struct kvm_vcpu, arch),
4725 if (!kvm_vcpu_cache) {
4730 r = kvm_async_pf_init();
4734 kvm_chardev_ops.owner = module;
4735 kvm_vm_fops.owner = module;
4736 kvm_vcpu_fops.owner = module;
4738 r = misc_register(&kvm_dev);
4740 pr_err("kvm: misc device register failed\n");
4744 register_syscore_ops(&kvm_syscore_ops);
4746 kvm_preempt_ops.sched_in = kvm_sched_in;
4747 kvm_preempt_ops.sched_out = kvm_sched_out;
4751 r = kvm_vfio_ops_init();
4757 kvm_async_pf_deinit();
4759 kmem_cache_destroy(kvm_vcpu_cache);
4761 unregister_reboot_notifier(&kvm_reboot_notifier);
4762 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4764 kvm_arch_hardware_unsetup();
4766 free_cpumask_var(cpus_hardware_enabled);
4774 EXPORT_SYMBOL_GPL(kvm_init);
4778 debugfs_remove_recursive(kvm_debugfs_dir);
4779 misc_deregister(&kvm_dev);
4780 kmem_cache_destroy(kvm_vcpu_cache);
4781 kvm_async_pf_deinit();
4782 unregister_syscore_ops(&kvm_syscore_ops);
4783 unregister_reboot_notifier(&kvm_reboot_notifier);
4784 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4785 on_each_cpu(hardware_disable_nolock, NULL, 1);
4786 kvm_arch_hardware_unsetup();
4789 free_cpumask_var(cpus_hardware_enabled);
4790 kvm_vfio_ops_exit();
4792 EXPORT_SYMBOL_GPL(kvm_exit);
4794 struct kvm_vm_worker_thread_context {
4796 struct task_struct *parent;
4797 struct completion init_done;
4798 kvm_vm_thread_fn_t thread_fn;
4803 static int kvm_vm_worker_thread(void *context)
4806 * The init_context is allocated on the stack of the parent thread, so
4807 * we have to locally copy anything that is needed beyond initialization
4809 struct kvm_vm_worker_thread_context *init_context = context;
4810 struct kvm *kvm = init_context->kvm;
4811 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4812 uintptr_t data = init_context->data;
4815 err = kthread_park(current);
4816 /* kthread_park(current) is never supposed to return an error */
4821 err = cgroup_attach_task_all(init_context->parent, current);
4823 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4828 set_user_nice(current, task_nice(init_context->parent));
4831 init_context->err = err;
4832 complete(&init_context->init_done);
4833 init_context = NULL;
4838 /* Wait to be woken up by the spawner before proceeding. */
4841 if (!kthread_should_stop())
4842 err = thread_fn(kvm, data);
4847 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4848 uintptr_t data, const char *name,
4849 struct task_struct **thread_ptr)
4851 struct kvm_vm_worker_thread_context init_context = {};
4852 struct task_struct *thread;
4855 init_context.kvm = kvm;
4856 init_context.parent = current;
4857 init_context.thread_fn = thread_fn;
4858 init_context.data = data;
4859 init_completion(&init_context.init_done);
4861 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4862 "%s-%d", name, task_pid_nr(current));
4864 return PTR_ERR(thread);
4866 /* kthread_run is never supposed to return NULL */
4867 WARN_ON(thread == NULL);
4869 wait_for_completion(&init_context.init_done);
4871 if (!init_context.err)
4872 *thread_ptr = thread;
4874 return init_context.err;