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.
10 * Copyright (C) 2006 Qumranet, Inc.
11 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
22 #include "mmu_internal.h"
25 #include "kvm_cache_regs.h"
27 #include "kvm_emulate.h"
31 #include <linux/kvm_host.h>
32 #include <linux/types.h>
33 #include <linux/string.h>
35 #include <linux/highmem.h>
36 #include <linux/moduleparam.h>
37 #include <linux/export.h>
38 #include <linux/swap.h>
39 #include <linux/hugetlb.h>
40 #include <linux/compiler.h>
41 #include <linux/srcu.h>
42 #include <linux/slab.h>
43 #include <linux/sched/signal.h>
44 #include <linux/uaccess.h>
45 #include <linux/hash.h>
46 #include <linux/kern_levels.h>
47 #include <linux/kstrtox.h>
48 #include <linux/kthread.h>
51 #include <asm/memtype.h>
52 #include <asm/cmpxchg.h>
54 #include <asm/set_memory.h>
56 #include <asm/kvm_page_track.h>
59 extern bool itlb_multihit_kvm_mitigation;
61 static bool nx_hugepage_mitigation_hard_disabled;
63 int __read_mostly nx_huge_pages = -1;
64 static uint __read_mostly nx_huge_pages_recovery_period_ms;
65 #ifdef CONFIG_PREEMPT_RT
66 /* Recovery can cause latency spikes, disable it for PREEMPT_RT. */
67 static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
69 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
72 static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp);
73 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
74 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
76 static const struct kernel_param_ops nx_huge_pages_ops = {
77 .set = set_nx_huge_pages,
78 .get = get_nx_huge_pages,
81 static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
82 .set = set_nx_huge_pages_recovery_param,
83 .get = param_get_uint,
86 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
87 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
88 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
89 &nx_huge_pages_recovery_ratio, 0644);
90 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
91 module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
92 &nx_huge_pages_recovery_period_ms, 0644);
93 __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
95 static bool __read_mostly force_flush_and_sync_on_reuse;
96 module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
99 * When setting this variable to true it enables Two-Dimensional-Paging
100 * where the hardware walks 2 page tables:
101 * 1. the guest-virtual to guest-physical
102 * 2. while doing 1. it walks guest-physical to host-physical
103 * If the hardware supports that we don't need to do shadow paging.
105 bool tdp_enabled = false;
107 static bool __ro_after_init tdp_mmu_allowed;
110 bool __read_mostly tdp_mmu_enabled = true;
111 module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
114 static int max_huge_page_level __read_mostly;
115 static int tdp_root_level __read_mostly;
116 static int max_tdp_level __read_mostly;
120 module_param(dbg, bool, 0644);
123 #define PTE_PREFETCH_NUM 8
125 #include <trace/events/kvm.h>
127 /* make pte_list_desc fit well in cache lines */
128 #define PTE_LIST_EXT 14
131 * struct pte_list_desc is the core data structure used to implement a custom
132 * list for tracking a set of related SPTEs, e.g. all the SPTEs that map a
133 * given GFN when used in the context of rmaps. Using a custom list allows KVM
134 * to optimize for the common case where many GFNs will have at most a handful
135 * of SPTEs pointing at them, i.e. allows packing multiple SPTEs into a small
136 * memory footprint, which in turn improves runtime performance by exploiting
139 * A list is comprised of one or more pte_list_desc objects (descriptors).
140 * Each individual descriptor stores up to PTE_LIST_EXT SPTEs. If a descriptor
141 * is full and a new SPTEs needs to be added, a new descriptor is allocated and
142 * becomes the head of the list. This means that by definitions, all tail
143 * descriptors are full.
145 * Note, the meta data fields are deliberately placed at the start of the
146 * structure to optimize the cacheline layout; accessing the descriptor will
147 * touch only a single cacheline so long as @spte_count<=6 (or if only the
148 * descriptors metadata is accessed).
150 struct pte_list_desc {
151 struct pte_list_desc *more;
152 /* The number of PTEs stored in _this_ descriptor. */
154 /* The number of PTEs stored in all tails of this descriptor. */
156 u64 *sptes[PTE_LIST_EXT];
159 struct kvm_shadow_walk_iterator {
167 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
168 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
170 shadow_walk_okay(&(_walker)); \
171 shadow_walk_next(&(_walker)))
173 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
174 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
175 shadow_walk_okay(&(_walker)); \
176 shadow_walk_next(&(_walker)))
178 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
179 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
180 shadow_walk_okay(&(_walker)) && \
181 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
182 __shadow_walk_next(&(_walker), spte))
184 static struct kmem_cache *pte_list_desc_cache;
185 struct kmem_cache *mmu_page_header_cache;
186 static struct percpu_counter kvm_total_used_mmu_pages;
188 static void mmu_spte_set(u64 *sptep, u64 spte);
190 struct kvm_mmu_role_regs {
191 const unsigned long cr0;
192 const unsigned long cr4;
196 #define CREATE_TRACE_POINTS
197 #include "mmutrace.h"
200 * Yes, lot's of underscores. They're a hint that you probably shouldn't be
201 * reading from the role_regs. Once the root_role is constructed, it becomes
202 * the single source of truth for the MMU's state.
204 #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag) \
205 static inline bool __maybe_unused \
206 ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs) \
208 return !!(regs->reg & flag); \
210 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
211 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
212 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
213 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
214 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
215 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
216 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
217 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
218 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
219 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
222 * The MMU itself (with a valid role) is the single source of truth for the
223 * MMU. Do not use the regs used to build the MMU/role, nor the vCPU. The
224 * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
225 * and the vCPU may be incorrect/irrelevant.
227 #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name) \
228 static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu) \
230 return !!(mmu->cpu_role. base_or_ext . reg##_##name); \
232 BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
233 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pse);
234 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smep);
235 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smap);
236 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pke);
237 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, la57);
238 BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
239 BUILD_MMU_ROLE_ACCESSOR(ext, efer, lma);
241 static inline bool is_cr0_pg(struct kvm_mmu *mmu)
243 return mmu->cpu_role.base.level > 0;
246 static inline bool is_cr4_pae(struct kvm_mmu *mmu)
248 return !mmu->cpu_role.base.has_4_byte_gpte;
251 static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
253 struct kvm_mmu_role_regs regs = {
254 .cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
255 .cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
256 .efer = vcpu->arch.efer,
262 static unsigned long get_guest_cr3(struct kvm_vcpu *vcpu)
264 return kvm_read_cr3(vcpu);
267 static inline unsigned long kvm_mmu_get_guest_pgd(struct kvm_vcpu *vcpu,
270 if (IS_ENABLED(CONFIG_RETPOLINE) && mmu->get_guest_pgd == get_guest_cr3)
271 return kvm_read_cr3(vcpu);
273 return mmu->get_guest_pgd(vcpu);
276 static inline bool kvm_available_flush_remote_tlbs_range(void)
278 return kvm_x86_ops.flush_remote_tlbs_range;
281 void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t start_gfn,
284 int ret = -EOPNOTSUPP;
286 if (kvm_x86_ops.flush_remote_tlbs_range)
287 ret = static_call(kvm_x86_flush_remote_tlbs_range)(kvm, start_gfn,
290 kvm_flush_remote_tlbs(kvm);
293 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
295 /* Flush the range of guest memory mapped by the given SPTE. */
296 static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
298 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
299 gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
301 kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
304 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
307 u64 spte = make_mmio_spte(vcpu, gfn, access);
309 trace_mark_mmio_spte(sptep, gfn, spte);
310 mmu_spte_set(sptep, spte);
313 static gfn_t get_mmio_spte_gfn(u64 spte)
315 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
317 gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
318 & shadow_nonpresent_or_rsvd_mask;
320 return gpa >> PAGE_SHIFT;
323 static unsigned get_mmio_spte_access(u64 spte)
325 return spte & shadow_mmio_access_mask;
328 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
330 u64 kvm_gen, spte_gen, gen;
332 gen = kvm_vcpu_memslots(vcpu)->generation;
333 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
336 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
337 spte_gen = get_mmio_spte_generation(spte);
339 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
340 return likely(kvm_gen == spte_gen);
343 static int is_cpuid_PSE36(void)
349 static void __set_spte(u64 *sptep, u64 spte)
351 WRITE_ONCE(*sptep, spte);
354 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
356 WRITE_ONCE(*sptep, spte);
359 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
361 return xchg(sptep, spte);
364 static u64 __get_spte_lockless(u64 *sptep)
366 return READ_ONCE(*sptep);
377 static void count_spte_clear(u64 *sptep, u64 spte)
379 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
381 if (is_shadow_present_pte(spte))
384 /* Ensure the spte is completely set before we increase the count */
386 sp->clear_spte_count++;
389 static void __set_spte(u64 *sptep, u64 spte)
391 union split_spte *ssptep, sspte;
393 ssptep = (union split_spte *)sptep;
394 sspte = (union split_spte)spte;
396 ssptep->spte_high = sspte.spte_high;
399 * If we map the spte from nonpresent to present, We should store
400 * the high bits firstly, then set present bit, so cpu can not
401 * fetch this spte while we are setting the spte.
405 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
408 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
410 union split_spte *ssptep, sspte;
412 ssptep = (union split_spte *)sptep;
413 sspte = (union split_spte)spte;
415 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
418 * If we map the spte from present to nonpresent, we should clear
419 * present bit firstly to avoid vcpu fetch the old high bits.
423 ssptep->spte_high = sspte.spte_high;
424 count_spte_clear(sptep, spte);
427 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
429 union split_spte *ssptep, sspte, orig;
431 ssptep = (union split_spte *)sptep;
432 sspte = (union split_spte)spte;
434 /* xchg acts as a barrier before the setting of the high bits */
435 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
436 orig.spte_high = ssptep->spte_high;
437 ssptep->spte_high = sspte.spte_high;
438 count_spte_clear(sptep, spte);
444 * The idea using the light way get the spte on x86_32 guest is from
445 * gup_get_pte (mm/gup.c).
447 * An spte tlb flush may be pending, because kvm_set_pte_rmap
448 * coalesces them and we are running out of the MMU lock. Therefore
449 * we need to protect against in-progress updates of the spte.
451 * Reading the spte while an update is in progress may get the old value
452 * for the high part of the spte. The race is fine for a present->non-present
453 * change (because the high part of the spte is ignored for non-present spte),
454 * but for a present->present change we must reread the spte.
456 * All such changes are done in two steps (present->non-present and
457 * non-present->present), hence it is enough to count the number of
458 * present->non-present updates: if it changed while reading the spte,
459 * we might have hit the race. This is done using clear_spte_count.
461 static u64 __get_spte_lockless(u64 *sptep)
463 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
464 union split_spte spte, *orig = (union split_spte *)sptep;
468 count = sp->clear_spte_count;
471 spte.spte_low = orig->spte_low;
474 spte.spte_high = orig->spte_high;
477 if (unlikely(spte.spte_low != orig->spte_low ||
478 count != sp->clear_spte_count))
485 /* Rules for using mmu_spte_set:
486 * Set the sptep from nonpresent to present.
487 * Note: the sptep being assigned *must* be either not present
488 * or in a state where the hardware will not attempt to update
491 static void mmu_spte_set(u64 *sptep, u64 new_spte)
493 WARN_ON(is_shadow_present_pte(*sptep));
494 __set_spte(sptep, new_spte);
498 * Update the SPTE (excluding the PFN), but do not track changes in its
499 * accessed/dirty status.
501 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
503 u64 old_spte = *sptep;
505 WARN_ON(!is_shadow_present_pte(new_spte));
506 check_spte_writable_invariants(new_spte);
508 if (!is_shadow_present_pte(old_spte)) {
509 mmu_spte_set(sptep, new_spte);
513 if (!spte_has_volatile_bits(old_spte))
514 __update_clear_spte_fast(sptep, new_spte);
516 old_spte = __update_clear_spte_slow(sptep, new_spte);
518 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
523 /* Rules for using mmu_spte_update:
524 * Update the state bits, it means the mapped pfn is not changed.
526 * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
527 * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
528 * spte, even though the writable spte might be cached on a CPU's TLB.
530 * Returns true if the TLB needs to be flushed
532 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
535 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
537 if (!is_shadow_present_pte(old_spte))
541 * For the spte updated out of mmu-lock is safe, since
542 * we always atomically update it, see the comments in
543 * spte_has_volatile_bits().
545 if (is_mmu_writable_spte(old_spte) &&
546 !is_writable_pte(new_spte))
550 * Flush TLB when accessed/dirty states are changed in the page tables,
551 * to guarantee consistency between TLB and page tables.
554 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
556 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
559 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
561 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
568 * Rules for using mmu_spte_clear_track_bits:
569 * It sets the sptep from present to nonpresent, and track the
570 * state bits, it is used to clear the last level sptep.
571 * Returns the old PTE.
573 static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
576 u64 old_spte = *sptep;
577 int level = sptep_to_sp(sptep)->role.level;
580 if (!is_shadow_present_pte(old_spte) ||
581 !spte_has_volatile_bits(old_spte))
582 __update_clear_spte_fast(sptep, 0ull);
584 old_spte = __update_clear_spte_slow(sptep, 0ull);
586 if (!is_shadow_present_pte(old_spte))
589 kvm_update_page_stats(kvm, level, -1);
591 pfn = spte_to_pfn(old_spte);
594 * KVM doesn't hold a reference to any pages mapped into the guest, and
595 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
596 * before they are reclaimed. Sanity check that, if the pfn is backed
597 * by a refcounted page, the refcount is elevated.
599 page = kvm_pfn_to_refcounted_page(pfn);
600 WARN_ON(page && !page_count(page));
602 if (is_accessed_spte(old_spte))
603 kvm_set_pfn_accessed(pfn);
605 if (is_dirty_spte(old_spte))
606 kvm_set_pfn_dirty(pfn);
612 * Rules for using mmu_spte_clear_no_track:
613 * Directly clear spte without caring the state bits of sptep,
614 * it is used to set the upper level spte.
616 static void mmu_spte_clear_no_track(u64 *sptep)
618 __update_clear_spte_fast(sptep, 0ull);
621 static u64 mmu_spte_get_lockless(u64 *sptep)
623 return __get_spte_lockless(sptep);
626 /* Returns the Accessed status of the PTE and resets it at the same time. */
627 static bool mmu_spte_age(u64 *sptep)
629 u64 spte = mmu_spte_get_lockless(sptep);
631 if (!is_accessed_spte(spte))
634 if (spte_ad_enabled(spte)) {
635 clear_bit((ffs(shadow_accessed_mask) - 1),
636 (unsigned long *)sptep);
639 * Capture the dirty status of the page, so that it doesn't get
640 * lost when the SPTE is marked for access tracking.
642 if (is_writable_pte(spte))
643 kvm_set_pfn_dirty(spte_to_pfn(spte));
645 spte = mark_spte_for_access_track(spte);
646 mmu_spte_update_no_track(sptep, spte);
652 static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
654 return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
657 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
659 if (is_tdp_mmu_active(vcpu)) {
660 kvm_tdp_mmu_walk_lockless_begin();
663 * Prevent page table teardown by making any free-er wait during
664 * kvm_flush_remote_tlbs() IPI to all active vcpus.
669 * Make sure a following spte read is not reordered ahead of the write
672 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
676 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
678 if (is_tdp_mmu_active(vcpu)) {
679 kvm_tdp_mmu_walk_lockless_end();
682 * Make sure the write to vcpu->mode is not reordered in front of
683 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
684 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
686 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
691 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
695 /* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
696 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
697 1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
700 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
701 PT64_ROOT_MAX_LEVEL);
704 if (maybe_indirect) {
705 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
706 PT64_ROOT_MAX_LEVEL);
710 return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
711 PT64_ROOT_MAX_LEVEL);
714 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
716 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
717 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
718 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
719 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
722 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
724 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
727 static bool sp_has_gptes(struct kvm_mmu_page *sp);
729 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
731 if (sp->role.passthrough)
734 if (!sp->role.direct)
735 return sp->shadowed_translation[index] >> PAGE_SHIFT;
737 return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
741 * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
742 * that the SPTE itself may have a more constrained access permissions that
743 * what the guest enforces. For example, a guest may create an executable
744 * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
746 static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
748 if (sp_has_gptes(sp))
749 return sp->shadowed_translation[index] & ACC_ALL;
752 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
753 * KVM is not shadowing any guest page tables, so the "guest access
754 * permissions" are just ACC_ALL.
756 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
757 * is shadowing a guest huge page with small pages, the guest access
758 * permissions being shadowed are the access permissions of the huge
761 * In both cases, sp->role.access contains the correct access bits.
763 return sp->role.access;
766 static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
767 gfn_t gfn, unsigned int access)
769 if (sp_has_gptes(sp)) {
770 sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
774 WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
775 "access mismatch under %s page %llx (expected %u, got %u)\n",
776 sp->role.passthrough ? "passthrough" : "direct",
777 sp->gfn, kvm_mmu_page_get_access(sp, index), access);
779 WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
780 "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
781 sp->role.passthrough ? "passthrough" : "direct",
782 sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
785 static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
788 gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
790 kvm_mmu_page_set_translation(sp, index, gfn, access);
794 * Return the pointer to the large page information for a given gfn,
795 * handling slots that are not large page aligned.
797 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
798 const struct kvm_memory_slot *slot, int level)
802 idx = gfn_to_index(gfn, slot->base_gfn, level);
803 return &slot->arch.lpage_info[level - 2][idx];
806 static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
807 gfn_t gfn, int count)
809 struct kvm_lpage_info *linfo;
812 for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
813 linfo = lpage_info_slot(gfn, slot, i);
814 linfo->disallow_lpage += count;
815 WARN_ON(linfo->disallow_lpage < 0);
819 void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
821 update_gfn_disallow_lpage_count(slot, gfn, 1);
824 void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
826 update_gfn_disallow_lpage_count(slot, gfn, -1);
829 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
831 struct kvm_memslots *slots;
832 struct kvm_memory_slot *slot;
835 kvm->arch.indirect_shadow_pages++;
837 slots = kvm_memslots_for_spte_role(kvm, sp->role);
838 slot = __gfn_to_memslot(slots, gfn);
840 /* the non-leaf shadow pages are keeping readonly. */
841 if (sp->role.level > PG_LEVEL_4K)
842 return kvm_slot_page_track_add_page(kvm, slot, gfn,
843 KVM_PAGE_TRACK_WRITE);
845 kvm_mmu_gfn_disallow_lpage(slot, gfn);
847 if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
848 kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
851 void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
854 * If it's possible to replace the shadow page with an NX huge page,
855 * i.e. if the shadow page is the only thing currently preventing KVM
856 * from using a huge page, add the shadow page to the list of "to be
857 * zapped for NX recovery" pages. Note, the shadow page can already be
858 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
859 * links a shadow page at multiple points.
861 if (!list_empty(&sp->possible_nx_huge_page_link))
864 ++kvm->stat.nx_lpage_splits;
865 list_add_tail(&sp->possible_nx_huge_page_link,
866 &kvm->arch.possible_nx_huge_pages);
869 static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
870 bool nx_huge_page_possible)
872 sp->nx_huge_page_disallowed = true;
874 if (nx_huge_page_possible)
875 track_possible_nx_huge_page(kvm, sp);
878 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
880 struct kvm_memslots *slots;
881 struct kvm_memory_slot *slot;
884 kvm->arch.indirect_shadow_pages--;
886 slots = kvm_memslots_for_spte_role(kvm, sp->role);
887 slot = __gfn_to_memslot(slots, gfn);
888 if (sp->role.level > PG_LEVEL_4K)
889 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
890 KVM_PAGE_TRACK_WRITE);
892 kvm_mmu_gfn_allow_lpage(slot, gfn);
895 void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
897 if (list_empty(&sp->possible_nx_huge_page_link))
900 --kvm->stat.nx_lpage_splits;
901 list_del_init(&sp->possible_nx_huge_page_link);
904 static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
906 sp->nx_huge_page_disallowed = false;
908 untrack_possible_nx_huge_page(kvm, sp);
911 static struct kvm_memory_slot *gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu,
915 struct kvm_memory_slot *slot;
917 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
918 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
920 if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
927 * About rmap_head encoding:
929 * If the bit zero of rmap_head->val is clear, then it points to the only spte
930 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
931 * pte_list_desc containing more mappings.
935 * Returns the number of pointers in the rmap chain, not counting the new one.
937 static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
938 struct kvm_rmap_head *rmap_head)
940 struct pte_list_desc *desc;
943 if (!rmap_head->val) {
944 rmap_printk("%p %llx 0->1\n", spte, *spte);
945 rmap_head->val = (unsigned long)spte;
946 } else if (!(rmap_head->val & 1)) {
947 rmap_printk("%p %llx 1->many\n", spte, *spte);
948 desc = kvm_mmu_memory_cache_alloc(cache);
949 desc->sptes[0] = (u64 *)rmap_head->val;
950 desc->sptes[1] = spte;
951 desc->spte_count = 2;
952 desc->tail_count = 0;
953 rmap_head->val = (unsigned long)desc | 1;
956 rmap_printk("%p %llx many->many\n", spte, *spte);
957 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
958 count = desc->tail_count + desc->spte_count;
961 * If the previous head is full, allocate a new head descriptor
962 * as tail descriptors are always kept full.
964 if (desc->spte_count == PTE_LIST_EXT) {
965 desc = kvm_mmu_memory_cache_alloc(cache);
966 desc->more = (struct pte_list_desc *)(rmap_head->val & ~1ul);
967 desc->spte_count = 0;
968 desc->tail_count = count;
969 rmap_head->val = (unsigned long)desc | 1;
971 desc->sptes[desc->spte_count++] = spte;
976 static void pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
977 struct pte_list_desc *desc, int i)
979 struct pte_list_desc *head_desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
980 int j = head_desc->spte_count - 1;
983 * The head descriptor should never be empty. A new head is added only
984 * when adding an entry and the previous head is full, and heads are
985 * removed (this flow) when they become empty.
990 * Replace the to-be-freed SPTE with the last valid entry from the head
991 * descriptor to ensure that tail descriptors are full at all times.
992 * Note, this also means that tail_count is stable for each descriptor.
994 desc->sptes[i] = head_desc->sptes[j];
995 head_desc->sptes[j] = NULL;
996 head_desc->spte_count--;
997 if (head_desc->spte_count)
1001 * The head descriptor is empty. If there are no tail descriptors,
1002 * nullify the rmap head to mark the list as emtpy, else point the rmap
1003 * head at the next descriptor, i.e. the new head.
1005 if (!head_desc->more)
1008 rmap_head->val = (unsigned long)head_desc->more | 1;
1009 mmu_free_pte_list_desc(head_desc);
1012 static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1014 struct pte_list_desc *desc;
1017 if (!rmap_head->val) {
1018 pr_err("%s: %p 0->BUG\n", __func__, spte);
1020 } else if (!(rmap_head->val & 1)) {
1021 rmap_printk("%p 1->0\n", spte);
1022 if ((u64 *)rmap_head->val != spte) {
1023 pr_err("%s: %p 1->BUG\n", __func__, spte);
1028 rmap_printk("%p many->many\n", spte);
1029 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1031 for (i = 0; i < desc->spte_count; ++i) {
1032 if (desc->sptes[i] == spte) {
1033 pte_list_desc_remove_entry(rmap_head, desc, i);
1039 pr_err("%s: %p many->many\n", __func__, spte);
1044 static void kvm_zap_one_rmap_spte(struct kvm *kvm,
1045 struct kvm_rmap_head *rmap_head, u64 *sptep)
1047 mmu_spte_clear_track_bits(kvm, sptep);
1048 pte_list_remove(sptep, rmap_head);
1051 /* Return true if at least one SPTE was zapped, false otherwise */
1052 static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
1053 struct kvm_rmap_head *rmap_head)
1055 struct pte_list_desc *desc, *next;
1058 if (!rmap_head->val)
1061 if (!(rmap_head->val & 1)) {
1062 mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1066 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1068 for (; desc; desc = next) {
1069 for (i = 0; i < desc->spte_count; i++)
1070 mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1072 mmu_free_pte_list_desc(desc);
1075 /* rmap_head is meaningless now, remember to reset it */
1080 unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
1082 struct pte_list_desc *desc;
1084 if (!rmap_head->val)
1086 else if (!(rmap_head->val & 1))
1089 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1090 return desc->tail_count + desc->spte_count;
1093 static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1094 const struct kvm_memory_slot *slot)
1098 idx = gfn_to_index(gfn, slot->base_gfn, level);
1099 return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1102 static void rmap_remove(struct kvm *kvm, u64 *spte)
1104 struct kvm_memslots *slots;
1105 struct kvm_memory_slot *slot;
1106 struct kvm_mmu_page *sp;
1108 struct kvm_rmap_head *rmap_head;
1110 sp = sptep_to_sp(spte);
1111 gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1114 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
1115 * so we have to determine which memslots to use based on context
1116 * information in sp->role.
1118 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1120 slot = __gfn_to_memslot(slots, gfn);
1121 rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1123 pte_list_remove(spte, rmap_head);
1127 * Used by the following functions to iterate through the sptes linked by a
1128 * rmap. All fields are private and not assumed to be used outside.
1130 struct rmap_iterator {
1131 /* private fields */
1132 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1133 int pos; /* index of the sptep */
1137 * Iteration must be started by this function. This should also be used after
1138 * removing/dropping sptes from the rmap link because in such cases the
1139 * information in the iterator may not be valid.
1141 * Returns sptep if found, NULL otherwise.
1143 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1144 struct rmap_iterator *iter)
1148 if (!rmap_head->val)
1151 if (!(rmap_head->val & 1)) {
1153 sptep = (u64 *)rmap_head->val;
1157 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1159 sptep = iter->desc->sptes[iter->pos];
1161 BUG_ON(!is_shadow_present_pte(*sptep));
1166 * Must be used with a valid iterator: e.g. after rmap_get_first().
1168 * Returns sptep if found, NULL otherwise.
1170 static u64 *rmap_get_next(struct rmap_iterator *iter)
1175 if (iter->pos < PTE_LIST_EXT - 1) {
1177 sptep = iter->desc->sptes[iter->pos];
1182 iter->desc = iter->desc->more;
1186 /* desc->sptes[0] cannot be NULL */
1187 sptep = iter->desc->sptes[iter->pos];
1194 BUG_ON(!is_shadow_present_pte(*sptep));
1198 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1199 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1200 _spte_; _spte_ = rmap_get_next(_iter_))
1202 static void drop_spte(struct kvm *kvm, u64 *sptep)
1204 u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
1206 if (is_shadow_present_pte(old_spte))
1207 rmap_remove(kvm, sptep);
1210 static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1212 struct kvm_mmu_page *sp;
1214 sp = sptep_to_sp(sptep);
1215 WARN_ON(sp->role.level == PG_LEVEL_4K);
1217 drop_spte(kvm, sptep);
1220 kvm_flush_remote_tlbs_sptep(kvm, sptep);
1224 * Write-protect on the specified @sptep, @pt_protect indicates whether
1225 * spte write-protection is caused by protecting shadow page table.
1227 * Note: write protection is difference between dirty logging and spte
1229 * - for dirty logging, the spte can be set to writable at anytime if
1230 * its dirty bitmap is properly set.
1231 * - for spte protection, the spte can be writable only after unsync-ing
1234 * Return true if tlb need be flushed.
1236 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1240 if (!is_writable_pte(spte) &&
1241 !(pt_protect && is_mmu_writable_spte(spte)))
1244 rmap_printk("spte %p %llx\n", sptep, *sptep);
1247 spte &= ~shadow_mmu_writable_mask;
1248 spte = spte & ~PT_WRITABLE_MASK;
1250 return mmu_spte_update(sptep, spte);
1253 static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1257 struct rmap_iterator iter;
1260 for_each_rmap_spte(rmap_head, &iter, sptep)
1261 flush |= spte_write_protect(sptep, pt_protect);
1266 static bool spte_clear_dirty(u64 *sptep)
1270 rmap_printk("spte %p %llx\n", sptep, *sptep);
1272 MMU_WARN_ON(!spte_ad_enabled(spte));
1273 spte &= ~shadow_dirty_mask;
1274 return mmu_spte_update(sptep, spte);
1277 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1279 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1280 (unsigned long *)sptep);
1281 if (was_writable && !spte_ad_enabled(*sptep))
1282 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1284 return was_writable;
1288 * Gets the GFN ready for another round of dirty logging by clearing the
1289 * - D bit on ad-enabled SPTEs, and
1290 * - W bit on ad-disabled SPTEs.
1291 * Returns true iff any D or W bits were cleared.
1293 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1294 const struct kvm_memory_slot *slot)
1297 struct rmap_iterator iter;
1300 for_each_rmap_spte(rmap_head, &iter, sptep)
1301 if (spte_ad_need_write_protect(*sptep))
1302 flush |= spte_wrprot_for_clear_dirty(sptep);
1304 flush |= spte_clear_dirty(sptep);
1310 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1311 * @kvm: kvm instance
1312 * @slot: slot to protect
1313 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1314 * @mask: indicates which pages we should protect
1316 * Used when we do not need to care about huge page mappings.
1318 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1319 struct kvm_memory_slot *slot,
1320 gfn_t gfn_offset, unsigned long mask)
1322 struct kvm_rmap_head *rmap_head;
1324 if (tdp_mmu_enabled)
1325 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1326 slot->base_gfn + gfn_offset, mask, true);
1328 if (!kvm_memslots_have_rmaps(kvm))
1332 rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1334 rmap_write_protect(rmap_head, false);
1336 /* clear the first set bit */
1342 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1343 * protect the page if the D-bit isn't supported.
1344 * @kvm: kvm instance
1345 * @slot: slot to clear D-bit
1346 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1347 * @mask: indicates which pages we should clear D-bit
1349 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1351 static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1352 struct kvm_memory_slot *slot,
1353 gfn_t gfn_offset, unsigned long mask)
1355 struct kvm_rmap_head *rmap_head;
1357 if (tdp_mmu_enabled)
1358 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1359 slot->base_gfn + gfn_offset, mask, false);
1361 if (!kvm_memslots_have_rmaps(kvm))
1365 rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1367 __rmap_clear_dirty(kvm, rmap_head, slot);
1369 /* clear the first set bit */
1375 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1378 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1379 * enable dirty logging for them.
1381 * We need to care about huge page mappings: e.g. during dirty logging we may
1382 * have such mappings.
1384 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1385 struct kvm_memory_slot *slot,
1386 gfn_t gfn_offset, unsigned long mask)
1389 * Huge pages are NOT write protected when we start dirty logging in
1390 * initially-all-set mode; must write protect them here so that they
1391 * are split to 4K on the first write.
1393 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
1394 * of memslot has no such restriction, so the range can cross two large
1397 if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1398 gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
1399 gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
1401 if (READ_ONCE(eager_page_split))
1402 kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1404 kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
1406 /* Cross two large pages? */
1407 if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
1408 ALIGN(end << PAGE_SHIFT, PMD_SIZE))
1409 kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
1413 /* Now handle 4K PTEs. */
1414 if (kvm_x86_ops.cpu_dirty_log_size)
1415 kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1417 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1420 int kvm_cpu_dirty_log_size(void)
1422 return kvm_x86_ops.cpu_dirty_log_size;
1425 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1426 struct kvm_memory_slot *slot, u64 gfn,
1429 struct kvm_rmap_head *rmap_head;
1431 bool write_protected = false;
1433 if (kvm_memslots_have_rmaps(kvm)) {
1434 for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1435 rmap_head = gfn_to_rmap(gfn, i, slot);
1436 write_protected |= rmap_write_protect(rmap_head, true);
1440 if (tdp_mmu_enabled)
1442 kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
1444 return write_protected;
1447 static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1449 struct kvm_memory_slot *slot;
1451 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1452 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1455 static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1456 const struct kvm_memory_slot *slot)
1458 return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1461 static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1462 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1465 return __kvm_zap_rmap(kvm, rmap_head, slot);
1468 static bool kvm_set_pte_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1469 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1473 struct rmap_iterator iter;
1474 bool need_flush = false;
1478 WARN_ON(pte_huge(pte));
1479 new_pfn = pte_pfn(pte);
1482 for_each_rmap_spte(rmap_head, &iter, sptep) {
1483 rmap_printk("spte %p %llx gfn %llx (%d)\n",
1484 sptep, *sptep, gfn, level);
1488 if (pte_write(pte)) {
1489 kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
1492 new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1495 mmu_spte_clear_track_bits(kvm, sptep);
1496 mmu_spte_set(sptep, new_spte);
1500 if (need_flush && kvm_available_flush_remote_tlbs_range()) {
1501 kvm_flush_remote_tlbs_gfn(kvm, gfn, level);
1508 struct slot_rmap_walk_iterator {
1510 const struct kvm_memory_slot *slot;
1516 /* output fields. */
1518 struct kvm_rmap_head *rmap;
1521 /* private field. */
1522 struct kvm_rmap_head *end_rmap;
1525 static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
1528 iterator->level = level;
1529 iterator->gfn = iterator->start_gfn;
1530 iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
1531 iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1534 static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1535 const struct kvm_memory_slot *slot,
1536 int start_level, int end_level,
1537 gfn_t start_gfn, gfn_t end_gfn)
1539 iterator->slot = slot;
1540 iterator->start_level = start_level;
1541 iterator->end_level = end_level;
1542 iterator->start_gfn = start_gfn;
1543 iterator->end_gfn = end_gfn;
1545 rmap_walk_init_level(iterator, iterator->start_level);
1548 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1550 return !!iterator->rmap;
1553 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1555 while (++iterator->rmap <= iterator->end_rmap) {
1556 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1558 if (iterator->rmap->val)
1562 if (++iterator->level > iterator->end_level) {
1563 iterator->rmap = NULL;
1567 rmap_walk_init_level(iterator, iterator->level);
1570 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1571 _start_gfn, _end_gfn, _iter_) \
1572 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1573 _end_level_, _start_gfn, _end_gfn); \
1574 slot_rmap_walk_okay(_iter_); \
1575 slot_rmap_walk_next(_iter_))
1577 typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1578 struct kvm_memory_slot *slot, gfn_t gfn,
1579 int level, pte_t pte);
1581 static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
1582 struct kvm_gfn_range *range,
1583 rmap_handler_t handler)
1585 struct slot_rmap_walk_iterator iterator;
1588 for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
1589 range->start, range->end - 1, &iterator)
1590 ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
1591 iterator.level, range->pte);
1596 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1600 if (kvm_memslots_have_rmaps(kvm))
1601 flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1603 if (tdp_mmu_enabled)
1604 flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1606 if (kvm_x86_ops.set_apic_access_page_addr &&
1607 range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)
1608 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
1613 bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1617 if (kvm_memslots_have_rmaps(kvm))
1618 flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmap);
1620 if (tdp_mmu_enabled)
1621 flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
1626 static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1627 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1631 struct rmap_iterator iter;
1634 for_each_rmap_spte(rmap_head, &iter, sptep)
1635 young |= mmu_spte_age(sptep);
1640 static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1641 struct kvm_memory_slot *slot, gfn_t gfn,
1642 int level, pte_t unused)
1645 struct rmap_iterator iter;
1647 for_each_rmap_spte(rmap_head, &iter, sptep)
1648 if (is_accessed_spte(*sptep))
1653 #define RMAP_RECYCLE_THRESHOLD 1000
1655 static void __rmap_add(struct kvm *kvm,
1656 struct kvm_mmu_memory_cache *cache,
1657 const struct kvm_memory_slot *slot,
1658 u64 *spte, gfn_t gfn, unsigned int access)
1660 struct kvm_mmu_page *sp;
1661 struct kvm_rmap_head *rmap_head;
1664 sp = sptep_to_sp(spte);
1665 kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
1666 kvm_update_page_stats(kvm, sp->role.level, 1);
1668 rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1669 rmap_count = pte_list_add(cache, spte, rmap_head);
1671 if (rmap_count > kvm->stat.max_mmu_rmap_size)
1672 kvm->stat.max_mmu_rmap_size = rmap_count;
1673 if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
1674 kvm_zap_all_rmap_sptes(kvm, rmap_head);
1675 kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
1679 static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
1680 u64 *spte, gfn_t gfn, unsigned int access)
1682 struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
1684 __rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
1687 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1691 if (kvm_memslots_have_rmaps(kvm))
1692 young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
1694 if (tdp_mmu_enabled)
1695 young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1700 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1704 if (kvm_memslots_have_rmaps(kvm))
1705 young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
1707 if (tdp_mmu_enabled)
1708 young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1714 static int is_empty_shadow_page(u64 *spt)
1719 for (pos = spt, end = pos + SPTE_ENT_PER_PAGE; pos != end; pos++)
1720 if (is_shadow_present_pte(*pos)) {
1721 printk(KERN_ERR "%s: %p %llx\n", __func__,
1730 * This value is the sum of all of the kvm instances's
1731 * kvm->arch.n_used_mmu_pages values. We need a global,
1732 * aggregate version in order to make the slab shrinker
1735 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1737 kvm->arch.n_used_mmu_pages += nr;
1738 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1741 static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1743 kvm_mod_used_mmu_pages(kvm, +1);
1744 kvm_account_pgtable_pages((void *)sp->spt, +1);
1747 static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1749 kvm_mod_used_mmu_pages(kvm, -1);
1750 kvm_account_pgtable_pages((void *)sp->spt, -1);
1753 static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1755 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1756 hlist_del(&sp->hash_link);
1757 list_del(&sp->link);
1758 free_page((unsigned long)sp->spt);
1759 if (!sp->role.direct)
1760 free_page((unsigned long)sp->shadowed_translation);
1761 kmem_cache_free(mmu_page_header_cache, sp);
1764 static unsigned kvm_page_table_hashfn(gfn_t gfn)
1766 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1769 static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1770 struct kvm_mmu_page *sp, u64 *parent_pte)
1775 pte_list_add(cache, parent_pte, &sp->parent_ptes);
1778 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1781 pte_list_remove(parent_pte, &sp->parent_ptes);
1784 static void drop_parent_pte(struct kvm_mmu_page *sp,
1787 mmu_page_remove_parent_pte(sp, parent_pte);
1788 mmu_spte_clear_no_track(parent_pte);
1791 static void mark_unsync(u64 *spte);
1792 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1795 struct rmap_iterator iter;
1797 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1802 static void mark_unsync(u64 *spte)
1804 struct kvm_mmu_page *sp;
1806 sp = sptep_to_sp(spte);
1807 if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1809 if (sp->unsync_children++)
1811 kvm_mmu_mark_parents_unsync(sp);
1814 #define KVM_PAGE_ARRAY_NR 16
1816 struct kvm_mmu_pages {
1817 struct mmu_page_and_offset {
1818 struct kvm_mmu_page *sp;
1820 } page[KVM_PAGE_ARRAY_NR];
1824 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1830 for (i=0; i < pvec->nr; i++)
1831 if (pvec->page[i].sp == sp)
1834 pvec->page[pvec->nr].sp = sp;
1835 pvec->page[pvec->nr].idx = idx;
1837 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1840 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1842 --sp->unsync_children;
1843 WARN_ON((int)sp->unsync_children < 0);
1844 __clear_bit(idx, sp->unsync_child_bitmap);
1847 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1848 struct kvm_mmu_pages *pvec)
1850 int i, ret, nr_unsync_leaf = 0;
1852 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1853 struct kvm_mmu_page *child;
1854 u64 ent = sp->spt[i];
1856 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1857 clear_unsync_child_bit(sp, i);
1861 child = spte_to_child_sp(ent);
1863 if (child->unsync_children) {
1864 if (mmu_pages_add(pvec, child, i))
1867 ret = __mmu_unsync_walk(child, pvec);
1869 clear_unsync_child_bit(sp, i);
1871 } else if (ret > 0) {
1872 nr_unsync_leaf += ret;
1875 } else if (child->unsync) {
1877 if (mmu_pages_add(pvec, child, i))
1880 clear_unsync_child_bit(sp, i);
1883 return nr_unsync_leaf;
1886 #define INVALID_INDEX (-1)
1888 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1889 struct kvm_mmu_pages *pvec)
1892 if (!sp->unsync_children)
1895 mmu_pages_add(pvec, sp, INVALID_INDEX);
1896 return __mmu_unsync_walk(sp, pvec);
1899 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1901 WARN_ON(!sp->unsync);
1902 trace_kvm_mmu_sync_page(sp);
1904 --kvm->stat.mmu_unsync;
1907 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1908 struct list_head *invalid_list);
1909 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1910 struct list_head *invalid_list);
1912 static bool sp_has_gptes(struct kvm_mmu_page *sp)
1914 if (sp->role.direct)
1917 if (sp->role.passthrough)
1923 #define for_each_valid_sp(_kvm, _sp, _list) \
1924 hlist_for_each_entry(_sp, _list, hash_link) \
1925 if (is_obsolete_sp((_kvm), (_sp))) { \
1928 #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn) \
1929 for_each_valid_sp(_kvm, _sp, \
1930 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
1931 if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1933 static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1935 union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
1938 * Ignore various flags when verifying that it's safe to sync a shadow
1939 * page using the current MMU context.
1941 * - level: not part of the overall MMU role and will never match as the MMU's
1942 * level tracks the root level
1943 * - access: updated based on the new guest PTE
1944 * - quadrant: not part of the overall MMU role (similar to level)
1946 const union kvm_mmu_page_role sync_role_ign = {
1954 * Direct pages can never be unsync, and KVM should never attempt to
1955 * sync a shadow page for a different MMU context, e.g. if the role
1956 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
1957 * reserved bits checks will be wrong, etc...
1959 if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
1960 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
1966 static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
1971 return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
1974 static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1979 if (!kvm_sync_page_check(vcpu, sp))
1982 for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
1983 int ret = kvm_sync_spte(vcpu, sp, i);
1991 * Note, any flush is purely for KVM's correctness, e.g. when dropping
1992 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1993 * unmap or dirty logging event doesn't fail to flush. The guest is
1994 * responsible for flushing the TLB to ensure any changes in protection
1995 * bits are recognized, i.e. until the guest flushes or page faults on
1996 * a relevant address, KVM is architecturally allowed to let vCPUs use
1997 * cached translations with the old protection bits.
2002 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2003 struct list_head *invalid_list)
2005 int ret = __kvm_sync_page(vcpu, sp);
2008 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2012 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2013 struct list_head *invalid_list,
2016 if (!remote_flush && list_empty(invalid_list))
2019 if (!list_empty(invalid_list))
2020 kvm_mmu_commit_zap_page(kvm, invalid_list);
2022 kvm_flush_remote_tlbs(kvm);
2026 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2028 if (sp->role.invalid)
2031 /* TDP MMU pages do not use the MMU generation. */
2032 return !is_tdp_mmu_page(sp) &&
2033 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2036 struct mmu_page_path {
2037 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2038 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2041 #define for_each_sp(pvec, sp, parents, i) \
2042 for (i = mmu_pages_first(&pvec, &parents); \
2043 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2044 i = mmu_pages_next(&pvec, &parents, i))
2046 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2047 struct mmu_page_path *parents,
2052 for (n = i+1; n < pvec->nr; n++) {
2053 struct kvm_mmu_page *sp = pvec->page[n].sp;
2054 unsigned idx = pvec->page[n].idx;
2055 int level = sp->role.level;
2057 parents->idx[level-1] = idx;
2058 if (level == PG_LEVEL_4K)
2061 parents->parent[level-2] = sp;
2067 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2068 struct mmu_page_path *parents)
2070 struct kvm_mmu_page *sp;
2076 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2078 sp = pvec->page[0].sp;
2079 level = sp->role.level;
2080 WARN_ON(level == PG_LEVEL_4K);
2082 parents->parent[level-2] = sp;
2084 /* Also set up a sentinel. Further entries in pvec are all
2085 * children of sp, so this element is never overwritten.
2087 parents->parent[level-1] = NULL;
2088 return mmu_pages_next(pvec, parents, 0);
2091 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2093 struct kvm_mmu_page *sp;
2094 unsigned int level = 0;
2097 unsigned int idx = parents->idx[level];
2098 sp = parents->parent[level];
2102 WARN_ON(idx == INVALID_INDEX);
2103 clear_unsync_child_bit(sp, idx);
2105 } while (!sp->unsync_children);
2108 static int mmu_sync_children(struct kvm_vcpu *vcpu,
2109 struct kvm_mmu_page *parent, bool can_yield)
2112 struct kvm_mmu_page *sp;
2113 struct mmu_page_path parents;
2114 struct kvm_mmu_pages pages;
2115 LIST_HEAD(invalid_list);
2118 while (mmu_unsync_walk(parent, &pages)) {
2119 bool protected = false;
2121 for_each_sp(pages, sp, parents, i)
2122 protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2125 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2129 for_each_sp(pages, sp, parents, i) {
2130 kvm_unlink_unsync_page(vcpu->kvm, sp);
2131 flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2132 mmu_pages_clear_parents(&parents);
2134 if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2135 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2137 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2141 cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2146 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2150 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2152 atomic_set(&sp->write_flooding_count, 0);
2155 static void clear_sp_write_flooding_count(u64 *spte)
2157 __clear_sp_write_flooding_count(sptep_to_sp(spte));
2161 * The vCPU is required when finding indirect shadow pages; the shadow
2162 * page may already exist and syncing it needs the vCPU pointer in
2163 * order to read guest page tables. Direct shadow pages are never
2164 * unsync, thus @vcpu can be NULL if @role.direct is true.
2166 static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
2167 struct kvm_vcpu *vcpu,
2169 struct hlist_head *sp_list,
2170 union kvm_mmu_page_role role)
2172 struct kvm_mmu_page *sp;
2175 LIST_HEAD(invalid_list);
2177 for_each_valid_sp(kvm, sp, sp_list) {
2178 if (sp->gfn != gfn) {
2183 if (sp->role.word != role.word) {
2185 * If the guest is creating an upper-level page, zap
2186 * unsync pages for the same gfn. While it's possible
2187 * the guest is using recursive page tables, in all
2188 * likelihood the guest has stopped using the unsync
2189 * page and is installing a completely unrelated page.
2190 * Unsync pages must not be left as is, because the new
2191 * upper-level page will be write-protected.
2193 if (role.level > PG_LEVEL_4K && sp->unsync)
2194 kvm_mmu_prepare_zap_page(kvm, sp,
2199 /* unsync and write-flooding only apply to indirect SPs. */
2200 if (sp->role.direct)
2204 if (KVM_BUG_ON(!vcpu, kvm))
2208 * The page is good, but is stale. kvm_sync_page does
2209 * get the latest guest state, but (unlike mmu_unsync_children)
2210 * it doesn't write-protect the page or mark it synchronized!
2211 * This way the validity of the mapping is ensured, but the
2212 * overhead of write protection is not incurred until the
2213 * guest invalidates the TLB mapping. This allows multiple
2214 * SPs for a single gfn to be unsync.
2216 * If the sync fails, the page is zapped. If so, break
2217 * in order to rebuild it.
2219 ret = kvm_sync_page(vcpu, sp, &invalid_list);
2223 WARN_ON(!list_empty(&invalid_list));
2225 kvm_flush_remote_tlbs(kvm);
2228 __clear_sp_write_flooding_count(sp);
2234 ++kvm->stat.mmu_cache_miss;
2237 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2239 if (collisions > kvm->stat.max_mmu_page_hash_collisions)
2240 kvm->stat.max_mmu_page_hash_collisions = collisions;
2244 /* Caches used when allocating a new shadow page. */
2245 struct shadow_page_caches {
2246 struct kvm_mmu_memory_cache *page_header_cache;
2247 struct kvm_mmu_memory_cache *shadow_page_cache;
2248 struct kvm_mmu_memory_cache *shadowed_info_cache;
2251 static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
2252 struct shadow_page_caches *caches,
2254 struct hlist_head *sp_list,
2255 union kvm_mmu_page_role role)
2257 struct kvm_mmu_page *sp;
2259 sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
2260 sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2262 sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2264 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2266 INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2269 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2270 * depends on valid pages being added to the head of the list. See
2271 * comments in kvm_zap_obsolete_pages().
2273 sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2274 list_add(&sp->link, &kvm->arch.active_mmu_pages);
2275 kvm_account_mmu_page(kvm, sp);
2279 hlist_add_head(&sp->hash_link, sp_list);
2280 if (sp_has_gptes(sp))
2281 account_shadowed(kvm, sp);
2286 /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
2287 static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
2288 struct kvm_vcpu *vcpu,
2289 struct shadow_page_caches *caches,
2291 union kvm_mmu_page_role role)
2293 struct hlist_head *sp_list;
2294 struct kvm_mmu_page *sp;
2295 bool created = false;
2297 sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2299 sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
2302 sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
2305 trace_kvm_mmu_get_page(sp, created);
2309 static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
2311 union kvm_mmu_page_role role)
2313 struct shadow_page_caches caches = {
2314 .page_header_cache = &vcpu->arch.mmu_page_header_cache,
2315 .shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
2316 .shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
2319 return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
2322 static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
2323 unsigned int access)
2325 struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
2326 union kvm_mmu_page_role role;
2328 role = parent_sp->role;
2330 role.access = access;
2331 role.direct = direct;
2332 role.passthrough = 0;
2335 * If the guest has 4-byte PTEs then that means it's using 32-bit,
2336 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
2337 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
2338 * shadow each guest page table with multiple shadow page tables, which
2339 * requires extra bookkeeping in the role.
2341 * Specifically, to shadow the guest's page directory (which covers a
2342 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
2343 * 1GiB of the address space. @role.quadrant encodes which quarter of
2344 * the address space each maps.
2346 * To shadow the guest's page tables (which each map a 4MiB region), KVM
2347 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
2348 * @role.quadrant encodes which half of the region they map.
2350 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
2351 * consumes bits 29:21. To consume bits 31:30, KVM's uses 4 shadow
2352 * PDPTEs; those 4 PAE page directories are pre-allocated and their
2353 * quadrant is assigned in mmu_alloc_root(). A 4-byte PTE consumes
2354 * bits 21:12, while an 8-byte PTE consumes bits 20:12. To consume
2355 * bit 21 in the PTE (the child here), KVM propagates that bit to the
2356 * quadrant, i.e. sets quadrant to '0' or '1'. The parent 8-byte PDE
2357 * covers bit 21 (see above), thus the quadrant is calculated from the
2358 * _least_ significant bit of the PDE index.
2360 if (role.has_4_byte_gpte) {
2361 WARN_ON_ONCE(role.level != PG_LEVEL_4K);
2362 role.quadrant = spte_index(sptep) & 1;
2368 static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
2369 u64 *sptep, gfn_t gfn,
2370 bool direct, unsigned int access)
2372 union kvm_mmu_page_role role;
2374 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
2375 return ERR_PTR(-EEXIST);
2377 role = kvm_mmu_child_role(sptep, direct, access);
2378 return kvm_mmu_get_shadow_page(vcpu, gfn, role);
2381 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2382 struct kvm_vcpu *vcpu, hpa_t root,
2385 iterator->addr = addr;
2386 iterator->shadow_addr = root;
2387 iterator->level = vcpu->arch.mmu->root_role.level;
2389 if (iterator->level >= PT64_ROOT_4LEVEL &&
2390 vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2391 !vcpu->arch.mmu->root_role.direct)
2392 iterator->level = PT32E_ROOT_LEVEL;
2394 if (iterator->level == PT32E_ROOT_LEVEL) {
2396 * prev_root is currently only used for 64-bit hosts. So only
2397 * the active root_hpa is valid here.
2399 BUG_ON(root != vcpu->arch.mmu->root.hpa);
2401 iterator->shadow_addr
2402 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2403 iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2405 if (!iterator->shadow_addr)
2406 iterator->level = 0;
2410 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2411 struct kvm_vcpu *vcpu, u64 addr)
2413 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2417 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2419 if (iterator->level < PG_LEVEL_4K)
2422 iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2423 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2427 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2430 if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2431 iterator->level = 0;
2435 iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2439 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2441 __shadow_walk_next(iterator, *iterator->sptep);
2444 static void __link_shadow_page(struct kvm *kvm,
2445 struct kvm_mmu_memory_cache *cache, u64 *sptep,
2446 struct kvm_mmu_page *sp, bool flush)
2450 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2453 * If an SPTE is present already, it must be a leaf and therefore
2454 * a large one. Drop it, and flush the TLB if needed, before
2457 if (is_shadow_present_pte(*sptep))
2458 drop_large_spte(kvm, sptep, flush);
2460 spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2462 mmu_spte_set(sptep, spte);
2464 mmu_page_add_parent_pte(cache, sp, sptep);
2467 * The non-direct sub-pagetable must be updated before linking. For
2468 * L1 sp, the pagetable is updated via kvm_sync_page() in
2469 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2470 * so sp->unsync can be true or false. For higher level non-direct
2471 * sp, the pagetable is updated/synced via mmu_sync_children() in
2472 * FNAME(fetch)(), so sp->unsync_children can only be false.
2473 * WARN_ON_ONCE() if anything happens unexpectedly.
2475 if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2479 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2480 struct kvm_mmu_page *sp)
2482 __link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
2485 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2486 unsigned direct_access)
2488 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2489 struct kvm_mmu_page *child;
2492 * For the direct sp, if the guest pte's dirty bit
2493 * changed form clean to dirty, it will corrupt the
2494 * sp's access: allow writable in the read-only sp,
2495 * so we should update the spte at this point to get
2496 * a new sp with the correct access.
2498 child = spte_to_child_sp(*sptep);
2499 if (child->role.access == direct_access)
2502 drop_parent_pte(child, sptep);
2503 kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2507 /* Returns the number of zapped non-leaf child shadow pages. */
2508 static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2509 u64 *spte, struct list_head *invalid_list)
2512 struct kvm_mmu_page *child;
2515 if (is_shadow_present_pte(pte)) {
2516 if (is_last_spte(pte, sp->role.level)) {
2517 drop_spte(kvm, spte);
2519 child = spte_to_child_sp(pte);
2520 drop_parent_pte(child, spte);
2523 * Recursively zap nested TDP SPs, parentless SPs are
2524 * unlikely to be used again in the near future. This
2525 * avoids retaining a large number of stale nested SPs.
2527 if (tdp_enabled && invalid_list &&
2528 child->role.guest_mode && !child->parent_ptes.val)
2529 return kvm_mmu_prepare_zap_page(kvm, child,
2532 } else if (is_mmio_spte(pte)) {
2533 mmu_spte_clear_no_track(spte);
2538 static int kvm_mmu_page_unlink_children(struct kvm *kvm,
2539 struct kvm_mmu_page *sp,
2540 struct list_head *invalid_list)
2545 for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
2546 zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
2551 static void kvm_mmu_unlink_parents(struct kvm_mmu_page *sp)
2554 struct rmap_iterator iter;
2556 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2557 drop_parent_pte(sp, sptep);
2560 static int mmu_zap_unsync_children(struct kvm *kvm,
2561 struct kvm_mmu_page *parent,
2562 struct list_head *invalid_list)
2565 struct mmu_page_path parents;
2566 struct kvm_mmu_pages pages;
2568 if (parent->role.level == PG_LEVEL_4K)
2571 while (mmu_unsync_walk(parent, &pages)) {
2572 struct kvm_mmu_page *sp;
2574 for_each_sp(pages, sp, parents, i) {
2575 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2576 mmu_pages_clear_parents(&parents);
2584 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2585 struct kvm_mmu_page *sp,
2586 struct list_head *invalid_list,
2589 bool list_unstable, zapped_root = false;
2591 lockdep_assert_held_write(&kvm->mmu_lock);
2592 trace_kvm_mmu_prepare_zap_page(sp);
2593 ++kvm->stat.mmu_shadow_zapped;
2594 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2595 *nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2596 kvm_mmu_unlink_parents(sp);
2598 /* Zapping children means active_mmu_pages has become unstable. */
2599 list_unstable = *nr_zapped;
2601 if (!sp->role.invalid && sp_has_gptes(sp))
2602 unaccount_shadowed(kvm, sp);
2605 kvm_unlink_unsync_page(kvm, sp);
2606 if (!sp->root_count) {
2611 * Already invalid pages (previously active roots) are not on
2612 * the active page list. See list_del() in the "else" case of
2615 if (sp->role.invalid)
2616 list_add(&sp->link, invalid_list);
2618 list_move(&sp->link, invalid_list);
2619 kvm_unaccount_mmu_page(kvm, sp);
2622 * Remove the active root from the active page list, the root
2623 * will be explicitly freed when the root_count hits zero.
2625 list_del(&sp->link);
2628 * Obsolete pages cannot be used on any vCPUs, see the comment
2629 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2630 * treats invalid shadow pages as being obsolete.
2632 zapped_root = !is_obsolete_sp(kvm, sp);
2635 if (sp->nx_huge_page_disallowed)
2636 unaccount_nx_huge_page(kvm, sp);
2638 sp->role.invalid = 1;
2641 * Make the request to free obsolete roots after marking the root
2642 * invalid, otherwise other vCPUs may not see it as invalid.
2645 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2646 return list_unstable;
2649 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2650 struct list_head *invalid_list)
2654 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2658 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2659 struct list_head *invalid_list)
2661 struct kvm_mmu_page *sp, *nsp;
2663 if (list_empty(invalid_list))
2667 * We need to make sure everyone sees our modifications to
2668 * the page tables and see changes to vcpu->mode here. The barrier
2669 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2670 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2672 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2673 * guest mode and/or lockless shadow page table walks.
2675 kvm_flush_remote_tlbs(kvm);
2677 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2678 WARN_ON(!sp->role.invalid || sp->root_count);
2679 kvm_mmu_free_shadow_page(sp);
2683 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2684 unsigned long nr_to_zap)
2686 unsigned long total_zapped = 0;
2687 struct kvm_mmu_page *sp, *tmp;
2688 LIST_HEAD(invalid_list);
2692 if (list_empty(&kvm->arch.active_mmu_pages))
2696 list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2698 * Don't zap active root pages, the page itself can't be freed
2699 * and zapping it will just force vCPUs to realloc and reload.
2704 unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2706 total_zapped += nr_zapped;
2707 if (total_zapped >= nr_to_zap)
2714 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2716 kvm->stat.mmu_recycled += total_zapped;
2717 return total_zapped;
2720 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2722 if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2723 return kvm->arch.n_max_mmu_pages -
2724 kvm->arch.n_used_mmu_pages;
2729 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2731 unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2733 if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2736 kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2739 * Note, this check is intentionally soft, it only guarantees that one
2740 * page is available, while the caller may end up allocating as many as
2741 * four pages, e.g. for PAE roots or for 5-level paging. Temporarily
2742 * exceeding the (arbitrary by default) limit will not harm the host,
2743 * being too aggressive may unnecessarily kill the guest, and getting an
2744 * exact count is far more trouble than it's worth, especially in the
2747 if (!kvm_mmu_available_pages(vcpu->kvm))
2753 * Changing the number of mmu pages allocated to the vm
2754 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2756 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2758 write_lock(&kvm->mmu_lock);
2760 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2761 kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2764 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2767 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2769 write_unlock(&kvm->mmu_lock);
2772 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2774 struct kvm_mmu_page *sp;
2775 LIST_HEAD(invalid_list);
2778 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2780 write_lock(&kvm->mmu_lock);
2781 for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2782 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2785 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2787 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2788 write_unlock(&kvm->mmu_lock);
2793 static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2798 if (vcpu->arch.mmu->root_role.direct)
2801 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
2803 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2808 static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2810 trace_kvm_mmu_unsync_page(sp);
2811 ++kvm->stat.mmu_unsync;
2814 kvm_mmu_mark_parents_unsync(sp);
2818 * Attempt to unsync any shadow pages that can be reached by the specified gfn,
2819 * KVM is creating a writable mapping for said gfn. Returns 0 if all pages
2820 * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
2821 * be write-protected.
2823 int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
2824 gfn_t gfn, bool can_unsync, bool prefetch)
2826 struct kvm_mmu_page *sp;
2827 bool locked = false;
2830 * Force write-protection if the page is being tracked. Note, the page
2831 * track machinery is used to write-protect upper-level shadow pages,
2832 * i.e. this guards the role.level == 4K assertion below!
2834 if (kvm_slot_page_track_is_active(kvm, slot, gfn, KVM_PAGE_TRACK_WRITE))
2838 * The page is not write-tracked, mark existing shadow pages unsync
2839 * unless KVM is synchronizing an unsync SP (can_unsync = false). In
2840 * that case, KVM must complete emulation of the guest TLB flush before
2841 * allowing shadow pages to become unsync (writable by the guest).
2843 for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2854 * TDP MMU page faults require an additional spinlock as they
2855 * run with mmu_lock held for read, not write, and the unsync
2856 * logic is not thread safe. Take the spinklock regardless of
2857 * the MMU type to avoid extra conditionals/parameters, there's
2858 * no meaningful penalty if mmu_lock is held for write.
2862 spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2865 * Recheck after taking the spinlock, a different vCPU
2866 * may have since marked the page unsync. A false
2867 * positive on the unprotected check above is not
2868 * possible as clearing sp->unsync _must_ hold mmu_lock
2869 * for write, i.e. unsync cannot transition from 0->1
2870 * while this CPU holds mmu_lock for read (or write).
2872 if (READ_ONCE(sp->unsync))
2876 WARN_ON(sp->role.level != PG_LEVEL_4K);
2877 kvm_unsync_page(kvm, sp);
2880 spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2883 * We need to ensure that the marking of unsync pages is visible
2884 * before the SPTE is updated to allow writes because
2885 * kvm_mmu_sync_roots() checks the unsync flags without holding
2886 * the MMU lock and so can race with this. If the SPTE was updated
2887 * before the page had been marked as unsync-ed, something like the
2888 * following could happen:
2891 * ---------------------------------------------------------------------
2892 * 1.2 Host updates SPTE
2894 * 2.1 Guest writes a GPTE for GVA X.
2895 * (GPTE being in the guest page table shadowed
2896 * by the SP from CPU 1.)
2897 * This reads SPTE during the page table walk.
2898 * Since SPTE.W is read as 1, there is no
2901 * 2.2 Guest issues TLB flush.
2902 * That causes a VM Exit.
2904 * 2.3 Walking of unsync pages sees sp->unsync is
2905 * false and skips the page.
2907 * 2.4 Guest accesses GVA X.
2908 * Since the mapping in the SP was not updated,
2909 * so the old mapping for GVA X incorrectly
2913 * (sp->unsync = true)
2915 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2916 * the situation in 2.4 does not arise. It pairs with the read barrier
2917 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2924 static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
2925 u64 *sptep, unsigned int pte_access, gfn_t gfn,
2926 kvm_pfn_t pfn, struct kvm_page_fault *fault)
2928 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2929 int level = sp->role.level;
2930 int was_rmapped = 0;
2931 int ret = RET_PF_FIXED;
2936 /* Prefetching always gets a writable pfn. */
2937 bool host_writable = !fault || fault->map_writable;
2938 bool prefetch = !fault || fault->prefetch;
2939 bool write_fault = fault && fault->write;
2941 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2942 *sptep, write_fault, gfn);
2944 if (unlikely(is_noslot_pfn(pfn))) {
2945 vcpu->stat.pf_mmio_spte_created++;
2946 mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2947 return RET_PF_EMULATE;
2950 if (is_shadow_present_pte(*sptep)) {
2952 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2953 * the parent of the now unreachable PTE.
2955 if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2956 struct kvm_mmu_page *child;
2959 child = spte_to_child_sp(pte);
2960 drop_parent_pte(child, sptep);
2962 } else if (pfn != spte_to_pfn(*sptep)) {
2963 pgprintk("hfn old %llx new %llx\n",
2964 spte_to_pfn(*sptep), pfn);
2965 drop_spte(vcpu->kvm, sptep);
2971 wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
2972 true, host_writable, &spte);
2974 if (*sptep == spte) {
2975 ret = RET_PF_SPURIOUS;
2977 flush |= mmu_spte_update(sptep, spte);
2978 trace_kvm_mmu_set_spte(level, gfn, sptep);
2983 ret = RET_PF_EMULATE;
2987 kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
2989 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2992 WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
2993 rmap_add(vcpu, slot, sptep, gfn, pte_access);
2995 /* Already rmapped but the pte_access bits may have changed. */
2996 kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
3002 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3003 struct kvm_mmu_page *sp,
3004 u64 *start, u64 *end)
3006 struct page *pages[PTE_PREFETCH_NUM];
3007 struct kvm_memory_slot *slot;
3008 unsigned int access = sp->role.access;
3012 gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
3013 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3017 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3021 for (i = 0; i < ret; i++, gfn++, start++) {
3022 mmu_set_spte(vcpu, slot, start, access, gfn,
3023 page_to_pfn(pages[i]), NULL);
3030 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3031 struct kvm_mmu_page *sp, u64 *sptep)
3033 u64 *spte, *start = NULL;
3036 WARN_ON(!sp->role.direct);
3038 i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
3041 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3042 if (is_shadow_present_pte(*spte) || spte == sptep) {
3045 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3052 direct_pte_prefetch_many(vcpu, sp, start, spte);
3055 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3057 struct kvm_mmu_page *sp;
3059 sp = sptep_to_sp(sptep);
3062 * Without accessed bits, there's no way to distinguish between
3063 * actually accessed translations and prefetched, so disable pte
3064 * prefetch if accessed bits aren't available.
3066 if (sp_ad_disabled(sp))
3069 if (sp->role.level > PG_LEVEL_4K)
3073 * If addresses are being invalidated, skip prefetching to avoid
3074 * accidentally prefetching those addresses.
3076 if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
3079 __direct_pte_prefetch(vcpu, sp, sptep);
3083 * Lookup the mapping level for @gfn in the current mm.
3085 * WARNING! Use of host_pfn_mapping_level() requires the caller and the end
3086 * consumer to be tied into KVM's handlers for MMU notifier events!
3088 * There are several ways to safely use this helper:
3090 * - Check mmu_invalidate_retry_hva() after grabbing the mapping level, before
3091 * consuming it. In this case, mmu_lock doesn't need to be held during the
3092 * lookup, but it does need to be held while checking the MMU notifier.
3094 * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
3095 * event for the hva. This can be done by explicit checking the MMU notifier
3096 * or by ensuring that KVM already has a valid mapping that covers the hva.
3098 * - Do not use the result to install new mappings, e.g. use the host mapping
3099 * level only to decide whether or not to zap an entry. In this case, it's
3100 * not required to hold mmu_lock (though it's highly likely the caller will
3101 * want to hold mmu_lock anyways, e.g. to modify SPTEs).
3103 * Note! The lookup can still race with modifications to host page tables, but
3104 * the above "rules" ensure KVM will not _consume_ the result of the walk if a
3105 * race with the primary MMU occurs.
3107 static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
3108 const struct kvm_memory_slot *slot)
3110 int level = PG_LEVEL_4K;
3112 unsigned long flags;
3119 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3120 * is not solely for performance, it's also necessary to avoid the
3121 * "writable" check in __gfn_to_hva_many(), which will always fail on
3122 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
3123 * page fault steps have already verified the guest isn't writing a
3124 * read-only memslot.
3126 hva = __gfn_to_hva_memslot(slot, gfn);
3129 * Disable IRQs to prevent concurrent tear down of host page tables,
3130 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
3131 * the original page table.
3133 local_irq_save(flags);
3136 * Read each entry once. As above, a non-leaf entry can be promoted to
3137 * a huge page _during_ this walk. Re-reading the entry could send the
3138 * walk into the weeks, e.g. p*d_large() returns false (sees the old
3139 * value) and then p*d_offset() walks into the target huge page instead
3140 * of the old page table (sees the new value).
3142 pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
3146 p4d = READ_ONCE(*p4d_offset(&pgd, hva));
3147 if (p4d_none(p4d) || !p4d_present(p4d))
3150 pud = READ_ONCE(*pud_offset(&p4d, hva));
3151 if (pud_none(pud) || !pud_present(pud))
3154 if (pud_large(pud)) {
3155 level = PG_LEVEL_1G;
3159 pmd = READ_ONCE(*pmd_offset(&pud, hva));
3160 if (pmd_none(pmd) || !pmd_present(pmd))
3164 level = PG_LEVEL_2M;
3167 local_irq_restore(flags);
3171 int kvm_mmu_max_mapping_level(struct kvm *kvm,
3172 const struct kvm_memory_slot *slot, gfn_t gfn,
3175 struct kvm_lpage_info *linfo;
3178 max_level = min(max_level, max_huge_page_level);
3179 for ( ; max_level > PG_LEVEL_4K; max_level--) {
3180 linfo = lpage_info_slot(gfn, slot, max_level);
3181 if (!linfo->disallow_lpage)
3185 if (max_level == PG_LEVEL_4K)
3188 host_level = host_pfn_mapping_level(kvm, gfn, slot);
3189 return min(host_level, max_level);
3192 void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3194 struct kvm_memory_slot *slot = fault->slot;
3197 fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
3199 if (unlikely(fault->max_level == PG_LEVEL_4K))
3202 if (is_error_noslot_pfn(fault->pfn))
3205 if (kvm_slot_dirty_track_enabled(slot))
3209 * Enforce the iTLB multihit workaround after capturing the requested
3210 * level, which will be used to do precise, accurate accounting.
3212 fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3213 fault->gfn, fault->max_level);
3214 if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
3218 * mmu_invalidate_retry() was successful and mmu_lock is held, so
3219 * the pmd can't be split from under us.
3221 fault->goal_level = fault->req_level;
3222 mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
3223 VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
3224 fault->pfn &= ~mask;
3227 void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3229 if (cur_level > PG_LEVEL_4K &&
3230 cur_level == fault->goal_level &&
3231 is_shadow_present_pte(spte) &&
3232 !is_large_pte(spte) &&
3233 spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3235 * A small SPTE exists for this pfn, but FNAME(fetch),
3236 * direct_map(), or kvm_tdp_mmu_map() would like to create a
3237 * large PTE instead: just force them to go down another level,
3238 * patching back for them into pfn the next 9 bits of the
3241 u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3242 KVM_PAGES_PER_HPAGE(cur_level - 1);
3243 fault->pfn |= fault->gfn & page_mask;
3244 fault->goal_level--;
3248 static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3250 struct kvm_shadow_walk_iterator it;
3251 struct kvm_mmu_page *sp;
3253 gfn_t base_gfn = fault->gfn;
3255 kvm_mmu_hugepage_adjust(vcpu, fault);
3257 trace_kvm_mmu_spte_requested(fault);
3258 for_each_shadow_entry(vcpu, fault->addr, it) {
3260 * We cannot overwrite existing page tables with an NX
3261 * large page, as the leaf could be executable.
3263 if (fault->nx_huge_page_workaround_enabled)
3264 disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3266 base_gfn = gfn_round_for_level(fault->gfn, it.level);
3267 if (it.level == fault->goal_level)
3270 sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
3271 if (sp == ERR_PTR(-EEXIST))
3274 link_shadow_page(vcpu, it.sptep, sp);
3275 if (fault->huge_page_disallowed)
3276 account_nx_huge_page(vcpu->kvm, sp,
3277 fault->req_level >= it.level);
3280 if (WARN_ON_ONCE(it.level != fault->goal_level))
3283 ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3284 base_gfn, fault->pfn, fault);
3285 if (ret == RET_PF_SPURIOUS)
3288 direct_pte_prefetch(vcpu, it.sptep);
3292 static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3294 unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3296 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3299 static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3301 if (is_sigpending_pfn(fault->pfn)) {
3302 kvm_handle_signal_exit(vcpu);
3307 * Do not cache the mmio info caused by writing the readonly gfn
3308 * into the spte otherwise read access on readonly gfn also can
3309 * caused mmio page fault and treat it as mmio access.
3311 if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3312 return RET_PF_EMULATE;
3314 if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3315 kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3316 return RET_PF_RETRY;
3322 static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3323 struct kvm_page_fault *fault,
3324 unsigned int access)
3326 gva_t gva = fault->is_tdp ? 0 : fault->addr;
3328 vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3329 access & shadow_mmio_access_mask);
3332 * If MMIO caching is disabled, emulate immediately without
3333 * touching the shadow page tables as attempting to install an
3334 * MMIO SPTE will just be an expensive nop.
3336 if (unlikely(!enable_mmio_caching))
3337 return RET_PF_EMULATE;
3340 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3341 * any guest that generates such gfns is running nested and is being
3342 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3343 * only if L1's MAXPHYADDR is inaccurate with respect to the
3346 if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3347 return RET_PF_EMULATE;
3349 return RET_PF_CONTINUE;
3352 static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3355 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
3356 * reach the common page fault handler if the SPTE has an invalid MMIO
3357 * generation number. Refreshing the MMIO generation needs to go down
3358 * the slow path. Note, EPT Misconfigs do NOT set the PRESENT flag!
3364 * #PF can be fast if:
3366 * 1. The shadow page table entry is not present and A/D bits are
3367 * disabled _by KVM_, which could mean that the fault is potentially
3368 * caused by access tracking (if enabled). If A/D bits are enabled
3369 * by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
3370 * bits for L2 and employ access tracking, but the fast page fault
3371 * mechanism only supports direct MMUs.
3372 * 2. The shadow page table entry is present, the access is a write,
3373 * and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
3374 * the fault was caused by a write-protection violation. If the
3375 * SPTE is MMU-writable (determined later), the fault can be fixed
3376 * by setting the Writable bit, which can be done out of mmu_lock.
3378 if (!fault->present)
3379 return !kvm_ad_enabled();
3382 * Note, instruction fetches and writes are mutually exclusive, ignore
3385 return fault->write;
3389 * Returns true if the SPTE was fixed successfully. Otherwise,
3390 * someone else modified the SPTE from its original value.
3392 static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu,
3393 struct kvm_page_fault *fault,
3394 u64 *sptep, u64 old_spte, u64 new_spte)
3397 * Theoretically we could also set dirty bit (and flush TLB) here in
3398 * order to eliminate unnecessary PML logging. See comments in
3399 * set_spte. But fast_page_fault is very unlikely to happen with PML
3400 * enabled, so we do not do this. This might result in the same GPA
3401 * to be logged in PML buffer again when the write really happens, and
3402 * eventually to be called by mark_page_dirty twice. But it's also no
3403 * harm. This also avoids the TLB flush needed after setting dirty bit
3404 * so non-PML cases won't be impacted.
3406 * Compare with set_spte where instead shadow_dirty_mask is set.
3408 if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3411 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3412 mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3417 static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3420 return is_executable_pte(spte);
3423 return is_writable_pte(spte);
3425 /* Fault was on Read access */
3426 return spte & PT_PRESENT_MASK;
3430 * Returns the last level spte pointer of the shadow page walk for the given
3431 * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
3432 * walk could be performed, returns NULL and *spte does not contain valid data.
3435 * - Must be called between walk_shadow_page_lockless_{begin,end}.
3436 * - The returned sptep must not be used after walk_shadow_page_lockless_end.
3438 static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
3440 struct kvm_shadow_walk_iterator iterator;
3444 for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
3445 sptep = iterator.sptep;
3453 * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3455 static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3457 struct kvm_mmu_page *sp;
3458 int ret = RET_PF_INVALID;
3461 uint retry_count = 0;
3463 if (!page_fault_can_be_fast(fault))
3466 walk_shadow_page_lockless_begin(vcpu);
3471 if (tdp_mmu_enabled)
3472 sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3474 sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3476 if (!is_shadow_present_pte(spte))
3479 sp = sptep_to_sp(sptep);
3480 if (!is_last_spte(spte, sp->role.level))
3484 * Check whether the memory access that caused the fault would
3485 * still cause it if it were to be performed right now. If not,
3486 * then this is a spurious fault caused by TLB lazily flushed,
3487 * or some other CPU has already fixed the PTE after the
3488 * current CPU took the fault.
3490 * Need not check the access of upper level table entries since
3491 * they are always ACC_ALL.
3493 if (is_access_allowed(fault, spte)) {
3494 ret = RET_PF_SPURIOUS;
3501 * KVM only supports fixing page faults outside of MMU lock for
3502 * direct MMUs, nested MMUs are always indirect, and KVM always
3503 * uses A/D bits for non-nested MMUs. Thus, if A/D bits are
3504 * enabled, the SPTE can't be an access-tracked SPTE.
3506 if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3507 new_spte = restore_acc_track_spte(new_spte);
3510 * To keep things simple, only SPTEs that are MMU-writable can
3511 * be made fully writable outside of mmu_lock, e.g. only SPTEs
3512 * that were write-protected for dirty-logging or access
3513 * tracking are handled here. Don't bother checking if the
3514 * SPTE is writable to prioritize running with A/D bits enabled.
3515 * The is_access_allowed() check above handles the common case
3516 * of the fault being spurious, and the SPTE is known to be
3517 * shadow-present, i.e. except for access tracking restoration
3518 * making the new SPTE writable, the check is wasteful.
3520 if (fault->write && is_mmu_writable_spte(spte)) {
3521 new_spte |= PT_WRITABLE_MASK;
3524 * Do not fix write-permission on the large spte when
3525 * dirty logging is enabled. Since we only dirty the
3526 * first page into the dirty-bitmap in
3527 * fast_pf_fix_direct_spte(), other pages are missed
3528 * if its slot has dirty logging enabled.
3530 * Instead, we let the slow page fault path create a
3531 * normal spte to fix the access.
3533 if (sp->role.level > PG_LEVEL_4K &&
3534 kvm_slot_dirty_track_enabled(fault->slot))
3538 /* Verify that the fault can be handled in the fast path */
3539 if (new_spte == spte ||
3540 !is_access_allowed(fault, new_spte))
3544 * Currently, fast page fault only works for direct mapping
3545 * since the gfn is not stable for indirect shadow page. See
3546 * Documentation/virt/kvm/locking.rst to get more detail.
3548 if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3553 if (++retry_count > 4) {
3554 pr_warn_once("Fast #PF retrying more than 4 times.\n");
3560 trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3561 walk_shadow_page_lockless_end(vcpu);
3563 if (ret != RET_PF_INVALID)
3564 vcpu->stat.pf_fast++;
3569 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3570 struct list_head *invalid_list)
3572 struct kvm_mmu_page *sp;
3574 if (!VALID_PAGE(*root_hpa))
3578 * The "root" may be a special root, e.g. a PAE entry, treat it as a
3579 * SPTE to ensure any non-PA bits are dropped.
3581 sp = spte_to_child_sp(*root_hpa);
3585 if (is_tdp_mmu_page(sp))
3586 kvm_tdp_mmu_put_root(kvm, sp, false);
3587 else if (!--sp->root_count && sp->role.invalid)
3588 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3590 *root_hpa = INVALID_PAGE;
3593 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3594 void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3595 ulong roots_to_free)
3598 LIST_HEAD(invalid_list);
3599 bool free_active_root;
3601 WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3603 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3605 /* Before acquiring the MMU lock, see if we need to do any real work. */
3606 free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3607 && VALID_PAGE(mmu->root.hpa);
3609 if (!free_active_root) {
3610 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3611 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3612 VALID_PAGE(mmu->prev_roots[i].hpa))
3615 if (i == KVM_MMU_NUM_PREV_ROOTS)
3619 write_lock(&kvm->mmu_lock);
3621 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3622 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3623 mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3626 if (free_active_root) {
3627 if (to_shadow_page(mmu->root.hpa)) {
3628 mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
3629 } else if (mmu->pae_root) {
3630 for (i = 0; i < 4; ++i) {
3631 if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3634 mmu_free_root_page(kvm, &mmu->pae_root[i],
3636 mmu->pae_root[i] = INVALID_PAE_ROOT;
3639 mmu->root.hpa = INVALID_PAGE;
3643 kvm_mmu_commit_zap_page(kvm, &invalid_list);
3644 write_unlock(&kvm->mmu_lock);
3646 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3648 void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
3650 unsigned long roots_to_free = 0;
3655 * This should not be called while L2 is active, L2 can't invalidate
3656 * _only_ its own roots, e.g. INVVPID unconditionally exits.
3658 WARN_ON_ONCE(mmu->root_role.guest_mode);
3660 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
3661 root_hpa = mmu->prev_roots[i].hpa;
3662 if (!VALID_PAGE(root_hpa))
3665 if (!to_shadow_page(root_hpa) ||
3666 to_shadow_page(root_hpa)->role.guest_mode)
3667 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
3670 kvm_mmu_free_roots(kvm, mmu, roots_to_free);
3672 EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
3675 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3679 if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3680 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3687 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
3690 union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3691 struct kvm_mmu_page *sp;
3694 role.quadrant = quadrant;
3696 WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
3697 WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
3699 sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
3702 return __pa(sp->spt);
3705 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3707 struct kvm_mmu *mmu = vcpu->arch.mmu;
3708 u8 shadow_root_level = mmu->root_role.level;
3713 write_lock(&vcpu->kvm->mmu_lock);
3714 r = make_mmu_pages_available(vcpu);
3718 if (tdp_mmu_enabled) {
3719 root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3720 mmu->root.hpa = root;
3721 } else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3722 root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3723 mmu->root.hpa = root;
3724 } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3725 if (WARN_ON_ONCE(!mmu->pae_root)) {
3730 for (i = 0; i < 4; ++i) {
3731 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3733 root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
3735 mmu->pae_root[i] = root | PT_PRESENT_MASK |
3738 mmu->root.hpa = __pa(mmu->pae_root);
3740 WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
3745 /* root.pgd is ignored for direct MMUs. */
3748 write_unlock(&vcpu->kvm->mmu_lock);
3752 static int mmu_first_shadow_root_alloc(struct kvm *kvm)
3754 struct kvm_memslots *slots;
3755 struct kvm_memory_slot *slot;
3759 * Check if this is the first shadow root being allocated before
3762 if (kvm_shadow_root_allocated(kvm))
3765 mutex_lock(&kvm->slots_arch_lock);
3767 /* Recheck, under the lock, whether this is the first shadow root. */
3768 if (kvm_shadow_root_allocated(kvm))
3772 * Check if anything actually needs to be allocated, e.g. all metadata
3773 * will be allocated upfront if TDP is disabled.
3775 if (kvm_memslots_have_rmaps(kvm) &&
3776 kvm_page_track_write_tracking_enabled(kvm))
3779 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
3780 slots = __kvm_memslots(kvm, i);
3781 kvm_for_each_memslot(slot, bkt, slots) {
3783 * Both of these functions are no-ops if the target is
3784 * already allocated, so unconditionally calling both
3785 * is safe. Intentionally do NOT free allocations on
3786 * failure to avoid having to track which allocations
3787 * were made now versus when the memslot was created.
3788 * The metadata is guaranteed to be freed when the slot
3789 * is freed, and will be kept/used if userspace retries
3790 * KVM_RUN instead of killing the VM.
3792 r = memslot_rmap_alloc(slot, slot->npages);
3795 r = kvm_page_track_write_tracking_alloc(slot);
3802 * Ensure that shadow_root_allocated becomes true strictly after
3803 * all the related pointers are set.
3806 smp_store_release(&kvm->arch.shadow_root_allocated, true);
3809 mutex_unlock(&kvm->slots_arch_lock);
3813 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3815 struct kvm_mmu *mmu = vcpu->arch.mmu;
3816 u64 pdptrs[4], pm_mask;
3817 gfn_t root_gfn, root_pgd;
3821 root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
3822 root_gfn = root_pgd >> PAGE_SHIFT;
3824 if (mmu_check_root(vcpu, root_gfn))
3828 * On SVM, reading PDPTRs might access guest memory, which might fault
3829 * and thus might sleep. Grab the PDPTRs before acquiring mmu_lock.
3831 if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3832 for (i = 0; i < 4; ++i) {
3833 pdptrs[i] = mmu->get_pdptr(vcpu, i);
3834 if (!(pdptrs[i] & PT_PRESENT_MASK))
3837 if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
3842 r = mmu_first_shadow_root_alloc(vcpu->kvm);
3846 write_lock(&vcpu->kvm->mmu_lock);
3847 r = make_mmu_pages_available(vcpu);
3852 * Do we shadow a long mode page table? If so we need to
3853 * write-protect the guests page table root.
3855 if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3856 root = mmu_alloc_root(vcpu, root_gfn, 0,
3857 mmu->root_role.level);
3858 mmu->root.hpa = root;
3862 if (WARN_ON_ONCE(!mmu->pae_root)) {
3868 * We shadow a 32 bit page table. This may be a legacy 2-level
3869 * or a PAE 3-level page table. In either case we need to be aware that
3870 * the shadow page table may be a PAE or a long mode page table.
3872 pm_mask = PT_PRESENT_MASK | shadow_me_value;
3873 if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3874 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3876 if (WARN_ON_ONCE(!mmu->pml4_root)) {
3880 mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3882 if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3883 if (WARN_ON_ONCE(!mmu->pml5_root)) {
3887 mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3891 for (i = 0; i < 4; ++i) {
3892 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3894 if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3895 if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3896 mmu->pae_root[i] = INVALID_PAE_ROOT;
3899 root_gfn = pdptrs[i] >> PAGE_SHIFT;
3903 * If shadowing 32-bit non-PAE page tables, each PAE page
3904 * directory maps one quarter of the guest's non-PAE page
3905 * directory. Othwerise each PAE page direct shadows one guest
3906 * PAE page directory so that quadrant should be 0.
3908 quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
3910 root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3911 mmu->pae_root[i] = root | pm_mask;
3914 if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3915 mmu->root.hpa = __pa(mmu->pml5_root);
3916 else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3917 mmu->root.hpa = __pa(mmu->pml4_root);
3919 mmu->root.hpa = __pa(mmu->pae_root);
3922 mmu->root.pgd = root_pgd;
3924 write_unlock(&vcpu->kvm->mmu_lock);
3929 static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3931 struct kvm_mmu *mmu = vcpu->arch.mmu;
3932 bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3933 u64 *pml5_root = NULL;
3934 u64 *pml4_root = NULL;
3938 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3939 * tables are allocated and initialized at root creation as there is no
3940 * equivalent level in the guest's NPT to shadow. Allocate the tables
3941 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3943 if (mmu->root_role.direct ||
3944 mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3945 mmu->root_role.level < PT64_ROOT_4LEVEL)
3949 * NPT, the only paging mode that uses this horror, uses a fixed number
3950 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3951 * all MMus are 5-level. Thus, this can safely require that pml5_root
3952 * is allocated if the other roots are valid and pml5 is needed, as any
3953 * prior MMU would also have required pml5.
3955 if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3959 * The special roots should always be allocated in concert. Yell and
3960 * bail if KVM ends up in a state where only one of the roots is valid.
3962 if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3963 (need_pml5 && mmu->pml5_root)))
3967 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
3968 * doesn't need to be decrypted.
3970 pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3974 #ifdef CONFIG_X86_64
3975 pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3980 pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3986 mmu->pae_root = pae_root;
3987 mmu->pml4_root = pml4_root;
3988 mmu->pml5_root = pml5_root;
3992 #ifdef CONFIG_X86_64
3994 free_page((unsigned long)pml4_root);
3996 free_page((unsigned long)pae_root);
4001 static bool is_unsync_root(hpa_t root)
4003 struct kvm_mmu_page *sp;
4005 if (!VALID_PAGE(root))
4009 * The read barrier orders the CPU's read of SPTE.W during the page table
4010 * walk before the reads of sp->unsync/sp->unsync_children here.
4012 * Even if another CPU was marking the SP as unsync-ed simultaneously,
4013 * any guest page table changes are not guaranteed to be visible anyway
4014 * until this VCPU issues a TLB flush strictly after those changes are
4015 * made. We only need to ensure that the other CPU sets these flags
4016 * before any actual changes to the page tables are made. The comments
4017 * in mmu_try_to_unsync_pages() describe what could go wrong if this
4018 * requirement isn't satisfied.
4021 sp = to_shadow_page(root);
4024 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
4025 * PDPTEs for a given PAE root need to be synchronized individually.
4027 if (WARN_ON_ONCE(!sp))
4030 if (sp->unsync || sp->unsync_children)
4036 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
4039 struct kvm_mmu_page *sp;
4041 if (vcpu->arch.mmu->root_role.direct)
4044 if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
4047 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4049 if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
4050 hpa_t root = vcpu->arch.mmu->root.hpa;
4051 sp = to_shadow_page(root);
4053 if (!is_unsync_root(root))
4056 write_lock(&vcpu->kvm->mmu_lock);
4057 mmu_sync_children(vcpu, sp, true);
4058 write_unlock(&vcpu->kvm->mmu_lock);
4062 write_lock(&vcpu->kvm->mmu_lock);
4064 for (i = 0; i < 4; ++i) {
4065 hpa_t root = vcpu->arch.mmu->pae_root[i];
4067 if (IS_VALID_PAE_ROOT(root)) {
4068 sp = spte_to_child_sp(root);
4069 mmu_sync_children(vcpu, sp, true);
4073 write_unlock(&vcpu->kvm->mmu_lock);
4076 void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
4078 unsigned long roots_to_free = 0;
4081 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4082 if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
4083 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
4085 /* sync prev_roots by simply freeing them */
4086 kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
4089 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4090 gpa_t vaddr, u64 access,
4091 struct x86_exception *exception)
4094 exception->error_code = 0;
4095 return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4098 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4101 * A nested guest cannot use the MMIO cache if it is using nested
4102 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4104 if (mmu_is_nested(vcpu))
4108 return vcpu_match_mmio_gpa(vcpu, addr);
4110 return vcpu_match_mmio_gva(vcpu, addr);
4114 * Return the level of the lowest level SPTE added to sptes.
4115 * That SPTE may be non-present.
4117 * Must be called between walk_shadow_page_lockless_{begin,end}.
4119 static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4121 struct kvm_shadow_walk_iterator iterator;
4125 for (shadow_walk_init(&iterator, vcpu, addr),
4126 *root_level = iterator.level;
4127 shadow_walk_okay(&iterator);
4128 __shadow_walk_next(&iterator, spte)) {
4129 leaf = iterator.level;
4130 spte = mmu_spte_get_lockless(iterator.sptep);
4138 /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
4139 static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
4141 u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
4142 struct rsvd_bits_validate *rsvd_check;
4143 int root, leaf, level;
4144 bool reserved = false;
4146 walk_shadow_page_lockless_begin(vcpu);
4148 if (is_tdp_mmu_active(vcpu))
4149 leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
4151 leaf = get_walk(vcpu, addr, sptes, &root);
4153 walk_shadow_page_lockless_end(vcpu);
4155 if (unlikely(leaf < 0)) {
4160 *sptep = sptes[leaf];
4163 * Skip reserved bits checks on the terminal leaf if it's not a valid
4164 * SPTE. Note, this also (intentionally) skips MMIO SPTEs, which, by
4165 * design, always have reserved bits set. The purpose of the checks is
4166 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
4168 if (!is_shadow_present_pte(sptes[leaf]))
4171 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
4173 for (level = root; level >= leaf; level--)
4174 reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4177 pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4179 for (level = root; level >= leaf; level--)
4180 pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4181 sptes[level], level,
4182 get_rsvd_bits(rsvd_check, sptes[level], level));
4188 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4193 if (mmio_info_in_cache(vcpu, addr, direct))
4194 return RET_PF_EMULATE;
4196 reserved = get_mmio_spte(vcpu, addr, &spte);
4197 if (WARN_ON(reserved))
4200 if (is_mmio_spte(spte)) {
4201 gfn_t gfn = get_mmio_spte_gfn(spte);
4202 unsigned int access = get_mmio_spte_access(spte);
4204 if (!check_mmio_spte(vcpu, spte))
4205 return RET_PF_INVALID;
4210 trace_handle_mmio_page_fault(addr, gfn, access);
4211 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4212 return RET_PF_EMULATE;
4216 * If the page table is zapped by other cpus, let CPU fault again on
4219 return RET_PF_RETRY;
4222 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4223 struct kvm_page_fault *fault)
4225 if (unlikely(fault->rsvd))
4228 if (!fault->present || !fault->write)
4232 * guest is writing the page which is write tracked which can
4233 * not be fixed by page fault handler.
4235 if (kvm_slot_page_track_is_active(vcpu->kvm, fault->slot, fault->gfn, KVM_PAGE_TRACK_WRITE))
4241 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4243 struct kvm_shadow_walk_iterator iterator;
4246 walk_shadow_page_lockless_begin(vcpu);
4247 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4248 clear_sp_write_flooding_count(iterator.sptep);
4249 walk_shadow_page_lockless_end(vcpu);
4252 static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
4254 /* make sure the token value is not 0 */
4255 u32 id = vcpu->arch.apf.id;
4258 vcpu->arch.apf.id = 1;
4260 return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4263 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4266 struct kvm_arch_async_pf arch;
4268 arch.token = alloc_apf_token(vcpu);
4270 arch.direct_map = vcpu->arch.mmu->root_role.direct;
4271 arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
4273 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4274 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4277 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
4281 if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
4285 r = kvm_mmu_reload(vcpu);
4289 if (!vcpu->arch.mmu->root_role.direct &&
4290 work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
4293 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true, NULL);
4296 static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4298 struct kvm_memory_slot *slot = fault->slot;
4302 * Retry the page fault if the gfn hit a memslot that is being deleted
4303 * or moved. This ensures any existing SPTEs for the old memslot will
4304 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4306 if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
4307 return RET_PF_RETRY;
4309 if (!kvm_is_visible_memslot(slot)) {
4310 /* Don't expose private memslots to L2. */
4311 if (is_guest_mode(vcpu)) {
4313 fault->pfn = KVM_PFN_NOSLOT;
4314 fault->map_writable = false;
4315 return RET_PF_CONTINUE;
4318 * If the APIC access page exists but is disabled, go directly
4319 * to emulation without caching the MMIO access or creating a
4320 * MMIO SPTE. That way the cache doesn't need to be purged
4321 * when the AVIC is re-enabled.
4323 if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
4324 !kvm_apicv_activated(vcpu->kvm))
4325 return RET_PF_EMULATE;
4329 fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, false, &async,
4330 fault->write, &fault->map_writable,
4333 return RET_PF_CONTINUE; /* *pfn has correct page already */
4335 if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
4336 trace_kvm_try_async_get_page(fault->addr, fault->gfn);
4337 if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
4338 trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4339 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4340 return RET_PF_RETRY;
4341 } else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
4342 return RET_PF_RETRY;
4347 * Allow gup to bail on pending non-fatal signals when it's also allowed
4348 * to wait for IO. Note, gup always bails if it is unable to quickly
4349 * get a page and a fatal signal, i.e. SIGKILL, is pending.
4351 fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, true, NULL,
4352 fault->write, &fault->map_writable,
4354 return RET_PF_CONTINUE;
4357 static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4358 unsigned int access)
4362 fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4365 ret = __kvm_faultin_pfn(vcpu, fault);
4366 if (ret != RET_PF_CONTINUE)
4369 if (unlikely(is_error_pfn(fault->pfn)))
4370 return kvm_handle_error_pfn(vcpu, fault);
4372 if (unlikely(!fault->slot))
4373 return kvm_handle_noslot_fault(vcpu, fault, access);
4375 return RET_PF_CONTINUE;
4379 * Returns true if the page fault is stale and needs to be retried, i.e. if the
4380 * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4382 static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4383 struct kvm_page_fault *fault)
4385 struct kvm_mmu_page *sp = to_shadow_page(vcpu->arch.mmu->root.hpa);
4387 /* Special roots, e.g. pae_root, are not backed by shadow pages. */
4388 if (sp && is_obsolete_sp(vcpu->kvm, sp))
4392 * Roots without an associated shadow page are considered invalid if
4393 * there is a pending request to free obsolete roots. The request is
4394 * only a hint that the current root _may_ be obsolete and needs to be
4395 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
4396 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
4397 * to reload even if no vCPU is actively using the root.
4399 if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4402 return fault->slot &&
4403 mmu_invalidate_retry_hva(vcpu->kvm, fault->mmu_seq, fault->hva);
4406 static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4410 if (page_fault_handle_page_track(vcpu, fault))
4411 return RET_PF_EMULATE;
4413 r = fast_page_fault(vcpu, fault);
4414 if (r != RET_PF_INVALID)
4417 r = mmu_topup_memory_caches(vcpu, false);
4421 r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4422 if (r != RET_PF_CONTINUE)
4426 write_lock(&vcpu->kvm->mmu_lock);
4428 if (is_page_fault_stale(vcpu, fault))
4431 r = make_mmu_pages_available(vcpu);
4435 r = direct_map(vcpu, fault);
4438 write_unlock(&vcpu->kvm->mmu_lock);
4439 kvm_release_pfn_clean(fault->pfn);
4443 static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4444 struct kvm_page_fault *fault)
4446 pgprintk("%s: gva %lx error %x\n", __func__, fault->addr, fault->error_code);
4448 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4449 fault->max_level = PG_LEVEL_2M;
4450 return direct_page_fault(vcpu, fault);
4453 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4454 u64 fault_address, char *insn, int insn_len)
4457 u32 flags = vcpu->arch.apf.host_apf_flags;
4459 #ifndef CONFIG_X86_64
4460 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4461 if (WARN_ON_ONCE(fault_address >> 32))
4465 vcpu->arch.l1tf_flush_l1d = true;
4467 trace_kvm_page_fault(vcpu, fault_address, error_code);
4469 if (kvm_event_needs_reinjection(vcpu))
4470 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4471 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4473 } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
4474 vcpu->arch.apf.host_apf_flags = 0;
4475 local_irq_disable();
4476 kvm_async_pf_task_wait_schedule(fault_address);
4479 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4484 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4486 #ifdef CONFIG_X86_64
4487 static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
4488 struct kvm_page_fault *fault)
4492 if (page_fault_handle_page_track(vcpu, fault))
4493 return RET_PF_EMULATE;
4495 r = fast_page_fault(vcpu, fault);
4496 if (r != RET_PF_INVALID)
4499 r = mmu_topup_memory_caches(vcpu, false);
4503 r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4504 if (r != RET_PF_CONTINUE)
4508 read_lock(&vcpu->kvm->mmu_lock);
4510 if (is_page_fault_stale(vcpu, fault))
4513 r = kvm_tdp_mmu_map(vcpu, fault);
4516 read_unlock(&vcpu->kvm->mmu_lock);
4517 kvm_release_pfn_clean(fault->pfn);
4522 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4525 * If the guest's MTRRs may be used to compute the "real" memtype,
4526 * restrict the mapping level to ensure KVM uses a consistent memtype
4527 * across the entire mapping. If the host MTRRs are ignored by TDP
4528 * (shadow_memtype_mask is non-zero), and the VM has non-coherent DMA
4529 * (DMA doesn't snoop CPU caches), KVM's ABI is to honor the memtype
4530 * from the guest's MTRRs so that guest accesses to memory that is
4531 * DMA'd aren't cached against the guest's wishes.
4533 * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
4534 * e.g. KVM will force UC memtype for host MMIO.
4536 if (shadow_memtype_mask && kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
4537 for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
4538 int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
4539 gfn_t base = gfn_round_for_level(fault->gfn,
4542 if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4547 #ifdef CONFIG_X86_64
4548 if (tdp_mmu_enabled)
4549 return kvm_tdp_mmu_page_fault(vcpu, fault);
4552 return direct_page_fault(vcpu, fault);
4555 static void nonpaging_init_context(struct kvm_mmu *context)
4557 context->page_fault = nonpaging_page_fault;
4558 context->gva_to_gpa = nonpaging_gva_to_gpa;
4559 context->sync_spte = NULL;
4562 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
4563 union kvm_mmu_page_role role)
4565 return (role.direct || pgd == root->pgd) &&
4566 VALID_PAGE(root->hpa) &&
4567 role.word == to_shadow_page(root->hpa)->role.word;
4571 * Find out if a previously cached root matching the new pgd/role is available,
4572 * and insert the current root as the MRU in the cache.
4573 * If a matching root is found, it is assigned to kvm_mmu->root and
4575 * If no match is found, kvm_mmu->root is left invalid, the LRU root is
4576 * evicted to make room for the current root, and false is returned.
4578 static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
4580 union kvm_mmu_page_role new_role)
4584 if (is_root_usable(&mmu->root, new_pgd, new_role))
4587 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4589 * The swaps end up rotating the cache like this:
4590 * C 0 1 2 3 (on entry to the function)
4594 * 3 C 0 1 2 (on exit from the loop)
4596 swap(mmu->root, mmu->prev_roots[i]);
4597 if (is_root_usable(&mmu->root, new_pgd, new_role))
4601 kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4606 * Find out if a previously cached root matching the new pgd/role is available.
4607 * On entry, mmu->root is invalid.
4608 * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
4609 * of the cache becomes invalid, and true is returned.
4610 * If no match is found, kvm_mmu->root is left invalid and false is returned.
4612 static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
4614 union kvm_mmu_page_role new_role)
4618 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4619 if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
4625 swap(mmu->root, mmu->prev_roots[i]);
4626 /* Bubble up the remaining roots. */
4627 for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
4628 mmu->prev_roots[i] = mmu->prev_roots[i + 1];
4629 mmu->prev_roots[i].hpa = INVALID_PAGE;
4633 static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
4634 gpa_t new_pgd, union kvm_mmu_page_role new_role)
4637 * For now, limit the caching to 64-bit hosts+VMs in order to avoid
4638 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4639 * later if necessary.
4641 if (VALID_PAGE(mmu->root.hpa) && !to_shadow_page(mmu->root.hpa))
4642 kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4644 if (VALID_PAGE(mmu->root.hpa))
4645 return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
4647 return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4650 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4652 struct kvm_mmu *mmu = vcpu->arch.mmu;
4653 union kvm_mmu_page_role new_role = mmu->root_role;
4656 * Return immediately if no usable root was found, kvm_mmu_reload()
4657 * will establish a valid root prior to the next VM-Enter.
4659 if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4663 * It's possible that the cached previous root page is obsolete because
4664 * of a change in the MMU generation number. However, changing the
4665 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4666 * which will free the root set here and allocate a new one.
4668 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4670 if (force_flush_and_sync_on_reuse) {
4671 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4672 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4676 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4677 * switching to a new CR3, that GVA->GPA mapping may no longer be
4678 * valid. So clear any cached MMIO info even when we don't need to sync
4679 * the shadow page tables.
4681 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4684 * If this is a direct root page, it doesn't have a write flooding
4685 * count. Otherwise, clear the write flooding count.
4687 if (!new_role.direct)
4688 __clear_sp_write_flooding_count(
4689 to_shadow_page(vcpu->arch.mmu->root.hpa));
4691 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4693 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4694 unsigned int access)
4696 if (unlikely(is_mmio_spte(*sptep))) {
4697 if (gfn != get_mmio_spte_gfn(*sptep)) {
4698 mmu_spte_clear_no_track(sptep);
4702 mark_mmio_spte(vcpu, sptep, gfn, access);
4709 #define PTTYPE_EPT 18 /* arbitrary */
4710 #define PTTYPE PTTYPE_EPT
4711 #include "paging_tmpl.h"
4715 #include "paging_tmpl.h"
4719 #include "paging_tmpl.h"
4722 static void __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
4723 u64 pa_bits_rsvd, int level, bool nx,
4724 bool gbpages, bool pse, bool amd)
4726 u64 gbpages_bit_rsvd = 0;
4727 u64 nonleaf_bit8_rsvd = 0;
4730 rsvd_check->bad_mt_xwr = 0;
4733 gbpages_bit_rsvd = rsvd_bits(7, 7);
4735 if (level == PT32E_ROOT_LEVEL)
4736 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
4738 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4740 /* Note, NX doesn't exist in PDPTEs, this is handled below. */
4742 high_bits_rsvd |= rsvd_bits(63, 63);
4745 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4746 * leaf entries) on AMD CPUs only.
4749 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4752 case PT32_ROOT_LEVEL:
4753 /* no rsvd bits for 2 level 4K page table entries */
4754 rsvd_check->rsvd_bits_mask[0][1] = 0;
4755 rsvd_check->rsvd_bits_mask[0][0] = 0;
4756 rsvd_check->rsvd_bits_mask[1][0] =
4757 rsvd_check->rsvd_bits_mask[0][0];
4760 rsvd_check->rsvd_bits_mask[1][1] = 0;
4764 if (is_cpuid_PSE36())
4765 /* 36bits PSE 4MB page */
4766 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4768 /* 32 bits PSE 4MB page */
4769 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4771 case PT32E_ROOT_LEVEL:
4772 rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
4775 rsvd_bits(1, 2); /* PDPTE */
4776 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd; /* PDE */
4777 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd; /* PTE */
4778 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4779 rsvd_bits(13, 20); /* large page */
4780 rsvd_check->rsvd_bits_mask[1][0] =
4781 rsvd_check->rsvd_bits_mask[0][0];
4783 case PT64_ROOT_5LEVEL:
4784 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
4787 rsvd_check->rsvd_bits_mask[1][4] =
4788 rsvd_check->rsvd_bits_mask[0][4];
4790 case PT64_ROOT_4LEVEL:
4791 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
4794 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
4796 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
4797 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4798 rsvd_check->rsvd_bits_mask[1][3] =
4799 rsvd_check->rsvd_bits_mask[0][3];
4800 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
4803 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4804 rsvd_bits(13, 20); /* large page */
4805 rsvd_check->rsvd_bits_mask[1][0] =
4806 rsvd_check->rsvd_bits_mask[0][0];
4811 static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
4814 * If TDP is enabled, let the guest use GBPAGES if they're supported in
4815 * hardware. The hardware page walker doesn't let KVM disable GBPAGES,
4816 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
4817 * walk for performance and complexity reasons. Not to mention KVM
4818 * _can't_ solve the problem because GVA->GPA walks aren't visible to
4819 * KVM once a TDP translation is installed. Mimic hardware behavior so
4820 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
4822 return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
4823 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
4826 static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4827 struct kvm_mmu *context)
4829 __reset_rsvds_bits_mask(&context->guest_rsvd_check,
4830 vcpu->arch.reserved_gpa_bits,
4831 context->cpu_role.base.level, is_efer_nx(context),
4832 guest_can_use_gbpages(vcpu),
4833 is_cr4_pse(context),
4834 guest_cpuid_is_amd_or_hygon(vcpu));
4837 static void __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4838 u64 pa_bits_rsvd, bool execonly,
4839 int huge_page_level)
4841 u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4842 u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4845 if (huge_page_level < PG_LEVEL_1G)
4846 large_1g_rsvd = rsvd_bits(7, 7);
4847 if (huge_page_level < PG_LEVEL_2M)
4848 large_2m_rsvd = rsvd_bits(7, 7);
4850 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
4851 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
4852 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
4853 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
4854 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4857 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4858 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4859 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
4860 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4861 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4863 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4864 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4865 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4866 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4867 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4869 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4870 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4872 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4875 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4876 struct kvm_mmu *context, bool execonly, int huge_page_level)
4878 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4879 vcpu->arch.reserved_gpa_bits, execonly,
4883 static inline u64 reserved_hpa_bits(void)
4885 return rsvd_bits(shadow_phys_bits, 63);
4889 * the page table on host is the shadow page table for the page
4890 * table in guest or amd nested guest, its mmu features completely
4891 * follow the features in guest.
4893 static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4894 struct kvm_mmu *context)
4896 /* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
4898 /* KVM doesn't use 2-level page tables for the shadow MMU. */
4899 bool is_pse = false;
4900 struct rsvd_bits_validate *shadow_zero_check;
4903 WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
4905 shadow_zero_check = &context->shadow_zero_check;
4906 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4907 context->root_role.level,
4908 context->root_role.efer_nx,
4909 guest_can_use_gbpages(vcpu), is_pse, is_amd);
4911 if (!shadow_me_mask)
4914 for (i = context->root_role.level; --i >= 0;) {
4916 * So far shadow_me_value is a constant during KVM's life
4917 * time. Bits in shadow_me_value are allowed to be set.
4918 * Bits in shadow_me_mask but not in shadow_me_value are
4919 * not allowed to be set.
4921 shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4922 shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4923 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4924 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4929 static inline bool boot_cpu_is_amd(void)
4931 WARN_ON_ONCE(!tdp_enabled);
4932 return shadow_x_mask == 0;
4936 * the direct page table on host, use as much mmu features as
4937 * possible, however, kvm currently does not do execution-protection.
4939 static void reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4941 struct rsvd_bits_validate *shadow_zero_check;
4944 shadow_zero_check = &context->shadow_zero_check;
4946 if (boot_cpu_is_amd())
4947 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4948 context->root_role.level, true,
4949 boot_cpu_has(X86_FEATURE_GBPAGES),
4952 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4953 reserved_hpa_bits(), false,
4954 max_huge_page_level);
4956 if (!shadow_me_mask)
4959 for (i = context->root_role.level; --i >= 0;) {
4960 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4961 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4966 * as the comments in reset_shadow_zero_bits_mask() except it
4967 * is the shadow page table for intel nested guest.
4970 reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
4972 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4973 reserved_hpa_bits(), execonly,
4974 max_huge_page_level);
4977 #define BYTE_MASK(access) \
4978 ((1 & (access) ? 2 : 0) | \
4979 (2 & (access) ? 4 : 0) | \
4980 (3 & (access) ? 8 : 0) | \
4981 (4 & (access) ? 16 : 0) | \
4982 (5 & (access) ? 32 : 0) | \
4983 (6 & (access) ? 64 : 0) | \
4984 (7 & (access) ? 128 : 0))
4987 static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4991 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4992 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4993 const u8 u = BYTE_MASK(ACC_USER_MASK);
4995 bool cr4_smep = is_cr4_smep(mmu);
4996 bool cr4_smap = is_cr4_smap(mmu);
4997 bool cr0_wp = is_cr0_wp(mmu);
4998 bool efer_nx = is_efer_nx(mmu);
5000 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
5001 unsigned pfec = byte << 1;
5004 * Each "*f" variable has a 1 bit for each UWX value
5005 * that causes a fault with the given PFEC.
5008 /* Faults from writes to non-writable pages */
5009 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
5010 /* Faults from user mode accesses to supervisor pages */
5011 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
5012 /* Faults from fetches of non-executable pages*/
5013 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
5014 /* Faults from kernel mode fetches of user pages */
5016 /* Faults from kernel mode accesses of user pages */
5020 /* Faults from kernel mode accesses to user pages */
5021 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
5023 /* Not really needed: !nx will cause pte.nx to fault */
5027 /* Allow supervisor writes if !cr0.wp */
5029 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
5031 /* Disallow supervisor fetches of user code if cr4.smep */
5033 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
5036 * SMAP:kernel-mode data accesses from user-mode
5037 * mappings should fault. A fault is considered
5038 * as a SMAP violation if all of the following
5039 * conditions are true:
5040 * - X86_CR4_SMAP is set in CR4
5041 * - A user page is accessed
5042 * - The access is not a fetch
5043 * - The access is supervisor mode
5044 * - If implicit supervisor access or X86_EFLAGS_AC is clear
5046 * Here, we cover the first four conditions.
5047 * The fifth is computed dynamically in permission_fault();
5048 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5049 * *not* subject to SMAP restrictions.
5052 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5055 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5060 * PKU is an additional mechanism by which the paging controls access to
5061 * user-mode addresses based on the value in the PKRU register. Protection
5062 * key violations are reported through a bit in the page fault error code.
5063 * Unlike other bits of the error code, the PK bit is not known at the
5064 * call site of e.g. gva_to_gpa; it must be computed directly in
5065 * permission_fault based on two bits of PKRU, on some machine state (CR4,
5066 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5068 * In particular the following conditions come from the error code, the
5069 * page tables and the machine state:
5070 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5071 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5072 * - PK is always zero if U=0 in the page tables
5073 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5075 * The PKRU bitmask caches the result of these four conditions. The error
5076 * code (minus the P bit) and the page table's U bit form an index into the
5077 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
5078 * with the two bits of the PKRU register corresponding to the protection key.
5079 * For the first three conditions above the bits will be 00, thus masking
5080 * away both AD and WD. For all reads or if the last condition holds, WD
5081 * only will be masked away.
5083 static void update_pkru_bitmask(struct kvm_mmu *mmu)
5090 if (!is_cr4_pke(mmu))
5093 wp = is_cr0_wp(mmu);
5095 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5096 unsigned pfec, pkey_bits;
5097 bool check_pkey, check_write, ff, uf, wf, pte_user;
5100 ff = pfec & PFERR_FETCH_MASK;
5101 uf = pfec & PFERR_USER_MASK;
5102 wf = pfec & PFERR_WRITE_MASK;
5104 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
5105 pte_user = pfec & PFERR_RSVD_MASK;
5108 * Only need to check the access which is not an
5109 * instruction fetch and is to a user page.
5111 check_pkey = (!ff && pte_user);
5113 * write access is controlled by PKRU if it is a
5114 * user access or CR0.WP = 1.
5116 check_write = check_pkey && wf && (uf || wp);
5118 /* PKRU.AD stops both read and write access. */
5119 pkey_bits = !!check_pkey;
5120 /* PKRU.WD stops write access. */
5121 pkey_bits |= (!!check_write) << 1;
5123 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5127 static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5128 struct kvm_mmu *mmu)
5130 if (!is_cr0_pg(mmu))
5133 reset_guest_rsvds_bits_mask(vcpu, mmu);
5134 update_permission_bitmask(mmu, false);
5135 update_pkru_bitmask(mmu);
5138 static void paging64_init_context(struct kvm_mmu *context)
5140 context->page_fault = paging64_page_fault;
5141 context->gva_to_gpa = paging64_gva_to_gpa;
5142 context->sync_spte = paging64_sync_spte;
5145 static void paging32_init_context(struct kvm_mmu *context)
5147 context->page_fault = paging32_page_fault;
5148 context->gva_to_gpa = paging32_gva_to_gpa;
5149 context->sync_spte = paging32_sync_spte;
5152 static union kvm_cpu_role kvm_calc_cpu_role(struct kvm_vcpu *vcpu,
5153 const struct kvm_mmu_role_regs *regs)
5155 union kvm_cpu_role role = {0};
5157 role.base.access = ACC_ALL;
5158 role.base.smm = is_smm(vcpu);
5159 role.base.guest_mode = is_guest_mode(vcpu);
5162 if (!____is_cr0_pg(regs)) {
5163 role.base.direct = 1;
5167 role.base.efer_nx = ____is_efer_nx(regs);
5168 role.base.cr0_wp = ____is_cr0_wp(regs);
5169 role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5170 role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5171 role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
5173 if (____is_efer_lma(regs))
5174 role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
5176 else if (____is_cr4_pae(regs))
5177 role.base.level = PT32E_ROOT_LEVEL;
5179 role.base.level = PT32_ROOT_LEVEL;
5181 role.ext.cr4_smep = ____is_cr4_smep(regs);
5182 role.ext.cr4_smap = ____is_cr4_smap(regs);
5183 role.ext.cr4_pse = ____is_cr4_pse(regs);
5185 /* PKEY and LA57 are active iff long mode is active. */
5186 role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5187 role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5188 role.ext.efer_lma = ____is_efer_lma(regs);
5192 void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
5193 struct kvm_mmu *mmu)
5195 const bool cr0_wp = kvm_is_cr0_bit_set(vcpu, X86_CR0_WP);
5197 BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
5198 BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
5200 if (is_cr0_wp(mmu) == cr0_wp)
5203 mmu->cpu_role.base.cr0_wp = cr0_wp;
5204 reset_guest_paging_metadata(vcpu, mmu);
5207 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5209 /* tdp_root_level is architecture forced level, use it if nonzero */
5211 return tdp_root_level;
5213 /* Use 5-level TDP if and only if it's useful/necessary. */
5214 if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5217 return max_tdp_level;
5220 static union kvm_mmu_page_role
5221 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
5222 union kvm_cpu_role cpu_role)
5224 union kvm_mmu_page_role role = {0};
5226 role.access = ACC_ALL;
5228 role.efer_nx = true;
5229 role.smm = cpu_role.base.smm;
5230 role.guest_mode = cpu_role.base.guest_mode;
5231 role.ad_disabled = !kvm_ad_enabled();
5232 role.level = kvm_mmu_get_tdp_level(vcpu);
5234 role.has_4_byte_gpte = false;
5239 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5240 union kvm_cpu_role cpu_role)
5242 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5243 union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5245 if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5246 root_role.word == context->root_role.word)
5249 context->cpu_role.as_u64 = cpu_role.as_u64;
5250 context->root_role.word = root_role.word;
5251 context->page_fault = kvm_tdp_page_fault;
5252 context->sync_spte = NULL;
5253 context->get_guest_pgd = get_guest_cr3;
5254 context->get_pdptr = kvm_pdptr_read;
5255 context->inject_page_fault = kvm_inject_page_fault;
5257 if (!is_cr0_pg(context))
5258 context->gva_to_gpa = nonpaging_gva_to_gpa;
5259 else if (is_cr4_pae(context))
5260 context->gva_to_gpa = paging64_gva_to_gpa;
5262 context->gva_to_gpa = paging32_gva_to_gpa;
5264 reset_guest_paging_metadata(vcpu, context);
5265 reset_tdp_shadow_zero_bits_mask(context);
5268 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
5269 union kvm_cpu_role cpu_role,
5270 union kvm_mmu_page_role root_role)
5272 if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5273 root_role.word == context->root_role.word)
5276 context->cpu_role.as_u64 = cpu_role.as_u64;
5277 context->root_role.word = root_role.word;
5279 if (!is_cr0_pg(context))
5280 nonpaging_init_context(context);
5281 else if (is_cr4_pae(context))
5282 paging64_init_context(context);
5284 paging32_init_context(context);
5286 reset_guest_paging_metadata(vcpu, context);
5287 reset_shadow_zero_bits_mask(vcpu, context);
5290 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5291 union kvm_cpu_role cpu_role)
5293 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5294 union kvm_mmu_page_role root_role;
5296 root_role = cpu_role.base;
5298 /* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
5299 root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
5302 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
5303 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
5304 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
5305 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
5306 * The iTLB multi-hit workaround can be toggled at any time, so assume
5307 * NX can be used by any non-nested shadow MMU to avoid having to reset
5310 root_role.efer_nx = true;
5312 shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5315 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5316 unsigned long cr4, u64 efer, gpa_t nested_cr3)
5318 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5319 struct kvm_mmu_role_regs regs = {
5321 .cr4 = cr4 & ~X86_CR4_PKE,
5324 union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, ®s);
5325 union kvm_mmu_page_role root_role;
5327 /* NPT requires CR0.PG=1. */
5328 WARN_ON_ONCE(cpu_role.base.direct);
5330 root_role = cpu_role.base;
5331 root_role.level = kvm_mmu_get_tdp_level(vcpu);
5332 if (root_role.level == PT64_ROOT_5LEVEL &&
5333 cpu_role.base.level == PT64_ROOT_4LEVEL)
5334 root_role.passthrough = 1;
5336 shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5337 kvm_mmu_new_pgd(vcpu, nested_cr3);
5339 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5341 static union kvm_cpu_role
5342 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5343 bool execonly, u8 level)
5345 union kvm_cpu_role role = {0};
5348 * KVM does not support SMM transfer monitors, and consequently does not
5349 * support the "entry to SMM" control either. role.base.smm is always 0.
5351 WARN_ON_ONCE(is_smm(vcpu));
5352 role.base.level = level;
5353 role.base.has_4_byte_gpte = false;
5354 role.base.direct = false;
5355 role.base.ad_disabled = !accessed_dirty;
5356 role.base.guest_mode = true;
5357 role.base.access = ACC_ALL;
5360 role.ext.execonly = execonly;
5366 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5367 int huge_page_level, bool accessed_dirty,
5370 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5371 u8 level = vmx_eptp_page_walk_level(new_eptp);
5372 union kvm_cpu_role new_mode =
5373 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5376 if (new_mode.as_u64 != context->cpu_role.as_u64) {
5377 /* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5378 context->cpu_role.as_u64 = new_mode.as_u64;
5379 context->root_role.word = new_mode.base.word;
5381 context->page_fault = ept_page_fault;
5382 context->gva_to_gpa = ept_gva_to_gpa;
5383 context->sync_spte = ept_sync_spte;
5385 update_permission_bitmask(context, true);
5386 context->pkru_mask = 0;
5387 reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5388 reset_ept_shadow_zero_bits_mask(context, execonly);
5391 kvm_mmu_new_pgd(vcpu, new_eptp);
5393 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5395 static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5396 union kvm_cpu_role cpu_role)
5398 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5400 kvm_init_shadow_mmu(vcpu, cpu_role);
5402 context->get_guest_pgd = get_guest_cr3;
5403 context->get_pdptr = kvm_pdptr_read;
5404 context->inject_page_fault = kvm_inject_page_fault;
5407 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5408 union kvm_cpu_role new_mode)
5410 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5412 if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5415 g_context->cpu_role.as_u64 = new_mode.as_u64;
5416 g_context->get_guest_pgd = get_guest_cr3;
5417 g_context->get_pdptr = kvm_pdptr_read;
5418 g_context->inject_page_fault = kvm_inject_page_fault;
5421 * L2 page tables are never shadowed, so there is no need to sync
5424 g_context->sync_spte = NULL;
5427 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5428 * L1's nested page tables (e.g. EPT12). The nested translation
5429 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5430 * L2's page tables as the first level of translation and L1's
5431 * nested page tables as the second level of translation. Basically
5432 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5434 if (!is_paging(vcpu))
5435 g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5436 else if (is_long_mode(vcpu))
5437 g_context->gva_to_gpa = paging64_gva_to_gpa;
5438 else if (is_pae(vcpu))
5439 g_context->gva_to_gpa = paging64_gva_to_gpa;
5441 g_context->gva_to_gpa = paging32_gva_to_gpa;
5443 reset_guest_paging_metadata(vcpu, g_context);
5446 void kvm_init_mmu(struct kvm_vcpu *vcpu)
5448 struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5449 union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, ®s);
5451 if (mmu_is_nested(vcpu))
5452 init_kvm_nested_mmu(vcpu, cpu_role);
5453 else if (tdp_enabled)
5454 init_kvm_tdp_mmu(vcpu, cpu_role);
5456 init_kvm_softmmu(vcpu, cpu_role);
5458 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5460 void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
5463 * Invalidate all MMU roles to force them to reinitialize as CPUID
5464 * information is factored into reserved bit calculations.
5466 * Correctly handling multiple vCPU models with respect to paging and
5467 * physical address properties) in a single VM would require tracking
5468 * all relevant CPUID information in kvm_mmu_page_role. That is very
5469 * undesirable as it would increase the memory requirements for
5470 * gfn_track (see struct kvm_mmu_page_role comments). For now that
5471 * problem is swept under the rug; KVM's CPUID API is horrific and
5472 * it's all but impossible to solve it without introducing a new API.
5474 vcpu->arch.root_mmu.root_role.word = 0;
5475 vcpu->arch.guest_mmu.root_role.word = 0;
5476 vcpu->arch.nested_mmu.root_role.word = 0;
5477 vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5478 vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5479 vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
5480 kvm_mmu_reset_context(vcpu);
5483 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5484 * kvm_arch_vcpu_ioctl().
5486 KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm);
5489 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5491 kvm_mmu_unload(vcpu);
5494 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5496 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5500 r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5503 r = mmu_alloc_special_roots(vcpu);
5506 if (vcpu->arch.mmu->root_role.direct)
5507 r = mmu_alloc_direct_roots(vcpu);
5509 r = mmu_alloc_shadow_roots(vcpu);
5513 kvm_mmu_sync_roots(vcpu);
5515 kvm_mmu_load_pgd(vcpu);
5518 * Flush any TLB entries for the new root, the provenance of the root
5519 * is unknown. Even if KVM ensures there are no stale TLB entries
5520 * for a freed root, in theory another hypervisor could have left
5521 * stale entries. Flushing on alloc also allows KVM to skip the TLB
5522 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5524 static_call(kvm_x86_flush_tlb_current)(vcpu);
5529 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5531 struct kvm *kvm = vcpu->kvm;
5533 kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5534 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
5535 kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5536 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
5537 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5540 static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5542 struct kvm_mmu_page *sp;
5544 if (!VALID_PAGE(root_hpa))
5548 * When freeing obsolete roots, treat roots as obsolete if they don't
5549 * have an associated shadow page. This does mean KVM will get false
5550 * positives and free roots that don't strictly need to be freed, but
5551 * such false positives are relatively rare:
5553 * (a) only PAE paging and nested NPT has roots without shadow pages
5554 * (b) remote reloads due to a memslot update obsoletes _all_ roots
5555 * (c) KVM doesn't track previous roots for PAE paging, and the guest
5556 * is unlikely to zap an in-use PGD.
5558 sp = to_shadow_page(root_hpa);
5559 return !sp || is_obsolete_sp(kvm, sp);
5562 static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5564 unsigned long roots_to_free = 0;
5567 if (is_obsolete_root(kvm, mmu->root.hpa))
5568 roots_to_free |= KVM_MMU_ROOT_CURRENT;
5570 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5571 if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5572 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5576 kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5579 void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5581 __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5582 __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5585 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5592 * Assume that the pte write on a page table of the same type
5593 * as the current vcpu paging mode since we update the sptes only
5594 * when they have the same mode.
5596 if (is_pae(vcpu) && *bytes == 4) {
5597 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5602 if (*bytes == 4 || *bytes == 8) {
5603 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5612 * If we're seeing too many writes to a page, it may no longer be a page table,
5613 * or we may be forking, in which case it is better to unmap the page.
5615 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5618 * Skip write-flooding detected for the sp whose level is 1, because
5619 * it can become unsync, then the guest page is not write-protected.
5621 if (sp->role.level == PG_LEVEL_4K)
5624 atomic_inc(&sp->write_flooding_count);
5625 return atomic_read(&sp->write_flooding_count) >= 3;
5629 * Misaligned accesses are too much trouble to fix up; also, they usually
5630 * indicate a page is not used as a page table.
5632 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5635 unsigned offset, pte_size, misaligned;
5637 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5638 gpa, bytes, sp->role.word);
5640 offset = offset_in_page(gpa);
5641 pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5644 * Sometimes, the OS only writes the last one bytes to update status
5645 * bits, for example, in linux, andb instruction is used in clear_bit().
5647 if (!(offset & (pte_size - 1)) && bytes == 1)
5650 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5651 misaligned |= bytes < 4;
5656 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5658 unsigned page_offset, quadrant;
5662 page_offset = offset_in_page(gpa);
5663 level = sp->role.level;
5665 if (sp->role.has_4_byte_gpte) {
5666 page_offset <<= 1; /* 32->64 */
5668 * A 32-bit pde maps 4MB while the shadow pdes map
5669 * only 2MB. So we need to double the offset again
5670 * and zap two pdes instead of one.
5672 if (level == PT32_ROOT_LEVEL) {
5673 page_offset &= ~7; /* kill rounding error */
5677 quadrant = page_offset >> PAGE_SHIFT;
5678 page_offset &= ~PAGE_MASK;
5679 if (quadrant != sp->role.quadrant)
5683 spte = &sp->spt[page_offset / sizeof(*spte)];
5687 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5688 const u8 *new, int bytes,
5689 struct kvm_page_track_notifier_node *node)
5691 gfn_t gfn = gpa >> PAGE_SHIFT;
5692 struct kvm_mmu_page *sp;
5693 LIST_HEAD(invalid_list);
5694 u64 entry, gentry, *spte;
5699 * If we don't have indirect shadow pages, it means no page is
5700 * write-protected, so we can exit simply.
5702 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5705 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5707 write_lock(&vcpu->kvm->mmu_lock);
5709 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5711 ++vcpu->kvm->stat.mmu_pte_write;
5713 for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5714 if (detect_write_misaligned(sp, gpa, bytes) ||
5715 detect_write_flooding(sp)) {
5716 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5717 ++vcpu->kvm->stat.mmu_flooded;
5721 spte = get_written_sptes(sp, gpa, &npte);
5727 mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5728 if (gentry && sp->role.level != PG_LEVEL_4K)
5729 ++vcpu->kvm->stat.mmu_pde_zapped;
5730 if (is_shadow_present_pte(entry))
5735 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5736 write_unlock(&vcpu->kvm->mmu_lock);
5739 int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5740 void *insn, int insn_len)
5742 int r, emulation_type = EMULTYPE_PF;
5743 bool direct = vcpu->arch.mmu->root_role.direct;
5745 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5746 return RET_PF_RETRY;
5749 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5750 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5751 if (r == RET_PF_EMULATE)
5755 if (r == RET_PF_INVALID) {
5756 r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5757 lower_32_bits(error_code), false,
5759 if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
5765 if (r != RET_PF_EMULATE)
5769 * Before emulating the instruction, check if the error code
5770 * was due to a RO violation while translating the guest page.
5771 * This can occur when using nested virtualization with nested
5772 * paging in both guests. If true, we simply unprotect the page
5773 * and resume the guest.
5775 if (vcpu->arch.mmu->root_role.direct &&
5776 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5777 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5782 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5783 * optimistically try to just unprotect the page and let the processor
5784 * re-execute the instruction that caused the page fault. Do not allow
5785 * retrying MMIO emulation, as it's not only pointless but could also
5786 * cause us to enter an infinite loop because the processor will keep
5787 * faulting on the non-existent MMIO address. Retrying an instruction
5788 * from a nested guest is also pointless and dangerous as we are only
5789 * explicitly shadowing L1's page tables, i.e. unprotecting something
5790 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5792 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5793 emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5795 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5798 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5800 static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5801 u64 addr, hpa_t root_hpa)
5803 struct kvm_shadow_walk_iterator iterator;
5805 vcpu_clear_mmio_info(vcpu, addr);
5808 * Walking and synchronizing SPTEs both assume they are operating in
5809 * the context of the current MMU, and would need to be reworked if
5810 * this is ever used to sync the guest_mmu, e.g. to emulate INVEPT.
5812 if (WARN_ON_ONCE(mmu != vcpu->arch.mmu))
5815 if (!VALID_PAGE(root_hpa))
5818 write_lock(&vcpu->kvm->mmu_lock);
5819 for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
5820 struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
5823 int ret = kvm_sync_spte(vcpu, sp, iterator.index);
5826 mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
5828 kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
5831 if (!sp->unsync_children)
5834 write_unlock(&vcpu->kvm->mmu_lock);
5837 void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5838 u64 addr, unsigned long roots)
5842 WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
5844 /* It's actually a GPA for vcpu->arch.guest_mmu. */
5845 if (mmu != &vcpu->arch.guest_mmu) {
5846 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
5847 if (is_noncanonical_address(addr, vcpu))
5850 static_call(kvm_x86_flush_tlb_gva)(vcpu, addr);
5853 if (!mmu->sync_spte)
5856 if (roots & KVM_MMU_ROOT_CURRENT)
5857 __kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
5859 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5860 if (roots & KVM_MMU_ROOT_PREVIOUS(i))
5861 __kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
5864 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
5866 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5869 * INVLPG is required to invalidate any global mappings for the VA,
5870 * irrespective of PCID. Blindly sync all roots as it would take
5871 * roughly the same amount of work/time to determine whether any of the
5872 * previous roots have a global mapping.
5874 * Mappings not reachable via the current or previous cached roots will
5875 * be synced when switching to that new cr3, so nothing needs to be
5876 * done here for them.
5878 kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
5879 ++vcpu->stat.invlpg;
5881 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5884 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5886 struct kvm_mmu *mmu = vcpu->arch.mmu;
5887 unsigned long roots = 0;
5890 if (pcid == kvm_get_active_pcid(vcpu))
5891 roots |= KVM_MMU_ROOT_CURRENT;
5893 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5894 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5895 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
5896 roots |= KVM_MMU_ROOT_PREVIOUS(i);
5900 kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
5901 ++vcpu->stat.invlpg;
5904 * Mappings not reachable via the current cr3 or the prev_roots will be
5905 * synced when switching to that cr3, so nothing needs to be done here
5910 void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5911 int tdp_max_root_level, int tdp_huge_page_level)
5913 tdp_enabled = enable_tdp;
5914 tdp_root_level = tdp_forced_root_level;
5915 max_tdp_level = tdp_max_root_level;
5917 #ifdef CONFIG_X86_64
5918 tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
5921 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5922 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5923 * the kernel is not. But, KVM never creates a page size greater than
5924 * what is used by the kernel for any given HVA, i.e. the kernel's
5925 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5928 max_huge_page_level = tdp_huge_page_level;
5929 else if (boot_cpu_has(X86_FEATURE_GBPAGES))
5930 max_huge_page_level = PG_LEVEL_1G;
5932 max_huge_page_level = PG_LEVEL_2M;
5934 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5936 /* The return value indicates if tlb flush on all vcpus is needed. */
5937 typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
5938 struct kvm_rmap_head *rmap_head,
5939 const struct kvm_memory_slot *slot);
5941 static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
5942 const struct kvm_memory_slot *slot,
5943 slot_rmaps_handler fn,
5944 int start_level, int end_level,
5945 gfn_t start_gfn, gfn_t end_gfn,
5946 bool flush_on_yield, bool flush)
5948 struct slot_rmap_walk_iterator iterator;
5950 lockdep_assert_held_write(&kvm->mmu_lock);
5952 for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
5953 end_gfn, &iterator) {
5955 flush |= fn(kvm, iterator.rmap, slot);
5957 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5958 if (flush && flush_on_yield) {
5959 kvm_flush_remote_tlbs_range(kvm, start_gfn,
5960 iterator.gfn - start_gfn + 1);
5963 cond_resched_rwlock_write(&kvm->mmu_lock);
5970 static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
5971 const struct kvm_memory_slot *slot,
5972 slot_rmaps_handler fn,
5973 int start_level, int end_level,
5974 bool flush_on_yield)
5976 return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
5977 slot->base_gfn, slot->base_gfn + slot->npages - 1,
5978 flush_on_yield, false);
5981 static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
5982 const struct kvm_memory_slot *slot,
5983 slot_rmaps_handler fn,
5984 bool flush_on_yield)
5986 return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
5989 static void free_mmu_pages(struct kvm_mmu *mmu)
5991 if (!tdp_enabled && mmu->pae_root)
5992 set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5993 free_page((unsigned long)mmu->pae_root);
5994 free_page((unsigned long)mmu->pml4_root);
5995 free_page((unsigned long)mmu->pml5_root);
5998 static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6003 mmu->root.hpa = INVALID_PAGE;
6005 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
6006 mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
6008 /* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
6009 if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
6013 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
6014 * while the PDP table is a per-vCPU construct that's allocated at MMU
6015 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
6016 * x86_64. Therefore we need to allocate the PDP table in the first
6017 * 4GB of memory, which happens to fit the DMA32 zone. TDP paging
6018 * generally doesn't use PAE paging and can skip allocating the PDP
6019 * table. The main exception, handled here, is SVM's 32-bit NPT. The
6020 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
6021 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
6023 if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
6026 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
6030 mmu->pae_root = page_address(page);
6033 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
6034 * get the CPU to treat the PDPTEs as encrypted. Decrypt the page so
6035 * that KVM's writes and the CPU's reads get along. Note, this is
6036 * only necessary when using shadow paging, as 64-bit NPT can get at
6037 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
6038 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
6041 set_memory_decrypted((unsigned long)mmu->pae_root, 1);
6043 WARN_ON_ONCE(shadow_me_value);
6045 for (i = 0; i < 4; ++i)
6046 mmu->pae_root[i] = INVALID_PAE_ROOT;
6051 int kvm_mmu_create(struct kvm_vcpu *vcpu)
6055 vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
6056 vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
6058 vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
6059 vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
6061 vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
6063 vcpu->arch.mmu = &vcpu->arch.root_mmu;
6064 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6066 ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6070 ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6072 goto fail_allocate_root;
6076 free_mmu_pages(&vcpu->arch.guest_mmu);
6080 #define BATCH_ZAP_PAGES 10
6081 static void kvm_zap_obsolete_pages(struct kvm *kvm)
6083 struct kvm_mmu_page *sp, *node;
6084 int nr_zapped, batch = 0;
6088 list_for_each_entry_safe_reverse(sp, node,
6089 &kvm->arch.active_mmu_pages, link) {
6091 * No obsolete valid page exists before a newly created page
6092 * since active_mmu_pages is a FIFO list.
6094 if (!is_obsolete_sp(kvm, sp))
6098 * Invalid pages should never land back on the list of active
6099 * pages. Skip the bogus page, otherwise we'll get stuck in an
6100 * infinite loop if the page gets put back on the list (again).
6102 if (WARN_ON(sp->role.invalid))
6106 * No need to flush the TLB since we're only zapping shadow
6107 * pages with an obsolete generation number and all vCPUS have
6108 * loaded a new root, i.e. the shadow pages being zapped cannot
6109 * be in active use by the guest.
6111 if (batch >= BATCH_ZAP_PAGES &&
6112 cond_resched_rwlock_write(&kvm->mmu_lock)) {
6117 unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6118 &kvm->arch.zapped_obsolete_pages, &nr_zapped);
6126 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
6127 * to ensure KVM is not in the middle of a lockless shadow page table
6128 * walk, which may reference the pages. The remote TLB flush itself is
6129 * not required and is simply a convenient way to kick vCPUs as needed.
6130 * KVM performs a local TLB flush when allocating a new root (see
6131 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
6132 * running with an obsolete MMU.
6134 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6138 * Fast invalidate all shadow pages and use lock-break technique
6139 * to zap obsolete pages.
6141 * It's required when memslot is being deleted or VM is being
6142 * destroyed, in these cases, we should ensure that KVM MMU does
6143 * not use any resource of the being-deleted slot or all slots
6144 * after calling the function.
6146 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6148 lockdep_assert_held(&kvm->slots_lock);
6150 write_lock(&kvm->mmu_lock);
6151 trace_kvm_mmu_zap_all_fast(kvm);
6154 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
6155 * held for the entire duration of zapping obsolete pages, it's
6156 * impossible for there to be multiple invalid generations associated
6157 * with *valid* shadow pages at any given time, i.e. there is exactly
6158 * one valid generation and (at most) one invalid generation.
6160 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6163 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
6164 * invalidating TDP MMU roots must be done while holding mmu_lock for
6165 * write and in the same critical section as making the reload request,
6166 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6168 if (tdp_mmu_enabled)
6169 kvm_tdp_mmu_invalidate_all_roots(kvm);
6172 * Notify all vcpus to reload its shadow page table and flush TLB.
6173 * Then all vcpus will switch to new shadow page table with the new
6176 * Note: we need to do this under the protection of mmu_lock,
6177 * otherwise, vcpu would purge shadow page but miss tlb flush.
6179 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6181 kvm_zap_obsolete_pages(kvm);
6183 write_unlock(&kvm->mmu_lock);
6186 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6187 * returning to the caller, e.g. if the zap is in response to a memslot
6188 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6189 * associated with the deleted memslot once the update completes, and
6190 * Deferring the zap until the final reference to the root is put would
6191 * lead to use-after-free.
6193 if (tdp_mmu_enabled)
6194 kvm_tdp_mmu_zap_invalidated_roots(kvm);
6197 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6199 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6202 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
6203 struct kvm_memory_slot *slot,
6204 struct kvm_page_track_notifier_node *node)
6206 kvm_mmu_zap_all_fast(kvm);
6209 int kvm_mmu_init_vm(struct kvm *kvm)
6211 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6214 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6215 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
6216 INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6217 spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6219 if (tdp_mmu_enabled) {
6220 r = kvm_mmu_init_tdp_mmu(kvm);
6225 node->track_write = kvm_mmu_pte_write;
6226 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
6227 kvm_page_track_register_notifier(kvm, node);
6229 kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6230 kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6232 kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6234 kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6235 kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6240 static void mmu_free_vm_memory_caches(struct kvm *kvm)
6242 kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6243 kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6244 kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6247 void kvm_mmu_uninit_vm(struct kvm *kvm)
6249 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6251 kvm_page_track_unregister_notifier(kvm, node);
6253 if (tdp_mmu_enabled)
6254 kvm_mmu_uninit_tdp_mmu(kvm);
6256 mmu_free_vm_memory_caches(kvm);
6259 static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6261 const struct kvm_memory_slot *memslot;
6262 struct kvm_memslots *slots;
6263 struct kvm_memslot_iter iter;
6268 if (!kvm_memslots_have_rmaps(kvm))
6271 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6272 slots = __kvm_memslots(kvm, i);
6274 kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6275 memslot = iter.slot;
6276 start = max(gfn_start, memslot->base_gfn);
6277 end = min(gfn_end, memslot->base_gfn + memslot->npages);
6278 if (WARN_ON_ONCE(start >= end))
6281 flush = __walk_slot_rmaps(kvm, memslot, __kvm_zap_rmap,
6282 PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
6283 start, end - 1, true, flush);
6291 * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
6292 * (not including it)
6294 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6299 if (WARN_ON_ONCE(gfn_end <= gfn_start))
6302 write_lock(&kvm->mmu_lock);
6304 kvm_mmu_invalidate_begin(kvm, 0, -1ul);
6306 flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
6308 if (tdp_mmu_enabled) {
6309 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
6310 flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
6311 gfn_end, true, flush);
6315 kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
6317 kvm_mmu_invalidate_end(kvm, 0, -1ul);
6319 write_unlock(&kvm->mmu_lock);
6322 static bool slot_rmap_write_protect(struct kvm *kvm,
6323 struct kvm_rmap_head *rmap_head,
6324 const struct kvm_memory_slot *slot)
6326 return rmap_write_protect(rmap_head, false);
6329 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6330 const struct kvm_memory_slot *memslot,
6333 if (kvm_memslots_have_rmaps(kvm)) {
6334 write_lock(&kvm->mmu_lock);
6335 walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6336 start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6337 write_unlock(&kvm->mmu_lock);
6340 if (tdp_mmu_enabled) {
6341 read_lock(&kvm->mmu_lock);
6342 kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
6343 read_unlock(&kvm->mmu_lock);
6347 static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6349 return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6352 static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6354 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6358 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6359 * to split a single huge page. Calculating how many are actually needed
6360 * is possible but not worth the complexity.
6362 return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6363 need_topup(&kvm->arch.split_page_header_cache, 1) ||
6364 need_topup(&kvm->arch.split_shadow_page_cache, 1);
6367 static int topup_split_caches(struct kvm *kvm)
6370 * Allocating rmap list entries when splitting huge pages for nested
6371 * MMUs is uncommon as KVM needs to use a list if and only if there is
6372 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6373 * aliased by multiple L2 gfns and/or from multiple nested roots with
6374 * different roles. Aliasing gfns when using TDP is atypical for VMMs;
6375 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6376 * but aliasing rarely occurs post-boot or for many gfns. If there is
6377 * only one rmap entry, rmap->val points directly at that one entry and
6378 * doesn't need to allocate a list. Buffer the cache by the default
6379 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6380 * encounters an aliased gfn or two.
6382 const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6383 KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6386 lockdep_assert_held(&kvm->slots_lock);
6388 r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6389 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6393 r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6397 return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6400 static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6402 struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6403 struct shadow_page_caches caches = {};
6404 union kvm_mmu_page_role role;
6405 unsigned int access;
6408 gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6409 access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6412 * Note, huge page splitting always uses direct shadow pages, regardless
6413 * of whether the huge page itself is mapped by a direct or indirect
6414 * shadow page, since the huge page region itself is being directly
6415 * mapped with smaller pages.
6417 role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6419 /* Direct SPs do not require a shadowed_info_cache. */
6420 caches.page_header_cache = &kvm->arch.split_page_header_cache;
6421 caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6423 /* Safe to pass NULL for vCPU since requesting a direct SP. */
6424 return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6427 static void shadow_mmu_split_huge_page(struct kvm *kvm,
6428 const struct kvm_memory_slot *slot,
6432 struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6433 u64 huge_spte = READ_ONCE(*huge_sptep);
6434 struct kvm_mmu_page *sp;
6440 sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6442 for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6443 sptep = &sp->spt[index];
6444 gfn = kvm_mmu_page_get_gfn(sp, index);
6447 * The SP may already have populated SPTEs, e.g. if this huge
6448 * page is aliased by multiple sptes with the same access
6449 * permissions. These entries are guaranteed to map the same
6450 * gfn-to-pfn translation since the SP is direct, so no need to
6453 * However, if a given SPTE points to a lower level page table,
6454 * that lower level page table may only be partially populated.
6455 * Installing such SPTEs would effectively unmap a potion of the
6456 * huge page. Unmapping guest memory always requires a TLB flush
6457 * since a subsequent operation on the unmapped regions would
6458 * fail to detect the need to flush.
6460 if (is_shadow_present_pte(*sptep)) {
6461 flush |= !is_last_spte(*sptep, sp->role.level);
6465 spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6466 mmu_spte_set(sptep, spte);
6467 __rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6470 __link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6473 static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6474 const struct kvm_memory_slot *slot,
6477 struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6482 /* Grab information for the tracepoint before dropping the MMU lock. */
6483 gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6484 level = huge_sp->role.level;
6487 if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6492 if (need_topup_split_caches_or_resched(kvm)) {
6493 write_unlock(&kvm->mmu_lock);
6496 * If the topup succeeds, return -EAGAIN to indicate that the
6497 * rmap iterator should be restarted because the MMU lock was
6500 r = topup_split_caches(kvm) ?: -EAGAIN;
6501 write_lock(&kvm->mmu_lock);
6505 shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6508 trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6512 static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6513 struct kvm_rmap_head *rmap_head,
6514 const struct kvm_memory_slot *slot)
6516 struct rmap_iterator iter;
6517 struct kvm_mmu_page *sp;
6522 for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6523 sp = sptep_to_sp(huge_sptep);
6525 /* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6526 if (WARN_ON_ONCE(!sp->role.guest_mode))
6529 /* The rmaps should never contain non-leaf SPTEs. */
6530 if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6533 /* SPs with level >PG_LEVEL_4K should never by unsync. */
6534 if (WARN_ON_ONCE(sp->unsync))
6537 /* Don't bother splitting huge pages on invalid SPs. */
6538 if (sp->role.invalid)
6541 r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6544 * The split succeeded or needs to be retried because the MMU
6545 * lock was dropped. Either way, restart the iterator to get it
6546 * back into a consistent state.
6548 if (!r || r == -EAGAIN)
6551 /* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6558 static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6559 const struct kvm_memory_slot *slot,
6560 gfn_t start, gfn_t end,
6566 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6567 * down to the target level. This ensures pages are recursively split
6568 * all the way to the target level. There's no need to split pages
6569 * already at the target level.
6571 for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
6572 __walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
6573 level, level, start, end - 1, true, false);
6576 /* Must be called with the mmu_lock held in write-mode. */
6577 void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6578 const struct kvm_memory_slot *memslot,
6582 if (!tdp_mmu_enabled)
6585 if (kvm_memslots_have_rmaps(kvm))
6586 kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6588 kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6591 * A TLB flush is unnecessary at this point for the same resons as in
6592 * kvm_mmu_slot_try_split_huge_pages().
6596 void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6597 const struct kvm_memory_slot *memslot,
6600 u64 start = memslot->base_gfn;
6601 u64 end = start + memslot->npages;
6603 if (!tdp_mmu_enabled)
6606 if (kvm_memslots_have_rmaps(kvm)) {
6607 write_lock(&kvm->mmu_lock);
6608 kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6609 write_unlock(&kvm->mmu_lock);
6612 read_lock(&kvm->mmu_lock);
6613 kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6614 read_unlock(&kvm->mmu_lock);
6617 * No TLB flush is necessary here. KVM will flush TLBs after
6618 * write-protecting and/or clearing dirty on the newly split SPTEs to
6619 * ensure that guest writes are reflected in the dirty log before the
6620 * ioctl to enable dirty logging on this memslot completes. Since the
6621 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6622 * safe for KVM to decide if a TLB flush is necessary based on the split
6627 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
6628 struct kvm_rmap_head *rmap_head,
6629 const struct kvm_memory_slot *slot)
6632 struct rmap_iterator iter;
6633 int need_tlb_flush = 0;
6634 struct kvm_mmu_page *sp;
6637 for_each_rmap_spte(rmap_head, &iter, sptep) {
6638 sp = sptep_to_sp(sptep);
6641 * We cannot do huge page mapping for indirect shadow pages,
6642 * which are found on the last rmap (level = 1) when not using
6643 * tdp; such shadow pages are synced with the page table in
6644 * the guest, and the guest page table is using 4K page size
6645 * mapping if the indirect sp has level = 1.
6647 if (sp->role.direct &&
6648 sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6650 kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6652 if (kvm_available_flush_remote_tlbs_range())
6653 kvm_flush_remote_tlbs_sptep(kvm, sptep);
6661 return need_tlb_flush;
6664 static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
6665 const struct kvm_memory_slot *slot)
6668 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
6669 * pages that are already mapped at the maximum hugepage level.
6671 if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
6672 PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
6673 kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
6676 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6677 const struct kvm_memory_slot *slot)
6679 if (kvm_memslots_have_rmaps(kvm)) {
6680 write_lock(&kvm->mmu_lock);
6681 kvm_rmap_zap_collapsible_sptes(kvm, slot);
6682 write_unlock(&kvm->mmu_lock);
6685 if (tdp_mmu_enabled) {
6686 read_lock(&kvm->mmu_lock);
6687 kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
6688 read_unlock(&kvm->mmu_lock);
6692 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
6693 const struct kvm_memory_slot *memslot)
6696 * All current use cases for flushing the TLBs for a specific memslot
6697 * related to dirty logging, and many do the TLB flush out of mmu_lock.
6698 * The interaction between the various operations on memslot must be
6699 * serialized by slots_locks to ensure the TLB flush from one operation
6700 * is observed by any other operation on the same memslot.
6702 lockdep_assert_held(&kvm->slots_lock);
6703 kvm_flush_remote_tlbs_range(kvm, memslot->base_gfn, memslot->npages);
6706 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6707 const struct kvm_memory_slot *memslot)
6709 if (kvm_memslots_have_rmaps(kvm)) {
6710 write_lock(&kvm->mmu_lock);
6712 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6713 * support dirty logging at a 4k granularity.
6715 walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
6716 write_unlock(&kvm->mmu_lock);
6719 if (tdp_mmu_enabled) {
6720 read_lock(&kvm->mmu_lock);
6721 kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
6722 read_unlock(&kvm->mmu_lock);
6726 * The caller will flush the TLBs after this function returns.
6728 * It's also safe to flush TLBs out of mmu lock here as currently this
6729 * function is only used for dirty logging, in which case flushing TLB
6730 * out of mmu lock also guarantees no dirty pages will be lost in
6735 void kvm_mmu_zap_all(struct kvm *kvm)
6737 struct kvm_mmu_page *sp, *node;
6738 LIST_HEAD(invalid_list);
6741 write_lock(&kvm->mmu_lock);
6743 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6744 if (WARN_ON(sp->role.invalid))
6746 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6748 if (cond_resched_rwlock_write(&kvm->mmu_lock))
6752 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6754 if (tdp_mmu_enabled)
6755 kvm_tdp_mmu_zap_all(kvm);
6757 write_unlock(&kvm->mmu_lock);
6760 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6762 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6764 gen &= MMIO_SPTE_GEN_MASK;
6767 * Generation numbers are incremented in multiples of the number of
6768 * address spaces in order to provide unique generations across all
6769 * address spaces. Strip what is effectively the address space
6770 * modifier prior to checking for a wrap of the MMIO generation so
6771 * that a wrap in any address space is detected.
6773 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6776 * The very rare case: if the MMIO generation number has wrapped,
6777 * zap all shadow pages.
6779 if (unlikely(gen == 0)) {
6780 kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
6781 kvm_mmu_zap_all_fast(kvm);
6785 static unsigned long mmu_shrink_scan(struct shrinker *shrink,
6786 struct shrink_control *sc)
6789 int nr_to_scan = sc->nr_to_scan;
6790 unsigned long freed = 0;
6792 mutex_lock(&kvm_lock);
6794 list_for_each_entry(kvm, &vm_list, vm_list) {
6796 LIST_HEAD(invalid_list);
6799 * Never scan more than sc->nr_to_scan VM instances.
6800 * Will not hit this condition practically since we do not try
6801 * to shrink more than one VM and it is very unlikely to see
6802 * !n_used_mmu_pages so many times.
6807 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6808 * here. We may skip a VM instance errorneosly, but we do not
6809 * want to shrink a VM that only started to populate its MMU
6812 if (!kvm->arch.n_used_mmu_pages &&
6813 !kvm_has_zapped_obsolete_pages(kvm))
6816 idx = srcu_read_lock(&kvm->srcu);
6817 write_lock(&kvm->mmu_lock);
6819 if (kvm_has_zapped_obsolete_pages(kvm)) {
6820 kvm_mmu_commit_zap_page(kvm,
6821 &kvm->arch.zapped_obsolete_pages);
6825 freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6828 write_unlock(&kvm->mmu_lock);
6829 srcu_read_unlock(&kvm->srcu, idx);
6832 * unfair on small ones
6833 * per-vm shrinkers cry out
6834 * sadness comes quickly
6836 list_move_tail(&kvm->vm_list, &vm_list);
6840 mutex_unlock(&kvm_lock);
6844 static unsigned long mmu_shrink_count(struct shrinker *shrink,
6845 struct shrink_control *sc)
6847 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6850 static struct shrinker mmu_shrinker = {
6851 .count_objects = mmu_shrink_count,
6852 .scan_objects = mmu_shrink_scan,
6853 .seeks = DEFAULT_SEEKS * 10,
6856 static void mmu_destroy_caches(void)
6858 kmem_cache_destroy(pte_list_desc_cache);
6859 kmem_cache_destroy(mmu_page_header_cache);
6862 static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp)
6864 if (nx_hugepage_mitigation_hard_disabled)
6865 return sprintf(buffer, "never\n");
6867 return param_get_bool(buffer, kp);
6870 static bool get_nx_auto_mode(void)
6872 /* Return true when CPU has the bug, and mitigations are ON */
6873 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6876 static void __set_nx_huge_pages(bool val)
6878 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6881 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6883 bool old_val = nx_huge_pages;
6886 if (nx_hugepage_mitigation_hard_disabled)
6889 /* In "auto" mode deploy workaround only if CPU has the bug. */
6890 if (sysfs_streq(val, "off")) {
6892 } else if (sysfs_streq(val, "force")) {
6894 } else if (sysfs_streq(val, "auto")) {
6895 new_val = get_nx_auto_mode();
6896 } else if (sysfs_streq(val, "never")) {
6899 mutex_lock(&kvm_lock);
6900 if (!list_empty(&vm_list)) {
6901 mutex_unlock(&kvm_lock);
6904 nx_hugepage_mitigation_hard_disabled = true;
6905 mutex_unlock(&kvm_lock);
6906 } else if (kstrtobool(val, &new_val) < 0) {
6910 __set_nx_huge_pages(new_val);
6912 if (new_val != old_val) {
6915 mutex_lock(&kvm_lock);
6917 list_for_each_entry(kvm, &vm_list, vm_list) {
6918 mutex_lock(&kvm->slots_lock);
6919 kvm_mmu_zap_all_fast(kvm);
6920 mutex_unlock(&kvm->slots_lock);
6922 wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6924 mutex_unlock(&kvm_lock);
6931 * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
6932 * its default value of -1 is technically undefined behavior for a boolean.
6933 * Forward the module init call to SPTE code so that it too can handle module
6934 * params that need to be resolved/snapshot.
6936 void __init kvm_mmu_x86_module_init(void)
6938 if (nx_huge_pages == -1)
6939 __set_nx_huge_pages(get_nx_auto_mode());
6942 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
6943 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
6944 * when the vendor module is loaded.
6946 tdp_mmu_allowed = tdp_mmu_enabled;
6948 kvm_mmu_spte_module_init();
6952 * The bulk of the MMU initialization is deferred until the vendor module is
6953 * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
6954 * to be reset when a potentially different vendor module is loaded.
6956 int kvm_mmu_vendor_module_init(void)
6961 * MMU roles use union aliasing which is, generally speaking, an
6962 * undefined behavior. However, we supposedly know how compilers behave
6963 * and the current status quo is unlikely to change. Guardians below are
6964 * supposed to let us know if the assumption becomes false.
6966 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6967 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6968 BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
6970 kvm_mmu_reset_all_pte_masks();
6972 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6973 sizeof(struct pte_list_desc),
6974 0, SLAB_ACCOUNT, NULL);
6975 if (!pte_list_desc_cache)
6978 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6979 sizeof(struct kvm_mmu_page),
6980 0, SLAB_ACCOUNT, NULL);
6981 if (!mmu_page_header_cache)
6984 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6987 ret = register_shrinker(&mmu_shrinker, "x86-mmu");
6994 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6996 mmu_destroy_caches();
7000 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
7002 kvm_mmu_unload(vcpu);
7003 free_mmu_pages(&vcpu->arch.root_mmu);
7004 free_mmu_pages(&vcpu->arch.guest_mmu);
7005 mmu_free_memory_caches(vcpu);
7008 void kvm_mmu_vendor_module_exit(void)
7010 mmu_destroy_caches();
7011 percpu_counter_destroy(&kvm_total_used_mmu_pages);
7012 unregister_shrinker(&mmu_shrinker);
7016 * Calculate the effective recovery period, accounting for '0' meaning "let KVM
7017 * select a halving time of 1 hour". Returns true if recovery is enabled.
7019 static bool calc_nx_huge_pages_recovery_period(uint *period)
7022 * Use READ_ONCE to get the params, this may be called outside of the
7023 * param setters, e.g. by the kthread to compute its next timeout.
7025 bool enabled = READ_ONCE(nx_huge_pages);
7026 uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7028 if (!enabled || !ratio)
7031 *period = READ_ONCE(nx_huge_pages_recovery_period_ms);
7033 /* Make sure the period is not less than one second. */
7034 ratio = min(ratio, 3600u);
7035 *period = 60 * 60 * 1000 / ratio;
7040 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
7042 bool was_recovery_enabled, is_recovery_enabled;
7043 uint old_period, new_period;
7046 if (nx_hugepage_mitigation_hard_disabled)
7049 was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
7051 err = param_set_uint(val, kp);
7055 is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
7057 if (is_recovery_enabled &&
7058 (!was_recovery_enabled || old_period > new_period)) {
7061 mutex_lock(&kvm_lock);
7063 list_for_each_entry(kvm, &vm_list, vm_list)
7064 wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
7066 mutex_unlock(&kvm_lock);
7072 static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7074 unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7075 struct kvm_memory_slot *slot;
7077 struct kvm_mmu_page *sp;
7079 LIST_HEAD(invalid_list);
7083 rcu_idx = srcu_read_lock(&kvm->srcu);
7084 write_lock(&kvm->mmu_lock);
7087 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7088 * be done under RCU protection, because the pages are freed via RCU
7093 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7094 to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
7095 for ( ; to_zap; --to_zap) {
7096 if (list_empty(&kvm->arch.possible_nx_huge_pages))
7100 * We use a separate list instead of just using active_mmu_pages
7101 * because the number of shadow pages that be replaced with an
7102 * NX huge page is expected to be relatively small compared to
7103 * the total number of shadow pages. And because the TDP MMU
7104 * doesn't use active_mmu_pages.
7106 sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7107 struct kvm_mmu_page,
7108 possible_nx_huge_page_link);
7109 WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7110 WARN_ON_ONCE(!sp->role.direct);
7113 * Unaccount and do not attempt to recover any NX Huge Pages
7114 * that are being dirty tracked, as they would just be faulted
7115 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7116 * recovered, along with all the other huge pages in the slot,
7117 * when dirty logging is disabled.
7119 * Since gfn_to_memslot() is relatively expensive, it helps to
7120 * skip it if it the test cannot possibly return true. On the
7121 * other hand, if any memslot has logging enabled, chances are
7122 * good that all of them do, in which case unaccount_nx_huge_page()
7123 * is much cheaper than zapping the page.
7125 * If a memslot update is in progress, reading an incorrect value
7126 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
7127 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
7128 * it is becoming nonzero, the page will be zapped unnecessarily.
7129 * Either way, this only affects efficiency in racy situations,
7130 * and not correctness.
7133 if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7134 struct kvm_memslots *slots;
7136 slots = kvm_memslots_for_spte_role(kvm, sp->role);
7137 slot = __gfn_to_memslot(slots, sp->gfn);
7138 WARN_ON_ONCE(!slot);
7141 if (slot && kvm_slot_dirty_track_enabled(slot))
7142 unaccount_nx_huge_page(kvm, sp);
7143 else if (is_tdp_mmu_page(sp))
7144 flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
7146 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7147 WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7149 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7150 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7153 cond_resched_rwlock_write(&kvm->mmu_lock);
7159 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7163 write_unlock(&kvm->mmu_lock);
7164 srcu_read_unlock(&kvm->srcu, rcu_idx);
7167 static long get_nx_huge_page_recovery_timeout(u64 start_time)
7172 enabled = calc_nx_huge_pages_recovery_period(&period);
7174 return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7175 : MAX_SCHEDULE_TIMEOUT;
7178 static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7181 long remaining_time;
7184 start_time = get_jiffies_64();
7185 remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7187 set_current_state(TASK_INTERRUPTIBLE);
7188 while (!kthread_should_stop() && remaining_time > 0) {
7189 schedule_timeout(remaining_time);
7190 remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7191 set_current_state(TASK_INTERRUPTIBLE);
7194 set_current_state(TASK_RUNNING);
7196 if (kthread_should_stop())
7199 kvm_recover_nx_huge_pages(kvm);
7203 int kvm_mmu_post_init_vm(struct kvm *kvm)
7207 if (nx_hugepage_mitigation_hard_disabled)
7210 err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7211 "kvm-nx-lpage-recovery",
7212 &kvm->arch.nx_huge_page_recovery_thread);
7214 kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7219 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7221 if (kvm->arch.nx_huge_page_recovery_thread)
7222 kthread_stop(kvm->arch.nx_huge_page_recovery_thread);