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 struct file_operations kvm_chardev_ops;
122 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
124 #ifdef CONFIG_KVM_COMPAT
125 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
127 #define KVM_COMPAT(c) .compat_ioctl = (c)
130 * For architectures that don't implement a compat infrastructure,
131 * adopt a double line of defense:
132 * - Prevent a compat task from opening /dev/kvm
133 * - If the open has been done by a 64bit task, and the KVM fd
134 * passed to a compat task, let the ioctls fail.
136 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
137 unsigned long arg) { return -EINVAL; }
139 static int kvm_no_compat_open(struct inode *inode, struct file *file)
141 return is_compat_task() ? -ENODEV : 0;
143 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
144 .open = kvm_no_compat_open
146 static int hardware_enable_all(void);
147 static void hardware_disable_all(void);
149 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
151 __visible bool kvm_rebooting;
152 EXPORT_SYMBOL_GPL(kvm_rebooting);
154 #define KVM_EVENT_CREATE_VM 0
155 #define KVM_EVENT_DESTROY_VM 1
156 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
157 static unsigned long long kvm_createvm_count;
158 static unsigned long long kvm_active_vms;
160 static DEFINE_PER_CPU(cpumask_var_t, cpu_kick_mask);
162 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
163 unsigned long start, unsigned long end)
167 __weak void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
171 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
174 * The metadata used by is_zone_device_page() to determine whether or
175 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
176 * the device has been pinned, e.g. by get_user_pages(). WARN if the
177 * page_count() is zero to help detect bad usage of this helper.
179 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
182 return is_zone_device_page(pfn_to_page(pfn));
185 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
188 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
189 * perspective they are "normal" pages, albeit with slightly different
193 return PageReserved(pfn_to_page(pfn)) &&
195 !kvm_is_zone_device_pfn(pfn);
201 * Switches to specified vcpu, until a matching vcpu_put()
203 void vcpu_load(struct kvm_vcpu *vcpu)
207 __this_cpu_write(kvm_running_vcpu, vcpu);
208 preempt_notifier_register(&vcpu->preempt_notifier);
209 kvm_arch_vcpu_load(vcpu, cpu);
212 EXPORT_SYMBOL_GPL(vcpu_load);
214 void vcpu_put(struct kvm_vcpu *vcpu)
217 kvm_arch_vcpu_put(vcpu);
218 preempt_notifier_unregister(&vcpu->preempt_notifier);
219 __this_cpu_write(kvm_running_vcpu, NULL);
222 EXPORT_SYMBOL_GPL(vcpu_put);
224 /* TODO: merge with kvm_arch_vcpu_should_kick */
225 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
227 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
230 * We need to wait for the VCPU to reenable interrupts and get out of
231 * READING_SHADOW_PAGE_TABLES mode.
233 if (req & KVM_REQUEST_WAIT)
234 return mode != OUTSIDE_GUEST_MODE;
237 * Need to kick a running VCPU, but otherwise there is nothing to do.
239 return mode == IN_GUEST_MODE;
242 static void ack_flush(void *_completed)
246 static inline bool kvm_kick_many_cpus(struct cpumask *cpus, bool wait)
248 if (cpumask_empty(cpus))
251 smp_call_function_many(cpus, ack_flush, NULL, wait);
255 static void kvm_make_vcpu_request(struct kvm_vcpu *vcpu, unsigned int req,
256 struct cpumask *tmp, int current_cpu)
260 if (likely(!(req & KVM_REQUEST_NO_ACTION)))
261 __kvm_make_request(req, vcpu);
263 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
267 * Note, the vCPU could get migrated to a different pCPU at any point
268 * after kvm_request_needs_ipi(), which could result in sending an IPI
269 * to the previous pCPU. But, that's OK because the purpose of the IPI
270 * is to ensure the vCPU returns to OUTSIDE_GUEST_MODE, which is
271 * satisfied if the vCPU migrates. Entering READING_SHADOW_PAGE_TABLES
272 * after this point is also OK, as the requirement is only that KVM wait
273 * for vCPUs that were reading SPTEs _before_ any changes were
274 * finalized. See kvm_vcpu_kick() for more details on handling requests.
276 if (kvm_request_needs_ipi(vcpu, req)) {
277 cpu = READ_ONCE(vcpu->cpu);
278 if (cpu != -1 && cpu != current_cpu)
279 __cpumask_set_cpu(cpu, tmp);
283 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
284 unsigned long *vcpu_bitmap)
286 struct kvm_vcpu *vcpu;
287 struct cpumask *cpus;
293 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
296 for_each_set_bit(i, vcpu_bitmap, KVM_MAX_VCPUS) {
297 vcpu = kvm_get_vcpu(kvm, i);
300 kvm_make_vcpu_request(vcpu, req, cpus, me);
303 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
309 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
310 struct kvm_vcpu *except)
312 struct kvm_vcpu *vcpu;
313 struct cpumask *cpus;
320 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
323 kvm_for_each_vcpu(i, vcpu, kvm) {
326 kvm_make_vcpu_request(vcpu, req, cpus, me);
329 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
335 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
337 return kvm_make_all_cpus_request_except(kvm, req, NULL);
339 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
341 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
342 void kvm_flush_remote_tlbs(struct kvm *kvm)
344 ++kvm->stat.generic.remote_tlb_flush_requests;
347 * We want to publish modifications to the page tables before reading
348 * mode. Pairs with a memory barrier in arch-specific code.
349 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
350 * and smp_mb in walk_shadow_page_lockless_begin/end.
351 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
353 * There is already an smp_mb__after_atomic() before
354 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
357 if (!kvm_arch_flush_remote_tlb(kvm)
358 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
359 ++kvm->stat.generic.remote_tlb_flush;
361 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
364 static void kvm_flush_shadow_all(struct kvm *kvm)
366 kvm_arch_flush_shadow_all(kvm);
367 kvm_arch_guest_memory_reclaimed(kvm);
370 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
371 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
374 gfp_flags |= mc->gfp_zero;
377 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
379 return (void *)__get_free_page(gfp_flags);
382 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
386 if (mc->nobjs >= min)
388 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
389 obj = mmu_memory_cache_alloc_obj(mc, (mc->gfp_custom) ?
393 return mc->nobjs >= min ? 0 : -ENOMEM;
394 mc->objects[mc->nobjs++] = obj;
399 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
404 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
408 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
410 free_page((unsigned long)mc->objects[--mc->nobjs]);
414 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
418 if (WARN_ON(!mc->nobjs))
419 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
421 p = mc->objects[--mc->nobjs];
427 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
429 mutex_init(&vcpu->mutex);
434 #ifndef __KVM_HAVE_ARCH_WQP
435 rcuwait_init(&vcpu->wait);
437 kvm_async_pf_vcpu_init(vcpu);
439 kvm_vcpu_set_in_spin_loop(vcpu, false);
440 kvm_vcpu_set_dy_eligible(vcpu, false);
441 vcpu->preempted = false;
443 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
444 vcpu->last_used_slot = NULL;
447 static void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
449 kvm_arch_vcpu_destroy(vcpu);
450 kvm_dirty_ring_free(&vcpu->dirty_ring);
453 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
454 * the vcpu->pid pointer, and at destruction time all file descriptors
457 put_pid(rcu_dereference_protected(vcpu->pid, 1));
459 free_page((unsigned long)vcpu->run);
460 kmem_cache_free(kvm_vcpu_cache, vcpu);
463 void kvm_destroy_vcpus(struct kvm *kvm)
466 struct kvm_vcpu *vcpu;
468 kvm_for_each_vcpu(i, vcpu, kvm) {
469 kvm_vcpu_destroy(vcpu);
470 xa_erase(&kvm->vcpu_array, i);
473 atomic_set(&kvm->online_vcpus, 0);
475 EXPORT_SYMBOL_GPL(kvm_destroy_vcpus);
477 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
478 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
480 return container_of(mn, struct kvm, mmu_notifier);
483 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
484 struct mm_struct *mm,
485 unsigned long start, unsigned long end)
487 struct kvm *kvm = mmu_notifier_to_kvm(mn);
490 idx = srcu_read_lock(&kvm->srcu);
491 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
492 srcu_read_unlock(&kvm->srcu, idx);
495 typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
497 typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
500 typedef void (*on_unlock_fn_t)(struct kvm *kvm);
502 struct kvm_hva_range {
506 hva_handler_t handler;
507 on_lock_fn_t on_lock;
508 on_unlock_fn_t on_unlock;
514 * Use a dedicated stub instead of NULL to indicate that there is no callback
515 * function/handler. The compiler technically can't guarantee that a real
516 * function will have a non-zero address, and so it will generate code to
517 * check for !NULL, whereas comparing against a stub will be elided at compile
518 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
520 static void kvm_null_fn(void)
524 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
526 /* Iterate over each memslot intersecting [start, last] (inclusive) range */
527 #define kvm_for_each_memslot_in_hva_range(node, slots, start, last) \
528 for (node = interval_tree_iter_first(&slots->hva_tree, start, last); \
530 node = interval_tree_iter_next(node, start, last)) \
532 static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
533 const struct kvm_hva_range *range)
535 bool ret = false, locked = false;
536 struct kvm_gfn_range gfn_range;
537 struct kvm_memory_slot *slot;
538 struct kvm_memslots *slots;
541 if (WARN_ON_ONCE(range->end <= range->start))
544 /* A null handler is allowed if and only if on_lock() is provided. */
545 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
546 IS_KVM_NULL_FN(range->handler)))
549 idx = srcu_read_lock(&kvm->srcu);
551 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
552 struct interval_tree_node *node;
554 slots = __kvm_memslots(kvm, i);
555 kvm_for_each_memslot_in_hva_range(node, slots,
556 range->start, range->end - 1) {
557 unsigned long hva_start, hva_end;
559 slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]);
560 hva_start = max(range->start, slot->userspace_addr);
561 hva_end = min(range->end, slot->userspace_addr +
562 (slot->npages << PAGE_SHIFT));
565 * To optimize for the likely case where the address
566 * range is covered by zero or one memslots, don't
567 * bother making these conditional (to avoid writes on
568 * the second or later invocation of the handler).
570 gfn_range.pte = range->pte;
571 gfn_range.may_block = range->may_block;
574 * {gfn(page) | page intersects with [hva_start, hva_end)} =
575 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
577 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
578 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
579 gfn_range.slot = slot;
584 if (!IS_KVM_NULL_FN(range->on_lock))
585 range->on_lock(kvm, range->start, range->end);
586 if (IS_KVM_NULL_FN(range->handler))
589 ret |= range->handler(kvm, &gfn_range);
593 if (range->flush_on_ret && ret)
594 kvm_flush_remote_tlbs(kvm);
598 if (!IS_KVM_NULL_FN(range->on_unlock))
599 range->on_unlock(kvm);
602 srcu_read_unlock(&kvm->srcu, idx);
604 /* The notifiers are averse to booleans. :-( */
608 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
612 hva_handler_t handler)
614 struct kvm *kvm = mmu_notifier_to_kvm(mn);
615 const struct kvm_hva_range range = {
620 .on_lock = (void *)kvm_null_fn,
621 .on_unlock = (void *)kvm_null_fn,
622 .flush_on_ret = true,
626 return __kvm_handle_hva_range(kvm, &range);
629 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
632 hva_handler_t handler)
634 struct kvm *kvm = mmu_notifier_to_kvm(mn);
635 const struct kvm_hva_range range = {
640 .on_lock = (void *)kvm_null_fn,
641 .on_unlock = (void *)kvm_null_fn,
642 .flush_on_ret = false,
646 return __kvm_handle_hva_range(kvm, &range);
648 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
649 struct mm_struct *mm,
650 unsigned long address,
653 struct kvm *kvm = mmu_notifier_to_kvm(mn);
655 trace_kvm_set_spte_hva(address);
658 * .change_pte() must be surrounded by .invalidate_range_{start,end}().
659 * If mmu_notifier_count is zero, then no in-progress invalidations,
660 * including this one, found a relevant memslot at start(); rechecking
661 * memslots here is unnecessary. Note, a false positive (count elevated
662 * by a different invalidation) is sub-optimal but functionally ok.
664 WARN_ON_ONCE(!READ_ONCE(kvm->mn_active_invalidate_count));
665 if (!READ_ONCE(kvm->mmu_notifier_count))
668 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
671 void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
675 * The count increase must become visible at unlock time as no
676 * spte can be established without taking the mmu_lock and
677 * count is also read inside the mmu_lock critical section.
679 kvm->mmu_notifier_count++;
680 if (likely(kvm->mmu_notifier_count == 1)) {
681 kvm->mmu_notifier_range_start = start;
682 kvm->mmu_notifier_range_end = end;
685 * Fully tracking multiple concurrent ranges has diminishing
686 * returns. Keep things simple and just find the minimal range
687 * which includes the current and new ranges. As there won't be
688 * enough information to subtract a range after its invalidate
689 * completes, any ranges invalidated concurrently will
690 * accumulate and persist until all outstanding invalidates
693 kvm->mmu_notifier_range_start =
694 min(kvm->mmu_notifier_range_start, start);
695 kvm->mmu_notifier_range_end =
696 max(kvm->mmu_notifier_range_end, end);
700 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
701 const struct mmu_notifier_range *range)
703 struct kvm *kvm = mmu_notifier_to_kvm(mn);
704 const struct kvm_hva_range hva_range = {
705 .start = range->start,
708 .handler = kvm_unmap_gfn_range,
709 .on_lock = kvm_inc_notifier_count,
710 .on_unlock = kvm_arch_guest_memory_reclaimed,
711 .flush_on_ret = true,
712 .may_block = mmu_notifier_range_blockable(range),
715 trace_kvm_unmap_hva_range(range->start, range->end);
718 * Prevent memslot modification between range_start() and range_end()
719 * so that conditionally locking provides the same result in both
720 * functions. Without that guarantee, the mmu_notifier_count
721 * adjustments will be imbalanced.
723 * Pairs with the decrement in range_end().
725 spin_lock(&kvm->mn_invalidate_lock);
726 kvm->mn_active_invalidate_count++;
727 spin_unlock(&kvm->mn_invalidate_lock);
729 gfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end,
730 hva_range.may_block);
732 __kvm_handle_hva_range(kvm, &hva_range);
737 void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
741 * This sequence increase will notify the kvm page fault that
742 * the page that is going to be mapped in the spte could have
745 kvm->mmu_notifier_seq++;
748 * The above sequence increase must be visible before the
749 * below count decrease, which is ensured by the smp_wmb above
750 * in conjunction with the smp_rmb in mmu_notifier_retry().
752 kvm->mmu_notifier_count--;
755 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
756 const struct mmu_notifier_range *range)
758 struct kvm *kvm = mmu_notifier_to_kvm(mn);
759 const struct kvm_hva_range hva_range = {
760 .start = range->start,
763 .handler = (void *)kvm_null_fn,
764 .on_lock = kvm_dec_notifier_count,
765 .on_unlock = (void *)kvm_null_fn,
766 .flush_on_ret = false,
767 .may_block = mmu_notifier_range_blockable(range),
771 __kvm_handle_hva_range(kvm, &hva_range);
773 /* Pairs with the increment in range_start(). */
774 spin_lock(&kvm->mn_invalidate_lock);
775 wake = (--kvm->mn_active_invalidate_count == 0);
776 spin_unlock(&kvm->mn_invalidate_lock);
779 * There can only be one waiter, since the wait happens under
783 rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
785 BUG_ON(kvm->mmu_notifier_count < 0);
788 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
789 struct mm_struct *mm,
793 trace_kvm_age_hva(start, end);
795 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
798 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
799 struct mm_struct *mm,
803 trace_kvm_age_hva(start, end);
806 * Even though we do not flush TLB, this will still adversely
807 * affect performance on pre-Haswell Intel EPT, where there is
808 * no EPT Access Bit to clear so that we have to tear down EPT
809 * tables instead. If we find this unacceptable, we can always
810 * add a parameter to kvm_age_hva so that it effectively doesn't
811 * do anything on clear_young.
813 * Also note that currently we never issue secondary TLB flushes
814 * from clear_young, leaving this job up to the regular system
815 * cadence. If we find this inaccurate, we might come up with a
816 * more sophisticated heuristic later.
818 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
821 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
822 struct mm_struct *mm,
823 unsigned long address)
825 trace_kvm_test_age_hva(address);
827 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
831 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
832 struct mm_struct *mm)
834 struct kvm *kvm = mmu_notifier_to_kvm(mn);
837 idx = srcu_read_lock(&kvm->srcu);
838 kvm_flush_shadow_all(kvm);
839 srcu_read_unlock(&kvm->srcu, idx);
842 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
843 .invalidate_range = kvm_mmu_notifier_invalidate_range,
844 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
845 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
846 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
847 .clear_young = kvm_mmu_notifier_clear_young,
848 .test_young = kvm_mmu_notifier_test_young,
849 .change_pte = kvm_mmu_notifier_change_pte,
850 .release = kvm_mmu_notifier_release,
853 static int kvm_init_mmu_notifier(struct kvm *kvm)
855 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
856 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
859 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
861 static int kvm_init_mmu_notifier(struct kvm *kvm)
866 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
868 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
869 static int kvm_pm_notifier_call(struct notifier_block *bl,
873 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
875 return kvm_arch_pm_notifier(kvm, state);
878 static void kvm_init_pm_notifier(struct kvm *kvm)
880 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
881 /* Suspend KVM before we suspend ftrace, RCU, etc. */
882 kvm->pm_notifier.priority = INT_MAX;
883 register_pm_notifier(&kvm->pm_notifier);
886 static void kvm_destroy_pm_notifier(struct kvm *kvm)
888 unregister_pm_notifier(&kvm->pm_notifier);
890 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
891 static void kvm_init_pm_notifier(struct kvm *kvm)
895 static void kvm_destroy_pm_notifier(struct kvm *kvm)
898 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
900 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
902 if (!memslot->dirty_bitmap)
905 kvfree(memslot->dirty_bitmap);
906 memslot->dirty_bitmap = NULL;
909 /* This does not remove the slot from struct kvm_memslots data structures */
910 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
912 kvm_destroy_dirty_bitmap(slot);
914 kvm_arch_free_memslot(kvm, slot);
919 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
921 struct hlist_node *idnode;
922 struct kvm_memory_slot *memslot;
926 * The same memslot objects live in both active and inactive sets,
927 * arbitrarily free using index '1' so the second invocation of this
928 * function isn't operating over a structure with dangling pointers
929 * (even though this function isn't actually touching them).
931 if (!slots->node_idx)
934 hash_for_each_safe(slots->id_hash, bkt, idnode, memslot, id_node[1])
935 kvm_free_memslot(kvm, memslot);
938 static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
940 switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
941 case KVM_STATS_TYPE_INSTANT:
943 case KVM_STATS_TYPE_CUMULATIVE:
944 case KVM_STATS_TYPE_PEAK:
951 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
954 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
955 kvm_vcpu_stats_header.num_desc;
957 if (IS_ERR(kvm->debugfs_dentry))
960 debugfs_remove_recursive(kvm->debugfs_dentry);
962 if (kvm->debugfs_stat_data) {
963 for (i = 0; i < kvm_debugfs_num_entries; i++)
964 kfree(kvm->debugfs_stat_data[i]);
965 kfree(kvm->debugfs_stat_data);
969 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
971 static DEFINE_MUTEX(kvm_debugfs_lock);
973 char dir_name[ITOA_MAX_LEN * 2];
974 struct kvm_stat_data *stat_data;
975 const struct _kvm_stats_desc *pdesc;
977 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
978 kvm_vcpu_stats_header.num_desc;
980 if (!debugfs_initialized())
983 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
984 mutex_lock(&kvm_debugfs_lock);
985 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
987 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
989 mutex_unlock(&kvm_debugfs_lock);
992 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
993 mutex_unlock(&kvm_debugfs_lock);
997 kvm->debugfs_dentry = dent;
998 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
999 sizeof(*kvm->debugfs_stat_data),
1000 GFP_KERNEL_ACCOUNT);
1001 if (!kvm->debugfs_stat_data)
1004 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
1005 pdesc = &kvm_vm_stats_desc[i];
1006 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1010 stat_data->kvm = kvm;
1011 stat_data->desc = pdesc;
1012 stat_data->kind = KVM_STAT_VM;
1013 kvm->debugfs_stat_data[i] = stat_data;
1014 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1015 kvm->debugfs_dentry, stat_data,
1019 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
1020 pdesc = &kvm_vcpu_stats_desc[i];
1021 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1025 stat_data->kvm = kvm;
1026 stat_data->desc = pdesc;
1027 stat_data->kind = KVM_STAT_VCPU;
1028 kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
1029 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1030 kvm->debugfs_dentry, stat_data,
1034 ret = kvm_arch_create_vm_debugfs(kvm);
1036 kvm_destroy_vm_debugfs(kvm);
1044 * Called after the VM is otherwise initialized, but just before adding it to
1047 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
1053 * Called just after removing the VM from the vm_list, but before doing any
1054 * other destruction.
1056 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
1061 * Called after per-vm debugfs created. When called kvm->debugfs_dentry should
1062 * be setup already, so we can create arch-specific debugfs entries under it.
1063 * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1064 * a per-arch destroy interface is not needed.
1066 int __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1071 static struct kvm *kvm_create_vm(unsigned long type)
1073 struct kvm *kvm = kvm_arch_alloc_vm();
1074 struct kvm_memslots *slots;
1079 return ERR_PTR(-ENOMEM);
1081 KVM_MMU_LOCK_INIT(kvm);
1082 mmgrab(current->mm);
1083 kvm->mm = current->mm;
1084 kvm_eventfd_init(kvm);
1085 mutex_init(&kvm->lock);
1086 mutex_init(&kvm->irq_lock);
1087 mutex_init(&kvm->slots_lock);
1088 mutex_init(&kvm->slots_arch_lock);
1089 spin_lock_init(&kvm->mn_invalidate_lock);
1090 rcuwait_init(&kvm->mn_memslots_update_rcuwait);
1091 xa_init(&kvm->vcpu_array);
1093 INIT_LIST_HEAD(&kvm->gpc_list);
1094 spin_lock_init(&kvm->gpc_lock);
1096 INIT_LIST_HEAD(&kvm->devices);
1097 kvm->max_vcpus = KVM_MAX_VCPUS;
1099 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1102 * Force subsequent debugfs file creations to fail if the VM directory
1103 * is not created (by kvm_create_vm_debugfs()).
1105 kvm->debugfs_dentry = ERR_PTR(-ENOENT);
1107 if (init_srcu_struct(&kvm->srcu))
1108 goto out_err_no_srcu;
1109 if (init_srcu_struct(&kvm->irq_srcu))
1110 goto out_err_no_irq_srcu;
1112 refcount_set(&kvm->users_count, 1);
1113 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1114 for (j = 0; j < 2; j++) {
1115 slots = &kvm->__memslots[i][j];
1117 atomic_long_set(&slots->last_used_slot, (unsigned long)NULL);
1118 slots->hva_tree = RB_ROOT_CACHED;
1119 slots->gfn_tree = RB_ROOT;
1120 hash_init(slots->id_hash);
1121 slots->node_idx = j;
1123 /* Generations must be different for each address space. */
1124 slots->generation = i;
1127 rcu_assign_pointer(kvm->memslots[i], &kvm->__memslots[i][0]);
1130 for (i = 0; i < KVM_NR_BUSES; i++) {
1131 rcu_assign_pointer(kvm->buses[i],
1132 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
1134 goto out_err_no_arch_destroy_vm;
1137 kvm->max_halt_poll_ns = halt_poll_ns;
1139 r = kvm_arch_init_vm(kvm, type);
1141 goto out_err_no_arch_destroy_vm;
1143 r = hardware_enable_all();
1145 goto out_err_no_disable;
1147 #ifdef CONFIG_HAVE_KVM_IRQFD
1148 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
1151 r = kvm_init_mmu_notifier(kvm);
1153 goto out_err_no_mmu_notifier;
1155 r = kvm_arch_post_init_vm(kvm);
1159 mutex_lock(&kvm_lock);
1160 list_add(&kvm->vm_list, &vm_list);
1161 mutex_unlock(&kvm_lock);
1163 preempt_notifier_inc();
1164 kvm_init_pm_notifier(kvm);
1167 * When the fd passed to this ioctl() is opened it pins the module,
1168 * but try_module_get() also prevents getting a reference if the module
1169 * is in MODULE_STATE_GOING (e.g. if someone ran "rmmod --wait").
1171 if (!try_module_get(kvm_chardev_ops.owner)) {
1179 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1180 if (kvm->mmu_notifier.ops)
1181 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1183 out_err_no_mmu_notifier:
1184 hardware_disable_all();
1186 kvm_arch_destroy_vm(kvm);
1187 out_err_no_arch_destroy_vm:
1188 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
1189 for (i = 0; i < KVM_NR_BUSES; i++)
1190 kfree(kvm_get_bus(kvm, i));
1191 cleanup_srcu_struct(&kvm->irq_srcu);
1192 out_err_no_irq_srcu:
1193 cleanup_srcu_struct(&kvm->srcu);
1195 kvm_arch_free_vm(kvm);
1196 mmdrop(current->mm);
1200 static void kvm_destroy_devices(struct kvm *kvm)
1202 struct kvm_device *dev, *tmp;
1205 * We do not need to take the kvm->lock here, because nobody else
1206 * has a reference to the struct kvm at this point and therefore
1207 * cannot access the devices list anyhow.
1209 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1210 list_del(&dev->vm_node);
1211 dev->ops->destroy(dev);
1215 static void kvm_destroy_vm(struct kvm *kvm)
1218 struct mm_struct *mm = kvm->mm;
1220 kvm_destroy_pm_notifier(kvm);
1221 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1222 kvm_destroy_vm_debugfs(kvm);
1223 kvm_arch_sync_events(kvm);
1224 mutex_lock(&kvm_lock);
1225 list_del(&kvm->vm_list);
1226 mutex_unlock(&kvm_lock);
1227 kvm_arch_pre_destroy_vm(kvm);
1229 kvm_free_irq_routing(kvm);
1230 for (i = 0; i < KVM_NR_BUSES; i++) {
1231 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1234 kvm_io_bus_destroy(bus);
1235 kvm->buses[i] = NULL;
1237 kvm_coalesced_mmio_free(kvm);
1238 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1239 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1241 * At this point, pending calls to invalidate_range_start()
1242 * have completed but no more MMU notifiers will run, so
1243 * mn_active_invalidate_count may remain unbalanced.
1244 * No threads can be waiting in install_new_memslots as the
1245 * last reference on KVM has been dropped, but freeing
1246 * memslots would deadlock without this manual intervention.
1248 WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1249 kvm->mn_active_invalidate_count = 0;
1251 kvm_flush_shadow_all(kvm);
1253 kvm_arch_destroy_vm(kvm);
1254 kvm_destroy_devices(kvm);
1255 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1256 kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
1257 kvm_free_memslots(kvm, &kvm->__memslots[i][1]);
1259 cleanup_srcu_struct(&kvm->irq_srcu);
1260 cleanup_srcu_struct(&kvm->srcu);
1261 kvm_arch_free_vm(kvm);
1262 preempt_notifier_dec();
1263 hardware_disable_all();
1265 module_put(kvm_chardev_ops.owner);
1268 void kvm_get_kvm(struct kvm *kvm)
1270 refcount_inc(&kvm->users_count);
1272 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1275 * Make sure the vm is not during destruction, which is a safe version of
1276 * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise.
1278 bool kvm_get_kvm_safe(struct kvm *kvm)
1280 return refcount_inc_not_zero(&kvm->users_count);
1282 EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1284 void kvm_put_kvm(struct kvm *kvm)
1286 if (refcount_dec_and_test(&kvm->users_count))
1287 kvm_destroy_vm(kvm);
1289 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1292 * Used to put a reference that was taken on behalf of an object associated
1293 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1294 * of the new file descriptor fails and the reference cannot be transferred to
1295 * its final owner. In such cases, the caller is still actively using @kvm and
1296 * will fail miserably if the refcount unexpectedly hits zero.
1298 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1300 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1302 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1304 static int kvm_vm_release(struct inode *inode, struct file *filp)
1306 struct kvm *kvm = filp->private_data;
1308 kvm_irqfd_release(kvm);
1315 * Allocation size is twice as large as the actual dirty bitmap size.
1316 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1318 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1320 unsigned long dirty_bytes = kvm_dirty_bitmap_bytes(memslot);
1322 memslot->dirty_bitmap = __vcalloc(2, dirty_bytes, GFP_KERNEL_ACCOUNT);
1323 if (!memslot->dirty_bitmap)
1329 static struct kvm_memslots *kvm_get_inactive_memslots(struct kvm *kvm, int as_id)
1331 struct kvm_memslots *active = __kvm_memslots(kvm, as_id);
1332 int node_idx_inactive = active->node_idx ^ 1;
1334 return &kvm->__memslots[as_id][node_idx_inactive];
1338 * Helper to get the address space ID when one of memslot pointers may be NULL.
1339 * This also serves as a sanity that at least one of the pointers is non-NULL,
1340 * and that their address space IDs don't diverge.
1342 static int kvm_memslots_get_as_id(struct kvm_memory_slot *a,
1343 struct kvm_memory_slot *b)
1345 if (WARN_ON_ONCE(!a && !b))
1353 WARN_ON_ONCE(a->as_id != b->as_id);
1357 static void kvm_insert_gfn_node(struct kvm_memslots *slots,
1358 struct kvm_memory_slot *slot)
1360 struct rb_root *gfn_tree = &slots->gfn_tree;
1361 struct rb_node **node, *parent;
1362 int idx = slots->node_idx;
1365 for (node = &gfn_tree->rb_node; *node; ) {
1366 struct kvm_memory_slot *tmp;
1368 tmp = container_of(*node, struct kvm_memory_slot, gfn_node[idx]);
1370 if (slot->base_gfn < tmp->base_gfn)
1371 node = &(*node)->rb_left;
1372 else if (slot->base_gfn > tmp->base_gfn)
1373 node = &(*node)->rb_right;
1378 rb_link_node(&slot->gfn_node[idx], parent, node);
1379 rb_insert_color(&slot->gfn_node[idx], gfn_tree);
1382 static void kvm_erase_gfn_node(struct kvm_memslots *slots,
1383 struct kvm_memory_slot *slot)
1385 rb_erase(&slot->gfn_node[slots->node_idx], &slots->gfn_tree);
1388 static void kvm_replace_gfn_node(struct kvm_memslots *slots,
1389 struct kvm_memory_slot *old,
1390 struct kvm_memory_slot *new)
1392 int idx = slots->node_idx;
1394 WARN_ON_ONCE(old->base_gfn != new->base_gfn);
1396 rb_replace_node(&old->gfn_node[idx], &new->gfn_node[idx],
1401 * Replace @old with @new in the inactive memslots.
1403 * With NULL @old this simply adds @new.
1404 * With NULL @new this simply removes @old.
1406 * If @new is non-NULL its hva_node[slots_idx] range has to be set
1409 static void kvm_replace_memslot(struct kvm *kvm,
1410 struct kvm_memory_slot *old,
1411 struct kvm_memory_slot *new)
1413 int as_id = kvm_memslots_get_as_id(old, new);
1414 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1415 int idx = slots->node_idx;
1418 hash_del(&old->id_node[idx]);
1419 interval_tree_remove(&old->hva_node[idx], &slots->hva_tree);
1421 if ((long)old == atomic_long_read(&slots->last_used_slot))
1422 atomic_long_set(&slots->last_used_slot, (long)new);
1425 kvm_erase_gfn_node(slots, old);
1431 * Initialize @new's hva range. Do this even when replacing an @old
1432 * slot, kvm_copy_memslot() deliberately does not touch node data.
1434 new->hva_node[idx].start = new->userspace_addr;
1435 new->hva_node[idx].last = new->userspace_addr +
1436 (new->npages << PAGE_SHIFT) - 1;
1439 * (Re)Add the new memslot. There is no O(1) interval_tree_replace(),
1440 * hva_node needs to be swapped with remove+insert even though hva can't
1441 * change when replacing an existing slot.
1443 hash_add(slots->id_hash, &new->id_node[idx], new->id);
1444 interval_tree_insert(&new->hva_node[idx], &slots->hva_tree);
1447 * If the memslot gfn is unchanged, rb_replace_node() can be used to
1448 * switch the node in the gfn tree instead of removing the old and
1449 * inserting the new as two separate operations. Replacement is a
1450 * single O(1) operation versus two O(log(n)) operations for
1453 if (old && old->base_gfn == new->base_gfn) {
1454 kvm_replace_gfn_node(slots, old, new);
1457 kvm_erase_gfn_node(slots, old);
1458 kvm_insert_gfn_node(slots, new);
1462 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1464 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1466 #ifdef __KVM_HAVE_READONLY_MEM
1467 valid_flags |= KVM_MEM_READONLY;
1470 if (mem->flags & ~valid_flags)
1476 static void kvm_swap_active_memslots(struct kvm *kvm, int as_id)
1478 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1480 /* Grab the generation from the activate memslots. */
1481 u64 gen = __kvm_memslots(kvm, as_id)->generation;
1483 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1484 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1487 * Do not store the new memslots while there are invalidations in
1488 * progress, otherwise the locking in invalidate_range_start and
1489 * invalidate_range_end will be unbalanced.
1491 spin_lock(&kvm->mn_invalidate_lock);
1492 prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1493 while (kvm->mn_active_invalidate_count) {
1494 set_current_state(TASK_UNINTERRUPTIBLE);
1495 spin_unlock(&kvm->mn_invalidate_lock);
1497 spin_lock(&kvm->mn_invalidate_lock);
1499 finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
1500 rcu_assign_pointer(kvm->memslots[as_id], slots);
1501 spin_unlock(&kvm->mn_invalidate_lock);
1504 * Acquired in kvm_set_memslot. Must be released before synchronize
1505 * SRCU below in order to avoid deadlock with another thread
1506 * acquiring the slots_arch_lock in an srcu critical section.
1508 mutex_unlock(&kvm->slots_arch_lock);
1510 synchronize_srcu_expedited(&kvm->srcu);
1513 * Increment the new memslot generation a second time, dropping the
1514 * update in-progress flag and incrementing the generation based on
1515 * the number of address spaces. This provides a unique and easily
1516 * identifiable generation number while the memslots are in flux.
1518 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1521 * Generations must be unique even across address spaces. We do not need
1522 * a global counter for that, instead the generation space is evenly split
1523 * across address spaces. For example, with two address spaces, address
1524 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1525 * use generations 1, 3, 5, ...
1527 gen += KVM_ADDRESS_SPACE_NUM;
1529 kvm_arch_memslots_updated(kvm, gen);
1531 slots->generation = gen;
1534 static int kvm_prepare_memory_region(struct kvm *kvm,
1535 const struct kvm_memory_slot *old,
1536 struct kvm_memory_slot *new,
1537 enum kvm_mr_change change)
1542 * If dirty logging is disabled, nullify the bitmap; the old bitmap
1543 * will be freed on "commit". If logging is enabled in both old and
1544 * new, reuse the existing bitmap. If logging is enabled only in the
1545 * new and KVM isn't using a ring buffer, allocate and initialize a
1548 if (change != KVM_MR_DELETE) {
1549 if (!(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
1550 new->dirty_bitmap = NULL;
1551 else if (old && old->dirty_bitmap)
1552 new->dirty_bitmap = old->dirty_bitmap;
1553 else if (!kvm->dirty_ring_size) {
1554 r = kvm_alloc_dirty_bitmap(new);
1558 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1559 bitmap_set(new->dirty_bitmap, 0, new->npages);
1563 r = kvm_arch_prepare_memory_region(kvm, old, new, change);
1565 /* Free the bitmap on failure if it was allocated above. */
1566 if (r && new && new->dirty_bitmap && (!old || !old->dirty_bitmap))
1567 kvm_destroy_dirty_bitmap(new);
1572 static void kvm_commit_memory_region(struct kvm *kvm,
1573 struct kvm_memory_slot *old,
1574 const struct kvm_memory_slot *new,
1575 enum kvm_mr_change change)
1578 * Update the total number of memslot pages before calling the arch
1579 * hook so that architectures can consume the result directly.
1581 if (change == KVM_MR_DELETE)
1582 kvm->nr_memslot_pages -= old->npages;
1583 else if (change == KVM_MR_CREATE)
1584 kvm->nr_memslot_pages += new->npages;
1586 kvm_arch_commit_memory_region(kvm, old, new, change);
1590 /* Nothing more to do. */
1593 /* Free the old memslot and all its metadata. */
1594 kvm_free_memslot(kvm, old);
1597 case KVM_MR_FLAGS_ONLY:
1599 * Free the dirty bitmap as needed; the below check encompasses
1600 * both the flags and whether a ring buffer is being used)
1602 if (old->dirty_bitmap && !new->dirty_bitmap)
1603 kvm_destroy_dirty_bitmap(old);
1606 * The final quirk. Free the detached, old slot, but only its
1607 * memory, not any metadata. Metadata, including arch specific
1608 * data, may be reused by @new.
1618 * Activate @new, which must be installed in the inactive slots by the caller,
1619 * by swapping the active slots and then propagating @new to @old once @old is
1620 * unreachable and can be safely modified.
1622 * With NULL @old this simply adds @new to @active (while swapping the sets).
1623 * With NULL @new this simply removes @old from @active and frees it
1624 * (while also swapping the sets).
1626 static void kvm_activate_memslot(struct kvm *kvm,
1627 struct kvm_memory_slot *old,
1628 struct kvm_memory_slot *new)
1630 int as_id = kvm_memslots_get_as_id(old, new);
1632 kvm_swap_active_memslots(kvm, as_id);
1634 /* Propagate the new memslot to the now inactive memslots. */
1635 kvm_replace_memslot(kvm, old, new);
1638 static void kvm_copy_memslot(struct kvm_memory_slot *dest,
1639 const struct kvm_memory_slot *src)
1641 dest->base_gfn = src->base_gfn;
1642 dest->npages = src->npages;
1643 dest->dirty_bitmap = src->dirty_bitmap;
1644 dest->arch = src->arch;
1645 dest->userspace_addr = src->userspace_addr;
1646 dest->flags = src->flags;
1648 dest->as_id = src->as_id;
1651 static void kvm_invalidate_memslot(struct kvm *kvm,
1652 struct kvm_memory_slot *old,
1653 struct kvm_memory_slot *invalid_slot)
1656 * Mark the current slot INVALID. As with all memslot modifications,
1657 * this must be done on an unreachable slot to avoid modifying the
1658 * current slot in the active tree.
1660 kvm_copy_memslot(invalid_slot, old);
1661 invalid_slot->flags |= KVM_MEMSLOT_INVALID;
1662 kvm_replace_memslot(kvm, old, invalid_slot);
1665 * Activate the slot that is now marked INVALID, but don't propagate
1666 * the slot to the now inactive slots. The slot is either going to be
1667 * deleted or recreated as a new slot.
1669 kvm_swap_active_memslots(kvm, old->as_id);
1672 * From this point no new shadow pages pointing to a deleted, or moved,
1673 * memslot will be created. Validation of sp->gfn happens in:
1674 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1675 * - kvm_is_visible_gfn (mmu_check_root)
1677 kvm_arch_flush_shadow_memslot(kvm, old);
1678 kvm_arch_guest_memory_reclaimed(kvm);
1680 /* Was released by kvm_swap_active_memslots, reacquire. */
1681 mutex_lock(&kvm->slots_arch_lock);
1684 * Copy the arch-specific field of the newly-installed slot back to the
1685 * old slot as the arch data could have changed between releasing
1686 * slots_arch_lock in install_new_memslots() and re-acquiring the lock
1687 * above. Writers are required to retrieve memslots *after* acquiring
1688 * slots_arch_lock, thus the active slot's data is guaranteed to be fresh.
1690 old->arch = invalid_slot->arch;
1693 static void kvm_create_memslot(struct kvm *kvm,
1694 struct kvm_memory_slot *new)
1696 /* Add the new memslot to the inactive set and activate. */
1697 kvm_replace_memslot(kvm, NULL, new);
1698 kvm_activate_memslot(kvm, NULL, new);
1701 static void kvm_delete_memslot(struct kvm *kvm,
1702 struct kvm_memory_slot *old,
1703 struct kvm_memory_slot *invalid_slot)
1706 * Remove the old memslot (in the inactive memslots) by passing NULL as
1707 * the "new" slot, and for the invalid version in the active slots.
1709 kvm_replace_memslot(kvm, old, NULL);
1710 kvm_activate_memslot(kvm, invalid_slot, NULL);
1713 static void kvm_move_memslot(struct kvm *kvm,
1714 struct kvm_memory_slot *old,
1715 struct kvm_memory_slot *new,
1716 struct kvm_memory_slot *invalid_slot)
1719 * Replace the old memslot in the inactive slots, and then swap slots
1720 * and replace the current INVALID with the new as well.
1722 kvm_replace_memslot(kvm, old, new);
1723 kvm_activate_memslot(kvm, invalid_slot, new);
1726 static void kvm_update_flags_memslot(struct kvm *kvm,
1727 struct kvm_memory_slot *old,
1728 struct kvm_memory_slot *new)
1731 * Similar to the MOVE case, but the slot doesn't need to be zapped as
1732 * an intermediate step. Instead, the old memslot is simply replaced
1733 * with a new, updated copy in both memslot sets.
1735 kvm_replace_memslot(kvm, old, new);
1736 kvm_activate_memslot(kvm, old, new);
1739 static int kvm_set_memslot(struct kvm *kvm,
1740 struct kvm_memory_slot *old,
1741 struct kvm_memory_slot *new,
1742 enum kvm_mr_change change)
1744 struct kvm_memory_slot *invalid_slot;
1748 * Released in kvm_swap_active_memslots.
1750 * Must be held from before the current memslots are copied until
1751 * after the new memslots are installed with rcu_assign_pointer,
1752 * then released before the synchronize srcu in kvm_swap_active_memslots.
1754 * When modifying memslots outside of the slots_lock, must be held
1755 * before reading the pointer to the current memslots until after all
1756 * changes to those memslots are complete.
1758 * These rules ensure that installing new memslots does not lose
1759 * changes made to the previous memslots.
1761 mutex_lock(&kvm->slots_arch_lock);
1764 * Invalidate the old slot if it's being deleted or moved. This is
1765 * done prior to actually deleting/moving the memslot to allow vCPUs to
1766 * continue running by ensuring there are no mappings or shadow pages
1767 * for the memslot when it is deleted/moved. Without pre-invalidation
1768 * (and without a lock), a window would exist between effecting the
1769 * delete/move and committing the changes in arch code where KVM or a
1770 * guest could access a non-existent memslot.
1772 * Modifications are done on a temporary, unreachable slot. The old
1773 * slot needs to be preserved in case a later step fails and the
1774 * invalidation needs to be reverted.
1776 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1777 invalid_slot = kzalloc(sizeof(*invalid_slot), GFP_KERNEL_ACCOUNT);
1778 if (!invalid_slot) {
1779 mutex_unlock(&kvm->slots_arch_lock);
1782 kvm_invalidate_memslot(kvm, old, invalid_slot);
1785 r = kvm_prepare_memory_region(kvm, old, new, change);
1788 * For DELETE/MOVE, revert the above INVALID change. No
1789 * modifications required since the original slot was preserved
1790 * in the inactive slots. Changing the active memslots also
1791 * release slots_arch_lock.
1793 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1794 kvm_activate_memslot(kvm, invalid_slot, old);
1795 kfree(invalid_slot);
1797 mutex_unlock(&kvm->slots_arch_lock);
1803 * For DELETE and MOVE, the working slot is now active as the INVALID
1804 * version of the old slot. MOVE is particularly special as it reuses
1805 * the old slot and returns a copy of the old slot (in working_slot).
1806 * For CREATE, there is no old slot. For DELETE and FLAGS_ONLY, the
1807 * old slot is detached but otherwise preserved.
1809 if (change == KVM_MR_CREATE)
1810 kvm_create_memslot(kvm, new);
1811 else if (change == KVM_MR_DELETE)
1812 kvm_delete_memslot(kvm, old, invalid_slot);
1813 else if (change == KVM_MR_MOVE)
1814 kvm_move_memslot(kvm, old, new, invalid_slot);
1815 else if (change == KVM_MR_FLAGS_ONLY)
1816 kvm_update_flags_memslot(kvm, old, new);
1820 /* Free the temporary INVALID slot used for DELETE and MOVE. */
1821 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1822 kfree(invalid_slot);
1825 * No need to refresh new->arch, changes after dropping slots_arch_lock
1826 * will directly hit the final, active memslot. Architectures are
1827 * responsible for knowing that new->arch may be stale.
1829 kvm_commit_memory_region(kvm, old, new, change);
1834 static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
1835 gfn_t start, gfn_t end)
1837 struct kvm_memslot_iter iter;
1839 kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
1840 if (iter.slot->id != id)
1848 * Allocate some memory and give it an address in the guest physical address
1851 * Discontiguous memory is allowed, mostly for framebuffers.
1853 * Must be called holding kvm->slots_lock for write.
1855 int __kvm_set_memory_region(struct kvm *kvm,
1856 const struct kvm_userspace_memory_region *mem)
1858 struct kvm_memory_slot *old, *new;
1859 struct kvm_memslots *slots;
1860 enum kvm_mr_change change;
1861 unsigned long npages;
1866 r = check_memory_region_flags(mem);
1870 as_id = mem->slot >> 16;
1871 id = (u16)mem->slot;
1873 /* General sanity checks */
1874 if ((mem->memory_size & (PAGE_SIZE - 1)) ||
1875 (mem->memory_size != (unsigned long)mem->memory_size))
1877 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1879 /* We can read the guest memory with __xxx_user() later on. */
1880 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1881 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1882 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1885 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1887 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1889 if ((mem->memory_size >> PAGE_SHIFT) > KVM_MEM_MAX_NR_PAGES)
1892 slots = __kvm_memslots(kvm, as_id);
1895 * Note, the old memslot (and the pointer itself!) may be invalidated
1896 * and/or destroyed by kvm_set_memslot().
1898 old = id_to_memslot(slots, id);
1900 if (!mem->memory_size) {
1901 if (!old || !old->npages)
1904 if (WARN_ON_ONCE(kvm->nr_memslot_pages < old->npages))
1907 return kvm_set_memslot(kvm, old, NULL, KVM_MR_DELETE);
1910 base_gfn = (mem->guest_phys_addr >> PAGE_SHIFT);
1911 npages = (mem->memory_size >> PAGE_SHIFT);
1913 if (!old || !old->npages) {
1914 change = KVM_MR_CREATE;
1917 * To simplify KVM internals, the total number of pages across
1918 * all memslots must fit in an unsigned long.
1920 if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages)
1922 } else { /* Modify an existing slot. */
1923 if ((mem->userspace_addr != old->userspace_addr) ||
1924 (npages != old->npages) ||
1925 ((mem->flags ^ old->flags) & KVM_MEM_READONLY))
1928 if (base_gfn != old->base_gfn)
1929 change = KVM_MR_MOVE;
1930 else if (mem->flags != old->flags)
1931 change = KVM_MR_FLAGS_ONLY;
1932 else /* Nothing to change. */
1936 if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) &&
1937 kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages))
1940 /* Allocate a slot that will persist in the memslot. */
1941 new = kzalloc(sizeof(*new), GFP_KERNEL_ACCOUNT);
1947 new->base_gfn = base_gfn;
1948 new->npages = npages;
1949 new->flags = mem->flags;
1950 new->userspace_addr = mem->userspace_addr;
1952 r = kvm_set_memslot(kvm, old, new, change);
1957 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1959 int kvm_set_memory_region(struct kvm *kvm,
1960 const struct kvm_userspace_memory_region *mem)
1964 mutex_lock(&kvm->slots_lock);
1965 r = __kvm_set_memory_region(kvm, mem);
1966 mutex_unlock(&kvm->slots_lock);
1969 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1971 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1972 struct kvm_userspace_memory_region *mem)
1974 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1977 return kvm_set_memory_region(kvm, mem);
1980 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1982 * kvm_get_dirty_log - get a snapshot of dirty pages
1983 * @kvm: pointer to kvm instance
1984 * @log: slot id and address to which we copy the log
1985 * @is_dirty: set to '1' if any dirty pages were found
1986 * @memslot: set to the associated memslot, always valid on success
1988 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1989 int *is_dirty, struct kvm_memory_slot **memslot)
1991 struct kvm_memslots *slots;
1994 unsigned long any = 0;
1996 /* Dirty ring tracking is exclusive to dirty log tracking */
1997 if (kvm->dirty_ring_size)
2003 as_id = log->slot >> 16;
2004 id = (u16)log->slot;
2005 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2008 slots = __kvm_memslots(kvm, as_id);
2009 *memslot = id_to_memslot(slots, id);
2010 if (!(*memslot) || !(*memslot)->dirty_bitmap)
2013 kvm_arch_sync_dirty_log(kvm, *memslot);
2015 n = kvm_dirty_bitmap_bytes(*memslot);
2017 for (i = 0; !any && i < n/sizeof(long); ++i)
2018 any = (*memslot)->dirty_bitmap[i];
2020 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
2027 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
2029 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2031 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
2032 * and reenable dirty page tracking for the corresponding pages.
2033 * @kvm: pointer to kvm instance
2034 * @log: slot id and address to which we copy the log
2036 * We need to keep it in mind that VCPU threads can write to the bitmap
2037 * concurrently. So, to avoid losing track of dirty pages we keep the
2040 * 1. Take a snapshot of the bit and clear it if needed.
2041 * 2. Write protect the corresponding page.
2042 * 3. Copy the snapshot to the userspace.
2043 * 4. Upon return caller flushes TLB's if needed.
2045 * Between 2 and 4, the guest may write to the page using the remaining TLB
2046 * entry. This is not a problem because the page is reported dirty using
2047 * the snapshot taken before and step 4 ensures that writes done after
2048 * exiting to userspace will be logged for the next call.
2051 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
2053 struct kvm_memslots *slots;
2054 struct kvm_memory_slot *memslot;
2057 unsigned long *dirty_bitmap;
2058 unsigned long *dirty_bitmap_buffer;
2061 /* Dirty ring tracking is exclusive to dirty log tracking */
2062 if (kvm->dirty_ring_size)
2065 as_id = log->slot >> 16;
2066 id = (u16)log->slot;
2067 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2070 slots = __kvm_memslots(kvm, as_id);
2071 memslot = id_to_memslot(slots, id);
2072 if (!memslot || !memslot->dirty_bitmap)
2075 dirty_bitmap = memslot->dirty_bitmap;
2077 kvm_arch_sync_dirty_log(kvm, memslot);
2079 n = kvm_dirty_bitmap_bytes(memslot);
2081 if (kvm->manual_dirty_log_protect) {
2083 * Unlike kvm_get_dirty_log, we always return false in *flush,
2084 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
2085 * is some code duplication between this function and
2086 * kvm_get_dirty_log, but hopefully all architecture
2087 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
2088 * can be eliminated.
2090 dirty_bitmap_buffer = dirty_bitmap;
2092 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2093 memset(dirty_bitmap_buffer, 0, n);
2096 for (i = 0; i < n / sizeof(long); i++) {
2100 if (!dirty_bitmap[i])
2104 mask = xchg(&dirty_bitmap[i], 0);
2105 dirty_bitmap_buffer[i] = mask;
2107 offset = i * BITS_PER_LONG;
2108 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2111 KVM_MMU_UNLOCK(kvm);
2115 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2117 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
2124 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
2125 * @kvm: kvm instance
2126 * @log: slot id and address to which we copy the log
2128 * Steps 1-4 below provide general overview of dirty page logging. See
2129 * kvm_get_dirty_log_protect() function description for additional details.
2131 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
2132 * always flush the TLB (step 4) even if previous step failed and the dirty
2133 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
2134 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
2135 * writes will be marked dirty for next log read.
2137 * 1. Take a snapshot of the bit and clear it if needed.
2138 * 2. Write protect the corresponding page.
2139 * 3. Copy the snapshot to the userspace.
2140 * 4. Flush TLB's if needed.
2142 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2143 struct kvm_dirty_log *log)
2147 mutex_lock(&kvm->slots_lock);
2149 r = kvm_get_dirty_log_protect(kvm, log);
2151 mutex_unlock(&kvm->slots_lock);
2156 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
2157 * and reenable dirty page tracking for the corresponding pages.
2158 * @kvm: pointer to kvm instance
2159 * @log: slot id and address from which to fetch the bitmap of dirty pages
2161 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
2162 struct kvm_clear_dirty_log *log)
2164 struct kvm_memslots *slots;
2165 struct kvm_memory_slot *memslot;
2169 unsigned long *dirty_bitmap;
2170 unsigned long *dirty_bitmap_buffer;
2173 /* Dirty ring tracking is exclusive to dirty log tracking */
2174 if (kvm->dirty_ring_size)
2177 as_id = log->slot >> 16;
2178 id = (u16)log->slot;
2179 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2182 if (log->first_page & 63)
2185 slots = __kvm_memslots(kvm, as_id);
2186 memslot = id_to_memslot(slots, id);
2187 if (!memslot || !memslot->dirty_bitmap)
2190 dirty_bitmap = memslot->dirty_bitmap;
2192 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
2194 if (log->first_page > memslot->npages ||
2195 log->num_pages > memslot->npages - log->first_page ||
2196 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
2199 kvm_arch_sync_dirty_log(kvm, memslot);
2202 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2203 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2207 for (offset = log->first_page, i = offset / BITS_PER_LONG,
2208 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2209 i++, offset += BITS_PER_LONG) {
2210 unsigned long mask = *dirty_bitmap_buffer++;
2211 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2215 mask &= atomic_long_fetch_andnot(mask, p);
2218 * mask contains the bits that really have been cleared. This
2219 * never includes any bits beyond the length of the memslot (if
2220 * the length is not aligned to 64 pages), therefore it is not
2221 * a problem if userspace sets them in log->dirty_bitmap.
2225 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2229 KVM_MMU_UNLOCK(kvm);
2232 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2237 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2238 struct kvm_clear_dirty_log *log)
2242 mutex_lock(&kvm->slots_lock);
2244 r = kvm_clear_dirty_log_protect(kvm, log);
2246 mutex_unlock(&kvm->slots_lock);
2249 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2251 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2253 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2255 EXPORT_SYMBOL_GPL(gfn_to_memslot);
2257 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2259 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2260 u64 gen = slots->generation;
2261 struct kvm_memory_slot *slot;
2264 * This also protects against using a memslot from a different address space,
2265 * since different address spaces have different generation numbers.
2267 if (unlikely(gen != vcpu->last_used_slot_gen)) {
2268 vcpu->last_used_slot = NULL;
2269 vcpu->last_used_slot_gen = gen;
2272 slot = try_get_memslot(vcpu->last_used_slot, gfn);
2277 * Fall back to searching all memslots. We purposely use
2278 * search_memslots() instead of __gfn_to_memslot() to avoid
2279 * thrashing the VM-wide last_used_slot in kvm_memslots.
2281 slot = search_memslots(slots, gfn, false);
2283 vcpu->last_used_slot = slot;
2290 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
2292 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
2294 return kvm_is_visible_memslot(memslot);
2296 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2298 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2300 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2302 return kvm_is_visible_memslot(memslot);
2304 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2306 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
2308 struct vm_area_struct *vma;
2309 unsigned long addr, size;
2313 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
2314 if (kvm_is_error_hva(addr))
2317 mmap_read_lock(current->mm);
2318 vma = find_vma(current->mm, addr);
2322 size = vma_kernel_pagesize(vma);
2325 mmap_read_unlock(current->mm);
2330 static bool memslot_is_readonly(const struct kvm_memory_slot *slot)
2332 return slot->flags & KVM_MEM_READONLY;
2335 static unsigned long __gfn_to_hva_many(const struct kvm_memory_slot *slot, gfn_t gfn,
2336 gfn_t *nr_pages, bool write)
2338 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
2339 return KVM_HVA_ERR_BAD;
2341 if (memslot_is_readonly(slot) && write)
2342 return KVM_HVA_ERR_RO_BAD;
2345 *nr_pages = slot->npages - (gfn - slot->base_gfn);
2347 return __gfn_to_hva_memslot(slot, gfn);
2350 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2353 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2356 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2359 return gfn_to_hva_many(slot, gfn, NULL);
2361 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2363 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2365 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2367 EXPORT_SYMBOL_GPL(gfn_to_hva);
2369 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2371 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2373 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2376 * Return the hva of a @gfn and the R/W attribute if possible.
2378 * @slot: the kvm_memory_slot which contains @gfn
2379 * @gfn: the gfn to be translated
2380 * @writable: used to return the read/write attribute of the @slot if the hva
2381 * is valid and @writable is not NULL
2383 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2384 gfn_t gfn, bool *writable)
2386 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2388 if (!kvm_is_error_hva(hva) && writable)
2389 *writable = !memslot_is_readonly(slot);
2394 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2396 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2398 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2401 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2403 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2405 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2408 static inline int check_user_page_hwpoison(unsigned long addr)
2410 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
2412 rc = get_user_pages(addr, 1, flags, NULL, NULL);
2413 return rc == -EHWPOISON;
2417 * The fast path to get the writable pfn which will be stored in @pfn,
2418 * true indicates success, otherwise false is returned. It's also the
2419 * only part that runs if we can in atomic context.
2421 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2422 bool *writable, kvm_pfn_t *pfn)
2424 struct page *page[1];
2427 * Fast pin a writable pfn only if it is a write fault request
2428 * or the caller allows to map a writable pfn for a read fault
2431 if (!(write_fault || writable))
2434 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2435 *pfn = page_to_pfn(page[0]);
2446 * The slow path to get the pfn of the specified host virtual address,
2447 * 1 indicates success, -errno is returned if error is detected.
2449 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2450 bool *writable, kvm_pfn_t *pfn)
2452 unsigned int flags = FOLL_HWPOISON;
2459 *writable = write_fault;
2462 flags |= FOLL_WRITE;
2464 flags |= FOLL_NOWAIT;
2466 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2470 /* map read fault as writable if possible */
2471 if (unlikely(!write_fault) && writable) {
2474 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2480 *pfn = page_to_pfn(page);
2484 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2486 if (unlikely(!(vma->vm_flags & VM_READ)))
2489 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2495 static int kvm_try_get_pfn(kvm_pfn_t pfn)
2497 if (kvm_is_reserved_pfn(pfn))
2499 return get_page_unless_zero(pfn_to_page(pfn));
2502 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2503 unsigned long addr, bool write_fault,
2504 bool *writable, kvm_pfn_t *p_pfn)
2511 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2514 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2515 * not call the fault handler, so do it here.
2517 bool unlocked = false;
2518 r = fixup_user_fault(current->mm, addr,
2519 (write_fault ? FAULT_FLAG_WRITE : 0),
2526 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2531 if (write_fault && !pte_write(*ptep)) {
2532 pfn = KVM_PFN_ERR_RO_FAULT;
2537 *writable = pte_write(*ptep);
2538 pfn = pte_pfn(*ptep);
2541 * Get a reference here because callers of *hva_to_pfn* and
2542 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2543 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2544 * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
2545 * simply do nothing for reserved pfns.
2547 * Whoever called remap_pfn_range is also going to call e.g.
2548 * unmap_mapping_range before the underlying pages are freed,
2549 * causing a call to our MMU notifier.
2551 * Certain IO or PFNMAP mappings can be backed with valid
2552 * struct pages, but be allocated without refcounting e.g.,
2553 * tail pages of non-compound higher order allocations, which
2554 * would then underflow the refcount when the caller does the
2555 * required put_page. Don't allow those pages here.
2557 if (!kvm_try_get_pfn(pfn))
2561 pte_unmap_unlock(ptep, ptl);
2568 * Pin guest page in memory and return its pfn.
2569 * @addr: host virtual address which maps memory to the guest
2570 * @atomic: whether this function can sleep
2571 * @async: whether this function need to wait IO complete if the
2572 * host page is not in the memory
2573 * @write_fault: whether we should get a writable host page
2574 * @writable: whether it allows to map a writable host page for !@write_fault
2576 * The function will map a writable host page for these two cases:
2577 * 1): @write_fault = true
2578 * 2): @write_fault = false && @writable, @writable will tell the caller
2579 * whether the mapping is writable.
2581 kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2582 bool write_fault, bool *writable)
2584 struct vm_area_struct *vma;
2588 /* we can do it either atomically or asynchronously, not both */
2589 BUG_ON(atomic && async);
2591 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2595 return KVM_PFN_ERR_FAULT;
2597 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2601 mmap_read_lock(current->mm);
2602 if (npages == -EHWPOISON ||
2603 (!async && check_user_page_hwpoison(addr))) {
2604 pfn = KVM_PFN_ERR_HWPOISON;
2609 vma = vma_lookup(current->mm, addr);
2612 pfn = KVM_PFN_ERR_FAULT;
2613 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2614 r = hva_to_pfn_remapped(vma, addr, write_fault, writable, &pfn);
2618 pfn = KVM_PFN_ERR_FAULT;
2620 if (async && vma_is_valid(vma, write_fault))
2622 pfn = KVM_PFN_ERR_FAULT;
2625 mmap_read_unlock(current->mm);
2629 kvm_pfn_t __gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn,
2630 bool atomic, bool *async, bool write_fault,
2631 bool *writable, hva_t *hva)
2633 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2638 if (addr == KVM_HVA_ERR_RO_BAD) {
2641 return KVM_PFN_ERR_RO_FAULT;
2644 if (kvm_is_error_hva(addr)) {
2647 return KVM_PFN_NOSLOT;
2650 /* Do not map writable pfn in the readonly memslot. */
2651 if (writable && memslot_is_readonly(slot)) {
2656 return hva_to_pfn(addr, atomic, async, write_fault,
2659 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2661 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2664 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2665 write_fault, writable, NULL);
2667 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2669 kvm_pfn_t gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn)
2671 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2673 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2675 kvm_pfn_t gfn_to_pfn_memslot_atomic(const struct kvm_memory_slot *slot, gfn_t gfn)
2677 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2679 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2681 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2683 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2685 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2687 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2689 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2691 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2693 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2695 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2697 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2699 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2700 struct page **pages, int nr_pages)
2705 addr = gfn_to_hva_many(slot, gfn, &entry);
2706 if (kvm_is_error_hva(addr))
2709 if (entry < nr_pages)
2712 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2714 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2716 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2718 if (is_error_noslot_pfn(pfn))
2719 return KVM_ERR_PTR_BAD_PAGE;
2721 if (kvm_is_reserved_pfn(pfn)) {
2723 return KVM_ERR_PTR_BAD_PAGE;
2726 return pfn_to_page(pfn);
2729 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2733 pfn = gfn_to_pfn(kvm, gfn);
2735 return kvm_pfn_to_page(pfn);
2737 EXPORT_SYMBOL_GPL(gfn_to_page);
2739 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty)
2745 kvm_release_pfn_dirty(pfn);
2747 kvm_release_pfn_clean(pfn);
2750 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2754 struct page *page = KVM_UNMAPPED_PAGE;
2759 pfn = gfn_to_pfn(vcpu->kvm, gfn);
2760 if (is_error_noslot_pfn(pfn))
2763 if (pfn_valid(pfn)) {
2764 page = pfn_to_page(pfn);
2766 #ifdef CONFIG_HAS_IOMEM
2768 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2782 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2784 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2792 if (map->page != KVM_UNMAPPED_PAGE)
2794 #ifdef CONFIG_HAS_IOMEM
2800 kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
2802 kvm_release_pfn(map->pfn, dirty);
2807 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2809 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2813 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2815 return kvm_pfn_to_page(pfn);
2817 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2819 void kvm_release_page_clean(struct page *page)
2821 WARN_ON(is_error_page(page));
2823 kvm_release_pfn_clean(page_to_pfn(page));
2825 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2827 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2829 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2830 put_page(pfn_to_page(pfn));
2832 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2834 void kvm_release_page_dirty(struct page *page)
2836 WARN_ON(is_error_page(page));
2838 kvm_release_pfn_dirty(page_to_pfn(page));
2840 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2842 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2844 kvm_set_pfn_dirty(pfn);
2845 kvm_release_pfn_clean(pfn);
2847 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2849 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2851 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2852 SetPageDirty(pfn_to_page(pfn));
2854 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2856 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2858 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2859 mark_page_accessed(pfn_to_page(pfn));
2861 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2863 static int next_segment(unsigned long len, int offset)
2865 if (len > PAGE_SIZE - offset)
2866 return PAGE_SIZE - offset;
2871 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2872 void *data, int offset, int len)
2877 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2878 if (kvm_is_error_hva(addr))
2880 r = __copy_from_user(data, (void __user *)addr + offset, len);
2886 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2889 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2891 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2893 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2895 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2896 int offset, int len)
2898 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2900 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2902 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2904 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2906 gfn_t gfn = gpa >> PAGE_SHIFT;
2908 int offset = offset_in_page(gpa);
2911 while ((seg = next_segment(len, offset)) != 0) {
2912 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2922 EXPORT_SYMBOL_GPL(kvm_read_guest);
2924 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2926 gfn_t gfn = gpa >> PAGE_SHIFT;
2928 int offset = offset_in_page(gpa);
2931 while ((seg = next_segment(len, offset)) != 0) {
2932 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2942 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2944 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2945 void *data, int offset, unsigned long len)
2950 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2951 if (kvm_is_error_hva(addr))
2953 pagefault_disable();
2954 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2961 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2962 void *data, unsigned long len)
2964 gfn_t gfn = gpa >> PAGE_SHIFT;
2965 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2966 int offset = offset_in_page(gpa);
2968 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2970 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2972 static int __kvm_write_guest_page(struct kvm *kvm,
2973 struct kvm_memory_slot *memslot, gfn_t gfn,
2974 const void *data, int offset, int len)
2979 addr = gfn_to_hva_memslot(memslot, gfn);
2980 if (kvm_is_error_hva(addr))
2982 r = __copy_to_user((void __user *)addr + offset, data, len);
2985 mark_page_dirty_in_slot(kvm, memslot, gfn);
2989 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2990 const void *data, int offset, int len)
2992 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2994 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2996 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2998 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2999 const void *data, int offset, int len)
3001 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3003 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
3005 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
3007 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
3010 gfn_t gfn = gpa >> PAGE_SHIFT;
3012 int offset = offset_in_page(gpa);
3015 while ((seg = next_segment(len, offset)) != 0) {
3016 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
3026 EXPORT_SYMBOL_GPL(kvm_write_guest);
3028 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
3031 gfn_t gfn = gpa >> PAGE_SHIFT;
3033 int offset = offset_in_page(gpa);
3036 while ((seg = next_segment(len, offset)) != 0) {
3037 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
3047 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
3049 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
3050 struct gfn_to_hva_cache *ghc,
3051 gpa_t gpa, unsigned long len)
3053 int offset = offset_in_page(gpa);
3054 gfn_t start_gfn = gpa >> PAGE_SHIFT;
3055 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
3056 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
3057 gfn_t nr_pages_avail;
3059 /* Update ghc->generation before performing any error checks. */
3060 ghc->generation = slots->generation;
3062 if (start_gfn > end_gfn) {
3063 ghc->hva = KVM_HVA_ERR_BAD;
3068 * If the requested region crosses two memslots, we still
3069 * verify that the entire region is valid here.
3071 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
3072 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
3073 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
3075 if (kvm_is_error_hva(ghc->hva))
3079 /* Use the slow path for cross page reads and writes. */
3080 if (nr_pages_needed == 1)
3083 ghc->memslot = NULL;
3090 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3091 gpa_t gpa, unsigned long len)
3093 struct kvm_memslots *slots = kvm_memslots(kvm);
3094 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
3096 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
3098 int kvm_write_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_write_guest(kvm, gpa, data, len);
3120 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
3123 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
3127 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
3129 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3130 void *data, unsigned long len)
3132 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
3134 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
3136 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3137 void *data, unsigned int offset,
3140 struct kvm_memslots *slots = kvm_memslots(kvm);
3142 gpa_t gpa = ghc->gpa + offset;
3144 if (WARN_ON_ONCE(len + offset > ghc->len))
3147 if (slots->generation != ghc->generation) {
3148 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3152 if (kvm_is_error_hva(ghc->hva))
3155 if (unlikely(!ghc->memslot))
3156 return kvm_read_guest(kvm, gpa, data, len);
3158 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
3164 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3166 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3167 void *data, unsigned long len)
3169 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3171 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
3173 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3175 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3176 gfn_t gfn = gpa >> PAGE_SHIFT;
3178 int offset = offset_in_page(gpa);
3181 while ((seg = next_segment(len, offset)) != 0) {
3182 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
3191 EXPORT_SYMBOL_GPL(kvm_clear_guest);
3193 void mark_page_dirty_in_slot(struct kvm *kvm,
3194 const struct kvm_memory_slot *memslot,
3197 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
3199 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3200 if (WARN_ON_ONCE(!vcpu) || WARN_ON_ONCE(vcpu->kvm != kvm))
3204 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
3205 unsigned long rel_gfn = gfn - memslot->base_gfn;
3206 u32 slot = (memslot->as_id << 16) | memslot->id;
3208 if (kvm->dirty_ring_size)
3209 kvm_dirty_ring_push(&vcpu->dirty_ring,
3212 set_bit_le(rel_gfn, memslot->dirty_bitmap);
3215 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
3217 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3219 struct kvm_memory_slot *memslot;
3221 memslot = gfn_to_memslot(kvm, gfn);
3222 mark_page_dirty_in_slot(kvm, memslot, gfn);
3224 EXPORT_SYMBOL_GPL(mark_page_dirty);
3226 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3228 struct kvm_memory_slot *memslot;
3230 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3231 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
3233 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3235 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3237 if (!vcpu->sigset_active)
3241 * This does a lockless modification of ->real_blocked, which is fine
3242 * because, only current can change ->real_blocked and all readers of
3243 * ->real_blocked don't care as long ->real_blocked is always a subset
3246 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
3249 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3251 if (!vcpu->sigset_active)
3254 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
3255 sigemptyset(¤t->real_blocked);
3258 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3260 unsigned int old, val, grow, grow_start;
3262 old = val = vcpu->halt_poll_ns;
3263 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3264 grow = READ_ONCE(halt_poll_ns_grow);
3269 if (val < grow_start)
3272 if (val > vcpu->kvm->max_halt_poll_ns)
3273 val = vcpu->kvm->max_halt_poll_ns;
3275 vcpu->halt_poll_ns = val;
3277 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
3280 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3282 unsigned int old, val, shrink, grow_start;
3284 old = val = vcpu->halt_poll_ns;
3285 shrink = READ_ONCE(halt_poll_ns_shrink);
3286 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3292 if (val < grow_start)
3295 vcpu->halt_poll_ns = val;
3296 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3299 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3302 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3304 if (kvm_arch_vcpu_runnable(vcpu)) {
3305 kvm_make_request(KVM_REQ_UNHALT, vcpu);
3308 if (kvm_cpu_has_pending_timer(vcpu))
3310 if (signal_pending(current))
3312 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3317 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3322 * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is
3323 * pending. This is mostly used when halting a vCPU, but may also be used
3324 * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI.
3326 bool kvm_vcpu_block(struct kvm_vcpu *vcpu)
3328 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
3329 bool waited = false;
3331 vcpu->stat.generic.blocking = 1;
3334 kvm_arch_vcpu_blocking(vcpu);
3335 prepare_to_rcuwait(wait);
3339 set_current_state(TASK_INTERRUPTIBLE);
3341 if (kvm_vcpu_check_block(vcpu) < 0)
3349 finish_rcuwait(wait);
3350 kvm_arch_vcpu_unblocking(vcpu);
3353 vcpu->stat.generic.blocking = 0;
3358 static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start,
3359 ktime_t end, bool success)
3361 struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic;
3362 u64 poll_ns = ktime_to_ns(ktime_sub(end, start));
3364 ++vcpu->stat.generic.halt_attempted_poll;
3367 ++vcpu->stat.generic.halt_successful_poll;
3369 if (!vcpu_valid_wakeup(vcpu))
3370 ++vcpu->stat.generic.halt_poll_invalid;
3372 stats->halt_poll_success_ns += poll_ns;
3373 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns);
3375 stats->halt_poll_fail_ns += poll_ns;
3376 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns);
3381 * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc... If halt
3382 * polling is enabled, busy wait for a short time before blocking to avoid the
3383 * expensive block+unblock sequence if a wake event arrives soon after the vCPU
3386 void kvm_vcpu_halt(struct kvm_vcpu *vcpu)
3388 bool halt_poll_allowed = !kvm_arch_no_poll(vcpu);
3389 bool do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns;
3390 ktime_t start, cur, poll_end;
3391 bool waited = false;
3394 start = cur = poll_end = ktime_get();
3396 ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns);
3400 * This sets KVM_REQ_UNHALT if an interrupt
3403 if (kvm_vcpu_check_block(vcpu) < 0)
3406 poll_end = cur = ktime_get();
3407 } while (kvm_vcpu_can_poll(cur, stop));
3410 waited = kvm_vcpu_block(vcpu);
3414 vcpu->stat.generic.halt_wait_ns +=
3415 ktime_to_ns(cur) - ktime_to_ns(poll_end);
3416 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3417 ktime_to_ns(cur) - ktime_to_ns(poll_end));
3420 /* The total time the vCPU was "halted", including polling time. */
3421 halt_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3424 * Note, halt-polling is considered successful so long as the vCPU was
3425 * never actually scheduled out, i.e. even if the wake event arrived
3426 * after of the halt-polling loop itself, but before the full wait.
3429 update_halt_poll_stats(vcpu, start, poll_end, !waited);
3431 if (halt_poll_allowed) {
3432 if (!vcpu_valid_wakeup(vcpu)) {
3433 shrink_halt_poll_ns(vcpu);
3434 } else if (vcpu->kvm->max_halt_poll_ns) {
3435 if (halt_ns <= vcpu->halt_poll_ns)
3437 /* we had a long block, shrink polling */
3438 else if (vcpu->halt_poll_ns &&
3439 halt_ns > vcpu->kvm->max_halt_poll_ns)
3440 shrink_halt_poll_ns(vcpu);
3441 /* we had a short halt and our poll time is too small */
3442 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3443 halt_ns < vcpu->kvm->max_halt_poll_ns)
3444 grow_halt_poll_ns(vcpu);
3446 vcpu->halt_poll_ns = 0;
3450 trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu));
3452 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
3454 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3456 if (__kvm_vcpu_wake_up(vcpu)) {
3457 WRITE_ONCE(vcpu->ready, true);
3458 ++vcpu->stat.generic.halt_wakeup;
3464 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3468 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3470 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3474 if (kvm_vcpu_wake_up(vcpu))
3479 * The only state change done outside the vcpu mutex is IN_GUEST_MODE
3480 * to EXITING_GUEST_MODE. Therefore the moderately expensive "should
3481 * kick" check does not need atomic operations if kvm_vcpu_kick is used
3482 * within the vCPU thread itself.
3484 if (vcpu == __this_cpu_read(kvm_running_vcpu)) {
3485 if (vcpu->mode == IN_GUEST_MODE)
3486 WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE);
3491 * Note, the vCPU could get migrated to a different pCPU at any point
3492 * after kvm_arch_vcpu_should_kick(), which could result in sending an
3493 * IPI to the previous pCPU. But, that's ok because the purpose of the
3494 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
3495 * vCPU also requires it to leave IN_GUEST_MODE.
3497 if (kvm_arch_vcpu_should_kick(vcpu)) {
3498 cpu = READ_ONCE(vcpu->cpu);
3499 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3500 smp_send_reschedule(cpu);
3505 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3506 #endif /* !CONFIG_S390 */
3508 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3511 struct task_struct *task = NULL;
3515 pid = rcu_dereference(target->pid);
3517 task = get_pid_task(pid, PIDTYPE_PID);
3521 ret = yield_to(task, 1);
3522 put_task_struct(task);
3526 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3529 * Helper that checks whether a VCPU is eligible for directed yield.
3530 * Most eligible candidate to yield is decided by following heuristics:
3532 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3533 * (preempted lock holder), indicated by @in_spin_loop.
3534 * Set at the beginning and cleared at the end of interception/PLE handler.
3536 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3537 * chance last time (mostly it has become eligible now since we have probably
3538 * yielded to lockholder in last iteration. This is done by toggling
3539 * @dy_eligible each time a VCPU checked for eligibility.)
3541 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3542 * to preempted lock-holder could result in wrong VCPU selection and CPU
3543 * burning. Giving priority for a potential lock-holder increases lock
3546 * Since algorithm is based on heuristics, accessing another VCPU data without
3547 * locking does not harm. It may result in trying to yield to same VCPU, fail
3548 * and continue with next VCPU and so on.
3550 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3552 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3555 eligible = !vcpu->spin_loop.in_spin_loop ||
3556 vcpu->spin_loop.dy_eligible;
3558 if (vcpu->spin_loop.in_spin_loop)
3559 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3568 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3569 * a vcpu_load/vcpu_put pair. However, for most architectures
3570 * kvm_arch_vcpu_runnable does not require vcpu_load.
3572 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3574 return kvm_arch_vcpu_runnable(vcpu);
3577 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3579 if (kvm_arch_dy_runnable(vcpu))
3582 #ifdef CONFIG_KVM_ASYNC_PF
3583 if (!list_empty_careful(&vcpu->async_pf.done))
3590 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3595 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3597 struct kvm *kvm = me->kvm;
3598 struct kvm_vcpu *vcpu;
3599 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3605 kvm_vcpu_set_in_spin_loop(me, true);
3607 * We boost the priority of a VCPU that is runnable but not
3608 * currently running, because it got preempted by something
3609 * else and called schedule in __vcpu_run. Hopefully that
3610 * VCPU is holding the lock that we need and will release it.
3611 * We approximate round-robin by starting at the last boosted VCPU.
3613 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3614 kvm_for_each_vcpu(i, vcpu, kvm) {
3615 if (!pass && i <= last_boosted_vcpu) {
3616 i = last_boosted_vcpu;
3618 } else if (pass && i > last_boosted_vcpu)
3620 if (!READ_ONCE(vcpu->ready))
3624 if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu))
3626 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3627 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3628 !kvm_arch_vcpu_in_kernel(vcpu))
3630 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3633 yielded = kvm_vcpu_yield_to(vcpu);
3635 kvm->last_boosted_vcpu = i;
3637 } else if (yielded < 0) {
3644 kvm_vcpu_set_in_spin_loop(me, false);
3646 /* Ensure vcpu is not eligible during next spinloop */
3647 kvm_vcpu_set_dy_eligible(me, false);
3649 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3651 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3653 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3654 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3655 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3656 kvm->dirty_ring_size / PAGE_SIZE);
3662 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3664 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3667 if (vmf->pgoff == 0)
3668 page = virt_to_page(vcpu->run);
3670 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3671 page = virt_to_page(vcpu->arch.pio_data);
3673 #ifdef CONFIG_KVM_MMIO
3674 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3675 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3677 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3678 page = kvm_dirty_ring_get_page(
3680 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3682 return kvm_arch_vcpu_fault(vcpu, vmf);
3688 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3689 .fault = kvm_vcpu_fault,
3692 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3694 struct kvm_vcpu *vcpu = file->private_data;
3695 unsigned long pages = vma_pages(vma);
3697 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3698 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3699 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3702 vma->vm_ops = &kvm_vcpu_vm_ops;
3706 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3708 struct kvm_vcpu *vcpu = filp->private_data;
3710 kvm_put_kvm(vcpu->kvm);
3714 static const struct file_operations kvm_vcpu_fops = {
3715 .release = kvm_vcpu_release,
3716 .unlocked_ioctl = kvm_vcpu_ioctl,
3717 .mmap = kvm_vcpu_mmap,
3718 .llseek = noop_llseek,
3719 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3723 * Allocates an inode for the vcpu.
3725 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3727 char name[8 + 1 + ITOA_MAX_LEN + 1];
3729 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3730 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3733 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3735 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3736 struct dentry *debugfs_dentry;
3737 char dir_name[ITOA_MAX_LEN * 2];
3739 if (!debugfs_initialized())
3742 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3743 debugfs_dentry = debugfs_create_dir(dir_name,
3744 vcpu->kvm->debugfs_dentry);
3746 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3751 * Creates some virtual cpus. Good luck creating more than one.
3753 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3756 struct kvm_vcpu *vcpu;
3759 if (id >= KVM_MAX_VCPU_IDS)
3762 mutex_lock(&kvm->lock);
3763 if (kvm->created_vcpus >= kvm->max_vcpus) {
3764 mutex_unlock(&kvm->lock);
3768 kvm->created_vcpus++;
3769 mutex_unlock(&kvm->lock);
3771 r = kvm_arch_vcpu_precreate(kvm, id);
3773 goto vcpu_decrement;
3775 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3778 goto vcpu_decrement;
3781 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3782 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3787 vcpu->run = page_address(page);
3789 kvm_vcpu_init(vcpu, kvm, id);
3791 r = kvm_arch_vcpu_create(vcpu);
3793 goto vcpu_free_run_page;
3795 if (kvm->dirty_ring_size) {
3796 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3797 id, kvm->dirty_ring_size);
3799 goto arch_vcpu_destroy;
3802 mutex_lock(&kvm->lock);
3803 if (kvm_get_vcpu_by_id(kvm, id)) {
3805 goto unlock_vcpu_destroy;
3808 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3809 r = xa_insert(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, GFP_KERNEL_ACCOUNT);
3810 BUG_ON(r == -EBUSY);
3812 goto unlock_vcpu_destroy;
3814 /* Fill the stats id string for the vcpu */
3815 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3816 task_pid_nr(current), id);
3818 /* Now it's all set up, let userspace reach it */
3820 r = create_vcpu_fd(vcpu);
3822 xa_erase(&kvm->vcpu_array, vcpu->vcpu_idx);
3823 kvm_put_kvm_no_destroy(kvm);
3824 goto unlock_vcpu_destroy;
3828 * Pairs with smp_rmb() in kvm_get_vcpu. Store the vcpu
3829 * pointer before kvm->online_vcpu's incremented value.
3832 atomic_inc(&kvm->online_vcpus);
3834 mutex_unlock(&kvm->lock);
3835 kvm_arch_vcpu_postcreate(vcpu);
3836 kvm_create_vcpu_debugfs(vcpu);
3839 unlock_vcpu_destroy:
3840 mutex_unlock(&kvm->lock);
3841 kvm_dirty_ring_free(&vcpu->dirty_ring);
3843 kvm_arch_vcpu_destroy(vcpu);
3845 free_page((unsigned long)vcpu->run);
3847 kmem_cache_free(kvm_vcpu_cache, vcpu);
3849 mutex_lock(&kvm->lock);
3850 kvm->created_vcpus--;
3851 mutex_unlock(&kvm->lock);
3855 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3858 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3859 vcpu->sigset_active = 1;
3860 vcpu->sigset = *sigset;
3862 vcpu->sigset_active = 0;
3866 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3867 size_t size, loff_t *offset)
3869 struct kvm_vcpu *vcpu = file->private_data;
3871 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3872 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3873 sizeof(vcpu->stat), user_buffer, size, offset);
3876 static const struct file_operations kvm_vcpu_stats_fops = {
3877 .read = kvm_vcpu_stats_read,
3878 .llseek = noop_llseek,
3881 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3885 char name[15 + ITOA_MAX_LEN + 1];
3887 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3889 fd = get_unused_fd_flags(O_CLOEXEC);
3893 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3896 return PTR_ERR(file);
3898 file->f_mode |= FMODE_PREAD;
3899 fd_install(fd, file);
3904 static long kvm_vcpu_ioctl(struct file *filp,
3905 unsigned int ioctl, unsigned long arg)
3907 struct kvm_vcpu *vcpu = filp->private_data;
3908 void __user *argp = (void __user *)arg;
3910 struct kvm_fpu *fpu = NULL;
3911 struct kvm_sregs *kvm_sregs = NULL;
3913 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
3916 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3920 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3921 * execution; mutex_lock() would break them.
3923 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3924 if (r != -ENOIOCTLCMD)
3927 if (mutex_lock_killable(&vcpu->mutex))
3935 oldpid = rcu_access_pointer(vcpu->pid);
3936 if (unlikely(oldpid != task_pid(current))) {
3937 /* The thread running this VCPU changed. */
3940 r = kvm_arch_vcpu_run_pid_change(vcpu);
3944 newpid = get_task_pid(current, PIDTYPE_PID);
3945 rcu_assign_pointer(vcpu->pid, newpid);
3950 r = kvm_arch_vcpu_ioctl_run(vcpu);
3951 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3954 case KVM_GET_REGS: {
3955 struct kvm_regs *kvm_regs;
3958 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3961 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3965 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3972 case KVM_SET_REGS: {
3973 struct kvm_regs *kvm_regs;
3975 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3976 if (IS_ERR(kvm_regs)) {
3977 r = PTR_ERR(kvm_regs);
3980 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3984 case KVM_GET_SREGS: {
3985 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3986 GFP_KERNEL_ACCOUNT);
3990 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3994 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3999 case KVM_SET_SREGS: {
4000 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
4001 if (IS_ERR(kvm_sregs)) {
4002 r = PTR_ERR(kvm_sregs);
4006 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
4009 case KVM_GET_MP_STATE: {
4010 struct kvm_mp_state mp_state;
4012 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
4016 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
4021 case KVM_SET_MP_STATE: {
4022 struct kvm_mp_state mp_state;
4025 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
4027 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
4030 case KVM_TRANSLATE: {
4031 struct kvm_translation tr;
4034 if (copy_from_user(&tr, argp, sizeof(tr)))
4036 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
4040 if (copy_to_user(argp, &tr, sizeof(tr)))
4045 case KVM_SET_GUEST_DEBUG: {
4046 struct kvm_guest_debug dbg;
4049 if (copy_from_user(&dbg, argp, sizeof(dbg)))
4051 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
4054 case KVM_SET_SIGNAL_MASK: {
4055 struct kvm_signal_mask __user *sigmask_arg = argp;
4056 struct kvm_signal_mask kvm_sigmask;
4057 sigset_t sigset, *p;
4062 if (copy_from_user(&kvm_sigmask, argp,
4063 sizeof(kvm_sigmask)))
4066 if (kvm_sigmask.len != sizeof(sigset))
4069 if (copy_from_user(&sigset, sigmask_arg->sigset,
4074 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
4078 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
4082 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
4086 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
4092 fpu = memdup_user(argp, sizeof(*fpu));
4098 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
4101 case KVM_GET_STATS_FD: {
4102 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
4106 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
4109 mutex_unlock(&vcpu->mutex);
4115 #ifdef CONFIG_KVM_COMPAT
4116 static long kvm_vcpu_compat_ioctl(struct file *filp,
4117 unsigned int ioctl, unsigned long arg)
4119 struct kvm_vcpu *vcpu = filp->private_data;
4120 void __user *argp = compat_ptr(arg);
4123 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
4127 case KVM_SET_SIGNAL_MASK: {
4128 struct kvm_signal_mask __user *sigmask_arg = argp;
4129 struct kvm_signal_mask kvm_sigmask;
4134 if (copy_from_user(&kvm_sigmask, argp,
4135 sizeof(kvm_sigmask)))
4138 if (kvm_sigmask.len != sizeof(compat_sigset_t))
4141 if (get_compat_sigset(&sigset,
4142 (compat_sigset_t __user *)sigmask_arg->sigset))
4144 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
4146 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
4150 r = kvm_vcpu_ioctl(filp, ioctl, arg);
4158 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
4160 struct kvm_device *dev = filp->private_data;
4163 return dev->ops->mmap(dev, vma);
4168 static int kvm_device_ioctl_attr(struct kvm_device *dev,
4169 int (*accessor)(struct kvm_device *dev,
4170 struct kvm_device_attr *attr),
4173 struct kvm_device_attr attr;
4178 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4181 return accessor(dev, &attr);
4184 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
4187 struct kvm_device *dev = filp->private_data;
4189 if (dev->kvm->mm != current->mm || dev->kvm->vm_dead)
4193 case KVM_SET_DEVICE_ATTR:
4194 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
4195 case KVM_GET_DEVICE_ATTR:
4196 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
4197 case KVM_HAS_DEVICE_ATTR:
4198 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
4200 if (dev->ops->ioctl)
4201 return dev->ops->ioctl(dev, ioctl, arg);
4207 static int kvm_device_release(struct inode *inode, struct file *filp)
4209 struct kvm_device *dev = filp->private_data;
4210 struct kvm *kvm = dev->kvm;
4212 if (dev->ops->release) {
4213 mutex_lock(&kvm->lock);
4214 list_del(&dev->vm_node);
4215 dev->ops->release(dev);
4216 mutex_unlock(&kvm->lock);
4223 static const struct file_operations kvm_device_fops = {
4224 .unlocked_ioctl = kvm_device_ioctl,
4225 .release = kvm_device_release,
4226 KVM_COMPAT(kvm_device_ioctl),
4227 .mmap = kvm_device_mmap,
4230 struct kvm_device *kvm_device_from_filp(struct file *filp)
4232 if (filp->f_op != &kvm_device_fops)
4235 return filp->private_data;
4238 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
4239 #ifdef CONFIG_KVM_MPIC
4240 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
4241 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
4245 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
4247 if (type >= ARRAY_SIZE(kvm_device_ops_table))
4250 if (kvm_device_ops_table[type] != NULL)
4253 kvm_device_ops_table[type] = ops;
4257 void kvm_unregister_device_ops(u32 type)
4259 if (kvm_device_ops_table[type] != NULL)
4260 kvm_device_ops_table[type] = NULL;
4263 static int kvm_ioctl_create_device(struct kvm *kvm,
4264 struct kvm_create_device *cd)
4266 const struct kvm_device_ops *ops = NULL;
4267 struct kvm_device *dev;
4268 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
4272 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4275 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4276 ops = kvm_device_ops_table[type];
4283 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
4290 mutex_lock(&kvm->lock);
4291 ret = ops->create(dev, type);
4293 mutex_unlock(&kvm->lock);
4297 list_add(&dev->vm_node, &kvm->devices);
4298 mutex_unlock(&kvm->lock);
4304 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
4306 kvm_put_kvm_no_destroy(kvm);
4307 mutex_lock(&kvm->lock);
4308 list_del(&dev->vm_node);
4311 mutex_unlock(&kvm->lock);
4321 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4324 case KVM_CAP_USER_MEMORY:
4325 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4326 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
4327 case KVM_CAP_INTERNAL_ERROR_DATA:
4328 #ifdef CONFIG_HAVE_KVM_MSI
4329 case KVM_CAP_SIGNAL_MSI:
4331 #ifdef CONFIG_HAVE_KVM_IRQFD
4333 case KVM_CAP_IRQFD_RESAMPLE:
4335 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
4336 case KVM_CAP_CHECK_EXTENSION_VM:
4337 case KVM_CAP_ENABLE_CAP_VM:
4338 case KVM_CAP_HALT_POLL:
4340 #ifdef CONFIG_KVM_MMIO
4341 case KVM_CAP_COALESCED_MMIO:
4342 return KVM_COALESCED_MMIO_PAGE_OFFSET;
4343 case KVM_CAP_COALESCED_PIO:
4346 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4347 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4348 return KVM_DIRTY_LOG_MANUAL_CAPS;
4350 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4351 case KVM_CAP_IRQ_ROUTING:
4352 return KVM_MAX_IRQ_ROUTES;
4354 #if KVM_ADDRESS_SPACE_NUM > 1
4355 case KVM_CAP_MULTI_ADDRESS_SPACE:
4356 return KVM_ADDRESS_SPACE_NUM;
4358 case KVM_CAP_NR_MEMSLOTS:
4359 return KVM_USER_MEM_SLOTS;
4360 case KVM_CAP_DIRTY_LOG_RING:
4361 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
4362 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4366 case KVM_CAP_BINARY_STATS_FD:
4367 case KVM_CAP_SYSTEM_EVENT_DATA:
4372 return kvm_vm_ioctl_check_extension(kvm, arg);
4375 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4379 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4382 /* the size should be power of 2 */
4383 if (!size || (size & (size - 1)))
4386 /* Should be bigger to keep the reserved entries, or a page */
4387 if (size < kvm_dirty_ring_get_rsvd_entries() *
4388 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4391 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4392 sizeof(struct kvm_dirty_gfn))
4395 /* We only allow it to set once */
4396 if (kvm->dirty_ring_size)
4399 mutex_lock(&kvm->lock);
4401 if (kvm->created_vcpus) {
4402 /* We don't allow to change this value after vcpu created */
4405 kvm->dirty_ring_size = size;
4409 mutex_unlock(&kvm->lock);
4413 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4416 struct kvm_vcpu *vcpu;
4419 if (!kvm->dirty_ring_size)
4422 mutex_lock(&kvm->slots_lock);
4424 kvm_for_each_vcpu(i, vcpu, kvm)
4425 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4427 mutex_unlock(&kvm->slots_lock);
4430 kvm_flush_remote_tlbs(kvm);
4435 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4436 struct kvm_enable_cap *cap)
4441 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4442 struct kvm_enable_cap *cap)
4445 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4446 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4447 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4449 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4450 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4452 if (cap->flags || (cap->args[0] & ~allowed_options))
4454 kvm->manual_dirty_log_protect = cap->args[0];
4458 case KVM_CAP_HALT_POLL: {
4459 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4462 kvm->max_halt_poll_ns = cap->args[0];
4465 case KVM_CAP_DIRTY_LOG_RING:
4466 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4468 return kvm_vm_ioctl_enable_cap(kvm, cap);
4472 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4473 size_t size, loff_t *offset)
4475 struct kvm *kvm = file->private_data;
4477 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4478 &kvm_vm_stats_desc[0], &kvm->stat,
4479 sizeof(kvm->stat), user_buffer, size, offset);
4482 static const struct file_operations kvm_vm_stats_fops = {
4483 .read = kvm_vm_stats_read,
4484 .llseek = noop_llseek,
4487 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4492 fd = get_unused_fd_flags(O_CLOEXEC);
4496 file = anon_inode_getfile("kvm-vm-stats",
4497 &kvm_vm_stats_fops, kvm, O_RDONLY);
4500 return PTR_ERR(file);
4502 file->f_mode |= FMODE_PREAD;
4503 fd_install(fd, file);
4508 static long kvm_vm_ioctl(struct file *filp,
4509 unsigned int ioctl, unsigned long arg)
4511 struct kvm *kvm = filp->private_data;
4512 void __user *argp = (void __user *)arg;
4515 if (kvm->mm != current->mm || kvm->vm_dead)
4518 case KVM_CREATE_VCPU:
4519 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4521 case KVM_ENABLE_CAP: {
4522 struct kvm_enable_cap cap;
4525 if (copy_from_user(&cap, argp, sizeof(cap)))
4527 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4530 case KVM_SET_USER_MEMORY_REGION: {
4531 struct kvm_userspace_memory_region kvm_userspace_mem;
4534 if (copy_from_user(&kvm_userspace_mem, argp,
4535 sizeof(kvm_userspace_mem)))
4538 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4541 case KVM_GET_DIRTY_LOG: {
4542 struct kvm_dirty_log log;
4545 if (copy_from_user(&log, argp, sizeof(log)))
4547 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4550 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4551 case KVM_CLEAR_DIRTY_LOG: {
4552 struct kvm_clear_dirty_log log;
4555 if (copy_from_user(&log, argp, sizeof(log)))
4557 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4561 #ifdef CONFIG_KVM_MMIO
4562 case KVM_REGISTER_COALESCED_MMIO: {
4563 struct kvm_coalesced_mmio_zone zone;
4566 if (copy_from_user(&zone, argp, sizeof(zone)))
4568 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4571 case KVM_UNREGISTER_COALESCED_MMIO: {
4572 struct kvm_coalesced_mmio_zone zone;
4575 if (copy_from_user(&zone, argp, sizeof(zone)))
4577 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4582 struct kvm_irqfd data;
4585 if (copy_from_user(&data, argp, sizeof(data)))
4587 r = kvm_irqfd(kvm, &data);
4590 case KVM_IOEVENTFD: {
4591 struct kvm_ioeventfd data;
4594 if (copy_from_user(&data, argp, sizeof(data)))
4596 r = kvm_ioeventfd(kvm, &data);
4599 #ifdef CONFIG_HAVE_KVM_MSI
4600 case KVM_SIGNAL_MSI: {
4604 if (copy_from_user(&msi, argp, sizeof(msi)))
4606 r = kvm_send_userspace_msi(kvm, &msi);
4610 #ifdef __KVM_HAVE_IRQ_LINE
4611 case KVM_IRQ_LINE_STATUS:
4612 case KVM_IRQ_LINE: {
4613 struct kvm_irq_level irq_event;
4616 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4619 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4620 ioctl == KVM_IRQ_LINE_STATUS);
4625 if (ioctl == KVM_IRQ_LINE_STATUS) {
4626 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4634 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4635 case KVM_SET_GSI_ROUTING: {
4636 struct kvm_irq_routing routing;
4637 struct kvm_irq_routing __user *urouting;
4638 struct kvm_irq_routing_entry *entries = NULL;
4641 if (copy_from_user(&routing, argp, sizeof(routing)))
4644 if (!kvm_arch_can_set_irq_routing(kvm))
4646 if (routing.nr > KVM_MAX_IRQ_ROUTES)
4652 entries = vmemdup_user(urouting->entries,
4653 array_size(sizeof(*entries),
4655 if (IS_ERR(entries)) {
4656 r = PTR_ERR(entries);
4660 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4665 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4666 case KVM_CREATE_DEVICE: {
4667 struct kvm_create_device cd;
4670 if (copy_from_user(&cd, argp, sizeof(cd)))
4673 r = kvm_ioctl_create_device(kvm, &cd);
4678 if (copy_to_user(argp, &cd, sizeof(cd)))
4684 case KVM_CHECK_EXTENSION:
4685 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4687 case KVM_RESET_DIRTY_RINGS:
4688 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4690 case KVM_GET_STATS_FD:
4691 r = kvm_vm_ioctl_get_stats_fd(kvm);
4694 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4700 #ifdef CONFIG_KVM_COMPAT
4701 struct compat_kvm_dirty_log {
4705 compat_uptr_t dirty_bitmap; /* one bit per page */
4710 struct compat_kvm_clear_dirty_log {
4715 compat_uptr_t dirty_bitmap; /* one bit per page */
4720 static long kvm_vm_compat_ioctl(struct file *filp,
4721 unsigned int ioctl, unsigned long arg)
4723 struct kvm *kvm = filp->private_data;
4726 if (kvm->mm != current->mm || kvm->vm_dead)
4729 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4730 case KVM_CLEAR_DIRTY_LOG: {
4731 struct compat_kvm_clear_dirty_log compat_log;
4732 struct kvm_clear_dirty_log log;
4734 if (copy_from_user(&compat_log, (void __user *)arg,
4735 sizeof(compat_log)))
4737 log.slot = compat_log.slot;
4738 log.num_pages = compat_log.num_pages;
4739 log.first_page = compat_log.first_page;
4740 log.padding2 = compat_log.padding2;
4741 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4743 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4747 case KVM_GET_DIRTY_LOG: {
4748 struct compat_kvm_dirty_log compat_log;
4749 struct kvm_dirty_log log;
4751 if (copy_from_user(&compat_log, (void __user *)arg,
4752 sizeof(compat_log)))
4754 log.slot = compat_log.slot;
4755 log.padding1 = compat_log.padding1;
4756 log.padding2 = compat_log.padding2;
4757 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4759 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4763 r = kvm_vm_ioctl(filp, ioctl, arg);
4769 static const struct file_operations kvm_vm_fops = {
4770 .release = kvm_vm_release,
4771 .unlocked_ioctl = kvm_vm_ioctl,
4772 .llseek = noop_llseek,
4773 KVM_COMPAT(kvm_vm_compat_ioctl),
4776 bool file_is_kvm(struct file *file)
4778 return file && file->f_op == &kvm_vm_fops;
4780 EXPORT_SYMBOL_GPL(file_is_kvm);
4782 static int kvm_dev_ioctl_create_vm(unsigned long type)
4788 kvm = kvm_create_vm(type);
4790 return PTR_ERR(kvm);
4791 #ifdef CONFIG_KVM_MMIO
4792 r = kvm_coalesced_mmio_init(kvm);
4796 r = get_unused_fd_flags(O_CLOEXEC);
4800 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4801 "kvm-%d", task_pid_nr(current));
4803 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4811 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4812 * already set, with ->release() being kvm_vm_release(). In error
4813 * cases it will be called by the final fput(file) and will take
4814 * care of doing kvm_put_kvm(kvm).
4816 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4821 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4823 fd_install(r, file);
4831 static long kvm_dev_ioctl(struct file *filp,
4832 unsigned int ioctl, unsigned long arg)
4837 case KVM_GET_API_VERSION:
4840 r = KVM_API_VERSION;
4843 r = kvm_dev_ioctl_create_vm(arg);
4845 case KVM_CHECK_EXTENSION:
4846 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4848 case KVM_GET_VCPU_MMAP_SIZE:
4851 r = PAGE_SIZE; /* struct kvm_run */
4853 r += PAGE_SIZE; /* pio data page */
4855 #ifdef CONFIG_KVM_MMIO
4856 r += PAGE_SIZE; /* coalesced mmio ring page */
4859 case KVM_TRACE_ENABLE:
4860 case KVM_TRACE_PAUSE:
4861 case KVM_TRACE_DISABLE:
4865 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4871 static struct file_operations kvm_chardev_ops = {
4872 .unlocked_ioctl = kvm_dev_ioctl,
4873 .llseek = noop_llseek,
4874 KVM_COMPAT(kvm_dev_ioctl),
4877 static struct miscdevice kvm_dev = {
4883 static void hardware_enable_nolock(void *junk)
4885 int cpu = raw_smp_processor_id();
4888 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4891 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4893 r = kvm_arch_hardware_enable();
4896 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4897 atomic_inc(&hardware_enable_failed);
4898 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4902 static int kvm_starting_cpu(unsigned int cpu)
4904 raw_spin_lock(&kvm_count_lock);
4905 if (kvm_usage_count)
4906 hardware_enable_nolock(NULL);
4907 raw_spin_unlock(&kvm_count_lock);
4911 static void hardware_disable_nolock(void *junk)
4913 int cpu = raw_smp_processor_id();
4915 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4917 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4918 kvm_arch_hardware_disable();
4921 static int kvm_dying_cpu(unsigned int cpu)
4923 raw_spin_lock(&kvm_count_lock);
4924 if (kvm_usage_count)
4925 hardware_disable_nolock(NULL);
4926 raw_spin_unlock(&kvm_count_lock);
4930 static void hardware_disable_all_nolock(void)
4932 BUG_ON(!kvm_usage_count);
4935 if (!kvm_usage_count)
4936 on_each_cpu(hardware_disable_nolock, NULL, 1);
4939 static void hardware_disable_all(void)
4941 raw_spin_lock(&kvm_count_lock);
4942 hardware_disable_all_nolock();
4943 raw_spin_unlock(&kvm_count_lock);
4946 static int hardware_enable_all(void)
4950 raw_spin_lock(&kvm_count_lock);
4953 if (kvm_usage_count == 1) {
4954 atomic_set(&hardware_enable_failed, 0);
4955 on_each_cpu(hardware_enable_nolock, NULL, 1);
4957 if (atomic_read(&hardware_enable_failed)) {
4958 hardware_disable_all_nolock();
4963 raw_spin_unlock(&kvm_count_lock);
4968 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4972 * Some (well, at least mine) BIOSes hang on reboot if
4975 * And Intel TXT required VMX off for all cpu when system shutdown.
4977 pr_info("kvm: exiting hardware virtualization\n");
4978 kvm_rebooting = true;
4979 on_each_cpu(hardware_disable_nolock, NULL, 1);
4983 static struct notifier_block kvm_reboot_notifier = {
4984 .notifier_call = kvm_reboot,
4988 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4992 for (i = 0; i < bus->dev_count; i++) {
4993 struct kvm_io_device *pos = bus->range[i].dev;
4995 kvm_iodevice_destructor(pos);
5000 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
5001 const struct kvm_io_range *r2)
5003 gpa_t addr1 = r1->addr;
5004 gpa_t addr2 = r2->addr;
5009 /* If r2->len == 0, match the exact address. If r2->len != 0,
5010 * accept any overlapping write. Any order is acceptable for
5011 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
5012 * we process all of them.
5025 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
5027 return kvm_io_bus_cmp(p1, p2);
5030 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
5031 gpa_t addr, int len)
5033 struct kvm_io_range *range, key;
5036 key = (struct kvm_io_range) {
5041 range = bsearch(&key, bus->range, bus->dev_count,
5042 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
5046 off = range - bus->range;
5048 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
5054 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5055 struct kvm_io_range *range, const void *val)
5059 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5063 while (idx < bus->dev_count &&
5064 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5065 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
5074 /* kvm_io_bus_write - called under kvm->slots_lock */
5075 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5076 int len, const void *val)
5078 struct kvm_io_bus *bus;
5079 struct kvm_io_range range;
5082 range = (struct kvm_io_range) {
5087 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5090 r = __kvm_io_bus_write(vcpu, bus, &range, val);
5091 return r < 0 ? r : 0;
5093 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
5095 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
5096 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
5097 gpa_t addr, int len, const void *val, long cookie)
5099 struct kvm_io_bus *bus;
5100 struct kvm_io_range range;
5102 range = (struct kvm_io_range) {
5107 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5111 /* First try the device referenced by cookie. */
5112 if ((cookie >= 0) && (cookie < bus->dev_count) &&
5113 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
5114 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
5119 * cookie contained garbage; fall back to search and return the
5120 * correct cookie value.
5122 return __kvm_io_bus_write(vcpu, bus, &range, val);
5125 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5126 struct kvm_io_range *range, void *val)
5130 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5134 while (idx < bus->dev_count &&
5135 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5136 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
5145 /* kvm_io_bus_read - called under kvm->slots_lock */
5146 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5149 struct kvm_io_bus *bus;
5150 struct kvm_io_range range;
5153 range = (struct kvm_io_range) {
5158 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5161 r = __kvm_io_bus_read(vcpu, bus, &range, val);
5162 return r < 0 ? r : 0;
5165 /* Caller must hold slots_lock. */
5166 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
5167 int len, struct kvm_io_device *dev)
5170 struct kvm_io_bus *new_bus, *bus;
5171 struct kvm_io_range range;
5173 bus = kvm_get_bus(kvm, bus_idx);
5177 /* exclude ioeventfd which is limited by maximum fd */
5178 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
5181 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
5182 GFP_KERNEL_ACCOUNT);
5186 range = (struct kvm_io_range) {
5192 for (i = 0; i < bus->dev_count; i++)
5193 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
5196 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
5197 new_bus->dev_count++;
5198 new_bus->range[i] = range;
5199 memcpy(new_bus->range + i + 1, bus->range + i,
5200 (bus->dev_count - i) * sizeof(struct kvm_io_range));
5201 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5202 synchronize_srcu_expedited(&kvm->srcu);
5208 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5209 struct kvm_io_device *dev)
5212 struct kvm_io_bus *new_bus, *bus;
5214 lockdep_assert_held(&kvm->slots_lock);
5216 bus = kvm_get_bus(kvm, bus_idx);
5220 for (i = 0; i < bus->dev_count; i++) {
5221 if (bus->range[i].dev == dev) {
5226 if (i == bus->dev_count)
5229 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
5230 GFP_KERNEL_ACCOUNT);
5232 memcpy(new_bus, bus, struct_size(bus, range, i));
5233 new_bus->dev_count--;
5234 memcpy(new_bus->range + i, bus->range + i + 1,
5235 flex_array_size(new_bus, range, new_bus->dev_count - i));
5238 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5239 synchronize_srcu_expedited(&kvm->srcu);
5241 /* Destroy the old bus _after_ installing the (null) bus. */
5243 pr_err("kvm: failed to shrink bus, removing it completely\n");
5244 for (j = 0; j < bus->dev_count; j++) {
5247 kvm_iodevice_destructor(bus->range[j].dev);
5252 return new_bus ? 0 : -ENOMEM;
5255 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5258 struct kvm_io_bus *bus;
5259 int dev_idx, srcu_idx;
5260 struct kvm_io_device *iodev = NULL;
5262 srcu_idx = srcu_read_lock(&kvm->srcu);
5264 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
5268 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5272 iodev = bus->range[dev_idx].dev;
5275 srcu_read_unlock(&kvm->srcu, srcu_idx);
5279 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5281 static int kvm_debugfs_open(struct inode *inode, struct file *file,
5282 int (*get)(void *, u64 *), int (*set)(void *, u64),
5285 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5289 * The debugfs files are a reference to the kvm struct which
5290 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
5291 * avoids the race between open and the removal of the debugfs directory.
5293 if (!kvm_get_kvm_safe(stat_data->kvm))
5296 if (simple_attr_open(inode, file, get,
5297 kvm_stats_debugfs_mode(stat_data->desc) & 0222
5300 kvm_put_kvm(stat_data->kvm);
5307 static int kvm_debugfs_release(struct inode *inode, struct file *file)
5309 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5312 simple_attr_release(inode, file);
5313 kvm_put_kvm(stat_data->kvm);
5318 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
5320 *val = *(u64 *)((void *)(&kvm->stat) + offset);
5325 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
5327 *(u64 *)((void *)(&kvm->stat) + offset) = 0;
5332 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
5335 struct kvm_vcpu *vcpu;
5339 kvm_for_each_vcpu(i, vcpu, kvm)
5340 *val += *(u64 *)((void *)(&vcpu->stat) + offset);
5345 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
5348 struct kvm_vcpu *vcpu;
5350 kvm_for_each_vcpu(i, vcpu, kvm)
5351 *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
5356 static int kvm_stat_data_get(void *data, u64 *val)
5359 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5361 switch (stat_data->kind) {
5363 r = kvm_get_stat_per_vm(stat_data->kvm,
5364 stat_data->desc->desc.offset, val);
5367 r = kvm_get_stat_per_vcpu(stat_data->kvm,
5368 stat_data->desc->desc.offset, val);
5375 static int kvm_stat_data_clear(void *data, u64 val)
5378 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5383 switch (stat_data->kind) {
5385 r = kvm_clear_stat_per_vm(stat_data->kvm,
5386 stat_data->desc->desc.offset);
5389 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
5390 stat_data->desc->desc.offset);
5397 static int kvm_stat_data_open(struct inode *inode, struct file *file)
5399 __simple_attr_check_format("%llu\n", 0ull);
5400 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5401 kvm_stat_data_clear, "%llu\n");
5404 static const struct file_operations stat_fops_per_vm = {
5405 .owner = THIS_MODULE,
5406 .open = kvm_stat_data_open,
5407 .release = kvm_debugfs_release,
5408 .read = simple_attr_read,
5409 .write = simple_attr_write,
5410 .llseek = no_llseek,
5413 static int vm_stat_get(void *_offset, u64 *val)
5415 unsigned offset = (long)_offset;
5420 mutex_lock(&kvm_lock);
5421 list_for_each_entry(kvm, &vm_list, vm_list) {
5422 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
5425 mutex_unlock(&kvm_lock);
5429 static int vm_stat_clear(void *_offset, u64 val)
5431 unsigned offset = (long)_offset;
5437 mutex_lock(&kvm_lock);
5438 list_for_each_entry(kvm, &vm_list, vm_list) {
5439 kvm_clear_stat_per_vm(kvm, offset);
5441 mutex_unlock(&kvm_lock);
5446 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
5447 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
5449 static int vcpu_stat_get(void *_offset, u64 *val)
5451 unsigned offset = (long)_offset;
5456 mutex_lock(&kvm_lock);
5457 list_for_each_entry(kvm, &vm_list, vm_list) {
5458 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
5461 mutex_unlock(&kvm_lock);
5465 static int vcpu_stat_clear(void *_offset, u64 val)
5467 unsigned offset = (long)_offset;
5473 mutex_lock(&kvm_lock);
5474 list_for_each_entry(kvm, &vm_list, vm_list) {
5475 kvm_clear_stat_per_vcpu(kvm, offset);
5477 mutex_unlock(&kvm_lock);
5482 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5484 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
5486 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5488 struct kobj_uevent_env *env;
5489 unsigned long long created, active;
5491 if (!kvm_dev.this_device || !kvm)
5494 mutex_lock(&kvm_lock);
5495 if (type == KVM_EVENT_CREATE_VM) {
5496 kvm_createvm_count++;
5498 } else if (type == KVM_EVENT_DESTROY_VM) {
5501 created = kvm_createvm_count;
5502 active = kvm_active_vms;
5503 mutex_unlock(&kvm_lock);
5505 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
5509 add_uevent_var(env, "CREATED=%llu", created);
5510 add_uevent_var(env, "COUNT=%llu", active);
5512 if (type == KVM_EVENT_CREATE_VM) {
5513 add_uevent_var(env, "EVENT=create");
5514 kvm->userspace_pid = task_pid_nr(current);
5515 } else if (type == KVM_EVENT_DESTROY_VM) {
5516 add_uevent_var(env, "EVENT=destroy");
5518 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5520 if (!IS_ERR(kvm->debugfs_dentry)) {
5521 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5524 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5526 add_uevent_var(env, "STATS_PATH=%s", tmp);
5530 /* no need for checks, since we are adding at most only 5 keys */
5531 env->envp[env->envp_idx++] = NULL;
5532 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5536 static void kvm_init_debug(void)
5538 const struct file_operations *fops;
5539 const struct _kvm_stats_desc *pdesc;
5542 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5544 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5545 pdesc = &kvm_vm_stats_desc[i];
5546 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5547 fops = &vm_stat_fops;
5549 fops = &vm_stat_readonly_fops;
5550 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5552 (void *)(long)pdesc->desc.offset, fops);
5555 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5556 pdesc = &kvm_vcpu_stats_desc[i];
5557 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5558 fops = &vcpu_stat_fops;
5560 fops = &vcpu_stat_readonly_fops;
5561 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5563 (void *)(long)pdesc->desc.offset, fops);
5567 static int kvm_suspend(void)
5569 if (kvm_usage_count)
5570 hardware_disable_nolock(NULL);
5574 static void kvm_resume(void)
5576 if (kvm_usage_count) {
5577 lockdep_assert_not_held(&kvm_count_lock);
5578 hardware_enable_nolock(NULL);
5582 static struct syscore_ops kvm_syscore_ops = {
5583 .suspend = kvm_suspend,
5584 .resume = kvm_resume,
5588 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5590 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5593 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5595 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5597 WRITE_ONCE(vcpu->preempted, false);
5598 WRITE_ONCE(vcpu->ready, false);
5600 __this_cpu_write(kvm_running_vcpu, vcpu);
5601 kvm_arch_sched_in(vcpu, cpu);
5602 kvm_arch_vcpu_load(vcpu, cpu);
5605 static void kvm_sched_out(struct preempt_notifier *pn,
5606 struct task_struct *next)
5608 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5610 if (current->on_rq) {
5611 WRITE_ONCE(vcpu->preempted, true);
5612 WRITE_ONCE(vcpu->ready, true);
5614 kvm_arch_vcpu_put(vcpu);
5615 __this_cpu_write(kvm_running_vcpu, NULL);
5619 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5621 * We can disable preemption locally around accessing the per-CPU variable,
5622 * and use the resolved vcpu pointer after enabling preemption again,
5623 * because even if the current thread is migrated to another CPU, reading
5624 * the per-CPU value later will give us the same value as we update the
5625 * per-CPU variable in the preempt notifier handlers.
5627 struct kvm_vcpu *kvm_get_running_vcpu(void)
5629 struct kvm_vcpu *vcpu;
5632 vcpu = __this_cpu_read(kvm_running_vcpu);
5637 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5640 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5642 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5644 return &kvm_running_vcpu;
5647 #ifdef CONFIG_GUEST_PERF_EVENTS
5648 static unsigned int kvm_guest_state(void)
5650 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5653 if (!kvm_arch_pmi_in_guest(vcpu))
5656 state = PERF_GUEST_ACTIVE;
5657 if (!kvm_arch_vcpu_in_kernel(vcpu))
5658 state |= PERF_GUEST_USER;
5663 static unsigned long kvm_guest_get_ip(void)
5665 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5667 /* Retrieving the IP must be guarded by a call to kvm_guest_state(). */
5668 if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu)))
5671 return kvm_arch_vcpu_get_ip(vcpu);
5674 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5675 .state = kvm_guest_state,
5676 .get_ip = kvm_guest_get_ip,
5677 .handle_intel_pt_intr = NULL,
5680 void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void))
5682 kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler;
5683 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5685 void kvm_unregister_perf_callbacks(void)
5687 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5691 struct kvm_cpu_compat_check {
5696 static void check_processor_compat(void *data)
5698 struct kvm_cpu_compat_check *c = data;
5700 *c->ret = kvm_arch_check_processor_compat(c->opaque);
5703 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5704 struct module *module)
5706 struct kvm_cpu_compat_check c;
5710 r = kvm_arch_init(opaque);
5715 * kvm_arch_init makes sure there's at most one caller
5716 * for architectures that support multiple implementations,
5717 * like intel and amd on x86.
5718 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5719 * conflicts in case kvm is already setup for another implementation.
5721 r = kvm_irqfd_init();
5725 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5730 r = kvm_arch_hardware_setup(opaque);
5736 for_each_online_cpu(cpu) {
5737 smp_call_function_single(cpu, check_processor_compat, &c, 1);
5742 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5743 kvm_starting_cpu, kvm_dying_cpu);
5746 register_reboot_notifier(&kvm_reboot_notifier);
5748 /* A kmem cache lets us meet the alignment requirements of fx_save. */
5750 vcpu_align = __alignof__(struct kvm_vcpu);
5752 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5754 offsetof(struct kvm_vcpu, arch),
5755 offsetofend(struct kvm_vcpu, stats_id)
5756 - offsetof(struct kvm_vcpu, arch),
5758 if (!kvm_vcpu_cache) {
5763 for_each_possible_cpu(cpu) {
5764 if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu),
5765 GFP_KERNEL, cpu_to_node(cpu))) {
5771 r = kvm_async_pf_init();
5775 kvm_chardev_ops.owner = module;
5777 r = misc_register(&kvm_dev);
5779 pr_err("kvm: misc device register failed\n");
5783 register_syscore_ops(&kvm_syscore_ops);
5785 kvm_preempt_ops.sched_in = kvm_sched_in;
5786 kvm_preempt_ops.sched_out = kvm_sched_out;
5790 r = kvm_vfio_ops_init();
5796 kvm_async_pf_deinit();
5798 for_each_possible_cpu(cpu)
5799 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5801 kmem_cache_destroy(kvm_vcpu_cache);
5803 unregister_reboot_notifier(&kvm_reboot_notifier);
5804 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5806 kvm_arch_hardware_unsetup();
5808 free_cpumask_var(cpus_hardware_enabled);
5816 EXPORT_SYMBOL_GPL(kvm_init);
5822 debugfs_remove_recursive(kvm_debugfs_dir);
5823 misc_deregister(&kvm_dev);
5824 for_each_possible_cpu(cpu)
5825 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5826 kmem_cache_destroy(kvm_vcpu_cache);
5827 kvm_async_pf_deinit();
5828 unregister_syscore_ops(&kvm_syscore_ops);
5829 unregister_reboot_notifier(&kvm_reboot_notifier);
5830 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5831 on_each_cpu(hardware_disable_nolock, NULL, 1);
5832 kvm_arch_hardware_unsetup();
5835 free_cpumask_var(cpus_hardware_enabled);
5836 kvm_vfio_ops_exit();
5838 EXPORT_SYMBOL_GPL(kvm_exit);
5840 struct kvm_vm_worker_thread_context {
5842 struct task_struct *parent;
5843 struct completion init_done;
5844 kvm_vm_thread_fn_t thread_fn;
5849 static int kvm_vm_worker_thread(void *context)
5852 * The init_context is allocated on the stack of the parent thread, so
5853 * we have to locally copy anything that is needed beyond initialization
5855 struct kvm_vm_worker_thread_context *init_context = context;
5856 struct task_struct *parent;
5857 struct kvm *kvm = init_context->kvm;
5858 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5859 uintptr_t data = init_context->data;
5862 err = kthread_park(current);
5863 /* kthread_park(current) is never supposed to return an error */
5868 err = cgroup_attach_task_all(init_context->parent, current);
5870 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5875 set_user_nice(current, task_nice(init_context->parent));
5878 init_context->err = err;
5879 complete(&init_context->init_done);
5880 init_context = NULL;
5885 /* Wait to be woken up by the spawner before proceeding. */
5888 if (!kthread_should_stop())
5889 err = thread_fn(kvm, data);
5893 * Move kthread back to its original cgroup to prevent it lingering in
5894 * the cgroup of the VM process, after the latter finishes its
5897 * kthread_stop() waits on the 'exited' completion condition which is
5898 * set in exit_mm(), via mm_release(), in do_exit(). However, the
5899 * kthread is removed from the cgroup in the cgroup_exit() which is
5900 * called after the exit_mm(). This causes the kthread_stop() to return
5901 * before the kthread actually quits the cgroup.
5904 parent = rcu_dereference(current->real_parent);
5905 get_task_struct(parent);
5907 cgroup_attach_task_all(parent, current);
5908 put_task_struct(parent);
5913 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5914 uintptr_t data, const char *name,
5915 struct task_struct **thread_ptr)
5917 struct kvm_vm_worker_thread_context init_context = {};
5918 struct task_struct *thread;
5921 init_context.kvm = kvm;
5922 init_context.parent = current;
5923 init_context.thread_fn = thread_fn;
5924 init_context.data = data;
5925 init_completion(&init_context.init_done);
5927 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5928 "%s-%d", name, task_pid_nr(current));
5930 return PTR_ERR(thread);
5932 /* kthread_run is never supposed to return NULL */
5933 WARN_ON(thread == NULL);
5935 wait_for_completion(&init_context.init_done);
5937 if (!init_context.err)
5938 *thread_ptr = thread;
5940 return init_context.err;