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))
1669 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1671 /* We can read the guest memory with __xxx_user() later on. */
1672 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1673 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1674 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1677 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1679 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1683 * Make a full copy of the old memslot, the pointer will become stale
1684 * when the memslots are re-sorted by update_memslots(), and the old
1685 * memslot needs to be referenced after calling update_memslots(), e.g.
1686 * to free its resources and for arch specific behavior.
1688 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1693 memset(&old, 0, sizeof(old));
1697 if (!mem->memory_size)
1698 return kvm_delete_memslot(kvm, mem, &old, as_id);
1702 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1703 new.npages = mem->memory_size >> PAGE_SHIFT;
1704 new.flags = mem->flags;
1705 new.userspace_addr = mem->userspace_addr;
1707 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1711 change = KVM_MR_CREATE;
1712 new.dirty_bitmap = NULL;
1713 memset(&new.arch, 0, sizeof(new.arch));
1714 } else { /* Modify an existing slot. */
1715 if ((new.userspace_addr != old.userspace_addr) ||
1716 (new.npages != old.npages) ||
1717 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1720 if (new.base_gfn != old.base_gfn)
1721 change = KVM_MR_MOVE;
1722 else if (new.flags != old.flags)
1723 change = KVM_MR_FLAGS_ONLY;
1724 else /* Nothing to change. */
1727 /* Copy dirty_bitmap and arch from the current memslot. */
1728 new.dirty_bitmap = old.dirty_bitmap;
1729 memcpy(&new.arch, &old.arch, sizeof(new.arch));
1732 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1733 /* Check for overlaps */
1734 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1737 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1738 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1743 /* Allocate/free page dirty bitmap as needed */
1744 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1745 new.dirty_bitmap = NULL;
1746 else if (!new.dirty_bitmap && !kvm->dirty_ring_size) {
1747 r = kvm_alloc_dirty_bitmap(&new);
1751 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1752 bitmap_set(new.dirty_bitmap, 0, new.npages);
1755 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1759 if (old.dirty_bitmap && !new.dirty_bitmap)
1760 kvm_destroy_dirty_bitmap(&old);
1764 if (new.dirty_bitmap && !old.dirty_bitmap)
1765 kvm_destroy_dirty_bitmap(&new);
1768 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1770 int kvm_set_memory_region(struct kvm *kvm,
1771 const struct kvm_userspace_memory_region *mem)
1775 mutex_lock(&kvm->slots_lock);
1776 r = __kvm_set_memory_region(kvm, mem);
1777 mutex_unlock(&kvm->slots_lock);
1780 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1782 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1783 struct kvm_userspace_memory_region *mem)
1785 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1788 return kvm_set_memory_region(kvm, mem);
1791 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1793 * kvm_get_dirty_log - get a snapshot of dirty pages
1794 * @kvm: pointer to kvm instance
1795 * @log: slot id and address to which we copy the log
1796 * @is_dirty: set to '1' if any dirty pages were found
1797 * @memslot: set to the associated memslot, always valid on success
1799 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1800 int *is_dirty, struct kvm_memory_slot **memslot)
1802 struct kvm_memslots *slots;
1805 unsigned long any = 0;
1807 /* Dirty ring tracking is exclusive to dirty log tracking */
1808 if (kvm->dirty_ring_size)
1814 as_id = log->slot >> 16;
1815 id = (u16)log->slot;
1816 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1819 slots = __kvm_memslots(kvm, as_id);
1820 *memslot = id_to_memslot(slots, id);
1821 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1824 kvm_arch_sync_dirty_log(kvm, *memslot);
1826 n = kvm_dirty_bitmap_bytes(*memslot);
1828 for (i = 0; !any && i < n/sizeof(long); ++i)
1829 any = (*memslot)->dirty_bitmap[i];
1831 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1838 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1840 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1842 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1843 * and reenable dirty page tracking for the corresponding pages.
1844 * @kvm: pointer to kvm instance
1845 * @log: slot id and address to which we copy the log
1847 * We need to keep it in mind that VCPU threads can write to the bitmap
1848 * concurrently. So, to avoid losing track of dirty pages we keep the
1851 * 1. Take a snapshot of the bit and clear it if needed.
1852 * 2. Write protect the corresponding page.
1853 * 3. Copy the snapshot to the userspace.
1854 * 4. Upon return caller flushes TLB's if needed.
1856 * Between 2 and 4, the guest may write to the page using the remaining TLB
1857 * entry. This is not a problem because the page is reported dirty using
1858 * the snapshot taken before and step 4 ensures that writes done after
1859 * exiting to userspace will be logged for the next call.
1862 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
1864 struct kvm_memslots *slots;
1865 struct kvm_memory_slot *memslot;
1868 unsigned long *dirty_bitmap;
1869 unsigned long *dirty_bitmap_buffer;
1872 /* Dirty ring tracking is exclusive to dirty log tracking */
1873 if (kvm->dirty_ring_size)
1876 as_id = log->slot >> 16;
1877 id = (u16)log->slot;
1878 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1881 slots = __kvm_memslots(kvm, as_id);
1882 memslot = id_to_memslot(slots, id);
1883 if (!memslot || !memslot->dirty_bitmap)
1886 dirty_bitmap = memslot->dirty_bitmap;
1888 kvm_arch_sync_dirty_log(kvm, memslot);
1890 n = kvm_dirty_bitmap_bytes(memslot);
1892 if (kvm->manual_dirty_log_protect) {
1894 * Unlike kvm_get_dirty_log, we always return false in *flush,
1895 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1896 * is some code duplication between this function and
1897 * kvm_get_dirty_log, but hopefully all architecture
1898 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1899 * can be eliminated.
1901 dirty_bitmap_buffer = dirty_bitmap;
1903 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1904 memset(dirty_bitmap_buffer, 0, n);
1907 for (i = 0; i < n / sizeof(long); i++) {
1911 if (!dirty_bitmap[i])
1915 mask = xchg(&dirty_bitmap[i], 0);
1916 dirty_bitmap_buffer[i] = mask;
1918 offset = i * BITS_PER_LONG;
1919 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1922 KVM_MMU_UNLOCK(kvm);
1926 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1928 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1935 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1936 * @kvm: kvm instance
1937 * @log: slot id and address to which we copy the log
1939 * Steps 1-4 below provide general overview of dirty page logging. See
1940 * kvm_get_dirty_log_protect() function description for additional details.
1942 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1943 * always flush the TLB (step 4) even if previous step failed and the dirty
1944 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1945 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1946 * writes will be marked dirty for next log read.
1948 * 1. Take a snapshot of the bit and clear it if needed.
1949 * 2. Write protect the corresponding page.
1950 * 3. Copy the snapshot to the userspace.
1951 * 4. Flush TLB's if needed.
1953 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1954 struct kvm_dirty_log *log)
1958 mutex_lock(&kvm->slots_lock);
1960 r = kvm_get_dirty_log_protect(kvm, log);
1962 mutex_unlock(&kvm->slots_lock);
1967 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1968 * and reenable dirty page tracking for the corresponding pages.
1969 * @kvm: pointer to kvm instance
1970 * @log: slot id and address from which to fetch the bitmap of dirty pages
1972 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1973 struct kvm_clear_dirty_log *log)
1975 struct kvm_memslots *slots;
1976 struct kvm_memory_slot *memslot;
1980 unsigned long *dirty_bitmap;
1981 unsigned long *dirty_bitmap_buffer;
1984 /* Dirty ring tracking is exclusive to dirty log tracking */
1985 if (kvm->dirty_ring_size)
1988 as_id = log->slot >> 16;
1989 id = (u16)log->slot;
1990 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1993 if (log->first_page & 63)
1996 slots = __kvm_memslots(kvm, as_id);
1997 memslot = id_to_memslot(slots, id);
1998 if (!memslot || !memslot->dirty_bitmap)
2001 dirty_bitmap = memslot->dirty_bitmap;
2003 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
2005 if (log->first_page > memslot->npages ||
2006 log->num_pages > memslot->npages - log->first_page ||
2007 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
2010 kvm_arch_sync_dirty_log(kvm, memslot);
2013 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2014 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2018 for (offset = log->first_page, i = offset / BITS_PER_LONG,
2019 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2020 i++, offset += BITS_PER_LONG) {
2021 unsigned long mask = *dirty_bitmap_buffer++;
2022 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2026 mask &= atomic_long_fetch_andnot(mask, p);
2029 * mask contains the bits that really have been cleared. This
2030 * never includes any bits beyond the length of the memslot (if
2031 * the length is not aligned to 64 pages), therefore it is not
2032 * a problem if userspace sets them in log->dirty_bitmap.
2036 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2040 KVM_MMU_UNLOCK(kvm);
2043 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2048 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2049 struct kvm_clear_dirty_log *log)
2053 mutex_lock(&kvm->slots_lock);
2055 r = kvm_clear_dirty_log_protect(kvm, log);
2057 mutex_unlock(&kvm->slots_lock);
2060 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2062 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2064 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2066 EXPORT_SYMBOL_GPL(gfn_to_memslot);
2068 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2070 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2071 struct kvm_memory_slot *slot;
2074 slot = try_get_memslot(slots, vcpu->last_used_slot, gfn);
2079 * Fall back to searching all memslots. We purposely use
2080 * search_memslots() instead of __gfn_to_memslot() to avoid
2081 * thrashing the VM-wide last_used_index in kvm_memslots.
2083 slot = search_memslots(slots, gfn, &slot_index);
2085 vcpu->last_used_slot = slot_index;
2091 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
2093 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
2095 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
2097 return kvm_is_visible_memslot(memslot);
2099 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2101 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2103 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2105 return kvm_is_visible_memslot(memslot);
2107 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2109 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
2111 struct vm_area_struct *vma;
2112 unsigned long addr, size;
2116 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
2117 if (kvm_is_error_hva(addr))
2120 mmap_read_lock(current->mm);
2121 vma = find_vma(current->mm, addr);
2125 size = vma_kernel_pagesize(vma);
2128 mmap_read_unlock(current->mm);
2133 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
2135 return slot->flags & KVM_MEM_READONLY;
2138 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2139 gfn_t *nr_pages, bool write)
2141 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
2142 return KVM_HVA_ERR_BAD;
2144 if (memslot_is_readonly(slot) && write)
2145 return KVM_HVA_ERR_RO_BAD;
2148 *nr_pages = slot->npages - (gfn - slot->base_gfn);
2150 return __gfn_to_hva_memslot(slot, gfn);
2153 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2156 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2159 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2162 return gfn_to_hva_many(slot, gfn, NULL);
2164 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2166 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2168 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2170 EXPORT_SYMBOL_GPL(gfn_to_hva);
2172 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2174 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2176 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2179 * Return the hva of a @gfn and the R/W attribute if possible.
2181 * @slot: the kvm_memory_slot which contains @gfn
2182 * @gfn: the gfn to be translated
2183 * @writable: used to return the read/write attribute of the @slot if the hva
2184 * is valid and @writable is not NULL
2186 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2187 gfn_t gfn, bool *writable)
2189 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2191 if (!kvm_is_error_hva(hva) && writable)
2192 *writable = !memslot_is_readonly(slot);
2197 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2199 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2201 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2204 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2206 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2208 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2211 static inline int check_user_page_hwpoison(unsigned long addr)
2213 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
2215 rc = get_user_pages(addr, 1, flags, NULL, NULL);
2216 return rc == -EHWPOISON;
2220 * The fast path to get the writable pfn which will be stored in @pfn,
2221 * true indicates success, otherwise false is returned. It's also the
2222 * only part that runs if we can in atomic context.
2224 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2225 bool *writable, kvm_pfn_t *pfn)
2227 struct page *page[1];
2230 * Fast pin a writable pfn only if it is a write fault request
2231 * or the caller allows to map a writable pfn for a read fault
2234 if (!(write_fault || writable))
2237 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2238 *pfn = page_to_pfn(page[0]);
2249 * The slow path to get the pfn of the specified host virtual address,
2250 * 1 indicates success, -errno is returned if error is detected.
2252 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2253 bool *writable, kvm_pfn_t *pfn)
2255 unsigned int flags = FOLL_HWPOISON;
2262 *writable = write_fault;
2265 flags |= FOLL_WRITE;
2267 flags |= FOLL_NOWAIT;
2269 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2273 /* map read fault as writable if possible */
2274 if (unlikely(!write_fault) && writable) {
2277 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2283 *pfn = page_to_pfn(page);
2287 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2289 if (unlikely(!(vma->vm_flags & VM_READ)))
2292 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2298 static int kvm_try_get_pfn(kvm_pfn_t pfn)
2300 if (kvm_is_reserved_pfn(pfn))
2302 return get_page_unless_zero(pfn_to_page(pfn));
2305 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2306 unsigned long addr, bool *async,
2307 bool write_fault, bool *writable,
2315 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2318 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2319 * not call the fault handler, so do it here.
2321 bool unlocked = false;
2322 r = fixup_user_fault(current->mm, addr,
2323 (write_fault ? FAULT_FLAG_WRITE : 0),
2330 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2335 if (write_fault && !pte_write(*ptep)) {
2336 pfn = KVM_PFN_ERR_RO_FAULT;
2341 *writable = pte_write(*ptep);
2342 pfn = pte_pfn(*ptep);
2345 * Get a reference here because callers of *hva_to_pfn* and
2346 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2347 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2348 * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
2349 * simply do nothing for reserved pfns.
2351 * Whoever called remap_pfn_range is also going to call e.g.
2352 * unmap_mapping_range before the underlying pages are freed,
2353 * causing a call to our MMU notifier.
2355 * Certain IO or PFNMAP mappings can be backed with valid
2356 * struct pages, but be allocated without refcounting e.g.,
2357 * tail pages of non-compound higher order allocations, which
2358 * would then underflow the refcount when the caller does the
2359 * required put_page. Don't allow those pages here.
2361 if (!kvm_try_get_pfn(pfn))
2365 pte_unmap_unlock(ptep, ptl);
2372 * Pin guest page in memory and return its pfn.
2373 * @addr: host virtual address which maps memory to the guest
2374 * @atomic: whether this function can sleep
2375 * @async: whether this function need to wait IO complete if the
2376 * host page is not in the memory
2377 * @write_fault: whether we should get a writable host page
2378 * @writable: whether it allows to map a writable host page for !@write_fault
2380 * The function will map a writable host page for these two cases:
2381 * 1): @write_fault = true
2382 * 2): @write_fault = false && @writable, @writable will tell the caller
2383 * whether the mapping is writable.
2385 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2386 bool write_fault, bool *writable)
2388 struct vm_area_struct *vma;
2392 /* we can do it either atomically or asynchronously, not both */
2393 BUG_ON(atomic && async);
2395 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2399 return KVM_PFN_ERR_FAULT;
2401 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2405 mmap_read_lock(current->mm);
2406 if (npages == -EHWPOISON ||
2407 (!async && check_user_page_hwpoison(addr))) {
2408 pfn = KVM_PFN_ERR_HWPOISON;
2413 vma = vma_lookup(current->mm, addr);
2416 pfn = KVM_PFN_ERR_FAULT;
2417 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2418 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
2422 pfn = KVM_PFN_ERR_FAULT;
2424 if (async && vma_is_valid(vma, write_fault))
2426 pfn = KVM_PFN_ERR_FAULT;
2429 mmap_read_unlock(current->mm);
2433 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
2434 bool atomic, bool *async, bool write_fault,
2435 bool *writable, hva_t *hva)
2437 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2442 if (addr == KVM_HVA_ERR_RO_BAD) {
2445 return KVM_PFN_ERR_RO_FAULT;
2448 if (kvm_is_error_hva(addr)) {
2451 return KVM_PFN_NOSLOT;
2454 /* Do not map writable pfn in the readonly memslot. */
2455 if (writable && memslot_is_readonly(slot)) {
2460 return hva_to_pfn(addr, atomic, async, write_fault,
2463 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2465 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2468 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2469 write_fault, writable, NULL);
2471 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2473 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
2475 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2477 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2479 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
2481 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2483 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2485 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2487 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2489 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2491 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2493 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2495 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2497 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2499 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2501 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2503 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2504 struct page **pages, int nr_pages)
2509 addr = gfn_to_hva_many(slot, gfn, &entry);
2510 if (kvm_is_error_hva(addr))
2513 if (entry < nr_pages)
2516 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2518 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2520 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2522 if (is_error_noslot_pfn(pfn))
2523 return KVM_ERR_PTR_BAD_PAGE;
2525 if (kvm_is_reserved_pfn(pfn)) {
2527 return KVM_ERR_PTR_BAD_PAGE;
2530 return pfn_to_page(pfn);
2533 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2537 pfn = gfn_to_pfn(kvm, gfn);
2539 return kvm_pfn_to_page(pfn);
2541 EXPORT_SYMBOL_GPL(gfn_to_page);
2543 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2549 cache->pfn = cache->gfn = 0;
2552 kvm_release_pfn_dirty(pfn);
2554 kvm_release_pfn_clean(pfn);
2557 static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2558 struct gfn_to_pfn_cache *cache, u64 gen)
2560 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2562 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2564 cache->dirty = false;
2565 cache->generation = gen;
2568 static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2569 struct kvm_host_map *map,
2570 struct gfn_to_pfn_cache *cache,
2575 struct page *page = KVM_UNMAPPED_PAGE;
2576 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2577 u64 gen = slots->generation;
2583 if (!cache->pfn || cache->gfn != gfn ||
2584 cache->generation != gen) {
2587 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2593 pfn = gfn_to_pfn_memslot(slot, gfn);
2595 if (is_error_noslot_pfn(pfn))
2598 if (pfn_valid(pfn)) {
2599 page = pfn_to_page(pfn);
2601 hva = kmap_atomic(page);
2604 #ifdef CONFIG_HAS_IOMEM
2605 } else if (!atomic) {
2606 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2623 int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2624 struct gfn_to_pfn_cache *cache, bool atomic)
2626 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2629 EXPORT_SYMBOL_GPL(kvm_map_gfn);
2631 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2633 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2636 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2638 static void __kvm_unmap_gfn(struct kvm *kvm,
2639 struct kvm_memory_slot *memslot,
2640 struct kvm_host_map *map,
2641 struct gfn_to_pfn_cache *cache,
2642 bool dirty, bool atomic)
2650 if (map->page != KVM_UNMAPPED_PAGE) {
2652 kunmap_atomic(map->hva);
2656 #ifdef CONFIG_HAS_IOMEM
2660 WARN_ONCE(1, "Unexpected unmapping in atomic context");
2664 mark_page_dirty_in_slot(kvm, memslot, map->gfn);
2667 cache->dirty |= dirty;
2669 kvm_release_pfn(map->pfn, dirty, NULL);
2675 int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2676 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2678 __kvm_unmap_gfn(vcpu->kvm, gfn_to_memslot(vcpu->kvm, map->gfn), map,
2679 cache, dirty, atomic);
2682 EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2684 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2686 __kvm_unmap_gfn(vcpu->kvm, kvm_vcpu_gfn_to_memslot(vcpu, map->gfn),
2687 map, NULL, dirty, false);
2689 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2691 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2695 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2697 return kvm_pfn_to_page(pfn);
2699 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2701 void kvm_release_page_clean(struct page *page)
2703 WARN_ON(is_error_page(page));
2705 kvm_release_pfn_clean(page_to_pfn(page));
2707 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2709 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2711 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2712 put_page(pfn_to_page(pfn));
2714 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2716 void kvm_release_page_dirty(struct page *page)
2718 WARN_ON(is_error_page(page));
2720 kvm_release_pfn_dirty(page_to_pfn(page));
2722 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2724 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2726 kvm_set_pfn_dirty(pfn);
2727 kvm_release_pfn_clean(pfn);
2729 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2731 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2733 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2734 SetPageDirty(pfn_to_page(pfn));
2736 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2738 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2740 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2741 mark_page_accessed(pfn_to_page(pfn));
2743 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2745 static int next_segment(unsigned long len, int offset)
2747 if (len > PAGE_SIZE - offset)
2748 return PAGE_SIZE - offset;
2753 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2754 void *data, int offset, int len)
2759 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2760 if (kvm_is_error_hva(addr))
2762 r = __copy_from_user(data, (void __user *)addr + offset, len);
2768 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2771 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2773 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2775 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2777 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2778 int offset, int len)
2780 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2782 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2784 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2786 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2788 gfn_t gfn = gpa >> PAGE_SHIFT;
2790 int offset = offset_in_page(gpa);
2793 while ((seg = next_segment(len, offset)) != 0) {
2794 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2804 EXPORT_SYMBOL_GPL(kvm_read_guest);
2806 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2808 gfn_t gfn = gpa >> PAGE_SHIFT;
2810 int offset = offset_in_page(gpa);
2813 while ((seg = next_segment(len, offset)) != 0) {
2814 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2824 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2826 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2827 void *data, int offset, unsigned long len)
2832 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2833 if (kvm_is_error_hva(addr))
2835 pagefault_disable();
2836 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2843 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2844 void *data, unsigned long len)
2846 gfn_t gfn = gpa >> PAGE_SHIFT;
2847 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2848 int offset = offset_in_page(gpa);
2850 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2852 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2854 static int __kvm_write_guest_page(struct kvm *kvm,
2855 struct kvm_memory_slot *memslot, gfn_t gfn,
2856 const void *data, int offset, int len)
2861 addr = gfn_to_hva_memslot(memslot, gfn);
2862 if (kvm_is_error_hva(addr))
2864 r = __copy_to_user((void __user *)addr + offset, data, len);
2867 mark_page_dirty_in_slot(kvm, memslot, gfn);
2871 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2872 const void *data, int offset, int len)
2874 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2876 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2878 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2880 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2881 const void *data, int offset, int len)
2883 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2885 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
2887 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2889 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2892 gfn_t gfn = gpa >> PAGE_SHIFT;
2894 int offset = offset_in_page(gpa);
2897 while ((seg = next_segment(len, offset)) != 0) {
2898 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2908 EXPORT_SYMBOL_GPL(kvm_write_guest);
2910 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2913 gfn_t gfn = gpa >> PAGE_SHIFT;
2915 int offset = offset_in_page(gpa);
2918 while ((seg = next_segment(len, offset)) != 0) {
2919 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2929 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2931 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2932 struct gfn_to_hva_cache *ghc,
2933 gpa_t gpa, unsigned long len)
2935 int offset = offset_in_page(gpa);
2936 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2937 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2938 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2939 gfn_t nr_pages_avail;
2941 /* Update ghc->generation before performing any error checks. */
2942 ghc->generation = slots->generation;
2944 if (start_gfn > end_gfn) {
2945 ghc->hva = KVM_HVA_ERR_BAD;
2950 * If the requested region crosses two memslots, we still
2951 * verify that the entire region is valid here.
2953 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
2954 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2955 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2957 if (kvm_is_error_hva(ghc->hva))
2961 /* Use the slow path for cross page reads and writes. */
2962 if (nr_pages_needed == 1)
2965 ghc->memslot = NULL;
2972 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2973 gpa_t gpa, unsigned long len)
2975 struct kvm_memslots *slots = kvm_memslots(kvm);
2976 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2978 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2980 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2981 void *data, unsigned int offset,
2984 struct kvm_memslots *slots = kvm_memslots(kvm);
2986 gpa_t gpa = ghc->gpa + offset;
2988 BUG_ON(len + offset > ghc->len);
2990 if (slots->generation != ghc->generation) {
2991 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2995 if (kvm_is_error_hva(ghc->hva))
2998 if (unlikely(!ghc->memslot))
2999 return kvm_write_guest(kvm, gpa, data, len);
3001 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
3004 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
3008 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
3010 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3011 void *data, unsigned long len)
3013 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
3015 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
3017 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3018 void *data, unsigned int offset,
3021 struct kvm_memslots *slots = kvm_memslots(kvm);
3023 gpa_t gpa = ghc->gpa + offset;
3025 BUG_ON(len + offset > ghc->len);
3027 if (slots->generation != ghc->generation) {
3028 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3032 if (kvm_is_error_hva(ghc->hva))
3035 if (unlikely(!ghc->memslot))
3036 return kvm_read_guest(kvm, gpa, data, len);
3038 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
3044 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3046 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3047 void *data, unsigned long len)
3049 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3051 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
3053 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3055 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3056 gfn_t gfn = gpa >> PAGE_SHIFT;
3058 int offset = offset_in_page(gpa);
3061 while ((seg = next_segment(len, offset)) != 0) {
3062 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
3071 EXPORT_SYMBOL_GPL(kvm_clear_guest);
3073 void mark_page_dirty_in_slot(struct kvm *kvm,
3074 struct kvm_memory_slot *memslot,
3077 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
3078 unsigned long rel_gfn = gfn - memslot->base_gfn;
3079 u32 slot = (memslot->as_id << 16) | memslot->id;
3081 if (kvm->dirty_ring_size)
3082 kvm_dirty_ring_push(kvm_dirty_ring_get(kvm),
3085 set_bit_le(rel_gfn, memslot->dirty_bitmap);
3088 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
3090 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3092 struct kvm_memory_slot *memslot;
3094 memslot = gfn_to_memslot(kvm, gfn);
3095 mark_page_dirty_in_slot(kvm, memslot, gfn);
3097 EXPORT_SYMBOL_GPL(mark_page_dirty);
3099 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3101 struct kvm_memory_slot *memslot;
3103 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3104 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
3106 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3108 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3110 if (!vcpu->sigset_active)
3114 * This does a lockless modification of ->real_blocked, which is fine
3115 * because, only current can change ->real_blocked and all readers of
3116 * ->real_blocked don't care as long ->real_blocked is always a subset
3119 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
3122 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3124 if (!vcpu->sigset_active)
3127 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
3128 sigemptyset(¤t->real_blocked);
3131 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3133 unsigned int old, val, grow, grow_start;
3135 old = val = vcpu->halt_poll_ns;
3136 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3137 grow = READ_ONCE(halt_poll_ns_grow);
3142 if (val < grow_start)
3145 if (val > vcpu->kvm->max_halt_poll_ns)
3146 val = vcpu->kvm->max_halt_poll_ns;
3148 vcpu->halt_poll_ns = val;
3150 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
3153 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3155 unsigned int old, val, shrink, grow_start;
3157 old = val = vcpu->halt_poll_ns;
3158 shrink = READ_ONCE(halt_poll_ns_shrink);
3159 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3165 if (val < grow_start)
3168 vcpu->halt_poll_ns = val;
3169 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3172 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3175 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3177 if (kvm_arch_vcpu_runnable(vcpu)) {
3178 kvm_make_request(KVM_REQ_UNHALT, vcpu);
3181 if (kvm_cpu_has_pending_timer(vcpu))
3183 if (signal_pending(current))
3185 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3190 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3195 update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
3198 vcpu->stat.generic.halt_poll_fail_ns += poll_ns;
3200 vcpu->stat.generic.halt_poll_success_ns += poll_ns;
3204 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
3206 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
3208 ktime_t start, cur, poll_end;
3209 bool waited = false;
3212 kvm_arch_vcpu_blocking(vcpu);
3214 start = cur = poll_end = ktime_get();
3215 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
3216 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
3218 ++vcpu->stat.generic.halt_attempted_poll;
3221 * This sets KVM_REQ_UNHALT if an interrupt
3224 if (kvm_vcpu_check_block(vcpu) < 0) {
3225 ++vcpu->stat.generic.halt_successful_poll;
3226 if (!vcpu_valid_wakeup(vcpu))
3227 ++vcpu->stat.generic.halt_poll_invalid;
3229 KVM_STATS_LOG_HIST_UPDATE(
3230 vcpu->stat.generic.halt_poll_success_hist,
3231 ktime_to_ns(ktime_get()) -
3232 ktime_to_ns(start));
3236 poll_end = cur = ktime_get();
3237 } while (kvm_vcpu_can_poll(cur, stop));
3239 KVM_STATS_LOG_HIST_UPDATE(
3240 vcpu->stat.generic.halt_poll_fail_hist,
3241 ktime_to_ns(ktime_get()) - ktime_to_ns(start));
3245 prepare_to_rcuwait(&vcpu->wait);
3247 set_current_state(TASK_INTERRUPTIBLE);
3249 if (kvm_vcpu_check_block(vcpu) < 0)
3255 finish_rcuwait(&vcpu->wait);
3258 vcpu->stat.generic.halt_wait_ns +=
3259 ktime_to_ns(cur) - ktime_to_ns(poll_end);
3260 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3261 ktime_to_ns(cur) - ktime_to_ns(poll_end));
3264 kvm_arch_vcpu_unblocking(vcpu);
3265 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3267 update_halt_poll_stats(
3268 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
3270 if (!kvm_arch_no_poll(vcpu)) {
3271 if (!vcpu_valid_wakeup(vcpu)) {
3272 shrink_halt_poll_ns(vcpu);
3273 } else if (vcpu->kvm->max_halt_poll_ns) {
3274 if (block_ns <= vcpu->halt_poll_ns)
3276 /* we had a long block, shrink polling */
3277 else if (vcpu->halt_poll_ns &&
3278 block_ns > vcpu->kvm->max_halt_poll_ns)
3279 shrink_halt_poll_ns(vcpu);
3280 /* we had a short halt and our poll time is too small */
3281 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3282 block_ns < vcpu->kvm->max_halt_poll_ns)
3283 grow_halt_poll_ns(vcpu);
3285 vcpu->halt_poll_ns = 0;
3289 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
3290 kvm_arch_vcpu_block_finish(vcpu);
3292 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
3294 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3296 struct rcuwait *waitp;
3298 waitp = kvm_arch_vcpu_get_wait(vcpu);
3299 if (rcuwait_wake_up(waitp)) {
3300 WRITE_ONCE(vcpu->ready, true);
3301 ++vcpu->stat.generic.halt_wakeup;
3307 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3311 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3313 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3317 if (kvm_vcpu_wake_up(vcpu))
3321 * Note, the vCPU could get migrated to a different pCPU at any point
3322 * after kvm_arch_vcpu_should_kick(), which could result in sending an
3323 * IPI to the previous pCPU. But, that's ok because the purpose of the
3324 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
3325 * vCPU also requires it to leave IN_GUEST_MODE.
3328 if (kvm_arch_vcpu_should_kick(vcpu)) {
3329 cpu = READ_ONCE(vcpu->cpu);
3330 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3331 smp_send_reschedule(cpu);
3335 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3336 #endif /* !CONFIG_S390 */
3338 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3341 struct task_struct *task = NULL;
3345 pid = rcu_dereference(target->pid);
3347 task = get_pid_task(pid, PIDTYPE_PID);
3351 ret = yield_to(task, 1);
3352 put_task_struct(task);
3356 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3359 * Helper that checks whether a VCPU is eligible for directed yield.
3360 * Most eligible candidate to yield is decided by following heuristics:
3362 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3363 * (preempted lock holder), indicated by @in_spin_loop.
3364 * Set at the beginning and cleared at the end of interception/PLE handler.
3366 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3367 * chance last time (mostly it has become eligible now since we have probably
3368 * yielded to lockholder in last iteration. This is done by toggling
3369 * @dy_eligible each time a VCPU checked for eligibility.)
3371 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3372 * to preempted lock-holder could result in wrong VCPU selection and CPU
3373 * burning. Giving priority for a potential lock-holder increases lock
3376 * Since algorithm is based on heuristics, accessing another VCPU data without
3377 * locking does not harm. It may result in trying to yield to same VCPU, fail
3378 * and continue with next VCPU and so on.
3380 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3382 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3385 eligible = !vcpu->spin_loop.in_spin_loop ||
3386 vcpu->spin_loop.dy_eligible;
3388 if (vcpu->spin_loop.in_spin_loop)
3389 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3398 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3399 * a vcpu_load/vcpu_put pair. However, for most architectures
3400 * kvm_arch_vcpu_runnable does not require vcpu_load.
3402 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3404 return kvm_arch_vcpu_runnable(vcpu);
3407 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3409 if (kvm_arch_dy_runnable(vcpu))
3412 #ifdef CONFIG_KVM_ASYNC_PF
3413 if (!list_empty_careful(&vcpu->async_pf.done))
3420 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3425 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3427 struct kvm *kvm = me->kvm;
3428 struct kvm_vcpu *vcpu;
3429 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3435 kvm_vcpu_set_in_spin_loop(me, true);
3437 * We boost the priority of a VCPU that is runnable but not
3438 * currently running, because it got preempted by something
3439 * else and called schedule in __vcpu_run. Hopefully that
3440 * VCPU is holding the lock that we need and will release it.
3441 * We approximate round-robin by starting at the last boosted VCPU.
3443 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3444 kvm_for_each_vcpu(i, vcpu, kvm) {
3445 if (!pass && i <= last_boosted_vcpu) {
3446 i = last_boosted_vcpu;
3448 } else if (pass && i > last_boosted_vcpu)
3450 if (!READ_ONCE(vcpu->ready))
3454 if (rcuwait_active(&vcpu->wait) &&
3455 !vcpu_dy_runnable(vcpu))
3457 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3458 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3459 !kvm_arch_vcpu_in_kernel(vcpu))
3461 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3464 yielded = kvm_vcpu_yield_to(vcpu);
3466 kvm->last_boosted_vcpu = i;
3468 } else if (yielded < 0) {
3475 kvm_vcpu_set_in_spin_loop(me, false);
3477 /* Ensure vcpu is not eligible during next spinloop */
3478 kvm_vcpu_set_dy_eligible(me, false);
3480 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3482 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3484 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3485 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3486 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3487 kvm->dirty_ring_size / PAGE_SIZE);
3493 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3495 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3498 if (vmf->pgoff == 0)
3499 page = virt_to_page(vcpu->run);
3501 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3502 page = virt_to_page(vcpu->arch.pio_data);
3504 #ifdef CONFIG_KVM_MMIO
3505 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3506 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3508 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3509 page = kvm_dirty_ring_get_page(
3511 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3513 return kvm_arch_vcpu_fault(vcpu, vmf);
3519 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3520 .fault = kvm_vcpu_fault,
3523 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3525 struct kvm_vcpu *vcpu = file->private_data;
3526 unsigned long pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
3528 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3529 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3530 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3533 vma->vm_ops = &kvm_vcpu_vm_ops;
3537 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3539 struct kvm_vcpu *vcpu = filp->private_data;
3541 kvm_put_kvm(vcpu->kvm);
3545 static struct file_operations kvm_vcpu_fops = {
3546 .release = kvm_vcpu_release,
3547 .unlocked_ioctl = kvm_vcpu_ioctl,
3548 .mmap = kvm_vcpu_mmap,
3549 .llseek = noop_llseek,
3550 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3554 * Allocates an inode for the vcpu.
3556 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3558 char name[8 + 1 + ITOA_MAX_LEN + 1];
3560 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3561 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3564 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3566 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3567 struct dentry *debugfs_dentry;
3568 char dir_name[ITOA_MAX_LEN * 2];
3570 if (!debugfs_initialized())
3573 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3574 debugfs_dentry = debugfs_create_dir(dir_name,
3575 vcpu->kvm->debugfs_dentry);
3577 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3582 * Creates some virtual cpus. Good luck creating more than one.
3584 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3587 struct kvm_vcpu *vcpu;
3590 if (id >= KVM_MAX_VCPU_ID)
3593 mutex_lock(&kvm->lock);
3594 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3595 mutex_unlock(&kvm->lock);
3599 kvm->created_vcpus++;
3600 mutex_unlock(&kvm->lock);
3602 r = kvm_arch_vcpu_precreate(kvm, id);
3604 goto vcpu_decrement;
3606 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3609 goto vcpu_decrement;
3612 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3613 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3618 vcpu->run = page_address(page);
3620 kvm_vcpu_init(vcpu, kvm, id);
3622 r = kvm_arch_vcpu_create(vcpu);
3624 goto vcpu_free_run_page;
3626 if (kvm->dirty_ring_size) {
3627 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3628 id, kvm->dirty_ring_size);
3630 goto arch_vcpu_destroy;
3633 mutex_lock(&kvm->lock);
3634 if (kvm_get_vcpu_by_id(kvm, id)) {
3636 goto unlock_vcpu_destroy;
3639 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3640 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
3642 /* Fill the stats id string for the vcpu */
3643 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3644 task_pid_nr(current), id);
3646 /* Now it's all set up, let userspace reach it */
3648 r = create_vcpu_fd(vcpu);
3650 kvm_put_kvm_no_destroy(kvm);
3651 goto unlock_vcpu_destroy;
3654 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
3657 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3658 * before kvm->online_vcpu's incremented value.
3661 atomic_inc(&kvm->online_vcpus);
3663 mutex_unlock(&kvm->lock);
3664 kvm_arch_vcpu_postcreate(vcpu);
3665 kvm_create_vcpu_debugfs(vcpu);
3668 unlock_vcpu_destroy:
3669 mutex_unlock(&kvm->lock);
3670 kvm_dirty_ring_free(&vcpu->dirty_ring);
3672 kvm_arch_vcpu_destroy(vcpu);
3674 free_page((unsigned long)vcpu->run);
3676 kmem_cache_free(kvm_vcpu_cache, vcpu);
3678 mutex_lock(&kvm->lock);
3679 kvm->created_vcpus--;
3680 mutex_unlock(&kvm->lock);
3684 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3687 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3688 vcpu->sigset_active = 1;
3689 vcpu->sigset = *sigset;
3691 vcpu->sigset_active = 0;
3695 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3696 size_t size, loff_t *offset)
3698 struct kvm_vcpu *vcpu = file->private_data;
3700 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3701 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3702 sizeof(vcpu->stat), user_buffer, size, offset);
3705 static const struct file_operations kvm_vcpu_stats_fops = {
3706 .read = kvm_vcpu_stats_read,
3707 .llseek = noop_llseek,
3710 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3714 char name[15 + ITOA_MAX_LEN + 1];
3716 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3718 fd = get_unused_fd_flags(O_CLOEXEC);
3722 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3725 return PTR_ERR(file);
3727 file->f_mode |= FMODE_PREAD;
3728 fd_install(fd, file);
3733 static long kvm_vcpu_ioctl(struct file *filp,
3734 unsigned int ioctl, unsigned long arg)
3736 struct kvm_vcpu *vcpu = filp->private_data;
3737 void __user *argp = (void __user *)arg;
3739 struct kvm_fpu *fpu = NULL;
3740 struct kvm_sregs *kvm_sregs = NULL;
3742 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
3745 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3749 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3750 * execution; mutex_lock() would break them.
3752 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3753 if (r != -ENOIOCTLCMD)
3756 if (mutex_lock_killable(&vcpu->mutex))
3764 oldpid = rcu_access_pointer(vcpu->pid);
3765 if (unlikely(oldpid != task_pid(current))) {
3766 /* The thread running this VCPU changed. */
3769 r = kvm_arch_vcpu_run_pid_change(vcpu);
3773 newpid = get_task_pid(current, PIDTYPE_PID);
3774 rcu_assign_pointer(vcpu->pid, newpid);
3779 r = kvm_arch_vcpu_ioctl_run(vcpu);
3780 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3783 case KVM_GET_REGS: {
3784 struct kvm_regs *kvm_regs;
3787 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3790 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3794 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3801 case KVM_SET_REGS: {
3802 struct kvm_regs *kvm_regs;
3804 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3805 if (IS_ERR(kvm_regs)) {
3806 r = PTR_ERR(kvm_regs);
3809 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3813 case KVM_GET_SREGS: {
3814 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3815 GFP_KERNEL_ACCOUNT);
3819 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3823 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3828 case KVM_SET_SREGS: {
3829 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3830 if (IS_ERR(kvm_sregs)) {
3831 r = PTR_ERR(kvm_sregs);
3835 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3838 case KVM_GET_MP_STATE: {
3839 struct kvm_mp_state mp_state;
3841 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3845 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3850 case KVM_SET_MP_STATE: {
3851 struct kvm_mp_state mp_state;
3854 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3856 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3859 case KVM_TRANSLATE: {
3860 struct kvm_translation tr;
3863 if (copy_from_user(&tr, argp, sizeof(tr)))
3865 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3869 if (copy_to_user(argp, &tr, sizeof(tr)))
3874 case KVM_SET_GUEST_DEBUG: {
3875 struct kvm_guest_debug dbg;
3878 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3880 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3883 case KVM_SET_SIGNAL_MASK: {
3884 struct kvm_signal_mask __user *sigmask_arg = argp;
3885 struct kvm_signal_mask kvm_sigmask;
3886 sigset_t sigset, *p;
3891 if (copy_from_user(&kvm_sigmask, argp,
3892 sizeof(kvm_sigmask)))
3895 if (kvm_sigmask.len != sizeof(sigset))
3898 if (copy_from_user(&sigset, sigmask_arg->sigset,
3903 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3907 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
3911 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3915 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3921 fpu = memdup_user(argp, sizeof(*fpu));
3927 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3930 case KVM_GET_STATS_FD: {
3931 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
3935 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3938 mutex_unlock(&vcpu->mutex);
3944 #ifdef CONFIG_KVM_COMPAT
3945 static long kvm_vcpu_compat_ioctl(struct file *filp,
3946 unsigned int ioctl, unsigned long arg)
3948 struct kvm_vcpu *vcpu = filp->private_data;
3949 void __user *argp = compat_ptr(arg);
3952 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
3956 case KVM_SET_SIGNAL_MASK: {
3957 struct kvm_signal_mask __user *sigmask_arg = argp;
3958 struct kvm_signal_mask kvm_sigmask;
3963 if (copy_from_user(&kvm_sigmask, argp,
3964 sizeof(kvm_sigmask)))
3967 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3970 if (get_compat_sigset(&sigset,
3971 (compat_sigset_t __user *)sigmask_arg->sigset))
3973 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3975 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3979 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3987 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3989 struct kvm_device *dev = filp->private_data;
3992 return dev->ops->mmap(dev, vma);
3997 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3998 int (*accessor)(struct kvm_device *dev,
3999 struct kvm_device_attr *attr),
4002 struct kvm_device_attr attr;
4007 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4010 return accessor(dev, &attr);
4013 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
4016 struct kvm_device *dev = filp->private_data;
4018 if (dev->kvm->mm != current->mm || dev->kvm->vm_bugged)
4022 case KVM_SET_DEVICE_ATTR:
4023 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
4024 case KVM_GET_DEVICE_ATTR:
4025 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
4026 case KVM_HAS_DEVICE_ATTR:
4027 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
4029 if (dev->ops->ioctl)
4030 return dev->ops->ioctl(dev, ioctl, arg);
4036 static int kvm_device_release(struct inode *inode, struct file *filp)
4038 struct kvm_device *dev = filp->private_data;
4039 struct kvm *kvm = dev->kvm;
4041 if (dev->ops->release) {
4042 mutex_lock(&kvm->lock);
4043 list_del(&dev->vm_node);
4044 dev->ops->release(dev);
4045 mutex_unlock(&kvm->lock);
4052 static const struct file_operations kvm_device_fops = {
4053 .unlocked_ioctl = kvm_device_ioctl,
4054 .release = kvm_device_release,
4055 KVM_COMPAT(kvm_device_ioctl),
4056 .mmap = kvm_device_mmap,
4059 struct kvm_device *kvm_device_from_filp(struct file *filp)
4061 if (filp->f_op != &kvm_device_fops)
4064 return filp->private_data;
4067 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
4068 #ifdef CONFIG_KVM_MPIC
4069 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
4070 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
4074 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
4076 if (type >= ARRAY_SIZE(kvm_device_ops_table))
4079 if (kvm_device_ops_table[type] != NULL)
4082 kvm_device_ops_table[type] = ops;
4086 void kvm_unregister_device_ops(u32 type)
4088 if (kvm_device_ops_table[type] != NULL)
4089 kvm_device_ops_table[type] = NULL;
4092 static int kvm_ioctl_create_device(struct kvm *kvm,
4093 struct kvm_create_device *cd)
4095 const struct kvm_device_ops *ops = NULL;
4096 struct kvm_device *dev;
4097 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
4101 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4104 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4105 ops = kvm_device_ops_table[type];
4112 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
4119 mutex_lock(&kvm->lock);
4120 ret = ops->create(dev, type);
4122 mutex_unlock(&kvm->lock);
4126 list_add(&dev->vm_node, &kvm->devices);
4127 mutex_unlock(&kvm->lock);
4133 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
4135 kvm_put_kvm_no_destroy(kvm);
4136 mutex_lock(&kvm->lock);
4137 list_del(&dev->vm_node);
4138 mutex_unlock(&kvm->lock);
4147 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4150 case KVM_CAP_USER_MEMORY:
4151 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4152 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
4153 case KVM_CAP_INTERNAL_ERROR_DATA:
4154 #ifdef CONFIG_HAVE_KVM_MSI
4155 case KVM_CAP_SIGNAL_MSI:
4157 #ifdef CONFIG_HAVE_KVM_IRQFD
4159 case KVM_CAP_IRQFD_RESAMPLE:
4161 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
4162 case KVM_CAP_CHECK_EXTENSION_VM:
4163 case KVM_CAP_ENABLE_CAP_VM:
4164 case KVM_CAP_HALT_POLL:
4166 #ifdef CONFIG_KVM_MMIO
4167 case KVM_CAP_COALESCED_MMIO:
4168 return KVM_COALESCED_MMIO_PAGE_OFFSET;
4169 case KVM_CAP_COALESCED_PIO:
4172 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4173 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4174 return KVM_DIRTY_LOG_MANUAL_CAPS;
4176 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4177 case KVM_CAP_IRQ_ROUTING:
4178 return KVM_MAX_IRQ_ROUTES;
4180 #if KVM_ADDRESS_SPACE_NUM > 1
4181 case KVM_CAP_MULTI_ADDRESS_SPACE:
4182 return KVM_ADDRESS_SPACE_NUM;
4184 case KVM_CAP_NR_MEMSLOTS:
4185 return KVM_USER_MEM_SLOTS;
4186 case KVM_CAP_DIRTY_LOG_RING:
4187 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
4188 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4192 case KVM_CAP_BINARY_STATS_FD:
4197 return kvm_vm_ioctl_check_extension(kvm, arg);
4200 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4204 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4207 /* the size should be power of 2 */
4208 if (!size || (size & (size - 1)))
4211 /* Should be bigger to keep the reserved entries, or a page */
4212 if (size < kvm_dirty_ring_get_rsvd_entries() *
4213 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4216 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4217 sizeof(struct kvm_dirty_gfn))
4220 /* We only allow it to set once */
4221 if (kvm->dirty_ring_size)
4224 mutex_lock(&kvm->lock);
4226 if (kvm->created_vcpus) {
4227 /* We don't allow to change this value after vcpu created */
4230 kvm->dirty_ring_size = size;
4234 mutex_unlock(&kvm->lock);
4238 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4241 struct kvm_vcpu *vcpu;
4244 if (!kvm->dirty_ring_size)
4247 mutex_lock(&kvm->slots_lock);
4249 kvm_for_each_vcpu(i, vcpu, kvm)
4250 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4252 mutex_unlock(&kvm->slots_lock);
4255 kvm_flush_remote_tlbs(kvm);
4260 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4261 struct kvm_enable_cap *cap)
4266 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4267 struct kvm_enable_cap *cap)
4270 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4271 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4272 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4274 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4275 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4277 if (cap->flags || (cap->args[0] & ~allowed_options))
4279 kvm->manual_dirty_log_protect = cap->args[0];
4283 case KVM_CAP_HALT_POLL: {
4284 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4287 kvm->max_halt_poll_ns = cap->args[0];
4290 case KVM_CAP_DIRTY_LOG_RING:
4291 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4293 return kvm_vm_ioctl_enable_cap(kvm, cap);
4297 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4298 size_t size, loff_t *offset)
4300 struct kvm *kvm = file->private_data;
4302 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4303 &kvm_vm_stats_desc[0], &kvm->stat,
4304 sizeof(kvm->stat), user_buffer, size, offset);
4307 static const struct file_operations kvm_vm_stats_fops = {
4308 .read = kvm_vm_stats_read,
4309 .llseek = noop_llseek,
4312 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4317 fd = get_unused_fd_flags(O_CLOEXEC);
4321 file = anon_inode_getfile("kvm-vm-stats",
4322 &kvm_vm_stats_fops, kvm, O_RDONLY);
4325 return PTR_ERR(file);
4327 file->f_mode |= FMODE_PREAD;
4328 fd_install(fd, file);
4333 static long kvm_vm_ioctl(struct file *filp,
4334 unsigned int ioctl, unsigned long arg)
4336 struct kvm *kvm = filp->private_data;
4337 void __user *argp = (void __user *)arg;
4340 if (kvm->mm != current->mm || kvm->vm_bugged)
4343 case KVM_CREATE_VCPU:
4344 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4346 case KVM_ENABLE_CAP: {
4347 struct kvm_enable_cap cap;
4350 if (copy_from_user(&cap, argp, sizeof(cap)))
4352 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4355 case KVM_SET_USER_MEMORY_REGION: {
4356 struct kvm_userspace_memory_region kvm_userspace_mem;
4359 if (copy_from_user(&kvm_userspace_mem, argp,
4360 sizeof(kvm_userspace_mem)))
4363 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4366 case KVM_GET_DIRTY_LOG: {
4367 struct kvm_dirty_log log;
4370 if (copy_from_user(&log, argp, sizeof(log)))
4372 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4375 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4376 case KVM_CLEAR_DIRTY_LOG: {
4377 struct kvm_clear_dirty_log log;
4380 if (copy_from_user(&log, argp, sizeof(log)))
4382 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4386 #ifdef CONFIG_KVM_MMIO
4387 case KVM_REGISTER_COALESCED_MMIO: {
4388 struct kvm_coalesced_mmio_zone zone;
4391 if (copy_from_user(&zone, argp, sizeof(zone)))
4393 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4396 case KVM_UNREGISTER_COALESCED_MMIO: {
4397 struct kvm_coalesced_mmio_zone zone;
4400 if (copy_from_user(&zone, argp, sizeof(zone)))
4402 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4407 struct kvm_irqfd data;
4410 if (copy_from_user(&data, argp, sizeof(data)))
4412 r = kvm_irqfd(kvm, &data);
4415 case KVM_IOEVENTFD: {
4416 struct kvm_ioeventfd data;
4419 if (copy_from_user(&data, argp, sizeof(data)))
4421 r = kvm_ioeventfd(kvm, &data);
4424 #ifdef CONFIG_HAVE_KVM_MSI
4425 case KVM_SIGNAL_MSI: {
4429 if (copy_from_user(&msi, argp, sizeof(msi)))
4431 r = kvm_send_userspace_msi(kvm, &msi);
4435 #ifdef __KVM_HAVE_IRQ_LINE
4436 case KVM_IRQ_LINE_STATUS:
4437 case KVM_IRQ_LINE: {
4438 struct kvm_irq_level irq_event;
4441 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4444 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4445 ioctl == KVM_IRQ_LINE_STATUS);
4450 if (ioctl == KVM_IRQ_LINE_STATUS) {
4451 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4459 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4460 case KVM_SET_GSI_ROUTING: {
4461 struct kvm_irq_routing routing;
4462 struct kvm_irq_routing __user *urouting;
4463 struct kvm_irq_routing_entry *entries = NULL;
4466 if (copy_from_user(&routing, argp, sizeof(routing)))
4469 if (!kvm_arch_can_set_irq_routing(kvm))
4471 if (routing.nr > KVM_MAX_IRQ_ROUTES)
4477 entries = vmemdup_user(urouting->entries,
4478 array_size(sizeof(*entries),
4480 if (IS_ERR(entries)) {
4481 r = PTR_ERR(entries);
4485 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4490 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4491 case KVM_CREATE_DEVICE: {
4492 struct kvm_create_device cd;
4495 if (copy_from_user(&cd, argp, sizeof(cd)))
4498 r = kvm_ioctl_create_device(kvm, &cd);
4503 if (copy_to_user(argp, &cd, sizeof(cd)))
4509 case KVM_CHECK_EXTENSION:
4510 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4512 case KVM_RESET_DIRTY_RINGS:
4513 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4515 case KVM_GET_STATS_FD:
4516 r = kvm_vm_ioctl_get_stats_fd(kvm);
4519 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4525 #ifdef CONFIG_KVM_COMPAT
4526 struct compat_kvm_dirty_log {
4530 compat_uptr_t dirty_bitmap; /* one bit per page */
4535 struct compat_kvm_clear_dirty_log {
4540 compat_uptr_t dirty_bitmap; /* one bit per page */
4545 static long kvm_vm_compat_ioctl(struct file *filp,
4546 unsigned int ioctl, unsigned long arg)
4548 struct kvm *kvm = filp->private_data;
4551 if (kvm->mm != current->mm || kvm->vm_bugged)
4554 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4555 case KVM_CLEAR_DIRTY_LOG: {
4556 struct compat_kvm_clear_dirty_log compat_log;
4557 struct kvm_clear_dirty_log log;
4559 if (copy_from_user(&compat_log, (void __user *)arg,
4560 sizeof(compat_log)))
4562 log.slot = compat_log.slot;
4563 log.num_pages = compat_log.num_pages;
4564 log.first_page = compat_log.first_page;
4565 log.padding2 = compat_log.padding2;
4566 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4568 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4572 case KVM_GET_DIRTY_LOG: {
4573 struct compat_kvm_dirty_log compat_log;
4574 struct kvm_dirty_log log;
4576 if (copy_from_user(&compat_log, (void __user *)arg,
4577 sizeof(compat_log)))
4579 log.slot = compat_log.slot;
4580 log.padding1 = compat_log.padding1;
4581 log.padding2 = compat_log.padding2;
4582 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4584 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4588 r = kvm_vm_ioctl(filp, ioctl, arg);
4594 static struct file_operations kvm_vm_fops = {
4595 .release = kvm_vm_release,
4596 .unlocked_ioctl = kvm_vm_ioctl,
4597 .llseek = noop_llseek,
4598 KVM_COMPAT(kvm_vm_compat_ioctl),
4601 bool file_is_kvm(struct file *file)
4603 return file && file->f_op == &kvm_vm_fops;
4605 EXPORT_SYMBOL_GPL(file_is_kvm);
4607 static int kvm_dev_ioctl_create_vm(unsigned long type)
4613 kvm = kvm_create_vm(type);
4615 return PTR_ERR(kvm);
4616 #ifdef CONFIG_KVM_MMIO
4617 r = kvm_coalesced_mmio_init(kvm);
4621 r = get_unused_fd_flags(O_CLOEXEC);
4625 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4626 "kvm-%d", task_pid_nr(current));
4628 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4636 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4637 * already set, with ->release() being kvm_vm_release(). In error
4638 * cases it will be called by the final fput(file) and will take
4639 * care of doing kvm_put_kvm(kvm).
4641 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4646 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4648 fd_install(r, file);
4656 static long kvm_dev_ioctl(struct file *filp,
4657 unsigned int ioctl, unsigned long arg)
4662 case KVM_GET_API_VERSION:
4665 r = KVM_API_VERSION;
4668 r = kvm_dev_ioctl_create_vm(arg);
4670 case KVM_CHECK_EXTENSION:
4671 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4673 case KVM_GET_VCPU_MMAP_SIZE:
4676 r = PAGE_SIZE; /* struct kvm_run */
4678 r += PAGE_SIZE; /* pio data page */
4680 #ifdef CONFIG_KVM_MMIO
4681 r += PAGE_SIZE; /* coalesced mmio ring page */
4684 case KVM_TRACE_ENABLE:
4685 case KVM_TRACE_PAUSE:
4686 case KVM_TRACE_DISABLE:
4690 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4696 static struct file_operations kvm_chardev_ops = {
4697 .unlocked_ioctl = kvm_dev_ioctl,
4698 .llseek = noop_llseek,
4699 KVM_COMPAT(kvm_dev_ioctl),
4702 static struct miscdevice kvm_dev = {
4708 static void hardware_enable_nolock(void *junk)
4710 int cpu = raw_smp_processor_id();
4713 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4716 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4718 r = kvm_arch_hardware_enable();
4721 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4722 atomic_inc(&hardware_enable_failed);
4723 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4727 static int kvm_starting_cpu(unsigned int cpu)
4729 raw_spin_lock(&kvm_count_lock);
4730 if (kvm_usage_count)
4731 hardware_enable_nolock(NULL);
4732 raw_spin_unlock(&kvm_count_lock);
4736 static void hardware_disable_nolock(void *junk)
4738 int cpu = raw_smp_processor_id();
4740 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4742 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4743 kvm_arch_hardware_disable();
4746 static int kvm_dying_cpu(unsigned int cpu)
4748 raw_spin_lock(&kvm_count_lock);
4749 if (kvm_usage_count)
4750 hardware_disable_nolock(NULL);
4751 raw_spin_unlock(&kvm_count_lock);
4755 static void hardware_disable_all_nolock(void)
4757 BUG_ON(!kvm_usage_count);
4760 if (!kvm_usage_count)
4761 on_each_cpu(hardware_disable_nolock, NULL, 1);
4764 static void hardware_disable_all(void)
4766 raw_spin_lock(&kvm_count_lock);
4767 hardware_disable_all_nolock();
4768 raw_spin_unlock(&kvm_count_lock);
4771 static int hardware_enable_all(void)
4775 raw_spin_lock(&kvm_count_lock);
4778 if (kvm_usage_count == 1) {
4779 atomic_set(&hardware_enable_failed, 0);
4780 on_each_cpu(hardware_enable_nolock, NULL, 1);
4782 if (atomic_read(&hardware_enable_failed)) {
4783 hardware_disable_all_nolock();
4788 raw_spin_unlock(&kvm_count_lock);
4793 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4797 * Some (well, at least mine) BIOSes hang on reboot if
4800 * And Intel TXT required VMX off for all cpu when system shutdown.
4802 pr_info("kvm: exiting hardware virtualization\n");
4803 kvm_rebooting = true;
4804 on_each_cpu(hardware_disable_nolock, NULL, 1);
4808 static struct notifier_block kvm_reboot_notifier = {
4809 .notifier_call = kvm_reboot,
4813 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4817 for (i = 0; i < bus->dev_count; i++) {
4818 struct kvm_io_device *pos = bus->range[i].dev;
4820 kvm_iodevice_destructor(pos);
4825 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4826 const struct kvm_io_range *r2)
4828 gpa_t addr1 = r1->addr;
4829 gpa_t addr2 = r2->addr;
4834 /* If r2->len == 0, match the exact address. If r2->len != 0,
4835 * accept any overlapping write. Any order is acceptable for
4836 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4837 * we process all of them.
4850 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4852 return kvm_io_bus_cmp(p1, p2);
4855 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4856 gpa_t addr, int len)
4858 struct kvm_io_range *range, key;
4861 key = (struct kvm_io_range) {
4866 range = bsearch(&key, bus->range, bus->dev_count,
4867 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4871 off = range - bus->range;
4873 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4879 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4880 struct kvm_io_range *range, const void *val)
4884 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4888 while (idx < bus->dev_count &&
4889 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4890 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4899 /* kvm_io_bus_write - called under kvm->slots_lock */
4900 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4901 int len, const void *val)
4903 struct kvm_io_bus *bus;
4904 struct kvm_io_range range;
4907 range = (struct kvm_io_range) {
4912 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4915 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4916 return r < 0 ? r : 0;
4918 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
4920 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4921 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4922 gpa_t addr, int len, const void *val, long cookie)
4924 struct kvm_io_bus *bus;
4925 struct kvm_io_range range;
4927 range = (struct kvm_io_range) {
4932 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4936 /* First try the device referenced by cookie. */
4937 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4938 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4939 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4944 * cookie contained garbage; fall back to search and return the
4945 * correct cookie value.
4947 return __kvm_io_bus_write(vcpu, bus, &range, val);
4950 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4951 struct kvm_io_range *range, void *val)
4955 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4959 while (idx < bus->dev_count &&
4960 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4961 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4970 /* kvm_io_bus_read - called under kvm->slots_lock */
4971 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4974 struct kvm_io_bus *bus;
4975 struct kvm_io_range range;
4978 range = (struct kvm_io_range) {
4983 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4986 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4987 return r < 0 ? r : 0;
4990 /* Caller must hold slots_lock. */
4991 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4992 int len, struct kvm_io_device *dev)
4995 struct kvm_io_bus *new_bus, *bus;
4996 struct kvm_io_range range;
4998 bus = kvm_get_bus(kvm, bus_idx);
5002 /* exclude ioeventfd which is limited by maximum fd */
5003 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
5006 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
5007 GFP_KERNEL_ACCOUNT);
5011 range = (struct kvm_io_range) {
5017 for (i = 0; i < bus->dev_count; i++)
5018 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
5021 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
5022 new_bus->dev_count++;
5023 new_bus->range[i] = range;
5024 memcpy(new_bus->range + i + 1, bus->range + i,
5025 (bus->dev_count - i) * sizeof(struct kvm_io_range));
5026 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5027 synchronize_srcu_expedited(&kvm->srcu);
5033 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5034 struct kvm_io_device *dev)
5037 struct kvm_io_bus *new_bus, *bus;
5039 lockdep_assert_held(&kvm->slots_lock);
5041 bus = kvm_get_bus(kvm, bus_idx);
5045 for (i = 0; i < bus->dev_count; i++) {
5046 if (bus->range[i].dev == dev) {
5051 if (i == bus->dev_count)
5054 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
5055 GFP_KERNEL_ACCOUNT);
5057 memcpy(new_bus, bus, struct_size(bus, range, i));
5058 new_bus->dev_count--;
5059 memcpy(new_bus->range + i, bus->range + i + 1,
5060 flex_array_size(new_bus, range, new_bus->dev_count - i));
5063 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5064 synchronize_srcu_expedited(&kvm->srcu);
5066 /* Destroy the old bus _after_ installing the (null) bus. */
5068 pr_err("kvm: failed to shrink bus, removing it completely\n");
5069 for (j = 0; j < bus->dev_count; j++) {
5072 kvm_iodevice_destructor(bus->range[j].dev);
5077 return new_bus ? 0 : -ENOMEM;
5080 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5083 struct kvm_io_bus *bus;
5084 int dev_idx, srcu_idx;
5085 struct kvm_io_device *iodev = NULL;
5087 srcu_idx = srcu_read_lock(&kvm->srcu);
5089 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
5093 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5097 iodev = bus->range[dev_idx].dev;
5100 srcu_read_unlock(&kvm->srcu, srcu_idx);
5104 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5106 static int kvm_debugfs_open(struct inode *inode, struct file *file,
5107 int (*get)(void *, u64 *), int (*set)(void *, u64),
5110 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5114 * The debugfs files are a reference to the kvm struct which
5115 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
5116 * avoids the race between open and the removal of the debugfs directory.
5118 if (!kvm_get_kvm_safe(stat_data->kvm))
5121 if (simple_attr_open(inode, file, get,
5122 kvm_stats_debugfs_mode(stat_data->desc) & 0222
5125 kvm_put_kvm(stat_data->kvm);
5132 static int kvm_debugfs_release(struct inode *inode, struct file *file)
5134 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5137 simple_attr_release(inode, file);
5138 kvm_put_kvm(stat_data->kvm);
5143 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
5145 *val = *(u64 *)((void *)(&kvm->stat) + offset);
5150 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
5152 *(u64 *)((void *)(&kvm->stat) + offset) = 0;
5157 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
5160 struct kvm_vcpu *vcpu;
5164 kvm_for_each_vcpu(i, vcpu, kvm)
5165 *val += *(u64 *)((void *)(&vcpu->stat) + offset);
5170 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
5173 struct kvm_vcpu *vcpu;
5175 kvm_for_each_vcpu(i, vcpu, kvm)
5176 *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
5181 static int kvm_stat_data_get(void *data, u64 *val)
5184 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5186 switch (stat_data->kind) {
5188 r = kvm_get_stat_per_vm(stat_data->kvm,
5189 stat_data->desc->desc.offset, val);
5192 r = kvm_get_stat_per_vcpu(stat_data->kvm,
5193 stat_data->desc->desc.offset, val);
5200 static int kvm_stat_data_clear(void *data, u64 val)
5203 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5208 switch (stat_data->kind) {
5210 r = kvm_clear_stat_per_vm(stat_data->kvm,
5211 stat_data->desc->desc.offset);
5214 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
5215 stat_data->desc->desc.offset);
5222 static int kvm_stat_data_open(struct inode *inode, struct file *file)
5224 __simple_attr_check_format("%llu\n", 0ull);
5225 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5226 kvm_stat_data_clear, "%llu\n");
5229 static const struct file_operations stat_fops_per_vm = {
5230 .owner = THIS_MODULE,
5231 .open = kvm_stat_data_open,
5232 .release = kvm_debugfs_release,
5233 .read = simple_attr_read,
5234 .write = simple_attr_write,
5235 .llseek = no_llseek,
5238 static int vm_stat_get(void *_offset, u64 *val)
5240 unsigned offset = (long)_offset;
5245 mutex_lock(&kvm_lock);
5246 list_for_each_entry(kvm, &vm_list, vm_list) {
5247 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
5250 mutex_unlock(&kvm_lock);
5254 static int vm_stat_clear(void *_offset, u64 val)
5256 unsigned offset = (long)_offset;
5262 mutex_lock(&kvm_lock);
5263 list_for_each_entry(kvm, &vm_list, vm_list) {
5264 kvm_clear_stat_per_vm(kvm, offset);
5266 mutex_unlock(&kvm_lock);
5271 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
5272 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
5274 static int vcpu_stat_get(void *_offset, u64 *val)
5276 unsigned offset = (long)_offset;
5281 mutex_lock(&kvm_lock);
5282 list_for_each_entry(kvm, &vm_list, vm_list) {
5283 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
5286 mutex_unlock(&kvm_lock);
5290 static int vcpu_stat_clear(void *_offset, u64 val)
5292 unsigned offset = (long)_offset;
5298 mutex_lock(&kvm_lock);
5299 list_for_each_entry(kvm, &vm_list, vm_list) {
5300 kvm_clear_stat_per_vcpu(kvm, offset);
5302 mutex_unlock(&kvm_lock);
5307 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5309 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
5311 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5313 struct kobj_uevent_env *env;
5314 unsigned long long created, active;
5316 if (!kvm_dev.this_device || !kvm)
5319 mutex_lock(&kvm_lock);
5320 if (type == KVM_EVENT_CREATE_VM) {
5321 kvm_createvm_count++;
5323 } else if (type == KVM_EVENT_DESTROY_VM) {
5326 created = kvm_createvm_count;
5327 active = kvm_active_vms;
5328 mutex_unlock(&kvm_lock);
5330 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
5334 add_uevent_var(env, "CREATED=%llu", created);
5335 add_uevent_var(env, "COUNT=%llu", active);
5337 if (type == KVM_EVENT_CREATE_VM) {
5338 add_uevent_var(env, "EVENT=create");
5339 kvm->userspace_pid = task_pid_nr(current);
5340 } else if (type == KVM_EVENT_DESTROY_VM) {
5341 add_uevent_var(env, "EVENT=destroy");
5343 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5345 if (kvm->debugfs_dentry) {
5346 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5349 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5351 add_uevent_var(env, "STATS_PATH=%s", tmp);
5355 /* no need for checks, since we are adding at most only 5 keys */
5356 env->envp[env->envp_idx++] = NULL;
5357 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5361 static void kvm_init_debug(void)
5363 const struct file_operations *fops;
5364 const struct _kvm_stats_desc *pdesc;
5367 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5369 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5370 pdesc = &kvm_vm_stats_desc[i];
5371 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5372 fops = &vm_stat_fops;
5374 fops = &vm_stat_readonly_fops;
5375 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5377 (void *)(long)pdesc->desc.offset, fops);
5380 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5381 pdesc = &kvm_vcpu_stats_desc[i];
5382 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5383 fops = &vcpu_stat_fops;
5385 fops = &vcpu_stat_readonly_fops;
5386 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5388 (void *)(long)pdesc->desc.offset, fops);
5392 static int kvm_suspend(void)
5394 if (kvm_usage_count)
5395 hardware_disable_nolock(NULL);
5399 static void kvm_resume(void)
5401 if (kvm_usage_count) {
5402 #ifdef CONFIG_LOCKDEP
5403 WARN_ON(lockdep_is_held(&kvm_count_lock));
5405 hardware_enable_nolock(NULL);
5409 static struct syscore_ops kvm_syscore_ops = {
5410 .suspend = kvm_suspend,
5411 .resume = kvm_resume,
5415 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5417 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5420 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5422 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5424 WRITE_ONCE(vcpu->preempted, false);
5425 WRITE_ONCE(vcpu->ready, false);
5427 __this_cpu_write(kvm_running_vcpu, vcpu);
5428 kvm_arch_sched_in(vcpu, cpu);
5429 kvm_arch_vcpu_load(vcpu, cpu);
5432 static void kvm_sched_out(struct preempt_notifier *pn,
5433 struct task_struct *next)
5435 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5437 if (current->on_rq) {
5438 WRITE_ONCE(vcpu->preempted, true);
5439 WRITE_ONCE(vcpu->ready, true);
5441 kvm_arch_vcpu_put(vcpu);
5442 __this_cpu_write(kvm_running_vcpu, NULL);
5446 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5448 * We can disable preemption locally around accessing the per-CPU variable,
5449 * and use the resolved vcpu pointer after enabling preemption again,
5450 * because even if the current thread is migrated to another CPU, reading
5451 * the per-CPU value later will give us the same value as we update the
5452 * per-CPU variable in the preempt notifier handlers.
5454 struct kvm_vcpu *kvm_get_running_vcpu(void)
5456 struct kvm_vcpu *vcpu;
5459 vcpu = __this_cpu_read(kvm_running_vcpu);
5464 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5467 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5469 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5471 return &kvm_running_vcpu;
5474 struct kvm_cpu_compat_check {
5479 static void check_processor_compat(void *data)
5481 struct kvm_cpu_compat_check *c = data;
5483 *c->ret = kvm_arch_check_processor_compat(c->opaque);
5486 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5487 struct module *module)
5489 struct kvm_cpu_compat_check c;
5493 r = kvm_arch_init(opaque);
5498 * kvm_arch_init makes sure there's at most one caller
5499 * for architectures that support multiple implementations,
5500 * like intel and amd on x86.
5501 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5502 * conflicts in case kvm is already setup for another implementation.
5504 r = kvm_irqfd_init();
5508 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5513 r = kvm_arch_hardware_setup(opaque);
5519 for_each_online_cpu(cpu) {
5520 smp_call_function_single(cpu, check_processor_compat, &c, 1);
5525 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5526 kvm_starting_cpu, kvm_dying_cpu);
5529 register_reboot_notifier(&kvm_reboot_notifier);
5531 /* A kmem cache lets us meet the alignment requirements of fx_save. */
5533 vcpu_align = __alignof__(struct kvm_vcpu);
5535 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5537 offsetof(struct kvm_vcpu, arch),
5538 offsetofend(struct kvm_vcpu, stats_id)
5539 - offsetof(struct kvm_vcpu, arch),
5541 if (!kvm_vcpu_cache) {
5546 r = kvm_async_pf_init();
5550 kvm_chardev_ops.owner = module;
5551 kvm_vm_fops.owner = module;
5552 kvm_vcpu_fops.owner = module;
5554 r = misc_register(&kvm_dev);
5556 pr_err("kvm: misc device register failed\n");
5560 register_syscore_ops(&kvm_syscore_ops);
5562 kvm_preempt_ops.sched_in = kvm_sched_in;
5563 kvm_preempt_ops.sched_out = kvm_sched_out;
5567 r = kvm_vfio_ops_init();
5573 kvm_async_pf_deinit();
5575 kmem_cache_destroy(kvm_vcpu_cache);
5577 unregister_reboot_notifier(&kvm_reboot_notifier);
5578 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5580 kvm_arch_hardware_unsetup();
5582 free_cpumask_var(cpus_hardware_enabled);
5590 EXPORT_SYMBOL_GPL(kvm_init);
5594 debugfs_remove_recursive(kvm_debugfs_dir);
5595 misc_deregister(&kvm_dev);
5596 kmem_cache_destroy(kvm_vcpu_cache);
5597 kvm_async_pf_deinit();
5598 unregister_syscore_ops(&kvm_syscore_ops);
5599 unregister_reboot_notifier(&kvm_reboot_notifier);
5600 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5601 on_each_cpu(hardware_disable_nolock, NULL, 1);
5602 kvm_arch_hardware_unsetup();
5605 free_cpumask_var(cpus_hardware_enabled);
5606 kvm_vfio_ops_exit();
5608 EXPORT_SYMBOL_GPL(kvm_exit);
5610 struct kvm_vm_worker_thread_context {
5612 struct task_struct *parent;
5613 struct completion init_done;
5614 kvm_vm_thread_fn_t thread_fn;
5619 static int kvm_vm_worker_thread(void *context)
5622 * The init_context is allocated on the stack of the parent thread, so
5623 * we have to locally copy anything that is needed beyond initialization
5625 struct kvm_vm_worker_thread_context *init_context = context;
5626 struct kvm *kvm = init_context->kvm;
5627 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5628 uintptr_t data = init_context->data;
5631 err = kthread_park(current);
5632 /* kthread_park(current) is never supposed to return an error */
5637 err = cgroup_attach_task_all(init_context->parent, current);
5639 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5644 set_user_nice(current, task_nice(init_context->parent));
5647 init_context->err = err;
5648 complete(&init_context->init_done);
5649 init_context = NULL;
5654 /* Wait to be woken up by the spawner before proceeding. */
5657 if (!kthread_should_stop())
5658 err = thread_fn(kvm, data);
5663 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5664 uintptr_t data, const char *name,
5665 struct task_struct **thread_ptr)
5667 struct kvm_vm_worker_thread_context init_context = {};
5668 struct task_struct *thread;
5671 init_context.kvm = kvm;
5672 init_context.parent = current;
5673 init_context.thread_fn = thread_fn;
5674 init_context.data = data;
5675 init_completion(&init_context.init_done);
5677 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5678 "%s-%d", name, task_pid_nr(current));
5680 return PTR_ERR(thread);
5682 /* kthread_run is never supposed to return NULL */
5683 WARN_ON(thread == NULL);
5685 wait_for_completion(&init_context.init_done);
5687 if (!init_context.err)
5688 *thread_ptr = thread;
5690 return init_context.err;