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>
54 #include <linux/suspend.h>
56 #include <asm/processor.h>
57 #include <asm/ioctl.h>
58 #include <linux/uaccess.h>
60 #include "coalesced_mmio.h"
65 #define CREATE_TRACE_POINTS
66 #include <trace/events/kvm.h>
68 #include <linux/kvm_dirty_ring.h>
70 /* Worst case buffer size needed for holding an integer. */
71 #define ITOA_MAX_LEN 12
73 MODULE_AUTHOR("Qumranet");
74 MODULE_LICENSE("GPL");
76 /* Architectures should define their poll value according to the halt latency */
77 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
78 module_param(halt_poll_ns, uint, 0644);
79 EXPORT_SYMBOL_GPL(halt_poll_ns);
81 /* Default doubles per-vcpu halt_poll_ns. */
82 unsigned int halt_poll_ns_grow = 2;
83 module_param(halt_poll_ns_grow, uint, 0644);
84 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
86 /* The start value to grow halt_poll_ns from */
87 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
88 module_param(halt_poll_ns_grow_start, uint, 0644);
89 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
91 /* Default resets per-vcpu halt_poll_ns . */
92 unsigned int halt_poll_ns_shrink;
93 module_param(halt_poll_ns_shrink, uint, 0644);
94 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
99 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
102 DEFINE_MUTEX(kvm_lock);
103 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
106 static cpumask_var_t cpus_hardware_enabled;
107 static int kvm_usage_count;
108 static atomic_t hardware_enable_failed;
110 static struct kmem_cache *kvm_vcpu_cache;
112 static __read_mostly struct preempt_ops kvm_preempt_ops;
113 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
115 struct dentry *kvm_debugfs_dir;
116 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
118 static const struct file_operations stat_fops_per_vm;
120 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
122 #ifdef CONFIG_KVM_COMPAT
123 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
125 #define KVM_COMPAT(c) .compat_ioctl = (c)
128 * For architectures that don't implement a compat infrastructure,
129 * adopt a double line of defense:
130 * - Prevent a compat task from opening /dev/kvm
131 * - If the open has been done by a 64bit task, and the KVM fd
132 * passed to a compat task, let the ioctls fail.
134 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
135 unsigned long arg) { return -EINVAL; }
137 static int kvm_no_compat_open(struct inode *inode, struct file *file)
139 return is_compat_task() ? -ENODEV : 0;
141 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
142 .open = kvm_no_compat_open
144 static int hardware_enable_all(void);
145 static void hardware_disable_all(void);
147 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
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 static DEFINE_PER_CPU(cpumask_var_t, cpu_kick_mask);
160 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
161 unsigned long start, unsigned long end)
165 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
168 * The metadata used by is_zone_device_page() to determine whether or
169 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
170 * the device has been pinned, e.g. by get_user_pages(). WARN if the
171 * page_count() is zero to help detect bad usage of this helper.
173 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
176 return is_zone_device_page(pfn_to_page(pfn));
179 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
182 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
183 * perspective they are "normal" pages, albeit with slightly different
187 return PageReserved(pfn_to_page(pfn)) &&
189 !kvm_is_zone_device_pfn(pfn);
195 * Switches to specified vcpu, until a matching vcpu_put()
197 void vcpu_load(struct kvm_vcpu *vcpu)
201 __this_cpu_write(kvm_running_vcpu, vcpu);
202 preempt_notifier_register(&vcpu->preempt_notifier);
203 kvm_arch_vcpu_load(vcpu, cpu);
206 EXPORT_SYMBOL_GPL(vcpu_load);
208 void vcpu_put(struct kvm_vcpu *vcpu)
211 kvm_arch_vcpu_put(vcpu);
212 preempt_notifier_unregister(&vcpu->preempt_notifier);
213 __this_cpu_write(kvm_running_vcpu, NULL);
216 EXPORT_SYMBOL_GPL(vcpu_put);
218 /* TODO: merge with kvm_arch_vcpu_should_kick */
219 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
221 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
224 * We need to wait for the VCPU to reenable interrupts and get out of
225 * READING_SHADOW_PAGE_TABLES mode.
227 if (req & KVM_REQUEST_WAIT)
228 return mode != OUTSIDE_GUEST_MODE;
231 * Need to kick a running VCPU, but otherwise there is nothing to do.
233 return mode == IN_GUEST_MODE;
236 static void ack_flush(void *_completed)
240 static inline bool kvm_kick_many_cpus(struct cpumask *cpus, bool wait)
242 if (cpumask_empty(cpus))
245 smp_call_function_many(cpus, ack_flush, NULL, wait);
249 static void kvm_make_vcpu_request(struct kvm *kvm, struct kvm_vcpu *vcpu,
250 unsigned int req, struct cpumask *tmp,
255 kvm_make_request(req, vcpu);
257 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
261 * Note, the vCPU could get migrated to a different pCPU at any point
262 * after kvm_request_needs_ipi(), which could result in sending an IPI
263 * to the previous pCPU. But, that's OK because the purpose of the IPI
264 * is to ensure the vCPU returns to OUTSIDE_GUEST_MODE, which is
265 * satisfied if the vCPU migrates. Entering READING_SHADOW_PAGE_TABLES
266 * after this point is also OK, as the requirement is only that KVM wait
267 * for vCPUs that were reading SPTEs _before_ any changes were
268 * finalized. See kvm_vcpu_kick() for more details on handling requests.
270 if (kvm_request_needs_ipi(vcpu, req)) {
271 cpu = READ_ONCE(vcpu->cpu);
272 if (cpu != -1 && cpu != current_cpu)
273 __cpumask_set_cpu(cpu, tmp);
277 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
278 unsigned long *vcpu_bitmap)
280 struct kvm_vcpu *vcpu;
281 struct cpumask *cpus;
287 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
290 for_each_set_bit(i, vcpu_bitmap, KVM_MAX_VCPUS) {
291 vcpu = kvm_get_vcpu(kvm, i);
294 kvm_make_vcpu_request(kvm, vcpu, req, cpus, me);
297 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
303 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
304 struct kvm_vcpu *except)
306 struct kvm_vcpu *vcpu;
307 struct cpumask *cpus;
314 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
317 kvm_for_each_vcpu(i, vcpu, kvm) {
320 kvm_make_vcpu_request(kvm, vcpu, req, cpus, me);
323 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
329 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
331 return kvm_make_all_cpus_request_except(kvm, req, NULL);
333 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
335 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
336 void kvm_flush_remote_tlbs(struct kvm *kvm)
338 ++kvm->stat.generic.remote_tlb_flush_requests;
341 * We want to publish modifications to the page tables before reading
342 * mode. Pairs with a memory barrier in arch-specific code.
343 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
344 * and smp_mb in walk_shadow_page_lockless_begin/end.
345 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
347 * There is already an smp_mb__after_atomic() before
348 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
351 if (!kvm_arch_flush_remote_tlb(kvm)
352 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
353 ++kvm->stat.generic.remote_tlb_flush;
355 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
358 void kvm_reload_remote_mmus(struct kvm *kvm)
360 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
363 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
364 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
367 gfp_flags |= mc->gfp_zero;
370 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
372 return (void *)__get_free_page(gfp_flags);
375 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
379 if (mc->nobjs >= min)
381 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
382 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
384 return mc->nobjs >= min ? 0 : -ENOMEM;
385 mc->objects[mc->nobjs++] = obj;
390 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
395 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
399 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
401 free_page((unsigned long)mc->objects[--mc->nobjs]);
405 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
409 if (WARN_ON(!mc->nobjs))
410 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
412 p = mc->objects[--mc->nobjs];
418 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
420 mutex_init(&vcpu->mutex);
425 #ifndef __KVM_HAVE_ARCH_WQP
426 rcuwait_init(&vcpu->wait);
428 kvm_async_pf_vcpu_init(vcpu);
430 kvm_vcpu_set_in_spin_loop(vcpu, false);
431 kvm_vcpu_set_dy_eligible(vcpu, false);
432 vcpu->preempted = false;
434 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
435 vcpu->last_used_slot = NULL;
438 static void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
440 kvm_dirty_ring_free(&vcpu->dirty_ring);
441 kvm_arch_vcpu_destroy(vcpu);
444 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
445 * the vcpu->pid pointer, and at destruction time all file descriptors
448 put_pid(rcu_dereference_protected(vcpu->pid, 1));
450 free_page((unsigned long)vcpu->run);
451 kmem_cache_free(kvm_vcpu_cache, vcpu);
454 void kvm_destroy_vcpus(struct kvm *kvm)
457 struct kvm_vcpu *vcpu;
459 kvm_for_each_vcpu(i, vcpu, kvm) {
460 kvm_vcpu_destroy(vcpu);
461 xa_erase(&kvm->vcpu_array, i);
464 atomic_set(&kvm->online_vcpus, 0);
466 EXPORT_SYMBOL_GPL(kvm_destroy_vcpus);
468 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
469 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
471 return container_of(mn, struct kvm, mmu_notifier);
474 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
475 struct mm_struct *mm,
476 unsigned long start, unsigned long end)
478 struct kvm *kvm = mmu_notifier_to_kvm(mn);
481 idx = srcu_read_lock(&kvm->srcu);
482 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
483 srcu_read_unlock(&kvm->srcu, idx);
486 typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
488 typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
491 struct kvm_hva_range {
495 hva_handler_t handler;
496 on_lock_fn_t on_lock;
502 * Use a dedicated stub instead of NULL to indicate that there is no callback
503 * function/handler. The compiler technically can't guarantee that a real
504 * function will have a non-zero address, and so it will generate code to
505 * check for !NULL, whereas comparing against a stub will be elided at compile
506 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
508 static void kvm_null_fn(void)
512 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
514 /* Iterate over each memslot intersecting [start, last] (inclusive) range */
515 #define kvm_for_each_memslot_in_hva_range(node, slots, start, last) \
516 for (node = interval_tree_iter_first(&slots->hva_tree, start, last); \
518 node = interval_tree_iter_next(node, start, last)) \
520 static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
521 const struct kvm_hva_range *range)
523 bool ret = false, locked = false;
524 struct kvm_gfn_range gfn_range;
525 struct kvm_memory_slot *slot;
526 struct kvm_memslots *slots;
529 if (WARN_ON_ONCE(range->end <= range->start))
532 /* A null handler is allowed if and only if on_lock() is provided. */
533 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
534 IS_KVM_NULL_FN(range->handler)))
537 idx = srcu_read_lock(&kvm->srcu);
539 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
540 struct interval_tree_node *node;
542 slots = __kvm_memslots(kvm, i);
543 kvm_for_each_memslot_in_hva_range(node, slots,
544 range->start, range->end - 1) {
545 unsigned long hva_start, hva_end;
547 slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]);
548 hva_start = max(range->start, slot->userspace_addr);
549 hva_end = min(range->end, slot->userspace_addr +
550 (slot->npages << PAGE_SHIFT));
553 * To optimize for the likely case where the address
554 * range is covered by zero or one memslots, don't
555 * bother making these conditional (to avoid writes on
556 * the second or later invocation of the handler).
558 gfn_range.pte = range->pte;
559 gfn_range.may_block = range->may_block;
562 * {gfn(page) | page intersects with [hva_start, hva_end)} =
563 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
565 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
566 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
567 gfn_range.slot = slot;
572 if (!IS_KVM_NULL_FN(range->on_lock))
573 range->on_lock(kvm, range->start, range->end);
574 if (IS_KVM_NULL_FN(range->handler))
577 ret |= range->handler(kvm, &gfn_range);
581 if (range->flush_on_ret && ret)
582 kvm_flush_remote_tlbs(kvm);
587 srcu_read_unlock(&kvm->srcu, idx);
589 /* The notifiers are averse to booleans. :-( */
593 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
597 hva_handler_t handler)
599 struct kvm *kvm = mmu_notifier_to_kvm(mn);
600 const struct kvm_hva_range range = {
605 .on_lock = (void *)kvm_null_fn,
606 .flush_on_ret = true,
610 return __kvm_handle_hva_range(kvm, &range);
613 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
616 hva_handler_t handler)
618 struct kvm *kvm = mmu_notifier_to_kvm(mn);
619 const struct kvm_hva_range range = {
624 .on_lock = (void *)kvm_null_fn,
625 .flush_on_ret = false,
629 return __kvm_handle_hva_range(kvm, &range);
631 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
632 struct mm_struct *mm,
633 unsigned long address,
636 struct kvm *kvm = mmu_notifier_to_kvm(mn);
638 trace_kvm_set_spte_hva(address);
641 * .change_pte() must be surrounded by .invalidate_range_{start,end}().
642 * If mmu_notifier_count is zero, then no in-progress invalidations,
643 * including this one, found a relevant memslot at start(); rechecking
644 * memslots here is unnecessary. Note, a false positive (count elevated
645 * by a different invalidation) is sub-optimal but functionally ok.
647 WARN_ON_ONCE(!READ_ONCE(kvm->mn_active_invalidate_count));
648 if (!READ_ONCE(kvm->mmu_notifier_count))
651 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
654 void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
658 * The count increase must become visible at unlock time as no
659 * spte can be established without taking the mmu_lock and
660 * count is also read inside the mmu_lock critical section.
662 kvm->mmu_notifier_count++;
663 if (likely(kvm->mmu_notifier_count == 1)) {
664 kvm->mmu_notifier_range_start = start;
665 kvm->mmu_notifier_range_end = end;
668 * Fully tracking multiple concurrent ranges has dimishing
669 * returns. Keep things simple and just find the minimal range
670 * which includes the current and new ranges. As there won't be
671 * enough information to subtract a range after its invalidate
672 * completes, any ranges invalidated concurrently will
673 * accumulate and persist until all outstanding invalidates
676 kvm->mmu_notifier_range_start =
677 min(kvm->mmu_notifier_range_start, start);
678 kvm->mmu_notifier_range_end =
679 max(kvm->mmu_notifier_range_end, end);
683 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
684 const struct mmu_notifier_range *range)
686 struct kvm *kvm = mmu_notifier_to_kvm(mn);
687 const struct kvm_hva_range hva_range = {
688 .start = range->start,
691 .handler = kvm_unmap_gfn_range,
692 .on_lock = kvm_inc_notifier_count,
693 .flush_on_ret = true,
694 .may_block = mmu_notifier_range_blockable(range),
697 trace_kvm_unmap_hva_range(range->start, range->end);
700 * Prevent memslot modification between range_start() and range_end()
701 * so that conditionally locking provides the same result in both
702 * functions. Without that guarantee, the mmu_notifier_count
703 * adjustments will be imbalanced.
705 * Pairs with the decrement in range_end().
707 spin_lock(&kvm->mn_invalidate_lock);
708 kvm->mn_active_invalidate_count++;
709 spin_unlock(&kvm->mn_invalidate_lock);
711 gfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end,
712 hva_range.may_block);
714 __kvm_handle_hva_range(kvm, &hva_range);
719 void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
723 * This sequence increase will notify the kvm page fault that
724 * the page that is going to be mapped in the spte could have
727 kvm->mmu_notifier_seq++;
730 * The above sequence increase must be visible before the
731 * below count decrease, which is ensured by the smp_wmb above
732 * in conjunction with the smp_rmb in mmu_notifier_retry().
734 kvm->mmu_notifier_count--;
737 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
738 const struct mmu_notifier_range *range)
740 struct kvm *kvm = mmu_notifier_to_kvm(mn);
741 const struct kvm_hva_range hva_range = {
742 .start = range->start,
745 .handler = (void *)kvm_null_fn,
746 .on_lock = kvm_dec_notifier_count,
747 .flush_on_ret = false,
748 .may_block = mmu_notifier_range_blockable(range),
752 __kvm_handle_hva_range(kvm, &hva_range);
754 /* Pairs with the increment in range_start(). */
755 spin_lock(&kvm->mn_invalidate_lock);
756 wake = (--kvm->mn_active_invalidate_count == 0);
757 spin_unlock(&kvm->mn_invalidate_lock);
760 * There can only be one waiter, since the wait happens under
764 rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
766 BUG_ON(kvm->mmu_notifier_count < 0);
769 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
770 struct mm_struct *mm,
774 trace_kvm_age_hva(start, end);
776 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
779 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
780 struct mm_struct *mm,
784 trace_kvm_age_hva(start, end);
787 * Even though we do not flush TLB, this will still adversely
788 * affect performance on pre-Haswell Intel EPT, where there is
789 * no EPT Access Bit to clear so that we have to tear down EPT
790 * tables instead. If we find this unacceptable, we can always
791 * add a parameter to kvm_age_hva so that it effectively doesn't
792 * do anything on clear_young.
794 * Also note that currently we never issue secondary TLB flushes
795 * from clear_young, leaving this job up to the regular system
796 * cadence. If we find this inaccurate, we might come up with a
797 * more sophisticated heuristic later.
799 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
802 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
803 struct mm_struct *mm,
804 unsigned long address)
806 trace_kvm_test_age_hva(address);
808 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
812 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
813 struct mm_struct *mm)
815 struct kvm *kvm = mmu_notifier_to_kvm(mn);
818 idx = srcu_read_lock(&kvm->srcu);
819 kvm_arch_flush_shadow_all(kvm);
820 srcu_read_unlock(&kvm->srcu, idx);
823 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
824 .invalidate_range = kvm_mmu_notifier_invalidate_range,
825 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
826 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
827 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
828 .clear_young = kvm_mmu_notifier_clear_young,
829 .test_young = kvm_mmu_notifier_test_young,
830 .change_pte = kvm_mmu_notifier_change_pte,
831 .release = kvm_mmu_notifier_release,
834 static int kvm_init_mmu_notifier(struct kvm *kvm)
836 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
837 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
840 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
842 static int kvm_init_mmu_notifier(struct kvm *kvm)
847 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
849 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
850 static int kvm_pm_notifier_call(struct notifier_block *bl,
854 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
856 return kvm_arch_pm_notifier(kvm, state);
859 static void kvm_init_pm_notifier(struct kvm *kvm)
861 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
862 /* Suspend KVM before we suspend ftrace, RCU, etc. */
863 kvm->pm_notifier.priority = INT_MAX;
864 register_pm_notifier(&kvm->pm_notifier);
867 static void kvm_destroy_pm_notifier(struct kvm *kvm)
869 unregister_pm_notifier(&kvm->pm_notifier);
871 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
872 static void kvm_init_pm_notifier(struct kvm *kvm)
876 static void kvm_destroy_pm_notifier(struct kvm *kvm)
879 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
881 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
883 if (!memslot->dirty_bitmap)
886 kvfree(memslot->dirty_bitmap);
887 memslot->dirty_bitmap = NULL;
890 /* This does not remove the slot from struct kvm_memslots data structures */
891 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
893 kvm_destroy_dirty_bitmap(slot);
895 kvm_arch_free_memslot(kvm, slot);
900 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
902 struct hlist_node *idnode;
903 struct kvm_memory_slot *memslot;
907 * The same memslot objects live in both active and inactive sets,
908 * arbitrarily free using index '1' so the second invocation of this
909 * function isn't operating over a structure with dangling pointers
910 * (even though this function isn't actually touching them).
912 if (!slots->node_idx)
915 hash_for_each_safe(slots->id_hash, bkt, idnode, memslot, id_node[1])
916 kvm_free_memslot(kvm, memslot);
919 static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
921 switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
922 case KVM_STATS_TYPE_INSTANT:
924 case KVM_STATS_TYPE_CUMULATIVE:
925 case KVM_STATS_TYPE_PEAK:
932 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
935 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
936 kvm_vcpu_stats_header.num_desc;
938 if (!kvm->debugfs_dentry)
941 debugfs_remove_recursive(kvm->debugfs_dentry);
943 if (kvm->debugfs_stat_data) {
944 for (i = 0; i < kvm_debugfs_num_entries; i++)
945 kfree(kvm->debugfs_stat_data[i]);
946 kfree(kvm->debugfs_stat_data);
950 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
952 static DEFINE_MUTEX(kvm_debugfs_lock);
954 char dir_name[ITOA_MAX_LEN * 2];
955 struct kvm_stat_data *stat_data;
956 const struct _kvm_stats_desc *pdesc;
958 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
959 kvm_vcpu_stats_header.num_desc;
961 if (!debugfs_initialized())
964 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
965 mutex_lock(&kvm_debugfs_lock);
966 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
968 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
970 mutex_unlock(&kvm_debugfs_lock);
973 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
974 mutex_unlock(&kvm_debugfs_lock);
978 kvm->debugfs_dentry = dent;
979 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
980 sizeof(*kvm->debugfs_stat_data),
982 if (!kvm->debugfs_stat_data)
985 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
986 pdesc = &kvm_vm_stats_desc[i];
987 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
991 stat_data->kvm = kvm;
992 stat_data->desc = pdesc;
993 stat_data->kind = KVM_STAT_VM;
994 kvm->debugfs_stat_data[i] = stat_data;
995 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
996 kvm->debugfs_dentry, stat_data,
1000 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
1001 pdesc = &kvm_vcpu_stats_desc[i];
1002 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1006 stat_data->kvm = kvm;
1007 stat_data->desc = pdesc;
1008 stat_data->kind = KVM_STAT_VCPU;
1009 kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
1010 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1011 kvm->debugfs_dentry, stat_data,
1015 ret = kvm_arch_create_vm_debugfs(kvm);
1017 kvm_destroy_vm_debugfs(kvm);
1025 * Called after the VM is otherwise initialized, but just before adding it to
1028 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
1034 * Called just after removing the VM from the vm_list, but before doing any
1035 * other destruction.
1037 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
1042 * Called after per-vm debugfs created. When called kvm->debugfs_dentry should
1043 * be setup already, so we can create arch-specific debugfs entries under it.
1044 * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1045 * a per-arch destroy interface is not needed.
1047 int __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1052 static struct kvm *kvm_create_vm(unsigned long type)
1054 struct kvm *kvm = kvm_arch_alloc_vm();
1055 struct kvm_memslots *slots;
1060 return ERR_PTR(-ENOMEM);
1062 KVM_MMU_LOCK_INIT(kvm);
1063 mmgrab(current->mm);
1064 kvm->mm = current->mm;
1065 kvm_eventfd_init(kvm);
1066 mutex_init(&kvm->lock);
1067 mutex_init(&kvm->irq_lock);
1068 mutex_init(&kvm->slots_lock);
1069 mutex_init(&kvm->slots_arch_lock);
1070 spin_lock_init(&kvm->mn_invalidate_lock);
1071 rcuwait_init(&kvm->mn_memslots_update_rcuwait);
1072 xa_init(&kvm->vcpu_array);
1074 INIT_LIST_HEAD(&kvm->gpc_list);
1075 spin_lock_init(&kvm->gpc_lock);
1077 INIT_LIST_HEAD(&kvm->devices);
1079 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1081 if (init_srcu_struct(&kvm->srcu))
1082 goto out_err_no_srcu;
1083 if (init_srcu_struct(&kvm->irq_srcu))
1084 goto out_err_no_irq_srcu;
1086 refcount_set(&kvm->users_count, 1);
1087 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1088 for (j = 0; j < 2; j++) {
1089 slots = &kvm->__memslots[i][j];
1091 atomic_long_set(&slots->last_used_slot, (unsigned long)NULL);
1092 slots->hva_tree = RB_ROOT_CACHED;
1093 slots->gfn_tree = RB_ROOT;
1094 hash_init(slots->id_hash);
1095 slots->node_idx = j;
1097 /* Generations must be different for each address space. */
1098 slots->generation = i;
1101 rcu_assign_pointer(kvm->memslots[i], &kvm->__memslots[i][0]);
1104 for (i = 0; i < KVM_NR_BUSES; i++) {
1105 rcu_assign_pointer(kvm->buses[i],
1106 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
1108 goto out_err_no_arch_destroy_vm;
1111 kvm->max_halt_poll_ns = halt_poll_ns;
1113 r = kvm_arch_init_vm(kvm, type);
1115 goto out_err_no_arch_destroy_vm;
1117 r = hardware_enable_all();
1119 goto out_err_no_disable;
1121 #ifdef CONFIG_HAVE_KVM_IRQFD
1122 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
1125 r = kvm_init_mmu_notifier(kvm);
1127 goto out_err_no_mmu_notifier;
1129 r = kvm_arch_post_init_vm(kvm);
1133 mutex_lock(&kvm_lock);
1134 list_add(&kvm->vm_list, &vm_list);
1135 mutex_unlock(&kvm_lock);
1137 preempt_notifier_inc();
1138 kvm_init_pm_notifier(kvm);
1143 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1144 if (kvm->mmu_notifier.ops)
1145 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1147 out_err_no_mmu_notifier:
1148 hardware_disable_all();
1150 kvm_arch_destroy_vm(kvm);
1151 out_err_no_arch_destroy_vm:
1152 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
1153 for (i = 0; i < KVM_NR_BUSES; i++)
1154 kfree(kvm_get_bus(kvm, i));
1155 cleanup_srcu_struct(&kvm->irq_srcu);
1156 out_err_no_irq_srcu:
1157 cleanup_srcu_struct(&kvm->srcu);
1159 kvm_arch_free_vm(kvm);
1160 mmdrop(current->mm);
1164 static void kvm_destroy_devices(struct kvm *kvm)
1166 struct kvm_device *dev, *tmp;
1169 * We do not need to take the kvm->lock here, because nobody else
1170 * has a reference to the struct kvm at this point and therefore
1171 * cannot access the devices list anyhow.
1173 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1174 list_del(&dev->vm_node);
1175 dev->ops->destroy(dev);
1179 static void kvm_destroy_vm(struct kvm *kvm)
1182 struct mm_struct *mm = kvm->mm;
1184 kvm_destroy_pm_notifier(kvm);
1185 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1186 kvm_destroy_vm_debugfs(kvm);
1187 kvm_arch_sync_events(kvm);
1188 mutex_lock(&kvm_lock);
1189 list_del(&kvm->vm_list);
1190 mutex_unlock(&kvm_lock);
1191 kvm_arch_pre_destroy_vm(kvm);
1193 kvm_free_irq_routing(kvm);
1194 for (i = 0; i < KVM_NR_BUSES; i++) {
1195 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1198 kvm_io_bus_destroy(bus);
1199 kvm->buses[i] = NULL;
1201 kvm_coalesced_mmio_free(kvm);
1202 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1203 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1205 * At this point, pending calls to invalidate_range_start()
1206 * have completed but no more MMU notifiers will run, so
1207 * mn_active_invalidate_count may remain unbalanced.
1208 * No threads can be waiting in install_new_memslots as the
1209 * last reference on KVM has been dropped, but freeing
1210 * memslots would deadlock without this manual intervention.
1212 WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1213 kvm->mn_active_invalidate_count = 0;
1215 kvm_arch_flush_shadow_all(kvm);
1217 kvm_arch_destroy_vm(kvm);
1218 kvm_destroy_devices(kvm);
1219 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1220 kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
1221 kvm_free_memslots(kvm, &kvm->__memslots[i][1]);
1223 cleanup_srcu_struct(&kvm->irq_srcu);
1224 cleanup_srcu_struct(&kvm->srcu);
1225 kvm_arch_free_vm(kvm);
1226 preempt_notifier_dec();
1227 hardware_disable_all();
1231 void kvm_get_kvm(struct kvm *kvm)
1233 refcount_inc(&kvm->users_count);
1235 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1238 * Make sure the vm is not during destruction, which is a safe version of
1239 * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise.
1241 bool kvm_get_kvm_safe(struct kvm *kvm)
1243 return refcount_inc_not_zero(&kvm->users_count);
1245 EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1247 void kvm_put_kvm(struct kvm *kvm)
1249 if (refcount_dec_and_test(&kvm->users_count))
1250 kvm_destroy_vm(kvm);
1252 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1255 * Used to put a reference that was taken on behalf of an object associated
1256 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1257 * of the new file descriptor fails and the reference cannot be transferred to
1258 * its final owner. In such cases, the caller is still actively using @kvm and
1259 * will fail miserably if the refcount unexpectedly hits zero.
1261 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1263 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1265 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1267 static int kvm_vm_release(struct inode *inode, struct file *filp)
1269 struct kvm *kvm = filp->private_data;
1271 kvm_irqfd_release(kvm);
1278 * Allocation size is twice as large as the actual dirty bitmap size.
1279 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1281 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1283 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
1285 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
1286 if (!memslot->dirty_bitmap)
1292 static struct kvm_memslots *kvm_get_inactive_memslots(struct kvm *kvm, int as_id)
1294 struct kvm_memslots *active = __kvm_memslots(kvm, as_id);
1295 int node_idx_inactive = active->node_idx ^ 1;
1297 return &kvm->__memslots[as_id][node_idx_inactive];
1301 * Helper to get the address space ID when one of memslot pointers may be NULL.
1302 * This also serves as a sanity that at least one of the pointers is non-NULL,
1303 * and that their address space IDs don't diverge.
1305 static int kvm_memslots_get_as_id(struct kvm_memory_slot *a,
1306 struct kvm_memory_slot *b)
1308 if (WARN_ON_ONCE(!a && !b))
1316 WARN_ON_ONCE(a->as_id != b->as_id);
1320 static void kvm_insert_gfn_node(struct kvm_memslots *slots,
1321 struct kvm_memory_slot *slot)
1323 struct rb_root *gfn_tree = &slots->gfn_tree;
1324 struct rb_node **node, *parent;
1325 int idx = slots->node_idx;
1328 for (node = &gfn_tree->rb_node; *node; ) {
1329 struct kvm_memory_slot *tmp;
1331 tmp = container_of(*node, struct kvm_memory_slot, gfn_node[idx]);
1333 if (slot->base_gfn < tmp->base_gfn)
1334 node = &(*node)->rb_left;
1335 else if (slot->base_gfn > tmp->base_gfn)
1336 node = &(*node)->rb_right;
1341 rb_link_node(&slot->gfn_node[idx], parent, node);
1342 rb_insert_color(&slot->gfn_node[idx], gfn_tree);
1345 static void kvm_erase_gfn_node(struct kvm_memslots *slots,
1346 struct kvm_memory_slot *slot)
1348 rb_erase(&slot->gfn_node[slots->node_idx], &slots->gfn_tree);
1351 static void kvm_replace_gfn_node(struct kvm_memslots *slots,
1352 struct kvm_memory_slot *old,
1353 struct kvm_memory_slot *new)
1355 int idx = slots->node_idx;
1357 WARN_ON_ONCE(old->base_gfn != new->base_gfn);
1359 rb_replace_node(&old->gfn_node[idx], &new->gfn_node[idx],
1364 * Replace @old with @new in the inactive memslots.
1366 * With NULL @old this simply adds @new.
1367 * With NULL @new this simply removes @old.
1369 * If @new is non-NULL its hva_node[slots_idx] range has to be set
1372 static void kvm_replace_memslot(struct kvm *kvm,
1373 struct kvm_memory_slot *old,
1374 struct kvm_memory_slot *new)
1376 int as_id = kvm_memslots_get_as_id(old, new);
1377 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1378 int idx = slots->node_idx;
1381 hash_del(&old->id_node[idx]);
1382 interval_tree_remove(&old->hva_node[idx], &slots->hva_tree);
1384 if ((long)old == atomic_long_read(&slots->last_used_slot))
1385 atomic_long_set(&slots->last_used_slot, (long)new);
1388 kvm_erase_gfn_node(slots, old);
1394 * Initialize @new's hva range. Do this even when replacing an @old
1395 * slot, kvm_copy_memslot() deliberately does not touch node data.
1397 new->hva_node[idx].start = new->userspace_addr;
1398 new->hva_node[idx].last = new->userspace_addr +
1399 (new->npages << PAGE_SHIFT) - 1;
1402 * (Re)Add the new memslot. There is no O(1) interval_tree_replace(),
1403 * hva_node needs to be swapped with remove+insert even though hva can't
1404 * change when replacing an existing slot.
1406 hash_add(slots->id_hash, &new->id_node[idx], new->id);
1407 interval_tree_insert(&new->hva_node[idx], &slots->hva_tree);
1410 * If the memslot gfn is unchanged, rb_replace_node() can be used to
1411 * switch the node in the gfn tree instead of removing the old and
1412 * inserting the new as two separate operations. Replacement is a
1413 * single O(1) operation versus two O(log(n)) operations for
1416 if (old && old->base_gfn == new->base_gfn) {
1417 kvm_replace_gfn_node(slots, old, new);
1420 kvm_erase_gfn_node(slots, old);
1421 kvm_insert_gfn_node(slots, new);
1425 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1427 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1429 #ifdef __KVM_HAVE_READONLY_MEM
1430 valid_flags |= KVM_MEM_READONLY;
1433 if (mem->flags & ~valid_flags)
1439 static void kvm_swap_active_memslots(struct kvm *kvm, int as_id)
1441 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1443 /* Grab the generation from the activate memslots. */
1444 u64 gen = __kvm_memslots(kvm, as_id)->generation;
1446 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1447 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1450 * Do not store the new memslots while there are invalidations in
1451 * progress, otherwise the locking in invalidate_range_start and
1452 * invalidate_range_end will be unbalanced.
1454 spin_lock(&kvm->mn_invalidate_lock);
1455 prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1456 while (kvm->mn_active_invalidate_count) {
1457 set_current_state(TASK_UNINTERRUPTIBLE);
1458 spin_unlock(&kvm->mn_invalidate_lock);
1460 spin_lock(&kvm->mn_invalidate_lock);
1462 finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
1463 rcu_assign_pointer(kvm->memslots[as_id], slots);
1464 spin_unlock(&kvm->mn_invalidate_lock);
1467 * Acquired in kvm_set_memslot. Must be released before synchronize
1468 * SRCU below in order to avoid deadlock with another thread
1469 * acquiring the slots_arch_lock in an srcu critical section.
1471 mutex_unlock(&kvm->slots_arch_lock);
1473 synchronize_srcu_expedited(&kvm->srcu);
1476 * Increment the new memslot generation a second time, dropping the
1477 * update in-progress flag and incrementing the generation based on
1478 * the number of address spaces. This provides a unique and easily
1479 * identifiable generation number while the memslots are in flux.
1481 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1484 * Generations must be unique even across address spaces. We do not need
1485 * a global counter for that, instead the generation space is evenly split
1486 * across address spaces. For example, with two address spaces, address
1487 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1488 * use generations 1, 3, 5, ...
1490 gen += KVM_ADDRESS_SPACE_NUM;
1492 kvm_arch_memslots_updated(kvm, gen);
1494 slots->generation = gen;
1497 static int kvm_prepare_memory_region(struct kvm *kvm,
1498 const struct kvm_memory_slot *old,
1499 struct kvm_memory_slot *new,
1500 enum kvm_mr_change change)
1505 * If dirty logging is disabled, nullify the bitmap; the old bitmap
1506 * will be freed on "commit". If logging is enabled in both old and
1507 * new, reuse the existing bitmap. If logging is enabled only in the
1508 * new and KVM isn't using a ring buffer, allocate and initialize a
1511 if (change != KVM_MR_DELETE) {
1512 if (!(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
1513 new->dirty_bitmap = NULL;
1514 else if (old && old->dirty_bitmap)
1515 new->dirty_bitmap = old->dirty_bitmap;
1516 else if (!kvm->dirty_ring_size) {
1517 r = kvm_alloc_dirty_bitmap(new);
1521 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1522 bitmap_set(new->dirty_bitmap, 0, new->npages);
1526 r = kvm_arch_prepare_memory_region(kvm, old, new, change);
1528 /* Free the bitmap on failure if it was allocated above. */
1529 if (r && new && new->dirty_bitmap && old && !old->dirty_bitmap)
1530 kvm_destroy_dirty_bitmap(new);
1535 static void kvm_commit_memory_region(struct kvm *kvm,
1536 struct kvm_memory_slot *old,
1537 const struct kvm_memory_slot *new,
1538 enum kvm_mr_change change)
1541 * Update the total number of memslot pages before calling the arch
1542 * hook so that architectures can consume the result directly.
1544 if (change == KVM_MR_DELETE)
1545 kvm->nr_memslot_pages -= old->npages;
1546 else if (change == KVM_MR_CREATE)
1547 kvm->nr_memslot_pages += new->npages;
1549 kvm_arch_commit_memory_region(kvm, old, new, change);
1553 /* Nothing more to do. */
1556 /* Free the old memslot and all its metadata. */
1557 kvm_free_memslot(kvm, old);
1560 case KVM_MR_FLAGS_ONLY:
1562 * Free the dirty bitmap as needed; the below check encompasses
1563 * both the flags and whether a ring buffer is being used)
1565 if (old->dirty_bitmap && !new->dirty_bitmap)
1566 kvm_destroy_dirty_bitmap(old);
1569 * The final quirk. Free the detached, old slot, but only its
1570 * memory, not any metadata. Metadata, including arch specific
1571 * data, may be reused by @new.
1581 * Activate @new, which must be installed in the inactive slots by the caller,
1582 * by swapping the active slots and then propagating @new to @old once @old is
1583 * unreachable and can be safely modified.
1585 * With NULL @old this simply adds @new to @active (while swapping the sets).
1586 * With NULL @new this simply removes @old from @active and frees it
1587 * (while also swapping the sets).
1589 static void kvm_activate_memslot(struct kvm *kvm,
1590 struct kvm_memory_slot *old,
1591 struct kvm_memory_slot *new)
1593 int as_id = kvm_memslots_get_as_id(old, new);
1595 kvm_swap_active_memslots(kvm, as_id);
1597 /* Propagate the new memslot to the now inactive memslots. */
1598 kvm_replace_memslot(kvm, old, new);
1601 static void kvm_copy_memslot(struct kvm_memory_slot *dest,
1602 const struct kvm_memory_slot *src)
1604 dest->base_gfn = src->base_gfn;
1605 dest->npages = src->npages;
1606 dest->dirty_bitmap = src->dirty_bitmap;
1607 dest->arch = src->arch;
1608 dest->userspace_addr = src->userspace_addr;
1609 dest->flags = src->flags;
1611 dest->as_id = src->as_id;
1614 static void kvm_invalidate_memslot(struct kvm *kvm,
1615 struct kvm_memory_slot *old,
1616 struct kvm_memory_slot *invalid_slot)
1619 * Mark the current slot INVALID. As with all memslot modifications,
1620 * this must be done on an unreachable slot to avoid modifying the
1621 * current slot in the active tree.
1623 kvm_copy_memslot(invalid_slot, old);
1624 invalid_slot->flags |= KVM_MEMSLOT_INVALID;
1625 kvm_replace_memslot(kvm, old, invalid_slot);
1628 * Activate the slot that is now marked INVALID, but don't propagate
1629 * the slot to the now inactive slots. The slot is either going to be
1630 * deleted or recreated as a new slot.
1632 kvm_swap_active_memslots(kvm, old->as_id);
1635 * From this point no new shadow pages pointing to a deleted, or moved,
1636 * memslot will be created. Validation of sp->gfn happens in:
1637 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1638 * - kvm_is_visible_gfn (mmu_check_root)
1640 kvm_arch_flush_shadow_memslot(kvm, old);
1642 /* Was released by kvm_swap_active_memslots, reacquire. */
1643 mutex_lock(&kvm->slots_arch_lock);
1646 * Copy the arch-specific field of the newly-installed slot back to the
1647 * old slot as the arch data could have changed between releasing
1648 * slots_arch_lock in install_new_memslots() and re-acquiring the lock
1649 * above. Writers are required to retrieve memslots *after* acquiring
1650 * slots_arch_lock, thus the active slot's data is guaranteed to be fresh.
1652 old->arch = invalid_slot->arch;
1655 static void kvm_create_memslot(struct kvm *kvm,
1656 struct kvm_memory_slot *new)
1658 /* Add the new memslot to the inactive set and activate. */
1659 kvm_replace_memslot(kvm, NULL, new);
1660 kvm_activate_memslot(kvm, NULL, new);
1663 static void kvm_delete_memslot(struct kvm *kvm,
1664 struct kvm_memory_slot *old,
1665 struct kvm_memory_slot *invalid_slot)
1668 * Remove the old memslot (in the inactive memslots) by passing NULL as
1669 * the "new" slot, and for the invalid version in the active slots.
1671 kvm_replace_memslot(kvm, old, NULL);
1672 kvm_activate_memslot(kvm, invalid_slot, NULL);
1675 static void kvm_move_memslot(struct kvm *kvm,
1676 struct kvm_memory_slot *old,
1677 struct kvm_memory_slot *new,
1678 struct kvm_memory_slot *invalid_slot)
1681 * Replace the old memslot in the inactive slots, and then swap slots
1682 * and replace the current INVALID with the new as well.
1684 kvm_replace_memslot(kvm, old, new);
1685 kvm_activate_memslot(kvm, invalid_slot, new);
1688 static void kvm_update_flags_memslot(struct kvm *kvm,
1689 struct kvm_memory_slot *old,
1690 struct kvm_memory_slot *new)
1693 * Similar to the MOVE case, but the slot doesn't need to be zapped as
1694 * an intermediate step. Instead, the old memslot is simply replaced
1695 * with a new, updated copy in both memslot sets.
1697 kvm_replace_memslot(kvm, old, new);
1698 kvm_activate_memslot(kvm, old, new);
1701 static int kvm_set_memslot(struct kvm *kvm,
1702 struct kvm_memory_slot *old,
1703 struct kvm_memory_slot *new,
1704 enum kvm_mr_change change)
1706 struct kvm_memory_slot *invalid_slot;
1710 * Released in kvm_swap_active_memslots.
1712 * Must be held from before the current memslots are copied until
1713 * after the new memslots are installed with rcu_assign_pointer,
1714 * then released before the synchronize srcu in kvm_swap_active_memslots.
1716 * When modifying memslots outside of the slots_lock, must be held
1717 * before reading the pointer to the current memslots until after all
1718 * changes to those memslots are complete.
1720 * These rules ensure that installing new memslots does not lose
1721 * changes made to the previous memslots.
1723 mutex_lock(&kvm->slots_arch_lock);
1726 * Invalidate the old slot if it's being deleted or moved. This is
1727 * done prior to actually deleting/moving the memslot to allow vCPUs to
1728 * continue running by ensuring there are no mappings or shadow pages
1729 * for the memslot when it is deleted/moved. Without pre-invalidation
1730 * (and without a lock), a window would exist between effecting the
1731 * delete/move and committing the changes in arch code where KVM or a
1732 * guest could access a non-existent memslot.
1734 * Modifications are done on a temporary, unreachable slot. The old
1735 * slot needs to be preserved in case a later step fails and the
1736 * invalidation needs to be reverted.
1738 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1739 invalid_slot = kzalloc(sizeof(*invalid_slot), GFP_KERNEL_ACCOUNT);
1740 if (!invalid_slot) {
1741 mutex_unlock(&kvm->slots_arch_lock);
1744 kvm_invalidate_memslot(kvm, old, invalid_slot);
1747 r = kvm_prepare_memory_region(kvm, old, new, change);
1750 * For DELETE/MOVE, revert the above INVALID change. No
1751 * modifications required since the original slot was preserved
1752 * in the inactive slots. Changing the active memslots also
1753 * release slots_arch_lock.
1755 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1756 kvm_activate_memslot(kvm, invalid_slot, old);
1757 kfree(invalid_slot);
1759 mutex_unlock(&kvm->slots_arch_lock);
1765 * For DELETE and MOVE, the working slot is now active as the INVALID
1766 * version of the old slot. MOVE is particularly special as it reuses
1767 * the old slot and returns a copy of the old slot (in working_slot).
1768 * For CREATE, there is no old slot. For DELETE and FLAGS_ONLY, the
1769 * old slot is detached but otherwise preserved.
1771 if (change == KVM_MR_CREATE)
1772 kvm_create_memslot(kvm, new);
1773 else if (change == KVM_MR_DELETE)
1774 kvm_delete_memslot(kvm, old, invalid_slot);
1775 else if (change == KVM_MR_MOVE)
1776 kvm_move_memslot(kvm, old, new, invalid_slot);
1777 else if (change == KVM_MR_FLAGS_ONLY)
1778 kvm_update_flags_memslot(kvm, old, new);
1782 /* Free the temporary INVALID slot used for DELETE and MOVE. */
1783 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1784 kfree(invalid_slot);
1787 * No need to refresh new->arch, changes after dropping slots_arch_lock
1788 * will directly hit the final, active memsot. Architectures are
1789 * responsible for knowing that new->arch may be stale.
1791 kvm_commit_memory_region(kvm, old, new, change);
1796 static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
1797 gfn_t start, gfn_t end)
1799 struct kvm_memslot_iter iter;
1801 kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
1802 if (iter.slot->id != id)
1810 * Allocate some memory and give it an address in the guest physical address
1813 * Discontiguous memory is allowed, mostly for framebuffers.
1815 * Must be called holding kvm->slots_lock for write.
1817 int __kvm_set_memory_region(struct kvm *kvm,
1818 const struct kvm_userspace_memory_region *mem)
1820 struct kvm_memory_slot *old, *new;
1821 struct kvm_memslots *slots;
1822 enum kvm_mr_change change;
1823 unsigned long npages;
1828 r = check_memory_region_flags(mem);
1832 as_id = mem->slot >> 16;
1833 id = (u16)mem->slot;
1835 /* General sanity checks */
1836 if ((mem->memory_size & (PAGE_SIZE - 1)) ||
1837 (mem->memory_size != (unsigned long)mem->memory_size))
1839 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1841 /* We can read the guest memory with __xxx_user() later on. */
1842 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1843 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1844 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1847 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1849 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1851 if ((mem->memory_size >> PAGE_SHIFT) > KVM_MEM_MAX_NR_PAGES)
1854 slots = __kvm_memslots(kvm, as_id);
1857 * Note, the old memslot (and the pointer itself!) may be invalidated
1858 * and/or destroyed by kvm_set_memslot().
1860 old = id_to_memslot(slots, id);
1862 if (!mem->memory_size) {
1863 if (!old || !old->npages)
1866 if (WARN_ON_ONCE(kvm->nr_memslot_pages < old->npages))
1869 return kvm_set_memslot(kvm, old, NULL, KVM_MR_DELETE);
1872 base_gfn = (mem->guest_phys_addr >> PAGE_SHIFT);
1873 npages = (mem->memory_size >> PAGE_SHIFT);
1875 if (!old || !old->npages) {
1876 change = KVM_MR_CREATE;
1879 * To simplify KVM internals, the total number of pages across
1880 * all memslots must fit in an unsigned long.
1882 if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages)
1884 } else { /* Modify an existing slot. */
1885 if ((mem->userspace_addr != old->userspace_addr) ||
1886 (npages != old->npages) ||
1887 ((mem->flags ^ old->flags) & KVM_MEM_READONLY))
1890 if (base_gfn != old->base_gfn)
1891 change = KVM_MR_MOVE;
1892 else if (mem->flags != old->flags)
1893 change = KVM_MR_FLAGS_ONLY;
1894 else /* Nothing to change. */
1898 if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) &&
1899 kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages))
1902 /* Allocate a slot that will persist in the memslot. */
1903 new = kzalloc(sizeof(*new), GFP_KERNEL_ACCOUNT);
1909 new->base_gfn = base_gfn;
1910 new->npages = npages;
1911 new->flags = mem->flags;
1912 new->userspace_addr = mem->userspace_addr;
1914 r = kvm_set_memslot(kvm, old, new, change);
1919 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1921 int kvm_set_memory_region(struct kvm *kvm,
1922 const struct kvm_userspace_memory_region *mem)
1926 mutex_lock(&kvm->slots_lock);
1927 r = __kvm_set_memory_region(kvm, mem);
1928 mutex_unlock(&kvm->slots_lock);
1931 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1933 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1934 struct kvm_userspace_memory_region *mem)
1936 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1939 return kvm_set_memory_region(kvm, mem);
1942 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1944 * kvm_get_dirty_log - get a snapshot of dirty pages
1945 * @kvm: pointer to kvm instance
1946 * @log: slot id and address to which we copy the log
1947 * @is_dirty: set to '1' if any dirty pages were found
1948 * @memslot: set to the associated memslot, always valid on success
1950 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1951 int *is_dirty, struct kvm_memory_slot **memslot)
1953 struct kvm_memslots *slots;
1956 unsigned long any = 0;
1958 /* Dirty ring tracking is exclusive to dirty log tracking */
1959 if (kvm->dirty_ring_size)
1965 as_id = log->slot >> 16;
1966 id = (u16)log->slot;
1967 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1970 slots = __kvm_memslots(kvm, as_id);
1971 *memslot = id_to_memslot(slots, id);
1972 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1975 kvm_arch_sync_dirty_log(kvm, *memslot);
1977 n = kvm_dirty_bitmap_bytes(*memslot);
1979 for (i = 0; !any && i < n/sizeof(long); ++i)
1980 any = (*memslot)->dirty_bitmap[i];
1982 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1989 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1991 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1993 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1994 * and reenable dirty page tracking for the corresponding pages.
1995 * @kvm: pointer to kvm instance
1996 * @log: slot id and address to which we copy the log
1998 * We need to keep it in mind that VCPU threads can write to the bitmap
1999 * concurrently. So, to avoid losing track of dirty pages we keep the
2002 * 1. Take a snapshot of the bit and clear it if needed.
2003 * 2. Write protect the corresponding page.
2004 * 3. Copy the snapshot to the userspace.
2005 * 4. Upon return caller flushes TLB's if needed.
2007 * Between 2 and 4, the guest may write to the page using the remaining TLB
2008 * entry. This is not a problem because the page is reported dirty using
2009 * the snapshot taken before and step 4 ensures that writes done after
2010 * exiting to userspace will be logged for the next call.
2013 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
2015 struct kvm_memslots *slots;
2016 struct kvm_memory_slot *memslot;
2019 unsigned long *dirty_bitmap;
2020 unsigned long *dirty_bitmap_buffer;
2023 /* Dirty ring tracking is exclusive to dirty log tracking */
2024 if (kvm->dirty_ring_size)
2027 as_id = log->slot >> 16;
2028 id = (u16)log->slot;
2029 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2032 slots = __kvm_memslots(kvm, as_id);
2033 memslot = id_to_memslot(slots, id);
2034 if (!memslot || !memslot->dirty_bitmap)
2037 dirty_bitmap = memslot->dirty_bitmap;
2039 kvm_arch_sync_dirty_log(kvm, memslot);
2041 n = kvm_dirty_bitmap_bytes(memslot);
2043 if (kvm->manual_dirty_log_protect) {
2045 * Unlike kvm_get_dirty_log, we always return false in *flush,
2046 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
2047 * is some code duplication between this function and
2048 * kvm_get_dirty_log, but hopefully all architecture
2049 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
2050 * can be eliminated.
2052 dirty_bitmap_buffer = dirty_bitmap;
2054 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2055 memset(dirty_bitmap_buffer, 0, n);
2058 for (i = 0; i < n / sizeof(long); i++) {
2062 if (!dirty_bitmap[i])
2066 mask = xchg(&dirty_bitmap[i], 0);
2067 dirty_bitmap_buffer[i] = mask;
2069 offset = i * BITS_PER_LONG;
2070 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2073 KVM_MMU_UNLOCK(kvm);
2077 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2079 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
2086 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
2087 * @kvm: kvm instance
2088 * @log: slot id and address to which we copy the log
2090 * Steps 1-4 below provide general overview of dirty page logging. See
2091 * kvm_get_dirty_log_protect() function description for additional details.
2093 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
2094 * always flush the TLB (step 4) even if previous step failed and the dirty
2095 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
2096 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
2097 * writes will be marked dirty for next log read.
2099 * 1. Take a snapshot of the bit and clear it if needed.
2100 * 2. Write protect the corresponding page.
2101 * 3. Copy the snapshot to the userspace.
2102 * 4. Flush TLB's if needed.
2104 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2105 struct kvm_dirty_log *log)
2109 mutex_lock(&kvm->slots_lock);
2111 r = kvm_get_dirty_log_protect(kvm, log);
2113 mutex_unlock(&kvm->slots_lock);
2118 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
2119 * and reenable dirty page tracking for the corresponding pages.
2120 * @kvm: pointer to kvm instance
2121 * @log: slot id and address from which to fetch the bitmap of dirty pages
2123 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
2124 struct kvm_clear_dirty_log *log)
2126 struct kvm_memslots *slots;
2127 struct kvm_memory_slot *memslot;
2131 unsigned long *dirty_bitmap;
2132 unsigned long *dirty_bitmap_buffer;
2135 /* Dirty ring tracking is exclusive to dirty log tracking */
2136 if (kvm->dirty_ring_size)
2139 as_id = log->slot >> 16;
2140 id = (u16)log->slot;
2141 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2144 if (log->first_page & 63)
2147 slots = __kvm_memslots(kvm, as_id);
2148 memslot = id_to_memslot(slots, id);
2149 if (!memslot || !memslot->dirty_bitmap)
2152 dirty_bitmap = memslot->dirty_bitmap;
2154 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
2156 if (log->first_page > memslot->npages ||
2157 log->num_pages > memslot->npages - log->first_page ||
2158 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
2161 kvm_arch_sync_dirty_log(kvm, memslot);
2164 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2165 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2169 for (offset = log->first_page, i = offset / BITS_PER_LONG,
2170 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2171 i++, offset += BITS_PER_LONG) {
2172 unsigned long mask = *dirty_bitmap_buffer++;
2173 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2177 mask &= atomic_long_fetch_andnot(mask, p);
2180 * mask contains the bits that really have been cleared. This
2181 * never includes any bits beyond the length of the memslot (if
2182 * the length is not aligned to 64 pages), therefore it is not
2183 * a problem if userspace sets them in log->dirty_bitmap.
2187 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2191 KVM_MMU_UNLOCK(kvm);
2194 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2199 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2200 struct kvm_clear_dirty_log *log)
2204 mutex_lock(&kvm->slots_lock);
2206 r = kvm_clear_dirty_log_protect(kvm, log);
2208 mutex_unlock(&kvm->slots_lock);
2211 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2213 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2215 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2217 EXPORT_SYMBOL_GPL(gfn_to_memslot);
2219 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2221 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2222 u64 gen = slots->generation;
2223 struct kvm_memory_slot *slot;
2226 * This also protects against using a memslot from a different address space,
2227 * since different address spaces have different generation numbers.
2229 if (unlikely(gen != vcpu->last_used_slot_gen)) {
2230 vcpu->last_used_slot = NULL;
2231 vcpu->last_used_slot_gen = gen;
2234 slot = try_get_memslot(vcpu->last_used_slot, gfn);
2239 * Fall back to searching all memslots. We purposely use
2240 * search_memslots() instead of __gfn_to_memslot() to avoid
2241 * thrashing the VM-wide last_used_slot in kvm_memslots.
2243 slot = search_memslots(slots, gfn, false);
2245 vcpu->last_used_slot = slot;
2252 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
2254 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
2256 return kvm_is_visible_memslot(memslot);
2258 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2260 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2262 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2264 return kvm_is_visible_memslot(memslot);
2266 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2268 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
2270 struct vm_area_struct *vma;
2271 unsigned long addr, size;
2275 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
2276 if (kvm_is_error_hva(addr))
2279 mmap_read_lock(current->mm);
2280 vma = find_vma(current->mm, addr);
2284 size = vma_kernel_pagesize(vma);
2287 mmap_read_unlock(current->mm);
2292 static bool memslot_is_readonly(const struct kvm_memory_slot *slot)
2294 return slot->flags & KVM_MEM_READONLY;
2297 static unsigned long __gfn_to_hva_many(const struct kvm_memory_slot *slot, gfn_t gfn,
2298 gfn_t *nr_pages, bool write)
2300 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
2301 return KVM_HVA_ERR_BAD;
2303 if (memslot_is_readonly(slot) && write)
2304 return KVM_HVA_ERR_RO_BAD;
2307 *nr_pages = slot->npages - (gfn - slot->base_gfn);
2309 return __gfn_to_hva_memslot(slot, gfn);
2312 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2315 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2318 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2321 return gfn_to_hva_many(slot, gfn, NULL);
2323 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2325 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2327 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2329 EXPORT_SYMBOL_GPL(gfn_to_hva);
2331 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2333 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2335 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2338 * Return the hva of a @gfn and the R/W attribute if possible.
2340 * @slot: the kvm_memory_slot which contains @gfn
2341 * @gfn: the gfn to be translated
2342 * @writable: used to return the read/write attribute of the @slot if the hva
2343 * is valid and @writable is not NULL
2345 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2346 gfn_t gfn, bool *writable)
2348 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2350 if (!kvm_is_error_hva(hva) && writable)
2351 *writable = !memslot_is_readonly(slot);
2356 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2358 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2360 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2363 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2365 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2367 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2370 static inline int check_user_page_hwpoison(unsigned long addr)
2372 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
2374 rc = get_user_pages(addr, 1, flags, NULL, NULL);
2375 return rc == -EHWPOISON;
2379 * The fast path to get the writable pfn which will be stored in @pfn,
2380 * true indicates success, otherwise false is returned. It's also the
2381 * only part that runs if we can in atomic context.
2383 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2384 bool *writable, kvm_pfn_t *pfn)
2386 struct page *page[1];
2389 * Fast pin a writable pfn only if it is a write fault request
2390 * or the caller allows to map a writable pfn for a read fault
2393 if (!(write_fault || writable))
2396 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2397 *pfn = page_to_pfn(page[0]);
2408 * The slow path to get the pfn of the specified host virtual address,
2409 * 1 indicates success, -errno is returned if error is detected.
2411 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2412 bool *writable, kvm_pfn_t *pfn)
2414 unsigned int flags = FOLL_HWPOISON;
2421 *writable = write_fault;
2424 flags |= FOLL_WRITE;
2426 flags |= FOLL_NOWAIT;
2428 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2432 /* map read fault as writable if possible */
2433 if (unlikely(!write_fault) && writable) {
2436 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2442 *pfn = page_to_pfn(page);
2446 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2448 if (unlikely(!(vma->vm_flags & VM_READ)))
2451 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2457 static int kvm_try_get_pfn(kvm_pfn_t pfn)
2459 if (kvm_is_reserved_pfn(pfn))
2461 return get_page_unless_zero(pfn_to_page(pfn));
2464 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2465 unsigned long addr, bool write_fault,
2466 bool *writable, kvm_pfn_t *p_pfn)
2473 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2476 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2477 * not call the fault handler, so do it here.
2479 bool unlocked = false;
2480 r = fixup_user_fault(current->mm, addr,
2481 (write_fault ? FAULT_FLAG_WRITE : 0),
2488 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2493 if (write_fault && !pte_write(*ptep)) {
2494 pfn = KVM_PFN_ERR_RO_FAULT;
2499 *writable = pte_write(*ptep);
2500 pfn = pte_pfn(*ptep);
2503 * Get a reference here because callers of *hva_to_pfn* and
2504 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2505 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2506 * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
2507 * simply do nothing for reserved pfns.
2509 * Whoever called remap_pfn_range is also going to call e.g.
2510 * unmap_mapping_range before the underlying pages are freed,
2511 * causing a call to our MMU notifier.
2513 * Certain IO or PFNMAP mappings can be backed with valid
2514 * struct pages, but be allocated without refcounting e.g.,
2515 * tail pages of non-compound higher order allocations, which
2516 * would then underflow the refcount when the caller does the
2517 * required put_page. Don't allow those pages here.
2519 if (!kvm_try_get_pfn(pfn))
2523 pte_unmap_unlock(ptep, ptl);
2530 * Pin guest page in memory and return its pfn.
2531 * @addr: host virtual address which maps memory to the guest
2532 * @atomic: whether this function can sleep
2533 * @async: whether this function need to wait IO complete if the
2534 * host page is not in the memory
2535 * @write_fault: whether we should get a writable host page
2536 * @writable: whether it allows to map a writable host page for !@write_fault
2538 * The function will map a writable host page for these two cases:
2539 * 1): @write_fault = true
2540 * 2): @write_fault = false && @writable, @writable will tell the caller
2541 * whether the mapping is writable.
2543 kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2544 bool write_fault, bool *writable)
2546 struct vm_area_struct *vma;
2550 /* we can do it either atomically or asynchronously, not both */
2551 BUG_ON(atomic && async);
2553 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2557 return KVM_PFN_ERR_FAULT;
2559 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2563 mmap_read_lock(current->mm);
2564 if (npages == -EHWPOISON ||
2565 (!async && check_user_page_hwpoison(addr))) {
2566 pfn = KVM_PFN_ERR_HWPOISON;
2571 vma = vma_lookup(current->mm, addr);
2574 pfn = KVM_PFN_ERR_FAULT;
2575 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2576 r = hva_to_pfn_remapped(vma, addr, write_fault, writable, &pfn);
2580 pfn = KVM_PFN_ERR_FAULT;
2582 if (async && vma_is_valid(vma, write_fault))
2584 pfn = KVM_PFN_ERR_FAULT;
2587 mmap_read_unlock(current->mm);
2591 kvm_pfn_t __gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn,
2592 bool atomic, bool *async, bool write_fault,
2593 bool *writable, hva_t *hva)
2595 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2600 if (addr == KVM_HVA_ERR_RO_BAD) {
2603 return KVM_PFN_ERR_RO_FAULT;
2606 if (kvm_is_error_hva(addr)) {
2609 return KVM_PFN_NOSLOT;
2612 /* Do not map writable pfn in the readonly memslot. */
2613 if (writable && memslot_is_readonly(slot)) {
2618 return hva_to_pfn(addr, atomic, async, write_fault,
2621 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2623 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2626 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2627 write_fault, writable, NULL);
2629 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2631 kvm_pfn_t gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn)
2633 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2635 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2637 kvm_pfn_t gfn_to_pfn_memslot_atomic(const struct kvm_memory_slot *slot, gfn_t gfn)
2639 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2641 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2643 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2645 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2647 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2649 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2651 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2653 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2655 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2657 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2659 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2661 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2662 struct page **pages, int nr_pages)
2667 addr = gfn_to_hva_many(slot, gfn, &entry);
2668 if (kvm_is_error_hva(addr))
2671 if (entry < nr_pages)
2674 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2676 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2678 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2680 if (is_error_noslot_pfn(pfn))
2681 return KVM_ERR_PTR_BAD_PAGE;
2683 if (kvm_is_reserved_pfn(pfn)) {
2685 return KVM_ERR_PTR_BAD_PAGE;
2688 return pfn_to_page(pfn);
2691 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2695 pfn = gfn_to_pfn(kvm, gfn);
2697 return kvm_pfn_to_page(pfn);
2699 EXPORT_SYMBOL_GPL(gfn_to_page);
2701 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty)
2707 kvm_release_pfn_dirty(pfn);
2709 kvm_release_pfn_clean(pfn);
2712 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2716 struct page *page = KVM_UNMAPPED_PAGE;
2721 pfn = gfn_to_pfn(vcpu->kvm, gfn);
2722 if (is_error_noslot_pfn(pfn))
2725 if (pfn_valid(pfn)) {
2726 page = pfn_to_page(pfn);
2728 #ifdef CONFIG_HAS_IOMEM
2730 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2744 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2746 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2754 if (map->page != KVM_UNMAPPED_PAGE)
2756 #ifdef CONFIG_HAS_IOMEM
2762 kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
2764 kvm_release_pfn(map->pfn, dirty);
2769 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2771 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2775 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2777 return kvm_pfn_to_page(pfn);
2779 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2781 void kvm_release_page_clean(struct page *page)
2783 WARN_ON(is_error_page(page));
2785 kvm_release_pfn_clean(page_to_pfn(page));
2787 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2789 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2791 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2792 put_page(pfn_to_page(pfn));
2794 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2796 void kvm_release_page_dirty(struct page *page)
2798 WARN_ON(is_error_page(page));
2800 kvm_release_pfn_dirty(page_to_pfn(page));
2802 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2804 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2806 kvm_set_pfn_dirty(pfn);
2807 kvm_release_pfn_clean(pfn);
2809 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2811 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2813 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2814 SetPageDirty(pfn_to_page(pfn));
2816 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2818 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2820 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2821 mark_page_accessed(pfn_to_page(pfn));
2823 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2825 static int next_segment(unsigned long len, int offset)
2827 if (len > PAGE_SIZE - offset)
2828 return PAGE_SIZE - offset;
2833 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2834 void *data, int offset, int len)
2839 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2840 if (kvm_is_error_hva(addr))
2842 r = __copy_from_user(data, (void __user *)addr + offset, len);
2848 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2851 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2853 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2855 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2857 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2858 int offset, int len)
2860 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2862 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2864 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2866 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2868 gfn_t gfn = gpa >> PAGE_SHIFT;
2870 int offset = offset_in_page(gpa);
2873 while ((seg = next_segment(len, offset)) != 0) {
2874 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2884 EXPORT_SYMBOL_GPL(kvm_read_guest);
2886 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2888 gfn_t gfn = gpa >> PAGE_SHIFT;
2890 int offset = offset_in_page(gpa);
2893 while ((seg = next_segment(len, offset)) != 0) {
2894 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2904 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2906 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2907 void *data, int offset, unsigned long len)
2912 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2913 if (kvm_is_error_hva(addr))
2915 pagefault_disable();
2916 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2923 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2924 void *data, unsigned long len)
2926 gfn_t gfn = gpa >> PAGE_SHIFT;
2927 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2928 int offset = offset_in_page(gpa);
2930 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2932 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2934 static int __kvm_write_guest_page(struct kvm *kvm,
2935 struct kvm_memory_slot *memslot, gfn_t gfn,
2936 const void *data, int offset, int len)
2941 addr = gfn_to_hva_memslot(memslot, gfn);
2942 if (kvm_is_error_hva(addr))
2944 r = __copy_to_user((void __user *)addr + offset, data, len);
2947 mark_page_dirty_in_slot(kvm, memslot, gfn);
2951 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2952 const void *data, int offset, int len)
2954 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2956 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2958 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2960 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2961 const void *data, int offset, int len)
2963 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2965 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
2967 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2969 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2972 gfn_t gfn = gpa >> PAGE_SHIFT;
2974 int offset = offset_in_page(gpa);
2977 while ((seg = next_segment(len, offset)) != 0) {
2978 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2988 EXPORT_SYMBOL_GPL(kvm_write_guest);
2990 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2993 gfn_t gfn = gpa >> PAGE_SHIFT;
2995 int offset = offset_in_page(gpa);
2998 while ((seg = next_segment(len, offset)) != 0) {
2999 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
3009 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
3011 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
3012 struct gfn_to_hva_cache *ghc,
3013 gpa_t gpa, unsigned long len)
3015 int offset = offset_in_page(gpa);
3016 gfn_t start_gfn = gpa >> PAGE_SHIFT;
3017 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
3018 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
3019 gfn_t nr_pages_avail;
3021 /* Update ghc->generation before performing any error checks. */
3022 ghc->generation = slots->generation;
3024 if (start_gfn > end_gfn) {
3025 ghc->hva = KVM_HVA_ERR_BAD;
3030 * If the requested region crosses two memslots, we still
3031 * verify that the entire region is valid here.
3033 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
3034 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
3035 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
3037 if (kvm_is_error_hva(ghc->hva))
3041 /* Use the slow path for cross page reads and writes. */
3042 if (nr_pages_needed == 1)
3045 ghc->memslot = NULL;
3052 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3053 gpa_t gpa, unsigned long len)
3055 struct kvm_memslots *slots = kvm_memslots(kvm);
3056 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
3058 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
3060 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3061 void *data, unsigned int offset,
3064 struct kvm_memslots *slots = kvm_memslots(kvm);
3066 gpa_t gpa = ghc->gpa + offset;
3068 if (WARN_ON_ONCE(len + offset > ghc->len))
3071 if (slots->generation != ghc->generation) {
3072 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3076 if (kvm_is_error_hva(ghc->hva))
3079 if (unlikely(!ghc->memslot))
3080 return kvm_write_guest(kvm, gpa, data, len);
3082 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
3085 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
3089 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
3091 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3092 void *data, unsigned long len)
3094 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
3096 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
3098 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3099 void *data, unsigned int offset,
3102 struct kvm_memslots *slots = kvm_memslots(kvm);
3104 gpa_t gpa = ghc->gpa + offset;
3106 if (WARN_ON_ONCE(len + offset > ghc->len))
3109 if (slots->generation != ghc->generation) {
3110 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3114 if (kvm_is_error_hva(ghc->hva))
3117 if (unlikely(!ghc->memslot))
3118 return kvm_read_guest(kvm, gpa, data, len);
3120 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
3126 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3128 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3129 void *data, unsigned long len)
3131 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3133 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
3135 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3137 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3138 gfn_t gfn = gpa >> PAGE_SHIFT;
3140 int offset = offset_in_page(gpa);
3143 while ((seg = next_segment(len, offset)) != 0) {
3144 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
3153 EXPORT_SYMBOL_GPL(kvm_clear_guest);
3155 void mark_page_dirty_in_slot(struct kvm *kvm,
3156 const struct kvm_memory_slot *memslot,
3159 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
3161 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3162 if (WARN_ON_ONCE(!vcpu) || WARN_ON_ONCE(vcpu->kvm != kvm))
3166 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
3167 unsigned long rel_gfn = gfn - memslot->base_gfn;
3168 u32 slot = (memslot->as_id << 16) | memslot->id;
3170 if (kvm->dirty_ring_size)
3171 kvm_dirty_ring_push(&vcpu->dirty_ring,
3174 set_bit_le(rel_gfn, memslot->dirty_bitmap);
3177 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
3179 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3181 struct kvm_memory_slot *memslot;
3183 memslot = gfn_to_memslot(kvm, gfn);
3184 mark_page_dirty_in_slot(kvm, memslot, gfn);
3186 EXPORT_SYMBOL_GPL(mark_page_dirty);
3188 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3190 struct kvm_memory_slot *memslot;
3192 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3193 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
3195 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3197 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3199 if (!vcpu->sigset_active)
3203 * This does a lockless modification of ->real_blocked, which is fine
3204 * because, only current can change ->real_blocked and all readers of
3205 * ->real_blocked don't care as long ->real_blocked is always a subset
3208 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
3211 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3213 if (!vcpu->sigset_active)
3216 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
3217 sigemptyset(¤t->real_blocked);
3220 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3222 unsigned int old, val, grow, grow_start;
3224 old = val = vcpu->halt_poll_ns;
3225 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3226 grow = READ_ONCE(halt_poll_ns_grow);
3231 if (val < grow_start)
3234 if (val > vcpu->kvm->max_halt_poll_ns)
3235 val = vcpu->kvm->max_halt_poll_ns;
3237 vcpu->halt_poll_ns = val;
3239 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
3242 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3244 unsigned int old, val, shrink, grow_start;
3246 old = val = vcpu->halt_poll_ns;
3247 shrink = READ_ONCE(halt_poll_ns_shrink);
3248 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3254 if (val < grow_start)
3257 vcpu->halt_poll_ns = val;
3258 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3261 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3264 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3266 if (kvm_arch_vcpu_runnable(vcpu)) {
3267 kvm_make_request(KVM_REQ_UNHALT, vcpu);
3270 if (kvm_cpu_has_pending_timer(vcpu))
3272 if (signal_pending(current))
3274 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3279 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3284 * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is
3285 * pending. This is mostly used when halting a vCPU, but may also be used
3286 * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI.
3288 bool kvm_vcpu_block(struct kvm_vcpu *vcpu)
3290 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
3291 bool waited = false;
3293 vcpu->stat.generic.blocking = 1;
3295 kvm_arch_vcpu_blocking(vcpu);
3297 prepare_to_rcuwait(wait);
3299 set_current_state(TASK_INTERRUPTIBLE);
3301 if (kvm_vcpu_check_block(vcpu) < 0)
3307 finish_rcuwait(wait);
3309 kvm_arch_vcpu_unblocking(vcpu);
3311 vcpu->stat.generic.blocking = 0;
3316 static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start,
3317 ktime_t end, bool success)
3319 struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic;
3320 u64 poll_ns = ktime_to_ns(ktime_sub(end, start));
3322 ++vcpu->stat.generic.halt_attempted_poll;
3325 ++vcpu->stat.generic.halt_successful_poll;
3327 if (!vcpu_valid_wakeup(vcpu))
3328 ++vcpu->stat.generic.halt_poll_invalid;
3330 stats->halt_poll_success_ns += poll_ns;
3331 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns);
3333 stats->halt_poll_fail_ns += poll_ns;
3334 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns);
3339 * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc... If halt
3340 * polling is enabled, busy wait for a short time before blocking to avoid the
3341 * expensive block+unblock sequence if a wake event arrives soon after the vCPU
3344 void kvm_vcpu_halt(struct kvm_vcpu *vcpu)
3346 bool halt_poll_allowed = !kvm_arch_no_poll(vcpu);
3347 bool do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns;
3348 ktime_t start, cur, poll_end;
3349 bool waited = false;
3352 start = cur = poll_end = ktime_get();
3354 ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns);
3358 * This sets KVM_REQ_UNHALT if an interrupt
3361 if (kvm_vcpu_check_block(vcpu) < 0)
3364 poll_end = cur = ktime_get();
3365 } while (kvm_vcpu_can_poll(cur, stop));
3368 waited = kvm_vcpu_block(vcpu);
3372 vcpu->stat.generic.halt_wait_ns +=
3373 ktime_to_ns(cur) - ktime_to_ns(poll_end);
3374 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3375 ktime_to_ns(cur) - ktime_to_ns(poll_end));
3378 /* The total time the vCPU was "halted", including polling time. */
3379 halt_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3382 * Note, halt-polling is considered successful so long as the vCPU was
3383 * never actually scheduled out, i.e. even if the wake event arrived
3384 * after of the halt-polling loop itself, but before the full wait.
3387 update_halt_poll_stats(vcpu, start, poll_end, !waited);
3389 if (halt_poll_allowed) {
3390 if (!vcpu_valid_wakeup(vcpu)) {
3391 shrink_halt_poll_ns(vcpu);
3392 } else if (vcpu->kvm->max_halt_poll_ns) {
3393 if (halt_ns <= vcpu->halt_poll_ns)
3395 /* we had a long block, shrink polling */
3396 else if (vcpu->halt_poll_ns &&
3397 halt_ns > vcpu->kvm->max_halt_poll_ns)
3398 shrink_halt_poll_ns(vcpu);
3399 /* we had a short halt and our poll time is too small */
3400 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3401 halt_ns < vcpu->kvm->max_halt_poll_ns)
3402 grow_halt_poll_ns(vcpu);
3404 vcpu->halt_poll_ns = 0;
3408 trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu));
3410 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
3412 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3414 if (__kvm_vcpu_wake_up(vcpu)) {
3415 WRITE_ONCE(vcpu->ready, true);
3416 ++vcpu->stat.generic.halt_wakeup;
3422 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3426 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3428 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3432 if (kvm_vcpu_wake_up(vcpu))
3437 * The only state change done outside the vcpu mutex is IN_GUEST_MODE
3438 * to EXITING_GUEST_MODE. Therefore the moderately expensive "should
3439 * kick" check does not need atomic operations if kvm_vcpu_kick is used
3440 * within the vCPU thread itself.
3442 if (vcpu == __this_cpu_read(kvm_running_vcpu)) {
3443 if (vcpu->mode == IN_GUEST_MODE)
3444 WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE);
3449 * Note, the vCPU could get migrated to a different pCPU at any point
3450 * after kvm_arch_vcpu_should_kick(), which could result in sending an
3451 * IPI to the previous pCPU. But, that's ok because the purpose of the
3452 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
3453 * vCPU also requires it to leave IN_GUEST_MODE.
3455 if (kvm_arch_vcpu_should_kick(vcpu)) {
3456 cpu = READ_ONCE(vcpu->cpu);
3457 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3458 smp_send_reschedule(cpu);
3463 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3464 #endif /* !CONFIG_S390 */
3466 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3469 struct task_struct *task = NULL;
3473 pid = rcu_dereference(target->pid);
3475 task = get_pid_task(pid, PIDTYPE_PID);
3479 ret = yield_to(task, 1);
3480 put_task_struct(task);
3484 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3487 * Helper that checks whether a VCPU is eligible for directed yield.
3488 * Most eligible candidate to yield is decided by following heuristics:
3490 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3491 * (preempted lock holder), indicated by @in_spin_loop.
3492 * Set at the beginning and cleared at the end of interception/PLE handler.
3494 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3495 * chance last time (mostly it has become eligible now since we have probably
3496 * yielded to lockholder in last iteration. This is done by toggling
3497 * @dy_eligible each time a VCPU checked for eligibility.)
3499 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3500 * to preempted lock-holder could result in wrong VCPU selection and CPU
3501 * burning. Giving priority for a potential lock-holder increases lock
3504 * Since algorithm is based on heuristics, accessing another VCPU data without
3505 * locking does not harm. It may result in trying to yield to same VCPU, fail
3506 * and continue with next VCPU and so on.
3508 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3510 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3513 eligible = !vcpu->spin_loop.in_spin_loop ||
3514 vcpu->spin_loop.dy_eligible;
3516 if (vcpu->spin_loop.in_spin_loop)
3517 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3526 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3527 * a vcpu_load/vcpu_put pair. However, for most architectures
3528 * kvm_arch_vcpu_runnable does not require vcpu_load.
3530 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3532 return kvm_arch_vcpu_runnable(vcpu);
3535 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3537 if (kvm_arch_dy_runnable(vcpu))
3540 #ifdef CONFIG_KVM_ASYNC_PF
3541 if (!list_empty_careful(&vcpu->async_pf.done))
3548 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3553 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3555 struct kvm *kvm = me->kvm;
3556 struct kvm_vcpu *vcpu;
3557 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3563 kvm_vcpu_set_in_spin_loop(me, true);
3565 * We boost the priority of a VCPU that is runnable but not
3566 * currently running, because it got preempted by something
3567 * else and called schedule in __vcpu_run. Hopefully that
3568 * VCPU is holding the lock that we need and will release it.
3569 * We approximate round-robin by starting at the last boosted VCPU.
3571 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3572 kvm_for_each_vcpu(i, vcpu, kvm) {
3573 if (!pass && i <= last_boosted_vcpu) {
3574 i = last_boosted_vcpu;
3576 } else if (pass && i > last_boosted_vcpu)
3578 if (!READ_ONCE(vcpu->ready))
3582 if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu))
3584 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3585 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3586 !kvm_arch_vcpu_in_kernel(vcpu))
3588 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3591 yielded = kvm_vcpu_yield_to(vcpu);
3593 kvm->last_boosted_vcpu = i;
3595 } else if (yielded < 0) {
3602 kvm_vcpu_set_in_spin_loop(me, false);
3604 /* Ensure vcpu is not eligible during next spinloop */
3605 kvm_vcpu_set_dy_eligible(me, false);
3607 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3609 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3611 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3612 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3613 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3614 kvm->dirty_ring_size / PAGE_SIZE);
3620 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3622 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3625 if (vmf->pgoff == 0)
3626 page = virt_to_page(vcpu->run);
3628 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3629 page = virt_to_page(vcpu->arch.pio_data);
3631 #ifdef CONFIG_KVM_MMIO
3632 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3633 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3635 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3636 page = kvm_dirty_ring_get_page(
3638 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3640 return kvm_arch_vcpu_fault(vcpu, vmf);
3646 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3647 .fault = kvm_vcpu_fault,
3650 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3652 struct kvm_vcpu *vcpu = file->private_data;
3653 unsigned long pages = vma_pages(vma);
3655 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3656 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3657 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3660 vma->vm_ops = &kvm_vcpu_vm_ops;
3664 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3666 struct kvm_vcpu *vcpu = filp->private_data;
3668 kvm_put_kvm(vcpu->kvm);
3672 static struct file_operations kvm_vcpu_fops = {
3673 .release = kvm_vcpu_release,
3674 .unlocked_ioctl = kvm_vcpu_ioctl,
3675 .mmap = kvm_vcpu_mmap,
3676 .llseek = noop_llseek,
3677 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3681 * Allocates an inode for the vcpu.
3683 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3685 char name[8 + 1 + ITOA_MAX_LEN + 1];
3687 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3688 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3691 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3693 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3694 struct dentry *debugfs_dentry;
3695 char dir_name[ITOA_MAX_LEN * 2];
3697 if (!debugfs_initialized())
3700 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3701 debugfs_dentry = debugfs_create_dir(dir_name,
3702 vcpu->kvm->debugfs_dentry);
3704 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3709 * Creates some virtual cpus. Good luck creating more than one.
3711 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3714 struct kvm_vcpu *vcpu;
3717 if (id >= KVM_MAX_VCPU_IDS)
3720 mutex_lock(&kvm->lock);
3721 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3722 mutex_unlock(&kvm->lock);
3726 kvm->created_vcpus++;
3727 mutex_unlock(&kvm->lock);
3729 r = kvm_arch_vcpu_precreate(kvm, id);
3731 goto vcpu_decrement;
3733 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3736 goto vcpu_decrement;
3739 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3740 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3745 vcpu->run = page_address(page);
3747 kvm_vcpu_init(vcpu, kvm, id);
3749 r = kvm_arch_vcpu_create(vcpu);
3751 goto vcpu_free_run_page;
3753 if (kvm->dirty_ring_size) {
3754 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3755 id, kvm->dirty_ring_size);
3757 goto arch_vcpu_destroy;
3760 mutex_lock(&kvm->lock);
3761 if (kvm_get_vcpu_by_id(kvm, id)) {
3763 goto unlock_vcpu_destroy;
3766 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3767 r = xa_insert(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, GFP_KERNEL_ACCOUNT);
3768 BUG_ON(r == -EBUSY);
3770 goto unlock_vcpu_destroy;
3772 /* Fill the stats id string for the vcpu */
3773 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3774 task_pid_nr(current), id);
3776 /* Now it's all set up, let userspace reach it */
3778 r = create_vcpu_fd(vcpu);
3780 xa_erase(&kvm->vcpu_array, vcpu->vcpu_idx);
3781 kvm_put_kvm_no_destroy(kvm);
3782 goto unlock_vcpu_destroy;
3786 * Pairs with smp_rmb() in kvm_get_vcpu. Store the vcpu
3787 * pointer before kvm->online_vcpu's incremented value.
3790 atomic_inc(&kvm->online_vcpus);
3792 mutex_unlock(&kvm->lock);
3793 kvm_arch_vcpu_postcreate(vcpu);
3794 kvm_create_vcpu_debugfs(vcpu);
3797 unlock_vcpu_destroy:
3798 mutex_unlock(&kvm->lock);
3799 kvm_dirty_ring_free(&vcpu->dirty_ring);
3801 kvm_arch_vcpu_destroy(vcpu);
3803 free_page((unsigned long)vcpu->run);
3805 kmem_cache_free(kvm_vcpu_cache, vcpu);
3807 mutex_lock(&kvm->lock);
3808 kvm->created_vcpus--;
3809 mutex_unlock(&kvm->lock);
3813 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3816 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3817 vcpu->sigset_active = 1;
3818 vcpu->sigset = *sigset;
3820 vcpu->sigset_active = 0;
3824 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3825 size_t size, loff_t *offset)
3827 struct kvm_vcpu *vcpu = file->private_data;
3829 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3830 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3831 sizeof(vcpu->stat), user_buffer, size, offset);
3834 static const struct file_operations kvm_vcpu_stats_fops = {
3835 .read = kvm_vcpu_stats_read,
3836 .llseek = noop_llseek,
3839 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3843 char name[15 + ITOA_MAX_LEN + 1];
3845 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3847 fd = get_unused_fd_flags(O_CLOEXEC);
3851 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3854 return PTR_ERR(file);
3856 file->f_mode |= FMODE_PREAD;
3857 fd_install(fd, file);
3862 static long kvm_vcpu_ioctl(struct file *filp,
3863 unsigned int ioctl, unsigned long arg)
3865 struct kvm_vcpu *vcpu = filp->private_data;
3866 void __user *argp = (void __user *)arg;
3868 struct kvm_fpu *fpu = NULL;
3869 struct kvm_sregs *kvm_sregs = NULL;
3871 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
3874 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3878 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3879 * execution; mutex_lock() would break them.
3881 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3882 if (r != -ENOIOCTLCMD)
3885 if (mutex_lock_killable(&vcpu->mutex))
3893 oldpid = rcu_access_pointer(vcpu->pid);
3894 if (unlikely(oldpid != task_pid(current))) {
3895 /* The thread running this VCPU changed. */
3898 r = kvm_arch_vcpu_run_pid_change(vcpu);
3902 newpid = get_task_pid(current, PIDTYPE_PID);
3903 rcu_assign_pointer(vcpu->pid, newpid);
3908 r = kvm_arch_vcpu_ioctl_run(vcpu);
3909 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3912 case KVM_GET_REGS: {
3913 struct kvm_regs *kvm_regs;
3916 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3919 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3923 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3930 case KVM_SET_REGS: {
3931 struct kvm_regs *kvm_regs;
3933 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3934 if (IS_ERR(kvm_regs)) {
3935 r = PTR_ERR(kvm_regs);
3938 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3942 case KVM_GET_SREGS: {
3943 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3944 GFP_KERNEL_ACCOUNT);
3948 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3952 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3957 case KVM_SET_SREGS: {
3958 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3959 if (IS_ERR(kvm_sregs)) {
3960 r = PTR_ERR(kvm_sregs);
3964 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3967 case KVM_GET_MP_STATE: {
3968 struct kvm_mp_state mp_state;
3970 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3974 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3979 case KVM_SET_MP_STATE: {
3980 struct kvm_mp_state mp_state;
3983 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3985 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3988 case KVM_TRANSLATE: {
3989 struct kvm_translation tr;
3992 if (copy_from_user(&tr, argp, sizeof(tr)))
3994 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3998 if (copy_to_user(argp, &tr, sizeof(tr)))
4003 case KVM_SET_GUEST_DEBUG: {
4004 struct kvm_guest_debug dbg;
4007 if (copy_from_user(&dbg, argp, sizeof(dbg)))
4009 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
4012 case KVM_SET_SIGNAL_MASK: {
4013 struct kvm_signal_mask __user *sigmask_arg = argp;
4014 struct kvm_signal_mask kvm_sigmask;
4015 sigset_t sigset, *p;
4020 if (copy_from_user(&kvm_sigmask, argp,
4021 sizeof(kvm_sigmask)))
4024 if (kvm_sigmask.len != sizeof(sigset))
4027 if (copy_from_user(&sigset, sigmask_arg->sigset,
4032 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
4036 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
4040 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
4044 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
4050 fpu = memdup_user(argp, sizeof(*fpu));
4056 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
4059 case KVM_GET_STATS_FD: {
4060 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
4064 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
4067 mutex_unlock(&vcpu->mutex);
4073 #ifdef CONFIG_KVM_COMPAT
4074 static long kvm_vcpu_compat_ioctl(struct file *filp,
4075 unsigned int ioctl, unsigned long arg)
4077 struct kvm_vcpu *vcpu = filp->private_data;
4078 void __user *argp = compat_ptr(arg);
4081 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
4085 case KVM_SET_SIGNAL_MASK: {
4086 struct kvm_signal_mask __user *sigmask_arg = argp;
4087 struct kvm_signal_mask kvm_sigmask;
4092 if (copy_from_user(&kvm_sigmask, argp,
4093 sizeof(kvm_sigmask)))
4096 if (kvm_sigmask.len != sizeof(compat_sigset_t))
4099 if (get_compat_sigset(&sigset,
4100 (compat_sigset_t __user *)sigmask_arg->sigset))
4102 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
4104 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
4108 r = kvm_vcpu_ioctl(filp, ioctl, arg);
4116 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
4118 struct kvm_device *dev = filp->private_data;
4121 return dev->ops->mmap(dev, vma);
4126 static int kvm_device_ioctl_attr(struct kvm_device *dev,
4127 int (*accessor)(struct kvm_device *dev,
4128 struct kvm_device_attr *attr),
4131 struct kvm_device_attr attr;
4136 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4139 return accessor(dev, &attr);
4142 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
4145 struct kvm_device *dev = filp->private_data;
4147 if (dev->kvm->mm != current->mm || dev->kvm->vm_dead)
4151 case KVM_SET_DEVICE_ATTR:
4152 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
4153 case KVM_GET_DEVICE_ATTR:
4154 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
4155 case KVM_HAS_DEVICE_ATTR:
4156 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
4158 if (dev->ops->ioctl)
4159 return dev->ops->ioctl(dev, ioctl, arg);
4165 static int kvm_device_release(struct inode *inode, struct file *filp)
4167 struct kvm_device *dev = filp->private_data;
4168 struct kvm *kvm = dev->kvm;
4170 if (dev->ops->release) {
4171 mutex_lock(&kvm->lock);
4172 list_del(&dev->vm_node);
4173 dev->ops->release(dev);
4174 mutex_unlock(&kvm->lock);
4181 static const struct file_operations kvm_device_fops = {
4182 .unlocked_ioctl = kvm_device_ioctl,
4183 .release = kvm_device_release,
4184 KVM_COMPAT(kvm_device_ioctl),
4185 .mmap = kvm_device_mmap,
4188 struct kvm_device *kvm_device_from_filp(struct file *filp)
4190 if (filp->f_op != &kvm_device_fops)
4193 return filp->private_data;
4196 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
4197 #ifdef CONFIG_KVM_MPIC
4198 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
4199 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
4203 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
4205 if (type >= ARRAY_SIZE(kvm_device_ops_table))
4208 if (kvm_device_ops_table[type] != NULL)
4211 kvm_device_ops_table[type] = ops;
4215 void kvm_unregister_device_ops(u32 type)
4217 if (kvm_device_ops_table[type] != NULL)
4218 kvm_device_ops_table[type] = NULL;
4221 static int kvm_ioctl_create_device(struct kvm *kvm,
4222 struct kvm_create_device *cd)
4224 const struct kvm_device_ops *ops = NULL;
4225 struct kvm_device *dev;
4226 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
4230 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4233 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4234 ops = kvm_device_ops_table[type];
4241 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
4248 mutex_lock(&kvm->lock);
4249 ret = ops->create(dev, type);
4251 mutex_unlock(&kvm->lock);
4255 list_add(&dev->vm_node, &kvm->devices);
4256 mutex_unlock(&kvm->lock);
4262 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
4264 kvm_put_kvm_no_destroy(kvm);
4265 mutex_lock(&kvm->lock);
4266 list_del(&dev->vm_node);
4267 mutex_unlock(&kvm->lock);
4276 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4279 case KVM_CAP_USER_MEMORY:
4280 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4281 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
4282 case KVM_CAP_INTERNAL_ERROR_DATA:
4283 #ifdef CONFIG_HAVE_KVM_MSI
4284 case KVM_CAP_SIGNAL_MSI:
4286 #ifdef CONFIG_HAVE_KVM_IRQFD
4288 case KVM_CAP_IRQFD_RESAMPLE:
4290 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
4291 case KVM_CAP_CHECK_EXTENSION_VM:
4292 case KVM_CAP_ENABLE_CAP_VM:
4293 case KVM_CAP_HALT_POLL:
4295 #ifdef CONFIG_KVM_MMIO
4296 case KVM_CAP_COALESCED_MMIO:
4297 return KVM_COALESCED_MMIO_PAGE_OFFSET;
4298 case KVM_CAP_COALESCED_PIO:
4301 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4302 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4303 return KVM_DIRTY_LOG_MANUAL_CAPS;
4305 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4306 case KVM_CAP_IRQ_ROUTING:
4307 return KVM_MAX_IRQ_ROUTES;
4309 #if KVM_ADDRESS_SPACE_NUM > 1
4310 case KVM_CAP_MULTI_ADDRESS_SPACE:
4311 return KVM_ADDRESS_SPACE_NUM;
4313 case KVM_CAP_NR_MEMSLOTS:
4314 return KVM_USER_MEM_SLOTS;
4315 case KVM_CAP_DIRTY_LOG_RING:
4316 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
4317 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4321 case KVM_CAP_BINARY_STATS_FD:
4326 return kvm_vm_ioctl_check_extension(kvm, arg);
4329 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4333 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4336 /* the size should be power of 2 */
4337 if (!size || (size & (size - 1)))
4340 /* Should be bigger to keep the reserved entries, or a page */
4341 if (size < kvm_dirty_ring_get_rsvd_entries() *
4342 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4345 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4346 sizeof(struct kvm_dirty_gfn))
4349 /* We only allow it to set once */
4350 if (kvm->dirty_ring_size)
4353 mutex_lock(&kvm->lock);
4355 if (kvm->created_vcpus) {
4356 /* We don't allow to change this value after vcpu created */
4359 kvm->dirty_ring_size = size;
4363 mutex_unlock(&kvm->lock);
4367 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4370 struct kvm_vcpu *vcpu;
4373 if (!kvm->dirty_ring_size)
4376 mutex_lock(&kvm->slots_lock);
4378 kvm_for_each_vcpu(i, vcpu, kvm)
4379 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4381 mutex_unlock(&kvm->slots_lock);
4384 kvm_flush_remote_tlbs(kvm);
4389 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4390 struct kvm_enable_cap *cap)
4395 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4396 struct kvm_enable_cap *cap)
4399 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4400 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4401 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4403 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4404 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4406 if (cap->flags || (cap->args[0] & ~allowed_options))
4408 kvm->manual_dirty_log_protect = cap->args[0];
4412 case KVM_CAP_HALT_POLL: {
4413 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4416 kvm->max_halt_poll_ns = cap->args[0];
4419 case KVM_CAP_DIRTY_LOG_RING:
4420 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4422 return kvm_vm_ioctl_enable_cap(kvm, cap);
4426 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4427 size_t size, loff_t *offset)
4429 struct kvm *kvm = file->private_data;
4431 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4432 &kvm_vm_stats_desc[0], &kvm->stat,
4433 sizeof(kvm->stat), user_buffer, size, offset);
4436 static const struct file_operations kvm_vm_stats_fops = {
4437 .read = kvm_vm_stats_read,
4438 .llseek = noop_llseek,
4441 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4446 fd = get_unused_fd_flags(O_CLOEXEC);
4450 file = anon_inode_getfile("kvm-vm-stats",
4451 &kvm_vm_stats_fops, kvm, O_RDONLY);
4454 return PTR_ERR(file);
4456 file->f_mode |= FMODE_PREAD;
4457 fd_install(fd, file);
4462 static long kvm_vm_ioctl(struct file *filp,
4463 unsigned int ioctl, unsigned long arg)
4465 struct kvm *kvm = filp->private_data;
4466 void __user *argp = (void __user *)arg;
4469 if (kvm->mm != current->mm || kvm->vm_dead)
4472 case KVM_CREATE_VCPU:
4473 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4475 case KVM_ENABLE_CAP: {
4476 struct kvm_enable_cap cap;
4479 if (copy_from_user(&cap, argp, sizeof(cap)))
4481 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4484 case KVM_SET_USER_MEMORY_REGION: {
4485 struct kvm_userspace_memory_region kvm_userspace_mem;
4488 if (copy_from_user(&kvm_userspace_mem, argp,
4489 sizeof(kvm_userspace_mem)))
4492 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4495 case KVM_GET_DIRTY_LOG: {
4496 struct kvm_dirty_log log;
4499 if (copy_from_user(&log, argp, sizeof(log)))
4501 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4504 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4505 case KVM_CLEAR_DIRTY_LOG: {
4506 struct kvm_clear_dirty_log log;
4509 if (copy_from_user(&log, argp, sizeof(log)))
4511 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4515 #ifdef CONFIG_KVM_MMIO
4516 case KVM_REGISTER_COALESCED_MMIO: {
4517 struct kvm_coalesced_mmio_zone zone;
4520 if (copy_from_user(&zone, argp, sizeof(zone)))
4522 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4525 case KVM_UNREGISTER_COALESCED_MMIO: {
4526 struct kvm_coalesced_mmio_zone zone;
4529 if (copy_from_user(&zone, argp, sizeof(zone)))
4531 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4536 struct kvm_irqfd data;
4539 if (copy_from_user(&data, argp, sizeof(data)))
4541 r = kvm_irqfd(kvm, &data);
4544 case KVM_IOEVENTFD: {
4545 struct kvm_ioeventfd data;
4548 if (copy_from_user(&data, argp, sizeof(data)))
4550 r = kvm_ioeventfd(kvm, &data);
4553 #ifdef CONFIG_HAVE_KVM_MSI
4554 case KVM_SIGNAL_MSI: {
4558 if (copy_from_user(&msi, argp, sizeof(msi)))
4560 r = kvm_send_userspace_msi(kvm, &msi);
4564 #ifdef __KVM_HAVE_IRQ_LINE
4565 case KVM_IRQ_LINE_STATUS:
4566 case KVM_IRQ_LINE: {
4567 struct kvm_irq_level irq_event;
4570 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4573 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4574 ioctl == KVM_IRQ_LINE_STATUS);
4579 if (ioctl == KVM_IRQ_LINE_STATUS) {
4580 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4588 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4589 case KVM_SET_GSI_ROUTING: {
4590 struct kvm_irq_routing routing;
4591 struct kvm_irq_routing __user *urouting;
4592 struct kvm_irq_routing_entry *entries = NULL;
4595 if (copy_from_user(&routing, argp, sizeof(routing)))
4598 if (!kvm_arch_can_set_irq_routing(kvm))
4600 if (routing.nr > KVM_MAX_IRQ_ROUTES)
4606 entries = vmemdup_user(urouting->entries,
4607 array_size(sizeof(*entries),
4609 if (IS_ERR(entries)) {
4610 r = PTR_ERR(entries);
4614 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4619 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4620 case KVM_CREATE_DEVICE: {
4621 struct kvm_create_device cd;
4624 if (copy_from_user(&cd, argp, sizeof(cd)))
4627 r = kvm_ioctl_create_device(kvm, &cd);
4632 if (copy_to_user(argp, &cd, sizeof(cd)))
4638 case KVM_CHECK_EXTENSION:
4639 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4641 case KVM_RESET_DIRTY_RINGS:
4642 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4644 case KVM_GET_STATS_FD:
4645 r = kvm_vm_ioctl_get_stats_fd(kvm);
4648 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4654 #ifdef CONFIG_KVM_COMPAT
4655 struct compat_kvm_dirty_log {
4659 compat_uptr_t dirty_bitmap; /* one bit per page */
4664 struct compat_kvm_clear_dirty_log {
4669 compat_uptr_t dirty_bitmap; /* one bit per page */
4674 static long kvm_vm_compat_ioctl(struct file *filp,
4675 unsigned int ioctl, unsigned long arg)
4677 struct kvm *kvm = filp->private_data;
4680 if (kvm->mm != current->mm || kvm->vm_dead)
4683 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4684 case KVM_CLEAR_DIRTY_LOG: {
4685 struct compat_kvm_clear_dirty_log compat_log;
4686 struct kvm_clear_dirty_log log;
4688 if (copy_from_user(&compat_log, (void __user *)arg,
4689 sizeof(compat_log)))
4691 log.slot = compat_log.slot;
4692 log.num_pages = compat_log.num_pages;
4693 log.first_page = compat_log.first_page;
4694 log.padding2 = compat_log.padding2;
4695 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4697 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4701 case KVM_GET_DIRTY_LOG: {
4702 struct compat_kvm_dirty_log compat_log;
4703 struct kvm_dirty_log log;
4705 if (copy_from_user(&compat_log, (void __user *)arg,
4706 sizeof(compat_log)))
4708 log.slot = compat_log.slot;
4709 log.padding1 = compat_log.padding1;
4710 log.padding2 = compat_log.padding2;
4711 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4713 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4717 r = kvm_vm_ioctl(filp, ioctl, arg);
4723 static struct file_operations kvm_vm_fops = {
4724 .release = kvm_vm_release,
4725 .unlocked_ioctl = kvm_vm_ioctl,
4726 .llseek = noop_llseek,
4727 KVM_COMPAT(kvm_vm_compat_ioctl),
4730 bool file_is_kvm(struct file *file)
4732 return file && file->f_op == &kvm_vm_fops;
4734 EXPORT_SYMBOL_GPL(file_is_kvm);
4736 static int kvm_dev_ioctl_create_vm(unsigned long type)
4742 kvm = kvm_create_vm(type);
4744 return PTR_ERR(kvm);
4745 #ifdef CONFIG_KVM_MMIO
4746 r = kvm_coalesced_mmio_init(kvm);
4750 r = get_unused_fd_flags(O_CLOEXEC);
4754 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4755 "kvm-%d", task_pid_nr(current));
4757 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4765 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4766 * already set, with ->release() being kvm_vm_release(). In error
4767 * cases it will be called by the final fput(file) and will take
4768 * care of doing kvm_put_kvm(kvm).
4770 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4775 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4777 fd_install(r, file);
4785 static long kvm_dev_ioctl(struct file *filp,
4786 unsigned int ioctl, unsigned long arg)
4791 case KVM_GET_API_VERSION:
4794 r = KVM_API_VERSION;
4797 r = kvm_dev_ioctl_create_vm(arg);
4799 case KVM_CHECK_EXTENSION:
4800 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4802 case KVM_GET_VCPU_MMAP_SIZE:
4805 r = PAGE_SIZE; /* struct kvm_run */
4807 r += PAGE_SIZE; /* pio data page */
4809 #ifdef CONFIG_KVM_MMIO
4810 r += PAGE_SIZE; /* coalesced mmio ring page */
4813 case KVM_TRACE_ENABLE:
4814 case KVM_TRACE_PAUSE:
4815 case KVM_TRACE_DISABLE:
4819 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4825 static struct file_operations kvm_chardev_ops = {
4826 .unlocked_ioctl = kvm_dev_ioctl,
4827 .llseek = noop_llseek,
4828 KVM_COMPAT(kvm_dev_ioctl),
4831 static struct miscdevice kvm_dev = {
4837 static void hardware_enable_nolock(void *junk)
4839 int cpu = raw_smp_processor_id();
4842 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4845 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4847 r = kvm_arch_hardware_enable();
4850 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4851 atomic_inc(&hardware_enable_failed);
4852 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4856 static int kvm_starting_cpu(unsigned int cpu)
4858 raw_spin_lock(&kvm_count_lock);
4859 if (kvm_usage_count)
4860 hardware_enable_nolock(NULL);
4861 raw_spin_unlock(&kvm_count_lock);
4865 static void hardware_disable_nolock(void *junk)
4867 int cpu = raw_smp_processor_id();
4869 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4871 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4872 kvm_arch_hardware_disable();
4875 static int kvm_dying_cpu(unsigned int cpu)
4877 raw_spin_lock(&kvm_count_lock);
4878 if (kvm_usage_count)
4879 hardware_disable_nolock(NULL);
4880 raw_spin_unlock(&kvm_count_lock);
4884 static void hardware_disable_all_nolock(void)
4886 BUG_ON(!kvm_usage_count);
4889 if (!kvm_usage_count)
4890 on_each_cpu(hardware_disable_nolock, NULL, 1);
4893 static void hardware_disable_all(void)
4895 raw_spin_lock(&kvm_count_lock);
4896 hardware_disable_all_nolock();
4897 raw_spin_unlock(&kvm_count_lock);
4900 static int hardware_enable_all(void)
4904 raw_spin_lock(&kvm_count_lock);
4907 if (kvm_usage_count == 1) {
4908 atomic_set(&hardware_enable_failed, 0);
4909 on_each_cpu(hardware_enable_nolock, NULL, 1);
4911 if (atomic_read(&hardware_enable_failed)) {
4912 hardware_disable_all_nolock();
4917 raw_spin_unlock(&kvm_count_lock);
4922 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4926 * Some (well, at least mine) BIOSes hang on reboot if
4929 * And Intel TXT required VMX off for all cpu when system shutdown.
4931 pr_info("kvm: exiting hardware virtualization\n");
4932 kvm_rebooting = true;
4933 on_each_cpu(hardware_disable_nolock, NULL, 1);
4937 static struct notifier_block kvm_reboot_notifier = {
4938 .notifier_call = kvm_reboot,
4942 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4946 for (i = 0; i < bus->dev_count; i++) {
4947 struct kvm_io_device *pos = bus->range[i].dev;
4949 kvm_iodevice_destructor(pos);
4954 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4955 const struct kvm_io_range *r2)
4957 gpa_t addr1 = r1->addr;
4958 gpa_t addr2 = r2->addr;
4963 /* If r2->len == 0, match the exact address. If r2->len != 0,
4964 * accept any overlapping write. Any order is acceptable for
4965 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4966 * we process all of them.
4979 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4981 return kvm_io_bus_cmp(p1, p2);
4984 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4985 gpa_t addr, int len)
4987 struct kvm_io_range *range, key;
4990 key = (struct kvm_io_range) {
4995 range = bsearch(&key, bus->range, bus->dev_count,
4996 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
5000 off = range - bus->range;
5002 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
5008 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5009 struct kvm_io_range *range, const void *val)
5013 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5017 while (idx < bus->dev_count &&
5018 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5019 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
5028 /* kvm_io_bus_write - called under kvm->slots_lock */
5029 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5030 int len, const void *val)
5032 struct kvm_io_bus *bus;
5033 struct kvm_io_range range;
5036 range = (struct kvm_io_range) {
5041 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5044 r = __kvm_io_bus_write(vcpu, bus, &range, val);
5045 return r < 0 ? r : 0;
5047 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
5049 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
5050 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
5051 gpa_t addr, int len, const void *val, long cookie)
5053 struct kvm_io_bus *bus;
5054 struct kvm_io_range range;
5056 range = (struct kvm_io_range) {
5061 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5065 /* First try the device referenced by cookie. */
5066 if ((cookie >= 0) && (cookie < bus->dev_count) &&
5067 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
5068 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
5073 * cookie contained garbage; fall back to search and return the
5074 * correct cookie value.
5076 return __kvm_io_bus_write(vcpu, bus, &range, val);
5079 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5080 struct kvm_io_range *range, void *val)
5084 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5088 while (idx < bus->dev_count &&
5089 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5090 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
5099 /* kvm_io_bus_read - called under kvm->slots_lock */
5100 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5103 struct kvm_io_bus *bus;
5104 struct kvm_io_range range;
5107 range = (struct kvm_io_range) {
5112 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5115 r = __kvm_io_bus_read(vcpu, bus, &range, val);
5116 return r < 0 ? r : 0;
5119 /* Caller must hold slots_lock. */
5120 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
5121 int len, struct kvm_io_device *dev)
5124 struct kvm_io_bus *new_bus, *bus;
5125 struct kvm_io_range range;
5127 bus = kvm_get_bus(kvm, bus_idx);
5131 /* exclude ioeventfd which is limited by maximum fd */
5132 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
5135 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
5136 GFP_KERNEL_ACCOUNT);
5140 range = (struct kvm_io_range) {
5146 for (i = 0; i < bus->dev_count; i++)
5147 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
5150 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
5151 new_bus->dev_count++;
5152 new_bus->range[i] = range;
5153 memcpy(new_bus->range + i + 1, bus->range + i,
5154 (bus->dev_count - i) * sizeof(struct kvm_io_range));
5155 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5156 synchronize_srcu_expedited(&kvm->srcu);
5162 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5163 struct kvm_io_device *dev)
5166 struct kvm_io_bus *new_bus, *bus;
5168 lockdep_assert_held(&kvm->slots_lock);
5170 bus = kvm_get_bus(kvm, bus_idx);
5174 for (i = 0; i < bus->dev_count; i++) {
5175 if (bus->range[i].dev == dev) {
5180 if (i == bus->dev_count)
5183 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
5184 GFP_KERNEL_ACCOUNT);
5186 memcpy(new_bus, bus, struct_size(bus, range, i));
5187 new_bus->dev_count--;
5188 memcpy(new_bus->range + i, bus->range + i + 1,
5189 flex_array_size(new_bus, range, new_bus->dev_count - i));
5192 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5193 synchronize_srcu_expedited(&kvm->srcu);
5195 /* Destroy the old bus _after_ installing the (null) bus. */
5197 pr_err("kvm: failed to shrink bus, removing it completely\n");
5198 for (j = 0; j < bus->dev_count; j++) {
5201 kvm_iodevice_destructor(bus->range[j].dev);
5206 return new_bus ? 0 : -ENOMEM;
5209 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5212 struct kvm_io_bus *bus;
5213 int dev_idx, srcu_idx;
5214 struct kvm_io_device *iodev = NULL;
5216 srcu_idx = srcu_read_lock(&kvm->srcu);
5218 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
5222 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5226 iodev = bus->range[dev_idx].dev;
5229 srcu_read_unlock(&kvm->srcu, srcu_idx);
5233 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5235 static int kvm_debugfs_open(struct inode *inode, struct file *file,
5236 int (*get)(void *, u64 *), int (*set)(void *, u64),
5239 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5243 * The debugfs files are a reference to the kvm struct which
5244 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
5245 * avoids the race between open and the removal of the debugfs directory.
5247 if (!kvm_get_kvm_safe(stat_data->kvm))
5250 if (simple_attr_open(inode, file, get,
5251 kvm_stats_debugfs_mode(stat_data->desc) & 0222
5254 kvm_put_kvm(stat_data->kvm);
5261 static int kvm_debugfs_release(struct inode *inode, struct file *file)
5263 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5266 simple_attr_release(inode, file);
5267 kvm_put_kvm(stat_data->kvm);
5272 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
5274 *val = *(u64 *)((void *)(&kvm->stat) + offset);
5279 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
5281 *(u64 *)((void *)(&kvm->stat) + offset) = 0;
5286 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
5289 struct kvm_vcpu *vcpu;
5293 kvm_for_each_vcpu(i, vcpu, kvm)
5294 *val += *(u64 *)((void *)(&vcpu->stat) + offset);
5299 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
5302 struct kvm_vcpu *vcpu;
5304 kvm_for_each_vcpu(i, vcpu, kvm)
5305 *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
5310 static int kvm_stat_data_get(void *data, u64 *val)
5313 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5315 switch (stat_data->kind) {
5317 r = kvm_get_stat_per_vm(stat_data->kvm,
5318 stat_data->desc->desc.offset, val);
5321 r = kvm_get_stat_per_vcpu(stat_data->kvm,
5322 stat_data->desc->desc.offset, val);
5329 static int kvm_stat_data_clear(void *data, u64 val)
5332 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5337 switch (stat_data->kind) {
5339 r = kvm_clear_stat_per_vm(stat_data->kvm,
5340 stat_data->desc->desc.offset);
5343 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
5344 stat_data->desc->desc.offset);
5351 static int kvm_stat_data_open(struct inode *inode, struct file *file)
5353 __simple_attr_check_format("%llu\n", 0ull);
5354 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5355 kvm_stat_data_clear, "%llu\n");
5358 static const struct file_operations stat_fops_per_vm = {
5359 .owner = THIS_MODULE,
5360 .open = kvm_stat_data_open,
5361 .release = kvm_debugfs_release,
5362 .read = simple_attr_read,
5363 .write = simple_attr_write,
5364 .llseek = no_llseek,
5367 static int vm_stat_get(void *_offset, u64 *val)
5369 unsigned offset = (long)_offset;
5374 mutex_lock(&kvm_lock);
5375 list_for_each_entry(kvm, &vm_list, vm_list) {
5376 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
5379 mutex_unlock(&kvm_lock);
5383 static int vm_stat_clear(void *_offset, u64 val)
5385 unsigned offset = (long)_offset;
5391 mutex_lock(&kvm_lock);
5392 list_for_each_entry(kvm, &vm_list, vm_list) {
5393 kvm_clear_stat_per_vm(kvm, offset);
5395 mutex_unlock(&kvm_lock);
5400 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
5401 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
5403 static int vcpu_stat_get(void *_offset, u64 *val)
5405 unsigned offset = (long)_offset;
5410 mutex_lock(&kvm_lock);
5411 list_for_each_entry(kvm, &vm_list, vm_list) {
5412 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
5415 mutex_unlock(&kvm_lock);
5419 static int vcpu_stat_clear(void *_offset, u64 val)
5421 unsigned offset = (long)_offset;
5427 mutex_lock(&kvm_lock);
5428 list_for_each_entry(kvm, &vm_list, vm_list) {
5429 kvm_clear_stat_per_vcpu(kvm, offset);
5431 mutex_unlock(&kvm_lock);
5436 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5438 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
5440 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5442 struct kobj_uevent_env *env;
5443 unsigned long long created, active;
5445 if (!kvm_dev.this_device || !kvm)
5448 mutex_lock(&kvm_lock);
5449 if (type == KVM_EVENT_CREATE_VM) {
5450 kvm_createvm_count++;
5452 } else if (type == KVM_EVENT_DESTROY_VM) {
5455 created = kvm_createvm_count;
5456 active = kvm_active_vms;
5457 mutex_unlock(&kvm_lock);
5459 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
5463 add_uevent_var(env, "CREATED=%llu", created);
5464 add_uevent_var(env, "COUNT=%llu", active);
5466 if (type == KVM_EVENT_CREATE_VM) {
5467 add_uevent_var(env, "EVENT=create");
5468 kvm->userspace_pid = task_pid_nr(current);
5469 } else if (type == KVM_EVENT_DESTROY_VM) {
5470 add_uevent_var(env, "EVENT=destroy");
5472 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5474 if (kvm->debugfs_dentry) {
5475 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5478 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5480 add_uevent_var(env, "STATS_PATH=%s", tmp);
5484 /* no need for checks, since we are adding at most only 5 keys */
5485 env->envp[env->envp_idx++] = NULL;
5486 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5490 static void kvm_init_debug(void)
5492 const struct file_operations *fops;
5493 const struct _kvm_stats_desc *pdesc;
5496 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5498 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5499 pdesc = &kvm_vm_stats_desc[i];
5500 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5501 fops = &vm_stat_fops;
5503 fops = &vm_stat_readonly_fops;
5504 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5506 (void *)(long)pdesc->desc.offset, fops);
5509 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5510 pdesc = &kvm_vcpu_stats_desc[i];
5511 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5512 fops = &vcpu_stat_fops;
5514 fops = &vcpu_stat_readonly_fops;
5515 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5517 (void *)(long)pdesc->desc.offset, fops);
5521 static int kvm_suspend(void)
5523 if (kvm_usage_count)
5524 hardware_disable_nolock(NULL);
5528 static void kvm_resume(void)
5530 if (kvm_usage_count) {
5531 lockdep_assert_not_held(&kvm_count_lock);
5532 hardware_enable_nolock(NULL);
5536 static struct syscore_ops kvm_syscore_ops = {
5537 .suspend = kvm_suspend,
5538 .resume = kvm_resume,
5542 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5544 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5547 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5549 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5551 WRITE_ONCE(vcpu->preempted, false);
5552 WRITE_ONCE(vcpu->ready, false);
5554 __this_cpu_write(kvm_running_vcpu, vcpu);
5555 kvm_arch_sched_in(vcpu, cpu);
5556 kvm_arch_vcpu_load(vcpu, cpu);
5559 static void kvm_sched_out(struct preempt_notifier *pn,
5560 struct task_struct *next)
5562 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5564 if (current->on_rq) {
5565 WRITE_ONCE(vcpu->preempted, true);
5566 WRITE_ONCE(vcpu->ready, true);
5568 kvm_arch_vcpu_put(vcpu);
5569 __this_cpu_write(kvm_running_vcpu, NULL);
5573 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5575 * We can disable preemption locally around accessing the per-CPU variable,
5576 * and use the resolved vcpu pointer after enabling preemption again,
5577 * because even if the current thread is migrated to another CPU, reading
5578 * the per-CPU value later will give us the same value as we update the
5579 * per-CPU variable in the preempt notifier handlers.
5581 struct kvm_vcpu *kvm_get_running_vcpu(void)
5583 struct kvm_vcpu *vcpu;
5586 vcpu = __this_cpu_read(kvm_running_vcpu);
5591 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5594 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5596 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5598 return &kvm_running_vcpu;
5601 #ifdef CONFIG_GUEST_PERF_EVENTS
5602 static unsigned int kvm_guest_state(void)
5604 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5607 if (!kvm_arch_pmi_in_guest(vcpu))
5610 state = PERF_GUEST_ACTIVE;
5611 if (!kvm_arch_vcpu_in_kernel(vcpu))
5612 state |= PERF_GUEST_USER;
5617 static unsigned long kvm_guest_get_ip(void)
5619 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5621 /* Retrieving the IP must be guarded by a call to kvm_guest_state(). */
5622 if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu)))
5625 return kvm_arch_vcpu_get_ip(vcpu);
5628 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5629 .state = kvm_guest_state,
5630 .get_ip = kvm_guest_get_ip,
5631 .handle_intel_pt_intr = NULL,
5634 void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void))
5636 kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler;
5637 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5639 void kvm_unregister_perf_callbacks(void)
5641 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5645 struct kvm_cpu_compat_check {
5650 static void check_processor_compat(void *data)
5652 struct kvm_cpu_compat_check *c = data;
5654 *c->ret = kvm_arch_check_processor_compat(c->opaque);
5657 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5658 struct module *module)
5660 struct kvm_cpu_compat_check c;
5664 r = kvm_arch_init(opaque);
5669 * kvm_arch_init makes sure there's at most one caller
5670 * for architectures that support multiple implementations,
5671 * like intel and amd on x86.
5672 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5673 * conflicts in case kvm is already setup for another implementation.
5675 r = kvm_irqfd_init();
5679 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5684 r = kvm_arch_hardware_setup(opaque);
5690 for_each_online_cpu(cpu) {
5691 smp_call_function_single(cpu, check_processor_compat, &c, 1);
5696 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5697 kvm_starting_cpu, kvm_dying_cpu);
5700 register_reboot_notifier(&kvm_reboot_notifier);
5702 /* A kmem cache lets us meet the alignment requirements of fx_save. */
5704 vcpu_align = __alignof__(struct kvm_vcpu);
5706 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5708 offsetof(struct kvm_vcpu, arch),
5709 offsetofend(struct kvm_vcpu, stats_id)
5710 - offsetof(struct kvm_vcpu, arch),
5712 if (!kvm_vcpu_cache) {
5717 for_each_possible_cpu(cpu) {
5718 if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu),
5719 GFP_KERNEL, cpu_to_node(cpu))) {
5725 r = kvm_async_pf_init();
5729 kvm_chardev_ops.owner = module;
5730 kvm_vm_fops.owner = module;
5731 kvm_vcpu_fops.owner = module;
5733 r = misc_register(&kvm_dev);
5735 pr_err("kvm: misc device register failed\n");
5739 register_syscore_ops(&kvm_syscore_ops);
5741 kvm_preempt_ops.sched_in = kvm_sched_in;
5742 kvm_preempt_ops.sched_out = kvm_sched_out;
5746 r = kvm_vfio_ops_init();
5752 kvm_async_pf_deinit();
5754 for_each_possible_cpu(cpu)
5755 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5757 kmem_cache_destroy(kvm_vcpu_cache);
5759 unregister_reboot_notifier(&kvm_reboot_notifier);
5760 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5762 kvm_arch_hardware_unsetup();
5764 free_cpumask_var(cpus_hardware_enabled);
5772 EXPORT_SYMBOL_GPL(kvm_init);
5778 debugfs_remove_recursive(kvm_debugfs_dir);
5779 misc_deregister(&kvm_dev);
5780 for_each_possible_cpu(cpu)
5781 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5782 kmem_cache_destroy(kvm_vcpu_cache);
5783 kvm_async_pf_deinit();
5784 unregister_syscore_ops(&kvm_syscore_ops);
5785 unregister_reboot_notifier(&kvm_reboot_notifier);
5786 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5787 on_each_cpu(hardware_disable_nolock, NULL, 1);
5788 kvm_arch_hardware_unsetup();
5791 free_cpumask_var(cpus_hardware_enabled);
5792 kvm_vfio_ops_exit();
5794 EXPORT_SYMBOL_GPL(kvm_exit);
5796 struct kvm_vm_worker_thread_context {
5798 struct task_struct *parent;
5799 struct completion init_done;
5800 kvm_vm_thread_fn_t thread_fn;
5805 static int kvm_vm_worker_thread(void *context)
5808 * The init_context is allocated on the stack of the parent thread, so
5809 * we have to locally copy anything that is needed beyond initialization
5811 struct kvm_vm_worker_thread_context *init_context = context;
5812 struct kvm *kvm = init_context->kvm;
5813 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5814 uintptr_t data = init_context->data;
5817 err = kthread_park(current);
5818 /* kthread_park(current) is never supposed to return an error */
5823 err = cgroup_attach_task_all(init_context->parent, current);
5825 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5830 set_user_nice(current, task_nice(init_context->parent));
5833 init_context->err = err;
5834 complete(&init_context->init_done);
5835 init_context = NULL;
5840 /* Wait to be woken up by the spawner before proceeding. */
5843 if (!kthread_should_stop())
5844 err = thread_fn(kvm, data);
5849 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5850 uintptr_t data, const char *name,
5851 struct task_struct **thread_ptr)
5853 struct kvm_vm_worker_thread_context init_context = {};
5854 struct task_struct *thread;
5857 init_context.kvm = kvm;
5858 init_context.parent = current;
5859 init_context.thread_fn = thread_fn;
5860 init_context.data = data;
5861 init_completion(&init_context.init_done);
5863 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5864 "%s-%d", name, task_pid_nr(current));
5866 return PTR_ERR(thread);
5868 /* kthread_run is never supposed to return NULL */
5869 WARN_ON(thread == NULL);
5871 wait_for_completion(&init_context.init_done);
5873 if (!init_context.err)
5874 *thread_ptr = thread;
5876 return init_context.err;