1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <kvm/iodev.h>
18 #include <linux/kvm_host.h>
19 #include <linux/kvm.h>
20 #include <linux/module.h>
21 #include <linux/errno.h>
22 #include <linux/percpu.h>
24 #include <linux/miscdevice.h>
25 #include <linux/vmalloc.h>
26 #include <linux/reboot.h>
27 #include <linux/debugfs.h>
28 #include <linux/highmem.h>
29 #include <linux/file.h>
30 #include <linux/syscore_ops.h>
31 #include <linux/cpu.h>
32 #include <linux/sched/signal.h>
33 #include <linux/sched/mm.h>
34 #include <linux/sched/stat.h>
35 #include <linux/cpumask.h>
36 #include <linux/smp.h>
37 #include <linux/anon_inodes.h>
38 #include <linux/profile.h>
39 #include <linux/kvm_para.h>
40 #include <linux/pagemap.h>
41 #include <linux/mman.h>
42 #include <linux/swap.h>
43 #include <linux/bitops.h>
44 #include <linux/spinlock.h>
45 #include <linux/compat.h>
46 #include <linux/srcu.h>
47 #include <linux/hugetlb.h>
48 #include <linux/slab.h>
49 #include <linux/sort.h>
50 #include <linux/bsearch.h>
52 #include <linux/lockdep.h>
53 #include <linux/kthread.h>
54 #include <linux/suspend.h>
56 #include <asm/processor.h>
57 #include <asm/ioctl.h>
58 #include <linux/uaccess.h>
60 #include "coalesced_mmio.h"
65 #define CREATE_TRACE_POINTS
66 #include <trace/events/kvm.h>
68 #include <linux/kvm_dirty_ring.h>
70 /* Worst case buffer size needed for holding an integer. */
71 #define ITOA_MAX_LEN 12
73 MODULE_AUTHOR("Qumranet");
74 MODULE_LICENSE("GPL");
76 /* Architectures should define their poll value according to the halt latency */
77 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
78 module_param(halt_poll_ns, uint, 0644);
79 EXPORT_SYMBOL_GPL(halt_poll_ns);
81 /* Default doubles per-vcpu halt_poll_ns. */
82 unsigned int halt_poll_ns_grow = 2;
83 module_param(halt_poll_ns_grow, uint, 0644);
84 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
86 /* The start value to grow halt_poll_ns from */
87 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
88 module_param(halt_poll_ns_grow_start, uint, 0644);
89 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
91 /* Default resets per-vcpu halt_poll_ns . */
92 unsigned int halt_poll_ns_shrink;
93 module_param(halt_poll_ns_shrink, uint, 0644);
94 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
99 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
102 DEFINE_MUTEX(kvm_lock);
103 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
106 static cpumask_var_t cpus_hardware_enabled;
107 static int kvm_usage_count;
108 static atomic_t hardware_enable_failed;
110 static struct kmem_cache *kvm_vcpu_cache;
112 static __read_mostly struct preempt_ops kvm_preempt_ops;
113 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
115 struct dentry *kvm_debugfs_dir;
116 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
118 static const struct file_operations stat_fops_per_vm;
120 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
122 #ifdef CONFIG_KVM_COMPAT
123 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
125 #define KVM_COMPAT(c) .compat_ioctl = (c)
128 * For architectures that don't implement a compat infrastructure,
129 * adopt a double line of defense:
130 * - Prevent a compat task from opening /dev/kvm
131 * - If the open has been done by a 64bit task, and the KVM fd
132 * passed to a compat task, let the ioctls fail.
134 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
135 unsigned long arg) { return -EINVAL; }
137 static int kvm_no_compat_open(struct inode *inode, struct file *file)
139 return is_compat_task() ? -ENODEV : 0;
141 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
142 .open = kvm_no_compat_open
144 static int hardware_enable_all(void);
145 static void hardware_disable_all(void);
147 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
149 __visible bool kvm_rebooting;
150 EXPORT_SYMBOL_GPL(kvm_rebooting);
152 #define KVM_EVENT_CREATE_VM 0
153 #define KVM_EVENT_DESTROY_VM 1
154 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
155 static unsigned long long kvm_createvm_count;
156 static unsigned long long kvm_active_vms;
158 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
159 unsigned long start, unsigned long end)
163 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
166 * The metadata used by is_zone_device_page() to determine whether or
167 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
168 * the device has been pinned, e.g. by get_user_pages(). WARN if the
169 * page_count() is zero to help detect bad usage of this helper.
171 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
174 return is_zone_device_page(pfn_to_page(pfn));
177 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
180 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
181 * perspective they are "normal" pages, albeit with slightly different
185 return PageReserved(pfn_to_page(pfn)) &&
187 !kvm_is_zone_device_pfn(pfn);
193 * Switches to specified vcpu, until a matching vcpu_put()
195 void vcpu_load(struct kvm_vcpu *vcpu)
199 __this_cpu_write(kvm_running_vcpu, vcpu);
200 preempt_notifier_register(&vcpu->preempt_notifier);
201 kvm_arch_vcpu_load(vcpu, cpu);
204 EXPORT_SYMBOL_GPL(vcpu_load);
206 void vcpu_put(struct kvm_vcpu *vcpu)
209 kvm_arch_vcpu_put(vcpu);
210 preempt_notifier_unregister(&vcpu->preempt_notifier);
211 __this_cpu_write(kvm_running_vcpu, NULL);
214 EXPORT_SYMBOL_GPL(vcpu_put);
216 /* TODO: merge with kvm_arch_vcpu_should_kick */
217 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
219 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
222 * We need to wait for the VCPU to reenable interrupts and get out of
223 * READING_SHADOW_PAGE_TABLES mode.
225 if (req & KVM_REQUEST_WAIT)
226 return mode != OUTSIDE_GUEST_MODE;
229 * Need to kick a running VCPU, but otherwise there is nothing to do.
231 return mode == IN_GUEST_MODE;
234 static void ack_flush(void *_completed)
238 static inline bool kvm_kick_many_cpus(cpumask_var_t tmp, bool wait)
240 const struct cpumask *cpus;
242 if (likely(cpumask_available(tmp)))
245 cpus = cpu_online_mask;
247 if (cpumask_empty(cpus))
250 smp_call_function_many(cpus, ack_flush, NULL, wait);
254 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
255 struct kvm_vcpu *except,
256 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
259 struct kvm_vcpu *vcpu;
264 kvm_for_each_vcpu(i, vcpu, kvm) {
265 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
269 kvm_make_request(req, vcpu);
271 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
275 * tmp can be "unavailable" if cpumasks are allocated off stack
276 * as allocation of the mask is deliberately not fatal and is
277 * handled by falling back to kicking all online CPUs.
279 if (!cpumask_available(tmp))
283 * Note, the vCPU could get migrated to a different pCPU at any
284 * point after kvm_request_needs_ipi(), which could result in
285 * sending an IPI to the previous pCPU. But, that's ok because
286 * the purpose of the IPI is to ensure the vCPU returns to
287 * OUTSIDE_GUEST_MODE, which is satisfied if the vCPU migrates.
288 * Entering READING_SHADOW_PAGE_TABLES after this point is also
289 * ok, as the requirement is only that KVM wait for vCPUs that
290 * were reading SPTEs _before_ any changes were finalized. See
291 * kvm_vcpu_kick() for more details on handling requests.
293 if (kvm_request_needs_ipi(vcpu, req)) {
294 cpu = READ_ONCE(vcpu->cpu);
295 if (cpu != -1 && cpu != me)
296 __cpumask_set_cpu(cpu, tmp);
300 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
306 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
307 struct kvm_vcpu *except)
312 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
314 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
316 free_cpumask_var(cpus);
320 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
322 return kvm_make_all_cpus_request_except(kvm, req, NULL);
324 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
326 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
327 void kvm_flush_remote_tlbs(struct kvm *kvm)
329 ++kvm->stat.generic.remote_tlb_flush_requests;
332 * We want to publish modifications to the page tables before reading
333 * mode. Pairs with a memory barrier in arch-specific code.
334 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
335 * and smp_mb in walk_shadow_page_lockless_begin/end.
336 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
338 * There is already an smp_mb__after_atomic() before
339 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
342 if (!kvm_arch_flush_remote_tlb(kvm)
343 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
344 ++kvm->stat.generic.remote_tlb_flush;
346 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
349 void kvm_reload_remote_mmus(struct kvm *kvm)
351 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
354 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
355 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
358 gfp_flags |= mc->gfp_zero;
361 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
363 return (void *)__get_free_page(gfp_flags);
366 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
370 if (mc->nobjs >= min)
372 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
373 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
375 return mc->nobjs >= min ? 0 : -ENOMEM;
376 mc->objects[mc->nobjs++] = obj;
381 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
386 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
390 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
392 free_page((unsigned long)mc->objects[--mc->nobjs]);
396 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
400 if (WARN_ON(!mc->nobjs))
401 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
403 p = mc->objects[--mc->nobjs];
409 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
411 mutex_init(&vcpu->mutex);
416 rcuwait_init(&vcpu->wait);
417 kvm_async_pf_vcpu_init(vcpu);
420 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
422 kvm_vcpu_set_in_spin_loop(vcpu, false);
423 kvm_vcpu_set_dy_eligible(vcpu, false);
424 vcpu->preempted = false;
426 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
427 vcpu->last_used_slot = 0;
430 void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
432 kvm_dirty_ring_free(&vcpu->dirty_ring);
433 kvm_arch_vcpu_destroy(vcpu);
436 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
437 * the vcpu->pid pointer, and at destruction time all file descriptors
440 put_pid(rcu_dereference_protected(vcpu->pid, 1));
442 free_page((unsigned long)vcpu->run);
443 kmem_cache_free(kvm_vcpu_cache, vcpu);
445 EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
447 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
448 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
450 return container_of(mn, struct kvm, mmu_notifier);
453 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
454 struct mm_struct *mm,
455 unsigned long start, unsigned long end)
457 struct kvm *kvm = mmu_notifier_to_kvm(mn);
460 idx = srcu_read_lock(&kvm->srcu);
461 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
462 srcu_read_unlock(&kvm->srcu, idx);
465 typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
467 typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
470 struct kvm_hva_range {
474 hva_handler_t handler;
475 on_lock_fn_t on_lock;
481 * Use a dedicated stub instead of NULL to indicate that there is no callback
482 * function/handler. The compiler technically can't guarantee that a real
483 * function will have a non-zero address, and so it will generate code to
484 * check for !NULL, whereas comparing against a stub will be elided at compile
485 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
487 static void kvm_null_fn(void)
491 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
493 static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
494 const struct kvm_hva_range *range)
496 bool ret = false, locked = false;
497 struct kvm_gfn_range gfn_range;
498 struct kvm_memory_slot *slot;
499 struct kvm_memslots *slots;
502 /* A null handler is allowed if and only if on_lock() is provided. */
503 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
504 IS_KVM_NULL_FN(range->handler)))
507 idx = srcu_read_lock(&kvm->srcu);
509 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
510 slots = __kvm_memslots(kvm, i);
511 kvm_for_each_memslot(slot, slots) {
512 unsigned long hva_start, hva_end;
514 hva_start = max(range->start, slot->userspace_addr);
515 hva_end = min(range->end, slot->userspace_addr +
516 (slot->npages << PAGE_SHIFT));
517 if (hva_start >= hva_end)
521 * To optimize for the likely case where the address
522 * range is covered by zero or one memslots, don't
523 * bother making these conditional (to avoid writes on
524 * the second or later invocation of the handler).
526 gfn_range.pte = range->pte;
527 gfn_range.may_block = range->may_block;
530 * {gfn(page) | page intersects with [hva_start, hva_end)} =
531 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
533 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
534 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
535 gfn_range.slot = slot;
540 if (!IS_KVM_NULL_FN(range->on_lock))
541 range->on_lock(kvm, range->start, range->end);
542 if (IS_KVM_NULL_FN(range->handler))
545 ret |= range->handler(kvm, &gfn_range);
549 if (range->flush_on_ret && ret)
550 kvm_flush_remote_tlbs(kvm);
555 srcu_read_unlock(&kvm->srcu, idx);
557 /* The notifiers are averse to booleans. :-( */
561 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
565 hva_handler_t handler)
567 struct kvm *kvm = mmu_notifier_to_kvm(mn);
568 const struct kvm_hva_range range = {
573 .on_lock = (void *)kvm_null_fn,
574 .flush_on_ret = true,
578 return __kvm_handle_hva_range(kvm, &range);
581 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
584 hva_handler_t handler)
586 struct kvm *kvm = mmu_notifier_to_kvm(mn);
587 const struct kvm_hva_range range = {
592 .on_lock = (void *)kvm_null_fn,
593 .flush_on_ret = false,
597 return __kvm_handle_hva_range(kvm, &range);
599 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
600 struct mm_struct *mm,
601 unsigned long address,
604 struct kvm *kvm = mmu_notifier_to_kvm(mn);
606 trace_kvm_set_spte_hva(address);
609 * .change_pte() must be surrounded by .invalidate_range_{start,end}().
610 * If mmu_notifier_count is zero, then no in-progress invalidations,
611 * including this one, found a relevant memslot at start(); rechecking
612 * memslots here is unnecessary. Note, a false positive (count elevated
613 * by a different invalidation) is sub-optimal but functionally ok.
615 WARN_ON_ONCE(!READ_ONCE(kvm->mn_active_invalidate_count));
616 if (!READ_ONCE(kvm->mmu_notifier_count))
619 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
622 void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
626 * The count increase must become visible at unlock time as no
627 * spte can be established without taking the mmu_lock and
628 * count is also read inside the mmu_lock critical section.
630 kvm->mmu_notifier_count++;
631 if (likely(kvm->mmu_notifier_count == 1)) {
632 kvm->mmu_notifier_range_start = start;
633 kvm->mmu_notifier_range_end = end;
636 * Fully tracking multiple concurrent ranges has dimishing
637 * returns. Keep things simple and just find the minimal range
638 * which includes the current and new ranges. As there won't be
639 * enough information to subtract a range after its invalidate
640 * completes, any ranges invalidated concurrently will
641 * accumulate and persist until all outstanding invalidates
644 kvm->mmu_notifier_range_start =
645 min(kvm->mmu_notifier_range_start, start);
646 kvm->mmu_notifier_range_end =
647 max(kvm->mmu_notifier_range_end, end);
651 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
652 const struct mmu_notifier_range *range)
654 struct kvm *kvm = mmu_notifier_to_kvm(mn);
655 const struct kvm_hva_range hva_range = {
656 .start = range->start,
659 .handler = kvm_unmap_gfn_range,
660 .on_lock = kvm_inc_notifier_count,
661 .flush_on_ret = true,
662 .may_block = mmu_notifier_range_blockable(range),
665 trace_kvm_unmap_hva_range(range->start, range->end);
668 * Prevent memslot modification between range_start() and range_end()
669 * so that conditionally locking provides the same result in both
670 * functions. Without that guarantee, the mmu_notifier_count
671 * adjustments will be imbalanced.
673 * Pairs with the decrement in range_end().
675 spin_lock(&kvm->mn_invalidate_lock);
676 kvm->mn_active_invalidate_count++;
677 spin_unlock(&kvm->mn_invalidate_lock);
679 __kvm_handle_hva_range(kvm, &hva_range);
684 void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
688 * This sequence increase will notify the kvm page fault that
689 * the page that is going to be mapped in the spte could have
692 kvm->mmu_notifier_seq++;
695 * The above sequence increase must be visible before the
696 * below count decrease, which is ensured by the smp_wmb above
697 * in conjunction with the smp_rmb in mmu_notifier_retry().
699 kvm->mmu_notifier_count--;
702 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
703 const struct mmu_notifier_range *range)
705 struct kvm *kvm = mmu_notifier_to_kvm(mn);
706 const struct kvm_hva_range hva_range = {
707 .start = range->start,
710 .handler = (void *)kvm_null_fn,
711 .on_lock = kvm_dec_notifier_count,
712 .flush_on_ret = false,
713 .may_block = mmu_notifier_range_blockable(range),
717 __kvm_handle_hva_range(kvm, &hva_range);
719 /* Pairs with the increment in range_start(). */
720 spin_lock(&kvm->mn_invalidate_lock);
721 wake = (--kvm->mn_active_invalidate_count == 0);
722 spin_unlock(&kvm->mn_invalidate_lock);
725 * There can only be one waiter, since the wait happens under
729 rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
731 BUG_ON(kvm->mmu_notifier_count < 0);
734 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
735 struct mm_struct *mm,
739 trace_kvm_age_hva(start, end);
741 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
744 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
745 struct mm_struct *mm,
749 trace_kvm_age_hva(start, end);
752 * Even though we do not flush TLB, this will still adversely
753 * affect performance on pre-Haswell Intel EPT, where there is
754 * no EPT Access Bit to clear so that we have to tear down EPT
755 * tables instead. If we find this unacceptable, we can always
756 * add a parameter to kvm_age_hva so that it effectively doesn't
757 * do anything on clear_young.
759 * Also note that currently we never issue secondary TLB flushes
760 * from clear_young, leaving this job up to the regular system
761 * cadence. If we find this inaccurate, we might come up with a
762 * more sophisticated heuristic later.
764 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
767 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
768 struct mm_struct *mm,
769 unsigned long address)
771 trace_kvm_test_age_hva(address);
773 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
777 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
778 struct mm_struct *mm)
780 struct kvm *kvm = mmu_notifier_to_kvm(mn);
783 idx = srcu_read_lock(&kvm->srcu);
784 kvm_arch_flush_shadow_all(kvm);
785 srcu_read_unlock(&kvm->srcu, idx);
788 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
789 .invalidate_range = kvm_mmu_notifier_invalidate_range,
790 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
791 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
792 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
793 .clear_young = kvm_mmu_notifier_clear_young,
794 .test_young = kvm_mmu_notifier_test_young,
795 .change_pte = kvm_mmu_notifier_change_pte,
796 .release = kvm_mmu_notifier_release,
799 static int kvm_init_mmu_notifier(struct kvm *kvm)
801 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
802 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
805 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
807 static int kvm_init_mmu_notifier(struct kvm *kvm)
812 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
814 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
815 static int kvm_pm_notifier_call(struct notifier_block *bl,
819 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
821 return kvm_arch_pm_notifier(kvm, state);
824 static void kvm_init_pm_notifier(struct kvm *kvm)
826 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
827 /* Suspend KVM before we suspend ftrace, RCU, etc. */
828 kvm->pm_notifier.priority = INT_MAX;
829 register_pm_notifier(&kvm->pm_notifier);
832 static void kvm_destroy_pm_notifier(struct kvm *kvm)
834 unregister_pm_notifier(&kvm->pm_notifier);
836 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
837 static void kvm_init_pm_notifier(struct kvm *kvm)
841 static void kvm_destroy_pm_notifier(struct kvm *kvm)
844 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
846 static struct kvm_memslots *kvm_alloc_memslots(void)
849 struct kvm_memslots *slots;
851 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
855 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
856 slots->id_to_index[i] = -1;
861 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
863 if (!memslot->dirty_bitmap)
866 kvfree(memslot->dirty_bitmap);
867 memslot->dirty_bitmap = NULL;
870 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
872 kvm_destroy_dirty_bitmap(slot);
874 kvm_arch_free_memslot(kvm, slot);
880 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
882 struct kvm_memory_slot *memslot;
887 kvm_for_each_memslot(memslot, slots)
888 kvm_free_memslot(kvm, memslot);
893 static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
895 switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
896 case KVM_STATS_TYPE_INSTANT:
898 case KVM_STATS_TYPE_CUMULATIVE:
899 case KVM_STATS_TYPE_PEAK:
906 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
909 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
910 kvm_vcpu_stats_header.num_desc;
912 if (!kvm->debugfs_dentry)
915 debugfs_remove_recursive(kvm->debugfs_dentry);
917 if (kvm->debugfs_stat_data) {
918 for (i = 0; i < kvm_debugfs_num_entries; i++)
919 kfree(kvm->debugfs_stat_data[i]);
920 kfree(kvm->debugfs_stat_data);
924 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
926 static DEFINE_MUTEX(kvm_debugfs_lock);
928 char dir_name[ITOA_MAX_LEN * 2];
929 struct kvm_stat_data *stat_data;
930 const struct _kvm_stats_desc *pdesc;
932 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
933 kvm_vcpu_stats_header.num_desc;
935 if (!debugfs_initialized())
938 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
939 mutex_lock(&kvm_debugfs_lock);
940 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
942 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
944 mutex_unlock(&kvm_debugfs_lock);
947 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
948 mutex_unlock(&kvm_debugfs_lock);
952 kvm->debugfs_dentry = dent;
953 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
954 sizeof(*kvm->debugfs_stat_data),
956 if (!kvm->debugfs_stat_data)
959 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
960 pdesc = &kvm_vm_stats_desc[i];
961 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
965 stat_data->kvm = kvm;
966 stat_data->desc = pdesc;
967 stat_data->kind = KVM_STAT_VM;
968 kvm->debugfs_stat_data[i] = stat_data;
969 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
970 kvm->debugfs_dentry, stat_data,
974 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
975 pdesc = &kvm_vcpu_stats_desc[i];
976 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
980 stat_data->kvm = kvm;
981 stat_data->desc = pdesc;
982 stat_data->kind = KVM_STAT_VCPU;
983 kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
984 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
985 kvm->debugfs_dentry, stat_data,
989 ret = kvm_arch_create_vm_debugfs(kvm);
991 kvm_destroy_vm_debugfs(kvm);
999 * Called after the VM is otherwise initialized, but just before adding it to
1002 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
1008 * Called just after removing the VM from the vm_list, but before doing any
1009 * other destruction.
1011 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
1016 * Called after per-vm debugfs created. When called kvm->debugfs_dentry should
1017 * be setup already, so we can create arch-specific debugfs entries under it.
1018 * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1019 * a per-arch destroy interface is not needed.
1021 int __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1026 static struct kvm *kvm_create_vm(unsigned long type)
1028 struct kvm *kvm = kvm_arch_alloc_vm();
1033 return ERR_PTR(-ENOMEM);
1035 KVM_MMU_LOCK_INIT(kvm);
1036 mmgrab(current->mm);
1037 kvm->mm = current->mm;
1038 kvm_eventfd_init(kvm);
1039 mutex_init(&kvm->lock);
1040 mutex_init(&kvm->irq_lock);
1041 mutex_init(&kvm->slots_lock);
1042 mutex_init(&kvm->slots_arch_lock);
1043 spin_lock_init(&kvm->mn_invalidate_lock);
1044 rcuwait_init(&kvm->mn_memslots_update_rcuwait);
1046 INIT_LIST_HEAD(&kvm->devices);
1048 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1050 if (init_srcu_struct(&kvm->srcu))
1051 goto out_err_no_srcu;
1052 if (init_srcu_struct(&kvm->irq_srcu))
1053 goto out_err_no_irq_srcu;
1055 refcount_set(&kvm->users_count, 1);
1056 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1057 struct kvm_memslots *slots = kvm_alloc_memslots();
1060 goto out_err_no_arch_destroy_vm;
1061 /* Generations must be different for each address space. */
1062 slots->generation = i;
1063 rcu_assign_pointer(kvm->memslots[i], slots);
1066 for (i = 0; i < KVM_NR_BUSES; i++) {
1067 rcu_assign_pointer(kvm->buses[i],
1068 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
1070 goto out_err_no_arch_destroy_vm;
1073 kvm->max_halt_poll_ns = halt_poll_ns;
1075 r = kvm_arch_init_vm(kvm, type);
1077 goto out_err_no_arch_destroy_vm;
1079 r = hardware_enable_all();
1081 goto out_err_no_disable;
1083 #ifdef CONFIG_HAVE_KVM_IRQFD
1084 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
1087 r = kvm_init_mmu_notifier(kvm);
1089 goto out_err_no_mmu_notifier;
1091 r = kvm_arch_post_init_vm(kvm);
1095 mutex_lock(&kvm_lock);
1096 list_add(&kvm->vm_list, &vm_list);
1097 mutex_unlock(&kvm_lock);
1099 preempt_notifier_inc();
1100 kvm_init_pm_notifier(kvm);
1105 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1106 if (kvm->mmu_notifier.ops)
1107 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1109 out_err_no_mmu_notifier:
1110 hardware_disable_all();
1112 kvm_arch_destroy_vm(kvm);
1113 out_err_no_arch_destroy_vm:
1114 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
1115 for (i = 0; i < KVM_NR_BUSES; i++)
1116 kfree(kvm_get_bus(kvm, i));
1117 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
1118 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
1119 cleanup_srcu_struct(&kvm->irq_srcu);
1120 out_err_no_irq_srcu:
1121 cleanup_srcu_struct(&kvm->srcu);
1123 kvm_arch_free_vm(kvm);
1124 mmdrop(current->mm);
1128 static void kvm_destroy_devices(struct kvm *kvm)
1130 struct kvm_device *dev, *tmp;
1133 * We do not need to take the kvm->lock here, because nobody else
1134 * has a reference to the struct kvm at this point and therefore
1135 * cannot access the devices list anyhow.
1137 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1138 list_del(&dev->vm_node);
1139 dev->ops->destroy(dev);
1143 static void kvm_destroy_vm(struct kvm *kvm)
1146 struct mm_struct *mm = kvm->mm;
1148 kvm_destroy_pm_notifier(kvm);
1149 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1150 kvm_destroy_vm_debugfs(kvm);
1151 kvm_arch_sync_events(kvm);
1152 mutex_lock(&kvm_lock);
1153 list_del(&kvm->vm_list);
1154 mutex_unlock(&kvm_lock);
1155 kvm_arch_pre_destroy_vm(kvm);
1157 kvm_free_irq_routing(kvm);
1158 for (i = 0; i < KVM_NR_BUSES; i++) {
1159 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1162 kvm_io_bus_destroy(bus);
1163 kvm->buses[i] = NULL;
1165 kvm_coalesced_mmio_free(kvm);
1166 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1167 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1169 * At this point, pending calls to invalidate_range_start()
1170 * have completed but no more MMU notifiers will run, so
1171 * mn_active_invalidate_count may remain unbalanced.
1172 * No threads can be waiting in install_new_memslots as the
1173 * last reference on KVM has been dropped, but freeing
1174 * memslots would deadlock without this manual intervention.
1176 WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1177 kvm->mn_active_invalidate_count = 0;
1179 kvm_arch_flush_shadow_all(kvm);
1181 kvm_arch_destroy_vm(kvm);
1182 kvm_destroy_devices(kvm);
1183 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
1184 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
1185 cleanup_srcu_struct(&kvm->irq_srcu);
1186 cleanup_srcu_struct(&kvm->srcu);
1187 kvm_arch_free_vm(kvm);
1188 preempt_notifier_dec();
1189 hardware_disable_all();
1193 void kvm_get_kvm(struct kvm *kvm)
1195 refcount_inc(&kvm->users_count);
1197 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1200 * Make sure the vm is not during destruction, which is a safe version of
1201 * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise.
1203 bool kvm_get_kvm_safe(struct kvm *kvm)
1205 return refcount_inc_not_zero(&kvm->users_count);
1207 EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1209 void kvm_put_kvm(struct kvm *kvm)
1211 if (refcount_dec_and_test(&kvm->users_count))
1212 kvm_destroy_vm(kvm);
1214 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1217 * Used to put a reference that was taken on behalf of an object associated
1218 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1219 * of the new file descriptor fails and the reference cannot be transferred to
1220 * its final owner. In such cases, the caller is still actively using @kvm and
1221 * will fail miserably if the refcount unexpectedly hits zero.
1223 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1225 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1227 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1229 static int kvm_vm_release(struct inode *inode, struct file *filp)
1231 struct kvm *kvm = filp->private_data;
1233 kvm_irqfd_release(kvm);
1240 * Allocation size is twice as large as the actual dirty bitmap size.
1241 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1243 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1245 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
1247 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
1248 if (!memslot->dirty_bitmap)
1255 * Delete a memslot by decrementing the number of used slots and shifting all
1256 * other entries in the array forward one spot.
1258 static inline void kvm_memslot_delete(struct kvm_memslots *slots,
1259 struct kvm_memory_slot *memslot)
1261 struct kvm_memory_slot *mslots = slots->memslots;
1264 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
1267 slots->used_slots--;
1269 if (atomic_read(&slots->last_used_slot) >= slots->used_slots)
1270 atomic_set(&slots->last_used_slot, 0);
1272 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
1273 mslots[i] = mslots[i + 1];
1274 slots->id_to_index[mslots[i].id] = i;
1276 mslots[i] = *memslot;
1277 slots->id_to_index[memslot->id] = -1;
1281 * "Insert" a new memslot by incrementing the number of used slots. Returns
1282 * the new slot's initial index into the memslots array.
1284 static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
1286 return slots->used_slots++;
1290 * Move a changed memslot backwards in the array by shifting existing slots
1291 * with a higher GFN toward the front of the array. Note, the changed memslot
1292 * itself is not preserved in the array, i.e. not swapped at this time, only
1293 * its new index into the array is tracked. Returns the changed memslot's
1294 * current index into the memslots array.
1296 static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
1297 struct kvm_memory_slot *memslot)
1299 struct kvm_memory_slot *mslots = slots->memslots;
1302 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
1303 WARN_ON_ONCE(!slots->used_slots))
1307 * Move the target memslot backward in the array by shifting existing
1308 * memslots with a higher GFN (than the target memslot) towards the
1309 * front of the array.
1311 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
1312 if (memslot->base_gfn > mslots[i + 1].base_gfn)
1315 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
1317 /* Shift the next memslot forward one and update its index. */
1318 mslots[i] = mslots[i + 1];
1319 slots->id_to_index[mslots[i].id] = i;
1325 * Move a changed memslot forwards in the array by shifting existing slots with
1326 * a lower GFN toward the back of the array. Note, the changed memslot itself
1327 * is not preserved in the array, i.e. not swapped at this time, only its new
1328 * index into the array is tracked. Returns the changed memslot's final index
1329 * into the memslots array.
1331 static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
1332 struct kvm_memory_slot *memslot,
1335 struct kvm_memory_slot *mslots = slots->memslots;
1338 for (i = start; i > 0; i--) {
1339 if (memslot->base_gfn < mslots[i - 1].base_gfn)
1342 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
1344 /* Shift the next memslot back one and update its index. */
1345 mslots[i] = mslots[i - 1];
1346 slots->id_to_index[mslots[i].id] = i;
1352 * Re-sort memslots based on their GFN to account for an added, deleted, or
1353 * moved memslot. Sorting memslots by GFN allows using a binary search during
1356 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
1357 * at memslots[0] has the highest GFN.
1359 * The sorting algorithm takes advantage of having initially sorted memslots
1360 * and knowing the position of the changed memslot. Sorting is also optimized
1361 * by not swapping the updated memslot and instead only shifting other memslots
1362 * and tracking the new index for the update memslot. Only once its final
1363 * index is known is the updated memslot copied into its position in the array.
1365 * - When deleting a memslot, the deleted memslot simply needs to be moved to
1366 * the end of the array.
1368 * - When creating a memslot, the algorithm "inserts" the new memslot at the
1369 * end of the array and then it forward to its correct location.
1371 * - When moving a memslot, the algorithm first moves the updated memslot
1372 * backward to handle the scenario where the memslot's GFN was changed to a
1373 * lower value. update_memslots() then falls through and runs the same flow
1374 * as creating a memslot to move the memslot forward to handle the scenario
1375 * where its GFN was changed to a higher value.
1377 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1378 * historical reasons. Originally, invalid memslots where denoted by having
1379 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1380 * to the end of the array. The current algorithm uses dedicated logic to
1381 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1383 * The other historical motiviation for highest->lowest was to improve the
1384 * performance of memslot lookup. KVM originally used a linear search starting
1385 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1386 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1387 * single memslot above the 4gb boundary. As the largest memslot is also the
1388 * most likely to be referenced, sorting it to the front of the array was
1389 * advantageous. The current binary search starts from the middle of the array
1390 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1392 static void update_memslots(struct kvm_memslots *slots,
1393 struct kvm_memory_slot *memslot,
1394 enum kvm_mr_change change)
1398 if (change == KVM_MR_DELETE) {
1399 kvm_memslot_delete(slots, memslot);
1401 if (change == KVM_MR_CREATE)
1402 i = kvm_memslot_insert_back(slots);
1404 i = kvm_memslot_move_backward(slots, memslot);
1405 i = kvm_memslot_move_forward(slots, memslot, i);
1408 * Copy the memslot to its new position in memslots and update
1409 * its index accordingly.
1411 slots->memslots[i] = *memslot;
1412 slots->id_to_index[memslot->id] = i;
1416 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1418 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1420 #ifdef __KVM_HAVE_READONLY_MEM
1421 valid_flags |= KVM_MEM_READONLY;
1424 if (mem->flags & ~valid_flags)
1430 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
1431 int as_id, struct kvm_memslots *slots)
1433 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
1434 u64 gen = old_memslots->generation;
1436 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1437 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1440 * Do not store the new memslots while there are invalidations in
1441 * progress, otherwise the locking in invalidate_range_start and
1442 * invalidate_range_end will be unbalanced.
1444 spin_lock(&kvm->mn_invalidate_lock);
1445 prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1446 while (kvm->mn_active_invalidate_count) {
1447 set_current_state(TASK_UNINTERRUPTIBLE);
1448 spin_unlock(&kvm->mn_invalidate_lock);
1450 spin_lock(&kvm->mn_invalidate_lock);
1452 finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
1453 rcu_assign_pointer(kvm->memslots[as_id], slots);
1454 spin_unlock(&kvm->mn_invalidate_lock);
1457 * Acquired in kvm_set_memslot. Must be released before synchronize
1458 * SRCU below in order to avoid deadlock with another thread
1459 * acquiring the slots_arch_lock in an srcu critical section.
1461 mutex_unlock(&kvm->slots_arch_lock);
1463 synchronize_srcu_expedited(&kvm->srcu);
1466 * Increment the new memslot generation a second time, dropping the
1467 * update in-progress flag and incrementing the generation based on
1468 * the number of address spaces. This provides a unique and easily
1469 * identifiable generation number while the memslots are in flux.
1471 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1474 * Generations must be unique even across address spaces. We do not need
1475 * a global counter for that, instead the generation space is evenly split
1476 * across address spaces. For example, with two address spaces, address
1477 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1478 * use generations 1, 3, 5, ...
1480 gen += KVM_ADDRESS_SPACE_NUM;
1482 kvm_arch_memslots_updated(kvm, gen);
1484 slots->generation = gen;
1486 return old_memslots;
1489 static size_t kvm_memslots_size(int slots)
1491 return sizeof(struct kvm_memslots) +
1492 (sizeof(struct kvm_memory_slot) * slots);
1495 static void kvm_copy_memslots(struct kvm_memslots *to,
1496 struct kvm_memslots *from)
1498 memcpy(to, from, kvm_memslots_size(from->used_slots));
1502 * Note, at a minimum, the current number of used slots must be allocated, even
1503 * when deleting a memslot, as we need a complete duplicate of the memslots for
1504 * use when invalidating a memslot prior to deleting/moving the memslot.
1506 static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1507 enum kvm_mr_change change)
1509 struct kvm_memslots *slots;
1512 if (change == KVM_MR_CREATE)
1513 new_size = kvm_memslots_size(old->used_slots + 1);
1515 new_size = kvm_memslots_size(old->used_slots);
1517 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1519 kvm_copy_memslots(slots, old);
1524 static int kvm_set_memslot(struct kvm *kvm,
1525 const struct kvm_userspace_memory_region *mem,
1526 struct kvm_memory_slot *old,
1527 struct kvm_memory_slot *new, int as_id,
1528 enum kvm_mr_change change)
1530 struct kvm_memory_slot *slot;
1531 struct kvm_memslots *slots;
1535 * Released in install_new_memslots.
1537 * Must be held from before the current memslots are copied until
1538 * after the new memslots are installed with rcu_assign_pointer,
1539 * then released before the synchronize srcu in install_new_memslots.
1541 * When modifying memslots outside of the slots_lock, must be held
1542 * before reading the pointer to the current memslots until after all
1543 * changes to those memslots are complete.
1545 * These rules ensure that installing new memslots does not lose
1546 * changes made to the previous memslots.
1548 mutex_lock(&kvm->slots_arch_lock);
1550 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
1552 mutex_unlock(&kvm->slots_arch_lock);
1556 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1558 * Note, the INVALID flag needs to be in the appropriate entry
1559 * in the freshly allocated memslots, not in @old or @new.
1561 slot = id_to_memslot(slots, old->id);
1562 slot->flags |= KVM_MEMSLOT_INVALID;
1565 * We can re-use the memory from the old memslots.
1566 * It will be overwritten with a copy of the new memslots
1567 * after reacquiring the slots_arch_lock below.
1569 slots = install_new_memslots(kvm, as_id, slots);
1571 /* From this point no new shadow pages pointing to a deleted,
1572 * or moved, memslot will be created.
1574 * validation of sp->gfn happens in:
1575 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1576 * - kvm_is_visible_gfn (mmu_check_root)
1578 kvm_arch_flush_shadow_memslot(kvm, slot);
1580 /* Released in install_new_memslots. */
1581 mutex_lock(&kvm->slots_arch_lock);
1584 * The arch-specific fields of the memslots could have changed
1585 * between releasing the slots_arch_lock in
1586 * install_new_memslots and here, so get a fresh copy of the
1589 kvm_copy_memslots(slots, __kvm_memslots(kvm, as_id));
1592 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1596 update_memslots(slots, new, change);
1597 slots = install_new_memslots(kvm, as_id, slots);
1599 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1605 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1606 slot = id_to_memslot(slots, old->id);
1607 slot->flags &= ~KVM_MEMSLOT_INVALID;
1608 slots = install_new_memslots(kvm, as_id, slots);
1610 mutex_unlock(&kvm->slots_arch_lock);
1616 static int kvm_delete_memslot(struct kvm *kvm,
1617 const struct kvm_userspace_memory_region *mem,
1618 struct kvm_memory_slot *old, int as_id)
1620 struct kvm_memory_slot new;
1626 memset(&new, 0, sizeof(new));
1629 * This is only for debugging purpose; it should never be referenced
1630 * for a removed memslot.
1634 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1638 kvm_free_memslot(kvm, old);
1643 * Allocate some memory and give it an address in the guest physical address
1646 * Discontiguous memory is allowed, mostly for framebuffers.
1648 * Must be called holding kvm->slots_lock for write.
1650 int __kvm_set_memory_region(struct kvm *kvm,
1651 const struct kvm_userspace_memory_region *mem)
1653 struct kvm_memory_slot old, new;
1654 struct kvm_memory_slot *tmp;
1655 enum kvm_mr_change change;
1659 r = check_memory_region_flags(mem);
1663 as_id = mem->slot >> 16;
1664 id = (u16)mem->slot;
1666 /* General sanity checks */
1667 if ((mem->memory_size & (PAGE_SIZE - 1)) ||
1668 (mem->memory_size != (unsigned long)mem->memory_size))
1670 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1672 /* We can read the guest memory with __xxx_user() later on. */
1673 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1674 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1675 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1678 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1680 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1684 * Make a full copy of the old memslot, the pointer will become stale
1685 * when the memslots are re-sorted by update_memslots(), and the old
1686 * memslot needs to be referenced after calling update_memslots(), e.g.
1687 * to free its resources and for arch specific behavior.
1689 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1694 memset(&old, 0, sizeof(old));
1698 if (!mem->memory_size)
1699 return kvm_delete_memslot(kvm, mem, &old, as_id);
1703 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1704 new.npages = mem->memory_size >> PAGE_SHIFT;
1705 new.flags = mem->flags;
1706 new.userspace_addr = mem->userspace_addr;
1708 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1712 change = KVM_MR_CREATE;
1713 new.dirty_bitmap = NULL;
1714 memset(&new.arch, 0, sizeof(new.arch));
1715 } else { /* Modify an existing slot. */
1716 if ((new.userspace_addr != old.userspace_addr) ||
1717 (new.npages != old.npages) ||
1718 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1721 if (new.base_gfn != old.base_gfn)
1722 change = KVM_MR_MOVE;
1723 else if (new.flags != old.flags)
1724 change = KVM_MR_FLAGS_ONLY;
1725 else /* Nothing to change. */
1728 /* Copy dirty_bitmap and arch from the current memslot. */
1729 new.dirty_bitmap = old.dirty_bitmap;
1730 memcpy(&new.arch, &old.arch, sizeof(new.arch));
1733 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1734 /* Check for overlaps */
1735 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1738 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1739 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1744 /* Allocate/free page dirty bitmap as needed */
1745 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1746 new.dirty_bitmap = NULL;
1747 else if (!new.dirty_bitmap && !kvm->dirty_ring_size) {
1748 r = kvm_alloc_dirty_bitmap(&new);
1752 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1753 bitmap_set(new.dirty_bitmap, 0, new.npages);
1756 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1760 if (old.dirty_bitmap && !new.dirty_bitmap)
1761 kvm_destroy_dirty_bitmap(&old);
1765 if (new.dirty_bitmap && !old.dirty_bitmap)
1766 kvm_destroy_dirty_bitmap(&new);
1769 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1771 int kvm_set_memory_region(struct kvm *kvm,
1772 const struct kvm_userspace_memory_region *mem)
1776 mutex_lock(&kvm->slots_lock);
1777 r = __kvm_set_memory_region(kvm, mem);
1778 mutex_unlock(&kvm->slots_lock);
1781 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1783 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1784 struct kvm_userspace_memory_region *mem)
1786 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1789 return kvm_set_memory_region(kvm, mem);
1792 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1794 * kvm_get_dirty_log - get a snapshot of dirty pages
1795 * @kvm: pointer to kvm instance
1796 * @log: slot id and address to which we copy the log
1797 * @is_dirty: set to '1' if any dirty pages were found
1798 * @memslot: set to the associated memslot, always valid on success
1800 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1801 int *is_dirty, struct kvm_memory_slot **memslot)
1803 struct kvm_memslots *slots;
1806 unsigned long any = 0;
1808 /* Dirty ring tracking is exclusive to dirty log tracking */
1809 if (kvm->dirty_ring_size)
1815 as_id = log->slot >> 16;
1816 id = (u16)log->slot;
1817 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1820 slots = __kvm_memslots(kvm, as_id);
1821 *memslot = id_to_memslot(slots, id);
1822 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1825 kvm_arch_sync_dirty_log(kvm, *memslot);
1827 n = kvm_dirty_bitmap_bytes(*memslot);
1829 for (i = 0; !any && i < n/sizeof(long); ++i)
1830 any = (*memslot)->dirty_bitmap[i];
1832 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1839 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1841 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1843 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1844 * and reenable dirty page tracking for the corresponding pages.
1845 * @kvm: pointer to kvm instance
1846 * @log: slot id and address to which we copy the log
1848 * We need to keep it in mind that VCPU threads can write to the bitmap
1849 * concurrently. So, to avoid losing track of dirty pages we keep the
1852 * 1. Take a snapshot of the bit and clear it if needed.
1853 * 2. Write protect the corresponding page.
1854 * 3. Copy the snapshot to the userspace.
1855 * 4. Upon return caller flushes TLB's if needed.
1857 * Between 2 and 4, the guest may write to the page using the remaining TLB
1858 * entry. This is not a problem because the page is reported dirty using
1859 * the snapshot taken before and step 4 ensures that writes done after
1860 * exiting to userspace will be logged for the next call.
1863 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
1865 struct kvm_memslots *slots;
1866 struct kvm_memory_slot *memslot;
1869 unsigned long *dirty_bitmap;
1870 unsigned long *dirty_bitmap_buffer;
1873 /* Dirty ring tracking is exclusive to dirty log tracking */
1874 if (kvm->dirty_ring_size)
1877 as_id = log->slot >> 16;
1878 id = (u16)log->slot;
1879 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1882 slots = __kvm_memslots(kvm, as_id);
1883 memslot = id_to_memslot(slots, id);
1884 if (!memslot || !memslot->dirty_bitmap)
1887 dirty_bitmap = memslot->dirty_bitmap;
1889 kvm_arch_sync_dirty_log(kvm, memslot);
1891 n = kvm_dirty_bitmap_bytes(memslot);
1893 if (kvm->manual_dirty_log_protect) {
1895 * Unlike kvm_get_dirty_log, we always return false in *flush,
1896 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1897 * is some code duplication between this function and
1898 * kvm_get_dirty_log, but hopefully all architecture
1899 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1900 * can be eliminated.
1902 dirty_bitmap_buffer = dirty_bitmap;
1904 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1905 memset(dirty_bitmap_buffer, 0, n);
1908 for (i = 0; i < n / sizeof(long); i++) {
1912 if (!dirty_bitmap[i])
1916 mask = xchg(&dirty_bitmap[i], 0);
1917 dirty_bitmap_buffer[i] = mask;
1919 offset = i * BITS_PER_LONG;
1920 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1923 KVM_MMU_UNLOCK(kvm);
1927 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1929 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1936 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1937 * @kvm: kvm instance
1938 * @log: slot id and address to which we copy the log
1940 * Steps 1-4 below provide general overview of dirty page logging. See
1941 * kvm_get_dirty_log_protect() function description for additional details.
1943 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1944 * always flush the TLB (step 4) even if previous step failed and the dirty
1945 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1946 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1947 * writes will be marked dirty for next log read.
1949 * 1. Take a snapshot of the bit and clear it if needed.
1950 * 2. Write protect the corresponding page.
1951 * 3. Copy the snapshot to the userspace.
1952 * 4. Flush TLB's if needed.
1954 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1955 struct kvm_dirty_log *log)
1959 mutex_lock(&kvm->slots_lock);
1961 r = kvm_get_dirty_log_protect(kvm, log);
1963 mutex_unlock(&kvm->slots_lock);
1968 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1969 * and reenable dirty page tracking for the corresponding pages.
1970 * @kvm: pointer to kvm instance
1971 * @log: slot id and address from which to fetch the bitmap of dirty pages
1973 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1974 struct kvm_clear_dirty_log *log)
1976 struct kvm_memslots *slots;
1977 struct kvm_memory_slot *memslot;
1981 unsigned long *dirty_bitmap;
1982 unsigned long *dirty_bitmap_buffer;
1985 /* Dirty ring tracking is exclusive to dirty log tracking */
1986 if (kvm->dirty_ring_size)
1989 as_id = log->slot >> 16;
1990 id = (u16)log->slot;
1991 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1994 if (log->first_page & 63)
1997 slots = __kvm_memslots(kvm, as_id);
1998 memslot = id_to_memslot(slots, id);
1999 if (!memslot || !memslot->dirty_bitmap)
2002 dirty_bitmap = memslot->dirty_bitmap;
2004 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
2006 if (log->first_page > memslot->npages ||
2007 log->num_pages > memslot->npages - log->first_page ||
2008 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
2011 kvm_arch_sync_dirty_log(kvm, memslot);
2014 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2015 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2019 for (offset = log->first_page, i = offset / BITS_PER_LONG,
2020 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2021 i++, offset += BITS_PER_LONG) {
2022 unsigned long mask = *dirty_bitmap_buffer++;
2023 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2027 mask &= atomic_long_fetch_andnot(mask, p);
2030 * mask contains the bits that really have been cleared. This
2031 * never includes any bits beyond the length of the memslot (if
2032 * the length is not aligned to 64 pages), therefore it is not
2033 * a problem if userspace sets them in log->dirty_bitmap.
2037 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2041 KVM_MMU_UNLOCK(kvm);
2044 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2049 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2050 struct kvm_clear_dirty_log *log)
2054 mutex_lock(&kvm->slots_lock);
2056 r = kvm_clear_dirty_log_protect(kvm, log);
2058 mutex_unlock(&kvm->slots_lock);
2061 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2063 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2065 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2067 EXPORT_SYMBOL_GPL(gfn_to_memslot);
2069 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2071 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2072 struct kvm_memory_slot *slot;
2075 slot = try_get_memslot(slots, vcpu->last_used_slot, gfn);
2080 * Fall back to searching all memslots. We purposely use
2081 * search_memslots() instead of __gfn_to_memslot() to avoid
2082 * thrashing the VM-wide last_used_index in kvm_memslots.
2084 slot = search_memslots(slots, gfn, &slot_index);
2086 vcpu->last_used_slot = slot_index;
2092 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
2094 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
2096 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
2098 return kvm_is_visible_memslot(memslot);
2100 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2102 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2104 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2106 return kvm_is_visible_memslot(memslot);
2108 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2110 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
2112 struct vm_area_struct *vma;
2113 unsigned long addr, size;
2117 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
2118 if (kvm_is_error_hva(addr))
2121 mmap_read_lock(current->mm);
2122 vma = find_vma(current->mm, addr);
2126 size = vma_kernel_pagesize(vma);
2129 mmap_read_unlock(current->mm);
2134 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
2136 return slot->flags & KVM_MEM_READONLY;
2139 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2140 gfn_t *nr_pages, bool write)
2142 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
2143 return KVM_HVA_ERR_BAD;
2145 if (memslot_is_readonly(slot) && write)
2146 return KVM_HVA_ERR_RO_BAD;
2149 *nr_pages = slot->npages - (gfn - slot->base_gfn);
2151 return __gfn_to_hva_memslot(slot, gfn);
2154 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2157 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2160 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2163 return gfn_to_hva_many(slot, gfn, NULL);
2165 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2167 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2169 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2171 EXPORT_SYMBOL_GPL(gfn_to_hva);
2173 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2175 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2177 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2180 * Return the hva of a @gfn and the R/W attribute if possible.
2182 * @slot: the kvm_memory_slot which contains @gfn
2183 * @gfn: the gfn to be translated
2184 * @writable: used to return the read/write attribute of the @slot if the hva
2185 * is valid and @writable is not NULL
2187 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2188 gfn_t gfn, bool *writable)
2190 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2192 if (!kvm_is_error_hva(hva) && writable)
2193 *writable = !memslot_is_readonly(slot);
2198 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2200 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2202 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2205 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2207 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2209 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2212 static inline int check_user_page_hwpoison(unsigned long addr)
2214 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
2216 rc = get_user_pages(addr, 1, flags, NULL, NULL);
2217 return rc == -EHWPOISON;
2221 * The fast path to get the writable pfn which will be stored in @pfn,
2222 * true indicates success, otherwise false is returned. It's also the
2223 * only part that runs if we can in atomic context.
2225 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2226 bool *writable, kvm_pfn_t *pfn)
2228 struct page *page[1];
2231 * Fast pin a writable pfn only if it is a write fault request
2232 * or the caller allows to map a writable pfn for a read fault
2235 if (!(write_fault || writable))
2238 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2239 *pfn = page_to_pfn(page[0]);
2250 * The slow path to get the pfn of the specified host virtual address,
2251 * 1 indicates success, -errno is returned if error is detected.
2253 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2254 bool *writable, kvm_pfn_t *pfn)
2256 unsigned int flags = FOLL_HWPOISON;
2263 *writable = write_fault;
2266 flags |= FOLL_WRITE;
2268 flags |= FOLL_NOWAIT;
2270 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2274 /* map read fault as writable if possible */
2275 if (unlikely(!write_fault) && writable) {
2278 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2284 *pfn = page_to_pfn(page);
2288 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2290 if (unlikely(!(vma->vm_flags & VM_READ)))
2293 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2299 static int kvm_try_get_pfn(kvm_pfn_t pfn)
2301 if (kvm_is_reserved_pfn(pfn))
2303 return get_page_unless_zero(pfn_to_page(pfn));
2306 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2307 unsigned long addr, bool *async,
2308 bool write_fault, bool *writable,
2316 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2319 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2320 * not call the fault handler, so do it here.
2322 bool unlocked = false;
2323 r = fixup_user_fault(current->mm, addr,
2324 (write_fault ? FAULT_FLAG_WRITE : 0),
2331 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2336 if (write_fault && !pte_write(*ptep)) {
2337 pfn = KVM_PFN_ERR_RO_FAULT;
2342 *writable = pte_write(*ptep);
2343 pfn = pte_pfn(*ptep);
2346 * Get a reference here because callers of *hva_to_pfn* and
2347 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2348 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2349 * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
2350 * simply do nothing for reserved pfns.
2352 * Whoever called remap_pfn_range is also going to call e.g.
2353 * unmap_mapping_range before the underlying pages are freed,
2354 * causing a call to our MMU notifier.
2356 * Certain IO or PFNMAP mappings can be backed with valid
2357 * struct pages, but be allocated without refcounting e.g.,
2358 * tail pages of non-compound higher order allocations, which
2359 * would then underflow the refcount when the caller does the
2360 * required put_page. Don't allow those pages here.
2362 if (!kvm_try_get_pfn(pfn))
2366 pte_unmap_unlock(ptep, ptl);
2373 * Pin guest page in memory and return its pfn.
2374 * @addr: host virtual address which maps memory to the guest
2375 * @atomic: whether this function can sleep
2376 * @async: whether this function need to wait IO complete if the
2377 * host page is not in the memory
2378 * @write_fault: whether we should get a writable host page
2379 * @writable: whether it allows to map a writable host page for !@write_fault
2381 * The function will map a writable host page for these two cases:
2382 * 1): @write_fault = true
2383 * 2): @write_fault = false && @writable, @writable will tell the caller
2384 * whether the mapping is writable.
2386 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2387 bool write_fault, bool *writable)
2389 struct vm_area_struct *vma;
2393 /* we can do it either atomically or asynchronously, not both */
2394 BUG_ON(atomic && async);
2396 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2400 return KVM_PFN_ERR_FAULT;
2402 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2406 mmap_read_lock(current->mm);
2407 if (npages == -EHWPOISON ||
2408 (!async && check_user_page_hwpoison(addr))) {
2409 pfn = KVM_PFN_ERR_HWPOISON;
2414 vma = vma_lookup(current->mm, addr);
2417 pfn = KVM_PFN_ERR_FAULT;
2418 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2419 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
2423 pfn = KVM_PFN_ERR_FAULT;
2425 if (async && vma_is_valid(vma, write_fault))
2427 pfn = KVM_PFN_ERR_FAULT;
2430 mmap_read_unlock(current->mm);
2434 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
2435 bool atomic, bool *async, bool write_fault,
2436 bool *writable, hva_t *hva)
2438 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2443 if (addr == KVM_HVA_ERR_RO_BAD) {
2446 return KVM_PFN_ERR_RO_FAULT;
2449 if (kvm_is_error_hva(addr)) {
2452 return KVM_PFN_NOSLOT;
2455 /* Do not map writable pfn in the readonly memslot. */
2456 if (writable && memslot_is_readonly(slot)) {
2461 return hva_to_pfn(addr, atomic, async, write_fault,
2464 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2466 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2469 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2470 write_fault, writable, NULL);
2472 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2474 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
2476 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2478 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2480 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
2482 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2484 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2486 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2488 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2490 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2492 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2494 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2496 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2498 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2500 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2502 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2504 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2505 struct page **pages, int nr_pages)
2510 addr = gfn_to_hva_many(slot, gfn, &entry);
2511 if (kvm_is_error_hva(addr))
2514 if (entry < nr_pages)
2517 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2519 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2521 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2523 if (is_error_noslot_pfn(pfn))
2524 return KVM_ERR_PTR_BAD_PAGE;
2526 if (kvm_is_reserved_pfn(pfn)) {
2528 return KVM_ERR_PTR_BAD_PAGE;
2531 return pfn_to_page(pfn);
2534 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2538 pfn = gfn_to_pfn(kvm, gfn);
2540 return kvm_pfn_to_page(pfn);
2542 EXPORT_SYMBOL_GPL(gfn_to_page);
2544 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2550 cache->pfn = cache->gfn = 0;
2553 kvm_release_pfn_dirty(pfn);
2555 kvm_release_pfn_clean(pfn);
2558 static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2559 struct gfn_to_pfn_cache *cache, u64 gen)
2561 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2563 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2565 cache->dirty = false;
2566 cache->generation = gen;
2569 static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2570 struct kvm_host_map *map,
2571 struct gfn_to_pfn_cache *cache,
2576 struct page *page = KVM_UNMAPPED_PAGE;
2577 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2578 u64 gen = slots->generation;
2584 if (!cache->pfn || cache->gfn != gfn ||
2585 cache->generation != gen) {
2588 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2594 pfn = gfn_to_pfn_memslot(slot, gfn);
2596 if (is_error_noslot_pfn(pfn))
2599 if (pfn_valid(pfn)) {
2600 page = pfn_to_page(pfn);
2602 hva = kmap_atomic(page);
2605 #ifdef CONFIG_HAS_IOMEM
2606 } else if (!atomic) {
2607 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2624 int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2625 struct gfn_to_pfn_cache *cache, bool atomic)
2627 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2630 EXPORT_SYMBOL_GPL(kvm_map_gfn);
2632 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2634 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2637 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2639 static void __kvm_unmap_gfn(struct kvm *kvm,
2640 struct kvm_memory_slot *memslot,
2641 struct kvm_host_map *map,
2642 struct gfn_to_pfn_cache *cache,
2643 bool dirty, bool atomic)
2651 if (map->page != KVM_UNMAPPED_PAGE) {
2653 kunmap_atomic(map->hva);
2657 #ifdef CONFIG_HAS_IOMEM
2661 WARN_ONCE(1, "Unexpected unmapping in atomic context");
2665 mark_page_dirty_in_slot(kvm, memslot, map->gfn);
2668 cache->dirty |= dirty;
2670 kvm_release_pfn(map->pfn, dirty, NULL);
2676 int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2677 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2679 __kvm_unmap_gfn(vcpu->kvm, gfn_to_memslot(vcpu->kvm, map->gfn), map,
2680 cache, dirty, atomic);
2683 EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2685 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2687 __kvm_unmap_gfn(vcpu->kvm, kvm_vcpu_gfn_to_memslot(vcpu, map->gfn),
2688 map, NULL, dirty, false);
2690 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2692 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2696 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2698 return kvm_pfn_to_page(pfn);
2700 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2702 void kvm_release_page_clean(struct page *page)
2704 WARN_ON(is_error_page(page));
2706 kvm_release_pfn_clean(page_to_pfn(page));
2708 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2710 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2712 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2713 put_page(pfn_to_page(pfn));
2715 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2717 void kvm_release_page_dirty(struct page *page)
2719 WARN_ON(is_error_page(page));
2721 kvm_release_pfn_dirty(page_to_pfn(page));
2723 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2725 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2727 kvm_set_pfn_dirty(pfn);
2728 kvm_release_pfn_clean(pfn);
2730 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2732 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2734 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2735 SetPageDirty(pfn_to_page(pfn));
2737 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2739 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2741 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2742 mark_page_accessed(pfn_to_page(pfn));
2744 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2746 static int next_segment(unsigned long len, int offset)
2748 if (len > PAGE_SIZE - offset)
2749 return PAGE_SIZE - offset;
2754 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2755 void *data, int offset, int len)
2760 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2761 if (kvm_is_error_hva(addr))
2763 r = __copy_from_user(data, (void __user *)addr + offset, len);
2769 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2772 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2774 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2776 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2778 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2779 int offset, int len)
2781 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2783 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2785 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2787 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2789 gfn_t gfn = gpa >> PAGE_SHIFT;
2791 int offset = offset_in_page(gpa);
2794 while ((seg = next_segment(len, offset)) != 0) {
2795 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2805 EXPORT_SYMBOL_GPL(kvm_read_guest);
2807 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2809 gfn_t gfn = gpa >> PAGE_SHIFT;
2811 int offset = offset_in_page(gpa);
2814 while ((seg = next_segment(len, offset)) != 0) {
2815 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2825 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2827 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2828 void *data, int offset, unsigned long len)
2833 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2834 if (kvm_is_error_hva(addr))
2836 pagefault_disable();
2837 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2844 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2845 void *data, unsigned long len)
2847 gfn_t gfn = gpa >> PAGE_SHIFT;
2848 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2849 int offset = offset_in_page(gpa);
2851 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2853 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2855 static int __kvm_write_guest_page(struct kvm *kvm,
2856 struct kvm_memory_slot *memslot, gfn_t gfn,
2857 const void *data, int offset, int len)
2862 addr = gfn_to_hva_memslot(memslot, gfn);
2863 if (kvm_is_error_hva(addr))
2865 r = __copy_to_user((void __user *)addr + offset, data, len);
2868 mark_page_dirty_in_slot(kvm, memslot, gfn);
2872 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2873 const void *data, int offset, int len)
2875 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2877 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2879 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2881 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2882 const void *data, int offset, int len)
2884 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2886 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
2888 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2890 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2893 gfn_t gfn = gpa >> PAGE_SHIFT;
2895 int offset = offset_in_page(gpa);
2898 while ((seg = next_segment(len, offset)) != 0) {
2899 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2909 EXPORT_SYMBOL_GPL(kvm_write_guest);
2911 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2914 gfn_t gfn = gpa >> PAGE_SHIFT;
2916 int offset = offset_in_page(gpa);
2919 while ((seg = next_segment(len, offset)) != 0) {
2920 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2930 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2932 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2933 struct gfn_to_hva_cache *ghc,
2934 gpa_t gpa, unsigned long len)
2936 int offset = offset_in_page(gpa);
2937 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2938 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2939 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2940 gfn_t nr_pages_avail;
2942 /* Update ghc->generation before performing any error checks. */
2943 ghc->generation = slots->generation;
2945 if (start_gfn > end_gfn) {
2946 ghc->hva = KVM_HVA_ERR_BAD;
2951 * If the requested region crosses two memslots, we still
2952 * verify that the entire region is valid here.
2954 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
2955 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2956 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2958 if (kvm_is_error_hva(ghc->hva))
2962 /* Use the slow path for cross page reads and writes. */
2963 if (nr_pages_needed == 1)
2966 ghc->memslot = NULL;
2973 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2974 gpa_t gpa, unsigned long len)
2976 struct kvm_memslots *slots = kvm_memslots(kvm);
2977 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2979 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2981 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2982 void *data, unsigned int offset,
2985 struct kvm_memslots *slots = kvm_memslots(kvm);
2987 gpa_t gpa = ghc->gpa + offset;
2989 BUG_ON(len + offset > ghc->len);
2991 if (slots->generation != ghc->generation) {
2992 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2996 if (kvm_is_error_hva(ghc->hva))
2999 if (unlikely(!ghc->memslot))
3000 return kvm_write_guest(kvm, gpa, data, len);
3002 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
3005 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
3009 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
3011 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3012 void *data, unsigned long len)
3014 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
3016 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
3018 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3019 void *data, unsigned int offset,
3022 struct kvm_memslots *slots = kvm_memslots(kvm);
3024 gpa_t gpa = ghc->gpa + offset;
3026 BUG_ON(len + offset > ghc->len);
3028 if (slots->generation != ghc->generation) {
3029 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3033 if (kvm_is_error_hva(ghc->hva))
3036 if (unlikely(!ghc->memslot))
3037 return kvm_read_guest(kvm, gpa, data, len);
3039 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
3045 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3047 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3048 void *data, unsigned long len)
3050 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3052 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
3054 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3056 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3057 gfn_t gfn = gpa >> PAGE_SHIFT;
3059 int offset = offset_in_page(gpa);
3062 while ((seg = next_segment(len, offset)) != 0) {
3063 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
3072 EXPORT_SYMBOL_GPL(kvm_clear_guest);
3074 void mark_page_dirty_in_slot(struct kvm *kvm,
3075 struct kvm_memory_slot *memslot,
3078 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
3079 unsigned long rel_gfn = gfn - memslot->base_gfn;
3080 u32 slot = (memslot->as_id << 16) | memslot->id;
3082 if (kvm->dirty_ring_size)
3083 kvm_dirty_ring_push(kvm_dirty_ring_get(kvm),
3086 set_bit_le(rel_gfn, memslot->dirty_bitmap);
3089 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
3091 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3093 struct kvm_memory_slot *memslot;
3095 memslot = gfn_to_memslot(kvm, gfn);
3096 mark_page_dirty_in_slot(kvm, memslot, gfn);
3098 EXPORT_SYMBOL_GPL(mark_page_dirty);
3100 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3102 struct kvm_memory_slot *memslot;
3104 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3105 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
3107 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3109 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3111 if (!vcpu->sigset_active)
3115 * This does a lockless modification of ->real_blocked, which is fine
3116 * because, only current can change ->real_blocked and all readers of
3117 * ->real_blocked don't care as long ->real_blocked is always a subset
3120 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
3123 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3125 if (!vcpu->sigset_active)
3128 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
3129 sigemptyset(¤t->real_blocked);
3132 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3134 unsigned int old, val, grow, grow_start;
3136 old = val = vcpu->halt_poll_ns;
3137 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3138 grow = READ_ONCE(halt_poll_ns_grow);
3143 if (val < grow_start)
3146 if (val > vcpu->kvm->max_halt_poll_ns)
3147 val = vcpu->kvm->max_halt_poll_ns;
3149 vcpu->halt_poll_ns = val;
3151 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
3154 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3156 unsigned int old, val, shrink, grow_start;
3158 old = val = vcpu->halt_poll_ns;
3159 shrink = READ_ONCE(halt_poll_ns_shrink);
3160 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3166 if (val < grow_start)
3169 vcpu->halt_poll_ns = val;
3170 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3173 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3176 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3178 if (kvm_arch_vcpu_runnable(vcpu)) {
3179 kvm_make_request(KVM_REQ_UNHALT, vcpu);
3182 if (kvm_cpu_has_pending_timer(vcpu))
3184 if (signal_pending(current))
3186 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3191 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3196 update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
3199 vcpu->stat.generic.halt_poll_fail_ns += poll_ns;
3201 vcpu->stat.generic.halt_poll_success_ns += poll_ns;
3205 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
3207 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
3209 ktime_t start, cur, poll_end;
3210 bool waited = false;
3213 kvm_arch_vcpu_blocking(vcpu);
3215 start = cur = poll_end = ktime_get();
3216 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
3217 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
3219 ++vcpu->stat.generic.halt_attempted_poll;
3222 * This sets KVM_REQ_UNHALT if an interrupt
3225 if (kvm_vcpu_check_block(vcpu) < 0) {
3226 ++vcpu->stat.generic.halt_successful_poll;
3227 if (!vcpu_valid_wakeup(vcpu))
3228 ++vcpu->stat.generic.halt_poll_invalid;
3230 KVM_STATS_LOG_HIST_UPDATE(
3231 vcpu->stat.generic.halt_poll_success_hist,
3232 ktime_to_ns(ktime_get()) -
3233 ktime_to_ns(start));
3237 poll_end = cur = ktime_get();
3238 } while (kvm_vcpu_can_poll(cur, stop));
3240 KVM_STATS_LOG_HIST_UPDATE(
3241 vcpu->stat.generic.halt_poll_fail_hist,
3242 ktime_to_ns(ktime_get()) - ktime_to_ns(start));
3246 prepare_to_rcuwait(&vcpu->wait);
3248 set_current_state(TASK_INTERRUPTIBLE);
3250 if (kvm_vcpu_check_block(vcpu) < 0)
3256 finish_rcuwait(&vcpu->wait);
3259 vcpu->stat.generic.halt_wait_ns +=
3260 ktime_to_ns(cur) - ktime_to_ns(poll_end);
3261 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3262 ktime_to_ns(cur) - ktime_to_ns(poll_end));
3265 kvm_arch_vcpu_unblocking(vcpu);
3266 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3268 update_halt_poll_stats(
3269 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
3271 if (!kvm_arch_no_poll(vcpu)) {
3272 if (!vcpu_valid_wakeup(vcpu)) {
3273 shrink_halt_poll_ns(vcpu);
3274 } else if (vcpu->kvm->max_halt_poll_ns) {
3275 if (block_ns <= vcpu->halt_poll_ns)
3277 /* we had a long block, shrink polling */
3278 else if (vcpu->halt_poll_ns &&
3279 block_ns > vcpu->kvm->max_halt_poll_ns)
3280 shrink_halt_poll_ns(vcpu);
3281 /* we had a short halt and our poll time is too small */
3282 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3283 block_ns < vcpu->kvm->max_halt_poll_ns)
3284 grow_halt_poll_ns(vcpu);
3286 vcpu->halt_poll_ns = 0;
3290 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
3291 kvm_arch_vcpu_block_finish(vcpu);
3293 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
3295 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3297 struct rcuwait *waitp;
3299 waitp = kvm_arch_vcpu_get_wait(vcpu);
3300 if (rcuwait_wake_up(waitp)) {
3301 WRITE_ONCE(vcpu->ready, true);
3302 ++vcpu->stat.generic.halt_wakeup;
3308 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3312 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3314 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3318 if (kvm_vcpu_wake_up(vcpu))
3322 * Note, the vCPU could get migrated to a different pCPU at any point
3323 * after kvm_arch_vcpu_should_kick(), which could result in sending an
3324 * IPI to the previous pCPU. But, that's ok because the purpose of the
3325 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
3326 * vCPU also requires it to leave IN_GUEST_MODE.
3329 if (kvm_arch_vcpu_should_kick(vcpu)) {
3330 cpu = READ_ONCE(vcpu->cpu);
3331 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3332 smp_send_reschedule(cpu);
3336 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3337 #endif /* !CONFIG_S390 */
3339 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3342 struct task_struct *task = NULL;
3346 pid = rcu_dereference(target->pid);
3348 task = get_pid_task(pid, PIDTYPE_PID);
3352 ret = yield_to(task, 1);
3353 put_task_struct(task);
3357 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3360 * Helper that checks whether a VCPU is eligible for directed yield.
3361 * Most eligible candidate to yield is decided by following heuristics:
3363 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3364 * (preempted lock holder), indicated by @in_spin_loop.
3365 * Set at the beginning and cleared at the end of interception/PLE handler.
3367 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3368 * chance last time (mostly it has become eligible now since we have probably
3369 * yielded to lockholder in last iteration. This is done by toggling
3370 * @dy_eligible each time a VCPU checked for eligibility.)
3372 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3373 * to preempted lock-holder could result in wrong VCPU selection and CPU
3374 * burning. Giving priority for a potential lock-holder increases lock
3377 * Since algorithm is based on heuristics, accessing another VCPU data without
3378 * locking does not harm. It may result in trying to yield to same VCPU, fail
3379 * and continue with next VCPU and so on.
3381 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3383 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3386 eligible = !vcpu->spin_loop.in_spin_loop ||
3387 vcpu->spin_loop.dy_eligible;
3389 if (vcpu->spin_loop.in_spin_loop)
3390 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3399 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3400 * a vcpu_load/vcpu_put pair. However, for most architectures
3401 * kvm_arch_vcpu_runnable does not require vcpu_load.
3403 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3405 return kvm_arch_vcpu_runnable(vcpu);
3408 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3410 if (kvm_arch_dy_runnable(vcpu))
3413 #ifdef CONFIG_KVM_ASYNC_PF
3414 if (!list_empty_careful(&vcpu->async_pf.done))
3421 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3426 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3428 struct kvm *kvm = me->kvm;
3429 struct kvm_vcpu *vcpu;
3430 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3436 kvm_vcpu_set_in_spin_loop(me, true);
3438 * We boost the priority of a VCPU that is runnable but not
3439 * currently running, because it got preempted by something
3440 * else and called schedule in __vcpu_run. Hopefully that
3441 * VCPU is holding the lock that we need and will release it.
3442 * We approximate round-robin by starting at the last boosted VCPU.
3444 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3445 kvm_for_each_vcpu(i, vcpu, kvm) {
3446 if (!pass && i <= last_boosted_vcpu) {
3447 i = last_boosted_vcpu;
3449 } else if (pass && i > last_boosted_vcpu)
3451 if (!READ_ONCE(vcpu->ready))
3455 if (rcuwait_active(&vcpu->wait) &&
3456 !vcpu_dy_runnable(vcpu))
3458 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3459 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3460 !kvm_arch_vcpu_in_kernel(vcpu))
3462 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3465 yielded = kvm_vcpu_yield_to(vcpu);
3467 kvm->last_boosted_vcpu = i;
3469 } else if (yielded < 0) {
3476 kvm_vcpu_set_in_spin_loop(me, false);
3478 /* Ensure vcpu is not eligible during next spinloop */
3479 kvm_vcpu_set_dy_eligible(me, false);
3481 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3483 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3485 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3486 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3487 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3488 kvm->dirty_ring_size / PAGE_SIZE);
3494 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3496 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3499 if (vmf->pgoff == 0)
3500 page = virt_to_page(vcpu->run);
3502 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3503 page = virt_to_page(vcpu->arch.pio_data);
3505 #ifdef CONFIG_KVM_MMIO
3506 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3507 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3509 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3510 page = kvm_dirty_ring_get_page(
3512 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3514 return kvm_arch_vcpu_fault(vcpu, vmf);
3520 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3521 .fault = kvm_vcpu_fault,
3524 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3526 struct kvm_vcpu *vcpu = file->private_data;
3527 unsigned long pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
3529 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3530 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3531 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3534 vma->vm_ops = &kvm_vcpu_vm_ops;
3538 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3540 struct kvm_vcpu *vcpu = filp->private_data;
3542 kvm_put_kvm(vcpu->kvm);
3546 static struct file_operations kvm_vcpu_fops = {
3547 .release = kvm_vcpu_release,
3548 .unlocked_ioctl = kvm_vcpu_ioctl,
3549 .mmap = kvm_vcpu_mmap,
3550 .llseek = noop_llseek,
3551 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3555 * Allocates an inode for the vcpu.
3557 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3559 char name[8 + 1 + ITOA_MAX_LEN + 1];
3561 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3562 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3565 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3567 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3568 struct dentry *debugfs_dentry;
3569 char dir_name[ITOA_MAX_LEN * 2];
3571 if (!debugfs_initialized())
3574 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3575 debugfs_dentry = debugfs_create_dir(dir_name,
3576 vcpu->kvm->debugfs_dentry);
3578 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3583 * Creates some virtual cpus. Good luck creating more than one.
3585 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3588 struct kvm_vcpu *vcpu;
3591 if (id >= KVM_MAX_VCPU_ID)
3594 mutex_lock(&kvm->lock);
3595 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3596 mutex_unlock(&kvm->lock);
3600 kvm->created_vcpus++;
3601 mutex_unlock(&kvm->lock);
3603 r = kvm_arch_vcpu_precreate(kvm, id);
3605 goto vcpu_decrement;
3607 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3610 goto vcpu_decrement;
3613 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3614 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3619 vcpu->run = page_address(page);
3621 kvm_vcpu_init(vcpu, kvm, id);
3623 r = kvm_arch_vcpu_create(vcpu);
3625 goto vcpu_free_run_page;
3627 if (kvm->dirty_ring_size) {
3628 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3629 id, kvm->dirty_ring_size);
3631 goto arch_vcpu_destroy;
3634 mutex_lock(&kvm->lock);
3635 if (kvm_get_vcpu_by_id(kvm, id)) {
3637 goto unlock_vcpu_destroy;
3640 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3641 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
3643 /* Fill the stats id string for the vcpu */
3644 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3645 task_pid_nr(current), id);
3647 /* Now it's all set up, let userspace reach it */
3649 r = create_vcpu_fd(vcpu);
3651 kvm_put_kvm_no_destroy(kvm);
3652 goto unlock_vcpu_destroy;
3655 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
3658 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3659 * before kvm->online_vcpu's incremented value.
3662 atomic_inc(&kvm->online_vcpus);
3664 mutex_unlock(&kvm->lock);
3665 kvm_arch_vcpu_postcreate(vcpu);
3666 kvm_create_vcpu_debugfs(vcpu);
3669 unlock_vcpu_destroy:
3670 mutex_unlock(&kvm->lock);
3671 kvm_dirty_ring_free(&vcpu->dirty_ring);
3673 kvm_arch_vcpu_destroy(vcpu);
3675 free_page((unsigned long)vcpu->run);
3677 kmem_cache_free(kvm_vcpu_cache, vcpu);
3679 mutex_lock(&kvm->lock);
3680 kvm->created_vcpus--;
3681 mutex_unlock(&kvm->lock);
3685 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3688 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3689 vcpu->sigset_active = 1;
3690 vcpu->sigset = *sigset;
3692 vcpu->sigset_active = 0;
3696 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3697 size_t size, loff_t *offset)
3699 struct kvm_vcpu *vcpu = file->private_data;
3701 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3702 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3703 sizeof(vcpu->stat), user_buffer, size, offset);
3706 static const struct file_operations kvm_vcpu_stats_fops = {
3707 .read = kvm_vcpu_stats_read,
3708 .llseek = noop_llseek,
3711 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3715 char name[15 + ITOA_MAX_LEN + 1];
3717 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3719 fd = get_unused_fd_flags(O_CLOEXEC);
3723 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3726 return PTR_ERR(file);
3728 file->f_mode |= FMODE_PREAD;
3729 fd_install(fd, file);
3734 static long kvm_vcpu_ioctl(struct file *filp,
3735 unsigned int ioctl, unsigned long arg)
3737 struct kvm_vcpu *vcpu = filp->private_data;
3738 void __user *argp = (void __user *)arg;
3740 struct kvm_fpu *fpu = NULL;
3741 struct kvm_sregs *kvm_sregs = NULL;
3743 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
3746 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3750 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3751 * execution; mutex_lock() would break them.
3753 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3754 if (r != -ENOIOCTLCMD)
3757 if (mutex_lock_killable(&vcpu->mutex))
3765 oldpid = rcu_access_pointer(vcpu->pid);
3766 if (unlikely(oldpid != task_pid(current))) {
3767 /* The thread running this VCPU changed. */
3770 r = kvm_arch_vcpu_run_pid_change(vcpu);
3774 newpid = get_task_pid(current, PIDTYPE_PID);
3775 rcu_assign_pointer(vcpu->pid, newpid);
3780 r = kvm_arch_vcpu_ioctl_run(vcpu);
3781 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3784 case KVM_GET_REGS: {
3785 struct kvm_regs *kvm_regs;
3788 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3791 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3795 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3802 case KVM_SET_REGS: {
3803 struct kvm_regs *kvm_regs;
3805 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3806 if (IS_ERR(kvm_regs)) {
3807 r = PTR_ERR(kvm_regs);
3810 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3814 case KVM_GET_SREGS: {
3815 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3816 GFP_KERNEL_ACCOUNT);
3820 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3824 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3829 case KVM_SET_SREGS: {
3830 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3831 if (IS_ERR(kvm_sregs)) {
3832 r = PTR_ERR(kvm_sregs);
3836 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3839 case KVM_GET_MP_STATE: {
3840 struct kvm_mp_state mp_state;
3842 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3846 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3851 case KVM_SET_MP_STATE: {
3852 struct kvm_mp_state mp_state;
3855 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3857 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3860 case KVM_TRANSLATE: {
3861 struct kvm_translation tr;
3864 if (copy_from_user(&tr, argp, sizeof(tr)))
3866 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3870 if (copy_to_user(argp, &tr, sizeof(tr)))
3875 case KVM_SET_GUEST_DEBUG: {
3876 struct kvm_guest_debug dbg;
3879 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3881 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3884 case KVM_SET_SIGNAL_MASK: {
3885 struct kvm_signal_mask __user *sigmask_arg = argp;
3886 struct kvm_signal_mask kvm_sigmask;
3887 sigset_t sigset, *p;
3892 if (copy_from_user(&kvm_sigmask, argp,
3893 sizeof(kvm_sigmask)))
3896 if (kvm_sigmask.len != sizeof(sigset))
3899 if (copy_from_user(&sigset, sigmask_arg->sigset,
3904 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3908 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
3912 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3916 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3922 fpu = memdup_user(argp, sizeof(*fpu));
3928 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3931 case KVM_GET_STATS_FD: {
3932 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
3936 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3939 mutex_unlock(&vcpu->mutex);
3945 #ifdef CONFIG_KVM_COMPAT
3946 static long kvm_vcpu_compat_ioctl(struct file *filp,
3947 unsigned int ioctl, unsigned long arg)
3949 struct kvm_vcpu *vcpu = filp->private_data;
3950 void __user *argp = compat_ptr(arg);
3953 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
3957 case KVM_SET_SIGNAL_MASK: {
3958 struct kvm_signal_mask __user *sigmask_arg = argp;
3959 struct kvm_signal_mask kvm_sigmask;
3964 if (copy_from_user(&kvm_sigmask, argp,
3965 sizeof(kvm_sigmask)))
3968 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3971 if (get_compat_sigset(&sigset,
3972 (compat_sigset_t __user *)sigmask_arg->sigset))
3974 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3976 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3980 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3988 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3990 struct kvm_device *dev = filp->private_data;
3993 return dev->ops->mmap(dev, vma);
3998 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3999 int (*accessor)(struct kvm_device *dev,
4000 struct kvm_device_attr *attr),
4003 struct kvm_device_attr attr;
4008 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4011 return accessor(dev, &attr);
4014 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
4017 struct kvm_device *dev = filp->private_data;
4019 if (dev->kvm->mm != current->mm || dev->kvm->vm_bugged)
4023 case KVM_SET_DEVICE_ATTR:
4024 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
4025 case KVM_GET_DEVICE_ATTR:
4026 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
4027 case KVM_HAS_DEVICE_ATTR:
4028 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
4030 if (dev->ops->ioctl)
4031 return dev->ops->ioctl(dev, ioctl, arg);
4037 static int kvm_device_release(struct inode *inode, struct file *filp)
4039 struct kvm_device *dev = filp->private_data;
4040 struct kvm *kvm = dev->kvm;
4042 if (dev->ops->release) {
4043 mutex_lock(&kvm->lock);
4044 list_del(&dev->vm_node);
4045 dev->ops->release(dev);
4046 mutex_unlock(&kvm->lock);
4053 static const struct file_operations kvm_device_fops = {
4054 .unlocked_ioctl = kvm_device_ioctl,
4055 .release = kvm_device_release,
4056 KVM_COMPAT(kvm_device_ioctl),
4057 .mmap = kvm_device_mmap,
4060 struct kvm_device *kvm_device_from_filp(struct file *filp)
4062 if (filp->f_op != &kvm_device_fops)
4065 return filp->private_data;
4068 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
4069 #ifdef CONFIG_KVM_MPIC
4070 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
4071 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
4075 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
4077 if (type >= ARRAY_SIZE(kvm_device_ops_table))
4080 if (kvm_device_ops_table[type] != NULL)
4083 kvm_device_ops_table[type] = ops;
4087 void kvm_unregister_device_ops(u32 type)
4089 if (kvm_device_ops_table[type] != NULL)
4090 kvm_device_ops_table[type] = NULL;
4093 static int kvm_ioctl_create_device(struct kvm *kvm,
4094 struct kvm_create_device *cd)
4096 const struct kvm_device_ops *ops = NULL;
4097 struct kvm_device *dev;
4098 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
4102 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4105 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4106 ops = kvm_device_ops_table[type];
4113 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
4120 mutex_lock(&kvm->lock);
4121 ret = ops->create(dev, type);
4123 mutex_unlock(&kvm->lock);
4127 list_add(&dev->vm_node, &kvm->devices);
4128 mutex_unlock(&kvm->lock);
4134 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
4136 kvm_put_kvm_no_destroy(kvm);
4137 mutex_lock(&kvm->lock);
4138 list_del(&dev->vm_node);
4139 mutex_unlock(&kvm->lock);
4148 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4151 case KVM_CAP_USER_MEMORY:
4152 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4153 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
4154 case KVM_CAP_INTERNAL_ERROR_DATA:
4155 #ifdef CONFIG_HAVE_KVM_MSI
4156 case KVM_CAP_SIGNAL_MSI:
4158 #ifdef CONFIG_HAVE_KVM_IRQFD
4160 case KVM_CAP_IRQFD_RESAMPLE:
4162 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
4163 case KVM_CAP_CHECK_EXTENSION_VM:
4164 case KVM_CAP_ENABLE_CAP_VM:
4165 case KVM_CAP_HALT_POLL:
4167 #ifdef CONFIG_KVM_MMIO
4168 case KVM_CAP_COALESCED_MMIO:
4169 return KVM_COALESCED_MMIO_PAGE_OFFSET;
4170 case KVM_CAP_COALESCED_PIO:
4173 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4174 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4175 return KVM_DIRTY_LOG_MANUAL_CAPS;
4177 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4178 case KVM_CAP_IRQ_ROUTING:
4179 return KVM_MAX_IRQ_ROUTES;
4181 #if KVM_ADDRESS_SPACE_NUM > 1
4182 case KVM_CAP_MULTI_ADDRESS_SPACE:
4183 return KVM_ADDRESS_SPACE_NUM;
4185 case KVM_CAP_NR_MEMSLOTS:
4186 return KVM_USER_MEM_SLOTS;
4187 case KVM_CAP_DIRTY_LOG_RING:
4188 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
4189 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4193 case KVM_CAP_BINARY_STATS_FD:
4198 return kvm_vm_ioctl_check_extension(kvm, arg);
4201 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4205 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4208 /* the size should be power of 2 */
4209 if (!size || (size & (size - 1)))
4212 /* Should be bigger to keep the reserved entries, or a page */
4213 if (size < kvm_dirty_ring_get_rsvd_entries() *
4214 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4217 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4218 sizeof(struct kvm_dirty_gfn))
4221 /* We only allow it to set once */
4222 if (kvm->dirty_ring_size)
4225 mutex_lock(&kvm->lock);
4227 if (kvm->created_vcpus) {
4228 /* We don't allow to change this value after vcpu created */
4231 kvm->dirty_ring_size = size;
4235 mutex_unlock(&kvm->lock);
4239 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4242 struct kvm_vcpu *vcpu;
4245 if (!kvm->dirty_ring_size)
4248 mutex_lock(&kvm->slots_lock);
4250 kvm_for_each_vcpu(i, vcpu, kvm)
4251 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4253 mutex_unlock(&kvm->slots_lock);
4256 kvm_flush_remote_tlbs(kvm);
4261 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4262 struct kvm_enable_cap *cap)
4267 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4268 struct kvm_enable_cap *cap)
4271 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4272 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4273 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4275 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4276 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4278 if (cap->flags || (cap->args[0] & ~allowed_options))
4280 kvm->manual_dirty_log_protect = cap->args[0];
4284 case KVM_CAP_HALT_POLL: {
4285 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4288 kvm->max_halt_poll_ns = cap->args[0];
4291 case KVM_CAP_DIRTY_LOG_RING:
4292 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4294 return kvm_vm_ioctl_enable_cap(kvm, cap);
4298 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4299 size_t size, loff_t *offset)
4301 struct kvm *kvm = file->private_data;
4303 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4304 &kvm_vm_stats_desc[0], &kvm->stat,
4305 sizeof(kvm->stat), user_buffer, size, offset);
4308 static const struct file_operations kvm_vm_stats_fops = {
4309 .read = kvm_vm_stats_read,
4310 .llseek = noop_llseek,
4313 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4318 fd = get_unused_fd_flags(O_CLOEXEC);
4322 file = anon_inode_getfile("kvm-vm-stats",
4323 &kvm_vm_stats_fops, kvm, O_RDONLY);
4326 return PTR_ERR(file);
4328 file->f_mode |= FMODE_PREAD;
4329 fd_install(fd, file);
4334 static long kvm_vm_ioctl(struct file *filp,
4335 unsigned int ioctl, unsigned long arg)
4337 struct kvm *kvm = filp->private_data;
4338 void __user *argp = (void __user *)arg;
4341 if (kvm->mm != current->mm || kvm->vm_bugged)
4344 case KVM_CREATE_VCPU:
4345 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4347 case KVM_ENABLE_CAP: {
4348 struct kvm_enable_cap cap;
4351 if (copy_from_user(&cap, argp, sizeof(cap)))
4353 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4356 case KVM_SET_USER_MEMORY_REGION: {
4357 struct kvm_userspace_memory_region kvm_userspace_mem;
4360 if (copy_from_user(&kvm_userspace_mem, argp,
4361 sizeof(kvm_userspace_mem)))
4364 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4367 case KVM_GET_DIRTY_LOG: {
4368 struct kvm_dirty_log log;
4371 if (copy_from_user(&log, argp, sizeof(log)))
4373 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4376 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4377 case KVM_CLEAR_DIRTY_LOG: {
4378 struct kvm_clear_dirty_log log;
4381 if (copy_from_user(&log, argp, sizeof(log)))
4383 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4387 #ifdef CONFIG_KVM_MMIO
4388 case KVM_REGISTER_COALESCED_MMIO: {
4389 struct kvm_coalesced_mmio_zone zone;
4392 if (copy_from_user(&zone, argp, sizeof(zone)))
4394 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4397 case KVM_UNREGISTER_COALESCED_MMIO: {
4398 struct kvm_coalesced_mmio_zone zone;
4401 if (copy_from_user(&zone, argp, sizeof(zone)))
4403 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4408 struct kvm_irqfd data;
4411 if (copy_from_user(&data, argp, sizeof(data)))
4413 r = kvm_irqfd(kvm, &data);
4416 case KVM_IOEVENTFD: {
4417 struct kvm_ioeventfd data;
4420 if (copy_from_user(&data, argp, sizeof(data)))
4422 r = kvm_ioeventfd(kvm, &data);
4425 #ifdef CONFIG_HAVE_KVM_MSI
4426 case KVM_SIGNAL_MSI: {
4430 if (copy_from_user(&msi, argp, sizeof(msi)))
4432 r = kvm_send_userspace_msi(kvm, &msi);
4436 #ifdef __KVM_HAVE_IRQ_LINE
4437 case KVM_IRQ_LINE_STATUS:
4438 case KVM_IRQ_LINE: {
4439 struct kvm_irq_level irq_event;
4442 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4445 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4446 ioctl == KVM_IRQ_LINE_STATUS);
4451 if (ioctl == KVM_IRQ_LINE_STATUS) {
4452 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4460 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4461 case KVM_SET_GSI_ROUTING: {
4462 struct kvm_irq_routing routing;
4463 struct kvm_irq_routing __user *urouting;
4464 struct kvm_irq_routing_entry *entries = NULL;
4467 if (copy_from_user(&routing, argp, sizeof(routing)))
4470 if (!kvm_arch_can_set_irq_routing(kvm))
4472 if (routing.nr > KVM_MAX_IRQ_ROUTES)
4478 entries = vmemdup_user(urouting->entries,
4479 array_size(sizeof(*entries),
4481 if (IS_ERR(entries)) {
4482 r = PTR_ERR(entries);
4486 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4491 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4492 case KVM_CREATE_DEVICE: {
4493 struct kvm_create_device cd;
4496 if (copy_from_user(&cd, argp, sizeof(cd)))
4499 r = kvm_ioctl_create_device(kvm, &cd);
4504 if (copy_to_user(argp, &cd, sizeof(cd)))
4510 case KVM_CHECK_EXTENSION:
4511 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4513 case KVM_RESET_DIRTY_RINGS:
4514 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4516 case KVM_GET_STATS_FD:
4517 r = kvm_vm_ioctl_get_stats_fd(kvm);
4520 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4526 #ifdef CONFIG_KVM_COMPAT
4527 struct compat_kvm_dirty_log {
4531 compat_uptr_t dirty_bitmap; /* one bit per page */
4536 struct compat_kvm_clear_dirty_log {
4541 compat_uptr_t dirty_bitmap; /* one bit per page */
4546 static long kvm_vm_compat_ioctl(struct file *filp,
4547 unsigned int ioctl, unsigned long arg)
4549 struct kvm *kvm = filp->private_data;
4552 if (kvm->mm != current->mm || kvm->vm_bugged)
4555 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4556 case KVM_CLEAR_DIRTY_LOG: {
4557 struct compat_kvm_clear_dirty_log compat_log;
4558 struct kvm_clear_dirty_log log;
4560 if (copy_from_user(&compat_log, (void __user *)arg,
4561 sizeof(compat_log)))
4563 log.slot = compat_log.slot;
4564 log.num_pages = compat_log.num_pages;
4565 log.first_page = compat_log.first_page;
4566 log.padding2 = compat_log.padding2;
4567 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4569 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4573 case KVM_GET_DIRTY_LOG: {
4574 struct compat_kvm_dirty_log compat_log;
4575 struct kvm_dirty_log log;
4577 if (copy_from_user(&compat_log, (void __user *)arg,
4578 sizeof(compat_log)))
4580 log.slot = compat_log.slot;
4581 log.padding1 = compat_log.padding1;
4582 log.padding2 = compat_log.padding2;
4583 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4585 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4589 r = kvm_vm_ioctl(filp, ioctl, arg);
4595 static struct file_operations kvm_vm_fops = {
4596 .release = kvm_vm_release,
4597 .unlocked_ioctl = kvm_vm_ioctl,
4598 .llseek = noop_llseek,
4599 KVM_COMPAT(kvm_vm_compat_ioctl),
4602 bool file_is_kvm(struct file *file)
4604 return file && file->f_op == &kvm_vm_fops;
4606 EXPORT_SYMBOL_GPL(file_is_kvm);
4608 static int kvm_dev_ioctl_create_vm(unsigned long type)
4614 kvm = kvm_create_vm(type);
4616 return PTR_ERR(kvm);
4617 #ifdef CONFIG_KVM_MMIO
4618 r = kvm_coalesced_mmio_init(kvm);
4622 r = get_unused_fd_flags(O_CLOEXEC);
4626 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4627 "kvm-%d", task_pid_nr(current));
4629 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4637 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4638 * already set, with ->release() being kvm_vm_release(). In error
4639 * cases it will be called by the final fput(file) and will take
4640 * care of doing kvm_put_kvm(kvm).
4642 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4647 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4649 fd_install(r, file);
4657 static long kvm_dev_ioctl(struct file *filp,
4658 unsigned int ioctl, unsigned long arg)
4663 case KVM_GET_API_VERSION:
4666 r = KVM_API_VERSION;
4669 r = kvm_dev_ioctl_create_vm(arg);
4671 case KVM_CHECK_EXTENSION:
4672 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4674 case KVM_GET_VCPU_MMAP_SIZE:
4677 r = PAGE_SIZE; /* struct kvm_run */
4679 r += PAGE_SIZE; /* pio data page */
4681 #ifdef CONFIG_KVM_MMIO
4682 r += PAGE_SIZE; /* coalesced mmio ring page */
4685 case KVM_TRACE_ENABLE:
4686 case KVM_TRACE_PAUSE:
4687 case KVM_TRACE_DISABLE:
4691 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4697 static struct file_operations kvm_chardev_ops = {
4698 .unlocked_ioctl = kvm_dev_ioctl,
4699 .llseek = noop_llseek,
4700 KVM_COMPAT(kvm_dev_ioctl),
4703 static struct miscdevice kvm_dev = {
4709 static void hardware_enable_nolock(void *junk)
4711 int cpu = raw_smp_processor_id();
4714 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4717 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4719 r = kvm_arch_hardware_enable();
4722 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4723 atomic_inc(&hardware_enable_failed);
4724 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4728 static int kvm_starting_cpu(unsigned int cpu)
4730 raw_spin_lock(&kvm_count_lock);
4731 if (kvm_usage_count)
4732 hardware_enable_nolock(NULL);
4733 raw_spin_unlock(&kvm_count_lock);
4737 static void hardware_disable_nolock(void *junk)
4739 int cpu = raw_smp_processor_id();
4741 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4743 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4744 kvm_arch_hardware_disable();
4747 static int kvm_dying_cpu(unsigned int cpu)
4749 raw_spin_lock(&kvm_count_lock);
4750 if (kvm_usage_count)
4751 hardware_disable_nolock(NULL);
4752 raw_spin_unlock(&kvm_count_lock);
4756 static void hardware_disable_all_nolock(void)
4758 BUG_ON(!kvm_usage_count);
4761 if (!kvm_usage_count)
4762 on_each_cpu(hardware_disable_nolock, NULL, 1);
4765 static void hardware_disable_all(void)
4767 raw_spin_lock(&kvm_count_lock);
4768 hardware_disable_all_nolock();
4769 raw_spin_unlock(&kvm_count_lock);
4772 static int hardware_enable_all(void)
4776 raw_spin_lock(&kvm_count_lock);
4779 if (kvm_usage_count == 1) {
4780 atomic_set(&hardware_enable_failed, 0);
4781 on_each_cpu(hardware_enable_nolock, NULL, 1);
4783 if (atomic_read(&hardware_enable_failed)) {
4784 hardware_disable_all_nolock();
4789 raw_spin_unlock(&kvm_count_lock);
4794 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4798 * Some (well, at least mine) BIOSes hang on reboot if
4801 * And Intel TXT required VMX off for all cpu when system shutdown.
4803 pr_info("kvm: exiting hardware virtualization\n");
4804 kvm_rebooting = true;
4805 on_each_cpu(hardware_disable_nolock, NULL, 1);
4809 static struct notifier_block kvm_reboot_notifier = {
4810 .notifier_call = kvm_reboot,
4814 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4818 for (i = 0; i < bus->dev_count; i++) {
4819 struct kvm_io_device *pos = bus->range[i].dev;
4821 kvm_iodevice_destructor(pos);
4826 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4827 const struct kvm_io_range *r2)
4829 gpa_t addr1 = r1->addr;
4830 gpa_t addr2 = r2->addr;
4835 /* If r2->len == 0, match the exact address. If r2->len != 0,
4836 * accept any overlapping write. Any order is acceptable for
4837 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4838 * we process all of them.
4851 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4853 return kvm_io_bus_cmp(p1, p2);
4856 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4857 gpa_t addr, int len)
4859 struct kvm_io_range *range, key;
4862 key = (struct kvm_io_range) {
4867 range = bsearch(&key, bus->range, bus->dev_count,
4868 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4872 off = range - bus->range;
4874 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4880 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4881 struct kvm_io_range *range, const void *val)
4885 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4889 while (idx < bus->dev_count &&
4890 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4891 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4900 /* kvm_io_bus_write - called under kvm->slots_lock */
4901 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4902 int len, const void *val)
4904 struct kvm_io_bus *bus;
4905 struct kvm_io_range range;
4908 range = (struct kvm_io_range) {
4913 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4916 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4917 return r < 0 ? r : 0;
4919 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
4921 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4922 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4923 gpa_t addr, int len, const void *val, long cookie)
4925 struct kvm_io_bus *bus;
4926 struct kvm_io_range range;
4928 range = (struct kvm_io_range) {
4933 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4937 /* First try the device referenced by cookie. */
4938 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4939 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4940 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4945 * cookie contained garbage; fall back to search and return the
4946 * correct cookie value.
4948 return __kvm_io_bus_write(vcpu, bus, &range, val);
4951 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4952 struct kvm_io_range *range, void *val)
4956 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4960 while (idx < bus->dev_count &&
4961 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4962 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4971 /* kvm_io_bus_read - called under kvm->slots_lock */
4972 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4975 struct kvm_io_bus *bus;
4976 struct kvm_io_range range;
4979 range = (struct kvm_io_range) {
4984 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4987 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4988 return r < 0 ? r : 0;
4991 /* Caller must hold slots_lock. */
4992 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4993 int len, struct kvm_io_device *dev)
4996 struct kvm_io_bus *new_bus, *bus;
4997 struct kvm_io_range range;
4999 bus = kvm_get_bus(kvm, bus_idx);
5003 /* exclude ioeventfd which is limited by maximum fd */
5004 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
5007 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
5008 GFP_KERNEL_ACCOUNT);
5012 range = (struct kvm_io_range) {
5018 for (i = 0; i < bus->dev_count; i++)
5019 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
5022 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
5023 new_bus->dev_count++;
5024 new_bus->range[i] = range;
5025 memcpy(new_bus->range + i + 1, bus->range + i,
5026 (bus->dev_count - i) * sizeof(struct kvm_io_range));
5027 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5028 synchronize_srcu_expedited(&kvm->srcu);
5034 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5035 struct kvm_io_device *dev)
5038 struct kvm_io_bus *new_bus, *bus;
5040 lockdep_assert_held(&kvm->slots_lock);
5042 bus = kvm_get_bus(kvm, bus_idx);
5046 for (i = 0; i < bus->dev_count; i++) {
5047 if (bus->range[i].dev == dev) {
5052 if (i == bus->dev_count)
5055 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
5056 GFP_KERNEL_ACCOUNT);
5058 memcpy(new_bus, bus, struct_size(bus, range, i));
5059 new_bus->dev_count--;
5060 memcpy(new_bus->range + i, bus->range + i + 1,
5061 flex_array_size(new_bus, range, new_bus->dev_count - i));
5064 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5065 synchronize_srcu_expedited(&kvm->srcu);
5067 /* Destroy the old bus _after_ installing the (null) bus. */
5069 pr_err("kvm: failed to shrink bus, removing it completely\n");
5070 for (j = 0; j < bus->dev_count; j++) {
5073 kvm_iodevice_destructor(bus->range[j].dev);
5078 return new_bus ? 0 : -ENOMEM;
5081 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5084 struct kvm_io_bus *bus;
5085 int dev_idx, srcu_idx;
5086 struct kvm_io_device *iodev = NULL;
5088 srcu_idx = srcu_read_lock(&kvm->srcu);
5090 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
5094 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5098 iodev = bus->range[dev_idx].dev;
5101 srcu_read_unlock(&kvm->srcu, srcu_idx);
5105 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5107 static int kvm_debugfs_open(struct inode *inode, struct file *file,
5108 int (*get)(void *, u64 *), int (*set)(void *, u64),
5111 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5115 * The debugfs files are a reference to the kvm struct which
5116 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
5117 * avoids the race between open and the removal of the debugfs directory.
5119 if (!kvm_get_kvm_safe(stat_data->kvm))
5122 if (simple_attr_open(inode, file, get,
5123 kvm_stats_debugfs_mode(stat_data->desc) & 0222
5126 kvm_put_kvm(stat_data->kvm);
5133 static int kvm_debugfs_release(struct inode *inode, struct file *file)
5135 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5138 simple_attr_release(inode, file);
5139 kvm_put_kvm(stat_data->kvm);
5144 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
5146 *val = *(u64 *)((void *)(&kvm->stat) + offset);
5151 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
5153 *(u64 *)((void *)(&kvm->stat) + offset) = 0;
5158 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
5161 struct kvm_vcpu *vcpu;
5165 kvm_for_each_vcpu(i, vcpu, kvm)
5166 *val += *(u64 *)((void *)(&vcpu->stat) + offset);
5171 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
5174 struct kvm_vcpu *vcpu;
5176 kvm_for_each_vcpu(i, vcpu, kvm)
5177 *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
5182 static int kvm_stat_data_get(void *data, u64 *val)
5185 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5187 switch (stat_data->kind) {
5189 r = kvm_get_stat_per_vm(stat_data->kvm,
5190 stat_data->desc->desc.offset, val);
5193 r = kvm_get_stat_per_vcpu(stat_data->kvm,
5194 stat_data->desc->desc.offset, val);
5201 static int kvm_stat_data_clear(void *data, u64 val)
5204 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5209 switch (stat_data->kind) {
5211 r = kvm_clear_stat_per_vm(stat_data->kvm,
5212 stat_data->desc->desc.offset);
5215 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
5216 stat_data->desc->desc.offset);
5223 static int kvm_stat_data_open(struct inode *inode, struct file *file)
5225 __simple_attr_check_format("%llu\n", 0ull);
5226 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5227 kvm_stat_data_clear, "%llu\n");
5230 static const struct file_operations stat_fops_per_vm = {
5231 .owner = THIS_MODULE,
5232 .open = kvm_stat_data_open,
5233 .release = kvm_debugfs_release,
5234 .read = simple_attr_read,
5235 .write = simple_attr_write,
5236 .llseek = no_llseek,
5239 static int vm_stat_get(void *_offset, u64 *val)
5241 unsigned offset = (long)_offset;
5246 mutex_lock(&kvm_lock);
5247 list_for_each_entry(kvm, &vm_list, vm_list) {
5248 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
5251 mutex_unlock(&kvm_lock);
5255 static int vm_stat_clear(void *_offset, u64 val)
5257 unsigned offset = (long)_offset;
5263 mutex_lock(&kvm_lock);
5264 list_for_each_entry(kvm, &vm_list, vm_list) {
5265 kvm_clear_stat_per_vm(kvm, offset);
5267 mutex_unlock(&kvm_lock);
5272 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
5273 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
5275 static int vcpu_stat_get(void *_offset, u64 *val)
5277 unsigned offset = (long)_offset;
5282 mutex_lock(&kvm_lock);
5283 list_for_each_entry(kvm, &vm_list, vm_list) {
5284 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
5287 mutex_unlock(&kvm_lock);
5291 static int vcpu_stat_clear(void *_offset, u64 val)
5293 unsigned offset = (long)_offset;
5299 mutex_lock(&kvm_lock);
5300 list_for_each_entry(kvm, &vm_list, vm_list) {
5301 kvm_clear_stat_per_vcpu(kvm, offset);
5303 mutex_unlock(&kvm_lock);
5308 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5310 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
5312 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5314 struct kobj_uevent_env *env;
5315 unsigned long long created, active;
5317 if (!kvm_dev.this_device || !kvm)
5320 mutex_lock(&kvm_lock);
5321 if (type == KVM_EVENT_CREATE_VM) {
5322 kvm_createvm_count++;
5324 } else if (type == KVM_EVENT_DESTROY_VM) {
5327 created = kvm_createvm_count;
5328 active = kvm_active_vms;
5329 mutex_unlock(&kvm_lock);
5331 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
5335 add_uevent_var(env, "CREATED=%llu", created);
5336 add_uevent_var(env, "COUNT=%llu", active);
5338 if (type == KVM_EVENT_CREATE_VM) {
5339 add_uevent_var(env, "EVENT=create");
5340 kvm->userspace_pid = task_pid_nr(current);
5341 } else if (type == KVM_EVENT_DESTROY_VM) {
5342 add_uevent_var(env, "EVENT=destroy");
5344 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5346 if (kvm->debugfs_dentry) {
5347 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5350 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5352 add_uevent_var(env, "STATS_PATH=%s", tmp);
5356 /* no need for checks, since we are adding at most only 5 keys */
5357 env->envp[env->envp_idx++] = NULL;
5358 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5362 static void kvm_init_debug(void)
5364 const struct file_operations *fops;
5365 const struct _kvm_stats_desc *pdesc;
5368 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5370 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5371 pdesc = &kvm_vm_stats_desc[i];
5372 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5373 fops = &vm_stat_fops;
5375 fops = &vm_stat_readonly_fops;
5376 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5378 (void *)(long)pdesc->desc.offset, fops);
5381 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5382 pdesc = &kvm_vcpu_stats_desc[i];
5383 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5384 fops = &vcpu_stat_fops;
5386 fops = &vcpu_stat_readonly_fops;
5387 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5389 (void *)(long)pdesc->desc.offset, fops);
5393 static int kvm_suspend(void)
5395 if (kvm_usage_count)
5396 hardware_disable_nolock(NULL);
5400 static void kvm_resume(void)
5402 if (kvm_usage_count) {
5403 #ifdef CONFIG_LOCKDEP
5404 WARN_ON(lockdep_is_held(&kvm_count_lock));
5406 hardware_enable_nolock(NULL);
5410 static struct syscore_ops kvm_syscore_ops = {
5411 .suspend = kvm_suspend,
5412 .resume = kvm_resume,
5416 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5418 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5421 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5423 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5425 WRITE_ONCE(vcpu->preempted, false);
5426 WRITE_ONCE(vcpu->ready, false);
5428 __this_cpu_write(kvm_running_vcpu, vcpu);
5429 kvm_arch_sched_in(vcpu, cpu);
5430 kvm_arch_vcpu_load(vcpu, cpu);
5433 static void kvm_sched_out(struct preempt_notifier *pn,
5434 struct task_struct *next)
5436 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5438 if (current->on_rq) {
5439 WRITE_ONCE(vcpu->preempted, true);
5440 WRITE_ONCE(vcpu->ready, true);
5442 kvm_arch_vcpu_put(vcpu);
5443 __this_cpu_write(kvm_running_vcpu, NULL);
5447 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5449 * We can disable preemption locally around accessing the per-CPU variable,
5450 * and use the resolved vcpu pointer after enabling preemption again,
5451 * because even if the current thread is migrated to another CPU, reading
5452 * the per-CPU value later will give us the same value as we update the
5453 * per-CPU variable in the preempt notifier handlers.
5455 struct kvm_vcpu *kvm_get_running_vcpu(void)
5457 struct kvm_vcpu *vcpu;
5460 vcpu = __this_cpu_read(kvm_running_vcpu);
5465 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5468 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5470 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5472 return &kvm_running_vcpu;
5475 struct kvm_cpu_compat_check {
5480 static void check_processor_compat(void *data)
5482 struct kvm_cpu_compat_check *c = data;
5484 *c->ret = kvm_arch_check_processor_compat(c->opaque);
5487 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5488 struct module *module)
5490 struct kvm_cpu_compat_check c;
5494 r = kvm_arch_init(opaque);
5499 * kvm_arch_init makes sure there's at most one caller
5500 * for architectures that support multiple implementations,
5501 * like intel and amd on x86.
5502 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5503 * conflicts in case kvm is already setup for another implementation.
5505 r = kvm_irqfd_init();
5509 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5514 r = kvm_arch_hardware_setup(opaque);
5520 for_each_online_cpu(cpu) {
5521 smp_call_function_single(cpu, check_processor_compat, &c, 1);
5526 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5527 kvm_starting_cpu, kvm_dying_cpu);
5530 register_reboot_notifier(&kvm_reboot_notifier);
5532 /* A kmem cache lets us meet the alignment requirements of fx_save. */
5534 vcpu_align = __alignof__(struct kvm_vcpu);
5536 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5538 offsetof(struct kvm_vcpu, arch),
5539 offsetofend(struct kvm_vcpu, stats_id)
5540 - offsetof(struct kvm_vcpu, arch),
5542 if (!kvm_vcpu_cache) {
5547 r = kvm_async_pf_init();
5551 kvm_chardev_ops.owner = module;
5552 kvm_vm_fops.owner = module;
5553 kvm_vcpu_fops.owner = module;
5555 r = misc_register(&kvm_dev);
5557 pr_err("kvm: misc device register failed\n");
5561 register_syscore_ops(&kvm_syscore_ops);
5563 kvm_preempt_ops.sched_in = kvm_sched_in;
5564 kvm_preempt_ops.sched_out = kvm_sched_out;
5568 r = kvm_vfio_ops_init();
5574 kvm_async_pf_deinit();
5576 kmem_cache_destroy(kvm_vcpu_cache);
5578 unregister_reboot_notifier(&kvm_reboot_notifier);
5579 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5581 kvm_arch_hardware_unsetup();
5583 free_cpumask_var(cpus_hardware_enabled);
5591 EXPORT_SYMBOL_GPL(kvm_init);
5595 debugfs_remove_recursive(kvm_debugfs_dir);
5596 misc_deregister(&kvm_dev);
5597 kmem_cache_destroy(kvm_vcpu_cache);
5598 kvm_async_pf_deinit();
5599 unregister_syscore_ops(&kvm_syscore_ops);
5600 unregister_reboot_notifier(&kvm_reboot_notifier);
5601 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5602 on_each_cpu(hardware_disable_nolock, NULL, 1);
5603 kvm_arch_hardware_unsetup();
5606 free_cpumask_var(cpus_hardware_enabled);
5607 kvm_vfio_ops_exit();
5609 EXPORT_SYMBOL_GPL(kvm_exit);
5611 struct kvm_vm_worker_thread_context {
5613 struct task_struct *parent;
5614 struct completion init_done;
5615 kvm_vm_thread_fn_t thread_fn;
5620 static int kvm_vm_worker_thread(void *context)
5623 * The init_context is allocated on the stack of the parent thread, so
5624 * we have to locally copy anything that is needed beyond initialization
5626 struct kvm_vm_worker_thread_context *init_context = context;
5627 struct kvm *kvm = init_context->kvm;
5628 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5629 uintptr_t data = init_context->data;
5632 err = kthread_park(current);
5633 /* kthread_park(current) is never supposed to return an error */
5638 err = cgroup_attach_task_all(init_context->parent, current);
5640 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5645 set_user_nice(current, task_nice(init_context->parent));
5648 init_context->err = err;
5649 complete(&init_context->init_done);
5650 init_context = NULL;
5655 /* Wait to be woken up by the spawner before proceeding. */
5658 if (!kthread_should_stop())
5659 err = thread_fn(kvm, data);
5664 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5665 uintptr_t data, const char *name,
5666 struct task_struct **thread_ptr)
5668 struct kvm_vm_worker_thread_context init_context = {};
5669 struct task_struct *thread;
5672 init_context.kvm = kvm;
5673 init_context.parent = current;
5674 init_context.thread_fn = thread_fn;
5675 init_context.data = data;
5676 init_completion(&init_context.init_done);
5678 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5679 "%s-%d", name, task_pid_nr(current));
5681 return PTR_ERR(thread);
5683 /* kthread_run is never supposed to return NULL */
5684 WARN_ON(thread == NULL);
5686 wait_for_completion(&init_context.init_done);
5688 if (!init_context.err)
5689 *thread_ptr = thread;
5691 return init_context.err;