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>
55 #include <asm/processor.h>
56 #include <asm/ioctl.h>
57 #include <linux/uaccess.h>
59 #include "coalesced_mmio.h"
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/kvm.h>
67 #include <linux/kvm_dirty_ring.h>
69 /* Worst case buffer size needed for holding an integer. */
70 #define ITOA_MAX_LEN 12
72 MODULE_AUTHOR("Qumranet");
73 MODULE_LICENSE("GPL");
75 /* Architectures should define their poll value according to the halt latency */
76 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
77 module_param(halt_poll_ns, uint, 0644);
78 EXPORT_SYMBOL_GPL(halt_poll_ns);
80 /* Default doubles per-vcpu halt_poll_ns. */
81 unsigned int halt_poll_ns_grow = 2;
82 module_param(halt_poll_ns_grow, uint, 0644);
83 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
85 /* The start value to grow halt_poll_ns from */
86 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
87 module_param(halt_poll_ns_grow_start, uint, 0644);
88 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
90 /* Default resets per-vcpu halt_poll_ns . */
91 unsigned int halt_poll_ns_shrink;
92 module_param(halt_poll_ns_shrink, uint, 0644);
93 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
98 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
101 DEFINE_MUTEX(kvm_lock);
102 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
105 static cpumask_var_t cpus_hardware_enabled;
106 static int kvm_usage_count;
107 static atomic_t hardware_enable_failed;
109 static struct kmem_cache *kvm_vcpu_cache;
111 static __read_mostly struct preempt_ops kvm_preempt_ops;
112 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
114 struct dentry *kvm_debugfs_dir;
115 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
117 static int kvm_debugfs_num_entries;
118 static const struct file_operations stat_fops_per_vm;
120 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
122 #ifdef CONFIG_KVM_COMPAT
123 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
125 #define KVM_COMPAT(c) .compat_ioctl = (c)
128 * For architectures that don't implement a compat infrastructure,
129 * adopt a double line of defense:
130 * - Prevent a compat task from opening /dev/kvm
131 * - If the open has been done by a 64bit task, and the KVM fd
132 * passed to a compat task, let the ioctls fail.
134 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
135 unsigned long arg) { return -EINVAL; }
137 static int kvm_no_compat_open(struct inode *inode, struct file *file)
139 return is_compat_task() ? -ENODEV : 0;
141 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
142 .open = kvm_no_compat_open
144 static int hardware_enable_all(void);
145 static void hardware_disable_all(void);
147 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
149 __visible bool kvm_rebooting;
150 EXPORT_SYMBOL_GPL(kvm_rebooting);
152 #define KVM_EVENT_CREATE_VM 0
153 #define KVM_EVENT_DESTROY_VM 1
154 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
155 static unsigned long long kvm_createvm_count;
156 static unsigned long long kvm_active_vms;
158 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
159 unsigned long start, unsigned long end)
163 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
166 * The metadata used by is_zone_device_page() to determine whether or
167 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
168 * the device has been pinned, e.g. by get_user_pages(). WARN if the
169 * page_count() is zero to help detect bad usage of this helper.
171 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
174 return is_zone_device_page(pfn_to_page(pfn));
177 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
180 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
181 * perspective they are "normal" pages, albeit with slightly different
185 return PageReserved(pfn_to_page(pfn)) &&
187 !kvm_is_zone_device_pfn(pfn);
192 bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
194 struct page *page = pfn_to_page(pfn);
196 if (!PageTransCompoundMap(page))
199 return is_transparent_hugepage(compound_head(page));
203 * Switches to specified vcpu, until a matching vcpu_put()
205 void vcpu_load(struct kvm_vcpu *vcpu)
209 __this_cpu_write(kvm_running_vcpu, vcpu);
210 preempt_notifier_register(&vcpu->preempt_notifier);
211 kvm_arch_vcpu_load(vcpu, cpu);
214 EXPORT_SYMBOL_GPL(vcpu_load);
216 void vcpu_put(struct kvm_vcpu *vcpu)
219 kvm_arch_vcpu_put(vcpu);
220 preempt_notifier_unregister(&vcpu->preempt_notifier);
221 __this_cpu_write(kvm_running_vcpu, NULL);
224 EXPORT_SYMBOL_GPL(vcpu_put);
226 /* TODO: merge with kvm_arch_vcpu_should_kick */
227 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
229 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
232 * We need to wait for the VCPU to reenable interrupts and get out of
233 * READING_SHADOW_PAGE_TABLES mode.
235 if (req & KVM_REQUEST_WAIT)
236 return mode != OUTSIDE_GUEST_MODE;
239 * Need to kick a running VCPU, but otherwise there is nothing to do.
241 return mode == IN_GUEST_MODE;
244 static void ack_flush(void *_completed)
248 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
251 cpus = cpu_online_mask;
253 if (cpumask_empty(cpus))
256 smp_call_function_many(cpus, ack_flush, NULL, wait);
260 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
261 struct kvm_vcpu *except,
262 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
265 struct kvm_vcpu *vcpu;
270 kvm_for_each_vcpu(i, vcpu, kvm) {
271 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
275 kvm_make_request(req, vcpu);
278 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
281 if (tmp != NULL && cpu != -1 && cpu != me &&
282 kvm_request_needs_ipi(vcpu, req))
283 __cpumask_set_cpu(cpu, tmp);
286 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
292 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
293 struct kvm_vcpu *except)
298 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
300 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
302 free_cpumask_var(cpus);
306 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
308 return kvm_make_all_cpus_request_except(kvm, req, NULL);
310 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
312 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
313 void kvm_flush_remote_tlbs(struct kvm *kvm)
316 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
317 * kvm_make_all_cpus_request.
319 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
322 * We want to publish modifications to the page tables before reading
323 * mode. Pairs with a memory barrier in arch-specific code.
324 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
325 * and smp_mb in walk_shadow_page_lockless_begin/end.
326 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
328 * There is already an smp_mb__after_atomic() before
329 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
332 if (!kvm_arch_flush_remote_tlb(kvm)
333 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
334 ++kvm->stat.remote_tlb_flush;
335 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
337 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
340 void kvm_reload_remote_mmus(struct kvm *kvm)
342 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
345 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
346 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
349 gfp_flags |= mc->gfp_zero;
352 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
354 return (void *)__get_free_page(gfp_flags);
357 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
361 if (mc->nobjs >= min)
363 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
364 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
366 return mc->nobjs >= min ? 0 : -ENOMEM;
367 mc->objects[mc->nobjs++] = obj;
372 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
377 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
381 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
383 free_page((unsigned long)mc->objects[--mc->nobjs]);
387 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
391 if (WARN_ON(!mc->nobjs))
392 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
394 p = mc->objects[--mc->nobjs];
400 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
402 mutex_init(&vcpu->mutex);
407 rcuwait_init(&vcpu->wait);
408 kvm_async_pf_vcpu_init(vcpu);
411 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
413 kvm_vcpu_set_in_spin_loop(vcpu, false);
414 kvm_vcpu_set_dy_eligible(vcpu, false);
415 vcpu->preempted = false;
417 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
420 void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
422 kvm_dirty_ring_free(&vcpu->dirty_ring);
423 kvm_arch_vcpu_destroy(vcpu);
426 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
427 * the vcpu->pid pointer, and at destruction time all file descriptors
430 put_pid(rcu_dereference_protected(vcpu->pid, 1));
432 free_page((unsigned long)vcpu->run);
433 kmem_cache_free(kvm_vcpu_cache, vcpu);
435 EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
437 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
438 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
440 return container_of(mn, struct kvm, mmu_notifier);
443 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
444 struct mm_struct *mm,
445 unsigned long start, unsigned long end)
447 struct kvm *kvm = mmu_notifier_to_kvm(mn);
450 idx = srcu_read_lock(&kvm->srcu);
451 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
452 srcu_read_unlock(&kvm->srcu, idx);
455 typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
457 typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
460 struct kvm_hva_range {
464 hva_handler_t handler;
465 on_lock_fn_t on_lock;
471 * Use a dedicated stub instead of NULL to indicate that there is no callback
472 * function/handler. The compiler technically can't guarantee that a real
473 * function will have a non-zero address, and so it will generate code to
474 * check for !NULL, whereas comparing against a stub will be elided at compile
475 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
477 static void kvm_null_fn(void)
481 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
483 static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
484 const struct kvm_hva_range *range)
486 bool ret = false, locked = false;
487 struct kvm_gfn_range gfn_range;
488 struct kvm_memory_slot *slot;
489 struct kvm_memslots *slots;
492 /* A null handler is allowed if and only if on_lock() is provided. */
493 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
494 IS_KVM_NULL_FN(range->handler)))
497 idx = srcu_read_lock(&kvm->srcu);
499 /* The on_lock() path does not yet support lock elision. */
500 if (!IS_KVM_NULL_FN(range->on_lock)) {
504 range->on_lock(kvm, range->start, range->end);
506 if (IS_KVM_NULL_FN(range->handler))
510 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
511 slots = __kvm_memslots(kvm, i);
512 kvm_for_each_memslot(slot, slots) {
513 unsigned long hva_start, hva_end;
515 hva_start = max(range->start, slot->userspace_addr);
516 hva_end = min(range->end, slot->userspace_addr +
517 (slot->npages << PAGE_SHIFT));
518 if (hva_start >= hva_end)
522 * To optimize for the likely case where the address
523 * range is covered by zero or one memslots, don't
524 * bother making these conditional (to avoid writes on
525 * the second or later invocation of the handler).
527 gfn_range.pte = range->pte;
528 gfn_range.may_block = range->may_block;
531 * {gfn(page) | page intersects with [hva_start, hva_end)} =
532 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
534 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
535 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
536 gfn_range.slot = slot;
542 ret |= range->handler(kvm, &gfn_range);
546 if (range->flush_on_ret && (ret || kvm->tlbs_dirty))
547 kvm_flush_remote_tlbs(kvm);
553 srcu_read_unlock(&kvm->srcu, idx);
555 /* The notifiers are averse to booleans. :-( */
559 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
563 hva_handler_t handler)
565 struct kvm *kvm = mmu_notifier_to_kvm(mn);
566 const struct kvm_hva_range range = {
571 .on_lock = (void *)kvm_null_fn,
572 .flush_on_ret = true,
576 return __kvm_handle_hva_range(kvm, &range);
579 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
582 hva_handler_t handler)
584 struct kvm *kvm = mmu_notifier_to_kvm(mn);
585 const struct kvm_hva_range range = {
590 .on_lock = (void *)kvm_null_fn,
591 .flush_on_ret = false,
595 return __kvm_handle_hva_range(kvm, &range);
597 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
598 struct mm_struct *mm,
599 unsigned long address,
602 struct kvm *kvm = mmu_notifier_to_kvm(mn);
604 trace_kvm_set_spte_hva(address);
607 * .change_pte() must be surrounded by .invalidate_range_{start,end}(),
608 * and so always runs with an elevated notifier count. This obviates
609 * the need to bump the sequence count.
611 WARN_ON_ONCE(!kvm->mmu_notifier_count);
613 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
616 static void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
620 * The count increase must become visible at unlock time as no
621 * spte can be established without taking the mmu_lock and
622 * count is also read inside the mmu_lock critical section.
624 kvm->mmu_notifier_count++;
625 if (likely(kvm->mmu_notifier_count == 1)) {
626 kvm->mmu_notifier_range_start = start;
627 kvm->mmu_notifier_range_end = end;
630 * Fully tracking multiple concurrent ranges has dimishing
631 * returns. Keep things simple and just find the minimal range
632 * which includes the current and new ranges. As there won't be
633 * enough information to subtract a range after its invalidate
634 * completes, any ranges invalidated concurrently will
635 * accumulate and persist until all outstanding invalidates
638 kvm->mmu_notifier_range_start =
639 min(kvm->mmu_notifier_range_start, start);
640 kvm->mmu_notifier_range_end =
641 max(kvm->mmu_notifier_range_end, end);
645 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
646 const struct mmu_notifier_range *range)
648 struct kvm *kvm = mmu_notifier_to_kvm(mn);
649 const struct kvm_hva_range hva_range = {
650 .start = range->start,
653 .handler = kvm_unmap_gfn_range,
654 .on_lock = kvm_inc_notifier_count,
655 .flush_on_ret = true,
656 .may_block = mmu_notifier_range_blockable(range),
659 trace_kvm_unmap_hva_range(range->start, range->end);
661 __kvm_handle_hva_range(kvm, &hva_range);
666 static void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
670 * This sequence increase will notify the kvm page fault that
671 * the page that is going to be mapped in the spte could have
674 kvm->mmu_notifier_seq++;
677 * The above sequence increase must be visible before the
678 * below count decrease, which is ensured by the smp_wmb above
679 * in conjunction with the smp_rmb in mmu_notifier_retry().
681 kvm->mmu_notifier_count--;
684 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
685 const struct mmu_notifier_range *range)
687 struct kvm *kvm = mmu_notifier_to_kvm(mn);
688 const struct kvm_hva_range hva_range = {
689 .start = range->start,
692 .handler = (void *)kvm_null_fn,
693 .on_lock = kvm_dec_notifier_count,
694 .flush_on_ret = false,
695 .may_block = mmu_notifier_range_blockable(range),
698 __kvm_handle_hva_range(kvm, &hva_range);
700 BUG_ON(kvm->mmu_notifier_count < 0);
703 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
704 struct mm_struct *mm,
708 trace_kvm_age_hva(start, end);
710 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
713 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
714 struct mm_struct *mm,
718 trace_kvm_age_hva(start, end);
721 * Even though we do not flush TLB, this will still adversely
722 * affect performance on pre-Haswell Intel EPT, where there is
723 * no EPT Access Bit to clear so that we have to tear down EPT
724 * tables instead. If we find this unacceptable, we can always
725 * add a parameter to kvm_age_hva so that it effectively doesn't
726 * do anything on clear_young.
728 * Also note that currently we never issue secondary TLB flushes
729 * from clear_young, leaving this job up to the regular system
730 * cadence. If we find this inaccurate, we might come up with a
731 * more sophisticated heuristic later.
733 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
736 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
737 struct mm_struct *mm,
738 unsigned long address)
740 trace_kvm_test_age_hva(address);
742 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
746 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
747 struct mm_struct *mm)
749 struct kvm *kvm = mmu_notifier_to_kvm(mn);
752 idx = srcu_read_lock(&kvm->srcu);
753 kvm_arch_flush_shadow_all(kvm);
754 srcu_read_unlock(&kvm->srcu, idx);
757 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
758 .invalidate_range = kvm_mmu_notifier_invalidate_range,
759 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
760 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
761 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
762 .clear_young = kvm_mmu_notifier_clear_young,
763 .test_young = kvm_mmu_notifier_test_young,
764 .change_pte = kvm_mmu_notifier_change_pte,
765 .release = kvm_mmu_notifier_release,
768 static int kvm_init_mmu_notifier(struct kvm *kvm)
770 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
771 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
774 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
776 static int kvm_init_mmu_notifier(struct kvm *kvm)
781 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
783 static struct kvm_memslots *kvm_alloc_memslots(void)
786 struct kvm_memslots *slots;
788 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
792 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
793 slots->id_to_index[i] = -1;
798 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
800 if (!memslot->dirty_bitmap)
803 kvfree(memslot->dirty_bitmap);
804 memslot->dirty_bitmap = NULL;
807 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
809 kvm_destroy_dirty_bitmap(slot);
811 kvm_arch_free_memslot(kvm, slot);
817 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
819 struct kvm_memory_slot *memslot;
824 kvm_for_each_memslot(memslot, slots)
825 kvm_free_memslot(kvm, memslot);
830 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
834 if (!kvm->debugfs_dentry)
837 debugfs_remove_recursive(kvm->debugfs_dentry);
839 if (kvm->debugfs_stat_data) {
840 for (i = 0; i < kvm_debugfs_num_entries; i++)
841 kfree(kvm->debugfs_stat_data[i]);
842 kfree(kvm->debugfs_stat_data);
846 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
848 static DEFINE_MUTEX(kvm_debugfs_lock);
850 char dir_name[ITOA_MAX_LEN * 2];
851 struct kvm_stat_data *stat_data;
852 struct kvm_stats_debugfs_item *p;
854 if (!debugfs_initialized())
857 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
858 mutex_lock(&kvm_debugfs_lock);
859 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
861 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
863 mutex_unlock(&kvm_debugfs_lock);
866 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
867 mutex_unlock(&kvm_debugfs_lock);
871 kvm->debugfs_dentry = dent;
872 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
873 sizeof(*kvm->debugfs_stat_data),
875 if (!kvm->debugfs_stat_data)
878 for (p = debugfs_entries; p->name; p++) {
879 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
883 stat_data->kvm = kvm;
884 stat_data->dbgfs_item = p;
885 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
886 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
887 kvm->debugfs_dentry, stat_data,
894 * Called after the VM is otherwise initialized, but just before adding it to
897 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
903 * Called just after removing the VM from the vm_list, but before doing any
906 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
910 static struct kvm *kvm_create_vm(unsigned long type)
912 struct kvm *kvm = kvm_arch_alloc_vm();
917 return ERR_PTR(-ENOMEM);
919 KVM_MMU_LOCK_INIT(kvm);
921 kvm->mm = current->mm;
922 kvm_eventfd_init(kvm);
923 mutex_init(&kvm->lock);
924 mutex_init(&kvm->irq_lock);
925 mutex_init(&kvm->slots_lock);
926 INIT_LIST_HEAD(&kvm->devices);
928 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
930 if (init_srcu_struct(&kvm->srcu))
931 goto out_err_no_srcu;
932 if (init_srcu_struct(&kvm->irq_srcu))
933 goto out_err_no_irq_srcu;
935 refcount_set(&kvm->users_count, 1);
936 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
937 struct kvm_memslots *slots = kvm_alloc_memslots();
940 goto out_err_no_arch_destroy_vm;
941 /* Generations must be different for each address space. */
942 slots->generation = i;
943 rcu_assign_pointer(kvm->memslots[i], slots);
946 for (i = 0; i < KVM_NR_BUSES; i++) {
947 rcu_assign_pointer(kvm->buses[i],
948 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
950 goto out_err_no_arch_destroy_vm;
953 kvm->max_halt_poll_ns = halt_poll_ns;
955 r = kvm_arch_init_vm(kvm, type);
957 goto out_err_no_arch_destroy_vm;
959 r = hardware_enable_all();
961 goto out_err_no_disable;
963 #ifdef CONFIG_HAVE_KVM_IRQFD
964 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
967 r = kvm_init_mmu_notifier(kvm);
969 goto out_err_no_mmu_notifier;
971 r = kvm_arch_post_init_vm(kvm);
975 mutex_lock(&kvm_lock);
976 list_add(&kvm->vm_list, &vm_list);
977 mutex_unlock(&kvm_lock);
979 preempt_notifier_inc();
984 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
985 if (kvm->mmu_notifier.ops)
986 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
988 out_err_no_mmu_notifier:
989 hardware_disable_all();
991 kvm_arch_destroy_vm(kvm);
992 out_err_no_arch_destroy_vm:
993 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
994 for (i = 0; i < KVM_NR_BUSES; i++)
995 kfree(kvm_get_bus(kvm, i));
996 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
997 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
998 cleanup_srcu_struct(&kvm->irq_srcu);
1000 cleanup_srcu_struct(&kvm->srcu);
1002 kvm_arch_free_vm(kvm);
1003 mmdrop(current->mm);
1007 static void kvm_destroy_devices(struct kvm *kvm)
1009 struct kvm_device *dev, *tmp;
1012 * We do not need to take the kvm->lock here, because nobody else
1013 * has a reference to the struct kvm at this point and therefore
1014 * cannot access the devices list anyhow.
1016 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1017 list_del(&dev->vm_node);
1018 dev->ops->destroy(dev);
1022 static void kvm_destroy_vm(struct kvm *kvm)
1025 struct mm_struct *mm = kvm->mm;
1027 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1028 kvm_destroy_vm_debugfs(kvm);
1029 kvm_arch_sync_events(kvm);
1030 mutex_lock(&kvm_lock);
1031 list_del(&kvm->vm_list);
1032 mutex_unlock(&kvm_lock);
1033 kvm_arch_pre_destroy_vm(kvm);
1035 kvm_free_irq_routing(kvm);
1036 for (i = 0; i < KVM_NR_BUSES; i++) {
1037 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1040 kvm_io_bus_destroy(bus);
1041 kvm->buses[i] = NULL;
1043 kvm_coalesced_mmio_free(kvm);
1044 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1045 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1047 kvm_arch_flush_shadow_all(kvm);
1049 kvm_arch_destroy_vm(kvm);
1050 kvm_destroy_devices(kvm);
1051 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
1052 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
1053 cleanup_srcu_struct(&kvm->irq_srcu);
1054 cleanup_srcu_struct(&kvm->srcu);
1055 kvm_arch_free_vm(kvm);
1056 preempt_notifier_dec();
1057 hardware_disable_all();
1061 void kvm_get_kvm(struct kvm *kvm)
1063 refcount_inc(&kvm->users_count);
1065 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1067 void kvm_put_kvm(struct kvm *kvm)
1069 if (refcount_dec_and_test(&kvm->users_count))
1070 kvm_destroy_vm(kvm);
1072 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1075 * Used to put a reference that was taken on behalf of an object associated
1076 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1077 * of the new file descriptor fails and the reference cannot be transferred to
1078 * its final owner. In such cases, the caller is still actively using @kvm and
1079 * will fail miserably if the refcount unexpectedly hits zero.
1081 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1083 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1085 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1087 static int kvm_vm_release(struct inode *inode, struct file *filp)
1089 struct kvm *kvm = filp->private_data;
1091 kvm_irqfd_release(kvm);
1098 * Allocation size is twice as large as the actual dirty bitmap size.
1099 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1101 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1103 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
1105 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
1106 if (!memslot->dirty_bitmap)
1113 * Delete a memslot by decrementing the number of used slots and shifting all
1114 * other entries in the array forward one spot.
1116 static inline void kvm_memslot_delete(struct kvm_memslots *slots,
1117 struct kvm_memory_slot *memslot)
1119 struct kvm_memory_slot *mslots = slots->memslots;
1122 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
1125 slots->used_slots--;
1127 if (atomic_read(&slots->lru_slot) >= slots->used_slots)
1128 atomic_set(&slots->lru_slot, 0);
1130 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
1131 mslots[i] = mslots[i + 1];
1132 slots->id_to_index[mslots[i].id] = i;
1134 mslots[i] = *memslot;
1135 slots->id_to_index[memslot->id] = -1;
1139 * "Insert" a new memslot by incrementing the number of used slots. Returns
1140 * the new slot's initial index into the memslots array.
1142 static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
1144 return slots->used_slots++;
1148 * Move a changed memslot backwards in the array by shifting existing slots
1149 * with a higher GFN toward the front of the array. Note, the changed memslot
1150 * itself is not preserved in the array, i.e. not swapped at this time, only
1151 * its new index into the array is tracked. Returns the changed memslot's
1152 * current index into the memslots array.
1154 static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
1155 struct kvm_memory_slot *memslot)
1157 struct kvm_memory_slot *mslots = slots->memslots;
1160 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
1161 WARN_ON_ONCE(!slots->used_slots))
1165 * Move the target memslot backward in the array by shifting existing
1166 * memslots with a higher GFN (than the target memslot) towards the
1167 * front of the array.
1169 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
1170 if (memslot->base_gfn > mslots[i + 1].base_gfn)
1173 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
1175 /* Shift the next memslot forward one and update its index. */
1176 mslots[i] = mslots[i + 1];
1177 slots->id_to_index[mslots[i].id] = i;
1183 * Move a changed memslot forwards in the array by shifting existing slots with
1184 * a lower GFN toward the back of the array. Note, the changed memslot itself
1185 * is not preserved in the array, i.e. not swapped at this time, only its new
1186 * index into the array is tracked. Returns the changed memslot's final index
1187 * into the memslots array.
1189 static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
1190 struct kvm_memory_slot *memslot,
1193 struct kvm_memory_slot *mslots = slots->memslots;
1196 for (i = start; i > 0; i--) {
1197 if (memslot->base_gfn < mslots[i - 1].base_gfn)
1200 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
1202 /* Shift the next memslot back one and update its index. */
1203 mslots[i] = mslots[i - 1];
1204 slots->id_to_index[mslots[i].id] = i;
1210 * Re-sort memslots based on their GFN to account for an added, deleted, or
1211 * moved memslot. Sorting memslots by GFN allows using a binary search during
1214 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
1215 * at memslots[0] has the highest GFN.
1217 * The sorting algorithm takes advantage of having initially sorted memslots
1218 * and knowing the position of the changed memslot. Sorting is also optimized
1219 * by not swapping the updated memslot and instead only shifting other memslots
1220 * and tracking the new index for the update memslot. Only once its final
1221 * index is known is the updated memslot copied into its position in the array.
1223 * - When deleting a memslot, the deleted memslot simply needs to be moved to
1224 * the end of the array.
1226 * - When creating a memslot, the algorithm "inserts" the new memslot at the
1227 * end of the array and then it forward to its correct location.
1229 * - When moving a memslot, the algorithm first moves the updated memslot
1230 * backward to handle the scenario where the memslot's GFN was changed to a
1231 * lower value. update_memslots() then falls through and runs the same flow
1232 * as creating a memslot to move the memslot forward to handle the scenario
1233 * where its GFN was changed to a higher value.
1235 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1236 * historical reasons. Originally, invalid memslots where denoted by having
1237 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1238 * to the end of the array. The current algorithm uses dedicated logic to
1239 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1241 * The other historical motiviation for highest->lowest was to improve the
1242 * performance of memslot lookup. KVM originally used a linear search starting
1243 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1244 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1245 * single memslot above the 4gb boundary. As the largest memslot is also the
1246 * most likely to be referenced, sorting it to the front of the array was
1247 * advantageous. The current binary search starts from the middle of the array
1248 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1250 static void update_memslots(struct kvm_memslots *slots,
1251 struct kvm_memory_slot *memslot,
1252 enum kvm_mr_change change)
1256 if (change == KVM_MR_DELETE) {
1257 kvm_memslot_delete(slots, memslot);
1259 if (change == KVM_MR_CREATE)
1260 i = kvm_memslot_insert_back(slots);
1262 i = kvm_memslot_move_backward(slots, memslot);
1263 i = kvm_memslot_move_forward(slots, memslot, i);
1266 * Copy the memslot to its new position in memslots and update
1267 * its index accordingly.
1269 slots->memslots[i] = *memslot;
1270 slots->id_to_index[memslot->id] = i;
1274 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1276 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1278 #ifdef __KVM_HAVE_READONLY_MEM
1279 valid_flags |= KVM_MEM_READONLY;
1282 if (mem->flags & ~valid_flags)
1288 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
1289 int as_id, struct kvm_memslots *slots)
1291 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
1292 u64 gen = old_memslots->generation;
1294 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1295 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1297 rcu_assign_pointer(kvm->memslots[as_id], slots);
1298 synchronize_srcu_expedited(&kvm->srcu);
1301 * Increment the new memslot generation a second time, dropping the
1302 * update in-progress flag and incrementing the generation based on
1303 * the number of address spaces. This provides a unique and easily
1304 * identifiable generation number while the memslots are in flux.
1306 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1309 * Generations must be unique even across address spaces. We do not need
1310 * a global counter for that, instead the generation space is evenly split
1311 * across address spaces. For example, with two address spaces, address
1312 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1313 * use generations 1, 3, 5, ...
1315 gen += KVM_ADDRESS_SPACE_NUM;
1317 kvm_arch_memslots_updated(kvm, gen);
1319 slots->generation = gen;
1321 return old_memslots;
1325 * Note, at a minimum, the current number of used slots must be allocated, even
1326 * when deleting a memslot, as we need a complete duplicate of the memslots for
1327 * use when invalidating a memslot prior to deleting/moving the memslot.
1329 static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1330 enum kvm_mr_change change)
1332 struct kvm_memslots *slots;
1333 size_t old_size, new_size;
1335 old_size = sizeof(struct kvm_memslots) +
1336 (sizeof(struct kvm_memory_slot) * old->used_slots);
1338 if (change == KVM_MR_CREATE)
1339 new_size = old_size + sizeof(struct kvm_memory_slot);
1341 new_size = old_size;
1343 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1345 memcpy(slots, old, old_size);
1350 static int kvm_set_memslot(struct kvm *kvm,
1351 const struct kvm_userspace_memory_region *mem,
1352 struct kvm_memory_slot *old,
1353 struct kvm_memory_slot *new, int as_id,
1354 enum kvm_mr_change change)
1356 struct kvm_memory_slot *slot;
1357 struct kvm_memslots *slots;
1360 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
1364 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1366 * Note, the INVALID flag needs to be in the appropriate entry
1367 * in the freshly allocated memslots, not in @old or @new.
1369 slot = id_to_memslot(slots, old->id);
1370 slot->flags |= KVM_MEMSLOT_INVALID;
1373 * We can re-use the old memslots, the only difference from the
1374 * newly installed memslots is the invalid flag, which will get
1375 * dropped by update_memslots anyway. We'll also revert to the
1376 * old memslots if preparing the new memory region fails.
1378 slots = install_new_memslots(kvm, as_id, slots);
1380 /* From this point no new shadow pages pointing to a deleted,
1381 * or moved, memslot will be created.
1383 * validation of sp->gfn happens in:
1384 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1385 * - kvm_is_visible_gfn (mmu_check_root)
1387 kvm_arch_flush_shadow_memslot(kvm, slot);
1390 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1394 update_memslots(slots, new, change);
1395 slots = install_new_memslots(kvm, as_id, slots);
1397 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1403 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1404 slots = install_new_memslots(kvm, as_id, slots);
1409 static int kvm_delete_memslot(struct kvm *kvm,
1410 const struct kvm_userspace_memory_region *mem,
1411 struct kvm_memory_slot *old, int as_id)
1413 struct kvm_memory_slot new;
1419 memset(&new, 0, sizeof(new));
1422 * This is only for debugging purpose; it should never be referenced
1423 * for a removed memslot.
1427 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1431 kvm_free_memslot(kvm, old);
1436 * Allocate some memory and give it an address in the guest physical address
1439 * Discontiguous memory is allowed, mostly for framebuffers.
1441 * Must be called holding kvm->slots_lock for write.
1443 int __kvm_set_memory_region(struct kvm *kvm,
1444 const struct kvm_userspace_memory_region *mem)
1446 struct kvm_memory_slot old, new;
1447 struct kvm_memory_slot *tmp;
1448 enum kvm_mr_change change;
1452 r = check_memory_region_flags(mem);
1456 as_id = mem->slot >> 16;
1457 id = (u16)mem->slot;
1459 /* General sanity checks */
1460 if (mem->memory_size & (PAGE_SIZE - 1))
1462 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1464 /* We can read the guest memory with __xxx_user() later on. */
1465 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1466 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1467 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1470 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1472 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1476 * Make a full copy of the old memslot, the pointer will become stale
1477 * when the memslots are re-sorted by update_memslots(), and the old
1478 * memslot needs to be referenced after calling update_memslots(), e.g.
1479 * to free its resources and for arch specific behavior.
1481 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1486 memset(&old, 0, sizeof(old));
1490 if (!mem->memory_size)
1491 return kvm_delete_memslot(kvm, mem, &old, as_id);
1495 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1496 new.npages = mem->memory_size >> PAGE_SHIFT;
1497 new.flags = mem->flags;
1498 new.userspace_addr = mem->userspace_addr;
1500 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1504 change = KVM_MR_CREATE;
1505 new.dirty_bitmap = NULL;
1506 memset(&new.arch, 0, sizeof(new.arch));
1507 } else { /* Modify an existing slot. */
1508 if ((new.userspace_addr != old.userspace_addr) ||
1509 (new.npages != old.npages) ||
1510 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1513 if (new.base_gfn != old.base_gfn)
1514 change = KVM_MR_MOVE;
1515 else if (new.flags != old.flags)
1516 change = KVM_MR_FLAGS_ONLY;
1517 else /* Nothing to change. */
1520 /* Copy dirty_bitmap and arch from the current memslot. */
1521 new.dirty_bitmap = old.dirty_bitmap;
1522 memcpy(&new.arch, &old.arch, sizeof(new.arch));
1525 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1526 /* Check for overlaps */
1527 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1530 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1531 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1536 /* Allocate/free page dirty bitmap as needed */
1537 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1538 new.dirty_bitmap = NULL;
1539 else if (!new.dirty_bitmap && !kvm->dirty_ring_size) {
1540 r = kvm_alloc_dirty_bitmap(&new);
1544 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1545 bitmap_set(new.dirty_bitmap, 0, new.npages);
1548 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1552 if (old.dirty_bitmap && !new.dirty_bitmap)
1553 kvm_destroy_dirty_bitmap(&old);
1557 if (new.dirty_bitmap && !old.dirty_bitmap)
1558 kvm_destroy_dirty_bitmap(&new);
1561 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1563 int kvm_set_memory_region(struct kvm *kvm,
1564 const struct kvm_userspace_memory_region *mem)
1568 mutex_lock(&kvm->slots_lock);
1569 r = __kvm_set_memory_region(kvm, mem);
1570 mutex_unlock(&kvm->slots_lock);
1573 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1575 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1576 struct kvm_userspace_memory_region *mem)
1578 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1581 return kvm_set_memory_region(kvm, mem);
1584 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1586 * kvm_get_dirty_log - get a snapshot of dirty pages
1587 * @kvm: pointer to kvm instance
1588 * @log: slot id and address to which we copy the log
1589 * @is_dirty: set to '1' if any dirty pages were found
1590 * @memslot: set to the associated memslot, always valid on success
1592 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1593 int *is_dirty, struct kvm_memory_slot **memslot)
1595 struct kvm_memslots *slots;
1598 unsigned long any = 0;
1600 /* Dirty ring tracking is exclusive to dirty log tracking */
1601 if (kvm->dirty_ring_size)
1607 as_id = log->slot >> 16;
1608 id = (u16)log->slot;
1609 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1612 slots = __kvm_memslots(kvm, as_id);
1613 *memslot = id_to_memslot(slots, id);
1614 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1617 kvm_arch_sync_dirty_log(kvm, *memslot);
1619 n = kvm_dirty_bitmap_bytes(*memslot);
1621 for (i = 0; !any && i < n/sizeof(long); ++i)
1622 any = (*memslot)->dirty_bitmap[i];
1624 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1631 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1633 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1635 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1636 * and reenable dirty page tracking for the corresponding pages.
1637 * @kvm: pointer to kvm instance
1638 * @log: slot id and address to which we copy the log
1640 * We need to keep it in mind that VCPU threads can write to the bitmap
1641 * concurrently. So, to avoid losing track of dirty pages we keep the
1644 * 1. Take a snapshot of the bit and clear it if needed.
1645 * 2. Write protect the corresponding page.
1646 * 3. Copy the snapshot to the userspace.
1647 * 4. Upon return caller flushes TLB's if needed.
1649 * Between 2 and 4, the guest may write to the page using the remaining TLB
1650 * entry. This is not a problem because the page is reported dirty using
1651 * the snapshot taken before and step 4 ensures that writes done after
1652 * exiting to userspace will be logged for the next call.
1655 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
1657 struct kvm_memslots *slots;
1658 struct kvm_memory_slot *memslot;
1661 unsigned long *dirty_bitmap;
1662 unsigned long *dirty_bitmap_buffer;
1665 /* Dirty ring tracking is exclusive to dirty log tracking */
1666 if (kvm->dirty_ring_size)
1669 as_id = log->slot >> 16;
1670 id = (u16)log->slot;
1671 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1674 slots = __kvm_memslots(kvm, as_id);
1675 memslot = id_to_memslot(slots, id);
1676 if (!memslot || !memslot->dirty_bitmap)
1679 dirty_bitmap = memslot->dirty_bitmap;
1681 kvm_arch_sync_dirty_log(kvm, memslot);
1683 n = kvm_dirty_bitmap_bytes(memslot);
1685 if (kvm->manual_dirty_log_protect) {
1687 * Unlike kvm_get_dirty_log, we always return false in *flush,
1688 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1689 * is some code duplication between this function and
1690 * kvm_get_dirty_log, but hopefully all architecture
1691 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1692 * can be eliminated.
1694 dirty_bitmap_buffer = dirty_bitmap;
1696 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1697 memset(dirty_bitmap_buffer, 0, n);
1700 for (i = 0; i < n / sizeof(long); i++) {
1704 if (!dirty_bitmap[i])
1708 mask = xchg(&dirty_bitmap[i], 0);
1709 dirty_bitmap_buffer[i] = mask;
1711 offset = i * BITS_PER_LONG;
1712 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1715 KVM_MMU_UNLOCK(kvm);
1719 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1721 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1728 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1729 * @kvm: kvm instance
1730 * @log: slot id and address to which we copy the log
1732 * Steps 1-4 below provide general overview of dirty page logging. See
1733 * kvm_get_dirty_log_protect() function description for additional details.
1735 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1736 * always flush the TLB (step 4) even if previous step failed and the dirty
1737 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1738 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1739 * writes will be marked dirty for next log read.
1741 * 1. Take a snapshot of the bit and clear it if needed.
1742 * 2. Write protect the corresponding page.
1743 * 3. Copy the snapshot to the userspace.
1744 * 4. Flush TLB's if needed.
1746 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1747 struct kvm_dirty_log *log)
1751 mutex_lock(&kvm->slots_lock);
1753 r = kvm_get_dirty_log_protect(kvm, log);
1755 mutex_unlock(&kvm->slots_lock);
1760 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1761 * and reenable dirty page tracking for the corresponding pages.
1762 * @kvm: pointer to kvm instance
1763 * @log: slot id and address from which to fetch the bitmap of dirty pages
1765 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1766 struct kvm_clear_dirty_log *log)
1768 struct kvm_memslots *slots;
1769 struct kvm_memory_slot *memslot;
1773 unsigned long *dirty_bitmap;
1774 unsigned long *dirty_bitmap_buffer;
1777 /* Dirty ring tracking is exclusive to dirty log tracking */
1778 if (kvm->dirty_ring_size)
1781 as_id = log->slot >> 16;
1782 id = (u16)log->slot;
1783 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1786 if (log->first_page & 63)
1789 slots = __kvm_memslots(kvm, as_id);
1790 memslot = id_to_memslot(slots, id);
1791 if (!memslot || !memslot->dirty_bitmap)
1794 dirty_bitmap = memslot->dirty_bitmap;
1796 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
1798 if (log->first_page > memslot->npages ||
1799 log->num_pages > memslot->npages - log->first_page ||
1800 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1803 kvm_arch_sync_dirty_log(kvm, memslot);
1806 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1807 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1811 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1812 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
1813 i++, offset += BITS_PER_LONG) {
1814 unsigned long mask = *dirty_bitmap_buffer++;
1815 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1819 mask &= atomic_long_fetch_andnot(mask, p);
1822 * mask contains the bits that really have been cleared. This
1823 * never includes any bits beyond the length of the memslot (if
1824 * the length is not aligned to 64 pages), therefore it is not
1825 * a problem if userspace sets them in log->dirty_bitmap.
1829 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1833 KVM_MMU_UNLOCK(kvm);
1836 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1841 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
1842 struct kvm_clear_dirty_log *log)
1846 mutex_lock(&kvm->slots_lock);
1848 r = kvm_clear_dirty_log_protect(kvm, log);
1850 mutex_unlock(&kvm->slots_lock);
1853 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1855 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1857 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1859 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1861 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1863 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1865 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
1867 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1869 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1871 return kvm_is_visible_memslot(memslot);
1873 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1875 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1877 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1879 return kvm_is_visible_memslot(memslot);
1881 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
1883 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
1885 struct vm_area_struct *vma;
1886 unsigned long addr, size;
1890 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
1891 if (kvm_is_error_hva(addr))
1894 mmap_read_lock(current->mm);
1895 vma = find_vma(current->mm, addr);
1899 size = vma_kernel_pagesize(vma);
1902 mmap_read_unlock(current->mm);
1907 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1909 return slot->flags & KVM_MEM_READONLY;
1912 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1913 gfn_t *nr_pages, bool write)
1915 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1916 return KVM_HVA_ERR_BAD;
1918 if (memslot_is_readonly(slot) && write)
1919 return KVM_HVA_ERR_RO_BAD;
1922 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1924 return __gfn_to_hva_memslot(slot, gfn);
1927 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1930 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1933 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1936 return gfn_to_hva_many(slot, gfn, NULL);
1938 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1940 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1942 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1944 EXPORT_SYMBOL_GPL(gfn_to_hva);
1946 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1948 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1950 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1953 * Return the hva of a @gfn and the R/W attribute if possible.
1955 * @slot: the kvm_memory_slot which contains @gfn
1956 * @gfn: the gfn to be translated
1957 * @writable: used to return the read/write attribute of the @slot if the hva
1958 * is valid and @writable is not NULL
1960 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1961 gfn_t gfn, bool *writable)
1963 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1965 if (!kvm_is_error_hva(hva) && writable)
1966 *writable = !memslot_is_readonly(slot);
1971 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1973 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1975 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1978 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1980 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1982 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1985 static inline int check_user_page_hwpoison(unsigned long addr)
1987 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1989 rc = get_user_pages(addr, 1, flags, NULL, NULL);
1990 return rc == -EHWPOISON;
1994 * The fast path to get the writable pfn which will be stored in @pfn,
1995 * true indicates success, otherwise false is returned. It's also the
1996 * only part that runs if we can in atomic context.
1998 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1999 bool *writable, kvm_pfn_t *pfn)
2001 struct page *page[1];
2004 * Fast pin a writable pfn only if it is a write fault request
2005 * or the caller allows to map a writable pfn for a read fault
2008 if (!(write_fault || writable))
2011 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2012 *pfn = page_to_pfn(page[0]);
2023 * The slow path to get the pfn of the specified host virtual address,
2024 * 1 indicates success, -errno is returned if error is detected.
2026 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2027 bool *writable, kvm_pfn_t *pfn)
2029 unsigned int flags = FOLL_HWPOISON;
2036 *writable = write_fault;
2039 flags |= FOLL_WRITE;
2041 flags |= FOLL_NOWAIT;
2043 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2047 /* map read fault as writable if possible */
2048 if (unlikely(!write_fault) && writable) {
2051 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2057 *pfn = page_to_pfn(page);
2061 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2063 if (unlikely(!(vma->vm_flags & VM_READ)))
2066 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2072 static int kvm_try_get_pfn(kvm_pfn_t pfn)
2074 if (kvm_is_reserved_pfn(pfn))
2076 return get_page_unless_zero(pfn_to_page(pfn));
2079 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2080 unsigned long addr, bool *async,
2081 bool write_fault, bool *writable,
2089 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2092 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2093 * not call the fault handler, so do it here.
2095 bool unlocked = false;
2096 r = fixup_user_fault(current->mm, addr,
2097 (write_fault ? FAULT_FLAG_WRITE : 0),
2104 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2109 if (write_fault && !pte_write(*ptep)) {
2110 pfn = KVM_PFN_ERR_RO_FAULT;
2115 *writable = pte_write(*ptep);
2116 pfn = pte_pfn(*ptep);
2119 * Get a reference here because callers of *hva_to_pfn* and
2120 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2121 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2122 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
2123 * simply do nothing for reserved pfns.
2125 * Whoever called remap_pfn_range is also going to call e.g.
2126 * unmap_mapping_range before the underlying pages are freed,
2127 * causing a call to our MMU notifier.
2129 * Certain IO or PFNMAP mappings can be backed with valid
2130 * struct pages, but be allocated without refcounting e.g.,
2131 * tail pages of non-compound higher order allocations, which
2132 * would then underflow the refcount when the caller does the
2133 * required put_page. Don't allow those pages here.
2135 if (!kvm_try_get_pfn(pfn))
2139 pte_unmap_unlock(ptep, ptl);
2146 * Pin guest page in memory and return its pfn.
2147 * @addr: host virtual address which maps memory to the guest
2148 * @atomic: whether this function can sleep
2149 * @async: whether this function need to wait IO complete if the
2150 * host page is not in the memory
2151 * @write_fault: whether we should get a writable host page
2152 * @writable: whether it allows to map a writable host page for !@write_fault
2154 * The function will map a writable host page for these two cases:
2155 * 1): @write_fault = true
2156 * 2): @write_fault = false && @writable, @writable will tell the caller
2157 * whether the mapping is writable.
2159 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2160 bool write_fault, bool *writable)
2162 struct vm_area_struct *vma;
2166 /* we can do it either atomically or asynchronously, not both */
2167 BUG_ON(atomic && async);
2169 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2173 return KVM_PFN_ERR_FAULT;
2175 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2179 mmap_read_lock(current->mm);
2180 if (npages == -EHWPOISON ||
2181 (!async && check_user_page_hwpoison(addr))) {
2182 pfn = KVM_PFN_ERR_HWPOISON;
2187 vma = find_vma_intersection(current->mm, addr, addr + 1);
2190 pfn = KVM_PFN_ERR_FAULT;
2191 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2192 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
2196 pfn = KVM_PFN_ERR_FAULT;
2198 if (async && vma_is_valid(vma, write_fault))
2200 pfn = KVM_PFN_ERR_FAULT;
2203 mmap_read_unlock(current->mm);
2207 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
2208 bool atomic, bool *async, bool write_fault,
2209 bool *writable, hva_t *hva)
2211 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2216 if (addr == KVM_HVA_ERR_RO_BAD) {
2219 return KVM_PFN_ERR_RO_FAULT;
2222 if (kvm_is_error_hva(addr)) {
2225 return KVM_PFN_NOSLOT;
2228 /* Do not map writable pfn in the readonly memslot. */
2229 if (writable && memslot_is_readonly(slot)) {
2234 return hva_to_pfn(addr, atomic, async, write_fault,
2237 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2239 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2242 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2243 write_fault, writable, NULL);
2245 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2247 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
2249 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2251 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2253 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
2255 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2257 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2259 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2261 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2263 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2265 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2267 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2269 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2271 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2273 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2275 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2277 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2278 struct page **pages, int nr_pages)
2283 addr = gfn_to_hva_many(slot, gfn, &entry);
2284 if (kvm_is_error_hva(addr))
2287 if (entry < nr_pages)
2290 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2292 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2294 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2296 if (is_error_noslot_pfn(pfn))
2297 return KVM_ERR_PTR_BAD_PAGE;
2299 if (kvm_is_reserved_pfn(pfn)) {
2301 return KVM_ERR_PTR_BAD_PAGE;
2304 return pfn_to_page(pfn);
2307 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2311 pfn = gfn_to_pfn(kvm, gfn);
2313 return kvm_pfn_to_page(pfn);
2315 EXPORT_SYMBOL_GPL(gfn_to_page);
2317 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2323 cache->pfn = cache->gfn = 0;
2326 kvm_release_pfn_dirty(pfn);
2328 kvm_release_pfn_clean(pfn);
2331 static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2332 struct gfn_to_pfn_cache *cache, u64 gen)
2334 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2336 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2338 cache->dirty = false;
2339 cache->generation = gen;
2342 static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2343 struct kvm_host_map *map,
2344 struct gfn_to_pfn_cache *cache,
2349 struct page *page = KVM_UNMAPPED_PAGE;
2350 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2351 u64 gen = slots->generation;
2357 if (!cache->pfn || cache->gfn != gfn ||
2358 cache->generation != gen) {
2361 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2367 pfn = gfn_to_pfn_memslot(slot, gfn);
2369 if (is_error_noslot_pfn(pfn))
2372 if (pfn_valid(pfn)) {
2373 page = pfn_to_page(pfn);
2375 hva = kmap_atomic(page);
2378 #ifdef CONFIG_HAS_IOMEM
2379 } else if (!atomic) {
2380 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2397 int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2398 struct gfn_to_pfn_cache *cache, bool atomic)
2400 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2403 EXPORT_SYMBOL_GPL(kvm_map_gfn);
2405 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2407 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2410 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2412 static void __kvm_unmap_gfn(struct kvm *kvm,
2413 struct kvm_memory_slot *memslot,
2414 struct kvm_host_map *map,
2415 struct gfn_to_pfn_cache *cache,
2416 bool dirty, bool atomic)
2424 if (map->page != KVM_UNMAPPED_PAGE) {
2426 kunmap_atomic(map->hva);
2430 #ifdef CONFIG_HAS_IOMEM
2434 WARN_ONCE(1, "Unexpected unmapping in atomic context");
2438 mark_page_dirty_in_slot(kvm, memslot, map->gfn);
2441 cache->dirty |= dirty;
2443 kvm_release_pfn(map->pfn, dirty, NULL);
2449 int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2450 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2452 __kvm_unmap_gfn(vcpu->kvm, gfn_to_memslot(vcpu->kvm, map->gfn), map,
2453 cache, dirty, atomic);
2456 EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2458 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2460 __kvm_unmap_gfn(vcpu->kvm, kvm_vcpu_gfn_to_memslot(vcpu, map->gfn),
2461 map, NULL, dirty, false);
2463 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2465 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2469 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2471 return kvm_pfn_to_page(pfn);
2473 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2475 void kvm_release_page_clean(struct page *page)
2477 WARN_ON(is_error_page(page));
2479 kvm_release_pfn_clean(page_to_pfn(page));
2481 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2483 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2485 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2486 put_page(pfn_to_page(pfn));
2488 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2490 void kvm_release_page_dirty(struct page *page)
2492 WARN_ON(is_error_page(page));
2494 kvm_release_pfn_dirty(page_to_pfn(page));
2496 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2498 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2500 kvm_set_pfn_dirty(pfn);
2501 kvm_release_pfn_clean(pfn);
2503 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2505 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2507 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2508 SetPageDirty(pfn_to_page(pfn));
2510 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2512 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2514 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2515 mark_page_accessed(pfn_to_page(pfn));
2517 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2519 void kvm_get_pfn(kvm_pfn_t pfn)
2521 if (!kvm_is_reserved_pfn(pfn))
2522 get_page(pfn_to_page(pfn));
2524 EXPORT_SYMBOL_GPL(kvm_get_pfn);
2526 static int next_segment(unsigned long len, int offset)
2528 if (len > PAGE_SIZE - offset)
2529 return PAGE_SIZE - offset;
2534 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2535 void *data, int offset, int len)
2540 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2541 if (kvm_is_error_hva(addr))
2543 r = __copy_from_user(data, (void __user *)addr + offset, len);
2549 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2552 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2554 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2556 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2558 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2559 int offset, int len)
2561 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2563 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2565 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2567 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2569 gfn_t gfn = gpa >> PAGE_SHIFT;
2571 int offset = offset_in_page(gpa);
2574 while ((seg = next_segment(len, offset)) != 0) {
2575 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2585 EXPORT_SYMBOL_GPL(kvm_read_guest);
2587 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2589 gfn_t gfn = gpa >> PAGE_SHIFT;
2591 int offset = offset_in_page(gpa);
2594 while ((seg = next_segment(len, offset)) != 0) {
2595 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2605 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2607 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2608 void *data, int offset, unsigned long len)
2613 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2614 if (kvm_is_error_hva(addr))
2616 pagefault_disable();
2617 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2624 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2625 void *data, unsigned long len)
2627 gfn_t gfn = gpa >> PAGE_SHIFT;
2628 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2629 int offset = offset_in_page(gpa);
2631 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2633 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2635 static int __kvm_write_guest_page(struct kvm *kvm,
2636 struct kvm_memory_slot *memslot, gfn_t gfn,
2637 const void *data, int offset, int len)
2642 addr = gfn_to_hva_memslot(memslot, gfn);
2643 if (kvm_is_error_hva(addr))
2645 r = __copy_to_user((void __user *)addr + offset, data, len);
2648 mark_page_dirty_in_slot(kvm, memslot, gfn);
2652 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2653 const void *data, int offset, int len)
2655 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2657 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2659 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2661 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2662 const void *data, int offset, int len)
2664 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2666 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
2668 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2670 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2673 gfn_t gfn = gpa >> PAGE_SHIFT;
2675 int offset = offset_in_page(gpa);
2678 while ((seg = next_segment(len, offset)) != 0) {
2679 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2689 EXPORT_SYMBOL_GPL(kvm_write_guest);
2691 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2694 gfn_t gfn = gpa >> PAGE_SHIFT;
2696 int offset = offset_in_page(gpa);
2699 while ((seg = next_segment(len, offset)) != 0) {
2700 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2710 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2712 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2713 struct gfn_to_hva_cache *ghc,
2714 gpa_t gpa, unsigned long len)
2716 int offset = offset_in_page(gpa);
2717 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2718 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2719 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2720 gfn_t nr_pages_avail;
2722 /* Update ghc->generation before performing any error checks. */
2723 ghc->generation = slots->generation;
2725 if (start_gfn > end_gfn) {
2726 ghc->hva = KVM_HVA_ERR_BAD;
2731 * If the requested region crosses two memslots, we still
2732 * verify that the entire region is valid here.
2734 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
2735 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2736 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2738 if (kvm_is_error_hva(ghc->hva))
2742 /* Use the slow path for cross page reads and writes. */
2743 if (nr_pages_needed == 1)
2746 ghc->memslot = NULL;
2753 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2754 gpa_t gpa, unsigned long len)
2756 struct kvm_memslots *slots = kvm_memslots(kvm);
2757 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2759 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2761 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2762 void *data, unsigned int offset,
2765 struct kvm_memslots *slots = kvm_memslots(kvm);
2767 gpa_t gpa = ghc->gpa + offset;
2769 BUG_ON(len + offset > ghc->len);
2771 if (slots->generation != ghc->generation) {
2772 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2776 if (kvm_is_error_hva(ghc->hva))
2779 if (unlikely(!ghc->memslot))
2780 return kvm_write_guest(kvm, gpa, data, len);
2782 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2785 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
2789 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2791 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2792 void *data, unsigned long len)
2794 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2796 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2798 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2799 void *data, unsigned int offset,
2802 struct kvm_memslots *slots = kvm_memslots(kvm);
2804 gpa_t gpa = ghc->gpa + offset;
2806 BUG_ON(len + offset > ghc->len);
2808 if (slots->generation != ghc->generation) {
2809 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2813 if (kvm_is_error_hva(ghc->hva))
2816 if (unlikely(!ghc->memslot))
2817 return kvm_read_guest(kvm, gpa, data, len);
2819 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
2825 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
2827 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2828 void *data, unsigned long len)
2830 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
2832 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2834 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2836 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2837 gfn_t gfn = gpa >> PAGE_SHIFT;
2839 int offset = offset_in_page(gpa);
2842 while ((seg = next_segment(len, offset)) != 0) {
2843 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2852 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2854 void mark_page_dirty_in_slot(struct kvm *kvm,
2855 struct kvm_memory_slot *memslot,
2858 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
2859 unsigned long rel_gfn = gfn - memslot->base_gfn;
2860 u32 slot = (memslot->as_id << 16) | memslot->id;
2862 if (kvm->dirty_ring_size)
2863 kvm_dirty_ring_push(kvm_dirty_ring_get(kvm),
2866 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2869 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
2871 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2873 struct kvm_memory_slot *memslot;
2875 memslot = gfn_to_memslot(kvm, gfn);
2876 mark_page_dirty_in_slot(kvm, memslot, gfn);
2878 EXPORT_SYMBOL_GPL(mark_page_dirty);
2880 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2882 struct kvm_memory_slot *memslot;
2884 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2885 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
2887 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2889 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2891 if (!vcpu->sigset_active)
2895 * This does a lockless modification of ->real_blocked, which is fine
2896 * because, only current can change ->real_blocked and all readers of
2897 * ->real_blocked don't care as long ->real_blocked is always a subset
2900 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
2903 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2905 if (!vcpu->sigset_active)
2908 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
2909 sigemptyset(¤t->real_blocked);
2912 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2914 unsigned int old, val, grow, grow_start;
2916 old = val = vcpu->halt_poll_ns;
2917 grow_start = READ_ONCE(halt_poll_ns_grow_start);
2918 grow = READ_ONCE(halt_poll_ns_grow);
2923 if (val < grow_start)
2926 if (val > vcpu->kvm->max_halt_poll_ns)
2927 val = vcpu->kvm->max_halt_poll_ns;
2929 vcpu->halt_poll_ns = val;
2931 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2934 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2936 unsigned int old, val, shrink;
2938 old = val = vcpu->halt_poll_ns;
2939 shrink = READ_ONCE(halt_poll_ns_shrink);
2945 vcpu->halt_poll_ns = val;
2946 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2949 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2952 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2954 if (kvm_arch_vcpu_runnable(vcpu)) {
2955 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2958 if (kvm_cpu_has_pending_timer(vcpu))
2960 if (signal_pending(current))
2962 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
2967 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2972 update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
2975 vcpu->stat.halt_poll_fail_ns += poll_ns;
2977 vcpu->stat.halt_poll_success_ns += poll_ns;
2981 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2983 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2985 ktime_t start, cur, poll_end;
2986 bool waited = false;
2989 kvm_arch_vcpu_blocking(vcpu);
2991 start = cur = poll_end = ktime_get();
2992 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
2993 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2995 ++vcpu->stat.halt_attempted_poll;
2998 * This sets KVM_REQ_UNHALT if an interrupt
3001 if (kvm_vcpu_check_block(vcpu) < 0) {
3002 ++vcpu->stat.halt_successful_poll;
3003 if (!vcpu_valid_wakeup(vcpu))
3004 ++vcpu->stat.halt_poll_invalid;
3007 poll_end = cur = ktime_get();
3008 } while (kvm_vcpu_can_poll(cur, stop));
3011 prepare_to_rcuwait(&vcpu->wait);
3013 set_current_state(TASK_INTERRUPTIBLE);
3015 if (kvm_vcpu_check_block(vcpu) < 0)
3021 finish_rcuwait(&vcpu->wait);
3024 kvm_arch_vcpu_unblocking(vcpu);
3025 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3027 update_halt_poll_stats(
3028 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
3030 if (!kvm_arch_no_poll(vcpu)) {
3031 if (!vcpu_valid_wakeup(vcpu)) {
3032 shrink_halt_poll_ns(vcpu);
3033 } else if (vcpu->kvm->max_halt_poll_ns) {
3034 if (block_ns <= vcpu->halt_poll_ns)
3036 /* we had a long block, shrink polling */
3037 else if (vcpu->halt_poll_ns &&
3038 block_ns > vcpu->kvm->max_halt_poll_ns)
3039 shrink_halt_poll_ns(vcpu);
3040 /* we had a short halt and our poll time is too small */
3041 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3042 block_ns < vcpu->kvm->max_halt_poll_ns)
3043 grow_halt_poll_ns(vcpu);
3045 vcpu->halt_poll_ns = 0;
3049 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
3050 kvm_arch_vcpu_block_finish(vcpu);
3052 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
3054 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3056 struct rcuwait *waitp;
3058 waitp = kvm_arch_vcpu_get_wait(vcpu);
3059 if (rcuwait_wake_up(waitp)) {
3060 WRITE_ONCE(vcpu->ready, true);
3061 ++vcpu->stat.halt_wakeup;
3067 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3071 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3073 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3076 int cpu = vcpu->cpu;
3078 if (kvm_vcpu_wake_up(vcpu))
3082 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3083 if (kvm_arch_vcpu_should_kick(vcpu))
3084 smp_send_reschedule(cpu);
3087 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3088 #endif /* !CONFIG_S390 */
3090 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3093 struct task_struct *task = NULL;
3097 pid = rcu_dereference(target->pid);
3099 task = get_pid_task(pid, PIDTYPE_PID);
3103 ret = yield_to(task, 1);
3104 put_task_struct(task);
3108 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3111 * Helper that checks whether a VCPU is eligible for directed yield.
3112 * Most eligible candidate to yield is decided by following heuristics:
3114 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3115 * (preempted lock holder), indicated by @in_spin_loop.
3116 * Set at the beginning and cleared at the end of interception/PLE handler.
3118 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3119 * chance last time (mostly it has become eligible now since we have probably
3120 * yielded to lockholder in last iteration. This is done by toggling
3121 * @dy_eligible each time a VCPU checked for eligibility.)
3123 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3124 * to preempted lock-holder could result in wrong VCPU selection and CPU
3125 * burning. Giving priority for a potential lock-holder increases lock
3128 * Since algorithm is based on heuristics, accessing another VCPU data without
3129 * locking does not harm. It may result in trying to yield to same VCPU, fail
3130 * and continue with next VCPU and so on.
3132 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3134 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3137 eligible = !vcpu->spin_loop.in_spin_loop ||
3138 vcpu->spin_loop.dy_eligible;
3140 if (vcpu->spin_loop.in_spin_loop)
3141 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3150 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3151 * a vcpu_load/vcpu_put pair. However, for most architectures
3152 * kvm_arch_vcpu_runnable does not require vcpu_load.
3154 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3156 return kvm_arch_vcpu_runnable(vcpu);
3159 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3161 if (kvm_arch_dy_runnable(vcpu))
3164 #ifdef CONFIG_KVM_ASYNC_PF
3165 if (!list_empty_careful(&vcpu->async_pf.done))
3172 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3177 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3179 struct kvm *kvm = me->kvm;
3180 struct kvm_vcpu *vcpu;
3181 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3187 kvm_vcpu_set_in_spin_loop(me, true);
3189 * We boost the priority of a VCPU that is runnable but not
3190 * currently running, because it got preempted by something
3191 * else and called schedule in __vcpu_run. Hopefully that
3192 * VCPU is holding the lock that we need and will release it.
3193 * We approximate round-robin by starting at the last boosted VCPU.
3195 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3196 kvm_for_each_vcpu(i, vcpu, kvm) {
3197 if (!pass && i <= last_boosted_vcpu) {
3198 i = last_boosted_vcpu;
3200 } else if (pass && i > last_boosted_vcpu)
3202 if (!READ_ONCE(vcpu->ready))
3206 if (rcuwait_active(&vcpu->wait) &&
3207 !vcpu_dy_runnable(vcpu))
3209 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3210 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3211 !kvm_arch_vcpu_in_kernel(vcpu))
3213 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3216 yielded = kvm_vcpu_yield_to(vcpu);
3218 kvm->last_boosted_vcpu = i;
3220 } else if (yielded < 0) {
3227 kvm_vcpu_set_in_spin_loop(me, false);
3229 /* Ensure vcpu is not eligible during next spinloop */
3230 kvm_vcpu_set_dy_eligible(me, false);
3232 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3234 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3236 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3237 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3238 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3239 kvm->dirty_ring_size / PAGE_SIZE);
3245 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3247 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3250 if (vmf->pgoff == 0)
3251 page = virt_to_page(vcpu->run);
3253 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3254 page = virt_to_page(vcpu->arch.pio_data);
3256 #ifdef CONFIG_KVM_MMIO
3257 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3258 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3260 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3261 page = kvm_dirty_ring_get_page(
3263 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3265 return kvm_arch_vcpu_fault(vcpu, vmf);
3271 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3272 .fault = kvm_vcpu_fault,
3275 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3277 struct kvm_vcpu *vcpu = file->private_data;
3278 unsigned long pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
3280 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3281 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3282 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3285 vma->vm_ops = &kvm_vcpu_vm_ops;
3289 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3291 struct kvm_vcpu *vcpu = filp->private_data;
3293 kvm_put_kvm(vcpu->kvm);
3297 static struct file_operations kvm_vcpu_fops = {
3298 .release = kvm_vcpu_release,
3299 .unlocked_ioctl = kvm_vcpu_ioctl,
3300 .mmap = kvm_vcpu_mmap,
3301 .llseek = noop_llseek,
3302 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3306 * Allocates an inode for the vcpu.
3308 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3310 char name[8 + 1 + ITOA_MAX_LEN + 1];
3312 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3313 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3316 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3318 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3319 struct dentry *debugfs_dentry;
3320 char dir_name[ITOA_MAX_LEN * 2];
3322 if (!debugfs_initialized())
3325 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3326 debugfs_dentry = debugfs_create_dir(dir_name,
3327 vcpu->kvm->debugfs_dentry);
3329 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3334 * Creates some virtual cpus. Good luck creating more than one.
3336 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3339 struct kvm_vcpu *vcpu;
3342 if (id >= KVM_MAX_VCPU_ID)
3345 mutex_lock(&kvm->lock);
3346 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3347 mutex_unlock(&kvm->lock);
3351 kvm->created_vcpus++;
3352 mutex_unlock(&kvm->lock);
3354 r = kvm_arch_vcpu_precreate(kvm, id);
3356 goto vcpu_decrement;
3358 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3361 goto vcpu_decrement;
3364 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3365 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3370 vcpu->run = page_address(page);
3372 kvm_vcpu_init(vcpu, kvm, id);
3374 r = kvm_arch_vcpu_create(vcpu);
3376 goto vcpu_free_run_page;
3378 if (kvm->dirty_ring_size) {
3379 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3380 id, kvm->dirty_ring_size);
3382 goto arch_vcpu_destroy;
3385 mutex_lock(&kvm->lock);
3386 if (kvm_get_vcpu_by_id(kvm, id)) {
3388 goto unlock_vcpu_destroy;
3391 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3392 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
3394 /* Now it's all set up, let userspace reach it */
3396 r = create_vcpu_fd(vcpu);
3398 kvm_put_kvm_no_destroy(kvm);
3399 goto unlock_vcpu_destroy;
3402 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
3405 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3406 * before kvm->online_vcpu's incremented value.
3409 atomic_inc(&kvm->online_vcpus);
3411 mutex_unlock(&kvm->lock);
3412 kvm_arch_vcpu_postcreate(vcpu);
3413 kvm_create_vcpu_debugfs(vcpu);
3416 unlock_vcpu_destroy:
3417 mutex_unlock(&kvm->lock);
3418 kvm_dirty_ring_free(&vcpu->dirty_ring);
3420 kvm_arch_vcpu_destroy(vcpu);
3422 free_page((unsigned long)vcpu->run);
3424 kmem_cache_free(kvm_vcpu_cache, vcpu);
3426 mutex_lock(&kvm->lock);
3427 kvm->created_vcpus--;
3428 mutex_unlock(&kvm->lock);
3432 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3435 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3436 vcpu->sigset_active = 1;
3437 vcpu->sigset = *sigset;
3439 vcpu->sigset_active = 0;
3443 static long kvm_vcpu_ioctl(struct file *filp,
3444 unsigned int ioctl, unsigned long arg)
3446 struct kvm_vcpu *vcpu = filp->private_data;
3447 void __user *argp = (void __user *)arg;
3449 struct kvm_fpu *fpu = NULL;
3450 struct kvm_sregs *kvm_sregs = NULL;
3452 if (vcpu->kvm->mm != current->mm)
3455 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3459 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3460 * execution; mutex_lock() would break them.
3462 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3463 if (r != -ENOIOCTLCMD)
3466 if (mutex_lock_killable(&vcpu->mutex))
3474 oldpid = rcu_access_pointer(vcpu->pid);
3475 if (unlikely(oldpid != task_pid(current))) {
3476 /* The thread running this VCPU changed. */
3479 r = kvm_arch_vcpu_run_pid_change(vcpu);
3483 newpid = get_task_pid(current, PIDTYPE_PID);
3484 rcu_assign_pointer(vcpu->pid, newpid);
3489 r = kvm_arch_vcpu_ioctl_run(vcpu);
3490 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3493 case KVM_GET_REGS: {
3494 struct kvm_regs *kvm_regs;
3497 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3500 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3504 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3511 case KVM_SET_REGS: {
3512 struct kvm_regs *kvm_regs;
3514 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3515 if (IS_ERR(kvm_regs)) {
3516 r = PTR_ERR(kvm_regs);
3519 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3523 case KVM_GET_SREGS: {
3524 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3525 GFP_KERNEL_ACCOUNT);
3529 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3533 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3538 case KVM_SET_SREGS: {
3539 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3540 if (IS_ERR(kvm_sregs)) {
3541 r = PTR_ERR(kvm_sregs);
3545 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3548 case KVM_GET_MP_STATE: {
3549 struct kvm_mp_state mp_state;
3551 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3555 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3560 case KVM_SET_MP_STATE: {
3561 struct kvm_mp_state mp_state;
3564 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3566 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3569 case KVM_TRANSLATE: {
3570 struct kvm_translation tr;
3573 if (copy_from_user(&tr, argp, sizeof(tr)))
3575 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3579 if (copy_to_user(argp, &tr, sizeof(tr)))
3584 case KVM_SET_GUEST_DEBUG: {
3585 struct kvm_guest_debug dbg;
3588 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3590 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3593 case KVM_SET_SIGNAL_MASK: {
3594 struct kvm_signal_mask __user *sigmask_arg = argp;
3595 struct kvm_signal_mask kvm_sigmask;
3596 sigset_t sigset, *p;
3601 if (copy_from_user(&kvm_sigmask, argp,
3602 sizeof(kvm_sigmask)))
3605 if (kvm_sigmask.len != sizeof(sigset))
3608 if (copy_from_user(&sigset, sigmask_arg->sigset,
3613 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3617 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
3621 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3625 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3631 fpu = memdup_user(argp, sizeof(*fpu));
3637 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3641 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3644 mutex_unlock(&vcpu->mutex);
3650 #ifdef CONFIG_KVM_COMPAT
3651 static long kvm_vcpu_compat_ioctl(struct file *filp,
3652 unsigned int ioctl, unsigned long arg)
3654 struct kvm_vcpu *vcpu = filp->private_data;
3655 void __user *argp = compat_ptr(arg);
3658 if (vcpu->kvm->mm != current->mm)
3662 case KVM_SET_SIGNAL_MASK: {
3663 struct kvm_signal_mask __user *sigmask_arg = argp;
3664 struct kvm_signal_mask kvm_sigmask;
3669 if (copy_from_user(&kvm_sigmask, argp,
3670 sizeof(kvm_sigmask)))
3673 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3676 if (get_compat_sigset(&sigset,
3677 (compat_sigset_t __user *)sigmask_arg->sigset))
3679 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3681 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3685 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3693 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3695 struct kvm_device *dev = filp->private_data;
3698 return dev->ops->mmap(dev, vma);
3703 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3704 int (*accessor)(struct kvm_device *dev,
3705 struct kvm_device_attr *attr),
3708 struct kvm_device_attr attr;
3713 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3716 return accessor(dev, &attr);
3719 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3722 struct kvm_device *dev = filp->private_data;
3724 if (dev->kvm->mm != current->mm)
3728 case KVM_SET_DEVICE_ATTR:
3729 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3730 case KVM_GET_DEVICE_ATTR:
3731 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3732 case KVM_HAS_DEVICE_ATTR:
3733 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3735 if (dev->ops->ioctl)
3736 return dev->ops->ioctl(dev, ioctl, arg);
3742 static int kvm_device_release(struct inode *inode, struct file *filp)
3744 struct kvm_device *dev = filp->private_data;
3745 struct kvm *kvm = dev->kvm;
3747 if (dev->ops->release) {
3748 mutex_lock(&kvm->lock);
3749 list_del(&dev->vm_node);
3750 dev->ops->release(dev);
3751 mutex_unlock(&kvm->lock);
3758 static const struct file_operations kvm_device_fops = {
3759 .unlocked_ioctl = kvm_device_ioctl,
3760 .release = kvm_device_release,
3761 KVM_COMPAT(kvm_device_ioctl),
3762 .mmap = kvm_device_mmap,
3765 struct kvm_device *kvm_device_from_filp(struct file *filp)
3767 if (filp->f_op != &kvm_device_fops)
3770 return filp->private_data;
3773 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
3774 #ifdef CONFIG_KVM_MPIC
3775 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3776 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3780 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
3782 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3785 if (kvm_device_ops_table[type] != NULL)
3788 kvm_device_ops_table[type] = ops;
3792 void kvm_unregister_device_ops(u32 type)
3794 if (kvm_device_ops_table[type] != NULL)
3795 kvm_device_ops_table[type] = NULL;
3798 static int kvm_ioctl_create_device(struct kvm *kvm,
3799 struct kvm_create_device *cd)
3801 const struct kvm_device_ops *ops = NULL;
3802 struct kvm_device *dev;
3803 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
3807 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3810 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3811 ops = kvm_device_ops_table[type];
3818 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
3825 mutex_lock(&kvm->lock);
3826 ret = ops->create(dev, type);
3828 mutex_unlock(&kvm->lock);
3832 list_add(&dev->vm_node, &kvm->devices);
3833 mutex_unlock(&kvm->lock);
3839 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3841 kvm_put_kvm_no_destroy(kvm);
3842 mutex_lock(&kvm->lock);
3843 list_del(&dev->vm_node);
3844 mutex_unlock(&kvm->lock);
3853 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3856 case KVM_CAP_USER_MEMORY:
3857 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3858 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3859 case KVM_CAP_INTERNAL_ERROR_DATA:
3860 #ifdef CONFIG_HAVE_KVM_MSI
3861 case KVM_CAP_SIGNAL_MSI:
3863 #ifdef CONFIG_HAVE_KVM_IRQFD
3865 case KVM_CAP_IRQFD_RESAMPLE:
3867 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3868 case KVM_CAP_CHECK_EXTENSION_VM:
3869 case KVM_CAP_ENABLE_CAP_VM:
3870 case KVM_CAP_HALT_POLL:
3872 #ifdef CONFIG_KVM_MMIO
3873 case KVM_CAP_COALESCED_MMIO:
3874 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3875 case KVM_CAP_COALESCED_PIO:
3878 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3879 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3880 return KVM_DIRTY_LOG_MANUAL_CAPS;
3882 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3883 case KVM_CAP_IRQ_ROUTING:
3884 return KVM_MAX_IRQ_ROUTES;
3886 #if KVM_ADDRESS_SPACE_NUM > 1
3887 case KVM_CAP_MULTI_ADDRESS_SPACE:
3888 return KVM_ADDRESS_SPACE_NUM;
3890 case KVM_CAP_NR_MEMSLOTS:
3891 return KVM_USER_MEM_SLOTS;
3892 case KVM_CAP_DIRTY_LOG_RING:
3893 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3894 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
3901 return kvm_vm_ioctl_check_extension(kvm, arg);
3904 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
3908 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
3911 /* the size should be power of 2 */
3912 if (!size || (size & (size - 1)))
3915 /* Should be bigger to keep the reserved entries, or a page */
3916 if (size < kvm_dirty_ring_get_rsvd_entries() *
3917 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
3920 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
3921 sizeof(struct kvm_dirty_gfn))
3924 /* We only allow it to set once */
3925 if (kvm->dirty_ring_size)
3928 mutex_lock(&kvm->lock);
3930 if (kvm->created_vcpus) {
3931 /* We don't allow to change this value after vcpu created */
3934 kvm->dirty_ring_size = size;
3938 mutex_unlock(&kvm->lock);
3942 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
3945 struct kvm_vcpu *vcpu;
3948 if (!kvm->dirty_ring_size)
3951 mutex_lock(&kvm->slots_lock);
3953 kvm_for_each_vcpu(i, vcpu, kvm)
3954 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
3956 mutex_unlock(&kvm->slots_lock);
3959 kvm_flush_remote_tlbs(kvm);
3964 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3965 struct kvm_enable_cap *cap)
3970 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3971 struct kvm_enable_cap *cap)
3974 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3975 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
3976 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
3978 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
3979 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
3981 if (cap->flags || (cap->args[0] & ~allowed_options))
3983 kvm->manual_dirty_log_protect = cap->args[0];
3987 case KVM_CAP_HALT_POLL: {
3988 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
3991 kvm->max_halt_poll_ns = cap->args[0];
3994 case KVM_CAP_DIRTY_LOG_RING:
3995 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
3997 return kvm_vm_ioctl_enable_cap(kvm, cap);
4001 static long kvm_vm_ioctl(struct file *filp,
4002 unsigned int ioctl, unsigned long arg)
4004 struct kvm *kvm = filp->private_data;
4005 void __user *argp = (void __user *)arg;
4008 if (kvm->mm != current->mm)
4011 case KVM_CREATE_VCPU:
4012 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4014 case KVM_ENABLE_CAP: {
4015 struct kvm_enable_cap cap;
4018 if (copy_from_user(&cap, argp, sizeof(cap)))
4020 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4023 case KVM_SET_USER_MEMORY_REGION: {
4024 struct kvm_userspace_memory_region kvm_userspace_mem;
4027 if (copy_from_user(&kvm_userspace_mem, argp,
4028 sizeof(kvm_userspace_mem)))
4031 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4034 case KVM_GET_DIRTY_LOG: {
4035 struct kvm_dirty_log log;
4038 if (copy_from_user(&log, argp, sizeof(log)))
4040 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4043 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4044 case KVM_CLEAR_DIRTY_LOG: {
4045 struct kvm_clear_dirty_log log;
4048 if (copy_from_user(&log, argp, sizeof(log)))
4050 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4054 #ifdef CONFIG_KVM_MMIO
4055 case KVM_REGISTER_COALESCED_MMIO: {
4056 struct kvm_coalesced_mmio_zone zone;
4059 if (copy_from_user(&zone, argp, sizeof(zone)))
4061 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4064 case KVM_UNREGISTER_COALESCED_MMIO: {
4065 struct kvm_coalesced_mmio_zone zone;
4068 if (copy_from_user(&zone, argp, sizeof(zone)))
4070 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4075 struct kvm_irqfd data;
4078 if (copy_from_user(&data, argp, sizeof(data)))
4080 r = kvm_irqfd(kvm, &data);
4083 case KVM_IOEVENTFD: {
4084 struct kvm_ioeventfd data;
4087 if (copy_from_user(&data, argp, sizeof(data)))
4089 r = kvm_ioeventfd(kvm, &data);
4092 #ifdef CONFIG_HAVE_KVM_MSI
4093 case KVM_SIGNAL_MSI: {
4097 if (copy_from_user(&msi, argp, sizeof(msi)))
4099 r = kvm_send_userspace_msi(kvm, &msi);
4103 #ifdef __KVM_HAVE_IRQ_LINE
4104 case KVM_IRQ_LINE_STATUS:
4105 case KVM_IRQ_LINE: {
4106 struct kvm_irq_level irq_event;
4109 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4112 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4113 ioctl == KVM_IRQ_LINE_STATUS);
4118 if (ioctl == KVM_IRQ_LINE_STATUS) {
4119 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4127 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4128 case KVM_SET_GSI_ROUTING: {
4129 struct kvm_irq_routing routing;
4130 struct kvm_irq_routing __user *urouting;
4131 struct kvm_irq_routing_entry *entries = NULL;
4134 if (copy_from_user(&routing, argp, sizeof(routing)))
4137 if (!kvm_arch_can_set_irq_routing(kvm))
4139 if (routing.nr > KVM_MAX_IRQ_ROUTES)
4145 entries = vmemdup_user(urouting->entries,
4146 array_size(sizeof(*entries),
4148 if (IS_ERR(entries)) {
4149 r = PTR_ERR(entries);
4153 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4158 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4159 case KVM_CREATE_DEVICE: {
4160 struct kvm_create_device cd;
4163 if (copy_from_user(&cd, argp, sizeof(cd)))
4166 r = kvm_ioctl_create_device(kvm, &cd);
4171 if (copy_to_user(argp, &cd, sizeof(cd)))
4177 case KVM_CHECK_EXTENSION:
4178 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4180 case KVM_RESET_DIRTY_RINGS:
4181 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4184 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4190 #ifdef CONFIG_KVM_COMPAT
4191 struct compat_kvm_dirty_log {
4195 compat_uptr_t dirty_bitmap; /* one bit per page */
4200 struct compat_kvm_clear_dirty_log {
4205 compat_uptr_t dirty_bitmap; /* one bit per page */
4210 static long kvm_vm_compat_ioctl(struct file *filp,
4211 unsigned int ioctl, unsigned long arg)
4213 struct kvm *kvm = filp->private_data;
4216 if (kvm->mm != current->mm)
4219 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4220 case KVM_CLEAR_DIRTY_LOG: {
4221 struct compat_kvm_clear_dirty_log compat_log;
4222 struct kvm_clear_dirty_log log;
4224 if (copy_from_user(&compat_log, (void __user *)arg,
4225 sizeof(compat_log)))
4227 log.slot = compat_log.slot;
4228 log.num_pages = compat_log.num_pages;
4229 log.first_page = compat_log.first_page;
4230 log.padding2 = compat_log.padding2;
4231 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4233 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4237 case KVM_GET_DIRTY_LOG: {
4238 struct compat_kvm_dirty_log compat_log;
4239 struct kvm_dirty_log log;
4241 if (copy_from_user(&compat_log, (void __user *)arg,
4242 sizeof(compat_log)))
4244 log.slot = compat_log.slot;
4245 log.padding1 = compat_log.padding1;
4246 log.padding2 = compat_log.padding2;
4247 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4249 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4253 r = kvm_vm_ioctl(filp, ioctl, arg);
4259 static struct file_operations kvm_vm_fops = {
4260 .release = kvm_vm_release,
4261 .unlocked_ioctl = kvm_vm_ioctl,
4262 .llseek = noop_llseek,
4263 KVM_COMPAT(kvm_vm_compat_ioctl),
4266 bool file_is_kvm(struct file *file)
4268 return file && file->f_op == &kvm_vm_fops;
4270 EXPORT_SYMBOL_GPL(file_is_kvm);
4272 static int kvm_dev_ioctl_create_vm(unsigned long type)
4278 kvm = kvm_create_vm(type);
4280 return PTR_ERR(kvm);
4281 #ifdef CONFIG_KVM_MMIO
4282 r = kvm_coalesced_mmio_init(kvm);
4286 r = get_unused_fd_flags(O_CLOEXEC);
4290 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4298 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4299 * already set, with ->release() being kvm_vm_release(). In error
4300 * cases it will be called by the final fput(file) and will take
4301 * care of doing kvm_put_kvm(kvm).
4303 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4308 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4310 fd_install(r, file);
4318 static long kvm_dev_ioctl(struct file *filp,
4319 unsigned int ioctl, unsigned long arg)
4324 case KVM_GET_API_VERSION:
4327 r = KVM_API_VERSION;
4330 r = kvm_dev_ioctl_create_vm(arg);
4332 case KVM_CHECK_EXTENSION:
4333 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4335 case KVM_GET_VCPU_MMAP_SIZE:
4338 r = PAGE_SIZE; /* struct kvm_run */
4340 r += PAGE_SIZE; /* pio data page */
4342 #ifdef CONFIG_KVM_MMIO
4343 r += PAGE_SIZE; /* coalesced mmio ring page */
4346 case KVM_TRACE_ENABLE:
4347 case KVM_TRACE_PAUSE:
4348 case KVM_TRACE_DISABLE:
4352 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4358 static struct file_operations kvm_chardev_ops = {
4359 .unlocked_ioctl = kvm_dev_ioctl,
4360 .llseek = noop_llseek,
4361 KVM_COMPAT(kvm_dev_ioctl),
4364 static struct miscdevice kvm_dev = {
4370 static void hardware_enable_nolock(void *junk)
4372 int cpu = raw_smp_processor_id();
4375 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4378 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4380 r = kvm_arch_hardware_enable();
4383 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4384 atomic_inc(&hardware_enable_failed);
4385 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4389 static int kvm_starting_cpu(unsigned int cpu)
4391 raw_spin_lock(&kvm_count_lock);
4392 if (kvm_usage_count)
4393 hardware_enable_nolock(NULL);
4394 raw_spin_unlock(&kvm_count_lock);
4398 static void hardware_disable_nolock(void *junk)
4400 int cpu = raw_smp_processor_id();
4402 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4404 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4405 kvm_arch_hardware_disable();
4408 static int kvm_dying_cpu(unsigned int cpu)
4410 raw_spin_lock(&kvm_count_lock);
4411 if (kvm_usage_count)
4412 hardware_disable_nolock(NULL);
4413 raw_spin_unlock(&kvm_count_lock);
4417 static void hardware_disable_all_nolock(void)
4419 BUG_ON(!kvm_usage_count);
4422 if (!kvm_usage_count)
4423 on_each_cpu(hardware_disable_nolock, NULL, 1);
4426 static void hardware_disable_all(void)
4428 raw_spin_lock(&kvm_count_lock);
4429 hardware_disable_all_nolock();
4430 raw_spin_unlock(&kvm_count_lock);
4433 static int hardware_enable_all(void)
4437 raw_spin_lock(&kvm_count_lock);
4440 if (kvm_usage_count == 1) {
4441 atomic_set(&hardware_enable_failed, 0);
4442 on_each_cpu(hardware_enable_nolock, NULL, 1);
4444 if (atomic_read(&hardware_enable_failed)) {
4445 hardware_disable_all_nolock();
4450 raw_spin_unlock(&kvm_count_lock);
4455 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4459 * Some (well, at least mine) BIOSes hang on reboot if
4462 * And Intel TXT required VMX off for all cpu when system shutdown.
4464 pr_info("kvm: exiting hardware virtualization\n");
4465 kvm_rebooting = true;
4466 on_each_cpu(hardware_disable_nolock, NULL, 1);
4470 static struct notifier_block kvm_reboot_notifier = {
4471 .notifier_call = kvm_reboot,
4475 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4479 for (i = 0; i < bus->dev_count; i++) {
4480 struct kvm_io_device *pos = bus->range[i].dev;
4482 kvm_iodevice_destructor(pos);
4487 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4488 const struct kvm_io_range *r2)
4490 gpa_t addr1 = r1->addr;
4491 gpa_t addr2 = r2->addr;
4496 /* If r2->len == 0, match the exact address. If r2->len != 0,
4497 * accept any overlapping write. Any order is acceptable for
4498 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4499 * we process all of them.
4512 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4514 return kvm_io_bus_cmp(p1, p2);
4517 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4518 gpa_t addr, int len)
4520 struct kvm_io_range *range, key;
4523 key = (struct kvm_io_range) {
4528 range = bsearch(&key, bus->range, bus->dev_count,
4529 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4533 off = range - bus->range;
4535 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4541 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4542 struct kvm_io_range *range, const void *val)
4546 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4550 while (idx < bus->dev_count &&
4551 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4552 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4561 /* kvm_io_bus_write - called under kvm->slots_lock */
4562 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4563 int len, const void *val)
4565 struct kvm_io_bus *bus;
4566 struct kvm_io_range range;
4569 range = (struct kvm_io_range) {
4574 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4577 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4578 return r < 0 ? r : 0;
4580 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
4582 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4583 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4584 gpa_t addr, int len, const void *val, long cookie)
4586 struct kvm_io_bus *bus;
4587 struct kvm_io_range range;
4589 range = (struct kvm_io_range) {
4594 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4598 /* First try the device referenced by cookie. */
4599 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4600 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4601 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4606 * cookie contained garbage; fall back to search and return the
4607 * correct cookie value.
4609 return __kvm_io_bus_write(vcpu, bus, &range, val);
4612 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4613 struct kvm_io_range *range, void *val)
4617 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4621 while (idx < bus->dev_count &&
4622 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4623 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4632 /* kvm_io_bus_read - called under kvm->slots_lock */
4633 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4636 struct kvm_io_bus *bus;
4637 struct kvm_io_range range;
4640 range = (struct kvm_io_range) {
4645 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4648 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4649 return r < 0 ? r : 0;
4652 /* Caller must hold slots_lock. */
4653 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4654 int len, struct kvm_io_device *dev)
4657 struct kvm_io_bus *new_bus, *bus;
4658 struct kvm_io_range range;
4660 bus = kvm_get_bus(kvm, bus_idx);
4664 /* exclude ioeventfd which is limited by maximum fd */
4665 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
4668 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
4669 GFP_KERNEL_ACCOUNT);
4673 range = (struct kvm_io_range) {
4679 for (i = 0; i < bus->dev_count; i++)
4680 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4683 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4684 new_bus->dev_count++;
4685 new_bus->range[i] = range;
4686 memcpy(new_bus->range + i + 1, bus->range + i,
4687 (bus->dev_count - i) * sizeof(struct kvm_io_range));
4688 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4689 synchronize_srcu_expedited(&kvm->srcu);
4695 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4696 struct kvm_io_device *dev)
4699 struct kvm_io_bus *new_bus, *bus;
4701 lockdep_assert_held(&kvm->slots_lock);
4703 bus = kvm_get_bus(kvm, bus_idx);
4707 for (i = 0; i < bus->dev_count; i++) {
4708 if (bus->range[i].dev == dev) {
4713 if (i == bus->dev_count)
4716 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
4717 GFP_KERNEL_ACCOUNT);
4719 memcpy(new_bus, bus, struct_size(bus, range, i));
4720 new_bus->dev_count--;
4721 memcpy(new_bus->range + i, bus->range + i + 1,
4722 flex_array_size(new_bus, range, new_bus->dev_count - i));
4725 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4726 synchronize_srcu_expedited(&kvm->srcu);
4728 /* Destroy the old bus _after_ installing the (null) bus. */
4730 pr_err("kvm: failed to shrink bus, removing it completely\n");
4731 for (j = 0; j < bus->dev_count; j++) {
4734 kvm_iodevice_destructor(bus->range[j].dev);
4739 return new_bus ? 0 : -ENOMEM;
4742 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4745 struct kvm_io_bus *bus;
4746 int dev_idx, srcu_idx;
4747 struct kvm_io_device *iodev = NULL;
4749 srcu_idx = srcu_read_lock(&kvm->srcu);
4751 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
4755 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4759 iodev = bus->range[dev_idx].dev;
4762 srcu_read_unlock(&kvm->srcu, srcu_idx);
4766 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4768 static int kvm_debugfs_open(struct inode *inode, struct file *file,
4769 int (*get)(void *, u64 *), int (*set)(void *, u64),
4772 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4775 /* The debugfs files are a reference to the kvm struct which
4776 * is still valid when kvm_destroy_vm is called.
4777 * To avoid the race between open and the removal of the debugfs
4778 * directory we test against the users count.
4780 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
4783 if (simple_attr_open(inode, file, get,
4784 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4787 kvm_put_kvm(stat_data->kvm);
4794 static int kvm_debugfs_release(struct inode *inode, struct file *file)
4796 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4799 simple_attr_release(inode, file);
4800 kvm_put_kvm(stat_data->kvm);
4805 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
4807 *val = *(ulong *)((void *)kvm + offset);
4812 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
4814 *(ulong *)((void *)kvm + offset) = 0;
4819 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
4822 struct kvm_vcpu *vcpu;
4826 kvm_for_each_vcpu(i, vcpu, kvm)
4827 *val += *(u64 *)((void *)vcpu + offset);
4832 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
4835 struct kvm_vcpu *vcpu;
4837 kvm_for_each_vcpu(i, vcpu, kvm)
4838 *(u64 *)((void *)vcpu + offset) = 0;
4843 static int kvm_stat_data_get(void *data, u64 *val)
4846 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4848 switch (stat_data->dbgfs_item->kind) {
4850 r = kvm_get_stat_per_vm(stat_data->kvm,
4851 stat_data->dbgfs_item->offset, val);
4854 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4855 stat_data->dbgfs_item->offset, val);
4862 static int kvm_stat_data_clear(void *data, u64 val)
4865 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4870 switch (stat_data->dbgfs_item->kind) {
4872 r = kvm_clear_stat_per_vm(stat_data->kvm,
4873 stat_data->dbgfs_item->offset);
4876 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4877 stat_data->dbgfs_item->offset);
4884 static int kvm_stat_data_open(struct inode *inode, struct file *file)
4886 __simple_attr_check_format("%llu\n", 0ull);
4887 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
4888 kvm_stat_data_clear, "%llu\n");
4891 static const struct file_operations stat_fops_per_vm = {
4892 .owner = THIS_MODULE,
4893 .open = kvm_stat_data_open,
4894 .release = kvm_debugfs_release,
4895 .read = simple_attr_read,
4896 .write = simple_attr_write,
4897 .llseek = no_llseek,
4900 static int vm_stat_get(void *_offset, u64 *val)
4902 unsigned offset = (long)_offset;
4907 mutex_lock(&kvm_lock);
4908 list_for_each_entry(kvm, &vm_list, vm_list) {
4909 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
4912 mutex_unlock(&kvm_lock);
4916 static int vm_stat_clear(void *_offset, u64 val)
4918 unsigned offset = (long)_offset;
4924 mutex_lock(&kvm_lock);
4925 list_for_each_entry(kvm, &vm_list, vm_list) {
4926 kvm_clear_stat_per_vm(kvm, offset);
4928 mutex_unlock(&kvm_lock);
4933 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
4935 static int vcpu_stat_get(void *_offset, u64 *val)
4937 unsigned offset = (long)_offset;
4942 mutex_lock(&kvm_lock);
4943 list_for_each_entry(kvm, &vm_list, vm_list) {
4944 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
4947 mutex_unlock(&kvm_lock);
4951 static int vcpu_stat_clear(void *_offset, u64 val)
4953 unsigned offset = (long)_offset;
4959 mutex_lock(&kvm_lock);
4960 list_for_each_entry(kvm, &vm_list, vm_list) {
4961 kvm_clear_stat_per_vcpu(kvm, offset);
4963 mutex_unlock(&kvm_lock);
4968 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4971 static const struct file_operations *stat_fops[] = {
4972 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4973 [KVM_STAT_VM] = &vm_stat_fops,
4976 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4978 struct kobj_uevent_env *env;
4979 unsigned long long created, active;
4981 if (!kvm_dev.this_device || !kvm)
4984 mutex_lock(&kvm_lock);
4985 if (type == KVM_EVENT_CREATE_VM) {
4986 kvm_createvm_count++;
4988 } else if (type == KVM_EVENT_DESTROY_VM) {
4991 created = kvm_createvm_count;
4992 active = kvm_active_vms;
4993 mutex_unlock(&kvm_lock);
4995 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
4999 add_uevent_var(env, "CREATED=%llu", created);
5000 add_uevent_var(env, "COUNT=%llu", active);
5002 if (type == KVM_EVENT_CREATE_VM) {
5003 add_uevent_var(env, "EVENT=create");
5004 kvm->userspace_pid = task_pid_nr(current);
5005 } else if (type == KVM_EVENT_DESTROY_VM) {
5006 add_uevent_var(env, "EVENT=destroy");
5008 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5010 if (kvm->debugfs_dentry) {
5011 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5014 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5016 add_uevent_var(env, "STATS_PATH=%s", tmp);
5020 /* no need for checks, since we are adding at most only 5 keys */
5021 env->envp[env->envp_idx++] = NULL;
5022 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5026 static void kvm_init_debug(void)
5028 struct kvm_stats_debugfs_item *p;
5030 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5032 kvm_debugfs_num_entries = 0;
5033 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
5034 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
5035 kvm_debugfs_dir, (void *)(long)p->offset,
5036 stat_fops[p->kind]);
5040 static int kvm_suspend(void)
5042 if (kvm_usage_count)
5043 hardware_disable_nolock(NULL);
5047 static void kvm_resume(void)
5049 if (kvm_usage_count) {
5050 #ifdef CONFIG_LOCKDEP
5051 WARN_ON(lockdep_is_held(&kvm_count_lock));
5053 hardware_enable_nolock(NULL);
5057 static struct syscore_ops kvm_syscore_ops = {
5058 .suspend = kvm_suspend,
5059 .resume = kvm_resume,
5063 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5065 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5068 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5070 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5072 WRITE_ONCE(vcpu->preempted, false);
5073 WRITE_ONCE(vcpu->ready, false);
5075 __this_cpu_write(kvm_running_vcpu, vcpu);
5076 kvm_arch_sched_in(vcpu, cpu);
5077 kvm_arch_vcpu_load(vcpu, cpu);
5080 static void kvm_sched_out(struct preempt_notifier *pn,
5081 struct task_struct *next)
5083 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5085 if (current->state == TASK_RUNNING) {
5086 WRITE_ONCE(vcpu->preempted, true);
5087 WRITE_ONCE(vcpu->ready, true);
5089 kvm_arch_vcpu_put(vcpu);
5090 __this_cpu_write(kvm_running_vcpu, NULL);
5094 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5096 * We can disable preemption locally around accessing the per-CPU variable,
5097 * and use the resolved vcpu pointer after enabling preemption again,
5098 * because even if the current thread is migrated to another CPU, reading
5099 * the per-CPU value later will give us the same value as we update the
5100 * per-CPU variable in the preempt notifier handlers.
5102 struct kvm_vcpu *kvm_get_running_vcpu(void)
5104 struct kvm_vcpu *vcpu;
5107 vcpu = __this_cpu_read(kvm_running_vcpu);
5112 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5115 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5117 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5119 return &kvm_running_vcpu;
5122 struct kvm_cpu_compat_check {
5127 static void check_processor_compat(void *data)
5129 struct kvm_cpu_compat_check *c = data;
5131 *c->ret = kvm_arch_check_processor_compat(c->opaque);
5134 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5135 struct module *module)
5137 struct kvm_cpu_compat_check c;
5141 r = kvm_arch_init(opaque);
5146 * kvm_arch_init makes sure there's at most one caller
5147 * for architectures that support multiple implementations,
5148 * like intel and amd on x86.
5149 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5150 * conflicts in case kvm is already setup for another implementation.
5152 r = kvm_irqfd_init();
5156 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5161 r = kvm_arch_hardware_setup(opaque);
5167 for_each_online_cpu(cpu) {
5168 smp_call_function_single(cpu, check_processor_compat, &c, 1);
5173 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5174 kvm_starting_cpu, kvm_dying_cpu);
5177 register_reboot_notifier(&kvm_reboot_notifier);
5179 /* A kmem cache lets us meet the alignment requirements of fx_save. */
5181 vcpu_align = __alignof__(struct kvm_vcpu);
5183 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5185 offsetof(struct kvm_vcpu, arch),
5186 sizeof_field(struct kvm_vcpu, arch),
5188 if (!kvm_vcpu_cache) {
5193 r = kvm_async_pf_init();
5197 kvm_chardev_ops.owner = module;
5198 kvm_vm_fops.owner = module;
5199 kvm_vcpu_fops.owner = module;
5201 r = misc_register(&kvm_dev);
5203 pr_err("kvm: misc device register failed\n");
5207 register_syscore_ops(&kvm_syscore_ops);
5209 kvm_preempt_ops.sched_in = kvm_sched_in;
5210 kvm_preempt_ops.sched_out = kvm_sched_out;
5214 r = kvm_vfio_ops_init();
5220 kvm_async_pf_deinit();
5222 kmem_cache_destroy(kvm_vcpu_cache);
5224 unregister_reboot_notifier(&kvm_reboot_notifier);
5225 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5227 kvm_arch_hardware_unsetup();
5229 free_cpumask_var(cpus_hardware_enabled);
5237 EXPORT_SYMBOL_GPL(kvm_init);
5241 debugfs_remove_recursive(kvm_debugfs_dir);
5242 misc_deregister(&kvm_dev);
5243 kmem_cache_destroy(kvm_vcpu_cache);
5244 kvm_async_pf_deinit();
5245 unregister_syscore_ops(&kvm_syscore_ops);
5246 unregister_reboot_notifier(&kvm_reboot_notifier);
5247 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5248 on_each_cpu(hardware_disable_nolock, NULL, 1);
5249 kvm_arch_hardware_unsetup();
5252 free_cpumask_var(cpus_hardware_enabled);
5253 kvm_vfio_ops_exit();
5255 EXPORT_SYMBOL_GPL(kvm_exit);
5257 struct kvm_vm_worker_thread_context {
5259 struct task_struct *parent;
5260 struct completion init_done;
5261 kvm_vm_thread_fn_t thread_fn;
5266 static int kvm_vm_worker_thread(void *context)
5269 * The init_context is allocated on the stack of the parent thread, so
5270 * we have to locally copy anything that is needed beyond initialization
5272 struct kvm_vm_worker_thread_context *init_context = context;
5273 struct kvm *kvm = init_context->kvm;
5274 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5275 uintptr_t data = init_context->data;
5278 err = kthread_park(current);
5279 /* kthread_park(current) is never supposed to return an error */
5284 err = cgroup_attach_task_all(init_context->parent, current);
5286 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5291 set_user_nice(current, task_nice(init_context->parent));
5294 init_context->err = err;
5295 complete(&init_context->init_done);
5296 init_context = NULL;
5301 /* Wait to be woken up by the spawner before proceeding. */
5304 if (!kthread_should_stop())
5305 err = thread_fn(kvm, data);
5310 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5311 uintptr_t data, const char *name,
5312 struct task_struct **thread_ptr)
5314 struct kvm_vm_worker_thread_context init_context = {};
5315 struct task_struct *thread;
5318 init_context.kvm = kvm;
5319 init_context.parent = current;
5320 init_context.thread_fn = thread_fn;
5321 init_context.data = data;
5322 init_completion(&init_context.init_done);
5324 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5325 "%s-%d", name, task_pid_nr(current));
5327 return PTR_ERR(thread);
5329 /* kthread_run is never supposed to return NULL */
5330 WARN_ON(thread == NULL);
5332 wait_for_completion(&init_context.init_done);
5334 if (!init_context.err)
5335 *thread_ptr = thread;
5337 return init_context.err;