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.
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Avi Kivity <avi@qumranet.com>
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 inline bool kvm_available_flush_tlb_with_range(void)
261 return kvm_x86_ops.tlb_remote_flush_with_range;
264 void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t start_gfn,
267 struct kvm_tlb_range range;
268 int ret = -EOPNOTSUPP;
270 range.start_gfn = start_gfn;
271 range.pages = nr_pages;
273 if (kvm_x86_ops.tlb_remote_flush_with_range)
274 ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, &range);
277 kvm_flush_remote_tlbs(kvm);
280 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
282 /* Flush the range of guest memory mapped by the given SPTE. */
283 static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
285 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
286 gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
288 kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
291 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
294 u64 spte = make_mmio_spte(vcpu, gfn, access);
296 trace_mark_mmio_spte(sptep, gfn, spte);
297 mmu_spte_set(sptep, spte);
300 static gfn_t get_mmio_spte_gfn(u64 spte)
302 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
304 gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
305 & shadow_nonpresent_or_rsvd_mask;
307 return gpa >> PAGE_SHIFT;
310 static unsigned get_mmio_spte_access(u64 spte)
312 return spte & shadow_mmio_access_mask;
315 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
317 u64 kvm_gen, spte_gen, gen;
319 gen = kvm_vcpu_memslots(vcpu)->generation;
320 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
323 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
324 spte_gen = get_mmio_spte_generation(spte);
326 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
327 return likely(kvm_gen == spte_gen);
330 static int is_cpuid_PSE36(void)
336 static void __set_spte(u64 *sptep, u64 spte)
338 WRITE_ONCE(*sptep, spte);
341 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
343 WRITE_ONCE(*sptep, spte);
346 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
348 return xchg(sptep, spte);
351 static u64 __get_spte_lockless(u64 *sptep)
353 return READ_ONCE(*sptep);
364 static void count_spte_clear(u64 *sptep, u64 spte)
366 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
368 if (is_shadow_present_pte(spte))
371 /* Ensure the spte is completely set before we increase the count */
373 sp->clear_spte_count++;
376 static void __set_spte(u64 *sptep, u64 spte)
378 union split_spte *ssptep, sspte;
380 ssptep = (union split_spte *)sptep;
381 sspte = (union split_spte)spte;
383 ssptep->spte_high = sspte.spte_high;
386 * If we map the spte from nonpresent to present, We should store
387 * the high bits firstly, then set present bit, so cpu can not
388 * fetch this spte while we are setting the spte.
392 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
395 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
397 union split_spte *ssptep, sspte;
399 ssptep = (union split_spte *)sptep;
400 sspte = (union split_spte)spte;
402 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
405 * If we map the spte from present to nonpresent, we should clear
406 * present bit firstly to avoid vcpu fetch the old high bits.
410 ssptep->spte_high = sspte.spte_high;
411 count_spte_clear(sptep, spte);
414 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
416 union split_spte *ssptep, sspte, orig;
418 ssptep = (union split_spte *)sptep;
419 sspte = (union split_spte)spte;
421 /* xchg acts as a barrier before the setting of the high bits */
422 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
423 orig.spte_high = ssptep->spte_high;
424 ssptep->spte_high = sspte.spte_high;
425 count_spte_clear(sptep, spte);
431 * The idea using the light way get the spte on x86_32 guest is from
432 * gup_get_pte (mm/gup.c).
434 * An spte tlb flush may be pending, because kvm_set_pte_rmap
435 * coalesces them and we are running out of the MMU lock. Therefore
436 * we need to protect against in-progress updates of the spte.
438 * Reading the spte while an update is in progress may get the old value
439 * for the high part of the spte. The race is fine for a present->non-present
440 * change (because the high part of the spte is ignored for non-present spte),
441 * but for a present->present change we must reread the spte.
443 * All such changes are done in two steps (present->non-present and
444 * non-present->present), hence it is enough to count the number of
445 * present->non-present updates: if it changed while reading the spte,
446 * we might have hit the race. This is done using clear_spte_count.
448 static u64 __get_spte_lockless(u64 *sptep)
450 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
451 union split_spte spte, *orig = (union split_spte *)sptep;
455 count = sp->clear_spte_count;
458 spte.spte_low = orig->spte_low;
461 spte.spte_high = orig->spte_high;
464 if (unlikely(spte.spte_low != orig->spte_low ||
465 count != sp->clear_spte_count))
472 /* Rules for using mmu_spte_set:
473 * Set the sptep from nonpresent to present.
474 * Note: the sptep being assigned *must* be either not present
475 * or in a state where the hardware will not attempt to update
478 static void mmu_spte_set(u64 *sptep, u64 new_spte)
480 WARN_ON(is_shadow_present_pte(*sptep));
481 __set_spte(sptep, new_spte);
485 * Update the SPTE (excluding the PFN), but do not track changes in its
486 * accessed/dirty status.
488 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
490 u64 old_spte = *sptep;
492 WARN_ON(!is_shadow_present_pte(new_spte));
493 check_spte_writable_invariants(new_spte);
495 if (!is_shadow_present_pte(old_spte)) {
496 mmu_spte_set(sptep, new_spte);
500 if (!spte_has_volatile_bits(old_spte))
501 __update_clear_spte_fast(sptep, new_spte);
503 old_spte = __update_clear_spte_slow(sptep, new_spte);
505 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
510 /* Rules for using mmu_spte_update:
511 * Update the state bits, it means the mapped pfn is not changed.
513 * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
514 * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
515 * spte, even though the writable spte might be cached on a CPU's TLB.
517 * Returns true if the TLB needs to be flushed
519 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
522 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
524 if (!is_shadow_present_pte(old_spte))
528 * For the spte updated out of mmu-lock is safe, since
529 * we always atomically update it, see the comments in
530 * spte_has_volatile_bits().
532 if (is_mmu_writable_spte(old_spte) &&
533 !is_writable_pte(new_spte))
537 * Flush TLB when accessed/dirty states are changed in the page tables,
538 * to guarantee consistency between TLB and page tables.
541 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
543 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
546 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
548 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
555 * Rules for using mmu_spte_clear_track_bits:
556 * It sets the sptep from present to nonpresent, and track the
557 * state bits, it is used to clear the last level sptep.
558 * Returns the old PTE.
560 static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
563 u64 old_spte = *sptep;
564 int level = sptep_to_sp(sptep)->role.level;
567 if (!is_shadow_present_pte(old_spte) ||
568 !spte_has_volatile_bits(old_spte))
569 __update_clear_spte_fast(sptep, 0ull);
571 old_spte = __update_clear_spte_slow(sptep, 0ull);
573 if (!is_shadow_present_pte(old_spte))
576 kvm_update_page_stats(kvm, level, -1);
578 pfn = spte_to_pfn(old_spte);
581 * KVM doesn't hold a reference to any pages mapped into the guest, and
582 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
583 * before they are reclaimed. Sanity check that, if the pfn is backed
584 * by a refcounted page, the refcount is elevated.
586 page = kvm_pfn_to_refcounted_page(pfn);
587 WARN_ON(page && !page_count(page));
589 if (is_accessed_spte(old_spte))
590 kvm_set_pfn_accessed(pfn);
592 if (is_dirty_spte(old_spte))
593 kvm_set_pfn_dirty(pfn);
599 * Rules for using mmu_spte_clear_no_track:
600 * Directly clear spte without caring the state bits of sptep,
601 * it is used to set the upper level spte.
603 static void mmu_spte_clear_no_track(u64 *sptep)
605 __update_clear_spte_fast(sptep, 0ull);
608 static u64 mmu_spte_get_lockless(u64 *sptep)
610 return __get_spte_lockless(sptep);
613 /* Returns the Accessed status of the PTE and resets it at the same time. */
614 static bool mmu_spte_age(u64 *sptep)
616 u64 spte = mmu_spte_get_lockless(sptep);
618 if (!is_accessed_spte(spte))
621 if (spte_ad_enabled(spte)) {
622 clear_bit((ffs(shadow_accessed_mask) - 1),
623 (unsigned long *)sptep);
626 * Capture the dirty status of the page, so that it doesn't get
627 * lost when the SPTE is marked for access tracking.
629 if (is_writable_pte(spte))
630 kvm_set_pfn_dirty(spte_to_pfn(spte));
632 spte = mark_spte_for_access_track(spte);
633 mmu_spte_update_no_track(sptep, spte);
639 static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
641 return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
644 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
646 if (is_tdp_mmu_active(vcpu)) {
647 kvm_tdp_mmu_walk_lockless_begin();
650 * Prevent page table teardown by making any free-er wait during
651 * kvm_flush_remote_tlbs() IPI to all active vcpus.
656 * Make sure a following spte read is not reordered ahead of the write
659 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
663 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
665 if (is_tdp_mmu_active(vcpu)) {
666 kvm_tdp_mmu_walk_lockless_end();
669 * Make sure the write to vcpu->mode is not reordered in front of
670 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
671 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
673 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
678 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
682 /* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
683 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
684 1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
687 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
688 PT64_ROOT_MAX_LEVEL);
691 if (maybe_indirect) {
692 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
693 PT64_ROOT_MAX_LEVEL);
697 return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
698 PT64_ROOT_MAX_LEVEL);
701 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
703 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
704 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
705 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
706 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
709 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
711 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
714 static bool sp_has_gptes(struct kvm_mmu_page *sp);
716 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
718 if (sp->role.passthrough)
721 if (!sp->role.direct)
722 return sp->shadowed_translation[index] >> PAGE_SHIFT;
724 return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
728 * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
729 * that the SPTE itself may have a more constrained access permissions that
730 * what the guest enforces. For example, a guest may create an executable
731 * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
733 static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
735 if (sp_has_gptes(sp))
736 return sp->shadowed_translation[index] & ACC_ALL;
739 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
740 * KVM is not shadowing any guest page tables, so the "guest access
741 * permissions" are just ACC_ALL.
743 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
744 * is shadowing a guest huge page with small pages, the guest access
745 * permissions being shadowed are the access permissions of the huge
748 * In both cases, sp->role.access contains the correct access bits.
750 return sp->role.access;
753 static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
754 gfn_t gfn, unsigned int access)
756 if (sp_has_gptes(sp)) {
757 sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
761 WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
762 "access mismatch under %s page %llx (expected %u, got %u)\n",
763 sp->role.passthrough ? "passthrough" : "direct",
764 sp->gfn, kvm_mmu_page_get_access(sp, index), access);
766 WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
767 "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
768 sp->role.passthrough ? "passthrough" : "direct",
769 sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
772 static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
775 gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
777 kvm_mmu_page_set_translation(sp, index, gfn, access);
781 * Return the pointer to the large page information for a given gfn,
782 * handling slots that are not large page aligned.
784 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
785 const struct kvm_memory_slot *slot, int level)
789 idx = gfn_to_index(gfn, slot->base_gfn, level);
790 return &slot->arch.lpage_info[level - 2][idx];
793 static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
794 gfn_t gfn, int count)
796 struct kvm_lpage_info *linfo;
799 for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
800 linfo = lpage_info_slot(gfn, slot, i);
801 linfo->disallow_lpage += count;
802 WARN_ON(linfo->disallow_lpage < 0);
806 void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
808 update_gfn_disallow_lpage_count(slot, gfn, 1);
811 void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
813 update_gfn_disallow_lpage_count(slot, gfn, -1);
816 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
818 struct kvm_memslots *slots;
819 struct kvm_memory_slot *slot;
822 kvm->arch.indirect_shadow_pages++;
824 slots = kvm_memslots_for_spte_role(kvm, sp->role);
825 slot = __gfn_to_memslot(slots, gfn);
827 /* the non-leaf shadow pages are keeping readonly. */
828 if (sp->role.level > PG_LEVEL_4K)
829 return kvm_slot_page_track_add_page(kvm, slot, gfn,
830 KVM_PAGE_TRACK_WRITE);
832 kvm_mmu_gfn_disallow_lpage(slot, gfn);
834 if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
835 kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
838 void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
841 * If it's possible to replace the shadow page with an NX huge page,
842 * i.e. if the shadow page is the only thing currently preventing KVM
843 * from using a huge page, add the shadow page to the list of "to be
844 * zapped for NX recovery" pages. Note, the shadow page can already be
845 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
846 * links a shadow page at multiple points.
848 if (!list_empty(&sp->possible_nx_huge_page_link))
851 ++kvm->stat.nx_lpage_splits;
852 list_add_tail(&sp->possible_nx_huge_page_link,
853 &kvm->arch.possible_nx_huge_pages);
856 static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
857 bool nx_huge_page_possible)
859 sp->nx_huge_page_disallowed = true;
861 if (nx_huge_page_possible)
862 track_possible_nx_huge_page(kvm, sp);
865 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
867 struct kvm_memslots *slots;
868 struct kvm_memory_slot *slot;
871 kvm->arch.indirect_shadow_pages--;
873 slots = kvm_memslots_for_spte_role(kvm, sp->role);
874 slot = __gfn_to_memslot(slots, gfn);
875 if (sp->role.level > PG_LEVEL_4K)
876 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
877 KVM_PAGE_TRACK_WRITE);
879 kvm_mmu_gfn_allow_lpage(slot, gfn);
882 void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
884 if (list_empty(&sp->possible_nx_huge_page_link))
887 --kvm->stat.nx_lpage_splits;
888 list_del_init(&sp->possible_nx_huge_page_link);
891 static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
893 sp->nx_huge_page_disallowed = false;
895 untrack_possible_nx_huge_page(kvm, sp);
898 static struct kvm_memory_slot *
899 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
902 struct kvm_memory_slot *slot;
904 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
905 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
907 if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
914 * About rmap_head encoding:
916 * If the bit zero of rmap_head->val is clear, then it points to the only spte
917 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
918 * pte_list_desc containing more mappings.
922 * Returns the number of pointers in the rmap chain, not counting the new one.
924 static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
925 struct kvm_rmap_head *rmap_head)
927 struct pte_list_desc *desc;
930 if (!rmap_head->val) {
931 rmap_printk("%p %llx 0->1\n", spte, *spte);
932 rmap_head->val = (unsigned long)spte;
933 } else if (!(rmap_head->val & 1)) {
934 rmap_printk("%p %llx 1->many\n", spte, *spte);
935 desc = kvm_mmu_memory_cache_alloc(cache);
936 desc->sptes[0] = (u64 *)rmap_head->val;
937 desc->sptes[1] = spte;
938 desc->spte_count = 2;
939 desc->tail_count = 0;
940 rmap_head->val = (unsigned long)desc | 1;
943 rmap_printk("%p %llx many->many\n", spte, *spte);
944 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
945 count = desc->tail_count + desc->spte_count;
948 * If the previous head is full, allocate a new head descriptor
949 * as tail descriptors are always kept full.
951 if (desc->spte_count == PTE_LIST_EXT) {
952 desc = kvm_mmu_memory_cache_alloc(cache);
953 desc->more = (struct pte_list_desc *)(rmap_head->val & ~1ul);
954 desc->spte_count = 0;
955 desc->tail_count = count;
956 rmap_head->val = (unsigned long)desc | 1;
958 desc->sptes[desc->spte_count++] = spte;
964 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
965 struct pte_list_desc *desc, int i)
967 struct pte_list_desc *head_desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
968 int j = head_desc->spte_count - 1;
971 * The head descriptor should never be empty. A new head is added only
972 * when adding an entry and the previous head is full, and heads are
973 * removed (this flow) when they become empty.
978 * Replace the to-be-freed SPTE with the last valid entry from the head
979 * descriptor to ensure that tail descriptors are full at all times.
980 * Note, this also means that tail_count is stable for each descriptor.
982 desc->sptes[i] = head_desc->sptes[j];
983 head_desc->sptes[j] = NULL;
984 head_desc->spte_count--;
985 if (head_desc->spte_count)
989 * The head descriptor is empty. If there are no tail descriptors,
990 * nullify the rmap head to mark the list as emtpy, else point the rmap
991 * head at the next descriptor, i.e. the new head.
993 if (!head_desc->more)
996 rmap_head->val = (unsigned long)head_desc->more | 1;
997 mmu_free_pte_list_desc(head_desc);
1000 static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1002 struct pte_list_desc *desc;
1005 if (!rmap_head->val) {
1006 pr_err("%s: %p 0->BUG\n", __func__, spte);
1008 } else if (!(rmap_head->val & 1)) {
1009 rmap_printk("%p 1->0\n", spte);
1010 if ((u64 *)rmap_head->val != spte) {
1011 pr_err("%s: %p 1->BUG\n", __func__, spte);
1016 rmap_printk("%p many->many\n", spte);
1017 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1019 for (i = 0; i < desc->spte_count; ++i) {
1020 if (desc->sptes[i] == spte) {
1021 pte_list_desc_remove_entry(rmap_head, desc, i);
1027 pr_err("%s: %p many->many\n", __func__, spte);
1032 static void kvm_zap_one_rmap_spte(struct kvm *kvm,
1033 struct kvm_rmap_head *rmap_head, u64 *sptep)
1035 mmu_spte_clear_track_bits(kvm, sptep);
1036 pte_list_remove(sptep, rmap_head);
1039 /* Return true if at least one SPTE was zapped, false otherwise */
1040 static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
1041 struct kvm_rmap_head *rmap_head)
1043 struct pte_list_desc *desc, *next;
1046 if (!rmap_head->val)
1049 if (!(rmap_head->val & 1)) {
1050 mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1054 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1056 for (; desc; desc = next) {
1057 for (i = 0; i < desc->spte_count; i++)
1058 mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1060 mmu_free_pte_list_desc(desc);
1063 /* rmap_head is meaningless now, remember to reset it */
1068 unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
1070 struct pte_list_desc *desc;
1072 if (!rmap_head->val)
1074 else if (!(rmap_head->val & 1))
1077 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1078 return desc->tail_count + desc->spte_count;
1081 static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1082 const struct kvm_memory_slot *slot)
1086 idx = gfn_to_index(gfn, slot->base_gfn, level);
1087 return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1090 static void rmap_remove(struct kvm *kvm, u64 *spte)
1092 struct kvm_memslots *slots;
1093 struct kvm_memory_slot *slot;
1094 struct kvm_mmu_page *sp;
1096 struct kvm_rmap_head *rmap_head;
1098 sp = sptep_to_sp(spte);
1099 gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1102 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
1103 * so we have to determine which memslots to use based on context
1104 * information in sp->role.
1106 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1108 slot = __gfn_to_memslot(slots, gfn);
1109 rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1111 pte_list_remove(spte, rmap_head);
1115 * Used by the following functions to iterate through the sptes linked by a
1116 * rmap. All fields are private and not assumed to be used outside.
1118 struct rmap_iterator {
1119 /* private fields */
1120 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1121 int pos; /* index of the sptep */
1125 * Iteration must be started by this function. This should also be used after
1126 * removing/dropping sptes from the rmap link because in such cases the
1127 * information in the iterator may not be valid.
1129 * Returns sptep if found, NULL otherwise.
1131 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1132 struct rmap_iterator *iter)
1136 if (!rmap_head->val)
1139 if (!(rmap_head->val & 1)) {
1141 sptep = (u64 *)rmap_head->val;
1145 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1147 sptep = iter->desc->sptes[iter->pos];
1149 BUG_ON(!is_shadow_present_pte(*sptep));
1154 * Must be used with a valid iterator: e.g. after rmap_get_first().
1156 * Returns sptep if found, NULL otherwise.
1158 static u64 *rmap_get_next(struct rmap_iterator *iter)
1163 if (iter->pos < PTE_LIST_EXT - 1) {
1165 sptep = iter->desc->sptes[iter->pos];
1170 iter->desc = iter->desc->more;
1174 /* desc->sptes[0] cannot be NULL */
1175 sptep = iter->desc->sptes[iter->pos];
1182 BUG_ON(!is_shadow_present_pte(*sptep));
1186 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1187 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1188 _spte_; _spte_ = rmap_get_next(_iter_))
1190 static void drop_spte(struct kvm *kvm, u64 *sptep)
1192 u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
1194 if (is_shadow_present_pte(old_spte))
1195 rmap_remove(kvm, sptep);
1198 static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1200 struct kvm_mmu_page *sp;
1202 sp = sptep_to_sp(sptep);
1203 WARN_ON(sp->role.level == PG_LEVEL_4K);
1205 drop_spte(kvm, sptep);
1208 kvm_flush_remote_tlbs_sptep(kvm, sptep);
1212 * Write-protect on the specified @sptep, @pt_protect indicates whether
1213 * spte write-protection is caused by protecting shadow page table.
1215 * Note: write protection is difference between dirty logging and spte
1217 * - for dirty logging, the spte can be set to writable at anytime if
1218 * its dirty bitmap is properly set.
1219 * - for spte protection, the spte can be writable only after unsync-ing
1222 * Return true if tlb need be flushed.
1224 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1228 if (!is_writable_pte(spte) &&
1229 !(pt_protect && is_mmu_writable_spte(spte)))
1232 rmap_printk("spte %p %llx\n", sptep, *sptep);
1235 spte &= ~shadow_mmu_writable_mask;
1236 spte = spte & ~PT_WRITABLE_MASK;
1238 return mmu_spte_update(sptep, spte);
1241 static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1245 struct rmap_iterator iter;
1248 for_each_rmap_spte(rmap_head, &iter, sptep)
1249 flush |= spte_write_protect(sptep, pt_protect);
1254 static bool spte_clear_dirty(u64 *sptep)
1258 rmap_printk("spte %p %llx\n", sptep, *sptep);
1260 MMU_WARN_ON(!spte_ad_enabled(spte));
1261 spte &= ~shadow_dirty_mask;
1262 return mmu_spte_update(sptep, spte);
1265 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1267 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1268 (unsigned long *)sptep);
1269 if (was_writable && !spte_ad_enabled(*sptep))
1270 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1272 return was_writable;
1276 * Gets the GFN ready for another round of dirty logging by clearing the
1277 * - D bit on ad-enabled SPTEs, and
1278 * - W bit on ad-disabled SPTEs.
1279 * Returns true iff any D or W bits were cleared.
1281 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1282 const struct kvm_memory_slot *slot)
1285 struct rmap_iterator iter;
1288 for_each_rmap_spte(rmap_head, &iter, sptep)
1289 if (spte_ad_need_write_protect(*sptep))
1290 flush |= spte_wrprot_for_clear_dirty(sptep);
1292 flush |= spte_clear_dirty(sptep);
1298 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1299 * @kvm: kvm instance
1300 * @slot: slot to protect
1301 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1302 * @mask: indicates which pages we should protect
1304 * Used when we do not need to care about huge page mappings.
1306 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1307 struct kvm_memory_slot *slot,
1308 gfn_t gfn_offset, unsigned long mask)
1310 struct kvm_rmap_head *rmap_head;
1312 if (tdp_mmu_enabled)
1313 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1314 slot->base_gfn + gfn_offset, mask, true);
1316 if (!kvm_memslots_have_rmaps(kvm))
1320 rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1322 rmap_write_protect(rmap_head, false);
1324 /* clear the first set bit */
1330 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1331 * protect the page if the D-bit isn't supported.
1332 * @kvm: kvm instance
1333 * @slot: slot to clear D-bit
1334 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1335 * @mask: indicates which pages we should clear D-bit
1337 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1339 static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1340 struct kvm_memory_slot *slot,
1341 gfn_t gfn_offset, unsigned long mask)
1343 struct kvm_rmap_head *rmap_head;
1345 if (tdp_mmu_enabled)
1346 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1347 slot->base_gfn + gfn_offset, mask, false);
1349 if (!kvm_memslots_have_rmaps(kvm))
1353 rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1355 __rmap_clear_dirty(kvm, rmap_head, slot);
1357 /* clear the first set bit */
1363 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1366 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1367 * enable dirty logging for them.
1369 * We need to care about huge page mappings: e.g. during dirty logging we may
1370 * have such mappings.
1372 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1373 struct kvm_memory_slot *slot,
1374 gfn_t gfn_offset, unsigned long mask)
1377 * Huge pages are NOT write protected when we start dirty logging in
1378 * initially-all-set mode; must write protect them here so that they
1379 * are split to 4K on the first write.
1381 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
1382 * of memslot has no such restriction, so the range can cross two large
1385 if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1386 gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
1387 gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
1389 if (READ_ONCE(eager_page_split))
1390 kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1392 kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
1394 /* Cross two large pages? */
1395 if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
1396 ALIGN(end << PAGE_SHIFT, PMD_SIZE))
1397 kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
1401 /* Now handle 4K PTEs. */
1402 if (kvm_x86_ops.cpu_dirty_log_size)
1403 kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1405 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1408 int kvm_cpu_dirty_log_size(void)
1410 return kvm_x86_ops.cpu_dirty_log_size;
1413 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1414 struct kvm_memory_slot *slot, u64 gfn,
1417 struct kvm_rmap_head *rmap_head;
1419 bool write_protected = false;
1421 if (kvm_memslots_have_rmaps(kvm)) {
1422 for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1423 rmap_head = gfn_to_rmap(gfn, i, slot);
1424 write_protected |= rmap_write_protect(rmap_head, true);
1428 if (tdp_mmu_enabled)
1430 kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
1432 return write_protected;
1435 static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1437 struct kvm_memory_slot *slot;
1439 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1440 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1443 static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1444 const struct kvm_memory_slot *slot)
1446 return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1449 static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1450 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1453 return __kvm_zap_rmap(kvm, rmap_head, slot);
1456 static bool kvm_set_pte_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1457 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1461 struct rmap_iterator iter;
1462 bool need_flush = false;
1466 WARN_ON(pte_huge(pte));
1467 new_pfn = pte_pfn(pte);
1470 for_each_rmap_spte(rmap_head, &iter, sptep) {
1471 rmap_printk("spte %p %llx gfn %llx (%d)\n",
1472 sptep, *sptep, gfn, level);
1476 if (pte_write(pte)) {
1477 kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
1480 new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1483 mmu_spte_clear_track_bits(kvm, sptep);
1484 mmu_spte_set(sptep, new_spte);
1488 if (need_flush && kvm_available_flush_tlb_with_range()) {
1489 kvm_flush_remote_tlbs_gfn(kvm, gfn, level);
1496 struct slot_rmap_walk_iterator {
1498 const struct kvm_memory_slot *slot;
1504 /* output fields. */
1506 struct kvm_rmap_head *rmap;
1509 /* private field. */
1510 struct kvm_rmap_head *end_rmap;
1514 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1516 iterator->level = level;
1517 iterator->gfn = iterator->start_gfn;
1518 iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
1519 iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1523 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1524 const struct kvm_memory_slot *slot, int start_level,
1525 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1527 iterator->slot = slot;
1528 iterator->start_level = start_level;
1529 iterator->end_level = end_level;
1530 iterator->start_gfn = start_gfn;
1531 iterator->end_gfn = end_gfn;
1533 rmap_walk_init_level(iterator, iterator->start_level);
1536 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1538 return !!iterator->rmap;
1541 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1543 while (++iterator->rmap <= iterator->end_rmap) {
1544 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1546 if (iterator->rmap->val)
1550 if (++iterator->level > iterator->end_level) {
1551 iterator->rmap = NULL;
1555 rmap_walk_init_level(iterator, iterator->level);
1558 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1559 _start_gfn, _end_gfn, _iter_) \
1560 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1561 _end_level_, _start_gfn, _end_gfn); \
1562 slot_rmap_walk_okay(_iter_); \
1563 slot_rmap_walk_next(_iter_))
1565 typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1566 struct kvm_memory_slot *slot, gfn_t gfn,
1567 int level, pte_t pte);
1569 static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
1570 struct kvm_gfn_range *range,
1571 rmap_handler_t handler)
1573 struct slot_rmap_walk_iterator iterator;
1576 for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
1577 range->start, range->end - 1, &iterator)
1578 ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
1579 iterator.level, range->pte);
1584 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1588 if (kvm_memslots_have_rmaps(kvm))
1589 flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1591 if (tdp_mmu_enabled)
1592 flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1597 bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1601 if (kvm_memslots_have_rmaps(kvm))
1602 flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmap);
1604 if (tdp_mmu_enabled)
1605 flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
1610 static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1611 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1615 struct rmap_iterator iter;
1618 for_each_rmap_spte(rmap_head, &iter, sptep)
1619 young |= mmu_spte_age(sptep);
1624 static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1625 struct kvm_memory_slot *slot, gfn_t gfn,
1626 int level, pte_t unused)
1629 struct rmap_iterator iter;
1631 for_each_rmap_spte(rmap_head, &iter, sptep)
1632 if (is_accessed_spte(*sptep))
1637 #define RMAP_RECYCLE_THRESHOLD 1000
1639 static void __rmap_add(struct kvm *kvm,
1640 struct kvm_mmu_memory_cache *cache,
1641 const struct kvm_memory_slot *slot,
1642 u64 *spte, gfn_t gfn, unsigned int access)
1644 struct kvm_mmu_page *sp;
1645 struct kvm_rmap_head *rmap_head;
1648 sp = sptep_to_sp(spte);
1649 kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
1650 kvm_update_page_stats(kvm, sp->role.level, 1);
1652 rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1653 rmap_count = pte_list_add(cache, spte, rmap_head);
1655 if (rmap_count > kvm->stat.max_mmu_rmap_size)
1656 kvm->stat.max_mmu_rmap_size = rmap_count;
1657 if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
1658 kvm_zap_all_rmap_sptes(kvm, rmap_head);
1659 kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
1663 static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
1664 u64 *spte, gfn_t gfn, unsigned int access)
1666 struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
1668 __rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
1671 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1675 if (kvm_memslots_have_rmaps(kvm))
1676 young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
1678 if (tdp_mmu_enabled)
1679 young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1684 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1688 if (kvm_memslots_have_rmaps(kvm))
1689 young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
1691 if (tdp_mmu_enabled)
1692 young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1698 static int is_empty_shadow_page(u64 *spt)
1703 for (pos = spt, end = pos + SPTE_ENT_PER_PAGE; pos != end; pos++)
1704 if (is_shadow_present_pte(*pos)) {
1705 printk(KERN_ERR "%s: %p %llx\n", __func__,
1714 * This value is the sum of all of the kvm instances's
1715 * kvm->arch.n_used_mmu_pages values. We need a global,
1716 * aggregate version in order to make the slab shrinker
1719 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1721 kvm->arch.n_used_mmu_pages += nr;
1722 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1725 static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1727 kvm_mod_used_mmu_pages(kvm, +1);
1728 kvm_account_pgtable_pages((void *)sp->spt, +1);
1731 static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1733 kvm_mod_used_mmu_pages(kvm, -1);
1734 kvm_account_pgtable_pages((void *)sp->spt, -1);
1737 static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1739 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1740 hlist_del(&sp->hash_link);
1741 list_del(&sp->link);
1742 free_page((unsigned long)sp->spt);
1743 if (!sp->role.direct)
1744 free_page((unsigned long)sp->shadowed_translation);
1745 kmem_cache_free(mmu_page_header_cache, sp);
1748 static unsigned kvm_page_table_hashfn(gfn_t gfn)
1750 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1753 static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1754 struct kvm_mmu_page *sp, u64 *parent_pte)
1759 pte_list_add(cache, parent_pte, &sp->parent_ptes);
1762 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1765 pte_list_remove(parent_pte, &sp->parent_ptes);
1768 static void drop_parent_pte(struct kvm_mmu_page *sp,
1771 mmu_page_remove_parent_pte(sp, parent_pte);
1772 mmu_spte_clear_no_track(parent_pte);
1775 static void mark_unsync(u64 *spte);
1776 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1779 struct rmap_iterator iter;
1781 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1786 static void mark_unsync(u64 *spte)
1788 struct kvm_mmu_page *sp;
1790 sp = sptep_to_sp(spte);
1791 if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1793 if (sp->unsync_children++)
1795 kvm_mmu_mark_parents_unsync(sp);
1798 #define KVM_PAGE_ARRAY_NR 16
1800 struct kvm_mmu_pages {
1801 struct mmu_page_and_offset {
1802 struct kvm_mmu_page *sp;
1804 } page[KVM_PAGE_ARRAY_NR];
1808 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1814 for (i=0; i < pvec->nr; i++)
1815 if (pvec->page[i].sp == sp)
1818 pvec->page[pvec->nr].sp = sp;
1819 pvec->page[pvec->nr].idx = idx;
1821 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1824 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1826 --sp->unsync_children;
1827 WARN_ON((int)sp->unsync_children < 0);
1828 __clear_bit(idx, sp->unsync_child_bitmap);
1831 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1832 struct kvm_mmu_pages *pvec)
1834 int i, ret, nr_unsync_leaf = 0;
1836 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1837 struct kvm_mmu_page *child;
1838 u64 ent = sp->spt[i];
1840 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1841 clear_unsync_child_bit(sp, i);
1845 child = spte_to_child_sp(ent);
1847 if (child->unsync_children) {
1848 if (mmu_pages_add(pvec, child, i))
1851 ret = __mmu_unsync_walk(child, pvec);
1853 clear_unsync_child_bit(sp, i);
1855 } else if (ret > 0) {
1856 nr_unsync_leaf += ret;
1859 } else if (child->unsync) {
1861 if (mmu_pages_add(pvec, child, i))
1864 clear_unsync_child_bit(sp, i);
1867 return nr_unsync_leaf;
1870 #define INVALID_INDEX (-1)
1872 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1873 struct kvm_mmu_pages *pvec)
1876 if (!sp->unsync_children)
1879 mmu_pages_add(pvec, sp, INVALID_INDEX);
1880 return __mmu_unsync_walk(sp, pvec);
1883 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1885 WARN_ON(!sp->unsync);
1886 trace_kvm_mmu_sync_page(sp);
1888 --kvm->stat.mmu_unsync;
1891 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1892 struct list_head *invalid_list);
1893 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1894 struct list_head *invalid_list);
1896 static bool sp_has_gptes(struct kvm_mmu_page *sp)
1898 if (sp->role.direct)
1901 if (sp->role.passthrough)
1907 #define for_each_valid_sp(_kvm, _sp, _list) \
1908 hlist_for_each_entry(_sp, _list, hash_link) \
1909 if (is_obsolete_sp((_kvm), (_sp))) { \
1912 #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn) \
1913 for_each_valid_sp(_kvm, _sp, \
1914 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
1915 if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1917 static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1919 union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
1922 * Ignore various flags when verifying that it's safe to sync a shadow
1923 * page using the current MMU context.
1925 * - level: not part of the overall MMU role and will never match as the MMU's
1926 * level tracks the root level
1927 * - access: updated based on the new guest PTE
1928 * - quadrant: not part of the overall MMU role (similar to level)
1930 const union kvm_mmu_page_role sync_role_ign = {
1938 * Direct pages can never be unsync, and KVM should never attempt to
1939 * sync a shadow page for a different MMU context, e.g. if the role
1940 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
1941 * reserved bits checks will be wrong, etc...
1943 if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
1944 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
1950 static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
1955 return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
1958 static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1963 if (!kvm_sync_page_check(vcpu, sp))
1966 for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
1967 int ret = kvm_sync_spte(vcpu, sp, i);
1975 * Note, any flush is purely for KVM's correctness, e.g. when dropping
1976 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1977 * unmap or dirty logging event doesn't fail to flush. The guest is
1978 * responsible for flushing the TLB to ensure any changes in protection
1979 * bits are recognized, i.e. until the guest flushes or page faults on
1980 * a relevant address, KVM is architecturally allowed to let vCPUs use
1981 * cached translations with the old protection bits.
1986 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1987 struct list_head *invalid_list)
1989 int ret = __kvm_sync_page(vcpu, sp);
1992 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1996 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1997 struct list_head *invalid_list,
2000 if (!remote_flush && list_empty(invalid_list))
2003 if (!list_empty(invalid_list))
2004 kvm_mmu_commit_zap_page(kvm, invalid_list);
2006 kvm_flush_remote_tlbs(kvm);
2010 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2012 if (sp->role.invalid)
2015 /* TDP MMU pages do not use the MMU generation. */
2016 return !is_tdp_mmu_page(sp) &&
2017 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2020 struct mmu_page_path {
2021 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2022 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2025 #define for_each_sp(pvec, sp, parents, i) \
2026 for (i = mmu_pages_first(&pvec, &parents); \
2027 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2028 i = mmu_pages_next(&pvec, &parents, i))
2030 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2031 struct mmu_page_path *parents,
2036 for (n = i+1; n < pvec->nr; n++) {
2037 struct kvm_mmu_page *sp = pvec->page[n].sp;
2038 unsigned idx = pvec->page[n].idx;
2039 int level = sp->role.level;
2041 parents->idx[level-1] = idx;
2042 if (level == PG_LEVEL_4K)
2045 parents->parent[level-2] = sp;
2051 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2052 struct mmu_page_path *parents)
2054 struct kvm_mmu_page *sp;
2060 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2062 sp = pvec->page[0].sp;
2063 level = sp->role.level;
2064 WARN_ON(level == PG_LEVEL_4K);
2066 parents->parent[level-2] = sp;
2068 /* Also set up a sentinel. Further entries in pvec are all
2069 * children of sp, so this element is never overwritten.
2071 parents->parent[level-1] = NULL;
2072 return mmu_pages_next(pvec, parents, 0);
2075 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2077 struct kvm_mmu_page *sp;
2078 unsigned int level = 0;
2081 unsigned int idx = parents->idx[level];
2082 sp = parents->parent[level];
2086 WARN_ON(idx == INVALID_INDEX);
2087 clear_unsync_child_bit(sp, idx);
2089 } while (!sp->unsync_children);
2092 static int mmu_sync_children(struct kvm_vcpu *vcpu,
2093 struct kvm_mmu_page *parent, bool can_yield)
2096 struct kvm_mmu_page *sp;
2097 struct mmu_page_path parents;
2098 struct kvm_mmu_pages pages;
2099 LIST_HEAD(invalid_list);
2102 while (mmu_unsync_walk(parent, &pages)) {
2103 bool protected = false;
2105 for_each_sp(pages, sp, parents, i)
2106 protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2109 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2113 for_each_sp(pages, sp, parents, i) {
2114 kvm_unlink_unsync_page(vcpu->kvm, sp);
2115 flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2116 mmu_pages_clear_parents(&parents);
2118 if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2119 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2121 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2125 cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2130 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2134 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2136 atomic_set(&sp->write_flooding_count, 0);
2139 static void clear_sp_write_flooding_count(u64 *spte)
2141 __clear_sp_write_flooding_count(sptep_to_sp(spte));
2145 * The vCPU is required when finding indirect shadow pages; the shadow
2146 * page may already exist and syncing it needs the vCPU pointer in
2147 * order to read guest page tables. Direct shadow pages are never
2148 * unsync, thus @vcpu can be NULL if @role.direct is true.
2150 static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
2151 struct kvm_vcpu *vcpu,
2153 struct hlist_head *sp_list,
2154 union kvm_mmu_page_role role)
2156 struct kvm_mmu_page *sp;
2159 LIST_HEAD(invalid_list);
2161 for_each_valid_sp(kvm, sp, sp_list) {
2162 if (sp->gfn != gfn) {
2167 if (sp->role.word != role.word) {
2169 * If the guest is creating an upper-level page, zap
2170 * unsync pages for the same gfn. While it's possible
2171 * the guest is using recursive page tables, in all
2172 * likelihood the guest has stopped using the unsync
2173 * page and is installing a completely unrelated page.
2174 * Unsync pages must not be left as is, because the new
2175 * upper-level page will be write-protected.
2177 if (role.level > PG_LEVEL_4K && sp->unsync)
2178 kvm_mmu_prepare_zap_page(kvm, sp,
2183 /* unsync and write-flooding only apply to indirect SPs. */
2184 if (sp->role.direct)
2188 if (KVM_BUG_ON(!vcpu, kvm))
2192 * The page is good, but is stale. kvm_sync_page does
2193 * get the latest guest state, but (unlike mmu_unsync_children)
2194 * it doesn't write-protect the page or mark it synchronized!
2195 * This way the validity of the mapping is ensured, but the
2196 * overhead of write protection is not incurred until the
2197 * guest invalidates the TLB mapping. This allows multiple
2198 * SPs for a single gfn to be unsync.
2200 * If the sync fails, the page is zapped. If so, break
2201 * in order to rebuild it.
2203 ret = kvm_sync_page(vcpu, sp, &invalid_list);
2207 WARN_ON(!list_empty(&invalid_list));
2209 kvm_flush_remote_tlbs(kvm);
2212 __clear_sp_write_flooding_count(sp);
2218 ++kvm->stat.mmu_cache_miss;
2221 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2223 if (collisions > kvm->stat.max_mmu_page_hash_collisions)
2224 kvm->stat.max_mmu_page_hash_collisions = collisions;
2228 /* Caches used when allocating a new shadow page. */
2229 struct shadow_page_caches {
2230 struct kvm_mmu_memory_cache *page_header_cache;
2231 struct kvm_mmu_memory_cache *shadow_page_cache;
2232 struct kvm_mmu_memory_cache *shadowed_info_cache;
2235 static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
2236 struct shadow_page_caches *caches,
2238 struct hlist_head *sp_list,
2239 union kvm_mmu_page_role role)
2241 struct kvm_mmu_page *sp;
2243 sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
2244 sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2246 sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2248 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2250 INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2253 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2254 * depends on valid pages being added to the head of the list. See
2255 * comments in kvm_zap_obsolete_pages().
2257 sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2258 list_add(&sp->link, &kvm->arch.active_mmu_pages);
2259 kvm_account_mmu_page(kvm, sp);
2263 hlist_add_head(&sp->hash_link, sp_list);
2264 if (sp_has_gptes(sp))
2265 account_shadowed(kvm, sp);
2270 /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
2271 static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
2272 struct kvm_vcpu *vcpu,
2273 struct shadow_page_caches *caches,
2275 union kvm_mmu_page_role role)
2277 struct hlist_head *sp_list;
2278 struct kvm_mmu_page *sp;
2279 bool created = false;
2281 sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2283 sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
2286 sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
2289 trace_kvm_mmu_get_page(sp, created);
2293 static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
2295 union kvm_mmu_page_role role)
2297 struct shadow_page_caches caches = {
2298 .page_header_cache = &vcpu->arch.mmu_page_header_cache,
2299 .shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
2300 .shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
2303 return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
2306 static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
2307 unsigned int access)
2309 struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
2310 union kvm_mmu_page_role role;
2312 role = parent_sp->role;
2314 role.access = access;
2315 role.direct = direct;
2316 role.passthrough = 0;
2319 * If the guest has 4-byte PTEs then that means it's using 32-bit,
2320 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
2321 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
2322 * shadow each guest page table with multiple shadow page tables, which
2323 * requires extra bookkeeping in the role.
2325 * Specifically, to shadow the guest's page directory (which covers a
2326 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
2327 * 1GiB of the address space. @role.quadrant encodes which quarter of
2328 * the address space each maps.
2330 * To shadow the guest's page tables (which each map a 4MiB region), KVM
2331 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
2332 * @role.quadrant encodes which half of the region they map.
2334 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
2335 * consumes bits 29:21. To consume bits 31:30, KVM's uses 4 shadow
2336 * PDPTEs; those 4 PAE page directories are pre-allocated and their
2337 * quadrant is assigned in mmu_alloc_root(). A 4-byte PTE consumes
2338 * bits 21:12, while an 8-byte PTE consumes bits 20:12. To consume
2339 * bit 21 in the PTE (the child here), KVM propagates that bit to the
2340 * quadrant, i.e. sets quadrant to '0' or '1'. The parent 8-byte PDE
2341 * covers bit 21 (see above), thus the quadrant is calculated from the
2342 * _least_ significant bit of the PDE index.
2344 if (role.has_4_byte_gpte) {
2345 WARN_ON_ONCE(role.level != PG_LEVEL_4K);
2346 role.quadrant = spte_index(sptep) & 1;
2352 static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
2353 u64 *sptep, gfn_t gfn,
2354 bool direct, unsigned int access)
2356 union kvm_mmu_page_role role;
2358 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
2359 return ERR_PTR(-EEXIST);
2361 role = kvm_mmu_child_role(sptep, direct, access);
2362 return kvm_mmu_get_shadow_page(vcpu, gfn, role);
2365 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2366 struct kvm_vcpu *vcpu, hpa_t root,
2369 iterator->addr = addr;
2370 iterator->shadow_addr = root;
2371 iterator->level = vcpu->arch.mmu->root_role.level;
2373 if (iterator->level >= PT64_ROOT_4LEVEL &&
2374 vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2375 !vcpu->arch.mmu->root_role.direct)
2376 iterator->level = PT32E_ROOT_LEVEL;
2378 if (iterator->level == PT32E_ROOT_LEVEL) {
2380 * prev_root is currently only used for 64-bit hosts. So only
2381 * the active root_hpa is valid here.
2383 BUG_ON(root != vcpu->arch.mmu->root.hpa);
2385 iterator->shadow_addr
2386 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2387 iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2389 if (!iterator->shadow_addr)
2390 iterator->level = 0;
2394 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2395 struct kvm_vcpu *vcpu, u64 addr)
2397 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2401 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2403 if (iterator->level < PG_LEVEL_4K)
2406 iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2407 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2411 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2414 if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2415 iterator->level = 0;
2419 iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2423 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2425 __shadow_walk_next(iterator, *iterator->sptep);
2428 static void __link_shadow_page(struct kvm *kvm,
2429 struct kvm_mmu_memory_cache *cache, u64 *sptep,
2430 struct kvm_mmu_page *sp, bool flush)
2434 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2437 * If an SPTE is present already, it must be a leaf and therefore
2438 * a large one. Drop it, and flush the TLB if needed, before
2441 if (is_shadow_present_pte(*sptep))
2442 drop_large_spte(kvm, sptep, flush);
2444 spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2446 mmu_spte_set(sptep, spte);
2448 mmu_page_add_parent_pte(cache, sp, sptep);
2451 * The non-direct sub-pagetable must be updated before linking. For
2452 * L1 sp, the pagetable is updated via kvm_sync_page() in
2453 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2454 * so sp->unsync can be true or false. For higher level non-direct
2455 * sp, the pagetable is updated/synced via mmu_sync_children() in
2456 * FNAME(fetch)(), so sp->unsync_children can only be false.
2457 * WARN_ON_ONCE() if anything happens unexpectedly.
2459 if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2463 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2464 struct kvm_mmu_page *sp)
2466 __link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
2469 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2470 unsigned direct_access)
2472 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2473 struct kvm_mmu_page *child;
2476 * For the direct sp, if the guest pte's dirty bit
2477 * changed form clean to dirty, it will corrupt the
2478 * sp's access: allow writable in the read-only sp,
2479 * so we should update the spte at this point to get
2480 * a new sp with the correct access.
2482 child = spte_to_child_sp(*sptep);
2483 if (child->role.access == direct_access)
2486 drop_parent_pte(child, sptep);
2487 kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2491 /* Returns the number of zapped non-leaf child shadow pages. */
2492 static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2493 u64 *spte, struct list_head *invalid_list)
2496 struct kvm_mmu_page *child;
2499 if (is_shadow_present_pte(pte)) {
2500 if (is_last_spte(pte, sp->role.level)) {
2501 drop_spte(kvm, spte);
2503 child = spte_to_child_sp(pte);
2504 drop_parent_pte(child, spte);
2507 * Recursively zap nested TDP SPs, parentless SPs are
2508 * unlikely to be used again in the near future. This
2509 * avoids retaining a large number of stale nested SPs.
2511 if (tdp_enabled && invalid_list &&
2512 child->role.guest_mode && !child->parent_ptes.val)
2513 return kvm_mmu_prepare_zap_page(kvm, child,
2516 } else if (is_mmio_spte(pte)) {
2517 mmu_spte_clear_no_track(spte);
2522 static int kvm_mmu_page_unlink_children(struct kvm *kvm,
2523 struct kvm_mmu_page *sp,
2524 struct list_head *invalid_list)
2529 for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
2530 zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
2535 static void kvm_mmu_unlink_parents(struct kvm_mmu_page *sp)
2538 struct rmap_iterator iter;
2540 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2541 drop_parent_pte(sp, sptep);
2544 static int mmu_zap_unsync_children(struct kvm *kvm,
2545 struct kvm_mmu_page *parent,
2546 struct list_head *invalid_list)
2549 struct mmu_page_path parents;
2550 struct kvm_mmu_pages pages;
2552 if (parent->role.level == PG_LEVEL_4K)
2555 while (mmu_unsync_walk(parent, &pages)) {
2556 struct kvm_mmu_page *sp;
2558 for_each_sp(pages, sp, parents, i) {
2559 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2560 mmu_pages_clear_parents(&parents);
2568 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2569 struct kvm_mmu_page *sp,
2570 struct list_head *invalid_list,
2573 bool list_unstable, zapped_root = false;
2575 lockdep_assert_held_write(&kvm->mmu_lock);
2576 trace_kvm_mmu_prepare_zap_page(sp);
2577 ++kvm->stat.mmu_shadow_zapped;
2578 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2579 *nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2580 kvm_mmu_unlink_parents(sp);
2582 /* Zapping children means active_mmu_pages has become unstable. */
2583 list_unstable = *nr_zapped;
2585 if (!sp->role.invalid && sp_has_gptes(sp))
2586 unaccount_shadowed(kvm, sp);
2589 kvm_unlink_unsync_page(kvm, sp);
2590 if (!sp->root_count) {
2595 * Already invalid pages (previously active roots) are not on
2596 * the active page list. See list_del() in the "else" case of
2599 if (sp->role.invalid)
2600 list_add(&sp->link, invalid_list);
2602 list_move(&sp->link, invalid_list);
2603 kvm_unaccount_mmu_page(kvm, sp);
2606 * Remove the active root from the active page list, the root
2607 * will be explicitly freed when the root_count hits zero.
2609 list_del(&sp->link);
2612 * Obsolete pages cannot be used on any vCPUs, see the comment
2613 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2614 * treats invalid shadow pages as being obsolete.
2616 zapped_root = !is_obsolete_sp(kvm, sp);
2619 if (sp->nx_huge_page_disallowed)
2620 unaccount_nx_huge_page(kvm, sp);
2622 sp->role.invalid = 1;
2625 * Make the request to free obsolete roots after marking the root
2626 * invalid, otherwise other vCPUs may not see it as invalid.
2629 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2630 return list_unstable;
2633 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2634 struct list_head *invalid_list)
2638 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2642 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2643 struct list_head *invalid_list)
2645 struct kvm_mmu_page *sp, *nsp;
2647 if (list_empty(invalid_list))
2651 * We need to make sure everyone sees our modifications to
2652 * the page tables and see changes to vcpu->mode here. The barrier
2653 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2654 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2656 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2657 * guest mode and/or lockless shadow page table walks.
2659 kvm_flush_remote_tlbs(kvm);
2661 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2662 WARN_ON(!sp->role.invalid || sp->root_count);
2663 kvm_mmu_free_shadow_page(sp);
2667 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2668 unsigned long nr_to_zap)
2670 unsigned long total_zapped = 0;
2671 struct kvm_mmu_page *sp, *tmp;
2672 LIST_HEAD(invalid_list);
2676 if (list_empty(&kvm->arch.active_mmu_pages))
2680 list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2682 * Don't zap active root pages, the page itself can't be freed
2683 * and zapping it will just force vCPUs to realloc and reload.
2688 unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2690 total_zapped += nr_zapped;
2691 if (total_zapped >= nr_to_zap)
2698 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2700 kvm->stat.mmu_recycled += total_zapped;
2701 return total_zapped;
2704 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2706 if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2707 return kvm->arch.n_max_mmu_pages -
2708 kvm->arch.n_used_mmu_pages;
2713 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2715 unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2717 if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2720 kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2723 * Note, this check is intentionally soft, it only guarantees that one
2724 * page is available, while the caller may end up allocating as many as
2725 * four pages, e.g. for PAE roots or for 5-level paging. Temporarily
2726 * exceeding the (arbitrary by default) limit will not harm the host,
2727 * being too aggressive may unnecessarily kill the guest, and getting an
2728 * exact count is far more trouble than it's worth, especially in the
2731 if (!kvm_mmu_available_pages(vcpu->kvm))
2737 * Changing the number of mmu pages allocated to the vm
2738 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2740 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2742 write_lock(&kvm->mmu_lock);
2744 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2745 kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2748 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2751 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2753 write_unlock(&kvm->mmu_lock);
2756 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2758 struct kvm_mmu_page *sp;
2759 LIST_HEAD(invalid_list);
2762 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2764 write_lock(&kvm->mmu_lock);
2765 for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2766 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2769 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2771 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2772 write_unlock(&kvm->mmu_lock);
2777 static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2782 if (vcpu->arch.mmu->root_role.direct)
2785 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
2787 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2792 static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2794 trace_kvm_mmu_unsync_page(sp);
2795 ++kvm->stat.mmu_unsync;
2798 kvm_mmu_mark_parents_unsync(sp);
2802 * Attempt to unsync any shadow pages that can be reached by the specified gfn,
2803 * KVM is creating a writable mapping for said gfn. Returns 0 if all pages
2804 * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
2805 * be write-protected.
2807 int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
2808 gfn_t gfn, bool can_unsync, bool prefetch)
2810 struct kvm_mmu_page *sp;
2811 bool locked = false;
2814 * Force write-protection if the page is being tracked. Note, the page
2815 * track machinery is used to write-protect upper-level shadow pages,
2816 * i.e. this guards the role.level == 4K assertion below!
2818 if (kvm_slot_page_track_is_active(kvm, slot, gfn, KVM_PAGE_TRACK_WRITE))
2822 * The page is not write-tracked, mark existing shadow pages unsync
2823 * unless KVM is synchronizing an unsync SP (can_unsync = false). In
2824 * that case, KVM must complete emulation of the guest TLB flush before
2825 * allowing shadow pages to become unsync (writable by the guest).
2827 for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2838 * TDP MMU page faults require an additional spinlock as they
2839 * run with mmu_lock held for read, not write, and the unsync
2840 * logic is not thread safe. Take the spinklock regardless of
2841 * the MMU type to avoid extra conditionals/parameters, there's
2842 * no meaningful penalty if mmu_lock is held for write.
2846 spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2849 * Recheck after taking the spinlock, a different vCPU
2850 * may have since marked the page unsync. A false
2851 * positive on the unprotected check above is not
2852 * possible as clearing sp->unsync _must_ hold mmu_lock
2853 * for write, i.e. unsync cannot transition from 0->1
2854 * while this CPU holds mmu_lock for read (or write).
2856 if (READ_ONCE(sp->unsync))
2860 WARN_ON(sp->role.level != PG_LEVEL_4K);
2861 kvm_unsync_page(kvm, sp);
2864 spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2867 * We need to ensure that the marking of unsync pages is visible
2868 * before the SPTE is updated to allow writes because
2869 * kvm_mmu_sync_roots() checks the unsync flags without holding
2870 * the MMU lock and so can race with this. If the SPTE was updated
2871 * before the page had been marked as unsync-ed, something like the
2872 * following could happen:
2875 * ---------------------------------------------------------------------
2876 * 1.2 Host updates SPTE
2878 * 2.1 Guest writes a GPTE for GVA X.
2879 * (GPTE being in the guest page table shadowed
2880 * by the SP from CPU 1.)
2881 * This reads SPTE during the page table walk.
2882 * Since SPTE.W is read as 1, there is no
2885 * 2.2 Guest issues TLB flush.
2886 * That causes a VM Exit.
2888 * 2.3 Walking of unsync pages sees sp->unsync is
2889 * false and skips the page.
2891 * 2.4 Guest accesses GVA X.
2892 * Since the mapping in the SP was not updated,
2893 * so the old mapping for GVA X incorrectly
2897 * (sp->unsync = true)
2899 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2900 * the situation in 2.4 does not arise. It pairs with the read barrier
2901 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2908 static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
2909 u64 *sptep, unsigned int pte_access, gfn_t gfn,
2910 kvm_pfn_t pfn, struct kvm_page_fault *fault)
2912 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2913 int level = sp->role.level;
2914 int was_rmapped = 0;
2915 int ret = RET_PF_FIXED;
2920 /* Prefetching always gets a writable pfn. */
2921 bool host_writable = !fault || fault->map_writable;
2922 bool prefetch = !fault || fault->prefetch;
2923 bool write_fault = fault && fault->write;
2925 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2926 *sptep, write_fault, gfn);
2928 if (unlikely(is_noslot_pfn(pfn))) {
2929 vcpu->stat.pf_mmio_spte_created++;
2930 mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2931 return RET_PF_EMULATE;
2934 if (is_shadow_present_pte(*sptep)) {
2936 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2937 * the parent of the now unreachable PTE.
2939 if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2940 struct kvm_mmu_page *child;
2943 child = spte_to_child_sp(pte);
2944 drop_parent_pte(child, sptep);
2946 } else if (pfn != spte_to_pfn(*sptep)) {
2947 pgprintk("hfn old %llx new %llx\n",
2948 spte_to_pfn(*sptep), pfn);
2949 drop_spte(vcpu->kvm, sptep);
2955 wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
2956 true, host_writable, &spte);
2958 if (*sptep == spte) {
2959 ret = RET_PF_SPURIOUS;
2961 flush |= mmu_spte_update(sptep, spte);
2962 trace_kvm_mmu_set_spte(level, gfn, sptep);
2967 ret = RET_PF_EMULATE;
2971 kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
2973 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2976 WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
2977 rmap_add(vcpu, slot, sptep, gfn, pte_access);
2979 /* Already rmapped but the pte_access bits may have changed. */
2980 kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2986 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2987 struct kvm_mmu_page *sp,
2988 u64 *start, u64 *end)
2990 struct page *pages[PTE_PREFETCH_NUM];
2991 struct kvm_memory_slot *slot;
2992 unsigned int access = sp->role.access;
2996 gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
2997 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3001 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3005 for (i = 0; i < ret; i++, gfn++, start++) {
3006 mmu_set_spte(vcpu, slot, start, access, gfn,
3007 page_to_pfn(pages[i]), NULL);
3014 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3015 struct kvm_mmu_page *sp, u64 *sptep)
3017 u64 *spte, *start = NULL;
3020 WARN_ON(!sp->role.direct);
3022 i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
3025 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3026 if (is_shadow_present_pte(*spte) || spte == sptep) {
3029 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3036 direct_pte_prefetch_many(vcpu, sp, start, spte);
3039 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3041 struct kvm_mmu_page *sp;
3043 sp = sptep_to_sp(sptep);
3046 * Without accessed bits, there's no way to distinguish between
3047 * actually accessed translations and prefetched, so disable pte
3048 * prefetch if accessed bits aren't available.
3050 if (sp_ad_disabled(sp))
3053 if (sp->role.level > PG_LEVEL_4K)
3057 * If addresses are being invalidated, skip prefetching to avoid
3058 * accidentally prefetching those addresses.
3060 if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
3063 __direct_pte_prefetch(vcpu, sp, sptep);
3067 * Lookup the mapping level for @gfn in the current mm.
3069 * WARNING! Use of host_pfn_mapping_level() requires the caller and the end
3070 * consumer to be tied into KVM's handlers for MMU notifier events!
3072 * There are several ways to safely use this helper:
3074 * - Check mmu_invalidate_retry_hva() after grabbing the mapping level, before
3075 * consuming it. In this case, mmu_lock doesn't need to be held during the
3076 * lookup, but it does need to be held while checking the MMU notifier.
3078 * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
3079 * event for the hva. This can be done by explicit checking the MMU notifier
3080 * or by ensuring that KVM already has a valid mapping that covers the hva.
3082 * - Do not use the result to install new mappings, e.g. use the host mapping
3083 * level only to decide whether or not to zap an entry. In this case, it's
3084 * not required to hold mmu_lock (though it's highly likely the caller will
3085 * want to hold mmu_lock anyways, e.g. to modify SPTEs).
3087 * Note! The lookup can still race with modifications to host page tables, but
3088 * the above "rules" ensure KVM will not _consume_ the result of the walk if a
3089 * race with the primary MMU occurs.
3091 static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
3092 const struct kvm_memory_slot *slot)
3094 int level = PG_LEVEL_4K;
3096 unsigned long flags;
3103 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3104 * is not solely for performance, it's also necessary to avoid the
3105 * "writable" check in __gfn_to_hva_many(), which will always fail on
3106 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
3107 * page fault steps have already verified the guest isn't writing a
3108 * read-only memslot.
3110 hva = __gfn_to_hva_memslot(slot, gfn);
3113 * Disable IRQs to prevent concurrent tear down of host page tables,
3114 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
3115 * the original page table.
3117 local_irq_save(flags);
3120 * Read each entry once. As above, a non-leaf entry can be promoted to
3121 * a huge page _during_ this walk. Re-reading the entry could send the
3122 * walk into the weeks, e.g. p*d_large() returns false (sees the old
3123 * value) and then p*d_offset() walks into the target huge page instead
3124 * of the old page table (sees the new value).
3126 pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
3130 p4d = READ_ONCE(*p4d_offset(&pgd, hva));
3131 if (p4d_none(p4d) || !p4d_present(p4d))
3134 pud = READ_ONCE(*pud_offset(&p4d, hva));
3135 if (pud_none(pud) || !pud_present(pud))
3138 if (pud_large(pud)) {
3139 level = PG_LEVEL_1G;
3143 pmd = READ_ONCE(*pmd_offset(&pud, hva));
3144 if (pmd_none(pmd) || !pmd_present(pmd))
3148 level = PG_LEVEL_2M;
3151 local_irq_restore(flags);
3155 int kvm_mmu_max_mapping_level(struct kvm *kvm,
3156 const struct kvm_memory_slot *slot, gfn_t gfn,
3159 struct kvm_lpage_info *linfo;
3162 max_level = min(max_level, max_huge_page_level);
3163 for ( ; max_level > PG_LEVEL_4K; max_level--) {
3164 linfo = lpage_info_slot(gfn, slot, max_level);
3165 if (!linfo->disallow_lpage)
3169 if (max_level == PG_LEVEL_4K)
3172 host_level = host_pfn_mapping_level(kvm, gfn, slot);
3173 return min(host_level, max_level);
3176 void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3178 struct kvm_memory_slot *slot = fault->slot;
3181 fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
3183 if (unlikely(fault->max_level == PG_LEVEL_4K))
3186 if (is_error_noslot_pfn(fault->pfn))
3189 if (kvm_slot_dirty_track_enabled(slot))
3193 * Enforce the iTLB multihit workaround after capturing the requested
3194 * level, which will be used to do precise, accurate accounting.
3196 fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3197 fault->gfn, fault->max_level);
3198 if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
3202 * mmu_invalidate_retry() was successful and mmu_lock is held, so
3203 * the pmd can't be split from under us.
3205 fault->goal_level = fault->req_level;
3206 mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
3207 VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
3208 fault->pfn &= ~mask;
3211 void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3213 if (cur_level > PG_LEVEL_4K &&
3214 cur_level == fault->goal_level &&
3215 is_shadow_present_pte(spte) &&
3216 !is_large_pte(spte) &&
3217 spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3219 * A small SPTE exists for this pfn, but FNAME(fetch),
3220 * direct_map(), or kvm_tdp_mmu_map() would like to create a
3221 * large PTE instead: just force them to go down another level,
3222 * patching back for them into pfn the next 9 bits of the
3225 u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3226 KVM_PAGES_PER_HPAGE(cur_level - 1);
3227 fault->pfn |= fault->gfn & page_mask;
3228 fault->goal_level--;
3232 static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3234 struct kvm_shadow_walk_iterator it;
3235 struct kvm_mmu_page *sp;
3237 gfn_t base_gfn = fault->gfn;
3239 kvm_mmu_hugepage_adjust(vcpu, fault);
3241 trace_kvm_mmu_spte_requested(fault);
3242 for_each_shadow_entry(vcpu, fault->addr, it) {
3244 * We cannot overwrite existing page tables with an NX
3245 * large page, as the leaf could be executable.
3247 if (fault->nx_huge_page_workaround_enabled)
3248 disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3250 base_gfn = gfn_round_for_level(fault->gfn, it.level);
3251 if (it.level == fault->goal_level)
3254 sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
3255 if (sp == ERR_PTR(-EEXIST))
3258 link_shadow_page(vcpu, it.sptep, sp);
3259 if (fault->huge_page_disallowed)
3260 account_nx_huge_page(vcpu->kvm, sp,
3261 fault->req_level >= it.level);
3264 if (WARN_ON_ONCE(it.level != fault->goal_level))
3267 ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3268 base_gfn, fault->pfn, fault);
3269 if (ret == RET_PF_SPURIOUS)
3272 direct_pte_prefetch(vcpu, it.sptep);
3276 static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3278 unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3280 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3283 static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3285 if (is_sigpending_pfn(fault->pfn)) {
3286 kvm_handle_signal_exit(vcpu);
3291 * Do not cache the mmio info caused by writing the readonly gfn
3292 * into the spte otherwise read access on readonly gfn also can
3293 * caused mmio page fault and treat it as mmio access.
3295 if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3296 return RET_PF_EMULATE;
3298 if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3299 kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3300 return RET_PF_RETRY;
3306 static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3307 struct kvm_page_fault *fault,
3308 unsigned int access)
3310 gva_t gva = fault->is_tdp ? 0 : fault->addr;
3312 vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3313 access & shadow_mmio_access_mask);
3316 * If MMIO caching is disabled, emulate immediately without
3317 * touching the shadow page tables as attempting to install an
3318 * MMIO SPTE will just be an expensive nop.
3320 if (unlikely(!enable_mmio_caching))
3321 return RET_PF_EMULATE;
3324 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3325 * any guest that generates such gfns is running nested and is being
3326 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3327 * only if L1's MAXPHYADDR is inaccurate with respect to the
3330 if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3331 return RET_PF_EMULATE;
3333 return RET_PF_CONTINUE;
3336 static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3339 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
3340 * reach the common page fault handler if the SPTE has an invalid MMIO
3341 * generation number. Refreshing the MMIO generation needs to go down
3342 * the slow path. Note, EPT Misconfigs do NOT set the PRESENT flag!
3348 * #PF can be fast if:
3350 * 1. The shadow page table entry is not present and A/D bits are
3351 * disabled _by KVM_, which could mean that the fault is potentially
3352 * caused by access tracking (if enabled). If A/D bits are enabled
3353 * by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
3354 * bits for L2 and employ access tracking, but the fast page fault
3355 * mechanism only supports direct MMUs.
3356 * 2. The shadow page table entry is present, the access is a write,
3357 * and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
3358 * the fault was caused by a write-protection violation. If the
3359 * SPTE is MMU-writable (determined later), the fault can be fixed
3360 * by setting the Writable bit, which can be done out of mmu_lock.
3362 if (!fault->present)
3363 return !kvm_ad_enabled();
3366 * Note, instruction fetches and writes are mutually exclusive, ignore
3369 return fault->write;
3373 * Returns true if the SPTE was fixed successfully. Otherwise,
3374 * someone else modified the SPTE from its original value.
3377 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
3378 u64 *sptep, u64 old_spte, u64 new_spte)
3381 * Theoretically we could also set dirty bit (and flush TLB) here in
3382 * order to eliminate unnecessary PML logging. See comments in
3383 * set_spte. But fast_page_fault is very unlikely to happen with PML
3384 * enabled, so we do not do this. This might result in the same GPA
3385 * to be logged in PML buffer again when the write really happens, and
3386 * eventually to be called by mark_page_dirty twice. But it's also no
3387 * harm. This also avoids the TLB flush needed after setting dirty bit
3388 * so non-PML cases won't be impacted.
3390 * Compare with set_spte where instead shadow_dirty_mask is set.
3392 if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3395 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3396 mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3401 static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3404 return is_executable_pte(spte);
3407 return is_writable_pte(spte);
3409 /* Fault was on Read access */
3410 return spte & PT_PRESENT_MASK;
3414 * Returns the last level spte pointer of the shadow page walk for the given
3415 * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
3416 * walk could be performed, returns NULL and *spte does not contain valid data.
3419 * - Must be called between walk_shadow_page_lockless_{begin,end}.
3420 * - The returned sptep must not be used after walk_shadow_page_lockless_end.
3422 static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
3424 struct kvm_shadow_walk_iterator iterator;
3428 for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
3429 sptep = iterator.sptep;
3437 * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3439 static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3441 struct kvm_mmu_page *sp;
3442 int ret = RET_PF_INVALID;
3445 uint retry_count = 0;
3447 if (!page_fault_can_be_fast(fault))
3450 walk_shadow_page_lockless_begin(vcpu);
3455 if (tdp_mmu_enabled)
3456 sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3458 sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3460 if (!is_shadow_present_pte(spte))
3463 sp = sptep_to_sp(sptep);
3464 if (!is_last_spte(spte, sp->role.level))
3468 * Check whether the memory access that caused the fault would
3469 * still cause it if it were to be performed right now. If not,
3470 * then this is a spurious fault caused by TLB lazily flushed,
3471 * or some other CPU has already fixed the PTE after the
3472 * current CPU took the fault.
3474 * Need not check the access of upper level table entries since
3475 * they are always ACC_ALL.
3477 if (is_access_allowed(fault, spte)) {
3478 ret = RET_PF_SPURIOUS;
3485 * KVM only supports fixing page faults outside of MMU lock for
3486 * direct MMUs, nested MMUs are always indirect, and KVM always
3487 * uses A/D bits for non-nested MMUs. Thus, if A/D bits are
3488 * enabled, the SPTE can't be an access-tracked SPTE.
3490 if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3491 new_spte = restore_acc_track_spte(new_spte);
3494 * To keep things simple, only SPTEs that are MMU-writable can
3495 * be made fully writable outside of mmu_lock, e.g. only SPTEs
3496 * that were write-protected for dirty-logging or access
3497 * tracking are handled here. Don't bother checking if the
3498 * SPTE is writable to prioritize running with A/D bits enabled.
3499 * The is_access_allowed() check above handles the common case
3500 * of the fault being spurious, and the SPTE is known to be
3501 * shadow-present, i.e. except for access tracking restoration
3502 * making the new SPTE writable, the check is wasteful.
3504 if (fault->write && is_mmu_writable_spte(spte)) {
3505 new_spte |= PT_WRITABLE_MASK;
3508 * Do not fix write-permission on the large spte when
3509 * dirty logging is enabled. Since we only dirty the
3510 * first page into the dirty-bitmap in
3511 * fast_pf_fix_direct_spte(), other pages are missed
3512 * if its slot has dirty logging enabled.
3514 * Instead, we let the slow page fault path create a
3515 * normal spte to fix the access.
3517 if (sp->role.level > PG_LEVEL_4K &&
3518 kvm_slot_dirty_track_enabled(fault->slot))
3522 /* Verify that the fault can be handled in the fast path */
3523 if (new_spte == spte ||
3524 !is_access_allowed(fault, new_spte))
3528 * Currently, fast page fault only works for direct mapping
3529 * since the gfn is not stable for indirect shadow page. See
3530 * Documentation/virt/kvm/locking.rst to get more detail.
3532 if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3537 if (++retry_count > 4) {
3538 pr_warn_once("Fast #PF retrying more than 4 times.\n");
3544 trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3545 walk_shadow_page_lockless_end(vcpu);
3547 if (ret != RET_PF_INVALID)
3548 vcpu->stat.pf_fast++;
3553 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3554 struct list_head *invalid_list)
3556 struct kvm_mmu_page *sp;
3558 if (!VALID_PAGE(*root_hpa))
3562 * The "root" may be a special root, e.g. a PAE entry, treat it as a
3563 * SPTE to ensure any non-PA bits are dropped.
3565 sp = spte_to_child_sp(*root_hpa);
3569 if (is_tdp_mmu_page(sp))
3570 kvm_tdp_mmu_put_root(kvm, sp, false);
3571 else if (!--sp->root_count && sp->role.invalid)
3572 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3574 *root_hpa = INVALID_PAGE;
3577 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3578 void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3579 ulong roots_to_free)
3582 LIST_HEAD(invalid_list);
3583 bool free_active_root;
3585 WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3587 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3589 /* Before acquiring the MMU lock, see if we need to do any real work. */
3590 free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3591 && VALID_PAGE(mmu->root.hpa);
3593 if (!free_active_root) {
3594 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3595 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3596 VALID_PAGE(mmu->prev_roots[i].hpa))
3599 if (i == KVM_MMU_NUM_PREV_ROOTS)
3603 write_lock(&kvm->mmu_lock);
3605 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3606 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3607 mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3610 if (free_active_root) {
3611 if (to_shadow_page(mmu->root.hpa)) {
3612 mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
3613 } else if (mmu->pae_root) {
3614 for (i = 0; i < 4; ++i) {
3615 if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3618 mmu_free_root_page(kvm, &mmu->pae_root[i],
3620 mmu->pae_root[i] = INVALID_PAE_ROOT;
3623 mmu->root.hpa = INVALID_PAGE;
3627 kvm_mmu_commit_zap_page(kvm, &invalid_list);
3628 write_unlock(&kvm->mmu_lock);
3630 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3632 void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
3634 unsigned long roots_to_free = 0;
3639 * This should not be called while L2 is active, L2 can't invalidate
3640 * _only_ its own roots, e.g. INVVPID unconditionally exits.
3642 WARN_ON_ONCE(mmu->root_role.guest_mode);
3644 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
3645 root_hpa = mmu->prev_roots[i].hpa;
3646 if (!VALID_PAGE(root_hpa))
3649 if (!to_shadow_page(root_hpa) ||
3650 to_shadow_page(root_hpa)->role.guest_mode)
3651 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
3654 kvm_mmu_free_roots(kvm, mmu, roots_to_free);
3656 EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
3659 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3663 if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3664 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3671 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
3674 union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3675 struct kvm_mmu_page *sp;
3678 role.quadrant = quadrant;
3680 WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
3681 WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
3683 sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
3686 return __pa(sp->spt);
3689 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3691 struct kvm_mmu *mmu = vcpu->arch.mmu;
3692 u8 shadow_root_level = mmu->root_role.level;
3697 write_lock(&vcpu->kvm->mmu_lock);
3698 r = make_mmu_pages_available(vcpu);
3702 if (tdp_mmu_enabled) {
3703 root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3704 mmu->root.hpa = root;
3705 } else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3706 root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3707 mmu->root.hpa = root;
3708 } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3709 if (WARN_ON_ONCE(!mmu->pae_root)) {
3714 for (i = 0; i < 4; ++i) {
3715 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3717 root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
3719 mmu->pae_root[i] = root | PT_PRESENT_MASK |
3722 mmu->root.hpa = __pa(mmu->pae_root);
3724 WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
3729 /* root.pgd is ignored for direct MMUs. */
3732 write_unlock(&vcpu->kvm->mmu_lock);
3736 static int mmu_first_shadow_root_alloc(struct kvm *kvm)
3738 struct kvm_memslots *slots;
3739 struct kvm_memory_slot *slot;
3743 * Check if this is the first shadow root being allocated before
3746 if (kvm_shadow_root_allocated(kvm))
3749 mutex_lock(&kvm->slots_arch_lock);
3751 /* Recheck, under the lock, whether this is the first shadow root. */
3752 if (kvm_shadow_root_allocated(kvm))
3756 * Check if anything actually needs to be allocated, e.g. all metadata
3757 * will be allocated upfront if TDP is disabled.
3759 if (kvm_memslots_have_rmaps(kvm) &&
3760 kvm_page_track_write_tracking_enabled(kvm))
3763 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
3764 slots = __kvm_memslots(kvm, i);
3765 kvm_for_each_memslot(slot, bkt, slots) {
3767 * Both of these functions are no-ops if the target is
3768 * already allocated, so unconditionally calling both
3769 * is safe. Intentionally do NOT free allocations on
3770 * failure to avoid having to track which allocations
3771 * were made now versus when the memslot was created.
3772 * The metadata is guaranteed to be freed when the slot
3773 * is freed, and will be kept/used if userspace retries
3774 * KVM_RUN instead of killing the VM.
3776 r = memslot_rmap_alloc(slot, slot->npages);
3779 r = kvm_page_track_write_tracking_alloc(slot);
3786 * Ensure that shadow_root_allocated becomes true strictly after
3787 * all the related pointers are set.
3790 smp_store_release(&kvm->arch.shadow_root_allocated, true);
3793 mutex_unlock(&kvm->slots_arch_lock);
3797 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3799 struct kvm_mmu *mmu = vcpu->arch.mmu;
3800 u64 pdptrs[4], pm_mask;
3801 gfn_t root_gfn, root_pgd;
3805 root_pgd = mmu->get_guest_pgd(vcpu);
3806 root_gfn = root_pgd >> PAGE_SHIFT;
3808 if (mmu_check_root(vcpu, root_gfn))
3812 * On SVM, reading PDPTRs might access guest memory, which might fault
3813 * and thus might sleep. Grab the PDPTRs before acquiring mmu_lock.
3815 if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3816 for (i = 0; i < 4; ++i) {
3817 pdptrs[i] = mmu->get_pdptr(vcpu, i);
3818 if (!(pdptrs[i] & PT_PRESENT_MASK))
3821 if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
3826 r = mmu_first_shadow_root_alloc(vcpu->kvm);
3830 write_lock(&vcpu->kvm->mmu_lock);
3831 r = make_mmu_pages_available(vcpu);
3836 * Do we shadow a long mode page table? If so we need to
3837 * write-protect the guests page table root.
3839 if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3840 root = mmu_alloc_root(vcpu, root_gfn, 0,
3841 mmu->root_role.level);
3842 mmu->root.hpa = root;
3846 if (WARN_ON_ONCE(!mmu->pae_root)) {
3852 * We shadow a 32 bit page table. This may be a legacy 2-level
3853 * or a PAE 3-level page table. In either case we need to be aware that
3854 * the shadow page table may be a PAE or a long mode page table.
3856 pm_mask = PT_PRESENT_MASK | shadow_me_value;
3857 if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3858 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3860 if (WARN_ON_ONCE(!mmu->pml4_root)) {
3864 mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3866 if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3867 if (WARN_ON_ONCE(!mmu->pml5_root)) {
3871 mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3875 for (i = 0; i < 4; ++i) {
3876 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3878 if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3879 if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3880 mmu->pae_root[i] = INVALID_PAE_ROOT;
3883 root_gfn = pdptrs[i] >> PAGE_SHIFT;
3887 * If shadowing 32-bit non-PAE page tables, each PAE page
3888 * directory maps one quarter of the guest's non-PAE page
3889 * directory. Othwerise each PAE page direct shadows one guest
3890 * PAE page directory so that quadrant should be 0.
3892 quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
3894 root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3895 mmu->pae_root[i] = root | pm_mask;
3898 if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3899 mmu->root.hpa = __pa(mmu->pml5_root);
3900 else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3901 mmu->root.hpa = __pa(mmu->pml4_root);
3903 mmu->root.hpa = __pa(mmu->pae_root);
3906 mmu->root.pgd = root_pgd;
3908 write_unlock(&vcpu->kvm->mmu_lock);
3913 static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3915 struct kvm_mmu *mmu = vcpu->arch.mmu;
3916 bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3917 u64 *pml5_root = NULL;
3918 u64 *pml4_root = NULL;
3922 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3923 * tables are allocated and initialized at root creation as there is no
3924 * equivalent level in the guest's NPT to shadow. Allocate the tables
3925 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3927 if (mmu->root_role.direct ||
3928 mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3929 mmu->root_role.level < PT64_ROOT_4LEVEL)
3933 * NPT, the only paging mode that uses this horror, uses a fixed number
3934 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3935 * all MMus are 5-level. Thus, this can safely require that pml5_root
3936 * is allocated if the other roots are valid and pml5 is needed, as any
3937 * prior MMU would also have required pml5.
3939 if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3943 * The special roots should always be allocated in concert. Yell and
3944 * bail if KVM ends up in a state where only one of the roots is valid.
3946 if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3947 (need_pml5 && mmu->pml5_root)))
3951 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
3952 * doesn't need to be decrypted.
3954 pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3958 #ifdef CONFIG_X86_64
3959 pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3964 pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3970 mmu->pae_root = pae_root;
3971 mmu->pml4_root = pml4_root;
3972 mmu->pml5_root = pml5_root;
3976 #ifdef CONFIG_X86_64
3978 free_page((unsigned long)pml4_root);
3980 free_page((unsigned long)pae_root);
3985 static bool is_unsync_root(hpa_t root)
3987 struct kvm_mmu_page *sp;
3989 if (!VALID_PAGE(root))
3993 * The read barrier orders the CPU's read of SPTE.W during the page table
3994 * walk before the reads of sp->unsync/sp->unsync_children here.
3996 * Even if another CPU was marking the SP as unsync-ed simultaneously,
3997 * any guest page table changes are not guaranteed to be visible anyway
3998 * until this VCPU issues a TLB flush strictly after those changes are
3999 * made. We only need to ensure that the other CPU sets these flags
4000 * before any actual changes to the page tables are made. The comments
4001 * in mmu_try_to_unsync_pages() describe what could go wrong if this
4002 * requirement isn't satisfied.
4005 sp = to_shadow_page(root);
4008 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
4009 * PDPTEs for a given PAE root need to be synchronized individually.
4011 if (WARN_ON_ONCE(!sp))
4014 if (sp->unsync || sp->unsync_children)
4020 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
4023 struct kvm_mmu_page *sp;
4025 if (vcpu->arch.mmu->root_role.direct)
4028 if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
4031 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4033 if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
4034 hpa_t root = vcpu->arch.mmu->root.hpa;
4035 sp = to_shadow_page(root);
4037 if (!is_unsync_root(root))
4040 write_lock(&vcpu->kvm->mmu_lock);
4041 mmu_sync_children(vcpu, sp, true);
4042 write_unlock(&vcpu->kvm->mmu_lock);
4046 write_lock(&vcpu->kvm->mmu_lock);
4048 for (i = 0; i < 4; ++i) {
4049 hpa_t root = vcpu->arch.mmu->pae_root[i];
4051 if (IS_VALID_PAE_ROOT(root)) {
4052 sp = spte_to_child_sp(root);
4053 mmu_sync_children(vcpu, sp, true);
4057 write_unlock(&vcpu->kvm->mmu_lock);
4060 void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
4062 unsigned long roots_to_free = 0;
4065 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4066 if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
4067 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
4069 /* sync prev_roots by simply freeing them */
4070 kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
4073 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4074 gpa_t vaddr, u64 access,
4075 struct x86_exception *exception)
4078 exception->error_code = 0;
4079 return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4082 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4085 * A nested guest cannot use the MMIO cache if it is using nested
4086 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4088 if (mmu_is_nested(vcpu))
4092 return vcpu_match_mmio_gpa(vcpu, addr);
4094 return vcpu_match_mmio_gva(vcpu, addr);
4098 * Return the level of the lowest level SPTE added to sptes.
4099 * That SPTE may be non-present.
4101 * Must be called between walk_shadow_page_lockless_{begin,end}.
4103 static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4105 struct kvm_shadow_walk_iterator iterator;
4109 for (shadow_walk_init(&iterator, vcpu, addr),
4110 *root_level = iterator.level;
4111 shadow_walk_okay(&iterator);
4112 __shadow_walk_next(&iterator, spte)) {
4113 leaf = iterator.level;
4114 spte = mmu_spte_get_lockless(iterator.sptep);
4122 /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
4123 static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
4125 u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
4126 struct rsvd_bits_validate *rsvd_check;
4127 int root, leaf, level;
4128 bool reserved = false;
4130 walk_shadow_page_lockless_begin(vcpu);
4132 if (is_tdp_mmu_active(vcpu))
4133 leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
4135 leaf = get_walk(vcpu, addr, sptes, &root);
4137 walk_shadow_page_lockless_end(vcpu);
4139 if (unlikely(leaf < 0)) {
4144 *sptep = sptes[leaf];
4147 * Skip reserved bits checks on the terminal leaf if it's not a valid
4148 * SPTE. Note, this also (intentionally) skips MMIO SPTEs, which, by
4149 * design, always have reserved bits set. The purpose of the checks is
4150 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
4152 if (!is_shadow_present_pte(sptes[leaf]))
4155 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
4157 for (level = root; level >= leaf; level--)
4158 reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4161 pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4163 for (level = root; level >= leaf; level--)
4164 pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4165 sptes[level], level,
4166 get_rsvd_bits(rsvd_check, sptes[level], level));
4172 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4177 if (mmio_info_in_cache(vcpu, addr, direct))
4178 return RET_PF_EMULATE;
4180 reserved = get_mmio_spte(vcpu, addr, &spte);
4181 if (WARN_ON(reserved))
4184 if (is_mmio_spte(spte)) {
4185 gfn_t gfn = get_mmio_spte_gfn(spte);
4186 unsigned int access = get_mmio_spte_access(spte);
4188 if (!check_mmio_spte(vcpu, spte))
4189 return RET_PF_INVALID;
4194 trace_handle_mmio_page_fault(addr, gfn, access);
4195 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4196 return RET_PF_EMULATE;
4200 * If the page table is zapped by other cpus, let CPU fault again on
4203 return RET_PF_RETRY;
4206 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4207 struct kvm_page_fault *fault)
4209 if (unlikely(fault->rsvd))
4212 if (!fault->present || !fault->write)
4216 * guest is writing the page which is write tracked which can
4217 * not be fixed by page fault handler.
4219 if (kvm_slot_page_track_is_active(vcpu->kvm, fault->slot, fault->gfn, KVM_PAGE_TRACK_WRITE))
4225 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4227 struct kvm_shadow_walk_iterator iterator;
4230 walk_shadow_page_lockless_begin(vcpu);
4231 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4232 clear_sp_write_flooding_count(iterator.sptep);
4233 walk_shadow_page_lockless_end(vcpu);
4236 static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
4238 /* make sure the token value is not 0 */
4239 u32 id = vcpu->arch.apf.id;
4242 vcpu->arch.apf.id = 1;
4244 return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4247 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4250 struct kvm_arch_async_pf arch;
4252 arch.token = alloc_apf_token(vcpu);
4254 arch.direct_map = vcpu->arch.mmu->root_role.direct;
4255 arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
4257 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4258 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4261 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
4265 if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
4269 r = kvm_mmu_reload(vcpu);
4273 if (!vcpu->arch.mmu->root_role.direct &&
4274 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
4277 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true, NULL);
4280 static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4282 struct kvm_memory_slot *slot = fault->slot;
4286 * Retry the page fault if the gfn hit a memslot that is being deleted
4287 * or moved. This ensures any existing SPTEs for the old memslot will
4288 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4290 if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
4291 return RET_PF_RETRY;
4293 if (!kvm_is_visible_memslot(slot)) {
4294 /* Don't expose private memslots to L2. */
4295 if (is_guest_mode(vcpu)) {
4297 fault->pfn = KVM_PFN_NOSLOT;
4298 fault->map_writable = false;
4299 return RET_PF_CONTINUE;
4302 * If the APIC access page exists but is disabled, go directly
4303 * to emulation without caching the MMIO access or creating a
4304 * MMIO SPTE. That way the cache doesn't need to be purged
4305 * when the AVIC is re-enabled.
4307 if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
4308 !kvm_apicv_activated(vcpu->kvm))
4309 return RET_PF_EMULATE;
4313 fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, false, &async,
4314 fault->write, &fault->map_writable,
4317 return RET_PF_CONTINUE; /* *pfn has correct page already */
4319 if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
4320 trace_kvm_try_async_get_page(fault->addr, fault->gfn);
4321 if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
4322 trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4323 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4324 return RET_PF_RETRY;
4325 } else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
4326 return RET_PF_RETRY;
4331 * Allow gup to bail on pending non-fatal signals when it's also allowed
4332 * to wait for IO. Note, gup always bails if it is unable to quickly
4333 * get a page and a fatal signal, i.e. SIGKILL, is pending.
4335 fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, true, NULL,
4336 fault->write, &fault->map_writable,
4338 return RET_PF_CONTINUE;
4341 static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4342 unsigned int access)
4346 fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4349 ret = __kvm_faultin_pfn(vcpu, fault);
4350 if (ret != RET_PF_CONTINUE)
4353 if (unlikely(is_error_pfn(fault->pfn)))
4354 return kvm_handle_error_pfn(vcpu, fault);
4356 if (unlikely(!fault->slot))
4357 return kvm_handle_noslot_fault(vcpu, fault, access);
4359 return RET_PF_CONTINUE;
4363 * Returns true if the page fault is stale and needs to be retried, i.e. if the
4364 * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4366 static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4367 struct kvm_page_fault *fault)
4369 struct kvm_mmu_page *sp = to_shadow_page(vcpu->arch.mmu->root.hpa);
4371 /* Special roots, e.g. pae_root, are not backed by shadow pages. */
4372 if (sp && is_obsolete_sp(vcpu->kvm, sp))
4376 * Roots without an associated shadow page are considered invalid if
4377 * there is a pending request to free obsolete roots. The request is
4378 * only a hint that the current root _may_ be obsolete and needs to be
4379 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
4380 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
4381 * to reload even if no vCPU is actively using the root.
4383 if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4386 return fault->slot &&
4387 mmu_invalidate_retry_hva(vcpu->kvm, fault->mmu_seq, fault->hva);
4390 static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4394 if (page_fault_handle_page_track(vcpu, fault))
4395 return RET_PF_EMULATE;
4397 r = fast_page_fault(vcpu, fault);
4398 if (r != RET_PF_INVALID)
4401 r = mmu_topup_memory_caches(vcpu, false);
4405 r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4406 if (r != RET_PF_CONTINUE)
4410 write_lock(&vcpu->kvm->mmu_lock);
4412 if (is_page_fault_stale(vcpu, fault))
4415 r = make_mmu_pages_available(vcpu);
4419 r = direct_map(vcpu, fault);
4422 write_unlock(&vcpu->kvm->mmu_lock);
4423 kvm_release_pfn_clean(fault->pfn);
4427 static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4428 struct kvm_page_fault *fault)
4430 pgprintk("%s: gva %lx error %x\n", __func__, fault->addr, fault->error_code);
4432 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4433 fault->max_level = PG_LEVEL_2M;
4434 return direct_page_fault(vcpu, fault);
4437 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4438 u64 fault_address, char *insn, int insn_len)
4441 u32 flags = vcpu->arch.apf.host_apf_flags;
4443 #ifndef CONFIG_X86_64
4444 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4445 if (WARN_ON_ONCE(fault_address >> 32))
4449 vcpu->arch.l1tf_flush_l1d = true;
4451 trace_kvm_page_fault(vcpu, fault_address, error_code);
4453 if (kvm_event_needs_reinjection(vcpu))
4454 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4455 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4457 } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
4458 vcpu->arch.apf.host_apf_flags = 0;
4459 local_irq_disable();
4460 kvm_async_pf_task_wait_schedule(fault_address);
4463 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4468 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4470 #ifdef CONFIG_X86_64
4471 static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
4472 struct kvm_page_fault *fault)
4476 if (page_fault_handle_page_track(vcpu, fault))
4477 return RET_PF_EMULATE;
4479 r = fast_page_fault(vcpu, fault);
4480 if (r != RET_PF_INVALID)
4483 r = mmu_topup_memory_caches(vcpu, false);
4487 r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4488 if (r != RET_PF_CONTINUE)
4492 read_lock(&vcpu->kvm->mmu_lock);
4494 if (is_page_fault_stale(vcpu, fault))
4497 r = kvm_tdp_mmu_map(vcpu, fault);
4500 read_unlock(&vcpu->kvm->mmu_lock);
4501 kvm_release_pfn_clean(fault->pfn);
4506 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4509 * If the guest's MTRRs may be used to compute the "real" memtype,
4510 * restrict the mapping level to ensure KVM uses a consistent memtype
4511 * across the entire mapping. If the host MTRRs are ignored by TDP
4512 * (shadow_memtype_mask is non-zero), and the VM has non-coherent DMA
4513 * (DMA doesn't snoop CPU caches), KVM's ABI is to honor the memtype
4514 * from the guest's MTRRs so that guest accesses to memory that is
4515 * DMA'd aren't cached against the guest's wishes.
4517 * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
4518 * e.g. KVM will force UC memtype for host MMIO.
4520 if (shadow_memtype_mask && kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
4521 for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
4522 int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
4523 gfn_t base = gfn_round_for_level(fault->gfn,
4526 if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4531 #ifdef CONFIG_X86_64
4532 if (tdp_mmu_enabled)
4533 return kvm_tdp_mmu_page_fault(vcpu, fault);
4536 return direct_page_fault(vcpu, fault);
4539 static void nonpaging_init_context(struct kvm_mmu *context)
4541 context->page_fault = nonpaging_page_fault;
4542 context->gva_to_gpa = nonpaging_gva_to_gpa;
4543 context->sync_spte = NULL;
4546 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
4547 union kvm_mmu_page_role role)
4549 return (role.direct || pgd == root->pgd) &&
4550 VALID_PAGE(root->hpa) &&
4551 role.word == to_shadow_page(root->hpa)->role.word;
4555 * Find out if a previously cached root matching the new pgd/role is available,
4556 * and insert the current root as the MRU in the cache.
4557 * If a matching root is found, it is assigned to kvm_mmu->root and
4559 * If no match is found, kvm_mmu->root is left invalid, the LRU root is
4560 * evicted to make room for the current root, and false is returned.
4562 static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
4564 union kvm_mmu_page_role new_role)
4568 if (is_root_usable(&mmu->root, new_pgd, new_role))
4571 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4573 * The swaps end up rotating the cache like this:
4574 * C 0 1 2 3 (on entry to the function)
4578 * 3 C 0 1 2 (on exit from the loop)
4580 swap(mmu->root, mmu->prev_roots[i]);
4581 if (is_root_usable(&mmu->root, new_pgd, new_role))
4585 kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4590 * Find out if a previously cached root matching the new pgd/role is available.
4591 * On entry, mmu->root is invalid.
4592 * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
4593 * of the cache becomes invalid, and true is returned.
4594 * If no match is found, kvm_mmu->root is left invalid and false is returned.
4596 static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
4598 union kvm_mmu_page_role new_role)
4602 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4603 if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
4609 swap(mmu->root, mmu->prev_roots[i]);
4610 /* Bubble up the remaining roots. */
4611 for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
4612 mmu->prev_roots[i] = mmu->prev_roots[i + 1];
4613 mmu->prev_roots[i].hpa = INVALID_PAGE;
4617 static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
4618 gpa_t new_pgd, union kvm_mmu_page_role new_role)
4621 * For now, limit the caching to 64-bit hosts+VMs in order to avoid
4622 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4623 * later if necessary.
4625 if (VALID_PAGE(mmu->root.hpa) && !to_shadow_page(mmu->root.hpa))
4626 kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4628 if (VALID_PAGE(mmu->root.hpa))
4629 return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
4631 return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4634 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4636 struct kvm_mmu *mmu = vcpu->arch.mmu;
4637 union kvm_mmu_page_role new_role = mmu->root_role;
4640 * Return immediately if no usable root was found, kvm_mmu_reload()
4641 * will establish a valid root prior to the next VM-Enter.
4643 if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4647 * It's possible that the cached previous root page is obsolete because
4648 * of a change in the MMU generation number. However, changing the
4649 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4650 * which will free the root set here and allocate a new one.
4652 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4654 if (force_flush_and_sync_on_reuse) {
4655 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4656 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4660 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4661 * switching to a new CR3, that GVA->GPA mapping may no longer be
4662 * valid. So clear any cached MMIO info even when we don't need to sync
4663 * the shadow page tables.
4665 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4668 * If this is a direct root page, it doesn't have a write flooding
4669 * count. Otherwise, clear the write flooding count.
4671 if (!new_role.direct)
4672 __clear_sp_write_flooding_count(
4673 to_shadow_page(vcpu->arch.mmu->root.hpa));
4675 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4677 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4679 return kvm_read_cr3(vcpu);
4682 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4683 unsigned int access)
4685 if (unlikely(is_mmio_spte(*sptep))) {
4686 if (gfn != get_mmio_spte_gfn(*sptep)) {
4687 mmu_spte_clear_no_track(sptep);
4691 mark_mmio_spte(vcpu, sptep, gfn, access);
4698 #define PTTYPE_EPT 18 /* arbitrary */
4699 #define PTTYPE PTTYPE_EPT
4700 #include "paging_tmpl.h"
4704 #include "paging_tmpl.h"
4708 #include "paging_tmpl.h"
4712 __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
4713 u64 pa_bits_rsvd, int level, bool nx, bool gbpages,
4716 u64 gbpages_bit_rsvd = 0;
4717 u64 nonleaf_bit8_rsvd = 0;
4720 rsvd_check->bad_mt_xwr = 0;
4723 gbpages_bit_rsvd = rsvd_bits(7, 7);
4725 if (level == PT32E_ROOT_LEVEL)
4726 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
4728 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4730 /* Note, NX doesn't exist in PDPTEs, this is handled below. */
4732 high_bits_rsvd |= rsvd_bits(63, 63);
4735 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4736 * leaf entries) on AMD CPUs only.
4739 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4742 case PT32_ROOT_LEVEL:
4743 /* no rsvd bits for 2 level 4K page table entries */
4744 rsvd_check->rsvd_bits_mask[0][1] = 0;
4745 rsvd_check->rsvd_bits_mask[0][0] = 0;
4746 rsvd_check->rsvd_bits_mask[1][0] =
4747 rsvd_check->rsvd_bits_mask[0][0];
4750 rsvd_check->rsvd_bits_mask[1][1] = 0;
4754 if (is_cpuid_PSE36())
4755 /* 36bits PSE 4MB page */
4756 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4758 /* 32 bits PSE 4MB page */
4759 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4761 case PT32E_ROOT_LEVEL:
4762 rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
4765 rsvd_bits(1, 2); /* PDPTE */
4766 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd; /* PDE */
4767 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd; /* PTE */
4768 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4769 rsvd_bits(13, 20); /* large page */
4770 rsvd_check->rsvd_bits_mask[1][0] =
4771 rsvd_check->rsvd_bits_mask[0][0];
4773 case PT64_ROOT_5LEVEL:
4774 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
4777 rsvd_check->rsvd_bits_mask[1][4] =
4778 rsvd_check->rsvd_bits_mask[0][4];
4780 case PT64_ROOT_4LEVEL:
4781 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
4784 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
4786 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
4787 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4788 rsvd_check->rsvd_bits_mask[1][3] =
4789 rsvd_check->rsvd_bits_mask[0][3];
4790 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
4793 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4794 rsvd_bits(13, 20); /* large page */
4795 rsvd_check->rsvd_bits_mask[1][0] =
4796 rsvd_check->rsvd_bits_mask[0][0];
4801 static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
4804 * If TDP is enabled, let the guest use GBPAGES if they're supported in
4805 * hardware. The hardware page walker doesn't let KVM disable GBPAGES,
4806 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
4807 * walk for performance and complexity reasons. Not to mention KVM
4808 * _can't_ solve the problem because GVA->GPA walks aren't visible to
4809 * KVM once a TDP translation is installed. Mimic hardware behavior so
4810 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
4812 return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
4813 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
4816 static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4817 struct kvm_mmu *context)
4819 __reset_rsvds_bits_mask(&context->guest_rsvd_check,
4820 vcpu->arch.reserved_gpa_bits,
4821 context->cpu_role.base.level, is_efer_nx(context),
4822 guest_can_use_gbpages(vcpu),
4823 is_cr4_pse(context),
4824 guest_cpuid_is_amd_or_hygon(vcpu));
4828 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4829 u64 pa_bits_rsvd, bool execonly, int huge_page_level)
4831 u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4832 u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4835 if (huge_page_level < PG_LEVEL_1G)
4836 large_1g_rsvd = rsvd_bits(7, 7);
4837 if (huge_page_level < PG_LEVEL_2M)
4838 large_2m_rsvd = rsvd_bits(7, 7);
4840 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
4841 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
4842 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
4843 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
4844 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4847 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4848 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4849 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
4850 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4851 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4853 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4854 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4855 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4856 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4857 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4859 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4860 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4862 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4865 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4866 struct kvm_mmu *context, bool execonly, int huge_page_level)
4868 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4869 vcpu->arch.reserved_gpa_bits, execonly,
4873 static inline u64 reserved_hpa_bits(void)
4875 return rsvd_bits(shadow_phys_bits, 63);
4879 * the page table on host is the shadow page table for the page
4880 * table in guest or amd nested guest, its mmu features completely
4881 * follow the features in guest.
4883 static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4884 struct kvm_mmu *context)
4886 /* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
4888 /* KVM doesn't use 2-level page tables for the shadow MMU. */
4889 bool is_pse = false;
4890 struct rsvd_bits_validate *shadow_zero_check;
4893 WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
4895 shadow_zero_check = &context->shadow_zero_check;
4896 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4897 context->root_role.level,
4898 context->root_role.efer_nx,
4899 guest_can_use_gbpages(vcpu), is_pse, is_amd);
4901 if (!shadow_me_mask)
4904 for (i = context->root_role.level; --i >= 0;) {
4906 * So far shadow_me_value is a constant during KVM's life
4907 * time. Bits in shadow_me_value are allowed to be set.
4908 * Bits in shadow_me_mask but not in shadow_me_value are
4909 * not allowed to be set.
4911 shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4912 shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4913 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4914 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4919 static inline bool boot_cpu_is_amd(void)
4921 WARN_ON_ONCE(!tdp_enabled);
4922 return shadow_x_mask == 0;
4926 * the direct page table on host, use as much mmu features as
4927 * possible, however, kvm currently does not do execution-protection.
4930 reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4932 struct rsvd_bits_validate *shadow_zero_check;
4935 shadow_zero_check = &context->shadow_zero_check;
4937 if (boot_cpu_is_amd())
4938 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4939 context->root_role.level, true,
4940 boot_cpu_has(X86_FEATURE_GBPAGES),
4943 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4944 reserved_hpa_bits(), false,
4945 max_huge_page_level);
4947 if (!shadow_me_mask)
4950 for (i = context->root_role.level; --i >= 0;) {
4951 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4952 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4957 * as the comments in reset_shadow_zero_bits_mask() except it
4958 * is the shadow page table for intel nested guest.
4961 reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
4963 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4964 reserved_hpa_bits(), execonly,
4965 max_huge_page_level);
4968 #define BYTE_MASK(access) \
4969 ((1 & (access) ? 2 : 0) | \
4970 (2 & (access) ? 4 : 0) | \
4971 (3 & (access) ? 8 : 0) | \
4972 (4 & (access) ? 16 : 0) | \
4973 (5 & (access) ? 32 : 0) | \
4974 (6 & (access) ? 64 : 0) | \
4975 (7 & (access) ? 128 : 0))
4978 static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4982 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4983 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4984 const u8 u = BYTE_MASK(ACC_USER_MASK);
4986 bool cr4_smep = is_cr4_smep(mmu);
4987 bool cr4_smap = is_cr4_smap(mmu);
4988 bool cr0_wp = is_cr0_wp(mmu);
4989 bool efer_nx = is_efer_nx(mmu);
4991 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4992 unsigned pfec = byte << 1;
4995 * Each "*f" variable has a 1 bit for each UWX value
4996 * that causes a fault with the given PFEC.
4999 /* Faults from writes to non-writable pages */
5000 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
5001 /* Faults from user mode accesses to supervisor pages */
5002 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
5003 /* Faults from fetches of non-executable pages*/
5004 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
5005 /* Faults from kernel mode fetches of user pages */
5007 /* Faults from kernel mode accesses of user pages */
5011 /* Faults from kernel mode accesses to user pages */
5012 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
5014 /* Not really needed: !nx will cause pte.nx to fault */
5018 /* Allow supervisor writes if !cr0.wp */
5020 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
5022 /* Disallow supervisor fetches of user code if cr4.smep */
5024 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
5027 * SMAP:kernel-mode data accesses from user-mode
5028 * mappings should fault. A fault is considered
5029 * as a SMAP violation if all of the following
5030 * conditions are true:
5031 * - X86_CR4_SMAP is set in CR4
5032 * - A user page is accessed
5033 * - The access is not a fetch
5034 * - The access is supervisor mode
5035 * - If implicit supervisor access or X86_EFLAGS_AC is clear
5037 * Here, we cover the first four conditions.
5038 * The fifth is computed dynamically in permission_fault();
5039 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5040 * *not* subject to SMAP restrictions.
5043 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5046 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5051 * PKU is an additional mechanism by which the paging controls access to
5052 * user-mode addresses based on the value in the PKRU register. Protection
5053 * key violations are reported through a bit in the page fault error code.
5054 * Unlike other bits of the error code, the PK bit is not known at the
5055 * call site of e.g. gva_to_gpa; it must be computed directly in
5056 * permission_fault based on two bits of PKRU, on some machine state (CR4,
5057 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5059 * In particular the following conditions come from the error code, the
5060 * page tables and the machine state:
5061 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5062 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5063 * - PK is always zero if U=0 in the page tables
5064 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5066 * The PKRU bitmask caches the result of these four conditions. The error
5067 * code (minus the P bit) and the page table's U bit form an index into the
5068 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
5069 * with the two bits of the PKRU register corresponding to the protection key.
5070 * For the first three conditions above the bits will be 00, thus masking
5071 * away both AD and WD. For all reads or if the last condition holds, WD
5072 * only will be masked away.
5074 static void update_pkru_bitmask(struct kvm_mmu *mmu)
5081 if (!is_cr4_pke(mmu))
5084 wp = is_cr0_wp(mmu);
5086 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5087 unsigned pfec, pkey_bits;
5088 bool check_pkey, check_write, ff, uf, wf, pte_user;
5091 ff = pfec & PFERR_FETCH_MASK;
5092 uf = pfec & PFERR_USER_MASK;
5093 wf = pfec & PFERR_WRITE_MASK;
5095 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
5096 pte_user = pfec & PFERR_RSVD_MASK;
5099 * Only need to check the access which is not an
5100 * instruction fetch and is to a user page.
5102 check_pkey = (!ff && pte_user);
5104 * write access is controlled by PKRU if it is a
5105 * user access or CR0.WP = 1.
5107 check_write = check_pkey && wf && (uf || wp);
5109 /* PKRU.AD stops both read and write access. */
5110 pkey_bits = !!check_pkey;
5111 /* PKRU.WD stops write access. */
5112 pkey_bits |= (!!check_write) << 1;
5114 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5118 static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5119 struct kvm_mmu *mmu)
5121 if (!is_cr0_pg(mmu))
5124 reset_guest_rsvds_bits_mask(vcpu, mmu);
5125 update_permission_bitmask(mmu, false);
5126 update_pkru_bitmask(mmu);
5129 static void paging64_init_context(struct kvm_mmu *context)
5131 context->page_fault = paging64_page_fault;
5132 context->gva_to_gpa = paging64_gva_to_gpa;
5133 context->sync_spte = paging64_sync_spte;
5136 static void paging32_init_context(struct kvm_mmu *context)
5138 context->page_fault = paging32_page_fault;
5139 context->gva_to_gpa = paging32_gva_to_gpa;
5140 context->sync_spte = paging32_sync_spte;
5143 static union kvm_cpu_role
5144 kvm_calc_cpu_role(struct kvm_vcpu *vcpu, const struct kvm_mmu_role_regs *regs)
5146 union kvm_cpu_role role = {0};
5148 role.base.access = ACC_ALL;
5149 role.base.smm = is_smm(vcpu);
5150 role.base.guest_mode = is_guest_mode(vcpu);
5153 if (!____is_cr0_pg(regs)) {
5154 role.base.direct = 1;
5158 role.base.efer_nx = ____is_efer_nx(regs);
5159 role.base.cr0_wp = ____is_cr0_wp(regs);
5160 role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5161 role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5162 role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
5164 if (____is_efer_lma(regs))
5165 role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
5167 else if (____is_cr4_pae(regs))
5168 role.base.level = PT32E_ROOT_LEVEL;
5170 role.base.level = PT32_ROOT_LEVEL;
5172 role.ext.cr4_smep = ____is_cr4_smep(regs);
5173 role.ext.cr4_smap = ____is_cr4_smap(regs);
5174 role.ext.cr4_pse = ____is_cr4_pse(regs);
5176 /* PKEY and LA57 are active iff long mode is active. */
5177 role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5178 role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5179 role.ext.efer_lma = ____is_efer_lma(regs);
5183 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5185 /* tdp_root_level is architecture forced level, use it if nonzero */
5187 return tdp_root_level;
5189 /* Use 5-level TDP if and only if it's useful/necessary. */
5190 if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5193 return max_tdp_level;
5196 static union kvm_mmu_page_role
5197 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
5198 union kvm_cpu_role cpu_role)
5200 union kvm_mmu_page_role role = {0};
5202 role.access = ACC_ALL;
5204 role.efer_nx = true;
5205 role.smm = cpu_role.base.smm;
5206 role.guest_mode = cpu_role.base.guest_mode;
5207 role.ad_disabled = !kvm_ad_enabled();
5208 role.level = kvm_mmu_get_tdp_level(vcpu);
5210 role.has_4_byte_gpte = false;
5215 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5216 union kvm_cpu_role cpu_role)
5218 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5219 union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5221 if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5222 root_role.word == context->root_role.word)
5225 context->cpu_role.as_u64 = cpu_role.as_u64;
5226 context->root_role.word = root_role.word;
5227 context->page_fault = kvm_tdp_page_fault;
5228 context->sync_spte = NULL;
5229 context->get_guest_pgd = get_cr3;
5230 context->get_pdptr = kvm_pdptr_read;
5231 context->inject_page_fault = kvm_inject_page_fault;
5233 if (!is_cr0_pg(context))
5234 context->gva_to_gpa = nonpaging_gva_to_gpa;
5235 else if (is_cr4_pae(context))
5236 context->gva_to_gpa = paging64_gva_to_gpa;
5238 context->gva_to_gpa = paging32_gva_to_gpa;
5240 reset_guest_paging_metadata(vcpu, context);
5241 reset_tdp_shadow_zero_bits_mask(context);
5244 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
5245 union kvm_cpu_role cpu_role,
5246 union kvm_mmu_page_role root_role)
5248 if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5249 root_role.word == context->root_role.word)
5252 context->cpu_role.as_u64 = cpu_role.as_u64;
5253 context->root_role.word = root_role.word;
5255 if (!is_cr0_pg(context))
5256 nonpaging_init_context(context);
5257 else if (is_cr4_pae(context))
5258 paging64_init_context(context);
5260 paging32_init_context(context);
5262 reset_guest_paging_metadata(vcpu, context);
5263 reset_shadow_zero_bits_mask(vcpu, context);
5266 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5267 union kvm_cpu_role cpu_role)
5269 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5270 union kvm_mmu_page_role root_role;
5272 root_role = cpu_role.base;
5274 /* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
5275 root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
5278 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
5279 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
5280 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
5281 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
5282 * The iTLB multi-hit workaround can be toggled at any time, so assume
5283 * NX can be used by any non-nested shadow MMU to avoid having to reset
5286 root_role.efer_nx = true;
5288 shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5291 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5292 unsigned long cr4, u64 efer, gpa_t nested_cr3)
5294 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5295 struct kvm_mmu_role_regs regs = {
5297 .cr4 = cr4 & ~X86_CR4_PKE,
5300 union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, ®s);
5301 union kvm_mmu_page_role root_role;
5303 /* NPT requires CR0.PG=1. */
5304 WARN_ON_ONCE(cpu_role.base.direct);
5306 root_role = cpu_role.base;
5307 root_role.level = kvm_mmu_get_tdp_level(vcpu);
5308 if (root_role.level == PT64_ROOT_5LEVEL &&
5309 cpu_role.base.level == PT64_ROOT_4LEVEL)
5310 root_role.passthrough = 1;
5312 shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5313 kvm_mmu_new_pgd(vcpu, nested_cr3);
5315 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5317 static union kvm_cpu_role
5318 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5319 bool execonly, u8 level)
5321 union kvm_cpu_role role = {0};
5324 * KVM does not support SMM transfer monitors, and consequently does not
5325 * support the "entry to SMM" control either. role.base.smm is always 0.
5327 WARN_ON_ONCE(is_smm(vcpu));
5328 role.base.level = level;
5329 role.base.has_4_byte_gpte = false;
5330 role.base.direct = false;
5331 role.base.ad_disabled = !accessed_dirty;
5332 role.base.guest_mode = true;
5333 role.base.access = ACC_ALL;
5336 role.ext.execonly = execonly;
5342 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5343 int huge_page_level, bool accessed_dirty,
5346 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5347 u8 level = vmx_eptp_page_walk_level(new_eptp);
5348 union kvm_cpu_role new_mode =
5349 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5352 if (new_mode.as_u64 != context->cpu_role.as_u64) {
5353 /* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5354 context->cpu_role.as_u64 = new_mode.as_u64;
5355 context->root_role.word = new_mode.base.word;
5357 context->page_fault = ept_page_fault;
5358 context->gva_to_gpa = ept_gva_to_gpa;
5359 context->sync_spte = ept_sync_spte;
5361 update_permission_bitmask(context, true);
5362 context->pkru_mask = 0;
5363 reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5364 reset_ept_shadow_zero_bits_mask(context, execonly);
5367 kvm_mmu_new_pgd(vcpu, new_eptp);
5369 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5371 static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5372 union kvm_cpu_role cpu_role)
5374 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5376 kvm_init_shadow_mmu(vcpu, cpu_role);
5378 context->get_guest_pgd = get_cr3;
5379 context->get_pdptr = kvm_pdptr_read;
5380 context->inject_page_fault = kvm_inject_page_fault;
5383 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5384 union kvm_cpu_role new_mode)
5386 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5388 if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5391 g_context->cpu_role.as_u64 = new_mode.as_u64;
5392 g_context->get_guest_pgd = get_cr3;
5393 g_context->get_pdptr = kvm_pdptr_read;
5394 g_context->inject_page_fault = kvm_inject_page_fault;
5397 * L2 page tables are never shadowed, so there is no need to sync
5400 g_context->sync_spte = NULL;
5403 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5404 * L1's nested page tables (e.g. EPT12). The nested translation
5405 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5406 * L2's page tables as the first level of translation and L1's
5407 * nested page tables as the second level of translation. Basically
5408 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5410 if (!is_paging(vcpu))
5411 g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5412 else if (is_long_mode(vcpu))
5413 g_context->gva_to_gpa = paging64_gva_to_gpa;
5414 else if (is_pae(vcpu))
5415 g_context->gva_to_gpa = paging64_gva_to_gpa;
5417 g_context->gva_to_gpa = paging32_gva_to_gpa;
5419 reset_guest_paging_metadata(vcpu, g_context);
5422 void kvm_init_mmu(struct kvm_vcpu *vcpu)
5424 struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5425 union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, ®s);
5427 if (mmu_is_nested(vcpu))
5428 init_kvm_nested_mmu(vcpu, cpu_role);
5429 else if (tdp_enabled)
5430 init_kvm_tdp_mmu(vcpu, cpu_role);
5432 init_kvm_softmmu(vcpu, cpu_role);
5434 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5436 void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
5439 * Invalidate all MMU roles to force them to reinitialize as CPUID
5440 * information is factored into reserved bit calculations.
5442 * Correctly handling multiple vCPU models with respect to paging and
5443 * physical address properties) in a single VM would require tracking
5444 * all relevant CPUID information in kvm_mmu_page_role. That is very
5445 * undesirable as it would increase the memory requirements for
5446 * gfn_track (see struct kvm_mmu_page_role comments). For now that
5447 * problem is swept under the rug; KVM's CPUID API is horrific and
5448 * it's all but impossible to solve it without introducing a new API.
5450 vcpu->arch.root_mmu.root_role.word = 0;
5451 vcpu->arch.guest_mmu.root_role.word = 0;
5452 vcpu->arch.nested_mmu.root_role.word = 0;
5453 vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5454 vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5455 vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
5456 kvm_mmu_reset_context(vcpu);
5459 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5460 * kvm_arch_vcpu_ioctl().
5462 KVM_BUG_ON(vcpu->arch.last_vmentry_cpu != -1, vcpu->kvm);
5465 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5467 kvm_mmu_unload(vcpu);
5470 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5472 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5476 r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5479 r = mmu_alloc_special_roots(vcpu);
5482 if (vcpu->arch.mmu->root_role.direct)
5483 r = mmu_alloc_direct_roots(vcpu);
5485 r = mmu_alloc_shadow_roots(vcpu);
5489 kvm_mmu_sync_roots(vcpu);
5491 kvm_mmu_load_pgd(vcpu);
5494 * Flush any TLB entries for the new root, the provenance of the root
5495 * is unknown. Even if KVM ensures there are no stale TLB entries
5496 * for a freed root, in theory another hypervisor could have left
5497 * stale entries. Flushing on alloc also allows KVM to skip the TLB
5498 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5500 static_call(kvm_x86_flush_tlb_current)(vcpu);
5505 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5507 struct kvm *kvm = vcpu->kvm;
5509 kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5510 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
5511 kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5512 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
5513 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5516 static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5518 struct kvm_mmu_page *sp;
5520 if (!VALID_PAGE(root_hpa))
5524 * When freeing obsolete roots, treat roots as obsolete if they don't
5525 * have an associated shadow page. This does mean KVM will get false
5526 * positives and free roots that don't strictly need to be freed, but
5527 * such false positives are relatively rare:
5529 * (a) only PAE paging and nested NPT has roots without shadow pages
5530 * (b) remote reloads due to a memslot update obsoletes _all_ roots
5531 * (c) KVM doesn't track previous roots for PAE paging, and the guest
5532 * is unlikely to zap an in-use PGD.
5534 sp = to_shadow_page(root_hpa);
5535 return !sp || is_obsolete_sp(kvm, sp);
5538 static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5540 unsigned long roots_to_free = 0;
5543 if (is_obsolete_root(kvm, mmu->root.hpa))
5544 roots_to_free |= KVM_MMU_ROOT_CURRENT;
5546 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5547 if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5548 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5552 kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5555 void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5557 __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5558 __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5561 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5568 * Assume that the pte write on a page table of the same type
5569 * as the current vcpu paging mode since we update the sptes only
5570 * when they have the same mode.
5572 if (is_pae(vcpu) && *bytes == 4) {
5573 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5578 if (*bytes == 4 || *bytes == 8) {
5579 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5588 * If we're seeing too many writes to a page, it may no longer be a page table,
5589 * or we may be forking, in which case it is better to unmap the page.
5591 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5594 * Skip write-flooding detected for the sp whose level is 1, because
5595 * it can become unsync, then the guest page is not write-protected.
5597 if (sp->role.level == PG_LEVEL_4K)
5600 atomic_inc(&sp->write_flooding_count);
5601 return atomic_read(&sp->write_flooding_count) >= 3;
5605 * Misaligned accesses are too much trouble to fix up; also, they usually
5606 * indicate a page is not used as a page table.
5608 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5611 unsigned offset, pte_size, misaligned;
5613 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5614 gpa, bytes, sp->role.word);
5616 offset = offset_in_page(gpa);
5617 pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5620 * Sometimes, the OS only writes the last one bytes to update status
5621 * bits, for example, in linux, andb instruction is used in clear_bit().
5623 if (!(offset & (pte_size - 1)) && bytes == 1)
5626 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5627 misaligned |= bytes < 4;
5632 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5634 unsigned page_offset, quadrant;
5638 page_offset = offset_in_page(gpa);
5639 level = sp->role.level;
5641 if (sp->role.has_4_byte_gpte) {
5642 page_offset <<= 1; /* 32->64 */
5644 * A 32-bit pde maps 4MB while the shadow pdes map
5645 * only 2MB. So we need to double the offset again
5646 * and zap two pdes instead of one.
5648 if (level == PT32_ROOT_LEVEL) {
5649 page_offset &= ~7; /* kill rounding error */
5653 quadrant = page_offset >> PAGE_SHIFT;
5654 page_offset &= ~PAGE_MASK;
5655 if (quadrant != sp->role.quadrant)
5659 spte = &sp->spt[page_offset / sizeof(*spte)];
5663 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5664 const u8 *new, int bytes,
5665 struct kvm_page_track_notifier_node *node)
5667 gfn_t gfn = gpa >> PAGE_SHIFT;
5668 struct kvm_mmu_page *sp;
5669 LIST_HEAD(invalid_list);
5670 u64 entry, gentry, *spte;
5675 * If we don't have indirect shadow pages, it means no page is
5676 * write-protected, so we can exit simply.
5678 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5681 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5683 write_lock(&vcpu->kvm->mmu_lock);
5685 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5687 ++vcpu->kvm->stat.mmu_pte_write;
5689 for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5690 if (detect_write_misaligned(sp, gpa, bytes) ||
5691 detect_write_flooding(sp)) {
5692 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5693 ++vcpu->kvm->stat.mmu_flooded;
5697 spte = get_written_sptes(sp, gpa, &npte);
5703 mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5704 if (gentry && sp->role.level != PG_LEVEL_4K)
5705 ++vcpu->kvm->stat.mmu_pde_zapped;
5706 if (is_shadow_present_pte(entry))
5711 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5712 write_unlock(&vcpu->kvm->mmu_lock);
5715 int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5716 void *insn, int insn_len)
5718 int r, emulation_type = EMULTYPE_PF;
5719 bool direct = vcpu->arch.mmu->root_role.direct;
5721 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5722 return RET_PF_RETRY;
5725 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5726 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5727 if (r == RET_PF_EMULATE)
5731 if (r == RET_PF_INVALID) {
5732 r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5733 lower_32_bits(error_code), false,
5735 if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
5741 if (r != RET_PF_EMULATE)
5745 * Before emulating the instruction, check if the error code
5746 * was due to a RO violation while translating the guest page.
5747 * This can occur when using nested virtualization with nested
5748 * paging in both guests. If true, we simply unprotect the page
5749 * and resume the guest.
5751 if (vcpu->arch.mmu->root_role.direct &&
5752 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5753 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5758 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5759 * optimistically try to just unprotect the page and let the processor
5760 * re-execute the instruction that caused the page fault. Do not allow
5761 * retrying MMIO emulation, as it's not only pointless but could also
5762 * cause us to enter an infinite loop because the processor will keep
5763 * faulting on the non-existent MMIO address. Retrying an instruction
5764 * from a nested guest is also pointless and dangerous as we are only
5765 * explicitly shadowing L1's page tables, i.e. unprotecting something
5766 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5768 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5769 emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5771 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5774 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5776 static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5777 u64 addr, hpa_t root_hpa)
5779 struct kvm_shadow_walk_iterator iterator;
5781 vcpu_clear_mmio_info(vcpu, addr);
5783 if (!VALID_PAGE(root_hpa))
5786 write_lock(&vcpu->kvm->mmu_lock);
5787 for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
5788 struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
5791 int ret = kvm_sync_spte(vcpu, sp, iterator.index);
5794 mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
5796 kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
5799 if (!sp->unsync_children)
5802 write_unlock(&vcpu->kvm->mmu_lock);
5805 void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5806 u64 addr, unsigned long roots)
5810 WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
5812 /* It's actually a GPA for vcpu->arch.guest_mmu. */
5813 if (mmu != &vcpu->arch.guest_mmu) {
5814 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
5815 if (is_noncanonical_address(addr, vcpu))
5818 static_call(kvm_x86_flush_tlb_gva)(vcpu, addr);
5821 if (!mmu->sync_spte)
5824 if (roots & KVM_MMU_ROOT_CURRENT)
5825 __kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
5827 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5828 if (roots & KVM_MMU_ROOT_PREVIOUS(i))
5829 __kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
5832 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
5834 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5837 * INVLPG is required to invalidate any global mappings for the VA,
5838 * irrespective of PCID. Blindly sync all roots as it would take
5839 * roughly the same amount of work/time to determine whether any of the
5840 * previous roots have a global mapping.
5842 * Mappings not reachable via the current or previous cached roots will
5843 * be synced when switching to that new cr3, so nothing needs to be
5844 * done here for them.
5846 kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
5847 ++vcpu->stat.invlpg;
5849 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5852 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5854 struct kvm_mmu *mmu = vcpu->arch.mmu;
5855 unsigned long roots = 0;
5858 if (pcid == kvm_get_active_pcid(vcpu))
5859 roots |= KVM_MMU_ROOT_CURRENT;
5861 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5862 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5863 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
5864 roots |= KVM_MMU_ROOT_PREVIOUS(i);
5868 kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
5869 ++vcpu->stat.invlpg;
5872 * Mappings not reachable via the current cr3 or the prev_roots will be
5873 * synced when switching to that cr3, so nothing needs to be done here
5878 void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5879 int tdp_max_root_level, int tdp_huge_page_level)
5881 tdp_enabled = enable_tdp;
5882 tdp_root_level = tdp_forced_root_level;
5883 max_tdp_level = tdp_max_root_level;
5885 #ifdef CONFIG_X86_64
5886 tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
5889 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5890 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5891 * the kernel is not. But, KVM never creates a page size greater than
5892 * what is used by the kernel for any given HVA, i.e. the kernel's
5893 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5896 max_huge_page_level = tdp_huge_page_level;
5897 else if (boot_cpu_has(X86_FEATURE_GBPAGES))
5898 max_huge_page_level = PG_LEVEL_1G;
5900 max_huge_page_level = PG_LEVEL_2M;
5902 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5904 /* The return value indicates if tlb flush on all vcpus is needed. */
5905 typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
5906 struct kvm_rmap_head *rmap_head,
5907 const struct kvm_memory_slot *slot);
5909 static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
5910 const struct kvm_memory_slot *slot,
5911 slot_rmaps_handler fn,
5912 int start_level, int end_level,
5913 gfn_t start_gfn, gfn_t end_gfn,
5914 bool flush_on_yield, bool flush)
5916 struct slot_rmap_walk_iterator iterator;
5918 lockdep_assert_held_write(&kvm->mmu_lock);
5920 for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
5921 end_gfn, &iterator) {
5923 flush |= fn(kvm, iterator.rmap, slot);
5925 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5926 if (flush && flush_on_yield) {
5927 kvm_flush_remote_tlbs_range(kvm, start_gfn,
5928 iterator.gfn - start_gfn + 1);
5931 cond_resched_rwlock_write(&kvm->mmu_lock);
5938 static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
5939 const struct kvm_memory_slot *slot,
5940 slot_rmaps_handler fn,
5941 int start_level, int end_level,
5942 bool flush_on_yield)
5944 return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
5945 slot->base_gfn, slot->base_gfn + slot->npages - 1,
5946 flush_on_yield, false);
5949 static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
5950 const struct kvm_memory_slot *slot,
5951 slot_rmaps_handler fn,
5952 bool flush_on_yield)
5954 return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
5957 static void free_mmu_pages(struct kvm_mmu *mmu)
5959 if (!tdp_enabled && mmu->pae_root)
5960 set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5961 free_page((unsigned long)mmu->pae_root);
5962 free_page((unsigned long)mmu->pml4_root);
5963 free_page((unsigned long)mmu->pml5_root);
5966 static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5971 mmu->root.hpa = INVALID_PAGE;
5973 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5974 mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5976 /* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
5977 if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
5981 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5982 * while the PDP table is a per-vCPU construct that's allocated at MMU
5983 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5984 * x86_64. Therefore we need to allocate the PDP table in the first
5985 * 4GB of memory, which happens to fit the DMA32 zone. TDP paging
5986 * generally doesn't use PAE paging and can skip allocating the PDP
5987 * table. The main exception, handled here, is SVM's 32-bit NPT. The
5988 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
5989 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
5991 if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5994 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5998 mmu->pae_root = page_address(page);
6001 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
6002 * get the CPU to treat the PDPTEs as encrypted. Decrypt the page so
6003 * that KVM's writes and the CPU's reads get along. Note, this is
6004 * only necessary when using shadow paging, as 64-bit NPT can get at
6005 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
6006 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
6009 set_memory_decrypted((unsigned long)mmu->pae_root, 1);
6011 WARN_ON_ONCE(shadow_me_value);
6013 for (i = 0; i < 4; ++i)
6014 mmu->pae_root[i] = INVALID_PAE_ROOT;
6019 int kvm_mmu_create(struct kvm_vcpu *vcpu)
6023 vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
6024 vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
6026 vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
6027 vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
6029 vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
6031 vcpu->arch.mmu = &vcpu->arch.root_mmu;
6032 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6034 ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6038 ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6040 goto fail_allocate_root;
6044 free_mmu_pages(&vcpu->arch.guest_mmu);
6048 #define BATCH_ZAP_PAGES 10
6049 static void kvm_zap_obsolete_pages(struct kvm *kvm)
6051 struct kvm_mmu_page *sp, *node;
6052 int nr_zapped, batch = 0;
6056 list_for_each_entry_safe_reverse(sp, node,
6057 &kvm->arch.active_mmu_pages, link) {
6059 * No obsolete valid page exists before a newly created page
6060 * since active_mmu_pages is a FIFO list.
6062 if (!is_obsolete_sp(kvm, sp))
6066 * Invalid pages should never land back on the list of active
6067 * pages. Skip the bogus page, otherwise we'll get stuck in an
6068 * infinite loop if the page gets put back on the list (again).
6070 if (WARN_ON(sp->role.invalid))
6074 * No need to flush the TLB since we're only zapping shadow
6075 * pages with an obsolete generation number and all vCPUS have
6076 * loaded a new root, i.e. the shadow pages being zapped cannot
6077 * be in active use by the guest.
6079 if (batch >= BATCH_ZAP_PAGES &&
6080 cond_resched_rwlock_write(&kvm->mmu_lock)) {
6085 unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6086 &kvm->arch.zapped_obsolete_pages, &nr_zapped);
6094 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
6095 * to ensure KVM is not in the middle of a lockless shadow page table
6096 * walk, which may reference the pages. The remote TLB flush itself is
6097 * not required and is simply a convenient way to kick vCPUs as needed.
6098 * KVM performs a local TLB flush when allocating a new root (see
6099 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
6100 * running with an obsolete MMU.
6102 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6106 * Fast invalidate all shadow pages and use lock-break technique
6107 * to zap obsolete pages.
6109 * It's required when memslot is being deleted or VM is being
6110 * destroyed, in these cases, we should ensure that KVM MMU does
6111 * not use any resource of the being-deleted slot or all slots
6112 * after calling the function.
6114 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6116 lockdep_assert_held(&kvm->slots_lock);
6118 write_lock(&kvm->mmu_lock);
6119 trace_kvm_mmu_zap_all_fast(kvm);
6122 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
6123 * held for the entire duration of zapping obsolete pages, it's
6124 * impossible for there to be multiple invalid generations associated
6125 * with *valid* shadow pages at any given time, i.e. there is exactly
6126 * one valid generation and (at most) one invalid generation.
6128 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6131 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
6132 * invalidating TDP MMU roots must be done while holding mmu_lock for
6133 * write and in the same critical section as making the reload request,
6134 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6136 if (tdp_mmu_enabled)
6137 kvm_tdp_mmu_invalidate_all_roots(kvm);
6140 * Notify all vcpus to reload its shadow page table and flush TLB.
6141 * Then all vcpus will switch to new shadow page table with the new
6144 * Note: we need to do this under the protection of mmu_lock,
6145 * otherwise, vcpu would purge shadow page but miss tlb flush.
6147 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6149 kvm_zap_obsolete_pages(kvm);
6151 write_unlock(&kvm->mmu_lock);
6154 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6155 * returning to the caller, e.g. if the zap is in response to a memslot
6156 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6157 * associated with the deleted memslot once the update completes, and
6158 * Deferring the zap until the final reference to the root is put would
6159 * lead to use-after-free.
6161 if (tdp_mmu_enabled)
6162 kvm_tdp_mmu_zap_invalidated_roots(kvm);
6165 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6167 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6170 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
6171 struct kvm_memory_slot *slot,
6172 struct kvm_page_track_notifier_node *node)
6174 kvm_mmu_zap_all_fast(kvm);
6177 int kvm_mmu_init_vm(struct kvm *kvm)
6179 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6182 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6183 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
6184 INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6185 spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6187 if (tdp_mmu_enabled) {
6188 r = kvm_mmu_init_tdp_mmu(kvm);
6193 node->track_write = kvm_mmu_pte_write;
6194 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
6195 kvm_page_track_register_notifier(kvm, node);
6197 kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6198 kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6200 kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6202 kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6203 kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6208 static void mmu_free_vm_memory_caches(struct kvm *kvm)
6210 kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6211 kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6212 kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6215 void kvm_mmu_uninit_vm(struct kvm *kvm)
6217 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6219 kvm_page_track_unregister_notifier(kvm, node);
6221 if (tdp_mmu_enabled)
6222 kvm_mmu_uninit_tdp_mmu(kvm);
6224 mmu_free_vm_memory_caches(kvm);
6227 static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6229 const struct kvm_memory_slot *memslot;
6230 struct kvm_memslots *slots;
6231 struct kvm_memslot_iter iter;
6236 if (!kvm_memslots_have_rmaps(kvm))
6239 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6240 slots = __kvm_memslots(kvm, i);
6242 kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6243 memslot = iter.slot;
6244 start = max(gfn_start, memslot->base_gfn);
6245 end = min(gfn_end, memslot->base_gfn + memslot->npages);
6246 if (WARN_ON_ONCE(start >= end))
6249 flush = __walk_slot_rmaps(kvm, memslot, __kvm_zap_rmap,
6250 PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
6251 start, end - 1, true, flush);
6259 * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
6260 * (not including it)
6262 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6267 if (WARN_ON_ONCE(gfn_end <= gfn_start))
6270 write_lock(&kvm->mmu_lock);
6272 kvm_mmu_invalidate_begin(kvm, 0, -1ul);
6274 flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
6276 if (tdp_mmu_enabled) {
6277 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
6278 flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
6279 gfn_end, true, flush);
6283 kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
6285 kvm_mmu_invalidate_end(kvm, 0, -1ul);
6287 write_unlock(&kvm->mmu_lock);
6290 static bool slot_rmap_write_protect(struct kvm *kvm,
6291 struct kvm_rmap_head *rmap_head,
6292 const struct kvm_memory_slot *slot)
6294 return rmap_write_protect(rmap_head, false);
6297 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6298 const struct kvm_memory_slot *memslot,
6301 if (kvm_memslots_have_rmaps(kvm)) {
6302 write_lock(&kvm->mmu_lock);
6303 walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6304 start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6305 write_unlock(&kvm->mmu_lock);
6308 if (tdp_mmu_enabled) {
6309 read_lock(&kvm->mmu_lock);
6310 kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
6311 read_unlock(&kvm->mmu_lock);
6315 static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6317 return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6320 static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6322 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6326 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6327 * to split a single huge page. Calculating how many are actually needed
6328 * is possible but not worth the complexity.
6330 return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6331 need_topup(&kvm->arch.split_page_header_cache, 1) ||
6332 need_topup(&kvm->arch.split_shadow_page_cache, 1);
6335 static int topup_split_caches(struct kvm *kvm)
6338 * Allocating rmap list entries when splitting huge pages for nested
6339 * MMUs is uncommon as KVM needs to use a list if and only if there is
6340 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6341 * aliased by multiple L2 gfns and/or from multiple nested roots with
6342 * different roles. Aliasing gfns when using TDP is atypical for VMMs;
6343 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6344 * but aliasing rarely occurs post-boot or for many gfns. If there is
6345 * only one rmap entry, rmap->val points directly at that one entry and
6346 * doesn't need to allocate a list. Buffer the cache by the default
6347 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6348 * encounters an aliased gfn or two.
6350 const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6351 KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6354 lockdep_assert_held(&kvm->slots_lock);
6356 r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6357 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6361 r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6365 return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6368 static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6370 struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6371 struct shadow_page_caches caches = {};
6372 union kvm_mmu_page_role role;
6373 unsigned int access;
6376 gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6377 access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6380 * Note, huge page splitting always uses direct shadow pages, regardless
6381 * of whether the huge page itself is mapped by a direct or indirect
6382 * shadow page, since the huge page region itself is being directly
6383 * mapped with smaller pages.
6385 role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6387 /* Direct SPs do not require a shadowed_info_cache. */
6388 caches.page_header_cache = &kvm->arch.split_page_header_cache;
6389 caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6391 /* Safe to pass NULL for vCPU since requesting a direct SP. */
6392 return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6395 static void shadow_mmu_split_huge_page(struct kvm *kvm,
6396 const struct kvm_memory_slot *slot,
6400 struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6401 u64 huge_spte = READ_ONCE(*huge_sptep);
6402 struct kvm_mmu_page *sp;
6408 sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6410 for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6411 sptep = &sp->spt[index];
6412 gfn = kvm_mmu_page_get_gfn(sp, index);
6415 * The SP may already have populated SPTEs, e.g. if this huge
6416 * page is aliased by multiple sptes with the same access
6417 * permissions. These entries are guaranteed to map the same
6418 * gfn-to-pfn translation since the SP is direct, so no need to
6421 * However, if a given SPTE points to a lower level page table,
6422 * that lower level page table may only be partially populated.
6423 * Installing such SPTEs would effectively unmap a potion of the
6424 * huge page. Unmapping guest memory always requires a TLB flush
6425 * since a subsequent operation on the unmapped regions would
6426 * fail to detect the need to flush.
6428 if (is_shadow_present_pte(*sptep)) {
6429 flush |= !is_last_spte(*sptep, sp->role.level);
6433 spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6434 mmu_spte_set(sptep, spte);
6435 __rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6438 __link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6441 static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6442 const struct kvm_memory_slot *slot,
6445 struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6450 /* Grab information for the tracepoint before dropping the MMU lock. */
6451 gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6452 level = huge_sp->role.level;
6455 if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6460 if (need_topup_split_caches_or_resched(kvm)) {
6461 write_unlock(&kvm->mmu_lock);
6464 * If the topup succeeds, return -EAGAIN to indicate that the
6465 * rmap iterator should be restarted because the MMU lock was
6468 r = topup_split_caches(kvm) ?: -EAGAIN;
6469 write_lock(&kvm->mmu_lock);
6473 shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6476 trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6480 static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6481 struct kvm_rmap_head *rmap_head,
6482 const struct kvm_memory_slot *slot)
6484 struct rmap_iterator iter;
6485 struct kvm_mmu_page *sp;
6490 for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6491 sp = sptep_to_sp(huge_sptep);
6493 /* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6494 if (WARN_ON_ONCE(!sp->role.guest_mode))
6497 /* The rmaps should never contain non-leaf SPTEs. */
6498 if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6501 /* SPs with level >PG_LEVEL_4K should never by unsync. */
6502 if (WARN_ON_ONCE(sp->unsync))
6505 /* Don't bother splitting huge pages on invalid SPs. */
6506 if (sp->role.invalid)
6509 r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6512 * The split succeeded or needs to be retried because the MMU
6513 * lock was dropped. Either way, restart the iterator to get it
6514 * back into a consistent state.
6516 if (!r || r == -EAGAIN)
6519 /* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6526 static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6527 const struct kvm_memory_slot *slot,
6528 gfn_t start, gfn_t end,
6534 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6535 * down to the target level. This ensures pages are recursively split
6536 * all the way to the target level. There's no need to split pages
6537 * already at the target level.
6539 for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
6540 __walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
6541 level, level, start, end - 1, true, false);
6544 /* Must be called with the mmu_lock held in write-mode. */
6545 void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6546 const struct kvm_memory_slot *memslot,
6550 if (!tdp_mmu_enabled)
6553 if (kvm_memslots_have_rmaps(kvm))
6554 kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6556 kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6559 * A TLB flush is unnecessary at this point for the same resons as in
6560 * kvm_mmu_slot_try_split_huge_pages().
6564 void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6565 const struct kvm_memory_slot *memslot,
6568 u64 start = memslot->base_gfn;
6569 u64 end = start + memslot->npages;
6571 if (!tdp_mmu_enabled)
6574 if (kvm_memslots_have_rmaps(kvm)) {
6575 write_lock(&kvm->mmu_lock);
6576 kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6577 write_unlock(&kvm->mmu_lock);
6580 read_lock(&kvm->mmu_lock);
6581 kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6582 read_unlock(&kvm->mmu_lock);
6585 * No TLB flush is necessary here. KVM will flush TLBs after
6586 * write-protecting and/or clearing dirty on the newly split SPTEs to
6587 * ensure that guest writes are reflected in the dirty log before the
6588 * ioctl to enable dirty logging on this memslot completes. Since the
6589 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6590 * safe for KVM to decide if a TLB flush is necessary based on the split
6595 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
6596 struct kvm_rmap_head *rmap_head,
6597 const struct kvm_memory_slot *slot)
6600 struct rmap_iterator iter;
6601 int need_tlb_flush = 0;
6602 struct kvm_mmu_page *sp;
6605 for_each_rmap_spte(rmap_head, &iter, sptep) {
6606 sp = sptep_to_sp(sptep);
6609 * We cannot do huge page mapping for indirect shadow pages,
6610 * which are found on the last rmap (level = 1) when not using
6611 * tdp; such shadow pages are synced with the page table in
6612 * the guest, and the guest page table is using 4K page size
6613 * mapping if the indirect sp has level = 1.
6615 if (sp->role.direct &&
6616 sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6618 kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6620 if (kvm_available_flush_tlb_with_range())
6621 kvm_flush_remote_tlbs_sptep(kvm, sptep);
6629 return need_tlb_flush;
6632 static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
6633 const struct kvm_memory_slot *slot)
6636 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
6637 * pages that are already mapped at the maximum hugepage level.
6639 if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
6640 PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
6641 kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
6644 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6645 const struct kvm_memory_slot *slot)
6647 if (kvm_memslots_have_rmaps(kvm)) {
6648 write_lock(&kvm->mmu_lock);
6649 kvm_rmap_zap_collapsible_sptes(kvm, slot);
6650 write_unlock(&kvm->mmu_lock);
6653 if (tdp_mmu_enabled) {
6654 read_lock(&kvm->mmu_lock);
6655 kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
6656 read_unlock(&kvm->mmu_lock);
6660 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
6661 const struct kvm_memory_slot *memslot)
6664 * All current use cases for flushing the TLBs for a specific memslot
6665 * related to dirty logging, and many do the TLB flush out of mmu_lock.
6666 * The interaction between the various operations on memslot must be
6667 * serialized by slots_locks to ensure the TLB flush from one operation
6668 * is observed by any other operation on the same memslot.
6670 lockdep_assert_held(&kvm->slots_lock);
6671 kvm_flush_remote_tlbs_range(kvm, memslot->base_gfn, memslot->npages);
6674 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6675 const struct kvm_memory_slot *memslot)
6677 if (kvm_memslots_have_rmaps(kvm)) {
6678 write_lock(&kvm->mmu_lock);
6680 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6681 * support dirty logging at a 4k granularity.
6683 walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
6684 write_unlock(&kvm->mmu_lock);
6687 if (tdp_mmu_enabled) {
6688 read_lock(&kvm->mmu_lock);
6689 kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
6690 read_unlock(&kvm->mmu_lock);
6694 * The caller will flush the TLBs after this function returns.
6696 * It's also safe to flush TLBs out of mmu lock here as currently this
6697 * function is only used for dirty logging, in which case flushing TLB
6698 * out of mmu lock also guarantees no dirty pages will be lost in
6703 void kvm_mmu_zap_all(struct kvm *kvm)
6705 struct kvm_mmu_page *sp, *node;
6706 LIST_HEAD(invalid_list);
6709 write_lock(&kvm->mmu_lock);
6711 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6712 if (WARN_ON(sp->role.invalid))
6714 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6716 if (cond_resched_rwlock_write(&kvm->mmu_lock))
6720 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6722 if (tdp_mmu_enabled)
6723 kvm_tdp_mmu_zap_all(kvm);
6725 write_unlock(&kvm->mmu_lock);
6728 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6730 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6732 gen &= MMIO_SPTE_GEN_MASK;
6735 * Generation numbers are incremented in multiples of the number of
6736 * address spaces in order to provide unique generations across all
6737 * address spaces. Strip what is effectively the address space
6738 * modifier prior to checking for a wrap of the MMIO generation so
6739 * that a wrap in any address space is detected.
6741 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6744 * The very rare case: if the MMIO generation number has wrapped,
6745 * zap all shadow pages.
6747 if (unlikely(gen == 0)) {
6748 kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
6749 kvm_mmu_zap_all_fast(kvm);
6753 static unsigned long
6754 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6757 int nr_to_scan = sc->nr_to_scan;
6758 unsigned long freed = 0;
6760 mutex_lock(&kvm_lock);
6762 list_for_each_entry(kvm, &vm_list, vm_list) {
6764 LIST_HEAD(invalid_list);
6767 * Never scan more than sc->nr_to_scan VM instances.
6768 * Will not hit this condition practically since we do not try
6769 * to shrink more than one VM and it is very unlikely to see
6770 * !n_used_mmu_pages so many times.
6775 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6776 * here. We may skip a VM instance errorneosly, but we do not
6777 * want to shrink a VM that only started to populate its MMU
6780 if (!kvm->arch.n_used_mmu_pages &&
6781 !kvm_has_zapped_obsolete_pages(kvm))
6784 idx = srcu_read_lock(&kvm->srcu);
6785 write_lock(&kvm->mmu_lock);
6787 if (kvm_has_zapped_obsolete_pages(kvm)) {
6788 kvm_mmu_commit_zap_page(kvm,
6789 &kvm->arch.zapped_obsolete_pages);
6793 freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6796 write_unlock(&kvm->mmu_lock);
6797 srcu_read_unlock(&kvm->srcu, idx);
6800 * unfair on small ones
6801 * per-vm shrinkers cry out
6802 * sadness comes quickly
6804 list_move_tail(&kvm->vm_list, &vm_list);
6808 mutex_unlock(&kvm_lock);
6812 static unsigned long
6813 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6815 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6818 static struct shrinker mmu_shrinker = {
6819 .count_objects = mmu_shrink_count,
6820 .scan_objects = mmu_shrink_scan,
6821 .seeks = DEFAULT_SEEKS * 10,
6824 static void mmu_destroy_caches(void)
6826 kmem_cache_destroy(pte_list_desc_cache);
6827 kmem_cache_destroy(mmu_page_header_cache);
6830 static bool get_nx_auto_mode(void)
6832 /* Return true when CPU has the bug, and mitigations are ON */
6833 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6836 static void __set_nx_huge_pages(bool val)
6838 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6841 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6843 bool old_val = nx_huge_pages;
6846 /* In "auto" mode deploy workaround only if CPU has the bug. */
6847 if (sysfs_streq(val, "off"))
6849 else if (sysfs_streq(val, "force"))
6851 else if (sysfs_streq(val, "auto"))
6852 new_val = get_nx_auto_mode();
6853 else if (kstrtobool(val, &new_val) < 0)
6856 __set_nx_huge_pages(new_val);
6858 if (new_val != old_val) {
6861 mutex_lock(&kvm_lock);
6863 list_for_each_entry(kvm, &vm_list, vm_list) {
6864 mutex_lock(&kvm->slots_lock);
6865 kvm_mmu_zap_all_fast(kvm);
6866 mutex_unlock(&kvm->slots_lock);
6868 wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6870 mutex_unlock(&kvm_lock);
6877 * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
6878 * its default value of -1 is technically undefined behavior for a boolean.
6879 * Forward the module init call to SPTE code so that it too can handle module
6880 * params that need to be resolved/snapshot.
6882 void __init kvm_mmu_x86_module_init(void)
6884 if (nx_huge_pages == -1)
6885 __set_nx_huge_pages(get_nx_auto_mode());
6888 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
6889 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
6890 * when the vendor module is loaded.
6892 tdp_mmu_allowed = tdp_mmu_enabled;
6894 kvm_mmu_spte_module_init();
6898 * The bulk of the MMU initialization is deferred until the vendor module is
6899 * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
6900 * to be reset when a potentially different vendor module is loaded.
6902 int kvm_mmu_vendor_module_init(void)
6907 * MMU roles use union aliasing which is, generally speaking, an
6908 * undefined behavior. However, we supposedly know how compilers behave
6909 * and the current status quo is unlikely to change. Guardians below are
6910 * supposed to let us know if the assumption becomes false.
6912 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6913 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6914 BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
6916 kvm_mmu_reset_all_pte_masks();
6918 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6919 sizeof(struct pte_list_desc),
6920 0, SLAB_ACCOUNT, NULL);
6921 if (!pte_list_desc_cache)
6924 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6925 sizeof(struct kvm_mmu_page),
6926 0, SLAB_ACCOUNT, NULL);
6927 if (!mmu_page_header_cache)
6930 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6933 ret = register_shrinker(&mmu_shrinker, "x86-mmu");
6940 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6942 mmu_destroy_caches();
6946 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6948 kvm_mmu_unload(vcpu);
6949 free_mmu_pages(&vcpu->arch.root_mmu);
6950 free_mmu_pages(&vcpu->arch.guest_mmu);
6951 mmu_free_memory_caches(vcpu);
6954 void kvm_mmu_vendor_module_exit(void)
6956 mmu_destroy_caches();
6957 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6958 unregister_shrinker(&mmu_shrinker);
6962 * Calculate the effective recovery period, accounting for '0' meaning "let KVM
6963 * select a halving time of 1 hour". Returns true if recovery is enabled.
6965 static bool calc_nx_huge_pages_recovery_period(uint *period)
6968 * Use READ_ONCE to get the params, this may be called outside of the
6969 * param setters, e.g. by the kthread to compute its next timeout.
6971 bool enabled = READ_ONCE(nx_huge_pages);
6972 uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6974 if (!enabled || !ratio)
6977 *period = READ_ONCE(nx_huge_pages_recovery_period_ms);
6979 /* Make sure the period is not less than one second. */
6980 ratio = min(ratio, 3600u);
6981 *period = 60 * 60 * 1000 / ratio;
6986 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
6988 bool was_recovery_enabled, is_recovery_enabled;
6989 uint old_period, new_period;
6992 was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
6994 err = param_set_uint(val, kp);
6998 is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
7000 if (is_recovery_enabled &&
7001 (!was_recovery_enabled || old_period > new_period)) {
7004 mutex_lock(&kvm_lock);
7006 list_for_each_entry(kvm, &vm_list, vm_list)
7007 wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
7009 mutex_unlock(&kvm_lock);
7015 static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7017 unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7018 struct kvm_memory_slot *slot;
7020 struct kvm_mmu_page *sp;
7022 LIST_HEAD(invalid_list);
7026 rcu_idx = srcu_read_lock(&kvm->srcu);
7027 write_lock(&kvm->mmu_lock);
7030 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7031 * be done under RCU protection, because the pages are freed via RCU
7036 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7037 to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
7038 for ( ; to_zap; --to_zap) {
7039 if (list_empty(&kvm->arch.possible_nx_huge_pages))
7043 * We use a separate list instead of just using active_mmu_pages
7044 * because the number of shadow pages that be replaced with an
7045 * NX huge page is expected to be relatively small compared to
7046 * the total number of shadow pages. And because the TDP MMU
7047 * doesn't use active_mmu_pages.
7049 sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7050 struct kvm_mmu_page,
7051 possible_nx_huge_page_link);
7052 WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7053 WARN_ON_ONCE(!sp->role.direct);
7056 * Unaccount and do not attempt to recover any NX Huge Pages
7057 * that are being dirty tracked, as they would just be faulted
7058 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7059 * recovered, along with all the other huge pages in the slot,
7060 * when dirty logging is disabled.
7062 * Since gfn_to_memslot() is relatively expensive, it helps to
7063 * skip it if it the test cannot possibly return true. On the
7064 * other hand, if any memslot has logging enabled, chances are
7065 * good that all of them do, in which case unaccount_nx_huge_page()
7066 * is much cheaper than zapping the page.
7068 * If a memslot update is in progress, reading an incorrect value
7069 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
7070 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
7071 * it is becoming nonzero, the page will be zapped unnecessarily.
7072 * Either way, this only affects efficiency in racy situations,
7073 * and not correctness.
7076 if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7077 slot = gfn_to_memslot(kvm, sp->gfn);
7078 WARN_ON_ONCE(!slot);
7081 if (slot && kvm_slot_dirty_track_enabled(slot))
7082 unaccount_nx_huge_page(kvm, sp);
7083 else if (is_tdp_mmu_page(sp))
7084 flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
7086 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7087 WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7089 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7090 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7093 cond_resched_rwlock_write(&kvm->mmu_lock);
7099 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7103 write_unlock(&kvm->mmu_lock);
7104 srcu_read_unlock(&kvm->srcu, rcu_idx);
7107 static long get_nx_huge_page_recovery_timeout(u64 start_time)
7112 enabled = calc_nx_huge_pages_recovery_period(&period);
7114 return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7115 : MAX_SCHEDULE_TIMEOUT;
7118 static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7121 long remaining_time;
7124 start_time = get_jiffies_64();
7125 remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7127 set_current_state(TASK_INTERRUPTIBLE);
7128 while (!kthread_should_stop() && remaining_time > 0) {
7129 schedule_timeout(remaining_time);
7130 remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7131 set_current_state(TASK_INTERRUPTIBLE);
7134 set_current_state(TASK_RUNNING);
7136 if (kthread_should_stop())
7139 kvm_recover_nx_huge_pages(kvm);
7143 int kvm_mmu_post_init_vm(struct kvm *kvm)
7147 err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7148 "kvm-nx-lpage-recovery",
7149 &kvm->arch.nx_huge_page_recovery_thread);
7151 kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7156 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7158 if (kvm->arch.nx_huge_page_recovery_thread)
7159 kthread_stop(kvm->arch.nx_huge_page_recovery_thread);