1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <kvm/iodev.h>
18 #include <linux/kvm_host.h>
19 #include <linux/kvm.h>
20 #include <linux/module.h>
21 #include <linux/errno.h>
22 #include <linux/percpu.h>
24 #include <linux/miscdevice.h>
25 #include <linux/vmalloc.h>
26 #include <linux/reboot.h>
27 #include <linux/debugfs.h>
28 #include <linux/highmem.h>
29 #include <linux/file.h>
30 #include <linux/syscore_ops.h>
31 #include <linux/cpu.h>
32 #include <linux/sched/signal.h>
33 #include <linux/sched/mm.h>
34 #include <linux/sched/stat.h>
35 #include <linux/cpumask.h>
36 #include <linux/smp.h>
37 #include <linux/anon_inodes.h>
38 #include <linux/profile.h>
39 #include <linux/kvm_para.h>
40 #include <linux/pagemap.h>
41 #include <linux/mman.h>
42 #include <linux/swap.h>
43 #include <linux/bitops.h>
44 #include <linux/spinlock.h>
45 #include <linux/compat.h>
46 #include <linux/srcu.h>
47 #include <linux/hugetlb.h>
48 #include <linux/slab.h>
49 #include <linux/sort.h>
50 #include <linux/bsearch.h>
52 #include <linux/lockdep.h>
53 #include <linux/kthread.h>
54 #include <linux/suspend.h>
56 #include <asm/processor.h>
57 #include <asm/ioctl.h>
58 #include <linux/uaccess.h>
60 #include "coalesced_mmio.h"
65 #define CREATE_TRACE_POINTS
66 #include <trace/events/kvm.h>
68 #include <linux/kvm_dirty_ring.h>
70 /* Worst case buffer size needed for holding an integer. */
71 #define ITOA_MAX_LEN 12
73 MODULE_AUTHOR("Qumranet");
74 MODULE_LICENSE("GPL");
76 /* Architectures should define their poll value according to the halt latency */
77 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
78 module_param(halt_poll_ns, uint, 0644);
79 EXPORT_SYMBOL_GPL(halt_poll_ns);
81 /* Default doubles per-vcpu halt_poll_ns. */
82 unsigned int halt_poll_ns_grow = 2;
83 module_param(halt_poll_ns_grow, uint, 0644);
84 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
86 /* The start value to grow halt_poll_ns from */
87 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
88 module_param(halt_poll_ns_grow_start, uint, 0644);
89 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
91 /* Default resets per-vcpu halt_poll_ns . */
92 unsigned int halt_poll_ns_shrink;
93 module_param(halt_poll_ns_shrink, uint, 0644);
94 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
99 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
102 DEFINE_MUTEX(kvm_lock);
103 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
106 static cpumask_var_t cpus_hardware_enabled;
107 static int kvm_usage_count;
108 static atomic_t hardware_enable_failed;
110 static struct kmem_cache *kvm_vcpu_cache;
112 static __read_mostly struct preempt_ops kvm_preempt_ops;
113 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
115 struct dentry *kvm_debugfs_dir;
116 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
118 static const struct file_operations stat_fops_per_vm;
120 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
122 #ifdef CONFIG_KVM_COMPAT
123 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
125 #define KVM_COMPAT(c) .compat_ioctl = (c)
128 * For architectures that don't implement a compat infrastructure,
129 * adopt a double line of defense:
130 * - Prevent a compat task from opening /dev/kvm
131 * - If the open has been done by a 64bit task, and the KVM fd
132 * passed to a compat task, let the ioctls fail.
134 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
135 unsigned long arg) { return -EINVAL; }
137 static int kvm_no_compat_open(struct inode *inode, struct file *file)
139 return is_compat_task() ? -ENODEV : 0;
141 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
142 .open = kvm_no_compat_open
144 static int hardware_enable_all(void);
145 static void hardware_disable_all(void);
147 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
149 __visible bool kvm_rebooting;
150 EXPORT_SYMBOL_GPL(kvm_rebooting);
152 #define KVM_EVENT_CREATE_VM 0
153 #define KVM_EVENT_DESTROY_VM 1
154 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
155 static unsigned long long kvm_createvm_count;
156 static unsigned long long kvm_active_vms;
158 static DEFINE_PER_CPU(cpumask_var_t, cpu_kick_mask);
160 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
161 unsigned long start, unsigned long end)
165 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
168 * The metadata used by is_zone_device_page() to determine whether or
169 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
170 * the device has been pinned, e.g. by get_user_pages(). WARN if the
171 * page_count() is zero to help detect bad usage of this helper.
173 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
176 return is_zone_device_page(pfn_to_page(pfn));
179 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
182 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
183 * perspective they are "normal" pages, albeit with slightly different
187 return PageReserved(pfn_to_page(pfn)) &&
189 !kvm_is_zone_device_pfn(pfn);
195 * Switches to specified vcpu, until a matching vcpu_put()
197 void vcpu_load(struct kvm_vcpu *vcpu)
201 __this_cpu_write(kvm_running_vcpu, vcpu);
202 preempt_notifier_register(&vcpu->preempt_notifier);
203 kvm_arch_vcpu_load(vcpu, cpu);
206 EXPORT_SYMBOL_GPL(vcpu_load);
208 void vcpu_put(struct kvm_vcpu *vcpu)
211 kvm_arch_vcpu_put(vcpu);
212 preempt_notifier_unregister(&vcpu->preempt_notifier);
213 __this_cpu_write(kvm_running_vcpu, NULL);
216 EXPORT_SYMBOL_GPL(vcpu_put);
218 /* TODO: merge with kvm_arch_vcpu_should_kick */
219 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
221 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
224 * We need to wait for the VCPU to reenable interrupts and get out of
225 * READING_SHADOW_PAGE_TABLES mode.
227 if (req & KVM_REQUEST_WAIT)
228 return mode != OUTSIDE_GUEST_MODE;
231 * Need to kick a running VCPU, but otherwise there is nothing to do.
233 return mode == IN_GUEST_MODE;
236 static void ack_flush(void *_completed)
240 static inline bool kvm_kick_many_cpus(struct cpumask *cpus, bool wait)
242 if (cpumask_empty(cpus))
245 smp_call_function_many(cpus, ack_flush, NULL, wait);
249 static void kvm_make_vcpu_request(struct kvm_vcpu *vcpu, unsigned int req,
250 struct cpumask *tmp, int current_cpu)
254 kvm_make_request(req, vcpu);
256 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
260 * Note, the vCPU could get migrated to a different pCPU at any point
261 * after kvm_request_needs_ipi(), which could result in sending an IPI
262 * to the previous pCPU. But, that's OK because the purpose of the IPI
263 * is to ensure the vCPU returns to OUTSIDE_GUEST_MODE, which is
264 * satisfied if the vCPU migrates. Entering READING_SHADOW_PAGE_TABLES
265 * after this point is also OK, as the requirement is only that KVM wait
266 * for vCPUs that were reading SPTEs _before_ any changes were
267 * finalized. See kvm_vcpu_kick() for more details on handling requests.
269 if (kvm_request_needs_ipi(vcpu, req)) {
270 cpu = READ_ONCE(vcpu->cpu);
271 if (cpu != -1 && cpu != current_cpu)
272 __cpumask_set_cpu(cpu, tmp);
276 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
277 unsigned long *vcpu_bitmap)
279 struct kvm_vcpu *vcpu;
280 struct cpumask *cpus;
286 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
289 for_each_set_bit(i, vcpu_bitmap, KVM_MAX_VCPUS) {
290 vcpu = kvm_get_vcpu(kvm, i);
293 kvm_make_vcpu_request(vcpu, req, cpus, me);
296 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
302 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
303 struct kvm_vcpu *except)
305 struct kvm_vcpu *vcpu;
306 struct cpumask *cpus;
313 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
316 kvm_for_each_vcpu(i, vcpu, kvm) {
319 kvm_make_vcpu_request(vcpu, req, cpus, me);
322 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
328 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
330 return kvm_make_all_cpus_request_except(kvm, req, NULL);
332 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
334 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
335 void kvm_flush_remote_tlbs(struct kvm *kvm)
337 ++kvm->stat.generic.remote_tlb_flush_requests;
340 * We want to publish modifications to the page tables before reading
341 * mode. Pairs with a memory barrier in arch-specific code.
342 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
343 * and smp_mb in walk_shadow_page_lockless_begin/end.
344 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
346 * There is already an smp_mb__after_atomic() before
347 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
350 if (!kvm_arch_flush_remote_tlb(kvm)
351 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
352 ++kvm->stat.generic.remote_tlb_flush;
354 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
357 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
358 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
361 gfp_flags |= mc->gfp_zero;
364 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
366 return (void *)__get_free_page(gfp_flags);
369 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
373 if (mc->nobjs >= min)
375 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
376 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
378 return mc->nobjs >= min ? 0 : -ENOMEM;
379 mc->objects[mc->nobjs++] = obj;
384 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
389 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
393 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
395 free_page((unsigned long)mc->objects[--mc->nobjs]);
399 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
403 if (WARN_ON(!mc->nobjs))
404 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
406 p = mc->objects[--mc->nobjs];
412 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
414 mutex_init(&vcpu->mutex);
419 #ifndef __KVM_HAVE_ARCH_WQP
420 rcuwait_init(&vcpu->wait);
422 kvm_async_pf_vcpu_init(vcpu);
424 kvm_vcpu_set_in_spin_loop(vcpu, false);
425 kvm_vcpu_set_dy_eligible(vcpu, false);
426 vcpu->preempted = false;
428 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
429 vcpu->last_used_slot = NULL;
432 static void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
434 kvm_dirty_ring_free(&vcpu->dirty_ring);
435 kvm_arch_vcpu_destroy(vcpu);
438 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
439 * the vcpu->pid pointer, and at destruction time all file descriptors
442 put_pid(rcu_dereference_protected(vcpu->pid, 1));
444 free_page((unsigned long)vcpu->run);
445 kmem_cache_free(kvm_vcpu_cache, vcpu);
448 void kvm_destroy_vcpus(struct kvm *kvm)
451 struct kvm_vcpu *vcpu;
453 kvm_for_each_vcpu(i, vcpu, kvm) {
454 kvm_vcpu_destroy(vcpu);
455 xa_erase(&kvm->vcpu_array, i);
458 atomic_set(&kvm->online_vcpus, 0);
460 EXPORT_SYMBOL_GPL(kvm_destroy_vcpus);
462 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
463 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
465 return container_of(mn, struct kvm, mmu_notifier);
468 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
469 struct mm_struct *mm,
470 unsigned long start, unsigned long end)
472 struct kvm *kvm = mmu_notifier_to_kvm(mn);
475 idx = srcu_read_lock(&kvm->srcu);
476 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
477 srcu_read_unlock(&kvm->srcu, idx);
480 typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
482 typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
485 struct kvm_hva_range {
489 hva_handler_t handler;
490 on_lock_fn_t on_lock;
496 * Use a dedicated stub instead of NULL to indicate that there is no callback
497 * function/handler. The compiler technically can't guarantee that a real
498 * function will have a non-zero address, and so it will generate code to
499 * check for !NULL, whereas comparing against a stub will be elided at compile
500 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
502 static void kvm_null_fn(void)
506 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
508 /* Iterate over each memslot intersecting [start, last] (inclusive) range */
509 #define kvm_for_each_memslot_in_hva_range(node, slots, start, last) \
510 for (node = interval_tree_iter_first(&slots->hva_tree, start, last); \
512 node = interval_tree_iter_next(node, start, last)) \
514 static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
515 const struct kvm_hva_range *range)
517 bool ret = false, locked = false;
518 struct kvm_gfn_range gfn_range;
519 struct kvm_memory_slot *slot;
520 struct kvm_memslots *slots;
523 if (WARN_ON_ONCE(range->end <= range->start))
526 /* A null handler is allowed if and only if on_lock() is provided. */
527 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
528 IS_KVM_NULL_FN(range->handler)))
531 idx = srcu_read_lock(&kvm->srcu);
533 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
534 struct interval_tree_node *node;
536 slots = __kvm_memslots(kvm, i);
537 kvm_for_each_memslot_in_hva_range(node, slots,
538 range->start, range->end - 1) {
539 unsigned long hva_start, hva_end;
541 slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]);
542 hva_start = max(range->start, slot->userspace_addr);
543 hva_end = min(range->end, slot->userspace_addr +
544 (slot->npages << PAGE_SHIFT));
547 * To optimize for the likely case where the address
548 * range is covered by zero or one memslots, don't
549 * bother making these conditional (to avoid writes on
550 * the second or later invocation of the handler).
552 gfn_range.pte = range->pte;
553 gfn_range.may_block = range->may_block;
556 * {gfn(page) | page intersects with [hva_start, hva_end)} =
557 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
559 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
560 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
561 gfn_range.slot = slot;
566 if (!IS_KVM_NULL_FN(range->on_lock))
567 range->on_lock(kvm, range->start, range->end);
568 if (IS_KVM_NULL_FN(range->handler))
571 ret |= range->handler(kvm, &gfn_range);
575 if (range->flush_on_ret && ret)
576 kvm_flush_remote_tlbs(kvm);
581 srcu_read_unlock(&kvm->srcu, idx);
583 /* The notifiers are averse to booleans. :-( */
587 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
591 hva_handler_t handler)
593 struct kvm *kvm = mmu_notifier_to_kvm(mn);
594 const struct kvm_hva_range range = {
599 .on_lock = (void *)kvm_null_fn,
600 .flush_on_ret = true,
604 return __kvm_handle_hva_range(kvm, &range);
607 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
610 hva_handler_t handler)
612 struct kvm *kvm = mmu_notifier_to_kvm(mn);
613 const struct kvm_hva_range range = {
618 .on_lock = (void *)kvm_null_fn,
619 .flush_on_ret = false,
623 return __kvm_handle_hva_range(kvm, &range);
625 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
626 struct mm_struct *mm,
627 unsigned long address,
630 struct kvm *kvm = mmu_notifier_to_kvm(mn);
632 trace_kvm_set_spte_hva(address);
635 * .change_pte() must be surrounded by .invalidate_range_{start,end}().
636 * If mmu_notifier_count is zero, then no in-progress invalidations,
637 * including this one, found a relevant memslot at start(); rechecking
638 * memslots here is unnecessary. Note, a false positive (count elevated
639 * by a different invalidation) is sub-optimal but functionally ok.
641 WARN_ON_ONCE(!READ_ONCE(kvm->mn_active_invalidate_count));
642 if (!READ_ONCE(kvm->mmu_notifier_count))
645 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
648 void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
652 * The count increase must become visible at unlock time as no
653 * spte can be established without taking the mmu_lock and
654 * count is also read inside the mmu_lock critical section.
656 kvm->mmu_notifier_count++;
657 if (likely(kvm->mmu_notifier_count == 1)) {
658 kvm->mmu_notifier_range_start = start;
659 kvm->mmu_notifier_range_end = end;
662 * Fully tracking multiple concurrent ranges has dimishing
663 * returns. Keep things simple and just find the minimal range
664 * which includes the current and new ranges. As there won't be
665 * enough information to subtract a range after its invalidate
666 * completes, any ranges invalidated concurrently will
667 * accumulate and persist until all outstanding invalidates
670 kvm->mmu_notifier_range_start =
671 min(kvm->mmu_notifier_range_start, start);
672 kvm->mmu_notifier_range_end =
673 max(kvm->mmu_notifier_range_end, end);
677 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
678 const struct mmu_notifier_range *range)
680 struct kvm *kvm = mmu_notifier_to_kvm(mn);
681 const struct kvm_hva_range hva_range = {
682 .start = range->start,
685 .handler = kvm_unmap_gfn_range,
686 .on_lock = kvm_inc_notifier_count,
687 .flush_on_ret = true,
688 .may_block = mmu_notifier_range_blockable(range),
691 trace_kvm_unmap_hva_range(range->start, range->end);
694 * Prevent memslot modification between range_start() and range_end()
695 * so that conditionally locking provides the same result in both
696 * functions. Without that guarantee, the mmu_notifier_count
697 * adjustments will be imbalanced.
699 * Pairs with the decrement in range_end().
701 spin_lock(&kvm->mn_invalidate_lock);
702 kvm->mn_active_invalidate_count++;
703 spin_unlock(&kvm->mn_invalidate_lock);
705 gfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end,
706 hva_range.may_block);
708 __kvm_handle_hva_range(kvm, &hva_range);
713 void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
717 * This sequence increase will notify the kvm page fault that
718 * the page that is going to be mapped in the spte could have
721 kvm->mmu_notifier_seq++;
724 * The above sequence increase must be visible before the
725 * below count decrease, which is ensured by the smp_wmb above
726 * in conjunction with the smp_rmb in mmu_notifier_retry().
728 kvm->mmu_notifier_count--;
731 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
732 const struct mmu_notifier_range *range)
734 struct kvm *kvm = mmu_notifier_to_kvm(mn);
735 const struct kvm_hva_range hva_range = {
736 .start = range->start,
739 .handler = (void *)kvm_null_fn,
740 .on_lock = kvm_dec_notifier_count,
741 .flush_on_ret = false,
742 .may_block = mmu_notifier_range_blockable(range),
746 __kvm_handle_hva_range(kvm, &hva_range);
748 /* Pairs with the increment in range_start(). */
749 spin_lock(&kvm->mn_invalidate_lock);
750 wake = (--kvm->mn_active_invalidate_count == 0);
751 spin_unlock(&kvm->mn_invalidate_lock);
754 * There can only be one waiter, since the wait happens under
758 rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
760 BUG_ON(kvm->mmu_notifier_count < 0);
763 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
764 struct mm_struct *mm,
768 trace_kvm_age_hva(start, end);
770 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
773 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
774 struct mm_struct *mm,
778 trace_kvm_age_hva(start, end);
781 * Even though we do not flush TLB, this will still adversely
782 * affect performance on pre-Haswell Intel EPT, where there is
783 * no EPT Access Bit to clear so that we have to tear down EPT
784 * tables instead. If we find this unacceptable, we can always
785 * add a parameter to kvm_age_hva so that it effectively doesn't
786 * do anything on clear_young.
788 * Also note that currently we never issue secondary TLB flushes
789 * from clear_young, leaving this job up to the regular system
790 * cadence. If we find this inaccurate, we might come up with a
791 * more sophisticated heuristic later.
793 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
796 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
797 struct mm_struct *mm,
798 unsigned long address)
800 trace_kvm_test_age_hva(address);
802 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
806 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
807 struct mm_struct *mm)
809 struct kvm *kvm = mmu_notifier_to_kvm(mn);
812 idx = srcu_read_lock(&kvm->srcu);
813 kvm_arch_flush_shadow_all(kvm);
814 srcu_read_unlock(&kvm->srcu, idx);
817 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
818 .invalidate_range = kvm_mmu_notifier_invalidate_range,
819 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
820 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
821 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
822 .clear_young = kvm_mmu_notifier_clear_young,
823 .test_young = kvm_mmu_notifier_test_young,
824 .change_pte = kvm_mmu_notifier_change_pte,
825 .release = kvm_mmu_notifier_release,
828 static int kvm_init_mmu_notifier(struct kvm *kvm)
830 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
831 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
834 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
836 static int kvm_init_mmu_notifier(struct kvm *kvm)
841 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
843 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
844 static int kvm_pm_notifier_call(struct notifier_block *bl,
848 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
850 return kvm_arch_pm_notifier(kvm, state);
853 static void kvm_init_pm_notifier(struct kvm *kvm)
855 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
856 /* Suspend KVM before we suspend ftrace, RCU, etc. */
857 kvm->pm_notifier.priority = INT_MAX;
858 register_pm_notifier(&kvm->pm_notifier);
861 static void kvm_destroy_pm_notifier(struct kvm *kvm)
863 unregister_pm_notifier(&kvm->pm_notifier);
865 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
866 static void kvm_init_pm_notifier(struct kvm *kvm)
870 static void kvm_destroy_pm_notifier(struct kvm *kvm)
873 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
875 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
877 if (!memslot->dirty_bitmap)
880 kvfree(memslot->dirty_bitmap);
881 memslot->dirty_bitmap = NULL;
884 /* This does not remove the slot from struct kvm_memslots data structures */
885 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
887 kvm_destroy_dirty_bitmap(slot);
889 kvm_arch_free_memslot(kvm, slot);
894 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
896 struct hlist_node *idnode;
897 struct kvm_memory_slot *memslot;
901 * The same memslot objects live in both active and inactive sets,
902 * arbitrarily free using index '1' so the second invocation of this
903 * function isn't operating over a structure with dangling pointers
904 * (even though this function isn't actually touching them).
906 if (!slots->node_idx)
909 hash_for_each_safe(slots->id_hash, bkt, idnode, memslot, id_node[1])
910 kvm_free_memslot(kvm, memslot);
913 static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
915 switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
916 case KVM_STATS_TYPE_INSTANT:
918 case KVM_STATS_TYPE_CUMULATIVE:
919 case KVM_STATS_TYPE_PEAK:
926 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
929 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
930 kvm_vcpu_stats_header.num_desc;
932 if (!kvm->debugfs_dentry)
935 debugfs_remove_recursive(kvm->debugfs_dentry);
937 if (kvm->debugfs_stat_data) {
938 for (i = 0; i < kvm_debugfs_num_entries; i++)
939 kfree(kvm->debugfs_stat_data[i]);
940 kfree(kvm->debugfs_stat_data);
944 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
946 static DEFINE_MUTEX(kvm_debugfs_lock);
948 char dir_name[ITOA_MAX_LEN * 2];
949 struct kvm_stat_data *stat_data;
950 const struct _kvm_stats_desc *pdesc;
952 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
953 kvm_vcpu_stats_header.num_desc;
955 if (!debugfs_initialized())
958 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
959 mutex_lock(&kvm_debugfs_lock);
960 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
962 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
964 mutex_unlock(&kvm_debugfs_lock);
967 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
968 mutex_unlock(&kvm_debugfs_lock);
972 kvm->debugfs_dentry = dent;
973 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
974 sizeof(*kvm->debugfs_stat_data),
976 if (!kvm->debugfs_stat_data)
979 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
980 pdesc = &kvm_vm_stats_desc[i];
981 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
985 stat_data->kvm = kvm;
986 stat_data->desc = pdesc;
987 stat_data->kind = KVM_STAT_VM;
988 kvm->debugfs_stat_data[i] = stat_data;
989 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
990 kvm->debugfs_dentry, stat_data,
994 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
995 pdesc = &kvm_vcpu_stats_desc[i];
996 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
1000 stat_data->kvm = kvm;
1001 stat_data->desc = pdesc;
1002 stat_data->kind = KVM_STAT_VCPU;
1003 kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
1004 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
1005 kvm->debugfs_dentry, stat_data,
1009 ret = kvm_arch_create_vm_debugfs(kvm);
1011 kvm_destroy_vm_debugfs(kvm);
1019 * Called after the VM is otherwise initialized, but just before adding it to
1022 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
1028 * Called just after removing the VM from the vm_list, but before doing any
1029 * other destruction.
1031 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
1036 * Called after per-vm debugfs created. When called kvm->debugfs_dentry should
1037 * be setup already, so we can create arch-specific debugfs entries under it.
1038 * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1039 * a per-arch destroy interface is not needed.
1041 int __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1046 static struct kvm *kvm_create_vm(unsigned long type)
1048 struct kvm *kvm = kvm_arch_alloc_vm();
1049 struct kvm_memslots *slots;
1054 return ERR_PTR(-ENOMEM);
1056 KVM_MMU_LOCK_INIT(kvm);
1057 mmgrab(current->mm);
1058 kvm->mm = current->mm;
1059 kvm_eventfd_init(kvm);
1060 mutex_init(&kvm->lock);
1061 mutex_init(&kvm->irq_lock);
1062 mutex_init(&kvm->slots_lock);
1063 mutex_init(&kvm->slots_arch_lock);
1064 spin_lock_init(&kvm->mn_invalidate_lock);
1065 rcuwait_init(&kvm->mn_memslots_update_rcuwait);
1066 xa_init(&kvm->vcpu_array);
1068 INIT_LIST_HEAD(&kvm->gpc_list);
1069 spin_lock_init(&kvm->gpc_lock);
1071 INIT_LIST_HEAD(&kvm->devices);
1073 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1075 if (init_srcu_struct(&kvm->srcu))
1076 goto out_err_no_srcu;
1077 if (init_srcu_struct(&kvm->irq_srcu))
1078 goto out_err_no_irq_srcu;
1080 refcount_set(&kvm->users_count, 1);
1081 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1082 for (j = 0; j < 2; j++) {
1083 slots = &kvm->__memslots[i][j];
1085 atomic_long_set(&slots->last_used_slot, (unsigned long)NULL);
1086 slots->hva_tree = RB_ROOT_CACHED;
1087 slots->gfn_tree = RB_ROOT;
1088 hash_init(slots->id_hash);
1089 slots->node_idx = j;
1091 /* Generations must be different for each address space. */
1092 slots->generation = i;
1095 rcu_assign_pointer(kvm->memslots[i], &kvm->__memslots[i][0]);
1098 for (i = 0; i < KVM_NR_BUSES; i++) {
1099 rcu_assign_pointer(kvm->buses[i],
1100 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
1102 goto out_err_no_arch_destroy_vm;
1105 kvm->max_halt_poll_ns = halt_poll_ns;
1107 r = kvm_arch_init_vm(kvm, type);
1109 goto out_err_no_arch_destroy_vm;
1111 r = hardware_enable_all();
1113 goto out_err_no_disable;
1115 #ifdef CONFIG_HAVE_KVM_IRQFD
1116 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
1119 r = kvm_init_mmu_notifier(kvm);
1121 goto out_err_no_mmu_notifier;
1123 r = kvm_arch_post_init_vm(kvm);
1127 mutex_lock(&kvm_lock);
1128 list_add(&kvm->vm_list, &vm_list);
1129 mutex_unlock(&kvm_lock);
1131 preempt_notifier_inc();
1132 kvm_init_pm_notifier(kvm);
1137 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1138 if (kvm->mmu_notifier.ops)
1139 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1141 out_err_no_mmu_notifier:
1142 hardware_disable_all();
1144 kvm_arch_destroy_vm(kvm);
1145 out_err_no_arch_destroy_vm:
1146 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
1147 for (i = 0; i < KVM_NR_BUSES; i++)
1148 kfree(kvm_get_bus(kvm, i));
1149 cleanup_srcu_struct(&kvm->irq_srcu);
1150 out_err_no_irq_srcu:
1151 cleanup_srcu_struct(&kvm->srcu);
1153 kvm_arch_free_vm(kvm);
1154 mmdrop(current->mm);
1158 static void kvm_destroy_devices(struct kvm *kvm)
1160 struct kvm_device *dev, *tmp;
1163 * We do not need to take the kvm->lock here, because nobody else
1164 * has a reference to the struct kvm at this point and therefore
1165 * cannot access the devices list anyhow.
1167 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1168 list_del(&dev->vm_node);
1169 dev->ops->destroy(dev);
1173 static void kvm_destroy_vm(struct kvm *kvm)
1176 struct mm_struct *mm = kvm->mm;
1178 kvm_destroy_pm_notifier(kvm);
1179 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1180 kvm_destroy_vm_debugfs(kvm);
1181 kvm_arch_sync_events(kvm);
1182 mutex_lock(&kvm_lock);
1183 list_del(&kvm->vm_list);
1184 mutex_unlock(&kvm_lock);
1185 kvm_arch_pre_destroy_vm(kvm);
1187 kvm_free_irq_routing(kvm);
1188 for (i = 0; i < KVM_NR_BUSES; i++) {
1189 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1192 kvm_io_bus_destroy(bus);
1193 kvm->buses[i] = NULL;
1195 kvm_coalesced_mmio_free(kvm);
1196 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1197 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1199 * At this point, pending calls to invalidate_range_start()
1200 * have completed but no more MMU notifiers will run, so
1201 * mn_active_invalidate_count may remain unbalanced.
1202 * No threads can be waiting in install_new_memslots as the
1203 * last reference on KVM has been dropped, but freeing
1204 * memslots would deadlock without this manual intervention.
1206 WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1207 kvm->mn_active_invalidate_count = 0;
1209 kvm_arch_flush_shadow_all(kvm);
1211 kvm_arch_destroy_vm(kvm);
1212 kvm_destroy_devices(kvm);
1213 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1214 kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
1215 kvm_free_memslots(kvm, &kvm->__memslots[i][1]);
1217 cleanup_srcu_struct(&kvm->irq_srcu);
1218 cleanup_srcu_struct(&kvm->srcu);
1219 kvm_arch_free_vm(kvm);
1220 preempt_notifier_dec();
1221 hardware_disable_all();
1225 void kvm_get_kvm(struct kvm *kvm)
1227 refcount_inc(&kvm->users_count);
1229 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1232 * Make sure the vm is not during destruction, which is a safe version of
1233 * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise.
1235 bool kvm_get_kvm_safe(struct kvm *kvm)
1237 return refcount_inc_not_zero(&kvm->users_count);
1239 EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1241 void kvm_put_kvm(struct kvm *kvm)
1243 if (refcount_dec_and_test(&kvm->users_count))
1244 kvm_destroy_vm(kvm);
1246 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1249 * Used to put a reference that was taken on behalf of an object associated
1250 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1251 * of the new file descriptor fails and the reference cannot be transferred to
1252 * its final owner. In such cases, the caller is still actively using @kvm and
1253 * will fail miserably if the refcount unexpectedly hits zero.
1255 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1257 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1259 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1261 static int kvm_vm_release(struct inode *inode, struct file *filp)
1263 struct kvm *kvm = filp->private_data;
1265 kvm_irqfd_release(kvm);
1272 * Allocation size is twice as large as the actual dirty bitmap size.
1273 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1275 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1277 unsigned long dirty_bytes = kvm_dirty_bitmap_bytes(memslot);
1279 memslot->dirty_bitmap = __vcalloc(2, dirty_bytes, GFP_KERNEL_ACCOUNT);
1280 if (!memslot->dirty_bitmap)
1286 static struct kvm_memslots *kvm_get_inactive_memslots(struct kvm *kvm, int as_id)
1288 struct kvm_memslots *active = __kvm_memslots(kvm, as_id);
1289 int node_idx_inactive = active->node_idx ^ 1;
1291 return &kvm->__memslots[as_id][node_idx_inactive];
1295 * Helper to get the address space ID when one of memslot pointers may be NULL.
1296 * This also serves as a sanity that at least one of the pointers is non-NULL,
1297 * and that their address space IDs don't diverge.
1299 static int kvm_memslots_get_as_id(struct kvm_memory_slot *a,
1300 struct kvm_memory_slot *b)
1302 if (WARN_ON_ONCE(!a && !b))
1310 WARN_ON_ONCE(a->as_id != b->as_id);
1314 static void kvm_insert_gfn_node(struct kvm_memslots *slots,
1315 struct kvm_memory_slot *slot)
1317 struct rb_root *gfn_tree = &slots->gfn_tree;
1318 struct rb_node **node, *parent;
1319 int idx = slots->node_idx;
1322 for (node = &gfn_tree->rb_node; *node; ) {
1323 struct kvm_memory_slot *tmp;
1325 tmp = container_of(*node, struct kvm_memory_slot, gfn_node[idx]);
1327 if (slot->base_gfn < tmp->base_gfn)
1328 node = &(*node)->rb_left;
1329 else if (slot->base_gfn > tmp->base_gfn)
1330 node = &(*node)->rb_right;
1335 rb_link_node(&slot->gfn_node[idx], parent, node);
1336 rb_insert_color(&slot->gfn_node[idx], gfn_tree);
1339 static void kvm_erase_gfn_node(struct kvm_memslots *slots,
1340 struct kvm_memory_slot *slot)
1342 rb_erase(&slot->gfn_node[slots->node_idx], &slots->gfn_tree);
1345 static void kvm_replace_gfn_node(struct kvm_memslots *slots,
1346 struct kvm_memory_slot *old,
1347 struct kvm_memory_slot *new)
1349 int idx = slots->node_idx;
1351 WARN_ON_ONCE(old->base_gfn != new->base_gfn);
1353 rb_replace_node(&old->gfn_node[idx], &new->gfn_node[idx],
1358 * Replace @old with @new in the inactive memslots.
1360 * With NULL @old this simply adds @new.
1361 * With NULL @new this simply removes @old.
1363 * If @new is non-NULL its hva_node[slots_idx] range has to be set
1366 static void kvm_replace_memslot(struct kvm *kvm,
1367 struct kvm_memory_slot *old,
1368 struct kvm_memory_slot *new)
1370 int as_id = kvm_memslots_get_as_id(old, new);
1371 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1372 int idx = slots->node_idx;
1375 hash_del(&old->id_node[idx]);
1376 interval_tree_remove(&old->hva_node[idx], &slots->hva_tree);
1378 if ((long)old == atomic_long_read(&slots->last_used_slot))
1379 atomic_long_set(&slots->last_used_slot, (long)new);
1382 kvm_erase_gfn_node(slots, old);
1388 * Initialize @new's hva range. Do this even when replacing an @old
1389 * slot, kvm_copy_memslot() deliberately does not touch node data.
1391 new->hva_node[idx].start = new->userspace_addr;
1392 new->hva_node[idx].last = new->userspace_addr +
1393 (new->npages << PAGE_SHIFT) - 1;
1396 * (Re)Add the new memslot. There is no O(1) interval_tree_replace(),
1397 * hva_node needs to be swapped with remove+insert even though hva can't
1398 * change when replacing an existing slot.
1400 hash_add(slots->id_hash, &new->id_node[idx], new->id);
1401 interval_tree_insert(&new->hva_node[idx], &slots->hva_tree);
1404 * If the memslot gfn is unchanged, rb_replace_node() can be used to
1405 * switch the node in the gfn tree instead of removing the old and
1406 * inserting the new as two separate operations. Replacement is a
1407 * single O(1) operation versus two O(log(n)) operations for
1410 if (old && old->base_gfn == new->base_gfn) {
1411 kvm_replace_gfn_node(slots, old, new);
1414 kvm_erase_gfn_node(slots, old);
1415 kvm_insert_gfn_node(slots, new);
1419 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1421 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1423 #ifdef __KVM_HAVE_READONLY_MEM
1424 valid_flags |= KVM_MEM_READONLY;
1427 if (mem->flags & ~valid_flags)
1433 static void kvm_swap_active_memslots(struct kvm *kvm, int as_id)
1435 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
1437 /* Grab the generation from the activate memslots. */
1438 u64 gen = __kvm_memslots(kvm, as_id)->generation;
1440 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1441 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1444 * Do not store the new memslots while there are invalidations in
1445 * progress, otherwise the locking in invalidate_range_start and
1446 * invalidate_range_end will be unbalanced.
1448 spin_lock(&kvm->mn_invalidate_lock);
1449 prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1450 while (kvm->mn_active_invalidate_count) {
1451 set_current_state(TASK_UNINTERRUPTIBLE);
1452 spin_unlock(&kvm->mn_invalidate_lock);
1454 spin_lock(&kvm->mn_invalidate_lock);
1456 finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
1457 rcu_assign_pointer(kvm->memslots[as_id], slots);
1458 spin_unlock(&kvm->mn_invalidate_lock);
1461 * Acquired in kvm_set_memslot. Must be released before synchronize
1462 * SRCU below in order to avoid deadlock with another thread
1463 * acquiring the slots_arch_lock in an srcu critical section.
1465 mutex_unlock(&kvm->slots_arch_lock);
1467 synchronize_srcu_expedited(&kvm->srcu);
1470 * Increment the new memslot generation a second time, dropping the
1471 * update in-progress flag and incrementing the generation based on
1472 * the number of address spaces. This provides a unique and easily
1473 * identifiable generation number while the memslots are in flux.
1475 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1478 * Generations must be unique even across address spaces. We do not need
1479 * a global counter for that, instead the generation space is evenly split
1480 * across address spaces. For example, with two address spaces, address
1481 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1482 * use generations 1, 3, 5, ...
1484 gen += KVM_ADDRESS_SPACE_NUM;
1486 kvm_arch_memslots_updated(kvm, gen);
1488 slots->generation = gen;
1491 static int kvm_prepare_memory_region(struct kvm *kvm,
1492 const struct kvm_memory_slot *old,
1493 struct kvm_memory_slot *new,
1494 enum kvm_mr_change change)
1499 * If dirty logging is disabled, nullify the bitmap; the old bitmap
1500 * will be freed on "commit". If logging is enabled in both old and
1501 * new, reuse the existing bitmap. If logging is enabled only in the
1502 * new and KVM isn't using a ring buffer, allocate and initialize a
1505 if (change != KVM_MR_DELETE) {
1506 if (!(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
1507 new->dirty_bitmap = NULL;
1508 else if (old && old->dirty_bitmap)
1509 new->dirty_bitmap = old->dirty_bitmap;
1510 else if (!kvm->dirty_ring_size) {
1511 r = kvm_alloc_dirty_bitmap(new);
1515 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1516 bitmap_set(new->dirty_bitmap, 0, new->npages);
1520 r = kvm_arch_prepare_memory_region(kvm, old, new, change);
1522 /* Free the bitmap on failure if it was allocated above. */
1523 if (r && new && new->dirty_bitmap && old && !old->dirty_bitmap)
1524 kvm_destroy_dirty_bitmap(new);
1529 static void kvm_commit_memory_region(struct kvm *kvm,
1530 struct kvm_memory_slot *old,
1531 const struct kvm_memory_slot *new,
1532 enum kvm_mr_change change)
1535 * Update the total number of memslot pages before calling the arch
1536 * hook so that architectures can consume the result directly.
1538 if (change == KVM_MR_DELETE)
1539 kvm->nr_memslot_pages -= old->npages;
1540 else if (change == KVM_MR_CREATE)
1541 kvm->nr_memslot_pages += new->npages;
1543 kvm_arch_commit_memory_region(kvm, old, new, change);
1547 /* Nothing more to do. */
1550 /* Free the old memslot and all its metadata. */
1551 kvm_free_memslot(kvm, old);
1554 case KVM_MR_FLAGS_ONLY:
1556 * Free the dirty bitmap as needed; the below check encompasses
1557 * both the flags and whether a ring buffer is being used)
1559 if (old->dirty_bitmap && !new->dirty_bitmap)
1560 kvm_destroy_dirty_bitmap(old);
1563 * The final quirk. Free the detached, old slot, but only its
1564 * memory, not any metadata. Metadata, including arch specific
1565 * data, may be reused by @new.
1575 * Activate @new, which must be installed in the inactive slots by the caller,
1576 * by swapping the active slots and then propagating @new to @old once @old is
1577 * unreachable and can be safely modified.
1579 * With NULL @old this simply adds @new to @active (while swapping the sets).
1580 * With NULL @new this simply removes @old from @active and frees it
1581 * (while also swapping the sets).
1583 static void kvm_activate_memslot(struct kvm *kvm,
1584 struct kvm_memory_slot *old,
1585 struct kvm_memory_slot *new)
1587 int as_id = kvm_memslots_get_as_id(old, new);
1589 kvm_swap_active_memslots(kvm, as_id);
1591 /* Propagate the new memslot to the now inactive memslots. */
1592 kvm_replace_memslot(kvm, old, new);
1595 static void kvm_copy_memslot(struct kvm_memory_slot *dest,
1596 const struct kvm_memory_slot *src)
1598 dest->base_gfn = src->base_gfn;
1599 dest->npages = src->npages;
1600 dest->dirty_bitmap = src->dirty_bitmap;
1601 dest->arch = src->arch;
1602 dest->userspace_addr = src->userspace_addr;
1603 dest->flags = src->flags;
1605 dest->as_id = src->as_id;
1608 static void kvm_invalidate_memslot(struct kvm *kvm,
1609 struct kvm_memory_slot *old,
1610 struct kvm_memory_slot *invalid_slot)
1613 * Mark the current slot INVALID. As with all memslot modifications,
1614 * this must be done on an unreachable slot to avoid modifying the
1615 * current slot in the active tree.
1617 kvm_copy_memslot(invalid_slot, old);
1618 invalid_slot->flags |= KVM_MEMSLOT_INVALID;
1619 kvm_replace_memslot(kvm, old, invalid_slot);
1622 * Activate the slot that is now marked INVALID, but don't propagate
1623 * the slot to the now inactive slots. The slot is either going to be
1624 * deleted or recreated as a new slot.
1626 kvm_swap_active_memslots(kvm, old->as_id);
1629 * From this point no new shadow pages pointing to a deleted, or moved,
1630 * memslot will be created. Validation of sp->gfn happens in:
1631 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1632 * - kvm_is_visible_gfn (mmu_check_root)
1634 kvm_arch_flush_shadow_memslot(kvm, old);
1636 /* Was released by kvm_swap_active_memslots, reacquire. */
1637 mutex_lock(&kvm->slots_arch_lock);
1640 * Copy the arch-specific field of the newly-installed slot back to the
1641 * old slot as the arch data could have changed between releasing
1642 * slots_arch_lock in install_new_memslots() and re-acquiring the lock
1643 * above. Writers are required to retrieve memslots *after* acquiring
1644 * slots_arch_lock, thus the active slot's data is guaranteed to be fresh.
1646 old->arch = invalid_slot->arch;
1649 static void kvm_create_memslot(struct kvm *kvm,
1650 struct kvm_memory_slot *new)
1652 /* Add the new memslot to the inactive set and activate. */
1653 kvm_replace_memslot(kvm, NULL, new);
1654 kvm_activate_memslot(kvm, NULL, new);
1657 static void kvm_delete_memslot(struct kvm *kvm,
1658 struct kvm_memory_slot *old,
1659 struct kvm_memory_slot *invalid_slot)
1662 * Remove the old memslot (in the inactive memslots) by passing NULL as
1663 * the "new" slot, and for the invalid version in the active slots.
1665 kvm_replace_memslot(kvm, old, NULL);
1666 kvm_activate_memslot(kvm, invalid_slot, NULL);
1669 static void kvm_move_memslot(struct kvm *kvm,
1670 struct kvm_memory_slot *old,
1671 struct kvm_memory_slot *new,
1672 struct kvm_memory_slot *invalid_slot)
1675 * Replace the old memslot in the inactive slots, and then swap slots
1676 * and replace the current INVALID with the new as well.
1678 kvm_replace_memslot(kvm, old, new);
1679 kvm_activate_memslot(kvm, invalid_slot, new);
1682 static void kvm_update_flags_memslot(struct kvm *kvm,
1683 struct kvm_memory_slot *old,
1684 struct kvm_memory_slot *new)
1687 * Similar to the MOVE case, but the slot doesn't need to be zapped as
1688 * an intermediate step. Instead, the old memslot is simply replaced
1689 * with a new, updated copy in both memslot sets.
1691 kvm_replace_memslot(kvm, old, new);
1692 kvm_activate_memslot(kvm, old, new);
1695 static int kvm_set_memslot(struct kvm *kvm,
1696 struct kvm_memory_slot *old,
1697 struct kvm_memory_slot *new,
1698 enum kvm_mr_change change)
1700 struct kvm_memory_slot *invalid_slot;
1704 * Released in kvm_swap_active_memslots.
1706 * Must be held from before the current memslots are copied until
1707 * after the new memslots are installed with rcu_assign_pointer,
1708 * then released before the synchronize srcu in kvm_swap_active_memslots.
1710 * When modifying memslots outside of the slots_lock, must be held
1711 * before reading the pointer to the current memslots until after all
1712 * changes to those memslots are complete.
1714 * These rules ensure that installing new memslots does not lose
1715 * changes made to the previous memslots.
1717 mutex_lock(&kvm->slots_arch_lock);
1720 * Invalidate the old slot if it's being deleted or moved. This is
1721 * done prior to actually deleting/moving the memslot to allow vCPUs to
1722 * continue running by ensuring there are no mappings or shadow pages
1723 * for the memslot when it is deleted/moved. Without pre-invalidation
1724 * (and without a lock), a window would exist between effecting the
1725 * delete/move and committing the changes in arch code where KVM or a
1726 * guest could access a non-existent memslot.
1728 * Modifications are done on a temporary, unreachable slot. The old
1729 * slot needs to be preserved in case a later step fails and the
1730 * invalidation needs to be reverted.
1732 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1733 invalid_slot = kzalloc(sizeof(*invalid_slot), GFP_KERNEL_ACCOUNT);
1734 if (!invalid_slot) {
1735 mutex_unlock(&kvm->slots_arch_lock);
1738 kvm_invalidate_memslot(kvm, old, invalid_slot);
1741 r = kvm_prepare_memory_region(kvm, old, new, change);
1744 * For DELETE/MOVE, revert the above INVALID change. No
1745 * modifications required since the original slot was preserved
1746 * in the inactive slots. Changing the active memslots also
1747 * release slots_arch_lock.
1749 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1750 kvm_activate_memslot(kvm, invalid_slot, old);
1751 kfree(invalid_slot);
1753 mutex_unlock(&kvm->slots_arch_lock);
1759 * For DELETE and MOVE, the working slot is now active as the INVALID
1760 * version of the old slot. MOVE is particularly special as it reuses
1761 * the old slot and returns a copy of the old slot (in working_slot).
1762 * For CREATE, there is no old slot. For DELETE and FLAGS_ONLY, the
1763 * old slot is detached but otherwise preserved.
1765 if (change == KVM_MR_CREATE)
1766 kvm_create_memslot(kvm, new);
1767 else if (change == KVM_MR_DELETE)
1768 kvm_delete_memslot(kvm, old, invalid_slot);
1769 else if (change == KVM_MR_MOVE)
1770 kvm_move_memslot(kvm, old, new, invalid_slot);
1771 else if (change == KVM_MR_FLAGS_ONLY)
1772 kvm_update_flags_memslot(kvm, old, new);
1776 /* Free the temporary INVALID slot used for DELETE and MOVE. */
1777 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1778 kfree(invalid_slot);
1781 * No need to refresh new->arch, changes after dropping slots_arch_lock
1782 * will directly hit the final, active memsot. Architectures are
1783 * responsible for knowing that new->arch may be stale.
1785 kvm_commit_memory_region(kvm, old, new, change);
1790 static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
1791 gfn_t start, gfn_t end)
1793 struct kvm_memslot_iter iter;
1795 kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
1796 if (iter.slot->id != id)
1804 * Allocate some memory and give it an address in the guest physical address
1807 * Discontiguous memory is allowed, mostly for framebuffers.
1809 * Must be called holding kvm->slots_lock for write.
1811 int __kvm_set_memory_region(struct kvm *kvm,
1812 const struct kvm_userspace_memory_region *mem)
1814 struct kvm_memory_slot *old, *new;
1815 struct kvm_memslots *slots;
1816 enum kvm_mr_change change;
1817 unsigned long npages;
1822 r = check_memory_region_flags(mem);
1826 as_id = mem->slot >> 16;
1827 id = (u16)mem->slot;
1829 /* General sanity checks */
1830 if ((mem->memory_size & (PAGE_SIZE - 1)) ||
1831 (mem->memory_size != (unsigned long)mem->memory_size))
1833 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1835 /* We can read the guest memory with __xxx_user() later on. */
1836 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1837 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1838 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1841 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1843 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1845 if ((mem->memory_size >> PAGE_SHIFT) > KVM_MEM_MAX_NR_PAGES)
1848 slots = __kvm_memslots(kvm, as_id);
1851 * Note, the old memslot (and the pointer itself!) may be invalidated
1852 * and/or destroyed by kvm_set_memslot().
1854 old = id_to_memslot(slots, id);
1856 if (!mem->memory_size) {
1857 if (!old || !old->npages)
1860 if (WARN_ON_ONCE(kvm->nr_memslot_pages < old->npages))
1863 return kvm_set_memslot(kvm, old, NULL, KVM_MR_DELETE);
1866 base_gfn = (mem->guest_phys_addr >> PAGE_SHIFT);
1867 npages = (mem->memory_size >> PAGE_SHIFT);
1869 if (!old || !old->npages) {
1870 change = KVM_MR_CREATE;
1873 * To simplify KVM internals, the total number of pages across
1874 * all memslots must fit in an unsigned long.
1876 if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages)
1878 } else { /* Modify an existing slot. */
1879 if ((mem->userspace_addr != old->userspace_addr) ||
1880 (npages != old->npages) ||
1881 ((mem->flags ^ old->flags) & KVM_MEM_READONLY))
1884 if (base_gfn != old->base_gfn)
1885 change = KVM_MR_MOVE;
1886 else if (mem->flags != old->flags)
1887 change = KVM_MR_FLAGS_ONLY;
1888 else /* Nothing to change. */
1892 if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) &&
1893 kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages))
1896 /* Allocate a slot that will persist in the memslot. */
1897 new = kzalloc(sizeof(*new), GFP_KERNEL_ACCOUNT);
1903 new->base_gfn = base_gfn;
1904 new->npages = npages;
1905 new->flags = mem->flags;
1906 new->userspace_addr = mem->userspace_addr;
1908 r = kvm_set_memslot(kvm, old, new, change);
1913 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1915 int kvm_set_memory_region(struct kvm *kvm,
1916 const struct kvm_userspace_memory_region *mem)
1920 mutex_lock(&kvm->slots_lock);
1921 r = __kvm_set_memory_region(kvm, mem);
1922 mutex_unlock(&kvm->slots_lock);
1925 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1927 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1928 struct kvm_userspace_memory_region *mem)
1930 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1933 return kvm_set_memory_region(kvm, mem);
1936 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1938 * kvm_get_dirty_log - get a snapshot of dirty pages
1939 * @kvm: pointer to kvm instance
1940 * @log: slot id and address to which we copy the log
1941 * @is_dirty: set to '1' if any dirty pages were found
1942 * @memslot: set to the associated memslot, always valid on success
1944 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1945 int *is_dirty, struct kvm_memory_slot **memslot)
1947 struct kvm_memslots *slots;
1950 unsigned long any = 0;
1952 /* Dirty ring tracking is exclusive to dirty log tracking */
1953 if (kvm->dirty_ring_size)
1959 as_id = log->slot >> 16;
1960 id = (u16)log->slot;
1961 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1964 slots = __kvm_memslots(kvm, as_id);
1965 *memslot = id_to_memslot(slots, id);
1966 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1969 kvm_arch_sync_dirty_log(kvm, *memslot);
1971 n = kvm_dirty_bitmap_bytes(*memslot);
1973 for (i = 0; !any && i < n/sizeof(long); ++i)
1974 any = (*memslot)->dirty_bitmap[i];
1976 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1983 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1985 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1987 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1988 * and reenable dirty page tracking for the corresponding pages.
1989 * @kvm: pointer to kvm instance
1990 * @log: slot id and address to which we copy the log
1992 * We need to keep it in mind that VCPU threads can write to the bitmap
1993 * concurrently. So, to avoid losing track of dirty pages we keep the
1996 * 1. Take a snapshot of the bit and clear it if needed.
1997 * 2. Write protect the corresponding page.
1998 * 3. Copy the snapshot to the userspace.
1999 * 4. Upon return caller flushes TLB's if needed.
2001 * Between 2 and 4, the guest may write to the page using the remaining TLB
2002 * entry. This is not a problem because the page is reported dirty using
2003 * the snapshot taken before and step 4 ensures that writes done after
2004 * exiting to userspace will be logged for the next call.
2007 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
2009 struct kvm_memslots *slots;
2010 struct kvm_memory_slot *memslot;
2013 unsigned long *dirty_bitmap;
2014 unsigned long *dirty_bitmap_buffer;
2017 /* Dirty ring tracking is exclusive to dirty log tracking */
2018 if (kvm->dirty_ring_size)
2021 as_id = log->slot >> 16;
2022 id = (u16)log->slot;
2023 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2026 slots = __kvm_memslots(kvm, as_id);
2027 memslot = id_to_memslot(slots, id);
2028 if (!memslot || !memslot->dirty_bitmap)
2031 dirty_bitmap = memslot->dirty_bitmap;
2033 kvm_arch_sync_dirty_log(kvm, memslot);
2035 n = kvm_dirty_bitmap_bytes(memslot);
2037 if (kvm->manual_dirty_log_protect) {
2039 * Unlike kvm_get_dirty_log, we always return false in *flush,
2040 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
2041 * is some code duplication between this function and
2042 * kvm_get_dirty_log, but hopefully all architecture
2043 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
2044 * can be eliminated.
2046 dirty_bitmap_buffer = dirty_bitmap;
2048 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2049 memset(dirty_bitmap_buffer, 0, n);
2052 for (i = 0; i < n / sizeof(long); i++) {
2056 if (!dirty_bitmap[i])
2060 mask = xchg(&dirty_bitmap[i], 0);
2061 dirty_bitmap_buffer[i] = mask;
2063 offset = i * BITS_PER_LONG;
2064 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2067 KVM_MMU_UNLOCK(kvm);
2071 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2073 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
2080 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
2081 * @kvm: kvm instance
2082 * @log: slot id and address to which we copy the log
2084 * Steps 1-4 below provide general overview of dirty page logging. See
2085 * kvm_get_dirty_log_protect() function description for additional details.
2087 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
2088 * always flush the TLB (step 4) even if previous step failed and the dirty
2089 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
2090 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
2091 * writes will be marked dirty for next log read.
2093 * 1. Take a snapshot of the bit and clear it if needed.
2094 * 2. Write protect the corresponding page.
2095 * 3. Copy the snapshot to the userspace.
2096 * 4. Flush TLB's if needed.
2098 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2099 struct kvm_dirty_log *log)
2103 mutex_lock(&kvm->slots_lock);
2105 r = kvm_get_dirty_log_protect(kvm, log);
2107 mutex_unlock(&kvm->slots_lock);
2112 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
2113 * and reenable dirty page tracking for the corresponding pages.
2114 * @kvm: pointer to kvm instance
2115 * @log: slot id and address from which to fetch the bitmap of dirty pages
2117 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
2118 struct kvm_clear_dirty_log *log)
2120 struct kvm_memslots *slots;
2121 struct kvm_memory_slot *memslot;
2125 unsigned long *dirty_bitmap;
2126 unsigned long *dirty_bitmap_buffer;
2129 /* Dirty ring tracking is exclusive to dirty log tracking */
2130 if (kvm->dirty_ring_size)
2133 as_id = log->slot >> 16;
2134 id = (u16)log->slot;
2135 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
2138 if (log->first_page & 63)
2141 slots = __kvm_memslots(kvm, as_id);
2142 memslot = id_to_memslot(slots, id);
2143 if (!memslot || !memslot->dirty_bitmap)
2146 dirty_bitmap = memslot->dirty_bitmap;
2148 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
2150 if (log->first_page > memslot->npages ||
2151 log->num_pages > memslot->npages - log->first_page ||
2152 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
2155 kvm_arch_sync_dirty_log(kvm, memslot);
2158 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2159 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2163 for (offset = log->first_page, i = offset / BITS_PER_LONG,
2164 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2165 i++, offset += BITS_PER_LONG) {
2166 unsigned long mask = *dirty_bitmap_buffer++;
2167 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2171 mask &= atomic_long_fetch_andnot(mask, p);
2174 * mask contains the bits that really have been cleared. This
2175 * never includes any bits beyond the length of the memslot (if
2176 * the length is not aligned to 64 pages), therefore it is not
2177 * a problem if userspace sets them in log->dirty_bitmap.
2181 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2185 KVM_MMU_UNLOCK(kvm);
2188 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2193 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2194 struct kvm_clear_dirty_log *log)
2198 mutex_lock(&kvm->slots_lock);
2200 r = kvm_clear_dirty_log_protect(kvm, log);
2202 mutex_unlock(&kvm->slots_lock);
2205 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2207 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2209 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2211 EXPORT_SYMBOL_GPL(gfn_to_memslot);
2213 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2215 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2216 u64 gen = slots->generation;
2217 struct kvm_memory_slot *slot;
2220 * This also protects against using a memslot from a different address space,
2221 * since different address spaces have different generation numbers.
2223 if (unlikely(gen != vcpu->last_used_slot_gen)) {
2224 vcpu->last_used_slot = NULL;
2225 vcpu->last_used_slot_gen = gen;
2228 slot = try_get_memslot(vcpu->last_used_slot, gfn);
2233 * Fall back to searching all memslots. We purposely use
2234 * search_memslots() instead of __gfn_to_memslot() to avoid
2235 * thrashing the VM-wide last_used_slot in kvm_memslots.
2237 slot = search_memslots(slots, gfn, false);
2239 vcpu->last_used_slot = slot;
2246 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
2248 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
2250 return kvm_is_visible_memslot(memslot);
2252 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2254 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2256 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2258 return kvm_is_visible_memslot(memslot);
2260 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2262 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
2264 struct vm_area_struct *vma;
2265 unsigned long addr, size;
2269 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
2270 if (kvm_is_error_hva(addr))
2273 mmap_read_lock(current->mm);
2274 vma = find_vma(current->mm, addr);
2278 size = vma_kernel_pagesize(vma);
2281 mmap_read_unlock(current->mm);
2286 static bool memslot_is_readonly(const struct kvm_memory_slot *slot)
2288 return slot->flags & KVM_MEM_READONLY;
2291 static unsigned long __gfn_to_hva_many(const struct kvm_memory_slot *slot, gfn_t gfn,
2292 gfn_t *nr_pages, bool write)
2294 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
2295 return KVM_HVA_ERR_BAD;
2297 if (memslot_is_readonly(slot) && write)
2298 return KVM_HVA_ERR_RO_BAD;
2301 *nr_pages = slot->npages - (gfn - slot->base_gfn);
2303 return __gfn_to_hva_memslot(slot, gfn);
2306 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2309 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2312 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2315 return gfn_to_hva_many(slot, gfn, NULL);
2317 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2319 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2321 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2323 EXPORT_SYMBOL_GPL(gfn_to_hva);
2325 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2327 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2329 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2332 * Return the hva of a @gfn and the R/W attribute if possible.
2334 * @slot: the kvm_memory_slot which contains @gfn
2335 * @gfn: the gfn to be translated
2336 * @writable: used to return the read/write attribute of the @slot if the hva
2337 * is valid and @writable is not NULL
2339 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2340 gfn_t gfn, bool *writable)
2342 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2344 if (!kvm_is_error_hva(hva) && writable)
2345 *writable = !memslot_is_readonly(slot);
2350 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2352 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2354 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2357 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2359 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2361 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2364 static inline int check_user_page_hwpoison(unsigned long addr)
2366 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
2368 rc = get_user_pages(addr, 1, flags, NULL, NULL);
2369 return rc == -EHWPOISON;
2373 * The fast path to get the writable pfn which will be stored in @pfn,
2374 * true indicates success, otherwise false is returned. It's also the
2375 * only part that runs if we can in atomic context.
2377 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2378 bool *writable, kvm_pfn_t *pfn)
2380 struct page *page[1];
2383 * Fast pin a writable pfn only if it is a write fault request
2384 * or the caller allows to map a writable pfn for a read fault
2387 if (!(write_fault || writable))
2390 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2391 *pfn = page_to_pfn(page[0]);
2402 * The slow path to get the pfn of the specified host virtual address,
2403 * 1 indicates success, -errno is returned if error is detected.
2405 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2406 bool *writable, kvm_pfn_t *pfn)
2408 unsigned int flags = FOLL_HWPOISON;
2415 *writable = write_fault;
2418 flags |= FOLL_WRITE;
2420 flags |= FOLL_NOWAIT;
2422 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2426 /* map read fault as writable if possible */
2427 if (unlikely(!write_fault) && writable) {
2430 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2436 *pfn = page_to_pfn(page);
2440 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2442 if (unlikely(!(vma->vm_flags & VM_READ)))
2445 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2451 static int kvm_try_get_pfn(kvm_pfn_t pfn)
2453 if (kvm_is_reserved_pfn(pfn))
2455 return get_page_unless_zero(pfn_to_page(pfn));
2458 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2459 unsigned long addr, bool write_fault,
2460 bool *writable, kvm_pfn_t *p_pfn)
2467 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2470 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2471 * not call the fault handler, so do it here.
2473 bool unlocked = false;
2474 r = fixup_user_fault(current->mm, addr,
2475 (write_fault ? FAULT_FLAG_WRITE : 0),
2482 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2487 if (write_fault && !pte_write(*ptep)) {
2488 pfn = KVM_PFN_ERR_RO_FAULT;
2493 *writable = pte_write(*ptep);
2494 pfn = pte_pfn(*ptep);
2497 * Get a reference here because callers of *hva_to_pfn* and
2498 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2499 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2500 * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
2501 * simply do nothing for reserved pfns.
2503 * Whoever called remap_pfn_range is also going to call e.g.
2504 * unmap_mapping_range before the underlying pages are freed,
2505 * causing a call to our MMU notifier.
2507 * Certain IO or PFNMAP mappings can be backed with valid
2508 * struct pages, but be allocated without refcounting e.g.,
2509 * tail pages of non-compound higher order allocations, which
2510 * would then underflow the refcount when the caller does the
2511 * required put_page. Don't allow those pages here.
2513 if (!kvm_try_get_pfn(pfn))
2517 pte_unmap_unlock(ptep, ptl);
2524 * Pin guest page in memory and return its pfn.
2525 * @addr: host virtual address which maps memory to the guest
2526 * @atomic: whether this function can sleep
2527 * @async: whether this function need to wait IO complete if the
2528 * host page is not in the memory
2529 * @write_fault: whether we should get a writable host page
2530 * @writable: whether it allows to map a writable host page for !@write_fault
2532 * The function will map a writable host page for these two cases:
2533 * 1): @write_fault = true
2534 * 2): @write_fault = false && @writable, @writable will tell the caller
2535 * whether the mapping is writable.
2537 kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2538 bool write_fault, bool *writable)
2540 struct vm_area_struct *vma;
2544 /* we can do it either atomically or asynchronously, not both */
2545 BUG_ON(atomic && async);
2547 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2551 return KVM_PFN_ERR_FAULT;
2553 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2557 mmap_read_lock(current->mm);
2558 if (npages == -EHWPOISON ||
2559 (!async && check_user_page_hwpoison(addr))) {
2560 pfn = KVM_PFN_ERR_HWPOISON;
2565 vma = vma_lookup(current->mm, addr);
2568 pfn = KVM_PFN_ERR_FAULT;
2569 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2570 r = hva_to_pfn_remapped(vma, addr, write_fault, writable, &pfn);
2574 pfn = KVM_PFN_ERR_FAULT;
2576 if (async && vma_is_valid(vma, write_fault))
2578 pfn = KVM_PFN_ERR_FAULT;
2581 mmap_read_unlock(current->mm);
2585 kvm_pfn_t __gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn,
2586 bool atomic, bool *async, bool write_fault,
2587 bool *writable, hva_t *hva)
2589 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2594 if (addr == KVM_HVA_ERR_RO_BAD) {
2597 return KVM_PFN_ERR_RO_FAULT;
2600 if (kvm_is_error_hva(addr)) {
2603 return KVM_PFN_NOSLOT;
2606 /* Do not map writable pfn in the readonly memslot. */
2607 if (writable && memslot_is_readonly(slot)) {
2612 return hva_to_pfn(addr, atomic, async, write_fault,
2615 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2617 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2620 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2621 write_fault, writable, NULL);
2623 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2625 kvm_pfn_t gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn)
2627 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2629 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2631 kvm_pfn_t gfn_to_pfn_memslot_atomic(const struct kvm_memory_slot *slot, gfn_t gfn)
2633 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2635 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2637 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2639 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2641 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2643 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2645 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2647 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2649 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2651 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2653 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2655 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2656 struct page **pages, int nr_pages)
2661 addr = gfn_to_hva_many(slot, gfn, &entry);
2662 if (kvm_is_error_hva(addr))
2665 if (entry < nr_pages)
2668 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2670 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2672 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2674 if (is_error_noslot_pfn(pfn))
2675 return KVM_ERR_PTR_BAD_PAGE;
2677 if (kvm_is_reserved_pfn(pfn)) {
2679 return KVM_ERR_PTR_BAD_PAGE;
2682 return pfn_to_page(pfn);
2685 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2689 pfn = gfn_to_pfn(kvm, gfn);
2691 return kvm_pfn_to_page(pfn);
2693 EXPORT_SYMBOL_GPL(gfn_to_page);
2695 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty)
2701 kvm_release_pfn_dirty(pfn);
2703 kvm_release_pfn_clean(pfn);
2706 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2710 struct page *page = KVM_UNMAPPED_PAGE;
2715 pfn = gfn_to_pfn(vcpu->kvm, gfn);
2716 if (is_error_noslot_pfn(pfn))
2719 if (pfn_valid(pfn)) {
2720 page = pfn_to_page(pfn);
2722 #ifdef CONFIG_HAS_IOMEM
2724 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2738 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2740 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2748 if (map->page != KVM_UNMAPPED_PAGE)
2750 #ifdef CONFIG_HAS_IOMEM
2756 kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
2758 kvm_release_pfn(map->pfn, dirty);
2763 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2765 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2769 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2771 return kvm_pfn_to_page(pfn);
2773 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2775 void kvm_release_page_clean(struct page *page)
2777 WARN_ON(is_error_page(page));
2779 kvm_release_pfn_clean(page_to_pfn(page));
2781 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2783 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2785 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2786 put_page(pfn_to_page(pfn));
2788 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2790 void kvm_release_page_dirty(struct page *page)
2792 WARN_ON(is_error_page(page));
2794 kvm_release_pfn_dirty(page_to_pfn(page));
2796 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2798 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2800 kvm_set_pfn_dirty(pfn);
2801 kvm_release_pfn_clean(pfn);
2803 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2805 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2807 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2808 SetPageDirty(pfn_to_page(pfn));
2810 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2812 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2814 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2815 mark_page_accessed(pfn_to_page(pfn));
2817 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2819 static int next_segment(unsigned long len, int offset)
2821 if (len > PAGE_SIZE - offset)
2822 return PAGE_SIZE - offset;
2827 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2828 void *data, int offset, int len)
2833 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2834 if (kvm_is_error_hva(addr))
2836 r = __copy_from_user(data, (void __user *)addr + offset, len);
2842 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2845 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2847 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2849 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2851 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2852 int offset, int len)
2854 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2856 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2858 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2860 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2862 gfn_t gfn = gpa >> PAGE_SHIFT;
2864 int offset = offset_in_page(gpa);
2867 while ((seg = next_segment(len, offset)) != 0) {
2868 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2878 EXPORT_SYMBOL_GPL(kvm_read_guest);
2880 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2882 gfn_t gfn = gpa >> PAGE_SHIFT;
2884 int offset = offset_in_page(gpa);
2887 while ((seg = next_segment(len, offset)) != 0) {
2888 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2898 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2900 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2901 void *data, int offset, unsigned long len)
2906 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2907 if (kvm_is_error_hva(addr))
2909 pagefault_disable();
2910 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2917 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2918 void *data, unsigned long len)
2920 gfn_t gfn = gpa >> PAGE_SHIFT;
2921 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2922 int offset = offset_in_page(gpa);
2924 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2926 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2928 static int __kvm_write_guest_page(struct kvm *kvm,
2929 struct kvm_memory_slot *memslot, gfn_t gfn,
2930 const void *data, int offset, int len)
2935 addr = gfn_to_hva_memslot(memslot, gfn);
2936 if (kvm_is_error_hva(addr))
2938 r = __copy_to_user((void __user *)addr + offset, data, len);
2941 mark_page_dirty_in_slot(kvm, memslot, gfn);
2945 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2946 const void *data, int offset, int len)
2948 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2950 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2952 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2954 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2955 const void *data, int offset, int len)
2957 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2959 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
2961 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2963 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2966 gfn_t gfn = gpa >> PAGE_SHIFT;
2968 int offset = offset_in_page(gpa);
2971 while ((seg = next_segment(len, offset)) != 0) {
2972 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2982 EXPORT_SYMBOL_GPL(kvm_write_guest);
2984 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2987 gfn_t gfn = gpa >> PAGE_SHIFT;
2989 int offset = offset_in_page(gpa);
2992 while ((seg = next_segment(len, offset)) != 0) {
2993 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
3003 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
3005 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
3006 struct gfn_to_hva_cache *ghc,
3007 gpa_t gpa, unsigned long len)
3009 int offset = offset_in_page(gpa);
3010 gfn_t start_gfn = gpa >> PAGE_SHIFT;
3011 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
3012 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
3013 gfn_t nr_pages_avail;
3015 /* Update ghc->generation before performing any error checks. */
3016 ghc->generation = slots->generation;
3018 if (start_gfn > end_gfn) {
3019 ghc->hva = KVM_HVA_ERR_BAD;
3024 * If the requested region crosses two memslots, we still
3025 * verify that the entire region is valid here.
3027 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
3028 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
3029 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
3031 if (kvm_is_error_hva(ghc->hva))
3035 /* Use the slow path for cross page reads and writes. */
3036 if (nr_pages_needed == 1)
3039 ghc->memslot = NULL;
3046 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3047 gpa_t gpa, unsigned long len)
3049 struct kvm_memslots *slots = kvm_memslots(kvm);
3050 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
3052 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
3054 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3055 void *data, unsigned int offset,
3058 struct kvm_memslots *slots = kvm_memslots(kvm);
3060 gpa_t gpa = ghc->gpa + offset;
3062 if (WARN_ON_ONCE(len + offset > ghc->len))
3065 if (slots->generation != ghc->generation) {
3066 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3070 if (kvm_is_error_hva(ghc->hva))
3073 if (unlikely(!ghc->memslot))
3074 return kvm_write_guest(kvm, gpa, data, len);
3076 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
3079 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
3083 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
3085 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3086 void *data, unsigned long len)
3088 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
3090 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
3092 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3093 void *data, unsigned int offset,
3096 struct kvm_memslots *slots = kvm_memslots(kvm);
3098 gpa_t gpa = ghc->gpa + offset;
3100 if (WARN_ON_ONCE(len + offset > ghc->len))
3103 if (slots->generation != ghc->generation) {
3104 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3108 if (kvm_is_error_hva(ghc->hva))
3111 if (unlikely(!ghc->memslot))
3112 return kvm_read_guest(kvm, gpa, data, len);
3114 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
3120 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3122 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3123 void *data, unsigned long len)
3125 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3127 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
3129 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3131 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3132 gfn_t gfn = gpa >> PAGE_SHIFT;
3134 int offset = offset_in_page(gpa);
3137 while ((seg = next_segment(len, offset)) != 0) {
3138 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
3147 EXPORT_SYMBOL_GPL(kvm_clear_guest);
3149 void mark_page_dirty_in_slot(struct kvm *kvm,
3150 const struct kvm_memory_slot *memslot,
3153 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
3155 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3156 if (WARN_ON_ONCE(!vcpu) || WARN_ON_ONCE(vcpu->kvm != kvm))
3160 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
3161 unsigned long rel_gfn = gfn - memslot->base_gfn;
3162 u32 slot = (memslot->as_id << 16) | memslot->id;
3164 if (kvm->dirty_ring_size)
3165 kvm_dirty_ring_push(&vcpu->dirty_ring,
3168 set_bit_le(rel_gfn, memslot->dirty_bitmap);
3171 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
3173 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3175 struct kvm_memory_slot *memslot;
3177 memslot = gfn_to_memslot(kvm, gfn);
3178 mark_page_dirty_in_slot(kvm, memslot, gfn);
3180 EXPORT_SYMBOL_GPL(mark_page_dirty);
3182 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3184 struct kvm_memory_slot *memslot;
3186 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3187 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
3189 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3191 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3193 if (!vcpu->sigset_active)
3197 * This does a lockless modification of ->real_blocked, which is fine
3198 * because, only current can change ->real_blocked and all readers of
3199 * ->real_blocked don't care as long ->real_blocked is always a subset
3202 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
3205 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3207 if (!vcpu->sigset_active)
3210 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
3211 sigemptyset(¤t->real_blocked);
3214 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3216 unsigned int old, val, grow, grow_start;
3218 old = val = vcpu->halt_poll_ns;
3219 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3220 grow = READ_ONCE(halt_poll_ns_grow);
3225 if (val < grow_start)
3228 if (val > vcpu->kvm->max_halt_poll_ns)
3229 val = vcpu->kvm->max_halt_poll_ns;
3231 vcpu->halt_poll_ns = val;
3233 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
3236 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3238 unsigned int old, val, shrink, grow_start;
3240 old = val = vcpu->halt_poll_ns;
3241 shrink = READ_ONCE(halt_poll_ns_shrink);
3242 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3248 if (val < grow_start)
3251 vcpu->halt_poll_ns = val;
3252 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3255 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3258 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3260 if (kvm_arch_vcpu_runnable(vcpu)) {
3261 kvm_make_request(KVM_REQ_UNHALT, vcpu);
3264 if (kvm_cpu_has_pending_timer(vcpu))
3266 if (signal_pending(current))
3268 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3273 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3278 * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is
3279 * pending. This is mostly used when halting a vCPU, but may also be used
3280 * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI.
3282 bool kvm_vcpu_block(struct kvm_vcpu *vcpu)
3284 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
3285 bool waited = false;
3287 vcpu->stat.generic.blocking = 1;
3289 kvm_arch_vcpu_blocking(vcpu);
3291 prepare_to_rcuwait(wait);
3293 set_current_state(TASK_INTERRUPTIBLE);
3295 if (kvm_vcpu_check_block(vcpu) < 0)
3301 finish_rcuwait(wait);
3303 kvm_arch_vcpu_unblocking(vcpu);
3305 vcpu->stat.generic.blocking = 0;
3310 static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start,
3311 ktime_t end, bool success)
3313 struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic;
3314 u64 poll_ns = ktime_to_ns(ktime_sub(end, start));
3316 ++vcpu->stat.generic.halt_attempted_poll;
3319 ++vcpu->stat.generic.halt_successful_poll;
3321 if (!vcpu_valid_wakeup(vcpu))
3322 ++vcpu->stat.generic.halt_poll_invalid;
3324 stats->halt_poll_success_ns += poll_ns;
3325 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns);
3327 stats->halt_poll_fail_ns += poll_ns;
3328 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns);
3333 * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc... If halt
3334 * polling is enabled, busy wait for a short time before blocking to avoid the
3335 * expensive block+unblock sequence if a wake event arrives soon after the vCPU
3338 void kvm_vcpu_halt(struct kvm_vcpu *vcpu)
3340 bool halt_poll_allowed = !kvm_arch_no_poll(vcpu);
3341 bool do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns;
3342 ktime_t start, cur, poll_end;
3343 bool waited = false;
3346 start = cur = poll_end = ktime_get();
3348 ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns);
3352 * This sets KVM_REQ_UNHALT if an interrupt
3355 if (kvm_vcpu_check_block(vcpu) < 0)
3358 poll_end = cur = ktime_get();
3359 } while (kvm_vcpu_can_poll(cur, stop));
3362 waited = kvm_vcpu_block(vcpu);
3366 vcpu->stat.generic.halt_wait_ns +=
3367 ktime_to_ns(cur) - ktime_to_ns(poll_end);
3368 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3369 ktime_to_ns(cur) - ktime_to_ns(poll_end));
3372 /* The total time the vCPU was "halted", including polling time. */
3373 halt_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3376 * Note, halt-polling is considered successful so long as the vCPU was
3377 * never actually scheduled out, i.e. even if the wake event arrived
3378 * after of the halt-polling loop itself, but before the full wait.
3381 update_halt_poll_stats(vcpu, start, poll_end, !waited);
3383 if (halt_poll_allowed) {
3384 if (!vcpu_valid_wakeup(vcpu)) {
3385 shrink_halt_poll_ns(vcpu);
3386 } else if (vcpu->kvm->max_halt_poll_ns) {
3387 if (halt_ns <= vcpu->halt_poll_ns)
3389 /* we had a long block, shrink polling */
3390 else if (vcpu->halt_poll_ns &&
3391 halt_ns > vcpu->kvm->max_halt_poll_ns)
3392 shrink_halt_poll_ns(vcpu);
3393 /* we had a short halt and our poll time is too small */
3394 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3395 halt_ns < vcpu->kvm->max_halt_poll_ns)
3396 grow_halt_poll_ns(vcpu);
3398 vcpu->halt_poll_ns = 0;
3402 trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu));
3404 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
3406 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3408 if (__kvm_vcpu_wake_up(vcpu)) {
3409 WRITE_ONCE(vcpu->ready, true);
3410 ++vcpu->stat.generic.halt_wakeup;
3416 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3420 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3422 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3426 if (kvm_vcpu_wake_up(vcpu))
3431 * The only state change done outside the vcpu mutex is IN_GUEST_MODE
3432 * to EXITING_GUEST_MODE. Therefore the moderately expensive "should
3433 * kick" check does not need atomic operations if kvm_vcpu_kick is used
3434 * within the vCPU thread itself.
3436 if (vcpu == __this_cpu_read(kvm_running_vcpu)) {
3437 if (vcpu->mode == IN_GUEST_MODE)
3438 WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE);
3443 * Note, the vCPU could get migrated to a different pCPU at any point
3444 * after kvm_arch_vcpu_should_kick(), which could result in sending an
3445 * IPI to the previous pCPU. But, that's ok because the purpose of the
3446 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
3447 * vCPU also requires it to leave IN_GUEST_MODE.
3449 if (kvm_arch_vcpu_should_kick(vcpu)) {
3450 cpu = READ_ONCE(vcpu->cpu);
3451 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3452 smp_send_reschedule(cpu);
3457 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3458 #endif /* !CONFIG_S390 */
3460 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3463 struct task_struct *task = NULL;
3467 pid = rcu_dereference(target->pid);
3469 task = get_pid_task(pid, PIDTYPE_PID);
3473 ret = yield_to(task, 1);
3474 put_task_struct(task);
3478 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3481 * Helper that checks whether a VCPU is eligible for directed yield.
3482 * Most eligible candidate to yield is decided by following heuristics:
3484 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3485 * (preempted lock holder), indicated by @in_spin_loop.
3486 * Set at the beginning and cleared at the end of interception/PLE handler.
3488 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3489 * chance last time (mostly it has become eligible now since we have probably
3490 * yielded to lockholder in last iteration. This is done by toggling
3491 * @dy_eligible each time a VCPU checked for eligibility.)
3493 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3494 * to preempted lock-holder could result in wrong VCPU selection and CPU
3495 * burning. Giving priority for a potential lock-holder increases lock
3498 * Since algorithm is based on heuristics, accessing another VCPU data without
3499 * locking does not harm. It may result in trying to yield to same VCPU, fail
3500 * and continue with next VCPU and so on.
3502 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3504 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3507 eligible = !vcpu->spin_loop.in_spin_loop ||
3508 vcpu->spin_loop.dy_eligible;
3510 if (vcpu->spin_loop.in_spin_loop)
3511 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3520 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3521 * a vcpu_load/vcpu_put pair. However, for most architectures
3522 * kvm_arch_vcpu_runnable does not require vcpu_load.
3524 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3526 return kvm_arch_vcpu_runnable(vcpu);
3529 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3531 if (kvm_arch_dy_runnable(vcpu))
3534 #ifdef CONFIG_KVM_ASYNC_PF
3535 if (!list_empty_careful(&vcpu->async_pf.done))
3542 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3547 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3549 struct kvm *kvm = me->kvm;
3550 struct kvm_vcpu *vcpu;
3551 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3557 kvm_vcpu_set_in_spin_loop(me, true);
3559 * We boost the priority of a VCPU that is runnable but not
3560 * currently running, because it got preempted by something
3561 * else and called schedule in __vcpu_run. Hopefully that
3562 * VCPU is holding the lock that we need and will release it.
3563 * We approximate round-robin by starting at the last boosted VCPU.
3565 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3566 kvm_for_each_vcpu(i, vcpu, kvm) {
3567 if (!pass && i <= last_boosted_vcpu) {
3568 i = last_boosted_vcpu;
3570 } else if (pass && i > last_boosted_vcpu)
3572 if (!READ_ONCE(vcpu->ready))
3576 if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu))
3578 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3579 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3580 !kvm_arch_vcpu_in_kernel(vcpu))
3582 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3585 yielded = kvm_vcpu_yield_to(vcpu);
3587 kvm->last_boosted_vcpu = i;
3589 } else if (yielded < 0) {
3596 kvm_vcpu_set_in_spin_loop(me, false);
3598 /* Ensure vcpu is not eligible during next spinloop */
3599 kvm_vcpu_set_dy_eligible(me, false);
3601 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3603 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3605 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
3606 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3607 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3608 kvm->dirty_ring_size / PAGE_SIZE);
3614 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3616 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3619 if (vmf->pgoff == 0)
3620 page = virt_to_page(vcpu->run);
3622 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3623 page = virt_to_page(vcpu->arch.pio_data);
3625 #ifdef CONFIG_KVM_MMIO
3626 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3627 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3629 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3630 page = kvm_dirty_ring_get_page(
3632 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3634 return kvm_arch_vcpu_fault(vcpu, vmf);
3640 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3641 .fault = kvm_vcpu_fault,
3644 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3646 struct kvm_vcpu *vcpu = file->private_data;
3647 unsigned long pages = vma_pages(vma);
3649 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3650 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3651 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3654 vma->vm_ops = &kvm_vcpu_vm_ops;
3658 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3660 struct kvm_vcpu *vcpu = filp->private_data;
3662 kvm_put_kvm(vcpu->kvm);
3666 static struct file_operations kvm_vcpu_fops = {
3667 .release = kvm_vcpu_release,
3668 .unlocked_ioctl = kvm_vcpu_ioctl,
3669 .mmap = kvm_vcpu_mmap,
3670 .llseek = noop_llseek,
3671 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3675 * Allocates an inode for the vcpu.
3677 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3679 char name[8 + 1 + ITOA_MAX_LEN + 1];
3681 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3682 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3685 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3687 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3688 struct dentry *debugfs_dentry;
3689 char dir_name[ITOA_MAX_LEN * 2];
3691 if (!debugfs_initialized())
3694 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3695 debugfs_dentry = debugfs_create_dir(dir_name,
3696 vcpu->kvm->debugfs_dentry);
3698 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3703 * Creates some virtual cpus. Good luck creating more than one.
3705 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3708 struct kvm_vcpu *vcpu;
3711 if (id >= KVM_MAX_VCPU_IDS)
3714 mutex_lock(&kvm->lock);
3715 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3716 mutex_unlock(&kvm->lock);
3720 kvm->created_vcpus++;
3721 mutex_unlock(&kvm->lock);
3723 r = kvm_arch_vcpu_precreate(kvm, id);
3725 goto vcpu_decrement;
3727 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3730 goto vcpu_decrement;
3733 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3734 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3739 vcpu->run = page_address(page);
3741 kvm_vcpu_init(vcpu, kvm, id);
3743 r = kvm_arch_vcpu_create(vcpu);
3745 goto vcpu_free_run_page;
3747 if (kvm->dirty_ring_size) {
3748 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3749 id, kvm->dirty_ring_size);
3751 goto arch_vcpu_destroy;
3754 mutex_lock(&kvm->lock);
3755 if (kvm_get_vcpu_by_id(kvm, id)) {
3757 goto unlock_vcpu_destroy;
3760 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3761 r = xa_insert(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, GFP_KERNEL_ACCOUNT);
3762 BUG_ON(r == -EBUSY);
3764 goto unlock_vcpu_destroy;
3766 /* Fill the stats id string for the vcpu */
3767 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3768 task_pid_nr(current), id);
3770 /* Now it's all set up, let userspace reach it */
3772 r = create_vcpu_fd(vcpu);
3774 xa_erase(&kvm->vcpu_array, vcpu->vcpu_idx);
3775 kvm_put_kvm_no_destroy(kvm);
3776 goto unlock_vcpu_destroy;
3780 * Pairs with smp_rmb() in kvm_get_vcpu. Store the vcpu
3781 * pointer before kvm->online_vcpu's incremented value.
3784 atomic_inc(&kvm->online_vcpus);
3786 mutex_unlock(&kvm->lock);
3787 kvm_arch_vcpu_postcreate(vcpu);
3788 kvm_create_vcpu_debugfs(vcpu);
3791 unlock_vcpu_destroy:
3792 mutex_unlock(&kvm->lock);
3793 kvm_dirty_ring_free(&vcpu->dirty_ring);
3795 kvm_arch_vcpu_destroy(vcpu);
3797 free_page((unsigned long)vcpu->run);
3799 kmem_cache_free(kvm_vcpu_cache, vcpu);
3801 mutex_lock(&kvm->lock);
3802 kvm->created_vcpus--;
3803 mutex_unlock(&kvm->lock);
3807 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3810 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3811 vcpu->sigset_active = 1;
3812 vcpu->sigset = *sigset;
3814 vcpu->sigset_active = 0;
3818 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3819 size_t size, loff_t *offset)
3821 struct kvm_vcpu *vcpu = file->private_data;
3823 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3824 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3825 sizeof(vcpu->stat), user_buffer, size, offset);
3828 static const struct file_operations kvm_vcpu_stats_fops = {
3829 .read = kvm_vcpu_stats_read,
3830 .llseek = noop_llseek,
3833 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3837 char name[15 + ITOA_MAX_LEN + 1];
3839 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3841 fd = get_unused_fd_flags(O_CLOEXEC);
3845 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3848 return PTR_ERR(file);
3850 file->f_mode |= FMODE_PREAD;
3851 fd_install(fd, file);
3856 static long kvm_vcpu_ioctl(struct file *filp,
3857 unsigned int ioctl, unsigned long arg)
3859 struct kvm_vcpu *vcpu = filp->private_data;
3860 void __user *argp = (void __user *)arg;
3862 struct kvm_fpu *fpu = NULL;
3863 struct kvm_sregs *kvm_sregs = NULL;
3865 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
3868 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3872 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3873 * execution; mutex_lock() would break them.
3875 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3876 if (r != -ENOIOCTLCMD)
3879 if (mutex_lock_killable(&vcpu->mutex))
3887 oldpid = rcu_access_pointer(vcpu->pid);
3888 if (unlikely(oldpid != task_pid(current))) {
3889 /* The thread running this VCPU changed. */
3892 r = kvm_arch_vcpu_run_pid_change(vcpu);
3896 newpid = get_task_pid(current, PIDTYPE_PID);
3897 rcu_assign_pointer(vcpu->pid, newpid);
3902 r = kvm_arch_vcpu_ioctl_run(vcpu);
3903 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3906 case KVM_GET_REGS: {
3907 struct kvm_regs *kvm_regs;
3910 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3913 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3917 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3924 case KVM_SET_REGS: {
3925 struct kvm_regs *kvm_regs;
3927 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3928 if (IS_ERR(kvm_regs)) {
3929 r = PTR_ERR(kvm_regs);
3932 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3936 case KVM_GET_SREGS: {
3937 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3938 GFP_KERNEL_ACCOUNT);
3942 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3946 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3951 case KVM_SET_SREGS: {
3952 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3953 if (IS_ERR(kvm_sregs)) {
3954 r = PTR_ERR(kvm_sregs);
3958 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3961 case KVM_GET_MP_STATE: {
3962 struct kvm_mp_state mp_state;
3964 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3968 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3973 case KVM_SET_MP_STATE: {
3974 struct kvm_mp_state mp_state;
3977 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3979 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3982 case KVM_TRANSLATE: {
3983 struct kvm_translation tr;
3986 if (copy_from_user(&tr, argp, sizeof(tr)))
3988 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3992 if (copy_to_user(argp, &tr, sizeof(tr)))
3997 case KVM_SET_GUEST_DEBUG: {
3998 struct kvm_guest_debug dbg;
4001 if (copy_from_user(&dbg, argp, sizeof(dbg)))
4003 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
4006 case KVM_SET_SIGNAL_MASK: {
4007 struct kvm_signal_mask __user *sigmask_arg = argp;
4008 struct kvm_signal_mask kvm_sigmask;
4009 sigset_t sigset, *p;
4014 if (copy_from_user(&kvm_sigmask, argp,
4015 sizeof(kvm_sigmask)))
4018 if (kvm_sigmask.len != sizeof(sigset))
4021 if (copy_from_user(&sigset, sigmask_arg->sigset,
4026 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
4030 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
4034 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
4038 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
4044 fpu = memdup_user(argp, sizeof(*fpu));
4050 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
4053 case KVM_GET_STATS_FD: {
4054 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
4058 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
4061 mutex_unlock(&vcpu->mutex);
4067 #ifdef CONFIG_KVM_COMPAT
4068 static long kvm_vcpu_compat_ioctl(struct file *filp,
4069 unsigned int ioctl, unsigned long arg)
4071 struct kvm_vcpu *vcpu = filp->private_data;
4072 void __user *argp = compat_ptr(arg);
4075 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
4079 case KVM_SET_SIGNAL_MASK: {
4080 struct kvm_signal_mask __user *sigmask_arg = argp;
4081 struct kvm_signal_mask kvm_sigmask;
4086 if (copy_from_user(&kvm_sigmask, argp,
4087 sizeof(kvm_sigmask)))
4090 if (kvm_sigmask.len != sizeof(compat_sigset_t))
4093 if (get_compat_sigset(&sigset,
4094 (compat_sigset_t __user *)sigmask_arg->sigset))
4096 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
4098 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
4102 r = kvm_vcpu_ioctl(filp, ioctl, arg);
4110 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
4112 struct kvm_device *dev = filp->private_data;
4115 return dev->ops->mmap(dev, vma);
4120 static int kvm_device_ioctl_attr(struct kvm_device *dev,
4121 int (*accessor)(struct kvm_device *dev,
4122 struct kvm_device_attr *attr),
4125 struct kvm_device_attr attr;
4130 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4133 return accessor(dev, &attr);
4136 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
4139 struct kvm_device *dev = filp->private_data;
4141 if (dev->kvm->mm != current->mm || dev->kvm->vm_dead)
4145 case KVM_SET_DEVICE_ATTR:
4146 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
4147 case KVM_GET_DEVICE_ATTR:
4148 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
4149 case KVM_HAS_DEVICE_ATTR:
4150 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
4152 if (dev->ops->ioctl)
4153 return dev->ops->ioctl(dev, ioctl, arg);
4159 static int kvm_device_release(struct inode *inode, struct file *filp)
4161 struct kvm_device *dev = filp->private_data;
4162 struct kvm *kvm = dev->kvm;
4164 if (dev->ops->release) {
4165 mutex_lock(&kvm->lock);
4166 list_del(&dev->vm_node);
4167 dev->ops->release(dev);
4168 mutex_unlock(&kvm->lock);
4175 static const struct file_operations kvm_device_fops = {
4176 .unlocked_ioctl = kvm_device_ioctl,
4177 .release = kvm_device_release,
4178 KVM_COMPAT(kvm_device_ioctl),
4179 .mmap = kvm_device_mmap,
4182 struct kvm_device *kvm_device_from_filp(struct file *filp)
4184 if (filp->f_op != &kvm_device_fops)
4187 return filp->private_data;
4190 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
4191 #ifdef CONFIG_KVM_MPIC
4192 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
4193 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
4197 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
4199 if (type >= ARRAY_SIZE(kvm_device_ops_table))
4202 if (kvm_device_ops_table[type] != NULL)
4205 kvm_device_ops_table[type] = ops;
4209 void kvm_unregister_device_ops(u32 type)
4211 if (kvm_device_ops_table[type] != NULL)
4212 kvm_device_ops_table[type] = NULL;
4215 static int kvm_ioctl_create_device(struct kvm *kvm,
4216 struct kvm_create_device *cd)
4218 const struct kvm_device_ops *ops = NULL;
4219 struct kvm_device *dev;
4220 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
4224 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4227 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4228 ops = kvm_device_ops_table[type];
4235 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
4242 mutex_lock(&kvm->lock);
4243 ret = ops->create(dev, type);
4245 mutex_unlock(&kvm->lock);
4249 list_add(&dev->vm_node, &kvm->devices);
4250 mutex_unlock(&kvm->lock);
4256 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
4258 kvm_put_kvm_no_destroy(kvm);
4259 mutex_lock(&kvm->lock);
4260 list_del(&dev->vm_node);
4261 mutex_unlock(&kvm->lock);
4270 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4273 case KVM_CAP_USER_MEMORY:
4274 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4275 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
4276 case KVM_CAP_INTERNAL_ERROR_DATA:
4277 #ifdef CONFIG_HAVE_KVM_MSI
4278 case KVM_CAP_SIGNAL_MSI:
4280 #ifdef CONFIG_HAVE_KVM_IRQFD
4282 case KVM_CAP_IRQFD_RESAMPLE:
4284 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
4285 case KVM_CAP_CHECK_EXTENSION_VM:
4286 case KVM_CAP_ENABLE_CAP_VM:
4287 case KVM_CAP_HALT_POLL:
4289 #ifdef CONFIG_KVM_MMIO
4290 case KVM_CAP_COALESCED_MMIO:
4291 return KVM_COALESCED_MMIO_PAGE_OFFSET;
4292 case KVM_CAP_COALESCED_PIO:
4295 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4296 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4297 return KVM_DIRTY_LOG_MANUAL_CAPS;
4299 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4300 case KVM_CAP_IRQ_ROUTING:
4301 return KVM_MAX_IRQ_ROUTES;
4303 #if KVM_ADDRESS_SPACE_NUM > 1
4304 case KVM_CAP_MULTI_ADDRESS_SPACE:
4305 return KVM_ADDRESS_SPACE_NUM;
4307 case KVM_CAP_NR_MEMSLOTS:
4308 return KVM_USER_MEM_SLOTS;
4309 case KVM_CAP_DIRTY_LOG_RING:
4310 #ifdef CONFIG_HAVE_KVM_DIRTY_RING
4311 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4315 case KVM_CAP_BINARY_STATS_FD:
4320 return kvm_vm_ioctl_check_extension(kvm, arg);
4323 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4327 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4330 /* the size should be power of 2 */
4331 if (!size || (size & (size - 1)))
4334 /* Should be bigger to keep the reserved entries, or a page */
4335 if (size < kvm_dirty_ring_get_rsvd_entries() *
4336 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4339 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4340 sizeof(struct kvm_dirty_gfn))
4343 /* We only allow it to set once */
4344 if (kvm->dirty_ring_size)
4347 mutex_lock(&kvm->lock);
4349 if (kvm->created_vcpus) {
4350 /* We don't allow to change this value after vcpu created */
4353 kvm->dirty_ring_size = size;
4357 mutex_unlock(&kvm->lock);
4361 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4364 struct kvm_vcpu *vcpu;
4367 if (!kvm->dirty_ring_size)
4370 mutex_lock(&kvm->slots_lock);
4372 kvm_for_each_vcpu(i, vcpu, kvm)
4373 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4375 mutex_unlock(&kvm->slots_lock);
4378 kvm_flush_remote_tlbs(kvm);
4383 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4384 struct kvm_enable_cap *cap)
4389 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4390 struct kvm_enable_cap *cap)
4393 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4394 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4395 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4397 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4398 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4400 if (cap->flags || (cap->args[0] & ~allowed_options))
4402 kvm->manual_dirty_log_protect = cap->args[0];
4406 case KVM_CAP_HALT_POLL: {
4407 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4410 kvm->max_halt_poll_ns = cap->args[0];
4413 case KVM_CAP_DIRTY_LOG_RING:
4414 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4416 return kvm_vm_ioctl_enable_cap(kvm, cap);
4420 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4421 size_t size, loff_t *offset)
4423 struct kvm *kvm = file->private_data;
4425 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4426 &kvm_vm_stats_desc[0], &kvm->stat,
4427 sizeof(kvm->stat), user_buffer, size, offset);
4430 static const struct file_operations kvm_vm_stats_fops = {
4431 .read = kvm_vm_stats_read,
4432 .llseek = noop_llseek,
4435 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4440 fd = get_unused_fd_flags(O_CLOEXEC);
4444 file = anon_inode_getfile("kvm-vm-stats",
4445 &kvm_vm_stats_fops, kvm, O_RDONLY);
4448 return PTR_ERR(file);
4450 file->f_mode |= FMODE_PREAD;
4451 fd_install(fd, file);
4456 static long kvm_vm_ioctl(struct file *filp,
4457 unsigned int ioctl, unsigned long arg)
4459 struct kvm *kvm = filp->private_data;
4460 void __user *argp = (void __user *)arg;
4463 if (kvm->mm != current->mm || kvm->vm_dead)
4466 case KVM_CREATE_VCPU:
4467 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4469 case KVM_ENABLE_CAP: {
4470 struct kvm_enable_cap cap;
4473 if (copy_from_user(&cap, argp, sizeof(cap)))
4475 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4478 case KVM_SET_USER_MEMORY_REGION: {
4479 struct kvm_userspace_memory_region kvm_userspace_mem;
4482 if (copy_from_user(&kvm_userspace_mem, argp,
4483 sizeof(kvm_userspace_mem)))
4486 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4489 case KVM_GET_DIRTY_LOG: {
4490 struct kvm_dirty_log log;
4493 if (copy_from_user(&log, argp, sizeof(log)))
4495 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4498 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4499 case KVM_CLEAR_DIRTY_LOG: {
4500 struct kvm_clear_dirty_log log;
4503 if (copy_from_user(&log, argp, sizeof(log)))
4505 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4509 #ifdef CONFIG_KVM_MMIO
4510 case KVM_REGISTER_COALESCED_MMIO: {
4511 struct kvm_coalesced_mmio_zone zone;
4514 if (copy_from_user(&zone, argp, sizeof(zone)))
4516 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4519 case KVM_UNREGISTER_COALESCED_MMIO: {
4520 struct kvm_coalesced_mmio_zone zone;
4523 if (copy_from_user(&zone, argp, sizeof(zone)))
4525 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4530 struct kvm_irqfd data;
4533 if (copy_from_user(&data, argp, sizeof(data)))
4535 r = kvm_irqfd(kvm, &data);
4538 case KVM_IOEVENTFD: {
4539 struct kvm_ioeventfd data;
4542 if (copy_from_user(&data, argp, sizeof(data)))
4544 r = kvm_ioeventfd(kvm, &data);
4547 #ifdef CONFIG_HAVE_KVM_MSI
4548 case KVM_SIGNAL_MSI: {
4552 if (copy_from_user(&msi, argp, sizeof(msi)))
4554 r = kvm_send_userspace_msi(kvm, &msi);
4558 #ifdef __KVM_HAVE_IRQ_LINE
4559 case KVM_IRQ_LINE_STATUS:
4560 case KVM_IRQ_LINE: {
4561 struct kvm_irq_level irq_event;
4564 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4567 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4568 ioctl == KVM_IRQ_LINE_STATUS);
4573 if (ioctl == KVM_IRQ_LINE_STATUS) {
4574 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4582 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4583 case KVM_SET_GSI_ROUTING: {
4584 struct kvm_irq_routing routing;
4585 struct kvm_irq_routing __user *urouting;
4586 struct kvm_irq_routing_entry *entries = NULL;
4589 if (copy_from_user(&routing, argp, sizeof(routing)))
4592 if (!kvm_arch_can_set_irq_routing(kvm))
4594 if (routing.nr > KVM_MAX_IRQ_ROUTES)
4600 entries = vmemdup_user(urouting->entries,
4601 array_size(sizeof(*entries),
4603 if (IS_ERR(entries)) {
4604 r = PTR_ERR(entries);
4608 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4613 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4614 case KVM_CREATE_DEVICE: {
4615 struct kvm_create_device cd;
4618 if (copy_from_user(&cd, argp, sizeof(cd)))
4621 r = kvm_ioctl_create_device(kvm, &cd);
4626 if (copy_to_user(argp, &cd, sizeof(cd)))
4632 case KVM_CHECK_EXTENSION:
4633 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4635 case KVM_RESET_DIRTY_RINGS:
4636 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4638 case KVM_GET_STATS_FD:
4639 r = kvm_vm_ioctl_get_stats_fd(kvm);
4642 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4648 #ifdef CONFIG_KVM_COMPAT
4649 struct compat_kvm_dirty_log {
4653 compat_uptr_t dirty_bitmap; /* one bit per page */
4658 struct compat_kvm_clear_dirty_log {
4663 compat_uptr_t dirty_bitmap; /* one bit per page */
4668 static long kvm_vm_compat_ioctl(struct file *filp,
4669 unsigned int ioctl, unsigned long arg)
4671 struct kvm *kvm = filp->private_data;
4674 if (kvm->mm != current->mm || kvm->vm_dead)
4677 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4678 case KVM_CLEAR_DIRTY_LOG: {
4679 struct compat_kvm_clear_dirty_log compat_log;
4680 struct kvm_clear_dirty_log log;
4682 if (copy_from_user(&compat_log, (void __user *)arg,
4683 sizeof(compat_log)))
4685 log.slot = compat_log.slot;
4686 log.num_pages = compat_log.num_pages;
4687 log.first_page = compat_log.first_page;
4688 log.padding2 = compat_log.padding2;
4689 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4691 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4695 case KVM_GET_DIRTY_LOG: {
4696 struct compat_kvm_dirty_log compat_log;
4697 struct kvm_dirty_log log;
4699 if (copy_from_user(&compat_log, (void __user *)arg,
4700 sizeof(compat_log)))
4702 log.slot = compat_log.slot;
4703 log.padding1 = compat_log.padding1;
4704 log.padding2 = compat_log.padding2;
4705 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4707 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4711 r = kvm_vm_ioctl(filp, ioctl, arg);
4717 static struct file_operations kvm_vm_fops = {
4718 .release = kvm_vm_release,
4719 .unlocked_ioctl = kvm_vm_ioctl,
4720 .llseek = noop_llseek,
4721 KVM_COMPAT(kvm_vm_compat_ioctl),
4724 bool file_is_kvm(struct file *file)
4726 return file && file->f_op == &kvm_vm_fops;
4728 EXPORT_SYMBOL_GPL(file_is_kvm);
4730 static int kvm_dev_ioctl_create_vm(unsigned long type)
4736 kvm = kvm_create_vm(type);
4738 return PTR_ERR(kvm);
4739 #ifdef CONFIG_KVM_MMIO
4740 r = kvm_coalesced_mmio_init(kvm);
4744 r = get_unused_fd_flags(O_CLOEXEC);
4748 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4749 "kvm-%d", task_pid_nr(current));
4751 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4759 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4760 * already set, with ->release() being kvm_vm_release(). In error
4761 * cases it will be called by the final fput(file) and will take
4762 * care of doing kvm_put_kvm(kvm).
4764 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4769 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4771 fd_install(r, file);
4779 static long kvm_dev_ioctl(struct file *filp,
4780 unsigned int ioctl, unsigned long arg)
4785 case KVM_GET_API_VERSION:
4788 r = KVM_API_VERSION;
4791 r = kvm_dev_ioctl_create_vm(arg);
4793 case KVM_CHECK_EXTENSION:
4794 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4796 case KVM_GET_VCPU_MMAP_SIZE:
4799 r = PAGE_SIZE; /* struct kvm_run */
4801 r += PAGE_SIZE; /* pio data page */
4803 #ifdef CONFIG_KVM_MMIO
4804 r += PAGE_SIZE; /* coalesced mmio ring page */
4807 case KVM_TRACE_ENABLE:
4808 case KVM_TRACE_PAUSE:
4809 case KVM_TRACE_DISABLE:
4813 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4819 static struct file_operations kvm_chardev_ops = {
4820 .unlocked_ioctl = kvm_dev_ioctl,
4821 .llseek = noop_llseek,
4822 KVM_COMPAT(kvm_dev_ioctl),
4825 static struct miscdevice kvm_dev = {
4831 static void hardware_enable_nolock(void *junk)
4833 int cpu = raw_smp_processor_id();
4836 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4839 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4841 r = kvm_arch_hardware_enable();
4844 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4845 atomic_inc(&hardware_enable_failed);
4846 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4850 static int kvm_starting_cpu(unsigned int cpu)
4852 raw_spin_lock(&kvm_count_lock);
4853 if (kvm_usage_count)
4854 hardware_enable_nolock(NULL);
4855 raw_spin_unlock(&kvm_count_lock);
4859 static void hardware_disable_nolock(void *junk)
4861 int cpu = raw_smp_processor_id();
4863 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4865 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4866 kvm_arch_hardware_disable();
4869 static int kvm_dying_cpu(unsigned int cpu)
4871 raw_spin_lock(&kvm_count_lock);
4872 if (kvm_usage_count)
4873 hardware_disable_nolock(NULL);
4874 raw_spin_unlock(&kvm_count_lock);
4878 static void hardware_disable_all_nolock(void)
4880 BUG_ON(!kvm_usage_count);
4883 if (!kvm_usage_count)
4884 on_each_cpu(hardware_disable_nolock, NULL, 1);
4887 static void hardware_disable_all(void)
4889 raw_spin_lock(&kvm_count_lock);
4890 hardware_disable_all_nolock();
4891 raw_spin_unlock(&kvm_count_lock);
4894 static int hardware_enable_all(void)
4898 raw_spin_lock(&kvm_count_lock);
4901 if (kvm_usage_count == 1) {
4902 atomic_set(&hardware_enable_failed, 0);
4903 on_each_cpu(hardware_enable_nolock, NULL, 1);
4905 if (atomic_read(&hardware_enable_failed)) {
4906 hardware_disable_all_nolock();
4911 raw_spin_unlock(&kvm_count_lock);
4916 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4920 * Some (well, at least mine) BIOSes hang on reboot if
4923 * And Intel TXT required VMX off for all cpu when system shutdown.
4925 pr_info("kvm: exiting hardware virtualization\n");
4926 kvm_rebooting = true;
4927 on_each_cpu(hardware_disable_nolock, NULL, 1);
4931 static struct notifier_block kvm_reboot_notifier = {
4932 .notifier_call = kvm_reboot,
4936 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4940 for (i = 0; i < bus->dev_count; i++) {
4941 struct kvm_io_device *pos = bus->range[i].dev;
4943 kvm_iodevice_destructor(pos);
4948 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4949 const struct kvm_io_range *r2)
4951 gpa_t addr1 = r1->addr;
4952 gpa_t addr2 = r2->addr;
4957 /* If r2->len == 0, match the exact address. If r2->len != 0,
4958 * accept any overlapping write. Any order is acceptable for
4959 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4960 * we process all of them.
4973 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4975 return kvm_io_bus_cmp(p1, p2);
4978 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4979 gpa_t addr, int len)
4981 struct kvm_io_range *range, key;
4984 key = (struct kvm_io_range) {
4989 range = bsearch(&key, bus->range, bus->dev_count,
4990 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4994 off = range - bus->range;
4996 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
5002 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5003 struct kvm_io_range *range, const void *val)
5007 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5011 while (idx < bus->dev_count &&
5012 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5013 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
5022 /* kvm_io_bus_write - called under kvm->slots_lock */
5023 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5024 int len, const void *val)
5026 struct kvm_io_bus *bus;
5027 struct kvm_io_range range;
5030 range = (struct kvm_io_range) {
5035 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5038 r = __kvm_io_bus_write(vcpu, bus, &range, val);
5039 return r < 0 ? r : 0;
5041 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
5043 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
5044 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
5045 gpa_t addr, int len, const void *val, long cookie)
5047 struct kvm_io_bus *bus;
5048 struct kvm_io_range range;
5050 range = (struct kvm_io_range) {
5055 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5059 /* First try the device referenced by cookie. */
5060 if ((cookie >= 0) && (cookie < bus->dev_count) &&
5061 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
5062 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
5067 * cookie contained garbage; fall back to search and return the
5068 * correct cookie value.
5070 return __kvm_io_bus_write(vcpu, bus, &range, val);
5073 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
5074 struct kvm_io_range *range, void *val)
5078 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
5082 while (idx < bus->dev_count &&
5083 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
5084 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
5093 /* kvm_io_bus_read - called under kvm->slots_lock */
5094 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
5097 struct kvm_io_bus *bus;
5098 struct kvm_io_range range;
5101 range = (struct kvm_io_range) {
5106 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
5109 r = __kvm_io_bus_read(vcpu, bus, &range, val);
5110 return r < 0 ? r : 0;
5113 /* Caller must hold slots_lock. */
5114 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
5115 int len, struct kvm_io_device *dev)
5118 struct kvm_io_bus *new_bus, *bus;
5119 struct kvm_io_range range;
5121 bus = kvm_get_bus(kvm, bus_idx);
5125 /* exclude ioeventfd which is limited by maximum fd */
5126 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
5129 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
5130 GFP_KERNEL_ACCOUNT);
5134 range = (struct kvm_io_range) {
5140 for (i = 0; i < bus->dev_count; i++)
5141 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
5144 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
5145 new_bus->dev_count++;
5146 new_bus->range[i] = range;
5147 memcpy(new_bus->range + i + 1, bus->range + i,
5148 (bus->dev_count - i) * sizeof(struct kvm_io_range));
5149 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5150 synchronize_srcu_expedited(&kvm->srcu);
5156 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5157 struct kvm_io_device *dev)
5160 struct kvm_io_bus *new_bus, *bus;
5162 lockdep_assert_held(&kvm->slots_lock);
5164 bus = kvm_get_bus(kvm, bus_idx);
5168 for (i = 0; i < bus->dev_count; i++) {
5169 if (bus->range[i].dev == dev) {
5174 if (i == bus->dev_count)
5177 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
5178 GFP_KERNEL_ACCOUNT);
5180 memcpy(new_bus, bus, struct_size(bus, range, i));
5181 new_bus->dev_count--;
5182 memcpy(new_bus->range + i, bus->range + i + 1,
5183 flex_array_size(new_bus, range, new_bus->dev_count - i));
5186 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5187 synchronize_srcu_expedited(&kvm->srcu);
5189 /* Destroy the old bus _after_ installing the (null) bus. */
5191 pr_err("kvm: failed to shrink bus, removing it completely\n");
5192 for (j = 0; j < bus->dev_count; j++) {
5195 kvm_iodevice_destructor(bus->range[j].dev);
5200 return new_bus ? 0 : -ENOMEM;
5203 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5206 struct kvm_io_bus *bus;
5207 int dev_idx, srcu_idx;
5208 struct kvm_io_device *iodev = NULL;
5210 srcu_idx = srcu_read_lock(&kvm->srcu);
5212 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
5216 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5220 iodev = bus->range[dev_idx].dev;
5223 srcu_read_unlock(&kvm->srcu, srcu_idx);
5227 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5229 static int kvm_debugfs_open(struct inode *inode, struct file *file,
5230 int (*get)(void *, u64 *), int (*set)(void *, u64),
5233 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5237 * The debugfs files are a reference to the kvm struct which
5238 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
5239 * avoids the race between open and the removal of the debugfs directory.
5241 if (!kvm_get_kvm_safe(stat_data->kvm))
5244 if (simple_attr_open(inode, file, get,
5245 kvm_stats_debugfs_mode(stat_data->desc) & 0222
5248 kvm_put_kvm(stat_data->kvm);
5255 static int kvm_debugfs_release(struct inode *inode, struct file *file)
5257 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5260 simple_attr_release(inode, file);
5261 kvm_put_kvm(stat_data->kvm);
5266 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
5268 *val = *(u64 *)((void *)(&kvm->stat) + offset);
5273 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
5275 *(u64 *)((void *)(&kvm->stat) + offset) = 0;
5280 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
5283 struct kvm_vcpu *vcpu;
5287 kvm_for_each_vcpu(i, vcpu, kvm)
5288 *val += *(u64 *)((void *)(&vcpu->stat) + offset);
5293 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
5296 struct kvm_vcpu *vcpu;
5298 kvm_for_each_vcpu(i, vcpu, kvm)
5299 *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
5304 static int kvm_stat_data_get(void *data, u64 *val)
5307 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5309 switch (stat_data->kind) {
5311 r = kvm_get_stat_per_vm(stat_data->kvm,
5312 stat_data->desc->desc.offset, val);
5315 r = kvm_get_stat_per_vcpu(stat_data->kvm,
5316 stat_data->desc->desc.offset, val);
5323 static int kvm_stat_data_clear(void *data, u64 val)
5326 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5331 switch (stat_data->kind) {
5333 r = kvm_clear_stat_per_vm(stat_data->kvm,
5334 stat_data->desc->desc.offset);
5337 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
5338 stat_data->desc->desc.offset);
5345 static int kvm_stat_data_open(struct inode *inode, struct file *file)
5347 __simple_attr_check_format("%llu\n", 0ull);
5348 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5349 kvm_stat_data_clear, "%llu\n");
5352 static const struct file_operations stat_fops_per_vm = {
5353 .owner = THIS_MODULE,
5354 .open = kvm_stat_data_open,
5355 .release = kvm_debugfs_release,
5356 .read = simple_attr_read,
5357 .write = simple_attr_write,
5358 .llseek = no_llseek,
5361 static int vm_stat_get(void *_offset, u64 *val)
5363 unsigned offset = (long)_offset;
5368 mutex_lock(&kvm_lock);
5369 list_for_each_entry(kvm, &vm_list, vm_list) {
5370 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
5373 mutex_unlock(&kvm_lock);
5377 static int vm_stat_clear(void *_offset, u64 val)
5379 unsigned offset = (long)_offset;
5385 mutex_lock(&kvm_lock);
5386 list_for_each_entry(kvm, &vm_list, vm_list) {
5387 kvm_clear_stat_per_vm(kvm, offset);
5389 mutex_unlock(&kvm_lock);
5394 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
5395 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
5397 static int vcpu_stat_get(void *_offset, u64 *val)
5399 unsigned offset = (long)_offset;
5404 mutex_lock(&kvm_lock);
5405 list_for_each_entry(kvm, &vm_list, vm_list) {
5406 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
5409 mutex_unlock(&kvm_lock);
5413 static int vcpu_stat_clear(void *_offset, u64 val)
5415 unsigned offset = (long)_offset;
5421 mutex_lock(&kvm_lock);
5422 list_for_each_entry(kvm, &vm_list, vm_list) {
5423 kvm_clear_stat_per_vcpu(kvm, offset);
5425 mutex_unlock(&kvm_lock);
5430 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5432 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
5434 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5436 struct kobj_uevent_env *env;
5437 unsigned long long created, active;
5439 if (!kvm_dev.this_device || !kvm)
5442 mutex_lock(&kvm_lock);
5443 if (type == KVM_EVENT_CREATE_VM) {
5444 kvm_createvm_count++;
5446 } else if (type == KVM_EVENT_DESTROY_VM) {
5449 created = kvm_createvm_count;
5450 active = kvm_active_vms;
5451 mutex_unlock(&kvm_lock);
5453 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
5457 add_uevent_var(env, "CREATED=%llu", created);
5458 add_uevent_var(env, "COUNT=%llu", active);
5460 if (type == KVM_EVENT_CREATE_VM) {
5461 add_uevent_var(env, "EVENT=create");
5462 kvm->userspace_pid = task_pid_nr(current);
5463 } else if (type == KVM_EVENT_DESTROY_VM) {
5464 add_uevent_var(env, "EVENT=destroy");
5466 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5468 if (kvm->debugfs_dentry) {
5469 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5472 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5474 add_uevent_var(env, "STATS_PATH=%s", tmp);
5478 /* no need for checks, since we are adding at most only 5 keys */
5479 env->envp[env->envp_idx++] = NULL;
5480 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5484 static void kvm_init_debug(void)
5486 const struct file_operations *fops;
5487 const struct _kvm_stats_desc *pdesc;
5490 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5492 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5493 pdesc = &kvm_vm_stats_desc[i];
5494 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5495 fops = &vm_stat_fops;
5497 fops = &vm_stat_readonly_fops;
5498 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5500 (void *)(long)pdesc->desc.offset, fops);
5503 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5504 pdesc = &kvm_vcpu_stats_desc[i];
5505 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5506 fops = &vcpu_stat_fops;
5508 fops = &vcpu_stat_readonly_fops;
5509 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5511 (void *)(long)pdesc->desc.offset, fops);
5515 static int kvm_suspend(void)
5517 if (kvm_usage_count)
5518 hardware_disable_nolock(NULL);
5522 static void kvm_resume(void)
5524 if (kvm_usage_count) {
5525 lockdep_assert_not_held(&kvm_count_lock);
5526 hardware_enable_nolock(NULL);
5530 static struct syscore_ops kvm_syscore_ops = {
5531 .suspend = kvm_suspend,
5532 .resume = kvm_resume,
5536 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5538 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5541 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5543 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5545 WRITE_ONCE(vcpu->preempted, false);
5546 WRITE_ONCE(vcpu->ready, false);
5548 __this_cpu_write(kvm_running_vcpu, vcpu);
5549 kvm_arch_sched_in(vcpu, cpu);
5550 kvm_arch_vcpu_load(vcpu, cpu);
5553 static void kvm_sched_out(struct preempt_notifier *pn,
5554 struct task_struct *next)
5556 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5558 if (current->on_rq) {
5559 WRITE_ONCE(vcpu->preempted, true);
5560 WRITE_ONCE(vcpu->ready, true);
5562 kvm_arch_vcpu_put(vcpu);
5563 __this_cpu_write(kvm_running_vcpu, NULL);
5567 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5569 * We can disable preemption locally around accessing the per-CPU variable,
5570 * and use the resolved vcpu pointer after enabling preemption again,
5571 * because even if the current thread is migrated to another CPU, reading
5572 * the per-CPU value later will give us the same value as we update the
5573 * per-CPU variable in the preempt notifier handlers.
5575 struct kvm_vcpu *kvm_get_running_vcpu(void)
5577 struct kvm_vcpu *vcpu;
5580 vcpu = __this_cpu_read(kvm_running_vcpu);
5585 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5588 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5590 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5592 return &kvm_running_vcpu;
5595 #ifdef CONFIG_GUEST_PERF_EVENTS
5596 static unsigned int kvm_guest_state(void)
5598 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5601 if (!kvm_arch_pmi_in_guest(vcpu))
5604 state = PERF_GUEST_ACTIVE;
5605 if (!kvm_arch_vcpu_in_kernel(vcpu))
5606 state |= PERF_GUEST_USER;
5611 static unsigned long kvm_guest_get_ip(void)
5613 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
5615 /* Retrieving the IP must be guarded by a call to kvm_guest_state(). */
5616 if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu)))
5619 return kvm_arch_vcpu_get_ip(vcpu);
5622 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5623 .state = kvm_guest_state,
5624 .get_ip = kvm_guest_get_ip,
5625 .handle_intel_pt_intr = NULL,
5628 void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void))
5630 kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler;
5631 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5633 void kvm_unregister_perf_callbacks(void)
5635 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5639 struct kvm_cpu_compat_check {
5644 static void check_processor_compat(void *data)
5646 struct kvm_cpu_compat_check *c = data;
5648 *c->ret = kvm_arch_check_processor_compat(c->opaque);
5651 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5652 struct module *module)
5654 struct kvm_cpu_compat_check c;
5658 r = kvm_arch_init(opaque);
5663 * kvm_arch_init makes sure there's at most one caller
5664 * for architectures that support multiple implementations,
5665 * like intel and amd on x86.
5666 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5667 * conflicts in case kvm is already setup for another implementation.
5669 r = kvm_irqfd_init();
5673 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5678 r = kvm_arch_hardware_setup(opaque);
5684 for_each_online_cpu(cpu) {
5685 smp_call_function_single(cpu, check_processor_compat, &c, 1);
5690 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5691 kvm_starting_cpu, kvm_dying_cpu);
5694 register_reboot_notifier(&kvm_reboot_notifier);
5696 /* A kmem cache lets us meet the alignment requirements of fx_save. */
5698 vcpu_align = __alignof__(struct kvm_vcpu);
5700 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5702 offsetof(struct kvm_vcpu, arch),
5703 offsetofend(struct kvm_vcpu, stats_id)
5704 - offsetof(struct kvm_vcpu, arch),
5706 if (!kvm_vcpu_cache) {
5711 for_each_possible_cpu(cpu) {
5712 if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu),
5713 GFP_KERNEL, cpu_to_node(cpu))) {
5719 r = kvm_async_pf_init();
5723 kvm_chardev_ops.owner = module;
5724 kvm_vm_fops.owner = module;
5725 kvm_vcpu_fops.owner = module;
5727 r = misc_register(&kvm_dev);
5729 pr_err("kvm: misc device register failed\n");
5733 register_syscore_ops(&kvm_syscore_ops);
5735 kvm_preempt_ops.sched_in = kvm_sched_in;
5736 kvm_preempt_ops.sched_out = kvm_sched_out;
5740 r = kvm_vfio_ops_init();
5746 kvm_async_pf_deinit();
5748 for_each_possible_cpu(cpu)
5749 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5751 kmem_cache_destroy(kvm_vcpu_cache);
5753 unregister_reboot_notifier(&kvm_reboot_notifier);
5754 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5756 kvm_arch_hardware_unsetup();
5758 free_cpumask_var(cpus_hardware_enabled);
5766 EXPORT_SYMBOL_GPL(kvm_init);
5772 debugfs_remove_recursive(kvm_debugfs_dir);
5773 misc_deregister(&kvm_dev);
5774 for_each_possible_cpu(cpu)
5775 free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
5776 kmem_cache_destroy(kvm_vcpu_cache);
5777 kvm_async_pf_deinit();
5778 unregister_syscore_ops(&kvm_syscore_ops);
5779 unregister_reboot_notifier(&kvm_reboot_notifier);
5780 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5781 on_each_cpu(hardware_disable_nolock, NULL, 1);
5782 kvm_arch_hardware_unsetup();
5785 free_cpumask_var(cpus_hardware_enabled);
5786 kvm_vfio_ops_exit();
5788 EXPORT_SYMBOL_GPL(kvm_exit);
5790 struct kvm_vm_worker_thread_context {
5792 struct task_struct *parent;
5793 struct completion init_done;
5794 kvm_vm_thread_fn_t thread_fn;
5799 static int kvm_vm_worker_thread(void *context)
5802 * The init_context is allocated on the stack of the parent thread, so
5803 * we have to locally copy anything that is needed beyond initialization
5805 struct kvm_vm_worker_thread_context *init_context = context;
5806 struct task_struct *parent;
5807 struct kvm *kvm = init_context->kvm;
5808 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5809 uintptr_t data = init_context->data;
5812 err = kthread_park(current);
5813 /* kthread_park(current) is never supposed to return an error */
5818 err = cgroup_attach_task_all(init_context->parent, current);
5820 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5825 set_user_nice(current, task_nice(init_context->parent));
5828 init_context->err = err;
5829 complete(&init_context->init_done);
5830 init_context = NULL;
5835 /* Wait to be woken up by the spawner before proceeding. */
5838 if (!kthread_should_stop())
5839 err = thread_fn(kvm, data);
5843 * Move kthread back to its original cgroup to prevent it lingering in
5844 * the cgroup of the VM process, after the latter finishes its
5847 * kthread_stop() waits on the 'exited' completion condition which is
5848 * set in exit_mm(), via mm_release(), in do_exit(). However, the
5849 * kthread is removed from the cgroup in the cgroup_exit() which is
5850 * called after the exit_mm(). This causes the kthread_stop() to return
5851 * before the kthread actually quits the cgroup.
5854 parent = rcu_dereference(current->real_parent);
5855 get_task_struct(parent);
5857 cgroup_attach_task_all(parent, current);
5858 put_task_struct(parent);
5863 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5864 uintptr_t data, const char *name,
5865 struct task_struct **thread_ptr)
5867 struct kvm_vm_worker_thread_context init_context = {};
5868 struct task_struct *thread;
5871 init_context.kvm = kvm;
5872 init_context.parent = current;
5873 init_context.thread_fn = thread_fn;
5874 init_context.data = data;
5875 init_completion(&init_context.init_done);
5877 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5878 "%s-%d", name, task_pid_nr(current));
5880 return PTR_ERR(thread);
5882 /* kthread_run is never supposed to return NULL */
5883 WARN_ON(thread == NULL);
5885 wait_for_completion(&init_context.init_done);
5887 if (!init_context.err)
5888 *thread_ptr = thread;
5890 return init_context.err;