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, GFP_KERNEL_ACCOUNT);
391 return mc->nobjs >= min ? 0 : -ENOMEM;
392 mc->objects[mc->nobjs++] = obj;
397 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
402 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
406 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
408 free_page((unsigned long)mc->objects[--mc->nobjs]);
412 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
416 if (WARN_ON(!mc->nobjs))
417 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
419 p = mc->objects[--mc->nobjs];
425 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
427 mutex_init(&vcpu->mutex);
432 #ifndef __KVM_HAVE_ARCH_WQP
433 rcuwait_init(&vcpu->wait);
435 kvm_async_pf_vcpu_init(vcpu);
437 kvm_vcpu_set_in_spin_loop(vcpu, false);
438 kvm_vcpu_set_dy_eligible(vcpu, false);
439 vcpu->preempted = false;
441 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
442 vcpu->last_used_slot = NULL;
445 static void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
447 kvm_arch_vcpu_destroy(vcpu);
448 kvm_dirty_ring_free(&vcpu->dirty_ring);
451 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
452 * the vcpu->pid pointer, and at destruction time all file descriptors
455 put_pid(rcu_dereference_protected(vcpu->pid, 1));
457 free_page((unsigned long)vcpu->run);
458 kmem_cache_free(kvm_vcpu_cache, vcpu);
461 void kvm_destroy_vcpus(struct kvm *kvm)
464 struct kvm_vcpu *vcpu;
466 kvm_for_each_vcpu(i, vcpu, kvm) {
467 kvm_vcpu_destroy(vcpu);
468 xa_erase(&kvm->vcpu_array, i);
471 atomic_set(&kvm->online_vcpus, 0);
473 EXPORT_SYMBOL_GPL(kvm_destroy_vcpus);
475 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
476 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
478 return container_of(mn, struct kvm, mmu_notifier);
481 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
482 struct mm_struct *mm,
483 unsigned long start, unsigned long end)
485 struct kvm *kvm = mmu_notifier_to_kvm(mn);
488 idx = srcu_read_lock(&kvm->srcu);
489 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
490 srcu_read_unlock(&kvm->srcu, idx);
493 typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
495 typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
498 typedef void (*on_unlock_fn_t)(struct kvm *kvm);
500 struct kvm_hva_range {
504 hva_handler_t handler;
505 on_lock_fn_t on_lock;
506 on_unlock_fn_t on_unlock;
512 * Use a dedicated stub instead of NULL to indicate that there is no callback
513 * function/handler. The compiler technically can't guarantee that a real
514 * function will have a non-zero address, and so it will generate code to
515 * check for !NULL, whereas comparing against a stub will be elided at compile
516 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
518 static void kvm_null_fn(void)
522 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
524 /* Iterate over each memslot intersecting [start, last] (inclusive) range */
525 #define kvm_for_each_memslot_in_hva_range(node, slots, start, last) \
526 for (node = interval_tree_iter_first(&slots->hva_tree, start, last); \
528 node = interval_tree_iter_next(node, start, last)) \
530 static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
531 const struct kvm_hva_range *range)
533 bool ret = false, locked = false;
534 struct kvm_gfn_range gfn_range;
535 struct kvm_memory_slot *slot;
536 struct kvm_memslots *slots;
539 if (WARN_ON_ONCE(range->end <= range->start))
542 /* A null handler is allowed if and only if on_lock() is provided. */
543 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
544 IS_KVM_NULL_FN(range->handler)))
547 idx = srcu_read_lock(&kvm->srcu);
549 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
550 struct interval_tree_node *node;
552 slots = __kvm_memslots(kvm, i);
553 kvm_for_each_memslot_in_hva_range(node, slots,
554 range->start, range->end - 1) {
555 unsigned long hva_start, hva_end;
557 slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]);
558 hva_start = max(range->start, slot->userspace_addr);
559 hva_end = min(range->end, slot->userspace_addr +
560 (slot->npages << PAGE_SHIFT));
563 * To optimize for the likely case where the address
564 * range is covered by zero or one memslots, don't
565 * bother making these conditional (to avoid writes on
566 * the second or later invocation of the handler).
568 gfn_range.pte = range->pte;
569 gfn_range.may_block = range->may_block;
572 * {gfn(page) | page intersects with [hva_start, hva_end)} =
573 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
575 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
576 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
577 gfn_range.slot = slot;
582 if (!IS_KVM_NULL_FN(range->on_lock))
583 range->on_lock(kvm, range->start, range->end);
584 if (IS_KVM_NULL_FN(range->handler))
587 ret |= range->handler(kvm, &gfn_range);
591 if (range->flush_on_ret && ret)
592 kvm_flush_remote_tlbs(kvm);
596 if (!IS_KVM_NULL_FN(range->on_unlock))
597 range->on_unlock(kvm);
600 srcu_read_unlock(&kvm->srcu, idx);
602 /* The notifiers are averse to booleans. :-( */
606 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
610 hva_handler_t handler)
612 struct kvm *kvm = mmu_notifier_to_kvm(mn);
613 const struct kvm_hva_range range = {
618 .on_lock = (void *)kvm_null_fn,
619 .on_unlock = (void *)kvm_null_fn,
620 .flush_on_ret = true,
624 return __kvm_handle_hva_range(kvm, &range);
627 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
630 hva_handler_t handler)
632 struct kvm *kvm = mmu_notifier_to_kvm(mn);
633 const struct kvm_hva_range range = {
638 .on_lock = (void *)kvm_null_fn,
639 .on_unlock = (void *)kvm_null_fn,
640 .flush_on_ret = false,
644 return __kvm_handle_hva_range(kvm, &range);
646 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
647 struct mm_struct *mm,
648 unsigned long address,
651 struct kvm *kvm = mmu_notifier_to_kvm(mn);
653 trace_kvm_set_spte_hva(address);
656 * .change_pte() must be surrounded by .invalidate_range_{start,end}().
657 * If mmu_notifier_count is zero, then no in-progress invalidations,
658 * including this one, found a relevant memslot at start(); rechecking
659 * memslots here is unnecessary. Note, a false positive (count elevated
660 * by a different invalidation) is sub-optimal but functionally ok.
662 WARN_ON_ONCE(!READ_ONCE(kvm->mn_active_invalidate_count));
663 if (!READ_ONCE(kvm->mmu_notifier_count))
666 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
669 void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
673 * The count increase must become visible at unlock time as no
674 * spte can be established without taking the mmu_lock and
675 * count is also read inside the mmu_lock critical section.
677 kvm->mmu_notifier_count++;
678 if (likely(kvm->mmu_notifier_count == 1)) {
679 kvm->mmu_notifier_range_start = start;
680 kvm->mmu_notifier_range_end = end;
683 * Fully tracking multiple concurrent ranges has diminishing
684 * returns. Keep things simple and just find the minimal range
685 * which includes the current and new ranges. As there won't be
686 * enough information to subtract a range after its invalidate
687 * completes, any ranges invalidated concurrently will
688 * accumulate and persist until all outstanding invalidates
691 kvm->mmu_notifier_range_start =
692 min(kvm->mmu_notifier_range_start, start);
693 kvm->mmu_notifier_range_end =
694 max(kvm->mmu_notifier_range_end, end);
698 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
699 const struct mmu_notifier_range *range)
701 struct kvm *kvm = mmu_notifier_to_kvm(mn);
702 const struct kvm_hva_range hva_range = {
703 .start = range->start,
706 .handler = kvm_unmap_gfn_range,
707 .on_lock = kvm_inc_notifier_count,
708 .on_unlock = kvm_arch_guest_memory_reclaimed,
709 .flush_on_ret = true,
710 .may_block = mmu_notifier_range_blockable(range),
713 trace_kvm_unmap_hva_range(range->start, range->end);
716 * Prevent memslot modification between range_start() and range_end()
717 * so that conditionally locking provides the same result in both
718 * functions. Without that guarantee, the mmu_notifier_count
719 * adjustments will be imbalanced.
721 * Pairs with the decrement in range_end().
723 spin_lock(&kvm->mn_invalidate_lock);
724 kvm->mn_active_invalidate_count++;
725 spin_unlock(&kvm->mn_invalidate_lock);
727 gfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end,
728 hva_range.may_block);
730 __kvm_handle_hva_range(kvm, &hva_range);
735 void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
739 * This sequence increase will notify the kvm page fault that
740 * the page that is going to be mapped in the spte could have
743 kvm->mmu_notifier_seq++;
746 * The above sequence increase must be visible before the
747 * below count decrease, which is ensured by the smp_wmb above
748 * in conjunction with the smp_rmb in mmu_notifier_retry().
750 kvm->mmu_notifier_count--;
753 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
754 const struct mmu_notifier_range *range)
756 struct kvm *kvm = mmu_notifier_to_kvm(mn);
757 const struct kvm_hva_range hva_range = {
758 .start = range->start,
761 .handler = (void *)kvm_null_fn,
762 .on_lock = kvm_dec_notifier_count,
763 .on_unlock = (void *)kvm_null_fn,
764 .flush_on_ret = false,
765 .may_block = mmu_notifier_range_blockable(range),
769 __kvm_handle_hva_range(kvm, &hva_range);
771 /* Pairs with the increment in range_start(). */
772 spin_lock(&kvm->mn_invalidate_lock);
773 wake = (--kvm->mn_active_invalidate_count == 0);
774 spin_unlock(&kvm->mn_invalidate_lock);
777 * There can only be one waiter, since the wait happens under
781 rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
783 BUG_ON(kvm->mmu_notifier_count < 0);
786 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
787 struct mm_struct *mm,
791 trace_kvm_age_hva(start, end);
793 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
796 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
797 struct mm_struct *mm,
801 trace_kvm_age_hva(start, end);
804 * Even though we do not flush TLB, this will still adversely
805 * affect performance on pre-Haswell Intel EPT, where there is
806 * no EPT Access Bit to clear so that we have to tear down EPT
807 * tables instead. If we find this unacceptable, we can always
808 * add a parameter to kvm_age_hva so that it effectively doesn't
809 * do anything on clear_young.
811 * Also note that currently we never issue secondary TLB flushes
812 * from clear_young, leaving this job up to the regular system
813 * cadence. If we find this inaccurate, we might come up with a
814 * more sophisticated heuristic later.
816 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
819 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
820 struct mm_struct *mm,
821 unsigned long address)
823 trace_kvm_test_age_hva(address);
825 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
829 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
830 struct mm_struct *mm)
832 struct kvm *kvm = mmu_notifier_to_kvm(mn);
835 idx = srcu_read_lock(&kvm->srcu);
836 kvm_flush_shadow_all(kvm);
837 srcu_read_unlock(&kvm->srcu, idx);
840 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
841 .invalidate_range = kvm_mmu_notifier_invalidate_range,
842 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
843 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
844 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
845 .clear_young = kvm_mmu_notifier_clear_young,
846 .test_young = kvm_mmu_notifier_test_young,
847 .change_pte = kvm_mmu_notifier_change_pte,
848 .release = kvm_mmu_notifier_release,
851 static int kvm_init_mmu_notifier(struct kvm *kvm)
853 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
854 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
857 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
859 static int kvm_init_mmu_notifier(struct kvm *kvm)
864 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
866 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
867 static int kvm_pm_notifier_call(struct notifier_block *bl,
871 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
873 return kvm_arch_pm_notifier(kvm, state);
876 static void kvm_init_pm_notifier(struct kvm *kvm)
878 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
879 /* Suspend KVM before we suspend ftrace, RCU, etc. */
880 kvm->pm_notifier.priority = INT_MAX;
881 register_pm_notifier(&kvm->pm_notifier);
884 static void kvm_destroy_pm_notifier(struct kvm *kvm)
886 unregister_pm_notifier(&kvm->pm_notifier);
888 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
889 static void kvm_init_pm_notifier(struct kvm *kvm)
893 static void kvm_destroy_pm_notifier(struct kvm *kvm)
896 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
898 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
900 if (!memslot->dirty_bitmap)
903 kvfree(memslot->dirty_bitmap);
904 memslot->dirty_bitmap = NULL;
907 /* This does not remove the slot from struct kvm_memslots data structures */
908 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
910 kvm_destroy_dirty_bitmap(slot);
912 kvm_arch_free_memslot(kvm, slot);
917 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
919 struct hlist_node *idnode;
920 struct kvm_memory_slot *memslot;
924 * The same memslot objects live in both active and inactive sets,
925 * arbitrarily free using index '1' so the second invocation of this
926 * function isn't operating over a structure with dangling pointers
927 * (even though this function isn't actually touching them).
929 if (!slots->node_idx)
932 hash_for_each_safe(slots->id_hash, bkt, idnode, memslot, id_node[1])
933 kvm_free_memslot(kvm, memslot);
936 static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
938 switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
939 case KVM_STATS_TYPE_INSTANT:
941 case KVM_STATS_TYPE_CUMULATIVE:
942 case KVM_STATS_TYPE_PEAK:
949 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
952 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
953 kvm_vcpu_stats_header.num_desc;
955 if (IS_ERR(kvm->debugfs_dentry))
958 debugfs_remove_recursive(kvm->debugfs_dentry);
960 if (kvm->debugfs_stat_data) {
961 for (i = 0; i < kvm_debugfs_num_entries; i++)
962 kfree(kvm->debugfs_stat_data[i]);
963 kfree(kvm->debugfs_stat_data);
967 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
969 static DEFINE_MUTEX(kvm_debugfs_lock);
971 char dir_name[ITOA_MAX_LEN * 2];
972 struct kvm_stat_data *stat_data;
973 const struct _kvm_stats_desc *pdesc;
975 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
976 kvm_vcpu_stats_header.num_desc;
978 if (!debugfs_initialized())
981 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
982 mutex_lock(&kvm_debugfs_lock);
983 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
985 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
987 mutex_unlock(&kvm_debugfs_lock);
990 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
991 mutex_unlock(&kvm_debugfs_lock);
995 kvm->debugfs_dentry = dent;
996 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
997 sizeof(*kvm->debugfs_stat_data),
999 if (!kvm->debugfs_stat_data)
1002 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
1003 pdesc = &kvm_vm_stats_desc[i];
1004 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1008 stat_data->kvm = kvm;
1009 stat_data->desc = pdesc;
1010 stat_data->kind = KVM_STAT_VM;
1011 kvm->debugfs_stat_data[i] = stat_data;
1012 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1013 kvm->debugfs_dentry, stat_data,
1017 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
1018 pdesc = &kvm_vcpu_stats_desc[i];
1019 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1023 stat_data->kvm = kvm;
1024 stat_data->desc = pdesc;
1025 stat_data->kind = KVM_STAT_VCPU;
1026 kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
1027 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1028 kvm->debugfs_dentry, stat_data,
1032 ret = kvm_arch_create_vm_debugfs(kvm);
1034 kvm_destroy_vm_debugfs(kvm);
1042 * Called after the VM is otherwise initialized, but just before adding it to
1045 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
1051 * Called just after removing the VM from the vm_list, but before doing any
1052 * other destruction.
1054 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
1059 * Called after per-vm debugfs created. When called kvm->debugfs_dentry should
1060 * be setup already, so we can create arch-specific debugfs entries under it.
1061 * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1062 * a per-arch destroy interface is not needed.
1064 int __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1069 static struct kvm *kvm_create_vm(unsigned long type)
1071 struct kvm *kvm = kvm_arch_alloc_vm();
1072 struct kvm_memslots *slots;
1077 return ERR_PTR(-ENOMEM);
1079 KVM_MMU_LOCK_INIT(kvm);
1080 mmgrab(current->mm);
1081 kvm->mm = current->mm;
1082 kvm_eventfd_init(kvm);
1083 mutex_init(&kvm->lock);
1084 mutex_init(&kvm->irq_lock);
1085 mutex_init(&kvm->slots_lock);
1086 mutex_init(&kvm->slots_arch_lock);
1087 spin_lock_init(&kvm->mn_invalidate_lock);
1088 rcuwait_init(&kvm->mn_memslots_update_rcuwait);
1089 xa_init(&kvm->vcpu_array);
1091 INIT_LIST_HEAD(&kvm->gpc_list);
1092 spin_lock_init(&kvm->gpc_lock);
1094 INIT_LIST_HEAD(&kvm->devices);
1095 kvm->max_vcpus = KVM_MAX_VCPUS;
1097 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1100 * Force subsequent debugfs file creations to fail if the VM directory
1101 * is not created (by kvm_create_vm_debugfs()).
1103 kvm->debugfs_dentry = ERR_PTR(-ENOENT);
1105 if (init_srcu_struct(&kvm->srcu))
1106 goto out_err_no_srcu;
1107 if (init_srcu_struct(&kvm->irq_srcu))
1108 goto out_err_no_irq_srcu;
1110 refcount_set(&kvm->users_count, 1);
1111 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1112 for (j = 0; j < 2; j++) {
1113 slots = &kvm->__memslots[i][j];
1115 atomic_long_set(&slots->last_used_slot, (unsigned long)NULL);
1116 slots->hva_tree = RB_ROOT_CACHED;
1117 slots->gfn_tree = RB_ROOT;
1118 hash_init(slots->id_hash);
1119 slots->node_idx = j;
1121 /* Generations must be different for each address space. */
1122 slots->generation = i;
1125 rcu_assign_pointer(kvm->memslots[i], &kvm->__memslots[i][0]);
1128 for (i = 0; i < KVM_NR_BUSES; i++) {
1129 rcu_assign_pointer(kvm->buses[i],
1130 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
1132 goto out_err_no_arch_destroy_vm;
1135 kvm->max_halt_poll_ns = halt_poll_ns;
1137 r = kvm_arch_init_vm(kvm, type);
1139 goto out_err_no_arch_destroy_vm;
1141 r = hardware_enable_all();
1143 goto out_err_no_disable;
1145 #ifdef CONFIG_HAVE_KVM_IRQFD
1146 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
1149 r = kvm_init_mmu_notifier(kvm);
1151 goto out_err_no_mmu_notifier;
1153 r = kvm_arch_post_init_vm(kvm);
1157 mutex_lock(&kvm_lock);
1158 list_add(&kvm->vm_list, &vm_list);
1159 mutex_unlock(&kvm_lock);
1161 preempt_notifier_inc();
1162 kvm_init_pm_notifier(kvm);
1165 * When the fd passed to this ioctl() is opened it pins the module,
1166 * but try_module_get() also prevents getting a reference if the module
1167 * is in MODULE_STATE_GOING (e.g. if someone ran "rmmod --wait").
1169 if (!try_module_get(kvm_chardev_ops.owner)) {
1177 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1178 if (kvm->mmu_notifier.ops)
1179 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1181 out_err_no_mmu_notifier:
1182 hardware_disable_all();
1184 kvm_arch_destroy_vm(kvm);
1185 out_err_no_arch_destroy_vm:
1186 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
1187 for (i = 0; i < KVM_NR_BUSES; i++)
1188 kfree(kvm_get_bus(kvm, i));
1189 cleanup_srcu_struct(&kvm->irq_srcu);
1190 out_err_no_irq_srcu:
1191 cleanup_srcu_struct(&kvm->srcu);
1193 kvm_arch_free_vm(kvm);
1194 mmdrop(current->mm);
1198 static void kvm_destroy_devices(struct kvm *kvm)
1200 struct kvm_device *dev, *tmp;
1203 * We do not need to take the kvm->lock here, because nobody else
1204 * has a reference to the struct kvm at this point and therefore
1205 * cannot access the devices list anyhow.
1207 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1208 list_del(&dev->vm_node);
1209 dev->ops->destroy(dev);
1213 static void kvm_destroy_vm(struct kvm *kvm)
1216 struct mm_struct *mm = kvm->mm;
1218 kvm_destroy_pm_notifier(kvm);
1219 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1220 kvm_destroy_vm_debugfs(kvm);
1221 kvm_arch_sync_events(kvm);
1222 mutex_lock(&kvm_lock);
1223 list_del(&kvm->vm_list);
1224 mutex_unlock(&kvm_lock);
1225 kvm_arch_pre_destroy_vm(kvm);
1227 kvm_free_irq_routing(kvm);
1228 for (i = 0; i < KVM_NR_BUSES; i++) {
1229 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1232 kvm_io_bus_destroy(bus);
1233 kvm->buses[i] = NULL;
1235 kvm_coalesced_mmio_free(kvm);
1236 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1237 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1239 * At this point, pending calls to invalidate_range_start()
1240 * have completed but no more MMU notifiers will run, so
1241 * mn_active_invalidate_count may remain unbalanced.
1242 * No threads can be waiting in install_new_memslots as the
1243 * last reference on KVM has been dropped, but freeing
1244 * memslots would deadlock without this manual intervention.
1246 WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1247 kvm->mn_active_invalidate_count = 0;
1249 kvm_flush_shadow_all(kvm);
1251 kvm_arch_destroy_vm(kvm);
1252 kvm_destroy_devices(kvm);
1253 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1254 kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
1255 kvm_free_memslots(kvm, &kvm->__memslots[i][1]);
1257 cleanup_srcu_struct(&kvm->irq_srcu);
1258 cleanup_srcu_struct(&kvm->srcu);
1259 kvm_arch_free_vm(kvm);
1260 preempt_notifier_dec();
1261 hardware_disable_all();
1263 module_put(kvm_chardev_ops.owner);
1266 void kvm_get_kvm(struct kvm *kvm)
1268 refcount_inc(&kvm->users_count);
1270 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1273 * Make sure the vm is not during destruction, which is a safe version of
1274 * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise.
1276 bool kvm_get_kvm_safe(struct kvm *kvm)
1278 return refcount_inc_not_zero(&kvm->users_count);
1280 EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1282 void kvm_put_kvm(struct kvm *kvm)
1284 if (refcount_dec_and_test(&kvm->users_count))
1285 kvm_destroy_vm(kvm);
1287 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1290 * Used to put a reference that was taken on behalf of an object associated
1291 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1292 * of the new file descriptor fails and the reference cannot be transferred to
1293 * its final owner. In such cases, the caller is still actively using @kvm and
1294 * will fail miserably if the refcount unexpectedly hits zero.
1296 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1298 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1300 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1302 static int kvm_vm_release(struct inode *inode, struct file *filp)
1304 struct kvm *kvm = filp->private_data;
1306 kvm_irqfd_release(kvm);
1313 * Allocation size is twice as large as the actual dirty bitmap size.
1314 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1316 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1318 unsigned long dirty_bytes = kvm_dirty_bitmap_bytes(memslot);
1320 memslot->dirty_bitmap = __vcalloc(2, dirty_bytes, GFP_KERNEL_ACCOUNT);
1321 if (!memslot->dirty_bitmap)
1327 static struct kvm_memslots *kvm_get_inactive_memslots(struct kvm *kvm, int as_id)
1329 struct kvm_memslots *active = __kvm_memslots(kvm, as_id);
1330 int node_idx_inactive = active->node_idx ^ 1;
1332 return &kvm->__memslots[as_id][node_idx_inactive];
1336 * Helper to get the address space ID when one of memslot pointers may be NULL.
1337 * This also serves as a sanity that at least one of the pointers is non-NULL,
1338 * and that their address space IDs don't diverge.
1340 static int kvm_memslots_get_as_id(struct kvm_memory_slot *a,
1341 struct kvm_memory_slot *b)
1343 if (WARN_ON_ONCE(!a && !b))
1351 WARN_ON_ONCE(a->as_id != b->as_id);
1355 static void kvm_insert_gfn_node(struct kvm_memslots *slots,
1356 struct kvm_memory_slot *slot)
1358 struct rb_root *gfn_tree = &slots->gfn_tree;
1359 struct rb_node **node, *parent;
1360 int idx = slots->node_idx;
1363 for (node = &gfn_tree->rb_node; *node; ) {
1364 struct kvm_memory_slot *tmp;
1366 tmp = container_of(*node, struct kvm_memory_slot, gfn_node[idx]);
1368 if (slot->base_gfn < tmp->base_gfn)
1369 node = &(*node)->rb_left;
1370 else if (slot->base_gfn > tmp->base_gfn)
1371 node = &(*node)->rb_right;
1376 rb_link_node(&slot->gfn_node[idx], parent, node);
1377 rb_insert_color(&slot->gfn_node[idx], gfn_tree);
1380 static void kvm_erase_gfn_node(struct kvm_memslots *slots,
1381 struct kvm_memory_slot *slot)
1383 rb_erase(&slot->gfn_node[slots->node_idx], &slots->gfn_tree);
1386 static void kvm_replace_gfn_node(struct kvm_memslots *slots,
1387 struct kvm_memory_slot *old,
1388 struct kvm_memory_slot *new)
1390 int idx = slots->node_idx;
1392 WARN_ON_ONCE(old->base_gfn != new->base_gfn);
1394 rb_replace_node(&old->gfn_node[idx], &new->gfn_node[idx],
1399 * Replace @old with @new in the inactive memslots.
1401 * With NULL @old this simply adds @new.
1402 * With NULL @new this simply removes @old.
1404 * If @new is non-NULL its hva_node[slots_idx] range has to be set
1407 static void kvm_replace_memslot(struct kvm *kvm,
1408 struct kvm_memory_slot *old,
1409 struct kvm_memory_slot *new)
1411 int as_id = kvm_memslots_get_as_id(old, new);
1412 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1413 int idx = slots->node_idx;
1416 hash_del(&old->id_node[idx]);
1417 interval_tree_remove(&old->hva_node[idx], &slots->hva_tree);
1419 if ((long)old == atomic_long_read(&slots->last_used_slot))
1420 atomic_long_set(&slots->last_used_slot, (long)new);
1423 kvm_erase_gfn_node(slots, old);
1429 * Initialize @new's hva range. Do this even when replacing an @old
1430 * slot, kvm_copy_memslot() deliberately does not touch node data.
1432 new->hva_node[idx].start = new->userspace_addr;
1433 new->hva_node[idx].last = new->userspace_addr +
1434 (new->npages << PAGE_SHIFT) - 1;
1437 * (Re)Add the new memslot. There is no O(1) interval_tree_replace(),
1438 * hva_node needs to be swapped with remove+insert even though hva can't
1439 * change when replacing an existing slot.
1441 hash_add(slots->id_hash, &new->id_node[idx], new->id);
1442 interval_tree_insert(&new->hva_node[idx], &slots->hva_tree);
1445 * If the memslot gfn is unchanged, rb_replace_node() can be used to
1446 * switch the node in the gfn tree instead of removing the old and
1447 * inserting the new as two separate operations. Replacement is a
1448 * single O(1) operation versus two O(log(n)) operations for
1451 if (old && old->base_gfn == new->base_gfn) {
1452 kvm_replace_gfn_node(slots, old, new);
1455 kvm_erase_gfn_node(slots, old);
1456 kvm_insert_gfn_node(slots, new);
1460 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1462 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1464 #ifdef __KVM_HAVE_READONLY_MEM
1465 valid_flags |= KVM_MEM_READONLY;
1468 if (mem->flags & ~valid_flags)
1474 static void kvm_swap_active_memslots(struct kvm *kvm, int as_id)
1476 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1478 /* Grab the generation from the activate memslots. */
1479 u64 gen = __kvm_memslots(kvm, as_id)->generation;
1481 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1482 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1485 * Do not store the new memslots while there are invalidations in
1486 * progress, otherwise the locking in invalidate_range_start and
1487 * invalidate_range_end will be unbalanced.
1489 spin_lock(&kvm->mn_invalidate_lock);
1490 prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1491 while (kvm->mn_active_invalidate_count) {
1492 set_current_state(TASK_UNINTERRUPTIBLE);
1493 spin_unlock(&kvm->mn_invalidate_lock);
1495 spin_lock(&kvm->mn_invalidate_lock);
1497 finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
1498 rcu_assign_pointer(kvm->memslots[as_id], slots);
1499 spin_unlock(&kvm->mn_invalidate_lock);
1502 * Acquired in kvm_set_memslot. Must be released before synchronize
1503 * SRCU below in order to avoid deadlock with another thread
1504 * acquiring the slots_arch_lock in an srcu critical section.
1506 mutex_unlock(&kvm->slots_arch_lock);
1508 synchronize_srcu_expedited(&kvm->srcu);
1511 * Increment the new memslot generation a second time, dropping the
1512 * update in-progress flag and incrementing the generation based on
1513 * the number of address spaces. This provides a unique and easily
1514 * identifiable generation number while the memslots are in flux.
1516 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1519 * Generations must be unique even across address spaces. We do not need
1520 * a global counter for that, instead the generation space is evenly split
1521 * across address spaces. For example, with two address spaces, address
1522 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1523 * use generations 1, 3, 5, ...
1525 gen += KVM_ADDRESS_SPACE_NUM;
1527 kvm_arch_memslots_updated(kvm, gen);
1529 slots->generation = gen;
1532 static int kvm_prepare_memory_region(struct kvm *kvm,
1533 const struct kvm_memory_slot *old,
1534 struct kvm_memory_slot *new,
1535 enum kvm_mr_change change)
1540 * If dirty logging is disabled, nullify the bitmap; the old bitmap
1541 * will be freed on "commit". If logging is enabled in both old and
1542 * new, reuse the existing bitmap. If logging is enabled only in the
1543 * new and KVM isn't using a ring buffer, allocate and initialize a
1546 if (change != KVM_MR_DELETE) {
1547 if (!(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
1548 new->dirty_bitmap = NULL;
1549 else if (old && old->dirty_bitmap)
1550 new->dirty_bitmap = old->dirty_bitmap;
1551 else if (!kvm->dirty_ring_size) {
1552 r = kvm_alloc_dirty_bitmap(new);
1556 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1557 bitmap_set(new->dirty_bitmap, 0, new->npages);
1561 r = kvm_arch_prepare_memory_region(kvm, old, new, change);
1563 /* Free the bitmap on failure if it was allocated above. */
1564 if (r && new && new->dirty_bitmap && (!old || !old->dirty_bitmap))
1565 kvm_destroy_dirty_bitmap(new);
1570 static void kvm_commit_memory_region(struct kvm *kvm,
1571 struct kvm_memory_slot *old,
1572 const struct kvm_memory_slot *new,
1573 enum kvm_mr_change change)
1576 * Update the total number of memslot pages before calling the arch
1577 * hook so that architectures can consume the result directly.
1579 if (change == KVM_MR_DELETE)
1580 kvm->nr_memslot_pages -= old->npages;
1581 else if (change == KVM_MR_CREATE)
1582 kvm->nr_memslot_pages += new->npages;
1584 kvm_arch_commit_memory_region(kvm, old, new, change);
1588 /* Nothing more to do. */
1591 /* Free the old memslot and all its metadata. */
1592 kvm_free_memslot(kvm, old);
1595 case KVM_MR_FLAGS_ONLY:
1597 * Free the dirty bitmap as needed; the below check encompasses
1598 * both the flags and whether a ring buffer is being used)
1600 if (old->dirty_bitmap && !new->dirty_bitmap)
1601 kvm_destroy_dirty_bitmap(old);
1604 * The final quirk. Free the detached, old slot, but only its
1605 * memory, not any metadata. Metadata, including arch specific
1606 * data, may be reused by @new.
1616 * Activate @new, which must be installed in the inactive slots by the caller,
1617 * by swapping the active slots and then propagating @new to @old once @old is
1618 * unreachable and can be safely modified.
1620 * With NULL @old this simply adds @new to @active (while swapping the sets).
1621 * With NULL @new this simply removes @old from @active and frees it
1622 * (while also swapping the sets).
1624 static void kvm_activate_memslot(struct kvm *kvm,
1625 struct kvm_memory_slot *old,
1626 struct kvm_memory_slot *new)
1628 int as_id = kvm_memslots_get_as_id(old, new);
1630 kvm_swap_active_memslots(kvm, as_id);
1632 /* Propagate the new memslot to the now inactive memslots. */
1633 kvm_replace_memslot(kvm, old, new);
1636 static void kvm_copy_memslot(struct kvm_memory_slot *dest,
1637 const struct kvm_memory_slot *src)
1639 dest->base_gfn = src->base_gfn;
1640 dest->npages = src->npages;
1641 dest->dirty_bitmap = src->dirty_bitmap;
1642 dest->arch = src->arch;
1643 dest->userspace_addr = src->userspace_addr;
1644 dest->flags = src->flags;
1646 dest->as_id = src->as_id;
1649 static void kvm_invalidate_memslot(struct kvm *kvm,
1650 struct kvm_memory_slot *old,
1651 struct kvm_memory_slot *invalid_slot)
1654 * Mark the current slot INVALID. As with all memslot modifications,
1655 * this must be done on an unreachable slot to avoid modifying the
1656 * current slot in the active tree.
1658 kvm_copy_memslot(invalid_slot, old);
1659 invalid_slot->flags |= KVM_MEMSLOT_INVALID;
1660 kvm_replace_memslot(kvm, old, invalid_slot);
1663 * Activate the slot that is now marked INVALID, but don't propagate
1664 * the slot to the now inactive slots. The slot is either going to be
1665 * deleted or recreated as a new slot.
1667 kvm_swap_active_memslots(kvm, old->as_id);
1670 * From this point no new shadow pages pointing to a deleted, or moved,
1671 * memslot will be created. Validation of sp->gfn happens in:
1672 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1673 * - kvm_is_visible_gfn (mmu_check_root)
1675 kvm_arch_flush_shadow_memslot(kvm, old);
1676 kvm_arch_guest_memory_reclaimed(kvm);
1678 /* Was released by kvm_swap_active_memslots, reacquire. */
1679 mutex_lock(&kvm->slots_arch_lock);
1682 * Copy the arch-specific field of the newly-installed slot back to the
1683 * old slot as the arch data could have changed between releasing
1684 * slots_arch_lock in install_new_memslots() and re-acquiring the lock
1685 * above. Writers are required to retrieve memslots *after* acquiring
1686 * slots_arch_lock, thus the active slot's data is guaranteed to be fresh.
1688 old->arch = invalid_slot->arch;
1691 static void kvm_create_memslot(struct kvm *kvm,
1692 struct kvm_memory_slot *new)
1694 /* Add the new memslot to the inactive set and activate. */
1695 kvm_replace_memslot(kvm, NULL, new);
1696 kvm_activate_memslot(kvm, NULL, new);
1699 static void kvm_delete_memslot(struct kvm *kvm,
1700 struct kvm_memory_slot *old,
1701 struct kvm_memory_slot *invalid_slot)
1704 * Remove the old memslot (in the inactive memslots) by passing NULL as
1705 * the "new" slot, and for the invalid version in the active slots.
1707 kvm_replace_memslot(kvm, old, NULL);
1708 kvm_activate_memslot(kvm, invalid_slot, NULL);
1711 static void kvm_move_memslot(struct kvm *kvm,
1712 struct kvm_memory_slot *old,
1713 struct kvm_memory_slot *new,
1714 struct kvm_memory_slot *invalid_slot)
1717 * Replace the old memslot in the inactive slots, and then swap slots
1718 * and replace the current INVALID with the new as well.
1720 kvm_replace_memslot(kvm, old, new);
1721 kvm_activate_memslot(kvm, invalid_slot, new);
1724 static void kvm_update_flags_memslot(struct kvm *kvm,
1725 struct kvm_memory_slot *old,
1726 struct kvm_memory_slot *new)
1729 * Similar to the MOVE case, but the slot doesn't need to be zapped as
1730 * an intermediate step. Instead, the old memslot is simply replaced
1731 * with a new, updated copy in both memslot sets.
1733 kvm_replace_memslot(kvm, old, new);
1734 kvm_activate_memslot(kvm, old, new);
1737 static int kvm_set_memslot(struct kvm *kvm,
1738 struct kvm_memory_slot *old,
1739 struct kvm_memory_slot *new,
1740 enum kvm_mr_change change)
1742 struct kvm_memory_slot *invalid_slot;
1746 * Released in kvm_swap_active_memslots.
1748 * Must be held from before the current memslots are copied until
1749 * after the new memslots are installed with rcu_assign_pointer,
1750 * then released before the synchronize srcu in kvm_swap_active_memslots.
1752 * When modifying memslots outside of the slots_lock, must be held
1753 * before reading the pointer to the current memslots until after all
1754 * changes to those memslots are complete.
1756 * These rules ensure that installing new memslots does not lose
1757 * changes made to the previous memslots.
1759 mutex_lock(&kvm->slots_arch_lock);
1762 * Invalidate the old slot if it's being deleted or moved. This is
1763 * done prior to actually deleting/moving the memslot to allow vCPUs to
1764 * continue running by ensuring there are no mappings or shadow pages
1765 * for the memslot when it is deleted/moved. Without pre-invalidation
1766 * (and without a lock), a window would exist between effecting the
1767 * delete/move and committing the changes in arch code where KVM or a
1768 * guest could access a non-existent memslot.
1770 * Modifications are done on a temporary, unreachable slot. The old
1771 * slot needs to be preserved in case a later step fails and the
1772 * invalidation needs to be reverted.
1774 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1775 invalid_slot = kzalloc(sizeof(*invalid_slot), GFP_KERNEL_ACCOUNT);
1776 if (!invalid_slot) {
1777 mutex_unlock(&kvm->slots_arch_lock);
1780 kvm_invalidate_memslot(kvm, old, invalid_slot);
1783 r = kvm_prepare_memory_region(kvm, old, new, change);
1786 * For DELETE/MOVE, revert the above INVALID change. No
1787 * modifications required since the original slot was preserved
1788 * in the inactive slots. Changing the active memslots also
1789 * release slots_arch_lock.
1791 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1792 kvm_activate_memslot(kvm, invalid_slot, old);
1793 kfree(invalid_slot);
1795 mutex_unlock(&kvm->slots_arch_lock);
1801 * For DELETE and MOVE, the working slot is now active as the INVALID
1802 * version of the old slot. MOVE is particularly special as it reuses
1803 * the old slot and returns a copy of the old slot (in working_slot).
1804 * For CREATE, there is no old slot. For DELETE and FLAGS_ONLY, the
1805 * old slot is detached but otherwise preserved.
1807 if (change == KVM_MR_CREATE)
1808 kvm_create_memslot(kvm, new);
1809 else if (change == KVM_MR_DELETE)
1810 kvm_delete_memslot(kvm, old, invalid_slot);
1811 else if (change == KVM_MR_MOVE)
1812 kvm_move_memslot(kvm, old, new, invalid_slot);
1813 else if (change == KVM_MR_FLAGS_ONLY)
1814 kvm_update_flags_memslot(kvm, old, new);
1818 /* Free the temporary INVALID slot used for DELETE and MOVE. */
1819 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1820 kfree(invalid_slot);
1823 * No need to refresh new->arch, changes after dropping slots_arch_lock
1824 * will directly hit the final, active memslot. Architectures are
1825 * responsible for knowing that new->arch may be stale.
1827 kvm_commit_memory_region(kvm, old, new, change);
1832 static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
1833 gfn_t start, gfn_t end)
1835 struct kvm_memslot_iter iter;
1837 kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
1838 if (iter.slot->id != id)
1846 * Allocate some memory and give it an address in the guest physical address
1849 * Discontiguous memory is allowed, mostly for framebuffers.
1851 * Must be called holding kvm->slots_lock for write.
1853 int __kvm_set_memory_region(struct kvm *kvm,
1854 const struct kvm_userspace_memory_region *mem)
1856 struct kvm_memory_slot *old, *new;
1857 struct kvm_memslots *slots;
1858 enum kvm_mr_change change;
1859 unsigned long npages;
1864 r = check_memory_region_flags(mem);
1868 as_id = mem->slot >> 16;
1869 id = (u16)mem->slot;
1871 /* General sanity checks */
1872 if ((mem->memory_size & (PAGE_SIZE - 1)) ||
1873 (mem->memory_size != (unsigned long)mem->memory_size))
1875 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1877 /* We can read the guest memory with __xxx_user() later on. */
1878 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1879 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1880 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1883 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1885 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1887 if ((mem->memory_size >> PAGE_SHIFT) > KVM_MEM_MAX_NR_PAGES)
1890 slots = __kvm_memslots(kvm, as_id);
1893 * Note, the old memslot (and the pointer itself!) may be invalidated
1894 * and/or destroyed by kvm_set_memslot().
1896 old = id_to_memslot(slots, id);
1898 if (!mem->memory_size) {
1899 if (!old || !old->npages)
1902 if (WARN_ON_ONCE(kvm->nr_memslot_pages < old->npages))
1905 return kvm_set_memslot(kvm, old, NULL, KVM_MR_DELETE);
1908 base_gfn = (mem->guest_phys_addr >> PAGE_SHIFT);
1909 npages = (mem->memory_size >> PAGE_SHIFT);
1911 if (!old || !old->npages) {
1912 change = KVM_MR_CREATE;
1915 * To simplify KVM internals, the total number of pages across
1916 * all memslots must fit in an unsigned long.
1918 if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages)
1920 } else { /* Modify an existing slot. */
1921 if ((mem->userspace_addr != old->userspace_addr) ||
1922 (npages != old->npages) ||
1923 ((mem->flags ^ old->flags) & KVM_MEM_READONLY))
1926 if (base_gfn != old->base_gfn)
1927 change = KVM_MR_MOVE;
1928 else if (mem->flags != old->flags)
1929 change = KVM_MR_FLAGS_ONLY;
1930 else /* Nothing to change. */
1934 if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) &&
1935 kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages))
1938 /* Allocate a slot that will persist in the memslot. */
1939 new = kzalloc(sizeof(*new), GFP_KERNEL_ACCOUNT);
1945 new->base_gfn = base_gfn;
1946 new->npages = npages;
1947 new->flags = mem->flags;
1948 new->userspace_addr = mem->userspace_addr;
1950 r = kvm_set_memslot(kvm, old, new, change);
1955 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1957 int kvm_set_memory_region(struct kvm *kvm,
1958 const struct kvm_userspace_memory_region *mem)
1962 mutex_lock(&kvm->slots_lock);
1963 r = __kvm_set_memory_region(kvm, mem);
1964 mutex_unlock(&kvm->slots_lock);
1967 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1969 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1970 struct kvm_userspace_memory_region *mem)
1972 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1975 return kvm_set_memory_region(kvm, mem);
1978 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1980 * kvm_get_dirty_log - get a snapshot of dirty pages
1981 * @kvm: pointer to kvm instance
1982 * @log: slot id and address to which we copy the log
1983 * @is_dirty: set to '1' if any dirty pages were found
1984 * @memslot: set to the associated memslot, always valid on success
1986 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1987 int *is_dirty, struct kvm_memory_slot **memslot)
1989 struct kvm_memslots *slots;
1992 unsigned long any = 0;
1994 /* Dirty ring tracking is exclusive to dirty log tracking */
1995 if (kvm->dirty_ring_size)
2001 as_id = log->slot >> 16;
2002 id = (u16)log->slot;
2003 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2006 slots = __kvm_memslots(kvm, as_id);
2007 *memslot = id_to_memslot(slots, id);
2008 if (!(*memslot) || !(*memslot)->dirty_bitmap)
2011 kvm_arch_sync_dirty_log(kvm, *memslot);
2013 n = kvm_dirty_bitmap_bytes(*memslot);
2015 for (i = 0; !any && i < n/sizeof(long); ++i)
2016 any = (*memslot)->dirty_bitmap[i];
2018 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
2025 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
2027 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2029 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
2030 * and reenable dirty page tracking for the corresponding pages.
2031 * @kvm: pointer to kvm instance
2032 * @log: slot id and address to which we copy the log
2034 * We need to keep it in mind that VCPU threads can write to the bitmap
2035 * concurrently. So, to avoid losing track of dirty pages we keep the
2038 * 1. Take a snapshot of the bit and clear it if needed.
2039 * 2. Write protect the corresponding page.
2040 * 3. Copy the snapshot to the userspace.
2041 * 4. Upon return caller flushes TLB's if needed.
2043 * Between 2 and 4, the guest may write to the page using the remaining TLB
2044 * entry. This is not a problem because the page is reported dirty using
2045 * the snapshot taken before and step 4 ensures that writes done after
2046 * exiting to userspace will be logged for the next call.
2049 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
2051 struct kvm_memslots *slots;
2052 struct kvm_memory_slot *memslot;
2055 unsigned long *dirty_bitmap;
2056 unsigned long *dirty_bitmap_buffer;
2059 /* Dirty ring tracking is exclusive to dirty log tracking */
2060 if (kvm->dirty_ring_size)
2063 as_id = log->slot >> 16;
2064 id = (u16)log->slot;
2065 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2068 slots = __kvm_memslots(kvm, as_id);
2069 memslot = id_to_memslot(slots, id);
2070 if (!memslot || !memslot->dirty_bitmap)
2073 dirty_bitmap = memslot->dirty_bitmap;
2075 kvm_arch_sync_dirty_log(kvm, memslot);
2077 n = kvm_dirty_bitmap_bytes(memslot);
2079 if (kvm->manual_dirty_log_protect) {
2081 * Unlike kvm_get_dirty_log, we always return false in *flush,
2082 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
2083 * is some code duplication between this function and
2084 * kvm_get_dirty_log, but hopefully all architecture
2085 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
2086 * can be eliminated.
2088 dirty_bitmap_buffer = dirty_bitmap;
2090 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2091 memset(dirty_bitmap_buffer, 0, n);
2094 for (i = 0; i < n / sizeof(long); i++) {
2098 if (!dirty_bitmap[i])
2102 mask = xchg(&dirty_bitmap[i], 0);
2103 dirty_bitmap_buffer[i] = mask;
2105 offset = i * BITS_PER_LONG;
2106 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2109 KVM_MMU_UNLOCK(kvm);
2113 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2115 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
2122 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
2123 * @kvm: kvm instance
2124 * @log: slot id and address to which we copy the log
2126 * Steps 1-4 below provide general overview of dirty page logging. See
2127 * kvm_get_dirty_log_protect() function description for additional details.
2129 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
2130 * always flush the TLB (step 4) even if previous step failed and the dirty
2131 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
2132 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
2133 * writes will be marked dirty for next log read.
2135 * 1. Take a snapshot of the bit and clear it if needed.
2136 * 2. Write protect the corresponding page.
2137 * 3. Copy the snapshot to the userspace.
2138 * 4. Flush TLB's if needed.
2140 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2141 struct kvm_dirty_log *log)
2145 mutex_lock(&kvm->slots_lock);
2147 r = kvm_get_dirty_log_protect(kvm, log);
2149 mutex_unlock(&kvm->slots_lock);
2154 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
2155 * and reenable dirty page tracking for the corresponding pages.
2156 * @kvm: pointer to kvm instance
2157 * @log: slot id and address from which to fetch the bitmap of dirty pages
2159 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
2160 struct kvm_clear_dirty_log *log)
2162 struct kvm_memslots *slots;
2163 struct kvm_memory_slot *memslot;
2167 unsigned long *dirty_bitmap;
2168 unsigned long *dirty_bitmap_buffer;
2171 /* Dirty ring tracking is exclusive to dirty log tracking */
2172 if (kvm->dirty_ring_size)
2175 as_id = log->slot >> 16;
2176 id = (u16)log->slot;
2177 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2180 if (log->first_page & 63)
2183 slots = __kvm_memslots(kvm, as_id);
2184 memslot = id_to_memslot(slots, id);
2185 if (!memslot || !memslot->dirty_bitmap)
2188 dirty_bitmap = memslot->dirty_bitmap;
2190 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
2192 if (log->first_page > memslot->npages ||
2193 log->num_pages > memslot->npages - log->first_page ||
2194 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
2197 kvm_arch_sync_dirty_log(kvm, memslot);
2200 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2201 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2205 for (offset = log->first_page, i = offset / BITS_PER_LONG,
2206 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2207 i++, offset += BITS_PER_LONG) {
2208 unsigned long mask = *dirty_bitmap_buffer++;
2209 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2213 mask &= atomic_long_fetch_andnot(mask, p);
2216 * mask contains the bits that really have been cleared. This
2217 * never includes any bits beyond the length of the memslot (if
2218 * the length is not aligned to 64 pages), therefore it is not
2219 * a problem if userspace sets them in log->dirty_bitmap.
2223 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2227 KVM_MMU_UNLOCK(kvm);
2230 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2235 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2236 struct kvm_clear_dirty_log *log)
2240 mutex_lock(&kvm->slots_lock);
2242 r = kvm_clear_dirty_log_protect(kvm, log);
2244 mutex_unlock(&kvm->slots_lock);
2247 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2249 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2251 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2253 EXPORT_SYMBOL_GPL(gfn_to_memslot);
2255 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2257 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2258 u64 gen = slots->generation;
2259 struct kvm_memory_slot *slot;
2262 * This also protects against using a memslot from a different address space,
2263 * since different address spaces have different generation numbers.
2265 if (unlikely(gen != vcpu->last_used_slot_gen)) {
2266 vcpu->last_used_slot = NULL;
2267 vcpu->last_used_slot_gen = gen;
2270 slot = try_get_memslot(vcpu->last_used_slot, gfn);
2275 * Fall back to searching all memslots. We purposely use
2276 * search_memslots() instead of __gfn_to_memslot() to avoid
2277 * thrashing the VM-wide last_used_slot in kvm_memslots.
2279 slot = search_memslots(slots, gfn, false);
2281 vcpu->last_used_slot = slot;
2288 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
2290 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
2292 return kvm_is_visible_memslot(memslot);
2294 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2296 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2298 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2300 return kvm_is_visible_memslot(memslot);
2302 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2304 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
2306 struct vm_area_struct *vma;
2307 unsigned long addr, size;
2311 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
2312 if (kvm_is_error_hva(addr))
2315 mmap_read_lock(current->mm);
2316 vma = find_vma(current->mm, addr);
2320 size = vma_kernel_pagesize(vma);
2323 mmap_read_unlock(current->mm);
2328 static bool memslot_is_readonly(const struct kvm_memory_slot *slot)
2330 return slot->flags & KVM_MEM_READONLY;
2333 static unsigned long __gfn_to_hva_many(const struct kvm_memory_slot *slot, gfn_t gfn,
2334 gfn_t *nr_pages, bool write)
2336 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
2337 return KVM_HVA_ERR_BAD;
2339 if (memslot_is_readonly(slot) && write)
2340 return KVM_HVA_ERR_RO_BAD;
2343 *nr_pages = slot->npages - (gfn - slot->base_gfn);
2345 return __gfn_to_hva_memslot(slot, gfn);
2348 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2351 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2354 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2357 return gfn_to_hva_many(slot, gfn, NULL);
2359 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2361 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2363 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2365 EXPORT_SYMBOL_GPL(gfn_to_hva);
2367 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2369 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2371 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2374 * Return the hva of a @gfn and the R/W attribute if possible.
2376 * @slot: the kvm_memory_slot which contains @gfn
2377 * @gfn: the gfn to be translated
2378 * @writable: used to return the read/write attribute of the @slot if the hva
2379 * is valid and @writable is not NULL
2381 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2382 gfn_t gfn, bool *writable)
2384 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2386 if (!kvm_is_error_hva(hva) && writable)
2387 *writable = !memslot_is_readonly(slot);
2392 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2394 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2396 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2399 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2401 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2403 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2406 static inline int check_user_page_hwpoison(unsigned long addr)
2408 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
2410 rc = get_user_pages(addr, 1, flags, NULL, NULL);
2411 return rc == -EHWPOISON;
2415 * The fast path to get the writable pfn which will be stored in @pfn,
2416 * true indicates success, otherwise false is returned. It's also the
2417 * only part that runs if we can in atomic context.
2419 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2420 bool *writable, kvm_pfn_t *pfn)
2422 struct page *page[1];
2425 * Fast pin a writable pfn only if it is a write fault request
2426 * or the caller allows to map a writable pfn for a read fault
2429 if (!(write_fault || writable))
2432 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2433 *pfn = page_to_pfn(page[0]);
2444 * The slow path to get the pfn of the specified host virtual address,
2445 * 1 indicates success, -errno is returned if error is detected.
2447 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2448 bool *writable, kvm_pfn_t *pfn)
2450 unsigned int flags = FOLL_HWPOISON;
2457 *writable = write_fault;
2460 flags |= FOLL_WRITE;
2462 flags |= FOLL_NOWAIT;
2464 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2468 /* map read fault as writable if possible */
2469 if (unlikely(!write_fault) && writable) {
2472 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2478 *pfn = page_to_pfn(page);
2482 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2484 if (unlikely(!(vma->vm_flags & VM_READ)))
2487 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2493 static int kvm_try_get_pfn(kvm_pfn_t pfn)
2495 if (kvm_is_reserved_pfn(pfn))
2497 return get_page_unless_zero(pfn_to_page(pfn));
2500 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2501 unsigned long addr, bool write_fault,
2502 bool *writable, kvm_pfn_t *p_pfn)
2509 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2512 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2513 * not call the fault handler, so do it here.
2515 bool unlocked = false;
2516 r = fixup_user_fault(current->mm, addr,
2517 (write_fault ? FAULT_FLAG_WRITE : 0),
2524 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2529 if (write_fault && !pte_write(*ptep)) {
2530 pfn = KVM_PFN_ERR_RO_FAULT;
2535 *writable = pte_write(*ptep);
2536 pfn = pte_pfn(*ptep);
2539 * Get a reference here because callers of *hva_to_pfn* and
2540 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2541 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2542 * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
2543 * simply do nothing for reserved pfns.
2545 * Whoever called remap_pfn_range is also going to call e.g.
2546 * unmap_mapping_range before the underlying pages are freed,
2547 * causing a call to our MMU notifier.
2549 * Certain IO or PFNMAP mappings can be backed with valid
2550 * struct pages, but be allocated without refcounting e.g.,
2551 * tail pages of non-compound higher order allocations, which
2552 * would then underflow the refcount when the caller does the
2553 * required put_page. Don't allow those pages here.
2555 if (!kvm_try_get_pfn(pfn))
2559 pte_unmap_unlock(ptep, ptl);
2566 * Pin guest page in memory and return its pfn.
2567 * @addr: host virtual address which maps memory to the guest
2568 * @atomic: whether this function can sleep
2569 * @async: whether this function need to wait IO complete if the
2570 * host page is not in the memory
2571 * @write_fault: whether we should get a writable host page
2572 * @writable: whether it allows to map a writable host page for !@write_fault
2574 * The function will map a writable host page for these two cases:
2575 * 1): @write_fault = true
2576 * 2): @write_fault = false && @writable, @writable will tell the caller
2577 * whether the mapping is writable.
2579 kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2580 bool write_fault, bool *writable)
2582 struct vm_area_struct *vma;
2586 /* we can do it either atomically or asynchronously, not both */
2587 BUG_ON(atomic && async);
2589 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2593 return KVM_PFN_ERR_FAULT;
2595 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2599 mmap_read_lock(current->mm);
2600 if (npages == -EHWPOISON ||
2601 (!async && check_user_page_hwpoison(addr))) {
2602 pfn = KVM_PFN_ERR_HWPOISON;
2607 vma = vma_lookup(current->mm, addr);
2610 pfn = KVM_PFN_ERR_FAULT;
2611 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2612 r = hva_to_pfn_remapped(vma, addr, write_fault, writable, &pfn);
2616 pfn = KVM_PFN_ERR_FAULT;
2618 if (async && vma_is_valid(vma, write_fault))
2620 pfn = KVM_PFN_ERR_FAULT;
2623 mmap_read_unlock(current->mm);
2627 kvm_pfn_t __gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn,
2628 bool atomic, bool *async, bool write_fault,
2629 bool *writable, hva_t *hva)
2631 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2636 if (addr == KVM_HVA_ERR_RO_BAD) {
2639 return KVM_PFN_ERR_RO_FAULT;
2642 if (kvm_is_error_hva(addr)) {
2645 return KVM_PFN_NOSLOT;
2648 /* Do not map writable pfn in the readonly memslot. */
2649 if (writable && memslot_is_readonly(slot)) {
2654 return hva_to_pfn(addr, atomic, async, write_fault,
2657 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2659 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2662 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2663 write_fault, writable, NULL);
2665 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2667 kvm_pfn_t gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn)
2669 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2671 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2673 kvm_pfn_t gfn_to_pfn_memslot_atomic(const struct kvm_memory_slot *slot, gfn_t gfn)
2675 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2677 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2679 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2681 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2683 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2685 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2687 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2689 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2691 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2693 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2695 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2697 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2698 struct page **pages, int nr_pages)
2703 addr = gfn_to_hva_many(slot, gfn, &entry);
2704 if (kvm_is_error_hva(addr))
2707 if (entry < nr_pages)
2710 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2712 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2714 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2716 if (is_error_noslot_pfn(pfn))
2717 return KVM_ERR_PTR_BAD_PAGE;
2719 if (kvm_is_reserved_pfn(pfn)) {
2721 return KVM_ERR_PTR_BAD_PAGE;
2724 return pfn_to_page(pfn);
2727 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2731 pfn = gfn_to_pfn(kvm, gfn);
2733 return kvm_pfn_to_page(pfn);
2735 EXPORT_SYMBOL_GPL(gfn_to_page);
2737 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty)
2743 kvm_release_pfn_dirty(pfn);
2745 kvm_release_pfn_clean(pfn);
2748 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2752 struct page *page = KVM_UNMAPPED_PAGE;
2757 pfn = gfn_to_pfn(vcpu->kvm, gfn);
2758 if (is_error_noslot_pfn(pfn))
2761 if (pfn_valid(pfn)) {
2762 page = pfn_to_page(pfn);
2764 #ifdef CONFIG_HAS_IOMEM
2766 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2780 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2782 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2790 if (map->page != KVM_UNMAPPED_PAGE)
2792 #ifdef CONFIG_HAS_IOMEM
2798 kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
2800 kvm_release_pfn(map->pfn, dirty);
2805 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2807 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2811 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2813 return kvm_pfn_to_page(pfn);
2815 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2817 void kvm_release_page_clean(struct page *page)
2819 WARN_ON(is_error_page(page));
2821 kvm_release_pfn_clean(page_to_pfn(page));
2823 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2825 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2827 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2828 put_page(pfn_to_page(pfn));
2830 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2832 void kvm_release_page_dirty(struct page *page)
2834 WARN_ON(is_error_page(page));
2836 kvm_release_pfn_dirty(page_to_pfn(page));
2838 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2840 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2842 kvm_set_pfn_dirty(pfn);
2843 kvm_release_pfn_clean(pfn);
2845 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2847 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2849 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2850 SetPageDirty(pfn_to_page(pfn));
2852 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2854 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2856 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2857 mark_page_accessed(pfn_to_page(pfn));
2859 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2861 static int next_segment(unsigned long len, int offset)
2863 if (len > PAGE_SIZE - offset)
2864 return PAGE_SIZE - offset;
2869 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2870 void *data, int offset, int len)
2875 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2876 if (kvm_is_error_hva(addr))
2878 r = __copy_from_user(data, (void __user *)addr + offset, len);
2884 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2887 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2889 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2891 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2893 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2894 int offset, int len)
2896 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2898 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2900 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2902 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2904 gfn_t gfn = gpa >> PAGE_SHIFT;
2906 int offset = offset_in_page(gpa);
2909 while ((seg = next_segment(len, offset)) != 0) {
2910 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2920 EXPORT_SYMBOL_GPL(kvm_read_guest);
2922 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2924 gfn_t gfn = gpa >> PAGE_SHIFT;
2926 int offset = offset_in_page(gpa);
2929 while ((seg = next_segment(len, offset)) != 0) {
2930 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2940 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2942 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2943 void *data, int offset, unsigned long len)
2948 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2949 if (kvm_is_error_hva(addr))
2951 pagefault_disable();
2952 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2959 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2960 void *data, unsigned long len)
2962 gfn_t gfn = gpa >> PAGE_SHIFT;
2963 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2964 int offset = offset_in_page(gpa);
2966 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2968 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2970 static int __kvm_write_guest_page(struct kvm *kvm,
2971 struct kvm_memory_slot *memslot, gfn_t gfn,
2972 const void *data, int offset, int len)
2977 addr = gfn_to_hva_memslot(memslot, gfn);
2978 if (kvm_is_error_hva(addr))
2980 r = __copy_to_user((void __user *)addr + offset, data, len);
2983 mark_page_dirty_in_slot(kvm, memslot, gfn);
2987 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2988 const void *data, int offset, int len)
2990 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2992 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2994 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2996 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2997 const void *data, int offset, int len)
2999 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3001 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
3003 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
3005 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
3008 gfn_t gfn = gpa >> PAGE_SHIFT;
3010 int offset = offset_in_page(gpa);
3013 while ((seg = next_segment(len, offset)) != 0) {
3014 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
3024 EXPORT_SYMBOL_GPL(kvm_write_guest);
3026 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
3029 gfn_t gfn = gpa >> PAGE_SHIFT;
3031 int offset = offset_in_page(gpa);
3034 while ((seg = next_segment(len, offset)) != 0) {
3035 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
3045 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
3047 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
3048 struct gfn_to_hva_cache *ghc,
3049 gpa_t gpa, unsigned long len)
3051 int offset = offset_in_page(gpa);
3052 gfn_t start_gfn = gpa >> PAGE_SHIFT;
3053 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
3054 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
3055 gfn_t nr_pages_avail;
3057 /* Update ghc->generation before performing any error checks. */
3058 ghc->generation = slots->generation;
3060 if (start_gfn > end_gfn) {
3061 ghc->hva = KVM_HVA_ERR_BAD;
3066 * If the requested region crosses two memslots, we still
3067 * verify that the entire region is valid here.
3069 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
3070 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
3071 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
3073 if (kvm_is_error_hva(ghc->hva))
3077 /* Use the slow path for cross page reads and writes. */
3078 if (nr_pages_needed == 1)
3081 ghc->memslot = NULL;
3088 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3089 gpa_t gpa, unsigned long len)
3091 struct kvm_memslots *slots = kvm_memslots(kvm);
3092 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
3094 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
3096 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3097 void *data, unsigned int offset,
3100 struct kvm_memslots *slots = kvm_memslots(kvm);
3102 gpa_t gpa = ghc->gpa + offset;
3104 if (WARN_ON_ONCE(len + offset > ghc->len))
3107 if (slots->generation != ghc->generation) {
3108 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3112 if (kvm_is_error_hva(ghc->hva))
3115 if (unlikely(!ghc->memslot))
3116 return kvm_write_guest(kvm, gpa, data, len);
3118 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
3121 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
3125 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
3127 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3128 void *data, unsigned long len)
3130 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
3132 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
3134 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3135 void *data, unsigned int offset,
3138 struct kvm_memslots *slots = kvm_memslots(kvm);
3140 gpa_t gpa = ghc->gpa + offset;
3142 if (WARN_ON_ONCE(len + offset > ghc->len))
3145 if (slots->generation != ghc->generation) {
3146 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3150 if (kvm_is_error_hva(ghc->hva))
3153 if (unlikely(!ghc->memslot))
3154 return kvm_read_guest(kvm, gpa, data, len);
3156 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
3162 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3164 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3165 void *data, unsigned long len)
3167 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3169 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
3171 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3173 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3174 gfn_t gfn = gpa >> PAGE_SHIFT;
3176 int offset = offset_in_page(gpa);
3179 while ((seg = next_segment(len, offset)) != 0) {
3180 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
3189 EXPORT_SYMBOL_GPL(kvm_clear_guest);
3191 void mark_page_dirty_in_slot(struct kvm *kvm,
3192 const struct kvm_memory_slot *memslot,
3195 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
3197 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3198 if (WARN_ON_ONCE(!vcpu) || WARN_ON_ONCE(vcpu->kvm != kvm))
3202 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
3203 unsigned long rel_gfn = gfn - memslot->base_gfn;
3204 u32 slot = (memslot->as_id << 16) | memslot->id;
3206 if (kvm->dirty_ring_size)
3207 kvm_dirty_ring_push(&vcpu->dirty_ring,
3210 set_bit_le(rel_gfn, memslot->dirty_bitmap);
3213 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
3215 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3217 struct kvm_memory_slot *memslot;
3219 memslot = gfn_to_memslot(kvm, gfn);
3220 mark_page_dirty_in_slot(kvm, memslot, gfn);
3222 EXPORT_SYMBOL_GPL(mark_page_dirty);
3224 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3226 struct kvm_memory_slot *memslot;
3228 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3229 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
3231 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3233 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3235 if (!vcpu->sigset_active)
3239 * This does a lockless modification of ->real_blocked, which is fine
3240 * because, only current can change ->real_blocked and all readers of
3241 * ->real_blocked don't care as long ->real_blocked is always a subset
3244 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
3247 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3249 if (!vcpu->sigset_active)
3252 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
3253 sigemptyset(¤t->real_blocked);
3256 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3258 unsigned int old, val, grow, grow_start;
3260 old = val = vcpu->halt_poll_ns;
3261 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3262 grow = READ_ONCE(halt_poll_ns_grow);
3267 if (val < grow_start)
3270 if (val > vcpu->kvm->max_halt_poll_ns)
3271 val = vcpu->kvm->max_halt_poll_ns;
3273 vcpu->halt_poll_ns = val;
3275 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
3278 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3280 unsigned int old, val, shrink, grow_start;
3282 old = val = vcpu->halt_poll_ns;
3283 shrink = READ_ONCE(halt_poll_ns_shrink);
3284 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3290 if (val < grow_start)
3293 vcpu->halt_poll_ns = val;
3294 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3297 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3300 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3302 if (kvm_arch_vcpu_runnable(vcpu)) {
3303 kvm_make_request(KVM_REQ_UNHALT, vcpu);
3306 if (kvm_cpu_has_pending_timer(vcpu))
3308 if (signal_pending(current))
3310 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3315 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3320 * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is
3321 * pending. This is mostly used when halting a vCPU, but may also be used
3322 * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI.
3324 bool kvm_vcpu_block(struct kvm_vcpu *vcpu)
3326 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
3327 bool waited = false;
3329 vcpu->stat.generic.blocking = 1;
3331 kvm_arch_vcpu_blocking(vcpu);
3333 prepare_to_rcuwait(wait);
3335 set_current_state(TASK_INTERRUPTIBLE);
3337 if (kvm_vcpu_check_block(vcpu) < 0)
3343 finish_rcuwait(wait);
3345 kvm_arch_vcpu_unblocking(vcpu);
3347 vcpu->stat.generic.blocking = 0;
3352 static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start,
3353 ktime_t end, bool success)
3355 struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic;
3356 u64 poll_ns = ktime_to_ns(ktime_sub(end, start));
3358 ++vcpu->stat.generic.halt_attempted_poll;
3361 ++vcpu->stat.generic.halt_successful_poll;
3363 if (!vcpu_valid_wakeup(vcpu))
3364 ++vcpu->stat.generic.halt_poll_invalid;
3366 stats->halt_poll_success_ns += poll_ns;
3367 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns);
3369 stats->halt_poll_fail_ns += poll_ns;
3370 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns);
3375 * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc... If halt
3376 * polling is enabled, busy wait for a short time before blocking to avoid the
3377 * expensive block+unblock sequence if a wake event arrives soon after the vCPU
3380 void kvm_vcpu_halt(struct kvm_vcpu *vcpu)
3382 bool halt_poll_allowed = !kvm_arch_no_poll(vcpu);
3383 bool do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns;
3384 ktime_t start, cur, poll_end;
3385 bool waited = false;
3388 start = cur = poll_end = ktime_get();
3390 ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns);
3394 * This sets KVM_REQ_UNHALT if an interrupt
3397 if (kvm_vcpu_check_block(vcpu) < 0)
3400 poll_end = cur = ktime_get();
3401 } while (kvm_vcpu_can_poll(cur, stop));
3404 waited = kvm_vcpu_block(vcpu);
3408 vcpu->stat.generic.halt_wait_ns +=
3409 ktime_to_ns(cur) - ktime_to_ns(poll_end);
3410 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3411 ktime_to_ns(cur) - ktime_to_ns(poll_end));
3414 /* The total time the vCPU was "halted", including polling time. */
3415 halt_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3418 * Note, halt-polling is considered successful so long as the vCPU was
3419 * never actually scheduled out, i.e. even if the wake event arrived
3420 * after of the halt-polling loop itself, but before the full wait.
3423 update_halt_poll_stats(vcpu, start, poll_end, !waited);
3425 if (halt_poll_allowed) {
3426 if (!vcpu_valid_wakeup(vcpu)) {
3427 shrink_halt_poll_ns(vcpu);
3428 } else if (vcpu->kvm->max_halt_poll_ns) {
3429 if (halt_ns <= vcpu->halt_poll_ns)
3431 /* we had a long block, shrink polling */
3432 else if (vcpu->halt_poll_ns &&
3433 halt_ns > vcpu->kvm->max_halt_poll_ns)
3434 shrink_halt_poll_ns(vcpu);
3435 /* we had a short halt and our poll time is too small */
3436 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3437 halt_ns < vcpu->kvm->max_halt_poll_ns)
3438 grow_halt_poll_ns(vcpu);
3440 vcpu->halt_poll_ns = 0;
3444 trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu));
3446 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
3448 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3450 if (__kvm_vcpu_wake_up(vcpu)) {
3451 WRITE_ONCE(vcpu->ready, true);
3452 ++vcpu->stat.generic.halt_wakeup;
3458 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3462 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3464 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3468 if (kvm_vcpu_wake_up(vcpu))
3473 * The only state change done outside the vcpu mutex is IN_GUEST_MODE
3474 * to EXITING_GUEST_MODE. Therefore the moderately expensive "should
3475 * kick" check does not need atomic operations if kvm_vcpu_kick is used
3476 * within the vCPU thread itself.
3478 if (vcpu == __this_cpu_read(kvm_running_vcpu)) {
3479 if (vcpu->mode == IN_GUEST_MODE)
3480 WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE);
3485 * Note, the vCPU could get migrated to a different pCPU at any point
3486 * after kvm_arch_vcpu_should_kick(), which could result in sending an
3487 * IPI to the previous pCPU. But, that's ok because the purpose of the
3488 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
3489 * vCPU also requires it to leave IN_GUEST_MODE.
3491 if (kvm_arch_vcpu_should_kick(vcpu)) {
3492 cpu = READ_ONCE(vcpu->cpu);
3493 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3494 smp_send_reschedule(cpu);
3499 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3500 #endif /* !CONFIG_S390 */
3502 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3505 struct task_struct *task = NULL;
3509 pid = rcu_dereference(target->pid);
3511 task = get_pid_task(pid, PIDTYPE_PID);
3515 ret = yield_to(task, 1);
3516 put_task_struct(task);
3520 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3523 * Helper that checks whether a VCPU is eligible for directed yield.
3524 * Most eligible candidate to yield is decided by following heuristics:
3526 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3527 * (preempted lock holder), indicated by @in_spin_loop.
3528 * Set at the beginning and cleared at the end of interception/PLE handler.
3530 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3531 * chance last time (mostly it has become eligible now since we have probably
3532 * yielded to lockholder in last iteration. This is done by toggling
3533 * @dy_eligible each time a VCPU checked for eligibility.)
3535 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3536 * to preempted lock-holder could result in wrong VCPU selection and CPU
3537 * burning. Giving priority for a potential lock-holder increases lock
3540 * Since algorithm is based on heuristics, accessing another VCPU data without
3541 * locking does not harm. It may result in trying to yield to same VCPU, fail
3542 * and continue with next VCPU and so on.
3544 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3546 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3549 eligible = !vcpu->spin_loop.in_spin_loop ||
3550 vcpu->spin_loop.dy_eligible;
3552 if (vcpu->spin_loop.in_spin_loop)
3553 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3562 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3563 * a vcpu_load/vcpu_put pair. However, for most architectures
3564 * kvm_arch_vcpu_runnable does not require vcpu_load.
3566 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3568 return kvm_arch_vcpu_runnable(vcpu);
3571 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3573 if (kvm_arch_dy_runnable(vcpu))
3576 #ifdef CONFIG_KVM_ASYNC_PF
3577 if (!list_empty_careful(&vcpu->async_pf.done))
3584 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3589 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3591 struct kvm *kvm = me->kvm;
3592 struct kvm_vcpu *vcpu;
3593 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3599 kvm_vcpu_set_in_spin_loop(me, true);
3601 * We boost the priority of a VCPU that is runnable but not
3602 * currently running, because it got preempted by something
3603 * else and called schedule in __vcpu_run. Hopefully that
3604 * VCPU is holding the lock that we need and will release it.
3605 * We approximate round-robin by starting at the last boosted VCPU.
3607 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3608 kvm_for_each_vcpu(i, vcpu, kvm) {
3609 if (!pass && i <= last_boosted_vcpu) {
3610 i = last_boosted_vcpu;
3612 } else if (pass && i > last_boosted_vcpu)
3614 if (!READ_ONCE(vcpu->ready))
3618 if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu))
3620 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3621 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3622 !kvm_arch_vcpu_in_kernel(vcpu))
3624 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3627 yielded = kvm_vcpu_yield_to(vcpu);
3629 kvm->last_boosted_vcpu = i;
3631 } else if (yielded < 0) {
3638 kvm_vcpu_set_in_spin_loop(me, false);
3640 /* Ensure vcpu is not eligible during next spinloop */
3641 kvm_vcpu_set_dy_eligible(me, false);
3643 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3645 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3647 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3648 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3649 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3650 kvm->dirty_ring_size / PAGE_SIZE);
3656 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3658 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3661 if (vmf->pgoff == 0)
3662 page = virt_to_page(vcpu->run);
3664 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3665 page = virt_to_page(vcpu->arch.pio_data);
3667 #ifdef CONFIG_KVM_MMIO
3668 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3669 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3671 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3672 page = kvm_dirty_ring_get_page(
3674 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3676 return kvm_arch_vcpu_fault(vcpu, vmf);
3682 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3683 .fault = kvm_vcpu_fault,
3686 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3688 struct kvm_vcpu *vcpu = file->private_data;
3689 unsigned long pages = vma_pages(vma);
3691 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3692 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3693 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3696 vma->vm_ops = &kvm_vcpu_vm_ops;
3700 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3702 struct kvm_vcpu *vcpu = filp->private_data;
3704 kvm_put_kvm(vcpu->kvm);
3708 static const struct file_operations kvm_vcpu_fops = {
3709 .release = kvm_vcpu_release,
3710 .unlocked_ioctl = kvm_vcpu_ioctl,
3711 .mmap = kvm_vcpu_mmap,
3712 .llseek = noop_llseek,
3713 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3717 * Allocates an inode for the vcpu.
3719 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3721 char name[8 + 1 + ITOA_MAX_LEN + 1];
3723 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3724 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3727 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3729 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3730 struct dentry *debugfs_dentry;
3731 char dir_name[ITOA_MAX_LEN * 2];
3733 if (!debugfs_initialized())
3736 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3737 debugfs_dentry = debugfs_create_dir(dir_name,
3738 vcpu->kvm->debugfs_dentry);
3740 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3745 * Creates some virtual cpus. Good luck creating more than one.
3747 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3750 struct kvm_vcpu *vcpu;
3753 if (id >= KVM_MAX_VCPU_IDS)
3756 mutex_lock(&kvm->lock);
3757 if (kvm->created_vcpus >= kvm->max_vcpus) {
3758 mutex_unlock(&kvm->lock);
3762 kvm->created_vcpus++;
3763 mutex_unlock(&kvm->lock);
3765 r = kvm_arch_vcpu_precreate(kvm, id);
3767 goto vcpu_decrement;
3769 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3772 goto vcpu_decrement;
3775 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3776 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3781 vcpu->run = page_address(page);
3783 kvm_vcpu_init(vcpu, kvm, id);
3785 r = kvm_arch_vcpu_create(vcpu);
3787 goto vcpu_free_run_page;
3789 if (kvm->dirty_ring_size) {
3790 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3791 id, kvm->dirty_ring_size);
3793 goto arch_vcpu_destroy;
3796 mutex_lock(&kvm->lock);
3797 if (kvm_get_vcpu_by_id(kvm, id)) {
3799 goto unlock_vcpu_destroy;
3802 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3803 r = xa_insert(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, GFP_KERNEL_ACCOUNT);
3804 BUG_ON(r == -EBUSY);
3806 goto unlock_vcpu_destroy;
3808 /* Fill the stats id string for the vcpu */
3809 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3810 task_pid_nr(current), id);
3812 /* Now it's all set up, let userspace reach it */
3814 r = create_vcpu_fd(vcpu);
3816 xa_erase(&kvm->vcpu_array, vcpu->vcpu_idx);
3817 kvm_put_kvm_no_destroy(kvm);
3818 goto unlock_vcpu_destroy;
3822 * Pairs with smp_rmb() in kvm_get_vcpu. Store the vcpu
3823 * pointer before kvm->online_vcpu's incremented value.
3826 atomic_inc(&kvm->online_vcpus);
3828 mutex_unlock(&kvm->lock);
3829 kvm_arch_vcpu_postcreate(vcpu);
3830 kvm_create_vcpu_debugfs(vcpu);
3833 unlock_vcpu_destroy:
3834 mutex_unlock(&kvm->lock);
3835 kvm_dirty_ring_free(&vcpu->dirty_ring);
3837 kvm_arch_vcpu_destroy(vcpu);
3839 free_page((unsigned long)vcpu->run);
3841 kmem_cache_free(kvm_vcpu_cache, vcpu);
3843 mutex_lock(&kvm->lock);
3844 kvm->created_vcpus--;
3845 mutex_unlock(&kvm->lock);
3849 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3852 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3853 vcpu->sigset_active = 1;
3854 vcpu->sigset = *sigset;
3856 vcpu->sigset_active = 0;
3860 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3861 size_t size, loff_t *offset)
3863 struct kvm_vcpu *vcpu = file->private_data;
3865 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3866 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3867 sizeof(vcpu->stat), user_buffer, size, offset);
3870 static const struct file_operations kvm_vcpu_stats_fops = {
3871 .read = kvm_vcpu_stats_read,
3872 .llseek = noop_llseek,
3875 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3879 char name[15 + ITOA_MAX_LEN + 1];
3881 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3883 fd = get_unused_fd_flags(O_CLOEXEC);
3887 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3890 return PTR_ERR(file);
3892 file->f_mode |= FMODE_PREAD;
3893 fd_install(fd, file);
3898 static long kvm_vcpu_ioctl(struct file *filp,
3899 unsigned int ioctl, unsigned long arg)
3901 struct kvm_vcpu *vcpu = filp->private_data;
3902 void __user *argp = (void __user *)arg;
3904 struct kvm_fpu *fpu = NULL;
3905 struct kvm_sregs *kvm_sregs = NULL;
3907 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
3910 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3914 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3915 * execution; mutex_lock() would break them.
3917 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3918 if (r != -ENOIOCTLCMD)
3921 if (mutex_lock_killable(&vcpu->mutex))
3929 oldpid = rcu_access_pointer(vcpu->pid);
3930 if (unlikely(oldpid != task_pid(current))) {
3931 /* The thread running this VCPU changed. */
3934 r = kvm_arch_vcpu_run_pid_change(vcpu);
3938 newpid = get_task_pid(current, PIDTYPE_PID);
3939 rcu_assign_pointer(vcpu->pid, newpid);
3944 r = kvm_arch_vcpu_ioctl_run(vcpu);
3945 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3948 case KVM_GET_REGS: {
3949 struct kvm_regs *kvm_regs;
3952 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3955 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3959 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3966 case KVM_SET_REGS: {
3967 struct kvm_regs *kvm_regs;
3969 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3970 if (IS_ERR(kvm_regs)) {
3971 r = PTR_ERR(kvm_regs);
3974 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3978 case KVM_GET_SREGS: {
3979 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3980 GFP_KERNEL_ACCOUNT);
3984 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3988 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3993 case KVM_SET_SREGS: {
3994 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3995 if (IS_ERR(kvm_sregs)) {
3996 r = PTR_ERR(kvm_sregs);
4000 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
4003 case KVM_GET_MP_STATE: {
4004 struct kvm_mp_state mp_state;
4006 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
4010 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
4015 case KVM_SET_MP_STATE: {
4016 struct kvm_mp_state mp_state;
4019 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
4021 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
4024 case KVM_TRANSLATE: {
4025 struct kvm_translation tr;
4028 if (copy_from_user(&tr, argp, sizeof(tr)))
4030 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
4034 if (copy_to_user(argp, &tr, sizeof(tr)))
4039 case KVM_SET_GUEST_DEBUG: {
4040 struct kvm_guest_debug dbg;
4043 if (copy_from_user(&dbg, argp, sizeof(dbg)))
4045 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
4048 case KVM_SET_SIGNAL_MASK: {
4049 struct kvm_signal_mask __user *sigmask_arg = argp;
4050 struct kvm_signal_mask kvm_sigmask;
4051 sigset_t sigset, *p;
4056 if (copy_from_user(&kvm_sigmask, argp,
4057 sizeof(kvm_sigmask)))
4060 if (kvm_sigmask.len != sizeof(sigset))
4063 if (copy_from_user(&sigset, sigmask_arg->sigset,
4068 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
4072 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
4076 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
4080 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
4086 fpu = memdup_user(argp, sizeof(*fpu));
4092 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
4095 case KVM_GET_STATS_FD: {
4096 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
4100 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
4103 mutex_unlock(&vcpu->mutex);
4109 #ifdef CONFIG_KVM_COMPAT
4110 static long kvm_vcpu_compat_ioctl(struct file *filp,
4111 unsigned int ioctl, unsigned long arg)
4113 struct kvm_vcpu *vcpu = filp->private_data;
4114 void __user *argp = compat_ptr(arg);
4117 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
4121 case KVM_SET_SIGNAL_MASK: {
4122 struct kvm_signal_mask __user *sigmask_arg = argp;
4123 struct kvm_signal_mask kvm_sigmask;
4128 if (copy_from_user(&kvm_sigmask, argp,
4129 sizeof(kvm_sigmask)))
4132 if (kvm_sigmask.len != sizeof(compat_sigset_t))
4135 if (get_compat_sigset(&sigset,
4136 (compat_sigset_t __user *)sigmask_arg->sigset))
4138 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
4140 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
4144 r = kvm_vcpu_ioctl(filp, ioctl, arg);
4152 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
4154 struct kvm_device *dev = filp->private_data;
4157 return dev->ops->mmap(dev, vma);
4162 static int kvm_device_ioctl_attr(struct kvm_device *dev,
4163 int (*accessor)(struct kvm_device *dev,
4164 struct kvm_device_attr *attr),
4167 struct kvm_device_attr attr;
4172 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4175 return accessor(dev, &attr);
4178 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
4181 struct kvm_device *dev = filp->private_data;
4183 if (dev->kvm->mm != current->mm || dev->kvm->vm_dead)
4187 case KVM_SET_DEVICE_ATTR:
4188 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
4189 case KVM_GET_DEVICE_ATTR:
4190 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
4191 case KVM_HAS_DEVICE_ATTR:
4192 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
4194 if (dev->ops->ioctl)
4195 return dev->ops->ioctl(dev, ioctl, arg);
4201 static int kvm_device_release(struct inode *inode, struct file *filp)
4203 struct kvm_device *dev = filp->private_data;
4204 struct kvm *kvm = dev->kvm;
4206 if (dev->ops->release) {
4207 mutex_lock(&kvm->lock);
4208 list_del(&dev->vm_node);
4209 dev->ops->release(dev);
4210 mutex_unlock(&kvm->lock);
4217 static const struct file_operations kvm_device_fops = {
4218 .unlocked_ioctl = kvm_device_ioctl,
4219 .release = kvm_device_release,
4220 KVM_COMPAT(kvm_device_ioctl),
4221 .mmap = kvm_device_mmap,
4224 struct kvm_device *kvm_device_from_filp(struct file *filp)
4226 if (filp->f_op != &kvm_device_fops)
4229 return filp->private_data;
4232 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
4233 #ifdef CONFIG_KVM_MPIC
4234 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
4235 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
4239 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
4241 if (type >= ARRAY_SIZE(kvm_device_ops_table))
4244 if (kvm_device_ops_table[type] != NULL)
4247 kvm_device_ops_table[type] = ops;
4251 void kvm_unregister_device_ops(u32 type)
4253 if (kvm_device_ops_table[type] != NULL)
4254 kvm_device_ops_table[type] = NULL;
4257 static int kvm_ioctl_create_device(struct kvm *kvm,
4258 struct kvm_create_device *cd)
4260 const struct kvm_device_ops *ops = NULL;
4261 struct kvm_device *dev;
4262 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
4266 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4269 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4270 ops = kvm_device_ops_table[type];
4277 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
4284 mutex_lock(&kvm->lock);
4285 ret = ops->create(dev, type);
4287 mutex_unlock(&kvm->lock);
4291 list_add(&dev->vm_node, &kvm->devices);
4292 mutex_unlock(&kvm->lock);
4298 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
4300 kvm_put_kvm_no_destroy(kvm);
4301 mutex_lock(&kvm->lock);
4302 list_del(&dev->vm_node);
4303 mutex_unlock(&kvm->lock);
4312 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4315 case KVM_CAP_USER_MEMORY:
4316 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4317 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
4318 case KVM_CAP_INTERNAL_ERROR_DATA:
4319 #ifdef CONFIG_HAVE_KVM_MSI
4320 case KVM_CAP_SIGNAL_MSI:
4322 #ifdef CONFIG_HAVE_KVM_IRQFD
4324 case KVM_CAP_IRQFD_RESAMPLE:
4326 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
4327 case KVM_CAP_CHECK_EXTENSION_VM:
4328 case KVM_CAP_ENABLE_CAP_VM:
4329 case KVM_CAP_HALT_POLL:
4331 #ifdef CONFIG_KVM_MMIO
4332 case KVM_CAP_COALESCED_MMIO:
4333 return KVM_COALESCED_MMIO_PAGE_OFFSET;
4334 case KVM_CAP_COALESCED_PIO:
4337 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4338 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4339 return KVM_DIRTY_LOG_MANUAL_CAPS;
4341 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4342 case KVM_CAP_IRQ_ROUTING:
4343 return KVM_MAX_IRQ_ROUTES;
4345 #if KVM_ADDRESS_SPACE_NUM > 1
4346 case KVM_CAP_MULTI_ADDRESS_SPACE:
4347 return KVM_ADDRESS_SPACE_NUM;
4349 case KVM_CAP_NR_MEMSLOTS:
4350 return KVM_USER_MEM_SLOTS;
4351 case KVM_CAP_DIRTY_LOG_RING:
4352 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
4353 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4357 case KVM_CAP_BINARY_STATS_FD:
4358 case KVM_CAP_SYSTEM_EVENT_DATA:
4363 return kvm_vm_ioctl_check_extension(kvm, arg);
4366 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4370 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4373 /* the size should be power of 2 */
4374 if (!size || (size & (size - 1)))
4377 /* Should be bigger to keep the reserved entries, or a page */
4378 if (size < kvm_dirty_ring_get_rsvd_entries() *
4379 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4382 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4383 sizeof(struct kvm_dirty_gfn))
4386 /* We only allow it to set once */
4387 if (kvm->dirty_ring_size)
4390 mutex_lock(&kvm->lock);
4392 if (kvm->created_vcpus) {
4393 /* We don't allow to change this value after vcpu created */
4396 kvm->dirty_ring_size = size;
4400 mutex_unlock(&kvm->lock);
4404 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4407 struct kvm_vcpu *vcpu;
4410 if (!kvm->dirty_ring_size)
4413 mutex_lock(&kvm->slots_lock);
4415 kvm_for_each_vcpu(i, vcpu, kvm)
4416 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4418 mutex_unlock(&kvm->slots_lock);
4421 kvm_flush_remote_tlbs(kvm);
4426 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4427 struct kvm_enable_cap *cap)
4432 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4433 struct kvm_enable_cap *cap)
4436 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4437 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4438 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4440 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4441 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4443 if (cap->flags || (cap->args[0] & ~allowed_options))
4445 kvm->manual_dirty_log_protect = cap->args[0];
4449 case KVM_CAP_HALT_POLL: {
4450 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4453 kvm->max_halt_poll_ns = cap->args[0];
4456 case KVM_CAP_DIRTY_LOG_RING:
4457 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4459 return kvm_vm_ioctl_enable_cap(kvm, cap);
4463 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4464 size_t size, loff_t *offset)
4466 struct kvm *kvm = file->private_data;
4468 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4469 &kvm_vm_stats_desc[0], &kvm->stat,
4470 sizeof(kvm->stat), user_buffer, size, offset);
4473 static const struct file_operations kvm_vm_stats_fops = {
4474 .read = kvm_vm_stats_read,
4475 .llseek = noop_llseek,
4478 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4483 fd = get_unused_fd_flags(O_CLOEXEC);
4487 file = anon_inode_getfile("kvm-vm-stats",
4488 &kvm_vm_stats_fops, kvm, O_RDONLY);
4491 return PTR_ERR(file);
4493 file->f_mode |= FMODE_PREAD;
4494 fd_install(fd, file);
4499 static long kvm_vm_ioctl(struct file *filp,
4500 unsigned int ioctl, unsigned long arg)
4502 struct kvm *kvm = filp->private_data;
4503 void __user *argp = (void __user *)arg;
4506 if (kvm->mm != current->mm || kvm->vm_dead)
4509 case KVM_CREATE_VCPU:
4510 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4512 case KVM_ENABLE_CAP: {
4513 struct kvm_enable_cap cap;
4516 if (copy_from_user(&cap, argp, sizeof(cap)))
4518 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4521 case KVM_SET_USER_MEMORY_REGION: {
4522 struct kvm_userspace_memory_region kvm_userspace_mem;
4525 if (copy_from_user(&kvm_userspace_mem, argp,
4526 sizeof(kvm_userspace_mem)))
4529 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4532 case KVM_GET_DIRTY_LOG: {
4533 struct kvm_dirty_log log;
4536 if (copy_from_user(&log, argp, sizeof(log)))
4538 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4541 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4542 case KVM_CLEAR_DIRTY_LOG: {
4543 struct kvm_clear_dirty_log log;
4546 if (copy_from_user(&log, argp, sizeof(log)))
4548 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4552 #ifdef CONFIG_KVM_MMIO
4553 case KVM_REGISTER_COALESCED_MMIO: {
4554 struct kvm_coalesced_mmio_zone zone;
4557 if (copy_from_user(&zone, argp, sizeof(zone)))
4559 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4562 case KVM_UNREGISTER_COALESCED_MMIO: {
4563 struct kvm_coalesced_mmio_zone zone;
4566 if (copy_from_user(&zone, argp, sizeof(zone)))
4568 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4573 struct kvm_irqfd data;
4576 if (copy_from_user(&data, argp, sizeof(data)))
4578 r = kvm_irqfd(kvm, &data);
4581 case KVM_IOEVENTFD: {
4582 struct kvm_ioeventfd data;
4585 if (copy_from_user(&data, argp, sizeof(data)))
4587 r = kvm_ioeventfd(kvm, &data);
4590 #ifdef CONFIG_HAVE_KVM_MSI
4591 case KVM_SIGNAL_MSI: {
4595 if (copy_from_user(&msi, argp, sizeof(msi)))
4597 r = kvm_send_userspace_msi(kvm, &msi);
4601 #ifdef __KVM_HAVE_IRQ_LINE
4602 case KVM_IRQ_LINE_STATUS:
4603 case KVM_IRQ_LINE: {
4604 struct kvm_irq_level irq_event;
4607 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4610 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4611 ioctl == KVM_IRQ_LINE_STATUS);
4616 if (ioctl == KVM_IRQ_LINE_STATUS) {
4617 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4625 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4626 case KVM_SET_GSI_ROUTING: {
4627 struct kvm_irq_routing routing;
4628 struct kvm_irq_routing __user *urouting;
4629 struct kvm_irq_routing_entry *entries = NULL;
4632 if (copy_from_user(&routing, argp, sizeof(routing)))
4635 if (!kvm_arch_can_set_irq_routing(kvm))
4637 if (routing.nr > KVM_MAX_IRQ_ROUTES)
4643 entries = vmemdup_user(urouting->entries,
4644 array_size(sizeof(*entries),
4646 if (IS_ERR(entries)) {
4647 r = PTR_ERR(entries);
4651 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4656 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4657 case KVM_CREATE_DEVICE: {
4658 struct kvm_create_device cd;
4661 if (copy_from_user(&cd, argp, sizeof(cd)))
4664 r = kvm_ioctl_create_device(kvm, &cd);
4669 if (copy_to_user(argp, &cd, sizeof(cd)))
4675 case KVM_CHECK_EXTENSION:
4676 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4678 case KVM_RESET_DIRTY_RINGS:
4679 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4681 case KVM_GET_STATS_FD:
4682 r = kvm_vm_ioctl_get_stats_fd(kvm);
4685 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4691 #ifdef CONFIG_KVM_COMPAT
4692 struct compat_kvm_dirty_log {
4696 compat_uptr_t dirty_bitmap; /* one bit per page */
4701 struct compat_kvm_clear_dirty_log {
4706 compat_uptr_t dirty_bitmap; /* one bit per page */
4711 static long kvm_vm_compat_ioctl(struct file *filp,
4712 unsigned int ioctl, unsigned long arg)
4714 struct kvm *kvm = filp->private_data;
4717 if (kvm->mm != current->mm || kvm->vm_dead)
4720 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4721 case KVM_CLEAR_DIRTY_LOG: {
4722 struct compat_kvm_clear_dirty_log compat_log;
4723 struct kvm_clear_dirty_log log;
4725 if (copy_from_user(&compat_log, (void __user *)arg,
4726 sizeof(compat_log)))
4728 log.slot = compat_log.slot;
4729 log.num_pages = compat_log.num_pages;
4730 log.first_page = compat_log.first_page;
4731 log.padding2 = compat_log.padding2;
4732 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4734 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4738 case KVM_GET_DIRTY_LOG: {
4739 struct compat_kvm_dirty_log compat_log;
4740 struct kvm_dirty_log log;
4742 if (copy_from_user(&compat_log, (void __user *)arg,
4743 sizeof(compat_log)))
4745 log.slot = compat_log.slot;
4746 log.padding1 = compat_log.padding1;
4747 log.padding2 = compat_log.padding2;
4748 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4750 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4754 r = kvm_vm_ioctl(filp, ioctl, arg);
4760 static const struct file_operations kvm_vm_fops = {
4761 .release = kvm_vm_release,
4762 .unlocked_ioctl = kvm_vm_ioctl,
4763 .llseek = noop_llseek,
4764 KVM_COMPAT(kvm_vm_compat_ioctl),
4767 bool file_is_kvm(struct file *file)
4769 return file && file->f_op == &kvm_vm_fops;
4771 EXPORT_SYMBOL_GPL(file_is_kvm);
4773 static int kvm_dev_ioctl_create_vm(unsigned long type)
4779 kvm = kvm_create_vm(type);
4781 return PTR_ERR(kvm);
4782 #ifdef CONFIG_KVM_MMIO
4783 r = kvm_coalesced_mmio_init(kvm);
4787 r = get_unused_fd_flags(O_CLOEXEC);
4791 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4792 "kvm-%d", task_pid_nr(current));
4794 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4802 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4803 * already set, with ->release() being kvm_vm_release(). In error
4804 * cases it will be called by the final fput(file) and will take
4805 * care of doing kvm_put_kvm(kvm).
4807 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4812 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4814 fd_install(r, file);
4822 static long kvm_dev_ioctl(struct file *filp,
4823 unsigned int ioctl, unsigned long arg)
4828 case KVM_GET_API_VERSION:
4831 r = KVM_API_VERSION;
4834 r = kvm_dev_ioctl_create_vm(arg);
4836 case KVM_CHECK_EXTENSION:
4837 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4839 case KVM_GET_VCPU_MMAP_SIZE:
4842 r = PAGE_SIZE; /* struct kvm_run */
4844 r += PAGE_SIZE; /* pio data page */
4846 #ifdef CONFIG_KVM_MMIO
4847 r += PAGE_SIZE; /* coalesced mmio ring page */
4850 case KVM_TRACE_ENABLE:
4851 case KVM_TRACE_PAUSE:
4852 case KVM_TRACE_DISABLE:
4856 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4862 static struct file_operations kvm_chardev_ops = {
4863 .unlocked_ioctl = kvm_dev_ioctl,
4864 .llseek = noop_llseek,
4865 KVM_COMPAT(kvm_dev_ioctl),
4868 static struct miscdevice kvm_dev = {
4874 static void hardware_enable_nolock(void *junk)
4876 int cpu = raw_smp_processor_id();
4879 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4882 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4884 r = kvm_arch_hardware_enable();
4887 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4888 atomic_inc(&hardware_enable_failed);
4889 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4893 static int kvm_starting_cpu(unsigned int cpu)
4895 raw_spin_lock(&kvm_count_lock);
4896 if (kvm_usage_count)
4897 hardware_enable_nolock(NULL);
4898 raw_spin_unlock(&kvm_count_lock);
4902 static void hardware_disable_nolock(void *junk)
4904 int cpu = raw_smp_processor_id();
4906 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4908 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4909 kvm_arch_hardware_disable();
4912 static int kvm_dying_cpu(unsigned int cpu)
4914 raw_spin_lock(&kvm_count_lock);
4915 if (kvm_usage_count)
4916 hardware_disable_nolock(NULL);
4917 raw_spin_unlock(&kvm_count_lock);
4921 static void hardware_disable_all_nolock(void)
4923 BUG_ON(!kvm_usage_count);
4926 if (!kvm_usage_count)
4927 on_each_cpu(hardware_disable_nolock, NULL, 1);
4930 static void hardware_disable_all(void)
4932 raw_spin_lock(&kvm_count_lock);
4933 hardware_disable_all_nolock();
4934 raw_spin_unlock(&kvm_count_lock);
4937 static int hardware_enable_all(void)
4941 raw_spin_lock(&kvm_count_lock);
4944 if (kvm_usage_count == 1) {
4945 atomic_set(&hardware_enable_failed, 0);
4946 on_each_cpu(hardware_enable_nolock, NULL, 1);
4948 if (atomic_read(&hardware_enable_failed)) {
4949 hardware_disable_all_nolock();
4954 raw_spin_unlock(&kvm_count_lock);
4959 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4963 * Some (well, at least mine) BIOSes hang on reboot if
4966 * And Intel TXT required VMX off for all cpu when system shutdown.
4968 pr_info("kvm: exiting hardware virtualization\n");
4969 kvm_rebooting = true;
4970 on_each_cpu(hardware_disable_nolock, NULL, 1);
4974 static struct notifier_block kvm_reboot_notifier = {
4975 .notifier_call = kvm_reboot,
4979 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4983 for (i = 0; i < bus->dev_count; i++) {
4984 struct kvm_io_device *pos = bus->range[i].dev;
4986 kvm_iodevice_destructor(pos);
4991 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4992 const struct kvm_io_range *r2)
4994 gpa_t addr1 = r1->addr;
4995 gpa_t addr2 = r2->addr;
5000 /* If r2->len == 0, match the exact address. If r2->len != 0,
5001 * accept any overlapping write. Any order is acceptable for
5002 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
5003 * we process all of them.
5016 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
5018 return kvm_io_bus_cmp(p1, p2);
5021 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
5022 gpa_t addr, int len)
5024 struct kvm_io_range *range, key;
5027 key = (struct kvm_io_range) {
5032 range = bsearch(&key, bus->range, bus->dev_count,
5033 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
5037 off = range - bus->range;
5039 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
5045 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5046 struct kvm_io_range *range, const void *val)
5050 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5054 while (idx < bus->dev_count &&
5055 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5056 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
5065 /* kvm_io_bus_write - called under kvm->slots_lock */
5066 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5067 int len, const void *val)
5069 struct kvm_io_bus *bus;
5070 struct kvm_io_range range;
5073 range = (struct kvm_io_range) {
5078 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5081 r = __kvm_io_bus_write(vcpu, bus, &range, val);
5082 return r < 0 ? r : 0;
5084 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
5086 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
5087 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
5088 gpa_t addr, int len, const void *val, long cookie)
5090 struct kvm_io_bus *bus;
5091 struct kvm_io_range range;
5093 range = (struct kvm_io_range) {
5098 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5102 /* First try the device referenced by cookie. */
5103 if ((cookie >= 0) && (cookie < bus->dev_count) &&
5104 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
5105 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
5110 * cookie contained garbage; fall back to search and return the
5111 * correct cookie value.
5113 return __kvm_io_bus_write(vcpu, bus, &range, val);
5116 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5117 struct kvm_io_range *range, void *val)
5121 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5125 while (idx < bus->dev_count &&
5126 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5127 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
5136 /* kvm_io_bus_read - called under kvm->slots_lock */
5137 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5140 struct kvm_io_bus *bus;
5141 struct kvm_io_range range;
5144 range = (struct kvm_io_range) {
5149 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5152 r = __kvm_io_bus_read(vcpu, bus, &range, val);
5153 return r < 0 ? r : 0;
5156 /* Caller must hold slots_lock. */
5157 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
5158 int len, struct kvm_io_device *dev)
5161 struct kvm_io_bus *new_bus, *bus;
5162 struct kvm_io_range range;
5164 bus = kvm_get_bus(kvm, bus_idx);
5168 /* exclude ioeventfd which is limited by maximum fd */
5169 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
5172 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
5173 GFP_KERNEL_ACCOUNT);
5177 range = (struct kvm_io_range) {
5183 for (i = 0; i < bus->dev_count; i++)
5184 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
5187 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
5188 new_bus->dev_count++;
5189 new_bus->range[i] = range;
5190 memcpy(new_bus->range + i + 1, bus->range + i,
5191 (bus->dev_count - i) * sizeof(struct kvm_io_range));
5192 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5193 synchronize_srcu_expedited(&kvm->srcu);
5199 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5200 struct kvm_io_device *dev)
5203 struct kvm_io_bus *new_bus, *bus;
5205 lockdep_assert_held(&kvm->slots_lock);
5207 bus = kvm_get_bus(kvm, bus_idx);
5211 for (i = 0; i < bus->dev_count; i++) {
5212 if (bus->range[i].dev == dev) {
5217 if (i == bus->dev_count)
5220 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
5221 GFP_KERNEL_ACCOUNT);
5223 memcpy(new_bus, bus, struct_size(bus, range, i));
5224 new_bus->dev_count--;
5225 memcpy(new_bus->range + i, bus->range + i + 1,
5226 flex_array_size(new_bus, range, new_bus->dev_count - i));
5229 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5230 synchronize_srcu_expedited(&kvm->srcu);
5232 /* Destroy the old bus _after_ installing the (null) bus. */
5234 pr_err("kvm: failed to shrink bus, removing it completely\n");
5235 for (j = 0; j < bus->dev_count; j++) {
5238 kvm_iodevice_destructor(bus->range[j].dev);
5243 return new_bus ? 0 : -ENOMEM;
5246 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5249 struct kvm_io_bus *bus;
5250 int dev_idx, srcu_idx;
5251 struct kvm_io_device *iodev = NULL;
5253 srcu_idx = srcu_read_lock(&kvm->srcu);
5255 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
5259 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5263 iodev = bus->range[dev_idx].dev;
5266 srcu_read_unlock(&kvm->srcu, srcu_idx);
5270 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5272 static int kvm_debugfs_open(struct inode *inode, struct file *file,
5273 int (*get)(void *, u64 *), int (*set)(void *, u64),
5276 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5280 * The debugfs files are a reference to the kvm struct which
5281 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
5282 * avoids the race between open and the removal of the debugfs directory.
5284 if (!kvm_get_kvm_safe(stat_data->kvm))
5287 if (simple_attr_open(inode, file, get,
5288 kvm_stats_debugfs_mode(stat_data->desc) & 0222
5291 kvm_put_kvm(stat_data->kvm);
5298 static int kvm_debugfs_release(struct inode *inode, struct file *file)
5300 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5303 simple_attr_release(inode, file);
5304 kvm_put_kvm(stat_data->kvm);
5309 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
5311 *val = *(u64 *)((void *)(&kvm->stat) + offset);
5316 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
5318 *(u64 *)((void *)(&kvm->stat) + offset) = 0;
5323 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
5326 struct kvm_vcpu *vcpu;
5330 kvm_for_each_vcpu(i, vcpu, kvm)
5331 *val += *(u64 *)((void *)(&vcpu->stat) + offset);
5336 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
5339 struct kvm_vcpu *vcpu;
5341 kvm_for_each_vcpu(i, vcpu, kvm)
5342 *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
5347 static int kvm_stat_data_get(void *data, u64 *val)
5350 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5352 switch (stat_data->kind) {
5354 r = kvm_get_stat_per_vm(stat_data->kvm,
5355 stat_data->desc->desc.offset, val);
5358 r = kvm_get_stat_per_vcpu(stat_data->kvm,
5359 stat_data->desc->desc.offset, val);
5366 static int kvm_stat_data_clear(void *data, u64 val)
5369 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5374 switch (stat_data->kind) {
5376 r = kvm_clear_stat_per_vm(stat_data->kvm,
5377 stat_data->desc->desc.offset);
5380 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
5381 stat_data->desc->desc.offset);
5388 static int kvm_stat_data_open(struct inode *inode, struct file *file)
5390 __simple_attr_check_format("%llu\n", 0ull);
5391 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5392 kvm_stat_data_clear, "%llu\n");
5395 static const struct file_operations stat_fops_per_vm = {
5396 .owner = THIS_MODULE,
5397 .open = kvm_stat_data_open,
5398 .release = kvm_debugfs_release,
5399 .read = simple_attr_read,
5400 .write = simple_attr_write,
5401 .llseek = no_llseek,
5404 static int vm_stat_get(void *_offset, u64 *val)
5406 unsigned offset = (long)_offset;
5411 mutex_lock(&kvm_lock);
5412 list_for_each_entry(kvm, &vm_list, vm_list) {
5413 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
5416 mutex_unlock(&kvm_lock);
5420 static int vm_stat_clear(void *_offset, u64 val)
5422 unsigned offset = (long)_offset;
5428 mutex_lock(&kvm_lock);
5429 list_for_each_entry(kvm, &vm_list, vm_list) {
5430 kvm_clear_stat_per_vm(kvm, offset);
5432 mutex_unlock(&kvm_lock);
5437 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
5438 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
5440 static int vcpu_stat_get(void *_offset, u64 *val)
5442 unsigned offset = (long)_offset;
5447 mutex_lock(&kvm_lock);
5448 list_for_each_entry(kvm, &vm_list, vm_list) {
5449 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
5452 mutex_unlock(&kvm_lock);
5456 static int vcpu_stat_clear(void *_offset, u64 val)
5458 unsigned offset = (long)_offset;
5464 mutex_lock(&kvm_lock);
5465 list_for_each_entry(kvm, &vm_list, vm_list) {
5466 kvm_clear_stat_per_vcpu(kvm, offset);
5468 mutex_unlock(&kvm_lock);
5473 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5475 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
5477 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5479 struct kobj_uevent_env *env;
5480 unsigned long long created, active;
5482 if (!kvm_dev.this_device || !kvm)
5485 mutex_lock(&kvm_lock);
5486 if (type == KVM_EVENT_CREATE_VM) {
5487 kvm_createvm_count++;
5489 } else if (type == KVM_EVENT_DESTROY_VM) {
5492 created = kvm_createvm_count;
5493 active = kvm_active_vms;
5494 mutex_unlock(&kvm_lock);
5496 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
5500 add_uevent_var(env, "CREATED=%llu", created);
5501 add_uevent_var(env, "COUNT=%llu", active);
5503 if (type == KVM_EVENT_CREATE_VM) {
5504 add_uevent_var(env, "EVENT=create");
5505 kvm->userspace_pid = task_pid_nr(current);
5506 } else if (type == KVM_EVENT_DESTROY_VM) {
5507 add_uevent_var(env, "EVENT=destroy");
5509 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5511 if (!IS_ERR(kvm->debugfs_dentry)) {
5512 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5515 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5517 add_uevent_var(env, "STATS_PATH=%s", tmp);
5521 /* no need for checks, since we are adding at most only 5 keys */
5522 env->envp[env->envp_idx++] = NULL;
5523 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5527 static void kvm_init_debug(void)
5529 const struct file_operations *fops;
5530 const struct _kvm_stats_desc *pdesc;
5533 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5535 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5536 pdesc = &kvm_vm_stats_desc[i];
5537 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5538 fops = &vm_stat_fops;
5540 fops = &vm_stat_readonly_fops;
5541 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5543 (void *)(long)pdesc->desc.offset, fops);
5546 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5547 pdesc = &kvm_vcpu_stats_desc[i];
5548 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5549 fops = &vcpu_stat_fops;
5551 fops = &vcpu_stat_readonly_fops;
5552 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5554 (void *)(long)pdesc->desc.offset, fops);
5558 static int kvm_suspend(void)
5560 if (kvm_usage_count)
5561 hardware_disable_nolock(NULL);
5565 static void kvm_resume(void)
5567 if (kvm_usage_count) {
5568 lockdep_assert_not_held(&kvm_count_lock);
5569 hardware_enable_nolock(NULL);
5573 static struct syscore_ops kvm_syscore_ops = {
5574 .suspend = kvm_suspend,
5575 .resume = kvm_resume,
5579 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5581 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5584 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5586 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5588 WRITE_ONCE(vcpu->preempted, false);
5589 WRITE_ONCE(vcpu->ready, false);
5591 __this_cpu_write(kvm_running_vcpu, vcpu);
5592 kvm_arch_sched_in(vcpu, cpu);
5593 kvm_arch_vcpu_load(vcpu, cpu);
5596 static void kvm_sched_out(struct preempt_notifier *pn,
5597 struct task_struct *next)
5599 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5601 if (current->on_rq) {
5602 WRITE_ONCE(vcpu->preempted, true);
5603 WRITE_ONCE(vcpu->ready, true);
5605 kvm_arch_vcpu_put(vcpu);
5606 __this_cpu_write(kvm_running_vcpu, NULL);
5610 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5612 * We can disable preemption locally around accessing the per-CPU variable,
5613 * and use the resolved vcpu pointer after enabling preemption again,
5614 * because even if the current thread is migrated to another CPU, reading
5615 * the per-CPU value later will give us the same value as we update the
5616 * per-CPU variable in the preempt notifier handlers.
5618 struct kvm_vcpu *kvm_get_running_vcpu(void)
5620 struct kvm_vcpu *vcpu;
5623 vcpu = __this_cpu_read(kvm_running_vcpu);
5628 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5631 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5633 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5635 return &kvm_running_vcpu;
5638 #ifdef CONFIG_GUEST_PERF_EVENTS
5639 static unsigned int kvm_guest_state(void)
5641 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5644 if (!kvm_arch_pmi_in_guest(vcpu))
5647 state = PERF_GUEST_ACTIVE;
5648 if (!kvm_arch_vcpu_in_kernel(vcpu))
5649 state |= PERF_GUEST_USER;
5654 static unsigned long kvm_guest_get_ip(void)
5656 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5658 /* Retrieving the IP must be guarded by a call to kvm_guest_state(). */
5659 if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu)))
5662 return kvm_arch_vcpu_get_ip(vcpu);
5665 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5666 .state = kvm_guest_state,
5667 .get_ip = kvm_guest_get_ip,
5668 .handle_intel_pt_intr = NULL,
5671 void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void))
5673 kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler;
5674 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5676 void kvm_unregister_perf_callbacks(void)
5678 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5682 struct kvm_cpu_compat_check {
5687 static void check_processor_compat(void *data)
5689 struct kvm_cpu_compat_check *c = data;
5691 *c->ret = kvm_arch_check_processor_compat(c->opaque);
5694 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5695 struct module *module)
5697 struct kvm_cpu_compat_check c;
5701 r = kvm_arch_init(opaque);
5706 * kvm_arch_init makes sure there's at most one caller
5707 * for architectures that support multiple implementations,
5708 * like intel and amd on x86.
5709 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5710 * conflicts in case kvm is already setup for another implementation.
5712 r = kvm_irqfd_init();
5716 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5721 r = kvm_arch_hardware_setup(opaque);
5727 for_each_online_cpu(cpu) {
5728 smp_call_function_single(cpu, check_processor_compat, &c, 1);
5733 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5734 kvm_starting_cpu, kvm_dying_cpu);
5737 register_reboot_notifier(&kvm_reboot_notifier);
5739 /* A kmem cache lets us meet the alignment requirements of fx_save. */
5741 vcpu_align = __alignof__(struct kvm_vcpu);
5743 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5745 offsetof(struct kvm_vcpu, arch),
5746 offsetofend(struct kvm_vcpu, stats_id)
5747 - offsetof(struct kvm_vcpu, arch),
5749 if (!kvm_vcpu_cache) {
5754 for_each_possible_cpu(cpu) {
5755 if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu),
5756 GFP_KERNEL, cpu_to_node(cpu))) {
5762 r = kvm_async_pf_init();
5766 kvm_chardev_ops.owner = module;
5768 r = misc_register(&kvm_dev);
5770 pr_err("kvm: misc device register failed\n");
5774 register_syscore_ops(&kvm_syscore_ops);
5776 kvm_preempt_ops.sched_in = kvm_sched_in;
5777 kvm_preempt_ops.sched_out = kvm_sched_out;
5781 r = kvm_vfio_ops_init();
5787 kvm_async_pf_deinit();
5789 for_each_possible_cpu(cpu)
5790 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5792 kmem_cache_destroy(kvm_vcpu_cache);
5794 unregister_reboot_notifier(&kvm_reboot_notifier);
5795 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5797 kvm_arch_hardware_unsetup();
5799 free_cpumask_var(cpus_hardware_enabled);
5807 EXPORT_SYMBOL_GPL(kvm_init);
5813 debugfs_remove_recursive(kvm_debugfs_dir);
5814 misc_deregister(&kvm_dev);
5815 for_each_possible_cpu(cpu)
5816 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5817 kmem_cache_destroy(kvm_vcpu_cache);
5818 kvm_async_pf_deinit();
5819 unregister_syscore_ops(&kvm_syscore_ops);
5820 unregister_reboot_notifier(&kvm_reboot_notifier);
5821 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5822 on_each_cpu(hardware_disable_nolock, NULL, 1);
5823 kvm_arch_hardware_unsetup();
5826 free_cpumask_var(cpus_hardware_enabled);
5827 kvm_vfio_ops_exit();
5829 EXPORT_SYMBOL_GPL(kvm_exit);
5831 struct kvm_vm_worker_thread_context {
5833 struct task_struct *parent;
5834 struct completion init_done;
5835 kvm_vm_thread_fn_t thread_fn;
5840 static int kvm_vm_worker_thread(void *context)
5843 * The init_context is allocated on the stack of the parent thread, so
5844 * we have to locally copy anything that is needed beyond initialization
5846 struct kvm_vm_worker_thread_context *init_context = context;
5847 struct task_struct *parent;
5848 struct kvm *kvm = init_context->kvm;
5849 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5850 uintptr_t data = init_context->data;
5853 err = kthread_park(current);
5854 /* kthread_park(current) is never supposed to return an error */
5859 err = cgroup_attach_task_all(init_context->parent, current);
5861 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5866 set_user_nice(current, task_nice(init_context->parent));
5869 init_context->err = err;
5870 complete(&init_context->init_done);
5871 init_context = NULL;
5876 /* Wait to be woken up by the spawner before proceeding. */
5879 if (!kthread_should_stop())
5880 err = thread_fn(kvm, data);
5884 * Move kthread back to its original cgroup to prevent it lingering in
5885 * the cgroup of the VM process, after the latter finishes its
5888 * kthread_stop() waits on the 'exited' completion condition which is
5889 * set in exit_mm(), via mm_release(), in do_exit(). However, the
5890 * kthread is removed from the cgroup in the cgroup_exit() which is
5891 * called after the exit_mm(). This causes the kthread_stop() to return
5892 * before the kthread actually quits the cgroup.
5895 parent = rcu_dereference(current->real_parent);
5896 get_task_struct(parent);
5898 cgroup_attach_task_all(parent, current);
5899 put_task_struct(parent);
5904 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5905 uintptr_t data, const char *name,
5906 struct task_struct **thread_ptr)
5908 struct kvm_vm_worker_thread_context init_context = {};
5909 struct task_struct *thread;
5912 init_context.kvm = kvm;
5913 init_context.parent = current;
5914 init_context.thread_fn = thread_fn;
5915 init_context.data = data;
5916 init_completion(&init_context.init_done);
5918 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5919 "%s-%d", name, task_pid_nr(current));
5921 return PTR_ERR(thread);
5923 /* kthread_run is never supposed to return NULL */
5924 WARN_ON(thread == NULL);
5926 wait_for_completion(&init_context.init_done);
5928 if (!init_context.err)
5929 *thread_ptr = thread;
5931 return init_context.err;