1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <kvm/iodev.h>
18 #include <linux/kvm_host.h>
19 #include <linux/kvm.h>
20 #include <linux/module.h>
21 #include <linux/errno.h>
22 #include <linux/percpu.h>
24 #include <linux/miscdevice.h>
25 #include <linux/vmalloc.h>
26 #include <linux/reboot.h>
27 #include <linux/debugfs.h>
28 #include <linux/highmem.h>
29 #include <linux/file.h>
30 #include <linux/syscore_ops.h>
31 #include <linux/cpu.h>
32 #include <linux/sched/signal.h>
33 #include <linux/sched/mm.h>
34 #include <linux/sched/stat.h>
35 #include <linux/cpumask.h>
36 #include <linux/smp.h>
37 #include <linux/anon_inodes.h>
38 #include <linux/profile.h>
39 #include <linux/kvm_para.h>
40 #include <linux/pagemap.h>
41 #include <linux/mman.h>
42 #include <linux/swap.h>
43 #include <linux/bitops.h>
44 #include <linux/spinlock.h>
45 #include <linux/compat.h>
46 #include <linux/srcu.h>
47 #include <linux/hugetlb.h>
48 #include <linux/slab.h>
49 #include <linux/sort.h>
50 #include <linux/bsearch.h>
52 #include <linux/lockdep.h>
53 #include <linux/kthread.h>
54 #include <linux/suspend.h>
56 #include <asm/processor.h>
57 #include <asm/ioctl.h>
58 #include <linux/uaccess.h>
60 #include "coalesced_mmio.h"
65 #define CREATE_TRACE_POINTS
66 #include <trace/events/kvm.h>
68 #include <linux/kvm_dirty_ring.h>
70 /* Worst case buffer size needed for holding an integer. */
71 #define ITOA_MAX_LEN 12
73 MODULE_AUTHOR("Qumranet");
74 MODULE_LICENSE("GPL");
76 /* Architectures should define their poll value according to the halt latency */
77 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
78 module_param(halt_poll_ns, uint, 0644);
79 EXPORT_SYMBOL_GPL(halt_poll_ns);
81 /* Default doubles per-vcpu halt_poll_ns. */
82 unsigned int halt_poll_ns_grow = 2;
83 module_param(halt_poll_ns_grow, uint, 0644);
84 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
86 /* The start value to grow halt_poll_ns from */
87 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
88 module_param(halt_poll_ns_grow_start, uint, 0644);
89 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
91 /* Default resets per-vcpu halt_poll_ns . */
92 unsigned int halt_poll_ns_shrink;
93 module_param(halt_poll_ns_shrink, uint, 0644);
94 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
99 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
102 DEFINE_MUTEX(kvm_lock);
103 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
106 static cpumask_var_t cpus_hardware_enabled;
107 static int kvm_usage_count;
108 static atomic_t hardware_enable_failed;
110 static struct kmem_cache *kvm_vcpu_cache;
112 static __read_mostly struct preempt_ops kvm_preempt_ops;
113 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
115 struct dentry *kvm_debugfs_dir;
116 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
118 static const struct file_operations stat_fops_per_vm;
120 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
122 #ifdef CONFIG_KVM_COMPAT
123 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
125 #define KVM_COMPAT(c) .compat_ioctl = (c)
128 * For architectures that don't implement a compat infrastructure,
129 * adopt a double line of defense:
130 * - Prevent a compat task from opening /dev/kvm
131 * - If the open has been done by a 64bit task, and the KVM fd
132 * passed to a compat task, let the ioctls fail.
134 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
135 unsigned long arg) { return -EINVAL; }
137 static int kvm_no_compat_open(struct inode *inode, struct file *file)
139 return is_compat_task() ? -ENODEV : 0;
141 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
142 .open = kvm_no_compat_open
144 static int hardware_enable_all(void);
145 static void hardware_disable_all(void);
147 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
149 __visible bool kvm_rebooting;
150 EXPORT_SYMBOL_GPL(kvm_rebooting);
152 #define KVM_EVENT_CREATE_VM 0
153 #define KVM_EVENT_DESTROY_VM 1
154 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
155 static unsigned long long kvm_createvm_count;
156 static unsigned long long kvm_active_vms;
158 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
159 unsigned long start, unsigned long end)
163 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
166 * The metadata used by is_zone_device_page() to determine whether or
167 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
168 * the device has been pinned, e.g. by get_user_pages(). WARN if the
169 * page_count() is zero to help detect bad usage of this helper.
171 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
174 return is_zone_device_page(pfn_to_page(pfn));
177 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
180 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
181 * perspective they are "normal" pages, albeit with slightly different
185 return PageReserved(pfn_to_page(pfn)) &&
187 !kvm_is_zone_device_pfn(pfn);
193 * Switches to specified vcpu, until a matching vcpu_put()
195 void vcpu_load(struct kvm_vcpu *vcpu)
199 __this_cpu_write(kvm_running_vcpu, vcpu);
200 preempt_notifier_register(&vcpu->preempt_notifier);
201 kvm_arch_vcpu_load(vcpu, cpu);
204 EXPORT_SYMBOL_GPL(vcpu_load);
206 void vcpu_put(struct kvm_vcpu *vcpu)
209 kvm_arch_vcpu_put(vcpu);
210 preempt_notifier_unregister(&vcpu->preempt_notifier);
211 __this_cpu_write(kvm_running_vcpu, NULL);
214 EXPORT_SYMBOL_GPL(vcpu_put);
216 /* TODO: merge with kvm_arch_vcpu_should_kick */
217 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
219 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
222 * We need to wait for the VCPU to reenable interrupts and get out of
223 * READING_SHADOW_PAGE_TABLES mode.
225 if (req & KVM_REQUEST_WAIT)
226 return mode != OUTSIDE_GUEST_MODE;
229 * Need to kick a running VCPU, but otherwise there is nothing to do.
231 return mode == IN_GUEST_MODE;
234 static void ack_flush(void *_completed)
238 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
241 cpus = cpu_online_mask;
243 if (cpumask_empty(cpus))
246 smp_call_function_many(cpus, ack_flush, NULL, wait);
250 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
251 struct kvm_vcpu *except,
252 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
255 struct kvm_vcpu *vcpu;
260 kvm_for_each_vcpu(i, vcpu, kvm) {
261 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
265 kvm_make_request(req, vcpu);
268 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
271 if (tmp != NULL && cpu != -1 && cpu != me &&
272 kvm_request_needs_ipi(vcpu, req))
273 __cpumask_set_cpu(cpu, tmp);
276 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
282 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
283 struct kvm_vcpu *except)
288 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
290 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
292 free_cpumask_var(cpus);
296 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
298 return kvm_make_all_cpus_request_except(kvm, req, NULL);
300 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
302 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
303 void kvm_flush_remote_tlbs(struct kvm *kvm)
306 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
307 * kvm_make_all_cpus_request.
309 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
311 ++kvm->stat.generic.remote_tlb_flush_requests;
313 * We want to publish modifications to the page tables before reading
314 * mode. Pairs with a memory barrier in arch-specific code.
315 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
316 * and smp_mb in walk_shadow_page_lockless_begin/end.
317 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
319 * There is already an smp_mb__after_atomic() before
320 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
323 if (!kvm_arch_flush_remote_tlb(kvm)
324 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
325 ++kvm->stat.generic.remote_tlb_flush;
326 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
328 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
331 void kvm_reload_remote_mmus(struct kvm *kvm)
333 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
336 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
337 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
340 gfp_flags |= mc->gfp_zero;
343 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
345 return (void *)__get_free_page(gfp_flags);
348 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
352 if (mc->nobjs >= min)
354 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
355 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
357 return mc->nobjs >= min ? 0 : -ENOMEM;
358 mc->objects[mc->nobjs++] = obj;
363 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
368 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
372 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
374 free_page((unsigned long)mc->objects[--mc->nobjs]);
378 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
382 if (WARN_ON(!mc->nobjs))
383 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
385 p = mc->objects[--mc->nobjs];
391 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
393 mutex_init(&vcpu->mutex);
398 rcuwait_init(&vcpu->wait);
399 kvm_async_pf_vcpu_init(vcpu);
402 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
404 kvm_vcpu_set_in_spin_loop(vcpu, false);
405 kvm_vcpu_set_dy_eligible(vcpu, false);
406 vcpu->preempted = false;
408 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
409 vcpu->last_used_slot = 0;
412 void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
414 kvm_dirty_ring_free(&vcpu->dirty_ring);
415 kvm_arch_vcpu_destroy(vcpu);
418 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
419 * the vcpu->pid pointer, and at destruction time all file descriptors
422 put_pid(rcu_dereference_protected(vcpu->pid, 1));
424 free_page((unsigned long)vcpu->run);
425 kmem_cache_free(kvm_vcpu_cache, vcpu);
427 EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
429 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
430 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
432 return container_of(mn, struct kvm, mmu_notifier);
435 static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
436 struct mm_struct *mm,
437 unsigned long start, unsigned long end)
439 struct kvm *kvm = mmu_notifier_to_kvm(mn);
442 idx = srcu_read_lock(&kvm->srcu);
443 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
444 srcu_read_unlock(&kvm->srcu, idx);
447 typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
449 typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
452 struct kvm_hva_range {
456 hva_handler_t handler;
457 on_lock_fn_t on_lock;
463 * Use a dedicated stub instead of NULL to indicate that there is no callback
464 * function/handler. The compiler technically can't guarantee that a real
465 * function will have a non-zero address, and so it will generate code to
466 * check for !NULL, whereas comparing against a stub will be elided at compile
467 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
469 static void kvm_null_fn(void)
473 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
475 static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
476 const struct kvm_hva_range *range)
478 bool ret = false, locked = false;
479 struct kvm_gfn_range gfn_range;
480 struct kvm_memory_slot *slot;
481 struct kvm_memslots *slots;
484 /* A null handler is allowed if and only if on_lock() is provided. */
485 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
486 IS_KVM_NULL_FN(range->handler)))
489 idx = srcu_read_lock(&kvm->srcu);
491 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
492 slots = __kvm_memslots(kvm, i);
493 kvm_for_each_memslot(slot, slots) {
494 unsigned long hva_start, hva_end;
496 hva_start = max(range->start, slot->userspace_addr);
497 hva_end = min(range->end, slot->userspace_addr +
498 (slot->npages << PAGE_SHIFT));
499 if (hva_start >= hva_end)
503 * To optimize for the likely case where the address
504 * range is covered by zero or one memslots, don't
505 * bother making these conditional (to avoid writes on
506 * the second or later invocation of the handler).
508 gfn_range.pte = range->pte;
509 gfn_range.may_block = range->may_block;
512 * {gfn(page) | page intersects with [hva_start, hva_end)} =
513 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
515 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
516 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
517 gfn_range.slot = slot;
522 if (!IS_KVM_NULL_FN(range->on_lock))
523 range->on_lock(kvm, range->start, range->end);
524 if (IS_KVM_NULL_FN(range->handler))
527 ret |= range->handler(kvm, &gfn_range);
531 if (range->flush_on_ret && (ret || kvm->tlbs_dirty))
532 kvm_flush_remote_tlbs(kvm);
537 srcu_read_unlock(&kvm->srcu, idx);
539 /* The notifiers are averse to booleans. :-( */
543 static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
547 hva_handler_t handler)
549 struct kvm *kvm = mmu_notifier_to_kvm(mn);
550 const struct kvm_hva_range range = {
555 .on_lock = (void *)kvm_null_fn,
556 .flush_on_ret = true,
560 return __kvm_handle_hva_range(kvm, &range);
563 static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
566 hva_handler_t handler)
568 struct kvm *kvm = mmu_notifier_to_kvm(mn);
569 const struct kvm_hva_range range = {
574 .on_lock = (void *)kvm_null_fn,
575 .flush_on_ret = false,
579 return __kvm_handle_hva_range(kvm, &range);
581 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
582 struct mm_struct *mm,
583 unsigned long address,
586 struct kvm *kvm = mmu_notifier_to_kvm(mn);
588 trace_kvm_set_spte_hva(address);
591 * .change_pte() must be surrounded by .invalidate_range_{start,end}().
592 * If mmu_notifier_count is zero, then no in-progress invalidations,
593 * including this one, found a relevant memslot at start(); rechecking
594 * memslots here is unnecessary. Note, a false positive (count elevated
595 * by a different invalidation) is sub-optimal but functionally ok.
597 WARN_ON_ONCE(!READ_ONCE(kvm->mn_active_invalidate_count));
598 if (!READ_ONCE(kvm->mmu_notifier_count))
601 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
604 void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
608 * The count increase must become visible at unlock time as no
609 * spte can be established without taking the mmu_lock and
610 * count is also read inside the mmu_lock critical section.
612 kvm->mmu_notifier_count++;
613 if (likely(kvm->mmu_notifier_count == 1)) {
614 kvm->mmu_notifier_range_start = start;
615 kvm->mmu_notifier_range_end = end;
618 * Fully tracking multiple concurrent ranges has dimishing
619 * returns. Keep things simple and just find the minimal range
620 * which includes the current and new ranges. As there won't be
621 * enough information to subtract a range after its invalidate
622 * completes, any ranges invalidated concurrently will
623 * accumulate and persist until all outstanding invalidates
626 kvm->mmu_notifier_range_start =
627 min(kvm->mmu_notifier_range_start, start);
628 kvm->mmu_notifier_range_end =
629 max(kvm->mmu_notifier_range_end, end);
633 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
634 const struct mmu_notifier_range *range)
636 struct kvm *kvm = mmu_notifier_to_kvm(mn);
637 const struct kvm_hva_range hva_range = {
638 .start = range->start,
641 .handler = kvm_unmap_gfn_range,
642 .on_lock = kvm_inc_notifier_count,
643 .flush_on_ret = true,
644 .may_block = mmu_notifier_range_blockable(range),
647 trace_kvm_unmap_hva_range(range->start, range->end);
650 * Prevent memslot modification between range_start() and range_end()
651 * so that conditionally locking provides the same result in both
652 * functions. Without that guarantee, the mmu_notifier_count
653 * adjustments will be imbalanced.
655 * Pairs with the decrement in range_end().
657 spin_lock(&kvm->mn_invalidate_lock);
658 kvm->mn_active_invalidate_count++;
659 spin_unlock(&kvm->mn_invalidate_lock);
661 __kvm_handle_hva_range(kvm, &hva_range);
666 void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
670 * This sequence increase will notify the kvm page fault that
671 * the page that is going to be mapped in the spte could have
674 kvm->mmu_notifier_seq++;
677 * The above sequence increase must be visible before the
678 * below count decrease, which is ensured by the smp_wmb above
679 * in conjunction with the smp_rmb in mmu_notifier_retry().
681 kvm->mmu_notifier_count--;
684 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
685 const struct mmu_notifier_range *range)
687 struct kvm *kvm = mmu_notifier_to_kvm(mn);
688 const struct kvm_hva_range hva_range = {
689 .start = range->start,
692 .handler = (void *)kvm_null_fn,
693 .on_lock = kvm_dec_notifier_count,
694 .flush_on_ret = false,
695 .may_block = mmu_notifier_range_blockable(range),
699 __kvm_handle_hva_range(kvm, &hva_range);
701 /* Pairs with the increment in range_start(). */
702 spin_lock(&kvm->mn_invalidate_lock);
703 wake = (--kvm->mn_active_invalidate_count == 0);
704 spin_unlock(&kvm->mn_invalidate_lock);
707 * There can only be one waiter, since the wait happens under
711 rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
713 BUG_ON(kvm->mmu_notifier_count < 0);
716 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
717 struct mm_struct *mm,
721 trace_kvm_age_hva(start, end);
723 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
726 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
727 struct mm_struct *mm,
731 trace_kvm_age_hva(start, end);
734 * Even though we do not flush TLB, this will still adversely
735 * affect performance on pre-Haswell Intel EPT, where there is
736 * no EPT Access Bit to clear so that we have to tear down EPT
737 * tables instead. If we find this unacceptable, we can always
738 * add a parameter to kvm_age_hva so that it effectively doesn't
739 * do anything on clear_young.
741 * Also note that currently we never issue secondary TLB flushes
742 * from clear_young, leaving this job up to the regular system
743 * cadence. If we find this inaccurate, we might come up with a
744 * more sophisticated heuristic later.
746 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
749 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
750 struct mm_struct *mm,
751 unsigned long address)
753 trace_kvm_test_age_hva(address);
755 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
759 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
760 struct mm_struct *mm)
762 struct kvm *kvm = mmu_notifier_to_kvm(mn);
765 idx = srcu_read_lock(&kvm->srcu);
766 kvm_arch_flush_shadow_all(kvm);
767 srcu_read_unlock(&kvm->srcu, idx);
770 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
771 .invalidate_range = kvm_mmu_notifier_invalidate_range,
772 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
773 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
774 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
775 .clear_young = kvm_mmu_notifier_clear_young,
776 .test_young = kvm_mmu_notifier_test_young,
777 .change_pte = kvm_mmu_notifier_change_pte,
778 .release = kvm_mmu_notifier_release,
781 static int kvm_init_mmu_notifier(struct kvm *kvm)
783 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
784 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
787 #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
789 static int kvm_init_mmu_notifier(struct kvm *kvm)
794 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
796 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
797 static int kvm_pm_notifier_call(struct notifier_block *bl,
801 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
803 return kvm_arch_pm_notifier(kvm, state);
806 static void kvm_init_pm_notifier(struct kvm *kvm)
808 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
809 /* Suspend KVM before we suspend ftrace, RCU, etc. */
810 kvm->pm_notifier.priority = INT_MAX;
811 register_pm_notifier(&kvm->pm_notifier);
814 static void kvm_destroy_pm_notifier(struct kvm *kvm)
816 unregister_pm_notifier(&kvm->pm_notifier);
818 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
819 static void kvm_init_pm_notifier(struct kvm *kvm)
823 static void kvm_destroy_pm_notifier(struct kvm *kvm)
826 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
828 static struct kvm_memslots *kvm_alloc_memslots(void)
831 struct kvm_memslots *slots;
833 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
837 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
838 slots->id_to_index[i] = -1;
843 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
845 if (!memslot->dirty_bitmap)
848 kvfree(memslot->dirty_bitmap);
849 memslot->dirty_bitmap = NULL;
852 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
854 kvm_destroy_dirty_bitmap(slot);
856 kvm_arch_free_memslot(kvm, slot);
862 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
864 struct kvm_memory_slot *memslot;
869 kvm_for_each_memslot(memslot, slots)
870 kvm_free_memslot(kvm, memslot);
875 static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
877 switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
878 case KVM_STATS_TYPE_INSTANT:
880 case KVM_STATS_TYPE_CUMULATIVE:
881 case KVM_STATS_TYPE_PEAK:
888 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
891 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
892 kvm_vcpu_stats_header.num_desc;
894 if (!kvm->debugfs_dentry)
897 debugfs_remove_recursive(kvm->debugfs_dentry);
899 if (kvm->debugfs_stat_data) {
900 for (i = 0; i < kvm_debugfs_num_entries; i++)
901 kfree(kvm->debugfs_stat_data[i]);
902 kfree(kvm->debugfs_stat_data);
906 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
908 static DEFINE_MUTEX(kvm_debugfs_lock);
910 char dir_name[ITOA_MAX_LEN * 2];
911 struct kvm_stat_data *stat_data;
912 const struct _kvm_stats_desc *pdesc;
914 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
915 kvm_vcpu_stats_header.num_desc;
917 if (!debugfs_initialized())
920 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
921 mutex_lock(&kvm_debugfs_lock);
922 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
924 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
926 mutex_unlock(&kvm_debugfs_lock);
929 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
930 mutex_unlock(&kvm_debugfs_lock);
934 kvm->debugfs_dentry = dent;
935 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
936 sizeof(*kvm->debugfs_stat_data),
938 if (!kvm->debugfs_stat_data)
941 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
942 pdesc = &kvm_vm_stats_desc[i];
943 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
947 stat_data->kvm = kvm;
948 stat_data->desc = pdesc;
949 stat_data->kind = KVM_STAT_VM;
950 kvm->debugfs_stat_data[i] = stat_data;
951 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
952 kvm->debugfs_dentry, stat_data,
956 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
957 pdesc = &kvm_vcpu_stats_desc[i];
958 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
962 stat_data->kvm = kvm;
963 stat_data->desc = pdesc;
964 stat_data->kind = KVM_STAT_VCPU;
965 kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
966 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
967 kvm->debugfs_dentry, stat_data,
971 ret = kvm_arch_create_vm_debugfs(kvm);
973 kvm_destroy_vm_debugfs(kvm);
981 * Called after the VM is otherwise initialized, but just before adding it to
984 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
990 * Called just after removing the VM from the vm_list, but before doing any
993 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
998 * Called after per-vm debugfs created. When called kvm->debugfs_dentry should
999 * be setup already, so we can create arch-specific debugfs entries under it.
1000 * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1001 * a per-arch destroy interface is not needed.
1003 int __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1008 static struct kvm *kvm_create_vm(unsigned long type)
1010 struct kvm *kvm = kvm_arch_alloc_vm();
1015 return ERR_PTR(-ENOMEM);
1017 KVM_MMU_LOCK_INIT(kvm);
1018 mmgrab(current->mm);
1019 kvm->mm = current->mm;
1020 kvm_eventfd_init(kvm);
1021 mutex_init(&kvm->lock);
1022 mutex_init(&kvm->irq_lock);
1023 mutex_init(&kvm->slots_lock);
1024 mutex_init(&kvm->slots_arch_lock);
1025 spin_lock_init(&kvm->mn_invalidate_lock);
1026 rcuwait_init(&kvm->mn_memslots_update_rcuwait);
1028 INIT_LIST_HEAD(&kvm->devices);
1030 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1032 if (init_srcu_struct(&kvm->srcu))
1033 goto out_err_no_srcu;
1034 if (init_srcu_struct(&kvm->irq_srcu))
1035 goto out_err_no_irq_srcu;
1037 refcount_set(&kvm->users_count, 1);
1038 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1039 struct kvm_memslots *slots = kvm_alloc_memslots();
1042 goto out_err_no_arch_destroy_vm;
1043 /* Generations must be different for each address space. */
1044 slots->generation = i;
1045 rcu_assign_pointer(kvm->memslots[i], slots);
1048 for (i = 0; i < KVM_NR_BUSES; i++) {
1049 rcu_assign_pointer(kvm->buses[i],
1050 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
1052 goto out_err_no_arch_destroy_vm;
1055 kvm->max_halt_poll_ns = halt_poll_ns;
1057 r = kvm_arch_init_vm(kvm, type);
1059 goto out_err_no_arch_destroy_vm;
1061 r = hardware_enable_all();
1063 goto out_err_no_disable;
1065 #ifdef CONFIG_HAVE_KVM_IRQFD
1066 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
1069 r = kvm_init_mmu_notifier(kvm);
1071 goto out_err_no_mmu_notifier;
1073 r = kvm_arch_post_init_vm(kvm);
1077 mutex_lock(&kvm_lock);
1078 list_add(&kvm->vm_list, &vm_list);
1079 mutex_unlock(&kvm_lock);
1081 preempt_notifier_inc();
1082 kvm_init_pm_notifier(kvm);
1087 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1088 if (kvm->mmu_notifier.ops)
1089 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1091 out_err_no_mmu_notifier:
1092 hardware_disable_all();
1094 kvm_arch_destroy_vm(kvm);
1095 out_err_no_arch_destroy_vm:
1096 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
1097 for (i = 0; i < KVM_NR_BUSES; i++)
1098 kfree(kvm_get_bus(kvm, i));
1099 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
1100 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
1101 cleanup_srcu_struct(&kvm->irq_srcu);
1102 out_err_no_irq_srcu:
1103 cleanup_srcu_struct(&kvm->srcu);
1105 kvm_arch_free_vm(kvm);
1106 mmdrop(current->mm);
1110 static void kvm_destroy_devices(struct kvm *kvm)
1112 struct kvm_device *dev, *tmp;
1115 * We do not need to take the kvm->lock here, because nobody else
1116 * has a reference to the struct kvm at this point and therefore
1117 * cannot access the devices list anyhow.
1119 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1120 list_del(&dev->vm_node);
1121 dev->ops->destroy(dev);
1125 static void kvm_destroy_vm(struct kvm *kvm)
1128 struct mm_struct *mm = kvm->mm;
1130 kvm_destroy_pm_notifier(kvm);
1131 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
1132 kvm_destroy_vm_debugfs(kvm);
1133 kvm_arch_sync_events(kvm);
1134 mutex_lock(&kvm_lock);
1135 list_del(&kvm->vm_list);
1136 mutex_unlock(&kvm_lock);
1137 kvm_arch_pre_destroy_vm(kvm);
1139 kvm_free_irq_routing(kvm);
1140 for (i = 0; i < KVM_NR_BUSES; i++) {
1141 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
1144 kvm_io_bus_destroy(bus);
1145 kvm->buses[i] = NULL;
1147 kvm_coalesced_mmio_free(kvm);
1148 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1149 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
1151 * At this point, pending calls to invalidate_range_start()
1152 * have completed but no more MMU notifiers will run, so
1153 * mn_active_invalidate_count may remain unbalanced.
1154 * No threads can be waiting in install_new_memslots as the
1155 * last reference on KVM has been dropped, but freeing
1156 * memslots would deadlock without this manual intervention.
1158 WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1159 kvm->mn_active_invalidate_count = 0;
1161 kvm_arch_flush_shadow_all(kvm);
1163 kvm_arch_destroy_vm(kvm);
1164 kvm_destroy_devices(kvm);
1165 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
1166 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
1167 cleanup_srcu_struct(&kvm->irq_srcu);
1168 cleanup_srcu_struct(&kvm->srcu);
1169 kvm_arch_free_vm(kvm);
1170 preempt_notifier_dec();
1171 hardware_disable_all();
1175 void kvm_get_kvm(struct kvm *kvm)
1177 refcount_inc(&kvm->users_count);
1179 EXPORT_SYMBOL_GPL(kvm_get_kvm);
1182 * Make sure the vm is not during destruction, which is a safe version of
1183 * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise.
1185 bool kvm_get_kvm_safe(struct kvm *kvm)
1187 return refcount_inc_not_zero(&kvm->users_count);
1189 EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1191 void kvm_put_kvm(struct kvm *kvm)
1193 if (refcount_dec_and_test(&kvm->users_count))
1194 kvm_destroy_vm(kvm);
1196 EXPORT_SYMBOL_GPL(kvm_put_kvm);
1199 * Used to put a reference that was taken on behalf of an object associated
1200 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1201 * of the new file descriptor fails and the reference cannot be transferred to
1202 * its final owner. In such cases, the caller is still actively using @kvm and
1203 * will fail miserably if the refcount unexpectedly hits zero.
1205 void kvm_put_kvm_no_destroy(struct kvm *kvm)
1207 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1209 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
1211 static int kvm_vm_release(struct inode *inode, struct file *filp)
1213 struct kvm *kvm = filp->private_data;
1215 kvm_irqfd_release(kvm);
1222 * Allocation size is twice as large as the actual dirty bitmap size.
1223 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
1225 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
1227 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
1229 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
1230 if (!memslot->dirty_bitmap)
1237 * Delete a memslot by decrementing the number of used slots and shifting all
1238 * other entries in the array forward one spot.
1240 static inline void kvm_memslot_delete(struct kvm_memslots *slots,
1241 struct kvm_memory_slot *memslot)
1243 struct kvm_memory_slot *mslots = slots->memslots;
1246 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
1249 slots->used_slots--;
1251 if (atomic_read(&slots->last_used_slot) >= slots->used_slots)
1252 atomic_set(&slots->last_used_slot, 0);
1254 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
1255 mslots[i] = mslots[i + 1];
1256 slots->id_to_index[mslots[i].id] = i;
1258 mslots[i] = *memslot;
1259 slots->id_to_index[memslot->id] = -1;
1263 * "Insert" a new memslot by incrementing the number of used slots. Returns
1264 * the new slot's initial index into the memslots array.
1266 static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
1268 return slots->used_slots++;
1272 * Move a changed memslot backwards in the array by shifting existing slots
1273 * with a higher GFN toward the front of the array. Note, the changed memslot
1274 * itself is not preserved in the array, i.e. not swapped at this time, only
1275 * its new index into the array is tracked. Returns the changed memslot's
1276 * current index into the memslots array.
1278 static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
1279 struct kvm_memory_slot *memslot)
1281 struct kvm_memory_slot *mslots = slots->memslots;
1284 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
1285 WARN_ON_ONCE(!slots->used_slots))
1289 * Move the target memslot backward in the array by shifting existing
1290 * memslots with a higher GFN (than the target memslot) towards the
1291 * front of the array.
1293 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
1294 if (memslot->base_gfn > mslots[i + 1].base_gfn)
1297 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
1299 /* Shift the next memslot forward one and update its index. */
1300 mslots[i] = mslots[i + 1];
1301 slots->id_to_index[mslots[i].id] = i;
1307 * Move a changed memslot forwards in the array by shifting existing slots with
1308 * a lower GFN toward the back of the array. Note, the changed memslot itself
1309 * is not preserved in the array, i.e. not swapped at this time, only its new
1310 * index into the array is tracked. Returns the changed memslot's final index
1311 * into the memslots array.
1313 static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
1314 struct kvm_memory_slot *memslot,
1317 struct kvm_memory_slot *mslots = slots->memslots;
1320 for (i = start; i > 0; i--) {
1321 if (memslot->base_gfn < mslots[i - 1].base_gfn)
1324 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
1326 /* Shift the next memslot back one and update its index. */
1327 mslots[i] = mslots[i - 1];
1328 slots->id_to_index[mslots[i].id] = i;
1334 * Re-sort memslots based on their GFN to account for an added, deleted, or
1335 * moved memslot. Sorting memslots by GFN allows using a binary search during
1338 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
1339 * at memslots[0] has the highest GFN.
1341 * The sorting algorithm takes advantage of having initially sorted memslots
1342 * and knowing the position of the changed memslot. Sorting is also optimized
1343 * by not swapping the updated memslot and instead only shifting other memslots
1344 * and tracking the new index for the update memslot. Only once its final
1345 * index is known is the updated memslot copied into its position in the array.
1347 * - When deleting a memslot, the deleted memslot simply needs to be moved to
1348 * the end of the array.
1350 * - When creating a memslot, the algorithm "inserts" the new memslot at the
1351 * end of the array and then it forward to its correct location.
1353 * - When moving a memslot, the algorithm first moves the updated memslot
1354 * backward to handle the scenario where the memslot's GFN was changed to a
1355 * lower value. update_memslots() then falls through and runs the same flow
1356 * as creating a memslot to move the memslot forward to handle the scenario
1357 * where its GFN was changed to a higher value.
1359 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1360 * historical reasons. Originally, invalid memslots where denoted by having
1361 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1362 * to the end of the array. The current algorithm uses dedicated logic to
1363 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1365 * The other historical motiviation for highest->lowest was to improve the
1366 * performance of memslot lookup. KVM originally used a linear search starting
1367 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1368 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1369 * single memslot above the 4gb boundary. As the largest memslot is also the
1370 * most likely to be referenced, sorting it to the front of the array was
1371 * advantageous. The current binary search starts from the middle of the array
1372 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1374 static void update_memslots(struct kvm_memslots *slots,
1375 struct kvm_memory_slot *memslot,
1376 enum kvm_mr_change change)
1380 if (change == KVM_MR_DELETE) {
1381 kvm_memslot_delete(slots, memslot);
1383 if (change == KVM_MR_CREATE)
1384 i = kvm_memslot_insert_back(slots);
1386 i = kvm_memslot_move_backward(slots, memslot);
1387 i = kvm_memslot_move_forward(slots, memslot, i);
1390 * Copy the memslot to its new position in memslots and update
1391 * its index accordingly.
1393 slots->memslots[i] = *memslot;
1394 slots->id_to_index[memslot->id] = i;
1398 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
1400 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1402 #ifdef __KVM_HAVE_READONLY_MEM
1403 valid_flags |= KVM_MEM_READONLY;
1406 if (mem->flags & ~valid_flags)
1412 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
1413 int as_id, struct kvm_memslots *slots)
1415 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
1416 u64 gen = old_memslots->generation;
1418 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1419 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1422 * Do not store the new memslots while there are invalidations in
1423 * progress, otherwise the locking in invalidate_range_start and
1424 * invalidate_range_end will be unbalanced.
1426 spin_lock(&kvm->mn_invalidate_lock);
1427 prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1428 while (kvm->mn_active_invalidate_count) {
1429 set_current_state(TASK_UNINTERRUPTIBLE);
1430 spin_unlock(&kvm->mn_invalidate_lock);
1432 spin_lock(&kvm->mn_invalidate_lock);
1434 finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
1435 rcu_assign_pointer(kvm->memslots[as_id], slots);
1436 spin_unlock(&kvm->mn_invalidate_lock);
1439 * Acquired in kvm_set_memslot. Must be released before synchronize
1440 * SRCU below in order to avoid deadlock with another thread
1441 * acquiring the slots_arch_lock in an srcu critical section.
1443 mutex_unlock(&kvm->slots_arch_lock);
1445 synchronize_srcu_expedited(&kvm->srcu);
1448 * Increment the new memslot generation a second time, dropping the
1449 * update in-progress flag and incrementing the generation based on
1450 * the number of address spaces. This provides a unique and easily
1451 * identifiable generation number while the memslots are in flux.
1453 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1456 * Generations must be unique even across address spaces. We do not need
1457 * a global counter for that, instead the generation space is evenly split
1458 * across address spaces. For example, with two address spaces, address
1459 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1460 * use generations 1, 3, 5, ...
1462 gen += KVM_ADDRESS_SPACE_NUM;
1464 kvm_arch_memslots_updated(kvm, gen);
1466 slots->generation = gen;
1468 return old_memslots;
1471 static size_t kvm_memslots_size(int slots)
1473 return sizeof(struct kvm_memslots) +
1474 (sizeof(struct kvm_memory_slot) * slots);
1477 static void kvm_copy_memslots(struct kvm_memslots *to,
1478 struct kvm_memslots *from)
1480 memcpy(to, from, kvm_memslots_size(from->used_slots));
1484 * Note, at a minimum, the current number of used slots must be allocated, even
1485 * when deleting a memslot, as we need a complete duplicate of the memslots for
1486 * use when invalidating a memslot prior to deleting/moving the memslot.
1488 static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1489 enum kvm_mr_change change)
1491 struct kvm_memslots *slots;
1494 if (change == KVM_MR_CREATE)
1495 new_size = kvm_memslots_size(old->used_slots + 1);
1497 new_size = kvm_memslots_size(old->used_slots);
1499 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1501 kvm_copy_memslots(slots, old);
1506 static int kvm_set_memslot(struct kvm *kvm,
1507 const struct kvm_userspace_memory_region *mem,
1508 struct kvm_memory_slot *old,
1509 struct kvm_memory_slot *new, int as_id,
1510 enum kvm_mr_change change)
1512 struct kvm_memory_slot *slot;
1513 struct kvm_memslots *slots;
1517 * Released in install_new_memslots.
1519 * Must be held from before the current memslots are copied until
1520 * after the new memslots are installed with rcu_assign_pointer,
1521 * then released before the synchronize srcu in install_new_memslots.
1523 * When modifying memslots outside of the slots_lock, must be held
1524 * before reading the pointer to the current memslots until after all
1525 * changes to those memslots are complete.
1527 * These rules ensure that installing new memslots does not lose
1528 * changes made to the previous memslots.
1530 mutex_lock(&kvm->slots_arch_lock);
1532 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
1534 mutex_unlock(&kvm->slots_arch_lock);
1538 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1540 * Note, the INVALID flag needs to be in the appropriate entry
1541 * in the freshly allocated memslots, not in @old or @new.
1543 slot = id_to_memslot(slots, old->id);
1544 slot->flags |= KVM_MEMSLOT_INVALID;
1547 * We can re-use the memory from the old memslots.
1548 * It will be overwritten with a copy of the new memslots
1549 * after reacquiring the slots_arch_lock below.
1551 slots = install_new_memslots(kvm, as_id, slots);
1553 /* From this point no new shadow pages pointing to a deleted,
1554 * or moved, memslot will be created.
1556 * validation of sp->gfn happens in:
1557 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1558 * - kvm_is_visible_gfn (mmu_check_root)
1560 kvm_arch_flush_shadow_memslot(kvm, slot);
1562 /* Released in install_new_memslots. */
1563 mutex_lock(&kvm->slots_arch_lock);
1566 * The arch-specific fields of the memslots could have changed
1567 * between releasing the slots_arch_lock in
1568 * install_new_memslots and here, so get a fresh copy of the
1571 kvm_copy_memslots(slots, __kvm_memslots(kvm, as_id));
1574 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1578 update_memslots(slots, new, change);
1579 slots = install_new_memslots(kvm, as_id, slots);
1581 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1587 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1588 slot = id_to_memslot(slots, old->id);
1589 slot->flags &= ~KVM_MEMSLOT_INVALID;
1590 slots = install_new_memslots(kvm, as_id, slots);
1592 mutex_unlock(&kvm->slots_arch_lock);
1598 static int kvm_delete_memslot(struct kvm *kvm,
1599 const struct kvm_userspace_memory_region *mem,
1600 struct kvm_memory_slot *old, int as_id)
1602 struct kvm_memory_slot new;
1608 memset(&new, 0, sizeof(new));
1611 * This is only for debugging purpose; it should never be referenced
1612 * for a removed memslot.
1616 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1620 kvm_free_memslot(kvm, old);
1625 * Allocate some memory and give it an address in the guest physical address
1628 * Discontiguous memory is allowed, mostly for framebuffers.
1630 * Must be called holding kvm->slots_lock for write.
1632 int __kvm_set_memory_region(struct kvm *kvm,
1633 const struct kvm_userspace_memory_region *mem)
1635 struct kvm_memory_slot old, new;
1636 struct kvm_memory_slot *tmp;
1637 enum kvm_mr_change change;
1641 r = check_memory_region_flags(mem);
1645 as_id = mem->slot >> 16;
1646 id = (u16)mem->slot;
1648 /* General sanity checks */
1649 if (mem->memory_size & (PAGE_SIZE - 1))
1651 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
1653 /* We can read the guest memory with __xxx_user() later on. */
1654 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
1655 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
1656 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
1659 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
1661 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
1665 * Make a full copy of the old memslot, the pointer will become stale
1666 * when the memslots are re-sorted by update_memslots(), and the old
1667 * memslot needs to be referenced after calling update_memslots(), e.g.
1668 * to free its resources and for arch specific behavior.
1670 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1675 memset(&old, 0, sizeof(old));
1679 if (!mem->memory_size)
1680 return kvm_delete_memslot(kvm, mem, &old, as_id);
1684 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1685 new.npages = mem->memory_size >> PAGE_SHIFT;
1686 new.flags = mem->flags;
1687 new.userspace_addr = mem->userspace_addr;
1689 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1693 change = KVM_MR_CREATE;
1694 new.dirty_bitmap = NULL;
1695 memset(&new.arch, 0, sizeof(new.arch));
1696 } else { /* Modify an existing slot. */
1697 if ((new.userspace_addr != old.userspace_addr) ||
1698 (new.npages != old.npages) ||
1699 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1702 if (new.base_gfn != old.base_gfn)
1703 change = KVM_MR_MOVE;
1704 else if (new.flags != old.flags)
1705 change = KVM_MR_FLAGS_ONLY;
1706 else /* Nothing to change. */
1709 /* Copy dirty_bitmap and arch from the current memslot. */
1710 new.dirty_bitmap = old.dirty_bitmap;
1711 memcpy(&new.arch, &old.arch, sizeof(new.arch));
1714 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1715 /* Check for overlaps */
1716 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1719 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1720 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
1725 /* Allocate/free page dirty bitmap as needed */
1726 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1727 new.dirty_bitmap = NULL;
1728 else if (!new.dirty_bitmap && !kvm->dirty_ring_size) {
1729 r = kvm_alloc_dirty_bitmap(&new);
1733 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1734 bitmap_set(new.dirty_bitmap, 0, new.npages);
1737 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1741 if (old.dirty_bitmap && !new.dirty_bitmap)
1742 kvm_destroy_dirty_bitmap(&old);
1746 if (new.dirty_bitmap && !old.dirty_bitmap)
1747 kvm_destroy_dirty_bitmap(&new);
1750 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1752 int kvm_set_memory_region(struct kvm *kvm,
1753 const struct kvm_userspace_memory_region *mem)
1757 mutex_lock(&kvm->slots_lock);
1758 r = __kvm_set_memory_region(kvm, mem);
1759 mutex_unlock(&kvm->slots_lock);
1762 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1764 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1765 struct kvm_userspace_memory_region *mem)
1767 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1770 return kvm_set_memory_region(kvm, mem);
1773 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1775 * kvm_get_dirty_log - get a snapshot of dirty pages
1776 * @kvm: pointer to kvm instance
1777 * @log: slot id and address to which we copy the log
1778 * @is_dirty: set to '1' if any dirty pages were found
1779 * @memslot: set to the associated memslot, always valid on success
1781 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1782 int *is_dirty, struct kvm_memory_slot **memslot)
1784 struct kvm_memslots *slots;
1787 unsigned long any = 0;
1789 /* Dirty ring tracking is exclusive to dirty log tracking */
1790 if (kvm->dirty_ring_size)
1796 as_id = log->slot >> 16;
1797 id = (u16)log->slot;
1798 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1801 slots = __kvm_memslots(kvm, as_id);
1802 *memslot = id_to_memslot(slots, id);
1803 if (!(*memslot) || !(*memslot)->dirty_bitmap)
1806 kvm_arch_sync_dirty_log(kvm, *memslot);
1808 n = kvm_dirty_bitmap_bytes(*memslot);
1810 for (i = 0; !any && i < n/sizeof(long); ++i)
1811 any = (*memslot)->dirty_bitmap[i];
1813 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
1820 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1822 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1824 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
1825 * and reenable dirty page tracking for the corresponding pages.
1826 * @kvm: pointer to kvm instance
1827 * @log: slot id and address to which we copy the log
1829 * We need to keep it in mind that VCPU threads can write to the bitmap
1830 * concurrently. So, to avoid losing track of dirty pages we keep the
1833 * 1. Take a snapshot of the bit and clear it if needed.
1834 * 2. Write protect the corresponding page.
1835 * 3. Copy the snapshot to the userspace.
1836 * 4. Upon return caller flushes TLB's if needed.
1838 * Between 2 and 4, the guest may write to the page using the remaining TLB
1839 * entry. This is not a problem because the page is reported dirty using
1840 * the snapshot taken before and step 4 ensures that writes done after
1841 * exiting to userspace will be logged for the next call.
1844 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
1846 struct kvm_memslots *slots;
1847 struct kvm_memory_slot *memslot;
1850 unsigned long *dirty_bitmap;
1851 unsigned long *dirty_bitmap_buffer;
1854 /* Dirty ring tracking is exclusive to dirty log tracking */
1855 if (kvm->dirty_ring_size)
1858 as_id = log->slot >> 16;
1859 id = (u16)log->slot;
1860 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1863 slots = __kvm_memslots(kvm, as_id);
1864 memslot = id_to_memslot(slots, id);
1865 if (!memslot || !memslot->dirty_bitmap)
1868 dirty_bitmap = memslot->dirty_bitmap;
1870 kvm_arch_sync_dirty_log(kvm, memslot);
1872 n = kvm_dirty_bitmap_bytes(memslot);
1874 if (kvm->manual_dirty_log_protect) {
1876 * Unlike kvm_get_dirty_log, we always return false in *flush,
1877 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1878 * is some code duplication between this function and
1879 * kvm_get_dirty_log, but hopefully all architecture
1880 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1881 * can be eliminated.
1883 dirty_bitmap_buffer = dirty_bitmap;
1885 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1886 memset(dirty_bitmap_buffer, 0, n);
1889 for (i = 0; i < n / sizeof(long); i++) {
1893 if (!dirty_bitmap[i])
1897 mask = xchg(&dirty_bitmap[i], 0);
1898 dirty_bitmap_buffer[i] = mask;
1900 offset = i * BITS_PER_LONG;
1901 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1904 KVM_MMU_UNLOCK(kvm);
1908 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1910 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1917 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1918 * @kvm: kvm instance
1919 * @log: slot id and address to which we copy the log
1921 * Steps 1-4 below provide general overview of dirty page logging. See
1922 * kvm_get_dirty_log_protect() function description for additional details.
1924 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1925 * always flush the TLB (step 4) even if previous step failed and the dirty
1926 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1927 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1928 * writes will be marked dirty for next log read.
1930 * 1. Take a snapshot of the bit and clear it if needed.
1931 * 2. Write protect the corresponding page.
1932 * 3. Copy the snapshot to the userspace.
1933 * 4. Flush TLB's if needed.
1935 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1936 struct kvm_dirty_log *log)
1940 mutex_lock(&kvm->slots_lock);
1942 r = kvm_get_dirty_log_protect(kvm, log);
1944 mutex_unlock(&kvm->slots_lock);
1949 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1950 * and reenable dirty page tracking for the corresponding pages.
1951 * @kvm: pointer to kvm instance
1952 * @log: slot id and address from which to fetch the bitmap of dirty pages
1954 static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1955 struct kvm_clear_dirty_log *log)
1957 struct kvm_memslots *slots;
1958 struct kvm_memory_slot *memslot;
1962 unsigned long *dirty_bitmap;
1963 unsigned long *dirty_bitmap_buffer;
1966 /* Dirty ring tracking is exclusive to dirty log tracking */
1967 if (kvm->dirty_ring_size)
1970 as_id = log->slot >> 16;
1971 id = (u16)log->slot;
1972 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1975 if (log->first_page & 63)
1978 slots = __kvm_memslots(kvm, as_id);
1979 memslot = id_to_memslot(slots, id);
1980 if (!memslot || !memslot->dirty_bitmap)
1983 dirty_bitmap = memslot->dirty_bitmap;
1985 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
1987 if (log->first_page > memslot->npages ||
1988 log->num_pages > memslot->npages - log->first_page ||
1989 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1992 kvm_arch_sync_dirty_log(kvm, memslot);
1995 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1996 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2000 for (offset = log->first_page, i = offset / BITS_PER_LONG,
2001 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
2002 i++, offset += BITS_PER_LONG) {
2003 unsigned long mask = *dirty_bitmap_buffer++;
2004 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2008 mask &= atomic_long_fetch_andnot(mask, p);
2011 * mask contains the bits that really have been cleared. This
2012 * never includes any bits beyond the length of the memslot (if
2013 * the length is not aligned to 64 pages), therefore it is not
2014 * a problem if userspace sets them in log->dirty_bitmap.
2018 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2022 KVM_MMU_UNLOCK(kvm);
2025 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2030 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2031 struct kvm_clear_dirty_log *log)
2035 mutex_lock(&kvm->slots_lock);
2037 r = kvm_clear_dirty_log_protect(kvm, log);
2039 mutex_unlock(&kvm->slots_lock);
2042 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
2044 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2046 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2048 EXPORT_SYMBOL_GPL(gfn_to_memslot);
2050 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2052 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2053 struct kvm_memory_slot *slot;
2056 slot = try_get_memslot(slots, vcpu->last_used_slot, gfn);
2061 * Fall back to searching all memslots. We purposely use
2062 * search_memslots() instead of __gfn_to_memslot() to avoid
2063 * thrashing the VM-wide last_used_index in kvm_memslots.
2065 slot = search_memslots(slots, gfn, &slot_index);
2067 vcpu->last_used_slot = slot_index;
2073 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
2075 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
2077 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
2079 return kvm_is_visible_memslot(memslot);
2081 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2083 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2085 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2087 return kvm_is_visible_memslot(memslot);
2089 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2091 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
2093 struct vm_area_struct *vma;
2094 unsigned long addr, size;
2098 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
2099 if (kvm_is_error_hva(addr))
2102 mmap_read_lock(current->mm);
2103 vma = find_vma(current->mm, addr);
2107 size = vma_kernel_pagesize(vma);
2110 mmap_read_unlock(current->mm);
2115 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
2117 return slot->flags & KVM_MEM_READONLY;
2120 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2121 gfn_t *nr_pages, bool write)
2123 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
2124 return KVM_HVA_ERR_BAD;
2126 if (memslot_is_readonly(slot) && write)
2127 return KVM_HVA_ERR_RO_BAD;
2130 *nr_pages = slot->npages - (gfn - slot->base_gfn);
2132 return __gfn_to_hva_memslot(slot, gfn);
2135 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2138 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2141 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
2144 return gfn_to_hva_many(slot, gfn, NULL);
2146 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2148 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2150 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
2152 EXPORT_SYMBOL_GPL(gfn_to_hva);
2154 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2156 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2158 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2161 * Return the hva of a @gfn and the R/W attribute if possible.
2163 * @slot: the kvm_memory_slot which contains @gfn
2164 * @gfn: the gfn to be translated
2165 * @writable: used to return the read/write attribute of the @slot if the hva
2166 * is valid and @writable is not NULL
2168 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2169 gfn_t gfn, bool *writable)
2171 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2173 if (!kvm_is_error_hva(hva) && writable)
2174 *writable = !memslot_is_readonly(slot);
2179 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2181 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2183 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2186 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2188 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2190 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2193 static inline int check_user_page_hwpoison(unsigned long addr)
2195 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
2197 rc = get_user_pages(addr, 1, flags, NULL, NULL);
2198 return rc == -EHWPOISON;
2202 * The fast path to get the writable pfn which will be stored in @pfn,
2203 * true indicates success, otherwise false is returned. It's also the
2204 * only part that runs if we can in atomic context.
2206 static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2207 bool *writable, kvm_pfn_t *pfn)
2209 struct page *page[1];
2212 * Fast pin a writable pfn only if it is a write fault request
2213 * or the caller allows to map a writable pfn for a read fault
2216 if (!(write_fault || writable))
2219 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
2220 *pfn = page_to_pfn(page[0]);
2231 * The slow path to get the pfn of the specified host virtual address,
2232 * 1 indicates success, -errno is returned if error is detected.
2234 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
2235 bool *writable, kvm_pfn_t *pfn)
2237 unsigned int flags = FOLL_HWPOISON;
2244 *writable = write_fault;
2247 flags |= FOLL_WRITE;
2249 flags |= FOLL_NOWAIT;
2251 npages = get_user_pages_unlocked(addr, 1, &page, flags);
2255 /* map read fault as writable if possible */
2256 if (unlikely(!write_fault) && writable) {
2259 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
2265 *pfn = page_to_pfn(page);
2269 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2271 if (unlikely(!(vma->vm_flags & VM_READ)))
2274 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2280 static int kvm_try_get_pfn(kvm_pfn_t pfn)
2282 if (kvm_is_reserved_pfn(pfn))
2284 return get_page_unless_zero(pfn_to_page(pfn));
2287 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2288 unsigned long addr, bool *async,
2289 bool write_fault, bool *writable,
2297 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2300 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2301 * not call the fault handler, so do it here.
2303 bool unlocked = false;
2304 r = fixup_user_fault(current->mm, addr,
2305 (write_fault ? FAULT_FLAG_WRITE : 0),
2312 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
2317 if (write_fault && !pte_write(*ptep)) {
2318 pfn = KVM_PFN_ERR_RO_FAULT;
2323 *writable = pte_write(*ptep);
2324 pfn = pte_pfn(*ptep);
2327 * Get a reference here because callers of *hva_to_pfn* and
2328 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2329 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2330 * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
2331 * simply do nothing for reserved pfns.
2333 * Whoever called remap_pfn_range is also going to call e.g.
2334 * unmap_mapping_range before the underlying pages are freed,
2335 * causing a call to our MMU notifier.
2337 * Certain IO or PFNMAP mappings can be backed with valid
2338 * struct pages, but be allocated without refcounting e.g.,
2339 * tail pages of non-compound higher order allocations, which
2340 * would then underflow the refcount when the caller does the
2341 * required put_page. Don't allow those pages here.
2343 if (!kvm_try_get_pfn(pfn))
2347 pte_unmap_unlock(ptep, ptl);
2354 * Pin guest page in memory and return its pfn.
2355 * @addr: host virtual address which maps memory to the guest
2356 * @atomic: whether this function can sleep
2357 * @async: whether this function need to wait IO complete if the
2358 * host page is not in the memory
2359 * @write_fault: whether we should get a writable host page
2360 * @writable: whether it allows to map a writable host page for !@write_fault
2362 * The function will map a writable host page for these two cases:
2363 * 1): @write_fault = true
2364 * 2): @write_fault = false && @writable, @writable will tell the caller
2365 * whether the mapping is writable.
2367 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
2368 bool write_fault, bool *writable)
2370 struct vm_area_struct *vma;
2374 /* we can do it either atomically or asynchronously, not both */
2375 BUG_ON(atomic && async);
2377 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
2381 return KVM_PFN_ERR_FAULT;
2383 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2387 mmap_read_lock(current->mm);
2388 if (npages == -EHWPOISON ||
2389 (!async && check_user_page_hwpoison(addr))) {
2390 pfn = KVM_PFN_ERR_HWPOISON;
2395 vma = vma_lookup(current->mm, addr);
2398 pfn = KVM_PFN_ERR_FAULT;
2399 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
2400 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
2404 pfn = KVM_PFN_ERR_FAULT;
2406 if (async && vma_is_valid(vma, write_fault))
2408 pfn = KVM_PFN_ERR_FAULT;
2411 mmap_read_unlock(current->mm);
2415 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
2416 bool atomic, bool *async, bool write_fault,
2417 bool *writable, hva_t *hva)
2419 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2424 if (addr == KVM_HVA_ERR_RO_BAD) {
2427 return KVM_PFN_ERR_RO_FAULT;
2430 if (kvm_is_error_hva(addr)) {
2433 return KVM_PFN_NOSLOT;
2436 /* Do not map writable pfn in the readonly memslot. */
2437 if (writable && memslot_is_readonly(slot)) {
2442 return hva_to_pfn(addr, atomic, async, write_fault,
2445 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
2447 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
2450 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2451 write_fault, writable, NULL);
2453 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2455 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
2457 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
2459 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
2461 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
2463 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
2465 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2467 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
2469 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2471 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2473 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
2475 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2477 EXPORT_SYMBOL_GPL(gfn_to_pfn);
2479 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2481 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2483 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2485 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2486 struct page **pages, int nr_pages)
2491 addr = gfn_to_hva_many(slot, gfn, &entry);
2492 if (kvm_is_error_hva(addr))
2495 if (entry < nr_pages)
2498 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
2500 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2502 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
2504 if (is_error_noslot_pfn(pfn))
2505 return KVM_ERR_PTR_BAD_PAGE;
2507 if (kvm_is_reserved_pfn(pfn)) {
2509 return KVM_ERR_PTR_BAD_PAGE;
2512 return pfn_to_page(pfn);
2515 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2519 pfn = gfn_to_pfn(kvm, gfn);
2521 return kvm_pfn_to_page(pfn);
2523 EXPORT_SYMBOL_GPL(gfn_to_page);
2525 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2531 cache->pfn = cache->gfn = 0;
2534 kvm_release_pfn_dirty(pfn);
2536 kvm_release_pfn_clean(pfn);
2539 static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2540 struct gfn_to_pfn_cache *cache, u64 gen)
2542 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2544 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2546 cache->dirty = false;
2547 cache->generation = gen;
2550 static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
2551 struct kvm_host_map *map,
2552 struct gfn_to_pfn_cache *cache,
2557 struct page *page = KVM_UNMAPPED_PAGE;
2558 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
2559 u64 gen = slots->generation;
2565 if (!cache->pfn || cache->gfn != gfn ||
2566 cache->generation != gen) {
2569 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2575 pfn = gfn_to_pfn_memslot(slot, gfn);
2577 if (is_error_noslot_pfn(pfn))
2580 if (pfn_valid(pfn)) {
2581 page = pfn_to_page(pfn);
2583 hva = kmap_atomic(page);
2586 #ifdef CONFIG_HAS_IOMEM
2587 } else if (!atomic) {
2588 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
2605 int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2606 struct gfn_to_pfn_cache *cache, bool atomic)
2608 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2611 EXPORT_SYMBOL_GPL(kvm_map_gfn);
2613 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2615 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2618 EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2620 static void __kvm_unmap_gfn(struct kvm *kvm,
2621 struct kvm_memory_slot *memslot,
2622 struct kvm_host_map *map,
2623 struct gfn_to_pfn_cache *cache,
2624 bool dirty, bool atomic)
2632 if (map->page != KVM_UNMAPPED_PAGE) {
2634 kunmap_atomic(map->hva);
2638 #ifdef CONFIG_HAS_IOMEM
2642 WARN_ONCE(1, "Unexpected unmapping in atomic context");
2646 mark_page_dirty_in_slot(kvm, memslot, map->gfn);
2649 cache->dirty |= dirty;
2651 kvm_release_pfn(map->pfn, dirty, NULL);
2657 int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2658 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
2660 __kvm_unmap_gfn(vcpu->kvm, gfn_to_memslot(vcpu->kvm, map->gfn), map,
2661 cache, dirty, atomic);
2664 EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2666 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2668 __kvm_unmap_gfn(vcpu->kvm, kvm_vcpu_gfn_to_memslot(vcpu, map->gfn),
2669 map, NULL, dirty, false);
2671 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2673 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2677 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2679 return kvm_pfn_to_page(pfn);
2681 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2683 void kvm_release_page_clean(struct page *page)
2685 WARN_ON(is_error_page(page));
2687 kvm_release_pfn_clean(page_to_pfn(page));
2689 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2691 void kvm_release_pfn_clean(kvm_pfn_t pfn)
2693 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
2694 put_page(pfn_to_page(pfn));
2696 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2698 void kvm_release_page_dirty(struct page *page)
2700 WARN_ON(is_error_page(page));
2702 kvm_release_pfn_dirty(page_to_pfn(page));
2704 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
2706 void kvm_release_pfn_dirty(kvm_pfn_t pfn)
2708 kvm_set_pfn_dirty(pfn);
2709 kvm_release_pfn_clean(pfn);
2711 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
2713 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
2715 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2716 SetPageDirty(pfn_to_page(pfn));
2718 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2720 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
2722 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2723 mark_page_accessed(pfn_to_page(pfn));
2725 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2727 static int next_segment(unsigned long len, int offset)
2729 if (len > PAGE_SIZE - offset)
2730 return PAGE_SIZE - offset;
2735 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2736 void *data, int offset, int len)
2741 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2742 if (kvm_is_error_hva(addr))
2744 r = __copy_from_user(data, (void __user *)addr + offset, len);
2750 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2753 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2755 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2757 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2759 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2760 int offset, int len)
2762 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2764 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2766 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2768 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2770 gfn_t gfn = gpa >> PAGE_SHIFT;
2772 int offset = offset_in_page(gpa);
2775 while ((seg = next_segment(len, offset)) != 0) {
2776 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2786 EXPORT_SYMBOL_GPL(kvm_read_guest);
2788 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2790 gfn_t gfn = gpa >> PAGE_SHIFT;
2792 int offset = offset_in_page(gpa);
2795 while ((seg = next_segment(len, offset)) != 0) {
2796 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2806 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2808 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2809 void *data, int offset, unsigned long len)
2814 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
2815 if (kvm_is_error_hva(addr))
2817 pagefault_disable();
2818 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
2825 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2826 void *data, unsigned long len)
2828 gfn_t gfn = gpa >> PAGE_SHIFT;
2829 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2830 int offset = offset_in_page(gpa);
2832 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2834 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2836 static int __kvm_write_guest_page(struct kvm *kvm,
2837 struct kvm_memory_slot *memslot, gfn_t gfn,
2838 const void *data, int offset, int len)
2843 addr = gfn_to_hva_memslot(memslot, gfn);
2844 if (kvm_is_error_hva(addr))
2846 r = __copy_to_user((void __user *)addr + offset, data, len);
2849 mark_page_dirty_in_slot(kvm, memslot, gfn);
2853 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2854 const void *data, int offset, int len)
2856 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2858 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
2860 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2862 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2863 const void *data, int offset, int len)
2865 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2867 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
2869 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2871 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2874 gfn_t gfn = gpa >> PAGE_SHIFT;
2876 int offset = offset_in_page(gpa);
2879 while ((seg = next_segment(len, offset)) != 0) {
2880 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2890 EXPORT_SYMBOL_GPL(kvm_write_guest);
2892 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2895 gfn_t gfn = gpa >> PAGE_SHIFT;
2897 int offset = offset_in_page(gpa);
2900 while ((seg = next_segment(len, offset)) != 0) {
2901 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2911 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2913 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2914 struct gfn_to_hva_cache *ghc,
2915 gpa_t gpa, unsigned long len)
2917 int offset = offset_in_page(gpa);
2918 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2919 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2920 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2921 gfn_t nr_pages_avail;
2923 /* Update ghc->generation before performing any error checks. */
2924 ghc->generation = slots->generation;
2926 if (start_gfn > end_gfn) {
2927 ghc->hva = KVM_HVA_ERR_BAD;
2932 * If the requested region crosses two memslots, we still
2933 * verify that the entire region is valid here.
2935 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
2936 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2937 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2939 if (kvm_is_error_hva(ghc->hva))
2943 /* Use the slow path for cross page reads and writes. */
2944 if (nr_pages_needed == 1)
2947 ghc->memslot = NULL;
2954 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2955 gpa_t gpa, unsigned long len)
2957 struct kvm_memslots *slots = kvm_memslots(kvm);
2958 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2960 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2962 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2963 void *data, unsigned int offset,
2966 struct kvm_memslots *slots = kvm_memslots(kvm);
2968 gpa_t gpa = ghc->gpa + offset;
2970 BUG_ON(len + offset > ghc->len);
2972 if (slots->generation != ghc->generation) {
2973 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2977 if (kvm_is_error_hva(ghc->hva))
2980 if (unlikely(!ghc->memslot))
2981 return kvm_write_guest(kvm, gpa, data, len);
2983 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2986 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
2990 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2992 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2993 void *data, unsigned long len)
2995 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2997 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2999 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3000 void *data, unsigned int offset,
3003 struct kvm_memslots *slots = kvm_memslots(kvm);
3005 gpa_t gpa = ghc->gpa + offset;
3007 BUG_ON(len + offset > ghc->len);
3009 if (slots->generation != ghc->generation) {
3010 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3014 if (kvm_is_error_hva(ghc->hva))
3017 if (unlikely(!ghc->memslot))
3018 return kvm_read_guest(kvm, gpa, data, len);
3020 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
3026 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3028 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3029 void *data, unsigned long len)
3031 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3033 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
3035 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3037 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3038 gfn_t gfn = gpa >> PAGE_SHIFT;
3040 int offset = offset_in_page(gpa);
3043 while ((seg = next_segment(len, offset)) != 0) {
3044 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
3053 EXPORT_SYMBOL_GPL(kvm_clear_guest);
3055 void mark_page_dirty_in_slot(struct kvm *kvm,
3056 struct kvm_memory_slot *memslot,
3059 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
3060 unsigned long rel_gfn = gfn - memslot->base_gfn;
3061 u32 slot = (memslot->as_id << 16) | memslot->id;
3063 if (kvm->dirty_ring_size)
3064 kvm_dirty_ring_push(kvm_dirty_ring_get(kvm),
3067 set_bit_le(rel_gfn, memslot->dirty_bitmap);
3070 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
3072 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3074 struct kvm_memory_slot *memslot;
3076 memslot = gfn_to_memslot(kvm, gfn);
3077 mark_page_dirty_in_slot(kvm, memslot, gfn);
3079 EXPORT_SYMBOL_GPL(mark_page_dirty);
3081 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3083 struct kvm_memory_slot *memslot;
3085 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3086 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
3088 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3090 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3092 if (!vcpu->sigset_active)
3096 * This does a lockless modification of ->real_blocked, which is fine
3097 * because, only current can change ->real_blocked and all readers of
3098 * ->real_blocked don't care as long ->real_blocked is always a subset
3101 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked);
3104 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3106 if (!vcpu->sigset_active)
3109 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL);
3110 sigemptyset(¤t->real_blocked);
3113 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3115 unsigned int old, val, grow, grow_start;
3117 old = val = vcpu->halt_poll_ns;
3118 grow_start = READ_ONCE(halt_poll_ns_grow_start);
3119 grow = READ_ONCE(halt_poll_ns_grow);
3124 if (val < grow_start)
3127 if (val > vcpu->kvm->max_halt_poll_ns)
3128 val = vcpu->kvm->max_halt_poll_ns;
3130 vcpu->halt_poll_ns = val;
3132 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
3135 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3137 unsigned int old, val, shrink;
3139 old = val = vcpu->halt_poll_ns;
3140 shrink = READ_ONCE(halt_poll_ns_shrink);
3146 vcpu->halt_poll_ns = val;
3147 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
3150 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3153 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3155 if (kvm_arch_vcpu_runnable(vcpu)) {
3156 kvm_make_request(KVM_REQ_UNHALT, vcpu);
3159 if (kvm_cpu_has_pending_timer(vcpu))
3161 if (signal_pending(current))
3163 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3168 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3173 update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
3176 vcpu->stat.generic.halt_poll_fail_ns += poll_ns;
3178 vcpu->stat.generic.halt_poll_success_ns += poll_ns;
3182 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
3184 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
3186 ktime_t start, cur, poll_end;
3187 bool waited = false;
3190 kvm_arch_vcpu_blocking(vcpu);
3192 start = cur = poll_end = ktime_get();
3193 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
3194 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
3196 ++vcpu->stat.generic.halt_attempted_poll;
3199 * This sets KVM_REQ_UNHALT if an interrupt
3202 if (kvm_vcpu_check_block(vcpu) < 0) {
3203 ++vcpu->stat.generic.halt_successful_poll;
3204 if (!vcpu_valid_wakeup(vcpu))
3205 ++vcpu->stat.generic.halt_poll_invalid;
3207 KVM_STATS_LOG_HIST_UPDATE(
3208 vcpu->stat.generic.halt_poll_success_hist,
3209 ktime_to_ns(ktime_get()) -
3210 ktime_to_ns(start));
3214 poll_end = cur = ktime_get();
3215 } while (kvm_vcpu_can_poll(cur, stop));
3217 KVM_STATS_LOG_HIST_UPDATE(
3218 vcpu->stat.generic.halt_poll_fail_hist,
3219 ktime_to_ns(ktime_get()) - ktime_to_ns(start));
3223 prepare_to_rcuwait(&vcpu->wait);
3225 set_current_state(TASK_INTERRUPTIBLE);
3227 if (kvm_vcpu_check_block(vcpu) < 0)
3233 finish_rcuwait(&vcpu->wait);
3236 vcpu->stat.generic.halt_wait_ns +=
3237 ktime_to_ns(cur) - ktime_to_ns(poll_end);
3238 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
3239 ktime_to_ns(cur) - ktime_to_ns(poll_end));
3242 kvm_arch_vcpu_unblocking(vcpu);
3243 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3245 update_halt_poll_stats(
3246 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
3248 if (!kvm_arch_no_poll(vcpu)) {
3249 if (!vcpu_valid_wakeup(vcpu)) {
3250 shrink_halt_poll_ns(vcpu);
3251 } else if (vcpu->kvm->max_halt_poll_ns) {
3252 if (block_ns <= vcpu->halt_poll_ns)
3254 /* we had a long block, shrink polling */
3255 else if (vcpu->halt_poll_ns &&
3256 block_ns > vcpu->kvm->max_halt_poll_ns)
3257 shrink_halt_poll_ns(vcpu);
3258 /* we had a short halt and our poll time is too small */
3259 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3260 block_ns < vcpu->kvm->max_halt_poll_ns)
3261 grow_halt_poll_ns(vcpu);
3263 vcpu->halt_poll_ns = 0;
3267 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
3268 kvm_arch_vcpu_block_finish(vcpu);
3270 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
3272 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
3274 struct rcuwait *waitp;
3276 waitp = kvm_arch_vcpu_get_wait(vcpu);
3277 if (rcuwait_wake_up(waitp)) {
3278 WRITE_ONCE(vcpu->ready, true);
3279 ++vcpu->stat.generic.halt_wakeup;
3285 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3289 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3291 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3294 int cpu = vcpu->cpu;
3296 if (kvm_vcpu_wake_up(vcpu))
3300 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3301 if (kvm_arch_vcpu_should_kick(vcpu))
3302 smp_send_reschedule(cpu);
3305 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
3306 #endif /* !CONFIG_S390 */
3308 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
3311 struct task_struct *task = NULL;
3315 pid = rcu_dereference(target->pid);
3317 task = get_pid_task(pid, PIDTYPE_PID);
3321 ret = yield_to(task, 1);
3322 put_task_struct(task);
3326 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3329 * Helper that checks whether a VCPU is eligible for directed yield.
3330 * Most eligible candidate to yield is decided by following heuristics:
3332 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3333 * (preempted lock holder), indicated by @in_spin_loop.
3334 * Set at the beginning and cleared at the end of interception/PLE handler.
3336 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3337 * chance last time (mostly it has become eligible now since we have probably
3338 * yielded to lockholder in last iteration. This is done by toggling
3339 * @dy_eligible each time a VCPU checked for eligibility.)
3341 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3342 * to preempted lock-holder could result in wrong VCPU selection and CPU
3343 * burning. Giving priority for a potential lock-holder increases lock
3346 * Since algorithm is based on heuristics, accessing another VCPU data without
3347 * locking does not harm. It may result in trying to yield to same VCPU, fail
3348 * and continue with next VCPU and so on.
3350 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
3352 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3355 eligible = !vcpu->spin_loop.in_spin_loop ||
3356 vcpu->spin_loop.dy_eligible;
3358 if (vcpu->spin_loop.in_spin_loop)
3359 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3368 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3369 * a vcpu_load/vcpu_put pair. However, for most architectures
3370 * kvm_arch_vcpu_runnable does not require vcpu_load.
3372 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3374 return kvm_arch_vcpu_runnable(vcpu);
3377 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3379 if (kvm_arch_dy_runnable(vcpu))
3382 #ifdef CONFIG_KVM_ASYNC_PF
3383 if (!list_empty_careful(&vcpu->async_pf.done))
3390 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3395 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
3397 struct kvm *kvm = me->kvm;
3398 struct kvm_vcpu *vcpu;
3399 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3405 kvm_vcpu_set_in_spin_loop(me, true);
3407 * We boost the priority of a VCPU that is runnable but not
3408 * currently running, because it got preempted by something
3409 * else and called schedule in __vcpu_run. Hopefully that
3410 * VCPU is holding the lock that we need and will release it.
3411 * We approximate round-robin by starting at the last boosted VCPU.
3413 for (pass = 0; pass < 2 && !yielded && try; pass++) {
3414 kvm_for_each_vcpu(i, vcpu, kvm) {
3415 if (!pass && i <= last_boosted_vcpu) {
3416 i = last_boosted_vcpu;
3418 } else if (pass && i > last_boosted_vcpu)
3420 if (!READ_ONCE(vcpu->ready))
3424 if (rcuwait_active(&vcpu->wait) &&
3425 !vcpu_dy_runnable(vcpu))
3427 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
3428 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3429 !kvm_arch_vcpu_in_kernel(vcpu))
3431 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3434 yielded = kvm_vcpu_yield_to(vcpu);
3436 kvm->last_boosted_vcpu = i;
3438 } else if (yielded < 0) {
3445 kvm_vcpu_set_in_spin_loop(me, false);
3447 /* Ensure vcpu is not eligible during next spinloop */
3448 kvm_vcpu_set_dy_eligible(me, false);
3450 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3452 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3454 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3455 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3456 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3457 kvm->dirty_ring_size / PAGE_SIZE);
3463 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
3465 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
3468 if (vmf->pgoff == 0)
3469 page = virt_to_page(vcpu->run);
3471 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
3472 page = virt_to_page(vcpu->arch.pio_data);
3474 #ifdef CONFIG_KVM_MMIO
3475 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3476 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3478 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3479 page = kvm_dirty_ring_get_page(
3481 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
3483 return kvm_arch_vcpu_fault(vcpu, vmf);
3489 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
3490 .fault = kvm_vcpu_fault,
3493 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3495 struct kvm_vcpu *vcpu = file->private_data;
3496 unsigned long pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
3498 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3499 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3500 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3503 vma->vm_ops = &kvm_vcpu_vm_ops;
3507 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3509 struct kvm_vcpu *vcpu = filp->private_data;
3511 kvm_put_kvm(vcpu->kvm);
3515 static struct file_operations kvm_vcpu_fops = {
3516 .release = kvm_vcpu_release,
3517 .unlocked_ioctl = kvm_vcpu_ioctl,
3518 .mmap = kvm_vcpu_mmap,
3519 .llseek = noop_llseek,
3520 KVM_COMPAT(kvm_vcpu_compat_ioctl),
3524 * Allocates an inode for the vcpu.
3526 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3528 char name[8 + 1 + ITOA_MAX_LEN + 1];
3530 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3531 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
3534 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
3536 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
3537 struct dentry *debugfs_dentry;
3538 char dir_name[ITOA_MAX_LEN * 2];
3540 if (!debugfs_initialized())
3543 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
3544 debugfs_dentry = debugfs_create_dir(dir_name,
3545 vcpu->kvm->debugfs_dentry);
3547 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
3552 * Creates some virtual cpus. Good luck creating more than one.
3554 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
3557 struct kvm_vcpu *vcpu;
3560 if (id >= KVM_MAX_VCPU_ID)
3563 mutex_lock(&kvm->lock);
3564 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3565 mutex_unlock(&kvm->lock);
3569 kvm->created_vcpus++;
3570 mutex_unlock(&kvm->lock);
3572 r = kvm_arch_vcpu_precreate(kvm, id);
3574 goto vcpu_decrement;
3576 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
3579 goto vcpu_decrement;
3582 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
3583 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3588 vcpu->run = page_address(page);
3590 kvm_vcpu_init(vcpu, kvm, id);
3592 r = kvm_arch_vcpu_create(vcpu);
3594 goto vcpu_free_run_page;
3596 if (kvm->dirty_ring_size) {
3597 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3598 id, kvm->dirty_ring_size);
3600 goto arch_vcpu_destroy;
3603 mutex_lock(&kvm->lock);
3604 if (kvm_get_vcpu_by_id(kvm, id)) {
3606 goto unlock_vcpu_destroy;
3609 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3610 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
3612 /* Fill the stats id string for the vcpu */
3613 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3614 task_pid_nr(current), id);
3616 /* Now it's all set up, let userspace reach it */
3618 r = create_vcpu_fd(vcpu);
3620 kvm_put_kvm_no_destroy(kvm);
3621 goto unlock_vcpu_destroy;
3624 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
3627 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3628 * before kvm->online_vcpu's incremented value.
3631 atomic_inc(&kvm->online_vcpus);
3633 mutex_unlock(&kvm->lock);
3634 kvm_arch_vcpu_postcreate(vcpu);
3635 kvm_create_vcpu_debugfs(vcpu);
3638 unlock_vcpu_destroy:
3639 mutex_unlock(&kvm->lock);
3640 kvm_dirty_ring_free(&vcpu->dirty_ring);
3642 kvm_arch_vcpu_destroy(vcpu);
3644 free_page((unsigned long)vcpu->run);
3646 kmem_cache_free(kvm_vcpu_cache, vcpu);
3648 mutex_lock(&kvm->lock);
3649 kvm->created_vcpus--;
3650 mutex_unlock(&kvm->lock);
3654 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3657 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3658 vcpu->sigset_active = 1;
3659 vcpu->sigset = *sigset;
3661 vcpu->sigset_active = 0;
3665 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3666 size_t size, loff_t *offset)
3668 struct kvm_vcpu *vcpu = file->private_data;
3670 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3671 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3672 sizeof(vcpu->stat), user_buffer, size, offset);
3675 static const struct file_operations kvm_vcpu_stats_fops = {
3676 .read = kvm_vcpu_stats_read,
3677 .llseek = noop_llseek,
3680 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3684 char name[15 + ITOA_MAX_LEN + 1];
3686 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3688 fd = get_unused_fd_flags(O_CLOEXEC);
3692 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3695 return PTR_ERR(file);
3697 file->f_mode |= FMODE_PREAD;
3698 fd_install(fd, file);
3703 static long kvm_vcpu_ioctl(struct file *filp,
3704 unsigned int ioctl, unsigned long arg)
3706 struct kvm_vcpu *vcpu = filp->private_data;
3707 void __user *argp = (void __user *)arg;
3709 struct kvm_fpu *fpu = NULL;
3710 struct kvm_sregs *kvm_sregs = NULL;
3712 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
3715 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3719 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3720 * execution; mutex_lock() would break them.
3722 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3723 if (r != -ENOIOCTLCMD)
3726 if (mutex_lock_killable(&vcpu->mutex))
3734 oldpid = rcu_access_pointer(vcpu->pid);
3735 if (unlikely(oldpid != task_pid(current))) {
3736 /* The thread running this VCPU changed. */
3739 r = kvm_arch_vcpu_run_pid_change(vcpu);
3743 newpid = get_task_pid(current, PIDTYPE_PID);
3744 rcu_assign_pointer(vcpu->pid, newpid);
3749 r = kvm_arch_vcpu_ioctl_run(vcpu);
3750 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
3753 case KVM_GET_REGS: {
3754 struct kvm_regs *kvm_regs;
3757 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
3760 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
3764 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3771 case KVM_SET_REGS: {
3772 struct kvm_regs *kvm_regs;
3774 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3775 if (IS_ERR(kvm_regs)) {
3776 r = PTR_ERR(kvm_regs);
3779 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
3783 case KVM_GET_SREGS: {
3784 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3785 GFP_KERNEL_ACCOUNT);
3789 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
3793 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
3798 case KVM_SET_SREGS: {
3799 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3800 if (IS_ERR(kvm_sregs)) {
3801 r = PTR_ERR(kvm_sregs);
3805 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
3808 case KVM_GET_MP_STATE: {
3809 struct kvm_mp_state mp_state;
3811 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3815 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
3820 case KVM_SET_MP_STATE: {
3821 struct kvm_mp_state mp_state;
3824 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
3826 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
3829 case KVM_TRANSLATE: {
3830 struct kvm_translation tr;
3833 if (copy_from_user(&tr, argp, sizeof(tr)))
3835 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
3839 if (copy_to_user(argp, &tr, sizeof(tr)))
3844 case KVM_SET_GUEST_DEBUG: {
3845 struct kvm_guest_debug dbg;
3848 if (copy_from_user(&dbg, argp, sizeof(dbg)))
3850 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
3853 case KVM_SET_SIGNAL_MASK: {
3854 struct kvm_signal_mask __user *sigmask_arg = argp;
3855 struct kvm_signal_mask kvm_sigmask;
3856 sigset_t sigset, *p;
3861 if (copy_from_user(&kvm_sigmask, argp,
3862 sizeof(kvm_sigmask)))
3865 if (kvm_sigmask.len != sizeof(sigset))
3868 if (copy_from_user(&sigset, sigmask_arg->sigset,
3873 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
3877 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
3881 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
3885 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
3891 fpu = memdup_user(argp, sizeof(*fpu));
3897 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
3900 case KVM_GET_STATS_FD: {
3901 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
3905 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
3908 mutex_unlock(&vcpu->mutex);
3914 #ifdef CONFIG_KVM_COMPAT
3915 static long kvm_vcpu_compat_ioctl(struct file *filp,
3916 unsigned int ioctl, unsigned long arg)
3918 struct kvm_vcpu *vcpu = filp->private_data;
3919 void __user *argp = compat_ptr(arg);
3922 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
3926 case KVM_SET_SIGNAL_MASK: {
3927 struct kvm_signal_mask __user *sigmask_arg = argp;
3928 struct kvm_signal_mask kvm_sigmask;
3933 if (copy_from_user(&kvm_sigmask, argp,
3934 sizeof(kvm_sigmask)))
3937 if (kvm_sigmask.len != sizeof(compat_sigset_t))
3940 if (get_compat_sigset(&sigset,
3941 (compat_sigset_t __user *)sigmask_arg->sigset))
3943 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3945 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3949 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3957 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3959 struct kvm_device *dev = filp->private_data;
3962 return dev->ops->mmap(dev, vma);
3967 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3968 int (*accessor)(struct kvm_device *dev,
3969 struct kvm_device_attr *attr),
3972 struct kvm_device_attr attr;
3977 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3980 return accessor(dev, &attr);
3983 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3986 struct kvm_device *dev = filp->private_data;
3988 if (dev->kvm->mm != current->mm || dev->kvm->vm_bugged)
3992 case KVM_SET_DEVICE_ATTR:
3993 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3994 case KVM_GET_DEVICE_ATTR:
3995 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3996 case KVM_HAS_DEVICE_ATTR:
3997 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3999 if (dev->ops->ioctl)
4000 return dev->ops->ioctl(dev, ioctl, arg);
4006 static int kvm_device_release(struct inode *inode, struct file *filp)
4008 struct kvm_device *dev = filp->private_data;
4009 struct kvm *kvm = dev->kvm;
4011 if (dev->ops->release) {
4012 mutex_lock(&kvm->lock);
4013 list_del(&dev->vm_node);
4014 dev->ops->release(dev);
4015 mutex_unlock(&kvm->lock);
4022 static const struct file_operations kvm_device_fops = {
4023 .unlocked_ioctl = kvm_device_ioctl,
4024 .release = kvm_device_release,
4025 KVM_COMPAT(kvm_device_ioctl),
4026 .mmap = kvm_device_mmap,
4029 struct kvm_device *kvm_device_from_filp(struct file *filp)
4031 if (filp->f_op != &kvm_device_fops)
4034 return filp->private_data;
4037 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
4038 #ifdef CONFIG_KVM_MPIC
4039 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
4040 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
4044 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
4046 if (type >= ARRAY_SIZE(kvm_device_ops_table))
4049 if (kvm_device_ops_table[type] != NULL)
4052 kvm_device_ops_table[type] = ops;
4056 void kvm_unregister_device_ops(u32 type)
4058 if (kvm_device_ops_table[type] != NULL)
4059 kvm_device_ops_table[type] = NULL;
4062 static int kvm_ioctl_create_device(struct kvm *kvm,
4063 struct kvm_create_device *cd)
4065 const struct kvm_device_ops *ops = NULL;
4066 struct kvm_device *dev;
4067 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
4071 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
4074 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4075 ops = kvm_device_ops_table[type];
4082 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
4089 mutex_lock(&kvm->lock);
4090 ret = ops->create(dev, type);
4092 mutex_unlock(&kvm->lock);
4096 list_add(&dev->vm_node, &kvm->devices);
4097 mutex_unlock(&kvm->lock);
4103 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
4105 kvm_put_kvm_no_destroy(kvm);
4106 mutex_lock(&kvm->lock);
4107 list_del(&dev->vm_node);
4108 mutex_unlock(&kvm->lock);
4117 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4120 case KVM_CAP_USER_MEMORY:
4121 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4122 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
4123 case KVM_CAP_INTERNAL_ERROR_DATA:
4124 #ifdef CONFIG_HAVE_KVM_MSI
4125 case KVM_CAP_SIGNAL_MSI:
4127 #ifdef CONFIG_HAVE_KVM_IRQFD
4129 case KVM_CAP_IRQFD_RESAMPLE:
4131 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
4132 case KVM_CAP_CHECK_EXTENSION_VM:
4133 case KVM_CAP_ENABLE_CAP_VM:
4134 case KVM_CAP_HALT_POLL:
4136 #ifdef CONFIG_KVM_MMIO
4137 case KVM_CAP_COALESCED_MMIO:
4138 return KVM_COALESCED_MMIO_PAGE_OFFSET;
4139 case KVM_CAP_COALESCED_PIO:
4142 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4143 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4144 return KVM_DIRTY_LOG_MANUAL_CAPS;
4146 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4147 case KVM_CAP_IRQ_ROUTING:
4148 return KVM_MAX_IRQ_ROUTES;
4150 #if KVM_ADDRESS_SPACE_NUM > 1
4151 case KVM_CAP_MULTI_ADDRESS_SPACE:
4152 return KVM_ADDRESS_SPACE_NUM;
4154 case KVM_CAP_NR_MEMSLOTS:
4155 return KVM_USER_MEM_SLOTS;
4156 case KVM_CAP_DIRTY_LOG_RING:
4157 #if KVM_DIRTY_LOG_PAGE_OFFSET > 0
4158 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4162 case KVM_CAP_BINARY_STATS_FD:
4167 return kvm_vm_ioctl_check_extension(kvm, arg);
4170 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4174 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4177 /* the size should be power of 2 */
4178 if (!size || (size & (size - 1)))
4181 /* Should be bigger to keep the reserved entries, or a page */
4182 if (size < kvm_dirty_ring_get_rsvd_entries() *
4183 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4186 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4187 sizeof(struct kvm_dirty_gfn))
4190 /* We only allow it to set once */
4191 if (kvm->dirty_ring_size)
4194 mutex_lock(&kvm->lock);
4196 if (kvm->created_vcpus) {
4197 /* We don't allow to change this value after vcpu created */
4200 kvm->dirty_ring_size = size;
4204 mutex_unlock(&kvm->lock);
4208 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4211 struct kvm_vcpu *vcpu;
4214 if (!kvm->dirty_ring_size)
4217 mutex_lock(&kvm->slots_lock);
4219 kvm_for_each_vcpu(i, vcpu, kvm)
4220 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4222 mutex_unlock(&kvm->slots_lock);
4225 kvm_flush_remote_tlbs(kvm);
4230 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4231 struct kvm_enable_cap *cap)
4236 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4237 struct kvm_enable_cap *cap)
4240 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4241 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4242 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4244 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4245 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4247 if (cap->flags || (cap->args[0] & ~allowed_options))
4249 kvm->manual_dirty_log_protect = cap->args[0];
4253 case KVM_CAP_HALT_POLL: {
4254 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4257 kvm->max_halt_poll_ns = cap->args[0];
4260 case KVM_CAP_DIRTY_LOG_RING:
4261 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
4263 return kvm_vm_ioctl_enable_cap(kvm, cap);
4267 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4268 size_t size, loff_t *offset)
4270 struct kvm *kvm = file->private_data;
4272 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4273 &kvm_vm_stats_desc[0], &kvm->stat,
4274 sizeof(kvm->stat), user_buffer, size, offset);
4277 static const struct file_operations kvm_vm_stats_fops = {
4278 .read = kvm_vm_stats_read,
4279 .llseek = noop_llseek,
4282 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4287 fd = get_unused_fd_flags(O_CLOEXEC);
4291 file = anon_inode_getfile("kvm-vm-stats",
4292 &kvm_vm_stats_fops, kvm, O_RDONLY);
4295 return PTR_ERR(file);
4297 file->f_mode |= FMODE_PREAD;
4298 fd_install(fd, file);
4303 static long kvm_vm_ioctl(struct file *filp,
4304 unsigned int ioctl, unsigned long arg)
4306 struct kvm *kvm = filp->private_data;
4307 void __user *argp = (void __user *)arg;
4310 if (kvm->mm != current->mm || kvm->vm_bugged)
4313 case KVM_CREATE_VCPU:
4314 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
4316 case KVM_ENABLE_CAP: {
4317 struct kvm_enable_cap cap;
4320 if (copy_from_user(&cap, argp, sizeof(cap)))
4322 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4325 case KVM_SET_USER_MEMORY_REGION: {
4326 struct kvm_userspace_memory_region kvm_userspace_mem;
4329 if (copy_from_user(&kvm_userspace_mem, argp,
4330 sizeof(kvm_userspace_mem)))
4333 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
4336 case KVM_GET_DIRTY_LOG: {
4337 struct kvm_dirty_log log;
4340 if (copy_from_user(&log, argp, sizeof(log)))
4342 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4345 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4346 case KVM_CLEAR_DIRTY_LOG: {
4347 struct kvm_clear_dirty_log log;
4350 if (copy_from_user(&log, argp, sizeof(log)))
4352 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4356 #ifdef CONFIG_KVM_MMIO
4357 case KVM_REGISTER_COALESCED_MMIO: {
4358 struct kvm_coalesced_mmio_zone zone;
4361 if (copy_from_user(&zone, argp, sizeof(zone)))
4363 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
4366 case KVM_UNREGISTER_COALESCED_MMIO: {
4367 struct kvm_coalesced_mmio_zone zone;
4370 if (copy_from_user(&zone, argp, sizeof(zone)))
4372 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
4377 struct kvm_irqfd data;
4380 if (copy_from_user(&data, argp, sizeof(data)))
4382 r = kvm_irqfd(kvm, &data);
4385 case KVM_IOEVENTFD: {
4386 struct kvm_ioeventfd data;
4389 if (copy_from_user(&data, argp, sizeof(data)))
4391 r = kvm_ioeventfd(kvm, &data);
4394 #ifdef CONFIG_HAVE_KVM_MSI
4395 case KVM_SIGNAL_MSI: {
4399 if (copy_from_user(&msi, argp, sizeof(msi)))
4401 r = kvm_send_userspace_msi(kvm, &msi);
4405 #ifdef __KVM_HAVE_IRQ_LINE
4406 case KVM_IRQ_LINE_STATUS:
4407 case KVM_IRQ_LINE: {
4408 struct kvm_irq_level irq_event;
4411 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
4414 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4415 ioctl == KVM_IRQ_LINE_STATUS);
4420 if (ioctl == KVM_IRQ_LINE_STATUS) {
4421 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
4429 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4430 case KVM_SET_GSI_ROUTING: {
4431 struct kvm_irq_routing routing;
4432 struct kvm_irq_routing __user *urouting;
4433 struct kvm_irq_routing_entry *entries = NULL;
4436 if (copy_from_user(&routing, argp, sizeof(routing)))
4439 if (!kvm_arch_can_set_irq_routing(kvm))
4441 if (routing.nr > KVM_MAX_IRQ_ROUTES)
4447 entries = vmemdup_user(urouting->entries,
4448 array_size(sizeof(*entries),
4450 if (IS_ERR(entries)) {
4451 r = PTR_ERR(entries);
4455 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4460 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
4461 case KVM_CREATE_DEVICE: {
4462 struct kvm_create_device cd;
4465 if (copy_from_user(&cd, argp, sizeof(cd)))
4468 r = kvm_ioctl_create_device(kvm, &cd);
4473 if (copy_to_user(argp, &cd, sizeof(cd)))
4479 case KVM_CHECK_EXTENSION:
4480 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4482 case KVM_RESET_DIRTY_RINGS:
4483 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4485 case KVM_GET_STATS_FD:
4486 r = kvm_vm_ioctl_get_stats_fd(kvm);
4489 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
4495 #ifdef CONFIG_KVM_COMPAT
4496 struct compat_kvm_dirty_log {
4500 compat_uptr_t dirty_bitmap; /* one bit per page */
4505 struct compat_kvm_clear_dirty_log {
4510 compat_uptr_t dirty_bitmap; /* one bit per page */
4515 static long kvm_vm_compat_ioctl(struct file *filp,
4516 unsigned int ioctl, unsigned long arg)
4518 struct kvm *kvm = filp->private_data;
4521 if (kvm->mm != current->mm || kvm->vm_bugged)
4524 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4525 case KVM_CLEAR_DIRTY_LOG: {
4526 struct compat_kvm_clear_dirty_log compat_log;
4527 struct kvm_clear_dirty_log log;
4529 if (copy_from_user(&compat_log, (void __user *)arg,
4530 sizeof(compat_log)))
4532 log.slot = compat_log.slot;
4533 log.num_pages = compat_log.num_pages;
4534 log.first_page = compat_log.first_page;
4535 log.padding2 = compat_log.padding2;
4536 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4538 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4542 case KVM_GET_DIRTY_LOG: {
4543 struct compat_kvm_dirty_log compat_log;
4544 struct kvm_dirty_log log;
4546 if (copy_from_user(&compat_log, (void __user *)arg,
4547 sizeof(compat_log)))
4549 log.slot = compat_log.slot;
4550 log.padding1 = compat_log.padding1;
4551 log.padding2 = compat_log.padding2;
4552 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4554 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
4558 r = kvm_vm_ioctl(filp, ioctl, arg);
4564 static struct file_operations kvm_vm_fops = {
4565 .release = kvm_vm_release,
4566 .unlocked_ioctl = kvm_vm_ioctl,
4567 .llseek = noop_llseek,
4568 KVM_COMPAT(kvm_vm_compat_ioctl),
4571 bool file_is_kvm(struct file *file)
4573 return file && file->f_op == &kvm_vm_fops;
4575 EXPORT_SYMBOL_GPL(file_is_kvm);
4577 static int kvm_dev_ioctl_create_vm(unsigned long type)
4583 kvm = kvm_create_vm(type);
4585 return PTR_ERR(kvm);
4586 #ifdef CONFIG_KVM_MMIO
4587 r = kvm_coalesced_mmio_init(kvm);
4591 r = get_unused_fd_flags(O_CLOEXEC);
4595 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4596 "kvm-%d", task_pid_nr(current));
4598 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4606 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4607 * already set, with ->release() being kvm_vm_release(). In error
4608 * cases it will be called by the final fput(file) and will take
4609 * care of doing kvm_put_kvm(kvm).
4611 if (kvm_create_vm_debugfs(kvm, r) < 0) {
4616 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
4618 fd_install(r, file);
4626 static long kvm_dev_ioctl(struct file *filp,
4627 unsigned int ioctl, unsigned long arg)
4632 case KVM_GET_API_VERSION:
4635 r = KVM_API_VERSION;
4638 r = kvm_dev_ioctl_create_vm(arg);
4640 case KVM_CHECK_EXTENSION:
4641 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
4643 case KVM_GET_VCPU_MMAP_SIZE:
4646 r = PAGE_SIZE; /* struct kvm_run */
4648 r += PAGE_SIZE; /* pio data page */
4650 #ifdef CONFIG_KVM_MMIO
4651 r += PAGE_SIZE; /* coalesced mmio ring page */
4654 case KVM_TRACE_ENABLE:
4655 case KVM_TRACE_PAUSE:
4656 case KVM_TRACE_DISABLE:
4660 return kvm_arch_dev_ioctl(filp, ioctl, arg);
4666 static struct file_operations kvm_chardev_ops = {
4667 .unlocked_ioctl = kvm_dev_ioctl,
4668 .llseek = noop_llseek,
4669 KVM_COMPAT(kvm_dev_ioctl),
4672 static struct miscdevice kvm_dev = {
4678 static void hardware_enable_nolock(void *junk)
4680 int cpu = raw_smp_processor_id();
4683 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
4686 cpumask_set_cpu(cpu, cpus_hardware_enabled);
4688 r = kvm_arch_hardware_enable();
4691 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4692 atomic_inc(&hardware_enable_failed);
4693 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
4697 static int kvm_starting_cpu(unsigned int cpu)
4699 raw_spin_lock(&kvm_count_lock);
4700 if (kvm_usage_count)
4701 hardware_enable_nolock(NULL);
4702 raw_spin_unlock(&kvm_count_lock);
4706 static void hardware_disable_nolock(void *junk)
4708 int cpu = raw_smp_processor_id();
4710 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
4712 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4713 kvm_arch_hardware_disable();
4716 static int kvm_dying_cpu(unsigned int cpu)
4718 raw_spin_lock(&kvm_count_lock);
4719 if (kvm_usage_count)
4720 hardware_disable_nolock(NULL);
4721 raw_spin_unlock(&kvm_count_lock);
4725 static void hardware_disable_all_nolock(void)
4727 BUG_ON(!kvm_usage_count);
4730 if (!kvm_usage_count)
4731 on_each_cpu(hardware_disable_nolock, NULL, 1);
4734 static void hardware_disable_all(void)
4736 raw_spin_lock(&kvm_count_lock);
4737 hardware_disable_all_nolock();
4738 raw_spin_unlock(&kvm_count_lock);
4741 static int hardware_enable_all(void)
4745 raw_spin_lock(&kvm_count_lock);
4748 if (kvm_usage_count == 1) {
4749 atomic_set(&hardware_enable_failed, 0);
4750 on_each_cpu(hardware_enable_nolock, NULL, 1);
4752 if (atomic_read(&hardware_enable_failed)) {
4753 hardware_disable_all_nolock();
4758 raw_spin_unlock(&kvm_count_lock);
4763 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
4767 * Some (well, at least mine) BIOSes hang on reboot if
4770 * And Intel TXT required VMX off for all cpu when system shutdown.
4772 pr_info("kvm: exiting hardware virtualization\n");
4773 kvm_rebooting = true;
4774 on_each_cpu(hardware_disable_nolock, NULL, 1);
4778 static struct notifier_block kvm_reboot_notifier = {
4779 .notifier_call = kvm_reboot,
4783 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
4787 for (i = 0; i < bus->dev_count; i++) {
4788 struct kvm_io_device *pos = bus->range[i].dev;
4790 kvm_iodevice_destructor(pos);
4795 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
4796 const struct kvm_io_range *r2)
4798 gpa_t addr1 = r1->addr;
4799 gpa_t addr2 = r2->addr;
4804 /* If r2->len == 0, match the exact address. If r2->len != 0,
4805 * accept any overlapping write. Any order is acceptable for
4806 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4807 * we process all of them.
4820 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4822 return kvm_io_bus_cmp(p1, p2);
4825 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
4826 gpa_t addr, int len)
4828 struct kvm_io_range *range, key;
4831 key = (struct kvm_io_range) {
4836 range = bsearch(&key, bus->range, bus->dev_count,
4837 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4841 off = range - bus->range;
4843 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
4849 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4850 struct kvm_io_range *range, const void *val)
4854 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4858 while (idx < bus->dev_count &&
4859 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4860 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
4869 /* kvm_io_bus_write - called under kvm->slots_lock */
4870 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4871 int len, const void *val)
4873 struct kvm_io_bus *bus;
4874 struct kvm_io_range range;
4877 range = (struct kvm_io_range) {
4882 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4885 r = __kvm_io_bus_write(vcpu, bus, &range, val);
4886 return r < 0 ? r : 0;
4888 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
4890 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
4891 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4892 gpa_t addr, int len, const void *val, long cookie)
4894 struct kvm_io_bus *bus;
4895 struct kvm_io_range range;
4897 range = (struct kvm_io_range) {
4902 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4906 /* First try the device referenced by cookie. */
4907 if ((cookie >= 0) && (cookie < bus->dev_count) &&
4908 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
4909 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
4914 * cookie contained garbage; fall back to search and return the
4915 * correct cookie value.
4917 return __kvm_io_bus_write(vcpu, bus, &range, val);
4920 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4921 struct kvm_io_range *range, void *val)
4925 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4929 while (idx < bus->dev_count &&
4930 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
4931 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
4940 /* kvm_io_bus_read - called under kvm->slots_lock */
4941 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
4944 struct kvm_io_bus *bus;
4945 struct kvm_io_range range;
4948 range = (struct kvm_io_range) {
4953 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
4956 r = __kvm_io_bus_read(vcpu, bus, &range, val);
4957 return r < 0 ? r : 0;
4960 /* Caller must hold slots_lock. */
4961 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4962 int len, struct kvm_io_device *dev)
4965 struct kvm_io_bus *new_bus, *bus;
4966 struct kvm_io_range range;
4968 bus = kvm_get_bus(kvm, bus_idx);
4972 /* exclude ioeventfd which is limited by maximum fd */
4973 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
4976 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
4977 GFP_KERNEL_ACCOUNT);
4981 range = (struct kvm_io_range) {
4987 for (i = 0; i < bus->dev_count; i++)
4988 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4991 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4992 new_bus->dev_count++;
4993 new_bus->range[i] = range;
4994 memcpy(new_bus->range + i + 1, bus->range + i,
4995 (bus->dev_count - i) * sizeof(struct kvm_io_range));
4996 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4997 synchronize_srcu_expedited(&kvm->srcu);
5003 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5004 struct kvm_io_device *dev)
5007 struct kvm_io_bus *new_bus, *bus;
5009 lockdep_assert_held(&kvm->slots_lock);
5011 bus = kvm_get_bus(kvm, bus_idx);
5015 for (i = 0; i < bus->dev_count; i++) {
5016 if (bus->range[i].dev == dev) {
5021 if (i == bus->dev_count)
5024 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
5025 GFP_KERNEL_ACCOUNT);
5027 memcpy(new_bus, bus, struct_size(bus, range, i));
5028 new_bus->dev_count--;
5029 memcpy(new_bus->range + i, bus->range + i + 1,
5030 flex_array_size(new_bus, range, new_bus->dev_count - i));
5033 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5034 synchronize_srcu_expedited(&kvm->srcu);
5036 /* Destroy the old bus _after_ installing the (null) bus. */
5038 pr_err("kvm: failed to shrink bus, removing it completely\n");
5039 for (j = 0; j < bus->dev_count; j++) {
5042 kvm_iodevice_destructor(bus->range[j].dev);
5047 return new_bus ? 0 : -ENOMEM;
5050 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5053 struct kvm_io_bus *bus;
5054 int dev_idx, srcu_idx;
5055 struct kvm_io_device *iodev = NULL;
5057 srcu_idx = srcu_read_lock(&kvm->srcu);
5059 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
5063 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5067 iodev = bus->range[dev_idx].dev;
5070 srcu_read_unlock(&kvm->srcu, srcu_idx);
5074 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5076 static int kvm_debugfs_open(struct inode *inode, struct file *file,
5077 int (*get)(void *, u64 *), int (*set)(void *, u64),
5080 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5084 * The debugfs files are a reference to the kvm struct which
5085 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
5086 * avoids the race between open and the removal of the debugfs directory.
5088 if (!kvm_get_kvm_safe(stat_data->kvm))
5091 if (simple_attr_open(inode, file, get,
5092 kvm_stats_debugfs_mode(stat_data->desc) & 0222
5095 kvm_put_kvm(stat_data->kvm);
5102 static int kvm_debugfs_release(struct inode *inode, struct file *file)
5104 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5107 simple_attr_release(inode, file);
5108 kvm_put_kvm(stat_data->kvm);
5113 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
5115 *val = *(u64 *)((void *)(&kvm->stat) + offset);
5120 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
5122 *(u64 *)((void *)(&kvm->stat) + offset) = 0;
5127 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
5130 struct kvm_vcpu *vcpu;
5134 kvm_for_each_vcpu(i, vcpu, kvm)
5135 *val += *(u64 *)((void *)(&vcpu->stat) + offset);
5140 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
5143 struct kvm_vcpu *vcpu;
5145 kvm_for_each_vcpu(i, vcpu, kvm)
5146 *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
5151 static int kvm_stat_data_get(void *data, u64 *val)
5154 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5156 switch (stat_data->kind) {
5158 r = kvm_get_stat_per_vm(stat_data->kvm,
5159 stat_data->desc->desc.offset, val);
5162 r = kvm_get_stat_per_vcpu(stat_data->kvm,
5163 stat_data->desc->desc.offset, val);
5170 static int kvm_stat_data_clear(void *data, u64 val)
5173 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5178 switch (stat_data->kind) {
5180 r = kvm_clear_stat_per_vm(stat_data->kvm,
5181 stat_data->desc->desc.offset);
5184 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
5185 stat_data->desc->desc.offset);
5192 static int kvm_stat_data_open(struct inode *inode, struct file *file)
5194 __simple_attr_check_format("%llu\n", 0ull);
5195 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5196 kvm_stat_data_clear, "%llu\n");
5199 static const struct file_operations stat_fops_per_vm = {
5200 .owner = THIS_MODULE,
5201 .open = kvm_stat_data_open,
5202 .release = kvm_debugfs_release,
5203 .read = simple_attr_read,
5204 .write = simple_attr_write,
5205 .llseek = no_llseek,
5208 static int vm_stat_get(void *_offset, u64 *val)
5210 unsigned offset = (long)_offset;
5215 mutex_lock(&kvm_lock);
5216 list_for_each_entry(kvm, &vm_list, vm_list) {
5217 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
5220 mutex_unlock(&kvm_lock);
5224 static int vm_stat_clear(void *_offset, u64 val)
5226 unsigned offset = (long)_offset;
5232 mutex_lock(&kvm_lock);
5233 list_for_each_entry(kvm, &vm_list, vm_list) {
5234 kvm_clear_stat_per_vm(kvm, offset);
5236 mutex_unlock(&kvm_lock);
5241 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
5242 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
5244 static int vcpu_stat_get(void *_offset, u64 *val)
5246 unsigned offset = (long)_offset;
5251 mutex_lock(&kvm_lock);
5252 list_for_each_entry(kvm, &vm_list, vm_list) {
5253 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
5256 mutex_unlock(&kvm_lock);
5260 static int vcpu_stat_clear(void *_offset, u64 val)
5262 unsigned offset = (long)_offset;
5268 mutex_lock(&kvm_lock);
5269 list_for_each_entry(kvm, &vm_list, vm_list) {
5270 kvm_clear_stat_per_vcpu(kvm, offset);
5272 mutex_unlock(&kvm_lock);
5277 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5279 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
5281 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5283 struct kobj_uevent_env *env;
5284 unsigned long long created, active;
5286 if (!kvm_dev.this_device || !kvm)
5289 mutex_lock(&kvm_lock);
5290 if (type == KVM_EVENT_CREATE_VM) {
5291 kvm_createvm_count++;
5293 } else if (type == KVM_EVENT_DESTROY_VM) {
5296 created = kvm_createvm_count;
5297 active = kvm_active_vms;
5298 mutex_unlock(&kvm_lock);
5300 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
5304 add_uevent_var(env, "CREATED=%llu", created);
5305 add_uevent_var(env, "COUNT=%llu", active);
5307 if (type == KVM_EVENT_CREATE_VM) {
5308 add_uevent_var(env, "EVENT=create");
5309 kvm->userspace_pid = task_pid_nr(current);
5310 } else if (type == KVM_EVENT_DESTROY_VM) {
5311 add_uevent_var(env, "EVENT=destroy");
5313 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
5315 if (kvm->debugfs_dentry) {
5316 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
5319 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5321 add_uevent_var(env, "STATS_PATH=%s", tmp);
5325 /* no need for checks, since we are adding at most only 5 keys */
5326 env->envp[env->envp_idx++] = NULL;
5327 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5331 static void kvm_init_debug(void)
5333 const struct file_operations *fops;
5334 const struct _kvm_stats_desc *pdesc;
5337 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
5339 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5340 pdesc = &kvm_vm_stats_desc[i];
5341 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5342 fops = &vm_stat_fops;
5344 fops = &vm_stat_readonly_fops;
5345 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5347 (void *)(long)pdesc->desc.offset, fops);
5350 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5351 pdesc = &kvm_vcpu_stats_desc[i];
5352 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5353 fops = &vcpu_stat_fops;
5355 fops = &vcpu_stat_readonly_fops;
5356 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5358 (void *)(long)pdesc->desc.offset, fops);
5362 static int kvm_suspend(void)
5364 if (kvm_usage_count)
5365 hardware_disable_nolock(NULL);
5369 static void kvm_resume(void)
5371 if (kvm_usage_count) {
5372 #ifdef CONFIG_LOCKDEP
5373 WARN_ON(lockdep_is_held(&kvm_count_lock));
5375 hardware_enable_nolock(NULL);
5379 static struct syscore_ops kvm_syscore_ops = {
5380 .suspend = kvm_suspend,
5381 .resume = kvm_resume,
5385 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5387 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5390 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5392 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5394 WRITE_ONCE(vcpu->preempted, false);
5395 WRITE_ONCE(vcpu->ready, false);
5397 __this_cpu_write(kvm_running_vcpu, vcpu);
5398 kvm_arch_sched_in(vcpu, cpu);
5399 kvm_arch_vcpu_load(vcpu, cpu);
5402 static void kvm_sched_out(struct preempt_notifier *pn,
5403 struct task_struct *next)
5405 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5407 if (current->on_rq) {
5408 WRITE_ONCE(vcpu->preempted, true);
5409 WRITE_ONCE(vcpu->ready, true);
5411 kvm_arch_vcpu_put(vcpu);
5412 __this_cpu_write(kvm_running_vcpu, NULL);
5416 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
5418 * We can disable preemption locally around accessing the per-CPU variable,
5419 * and use the resolved vcpu pointer after enabling preemption again,
5420 * because even if the current thread is migrated to another CPU, reading
5421 * the per-CPU value later will give us the same value as we update the
5422 * per-CPU variable in the preempt notifier handlers.
5424 struct kvm_vcpu *kvm_get_running_vcpu(void)
5426 struct kvm_vcpu *vcpu;
5429 vcpu = __this_cpu_read(kvm_running_vcpu);
5434 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
5437 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5439 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5441 return &kvm_running_vcpu;
5444 struct kvm_cpu_compat_check {
5449 static void check_processor_compat(void *data)
5451 struct kvm_cpu_compat_check *c = data;
5453 *c->ret = kvm_arch_check_processor_compat(c->opaque);
5456 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
5457 struct module *module)
5459 struct kvm_cpu_compat_check c;
5463 r = kvm_arch_init(opaque);
5468 * kvm_arch_init makes sure there's at most one caller
5469 * for architectures that support multiple implementations,
5470 * like intel and amd on x86.
5471 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5472 * conflicts in case kvm is already setup for another implementation.
5474 r = kvm_irqfd_init();
5478 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
5483 r = kvm_arch_hardware_setup(opaque);
5489 for_each_online_cpu(cpu) {
5490 smp_call_function_single(cpu, check_processor_compat, &c, 1);
5495 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
5496 kvm_starting_cpu, kvm_dying_cpu);
5499 register_reboot_notifier(&kvm_reboot_notifier);
5501 /* A kmem cache lets us meet the alignment requirements of fx_save. */
5503 vcpu_align = __alignof__(struct kvm_vcpu);
5505 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5507 offsetof(struct kvm_vcpu, arch),
5508 offsetofend(struct kvm_vcpu, stats_id)
5509 - offsetof(struct kvm_vcpu, arch),
5511 if (!kvm_vcpu_cache) {
5516 r = kvm_async_pf_init();
5520 kvm_chardev_ops.owner = module;
5521 kvm_vm_fops.owner = module;
5522 kvm_vcpu_fops.owner = module;
5524 r = misc_register(&kvm_dev);
5526 pr_err("kvm: misc device register failed\n");
5530 register_syscore_ops(&kvm_syscore_ops);
5532 kvm_preempt_ops.sched_in = kvm_sched_in;
5533 kvm_preempt_ops.sched_out = kvm_sched_out;
5537 r = kvm_vfio_ops_init();
5543 kvm_async_pf_deinit();
5545 kmem_cache_destroy(kvm_vcpu_cache);
5547 unregister_reboot_notifier(&kvm_reboot_notifier);
5548 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5550 kvm_arch_hardware_unsetup();
5552 free_cpumask_var(cpus_hardware_enabled);
5560 EXPORT_SYMBOL_GPL(kvm_init);
5564 debugfs_remove_recursive(kvm_debugfs_dir);
5565 misc_deregister(&kvm_dev);
5566 kmem_cache_destroy(kvm_vcpu_cache);
5567 kvm_async_pf_deinit();
5568 unregister_syscore_ops(&kvm_syscore_ops);
5569 unregister_reboot_notifier(&kvm_reboot_notifier);
5570 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
5571 on_each_cpu(hardware_disable_nolock, NULL, 1);
5572 kvm_arch_hardware_unsetup();
5575 free_cpumask_var(cpus_hardware_enabled);
5576 kvm_vfio_ops_exit();
5578 EXPORT_SYMBOL_GPL(kvm_exit);
5580 struct kvm_vm_worker_thread_context {
5582 struct task_struct *parent;
5583 struct completion init_done;
5584 kvm_vm_thread_fn_t thread_fn;
5589 static int kvm_vm_worker_thread(void *context)
5592 * The init_context is allocated on the stack of the parent thread, so
5593 * we have to locally copy anything that is needed beyond initialization
5595 struct kvm_vm_worker_thread_context *init_context = context;
5596 struct kvm *kvm = init_context->kvm;
5597 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5598 uintptr_t data = init_context->data;
5601 err = kthread_park(current);
5602 /* kthread_park(current) is never supposed to return an error */
5607 err = cgroup_attach_task_all(init_context->parent, current);
5609 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5614 set_user_nice(current, task_nice(init_context->parent));
5617 init_context->err = err;
5618 complete(&init_context->init_done);
5619 init_context = NULL;
5624 /* Wait to be woken up by the spawner before proceeding. */
5627 if (!kthread_should_stop())
5628 err = thread_fn(kvm, data);
5633 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5634 uintptr_t data, const char *name,
5635 struct task_struct **thread_ptr)
5637 struct kvm_vm_worker_thread_context init_context = {};
5638 struct task_struct *thread;
5641 init_context.kvm = kvm;
5642 init_context.parent = current;
5643 init_context.thread_fn = thread_fn;
5644 init_context.data = data;
5645 init_completion(&init_context.init_done);
5647 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5648 "%s-%d", name, task_pid_nr(current));
5650 return PTR_ERR(thread);
5652 /* kthread_run is never supposed to return NULL */
5653 WARN_ON(thread == NULL);
5655 wait_for_completion(&init_context.init_done);
5657 if (!init_context.err)
5658 *thread_ptr = thread;
5660 return init_context.err;