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 int kvm_debugfs_num_entries;
119 static const struct file_operations stat_fops_per_vm;
121 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
123 #ifdef CONFIG_KVM_COMPAT
124 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
126 #define KVM_COMPAT(c) .compat_ioctl = (c)
129 * For architectures that don't implement a compat infrastructure,
130 * adopt a double line of defense:
131 * - Prevent a compat task from opening /dev/kvm
132 * - If the open has been done by a 64bit task, and the KVM fd
133 * passed to a compat task, let the ioctls fail.
135 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
136 unsigned long arg) { return -EINVAL; }
138 static int kvm_no_compat_open(struct inode *inode, struct file *file)
140 return is_compat_task() ? -ENODEV : 0;
142 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
143 .open = kvm_no_compat_open
145 static int hardware_enable_all(void);
146 static void hardware_disable_all(void);
148 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
150 __visible bool kvm_rebooting;
151 EXPORT_SYMBOL_GPL(kvm_rebooting);
153 #define KVM_EVENT_CREATE_VM 0
154 #define KVM_EVENT_DESTROY_VM 1
155 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
156 static unsigned long long kvm_createvm_count;
157 static unsigned long long kvm_active_vms;
159 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
160 unsigned long start, unsigned long end)
164 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
167 * The metadata used by is_zone_device_page() to determine whether or
168 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
169 * the device has been pinned, e.g. by get_user_pages(). WARN if the
170 * page_count() is zero to help detect bad usage of this helper.
172 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
175 return is_zone_device_page(pfn_to_page(pfn));
178 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
181 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
182 * perspective they are "normal" pages, albeit with slightly different
186 return PageReserved(pfn_to_page(pfn)) &&
188 !kvm_is_zone_device_pfn(pfn);
193 bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
195 struct page *page = pfn_to_page(pfn);
197 if (!PageTransCompoundMap(page))
200 return is_transparent_hugepage(compound_head(page));
204 * Switches to specified vcpu, until a matching vcpu_put()
206 void vcpu_load(struct kvm_vcpu *vcpu)
210 __this_cpu_write(kvm_running_vcpu, vcpu);
211 preempt_notifier_register(&vcpu->preempt_notifier);
212 kvm_arch_vcpu_load(vcpu, cpu);
215 EXPORT_SYMBOL_GPL(vcpu_load);
217 void vcpu_put(struct kvm_vcpu *vcpu)
220 kvm_arch_vcpu_put(vcpu);
221 preempt_notifier_unregister(&vcpu->preempt_notifier);
222 __this_cpu_write(kvm_running_vcpu, NULL);
225 EXPORT_SYMBOL_GPL(vcpu_put);
227 /* TODO: merge with kvm_arch_vcpu_should_kick */
228 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
230 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
233 * We need to wait for the VCPU to reenable interrupts and get out of
234 * READING_SHADOW_PAGE_TABLES mode.
236 if (req & KVM_REQUEST_WAIT)
237 return mode != OUTSIDE_GUEST_MODE;
240 * Need to kick a running VCPU, but otherwise there is nothing to do.
242 return mode == IN_GUEST_MODE;
245 static void ack_flush(void *_completed)
249 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
252 cpus = cpu_online_mask;
254 if (cpumask_empty(cpus))
257 smp_call_function_many(cpus, ack_flush, NULL, wait);
261 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
262 struct kvm_vcpu *except,
263 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
266 struct kvm_vcpu *vcpu;
271 kvm_for_each_vcpu(i, vcpu, kvm) {
272 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
276 kvm_make_request(req, vcpu);
279 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
282 if (tmp != NULL && cpu != -1 && cpu != me &&
283 kvm_request_needs_ipi(vcpu, req))
284 __cpumask_set_cpu(cpu, tmp);
287 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
293 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
294 struct kvm_vcpu *except)
299 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
301 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
303 free_cpumask_var(cpus);
307 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
309 return kvm_make_all_cpus_request_except(kvm, req, NULL);
311 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
313 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
314 void kvm_flush_remote_tlbs(struct kvm *kvm)
317 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
318 * kvm_make_all_cpus_request.
320 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
323 * We want to publish modifications to the page tables before reading
324 * mode. Pairs with a memory barrier in arch-specific code.
325 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
326 * and smp_mb in walk_shadow_page_lockless_begin/end.
327 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
329 * There is already an smp_mb__after_atomic() before
330 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
333 if (!kvm_arch_flush_remote_tlb(kvm)
334 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
335 ++kvm->stat.generic.remote_tlb_flush;
336 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
338 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
341 void kvm_reload_remote_mmus(struct kvm *kvm)
343 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
346 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
347 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
350 gfp_flags |= mc->gfp_zero;
353 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
355 return (void *)__get_free_page(gfp_flags);
358 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
362 if (mc->nobjs >= min)
364 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
365 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
367 return mc->nobjs >= min ? 0 : -ENOMEM;
368 mc->objects[mc->nobjs++] = obj;
373 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
378 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
382 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
384 free_page((unsigned long)mc->objects[--mc->nobjs]);
388 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
392 if (WARN_ON(!mc->nobjs))
393 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
395 p = mc->objects[--mc->nobjs];
401 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
403 mutex_init(&vcpu->mutex);
408 rcuwait_init(&vcpu->wait);
409 kvm_async_pf_vcpu_init(vcpu);
412 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
414 kvm_vcpu_set_in_spin_loop(vcpu, false);
415 kvm_vcpu_set_dy_eligible(vcpu, false);
416 vcpu->preempted = false;
418 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
421 void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
423 kvm_dirty_ring_free(&vcpu->dirty_ring);
424 kvm_arch_vcpu_destroy(vcpu);
427 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
428 * the vcpu->pid pointer, and at destruction time all file descriptors
431 put_pid(rcu_dereference_protected(vcpu->pid, 1));
433 free_page((unsigned long)vcpu->run);
434 kmem_cache_free(kvm_vcpu_cache, vcpu);
436 EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
438 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
439 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
441 return container_of(mn, struct kvm, mmu_notifier);
444 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
445 struct mm_struct *mm,
446 unsigned long start, unsigned long end)
448 struct kvm *kvm = mmu_notifier_to_kvm(mn);
451 idx = srcu_read_lock(&kvm->srcu);
452 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
453 srcu_read_unlock(&kvm->srcu, idx);
456 typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
458 typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
461 struct kvm_hva_range {
465 hva_handler_t handler;
466 on_lock_fn_t on_lock;
472 * Use a dedicated stub instead of NULL to indicate that there is no callback
473 * function/handler. The compiler technically can't guarantee that a real
474 * function will have a non-zero address, and so it will generate code to
475 * check for !NULL, whereas comparing against a stub will be elided at compile
476 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
478 static void kvm_null_fn(void)
482 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
484 static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
485 const struct kvm_hva_range *range)
487 bool ret = false, locked = false;
488 struct kvm_gfn_range gfn_range;
489 struct kvm_memory_slot *slot;
490 struct kvm_memslots *slots;
493 /* A null handler is allowed if and only if on_lock() is provided. */
494 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
495 IS_KVM_NULL_FN(range->handler)))
498 idx = srcu_read_lock(&kvm->srcu);
500 /* The on_lock() path does not yet support lock elision. */
501 if (!IS_KVM_NULL_FN(range->on_lock)) {
505 range->on_lock(kvm, range->start, range->end);
507 if (IS_KVM_NULL_FN(range->handler))
511 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
512 slots = __kvm_memslots(kvm, i);
513 kvm_for_each_memslot(slot, slots) {
514 unsigned long hva_start, hva_end;
516 hva_start = max(range->start, slot->userspace_addr);
517 hva_end = min(range->end, slot->userspace_addr +
518 (slot->npages << PAGE_SHIFT));
519 if (hva_start >= hva_end)
523 * To optimize for the likely case where the address
524 * range is covered by zero or one memslots, don't
525 * bother making these conditional (to avoid writes on
526 * the second or later invocation of the handler).
528 gfn_range.pte = range->pte;
529 gfn_range.may_block = range->may_block;
532 * {gfn(page) | page intersects with [hva_start, hva_end)} =
533 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
535 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
536 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
537 gfn_range.slot = slot;
543 ret |= range->handler(kvm, &gfn_range);
547 if (range->flush_on_ret && (ret || kvm->tlbs_dirty))
548 kvm_flush_remote_tlbs(kvm);
554 srcu_read_unlock(&kvm->srcu, idx);
556 /* The notifiers are averse to booleans. :-( */
560 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
564 hva_handler_t handler)
566 struct kvm *kvm = mmu_notifier_to_kvm(mn);
567 const struct kvm_hva_range range = {
572 .on_lock = (void *)kvm_null_fn,
573 .flush_on_ret = true,
577 return __kvm_handle_hva_range(kvm, &range);
580 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
583 hva_handler_t handler)
585 struct kvm *kvm = mmu_notifier_to_kvm(mn);
586 const struct kvm_hva_range range = {
591 .on_lock = (void *)kvm_null_fn,
592 .flush_on_ret = false,
596 return __kvm_handle_hva_range(kvm, &range);
598 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
599 struct mm_struct *mm,
600 unsigned long address,
603 struct kvm *kvm = mmu_notifier_to_kvm(mn);
605 trace_kvm_set_spte_hva(address);
608 * .change_pte() must be surrounded by .invalidate_range_{start,end}(),
609 * and so always runs with an elevated notifier count. This obviates
610 * the need to bump the sequence count.
612 WARN_ON_ONCE(!kvm->mmu_notifier_count);
614 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
617 static void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
621 * The count increase must become visible at unlock time as no
622 * spte can be established without taking the mmu_lock and
623 * count is also read inside the mmu_lock critical section.
625 kvm->mmu_notifier_count++;
626 if (likely(kvm->mmu_notifier_count == 1)) {
627 kvm->mmu_notifier_range_start = start;
628 kvm->mmu_notifier_range_end = end;
631 * Fully tracking multiple concurrent ranges has dimishing
632 * returns. Keep things simple and just find the minimal range
633 * which includes the current and new ranges. As there won't be
634 * enough information to subtract a range after its invalidate
635 * completes, any ranges invalidated concurrently will
636 * accumulate and persist until all outstanding invalidates
639 kvm->mmu_notifier_range_start =
640 min(kvm->mmu_notifier_range_start, start);
641 kvm->mmu_notifier_range_end =
642 max(kvm->mmu_notifier_range_end, end);
646 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
647 const struct mmu_notifier_range *range)
649 struct kvm *kvm = mmu_notifier_to_kvm(mn);
650 const struct kvm_hva_range hva_range = {
651 .start = range->start,
654 .handler = kvm_unmap_gfn_range,
655 .on_lock = kvm_inc_notifier_count,
656 .flush_on_ret = true,
657 .may_block = mmu_notifier_range_blockable(range),
660 trace_kvm_unmap_hva_range(range->start, range->end);
662 __kvm_handle_hva_range(kvm, &hva_range);
667 static void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
671 * This sequence increase will notify the kvm page fault that
672 * the page that is going to be mapped in the spte could have
675 kvm->mmu_notifier_seq++;
678 * The above sequence increase must be visible before the
679 * below count decrease, which is ensured by the smp_wmb above
680 * in conjunction with the smp_rmb in mmu_notifier_retry().
682 kvm->mmu_notifier_count--;
685 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
686 const struct mmu_notifier_range *range)
688 struct kvm *kvm = mmu_notifier_to_kvm(mn);
689 const struct kvm_hva_range hva_range = {
690 .start = range->start,
693 .handler = (void *)kvm_null_fn,
694 .on_lock = kvm_dec_notifier_count,
695 .flush_on_ret = false,
696 .may_block = mmu_notifier_range_blockable(range),
699 __kvm_handle_hva_range(kvm, &hva_range);
701 BUG_ON(kvm->mmu_notifier_count < 0);
704 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
705 struct mm_struct *mm,
709 trace_kvm_age_hva(start, end);
711 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
714 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
715 struct mm_struct *mm,
719 trace_kvm_age_hva(start, end);
722 * Even though we do not flush TLB, this will still adversely
723 * affect performance on pre-Haswell Intel EPT, where there is
724 * no EPT Access Bit to clear so that we have to tear down EPT
725 * tables instead. If we find this unacceptable, we can always
726 * add a parameter to kvm_age_hva so that it effectively doesn't
727 * do anything on clear_young.
729 * Also note that currently we never issue secondary TLB flushes
730 * from clear_young, leaving this job up to the regular system
731 * cadence. If we find this inaccurate, we might come up with a
732 * more sophisticated heuristic later.
734 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
737 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
738 struct mm_struct *mm,
739 unsigned long address)
741 trace_kvm_test_age_hva(address);
743 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
747 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
748 struct mm_struct *mm)
750 struct kvm *kvm = mmu_notifier_to_kvm(mn);
753 idx = srcu_read_lock(&kvm->srcu);
754 kvm_arch_flush_shadow_all(kvm);
755 srcu_read_unlock(&kvm->srcu, idx);
758 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
759 .invalidate_range = kvm_mmu_notifier_invalidate_range,
760 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
761 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
762 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
763 .clear_young = kvm_mmu_notifier_clear_young,
764 .test_young = kvm_mmu_notifier_test_young,
765 .change_pte = kvm_mmu_notifier_change_pte,
766 .release = kvm_mmu_notifier_release,
769 static int kvm_init_mmu_notifier(struct kvm *kvm)
771 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
772 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
775 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
777 static int kvm_init_mmu_notifier(struct kvm *kvm)
782 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
784 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
785 static int kvm_pm_notifier_call(struct notifier_block *bl,
789 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
791 return kvm_arch_pm_notifier(kvm, state);
794 static void kvm_init_pm_notifier(struct kvm *kvm)
796 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
797 /* Suspend KVM before we suspend ftrace, RCU, etc. */
798 kvm->pm_notifier.priority = INT_MAX;
799 register_pm_notifier(&kvm->pm_notifier);
802 static void kvm_destroy_pm_notifier(struct kvm *kvm)
804 unregister_pm_notifier(&kvm->pm_notifier);
806 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
807 static void kvm_init_pm_notifier(struct kvm *kvm)
811 static void kvm_destroy_pm_notifier(struct kvm *kvm)
814 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
816 static struct kvm_memslots *kvm_alloc_memslots(void)
819 struct kvm_memslots *slots;
821 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
825 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
826 slots->id_to_index[i] = -1;
831 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
833 if (!memslot->dirty_bitmap)
836 kvfree(memslot->dirty_bitmap);
837 memslot->dirty_bitmap = NULL;
840 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
842 kvm_destroy_dirty_bitmap(slot);
844 kvm_arch_free_memslot(kvm, slot);
850 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
852 struct kvm_memory_slot *memslot;
857 kvm_for_each_memslot(memslot, slots)
858 kvm_free_memslot(kvm, memslot);
863 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
867 if (!kvm->debugfs_dentry)
870 debugfs_remove_recursive(kvm->debugfs_dentry);
872 if (kvm->debugfs_stat_data) {
873 for (i = 0; i < kvm_debugfs_num_entries; i++)
874 kfree(kvm->debugfs_stat_data[i]);
875 kfree(kvm->debugfs_stat_data);
879 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
881 char dir_name[ITOA_MAX_LEN * 2];
882 struct kvm_stat_data *stat_data;
883 struct kvm_stats_debugfs_item *p;
885 if (!debugfs_initialized())
888 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
889 kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
891 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
892 sizeof(*kvm->debugfs_stat_data),
894 if (!kvm->debugfs_stat_data)
897 for (p = debugfs_entries; p->name; p++) {
898 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
902 stat_data->kvm = kvm;
903 stat_data->dbgfs_item = p;
904 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
905 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
906 kvm->debugfs_dentry, stat_data,
913 * Called after the VM is otherwise initialized, but just before adding it to
916 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
922 * Called just after removing the VM from the vm_list, but before doing any
925 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
929 static struct kvm *kvm_create_vm(unsigned long type)
931 struct kvm *kvm = kvm_arch_alloc_vm();
936 return ERR_PTR(-ENOMEM);
938 KVM_MMU_LOCK_INIT(kvm);
940 kvm->mm = current->mm;
941 kvm_eventfd_init(kvm);
942 mutex_init(&kvm->lock);
943 mutex_init(&kvm->irq_lock);
944 mutex_init(&kvm->slots_lock);
945 mutex_init(&kvm->slots_arch_lock);
946 INIT_LIST_HEAD(&kvm->devices);
948 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
950 if (init_srcu_struct(&kvm->srcu))
951 goto out_err_no_srcu;
952 if (init_srcu_struct(&kvm->irq_srcu))
953 goto out_err_no_irq_srcu;
955 refcount_set(&kvm->users_count, 1);
956 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
957 struct kvm_memslots *slots = kvm_alloc_memslots();
960 goto out_err_no_arch_destroy_vm;
961 /* Generations must be different for each address space. */
962 slots->generation = i;
963 rcu_assign_pointer(kvm->memslots[i], slots);
966 for (i = 0; i < KVM_NR_BUSES; i++) {
967 rcu_assign_pointer(kvm->buses[i],
968 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
970 goto out_err_no_arch_destroy_vm;
973 kvm->max_halt_poll_ns = halt_poll_ns;
975 r = kvm_arch_init_vm(kvm, type);
977 goto out_err_no_arch_destroy_vm;
979 r = hardware_enable_all();
981 goto out_err_no_disable;
983 #ifdef CONFIG_HAVE_KVM_IRQFD
984 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
987 r = kvm_init_mmu_notifier(kvm);
989 goto out_err_no_mmu_notifier;
991 r = kvm_arch_post_init_vm(kvm);
995 mutex_lock(&kvm_lock);
996 list_add(&kvm->vm_list, &vm_list);
997 mutex_unlock(&kvm_lock);
999 preempt_notifier_inc();
1000 kvm_init_pm_notifier(kvm);
1005 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1006 if (kvm->mmu_notifier.ops)
1007 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1009 out_err_no_mmu_notifier:
1010 hardware_disable_all();
1012 kvm_arch_destroy_vm(kvm);
1013 out_err_no_arch_destroy_vm:
1014 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
1015 for (i = 0; i < KVM_NR_BUSES; i++)
1016 kfree(kvm_get_bus(kvm, i));
1017 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
1018 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
1019 cleanup_srcu_struct(&kvm->irq_srcu);
1020 out_err_no_irq_srcu:
1021 cleanup_srcu_struct(&kvm->srcu);
1023 kvm_arch_free_vm(kvm);
1024 mmdrop(current->mm);
1028 static void kvm_destroy_devices(struct kvm *kvm)
1030 struct kvm_device *dev, *tmp;
1033 * We do not need to take the kvm->lock here, because nobody else
1034 * has a reference to the struct kvm at this point and therefore
1035 * cannot access the devices list anyhow.
1037 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1038 list_del(&dev->vm_node);
1039 dev->ops->destroy(dev);
1043 static void kvm_destroy_vm(struct kvm *kvm)
1046 struct mm_struct *mm = kvm->mm;
1048 kvm_destroy_pm_notifier(kvm);
1049 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1050 kvm_destroy_vm_debugfs(kvm);
1051 kvm_arch_sync_events(kvm);
1052 mutex_lock(&kvm_lock);
1053 list_del(&kvm->vm_list);
1054 mutex_unlock(&kvm_lock);
1055 kvm_arch_pre_destroy_vm(kvm);
1057 kvm_free_irq_routing(kvm);
1058 for (i = 0; i < KVM_NR_BUSES; i++) {
1059 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1062 kvm_io_bus_destroy(bus);
1063 kvm->buses[i] = NULL;
1065 kvm_coalesced_mmio_free(kvm);
1066 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1067 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1069 kvm_arch_flush_shadow_all(kvm);
1071 kvm_arch_destroy_vm(kvm);
1072 kvm_destroy_devices(kvm);
1073 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
1074 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
1075 cleanup_srcu_struct(&kvm->irq_srcu);
1076 cleanup_srcu_struct(&kvm->srcu);
1077 kvm_arch_free_vm(kvm);
1078 preempt_notifier_dec();
1079 hardware_disable_all();
1083 void kvm_get_kvm(struct kvm *kvm)
1085 refcount_inc(&kvm->users_count);
1087 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1089 void kvm_put_kvm(struct kvm *kvm)
1091 if (refcount_dec_and_test(&kvm->users_count))
1092 kvm_destroy_vm(kvm);
1094 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1097 * Used to put a reference that was taken on behalf of an object associated
1098 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1099 * of the new file descriptor fails and the reference cannot be transferred to
1100 * its final owner. In such cases, the caller is still actively using @kvm and
1101 * will fail miserably if the refcount unexpectedly hits zero.
1103 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1105 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1107 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1109 static int kvm_vm_release(struct inode *inode, struct file *filp)
1111 struct kvm *kvm = filp->private_data;
1113 kvm_irqfd_release(kvm);
1120 * Allocation size is twice as large as the actual dirty bitmap size.
1121 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1123 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1125 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
1127 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
1128 if (!memslot->dirty_bitmap)
1135 * Delete a memslot by decrementing the number of used slots and shifting all
1136 * other entries in the array forward one spot.
1138 static inline void kvm_memslot_delete(struct kvm_memslots *slots,
1139 struct kvm_memory_slot *memslot)
1141 struct kvm_memory_slot *mslots = slots->memslots;
1144 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
1147 slots->used_slots--;
1149 if (atomic_read(&slots->lru_slot) >= slots->used_slots)
1150 atomic_set(&slots->lru_slot, 0);
1152 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
1153 mslots[i] = mslots[i + 1];
1154 slots->id_to_index[mslots[i].id] = i;
1156 mslots[i] = *memslot;
1157 slots->id_to_index[memslot->id] = -1;
1161 * "Insert" a new memslot by incrementing the number of used slots. Returns
1162 * the new slot's initial index into the memslots array.
1164 static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
1166 return slots->used_slots++;
1170 * Move a changed memslot backwards in the array by shifting existing slots
1171 * with a higher GFN toward the front of the array. Note, the changed memslot
1172 * itself is not preserved in the array, i.e. not swapped at this time, only
1173 * its new index into the array is tracked. Returns the changed memslot's
1174 * current index into the memslots array.
1176 static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
1177 struct kvm_memory_slot *memslot)
1179 struct kvm_memory_slot *mslots = slots->memslots;
1182 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
1183 WARN_ON_ONCE(!slots->used_slots))
1187 * Move the target memslot backward in the array by shifting existing
1188 * memslots with a higher GFN (than the target memslot) towards the
1189 * front of the array.
1191 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
1192 if (memslot->base_gfn > mslots[i + 1].base_gfn)
1195 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
1197 /* Shift the next memslot forward one and update its index. */
1198 mslots[i] = mslots[i + 1];
1199 slots->id_to_index[mslots[i].id] = i;
1205 * Move a changed memslot forwards in the array by shifting existing slots with
1206 * a lower GFN toward the back of the array. Note, the changed memslot itself
1207 * is not preserved in the array, i.e. not swapped at this time, only its new
1208 * index into the array is tracked. Returns the changed memslot's final index
1209 * into the memslots array.
1211 static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
1212 struct kvm_memory_slot *memslot,
1215 struct kvm_memory_slot *mslots = slots->memslots;
1218 for (i = start; i > 0; i--) {
1219 if (memslot->base_gfn < mslots[i - 1].base_gfn)
1222 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
1224 /* Shift the next memslot back one and update its index. */
1225 mslots[i] = mslots[i - 1];
1226 slots->id_to_index[mslots[i].id] = i;
1232 * Re-sort memslots based on their GFN to account for an added, deleted, or
1233 * moved memslot. Sorting memslots by GFN allows using a binary search during
1236 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
1237 * at memslots[0] has the highest GFN.
1239 * The sorting algorithm takes advantage of having initially sorted memslots
1240 * and knowing the position of the changed memslot. Sorting is also optimized
1241 * by not swapping the updated memslot and instead only shifting other memslots
1242 * and tracking the new index for the update memslot. Only once its final
1243 * index is known is the updated memslot copied into its position in the array.
1245 * - When deleting a memslot, the deleted memslot simply needs to be moved to
1246 * the end of the array.
1248 * - When creating a memslot, the algorithm "inserts" the new memslot at the
1249 * end of the array and then it forward to its correct location.
1251 * - When moving a memslot, the algorithm first moves the updated memslot
1252 * backward to handle the scenario where the memslot's GFN was changed to a
1253 * lower value. update_memslots() then falls through and runs the same flow
1254 * as creating a memslot to move the memslot forward to handle the scenario
1255 * where its GFN was changed to a higher value.
1257 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1258 * historical reasons. Originally, invalid memslots where denoted by having
1259 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1260 * to the end of the array. The current algorithm uses dedicated logic to
1261 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1263 * The other historical motiviation for highest->lowest was to improve the
1264 * performance of memslot lookup. KVM originally used a linear search starting
1265 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1266 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1267 * single memslot above the 4gb boundary. As the largest memslot is also the
1268 * most likely to be referenced, sorting it to the front of the array was
1269 * advantageous. The current binary search starts from the middle of the array
1270 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1272 static void update_memslots(struct kvm_memslots *slots,
1273 struct kvm_memory_slot *memslot,
1274 enum kvm_mr_change change)
1278 if (change == KVM_MR_DELETE) {
1279 kvm_memslot_delete(slots, memslot);
1281 if (change == KVM_MR_CREATE)
1282 i = kvm_memslot_insert_back(slots);
1284 i = kvm_memslot_move_backward(slots, memslot);
1285 i = kvm_memslot_move_forward(slots, memslot, i);
1288 * Copy the memslot to its new position in memslots and update
1289 * its index accordingly.
1291 slots->memslots[i] = *memslot;
1292 slots->id_to_index[memslot->id] = i;
1296 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1298 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1300 #ifdef __KVM_HAVE_READONLY_MEM
1301 valid_flags |= KVM_MEM_READONLY;
1304 if (mem->flags & ~valid_flags)
1310 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
1311 int as_id, struct kvm_memslots *slots)
1313 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
1314 u64 gen = old_memslots->generation;
1316 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1317 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1319 rcu_assign_pointer(kvm->memslots[as_id], slots);
1322 * Acquired in kvm_set_memslot. Must be released before synchronize
1323 * SRCU below in order to avoid deadlock with another thread
1324 * acquiring the slots_arch_lock in an srcu critical section.
1326 mutex_unlock(&kvm->slots_arch_lock);
1328 synchronize_srcu_expedited(&kvm->srcu);
1331 * Increment the new memslot generation a second time, dropping the
1332 * update in-progress flag and incrementing the generation based on
1333 * the number of address spaces. This provides a unique and easily
1334 * identifiable generation number while the memslots are in flux.
1336 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1339 * Generations must be unique even across address spaces. We do not need
1340 * a global counter for that, instead the generation space is evenly split
1341 * across address spaces. For example, with two address spaces, address
1342 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1343 * use generations 1, 3, 5, ...
1345 gen += KVM_ADDRESS_SPACE_NUM;
1347 kvm_arch_memslots_updated(kvm, gen);
1349 slots->generation = gen;
1351 return old_memslots;
1354 static size_t kvm_memslots_size(int slots)
1356 return sizeof(struct kvm_memslots) +
1357 (sizeof(struct kvm_memory_slot) * slots);
1360 static void kvm_copy_memslots(struct kvm_memslots *to,
1361 struct kvm_memslots *from)
1363 memcpy(to, from, kvm_memslots_size(from->used_slots));
1367 * Note, at a minimum, the current number of used slots must be allocated, even
1368 * when deleting a memslot, as we need a complete duplicate of the memslots for
1369 * use when invalidating a memslot prior to deleting/moving the memslot.
1371 static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1372 enum kvm_mr_change change)
1374 struct kvm_memslots *slots;
1377 if (change == KVM_MR_CREATE)
1378 new_size = kvm_memslots_size(old->used_slots + 1);
1380 new_size = kvm_memslots_size(old->used_slots);
1382 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1384 kvm_copy_memslots(slots, old);
1389 static int kvm_set_memslot(struct kvm *kvm,
1390 const struct kvm_userspace_memory_region *mem,
1391 struct kvm_memory_slot *old,
1392 struct kvm_memory_slot *new, int as_id,
1393 enum kvm_mr_change change)
1395 struct kvm_memory_slot *slot;
1396 struct kvm_memslots *slots;
1400 * Released in install_new_memslots.
1402 * Must be held from before the current memslots are copied until
1403 * after the new memslots are installed with rcu_assign_pointer,
1404 * then released before the synchronize srcu in install_new_memslots.
1406 * When modifying memslots outside of the slots_lock, must be held
1407 * before reading the pointer to the current memslots until after all
1408 * changes to those memslots are complete.
1410 * These rules ensure that installing new memslots does not lose
1411 * changes made to the previous memslots.
1413 mutex_lock(&kvm->slots_arch_lock);
1415 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
1417 mutex_unlock(&kvm->slots_arch_lock);
1421 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1423 * Note, the INVALID flag needs to be in the appropriate entry
1424 * in the freshly allocated memslots, not in @old or @new.
1426 slot = id_to_memslot(slots, old->id);
1427 slot->flags |= KVM_MEMSLOT_INVALID;
1430 * We can re-use the memory from the old memslots.
1431 * It will be overwritten with a copy of the new memslots
1432 * after reacquiring the slots_arch_lock below.
1434 slots = install_new_memslots(kvm, as_id, slots);
1436 /* From this point no new shadow pages pointing to a deleted,
1437 * or moved, memslot will be created.
1439 * validation of sp->gfn happens in:
1440 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1441 * - kvm_is_visible_gfn (mmu_check_root)
1443 kvm_arch_flush_shadow_memslot(kvm, slot);
1445 /* Released in install_new_memslots. */
1446 mutex_lock(&kvm->slots_arch_lock);
1449 * The arch-specific fields of the memslots could have changed
1450 * between releasing the slots_arch_lock in
1451 * install_new_memslots and here, so get a fresh copy of the
1454 kvm_copy_memslots(slots, __kvm_memslots(kvm, as_id));
1457 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1461 update_memslots(slots, new, change);
1462 slots = install_new_memslots(kvm, as_id, slots);
1464 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1470 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1471 slot = id_to_memslot(slots, old->id);
1472 slot->flags &= ~KVM_MEMSLOT_INVALID;
1473 slots = install_new_memslots(kvm, as_id, slots);
1475 mutex_unlock(&kvm->slots_arch_lock);
1481 static int kvm_delete_memslot(struct kvm *kvm,
1482 const struct kvm_userspace_memory_region *mem,
1483 struct kvm_memory_slot *old, int as_id)
1485 struct kvm_memory_slot new;
1491 memset(&new, 0, sizeof(new));
1494 * This is only for debugging purpose; it should never be referenced
1495 * for a removed memslot.
1499 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1503 kvm_free_memslot(kvm, old);
1508 * Allocate some memory and give it an address in the guest physical address
1511 * Discontiguous memory is allowed, mostly for framebuffers.
1513 * Must be called holding kvm->slots_lock for write.
1515 int __kvm_set_memory_region(struct kvm *kvm,
1516 const struct kvm_userspace_memory_region *mem)
1518 struct kvm_memory_slot old, new;
1519 struct kvm_memory_slot *tmp;
1520 enum kvm_mr_change change;
1524 r = check_memory_region_flags(mem);
1528 as_id = mem->slot >> 16;
1529 id = (u16)mem->slot;
1531 /* General sanity checks */
1532 if (mem->memory_size & (PAGE_SIZE - 1))
1534 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1536 /* We can read the guest memory with __xxx_user() later on. */
1537 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1538 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1539 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1542 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1544 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1548 * Make a full copy of the old memslot, the pointer will become stale
1549 * when the memslots are re-sorted by update_memslots(), and the old
1550 * memslot needs to be referenced after calling update_memslots(), e.g.
1551 * to free its resources and for arch specific behavior.
1553 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1558 memset(&old, 0, sizeof(old));
1562 if (!mem->memory_size)
1563 return kvm_delete_memslot(kvm, mem, &old, as_id);
1567 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1568 new.npages = mem->memory_size >> PAGE_SHIFT;
1569 new.flags = mem->flags;
1570 new.userspace_addr = mem->userspace_addr;
1572 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1576 change = KVM_MR_CREATE;
1577 new.dirty_bitmap = NULL;
1578 memset(&new.arch, 0, sizeof(new.arch));
1579 } else { /* Modify an existing slot. */
1580 if ((new.userspace_addr != old.userspace_addr) ||
1581 (new.npages != old.npages) ||
1582 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1585 if (new.base_gfn != old.base_gfn)
1586 change = KVM_MR_MOVE;
1587 else if (new.flags != old.flags)
1588 change = KVM_MR_FLAGS_ONLY;
1589 else /* Nothing to change. */
1592 /* Copy dirty_bitmap and arch from the current memslot. */
1593 new.dirty_bitmap = old.dirty_bitmap;
1594 memcpy(&new.arch, &old.arch, sizeof(new.arch));
1597 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1598 /* Check for overlaps */
1599 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1602 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1603 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1608 /* Allocate/free page dirty bitmap as needed */
1609 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1610 new.dirty_bitmap = NULL;
1611 else if (!new.dirty_bitmap && !kvm->dirty_ring_size) {
1612 r = kvm_alloc_dirty_bitmap(&new);
1616 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1617 bitmap_set(new.dirty_bitmap, 0, new.npages);
1620 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1624 if (old.dirty_bitmap && !new.dirty_bitmap)
1625 kvm_destroy_dirty_bitmap(&old);
1629 if (new.dirty_bitmap && !old.dirty_bitmap)
1630 kvm_destroy_dirty_bitmap(&new);
1633 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1635 int kvm_set_memory_region(struct kvm *kvm,
1636 const struct kvm_userspace_memory_region *mem)
1640 mutex_lock(&kvm->slots_lock);
1641 r = __kvm_set_memory_region(kvm, mem);
1642 mutex_unlock(&kvm->slots_lock);
1645 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1647 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1648 struct kvm_userspace_memory_region *mem)
1650 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1653 return kvm_set_memory_region(kvm, mem);
1656 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1658 * kvm_get_dirty_log - get a snapshot of dirty pages
1659 * @kvm: pointer to kvm instance
1660 * @log: slot id and address to which we copy the log
1661 * @is_dirty: set to '1' if any dirty pages were found
1662 * @memslot: set to the associated memslot, always valid on success
1664 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1665 int *is_dirty, struct kvm_memory_slot **memslot)
1667 struct kvm_memslots *slots;
1670 unsigned long any = 0;
1672 /* Dirty ring tracking is exclusive to dirty log tracking */
1673 if (kvm->dirty_ring_size)
1679 as_id = log->slot >> 16;
1680 id = (u16)log->slot;
1681 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1684 slots = __kvm_memslots(kvm, as_id);
1685 *memslot = id_to_memslot(slots, id);
1686 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1689 kvm_arch_sync_dirty_log(kvm, *memslot);
1691 n = kvm_dirty_bitmap_bytes(*memslot);
1693 for (i = 0; !any && i < n/sizeof(long); ++i)
1694 any = (*memslot)->dirty_bitmap[i];
1696 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1703 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1705 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1707 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1708 * and reenable dirty page tracking for the corresponding pages.
1709 * @kvm: pointer to kvm instance
1710 * @log: slot id and address to which we copy the log
1712 * We need to keep it in mind that VCPU threads can write to the bitmap
1713 * concurrently. So, to avoid losing track of dirty pages we keep the
1716 * 1. Take a snapshot of the bit and clear it if needed.
1717 * 2. Write protect the corresponding page.
1718 * 3. Copy the snapshot to the userspace.
1719 * 4. Upon return caller flushes TLB's if needed.
1721 * Between 2 and 4, the guest may write to the page using the remaining TLB
1722 * entry. This is not a problem because the page is reported dirty using
1723 * the snapshot taken before and step 4 ensures that writes done after
1724 * exiting to userspace will be logged for the next call.
1727 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
1729 struct kvm_memslots *slots;
1730 struct kvm_memory_slot *memslot;
1733 unsigned long *dirty_bitmap;
1734 unsigned long *dirty_bitmap_buffer;
1737 /* Dirty ring tracking is exclusive to dirty log tracking */
1738 if (kvm->dirty_ring_size)
1741 as_id = log->slot >> 16;
1742 id = (u16)log->slot;
1743 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1746 slots = __kvm_memslots(kvm, as_id);
1747 memslot = id_to_memslot(slots, id);
1748 if (!memslot || !memslot->dirty_bitmap)
1751 dirty_bitmap = memslot->dirty_bitmap;
1753 kvm_arch_sync_dirty_log(kvm, memslot);
1755 n = kvm_dirty_bitmap_bytes(memslot);
1757 if (kvm->manual_dirty_log_protect) {
1759 * Unlike kvm_get_dirty_log, we always return false in *flush,
1760 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1761 * is some code duplication between this function and
1762 * kvm_get_dirty_log, but hopefully all architecture
1763 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1764 * can be eliminated.
1766 dirty_bitmap_buffer = dirty_bitmap;
1768 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1769 memset(dirty_bitmap_buffer, 0, n);
1772 for (i = 0; i < n / sizeof(long); i++) {
1776 if (!dirty_bitmap[i])
1780 mask = xchg(&dirty_bitmap[i], 0);
1781 dirty_bitmap_buffer[i] = mask;
1783 offset = i * BITS_PER_LONG;
1784 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1787 KVM_MMU_UNLOCK(kvm);
1791 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1793 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1800 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1801 * @kvm: kvm instance
1802 * @log: slot id and address to which we copy the log
1804 * Steps 1-4 below provide general overview of dirty page logging. See
1805 * kvm_get_dirty_log_protect() function description for additional details.
1807 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1808 * always flush the TLB (step 4) even if previous step failed and the dirty
1809 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1810 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1811 * writes will be marked dirty for next log read.
1813 * 1. Take a snapshot of the bit and clear it if needed.
1814 * 2. Write protect the corresponding page.
1815 * 3. Copy the snapshot to the userspace.
1816 * 4. Flush TLB's if needed.
1818 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1819 struct kvm_dirty_log *log)
1823 mutex_lock(&kvm->slots_lock);
1825 r = kvm_get_dirty_log_protect(kvm, log);
1827 mutex_unlock(&kvm->slots_lock);
1832 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1833 * and reenable dirty page tracking for the corresponding pages.
1834 * @kvm: pointer to kvm instance
1835 * @log: slot id and address from which to fetch the bitmap of dirty pages
1837 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1838 struct kvm_clear_dirty_log *log)
1840 struct kvm_memslots *slots;
1841 struct kvm_memory_slot *memslot;
1845 unsigned long *dirty_bitmap;
1846 unsigned long *dirty_bitmap_buffer;
1849 /* Dirty ring tracking is exclusive to dirty log tracking */
1850 if (kvm->dirty_ring_size)
1853 as_id = log->slot >> 16;
1854 id = (u16)log->slot;
1855 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1858 if (log->first_page & 63)
1861 slots = __kvm_memslots(kvm, as_id);
1862 memslot = id_to_memslot(slots, id);
1863 if (!memslot || !memslot->dirty_bitmap)
1866 dirty_bitmap = memslot->dirty_bitmap;
1868 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
1870 if (log->first_page > memslot->npages ||
1871 log->num_pages > memslot->npages - log->first_page ||
1872 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1875 kvm_arch_sync_dirty_log(kvm, memslot);
1878 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1879 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1883 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1884 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
1885 i++, offset += BITS_PER_LONG) {
1886 unsigned long mask = *dirty_bitmap_buffer++;
1887 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1891 mask &= atomic_long_fetch_andnot(mask, p);
1894 * mask contains the bits that really have been cleared. This
1895 * never includes any bits beyond the length of the memslot (if
1896 * the length is not aligned to 64 pages), therefore it is not
1897 * a problem if userspace sets them in log->dirty_bitmap.
1901 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1905 KVM_MMU_UNLOCK(kvm);
1908 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1913 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
1914 struct kvm_clear_dirty_log *log)
1918 mutex_lock(&kvm->slots_lock);
1920 r = kvm_clear_dirty_log_protect(kvm, log);
1922 mutex_unlock(&kvm->slots_lock);
1925 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1927 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1929 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1931 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1933 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1935 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1937 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
1939 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1941 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1943 return kvm_is_visible_memslot(memslot);
1945 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1947 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1949 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1951 return kvm_is_visible_memslot(memslot);
1953 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
1955 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
1957 struct vm_area_struct *vma;
1958 unsigned long addr, size;
1962 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
1963 if (kvm_is_error_hva(addr))
1966 mmap_read_lock(current->mm);
1967 vma = find_vma(current->mm, addr);
1971 size = vma_kernel_pagesize(vma);
1974 mmap_read_unlock(current->mm);
1979 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1981 return slot->flags & KVM_MEM_READONLY;
1984 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1985 gfn_t *nr_pages, bool write)
1987 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1988 return KVM_HVA_ERR_BAD;
1990 if (memslot_is_readonly(slot) && write)
1991 return KVM_HVA_ERR_RO_BAD;
1994 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1996 return __gfn_to_hva_memslot(slot, gfn);
1999 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2002 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2005 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2008 return gfn_to_hva_many(slot, gfn, NULL);
2010 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2012 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2014 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2016 EXPORT_SYMBOL_GPL(gfn_to_hva);
2018 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2020 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2022 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2025 * Return the hva of a @gfn and the R/W attribute if possible.
2027 * @slot: the kvm_memory_slot which contains @gfn
2028 * @gfn: the gfn to be translated
2029 * @writable: used to return the read/write attribute of the @slot if the hva
2030 * is valid and @writable is not NULL
2032 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2033 gfn_t gfn, bool *writable)
2035 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2037 if (!kvm_is_error_hva(hva) && writable)
2038 *writable = !memslot_is_readonly(slot);
2043 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2045 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2047 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2050 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2052 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2054 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2057 static inline int check_user_page_hwpoison(unsigned long addr)
2059 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
2061 rc = get_user_pages(addr, 1, flags, NULL, NULL);
2062 return rc == -EHWPOISON;
2066 * The fast path to get the writable pfn which will be stored in @pfn,
2067 * true indicates success, otherwise false is returned. It's also the
2068 * only part that runs if we can in atomic context.
2070 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2071 bool *writable, kvm_pfn_t *pfn)
2073 struct page *page[1];
2076 * Fast pin a writable pfn only if it is a write fault request
2077 * or the caller allows to map a writable pfn for a read fault
2080 if (!(write_fault || writable))
2083 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2084 *pfn = page_to_pfn(page[0]);
2095 * The slow path to get the pfn of the specified host virtual address,
2096 * 1 indicates success, -errno is returned if error is detected.
2098 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2099 bool *writable, kvm_pfn_t *pfn)
2101 unsigned int flags = FOLL_HWPOISON;
2108 *writable = write_fault;
2111 flags |= FOLL_WRITE;
2113 flags |= FOLL_NOWAIT;
2115 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2119 /* map read fault as writable if possible */
2120 if (unlikely(!write_fault) && writable) {
2123 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2129 *pfn = page_to_pfn(page);
2133 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2135 if (unlikely(!(vma->vm_flags & VM_READ)))
2138 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2144 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2145 unsigned long addr, bool *async,
2146 bool write_fault, bool *writable,
2154 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2157 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2158 * not call the fault handler, so do it here.
2160 bool unlocked = false;
2161 r = fixup_user_fault(current->mm, addr,
2162 (write_fault ? FAULT_FLAG_WRITE : 0),
2169 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2174 if (write_fault && !pte_write(*ptep)) {
2175 pfn = KVM_PFN_ERR_RO_FAULT;
2180 *writable = pte_write(*ptep);
2181 pfn = pte_pfn(*ptep);
2184 * Get a reference here because callers of *hva_to_pfn* and
2185 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2186 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2187 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
2188 * simply do nothing for reserved pfns.
2190 * Whoever called remap_pfn_range is also going to call e.g.
2191 * unmap_mapping_range before the underlying pages are freed,
2192 * causing a call to our MMU notifier.
2197 pte_unmap_unlock(ptep, ptl);
2203 * Pin guest page in memory and return its pfn.
2204 * @addr: host virtual address which maps memory to the guest
2205 * @atomic: whether this function can sleep
2206 * @async: whether this function need to wait IO complete if the
2207 * host page is not in the memory
2208 * @write_fault: whether we should get a writable host page
2209 * @writable: whether it allows to map a writable host page for !@write_fault
2211 * The function will map a writable host page for these two cases:
2212 * 1): @write_fault = true
2213 * 2): @write_fault = false && @writable, @writable will tell the caller
2214 * whether the mapping is writable.
2216 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2217 bool write_fault, bool *writable)
2219 struct vm_area_struct *vma;
2223 /* we can do it either atomically or asynchronously, not both */
2224 BUG_ON(atomic && async);
2226 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2230 return KVM_PFN_ERR_FAULT;
2232 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2236 mmap_read_lock(current->mm);
2237 if (npages == -EHWPOISON ||
2238 (!async && check_user_page_hwpoison(addr))) {
2239 pfn = KVM_PFN_ERR_HWPOISON;
2244 vma = find_vma_intersection(current->mm, addr, addr + 1);
2247 pfn = KVM_PFN_ERR_FAULT;
2248 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2249 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
2253 pfn = KVM_PFN_ERR_FAULT;
2255 if (async && vma_is_valid(vma, write_fault))
2257 pfn = KVM_PFN_ERR_FAULT;
2260 mmap_read_unlock(current->mm);
2264 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
2265 bool atomic, bool *async, bool write_fault,
2266 bool *writable, hva_t *hva)
2268 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2273 if (addr == KVM_HVA_ERR_RO_BAD) {
2276 return KVM_PFN_ERR_RO_FAULT;
2279 if (kvm_is_error_hva(addr)) {
2282 return KVM_PFN_NOSLOT;
2285 /* Do not map writable pfn in the readonly memslot. */
2286 if (writable && memslot_is_readonly(slot)) {
2291 return hva_to_pfn(addr, atomic, async, write_fault,
2294 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2296 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2299 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2300 write_fault, writable, NULL);
2302 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2304 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
2306 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2308 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2310 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
2312 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2314 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2316 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2318 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2320 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2322 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2324 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2326 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2328 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2330 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2332 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2334 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2335 struct page **pages, int nr_pages)
2340 addr = gfn_to_hva_many(slot, gfn, &entry);
2341 if (kvm_is_error_hva(addr))
2344 if (entry < nr_pages)
2347 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2349 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2351 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2353 if (is_error_noslot_pfn(pfn))
2354 return KVM_ERR_PTR_BAD_PAGE;
2356 if (kvm_is_reserved_pfn(pfn)) {
2358 return KVM_ERR_PTR_BAD_PAGE;
2361 return pfn_to_page(pfn);
2364 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2368 pfn = gfn_to_pfn(kvm, gfn);
2370 return kvm_pfn_to_page(pfn);
2372 EXPORT_SYMBOL_GPL(gfn_to_page);
2374 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2380 cache->pfn = cache->gfn = 0;
2383 kvm_release_pfn_dirty(pfn);
2385 kvm_release_pfn_clean(pfn);
2388 static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2389 struct gfn_to_pfn_cache *cache, u64 gen)
2391 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2393 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2395 cache->dirty = false;
2396 cache->generation = gen;
2399 static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2400 struct kvm_host_map *map,
2401 struct gfn_to_pfn_cache *cache,
2406 struct page *page = KVM_UNMAPPED_PAGE;
2407 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2408 u64 gen = slots->generation;
2414 if (!cache->pfn || cache->gfn != gfn ||
2415 cache->generation != gen) {
2418 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2424 pfn = gfn_to_pfn_memslot(slot, gfn);
2426 if (is_error_noslot_pfn(pfn))
2429 if (pfn_valid(pfn)) {
2430 page = pfn_to_page(pfn);
2432 hva = kmap_atomic(page);
2435 #ifdef CONFIG_HAS_IOMEM
2436 } else if (!atomic) {
2437 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2454 int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2455 struct gfn_to_pfn_cache *cache, bool atomic)
2457 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2460 EXPORT_SYMBOL_GPL(kvm_map_gfn);
2462 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2464 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2467 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2469 static void __kvm_unmap_gfn(struct kvm *kvm,
2470 struct kvm_memory_slot *memslot,
2471 struct kvm_host_map *map,
2472 struct gfn_to_pfn_cache *cache,
2473 bool dirty, bool atomic)
2481 if (map->page != KVM_UNMAPPED_PAGE) {
2483 kunmap_atomic(map->hva);
2487 #ifdef CONFIG_HAS_IOMEM
2491 WARN_ONCE(1, "Unexpected unmapping in atomic context");
2495 mark_page_dirty_in_slot(kvm, memslot, map->gfn);
2498 cache->dirty |= dirty;
2500 kvm_release_pfn(map->pfn, dirty, NULL);
2506 int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2507 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2509 __kvm_unmap_gfn(vcpu->kvm, gfn_to_memslot(vcpu->kvm, map->gfn), map,
2510 cache, dirty, atomic);
2513 EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2515 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2517 __kvm_unmap_gfn(vcpu->kvm, kvm_vcpu_gfn_to_memslot(vcpu, map->gfn),
2518 map, NULL, dirty, false);
2520 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2522 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2526 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2528 return kvm_pfn_to_page(pfn);
2530 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2532 void kvm_release_page_clean(struct page *page)
2534 WARN_ON(is_error_page(page));
2536 kvm_release_pfn_clean(page_to_pfn(page));
2538 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2540 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2542 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2543 put_page(pfn_to_page(pfn));
2545 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2547 void kvm_release_page_dirty(struct page *page)
2549 WARN_ON(is_error_page(page));
2551 kvm_release_pfn_dirty(page_to_pfn(page));
2553 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2555 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2557 kvm_set_pfn_dirty(pfn);
2558 kvm_release_pfn_clean(pfn);
2560 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2562 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2564 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2565 SetPageDirty(pfn_to_page(pfn));
2567 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2569 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2571 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2572 mark_page_accessed(pfn_to_page(pfn));
2574 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2576 void kvm_get_pfn(kvm_pfn_t pfn)
2578 if (!kvm_is_reserved_pfn(pfn))
2579 get_page(pfn_to_page(pfn));
2581 EXPORT_SYMBOL_GPL(kvm_get_pfn);
2583 static int next_segment(unsigned long len, int offset)
2585 if (len > PAGE_SIZE - offset)
2586 return PAGE_SIZE - offset;
2591 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2592 void *data, int offset, int len)
2597 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2598 if (kvm_is_error_hva(addr))
2600 r = __copy_from_user(data, (void __user *)addr + offset, len);
2606 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2609 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2611 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2613 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2615 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2616 int offset, int len)
2618 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2620 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2622 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2624 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2626 gfn_t gfn = gpa >> PAGE_SHIFT;
2628 int offset = offset_in_page(gpa);
2631 while ((seg = next_segment(len, offset)) != 0) {
2632 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2642 EXPORT_SYMBOL_GPL(kvm_read_guest);
2644 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2646 gfn_t gfn = gpa >> PAGE_SHIFT;
2648 int offset = offset_in_page(gpa);
2651 while ((seg = next_segment(len, offset)) != 0) {
2652 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2662 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2664 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2665 void *data, int offset, unsigned long len)
2670 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2671 if (kvm_is_error_hva(addr))
2673 pagefault_disable();
2674 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2681 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2682 void *data, unsigned long len)
2684 gfn_t gfn = gpa >> PAGE_SHIFT;
2685 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2686 int offset = offset_in_page(gpa);
2688 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2690 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2692 static int __kvm_write_guest_page(struct kvm *kvm,
2693 struct kvm_memory_slot *memslot, gfn_t gfn,
2694 const void *data, int offset, int len)
2699 addr = gfn_to_hva_memslot(memslot, gfn);
2700 if (kvm_is_error_hva(addr))
2702 r = __copy_to_user((void __user *)addr + offset, data, len);
2705 mark_page_dirty_in_slot(kvm, memslot, gfn);
2709 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2710 const void *data, int offset, int len)
2712 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2714 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2716 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2718 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2719 const void *data, int offset, int len)
2721 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2723 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
2725 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2727 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2730 gfn_t gfn = gpa >> PAGE_SHIFT;
2732 int offset = offset_in_page(gpa);
2735 while ((seg = next_segment(len, offset)) != 0) {
2736 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2746 EXPORT_SYMBOL_GPL(kvm_write_guest);
2748 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2751 gfn_t gfn = gpa >> PAGE_SHIFT;
2753 int offset = offset_in_page(gpa);
2756 while ((seg = next_segment(len, offset)) != 0) {
2757 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2767 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2769 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2770 struct gfn_to_hva_cache *ghc,
2771 gpa_t gpa, unsigned long len)
2773 int offset = offset_in_page(gpa);
2774 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2775 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2776 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2777 gfn_t nr_pages_avail;
2779 /* Update ghc->generation before performing any error checks. */
2780 ghc->generation = slots->generation;
2782 if (start_gfn > end_gfn) {
2783 ghc->hva = KVM_HVA_ERR_BAD;
2788 * If the requested region crosses two memslots, we still
2789 * verify that the entire region is valid here.
2791 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
2792 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2793 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2795 if (kvm_is_error_hva(ghc->hva))
2799 /* Use the slow path for cross page reads and writes. */
2800 if (nr_pages_needed == 1)
2803 ghc->memslot = NULL;
2810 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2811 gpa_t gpa, unsigned long len)
2813 struct kvm_memslots *slots = kvm_memslots(kvm);
2814 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2816 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2818 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2819 void *data, unsigned int offset,
2822 struct kvm_memslots *slots = kvm_memslots(kvm);
2824 gpa_t gpa = ghc->gpa + offset;
2826 BUG_ON(len + offset > ghc->len);
2828 if (slots->generation != ghc->generation) {
2829 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2833 if (kvm_is_error_hva(ghc->hva))
2836 if (unlikely(!ghc->memslot))
2837 return kvm_write_guest(kvm, gpa, data, len);
2839 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2842 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
2846 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2848 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2849 void *data, unsigned long len)
2851 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2853 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2855 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2856 void *data, unsigned int offset,
2859 struct kvm_memslots *slots = kvm_memslots(kvm);
2861 gpa_t gpa = ghc->gpa + offset;
2863 BUG_ON(len + offset > ghc->len);
2865 if (slots->generation != ghc->generation) {
2866 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2870 if (kvm_is_error_hva(ghc->hva))
2873 if (unlikely(!ghc->memslot))
2874 return kvm_read_guest(kvm, gpa, data, len);
2876 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
2882 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
2884 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2885 void *data, unsigned long len)
2887 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
2889 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2891 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2893 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2894 gfn_t gfn = gpa >> PAGE_SHIFT;
2896 int offset = offset_in_page(gpa);
2899 while ((seg = next_segment(len, offset)) != 0) {
2900 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2909 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2911 void mark_page_dirty_in_slot(struct kvm *kvm,
2912 struct kvm_memory_slot *memslot,
2915 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
2916 unsigned long rel_gfn = gfn - memslot->base_gfn;
2917 u32 slot = (memslot->as_id << 16) | memslot->id;
2919 if (kvm->dirty_ring_size)
2920 kvm_dirty_ring_push(kvm_dirty_ring_get(kvm),
2923 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2926 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
2928 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2930 struct kvm_memory_slot *memslot;
2932 memslot = gfn_to_memslot(kvm, gfn);
2933 mark_page_dirty_in_slot(kvm, memslot, gfn);
2935 EXPORT_SYMBOL_GPL(mark_page_dirty);
2937 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2939 struct kvm_memory_slot *memslot;
2941 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2942 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
2944 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2946 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2948 if (!vcpu->sigset_active)
2952 * This does a lockless modification of ->real_blocked, which is fine
2953 * because, only current can change ->real_blocked and all readers of
2954 * ->real_blocked don't care as long ->real_blocked is always a subset
2957 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
2960 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2962 if (!vcpu->sigset_active)
2965 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
2966 sigemptyset(¤t->real_blocked);
2969 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2971 unsigned int old, val, grow, grow_start;
2973 old = val = vcpu->halt_poll_ns;
2974 grow_start = READ_ONCE(halt_poll_ns_grow_start);
2975 grow = READ_ONCE(halt_poll_ns_grow);
2980 if (val < grow_start)
2983 if (val > vcpu->kvm->max_halt_poll_ns)
2984 val = vcpu->kvm->max_halt_poll_ns;
2986 vcpu->halt_poll_ns = val;
2988 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2991 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2993 unsigned int old, val, shrink;
2995 old = val = vcpu->halt_poll_ns;
2996 shrink = READ_ONCE(halt_poll_ns_shrink);
3002 vcpu->halt_poll_ns = val;
3003 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3006 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3009 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3011 if (kvm_arch_vcpu_runnable(vcpu)) {
3012 kvm_make_request(KVM_REQ_UNHALT, vcpu);
3015 if (kvm_cpu_has_pending_timer(vcpu))
3017 if (signal_pending(current))
3019 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3024 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3029 update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
3032 vcpu->stat.generic.halt_poll_fail_ns += poll_ns;
3034 vcpu->stat.generic.halt_poll_success_ns += poll_ns;
3038 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
3040 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
3042 ktime_t start, cur, poll_end;
3043 bool waited = false;
3046 kvm_arch_vcpu_blocking(vcpu);
3048 start = cur = poll_end = ktime_get();
3049 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
3050 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
3052 ++vcpu->stat.generic.halt_attempted_poll;
3055 * This sets KVM_REQ_UNHALT if an interrupt
3058 if (kvm_vcpu_check_block(vcpu) < 0) {
3059 ++vcpu->stat.generic.halt_successful_poll;
3060 if (!vcpu_valid_wakeup(vcpu))
3061 ++vcpu->stat.generic.halt_poll_invalid;
3064 poll_end = cur = ktime_get();
3065 } while (kvm_vcpu_can_poll(cur, stop));
3068 prepare_to_rcuwait(&vcpu->wait);
3070 set_current_state(TASK_INTERRUPTIBLE);
3072 if (kvm_vcpu_check_block(vcpu) < 0)
3078 finish_rcuwait(&vcpu->wait);
3081 kvm_arch_vcpu_unblocking(vcpu);
3082 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3084 update_halt_poll_stats(
3085 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
3087 if (!kvm_arch_no_poll(vcpu)) {
3088 if (!vcpu_valid_wakeup(vcpu)) {
3089 shrink_halt_poll_ns(vcpu);
3090 } else if (vcpu->kvm->max_halt_poll_ns) {
3091 if (block_ns <= vcpu->halt_poll_ns)
3093 /* we had a long block, shrink polling */
3094 else if (vcpu->halt_poll_ns &&
3095 block_ns > vcpu->kvm->max_halt_poll_ns)
3096 shrink_halt_poll_ns(vcpu);
3097 /* we had a short halt and our poll time is too small */
3098 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3099 block_ns < vcpu->kvm->max_halt_poll_ns)
3100 grow_halt_poll_ns(vcpu);
3102 vcpu->halt_poll_ns = 0;
3106 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
3107 kvm_arch_vcpu_block_finish(vcpu);
3109 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
3111 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3113 struct rcuwait *waitp;
3115 waitp = kvm_arch_vcpu_get_wait(vcpu);
3116 if (rcuwait_wake_up(waitp)) {
3117 WRITE_ONCE(vcpu->ready, true);
3118 ++vcpu->stat.generic.halt_wakeup;
3124 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3128 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3130 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3133 int cpu = vcpu->cpu;
3135 if (kvm_vcpu_wake_up(vcpu))
3139 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3140 if (kvm_arch_vcpu_should_kick(vcpu))
3141 smp_send_reschedule(cpu);
3144 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3145 #endif /* !CONFIG_S390 */
3147 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3150 struct task_struct *task = NULL;
3154 pid = rcu_dereference(target->pid);
3156 task = get_pid_task(pid, PIDTYPE_PID);
3160 ret = yield_to(task, 1);
3161 put_task_struct(task);
3165 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3168 * Helper that checks whether a VCPU is eligible for directed yield.
3169 * Most eligible candidate to yield is decided by following heuristics:
3171 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3172 * (preempted lock holder), indicated by @in_spin_loop.
3173 * Set at the beginning and cleared at the end of interception/PLE handler.
3175 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3176 * chance last time (mostly it has become eligible now since we have probably
3177 * yielded to lockholder in last iteration. This is done by toggling
3178 * @dy_eligible each time a VCPU checked for eligibility.)
3180 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3181 * to preempted lock-holder could result in wrong VCPU selection and CPU
3182 * burning. Giving priority for a potential lock-holder increases lock
3185 * Since algorithm is based on heuristics, accessing another VCPU data without
3186 * locking does not harm. It may result in trying to yield to same VCPU, fail
3187 * and continue with next VCPU and so on.
3189 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3191 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3194 eligible = !vcpu->spin_loop.in_spin_loop ||
3195 vcpu->spin_loop.dy_eligible;
3197 if (vcpu->spin_loop.in_spin_loop)
3198 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3207 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3208 * a vcpu_load/vcpu_put pair. However, for most architectures
3209 * kvm_arch_vcpu_runnable does not require vcpu_load.
3211 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3213 return kvm_arch_vcpu_runnable(vcpu);
3216 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3218 if (kvm_arch_dy_runnable(vcpu))
3221 #ifdef CONFIG_KVM_ASYNC_PF
3222 if (!list_empty_careful(&vcpu->async_pf.done))
3229 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3234 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3236 struct kvm *kvm = me->kvm;
3237 struct kvm_vcpu *vcpu;
3238 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3244 kvm_vcpu_set_in_spin_loop(me, true);
3246 * We boost the priority of a VCPU that is runnable but not
3247 * currently running, because it got preempted by something
3248 * else and called schedule in __vcpu_run. Hopefully that
3249 * VCPU is holding the lock that we need and will release it.
3250 * We approximate round-robin by starting at the last boosted VCPU.
3252 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3253 kvm_for_each_vcpu(i, vcpu, kvm) {
3254 if (!pass && i <= last_boosted_vcpu) {
3255 i = last_boosted_vcpu;
3257 } else if (pass && i > last_boosted_vcpu)
3259 if (!READ_ONCE(vcpu->ready))
3263 if (rcuwait_active(&vcpu->wait) &&
3264 !vcpu_dy_runnable(vcpu))
3266 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3267 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3268 !kvm_arch_vcpu_in_kernel(vcpu))
3270 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3273 yielded = kvm_vcpu_yield_to(vcpu);
3275 kvm->last_boosted_vcpu = i;
3277 } else if (yielded < 0) {
3284 kvm_vcpu_set_in_spin_loop(me, false);
3286 /* Ensure vcpu is not eligible during next spinloop */
3287 kvm_vcpu_set_dy_eligible(me, false);
3289 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3291 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3293 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3294 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3295 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3296 kvm->dirty_ring_size / PAGE_SIZE);
3302 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3304 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3307 if (vmf->pgoff == 0)
3308 page = virt_to_page(vcpu->run);
3310 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3311 page = virt_to_page(vcpu->arch.pio_data);
3313 #ifdef CONFIG_KVM_MMIO
3314 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3315 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3317 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3318 page = kvm_dirty_ring_get_page(
3320 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3322 return kvm_arch_vcpu_fault(vcpu, vmf);
3328 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3329 .fault = kvm_vcpu_fault,
3332 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3334 struct kvm_vcpu *vcpu = file->private_data;
3335 unsigned long pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
3337 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3338 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3339 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3342 vma->vm_ops = &kvm_vcpu_vm_ops;
3346 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3348 struct kvm_vcpu *vcpu = filp->private_data;
3350 kvm_put_kvm(vcpu->kvm);
3354 static struct file_operations kvm_vcpu_fops = {
3355 .release = kvm_vcpu_release,
3356 .unlocked_ioctl = kvm_vcpu_ioctl,
3357 .mmap = kvm_vcpu_mmap,
3358 .llseek = noop_llseek,
3359 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3363 * Allocates an inode for the vcpu.
3365 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3367 char name[8 + 1 + ITOA_MAX_LEN + 1];
3369 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3370 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3373 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3375 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3376 struct dentry *debugfs_dentry;
3377 char dir_name[ITOA_MAX_LEN * 2];
3379 if (!debugfs_initialized())
3382 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3383 debugfs_dentry = debugfs_create_dir(dir_name,
3384 vcpu->kvm->debugfs_dentry);
3386 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3391 * Creates some virtual cpus. Good luck creating more than one.
3393 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3396 struct kvm_vcpu *vcpu;
3399 if (id >= KVM_MAX_VCPU_ID)
3402 mutex_lock(&kvm->lock);
3403 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3404 mutex_unlock(&kvm->lock);
3408 kvm->created_vcpus++;
3409 mutex_unlock(&kvm->lock);
3411 r = kvm_arch_vcpu_precreate(kvm, id);
3413 goto vcpu_decrement;
3415 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3418 goto vcpu_decrement;
3421 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3422 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3427 vcpu->run = page_address(page);
3429 kvm_vcpu_init(vcpu, kvm, id);
3431 r = kvm_arch_vcpu_create(vcpu);
3433 goto vcpu_free_run_page;
3435 if (kvm->dirty_ring_size) {
3436 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3437 id, kvm->dirty_ring_size);
3439 goto arch_vcpu_destroy;
3442 mutex_lock(&kvm->lock);
3443 if (kvm_get_vcpu_by_id(kvm, id)) {
3445 goto unlock_vcpu_destroy;
3448 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3449 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
3451 /* Fill the stats id string for the vcpu */
3452 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3453 task_pid_nr(current), id);
3455 /* Now it's all set up, let userspace reach it */
3457 r = create_vcpu_fd(vcpu);
3459 kvm_put_kvm_no_destroy(kvm);
3460 goto unlock_vcpu_destroy;
3463 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
3466 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3467 * before kvm->online_vcpu's incremented value.
3470 atomic_inc(&kvm->online_vcpus);
3472 mutex_unlock(&kvm->lock);
3473 kvm_arch_vcpu_postcreate(vcpu);
3474 kvm_create_vcpu_debugfs(vcpu);
3477 unlock_vcpu_destroy:
3478 mutex_unlock(&kvm->lock);
3479 kvm_dirty_ring_free(&vcpu->dirty_ring);
3481 kvm_arch_vcpu_destroy(vcpu);
3483 free_page((unsigned long)vcpu->run);
3485 kmem_cache_free(kvm_vcpu_cache, vcpu);
3487 mutex_lock(&kvm->lock);
3488 kvm->created_vcpus--;
3489 mutex_unlock(&kvm->lock);
3493 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3496 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3497 vcpu->sigset_active = 1;
3498 vcpu->sigset = *sigset;
3500 vcpu->sigset_active = 0;
3504 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3505 size_t size, loff_t *offset)
3507 struct kvm_vcpu *vcpu = file->private_data;
3509 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3510 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3511 sizeof(vcpu->stat), user_buffer, size, offset);
3514 static const struct file_operations kvm_vcpu_stats_fops = {
3515 .read = kvm_vcpu_stats_read,
3516 .llseek = noop_llseek,
3519 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3523 char name[15 + ITOA_MAX_LEN + 1];
3525 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3527 fd = get_unused_fd_flags(O_CLOEXEC);
3531 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3534 return PTR_ERR(file);
3536 file->f_mode |= FMODE_PREAD;
3537 fd_install(fd, file);
3542 static long kvm_vcpu_ioctl(struct file *filp,
3543 unsigned int ioctl, unsigned long arg)
3545 struct kvm_vcpu *vcpu = filp->private_data;
3546 void __user *argp = (void __user *)arg;
3548 struct kvm_fpu *fpu = NULL;
3549 struct kvm_sregs *kvm_sregs = NULL;
3551 if (vcpu->kvm->mm != current->mm)
3554 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3558 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3559 * execution; mutex_lock() would break them.
3561 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3562 if (r != -ENOIOCTLCMD)
3565 if (mutex_lock_killable(&vcpu->mutex))
3573 oldpid = rcu_access_pointer(vcpu->pid);
3574 if (unlikely(oldpid != task_pid(current))) {
3575 /* The thread running this VCPU changed. */
3578 r = kvm_arch_vcpu_run_pid_change(vcpu);
3582 newpid = get_task_pid(current, PIDTYPE_PID);
3583 rcu_assign_pointer(vcpu->pid, newpid);
3588 r = kvm_arch_vcpu_ioctl_run(vcpu);
3589 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3592 case KVM_GET_REGS: {
3593 struct kvm_regs *kvm_regs;
3596 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3599 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3603 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3610 case KVM_SET_REGS: {
3611 struct kvm_regs *kvm_regs;
3613 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3614 if (IS_ERR(kvm_regs)) {
3615 r = PTR_ERR(kvm_regs);
3618 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3622 case KVM_GET_SREGS: {
3623 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3624 GFP_KERNEL_ACCOUNT);
3628 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3632 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3637 case KVM_SET_SREGS: {
3638 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3639 if (IS_ERR(kvm_sregs)) {
3640 r = PTR_ERR(kvm_sregs);
3644 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3647 case KVM_GET_MP_STATE: {
3648 struct kvm_mp_state mp_state;
3650 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3654 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3659 case KVM_SET_MP_STATE: {
3660 struct kvm_mp_state mp_state;
3663 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3665 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3668 case KVM_TRANSLATE: {
3669 struct kvm_translation tr;
3672 if (copy_from_user(&tr, argp, sizeof(tr)))
3674 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3678 if (copy_to_user(argp, &tr, sizeof(tr)))
3683 case KVM_SET_GUEST_DEBUG: {
3684 struct kvm_guest_debug dbg;
3687 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3689 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3692 case KVM_SET_SIGNAL_MASK: {
3693 struct kvm_signal_mask __user *sigmask_arg = argp;
3694 struct kvm_signal_mask kvm_sigmask;
3695 sigset_t sigset, *p;
3700 if (copy_from_user(&kvm_sigmask, argp,
3701 sizeof(kvm_sigmask)))
3704 if (kvm_sigmask.len != sizeof(sigset))
3707 if (copy_from_user(&sigset, sigmask_arg->sigset,
3712 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3716 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
3720 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3724 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3730 fpu = memdup_user(argp, sizeof(*fpu));
3736 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3739 case KVM_GET_STATS_FD: {
3740 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
3744 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3747 mutex_unlock(&vcpu->mutex);
3753 #ifdef CONFIG_KVM_COMPAT
3754 static long kvm_vcpu_compat_ioctl(struct file *filp,
3755 unsigned int ioctl, unsigned long arg)
3757 struct kvm_vcpu *vcpu = filp->private_data;
3758 void __user *argp = compat_ptr(arg);
3761 if (vcpu->kvm->mm != current->mm)
3765 case KVM_SET_SIGNAL_MASK: {
3766 struct kvm_signal_mask __user *sigmask_arg = argp;
3767 struct kvm_signal_mask kvm_sigmask;
3772 if (copy_from_user(&kvm_sigmask, argp,
3773 sizeof(kvm_sigmask)))
3776 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3779 if (get_compat_sigset(&sigset,
3780 (compat_sigset_t __user *)sigmask_arg->sigset))
3782 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3784 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3788 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3796 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3798 struct kvm_device *dev = filp->private_data;
3801 return dev->ops->mmap(dev, vma);
3806 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3807 int (*accessor)(struct kvm_device *dev,
3808 struct kvm_device_attr *attr),
3811 struct kvm_device_attr attr;
3816 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3819 return accessor(dev, &attr);
3822 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3825 struct kvm_device *dev = filp->private_data;
3827 if (dev->kvm->mm != current->mm)
3831 case KVM_SET_DEVICE_ATTR:
3832 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3833 case KVM_GET_DEVICE_ATTR:
3834 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3835 case KVM_HAS_DEVICE_ATTR:
3836 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3838 if (dev->ops->ioctl)
3839 return dev->ops->ioctl(dev, ioctl, arg);
3845 static int kvm_device_release(struct inode *inode, struct file *filp)
3847 struct kvm_device *dev = filp->private_data;
3848 struct kvm *kvm = dev->kvm;
3850 if (dev->ops->release) {
3851 mutex_lock(&kvm->lock);
3852 list_del(&dev->vm_node);
3853 dev->ops->release(dev);
3854 mutex_unlock(&kvm->lock);
3861 static const struct file_operations kvm_device_fops = {
3862 .unlocked_ioctl = kvm_device_ioctl,
3863 .release = kvm_device_release,
3864 KVM_COMPAT(kvm_device_ioctl),
3865 .mmap = kvm_device_mmap,
3868 struct kvm_device *kvm_device_from_filp(struct file *filp)
3870 if (filp->f_op != &kvm_device_fops)
3873 return filp->private_data;
3876 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
3877 #ifdef CONFIG_KVM_MPIC
3878 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3879 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3883 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
3885 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3888 if (kvm_device_ops_table[type] != NULL)
3891 kvm_device_ops_table[type] = ops;
3895 void kvm_unregister_device_ops(u32 type)
3897 if (kvm_device_ops_table[type] != NULL)
3898 kvm_device_ops_table[type] = NULL;
3901 static int kvm_ioctl_create_device(struct kvm *kvm,
3902 struct kvm_create_device *cd)
3904 const struct kvm_device_ops *ops = NULL;
3905 struct kvm_device *dev;
3906 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
3910 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3913 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3914 ops = kvm_device_ops_table[type];
3921 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
3928 mutex_lock(&kvm->lock);
3929 ret = ops->create(dev, type);
3931 mutex_unlock(&kvm->lock);
3935 list_add(&dev->vm_node, &kvm->devices);
3936 mutex_unlock(&kvm->lock);
3942 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3944 kvm_put_kvm_no_destroy(kvm);
3945 mutex_lock(&kvm->lock);
3946 list_del(&dev->vm_node);
3947 mutex_unlock(&kvm->lock);
3956 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3959 case KVM_CAP_USER_MEMORY:
3960 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3961 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3962 case KVM_CAP_INTERNAL_ERROR_DATA:
3963 #ifdef CONFIG_HAVE_KVM_MSI
3964 case KVM_CAP_SIGNAL_MSI:
3966 #ifdef CONFIG_HAVE_KVM_IRQFD
3968 case KVM_CAP_IRQFD_RESAMPLE:
3970 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3971 case KVM_CAP_CHECK_EXTENSION_VM:
3972 case KVM_CAP_ENABLE_CAP_VM:
3973 case KVM_CAP_HALT_POLL:
3975 #ifdef CONFIG_KVM_MMIO
3976 case KVM_CAP_COALESCED_MMIO:
3977 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3978 case KVM_CAP_COALESCED_PIO:
3981 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3982 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3983 return KVM_DIRTY_LOG_MANUAL_CAPS;
3985 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3986 case KVM_CAP_IRQ_ROUTING:
3987 return KVM_MAX_IRQ_ROUTES;
3989 #if KVM_ADDRESS_SPACE_NUM > 1
3990 case KVM_CAP_MULTI_ADDRESS_SPACE:
3991 return KVM_ADDRESS_SPACE_NUM;
3993 case KVM_CAP_NR_MEMSLOTS:
3994 return KVM_USER_MEM_SLOTS;
3995 case KVM_CAP_DIRTY_LOG_RING:
3996 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3997 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4001 case KVM_CAP_BINARY_STATS_FD:
4006 return kvm_vm_ioctl_check_extension(kvm, arg);
4009 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4013 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4016 /* the size should be power of 2 */
4017 if (!size || (size & (size - 1)))
4020 /* Should be bigger to keep the reserved entries, or a page */
4021 if (size < kvm_dirty_ring_get_rsvd_entries() *
4022 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4025 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4026 sizeof(struct kvm_dirty_gfn))
4029 /* We only allow it to set once */
4030 if (kvm->dirty_ring_size)
4033 mutex_lock(&kvm->lock);
4035 if (kvm->created_vcpus) {
4036 /* We don't allow to change this value after vcpu created */
4039 kvm->dirty_ring_size = size;
4043 mutex_unlock(&kvm->lock);
4047 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4050 struct kvm_vcpu *vcpu;
4053 if (!kvm->dirty_ring_size)
4056 mutex_lock(&kvm->slots_lock);
4058 kvm_for_each_vcpu(i, vcpu, kvm)
4059 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4061 mutex_unlock(&kvm->slots_lock);
4064 kvm_flush_remote_tlbs(kvm);
4069 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4070 struct kvm_enable_cap *cap)
4075 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4076 struct kvm_enable_cap *cap)
4079 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4080 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4081 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4083 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4084 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4086 if (cap->flags || (cap->args[0] & ~allowed_options))
4088 kvm->manual_dirty_log_protect = cap->args[0];
4092 case KVM_CAP_HALT_POLL: {
4093 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4096 kvm->max_halt_poll_ns = cap->args[0];
4099 case KVM_CAP_DIRTY_LOG_RING:
4100 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4102 return kvm_vm_ioctl_enable_cap(kvm, cap);
4106 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4107 size_t size, loff_t *offset)
4109 struct kvm *kvm = file->private_data;
4111 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4112 &kvm_vm_stats_desc[0], &kvm->stat,
4113 sizeof(kvm->stat), user_buffer, size, offset);
4116 static const struct file_operations kvm_vm_stats_fops = {
4117 .read = kvm_vm_stats_read,
4118 .llseek = noop_llseek,
4121 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4126 fd = get_unused_fd_flags(O_CLOEXEC);
4130 file = anon_inode_getfile("kvm-vm-stats",
4131 &kvm_vm_stats_fops, kvm, O_RDONLY);
4134 return PTR_ERR(file);
4136 file->f_mode |= FMODE_PREAD;
4137 fd_install(fd, file);
4142 static long kvm_vm_ioctl(struct file *filp,
4143 unsigned int ioctl, unsigned long arg)
4145 struct kvm *kvm = filp->private_data;
4146 void __user *argp = (void __user *)arg;
4149 if (kvm->mm != current->mm)
4152 case KVM_CREATE_VCPU:
4153 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4155 case KVM_ENABLE_CAP: {
4156 struct kvm_enable_cap cap;
4159 if (copy_from_user(&cap, argp, sizeof(cap)))
4161 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4164 case KVM_SET_USER_MEMORY_REGION: {
4165 struct kvm_userspace_memory_region kvm_userspace_mem;
4168 if (copy_from_user(&kvm_userspace_mem, argp,
4169 sizeof(kvm_userspace_mem)))
4172 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4175 case KVM_GET_DIRTY_LOG: {
4176 struct kvm_dirty_log log;
4179 if (copy_from_user(&log, argp, sizeof(log)))
4181 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4184 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4185 case KVM_CLEAR_DIRTY_LOG: {
4186 struct kvm_clear_dirty_log log;
4189 if (copy_from_user(&log, argp, sizeof(log)))
4191 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4195 #ifdef CONFIG_KVM_MMIO
4196 case KVM_REGISTER_COALESCED_MMIO: {
4197 struct kvm_coalesced_mmio_zone zone;
4200 if (copy_from_user(&zone, argp, sizeof(zone)))
4202 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4205 case KVM_UNREGISTER_COALESCED_MMIO: {
4206 struct kvm_coalesced_mmio_zone zone;
4209 if (copy_from_user(&zone, argp, sizeof(zone)))
4211 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4216 struct kvm_irqfd data;
4219 if (copy_from_user(&data, argp, sizeof(data)))
4221 r = kvm_irqfd(kvm, &data);
4224 case KVM_IOEVENTFD: {
4225 struct kvm_ioeventfd data;
4228 if (copy_from_user(&data, argp, sizeof(data)))
4230 r = kvm_ioeventfd(kvm, &data);
4233 #ifdef CONFIG_HAVE_KVM_MSI
4234 case KVM_SIGNAL_MSI: {
4238 if (copy_from_user(&msi, argp, sizeof(msi)))
4240 r = kvm_send_userspace_msi(kvm, &msi);
4244 #ifdef __KVM_HAVE_IRQ_LINE
4245 case KVM_IRQ_LINE_STATUS:
4246 case KVM_IRQ_LINE: {
4247 struct kvm_irq_level irq_event;
4250 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4253 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4254 ioctl == KVM_IRQ_LINE_STATUS);
4259 if (ioctl == KVM_IRQ_LINE_STATUS) {
4260 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4268 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4269 case KVM_SET_GSI_ROUTING: {
4270 struct kvm_irq_routing routing;
4271 struct kvm_irq_routing __user *urouting;
4272 struct kvm_irq_routing_entry *entries = NULL;
4275 if (copy_from_user(&routing, argp, sizeof(routing)))
4278 if (!kvm_arch_can_set_irq_routing(kvm))
4280 if (routing.nr > KVM_MAX_IRQ_ROUTES)
4286 entries = vmemdup_user(urouting->entries,
4287 array_size(sizeof(*entries),
4289 if (IS_ERR(entries)) {
4290 r = PTR_ERR(entries);
4294 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4299 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4300 case KVM_CREATE_DEVICE: {
4301 struct kvm_create_device cd;
4304 if (copy_from_user(&cd, argp, sizeof(cd)))
4307 r = kvm_ioctl_create_device(kvm, &cd);
4312 if (copy_to_user(argp, &cd, sizeof(cd)))
4318 case KVM_CHECK_EXTENSION:
4319 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4321 case KVM_RESET_DIRTY_RINGS:
4322 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4324 case KVM_GET_STATS_FD:
4325 r = kvm_vm_ioctl_get_stats_fd(kvm);
4328 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4334 #ifdef CONFIG_KVM_COMPAT
4335 struct compat_kvm_dirty_log {
4339 compat_uptr_t dirty_bitmap; /* one bit per page */
4344 static long kvm_vm_compat_ioctl(struct file *filp,
4345 unsigned int ioctl, unsigned long arg)
4347 struct kvm *kvm = filp->private_data;
4350 if (kvm->mm != current->mm)
4353 case KVM_GET_DIRTY_LOG: {
4354 struct compat_kvm_dirty_log compat_log;
4355 struct kvm_dirty_log log;
4357 if (copy_from_user(&compat_log, (void __user *)arg,
4358 sizeof(compat_log)))
4360 log.slot = compat_log.slot;
4361 log.padding1 = compat_log.padding1;
4362 log.padding2 = compat_log.padding2;
4363 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4365 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4369 r = kvm_vm_ioctl(filp, ioctl, arg);
4375 static struct file_operations kvm_vm_fops = {
4376 .release = kvm_vm_release,
4377 .unlocked_ioctl = kvm_vm_ioctl,
4378 .llseek = noop_llseek,
4379 KVM_COMPAT(kvm_vm_compat_ioctl),
4382 bool file_is_kvm(struct file *file)
4384 return file && file->f_op == &kvm_vm_fops;
4386 EXPORT_SYMBOL_GPL(file_is_kvm);
4388 static int kvm_dev_ioctl_create_vm(unsigned long type)
4394 kvm = kvm_create_vm(type);
4396 return PTR_ERR(kvm);
4397 #ifdef CONFIG_KVM_MMIO
4398 r = kvm_coalesced_mmio_init(kvm);
4402 r = get_unused_fd_flags(O_CLOEXEC);
4406 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4407 "kvm-%d", task_pid_nr(current));
4409 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4417 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4418 * already set, with ->release() being kvm_vm_release(). In error
4419 * cases it will be called by the final fput(file) and will take
4420 * care of doing kvm_put_kvm(kvm).
4422 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4427 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4429 fd_install(r, file);
4437 static long kvm_dev_ioctl(struct file *filp,
4438 unsigned int ioctl, unsigned long arg)
4443 case KVM_GET_API_VERSION:
4446 r = KVM_API_VERSION;
4449 r = kvm_dev_ioctl_create_vm(arg);
4451 case KVM_CHECK_EXTENSION:
4452 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4454 case KVM_GET_VCPU_MMAP_SIZE:
4457 r = PAGE_SIZE; /* struct kvm_run */
4459 r += PAGE_SIZE; /* pio data page */
4461 #ifdef CONFIG_KVM_MMIO
4462 r += PAGE_SIZE; /* coalesced mmio ring page */
4465 case KVM_TRACE_ENABLE:
4466 case KVM_TRACE_PAUSE:
4467 case KVM_TRACE_DISABLE:
4471 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4477 static struct file_operations kvm_chardev_ops = {
4478 .unlocked_ioctl = kvm_dev_ioctl,
4479 .llseek = noop_llseek,
4480 KVM_COMPAT(kvm_dev_ioctl),
4483 static struct miscdevice kvm_dev = {
4489 static void hardware_enable_nolock(void *junk)
4491 int cpu = raw_smp_processor_id();
4494 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4497 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4499 r = kvm_arch_hardware_enable();
4502 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4503 atomic_inc(&hardware_enable_failed);
4504 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4508 static int kvm_starting_cpu(unsigned int cpu)
4510 raw_spin_lock(&kvm_count_lock);
4511 if (kvm_usage_count)
4512 hardware_enable_nolock(NULL);
4513 raw_spin_unlock(&kvm_count_lock);
4517 static void hardware_disable_nolock(void *junk)
4519 int cpu = raw_smp_processor_id();
4521 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4523 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4524 kvm_arch_hardware_disable();
4527 static int kvm_dying_cpu(unsigned int cpu)
4529 raw_spin_lock(&kvm_count_lock);
4530 if (kvm_usage_count)
4531 hardware_disable_nolock(NULL);
4532 raw_spin_unlock(&kvm_count_lock);
4536 static void hardware_disable_all_nolock(void)
4538 BUG_ON(!kvm_usage_count);
4541 if (!kvm_usage_count)
4542 on_each_cpu(hardware_disable_nolock, NULL, 1);
4545 static void hardware_disable_all(void)
4547 raw_spin_lock(&kvm_count_lock);
4548 hardware_disable_all_nolock();
4549 raw_spin_unlock(&kvm_count_lock);
4552 static int hardware_enable_all(void)
4556 raw_spin_lock(&kvm_count_lock);
4559 if (kvm_usage_count == 1) {
4560 atomic_set(&hardware_enable_failed, 0);
4561 on_each_cpu(hardware_enable_nolock, NULL, 1);
4563 if (atomic_read(&hardware_enable_failed)) {
4564 hardware_disable_all_nolock();
4569 raw_spin_unlock(&kvm_count_lock);
4574 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4578 * Some (well, at least mine) BIOSes hang on reboot if
4581 * And Intel TXT required VMX off for all cpu when system shutdown.
4583 pr_info("kvm: exiting hardware virtualization\n");
4584 kvm_rebooting = true;
4585 on_each_cpu(hardware_disable_nolock, NULL, 1);
4589 static struct notifier_block kvm_reboot_notifier = {
4590 .notifier_call = kvm_reboot,
4594 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4598 for (i = 0; i < bus->dev_count; i++) {
4599 struct kvm_io_device *pos = bus->range[i].dev;
4601 kvm_iodevice_destructor(pos);
4606 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4607 const struct kvm_io_range *r2)
4609 gpa_t addr1 = r1->addr;
4610 gpa_t addr2 = r2->addr;
4615 /* If r2->len == 0, match the exact address. If r2->len != 0,
4616 * accept any overlapping write. Any order is acceptable for
4617 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4618 * we process all of them.
4631 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4633 return kvm_io_bus_cmp(p1, p2);
4636 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4637 gpa_t addr, int len)
4639 struct kvm_io_range *range, key;
4642 key = (struct kvm_io_range) {
4647 range = bsearch(&key, bus->range, bus->dev_count,
4648 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4652 off = range - bus->range;
4654 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4660 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4661 struct kvm_io_range *range, const void *val)
4665 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4669 while (idx < bus->dev_count &&
4670 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4671 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4680 /* kvm_io_bus_write - called under kvm->slots_lock */
4681 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4682 int len, const void *val)
4684 struct kvm_io_bus *bus;
4685 struct kvm_io_range range;
4688 range = (struct kvm_io_range) {
4693 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4696 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4697 return r < 0 ? r : 0;
4699 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
4701 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4702 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4703 gpa_t addr, int len, const void *val, long cookie)
4705 struct kvm_io_bus *bus;
4706 struct kvm_io_range range;
4708 range = (struct kvm_io_range) {
4713 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4717 /* First try the device referenced by cookie. */
4718 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4719 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4720 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4725 * cookie contained garbage; fall back to search and return the
4726 * correct cookie value.
4728 return __kvm_io_bus_write(vcpu, bus, &range, val);
4731 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4732 struct kvm_io_range *range, void *val)
4736 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4740 while (idx < bus->dev_count &&
4741 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4742 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4751 /* kvm_io_bus_read - called under kvm->slots_lock */
4752 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4755 struct kvm_io_bus *bus;
4756 struct kvm_io_range range;
4759 range = (struct kvm_io_range) {
4764 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4767 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4768 return r < 0 ? r : 0;
4771 /* Caller must hold slots_lock. */
4772 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4773 int len, struct kvm_io_device *dev)
4776 struct kvm_io_bus *new_bus, *bus;
4777 struct kvm_io_range range;
4779 bus = kvm_get_bus(kvm, bus_idx);
4783 /* exclude ioeventfd which is limited by maximum fd */
4784 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
4787 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
4788 GFP_KERNEL_ACCOUNT);
4792 range = (struct kvm_io_range) {
4798 for (i = 0; i < bus->dev_count; i++)
4799 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4802 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4803 new_bus->dev_count++;
4804 new_bus->range[i] = range;
4805 memcpy(new_bus->range + i + 1, bus->range + i,
4806 (bus->dev_count - i) * sizeof(struct kvm_io_range));
4807 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4808 synchronize_srcu_expedited(&kvm->srcu);
4814 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4815 struct kvm_io_device *dev)
4818 struct kvm_io_bus *new_bus, *bus;
4820 lockdep_assert_held(&kvm->slots_lock);
4822 bus = kvm_get_bus(kvm, bus_idx);
4826 for (i = 0; i < bus->dev_count; i++) {
4827 if (bus->range[i].dev == dev) {
4832 if (i == bus->dev_count)
4835 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
4836 GFP_KERNEL_ACCOUNT);
4838 memcpy(new_bus, bus, struct_size(bus, range, i));
4839 new_bus->dev_count--;
4840 memcpy(new_bus->range + i, bus->range + i + 1,
4841 flex_array_size(new_bus, range, new_bus->dev_count - i));
4844 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4845 synchronize_srcu_expedited(&kvm->srcu);
4847 /* Destroy the old bus _after_ installing the (null) bus. */
4849 pr_err("kvm: failed to shrink bus, removing it completely\n");
4850 for (j = 0; j < bus->dev_count; j++) {
4853 kvm_iodevice_destructor(bus->range[j].dev);
4858 return new_bus ? 0 : -ENOMEM;
4861 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4864 struct kvm_io_bus *bus;
4865 int dev_idx, srcu_idx;
4866 struct kvm_io_device *iodev = NULL;
4868 srcu_idx = srcu_read_lock(&kvm->srcu);
4870 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
4874 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4878 iodev = bus->range[dev_idx].dev;
4881 srcu_read_unlock(&kvm->srcu, srcu_idx);
4885 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4887 static int kvm_debugfs_open(struct inode *inode, struct file *file,
4888 int (*get)(void *, u64 *), int (*set)(void *, u64),
4891 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4894 /* The debugfs files are a reference to the kvm struct which
4895 * is still valid when kvm_destroy_vm is called.
4896 * To avoid the race between open and the removal of the debugfs
4897 * directory we test against the users count.
4899 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
4902 if (simple_attr_open(inode, file, get,
4903 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4906 kvm_put_kvm(stat_data->kvm);
4913 static int kvm_debugfs_release(struct inode *inode, struct file *file)
4915 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4918 simple_attr_release(inode, file);
4919 kvm_put_kvm(stat_data->kvm);
4924 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
4926 *val = *(u64 *)((void *)kvm + offset);
4931 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
4933 *(u64 *)((void *)kvm + offset) = 0;
4938 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
4941 struct kvm_vcpu *vcpu;
4945 kvm_for_each_vcpu(i, vcpu, kvm)
4946 *val += *(u64 *)((void *)vcpu + offset);
4951 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
4954 struct kvm_vcpu *vcpu;
4956 kvm_for_each_vcpu(i, vcpu, kvm)
4957 *(u64 *)((void *)vcpu + offset) = 0;
4962 static int kvm_stat_data_get(void *data, u64 *val)
4965 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4967 switch (stat_data->dbgfs_item->kind) {
4969 r = kvm_get_stat_per_vm(stat_data->kvm,
4970 stat_data->dbgfs_item->offset, val);
4973 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4974 stat_data->dbgfs_item->offset, val);
4981 static int kvm_stat_data_clear(void *data, u64 val)
4984 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4989 switch (stat_data->dbgfs_item->kind) {
4991 r = kvm_clear_stat_per_vm(stat_data->kvm,
4992 stat_data->dbgfs_item->offset);
4995 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4996 stat_data->dbgfs_item->offset);
5003 static int kvm_stat_data_open(struct inode *inode, struct file *file)
5005 __simple_attr_check_format("%llu\n", 0ull);
5006 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5007 kvm_stat_data_clear, "%llu\n");
5010 static const struct file_operations stat_fops_per_vm = {
5011 .owner = THIS_MODULE,
5012 .open = kvm_stat_data_open,
5013 .release = kvm_debugfs_release,
5014 .read = simple_attr_read,
5015 .write = simple_attr_write,
5016 .llseek = no_llseek,
5019 static int vm_stat_get(void *_offset, u64 *val)
5021 unsigned offset = (long)_offset;
5026 mutex_lock(&kvm_lock);
5027 list_for_each_entry(kvm, &vm_list, vm_list) {
5028 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
5031 mutex_unlock(&kvm_lock);
5035 static int vm_stat_clear(void *_offset, u64 val)
5037 unsigned offset = (long)_offset;
5043 mutex_lock(&kvm_lock);
5044 list_for_each_entry(kvm, &vm_list, vm_list) {
5045 kvm_clear_stat_per_vm(kvm, offset);
5047 mutex_unlock(&kvm_lock);
5052 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
5054 static int vcpu_stat_get(void *_offset, u64 *val)
5056 unsigned offset = (long)_offset;
5061 mutex_lock(&kvm_lock);
5062 list_for_each_entry(kvm, &vm_list, vm_list) {
5063 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
5066 mutex_unlock(&kvm_lock);
5070 static int vcpu_stat_clear(void *_offset, u64 val)
5072 unsigned offset = (long)_offset;
5078 mutex_lock(&kvm_lock);
5079 list_for_each_entry(kvm, &vm_list, vm_list) {
5080 kvm_clear_stat_per_vcpu(kvm, offset);
5082 mutex_unlock(&kvm_lock);
5087 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5090 static const struct file_operations *stat_fops[] = {
5091 [KVM_STAT_VCPU] = &vcpu_stat_fops,
5092 [KVM_STAT_VM] = &vm_stat_fops,
5095 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5097 struct kobj_uevent_env *env;
5098 unsigned long long created, active;
5100 if (!kvm_dev.this_device || !kvm)
5103 mutex_lock(&kvm_lock);
5104 if (type == KVM_EVENT_CREATE_VM) {
5105 kvm_createvm_count++;
5107 } else if (type == KVM_EVENT_DESTROY_VM) {
5110 created = kvm_createvm_count;
5111 active = kvm_active_vms;
5112 mutex_unlock(&kvm_lock);
5114 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
5118 add_uevent_var(env, "CREATED=%llu", created);
5119 add_uevent_var(env, "COUNT=%llu", active);
5121 if (type == KVM_EVENT_CREATE_VM) {
5122 add_uevent_var(env, "EVENT=create");
5123 kvm->userspace_pid = task_pid_nr(current);
5124 } else if (type == KVM_EVENT_DESTROY_VM) {
5125 add_uevent_var(env, "EVENT=destroy");
5127 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5129 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
5130 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5133 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5135 add_uevent_var(env, "STATS_PATH=%s", tmp);
5139 /* no need for checks, since we are adding at most only 5 keys */
5140 env->envp[env->envp_idx++] = NULL;
5141 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5145 static void kvm_init_debug(void)
5147 struct kvm_stats_debugfs_item *p;
5149 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5151 kvm_debugfs_num_entries = 0;
5152 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
5153 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
5154 kvm_debugfs_dir, (void *)(long)p->offset,
5155 stat_fops[p->kind]);
5159 static int kvm_suspend(void)
5161 if (kvm_usage_count)
5162 hardware_disable_nolock(NULL);
5166 static void kvm_resume(void)
5168 if (kvm_usage_count) {
5169 #ifdef CONFIG_LOCKDEP
5170 WARN_ON(lockdep_is_held(&kvm_count_lock));
5172 hardware_enable_nolock(NULL);
5176 static struct syscore_ops kvm_syscore_ops = {
5177 .suspend = kvm_suspend,
5178 .resume = kvm_resume,
5182 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5184 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5187 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5189 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5191 WRITE_ONCE(vcpu->preempted, false);
5192 WRITE_ONCE(vcpu->ready, false);
5194 __this_cpu_write(kvm_running_vcpu, vcpu);
5195 kvm_arch_sched_in(vcpu, cpu);
5196 kvm_arch_vcpu_load(vcpu, cpu);
5199 static void kvm_sched_out(struct preempt_notifier *pn,
5200 struct task_struct *next)
5202 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5204 if (current->state == TASK_RUNNING) {
5205 WRITE_ONCE(vcpu->preempted, true);
5206 WRITE_ONCE(vcpu->ready, true);
5208 kvm_arch_vcpu_put(vcpu);
5209 __this_cpu_write(kvm_running_vcpu, NULL);
5213 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5215 * We can disable preemption locally around accessing the per-CPU variable,
5216 * and use the resolved vcpu pointer after enabling preemption again,
5217 * because even if the current thread is migrated to another CPU, reading
5218 * the per-CPU value later will give us the same value as we update the
5219 * per-CPU variable in the preempt notifier handlers.
5221 struct kvm_vcpu *kvm_get_running_vcpu(void)
5223 struct kvm_vcpu *vcpu;
5226 vcpu = __this_cpu_read(kvm_running_vcpu);
5231 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5234 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5236 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5238 return &kvm_running_vcpu;
5241 struct kvm_cpu_compat_check {
5246 static void check_processor_compat(void *data)
5248 struct kvm_cpu_compat_check *c = data;
5250 *c->ret = kvm_arch_check_processor_compat(c->opaque);
5253 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5254 struct module *module)
5256 struct kvm_cpu_compat_check c;
5260 r = kvm_arch_init(opaque);
5265 * kvm_arch_init makes sure there's at most one caller
5266 * for architectures that support multiple implementations,
5267 * like intel and amd on x86.
5268 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5269 * conflicts in case kvm is already setup for another implementation.
5271 r = kvm_irqfd_init();
5275 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5280 r = kvm_arch_hardware_setup(opaque);
5286 for_each_online_cpu(cpu) {
5287 smp_call_function_single(cpu, check_processor_compat, &c, 1);
5292 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5293 kvm_starting_cpu, kvm_dying_cpu);
5296 register_reboot_notifier(&kvm_reboot_notifier);
5298 /* A kmem cache lets us meet the alignment requirements of fx_save. */
5300 vcpu_align = __alignof__(struct kvm_vcpu);
5302 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5304 offsetof(struct kvm_vcpu, arch),
5305 offsetofend(struct kvm_vcpu, stats_id)
5306 - offsetof(struct kvm_vcpu, arch),
5308 if (!kvm_vcpu_cache) {
5313 r = kvm_async_pf_init();
5317 kvm_chardev_ops.owner = module;
5318 kvm_vm_fops.owner = module;
5319 kvm_vcpu_fops.owner = module;
5321 r = misc_register(&kvm_dev);
5323 pr_err("kvm: misc device register failed\n");
5327 register_syscore_ops(&kvm_syscore_ops);
5329 kvm_preempt_ops.sched_in = kvm_sched_in;
5330 kvm_preempt_ops.sched_out = kvm_sched_out;
5334 r = kvm_vfio_ops_init();
5340 kvm_async_pf_deinit();
5342 kmem_cache_destroy(kvm_vcpu_cache);
5344 unregister_reboot_notifier(&kvm_reboot_notifier);
5345 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5347 kvm_arch_hardware_unsetup();
5349 free_cpumask_var(cpus_hardware_enabled);
5357 EXPORT_SYMBOL_GPL(kvm_init);
5361 debugfs_remove_recursive(kvm_debugfs_dir);
5362 misc_deregister(&kvm_dev);
5363 kmem_cache_destroy(kvm_vcpu_cache);
5364 kvm_async_pf_deinit();
5365 unregister_syscore_ops(&kvm_syscore_ops);
5366 unregister_reboot_notifier(&kvm_reboot_notifier);
5367 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5368 on_each_cpu(hardware_disable_nolock, NULL, 1);
5369 kvm_arch_hardware_unsetup();
5372 free_cpumask_var(cpus_hardware_enabled);
5373 kvm_vfio_ops_exit();
5375 EXPORT_SYMBOL_GPL(kvm_exit);
5377 struct kvm_vm_worker_thread_context {
5379 struct task_struct *parent;
5380 struct completion init_done;
5381 kvm_vm_thread_fn_t thread_fn;
5386 static int kvm_vm_worker_thread(void *context)
5389 * The init_context is allocated on the stack of the parent thread, so
5390 * we have to locally copy anything that is needed beyond initialization
5392 struct kvm_vm_worker_thread_context *init_context = context;
5393 struct kvm *kvm = init_context->kvm;
5394 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5395 uintptr_t data = init_context->data;
5398 err = kthread_park(current);
5399 /* kthread_park(current) is never supposed to return an error */
5404 err = cgroup_attach_task_all(init_context->parent, current);
5406 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5411 set_user_nice(current, task_nice(init_context->parent));
5414 init_context->err = err;
5415 complete(&init_context->init_done);
5416 init_context = NULL;
5421 /* Wait to be woken up by the spawner before proceeding. */
5424 if (!kthread_should_stop())
5425 err = thread_fn(kvm, data);
5430 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5431 uintptr_t data, const char *name,
5432 struct task_struct **thread_ptr)
5434 struct kvm_vm_worker_thread_context init_context = {};
5435 struct task_struct *thread;
5438 init_context.kvm = kvm;
5439 init_context.parent = current;
5440 init_context.thread_fn = thread_fn;
5441 init_context.data = data;
5442 init_completion(&init_context.init_done);
5444 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5445 "%s-%d", name, task_pid_nr(current));
5447 return PTR_ERR(thread);
5449 /* kthread_run is never supposed to return NULL */
5450 WARN_ON(thread == NULL);
5452 wait_for_completion(&init_context.init_done);
5454 if (!init_context.err)
5455 *thread_ptr = thread;
5457 return init_context.err;