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 int __read_mostly nx_huge_pages = -1;
62 static uint __read_mostly nx_huge_pages_recovery_period_ms;
63 #ifdef CONFIG_PREEMPT_RT
64 /* Recovery can cause latency spikes, disable it for PREEMPT_RT. */
65 static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
67 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
70 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
71 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
73 static const struct kernel_param_ops nx_huge_pages_ops = {
74 .set = set_nx_huge_pages,
75 .get = param_get_bool,
78 static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
79 .set = set_nx_huge_pages_recovery_param,
80 .get = param_get_uint,
83 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
84 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
85 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
86 &nx_huge_pages_recovery_ratio, 0644);
87 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
88 module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
89 &nx_huge_pages_recovery_period_ms, 0644);
90 __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
92 static bool __read_mostly force_flush_and_sync_on_reuse;
93 module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
96 * When setting this variable to true it enables Two-Dimensional-Paging
97 * where the hardware walks 2 page tables:
98 * 1. the guest-virtual to guest-physical
99 * 2. while doing 1. it walks guest-physical to host-physical
100 * If the hardware supports that we don't need to do shadow paging.
102 bool tdp_enabled = false;
104 static bool __ro_after_init tdp_mmu_allowed;
107 bool __read_mostly tdp_mmu_enabled = true;
108 module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
111 static int max_huge_page_level __read_mostly;
112 static int tdp_root_level __read_mostly;
113 static int max_tdp_level __read_mostly;
117 module_param(dbg, bool, 0644);
120 #define PTE_PREFETCH_NUM 8
122 #include <trace/events/kvm.h>
124 /* make pte_list_desc fit well in cache lines */
125 #define PTE_LIST_EXT 14
128 * struct pte_list_desc is the core data structure used to implement a custom
129 * list for tracking a set of related SPTEs, e.g. all the SPTEs that map a
130 * given GFN when used in the context of rmaps. Using a custom list allows KVM
131 * to optimize for the common case where many GFNs will have at most a handful
132 * of SPTEs pointing at them, i.e. allows packing multiple SPTEs into a small
133 * memory footprint, which in turn improves runtime performance by exploiting
136 * A list is comprised of one or more pte_list_desc objects (descriptors).
137 * Each individual descriptor stores up to PTE_LIST_EXT SPTEs. If a descriptor
138 * is full and a new SPTEs needs to be added, a new descriptor is allocated and
139 * becomes the head of the list. This means that by definitions, all tail
140 * descriptors are full.
142 * Note, the meta data fields are deliberately placed at the start of the
143 * structure to optimize the cacheline layout; accessing the descriptor will
144 * touch only a single cacheline so long as @spte_count<=6 (or if only the
145 * descriptors metadata is accessed).
147 struct pte_list_desc {
148 struct pte_list_desc *more;
149 /* The number of PTEs stored in _this_ descriptor. */
151 /* The number of PTEs stored in all tails of this descriptor. */
153 u64 *sptes[PTE_LIST_EXT];
156 struct kvm_shadow_walk_iterator {
164 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
165 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
167 shadow_walk_okay(&(_walker)); \
168 shadow_walk_next(&(_walker)))
170 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
171 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
172 shadow_walk_okay(&(_walker)); \
173 shadow_walk_next(&(_walker)))
175 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
176 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
177 shadow_walk_okay(&(_walker)) && \
178 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
179 __shadow_walk_next(&(_walker), spte))
181 static struct kmem_cache *pte_list_desc_cache;
182 struct kmem_cache *mmu_page_header_cache;
183 static struct percpu_counter kvm_total_used_mmu_pages;
185 static void mmu_spte_set(u64 *sptep, u64 spte);
187 struct kvm_mmu_role_regs {
188 const unsigned long cr0;
189 const unsigned long cr4;
193 #define CREATE_TRACE_POINTS
194 #include "mmutrace.h"
197 * Yes, lot's of underscores. They're a hint that you probably shouldn't be
198 * reading from the role_regs. Once the root_role is constructed, it becomes
199 * the single source of truth for the MMU's state.
201 #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag) \
202 static inline bool __maybe_unused \
203 ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs) \
205 return !!(regs->reg & flag); \
207 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
208 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
209 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
210 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
211 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
212 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
213 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
214 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
215 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
216 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
219 * The MMU itself (with a valid role) is the single source of truth for the
220 * MMU. Do not use the regs used to build the MMU/role, nor the vCPU. The
221 * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
222 * and the vCPU may be incorrect/irrelevant.
224 #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name) \
225 static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu) \
227 return !!(mmu->cpu_role. base_or_ext . reg##_##name); \
229 BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
230 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pse);
231 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smep);
232 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smap);
233 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pke);
234 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, la57);
235 BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
236 BUILD_MMU_ROLE_ACCESSOR(ext, efer, lma);
238 static inline bool is_cr0_pg(struct kvm_mmu *mmu)
240 return mmu->cpu_role.base.level > 0;
243 static inline bool is_cr4_pae(struct kvm_mmu *mmu)
245 return !mmu->cpu_role.base.has_4_byte_gpte;
248 static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
250 struct kvm_mmu_role_regs regs = {
251 .cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
252 .cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
253 .efer = vcpu->arch.efer,
259 static unsigned long get_guest_cr3(struct kvm_vcpu *vcpu)
261 return kvm_read_cr3(vcpu);
264 static inline unsigned long kvm_mmu_get_guest_pgd(struct kvm_vcpu *vcpu,
267 if (IS_ENABLED(CONFIG_RETPOLINE) && mmu->get_guest_pgd == get_guest_cr3)
268 return kvm_read_cr3(vcpu);
270 return mmu->get_guest_pgd(vcpu);
273 static inline bool kvm_available_flush_remote_tlbs_range(void)
275 return kvm_x86_ops.flush_remote_tlbs_range;
278 void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t start_gfn,
281 int ret = -EOPNOTSUPP;
283 if (kvm_x86_ops.flush_remote_tlbs_range)
284 ret = static_call(kvm_x86_flush_remote_tlbs_range)(kvm, start_gfn,
287 kvm_flush_remote_tlbs(kvm);
290 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
292 /* Flush the range of guest memory mapped by the given SPTE. */
293 static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
295 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
296 gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
298 kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
301 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
304 u64 spte = make_mmio_spte(vcpu, gfn, access);
306 trace_mark_mmio_spte(sptep, gfn, spte);
307 mmu_spte_set(sptep, spte);
310 static gfn_t get_mmio_spte_gfn(u64 spte)
312 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
314 gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
315 & shadow_nonpresent_or_rsvd_mask;
317 return gpa >> PAGE_SHIFT;
320 static unsigned get_mmio_spte_access(u64 spte)
322 return spte & shadow_mmio_access_mask;
325 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
327 u64 kvm_gen, spte_gen, gen;
329 gen = kvm_vcpu_memslots(vcpu)->generation;
330 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
333 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
334 spte_gen = get_mmio_spte_generation(spte);
336 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
337 return likely(kvm_gen == spte_gen);
340 static int is_cpuid_PSE36(void)
346 static void __set_spte(u64 *sptep, u64 spte)
348 WRITE_ONCE(*sptep, spte);
351 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
353 WRITE_ONCE(*sptep, spte);
356 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
358 return xchg(sptep, spte);
361 static u64 __get_spte_lockless(u64 *sptep)
363 return READ_ONCE(*sptep);
374 static void count_spte_clear(u64 *sptep, u64 spte)
376 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
378 if (is_shadow_present_pte(spte))
381 /* Ensure the spte is completely set before we increase the count */
383 sp->clear_spte_count++;
386 static void __set_spte(u64 *sptep, u64 spte)
388 union split_spte *ssptep, sspte;
390 ssptep = (union split_spte *)sptep;
391 sspte = (union split_spte)spte;
393 ssptep->spte_high = sspte.spte_high;
396 * If we map the spte from nonpresent to present, We should store
397 * the high bits firstly, then set present bit, so cpu can not
398 * fetch this spte while we are setting the spte.
402 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
405 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
407 union split_spte *ssptep, sspte;
409 ssptep = (union split_spte *)sptep;
410 sspte = (union split_spte)spte;
412 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
415 * If we map the spte from present to nonpresent, we should clear
416 * present bit firstly to avoid vcpu fetch the old high bits.
420 ssptep->spte_high = sspte.spte_high;
421 count_spte_clear(sptep, spte);
424 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
426 union split_spte *ssptep, sspte, orig;
428 ssptep = (union split_spte *)sptep;
429 sspte = (union split_spte)spte;
431 /* xchg acts as a barrier before the setting of the high bits */
432 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
433 orig.spte_high = ssptep->spte_high;
434 ssptep->spte_high = sspte.spte_high;
435 count_spte_clear(sptep, spte);
441 * The idea using the light way get the spte on x86_32 guest is from
442 * gup_get_pte (mm/gup.c).
444 * An spte tlb flush may be pending, because kvm_set_pte_rmap
445 * coalesces them and we are running out of the MMU lock. Therefore
446 * we need to protect against in-progress updates of the spte.
448 * Reading the spte while an update is in progress may get the old value
449 * for the high part of the spte. The race is fine for a present->non-present
450 * change (because the high part of the spte is ignored for non-present spte),
451 * but for a present->present change we must reread the spte.
453 * All such changes are done in two steps (present->non-present and
454 * non-present->present), hence it is enough to count the number of
455 * present->non-present updates: if it changed while reading the spte,
456 * we might have hit the race. This is done using clear_spte_count.
458 static u64 __get_spte_lockless(u64 *sptep)
460 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
461 union split_spte spte, *orig = (union split_spte *)sptep;
465 count = sp->clear_spte_count;
468 spte.spte_low = orig->spte_low;
471 spte.spte_high = orig->spte_high;
474 if (unlikely(spte.spte_low != orig->spte_low ||
475 count != sp->clear_spte_count))
482 /* Rules for using mmu_spte_set:
483 * Set the sptep from nonpresent to present.
484 * Note: the sptep being assigned *must* be either not present
485 * or in a state where the hardware will not attempt to update
488 static void mmu_spte_set(u64 *sptep, u64 new_spte)
490 WARN_ON(is_shadow_present_pte(*sptep));
491 __set_spte(sptep, new_spte);
495 * Update the SPTE (excluding the PFN), but do not track changes in its
496 * accessed/dirty status.
498 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
500 u64 old_spte = *sptep;
502 WARN_ON(!is_shadow_present_pte(new_spte));
503 check_spte_writable_invariants(new_spte);
505 if (!is_shadow_present_pte(old_spte)) {
506 mmu_spte_set(sptep, new_spte);
510 if (!spte_has_volatile_bits(old_spte))
511 __update_clear_spte_fast(sptep, new_spte);
513 old_spte = __update_clear_spte_slow(sptep, new_spte);
515 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
520 /* Rules for using mmu_spte_update:
521 * Update the state bits, it means the mapped pfn is not changed.
523 * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
524 * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
525 * spte, even though the writable spte might be cached on a CPU's TLB.
527 * Returns true if the TLB needs to be flushed
529 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
532 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
534 if (!is_shadow_present_pte(old_spte))
538 * For the spte updated out of mmu-lock is safe, since
539 * we always atomically update it, see the comments in
540 * spte_has_volatile_bits().
542 if (is_mmu_writable_spte(old_spte) &&
543 !is_writable_pte(new_spte))
547 * Flush TLB when accessed/dirty states are changed in the page tables,
548 * to guarantee consistency between TLB and page tables.
551 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
553 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
556 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
558 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
565 * Rules for using mmu_spte_clear_track_bits:
566 * It sets the sptep from present to nonpresent, and track the
567 * state bits, it is used to clear the last level sptep.
568 * Returns the old PTE.
570 static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
573 u64 old_spte = *sptep;
574 int level = sptep_to_sp(sptep)->role.level;
577 if (!is_shadow_present_pte(old_spte) ||
578 !spte_has_volatile_bits(old_spte))
579 __update_clear_spte_fast(sptep, 0ull);
581 old_spte = __update_clear_spte_slow(sptep, 0ull);
583 if (!is_shadow_present_pte(old_spte))
586 kvm_update_page_stats(kvm, level, -1);
588 pfn = spte_to_pfn(old_spte);
591 * KVM doesn't hold a reference to any pages mapped into the guest, and
592 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
593 * before they are reclaimed. Sanity check that, if the pfn is backed
594 * by a refcounted page, the refcount is elevated.
596 page = kvm_pfn_to_refcounted_page(pfn);
597 WARN_ON(page && !page_count(page));
599 if (is_accessed_spte(old_spte))
600 kvm_set_pfn_accessed(pfn);
602 if (is_dirty_spte(old_spte))
603 kvm_set_pfn_dirty(pfn);
609 * Rules for using mmu_spte_clear_no_track:
610 * Directly clear spte without caring the state bits of sptep,
611 * it is used to set the upper level spte.
613 static void mmu_spte_clear_no_track(u64 *sptep)
615 __update_clear_spte_fast(sptep, 0ull);
618 static u64 mmu_spte_get_lockless(u64 *sptep)
620 return __get_spte_lockless(sptep);
623 /* Returns the Accessed status of the PTE and resets it at the same time. */
624 static bool mmu_spte_age(u64 *sptep)
626 u64 spte = mmu_spte_get_lockless(sptep);
628 if (!is_accessed_spte(spte))
631 if (spte_ad_enabled(spte)) {
632 clear_bit((ffs(shadow_accessed_mask) - 1),
633 (unsigned long *)sptep);
636 * Capture the dirty status of the page, so that it doesn't get
637 * lost when the SPTE is marked for access tracking.
639 if (is_writable_pte(spte))
640 kvm_set_pfn_dirty(spte_to_pfn(spte));
642 spte = mark_spte_for_access_track(spte);
643 mmu_spte_update_no_track(sptep, spte);
649 static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
651 return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
654 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
656 if (is_tdp_mmu_active(vcpu)) {
657 kvm_tdp_mmu_walk_lockless_begin();
660 * Prevent page table teardown by making any free-er wait during
661 * kvm_flush_remote_tlbs() IPI to all active vcpus.
666 * Make sure a following spte read is not reordered ahead of the write
669 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
673 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
675 if (is_tdp_mmu_active(vcpu)) {
676 kvm_tdp_mmu_walk_lockless_end();
679 * Make sure the write to vcpu->mode is not reordered in front of
680 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
681 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
683 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
688 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
692 /* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
693 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
694 1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
697 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
698 PT64_ROOT_MAX_LEVEL);
701 if (maybe_indirect) {
702 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
703 PT64_ROOT_MAX_LEVEL);
707 return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
708 PT64_ROOT_MAX_LEVEL);
711 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
713 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
714 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
715 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
716 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
719 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
721 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
724 static bool sp_has_gptes(struct kvm_mmu_page *sp);
726 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
728 if (sp->role.passthrough)
731 if (!sp->role.direct)
732 return sp->shadowed_translation[index] >> PAGE_SHIFT;
734 return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
738 * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
739 * that the SPTE itself may have a more constrained access permissions that
740 * what the guest enforces. For example, a guest may create an executable
741 * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
743 static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
745 if (sp_has_gptes(sp))
746 return sp->shadowed_translation[index] & ACC_ALL;
749 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
750 * KVM is not shadowing any guest page tables, so the "guest access
751 * permissions" are just ACC_ALL.
753 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
754 * is shadowing a guest huge page with small pages, the guest access
755 * permissions being shadowed are the access permissions of the huge
758 * In both cases, sp->role.access contains the correct access bits.
760 return sp->role.access;
763 static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
764 gfn_t gfn, unsigned int access)
766 if (sp_has_gptes(sp)) {
767 sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
771 WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
772 "access mismatch under %s page %llx (expected %u, got %u)\n",
773 sp->role.passthrough ? "passthrough" : "direct",
774 sp->gfn, kvm_mmu_page_get_access(sp, index), access);
776 WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
777 "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
778 sp->role.passthrough ? "passthrough" : "direct",
779 sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
782 static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
785 gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
787 kvm_mmu_page_set_translation(sp, index, gfn, access);
791 * Return the pointer to the large page information for a given gfn,
792 * handling slots that are not large page aligned.
794 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
795 const struct kvm_memory_slot *slot, int level)
799 idx = gfn_to_index(gfn, slot->base_gfn, level);
800 return &slot->arch.lpage_info[level - 2][idx];
803 static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
804 gfn_t gfn, int count)
806 struct kvm_lpage_info *linfo;
809 for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
810 linfo = lpage_info_slot(gfn, slot, i);
811 linfo->disallow_lpage += count;
812 WARN_ON(linfo->disallow_lpage < 0);
816 void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
818 update_gfn_disallow_lpage_count(slot, gfn, 1);
821 void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
823 update_gfn_disallow_lpage_count(slot, gfn, -1);
826 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
828 struct kvm_memslots *slots;
829 struct kvm_memory_slot *slot;
832 kvm->arch.indirect_shadow_pages++;
834 slots = kvm_memslots_for_spte_role(kvm, sp->role);
835 slot = __gfn_to_memslot(slots, gfn);
837 /* the non-leaf shadow pages are keeping readonly. */
838 if (sp->role.level > PG_LEVEL_4K)
839 return kvm_slot_page_track_add_page(kvm, slot, gfn,
840 KVM_PAGE_TRACK_WRITE);
842 kvm_mmu_gfn_disallow_lpage(slot, gfn);
844 if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
845 kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
848 void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
851 * If it's possible to replace the shadow page with an NX huge page,
852 * i.e. if the shadow page is the only thing currently preventing KVM
853 * from using a huge page, add the shadow page to the list of "to be
854 * zapped for NX recovery" pages. Note, the shadow page can already be
855 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
856 * links a shadow page at multiple points.
858 if (!list_empty(&sp->possible_nx_huge_page_link))
861 ++kvm->stat.nx_lpage_splits;
862 list_add_tail(&sp->possible_nx_huge_page_link,
863 &kvm->arch.possible_nx_huge_pages);
866 static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
867 bool nx_huge_page_possible)
869 sp->nx_huge_page_disallowed = true;
871 if (nx_huge_page_possible)
872 track_possible_nx_huge_page(kvm, sp);
875 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
877 struct kvm_memslots *slots;
878 struct kvm_memory_slot *slot;
881 kvm->arch.indirect_shadow_pages--;
883 slots = kvm_memslots_for_spte_role(kvm, sp->role);
884 slot = __gfn_to_memslot(slots, gfn);
885 if (sp->role.level > PG_LEVEL_4K)
886 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
887 KVM_PAGE_TRACK_WRITE);
889 kvm_mmu_gfn_allow_lpage(slot, gfn);
892 void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
894 if (list_empty(&sp->possible_nx_huge_page_link))
897 --kvm->stat.nx_lpage_splits;
898 list_del_init(&sp->possible_nx_huge_page_link);
901 static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
903 sp->nx_huge_page_disallowed = false;
905 untrack_possible_nx_huge_page(kvm, sp);
908 static struct kvm_memory_slot *gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu,
912 struct kvm_memory_slot *slot;
914 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
915 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
917 if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
924 * About rmap_head encoding:
926 * If the bit zero of rmap_head->val is clear, then it points to the only spte
927 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
928 * pte_list_desc containing more mappings.
932 * Returns the number of pointers in the rmap chain, not counting the new one.
934 static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
935 struct kvm_rmap_head *rmap_head)
937 struct pte_list_desc *desc;
940 if (!rmap_head->val) {
941 rmap_printk("%p %llx 0->1\n", spte, *spte);
942 rmap_head->val = (unsigned long)spte;
943 } else if (!(rmap_head->val & 1)) {
944 rmap_printk("%p %llx 1->many\n", spte, *spte);
945 desc = kvm_mmu_memory_cache_alloc(cache);
946 desc->sptes[0] = (u64 *)rmap_head->val;
947 desc->sptes[1] = spte;
948 desc->spte_count = 2;
949 desc->tail_count = 0;
950 rmap_head->val = (unsigned long)desc | 1;
953 rmap_printk("%p %llx many->many\n", spte, *spte);
954 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
955 count = desc->tail_count + desc->spte_count;
958 * If the previous head is full, allocate a new head descriptor
959 * as tail descriptors are always kept full.
961 if (desc->spte_count == PTE_LIST_EXT) {
962 desc = kvm_mmu_memory_cache_alloc(cache);
963 desc->more = (struct pte_list_desc *)(rmap_head->val & ~1ul);
964 desc->spte_count = 0;
965 desc->tail_count = count;
966 rmap_head->val = (unsigned long)desc | 1;
968 desc->sptes[desc->spte_count++] = spte;
973 static void pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
974 struct pte_list_desc *desc, int i)
976 struct pte_list_desc *head_desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
977 int j = head_desc->spte_count - 1;
980 * The head descriptor should never be empty. A new head is added only
981 * when adding an entry and the previous head is full, and heads are
982 * removed (this flow) when they become empty.
987 * Replace the to-be-freed SPTE with the last valid entry from the head
988 * descriptor to ensure that tail descriptors are full at all times.
989 * Note, this also means that tail_count is stable for each descriptor.
991 desc->sptes[i] = head_desc->sptes[j];
992 head_desc->sptes[j] = NULL;
993 head_desc->spte_count--;
994 if (head_desc->spte_count)
998 * The head descriptor is empty. If there are no tail descriptors,
999 * nullify the rmap head to mark the list as emtpy, else point the rmap
1000 * head at the next descriptor, i.e. the new head.
1002 if (!head_desc->more)
1005 rmap_head->val = (unsigned long)head_desc->more | 1;
1006 mmu_free_pte_list_desc(head_desc);
1009 static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1011 struct pte_list_desc *desc;
1014 if (!rmap_head->val) {
1015 pr_err("%s: %p 0->BUG\n", __func__, spte);
1017 } else if (!(rmap_head->val & 1)) {
1018 rmap_printk("%p 1->0\n", spte);
1019 if ((u64 *)rmap_head->val != spte) {
1020 pr_err("%s: %p 1->BUG\n", __func__, spte);
1025 rmap_printk("%p many->many\n", spte);
1026 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1028 for (i = 0; i < desc->spte_count; ++i) {
1029 if (desc->sptes[i] == spte) {
1030 pte_list_desc_remove_entry(rmap_head, desc, i);
1036 pr_err("%s: %p many->many\n", __func__, spte);
1041 static void kvm_zap_one_rmap_spte(struct kvm *kvm,
1042 struct kvm_rmap_head *rmap_head, u64 *sptep)
1044 mmu_spte_clear_track_bits(kvm, sptep);
1045 pte_list_remove(sptep, rmap_head);
1048 /* Return true if at least one SPTE was zapped, false otherwise */
1049 static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
1050 struct kvm_rmap_head *rmap_head)
1052 struct pte_list_desc *desc, *next;
1055 if (!rmap_head->val)
1058 if (!(rmap_head->val & 1)) {
1059 mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1063 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1065 for (; desc; desc = next) {
1066 for (i = 0; i < desc->spte_count; i++)
1067 mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1069 mmu_free_pte_list_desc(desc);
1072 /* rmap_head is meaningless now, remember to reset it */
1077 unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
1079 struct pte_list_desc *desc;
1081 if (!rmap_head->val)
1083 else if (!(rmap_head->val & 1))
1086 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1087 return desc->tail_count + desc->spte_count;
1090 static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1091 const struct kvm_memory_slot *slot)
1095 idx = gfn_to_index(gfn, slot->base_gfn, level);
1096 return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1099 static void rmap_remove(struct kvm *kvm, u64 *spte)
1101 struct kvm_memslots *slots;
1102 struct kvm_memory_slot *slot;
1103 struct kvm_mmu_page *sp;
1105 struct kvm_rmap_head *rmap_head;
1107 sp = sptep_to_sp(spte);
1108 gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1111 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
1112 * so we have to determine which memslots to use based on context
1113 * information in sp->role.
1115 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1117 slot = __gfn_to_memslot(slots, gfn);
1118 rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1120 pte_list_remove(spte, rmap_head);
1124 * Used by the following functions to iterate through the sptes linked by a
1125 * rmap. All fields are private and not assumed to be used outside.
1127 struct rmap_iterator {
1128 /* private fields */
1129 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1130 int pos; /* index of the sptep */
1134 * Iteration must be started by this function. This should also be used after
1135 * removing/dropping sptes from the rmap link because in such cases the
1136 * information in the iterator may not be valid.
1138 * Returns sptep if found, NULL otherwise.
1140 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1141 struct rmap_iterator *iter)
1145 if (!rmap_head->val)
1148 if (!(rmap_head->val & 1)) {
1150 sptep = (u64 *)rmap_head->val;
1154 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1156 sptep = iter->desc->sptes[iter->pos];
1158 BUG_ON(!is_shadow_present_pte(*sptep));
1163 * Must be used with a valid iterator: e.g. after rmap_get_first().
1165 * Returns sptep if found, NULL otherwise.
1167 static u64 *rmap_get_next(struct rmap_iterator *iter)
1172 if (iter->pos < PTE_LIST_EXT - 1) {
1174 sptep = iter->desc->sptes[iter->pos];
1179 iter->desc = iter->desc->more;
1183 /* desc->sptes[0] cannot be NULL */
1184 sptep = iter->desc->sptes[iter->pos];
1191 BUG_ON(!is_shadow_present_pte(*sptep));
1195 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1196 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1197 _spte_; _spte_ = rmap_get_next(_iter_))
1199 static void drop_spte(struct kvm *kvm, u64 *sptep)
1201 u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
1203 if (is_shadow_present_pte(old_spte))
1204 rmap_remove(kvm, sptep);
1207 static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1209 struct kvm_mmu_page *sp;
1211 sp = sptep_to_sp(sptep);
1212 WARN_ON(sp->role.level == PG_LEVEL_4K);
1214 drop_spte(kvm, sptep);
1217 kvm_flush_remote_tlbs_sptep(kvm, sptep);
1221 * Write-protect on the specified @sptep, @pt_protect indicates whether
1222 * spte write-protection is caused by protecting shadow page table.
1224 * Note: write protection is difference between dirty logging and spte
1226 * - for dirty logging, the spte can be set to writable at anytime if
1227 * its dirty bitmap is properly set.
1228 * - for spte protection, the spte can be writable only after unsync-ing
1231 * Return true if tlb need be flushed.
1233 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1237 if (!is_writable_pte(spte) &&
1238 !(pt_protect && is_mmu_writable_spte(spte)))
1241 rmap_printk("spte %p %llx\n", sptep, *sptep);
1244 spte &= ~shadow_mmu_writable_mask;
1245 spte = spte & ~PT_WRITABLE_MASK;
1247 return mmu_spte_update(sptep, spte);
1250 static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1254 struct rmap_iterator iter;
1257 for_each_rmap_spte(rmap_head, &iter, sptep)
1258 flush |= spte_write_protect(sptep, pt_protect);
1263 static bool spte_clear_dirty(u64 *sptep)
1267 rmap_printk("spte %p %llx\n", sptep, *sptep);
1269 MMU_WARN_ON(!spte_ad_enabled(spte));
1270 spte &= ~shadow_dirty_mask;
1271 return mmu_spte_update(sptep, spte);
1274 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1276 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1277 (unsigned long *)sptep);
1278 if (was_writable && !spte_ad_enabled(*sptep))
1279 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1281 return was_writable;
1285 * Gets the GFN ready for another round of dirty logging by clearing the
1286 * - D bit on ad-enabled SPTEs, and
1287 * - W bit on ad-disabled SPTEs.
1288 * Returns true iff any D or W bits were cleared.
1290 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1291 const struct kvm_memory_slot *slot)
1294 struct rmap_iterator iter;
1297 for_each_rmap_spte(rmap_head, &iter, sptep)
1298 if (spte_ad_need_write_protect(*sptep))
1299 flush |= spte_wrprot_for_clear_dirty(sptep);
1301 flush |= spte_clear_dirty(sptep);
1307 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1308 * @kvm: kvm instance
1309 * @slot: slot to protect
1310 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1311 * @mask: indicates which pages we should protect
1313 * Used when we do not need to care about huge page mappings.
1315 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1316 struct kvm_memory_slot *slot,
1317 gfn_t gfn_offset, unsigned long mask)
1319 struct kvm_rmap_head *rmap_head;
1321 if (tdp_mmu_enabled)
1322 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1323 slot->base_gfn + gfn_offset, mask, true);
1325 if (!kvm_memslots_have_rmaps(kvm))
1329 rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1331 rmap_write_protect(rmap_head, false);
1333 /* clear the first set bit */
1339 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1340 * protect the page if the D-bit isn't supported.
1341 * @kvm: kvm instance
1342 * @slot: slot to clear D-bit
1343 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1344 * @mask: indicates which pages we should clear D-bit
1346 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1348 static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1349 struct kvm_memory_slot *slot,
1350 gfn_t gfn_offset, unsigned long mask)
1352 struct kvm_rmap_head *rmap_head;
1354 if (tdp_mmu_enabled)
1355 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1356 slot->base_gfn + gfn_offset, mask, false);
1358 if (!kvm_memslots_have_rmaps(kvm))
1362 rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1364 __rmap_clear_dirty(kvm, rmap_head, slot);
1366 /* clear the first set bit */
1372 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1375 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1376 * enable dirty logging for them.
1378 * We need to care about huge page mappings: e.g. during dirty logging we may
1379 * have such mappings.
1381 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1382 struct kvm_memory_slot *slot,
1383 gfn_t gfn_offset, unsigned long mask)
1386 * Huge pages are NOT write protected when we start dirty logging in
1387 * initially-all-set mode; must write protect them here so that they
1388 * are split to 4K on the first write.
1390 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
1391 * of memslot has no such restriction, so the range can cross two large
1394 if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1395 gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
1396 gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
1398 if (READ_ONCE(eager_page_split))
1399 kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1401 kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
1403 /* Cross two large pages? */
1404 if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
1405 ALIGN(end << PAGE_SHIFT, PMD_SIZE))
1406 kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
1410 /* Now handle 4K PTEs. */
1411 if (kvm_x86_ops.cpu_dirty_log_size)
1412 kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1414 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1417 int kvm_cpu_dirty_log_size(void)
1419 return kvm_x86_ops.cpu_dirty_log_size;
1422 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1423 struct kvm_memory_slot *slot, u64 gfn,
1426 struct kvm_rmap_head *rmap_head;
1428 bool write_protected = false;
1430 if (kvm_memslots_have_rmaps(kvm)) {
1431 for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1432 rmap_head = gfn_to_rmap(gfn, i, slot);
1433 write_protected |= rmap_write_protect(rmap_head, true);
1437 if (tdp_mmu_enabled)
1439 kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
1441 return write_protected;
1444 static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1446 struct kvm_memory_slot *slot;
1448 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1449 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1452 static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1453 const struct kvm_memory_slot *slot)
1455 return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1458 static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1459 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1462 return __kvm_zap_rmap(kvm, rmap_head, slot);
1465 static bool kvm_set_pte_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1466 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1470 struct rmap_iterator iter;
1471 bool need_flush = false;
1475 WARN_ON(pte_huge(pte));
1476 new_pfn = pte_pfn(pte);
1479 for_each_rmap_spte(rmap_head, &iter, sptep) {
1480 rmap_printk("spte %p %llx gfn %llx (%d)\n",
1481 sptep, *sptep, gfn, level);
1485 if (pte_write(pte)) {
1486 kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
1489 new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1492 mmu_spte_clear_track_bits(kvm, sptep);
1493 mmu_spte_set(sptep, new_spte);
1497 if (need_flush && kvm_available_flush_remote_tlbs_range()) {
1498 kvm_flush_remote_tlbs_gfn(kvm, gfn, level);
1505 struct slot_rmap_walk_iterator {
1507 const struct kvm_memory_slot *slot;
1513 /* output fields. */
1515 struct kvm_rmap_head *rmap;
1518 /* private field. */
1519 struct kvm_rmap_head *end_rmap;
1522 static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
1525 iterator->level = level;
1526 iterator->gfn = iterator->start_gfn;
1527 iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
1528 iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1531 static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1532 const struct kvm_memory_slot *slot,
1533 int start_level, int end_level,
1534 gfn_t start_gfn, gfn_t end_gfn)
1536 iterator->slot = slot;
1537 iterator->start_level = start_level;
1538 iterator->end_level = end_level;
1539 iterator->start_gfn = start_gfn;
1540 iterator->end_gfn = end_gfn;
1542 rmap_walk_init_level(iterator, iterator->start_level);
1545 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1547 return !!iterator->rmap;
1550 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1552 while (++iterator->rmap <= iterator->end_rmap) {
1553 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1555 if (iterator->rmap->val)
1559 if (++iterator->level > iterator->end_level) {
1560 iterator->rmap = NULL;
1564 rmap_walk_init_level(iterator, iterator->level);
1567 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1568 _start_gfn, _end_gfn, _iter_) \
1569 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1570 _end_level_, _start_gfn, _end_gfn); \
1571 slot_rmap_walk_okay(_iter_); \
1572 slot_rmap_walk_next(_iter_))
1574 typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1575 struct kvm_memory_slot *slot, gfn_t gfn,
1576 int level, pte_t pte);
1578 static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
1579 struct kvm_gfn_range *range,
1580 rmap_handler_t handler)
1582 struct slot_rmap_walk_iterator iterator;
1585 for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
1586 range->start, range->end - 1, &iterator)
1587 ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
1588 iterator.level, range->pte);
1593 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1597 if (kvm_memslots_have_rmaps(kvm))
1598 flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1600 if (tdp_mmu_enabled)
1601 flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1606 bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1610 if (kvm_memslots_have_rmaps(kvm))
1611 flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmap);
1613 if (tdp_mmu_enabled)
1614 flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
1619 static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1620 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1624 struct rmap_iterator iter;
1627 for_each_rmap_spte(rmap_head, &iter, sptep)
1628 young |= mmu_spte_age(sptep);
1633 static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1634 struct kvm_memory_slot *slot, gfn_t gfn,
1635 int level, pte_t unused)
1638 struct rmap_iterator iter;
1640 for_each_rmap_spte(rmap_head, &iter, sptep)
1641 if (is_accessed_spte(*sptep))
1646 #define RMAP_RECYCLE_THRESHOLD 1000
1648 static void __rmap_add(struct kvm *kvm,
1649 struct kvm_mmu_memory_cache *cache,
1650 const struct kvm_memory_slot *slot,
1651 u64 *spte, gfn_t gfn, unsigned int access)
1653 struct kvm_mmu_page *sp;
1654 struct kvm_rmap_head *rmap_head;
1657 sp = sptep_to_sp(spte);
1658 kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
1659 kvm_update_page_stats(kvm, sp->role.level, 1);
1661 rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1662 rmap_count = pte_list_add(cache, spte, rmap_head);
1664 if (rmap_count > kvm->stat.max_mmu_rmap_size)
1665 kvm->stat.max_mmu_rmap_size = rmap_count;
1666 if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
1667 kvm_zap_all_rmap_sptes(kvm, rmap_head);
1668 kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
1672 static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
1673 u64 *spte, gfn_t gfn, unsigned int access)
1675 struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
1677 __rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
1680 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1684 if (kvm_memslots_have_rmaps(kvm))
1685 young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
1687 if (tdp_mmu_enabled)
1688 young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1693 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1697 if (kvm_memslots_have_rmaps(kvm))
1698 young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
1700 if (tdp_mmu_enabled)
1701 young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1707 static int is_empty_shadow_page(u64 *spt)
1712 for (pos = spt, end = pos + SPTE_ENT_PER_PAGE; pos != end; pos++)
1713 if (is_shadow_present_pte(*pos)) {
1714 printk(KERN_ERR "%s: %p %llx\n", __func__,
1723 * This value is the sum of all of the kvm instances's
1724 * kvm->arch.n_used_mmu_pages values. We need a global,
1725 * aggregate version in order to make the slab shrinker
1728 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1730 kvm->arch.n_used_mmu_pages += nr;
1731 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1734 static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1736 kvm_mod_used_mmu_pages(kvm, +1);
1737 kvm_account_pgtable_pages((void *)sp->spt, +1);
1740 static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1742 kvm_mod_used_mmu_pages(kvm, -1);
1743 kvm_account_pgtable_pages((void *)sp->spt, -1);
1746 static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1748 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1749 hlist_del(&sp->hash_link);
1750 list_del(&sp->link);
1751 free_page((unsigned long)sp->spt);
1752 if (!sp->role.direct)
1753 free_page((unsigned long)sp->shadowed_translation);
1754 kmem_cache_free(mmu_page_header_cache, sp);
1757 static unsigned kvm_page_table_hashfn(gfn_t gfn)
1759 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1762 static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1763 struct kvm_mmu_page *sp, u64 *parent_pte)
1768 pte_list_add(cache, parent_pte, &sp->parent_ptes);
1771 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1774 pte_list_remove(parent_pte, &sp->parent_ptes);
1777 static void drop_parent_pte(struct kvm_mmu_page *sp,
1780 mmu_page_remove_parent_pte(sp, parent_pte);
1781 mmu_spte_clear_no_track(parent_pte);
1784 static void mark_unsync(u64 *spte);
1785 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1788 struct rmap_iterator iter;
1790 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1795 static void mark_unsync(u64 *spte)
1797 struct kvm_mmu_page *sp;
1799 sp = sptep_to_sp(spte);
1800 if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1802 if (sp->unsync_children++)
1804 kvm_mmu_mark_parents_unsync(sp);
1807 #define KVM_PAGE_ARRAY_NR 16
1809 struct kvm_mmu_pages {
1810 struct mmu_page_and_offset {
1811 struct kvm_mmu_page *sp;
1813 } page[KVM_PAGE_ARRAY_NR];
1817 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1823 for (i=0; i < pvec->nr; i++)
1824 if (pvec->page[i].sp == sp)
1827 pvec->page[pvec->nr].sp = sp;
1828 pvec->page[pvec->nr].idx = idx;
1830 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1833 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1835 --sp->unsync_children;
1836 WARN_ON((int)sp->unsync_children < 0);
1837 __clear_bit(idx, sp->unsync_child_bitmap);
1840 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1841 struct kvm_mmu_pages *pvec)
1843 int i, ret, nr_unsync_leaf = 0;
1845 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1846 struct kvm_mmu_page *child;
1847 u64 ent = sp->spt[i];
1849 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1850 clear_unsync_child_bit(sp, i);
1854 child = spte_to_child_sp(ent);
1856 if (child->unsync_children) {
1857 if (mmu_pages_add(pvec, child, i))
1860 ret = __mmu_unsync_walk(child, pvec);
1862 clear_unsync_child_bit(sp, i);
1864 } else if (ret > 0) {
1865 nr_unsync_leaf += ret;
1868 } else if (child->unsync) {
1870 if (mmu_pages_add(pvec, child, i))
1873 clear_unsync_child_bit(sp, i);
1876 return nr_unsync_leaf;
1879 #define INVALID_INDEX (-1)
1881 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1882 struct kvm_mmu_pages *pvec)
1885 if (!sp->unsync_children)
1888 mmu_pages_add(pvec, sp, INVALID_INDEX);
1889 return __mmu_unsync_walk(sp, pvec);
1892 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1894 WARN_ON(!sp->unsync);
1895 trace_kvm_mmu_sync_page(sp);
1897 --kvm->stat.mmu_unsync;
1900 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1901 struct list_head *invalid_list);
1902 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1903 struct list_head *invalid_list);
1905 static bool sp_has_gptes(struct kvm_mmu_page *sp)
1907 if (sp->role.direct)
1910 if (sp->role.passthrough)
1916 #define for_each_valid_sp(_kvm, _sp, _list) \
1917 hlist_for_each_entry(_sp, _list, hash_link) \
1918 if (is_obsolete_sp((_kvm), (_sp))) { \
1921 #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn) \
1922 for_each_valid_sp(_kvm, _sp, \
1923 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
1924 if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1926 static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1928 union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
1931 * Ignore various flags when verifying that it's safe to sync a shadow
1932 * page using the current MMU context.
1934 * - level: not part of the overall MMU role and will never match as the MMU's
1935 * level tracks the root level
1936 * - access: updated based on the new guest PTE
1937 * - quadrant: not part of the overall MMU role (similar to level)
1939 const union kvm_mmu_page_role sync_role_ign = {
1947 * Direct pages can never be unsync, and KVM should never attempt to
1948 * sync a shadow page for a different MMU context, e.g. if the role
1949 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
1950 * reserved bits checks will be wrong, etc...
1952 if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
1953 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
1959 static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
1964 return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
1967 static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1972 if (!kvm_sync_page_check(vcpu, sp))
1975 for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
1976 int ret = kvm_sync_spte(vcpu, sp, i);
1984 * Note, any flush is purely for KVM's correctness, e.g. when dropping
1985 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1986 * unmap or dirty logging event doesn't fail to flush. The guest is
1987 * responsible for flushing the TLB to ensure any changes in protection
1988 * bits are recognized, i.e. until the guest flushes or page faults on
1989 * a relevant address, KVM is architecturally allowed to let vCPUs use
1990 * cached translations with the old protection bits.
1995 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1996 struct list_head *invalid_list)
1998 int ret = __kvm_sync_page(vcpu, sp);
2001 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2005 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2006 struct list_head *invalid_list,
2009 if (!remote_flush && list_empty(invalid_list))
2012 if (!list_empty(invalid_list))
2013 kvm_mmu_commit_zap_page(kvm, invalid_list);
2015 kvm_flush_remote_tlbs(kvm);
2019 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2021 if (sp->role.invalid)
2024 /* TDP MMU pages do not use the MMU generation. */
2025 return !is_tdp_mmu_page(sp) &&
2026 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2029 struct mmu_page_path {
2030 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2031 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2034 #define for_each_sp(pvec, sp, parents, i) \
2035 for (i = mmu_pages_first(&pvec, &parents); \
2036 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2037 i = mmu_pages_next(&pvec, &parents, i))
2039 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2040 struct mmu_page_path *parents,
2045 for (n = i+1; n < pvec->nr; n++) {
2046 struct kvm_mmu_page *sp = pvec->page[n].sp;
2047 unsigned idx = pvec->page[n].idx;
2048 int level = sp->role.level;
2050 parents->idx[level-1] = idx;
2051 if (level == PG_LEVEL_4K)
2054 parents->parent[level-2] = sp;
2060 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2061 struct mmu_page_path *parents)
2063 struct kvm_mmu_page *sp;
2069 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2071 sp = pvec->page[0].sp;
2072 level = sp->role.level;
2073 WARN_ON(level == PG_LEVEL_4K);
2075 parents->parent[level-2] = sp;
2077 /* Also set up a sentinel. Further entries in pvec are all
2078 * children of sp, so this element is never overwritten.
2080 parents->parent[level-1] = NULL;
2081 return mmu_pages_next(pvec, parents, 0);
2084 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2086 struct kvm_mmu_page *sp;
2087 unsigned int level = 0;
2090 unsigned int idx = parents->idx[level];
2091 sp = parents->parent[level];
2095 WARN_ON(idx == INVALID_INDEX);
2096 clear_unsync_child_bit(sp, idx);
2098 } while (!sp->unsync_children);
2101 static int mmu_sync_children(struct kvm_vcpu *vcpu,
2102 struct kvm_mmu_page *parent, bool can_yield)
2105 struct kvm_mmu_page *sp;
2106 struct mmu_page_path parents;
2107 struct kvm_mmu_pages pages;
2108 LIST_HEAD(invalid_list);
2111 while (mmu_unsync_walk(parent, &pages)) {
2112 bool protected = false;
2114 for_each_sp(pages, sp, parents, i)
2115 protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2118 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2122 for_each_sp(pages, sp, parents, i) {
2123 kvm_unlink_unsync_page(vcpu->kvm, sp);
2124 flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2125 mmu_pages_clear_parents(&parents);
2127 if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2128 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2130 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2134 cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2139 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2143 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2145 atomic_set(&sp->write_flooding_count, 0);
2148 static void clear_sp_write_flooding_count(u64 *spte)
2150 __clear_sp_write_flooding_count(sptep_to_sp(spte));
2154 * The vCPU is required when finding indirect shadow pages; the shadow
2155 * page may already exist and syncing it needs the vCPU pointer in
2156 * order to read guest page tables. Direct shadow pages are never
2157 * unsync, thus @vcpu can be NULL if @role.direct is true.
2159 static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
2160 struct kvm_vcpu *vcpu,
2162 struct hlist_head *sp_list,
2163 union kvm_mmu_page_role role)
2165 struct kvm_mmu_page *sp;
2168 LIST_HEAD(invalid_list);
2170 for_each_valid_sp(kvm, sp, sp_list) {
2171 if (sp->gfn != gfn) {
2176 if (sp->role.word != role.word) {
2178 * If the guest is creating an upper-level page, zap
2179 * unsync pages for the same gfn. While it's possible
2180 * the guest is using recursive page tables, in all
2181 * likelihood the guest has stopped using the unsync
2182 * page and is installing a completely unrelated page.
2183 * Unsync pages must not be left as is, because the new
2184 * upper-level page will be write-protected.
2186 if (role.level > PG_LEVEL_4K && sp->unsync)
2187 kvm_mmu_prepare_zap_page(kvm, sp,
2192 /* unsync and write-flooding only apply to indirect SPs. */
2193 if (sp->role.direct)
2197 if (KVM_BUG_ON(!vcpu, kvm))
2201 * The page is good, but is stale. kvm_sync_page does
2202 * get the latest guest state, but (unlike mmu_unsync_children)
2203 * it doesn't write-protect the page or mark it synchronized!
2204 * This way the validity of the mapping is ensured, but the
2205 * overhead of write protection is not incurred until the
2206 * guest invalidates the TLB mapping. This allows multiple
2207 * SPs for a single gfn to be unsync.
2209 * If the sync fails, the page is zapped. If so, break
2210 * in order to rebuild it.
2212 ret = kvm_sync_page(vcpu, sp, &invalid_list);
2216 WARN_ON(!list_empty(&invalid_list));
2218 kvm_flush_remote_tlbs(kvm);
2221 __clear_sp_write_flooding_count(sp);
2227 ++kvm->stat.mmu_cache_miss;
2230 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2232 if (collisions > kvm->stat.max_mmu_page_hash_collisions)
2233 kvm->stat.max_mmu_page_hash_collisions = collisions;
2237 /* Caches used when allocating a new shadow page. */
2238 struct shadow_page_caches {
2239 struct kvm_mmu_memory_cache *page_header_cache;
2240 struct kvm_mmu_memory_cache *shadow_page_cache;
2241 struct kvm_mmu_memory_cache *shadowed_info_cache;
2244 static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
2245 struct shadow_page_caches *caches,
2247 struct hlist_head *sp_list,
2248 union kvm_mmu_page_role role)
2250 struct kvm_mmu_page *sp;
2252 sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
2253 sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2255 sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2257 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2259 INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2262 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2263 * depends on valid pages being added to the head of the list. See
2264 * comments in kvm_zap_obsolete_pages().
2266 sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2267 list_add(&sp->link, &kvm->arch.active_mmu_pages);
2268 kvm_account_mmu_page(kvm, sp);
2272 hlist_add_head(&sp->hash_link, sp_list);
2273 if (sp_has_gptes(sp))
2274 account_shadowed(kvm, sp);
2279 /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
2280 static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
2281 struct kvm_vcpu *vcpu,
2282 struct shadow_page_caches *caches,
2284 union kvm_mmu_page_role role)
2286 struct hlist_head *sp_list;
2287 struct kvm_mmu_page *sp;
2288 bool created = false;
2290 sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2292 sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
2295 sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
2298 trace_kvm_mmu_get_page(sp, created);
2302 static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
2304 union kvm_mmu_page_role role)
2306 struct shadow_page_caches caches = {
2307 .page_header_cache = &vcpu->arch.mmu_page_header_cache,
2308 .shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
2309 .shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
2312 return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
2315 static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
2316 unsigned int access)
2318 struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
2319 union kvm_mmu_page_role role;
2321 role = parent_sp->role;
2323 role.access = access;
2324 role.direct = direct;
2325 role.passthrough = 0;
2328 * If the guest has 4-byte PTEs then that means it's using 32-bit,
2329 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
2330 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
2331 * shadow each guest page table with multiple shadow page tables, which
2332 * requires extra bookkeeping in the role.
2334 * Specifically, to shadow the guest's page directory (which covers a
2335 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
2336 * 1GiB of the address space. @role.quadrant encodes which quarter of
2337 * the address space each maps.
2339 * To shadow the guest's page tables (which each map a 4MiB region), KVM
2340 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
2341 * @role.quadrant encodes which half of the region they map.
2343 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
2344 * consumes bits 29:21. To consume bits 31:30, KVM's uses 4 shadow
2345 * PDPTEs; those 4 PAE page directories are pre-allocated and their
2346 * quadrant is assigned in mmu_alloc_root(). A 4-byte PTE consumes
2347 * bits 21:12, while an 8-byte PTE consumes bits 20:12. To consume
2348 * bit 21 in the PTE (the child here), KVM propagates that bit to the
2349 * quadrant, i.e. sets quadrant to '0' or '1'. The parent 8-byte PDE
2350 * covers bit 21 (see above), thus the quadrant is calculated from the
2351 * _least_ significant bit of the PDE index.
2353 if (role.has_4_byte_gpte) {
2354 WARN_ON_ONCE(role.level != PG_LEVEL_4K);
2355 role.quadrant = spte_index(sptep) & 1;
2361 static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
2362 u64 *sptep, gfn_t gfn,
2363 bool direct, unsigned int access)
2365 union kvm_mmu_page_role role;
2367 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
2368 return ERR_PTR(-EEXIST);
2370 role = kvm_mmu_child_role(sptep, direct, access);
2371 return kvm_mmu_get_shadow_page(vcpu, gfn, role);
2374 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2375 struct kvm_vcpu *vcpu, hpa_t root,
2378 iterator->addr = addr;
2379 iterator->shadow_addr = root;
2380 iterator->level = vcpu->arch.mmu->root_role.level;
2382 if (iterator->level >= PT64_ROOT_4LEVEL &&
2383 vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2384 !vcpu->arch.mmu->root_role.direct)
2385 iterator->level = PT32E_ROOT_LEVEL;
2387 if (iterator->level == PT32E_ROOT_LEVEL) {
2389 * prev_root is currently only used for 64-bit hosts. So only
2390 * the active root_hpa is valid here.
2392 BUG_ON(root != vcpu->arch.mmu->root.hpa);
2394 iterator->shadow_addr
2395 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2396 iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2398 if (!iterator->shadow_addr)
2399 iterator->level = 0;
2403 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2404 struct kvm_vcpu *vcpu, u64 addr)
2406 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2410 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2412 if (iterator->level < PG_LEVEL_4K)
2415 iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2416 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2420 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2423 if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2424 iterator->level = 0;
2428 iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2432 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2434 __shadow_walk_next(iterator, *iterator->sptep);
2437 static void __link_shadow_page(struct kvm *kvm,
2438 struct kvm_mmu_memory_cache *cache, u64 *sptep,
2439 struct kvm_mmu_page *sp, bool flush)
2443 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2446 * If an SPTE is present already, it must be a leaf and therefore
2447 * a large one. Drop it, and flush the TLB if needed, before
2450 if (is_shadow_present_pte(*sptep))
2451 drop_large_spte(kvm, sptep, flush);
2453 spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2455 mmu_spte_set(sptep, spte);
2457 mmu_page_add_parent_pte(cache, sp, sptep);
2460 * The non-direct sub-pagetable must be updated before linking. For
2461 * L1 sp, the pagetable is updated via kvm_sync_page() in
2462 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2463 * so sp->unsync can be true or false. For higher level non-direct
2464 * sp, the pagetable is updated/synced via mmu_sync_children() in
2465 * FNAME(fetch)(), so sp->unsync_children can only be false.
2466 * WARN_ON_ONCE() if anything happens unexpectedly.
2468 if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2472 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2473 struct kvm_mmu_page *sp)
2475 __link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
2478 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2479 unsigned direct_access)
2481 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2482 struct kvm_mmu_page *child;
2485 * For the direct sp, if the guest pte's dirty bit
2486 * changed form clean to dirty, it will corrupt the
2487 * sp's access: allow writable in the read-only sp,
2488 * so we should update the spte at this point to get
2489 * a new sp with the correct access.
2491 child = spte_to_child_sp(*sptep);
2492 if (child->role.access == direct_access)
2495 drop_parent_pte(child, sptep);
2496 kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2500 /* Returns the number of zapped non-leaf child shadow pages. */
2501 static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2502 u64 *spte, struct list_head *invalid_list)
2505 struct kvm_mmu_page *child;
2508 if (is_shadow_present_pte(pte)) {
2509 if (is_last_spte(pte, sp->role.level)) {
2510 drop_spte(kvm, spte);
2512 child = spte_to_child_sp(pte);
2513 drop_parent_pte(child, spte);
2516 * Recursively zap nested TDP SPs, parentless SPs are
2517 * unlikely to be used again in the near future. This
2518 * avoids retaining a large number of stale nested SPs.
2520 if (tdp_enabled && invalid_list &&
2521 child->role.guest_mode && !child->parent_ptes.val)
2522 return kvm_mmu_prepare_zap_page(kvm, child,
2525 } else if (is_mmio_spte(pte)) {
2526 mmu_spte_clear_no_track(spte);
2531 static int kvm_mmu_page_unlink_children(struct kvm *kvm,
2532 struct kvm_mmu_page *sp,
2533 struct list_head *invalid_list)
2538 for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
2539 zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
2544 static void kvm_mmu_unlink_parents(struct kvm_mmu_page *sp)
2547 struct rmap_iterator iter;
2549 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2550 drop_parent_pte(sp, sptep);
2553 static int mmu_zap_unsync_children(struct kvm *kvm,
2554 struct kvm_mmu_page *parent,
2555 struct list_head *invalid_list)
2558 struct mmu_page_path parents;
2559 struct kvm_mmu_pages pages;
2561 if (parent->role.level == PG_LEVEL_4K)
2564 while (mmu_unsync_walk(parent, &pages)) {
2565 struct kvm_mmu_page *sp;
2567 for_each_sp(pages, sp, parents, i) {
2568 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2569 mmu_pages_clear_parents(&parents);
2577 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2578 struct kvm_mmu_page *sp,
2579 struct list_head *invalid_list,
2582 bool list_unstable, zapped_root = false;
2584 lockdep_assert_held_write(&kvm->mmu_lock);
2585 trace_kvm_mmu_prepare_zap_page(sp);
2586 ++kvm->stat.mmu_shadow_zapped;
2587 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2588 *nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2589 kvm_mmu_unlink_parents(sp);
2591 /* Zapping children means active_mmu_pages has become unstable. */
2592 list_unstable = *nr_zapped;
2594 if (!sp->role.invalid && sp_has_gptes(sp))
2595 unaccount_shadowed(kvm, sp);
2598 kvm_unlink_unsync_page(kvm, sp);
2599 if (!sp->root_count) {
2604 * Already invalid pages (previously active roots) are not on
2605 * the active page list. See list_del() in the "else" case of
2608 if (sp->role.invalid)
2609 list_add(&sp->link, invalid_list);
2611 list_move(&sp->link, invalid_list);
2612 kvm_unaccount_mmu_page(kvm, sp);
2615 * Remove the active root from the active page list, the root
2616 * will be explicitly freed when the root_count hits zero.
2618 list_del(&sp->link);
2621 * Obsolete pages cannot be used on any vCPUs, see the comment
2622 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2623 * treats invalid shadow pages as being obsolete.
2625 zapped_root = !is_obsolete_sp(kvm, sp);
2628 if (sp->nx_huge_page_disallowed)
2629 unaccount_nx_huge_page(kvm, sp);
2631 sp->role.invalid = 1;
2634 * Make the request to free obsolete roots after marking the root
2635 * invalid, otherwise other vCPUs may not see it as invalid.
2638 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2639 return list_unstable;
2642 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2643 struct list_head *invalid_list)
2647 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2651 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2652 struct list_head *invalid_list)
2654 struct kvm_mmu_page *sp, *nsp;
2656 if (list_empty(invalid_list))
2660 * We need to make sure everyone sees our modifications to
2661 * the page tables and see changes to vcpu->mode here. The barrier
2662 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2663 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2665 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2666 * guest mode and/or lockless shadow page table walks.
2668 kvm_flush_remote_tlbs(kvm);
2670 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2671 WARN_ON(!sp->role.invalid || sp->root_count);
2672 kvm_mmu_free_shadow_page(sp);
2676 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2677 unsigned long nr_to_zap)
2679 unsigned long total_zapped = 0;
2680 struct kvm_mmu_page *sp, *tmp;
2681 LIST_HEAD(invalid_list);
2685 if (list_empty(&kvm->arch.active_mmu_pages))
2689 list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2691 * Don't zap active root pages, the page itself can't be freed
2692 * and zapping it will just force vCPUs to realloc and reload.
2697 unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2699 total_zapped += nr_zapped;
2700 if (total_zapped >= nr_to_zap)
2707 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2709 kvm->stat.mmu_recycled += total_zapped;
2710 return total_zapped;
2713 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2715 if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2716 return kvm->arch.n_max_mmu_pages -
2717 kvm->arch.n_used_mmu_pages;
2722 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2724 unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2726 if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2729 kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2732 * Note, this check is intentionally soft, it only guarantees that one
2733 * page is available, while the caller may end up allocating as many as
2734 * four pages, e.g. for PAE roots or for 5-level paging. Temporarily
2735 * exceeding the (arbitrary by default) limit will not harm the host,
2736 * being too aggressive may unnecessarily kill the guest, and getting an
2737 * exact count is far more trouble than it's worth, especially in the
2740 if (!kvm_mmu_available_pages(vcpu->kvm))
2746 * Changing the number of mmu pages allocated to the vm
2747 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2749 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2751 write_lock(&kvm->mmu_lock);
2753 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2754 kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2757 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2760 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2762 write_unlock(&kvm->mmu_lock);
2765 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2767 struct kvm_mmu_page *sp;
2768 LIST_HEAD(invalid_list);
2771 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2773 write_lock(&kvm->mmu_lock);
2774 for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2775 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2778 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2780 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2781 write_unlock(&kvm->mmu_lock);
2786 static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2791 if (vcpu->arch.mmu->root_role.direct)
2794 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
2796 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2801 static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2803 trace_kvm_mmu_unsync_page(sp);
2804 ++kvm->stat.mmu_unsync;
2807 kvm_mmu_mark_parents_unsync(sp);
2811 * Attempt to unsync any shadow pages that can be reached by the specified gfn,
2812 * KVM is creating a writable mapping for said gfn. Returns 0 if all pages
2813 * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
2814 * be write-protected.
2816 int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
2817 gfn_t gfn, bool can_unsync, bool prefetch)
2819 struct kvm_mmu_page *sp;
2820 bool locked = false;
2823 * Force write-protection if the page is being tracked. Note, the page
2824 * track machinery is used to write-protect upper-level shadow pages,
2825 * i.e. this guards the role.level == 4K assertion below!
2827 if (kvm_slot_page_track_is_active(kvm, slot, gfn, KVM_PAGE_TRACK_WRITE))
2831 * The page is not write-tracked, mark existing shadow pages unsync
2832 * unless KVM is synchronizing an unsync SP (can_unsync = false). In
2833 * that case, KVM must complete emulation of the guest TLB flush before
2834 * allowing shadow pages to become unsync (writable by the guest).
2836 for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2847 * TDP MMU page faults require an additional spinlock as they
2848 * run with mmu_lock held for read, not write, and the unsync
2849 * logic is not thread safe. Take the spinklock regardless of
2850 * the MMU type to avoid extra conditionals/parameters, there's
2851 * no meaningful penalty if mmu_lock is held for write.
2855 spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2858 * Recheck after taking the spinlock, a different vCPU
2859 * may have since marked the page unsync. A false
2860 * positive on the unprotected check above is not
2861 * possible as clearing sp->unsync _must_ hold mmu_lock
2862 * for write, i.e. unsync cannot transition from 0->1
2863 * while this CPU holds mmu_lock for read (or write).
2865 if (READ_ONCE(sp->unsync))
2869 WARN_ON(sp->role.level != PG_LEVEL_4K);
2870 kvm_unsync_page(kvm, sp);
2873 spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2876 * We need to ensure that the marking of unsync pages is visible
2877 * before the SPTE is updated to allow writes because
2878 * kvm_mmu_sync_roots() checks the unsync flags without holding
2879 * the MMU lock and so can race with this. If the SPTE was updated
2880 * before the page had been marked as unsync-ed, something like the
2881 * following could happen:
2884 * ---------------------------------------------------------------------
2885 * 1.2 Host updates SPTE
2887 * 2.1 Guest writes a GPTE for GVA X.
2888 * (GPTE being in the guest page table shadowed
2889 * by the SP from CPU 1.)
2890 * This reads SPTE during the page table walk.
2891 * Since SPTE.W is read as 1, there is no
2894 * 2.2 Guest issues TLB flush.
2895 * That causes a VM Exit.
2897 * 2.3 Walking of unsync pages sees sp->unsync is
2898 * false and skips the page.
2900 * 2.4 Guest accesses GVA X.
2901 * Since the mapping in the SP was not updated,
2902 * so the old mapping for GVA X incorrectly
2906 * (sp->unsync = true)
2908 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2909 * the situation in 2.4 does not arise. It pairs with the read barrier
2910 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2917 static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
2918 u64 *sptep, unsigned int pte_access, gfn_t gfn,
2919 kvm_pfn_t pfn, struct kvm_page_fault *fault)
2921 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2922 int level = sp->role.level;
2923 int was_rmapped = 0;
2924 int ret = RET_PF_FIXED;
2929 /* Prefetching always gets a writable pfn. */
2930 bool host_writable = !fault || fault->map_writable;
2931 bool prefetch = !fault || fault->prefetch;
2932 bool write_fault = fault && fault->write;
2934 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2935 *sptep, write_fault, gfn);
2937 if (unlikely(is_noslot_pfn(pfn))) {
2938 vcpu->stat.pf_mmio_spte_created++;
2939 mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2940 return RET_PF_EMULATE;
2943 if (is_shadow_present_pte(*sptep)) {
2945 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2946 * the parent of the now unreachable PTE.
2948 if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2949 struct kvm_mmu_page *child;
2952 child = spte_to_child_sp(pte);
2953 drop_parent_pte(child, sptep);
2955 } else if (pfn != spte_to_pfn(*sptep)) {
2956 pgprintk("hfn old %llx new %llx\n",
2957 spte_to_pfn(*sptep), pfn);
2958 drop_spte(vcpu->kvm, sptep);
2964 wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
2965 true, host_writable, &spte);
2967 if (*sptep == spte) {
2968 ret = RET_PF_SPURIOUS;
2970 flush |= mmu_spte_update(sptep, spte);
2971 trace_kvm_mmu_set_spte(level, gfn, sptep);
2976 ret = RET_PF_EMULATE;
2980 kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
2982 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2985 WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
2986 rmap_add(vcpu, slot, sptep, gfn, pte_access);
2988 /* Already rmapped but the pte_access bits may have changed. */
2989 kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2995 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2996 struct kvm_mmu_page *sp,
2997 u64 *start, u64 *end)
2999 struct page *pages[PTE_PREFETCH_NUM];
3000 struct kvm_memory_slot *slot;
3001 unsigned int access = sp->role.access;
3005 gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
3006 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3010 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3014 for (i = 0; i < ret; i++, gfn++, start++) {
3015 mmu_set_spte(vcpu, slot, start, access, gfn,
3016 page_to_pfn(pages[i]), NULL);
3023 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3024 struct kvm_mmu_page *sp, u64 *sptep)
3026 u64 *spte, *start = NULL;
3029 WARN_ON(!sp->role.direct);
3031 i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
3034 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3035 if (is_shadow_present_pte(*spte) || spte == sptep) {
3038 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3045 direct_pte_prefetch_many(vcpu, sp, start, spte);
3048 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3050 struct kvm_mmu_page *sp;
3052 sp = sptep_to_sp(sptep);
3055 * Without accessed bits, there's no way to distinguish between
3056 * actually accessed translations and prefetched, so disable pte
3057 * prefetch if accessed bits aren't available.
3059 if (sp_ad_disabled(sp))
3062 if (sp->role.level > PG_LEVEL_4K)
3066 * If addresses are being invalidated, skip prefetching to avoid
3067 * accidentally prefetching those addresses.
3069 if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
3072 __direct_pte_prefetch(vcpu, sp, sptep);
3076 * Lookup the mapping level for @gfn in the current mm.
3078 * WARNING! Use of host_pfn_mapping_level() requires the caller and the end
3079 * consumer to be tied into KVM's handlers for MMU notifier events!
3081 * There are several ways to safely use this helper:
3083 * - Check mmu_invalidate_retry_hva() after grabbing the mapping level, before
3084 * consuming it. In this case, mmu_lock doesn't need to be held during the
3085 * lookup, but it does need to be held while checking the MMU notifier.
3087 * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
3088 * event for the hva. This can be done by explicit checking the MMU notifier
3089 * or by ensuring that KVM already has a valid mapping that covers the hva.
3091 * - Do not use the result to install new mappings, e.g. use the host mapping
3092 * level only to decide whether or not to zap an entry. In this case, it's
3093 * not required to hold mmu_lock (though it's highly likely the caller will
3094 * want to hold mmu_lock anyways, e.g. to modify SPTEs).
3096 * Note! The lookup can still race with modifications to host page tables, but
3097 * the above "rules" ensure KVM will not _consume_ the result of the walk if a
3098 * race with the primary MMU occurs.
3100 static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
3101 const struct kvm_memory_slot *slot)
3103 int level = PG_LEVEL_4K;
3105 unsigned long flags;
3112 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3113 * is not solely for performance, it's also necessary to avoid the
3114 * "writable" check in __gfn_to_hva_many(), which will always fail on
3115 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
3116 * page fault steps have already verified the guest isn't writing a
3117 * read-only memslot.
3119 hva = __gfn_to_hva_memslot(slot, gfn);
3122 * Disable IRQs to prevent concurrent tear down of host page tables,
3123 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
3124 * the original page table.
3126 local_irq_save(flags);
3129 * Read each entry once. As above, a non-leaf entry can be promoted to
3130 * a huge page _during_ this walk. Re-reading the entry could send the
3131 * walk into the weeks, e.g. p*d_large() returns false (sees the old
3132 * value) and then p*d_offset() walks into the target huge page instead
3133 * of the old page table (sees the new value).
3135 pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
3139 p4d = READ_ONCE(*p4d_offset(&pgd, hva));
3140 if (p4d_none(p4d) || !p4d_present(p4d))
3143 pud = READ_ONCE(*pud_offset(&p4d, hva));
3144 if (pud_none(pud) || !pud_present(pud))
3147 if (pud_large(pud)) {
3148 level = PG_LEVEL_1G;
3152 pmd = READ_ONCE(*pmd_offset(&pud, hva));
3153 if (pmd_none(pmd) || !pmd_present(pmd))
3157 level = PG_LEVEL_2M;
3160 local_irq_restore(flags);
3164 int kvm_mmu_max_mapping_level(struct kvm *kvm,
3165 const struct kvm_memory_slot *slot, gfn_t gfn,
3168 struct kvm_lpage_info *linfo;
3171 max_level = min(max_level, max_huge_page_level);
3172 for ( ; max_level > PG_LEVEL_4K; max_level--) {
3173 linfo = lpage_info_slot(gfn, slot, max_level);
3174 if (!linfo->disallow_lpage)
3178 if (max_level == PG_LEVEL_4K)
3181 host_level = host_pfn_mapping_level(kvm, gfn, slot);
3182 return min(host_level, max_level);
3185 void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3187 struct kvm_memory_slot *slot = fault->slot;
3190 fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
3192 if (unlikely(fault->max_level == PG_LEVEL_4K))
3195 if (is_error_noslot_pfn(fault->pfn))
3198 if (kvm_slot_dirty_track_enabled(slot))
3202 * Enforce the iTLB multihit workaround after capturing the requested
3203 * level, which will be used to do precise, accurate accounting.
3205 fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3206 fault->gfn, fault->max_level);
3207 if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
3211 * mmu_invalidate_retry() was successful and mmu_lock is held, so
3212 * the pmd can't be split from under us.
3214 fault->goal_level = fault->req_level;
3215 mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
3216 VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
3217 fault->pfn &= ~mask;
3220 void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3222 if (cur_level > PG_LEVEL_4K &&
3223 cur_level == fault->goal_level &&
3224 is_shadow_present_pte(spte) &&
3225 !is_large_pte(spte) &&
3226 spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3228 * A small SPTE exists for this pfn, but FNAME(fetch),
3229 * direct_map(), or kvm_tdp_mmu_map() would like to create a
3230 * large PTE instead: just force them to go down another level,
3231 * patching back for them into pfn the next 9 bits of the
3234 u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3235 KVM_PAGES_PER_HPAGE(cur_level - 1);
3236 fault->pfn |= fault->gfn & page_mask;
3237 fault->goal_level--;
3241 static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3243 struct kvm_shadow_walk_iterator it;
3244 struct kvm_mmu_page *sp;
3246 gfn_t base_gfn = fault->gfn;
3248 kvm_mmu_hugepage_adjust(vcpu, fault);
3250 trace_kvm_mmu_spte_requested(fault);
3251 for_each_shadow_entry(vcpu, fault->addr, it) {
3253 * We cannot overwrite existing page tables with an NX
3254 * large page, as the leaf could be executable.
3256 if (fault->nx_huge_page_workaround_enabled)
3257 disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3259 base_gfn = gfn_round_for_level(fault->gfn, it.level);
3260 if (it.level == fault->goal_level)
3263 sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
3264 if (sp == ERR_PTR(-EEXIST))
3267 link_shadow_page(vcpu, it.sptep, sp);
3268 if (fault->huge_page_disallowed)
3269 account_nx_huge_page(vcpu->kvm, sp,
3270 fault->req_level >= it.level);
3273 if (WARN_ON_ONCE(it.level != fault->goal_level))
3276 ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3277 base_gfn, fault->pfn, fault);
3278 if (ret == RET_PF_SPURIOUS)
3281 direct_pte_prefetch(vcpu, it.sptep);
3285 static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3287 unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3289 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3292 static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3294 if (is_sigpending_pfn(fault->pfn)) {
3295 kvm_handle_signal_exit(vcpu);
3300 * Do not cache the mmio info caused by writing the readonly gfn
3301 * into the spte otherwise read access on readonly gfn also can
3302 * caused mmio page fault and treat it as mmio access.
3304 if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3305 return RET_PF_EMULATE;
3307 if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3308 kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3309 return RET_PF_RETRY;
3315 static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3316 struct kvm_page_fault *fault,
3317 unsigned int access)
3319 gva_t gva = fault->is_tdp ? 0 : fault->addr;
3321 vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3322 access & shadow_mmio_access_mask);
3325 * If MMIO caching is disabled, emulate immediately without
3326 * touching the shadow page tables as attempting to install an
3327 * MMIO SPTE will just be an expensive nop.
3329 if (unlikely(!enable_mmio_caching))
3330 return RET_PF_EMULATE;
3333 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3334 * any guest that generates such gfns is running nested and is being
3335 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3336 * only if L1's MAXPHYADDR is inaccurate with respect to the
3339 if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3340 return RET_PF_EMULATE;
3342 return RET_PF_CONTINUE;
3345 static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3348 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
3349 * reach the common page fault handler if the SPTE has an invalid MMIO
3350 * generation number. Refreshing the MMIO generation needs to go down
3351 * the slow path. Note, EPT Misconfigs do NOT set the PRESENT flag!
3357 * #PF can be fast if:
3359 * 1. The shadow page table entry is not present and A/D bits are
3360 * disabled _by KVM_, which could mean that the fault is potentially
3361 * caused by access tracking (if enabled). If A/D bits are enabled
3362 * by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
3363 * bits for L2 and employ access tracking, but the fast page fault
3364 * mechanism only supports direct MMUs.
3365 * 2. The shadow page table entry is present, the access is a write,
3366 * and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
3367 * the fault was caused by a write-protection violation. If the
3368 * SPTE is MMU-writable (determined later), the fault can be fixed
3369 * by setting the Writable bit, which can be done out of mmu_lock.
3371 if (!fault->present)
3372 return !kvm_ad_enabled();
3375 * Note, instruction fetches and writes are mutually exclusive, ignore
3378 return fault->write;
3382 * Returns true if the SPTE was fixed successfully. Otherwise,
3383 * someone else modified the SPTE from its original value.
3385 static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu,
3386 struct kvm_page_fault *fault,
3387 u64 *sptep, u64 old_spte, u64 new_spte)
3390 * Theoretically we could also set dirty bit (and flush TLB) here in
3391 * order to eliminate unnecessary PML logging. See comments in
3392 * set_spte. But fast_page_fault is very unlikely to happen with PML
3393 * enabled, so we do not do this. This might result in the same GPA
3394 * to be logged in PML buffer again when the write really happens, and
3395 * eventually to be called by mark_page_dirty twice. But it's also no
3396 * harm. This also avoids the TLB flush needed after setting dirty bit
3397 * so non-PML cases won't be impacted.
3399 * Compare with set_spte where instead shadow_dirty_mask is set.
3401 if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3404 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3405 mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3410 static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3413 return is_executable_pte(spte);
3416 return is_writable_pte(spte);
3418 /* Fault was on Read access */
3419 return spte & PT_PRESENT_MASK;
3423 * Returns the last level spte pointer of the shadow page walk for the given
3424 * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
3425 * walk could be performed, returns NULL and *spte does not contain valid data.
3428 * - Must be called between walk_shadow_page_lockless_{begin,end}.
3429 * - The returned sptep must not be used after walk_shadow_page_lockless_end.
3431 static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
3433 struct kvm_shadow_walk_iterator iterator;
3437 for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
3438 sptep = iterator.sptep;
3446 * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3448 static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3450 struct kvm_mmu_page *sp;
3451 int ret = RET_PF_INVALID;
3454 uint retry_count = 0;
3456 if (!page_fault_can_be_fast(fault))
3459 walk_shadow_page_lockless_begin(vcpu);
3464 if (tdp_mmu_enabled)
3465 sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3467 sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3469 if (!is_shadow_present_pte(spte))
3472 sp = sptep_to_sp(sptep);
3473 if (!is_last_spte(spte, sp->role.level))
3477 * Check whether the memory access that caused the fault would
3478 * still cause it if it were to be performed right now. If not,
3479 * then this is a spurious fault caused by TLB lazily flushed,
3480 * or some other CPU has already fixed the PTE after the
3481 * current CPU took the fault.
3483 * Need not check the access of upper level table entries since
3484 * they are always ACC_ALL.
3486 if (is_access_allowed(fault, spte)) {
3487 ret = RET_PF_SPURIOUS;
3494 * KVM only supports fixing page faults outside of MMU lock for
3495 * direct MMUs, nested MMUs are always indirect, and KVM always
3496 * uses A/D bits for non-nested MMUs. Thus, if A/D bits are
3497 * enabled, the SPTE can't be an access-tracked SPTE.
3499 if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3500 new_spte = restore_acc_track_spte(new_spte);
3503 * To keep things simple, only SPTEs that are MMU-writable can
3504 * be made fully writable outside of mmu_lock, e.g. only SPTEs
3505 * that were write-protected for dirty-logging or access
3506 * tracking are handled here. Don't bother checking if the
3507 * SPTE is writable to prioritize running with A/D bits enabled.
3508 * The is_access_allowed() check above handles the common case
3509 * of the fault being spurious, and the SPTE is known to be
3510 * shadow-present, i.e. except for access tracking restoration
3511 * making the new SPTE writable, the check is wasteful.
3513 if (fault->write && is_mmu_writable_spte(spte)) {
3514 new_spte |= PT_WRITABLE_MASK;
3517 * Do not fix write-permission on the large spte when
3518 * dirty logging is enabled. Since we only dirty the
3519 * first page into the dirty-bitmap in
3520 * fast_pf_fix_direct_spte(), other pages are missed
3521 * if its slot has dirty logging enabled.
3523 * Instead, we let the slow page fault path create a
3524 * normal spte to fix the access.
3526 if (sp->role.level > PG_LEVEL_4K &&
3527 kvm_slot_dirty_track_enabled(fault->slot))
3531 /* Verify that the fault can be handled in the fast path */
3532 if (new_spte == spte ||
3533 !is_access_allowed(fault, new_spte))
3537 * Currently, fast page fault only works for direct mapping
3538 * since the gfn is not stable for indirect shadow page. See
3539 * Documentation/virt/kvm/locking.rst to get more detail.
3541 if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3546 if (++retry_count > 4) {
3547 pr_warn_once("Fast #PF retrying more than 4 times.\n");
3553 trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3554 walk_shadow_page_lockless_end(vcpu);
3556 if (ret != RET_PF_INVALID)
3557 vcpu->stat.pf_fast++;
3562 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3563 struct list_head *invalid_list)
3565 struct kvm_mmu_page *sp;
3567 if (!VALID_PAGE(*root_hpa))
3571 * The "root" may be a special root, e.g. a PAE entry, treat it as a
3572 * SPTE to ensure any non-PA bits are dropped.
3574 sp = spte_to_child_sp(*root_hpa);
3578 if (is_tdp_mmu_page(sp))
3579 kvm_tdp_mmu_put_root(kvm, sp, false);
3580 else if (!--sp->root_count && sp->role.invalid)
3581 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3583 *root_hpa = INVALID_PAGE;
3586 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3587 void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3588 ulong roots_to_free)
3591 LIST_HEAD(invalid_list);
3592 bool free_active_root;
3594 WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3596 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3598 /* Before acquiring the MMU lock, see if we need to do any real work. */
3599 free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3600 && VALID_PAGE(mmu->root.hpa);
3602 if (!free_active_root) {
3603 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3604 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3605 VALID_PAGE(mmu->prev_roots[i].hpa))
3608 if (i == KVM_MMU_NUM_PREV_ROOTS)
3612 write_lock(&kvm->mmu_lock);
3614 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3615 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3616 mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3619 if (free_active_root) {
3620 if (to_shadow_page(mmu->root.hpa)) {
3621 mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
3622 } else if (mmu->pae_root) {
3623 for (i = 0; i < 4; ++i) {
3624 if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3627 mmu_free_root_page(kvm, &mmu->pae_root[i],
3629 mmu->pae_root[i] = INVALID_PAE_ROOT;
3632 mmu->root.hpa = INVALID_PAGE;
3636 kvm_mmu_commit_zap_page(kvm, &invalid_list);
3637 write_unlock(&kvm->mmu_lock);
3639 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3641 void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
3643 unsigned long roots_to_free = 0;
3648 * This should not be called while L2 is active, L2 can't invalidate
3649 * _only_ its own roots, e.g. INVVPID unconditionally exits.
3651 WARN_ON_ONCE(mmu->root_role.guest_mode);
3653 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
3654 root_hpa = mmu->prev_roots[i].hpa;
3655 if (!VALID_PAGE(root_hpa))
3658 if (!to_shadow_page(root_hpa) ||
3659 to_shadow_page(root_hpa)->role.guest_mode)
3660 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
3663 kvm_mmu_free_roots(kvm, mmu, roots_to_free);
3665 EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
3668 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3672 if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3673 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3680 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
3683 union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3684 struct kvm_mmu_page *sp;
3687 role.quadrant = quadrant;
3689 WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
3690 WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
3692 sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
3695 return __pa(sp->spt);
3698 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3700 struct kvm_mmu *mmu = vcpu->arch.mmu;
3701 u8 shadow_root_level = mmu->root_role.level;
3706 write_lock(&vcpu->kvm->mmu_lock);
3707 r = make_mmu_pages_available(vcpu);
3711 if (tdp_mmu_enabled) {
3712 root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3713 mmu->root.hpa = root;
3714 } else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3715 root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3716 mmu->root.hpa = root;
3717 } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3718 if (WARN_ON_ONCE(!mmu->pae_root)) {
3723 for (i = 0; i < 4; ++i) {
3724 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3726 root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
3728 mmu->pae_root[i] = root | PT_PRESENT_MASK |
3731 mmu->root.hpa = __pa(mmu->pae_root);
3733 WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
3738 /* root.pgd is ignored for direct MMUs. */
3741 write_unlock(&vcpu->kvm->mmu_lock);
3745 static int mmu_first_shadow_root_alloc(struct kvm *kvm)
3747 struct kvm_memslots *slots;
3748 struct kvm_memory_slot *slot;
3752 * Check if this is the first shadow root being allocated before
3755 if (kvm_shadow_root_allocated(kvm))
3758 mutex_lock(&kvm->slots_arch_lock);
3760 /* Recheck, under the lock, whether this is the first shadow root. */
3761 if (kvm_shadow_root_allocated(kvm))
3765 * Check if anything actually needs to be allocated, e.g. all metadata
3766 * will be allocated upfront if TDP is disabled.
3768 if (kvm_memslots_have_rmaps(kvm) &&
3769 kvm_page_track_write_tracking_enabled(kvm))
3772 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
3773 slots = __kvm_memslots(kvm, i);
3774 kvm_for_each_memslot(slot, bkt, slots) {
3776 * Both of these functions are no-ops if the target is
3777 * already allocated, so unconditionally calling both
3778 * is safe. Intentionally do NOT free allocations on
3779 * failure to avoid having to track which allocations
3780 * were made now versus when the memslot was created.
3781 * The metadata is guaranteed to be freed when the slot
3782 * is freed, and will be kept/used if userspace retries
3783 * KVM_RUN instead of killing the VM.
3785 r = memslot_rmap_alloc(slot, slot->npages);
3788 r = kvm_page_track_write_tracking_alloc(slot);
3795 * Ensure that shadow_root_allocated becomes true strictly after
3796 * all the related pointers are set.
3799 smp_store_release(&kvm->arch.shadow_root_allocated, true);
3802 mutex_unlock(&kvm->slots_arch_lock);
3806 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3808 struct kvm_mmu *mmu = vcpu->arch.mmu;
3809 u64 pdptrs[4], pm_mask;
3810 gfn_t root_gfn, root_pgd;
3814 root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
3815 root_gfn = root_pgd >> PAGE_SHIFT;
3817 if (mmu_check_root(vcpu, root_gfn))
3821 * On SVM, reading PDPTRs might access guest memory, which might fault
3822 * and thus might sleep. Grab the PDPTRs before acquiring mmu_lock.
3824 if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3825 for (i = 0; i < 4; ++i) {
3826 pdptrs[i] = mmu->get_pdptr(vcpu, i);
3827 if (!(pdptrs[i] & PT_PRESENT_MASK))
3830 if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
3835 r = mmu_first_shadow_root_alloc(vcpu->kvm);
3839 write_lock(&vcpu->kvm->mmu_lock);
3840 r = make_mmu_pages_available(vcpu);
3845 * Do we shadow a long mode page table? If so we need to
3846 * write-protect the guests page table root.
3848 if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3849 root = mmu_alloc_root(vcpu, root_gfn, 0,
3850 mmu->root_role.level);
3851 mmu->root.hpa = root;
3855 if (WARN_ON_ONCE(!mmu->pae_root)) {
3861 * We shadow a 32 bit page table. This may be a legacy 2-level
3862 * or a PAE 3-level page table. In either case we need to be aware that
3863 * the shadow page table may be a PAE or a long mode page table.
3865 pm_mask = PT_PRESENT_MASK | shadow_me_value;
3866 if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3867 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3869 if (WARN_ON_ONCE(!mmu->pml4_root)) {
3873 mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3875 if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3876 if (WARN_ON_ONCE(!mmu->pml5_root)) {
3880 mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3884 for (i = 0; i < 4; ++i) {
3885 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3887 if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3888 if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3889 mmu->pae_root[i] = INVALID_PAE_ROOT;
3892 root_gfn = pdptrs[i] >> PAGE_SHIFT;
3896 * If shadowing 32-bit non-PAE page tables, each PAE page
3897 * directory maps one quarter of the guest's non-PAE page
3898 * directory. Othwerise each PAE page direct shadows one guest
3899 * PAE page directory so that quadrant should be 0.
3901 quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
3903 root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3904 mmu->pae_root[i] = root | pm_mask;
3907 if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3908 mmu->root.hpa = __pa(mmu->pml5_root);
3909 else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3910 mmu->root.hpa = __pa(mmu->pml4_root);
3912 mmu->root.hpa = __pa(mmu->pae_root);
3915 mmu->root.pgd = root_pgd;
3917 write_unlock(&vcpu->kvm->mmu_lock);
3922 static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3924 struct kvm_mmu *mmu = vcpu->arch.mmu;
3925 bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3926 u64 *pml5_root = NULL;
3927 u64 *pml4_root = NULL;
3931 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3932 * tables are allocated and initialized at root creation as there is no
3933 * equivalent level in the guest's NPT to shadow. Allocate the tables
3934 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3936 if (mmu->root_role.direct ||
3937 mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3938 mmu->root_role.level < PT64_ROOT_4LEVEL)
3942 * NPT, the only paging mode that uses this horror, uses a fixed number
3943 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3944 * all MMus are 5-level. Thus, this can safely require that pml5_root
3945 * is allocated if the other roots are valid and pml5 is needed, as any
3946 * prior MMU would also have required pml5.
3948 if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3952 * The special roots should always be allocated in concert. Yell and
3953 * bail if KVM ends up in a state where only one of the roots is valid.
3955 if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3956 (need_pml5 && mmu->pml5_root)))
3960 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
3961 * doesn't need to be decrypted.
3963 pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3967 #ifdef CONFIG_X86_64
3968 pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3973 pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3979 mmu->pae_root = pae_root;
3980 mmu->pml4_root = pml4_root;
3981 mmu->pml5_root = pml5_root;
3985 #ifdef CONFIG_X86_64
3987 free_page((unsigned long)pml4_root);
3989 free_page((unsigned long)pae_root);
3994 static bool is_unsync_root(hpa_t root)
3996 struct kvm_mmu_page *sp;
3998 if (!VALID_PAGE(root))
4002 * The read barrier orders the CPU's read of SPTE.W during the page table
4003 * walk before the reads of sp->unsync/sp->unsync_children here.
4005 * Even if another CPU was marking the SP as unsync-ed simultaneously,
4006 * any guest page table changes are not guaranteed to be visible anyway
4007 * until this VCPU issues a TLB flush strictly after those changes are
4008 * made. We only need to ensure that the other CPU sets these flags
4009 * before any actual changes to the page tables are made. The comments
4010 * in mmu_try_to_unsync_pages() describe what could go wrong if this
4011 * requirement isn't satisfied.
4014 sp = to_shadow_page(root);
4017 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
4018 * PDPTEs for a given PAE root need to be synchronized individually.
4020 if (WARN_ON_ONCE(!sp))
4023 if (sp->unsync || sp->unsync_children)
4029 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
4032 struct kvm_mmu_page *sp;
4034 if (vcpu->arch.mmu->root_role.direct)
4037 if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
4040 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4042 if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
4043 hpa_t root = vcpu->arch.mmu->root.hpa;
4044 sp = to_shadow_page(root);
4046 if (!is_unsync_root(root))
4049 write_lock(&vcpu->kvm->mmu_lock);
4050 mmu_sync_children(vcpu, sp, true);
4051 write_unlock(&vcpu->kvm->mmu_lock);
4055 write_lock(&vcpu->kvm->mmu_lock);
4057 for (i = 0; i < 4; ++i) {
4058 hpa_t root = vcpu->arch.mmu->pae_root[i];
4060 if (IS_VALID_PAE_ROOT(root)) {
4061 sp = spte_to_child_sp(root);
4062 mmu_sync_children(vcpu, sp, true);
4066 write_unlock(&vcpu->kvm->mmu_lock);
4069 void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
4071 unsigned long roots_to_free = 0;
4074 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4075 if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
4076 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
4078 /* sync prev_roots by simply freeing them */
4079 kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
4082 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4083 gpa_t vaddr, u64 access,
4084 struct x86_exception *exception)
4087 exception->error_code = 0;
4088 return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4091 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4094 * A nested guest cannot use the MMIO cache if it is using nested
4095 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4097 if (mmu_is_nested(vcpu))
4101 return vcpu_match_mmio_gpa(vcpu, addr);
4103 return vcpu_match_mmio_gva(vcpu, addr);
4107 * Return the level of the lowest level SPTE added to sptes.
4108 * That SPTE may be non-present.
4110 * Must be called between walk_shadow_page_lockless_{begin,end}.
4112 static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4114 struct kvm_shadow_walk_iterator iterator;
4118 for (shadow_walk_init(&iterator, vcpu, addr),
4119 *root_level = iterator.level;
4120 shadow_walk_okay(&iterator);
4121 __shadow_walk_next(&iterator, spte)) {
4122 leaf = iterator.level;
4123 spte = mmu_spte_get_lockless(iterator.sptep);
4131 /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
4132 static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
4134 u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
4135 struct rsvd_bits_validate *rsvd_check;
4136 int root, leaf, level;
4137 bool reserved = false;
4139 walk_shadow_page_lockless_begin(vcpu);
4141 if (is_tdp_mmu_active(vcpu))
4142 leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
4144 leaf = get_walk(vcpu, addr, sptes, &root);
4146 walk_shadow_page_lockless_end(vcpu);
4148 if (unlikely(leaf < 0)) {
4153 *sptep = sptes[leaf];
4156 * Skip reserved bits checks on the terminal leaf if it's not a valid
4157 * SPTE. Note, this also (intentionally) skips MMIO SPTEs, which, by
4158 * design, always have reserved bits set. The purpose of the checks is
4159 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
4161 if (!is_shadow_present_pte(sptes[leaf]))
4164 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
4166 for (level = root; level >= leaf; level--)
4167 reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4170 pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4172 for (level = root; level >= leaf; level--)
4173 pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4174 sptes[level], level,
4175 get_rsvd_bits(rsvd_check, sptes[level], level));
4181 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4186 if (mmio_info_in_cache(vcpu, addr, direct))
4187 return RET_PF_EMULATE;
4189 reserved = get_mmio_spte(vcpu, addr, &spte);
4190 if (WARN_ON(reserved))
4193 if (is_mmio_spte(spte)) {
4194 gfn_t gfn = get_mmio_spte_gfn(spte);
4195 unsigned int access = get_mmio_spte_access(spte);
4197 if (!check_mmio_spte(vcpu, spte))
4198 return RET_PF_INVALID;
4203 trace_handle_mmio_page_fault(addr, gfn, access);
4204 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4205 return RET_PF_EMULATE;
4209 * If the page table is zapped by other cpus, let CPU fault again on
4212 return RET_PF_RETRY;
4215 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4216 struct kvm_page_fault *fault)
4218 if (unlikely(fault->rsvd))
4221 if (!fault->present || !fault->write)
4225 * guest is writing the page which is write tracked which can
4226 * not be fixed by page fault handler.
4228 if (kvm_slot_page_track_is_active(vcpu->kvm, fault->slot, fault->gfn, KVM_PAGE_TRACK_WRITE))
4234 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4236 struct kvm_shadow_walk_iterator iterator;
4239 walk_shadow_page_lockless_begin(vcpu);
4240 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4241 clear_sp_write_flooding_count(iterator.sptep);
4242 walk_shadow_page_lockless_end(vcpu);
4245 static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
4247 /* make sure the token value is not 0 */
4248 u32 id = vcpu->arch.apf.id;
4251 vcpu->arch.apf.id = 1;
4253 return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4256 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4259 struct kvm_arch_async_pf arch;
4261 arch.token = alloc_apf_token(vcpu);
4263 arch.direct_map = vcpu->arch.mmu->root_role.direct;
4264 arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
4266 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4267 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4270 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
4274 if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
4278 r = kvm_mmu_reload(vcpu);
4282 if (!vcpu->arch.mmu->root_role.direct &&
4283 work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
4286 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true, NULL);
4289 static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4291 struct kvm_memory_slot *slot = fault->slot;
4295 * Retry the page fault if the gfn hit a memslot that is being deleted
4296 * or moved. This ensures any existing SPTEs for the old memslot will
4297 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4299 if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
4300 return RET_PF_RETRY;
4302 if (!kvm_is_visible_memslot(slot)) {
4303 /* Don't expose private memslots to L2. */
4304 if (is_guest_mode(vcpu)) {
4306 fault->pfn = KVM_PFN_NOSLOT;
4307 fault->map_writable = false;
4308 return RET_PF_CONTINUE;
4311 * If the APIC access page exists but is disabled, go directly
4312 * to emulation without caching the MMIO access or creating a
4313 * MMIO SPTE. That way the cache doesn't need to be purged
4314 * when the AVIC is re-enabled.
4316 if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
4317 !kvm_apicv_activated(vcpu->kvm))
4318 return RET_PF_EMULATE;
4322 fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, false, &async,
4323 fault->write, &fault->map_writable,
4326 return RET_PF_CONTINUE; /* *pfn has correct page already */
4328 if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
4329 trace_kvm_try_async_get_page(fault->addr, fault->gfn);
4330 if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
4331 trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4332 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4333 return RET_PF_RETRY;
4334 } else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
4335 return RET_PF_RETRY;
4340 * Allow gup to bail on pending non-fatal signals when it's also allowed
4341 * to wait for IO. Note, gup always bails if it is unable to quickly
4342 * get a page and a fatal signal, i.e. SIGKILL, is pending.
4344 fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, true, NULL,
4345 fault->write, &fault->map_writable,
4347 return RET_PF_CONTINUE;
4350 static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4351 unsigned int access)
4355 fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4358 ret = __kvm_faultin_pfn(vcpu, fault);
4359 if (ret != RET_PF_CONTINUE)
4362 if (unlikely(is_error_pfn(fault->pfn)))
4363 return kvm_handle_error_pfn(vcpu, fault);
4365 if (unlikely(!fault->slot))
4366 return kvm_handle_noslot_fault(vcpu, fault, access);
4368 return RET_PF_CONTINUE;
4372 * Returns true if the page fault is stale and needs to be retried, i.e. if the
4373 * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4375 static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4376 struct kvm_page_fault *fault)
4378 struct kvm_mmu_page *sp = to_shadow_page(vcpu->arch.mmu->root.hpa);
4380 /* Special roots, e.g. pae_root, are not backed by shadow pages. */
4381 if (sp && is_obsolete_sp(vcpu->kvm, sp))
4385 * Roots without an associated shadow page are considered invalid if
4386 * there is a pending request to free obsolete roots. The request is
4387 * only a hint that the current root _may_ be obsolete and needs to be
4388 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
4389 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
4390 * to reload even if no vCPU is actively using the root.
4392 if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4395 return fault->slot &&
4396 mmu_invalidate_retry_hva(vcpu->kvm, fault->mmu_seq, fault->hva);
4399 static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4403 if (page_fault_handle_page_track(vcpu, fault))
4404 return RET_PF_EMULATE;
4406 r = fast_page_fault(vcpu, fault);
4407 if (r != RET_PF_INVALID)
4410 r = mmu_topup_memory_caches(vcpu, false);
4414 r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4415 if (r != RET_PF_CONTINUE)
4419 write_lock(&vcpu->kvm->mmu_lock);
4421 if (is_page_fault_stale(vcpu, fault))
4424 r = make_mmu_pages_available(vcpu);
4428 r = direct_map(vcpu, fault);
4431 write_unlock(&vcpu->kvm->mmu_lock);
4432 kvm_release_pfn_clean(fault->pfn);
4436 static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4437 struct kvm_page_fault *fault)
4439 pgprintk("%s: gva %lx error %x\n", __func__, fault->addr, fault->error_code);
4441 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4442 fault->max_level = PG_LEVEL_2M;
4443 return direct_page_fault(vcpu, fault);
4446 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4447 u64 fault_address, char *insn, int insn_len)
4450 u32 flags = vcpu->arch.apf.host_apf_flags;
4452 #ifndef CONFIG_X86_64
4453 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4454 if (WARN_ON_ONCE(fault_address >> 32))
4458 vcpu->arch.l1tf_flush_l1d = true;
4460 trace_kvm_page_fault(vcpu, fault_address, error_code);
4462 if (kvm_event_needs_reinjection(vcpu))
4463 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4464 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4466 } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
4467 vcpu->arch.apf.host_apf_flags = 0;
4468 local_irq_disable();
4469 kvm_async_pf_task_wait_schedule(fault_address);
4472 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4477 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4479 #ifdef CONFIG_X86_64
4480 static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
4481 struct kvm_page_fault *fault)
4485 if (page_fault_handle_page_track(vcpu, fault))
4486 return RET_PF_EMULATE;
4488 r = fast_page_fault(vcpu, fault);
4489 if (r != RET_PF_INVALID)
4492 r = mmu_topup_memory_caches(vcpu, false);
4496 r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4497 if (r != RET_PF_CONTINUE)
4501 read_lock(&vcpu->kvm->mmu_lock);
4503 if (is_page_fault_stale(vcpu, fault))
4506 r = kvm_tdp_mmu_map(vcpu, fault);
4509 read_unlock(&vcpu->kvm->mmu_lock);
4510 kvm_release_pfn_clean(fault->pfn);
4515 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4518 * If the guest's MTRRs may be used to compute the "real" memtype,
4519 * restrict the mapping level to ensure KVM uses a consistent memtype
4520 * across the entire mapping. If the host MTRRs are ignored by TDP
4521 * (shadow_memtype_mask is non-zero), and the VM has non-coherent DMA
4522 * (DMA doesn't snoop CPU caches), KVM's ABI is to honor the memtype
4523 * from the guest's MTRRs so that guest accesses to memory that is
4524 * DMA'd aren't cached against the guest's wishes.
4526 * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
4527 * e.g. KVM will force UC memtype for host MMIO.
4529 if (shadow_memtype_mask && kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
4530 for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
4531 int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
4532 gfn_t base = gfn_round_for_level(fault->gfn,
4535 if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4540 #ifdef CONFIG_X86_64
4541 if (tdp_mmu_enabled)
4542 return kvm_tdp_mmu_page_fault(vcpu, fault);
4545 return direct_page_fault(vcpu, fault);
4548 static void nonpaging_init_context(struct kvm_mmu *context)
4550 context->page_fault = nonpaging_page_fault;
4551 context->gva_to_gpa = nonpaging_gva_to_gpa;
4552 context->sync_spte = NULL;
4555 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
4556 union kvm_mmu_page_role role)
4558 return (role.direct || pgd == root->pgd) &&
4559 VALID_PAGE(root->hpa) &&
4560 role.word == to_shadow_page(root->hpa)->role.word;
4564 * Find out if a previously cached root matching the new pgd/role is available,
4565 * and insert the current root as the MRU in the cache.
4566 * If a matching root is found, it is assigned to kvm_mmu->root and
4568 * If no match is found, kvm_mmu->root is left invalid, the LRU root is
4569 * evicted to make room for the current root, and false is returned.
4571 static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
4573 union kvm_mmu_page_role new_role)
4577 if (is_root_usable(&mmu->root, new_pgd, new_role))
4580 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4582 * The swaps end up rotating the cache like this:
4583 * C 0 1 2 3 (on entry to the function)
4587 * 3 C 0 1 2 (on exit from the loop)
4589 swap(mmu->root, mmu->prev_roots[i]);
4590 if (is_root_usable(&mmu->root, new_pgd, new_role))
4594 kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4599 * Find out if a previously cached root matching the new pgd/role is available.
4600 * On entry, mmu->root is invalid.
4601 * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
4602 * of the cache becomes invalid, and true is returned.
4603 * If no match is found, kvm_mmu->root is left invalid and false is returned.
4605 static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
4607 union kvm_mmu_page_role new_role)
4611 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4612 if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
4618 swap(mmu->root, mmu->prev_roots[i]);
4619 /* Bubble up the remaining roots. */
4620 for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
4621 mmu->prev_roots[i] = mmu->prev_roots[i + 1];
4622 mmu->prev_roots[i].hpa = INVALID_PAGE;
4626 static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
4627 gpa_t new_pgd, union kvm_mmu_page_role new_role)
4630 * For now, limit the caching to 64-bit hosts+VMs in order to avoid
4631 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4632 * later if necessary.
4634 if (VALID_PAGE(mmu->root.hpa) && !to_shadow_page(mmu->root.hpa))
4635 kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4637 if (VALID_PAGE(mmu->root.hpa))
4638 return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
4640 return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4643 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4645 struct kvm_mmu *mmu = vcpu->arch.mmu;
4646 union kvm_mmu_page_role new_role = mmu->root_role;
4649 * Return immediately if no usable root was found, kvm_mmu_reload()
4650 * will establish a valid root prior to the next VM-Enter.
4652 if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4656 * It's possible that the cached previous root page is obsolete because
4657 * of a change in the MMU generation number. However, changing the
4658 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4659 * which will free the root set here and allocate a new one.
4661 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4663 if (force_flush_and_sync_on_reuse) {
4664 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4665 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4669 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4670 * switching to a new CR3, that GVA->GPA mapping may no longer be
4671 * valid. So clear any cached MMIO info even when we don't need to sync
4672 * the shadow page tables.
4674 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4677 * If this is a direct root page, it doesn't have a write flooding
4678 * count. Otherwise, clear the write flooding count.
4680 if (!new_role.direct)
4681 __clear_sp_write_flooding_count(
4682 to_shadow_page(vcpu->arch.mmu->root.hpa));
4684 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4686 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4687 unsigned int access)
4689 if (unlikely(is_mmio_spte(*sptep))) {
4690 if (gfn != get_mmio_spte_gfn(*sptep)) {
4691 mmu_spte_clear_no_track(sptep);
4695 mark_mmio_spte(vcpu, sptep, gfn, access);
4702 #define PTTYPE_EPT 18 /* arbitrary */
4703 #define PTTYPE PTTYPE_EPT
4704 #include "paging_tmpl.h"
4708 #include "paging_tmpl.h"
4712 #include "paging_tmpl.h"
4715 static void __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
4716 u64 pa_bits_rsvd, int level, bool nx,
4717 bool gbpages, bool pse, bool amd)
4719 u64 gbpages_bit_rsvd = 0;
4720 u64 nonleaf_bit8_rsvd = 0;
4723 rsvd_check->bad_mt_xwr = 0;
4726 gbpages_bit_rsvd = rsvd_bits(7, 7);
4728 if (level == PT32E_ROOT_LEVEL)
4729 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
4731 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4733 /* Note, NX doesn't exist in PDPTEs, this is handled below. */
4735 high_bits_rsvd |= rsvd_bits(63, 63);
4738 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4739 * leaf entries) on AMD CPUs only.
4742 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4745 case PT32_ROOT_LEVEL:
4746 /* no rsvd bits for 2 level 4K page table entries */
4747 rsvd_check->rsvd_bits_mask[0][1] = 0;
4748 rsvd_check->rsvd_bits_mask[0][0] = 0;
4749 rsvd_check->rsvd_bits_mask[1][0] =
4750 rsvd_check->rsvd_bits_mask[0][0];
4753 rsvd_check->rsvd_bits_mask[1][1] = 0;
4757 if (is_cpuid_PSE36())
4758 /* 36bits PSE 4MB page */
4759 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4761 /* 32 bits PSE 4MB page */
4762 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4764 case PT32E_ROOT_LEVEL:
4765 rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
4768 rsvd_bits(1, 2); /* PDPTE */
4769 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd; /* PDE */
4770 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd; /* PTE */
4771 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4772 rsvd_bits(13, 20); /* large page */
4773 rsvd_check->rsvd_bits_mask[1][0] =
4774 rsvd_check->rsvd_bits_mask[0][0];
4776 case PT64_ROOT_5LEVEL:
4777 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
4780 rsvd_check->rsvd_bits_mask[1][4] =
4781 rsvd_check->rsvd_bits_mask[0][4];
4783 case PT64_ROOT_4LEVEL:
4784 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
4787 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
4789 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
4790 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4791 rsvd_check->rsvd_bits_mask[1][3] =
4792 rsvd_check->rsvd_bits_mask[0][3];
4793 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
4796 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4797 rsvd_bits(13, 20); /* large page */
4798 rsvd_check->rsvd_bits_mask[1][0] =
4799 rsvd_check->rsvd_bits_mask[0][0];
4804 static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
4807 * If TDP is enabled, let the guest use GBPAGES if they're supported in
4808 * hardware. The hardware page walker doesn't let KVM disable GBPAGES,
4809 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
4810 * walk for performance and complexity reasons. Not to mention KVM
4811 * _can't_ solve the problem because GVA->GPA walks aren't visible to
4812 * KVM once a TDP translation is installed. Mimic hardware behavior so
4813 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
4815 return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
4816 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
4819 static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4820 struct kvm_mmu *context)
4822 __reset_rsvds_bits_mask(&context->guest_rsvd_check,
4823 vcpu->arch.reserved_gpa_bits,
4824 context->cpu_role.base.level, is_efer_nx(context),
4825 guest_can_use_gbpages(vcpu),
4826 is_cr4_pse(context),
4827 guest_cpuid_is_amd_or_hygon(vcpu));
4830 static void __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4831 u64 pa_bits_rsvd, bool execonly,
4832 int huge_page_level)
4834 u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4835 u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4838 if (huge_page_level < PG_LEVEL_1G)
4839 large_1g_rsvd = rsvd_bits(7, 7);
4840 if (huge_page_level < PG_LEVEL_2M)
4841 large_2m_rsvd = rsvd_bits(7, 7);
4843 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
4844 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
4845 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
4846 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
4847 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4850 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4851 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4852 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
4853 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4854 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4856 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4857 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4858 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4859 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4860 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4862 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4863 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4865 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4868 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4869 struct kvm_mmu *context, bool execonly, int huge_page_level)
4871 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4872 vcpu->arch.reserved_gpa_bits, execonly,
4876 static inline u64 reserved_hpa_bits(void)
4878 return rsvd_bits(shadow_phys_bits, 63);
4882 * the page table on host is the shadow page table for the page
4883 * table in guest or amd nested guest, its mmu features completely
4884 * follow the features in guest.
4886 static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4887 struct kvm_mmu *context)
4889 /* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
4891 /* KVM doesn't use 2-level page tables for the shadow MMU. */
4892 bool is_pse = false;
4893 struct rsvd_bits_validate *shadow_zero_check;
4896 WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
4898 shadow_zero_check = &context->shadow_zero_check;
4899 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4900 context->root_role.level,
4901 context->root_role.efer_nx,
4902 guest_can_use_gbpages(vcpu), is_pse, is_amd);
4904 if (!shadow_me_mask)
4907 for (i = context->root_role.level; --i >= 0;) {
4909 * So far shadow_me_value is a constant during KVM's life
4910 * time. Bits in shadow_me_value are allowed to be set.
4911 * Bits in shadow_me_mask but not in shadow_me_value are
4912 * not allowed to be set.
4914 shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4915 shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4916 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4917 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4922 static inline bool boot_cpu_is_amd(void)
4924 WARN_ON_ONCE(!tdp_enabled);
4925 return shadow_x_mask == 0;
4929 * the direct page table on host, use as much mmu features as
4930 * possible, however, kvm currently does not do execution-protection.
4932 static void reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4934 struct rsvd_bits_validate *shadow_zero_check;
4937 shadow_zero_check = &context->shadow_zero_check;
4939 if (boot_cpu_is_amd())
4940 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4941 context->root_role.level, true,
4942 boot_cpu_has(X86_FEATURE_GBPAGES),
4945 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4946 reserved_hpa_bits(), false,
4947 max_huge_page_level);
4949 if (!shadow_me_mask)
4952 for (i = context->root_role.level; --i >= 0;) {
4953 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4954 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4959 * as the comments in reset_shadow_zero_bits_mask() except it
4960 * is the shadow page table for intel nested guest.
4963 reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
4965 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4966 reserved_hpa_bits(), execonly,
4967 max_huge_page_level);
4970 #define BYTE_MASK(access) \
4971 ((1 & (access) ? 2 : 0) | \
4972 (2 & (access) ? 4 : 0) | \
4973 (3 & (access) ? 8 : 0) | \
4974 (4 & (access) ? 16 : 0) | \
4975 (5 & (access) ? 32 : 0) | \
4976 (6 & (access) ? 64 : 0) | \
4977 (7 & (access) ? 128 : 0))
4980 static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4984 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4985 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4986 const u8 u = BYTE_MASK(ACC_USER_MASK);
4988 bool cr4_smep = is_cr4_smep(mmu);
4989 bool cr4_smap = is_cr4_smap(mmu);
4990 bool cr0_wp = is_cr0_wp(mmu);
4991 bool efer_nx = is_efer_nx(mmu);
4993 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4994 unsigned pfec = byte << 1;
4997 * Each "*f" variable has a 1 bit for each UWX value
4998 * that causes a fault with the given PFEC.
5001 /* Faults from writes to non-writable pages */
5002 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
5003 /* Faults from user mode accesses to supervisor pages */
5004 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
5005 /* Faults from fetches of non-executable pages*/
5006 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
5007 /* Faults from kernel mode fetches of user pages */
5009 /* Faults from kernel mode accesses of user pages */
5013 /* Faults from kernel mode accesses to user pages */
5014 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
5016 /* Not really needed: !nx will cause pte.nx to fault */
5020 /* Allow supervisor writes if !cr0.wp */
5022 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
5024 /* Disallow supervisor fetches of user code if cr4.smep */
5026 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
5029 * SMAP:kernel-mode data accesses from user-mode
5030 * mappings should fault. A fault is considered
5031 * as a SMAP violation if all of the following
5032 * conditions are true:
5033 * - X86_CR4_SMAP is set in CR4
5034 * - A user page is accessed
5035 * - The access is not a fetch
5036 * - The access is supervisor mode
5037 * - If implicit supervisor access or X86_EFLAGS_AC is clear
5039 * Here, we cover the first four conditions.
5040 * The fifth is computed dynamically in permission_fault();
5041 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5042 * *not* subject to SMAP restrictions.
5045 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5048 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5053 * PKU is an additional mechanism by which the paging controls access to
5054 * user-mode addresses based on the value in the PKRU register. Protection
5055 * key violations are reported through a bit in the page fault error code.
5056 * Unlike other bits of the error code, the PK bit is not known at the
5057 * call site of e.g. gva_to_gpa; it must be computed directly in
5058 * permission_fault based on two bits of PKRU, on some machine state (CR4,
5059 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5061 * In particular the following conditions come from the error code, the
5062 * page tables and the machine state:
5063 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5064 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5065 * - PK is always zero if U=0 in the page tables
5066 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5068 * The PKRU bitmask caches the result of these four conditions. The error
5069 * code (minus the P bit) and the page table's U bit form an index into the
5070 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
5071 * with the two bits of the PKRU register corresponding to the protection key.
5072 * For the first three conditions above the bits will be 00, thus masking
5073 * away both AD and WD. For all reads or if the last condition holds, WD
5074 * only will be masked away.
5076 static void update_pkru_bitmask(struct kvm_mmu *mmu)
5083 if (!is_cr4_pke(mmu))
5086 wp = is_cr0_wp(mmu);
5088 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5089 unsigned pfec, pkey_bits;
5090 bool check_pkey, check_write, ff, uf, wf, pte_user;
5093 ff = pfec & PFERR_FETCH_MASK;
5094 uf = pfec & PFERR_USER_MASK;
5095 wf = pfec & PFERR_WRITE_MASK;
5097 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
5098 pte_user = pfec & PFERR_RSVD_MASK;
5101 * Only need to check the access which is not an
5102 * instruction fetch and is to a user page.
5104 check_pkey = (!ff && pte_user);
5106 * write access is controlled by PKRU if it is a
5107 * user access or CR0.WP = 1.
5109 check_write = check_pkey && wf && (uf || wp);
5111 /* PKRU.AD stops both read and write access. */
5112 pkey_bits = !!check_pkey;
5113 /* PKRU.WD stops write access. */
5114 pkey_bits |= (!!check_write) << 1;
5116 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5120 static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5121 struct kvm_mmu *mmu)
5123 if (!is_cr0_pg(mmu))
5126 reset_guest_rsvds_bits_mask(vcpu, mmu);
5127 update_permission_bitmask(mmu, false);
5128 update_pkru_bitmask(mmu);
5131 static void paging64_init_context(struct kvm_mmu *context)
5133 context->page_fault = paging64_page_fault;
5134 context->gva_to_gpa = paging64_gva_to_gpa;
5135 context->sync_spte = paging64_sync_spte;
5138 static void paging32_init_context(struct kvm_mmu *context)
5140 context->page_fault = paging32_page_fault;
5141 context->gva_to_gpa = paging32_gva_to_gpa;
5142 context->sync_spte = paging32_sync_spte;
5145 static union kvm_cpu_role kvm_calc_cpu_role(struct kvm_vcpu *vcpu,
5146 const struct kvm_mmu_role_regs *regs)
5148 union kvm_cpu_role role = {0};
5150 role.base.access = ACC_ALL;
5151 role.base.smm = is_smm(vcpu);
5152 role.base.guest_mode = is_guest_mode(vcpu);
5155 if (!____is_cr0_pg(regs)) {
5156 role.base.direct = 1;
5160 role.base.efer_nx = ____is_efer_nx(regs);
5161 role.base.cr0_wp = ____is_cr0_wp(regs);
5162 role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5163 role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5164 role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
5166 if (____is_efer_lma(regs))
5167 role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
5169 else if (____is_cr4_pae(regs))
5170 role.base.level = PT32E_ROOT_LEVEL;
5172 role.base.level = PT32_ROOT_LEVEL;
5174 role.ext.cr4_smep = ____is_cr4_smep(regs);
5175 role.ext.cr4_smap = ____is_cr4_smap(regs);
5176 role.ext.cr4_pse = ____is_cr4_pse(regs);
5178 /* PKEY and LA57 are active iff long mode is active. */
5179 role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5180 role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5181 role.ext.efer_lma = ____is_efer_lma(regs);
5185 void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
5186 struct kvm_mmu *mmu)
5188 const bool cr0_wp = kvm_is_cr0_bit_set(vcpu, X86_CR0_WP);
5190 BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
5191 BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
5193 if (is_cr0_wp(mmu) == cr0_wp)
5196 mmu->cpu_role.base.cr0_wp = cr0_wp;
5197 reset_guest_paging_metadata(vcpu, mmu);
5200 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5202 /* tdp_root_level is architecture forced level, use it if nonzero */
5204 return tdp_root_level;
5206 /* Use 5-level TDP if and only if it's useful/necessary. */
5207 if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5210 return max_tdp_level;
5213 static union kvm_mmu_page_role
5214 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
5215 union kvm_cpu_role cpu_role)
5217 union kvm_mmu_page_role role = {0};
5219 role.access = ACC_ALL;
5221 role.efer_nx = true;
5222 role.smm = cpu_role.base.smm;
5223 role.guest_mode = cpu_role.base.guest_mode;
5224 role.ad_disabled = !kvm_ad_enabled();
5225 role.level = kvm_mmu_get_tdp_level(vcpu);
5227 role.has_4_byte_gpte = false;
5232 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5233 union kvm_cpu_role cpu_role)
5235 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5236 union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5238 if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5239 root_role.word == context->root_role.word)
5242 context->cpu_role.as_u64 = cpu_role.as_u64;
5243 context->root_role.word = root_role.word;
5244 context->page_fault = kvm_tdp_page_fault;
5245 context->sync_spte = NULL;
5246 context->get_guest_pgd = get_guest_cr3;
5247 context->get_pdptr = kvm_pdptr_read;
5248 context->inject_page_fault = kvm_inject_page_fault;
5250 if (!is_cr0_pg(context))
5251 context->gva_to_gpa = nonpaging_gva_to_gpa;
5252 else if (is_cr4_pae(context))
5253 context->gva_to_gpa = paging64_gva_to_gpa;
5255 context->gva_to_gpa = paging32_gva_to_gpa;
5257 reset_guest_paging_metadata(vcpu, context);
5258 reset_tdp_shadow_zero_bits_mask(context);
5261 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
5262 union kvm_cpu_role cpu_role,
5263 union kvm_mmu_page_role root_role)
5265 if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5266 root_role.word == context->root_role.word)
5269 context->cpu_role.as_u64 = cpu_role.as_u64;
5270 context->root_role.word = root_role.word;
5272 if (!is_cr0_pg(context))
5273 nonpaging_init_context(context);
5274 else if (is_cr4_pae(context))
5275 paging64_init_context(context);
5277 paging32_init_context(context);
5279 reset_guest_paging_metadata(vcpu, context);
5280 reset_shadow_zero_bits_mask(vcpu, context);
5283 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5284 union kvm_cpu_role cpu_role)
5286 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5287 union kvm_mmu_page_role root_role;
5289 root_role = cpu_role.base;
5291 /* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
5292 root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
5295 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
5296 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
5297 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
5298 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
5299 * The iTLB multi-hit workaround can be toggled at any time, so assume
5300 * NX can be used by any non-nested shadow MMU to avoid having to reset
5303 root_role.efer_nx = true;
5305 shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5308 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5309 unsigned long cr4, u64 efer, gpa_t nested_cr3)
5311 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5312 struct kvm_mmu_role_regs regs = {
5314 .cr4 = cr4 & ~X86_CR4_PKE,
5317 union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, ®s);
5318 union kvm_mmu_page_role root_role;
5320 /* NPT requires CR0.PG=1. */
5321 WARN_ON_ONCE(cpu_role.base.direct);
5323 root_role = cpu_role.base;
5324 root_role.level = kvm_mmu_get_tdp_level(vcpu);
5325 if (root_role.level == PT64_ROOT_5LEVEL &&
5326 cpu_role.base.level == PT64_ROOT_4LEVEL)
5327 root_role.passthrough = 1;
5329 shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5330 kvm_mmu_new_pgd(vcpu, nested_cr3);
5332 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5334 static union kvm_cpu_role
5335 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5336 bool execonly, u8 level)
5338 union kvm_cpu_role role = {0};
5341 * KVM does not support SMM transfer monitors, and consequently does not
5342 * support the "entry to SMM" control either. role.base.smm is always 0.
5344 WARN_ON_ONCE(is_smm(vcpu));
5345 role.base.level = level;
5346 role.base.has_4_byte_gpte = false;
5347 role.base.direct = false;
5348 role.base.ad_disabled = !accessed_dirty;
5349 role.base.guest_mode = true;
5350 role.base.access = ACC_ALL;
5353 role.ext.execonly = execonly;
5359 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5360 int huge_page_level, bool accessed_dirty,
5363 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5364 u8 level = vmx_eptp_page_walk_level(new_eptp);
5365 union kvm_cpu_role new_mode =
5366 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5369 if (new_mode.as_u64 != context->cpu_role.as_u64) {
5370 /* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5371 context->cpu_role.as_u64 = new_mode.as_u64;
5372 context->root_role.word = new_mode.base.word;
5374 context->page_fault = ept_page_fault;
5375 context->gva_to_gpa = ept_gva_to_gpa;
5376 context->sync_spte = ept_sync_spte;
5378 update_permission_bitmask(context, true);
5379 context->pkru_mask = 0;
5380 reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5381 reset_ept_shadow_zero_bits_mask(context, execonly);
5384 kvm_mmu_new_pgd(vcpu, new_eptp);
5386 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5388 static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5389 union kvm_cpu_role cpu_role)
5391 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5393 kvm_init_shadow_mmu(vcpu, cpu_role);
5395 context->get_guest_pgd = get_guest_cr3;
5396 context->get_pdptr = kvm_pdptr_read;
5397 context->inject_page_fault = kvm_inject_page_fault;
5400 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5401 union kvm_cpu_role new_mode)
5403 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5405 if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5408 g_context->cpu_role.as_u64 = new_mode.as_u64;
5409 g_context->get_guest_pgd = get_guest_cr3;
5410 g_context->get_pdptr = kvm_pdptr_read;
5411 g_context->inject_page_fault = kvm_inject_page_fault;
5414 * L2 page tables are never shadowed, so there is no need to sync
5417 g_context->sync_spte = NULL;
5420 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5421 * L1's nested page tables (e.g. EPT12). The nested translation
5422 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5423 * L2's page tables as the first level of translation and L1's
5424 * nested page tables as the second level of translation. Basically
5425 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5427 if (!is_paging(vcpu))
5428 g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5429 else if (is_long_mode(vcpu))
5430 g_context->gva_to_gpa = paging64_gva_to_gpa;
5431 else if (is_pae(vcpu))
5432 g_context->gva_to_gpa = paging64_gva_to_gpa;
5434 g_context->gva_to_gpa = paging32_gva_to_gpa;
5436 reset_guest_paging_metadata(vcpu, g_context);
5439 void kvm_init_mmu(struct kvm_vcpu *vcpu)
5441 struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5442 union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, ®s);
5444 if (mmu_is_nested(vcpu))
5445 init_kvm_nested_mmu(vcpu, cpu_role);
5446 else if (tdp_enabled)
5447 init_kvm_tdp_mmu(vcpu, cpu_role);
5449 init_kvm_softmmu(vcpu, cpu_role);
5451 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5453 void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
5456 * Invalidate all MMU roles to force them to reinitialize as CPUID
5457 * information is factored into reserved bit calculations.
5459 * Correctly handling multiple vCPU models with respect to paging and
5460 * physical address properties) in a single VM would require tracking
5461 * all relevant CPUID information in kvm_mmu_page_role. That is very
5462 * undesirable as it would increase the memory requirements for
5463 * gfn_track (see struct kvm_mmu_page_role comments). For now that
5464 * problem is swept under the rug; KVM's CPUID API is horrific and
5465 * it's all but impossible to solve it without introducing a new API.
5467 vcpu->arch.root_mmu.root_role.word = 0;
5468 vcpu->arch.guest_mmu.root_role.word = 0;
5469 vcpu->arch.nested_mmu.root_role.word = 0;
5470 vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5471 vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5472 vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
5473 kvm_mmu_reset_context(vcpu);
5476 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5477 * kvm_arch_vcpu_ioctl().
5479 KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm);
5482 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5484 kvm_mmu_unload(vcpu);
5487 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5489 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5493 r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5496 r = mmu_alloc_special_roots(vcpu);
5499 if (vcpu->arch.mmu->root_role.direct)
5500 r = mmu_alloc_direct_roots(vcpu);
5502 r = mmu_alloc_shadow_roots(vcpu);
5506 kvm_mmu_sync_roots(vcpu);
5508 kvm_mmu_load_pgd(vcpu);
5511 * Flush any TLB entries for the new root, the provenance of the root
5512 * is unknown. Even if KVM ensures there are no stale TLB entries
5513 * for a freed root, in theory another hypervisor could have left
5514 * stale entries. Flushing on alloc also allows KVM to skip the TLB
5515 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5517 static_call(kvm_x86_flush_tlb_current)(vcpu);
5522 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5524 struct kvm *kvm = vcpu->kvm;
5526 kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5527 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
5528 kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5529 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
5530 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5533 static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5535 struct kvm_mmu_page *sp;
5537 if (!VALID_PAGE(root_hpa))
5541 * When freeing obsolete roots, treat roots as obsolete if they don't
5542 * have an associated shadow page. This does mean KVM will get false
5543 * positives and free roots that don't strictly need to be freed, but
5544 * such false positives are relatively rare:
5546 * (a) only PAE paging and nested NPT has roots without shadow pages
5547 * (b) remote reloads due to a memslot update obsoletes _all_ roots
5548 * (c) KVM doesn't track previous roots for PAE paging, and the guest
5549 * is unlikely to zap an in-use PGD.
5551 sp = to_shadow_page(root_hpa);
5552 return !sp || is_obsolete_sp(kvm, sp);
5555 static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5557 unsigned long roots_to_free = 0;
5560 if (is_obsolete_root(kvm, mmu->root.hpa))
5561 roots_to_free |= KVM_MMU_ROOT_CURRENT;
5563 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5564 if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5565 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5569 kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5572 void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5574 __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5575 __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5578 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5585 * Assume that the pte write on a page table of the same type
5586 * as the current vcpu paging mode since we update the sptes only
5587 * when they have the same mode.
5589 if (is_pae(vcpu) && *bytes == 4) {
5590 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5595 if (*bytes == 4 || *bytes == 8) {
5596 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5605 * If we're seeing too many writes to a page, it may no longer be a page table,
5606 * or we may be forking, in which case it is better to unmap the page.
5608 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5611 * Skip write-flooding detected for the sp whose level is 1, because
5612 * it can become unsync, then the guest page is not write-protected.
5614 if (sp->role.level == PG_LEVEL_4K)
5617 atomic_inc(&sp->write_flooding_count);
5618 return atomic_read(&sp->write_flooding_count) >= 3;
5622 * Misaligned accesses are too much trouble to fix up; also, they usually
5623 * indicate a page is not used as a page table.
5625 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5628 unsigned offset, pte_size, misaligned;
5630 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5631 gpa, bytes, sp->role.word);
5633 offset = offset_in_page(gpa);
5634 pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5637 * Sometimes, the OS only writes the last one bytes to update status
5638 * bits, for example, in linux, andb instruction is used in clear_bit().
5640 if (!(offset & (pte_size - 1)) && bytes == 1)
5643 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5644 misaligned |= bytes < 4;
5649 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5651 unsigned page_offset, quadrant;
5655 page_offset = offset_in_page(gpa);
5656 level = sp->role.level;
5658 if (sp->role.has_4_byte_gpte) {
5659 page_offset <<= 1; /* 32->64 */
5661 * A 32-bit pde maps 4MB while the shadow pdes map
5662 * only 2MB. So we need to double the offset again
5663 * and zap two pdes instead of one.
5665 if (level == PT32_ROOT_LEVEL) {
5666 page_offset &= ~7; /* kill rounding error */
5670 quadrant = page_offset >> PAGE_SHIFT;
5671 page_offset &= ~PAGE_MASK;
5672 if (quadrant != sp->role.quadrant)
5676 spte = &sp->spt[page_offset / sizeof(*spte)];
5680 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5681 const u8 *new, int bytes,
5682 struct kvm_page_track_notifier_node *node)
5684 gfn_t gfn = gpa >> PAGE_SHIFT;
5685 struct kvm_mmu_page *sp;
5686 LIST_HEAD(invalid_list);
5687 u64 entry, gentry, *spte;
5692 * If we don't have indirect shadow pages, it means no page is
5693 * write-protected, so we can exit simply.
5695 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5698 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5700 write_lock(&vcpu->kvm->mmu_lock);
5702 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5704 ++vcpu->kvm->stat.mmu_pte_write;
5706 for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5707 if (detect_write_misaligned(sp, gpa, bytes) ||
5708 detect_write_flooding(sp)) {
5709 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5710 ++vcpu->kvm->stat.mmu_flooded;
5714 spte = get_written_sptes(sp, gpa, &npte);
5720 mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5721 if (gentry && sp->role.level != PG_LEVEL_4K)
5722 ++vcpu->kvm->stat.mmu_pde_zapped;
5723 if (is_shadow_present_pte(entry))
5728 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5729 write_unlock(&vcpu->kvm->mmu_lock);
5732 int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5733 void *insn, int insn_len)
5735 int r, emulation_type = EMULTYPE_PF;
5736 bool direct = vcpu->arch.mmu->root_role.direct;
5738 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5739 return RET_PF_RETRY;
5742 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5743 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5744 if (r == RET_PF_EMULATE)
5748 if (r == RET_PF_INVALID) {
5749 r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5750 lower_32_bits(error_code), false,
5752 if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
5758 if (r != RET_PF_EMULATE)
5762 * Before emulating the instruction, check if the error code
5763 * was due to a RO violation while translating the guest page.
5764 * This can occur when using nested virtualization with nested
5765 * paging in both guests. If true, we simply unprotect the page
5766 * and resume the guest.
5768 if (vcpu->arch.mmu->root_role.direct &&
5769 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5770 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5775 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5776 * optimistically try to just unprotect the page and let the processor
5777 * re-execute the instruction that caused the page fault. Do not allow
5778 * retrying MMIO emulation, as it's not only pointless but could also
5779 * cause us to enter an infinite loop because the processor will keep
5780 * faulting on the non-existent MMIO address. Retrying an instruction
5781 * from a nested guest is also pointless and dangerous as we are only
5782 * explicitly shadowing L1's page tables, i.e. unprotecting something
5783 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5785 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5786 emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5788 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5791 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5793 static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5794 u64 addr, hpa_t root_hpa)
5796 struct kvm_shadow_walk_iterator iterator;
5798 vcpu_clear_mmio_info(vcpu, addr);
5800 if (!VALID_PAGE(root_hpa))
5803 write_lock(&vcpu->kvm->mmu_lock);
5804 for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
5805 struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
5808 int ret = kvm_sync_spte(vcpu, sp, iterator.index);
5811 mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
5813 kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
5816 if (!sp->unsync_children)
5819 write_unlock(&vcpu->kvm->mmu_lock);
5822 void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5823 u64 addr, unsigned long roots)
5827 WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
5829 /* It's actually a GPA for vcpu->arch.guest_mmu. */
5830 if (mmu != &vcpu->arch.guest_mmu) {
5831 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
5832 if (is_noncanonical_address(addr, vcpu))
5835 static_call(kvm_x86_flush_tlb_gva)(vcpu, addr);
5838 if (!mmu->sync_spte)
5841 if (roots & KVM_MMU_ROOT_CURRENT)
5842 __kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
5844 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5845 if (roots & KVM_MMU_ROOT_PREVIOUS(i))
5846 __kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
5849 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
5851 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5854 * INVLPG is required to invalidate any global mappings for the VA,
5855 * irrespective of PCID. Blindly sync all roots as it would take
5856 * roughly the same amount of work/time to determine whether any of the
5857 * previous roots have a global mapping.
5859 * Mappings not reachable via the current or previous cached roots will
5860 * be synced when switching to that new cr3, so nothing needs to be
5861 * done here for them.
5863 kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
5864 ++vcpu->stat.invlpg;
5866 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5869 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5871 struct kvm_mmu *mmu = vcpu->arch.mmu;
5872 unsigned long roots = 0;
5875 if (pcid == kvm_get_active_pcid(vcpu))
5876 roots |= KVM_MMU_ROOT_CURRENT;
5878 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5879 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5880 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
5881 roots |= KVM_MMU_ROOT_PREVIOUS(i);
5885 kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
5886 ++vcpu->stat.invlpg;
5889 * Mappings not reachable via the current cr3 or the prev_roots will be
5890 * synced when switching to that cr3, so nothing needs to be done here
5895 void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5896 int tdp_max_root_level, int tdp_huge_page_level)
5898 tdp_enabled = enable_tdp;
5899 tdp_root_level = tdp_forced_root_level;
5900 max_tdp_level = tdp_max_root_level;
5902 #ifdef CONFIG_X86_64
5903 tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
5906 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5907 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5908 * the kernel is not. But, KVM never creates a page size greater than
5909 * what is used by the kernel for any given HVA, i.e. the kernel's
5910 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5913 max_huge_page_level = tdp_huge_page_level;
5914 else if (boot_cpu_has(X86_FEATURE_GBPAGES))
5915 max_huge_page_level = PG_LEVEL_1G;
5917 max_huge_page_level = PG_LEVEL_2M;
5919 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5921 /* The return value indicates if tlb flush on all vcpus is needed. */
5922 typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
5923 struct kvm_rmap_head *rmap_head,
5924 const struct kvm_memory_slot *slot);
5926 static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
5927 const struct kvm_memory_slot *slot,
5928 slot_rmaps_handler fn,
5929 int start_level, int end_level,
5930 gfn_t start_gfn, gfn_t end_gfn,
5931 bool flush_on_yield, bool flush)
5933 struct slot_rmap_walk_iterator iterator;
5935 lockdep_assert_held_write(&kvm->mmu_lock);
5937 for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
5938 end_gfn, &iterator) {
5940 flush |= fn(kvm, iterator.rmap, slot);
5942 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5943 if (flush && flush_on_yield) {
5944 kvm_flush_remote_tlbs_range(kvm, start_gfn,
5945 iterator.gfn - start_gfn + 1);
5948 cond_resched_rwlock_write(&kvm->mmu_lock);
5955 static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
5956 const struct kvm_memory_slot *slot,
5957 slot_rmaps_handler fn,
5958 int start_level, int end_level,
5959 bool flush_on_yield)
5961 return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
5962 slot->base_gfn, slot->base_gfn + slot->npages - 1,
5963 flush_on_yield, false);
5966 static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
5967 const struct kvm_memory_slot *slot,
5968 slot_rmaps_handler fn,
5969 bool flush_on_yield)
5971 return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
5974 static void free_mmu_pages(struct kvm_mmu *mmu)
5976 if (!tdp_enabled && mmu->pae_root)
5977 set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5978 free_page((unsigned long)mmu->pae_root);
5979 free_page((unsigned long)mmu->pml4_root);
5980 free_page((unsigned long)mmu->pml5_root);
5983 static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5988 mmu->root.hpa = INVALID_PAGE;
5990 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5991 mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5993 /* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
5994 if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
5998 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5999 * while the PDP table is a per-vCPU construct that's allocated at MMU
6000 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
6001 * x86_64. Therefore we need to allocate the PDP table in the first
6002 * 4GB of memory, which happens to fit the DMA32 zone. TDP paging
6003 * generally doesn't use PAE paging and can skip allocating the PDP
6004 * table. The main exception, handled here, is SVM's 32-bit NPT. The
6005 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
6006 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
6008 if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
6011 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
6015 mmu->pae_root = page_address(page);
6018 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
6019 * get the CPU to treat the PDPTEs as encrypted. Decrypt the page so
6020 * that KVM's writes and the CPU's reads get along. Note, this is
6021 * only necessary when using shadow paging, as 64-bit NPT can get at
6022 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
6023 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
6026 set_memory_decrypted((unsigned long)mmu->pae_root, 1);
6028 WARN_ON_ONCE(shadow_me_value);
6030 for (i = 0; i < 4; ++i)
6031 mmu->pae_root[i] = INVALID_PAE_ROOT;
6036 int kvm_mmu_create(struct kvm_vcpu *vcpu)
6040 vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
6041 vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
6043 vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
6044 vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
6046 vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
6048 vcpu->arch.mmu = &vcpu->arch.root_mmu;
6049 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6051 ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6055 ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6057 goto fail_allocate_root;
6061 free_mmu_pages(&vcpu->arch.guest_mmu);
6065 #define BATCH_ZAP_PAGES 10
6066 static void kvm_zap_obsolete_pages(struct kvm *kvm)
6068 struct kvm_mmu_page *sp, *node;
6069 int nr_zapped, batch = 0;
6073 list_for_each_entry_safe_reverse(sp, node,
6074 &kvm->arch.active_mmu_pages, link) {
6076 * No obsolete valid page exists before a newly created page
6077 * since active_mmu_pages is a FIFO list.
6079 if (!is_obsolete_sp(kvm, sp))
6083 * Invalid pages should never land back on the list of active
6084 * pages. Skip the bogus page, otherwise we'll get stuck in an
6085 * infinite loop if the page gets put back on the list (again).
6087 if (WARN_ON(sp->role.invalid))
6091 * No need to flush the TLB since we're only zapping shadow
6092 * pages with an obsolete generation number and all vCPUS have
6093 * loaded a new root, i.e. the shadow pages being zapped cannot
6094 * be in active use by the guest.
6096 if (batch >= BATCH_ZAP_PAGES &&
6097 cond_resched_rwlock_write(&kvm->mmu_lock)) {
6102 unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6103 &kvm->arch.zapped_obsolete_pages, &nr_zapped);
6111 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
6112 * to ensure KVM is not in the middle of a lockless shadow page table
6113 * walk, which may reference the pages. The remote TLB flush itself is
6114 * not required and is simply a convenient way to kick vCPUs as needed.
6115 * KVM performs a local TLB flush when allocating a new root (see
6116 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
6117 * running with an obsolete MMU.
6119 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6123 * Fast invalidate all shadow pages and use lock-break technique
6124 * to zap obsolete pages.
6126 * It's required when memslot is being deleted or VM is being
6127 * destroyed, in these cases, we should ensure that KVM MMU does
6128 * not use any resource of the being-deleted slot or all slots
6129 * after calling the function.
6131 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6133 lockdep_assert_held(&kvm->slots_lock);
6135 write_lock(&kvm->mmu_lock);
6136 trace_kvm_mmu_zap_all_fast(kvm);
6139 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
6140 * held for the entire duration of zapping obsolete pages, it's
6141 * impossible for there to be multiple invalid generations associated
6142 * with *valid* shadow pages at any given time, i.e. there is exactly
6143 * one valid generation and (at most) one invalid generation.
6145 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6148 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
6149 * invalidating TDP MMU roots must be done while holding mmu_lock for
6150 * write and in the same critical section as making the reload request,
6151 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6153 if (tdp_mmu_enabled)
6154 kvm_tdp_mmu_invalidate_all_roots(kvm);
6157 * Notify all vcpus to reload its shadow page table and flush TLB.
6158 * Then all vcpus will switch to new shadow page table with the new
6161 * Note: we need to do this under the protection of mmu_lock,
6162 * otherwise, vcpu would purge shadow page but miss tlb flush.
6164 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6166 kvm_zap_obsolete_pages(kvm);
6168 write_unlock(&kvm->mmu_lock);
6171 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6172 * returning to the caller, e.g. if the zap is in response to a memslot
6173 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6174 * associated with the deleted memslot once the update completes, and
6175 * Deferring the zap until the final reference to the root is put would
6176 * lead to use-after-free.
6178 if (tdp_mmu_enabled)
6179 kvm_tdp_mmu_zap_invalidated_roots(kvm);
6182 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6184 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6187 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
6188 struct kvm_memory_slot *slot,
6189 struct kvm_page_track_notifier_node *node)
6191 kvm_mmu_zap_all_fast(kvm);
6194 int kvm_mmu_init_vm(struct kvm *kvm)
6196 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6199 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6200 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
6201 INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6202 spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6204 if (tdp_mmu_enabled) {
6205 r = kvm_mmu_init_tdp_mmu(kvm);
6210 node->track_write = kvm_mmu_pte_write;
6211 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
6212 kvm_page_track_register_notifier(kvm, node);
6214 kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6215 kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6217 kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6219 kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6220 kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6225 static void mmu_free_vm_memory_caches(struct kvm *kvm)
6227 kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6228 kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6229 kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6232 void kvm_mmu_uninit_vm(struct kvm *kvm)
6234 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6236 kvm_page_track_unregister_notifier(kvm, node);
6238 if (tdp_mmu_enabled)
6239 kvm_mmu_uninit_tdp_mmu(kvm);
6241 mmu_free_vm_memory_caches(kvm);
6244 static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6246 const struct kvm_memory_slot *memslot;
6247 struct kvm_memslots *slots;
6248 struct kvm_memslot_iter iter;
6253 if (!kvm_memslots_have_rmaps(kvm))
6256 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6257 slots = __kvm_memslots(kvm, i);
6259 kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6260 memslot = iter.slot;
6261 start = max(gfn_start, memslot->base_gfn);
6262 end = min(gfn_end, memslot->base_gfn + memslot->npages);
6263 if (WARN_ON_ONCE(start >= end))
6266 flush = __walk_slot_rmaps(kvm, memslot, __kvm_zap_rmap,
6267 PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
6268 start, end - 1, true, flush);
6276 * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
6277 * (not including it)
6279 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6284 if (WARN_ON_ONCE(gfn_end <= gfn_start))
6287 write_lock(&kvm->mmu_lock);
6289 kvm_mmu_invalidate_begin(kvm, 0, -1ul);
6291 flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
6293 if (tdp_mmu_enabled) {
6294 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
6295 flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
6296 gfn_end, true, flush);
6300 kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
6302 kvm_mmu_invalidate_end(kvm, 0, -1ul);
6304 write_unlock(&kvm->mmu_lock);
6307 static bool slot_rmap_write_protect(struct kvm *kvm,
6308 struct kvm_rmap_head *rmap_head,
6309 const struct kvm_memory_slot *slot)
6311 return rmap_write_protect(rmap_head, false);
6314 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6315 const struct kvm_memory_slot *memslot,
6318 if (kvm_memslots_have_rmaps(kvm)) {
6319 write_lock(&kvm->mmu_lock);
6320 walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6321 start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6322 write_unlock(&kvm->mmu_lock);
6325 if (tdp_mmu_enabled) {
6326 read_lock(&kvm->mmu_lock);
6327 kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
6328 read_unlock(&kvm->mmu_lock);
6332 static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6334 return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6337 static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6339 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6343 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6344 * to split a single huge page. Calculating how many are actually needed
6345 * is possible but not worth the complexity.
6347 return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6348 need_topup(&kvm->arch.split_page_header_cache, 1) ||
6349 need_topup(&kvm->arch.split_shadow_page_cache, 1);
6352 static int topup_split_caches(struct kvm *kvm)
6355 * Allocating rmap list entries when splitting huge pages for nested
6356 * MMUs is uncommon as KVM needs to use a list if and only if there is
6357 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6358 * aliased by multiple L2 gfns and/or from multiple nested roots with
6359 * different roles. Aliasing gfns when using TDP is atypical for VMMs;
6360 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6361 * but aliasing rarely occurs post-boot or for many gfns. If there is
6362 * only one rmap entry, rmap->val points directly at that one entry and
6363 * doesn't need to allocate a list. Buffer the cache by the default
6364 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6365 * encounters an aliased gfn or two.
6367 const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6368 KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6371 lockdep_assert_held(&kvm->slots_lock);
6373 r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6374 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6378 r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6382 return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6385 static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6387 struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6388 struct shadow_page_caches caches = {};
6389 union kvm_mmu_page_role role;
6390 unsigned int access;
6393 gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6394 access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6397 * Note, huge page splitting always uses direct shadow pages, regardless
6398 * of whether the huge page itself is mapped by a direct or indirect
6399 * shadow page, since the huge page region itself is being directly
6400 * mapped with smaller pages.
6402 role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6404 /* Direct SPs do not require a shadowed_info_cache. */
6405 caches.page_header_cache = &kvm->arch.split_page_header_cache;
6406 caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6408 /* Safe to pass NULL for vCPU since requesting a direct SP. */
6409 return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6412 static void shadow_mmu_split_huge_page(struct kvm *kvm,
6413 const struct kvm_memory_slot *slot,
6417 struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6418 u64 huge_spte = READ_ONCE(*huge_sptep);
6419 struct kvm_mmu_page *sp;
6425 sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6427 for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6428 sptep = &sp->spt[index];
6429 gfn = kvm_mmu_page_get_gfn(sp, index);
6432 * The SP may already have populated SPTEs, e.g. if this huge
6433 * page is aliased by multiple sptes with the same access
6434 * permissions. These entries are guaranteed to map the same
6435 * gfn-to-pfn translation since the SP is direct, so no need to
6438 * However, if a given SPTE points to a lower level page table,
6439 * that lower level page table may only be partially populated.
6440 * Installing such SPTEs would effectively unmap a potion of the
6441 * huge page. Unmapping guest memory always requires a TLB flush
6442 * since a subsequent operation on the unmapped regions would
6443 * fail to detect the need to flush.
6445 if (is_shadow_present_pte(*sptep)) {
6446 flush |= !is_last_spte(*sptep, sp->role.level);
6450 spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6451 mmu_spte_set(sptep, spte);
6452 __rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6455 __link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6458 static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6459 const struct kvm_memory_slot *slot,
6462 struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6467 /* Grab information for the tracepoint before dropping the MMU lock. */
6468 gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6469 level = huge_sp->role.level;
6472 if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6477 if (need_topup_split_caches_or_resched(kvm)) {
6478 write_unlock(&kvm->mmu_lock);
6481 * If the topup succeeds, return -EAGAIN to indicate that the
6482 * rmap iterator should be restarted because the MMU lock was
6485 r = topup_split_caches(kvm) ?: -EAGAIN;
6486 write_lock(&kvm->mmu_lock);
6490 shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6493 trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6497 static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6498 struct kvm_rmap_head *rmap_head,
6499 const struct kvm_memory_slot *slot)
6501 struct rmap_iterator iter;
6502 struct kvm_mmu_page *sp;
6507 for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6508 sp = sptep_to_sp(huge_sptep);
6510 /* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6511 if (WARN_ON_ONCE(!sp->role.guest_mode))
6514 /* The rmaps should never contain non-leaf SPTEs. */
6515 if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6518 /* SPs with level >PG_LEVEL_4K should never by unsync. */
6519 if (WARN_ON_ONCE(sp->unsync))
6522 /* Don't bother splitting huge pages on invalid SPs. */
6523 if (sp->role.invalid)
6526 r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6529 * The split succeeded or needs to be retried because the MMU
6530 * lock was dropped. Either way, restart the iterator to get it
6531 * back into a consistent state.
6533 if (!r || r == -EAGAIN)
6536 /* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6543 static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6544 const struct kvm_memory_slot *slot,
6545 gfn_t start, gfn_t end,
6551 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6552 * down to the target level. This ensures pages are recursively split
6553 * all the way to the target level. There's no need to split pages
6554 * already at the target level.
6556 for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
6557 __walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
6558 level, level, start, end - 1, true, false);
6561 /* Must be called with the mmu_lock held in write-mode. */
6562 void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6563 const struct kvm_memory_slot *memslot,
6567 if (!tdp_mmu_enabled)
6570 if (kvm_memslots_have_rmaps(kvm))
6571 kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6573 kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6576 * A TLB flush is unnecessary at this point for the same resons as in
6577 * kvm_mmu_slot_try_split_huge_pages().
6581 void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6582 const struct kvm_memory_slot *memslot,
6585 u64 start = memslot->base_gfn;
6586 u64 end = start + memslot->npages;
6588 if (!tdp_mmu_enabled)
6591 if (kvm_memslots_have_rmaps(kvm)) {
6592 write_lock(&kvm->mmu_lock);
6593 kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6594 write_unlock(&kvm->mmu_lock);
6597 read_lock(&kvm->mmu_lock);
6598 kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6599 read_unlock(&kvm->mmu_lock);
6602 * No TLB flush is necessary here. KVM will flush TLBs after
6603 * write-protecting and/or clearing dirty on the newly split SPTEs to
6604 * ensure that guest writes are reflected in the dirty log before the
6605 * ioctl to enable dirty logging on this memslot completes. Since the
6606 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6607 * safe for KVM to decide if a TLB flush is necessary based on the split
6612 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
6613 struct kvm_rmap_head *rmap_head,
6614 const struct kvm_memory_slot *slot)
6617 struct rmap_iterator iter;
6618 int need_tlb_flush = 0;
6619 struct kvm_mmu_page *sp;
6622 for_each_rmap_spte(rmap_head, &iter, sptep) {
6623 sp = sptep_to_sp(sptep);
6626 * We cannot do huge page mapping for indirect shadow pages,
6627 * which are found on the last rmap (level = 1) when not using
6628 * tdp; such shadow pages are synced with the page table in
6629 * the guest, and the guest page table is using 4K page size
6630 * mapping if the indirect sp has level = 1.
6632 if (sp->role.direct &&
6633 sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6635 kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6637 if (kvm_available_flush_remote_tlbs_range())
6638 kvm_flush_remote_tlbs_sptep(kvm, sptep);
6646 return need_tlb_flush;
6649 static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
6650 const struct kvm_memory_slot *slot)
6653 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
6654 * pages that are already mapped at the maximum hugepage level.
6656 if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
6657 PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
6658 kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
6661 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6662 const struct kvm_memory_slot *slot)
6664 if (kvm_memslots_have_rmaps(kvm)) {
6665 write_lock(&kvm->mmu_lock);
6666 kvm_rmap_zap_collapsible_sptes(kvm, slot);
6667 write_unlock(&kvm->mmu_lock);
6670 if (tdp_mmu_enabled) {
6671 read_lock(&kvm->mmu_lock);
6672 kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
6673 read_unlock(&kvm->mmu_lock);
6677 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
6678 const struct kvm_memory_slot *memslot)
6681 * All current use cases for flushing the TLBs for a specific memslot
6682 * related to dirty logging, and many do the TLB flush out of mmu_lock.
6683 * The interaction between the various operations on memslot must be
6684 * serialized by slots_locks to ensure the TLB flush from one operation
6685 * is observed by any other operation on the same memslot.
6687 lockdep_assert_held(&kvm->slots_lock);
6688 kvm_flush_remote_tlbs_range(kvm, memslot->base_gfn, memslot->npages);
6691 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6692 const struct kvm_memory_slot *memslot)
6694 if (kvm_memslots_have_rmaps(kvm)) {
6695 write_lock(&kvm->mmu_lock);
6697 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6698 * support dirty logging at a 4k granularity.
6700 walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
6701 write_unlock(&kvm->mmu_lock);
6704 if (tdp_mmu_enabled) {
6705 read_lock(&kvm->mmu_lock);
6706 kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
6707 read_unlock(&kvm->mmu_lock);
6711 * The caller will flush the TLBs after this function returns.
6713 * It's also safe to flush TLBs out of mmu lock here as currently this
6714 * function is only used for dirty logging, in which case flushing TLB
6715 * out of mmu lock also guarantees no dirty pages will be lost in
6720 void kvm_mmu_zap_all(struct kvm *kvm)
6722 struct kvm_mmu_page *sp, *node;
6723 LIST_HEAD(invalid_list);
6726 write_lock(&kvm->mmu_lock);
6728 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6729 if (WARN_ON(sp->role.invalid))
6731 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6733 if (cond_resched_rwlock_write(&kvm->mmu_lock))
6737 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6739 if (tdp_mmu_enabled)
6740 kvm_tdp_mmu_zap_all(kvm);
6742 write_unlock(&kvm->mmu_lock);
6745 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6747 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6749 gen &= MMIO_SPTE_GEN_MASK;
6752 * Generation numbers are incremented in multiples of the number of
6753 * address spaces in order to provide unique generations across all
6754 * address spaces. Strip what is effectively the address space
6755 * modifier prior to checking for a wrap of the MMIO generation so
6756 * that a wrap in any address space is detected.
6758 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6761 * The very rare case: if the MMIO generation number has wrapped,
6762 * zap all shadow pages.
6764 if (unlikely(gen == 0)) {
6765 kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
6766 kvm_mmu_zap_all_fast(kvm);
6770 static unsigned long mmu_shrink_scan(struct shrinker *shrink,
6771 struct shrink_control *sc)
6774 int nr_to_scan = sc->nr_to_scan;
6775 unsigned long freed = 0;
6777 mutex_lock(&kvm_lock);
6779 list_for_each_entry(kvm, &vm_list, vm_list) {
6781 LIST_HEAD(invalid_list);
6784 * Never scan more than sc->nr_to_scan VM instances.
6785 * Will not hit this condition practically since we do not try
6786 * to shrink more than one VM and it is very unlikely to see
6787 * !n_used_mmu_pages so many times.
6792 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6793 * here. We may skip a VM instance errorneosly, but we do not
6794 * want to shrink a VM that only started to populate its MMU
6797 if (!kvm->arch.n_used_mmu_pages &&
6798 !kvm_has_zapped_obsolete_pages(kvm))
6801 idx = srcu_read_lock(&kvm->srcu);
6802 write_lock(&kvm->mmu_lock);
6804 if (kvm_has_zapped_obsolete_pages(kvm)) {
6805 kvm_mmu_commit_zap_page(kvm,
6806 &kvm->arch.zapped_obsolete_pages);
6810 freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6813 write_unlock(&kvm->mmu_lock);
6814 srcu_read_unlock(&kvm->srcu, idx);
6817 * unfair on small ones
6818 * per-vm shrinkers cry out
6819 * sadness comes quickly
6821 list_move_tail(&kvm->vm_list, &vm_list);
6825 mutex_unlock(&kvm_lock);
6829 static unsigned long mmu_shrink_count(struct shrinker *shrink,
6830 struct shrink_control *sc)
6832 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6835 static struct shrinker mmu_shrinker = {
6836 .count_objects = mmu_shrink_count,
6837 .scan_objects = mmu_shrink_scan,
6838 .seeks = DEFAULT_SEEKS * 10,
6841 static void mmu_destroy_caches(void)
6843 kmem_cache_destroy(pte_list_desc_cache);
6844 kmem_cache_destroy(mmu_page_header_cache);
6847 static bool get_nx_auto_mode(void)
6849 /* Return true when CPU has the bug, and mitigations are ON */
6850 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6853 static void __set_nx_huge_pages(bool val)
6855 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6858 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6860 bool old_val = nx_huge_pages;
6863 /* In "auto" mode deploy workaround only if CPU has the bug. */
6864 if (sysfs_streq(val, "off"))
6866 else if (sysfs_streq(val, "force"))
6868 else if (sysfs_streq(val, "auto"))
6869 new_val = get_nx_auto_mode();
6870 else if (kstrtobool(val, &new_val) < 0)
6873 __set_nx_huge_pages(new_val);
6875 if (new_val != old_val) {
6878 mutex_lock(&kvm_lock);
6880 list_for_each_entry(kvm, &vm_list, vm_list) {
6881 mutex_lock(&kvm->slots_lock);
6882 kvm_mmu_zap_all_fast(kvm);
6883 mutex_unlock(&kvm->slots_lock);
6885 wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6887 mutex_unlock(&kvm_lock);
6894 * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
6895 * its default value of -1 is technically undefined behavior for a boolean.
6896 * Forward the module init call to SPTE code so that it too can handle module
6897 * params that need to be resolved/snapshot.
6899 void __init kvm_mmu_x86_module_init(void)
6901 if (nx_huge_pages == -1)
6902 __set_nx_huge_pages(get_nx_auto_mode());
6905 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
6906 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
6907 * when the vendor module is loaded.
6909 tdp_mmu_allowed = tdp_mmu_enabled;
6911 kvm_mmu_spte_module_init();
6915 * The bulk of the MMU initialization is deferred until the vendor module is
6916 * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
6917 * to be reset when a potentially different vendor module is loaded.
6919 int kvm_mmu_vendor_module_init(void)
6924 * MMU roles use union aliasing which is, generally speaking, an
6925 * undefined behavior. However, we supposedly know how compilers behave
6926 * and the current status quo is unlikely to change. Guardians below are
6927 * supposed to let us know if the assumption becomes false.
6929 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6930 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6931 BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
6933 kvm_mmu_reset_all_pte_masks();
6935 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6936 sizeof(struct pte_list_desc),
6937 0, SLAB_ACCOUNT, NULL);
6938 if (!pte_list_desc_cache)
6941 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6942 sizeof(struct kvm_mmu_page),
6943 0, SLAB_ACCOUNT, NULL);
6944 if (!mmu_page_header_cache)
6947 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6950 ret = register_shrinker(&mmu_shrinker, "x86-mmu");
6957 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6959 mmu_destroy_caches();
6963 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6965 kvm_mmu_unload(vcpu);
6966 free_mmu_pages(&vcpu->arch.root_mmu);
6967 free_mmu_pages(&vcpu->arch.guest_mmu);
6968 mmu_free_memory_caches(vcpu);
6971 void kvm_mmu_vendor_module_exit(void)
6973 mmu_destroy_caches();
6974 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6975 unregister_shrinker(&mmu_shrinker);
6979 * Calculate the effective recovery period, accounting for '0' meaning "let KVM
6980 * select a halving time of 1 hour". Returns true if recovery is enabled.
6982 static bool calc_nx_huge_pages_recovery_period(uint *period)
6985 * Use READ_ONCE to get the params, this may be called outside of the
6986 * param setters, e.g. by the kthread to compute its next timeout.
6988 bool enabled = READ_ONCE(nx_huge_pages);
6989 uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6991 if (!enabled || !ratio)
6994 *period = READ_ONCE(nx_huge_pages_recovery_period_ms);
6996 /* Make sure the period is not less than one second. */
6997 ratio = min(ratio, 3600u);
6998 *period = 60 * 60 * 1000 / ratio;
7003 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
7005 bool was_recovery_enabled, is_recovery_enabled;
7006 uint old_period, new_period;
7009 was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
7011 err = param_set_uint(val, kp);
7015 is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
7017 if (is_recovery_enabled &&
7018 (!was_recovery_enabled || old_period > new_period)) {
7021 mutex_lock(&kvm_lock);
7023 list_for_each_entry(kvm, &vm_list, vm_list)
7024 wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
7026 mutex_unlock(&kvm_lock);
7032 static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7034 unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7035 struct kvm_memory_slot *slot;
7037 struct kvm_mmu_page *sp;
7039 LIST_HEAD(invalid_list);
7043 rcu_idx = srcu_read_lock(&kvm->srcu);
7044 write_lock(&kvm->mmu_lock);
7047 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7048 * be done under RCU protection, because the pages are freed via RCU
7053 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7054 to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
7055 for ( ; to_zap; --to_zap) {
7056 if (list_empty(&kvm->arch.possible_nx_huge_pages))
7060 * We use a separate list instead of just using active_mmu_pages
7061 * because the number of shadow pages that be replaced with an
7062 * NX huge page is expected to be relatively small compared to
7063 * the total number of shadow pages. And because the TDP MMU
7064 * doesn't use active_mmu_pages.
7066 sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7067 struct kvm_mmu_page,
7068 possible_nx_huge_page_link);
7069 WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7070 WARN_ON_ONCE(!sp->role.direct);
7073 * Unaccount and do not attempt to recover any NX Huge Pages
7074 * that are being dirty tracked, as they would just be faulted
7075 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7076 * recovered, along with all the other huge pages in the slot,
7077 * when dirty logging is disabled.
7079 * Since gfn_to_memslot() is relatively expensive, it helps to
7080 * skip it if it the test cannot possibly return true. On the
7081 * other hand, if any memslot has logging enabled, chances are
7082 * good that all of them do, in which case unaccount_nx_huge_page()
7083 * is much cheaper than zapping the page.
7085 * If a memslot update is in progress, reading an incorrect value
7086 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
7087 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
7088 * it is becoming nonzero, the page will be zapped unnecessarily.
7089 * Either way, this only affects efficiency in racy situations,
7090 * and not correctness.
7093 if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7094 slot = gfn_to_memslot(kvm, sp->gfn);
7095 WARN_ON_ONCE(!slot);
7098 if (slot && kvm_slot_dirty_track_enabled(slot))
7099 unaccount_nx_huge_page(kvm, sp);
7100 else if (is_tdp_mmu_page(sp))
7101 flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
7103 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7104 WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7106 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7107 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7110 cond_resched_rwlock_write(&kvm->mmu_lock);
7116 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7120 write_unlock(&kvm->mmu_lock);
7121 srcu_read_unlock(&kvm->srcu, rcu_idx);
7124 static long get_nx_huge_page_recovery_timeout(u64 start_time)
7129 enabled = calc_nx_huge_pages_recovery_period(&period);
7131 return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7132 : MAX_SCHEDULE_TIMEOUT;
7135 static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7138 long remaining_time;
7141 start_time = get_jiffies_64();
7142 remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7144 set_current_state(TASK_INTERRUPTIBLE);
7145 while (!kthread_should_stop() && remaining_time > 0) {
7146 schedule_timeout(remaining_time);
7147 remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7148 set_current_state(TASK_INTERRUPTIBLE);
7151 set_current_state(TASK_RUNNING);
7153 if (kthread_should_stop())
7156 kvm_recover_nx_huge_pages(kvm);
7160 int kvm_mmu_post_init_vm(struct kvm *kvm)
7164 err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7165 "kvm-nx-lpage-recovery",
7166 &kvm->arch.nx_huge_page_recovery_thread);
7168 kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7173 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7175 if (kvm->arch.nx_huge_page_recovery_thread)
7176 kthread_stop(kvm->arch.nx_huge_page_recovery_thread);