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.
21 #include "mmu_internal.h"
23 #include "kvm_cache_regs.h"
24 #include "kvm_emulate.h"
27 #include <linux/kvm_host.h>
28 #include <linux/types.h>
29 #include <linux/string.h>
31 #include <linux/highmem.h>
32 #include <linux/moduleparam.h>
33 #include <linux/export.h>
34 #include <linux/swap.h>
35 #include <linux/hugetlb.h>
36 #include <linux/compiler.h>
37 #include <linux/srcu.h>
38 #include <linux/slab.h>
39 #include <linux/sched/signal.h>
40 #include <linux/uaccess.h>
41 #include <linux/hash.h>
42 #include <linux/kern_levels.h>
43 #include <linux/kthread.h>
46 #include <asm/memtype.h>
47 #include <asm/cmpxchg.h>
48 #include <asm/e820/api.h>
51 #include <asm/kvm_page_track.h>
54 extern bool itlb_multihit_kvm_mitigation;
56 static int __read_mostly nx_huge_pages = -1;
57 #ifdef CONFIG_PREEMPT_RT
58 /* Recovery can cause latency spikes, disable it for PREEMPT_RT. */
59 static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
61 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
64 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
65 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp);
67 static struct kernel_param_ops nx_huge_pages_ops = {
68 .set = set_nx_huge_pages,
69 .get = param_get_bool,
72 static struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
73 .set = set_nx_huge_pages_recovery_ratio,
74 .get = param_get_uint,
77 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
78 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
79 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
80 &nx_huge_pages_recovery_ratio, 0644);
81 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
83 static bool __read_mostly force_flush_and_sync_on_reuse;
84 module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
87 * When setting this variable to true it enables Two-Dimensional-Paging
88 * where the hardware walks 2 page tables:
89 * 1. the guest-virtual to guest-physical
90 * 2. while doing 1. it walks guest-physical to host-physical
91 * If the hardware supports that we don't need to do shadow paging.
93 bool tdp_enabled = false;
95 static int max_huge_page_level __read_mostly;
96 static int max_tdp_level __read_mostly;
100 AUDIT_POST_PAGE_FAULT,
102 AUDIT_POST_PTE_WRITE,
111 module_param(dbg, bool, 0644);
113 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
114 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
115 #define MMU_WARN_ON(x) WARN_ON(x)
117 #define pgprintk(x...) do { } while (0)
118 #define rmap_printk(x...) do { } while (0)
119 #define MMU_WARN_ON(x) do { } while (0)
122 #define PTE_PREFETCH_NUM 8
124 #define PT_FIRST_AVAIL_BITS_SHIFT 10
125 #define PT64_SECOND_AVAIL_BITS_SHIFT 54
128 * The mask used to denote special SPTEs, which can be either MMIO SPTEs or
129 * Access Tracking SPTEs.
131 #define SPTE_SPECIAL_MASK (3ULL << 52)
132 #define SPTE_AD_ENABLED_MASK (0ULL << 52)
133 #define SPTE_AD_DISABLED_MASK (1ULL << 52)
134 #define SPTE_AD_WRPROT_ONLY_MASK (2ULL << 52)
135 #define SPTE_MMIO_MASK (3ULL << 52)
137 #define PT64_LEVEL_BITS 9
139 #define PT64_LEVEL_SHIFT(level) \
140 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
142 #define PT64_INDEX(address, level)\
143 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
146 #define PT32_LEVEL_BITS 10
148 #define PT32_LEVEL_SHIFT(level) \
149 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
151 #define PT32_LVL_OFFSET_MASK(level) \
152 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
153 * PT32_LEVEL_BITS))) - 1))
155 #define PT32_INDEX(address, level)\
156 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
159 #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
160 #define PT64_BASE_ADDR_MASK (physical_mask & ~(u64)(PAGE_SIZE-1))
162 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
164 #define PT64_LVL_ADDR_MASK(level) \
165 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
166 * PT64_LEVEL_BITS))) - 1))
167 #define PT64_LVL_OFFSET_MASK(level) \
168 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
169 * PT64_LEVEL_BITS))) - 1))
171 #define PT32_BASE_ADDR_MASK PAGE_MASK
172 #define PT32_DIR_BASE_ADDR_MASK \
173 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
174 #define PT32_LVL_ADDR_MASK(level) \
175 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
176 * PT32_LEVEL_BITS))) - 1))
178 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
179 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
181 #define ACC_EXEC_MASK 1
182 #define ACC_WRITE_MASK PT_WRITABLE_MASK
183 #define ACC_USER_MASK PT_USER_MASK
184 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
186 /* The mask for the R/X bits in EPT PTEs */
187 #define PT64_EPT_READABLE_MASK 0x1ull
188 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
190 #include <trace/events/kvm.h>
192 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
193 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
195 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
197 /* make pte_list_desc fit well in cache line */
198 #define PTE_LIST_EXT 3
201 * Return values of handle_mmio_page_fault and mmu.page_fault:
202 * RET_PF_RETRY: let CPU fault again on the address.
203 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
205 * For handle_mmio_page_fault only:
206 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
214 struct pte_list_desc {
215 u64 *sptes[PTE_LIST_EXT];
216 struct pte_list_desc *more;
219 struct kvm_shadow_walk_iterator {
227 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
228 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
230 shadow_walk_okay(&(_walker)); \
231 shadow_walk_next(&(_walker)))
233 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
234 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
235 shadow_walk_okay(&(_walker)); \
236 shadow_walk_next(&(_walker)))
238 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
239 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
240 shadow_walk_okay(&(_walker)) && \
241 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
242 __shadow_walk_next(&(_walker), spte))
244 static struct kmem_cache *pte_list_desc_cache;
245 static struct kmem_cache *mmu_page_header_cache;
246 static struct percpu_counter kvm_total_used_mmu_pages;
248 static u64 __read_mostly shadow_nx_mask;
249 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
250 static u64 __read_mostly shadow_user_mask;
251 static u64 __read_mostly shadow_accessed_mask;
252 static u64 __read_mostly shadow_dirty_mask;
253 static u64 __read_mostly shadow_mmio_value;
254 static u64 __read_mostly shadow_mmio_access_mask;
255 static u64 __read_mostly shadow_present_mask;
256 static u64 __read_mostly shadow_me_mask;
259 * SPTEs used by MMUs without A/D bits are marked with SPTE_AD_DISABLED_MASK;
260 * shadow_acc_track_mask is the set of bits to be cleared in non-accessed
263 static u64 __read_mostly shadow_acc_track_mask;
266 * The mask/shift to use for saving the original R/X bits when marking the PTE
267 * as not-present for access tracking purposes. We do not save the W bit as the
268 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
269 * restored only when a write is attempted to the page.
271 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
272 PT64_EPT_EXECUTABLE_MASK;
273 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
276 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
277 * to guard against L1TF attacks.
279 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
282 * The number of high-order 1 bits to use in the mask above.
284 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
287 * In some cases, we need to preserve the GFN of a non-present or reserved
288 * SPTE when we usurp the upper five bits of the physical address space to
289 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
290 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
291 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
292 * high and low parts. This mask covers the lower bits of the GFN.
294 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
297 * The number of non-reserved physical address bits irrespective of features
298 * that repurpose legal bits, e.g. MKTME.
300 static u8 __read_mostly shadow_phys_bits;
302 static void mmu_spte_set(u64 *sptep, u64 spte);
303 static bool is_executable_pte(u64 spte);
304 static union kvm_mmu_page_role
305 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
307 #define CREATE_TRACE_POINTS
308 #include "mmutrace.h"
311 static inline bool kvm_available_flush_tlb_with_range(void)
313 return kvm_x86_ops.tlb_remote_flush_with_range;
316 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
317 struct kvm_tlb_range *range)
321 if (range && kvm_x86_ops.tlb_remote_flush_with_range)
322 ret = kvm_x86_ops.tlb_remote_flush_with_range(kvm, range);
325 kvm_flush_remote_tlbs(kvm);
328 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
329 u64 start_gfn, u64 pages)
331 struct kvm_tlb_range range;
333 range.start_gfn = start_gfn;
336 kvm_flush_remote_tlbs_with_range(kvm, &range);
339 void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 access_mask)
341 BUG_ON((u64)(unsigned)access_mask != access_mask);
342 WARN_ON(mmio_value & (shadow_nonpresent_or_rsvd_mask << shadow_nonpresent_or_rsvd_mask_len));
343 WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);
344 shadow_mmio_value = mmio_value | SPTE_MMIO_MASK;
345 shadow_mmio_access_mask = access_mask;
347 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
349 static bool is_mmio_spte(u64 spte)
351 return (spte & SPTE_SPECIAL_MASK) == SPTE_MMIO_MASK;
354 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
356 return sp->role.ad_disabled;
359 static inline bool kvm_vcpu_ad_need_write_protect(struct kvm_vcpu *vcpu)
362 * When using the EPT page-modification log, the GPAs in the log
363 * would come from L2 rather than L1. Therefore, we need to rely
364 * on write protection to record dirty pages. This also bypasses
365 * PML, since writes now result in a vmexit.
367 return vcpu->arch.mmu == &vcpu->arch.guest_mmu;
370 static inline bool spte_ad_enabled(u64 spte)
372 MMU_WARN_ON(is_mmio_spte(spte));
373 return (spte & SPTE_SPECIAL_MASK) != SPTE_AD_DISABLED_MASK;
376 static inline bool spte_ad_need_write_protect(u64 spte)
378 MMU_WARN_ON(is_mmio_spte(spte));
379 return (spte & SPTE_SPECIAL_MASK) != SPTE_AD_ENABLED_MASK;
382 static bool is_nx_huge_page_enabled(void)
384 return READ_ONCE(nx_huge_pages);
387 static inline u64 spte_shadow_accessed_mask(u64 spte)
389 MMU_WARN_ON(is_mmio_spte(spte));
390 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
393 static inline u64 spte_shadow_dirty_mask(u64 spte)
395 MMU_WARN_ON(is_mmio_spte(spte));
396 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
399 static inline bool is_access_track_spte(u64 spte)
401 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
405 * Due to limited space in PTEs, the MMIO generation is a 19 bit subset of
406 * the memslots generation and is derived as follows:
408 * Bits 0-8 of the MMIO generation are propagated to spte bits 3-11
409 * Bits 9-18 of the MMIO generation are propagated to spte bits 52-61
411 * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
412 * the MMIO generation number, as doing so would require stealing a bit from
413 * the "real" generation number and thus effectively halve the maximum number
414 * of MMIO generations that can be handled before encountering a wrap (which
415 * requires a full MMU zap). The flag is instead explicitly queried when
416 * checking for MMIO spte cache hits.
418 #define MMIO_SPTE_GEN_MASK GENMASK_ULL(17, 0)
420 #define MMIO_SPTE_GEN_LOW_START 3
421 #define MMIO_SPTE_GEN_LOW_END 11
422 #define MMIO_SPTE_GEN_LOW_MASK GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
423 MMIO_SPTE_GEN_LOW_START)
425 #define MMIO_SPTE_GEN_HIGH_START PT64_SECOND_AVAIL_BITS_SHIFT
426 #define MMIO_SPTE_GEN_HIGH_END 62
427 #define MMIO_SPTE_GEN_HIGH_MASK GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
428 MMIO_SPTE_GEN_HIGH_START)
430 static u64 generation_mmio_spte_mask(u64 gen)
434 WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
435 BUILD_BUG_ON((MMIO_SPTE_GEN_HIGH_MASK | MMIO_SPTE_GEN_LOW_MASK) & SPTE_SPECIAL_MASK);
437 mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
438 mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
442 static u64 get_mmio_spte_generation(u64 spte)
446 gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
447 gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
451 static u64 make_mmio_spte(struct kvm_vcpu *vcpu, u64 gfn, unsigned int access)
454 u64 gen = kvm_vcpu_memslots(vcpu)->generation & MMIO_SPTE_GEN_MASK;
455 u64 mask = generation_mmio_spte_mask(gen);
456 u64 gpa = gfn << PAGE_SHIFT;
458 access &= shadow_mmio_access_mask;
459 mask |= shadow_mmio_value | access;
460 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
461 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
462 << shadow_nonpresent_or_rsvd_mask_len;
467 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
470 u64 mask = make_mmio_spte(vcpu, gfn, access);
471 unsigned int gen = get_mmio_spte_generation(mask);
473 access = mask & ACC_ALL;
475 trace_mark_mmio_spte(sptep, gfn, access, gen);
476 mmu_spte_set(sptep, mask);
479 static gfn_t get_mmio_spte_gfn(u64 spte)
481 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
483 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
484 & shadow_nonpresent_or_rsvd_mask;
486 return gpa >> PAGE_SHIFT;
489 static unsigned get_mmio_spte_access(u64 spte)
491 return spte & shadow_mmio_access_mask;
494 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
495 kvm_pfn_t pfn, unsigned int access)
497 if (unlikely(is_noslot_pfn(pfn))) {
498 mark_mmio_spte(vcpu, sptep, gfn, access);
505 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
507 u64 kvm_gen, spte_gen, gen;
509 gen = kvm_vcpu_memslots(vcpu)->generation;
510 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
513 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
514 spte_gen = get_mmio_spte_generation(spte);
516 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
517 return likely(kvm_gen == spte_gen);
520 static gpa_t translate_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
521 struct x86_exception *exception)
523 /* Check if guest physical address doesn't exceed guest maximum */
524 if (kvm_mmu_is_illegal_gpa(vcpu, gpa)) {
525 exception->error_code |= PFERR_RSVD_MASK;
533 * Sets the shadow PTE masks used by the MMU.
536 * - Setting either @accessed_mask or @dirty_mask requires setting both
537 * - At least one of @accessed_mask or @acc_track_mask must be set
539 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
540 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
541 u64 acc_track_mask, u64 me_mask)
543 BUG_ON(!dirty_mask != !accessed_mask);
544 BUG_ON(!accessed_mask && !acc_track_mask);
545 BUG_ON(acc_track_mask & SPTE_SPECIAL_MASK);
547 shadow_user_mask = user_mask;
548 shadow_accessed_mask = accessed_mask;
549 shadow_dirty_mask = dirty_mask;
550 shadow_nx_mask = nx_mask;
551 shadow_x_mask = x_mask;
552 shadow_present_mask = p_mask;
553 shadow_acc_track_mask = acc_track_mask;
554 shadow_me_mask = me_mask;
556 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
558 static u8 kvm_get_shadow_phys_bits(void)
561 * boot_cpu_data.x86_phys_bits is reduced when MKTME or SME are detected
562 * in CPU detection code, but the processor treats those reduced bits as
563 * 'keyID' thus they are not reserved bits. Therefore KVM needs to look at
564 * the physical address bits reported by CPUID.
566 if (likely(boot_cpu_data.extended_cpuid_level >= 0x80000008))
567 return cpuid_eax(0x80000008) & 0xff;
570 * Quite weird to have VMX or SVM but not MAXPHYADDR; probably a VM with
571 * custom CPUID. Proceed with whatever the kernel found since these features
572 * aren't virtualizable (SME/SEV also require CPUIDs higher than 0x80000008).
574 return boot_cpu_data.x86_phys_bits;
577 static void kvm_mmu_reset_all_pte_masks(void)
581 shadow_user_mask = 0;
582 shadow_accessed_mask = 0;
583 shadow_dirty_mask = 0;
586 shadow_present_mask = 0;
587 shadow_acc_track_mask = 0;
589 shadow_phys_bits = kvm_get_shadow_phys_bits();
592 * If the CPU has 46 or less physical address bits, then set an
593 * appropriate mask to guard against L1TF attacks. Otherwise, it is
594 * assumed that the CPU is not vulnerable to L1TF.
596 * Some Intel CPUs address the L1 cache using more PA bits than are
597 * reported by CPUID. Use the PA width of the L1 cache when possible
598 * to achieve more effective mitigation, e.g. if system RAM overlaps
599 * the most significant bits of legal physical address space.
601 shadow_nonpresent_or_rsvd_mask = 0;
602 low_phys_bits = boot_cpu_data.x86_phys_bits;
603 if (boot_cpu_has_bug(X86_BUG_L1TF) &&
604 !WARN_ON_ONCE(boot_cpu_data.x86_cache_bits >=
605 52 - shadow_nonpresent_or_rsvd_mask_len)) {
606 low_phys_bits = boot_cpu_data.x86_cache_bits
607 - shadow_nonpresent_or_rsvd_mask_len;
608 shadow_nonpresent_or_rsvd_mask =
609 rsvd_bits(low_phys_bits, boot_cpu_data.x86_cache_bits - 1);
612 shadow_nonpresent_or_rsvd_lower_gfn_mask =
613 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
616 static int is_cpuid_PSE36(void)
621 static int is_nx(struct kvm_vcpu *vcpu)
623 return vcpu->arch.efer & EFER_NX;
626 static int is_shadow_present_pte(u64 pte)
628 return (pte != 0) && !is_mmio_spte(pte);
631 static int is_large_pte(u64 pte)
633 return pte & PT_PAGE_SIZE_MASK;
636 static int is_last_spte(u64 pte, int level)
638 if (level == PG_LEVEL_4K)
640 if (is_large_pte(pte))
645 static bool is_executable_pte(u64 spte)
647 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
650 static kvm_pfn_t spte_to_pfn(u64 pte)
652 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
655 static gfn_t pse36_gfn_delta(u32 gpte)
657 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
659 return (gpte & PT32_DIR_PSE36_MASK) << shift;
663 static void __set_spte(u64 *sptep, u64 spte)
665 WRITE_ONCE(*sptep, spte);
668 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
670 WRITE_ONCE(*sptep, spte);
673 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
675 return xchg(sptep, spte);
678 static u64 __get_spte_lockless(u64 *sptep)
680 return READ_ONCE(*sptep);
691 static void count_spte_clear(u64 *sptep, u64 spte)
693 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
695 if (is_shadow_present_pte(spte))
698 /* Ensure the spte is completely set before we increase the count */
700 sp->clear_spte_count++;
703 static void __set_spte(u64 *sptep, u64 spte)
705 union split_spte *ssptep, sspte;
707 ssptep = (union split_spte *)sptep;
708 sspte = (union split_spte)spte;
710 ssptep->spte_high = sspte.spte_high;
713 * If we map the spte from nonpresent to present, We should store
714 * the high bits firstly, then set present bit, so cpu can not
715 * fetch this spte while we are setting the spte.
719 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
722 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
724 union split_spte *ssptep, sspte;
726 ssptep = (union split_spte *)sptep;
727 sspte = (union split_spte)spte;
729 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
732 * If we map the spte from present to nonpresent, we should clear
733 * present bit firstly to avoid vcpu fetch the old high bits.
737 ssptep->spte_high = sspte.spte_high;
738 count_spte_clear(sptep, spte);
741 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
743 union split_spte *ssptep, sspte, orig;
745 ssptep = (union split_spte *)sptep;
746 sspte = (union split_spte)spte;
748 /* xchg acts as a barrier before the setting of the high bits */
749 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
750 orig.spte_high = ssptep->spte_high;
751 ssptep->spte_high = sspte.spte_high;
752 count_spte_clear(sptep, spte);
758 * The idea using the light way get the spte on x86_32 guest is from
759 * gup_get_pte (mm/gup.c).
761 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
762 * coalesces them and we are running out of the MMU lock. Therefore
763 * we need to protect against in-progress updates of the spte.
765 * Reading the spte while an update is in progress may get the old value
766 * for the high part of the spte. The race is fine for a present->non-present
767 * change (because the high part of the spte is ignored for non-present spte),
768 * but for a present->present change we must reread the spte.
770 * All such changes are done in two steps (present->non-present and
771 * non-present->present), hence it is enough to count the number of
772 * present->non-present updates: if it changed while reading the spte,
773 * we might have hit the race. This is done using clear_spte_count.
775 static u64 __get_spte_lockless(u64 *sptep)
777 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
778 union split_spte spte, *orig = (union split_spte *)sptep;
782 count = sp->clear_spte_count;
785 spte.spte_low = orig->spte_low;
788 spte.spte_high = orig->spte_high;
791 if (unlikely(spte.spte_low != orig->spte_low ||
792 count != sp->clear_spte_count))
799 static bool spte_can_locklessly_be_made_writable(u64 spte)
801 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
802 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
805 static bool spte_has_volatile_bits(u64 spte)
807 if (!is_shadow_present_pte(spte))
811 * Always atomically update spte if it can be updated
812 * out of mmu-lock, it can ensure dirty bit is not lost,
813 * also, it can help us to get a stable is_writable_pte()
814 * to ensure tlb flush is not missed.
816 if (spte_can_locklessly_be_made_writable(spte) ||
817 is_access_track_spte(spte))
820 if (spte_ad_enabled(spte)) {
821 if ((spte & shadow_accessed_mask) == 0 ||
822 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
829 static bool is_accessed_spte(u64 spte)
831 u64 accessed_mask = spte_shadow_accessed_mask(spte);
833 return accessed_mask ? spte & accessed_mask
834 : !is_access_track_spte(spte);
837 static bool is_dirty_spte(u64 spte)
839 u64 dirty_mask = spte_shadow_dirty_mask(spte);
841 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
844 /* Rules for using mmu_spte_set:
845 * Set the sptep from nonpresent to present.
846 * Note: the sptep being assigned *must* be either not present
847 * or in a state where the hardware will not attempt to update
850 static void mmu_spte_set(u64 *sptep, u64 new_spte)
852 WARN_ON(is_shadow_present_pte(*sptep));
853 __set_spte(sptep, new_spte);
857 * Update the SPTE (excluding the PFN), but do not track changes in its
858 * accessed/dirty status.
860 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
862 u64 old_spte = *sptep;
864 WARN_ON(!is_shadow_present_pte(new_spte));
866 if (!is_shadow_present_pte(old_spte)) {
867 mmu_spte_set(sptep, new_spte);
871 if (!spte_has_volatile_bits(old_spte))
872 __update_clear_spte_fast(sptep, new_spte);
874 old_spte = __update_clear_spte_slow(sptep, new_spte);
876 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
881 /* Rules for using mmu_spte_update:
882 * Update the state bits, it means the mapped pfn is not changed.
884 * Whenever we overwrite a writable spte with a read-only one we
885 * should flush remote TLBs. Otherwise rmap_write_protect
886 * will find a read-only spte, even though the writable spte
887 * might be cached on a CPU's TLB, the return value indicates this
890 * Returns true if the TLB needs to be flushed
892 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
895 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
897 if (!is_shadow_present_pte(old_spte))
901 * For the spte updated out of mmu-lock is safe, since
902 * we always atomically update it, see the comments in
903 * spte_has_volatile_bits().
905 if (spte_can_locklessly_be_made_writable(old_spte) &&
906 !is_writable_pte(new_spte))
910 * Flush TLB when accessed/dirty states are changed in the page tables,
911 * to guarantee consistency between TLB and page tables.
914 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
916 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
919 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
921 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
928 * Rules for using mmu_spte_clear_track_bits:
929 * It sets the sptep from present to nonpresent, and track the
930 * state bits, it is used to clear the last level sptep.
931 * Returns non-zero if the PTE was previously valid.
933 static int mmu_spte_clear_track_bits(u64 *sptep)
936 u64 old_spte = *sptep;
938 if (!spte_has_volatile_bits(old_spte))
939 __update_clear_spte_fast(sptep, 0ull);
941 old_spte = __update_clear_spte_slow(sptep, 0ull);
943 if (!is_shadow_present_pte(old_spte))
946 pfn = spte_to_pfn(old_spte);
949 * KVM does not hold the refcount of the page used by
950 * kvm mmu, before reclaiming the page, we should
951 * unmap it from mmu first.
953 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
955 if (is_accessed_spte(old_spte))
956 kvm_set_pfn_accessed(pfn);
958 if (is_dirty_spte(old_spte))
959 kvm_set_pfn_dirty(pfn);
965 * Rules for using mmu_spte_clear_no_track:
966 * Directly clear spte without caring the state bits of sptep,
967 * it is used to set the upper level spte.
969 static void mmu_spte_clear_no_track(u64 *sptep)
971 __update_clear_spte_fast(sptep, 0ull);
974 static u64 mmu_spte_get_lockless(u64 *sptep)
976 return __get_spte_lockless(sptep);
979 static u64 mark_spte_for_access_track(u64 spte)
981 if (spte_ad_enabled(spte))
982 return spte & ~shadow_accessed_mask;
984 if (is_access_track_spte(spte))
988 * Making an Access Tracking PTE will result in removal of write access
989 * from the PTE. So, verify that we will be able to restore the write
990 * access in the fast page fault path later on.
992 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
993 !spte_can_locklessly_be_made_writable(spte),
994 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
996 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
997 shadow_acc_track_saved_bits_shift),
998 "kvm: Access Tracking saved bit locations are not zero\n");
1000 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
1001 shadow_acc_track_saved_bits_shift;
1002 spte &= ~shadow_acc_track_mask;
1007 /* Restore an acc-track PTE back to a regular PTE */
1008 static u64 restore_acc_track_spte(u64 spte)
1010 u64 new_spte = spte;
1011 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
1012 & shadow_acc_track_saved_bits_mask;
1014 WARN_ON_ONCE(spte_ad_enabled(spte));
1015 WARN_ON_ONCE(!is_access_track_spte(spte));
1017 new_spte &= ~shadow_acc_track_mask;
1018 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
1019 shadow_acc_track_saved_bits_shift);
1020 new_spte |= saved_bits;
1025 /* Returns the Accessed status of the PTE and resets it at the same time. */
1026 static bool mmu_spte_age(u64 *sptep)
1028 u64 spte = mmu_spte_get_lockless(sptep);
1030 if (!is_accessed_spte(spte))
1033 if (spte_ad_enabled(spte)) {
1034 clear_bit((ffs(shadow_accessed_mask) - 1),
1035 (unsigned long *)sptep);
1038 * Capture the dirty status of the page, so that it doesn't get
1039 * lost when the SPTE is marked for access tracking.
1041 if (is_writable_pte(spte))
1042 kvm_set_pfn_dirty(spte_to_pfn(spte));
1044 spte = mark_spte_for_access_track(spte);
1045 mmu_spte_update_no_track(sptep, spte);
1051 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
1054 * Prevent page table teardown by making any free-er wait during
1055 * kvm_flush_remote_tlbs() IPI to all active vcpus.
1057 local_irq_disable();
1060 * Make sure a following spte read is not reordered ahead of the write
1063 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
1066 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
1069 * Make sure the write to vcpu->mode is not reordered in front of
1070 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
1071 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
1073 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
1077 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
1081 /* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
1082 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1083 1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
1086 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
1087 PT64_ROOT_MAX_LEVEL);
1090 if (maybe_indirect) {
1091 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_gfn_array_cache,
1092 PT64_ROOT_MAX_LEVEL);
1096 return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1097 PT64_ROOT_MAX_LEVEL);
1100 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1102 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
1103 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
1104 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
1105 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
1108 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1110 return kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1113 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1115 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1118 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1120 if (!sp->role.direct)
1121 return sp->gfns[index];
1123 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1126 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1128 if (!sp->role.direct) {
1129 sp->gfns[index] = gfn;
1133 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1134 pr_err_ratelimited("gfn mismatch under direct page %llx "
1135 "(expected %llx, got %llx)\n",
1137 kvm_mmu_page_get_gfn(sp, index), gfn);
1141 * Return the pointer to the large page information for a given gfn,
1142 * handling slots that are not large page aligned.
1144 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1145 struct kvm_memory_slot *slot,
1150 idx = gfn_to_index(gfn, slot->base_gfn, level);
1151 return &slot->arch.lpage_info[level - 2][idx];
1154 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1155 gfn_t gfn, int count)
1157 struct kvm_lpage_info *linfo;
1160 for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1161 linfo = lpage_info_slot(gfn, slot, i);
1162 linfo->disallow_lpage += count;
1163 WARN_ON(linfo->disallow_lpage < 0);
1167 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1169 update_gfn_disallow_lpage_count(slot, gfn, 1);
1172 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1174 update_gfn_disallow_lpage_count(slot, gfn, -1);
1177 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1179 struct kvm_memslots *slots;
1180 struct kvm_memory_slot *slot;
1183 kvm->arch.indirect_shadow_pages++;
1185 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1186 slot = __gfn_to_memslot(slots, gfn);
1188 /* the non-leaf shadow pages are keeping readonly. */
1189 if (sp->role.level > PG_LEVEL_4K)
1190 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1191 KVM_PAGE_TRACK_WRITE);
1193 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1196 static void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1198 if (sp->lpage_disallowed)
1201 ++kvm->stat.nx_lpage_splits;
1202 list_add_tail(&sp->lpage_disallowed_link,
1203 &kvm->arch.lpage_disallowed_mmu_pages);
1204 sp->lpage_disallowed = true;
1207 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1209 struct kvm_memslots *slots;
1210 struct kvm_memory_slot *slot;
1213 kvm->arch.indirect_shadow_pages--;
1215 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1216 slot = __gfn_to_memslot(slots, gfn);
1217 if (sp->role.level > PG_LEVEL_4K)
1218 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1219 KVM_PAGE_TRACK_WRITE);
1221 kvm_mmu_gfn_allow_lpage(slot, gfn);
1224 static void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1226 --kvm->stat.nx_lpage_splits;
1227 sp->lpage_disallowed = false;
1228 list_del(&sp->lpage_disallowed_link);
1231 static struct kvm_memory_slot *
1232 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1235 struct kvm_memory_slot *slot;
1237 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1238 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1240 if (no_dirty_log && slot->dirty_bitmap)
1247 * About rmap_head encoding:
1249 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1250 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1251 * pte_list_desc containing more mappings.
1255 * Returns the number of pointers in the rmap chain, not counting the new one.
1257 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1258 struct kvm_rmap_head *rmap_head)
1260 struct pte_list_desc *desc;
1263 if (!rmap_head->val) {
1264 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1265 rmap_head->val = (unsigned long)spte;
1266 } else if (!(rmap_head->val & 1)) {
1267 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1268 desc = mmu_alloc_pte_list_desc(vcpu);
1269 desc->sptes[0] = (u64 *)rmap_head->val;
1270 desc->sptes[1] = spte;
1271 rmap_head->val = (unsigned long)desc | 1;
1274 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1275 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1276 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1278 count += PTE_LIST_EXT;
1280 if (desc->sptes[PTE_LIST_EXT-1]) {
1281 desc->more = mmu_alloc_pte_list_desc(vcpu);
1284 for (i = 0; desc->sptes[i]; ++i)
1286 desc->sptes[i] = spte;
1292 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1293 struct pte_list_desc *desc, int i,
1294 struct pte_list_desc *prev_desc)
1298 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1300 desc->sptes[i] = desc->sptes[j];
1301 desc->sptes[j] = NULL;
1304 if (!prev_desc && !desc->more)
1308 prev_desc->more = desc->more;
1310 rmap_head->val = (unsigned long)desc->more | 1;
1311 mmu_free_pte_list_desc(desc);
1314 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1316 struct pte_list_desc *desc;
1317 struct pte_list_desc *prev_desc;
1320 if (!rmap_head->val) {
1321 pr_err("%s: %p 0->BUG\n", __func__, spte);
1323 } else if (!(rmap_head->val & 1)) {
1324 rmap_printk("%s: %p 1->0\n", __func__, spte);
1325 if ((u64 *)rmap_head->val != spte) {
1326 pr_err("%s: %p 1->BUG\n", __func__, spte);
1331 rmap_printk("%s: %p many->many\n", __func__, spte);
1332 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1335 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1336 if (desc->sptes[i] == spte) {
1337 pte_list_desc_remove_entry(rmap_head,
1338 desc, i, prev_desc);
1345 pr_err("%s: %p many->many\n", __func__, spte);
1350 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1352 mmu_spte_clear_track_bits(sptep);
1353 __pte_list_remove(sptep, rmap_head);
1356 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1357 struct kvm_memory_slot *slot)
1361 idx = gfn_to_index(gfn, slot->base_gfn, level);
1362 return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1365 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1366 struct kvm_mmu_page *sp)
1368 struct kvm_memslots *slots;
1369 struct kvm_memory_slot *slot;
1371 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1372 slot = __gfn_to_memslot(slots, gfn);
1373 return __gfn_to_rmap(gfn, sp->role.level, slot);
1376 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1378 struct kvm_mmu_memory_cache *mc;
1380 mc = &vcpu->arch.mmu_pte_list_desc_cache;
1381 return kvm_mmu_memory_cache_nr_free_objects(mc);
1384 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1386 struct kvm_mmu_page *sp;
1387 struct kvm_rmap_head *rmap_head;
1389 sp = sptep_to_sp(spte);
1390 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1391 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1392 return pte_list_add(vcpu, spte, rmap_head);
1395 static void rmap_remove(struct kvm *kvm, u64 *spte)
1397 struct kvm_mmu_page *sp;
1399 struct kvm_rmap_head *rmap_head;
1401 sp = sptep_to_sp(spte);
1402 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1403 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1404 __pte_list_remove(spte, rmap_head);
1408 * Used by the following functions to iterate through the sptes linked by a
1409 * rmap. All fields are private and not assumed to be used outside.
1411 struct rmap_iterator {
1412 /* private fields */
1413 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1414 int pos; /* index of the sptep */
1418 * Iteration must be started by this function. This should also be used after
1419 * removing/dropping sptes from the rmap link because in such cases the
1420 * information in the iterator may not be valid.
1422 * Returns sptep if found, NULL otherwise.
1424 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1425 struct rmap_iterator *iter)
1429 if (!rmap_head->val)
1432 if (!(rmap_head->val & 1)) {
1434 sptep = (u64 *)rmap_head->val;
1438 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1440 sptep = iter->desc->sptes[iter->pos];
1442 BUG_ON(!is_shadow_present_pte(*sptep));
1447 * Must be used with a valid iterator: e.g. after rmap_get_first().
1449 * Returns sptep if found, NULL otherwise.
1451 static u64 *rmap_get_next(struct rmap_iterator *iter)
1456 if (iter->pos < PTE_LIST_EXT - 1) {
1458 sptep = iter->desc->sptes[iter->pos];
1463 iter->desc = iter->desc->more;
1467 /* desc->sptes[0] cannot be NULL */
1468 sptep = iter->desc->sptes[iter->pos];
1475 BUG_ON(!is_shadow_present_pte(*sptep));
1479 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1480 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1481 _spte_; _spte_ = rmap_get_next(_iter_))
1483 static void drop_spte(struct kvm *kvm, u64 *sptep)
1485 if (mmu_spte_clear_track_bits(sptep))
1486 rmap_remove(kvm, sptep);
1490 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1492 if (is_large_pte(*sptep)) {
1493 WARN_ON(sptep_to_sp(sptep)->role.level == PG_LEVEL_4K);
1494 drop_spte(kvm, sptep);
1502 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1504 if (__drop_large_spte(vcpu->kvm, sptep)) {
1505 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
1507 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1508 KVM_PAGES_PER_HPAGE(sp->role.level));
1513 * Write-protect on the specified @sptep, @pt_protect indicates whether
1514 * spte write-protection is caused by protecting shadow page table.
1516 * Note: write protection is difference between dirty logging and spte
1518 * - for dirty logging, the spte can be set to writable at anytime if
1519 * its dirty bitmap is properly set.
1520 * - for spte protection, the spte can be writable only after unsync-ing
1523 * Return true if tlb need be flushed.
1525 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1529 if (!is_writable_pte(spte) &&
1530 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1533 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1536 spte &= ~SPTE_MMU_WRITEABLE;
1537 spte = spte & ~PT_WRITABLE_MASK;
1539 return mmu_spte_update(sptep, spte);
1542 static bool __rmap_write_protect(struct kvm *kvm,
1543 struct kvm_rmap_head *rmap_head,
1547 struct rmap_iterator iter;
1550 for_each_rmap_spte(rmap_head, &iter, sptep)
1551 flush |= spte_write_protect(sptep, pt_protect);
1556 static bool spte_clear_dirty(u64 *sptep)
1560 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1562 MMU_WARN_ON(!spte_ad_enabled(spte));
1563 spte &= ~shadow_dirty_mask;
1564 return mmu_spte_update(sptep, spte);
1567 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1569 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1570 (unsigned long *)sptep);
1571 if (was_writable && !spte_ad_enabled(*sptep))
1572 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1574 return was_writable;
1578 * Gets the GFN ready for another round of dirty logging by clearing the
1579 * - D bit on ad-enabled SPTEs, and
1580 * - W bit on ad-disabled SPTEs.
1581 * Returns true iff any D or W bits were cleared.
1583 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1586 struct rmap_iterator iter;
1589 for_each_rmap_spte(rmap_head, &iter, sptep)
1590 if (spte_ad_need_write_protect(*sptep))
1591 flush |= spte_wrprot_for_clear_dirty(sptep);
1593 flush |= spte_clear_dirty(sptep);
1598 static bool spte_set_dirty(u64 *sptep)
1602 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1605 * Similar to the !kvm_x86_ops.slot_disable_log_dirty case,
1606 * do not bother adding back write access to pages marked
1607 * SPTE_AD_WRPROT_ONLY_MASK.
1609 spte |= shadow_dirty_mask;
1611 return mmu_spte_update(sptep, spte);
1614 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1617 struct rmap_iterator iter;
1620 for_each_rmap_spte(rmap_head, &iter, sptep)
1621 if (spte_ad_enabled(*sptep))
1622 flush |= spte_set_dirty(sptep);
1628 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1629 * @kvm: kvm instance
1630 * @slot: slot to protect
1631 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1632 * @mask: indicates which pages we should protect
1634 * Used when we do not need to care about huge page mappings: e.g. during dirty
1635 * logging we do not have any such mappings.
1637 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1638 struct kvm_memory_slot *slot,
1639 gfn_t gfn_offset, unsigned long mask)
1641 struct kvm_rmap_head *rmap_head;
1644 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1646 __rmap_write_protect(kvm, rmap_head, false);
1648 /* clear the first set bit */
1654 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1655 * protect the page if the D-bit isn't supported.
1656 * @kvm: kvm instance
1657 * @slot: slot to clear D-bit
1658 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1659 * @mask: indicates which pages we should clear D-bit
1661 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1663 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1664 struct kvm_memory_slot *slot,
1665 gfn_t gfn_offset, unsigned long mask)
1667 struct kvm_rmap_head *rmap_head;
1670 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1672 __rmap_clear_dirty(kvm, rmap_head);
1674 /* clear the first set bit */
1678 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1681 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1684 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1685 * enable dirty logging for them.
1687 * Used when we do not need to care about huge page mappings: e.g. during dirty
1688 * logging we do not have any such mappings.
1690 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1691 struct kvm_memory_slot *slot,
1692 gfn_t gfn_offset, unsigned long mask)
1694 if (kvm_x86_ops.enable_log_dirty_pt_masked)
1695 kvm_x86_ops.enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1698 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1701 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1702 struct kvm_memory_slot *slot, u64 gfn)
1704 struct kvm_rmap_head *rmap_head;
1706 bool write_protected = false;
1708 for (i = PG_LEVEL_4K; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1709 rmap_head = __gfn_to_rmap(gfn, i, slot);
1710 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1713 return write_protected;
1716 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1718 struct kvm_memory_slot *slot;
1720 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1721 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1724 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1727 struct rmap_iterator iter;
1730 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1731 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1733 pte_list_remove(rmap_head, sptep);
1740 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1741 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1744 return kvm_zap_rmapp(kvm, rmap_head);
1747 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1748 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1752 struct rmap_iterator iter;
1755 pte_t *ptep = (pte_t *)data;
1758 WARN_ON(pte_huge(*ptep));
1759 new_pfn = pte_pfn(*ptep);
1762 for_each_rmap_spte(rmap_head, &iter, sptep) {
1763 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1764 sptep, *sptep, gfn, level);
1768 if (pte_write(*ptep)) {
1769 pte_list_remove(rmap_head, sptep);
1772 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1773 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1775 new_spte &= ~PT_WRITABLE_MASK;
1776 new_spte &= ~SPTE_HOST_WRITEABLE;
1778 new_spte = mark_spte_for_access_track(new_spte);
1780 mmu_spte_clear_track_bits(sptep);
1781 mmu_spte_set(sptep, new_spte);
1785 if (need_flush && kvm_available_flush_tlb_with_range()) {
1786 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1793 struct slot_rmap_walk_iterator {
1795 struct kvm_memory_slot *slot;
1801 /* output fields. */
1803 struct kvm_rmap_head *rmap;
1806 /* private field. */
1807 struct kvm_rmap_head *end_rmap;
1811 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1813 iterator->level = level;
1814 iterator->gfn = iterator->start_gfn;
1815 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1816 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1821 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1822 struct kvm_memory_slot *slot, int start_level,
1823 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1825 iterator->slot = slot;
1826 iterator->start_level = start_level;
1827 iterator->end_level = end_level;
1828 iterator->start_gfn = start_gfn;
1829 iterator->end_gfn = end_gfn;
1831 rmap_walk_init_level(iterator, iterator->start_level);
1834 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1836 return !!iterator->rmap;
1839 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1841 if (++iterator->rmap <= iterator->end_rmap) {
1842 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1846 if (++iterator->level > iterator->end_level) {
1847 iterator->rmap = NULL;
1851 rmap_walk_init_level(iterator, iterator->level);
1854 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1855 _start_gfn, _end_gfn, _iter_) \
1856 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1857 _end_level_, _start_gfn, _end_gfn); \
1858 slot_rmap_walk_okay(_iter_); \
1859 slot_rmap_walk_next(_iter_))
1861 static int kvm_handle_hva_range(struct kvm *kvm,
1862 unsigned long start,
1865 int (*handler)(struct kvm *kvm,
1866 struct kvm_rmap_head *rmap_head,
1867 struct kvm_memory_slot *slot,
1870 unsigned long data))
1872 struct kvm_memslots *slots;
1873 struct kvm_memory_slot *memslot;
1874 struct slot_rmap_walk_iterator iterator;
1878 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1879 slots = __kvm_memslots(kvm, i);
1880 kvm_for_each_memslot(memslot, slots) {
1881 unsigned long hva_start, hva_end;
1882 gfn_t gfn_start, gfn_end;
1884 hva_start = max(start, memslot->userspace_addr);
1885 hva_end = min(end, memslot->userspace_addr +
1886 (memslot->npages << PAGE_SHIFT));
1887 if (hva_start >= hva_end)
1890 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1891 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1893 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1894 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1896 for_each_slot_rmap_range(memslot, PG_LEVEL_4K,
1897 KVM_MAX_HUGEPAGE_LEVEL,
1898 gfn_start, gfn_end - 1,
1900 ret |= handler(kvm, iterator.rmap, memslot,
1901 iterator.gfn, iterator.level, data);
1908 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1910 int (*handler)(struct kvm *kvm,
1911 struct kvm_rmap_head *rmap_head,
1912 struct kvm_memory_slot *slot,
1913 gfn_t gfn, int level,
1914 unsigned long data))
1916 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1919 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end,
1922 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1925 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1927 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1930 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1931 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1935 struct rmap_iterator iter;
1938 for_each_rmap_spte(rmap_head, &iter, sptep)
1939 young |= mmu_spte_age(sptep);
1941 trace_kvm_age_page(gfn, level, slot, young);
1945 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1946 struct kvm_memory_slot *slot, gfn_t gfn,
1947 int level, unsigned long data)
1950 struct rmap_iterator iter;
1952 for_each_rmap_spte(rmap_head, &iter, sptep)
1953 if (is_accessed_spte(*sptep))
1958 #define RMAP_RECYCLE_THRESHOLD 1000
1960 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1962 struct kvm_rmap_head *rmap_head;
1963 struct kvm_mmu_page *sp;
1965 sp = sptep_to_sp(spte);
1967 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1969 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1970 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1971 KVM_PAGES_PER_HPAGE(sp->role.level));
1974 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1976 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
1979 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1981 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1985 static int is_empty_shadow_page(u64 *spt)
1990 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1991 if (is_shadow_present_pte(*pos)) {
1992 printk(KERN_ERR "%s: %p %llx\n", __func__,
2001 * This value is the sum of all of the kvm instances's
2002 * kvm->arch.n_used_mmu_pages values. We need a global,
2003 * aggregate version in order to make the slab shrinker
2006 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2008 kvm->arch.n_used_mmu_pages += nr;
2009 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2012 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2014 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2015 hlist_del(&sp->hash_link);
2016 list_del(&sp->link);
2017 free_page((unsigned long)sp->spt);
2018 if (!sp->role.direct)
2019 free_page((unsigned long)sp->gfns);
2020 kmem_cache_free(mmu_page_header_cache, sp);
2023 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2025 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2028 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2029 struct kvm_mmu_page *sp, u64 *parent_pte)
2034 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2037 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2040 __pte_list_remove(parent_pte, &sp->parent_ptes);
2043 static void drop_parent_pte(struct kvm_mmu_page *sp,
2046 mmu_page_remove_parent_pte(sp, parent_pte);
2047 mmu_spte_clear_no_track(parent_pte);
2050 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2052 struct kvm_mmu_page *sp;
2054 sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2055 sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
2057 sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
2058 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2061 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2062 * depends on valid pages being added to the head of the list. See
2063 * comments in kvm_zap_obsolete_pages().
2065 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2066 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2067 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2071 static void mark_unsync(u64 *spte);
2072 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2075 struct rmap_iterator iter;
2077 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2082 static void mark_unsync(u64 *spte)
2084 struct kvm_mmu_page *sp;
2087 sp = sptep_to_sp(spte);
2088 index = spte - sp->spt;
2089 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2091 if (sp->unsync_children++)
2093 kvm_mmu_mark_parents_unsync(sp);
2096 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2097 struct kvm_mmu_page *sp)
2102 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2103 struct kvm_mmu_page *sp, u64 *spte,
2109 #define KVM_PAGE_ARRAY_NR 16
2111 struct kvm_mmu_pages {
2112 struct mmu_page_and_offset {
2113 struct kvm_mmu_page *sp;
2115 } page[KVM_PAGE_ARRAY_NR];
2119 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2125 for (i=0; i < pvec->nr; i++)
2126 if (pvec->page[i].sp == sp)
2129 pvec->page[pvec->nr].sp = sp;
2130 pvec->page[pvec->nr].idx = idx;
2132 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2135 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2137 --sp->unsync_children;
2138 WARN_ON((int)sp->unsync_children < 0);
2139 __clear_bit(idx, sp->unsync_child_bitmap);
2142 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2143 struct kvm_mmu_pages *pvec)
2145 int i, ret, nr_unsync_leaf = 0;
2147 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2148 struct kvm_mmu_page *child;
2149 u64 ent = sp->spt[i];
2151 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2152 clear_unsync_child_bit(sp, i);
2156 child = to_shadow_page(ent & PT64_BASE_ADDR_MASK);
2158 if (child->unsync_children) {
2159 if (mmu_pages_add(pvec, child, i))
2162 ret = __mmu_unsync_walk(child, pvec);
2164 clear_unsync_child_bit(sp, i);
2166 } else if (ret > 0) {
2167 nr_unsync_leaf += ret;
2170 } else if (child->unsync) {
2172 if (mmu_pages_add(pvec, child, i))
2175 clear_unsync_child_bit(sp, i);
2178 return nr_unsync_leaf;
2181 #define INVALID_INDEX (-1)
2183 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2184 struct kvm_mmu_pages *pvec)
2187 if (!sp->unsync_children)
2190 mmu_pages_add(pvec, sp, INVALID_INDEX);
2191 return __mmu_unsync_walk(sp, pvec);
2194 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2196 WARN_ON(!sp->unsync);
2197 trace_kvm_mmu_sync_page(sp);
2199 --kvm->stat.mmu_unsync;
2202 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2203 struct list_head *invalid_list);
2204 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2205 struct list_head *invalid_list);
2207 #define for_each_valid_sp(_kvm, _sp, _list) \
2208 hlist_for_each_entry(_sp, _list, hash_link) \
2209 if (is_obsolete_sp((_kvm), (_sp))) { \
2212 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2213 for_each_valid_sp(_kvm, _sp, \
2214 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
2215 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2217 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2219 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2222 /* @sp->gfn should be write-protected at the call site */
2223 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2224 struct list_head *invalid_list)
2226 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2227 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2228 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2235 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2236 struct list_head *invalid_list,
2239 if (!remote_flush && list_empty(invalid_list))
2242 if (!list_empty(invalid_list))
2243 kvm_mmu_commit_zap_page(kvm, invalid_list);
2245 kvm_flush_remote_tlbs(kvm);
2249 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2250 struct list_head *invalid_list,
2251 bool remote_flush, bool local_flush)
2253 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2257 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2260 #ifdef CONFIG_KVM_MMU_AUDIT
2261 #include "mmu_audit.c"
2263 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2264 static void mmu_audit_disable(void) { }
2267 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2269 return sp->role.invalid ||
2270 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2273 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2274 struct list_head *invalid_list)
2276 kvm_unlink_unsync_page(vcpu->kvm, sp);
2277 return __kvm_sync_page(vcpu, sp, invalid_list);
2280 /* @gfn should be write-protected at the call site */
2281 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2282 struct list_head *invalid_list)
2284 struct kvm_mmu_page *s;
2287 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2291 WARN_ON(s->role.level != PG_LEVEL_4K);
2292 ret |= kvm_sync_page(vcpu, s, invalid_list);
2298 struct mmu_page_path {
2299 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2300 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2303 #define for_each_sp(pvec, sp, parents, i) \
2304 for (i = mmu_pages_first(&pvec, &parents); \
2305 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2306 i = mmu_pages_next(&pvec, &parents, i))
2308 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2309 struct mmu_page_path *parents,
2314 for (n = i+1; n < pvec->nr; n++) {
2315 struct kvm_mmu_page *sp = pvec->page[n].sp;
2316 unsigned idx = pvec->page[n].idx;
2317 int level = sp->role.level;
2319 parents->idx[level-1] = idx;
2320 if (level == PG_LEVEL_4K)
2323 parents->parent[level-2] = sp;
2329 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2330 struct mmu_page_path *parents)
2332 struct kvm_mmu_page *sp;
2338 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2340 sp = pvec->page[0].sp;
2341 level = sp->role.level;
2342 WARN_ON(level == PG_LEVEL_4K);
2344 parents->parent[level-2] = sp;
2346 /* Also set up a sentinel. Further entries in pvec are all
2347 * children of sp, so this element is never overwritten.
2349 parents->parent[level-1] = NULL;
2350 return mmu_pages_next(pvec, parents, 0);
2353 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2355 struct kvm_mmu_page *sp;
2356 unsigned int level = 0;
2359 unsigned int idx = parents->idx[level];
2360 sp = parents->parent[level];
2364 WARN_ON(idx == INVALID_INDEX);
2365 clear_unsync_child_bit(sp, idx);
2367 } while (!sp->unsync_children);
2370 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2371 struct kvm_mmu_page *parent)
2374 struct kvm_mmu_page *sp;
2375 struct mmu_page_path parents;
2376 struct kvm_mmu_pages pages;
2377 LIST_HEAD(invalid_list);
2380 while (mmu_unsync_walk(parent, &pages)) {
2381 bool protected = false;
2383 for_each_sp(pages, sp, parents, i)
2384 protected |= rmap_write_protect(vcpu, sp->gfn);
2387 kvm_flush_remote_tlbs(vcpu->kvm);
2391 for_each_sp(pages, sp, parents, i) {
2392 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2393 mmu_pages_clear_parents(&parents);
2395 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2396 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2397 cond_resched_lock(&vcpu->kvm->mmu_lock);
2402 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2405 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2407 atomic_set(&sp->write_flooding_count, 0);
2410 static void clear_sp_write_flooding_count(u64 *spte)
2412 __clear_sp_write_flooding_count(sptep_to_sp(spte));
2415 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2420 unsigned int access)
2422 bool direct_mmu = vcpu->arch.mmu->direct_map;
2423 union kvm_mmu_page_role role;
2424 struct hlist_head *sp_list;
2426 struct kvm_mmu_page *sp;
2427 bool need_sync = false;
2430 LIST_HEAD(invalid_list);
2432 role = vcpu->arch.mmu->mmu_role.base;
2434 role.direct = direct;
2436 role.gpte_is_8_bytes = true;
2437 role.access = access;
2438 if (!direct_mmu && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2439 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2440 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2441 role.quadrant = quadrant;
2444 sp_list = &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2445 for_each_valid_sp(vcpu->kvm, sp, sp_list) {
2446 if (sp->gfn != gfn) {
2451 if (!need_sync && sp->unsync)
2454 if (sp->role.word != role.word)
2458 goto trace_get_page;
2461 /* The page is good, but __kvm_sync_page might still end
2462 * up zapping it. If so, break in order to rebuild it.
2464 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2467 WARN_ON(!list_empty(&invalid_list));
2468 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2471 if (sp->unsync_children)
2472 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2474 __clear_sp_write_flooding_count(sp);
2477 trace_kvm_mmu_get_page(sp, false);
2481 ++vcpu->kvm->stat.mmu_cache_miss;
2483 sp = kvm_mmu_alloc_page(vcpu, direct);
2487 hlist_add_head(&sp->hash_link, sp_list);
2490 * we should do write protection before syncing pages
2491 * otherwise the content of the synced shadow page may
2492 * be inconsistent with guest page table.
2494 account_shadowed(vcpu->kvm, sp);
2495 if (level == PG_LEVEL_4K && rmap_write_protect(vcpu, gfn))
2496 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2498 if (level > PG_LEVEL_4K && need_sync)
2499 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2501 trace_kvm_mmu_get_page(sp, true);
2503 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2505 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2506 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2510 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2511 struct kvm_vcpu *vcpu, hpa_t root,
2514 iterator->addr = addr;
2515 iterator->shadow_addr = root;
2516 iterator->level = vcpu->arch.mmu->shadow_root_level;
2518 if (iterator->level == PT64_ROOT_4LEVEL &&
2519 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2520 !vcpu->arch.mmu->direct_map)
2523 if (iterator->level == PT32E_ROOT_LEVEL) {
2525 * prev_root is currently only used for 64-bit hosts. So only
2526 * the active root_hpa is valid here.
2528 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2530 iterator->shadow_addr
2531 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2532 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2534 if (!iterator->shadow_addr)
2535 iterator->level = 0;
2539 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2540 struct kvm_vcpu *vcpu, u64 addr)
2542 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2546 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2548 if (iterator->level < PG_LEVEL_4K)
2551 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2552 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2556 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2559 if (is_last_spte(spte, iterator->level)) {
2560 iterator->level = 0;
2564 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2568 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2570 __shadow_walk_next(iterator, *iterator->sptep);
2573 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2574 struct kvm_mmu_page *sp)
2578 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2580 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2581 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2583 if (sp_ad_disabled(sp))
2584 spte |= SPTE_AD_DISABLED_MASK;
2586 spte |= shadow_accessed_mask;
2588 mmu_spte_set(sptep, spte);
2590 mmu_page_add_parent_pte(vcpu, sp, sptep);
2592 if (sp->unsync_children || sp->unsync)
2596 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2597 unsigned direct_access)
2599 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2600 struct kvm_mmu_page *child;
2603 * For the direct sp, if the guest pte's dirty bit
2604 * changed form clean to dirty, it will corrupt the
2605 * sp's access: allow writable in the read-only sp,
2606 * so we should update the spte at this point to get
2607 * a new sp with the correct access.
2609 child = to_shadow_page(*sptep & PT64_BASE_ADDR_MASK);
2610 if (child->role.access == direct_access)
2613 drop_parent_pte(child, sptep);
2614 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2618 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2622 struct kvm_mmu_page *child;
2625 if (is_shadow_present_pte(pte)) {
2626 if (is_last_spte(pte, sp->role.level)) {
2627 drop_spte(kvm, spte);
2628 if (is_large_pte(pte))
2631 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
2632 drop_parent_pte(child, spte);
2637 if (is_mmio_spte(pte))
2638 mmu_spte_clear_no_track(spte);
2643 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2644 struct kvm_mmu_page *sp)
2648 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2649 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2652 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2655 struct rmap_iterator iter;
2657 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2658 drop_parent_pte(sp, sptep);
2661 static int mmu_zap_unsync_children(struct kvm *kvm,
2662 struct kvm_mmu_page *parent,
2663 struct list_head *invalid_list)
2666 struct mmu_page_path parents;
2667 struct kvm_mmu_pages pages;
2669 if (parent->role.level == PG_LEVEL_4K)
2672 while (mmu_unsync_walk(parent, &pages)) {
2673 struct kvm_mmu_page *sp;
2675 for_each_sp(pages, sp, parents, i) {
2676 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2677 mmu_pages_clear_parents(&parents);
2685 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2686 struct kvm_mmu_page *sp,
2687 struct list_head *invalid_list,
2692 trace_kvm_mmu_prepare_zap_page(sp);
2693 ++kvm->stat.mmu_shadow_zapped;
2694 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2695 kvm_mmu_page_unlink_children(kvm, sp);
2696 kvm_mmu_unlink_parents(kvm, sp);
2698 /* Zapping children means active_mmu_pages has become unstable. */
2699 list_unstable = *nr_zapped;
2701 if (!sp->role.invalid && !sp->role.direct)
2702 unaccount_shadowed(kvm, sp);
2705 kvm_unlink_unsync_page(kvm, sp);
2706 if (!sp->root_count) {
2711 * Already invalid pages (previously active roots) are not on
2712 * the active page list. See list_del() in the "else" case of
2715 if (sp->role.invalid)
2716 list_add(&sp->link, invalid_list);
2718 list_move(&sp->link, invalid_list);
2719 kvm_mod_used_mmu_pages(kvm, -1);
2722 * Remove the active root from the active page list, the root
2723 * will be explicitly freed when the root_count hits zero.
2725 list_del(&sp->link);
2728 * Obsolete pages cannot be used on any vCPUs, see the comment
2729 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2730 * treats invalid shadow pages as being obsolete.
2732 if (!is_obsolete_sp(kvm, sp))
2733 kvm_reload_remote_mmus(kvm);
2736 if (sp->lpage_disallowed)
2737 unaccount_huge_nx_page(kvm, sp);
2739 sp->role.invalid = 1;
2740 return list_unstable;
2743 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2744 struct list_head *invalid_list)
2748 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2752 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2753 struct list_head *invalid_list)
2755 struct kvm_mmu_page *sp, *nsp;
2757 if (list_empty(invalid_list))
2761 * We need to make sure everyone sees our modifications to
2762 * the page tables and see changes to vcpu->mode here. The barrier
2763 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2764 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2766 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2767 * guest mode and/or lockless shadow page table walks.
2769 kvm_flush_remote_tlbs(kvm);
2771 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2772 WARN_ON(!sp->role.invalid || sp->root_count);
2773 kvm_mmu_free_page(sp);
2777 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2778 unsigned long nr_to_zap)
2780 unsigned long total_zapped = 0;
2781 struct kvm_mmu_page *sp, *tmp;
2782 LIST_HEAD(invalid_list);
2786 if (list_empty(&kvm->arch.active_mmu_pages))
2790 list_for_each_entry_safe(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2792 * Don't zap active root pages, the page itself can't be freed
2793 * and zapping it will just force vCPUs to realloc and reload.
2798 unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2800 total_zapped += nr_zapped;
2801 if (total_zapped >= nr_to_zap)
2808 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2810 kvm->stat.mmu_recycled += total_zapped;
2811 return total_zapped;
2814 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2816 if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2817 return kvm->arch.n_max_mmu_pages -
2818 kvm->arch.n_used_mmu_pages;
2823 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2825 unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2827 if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2830 kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2832 if (!kvm_mmu_available_pages(vcpu->kvm))
2838 * Changing the number of mmu pages allocated to the vm
2839 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2841 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2843 spin_lock(&kvm->mmu_lock);
2845 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2846 kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2849 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2852 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2854 spin_unlock(&kvm->mmu_lock);
2857 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2859 struct kvm_mmu_page *sp;
2860 LIST_HEAD(invalid_list);
2863 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2865 spin_lock(&kvm->mmu_lock);
2866 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2867 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2870 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2872 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2873 spin_unlock(&kvm->mmu_lock);
2877 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2879 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2881 trace_kvm_mmu_unsync_page(sp);
2882 ++vcpu->kvm->stat.mmu_unsync;
2885 kvm_mmu_mark_parents_unsync(sp);
2888 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2891 struct kvm_mmu_page *sp;
2893 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2896 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2903 WARN_ON(sp->role.level != PG_LEVEL_4K);
2904 kvm_unsync_page(vcpu, sp);
2908 * We need to ensure that the marking of unsync pages is visible
2909 * before the SPTE is updated to allow writes because
2910 * kvm_mmu_sync_roots() checks the unsync flags without holding
2911 * the MMU lock and so can race with this. If the SPTE was updated
2912 * before the page had been marked as unsync-ed, something like the
2913 * following could happen:
2916 * ---------------------------------------------------------------------
2917 * 1.2 Host updates SPTE
2919 * 2.1 Guest writes a GPTE for GVA X.
2920 * (GPTE being in the guest page table shadowed
2921 * by the SP from CPU 1.)
2922 * This reads SPTE during the page table walk.
2923 * Since SPTE.W is read as 1, there is no
2926 * 2.2 Guest issues TLB flush.
2927 * That causes a VM Exit.
2929 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2930 * Since it is false, so it just returns.
2932 * 2.4 Guest accesses GVA X.
2933 * Since the mapping in the SP was not updated,
2934 * so the old mapping for GVA X incorrectly
2938 * (sp->unsync = true)
2940 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2941 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2942 * pairs with this write barrier.
2949 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2952 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2954 * Some reserved pages, such as those from NVDIMM
2955 * DAX devices, are not for MMIO, and can be mapped
2956 * with cached memory type for better performance.
2957 * However, the above check misconceives those pages
2958 * as MMIO, and results in KVM mapping them with UC
2959 * memory type, which would hurt the performance.
2960 * Therefore, we check the host memory type in addition
2961 * and only treat UC/UC-/WC pages as MMIO.
2963 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2965 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2966 pfn_to_hpa(pfn + 1) - 1,
2970 /* Bits which may be returned by set_spte() */
2971 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2972 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2974 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2975 unsigned int pte_access, int level,
2976 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2977 bool can_unsync, bool host_writable)
2981 struct kvm_mmu_page *sp;
2983 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2986 sp = sptep_to_sp(sptep);
2987 if (sp_ad_disabled(sp))
2988 spte |= SPTE_AD_DISABLED_MASK;
2989 else if (kvm_vcpu_ad_need_write_protect(vcpu))
2990 spte |= SPTE_AD_WRPROT_ONLY_MASK;
2993 * For the EPT case, shadow_present_mask is 0 if hardware
2994 * supports exec-only page table entries. In that case,
2995 * ACC_USER_MASK and shadow_user_mask are used to represent
2996 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2998 spte |= shadow_present_mask;
3000 spte |= spte_shadow_accessed_mask(spte);
3002 if (level > PG_LEVEL_4K && (pte_access & ACC_EXEC_MASK) &&
3003 is_nx_huge_page_enabled()) {
3004 pte_access &= ~ACC_EXEC_MASK;
3007 if (pte_access & ACC_EXEC_MASK)
3008 spte |= shadow_x_mask;
3010 spte |= shadow_nx_mask;
3012 if (pte_access & ACC_USER_MASK)
3013 spte |= shadow_user_mask;
3015 if (level > PG_LEVEL_4K)
3016 spte |= PT_PAGE_SIZE_MASK;
3018 spte |= kvm_x86_ops.get_mt_mask(vcpu, gfn,
3019 kvm_is_mmio_pfn(pfn));
3022 spte |= SPTE_HOST_WRITEABLE;
3024 pte_access &= ~ACC_WRITE_MASK;
3026 if (!kvm_is_mmio_pfn(pfn))
3027 spte |= shadow_me_mask;
3029 spte |= (u64)pfn << PAGE_SHIFT;
3031 if (pte_access & ACC_WRITE_MASK) {
3032 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3035 * Optimization: for pte sync, if spte was writable the hash
3036 * lookup is unnecessary (and expensive). Write protection
3037 * is responsibility of mmu_get_page / kvm_sync_page.
3038 * Same reasoning can be applied to dirty page accounting.
3040 if (!can_unsync && is_writable_pte(*sptep))
3043 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3044 pgprintk("%s: found shadow page for %llx, marking ro\n",
3046 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3047 pte_access &= ~ACC_WRITE_MASK;
3048 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3052 if (pte_access & ACC_WRITE_MASK) {
3053 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3054 spte |= spte_shadow_dirty_mask(spte);
3058 spte = mark_spte_for_access_track(spte);
3061 if (mmu_spte_update(sptep, spte))
3062 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3066 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
3067 unsigned int pte_access, int write_fault, int level,
3068 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
3071 int was_rmapped = 0;
3074 int ret = RET_PF_RETRY;
3077 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3078 *sptep, write_fault, gfn);
3080 if (is_shadow_present_pte(*sptep)) {
3082 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3083 * the parent of the now unreachable PTE.
3085 if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
3086 struct kvm_mmu_page *child;
3089 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
3090 drop_parent_pte(child, sptep);
3092 } else if (pfn != spte_to_pfn(*sptep)) {
3093 pgprintk("hfn old %llx new %llx\n",
3094 spte_to_pfn(*sptep), pfn);
3095 drop_spte(vcpu->kvm, sptep);
3101 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3102 speculative, true, host_writable);
3103 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3105 ret = RET_PF_EMULATE;
3106 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3109 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3110 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3111 KVM_PAGES_PER_HPAGE(level));
3113 if (unlikely(is_mmio_spte(*sptep)))
3114 ret = RET_PF_EMULATE;
3116 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3117 trace_kvm_mmu_set_spte(level, gfn, sptep);
3118 if (!was_rmapped && is_large_pte(*sptep))
3119 ++vcpu->kvm->stat.lpages;
3121 if (is_shadow_present_pte(*sptep)) {
3123 rmap_count = rmap_add(vcpu, sptep, gfn);
3124 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3125 rmap_recycle(vcpu, sptep, gfn);
3132 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3135 struct kvm_memory_slot *slot;
3137 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3139 return KVM_PFN_ERR_FAULT;
3141 return gfn_to_pfn_memslot_atomic(slot, gfn);
3144 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3145 struct kvm_mmu_page *sp,
3146 u64 *start, u64 *end)
3148 struct page *pages[PTE_PREFETCH_NUM];
3149 struct kvm_memory_slot *slot;
3150 unsigned int access = sp->role.access;
3154 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3155 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3159 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3163 for (i = 0; i < ret; i++, gfn++, start++) {
3164 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3165 page_to_pfn(pages[i]), true, true);
3172 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3173 struct kvm_mmu_page *sp, u64 *sptep)
3175 u64 *spte, *start = NULL;
3178 WARN_ON(!sp->role.direct);
3180 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3183 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3184 if (is_shadow_present_pte(*spte) || spte == sptep) {
3187 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3195 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3197 struct kvm_mmu_page *sp;
3199 sp = sptep_to_sp(sptep);
3202 * Without accessed bits, there's no way to distinguish between
3203 * actually accessed translations and prefetched, so disable pte
3204 * prefetch if accessed bits aren't available.
3206 if (sp_ad_disabled(sp))
3209 if (sp->role.level > PG_LEVEL_4K)
3212 __direct_pte_prefetch(vcpu, sp, sptep);
3215 static int host_pfn_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn,
3216 kvm_pfn_t pfn, struct kvm_memory_slot *slot)
3222 if (!PageCompound(pfn_to_page(pfn)) && !kvm_is_zone_device_pfn(pfn))
3226 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3227 * is not solely for performance, it's also necessary to avoid the
3228 * "writable" check in __gfn_to_hva_many(), which will always fail on
3229 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
3230 * page fault steps have already verified the guest isn't writing a
3231 * read-only memslot.
3233 hva = __gfn_to_hva_memslot(slot, gfn);
3235 pte = lookup_address_in_mm(vcpu->kvm->mm, hva, &level);
3242 static int kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t gfn,
3243 int max_level, kvm_pfn_t *pfnp)
3245 struct kvm_memory_slot *slot;
3246 struct kvm_lpage_info *linfo;
3247 kvm_pfn_t pfn = *pfnp;
3251 if (unlikely(max_level == PG_LEVEL_4K))
3254 if (is_error_noslot_pfn(pfn) || kvm_is_reserved_pfn(pfn))
3257 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, true);
3261 max_level = min(max_level, max_huge_page_level);
3262 for ( ; max_level > PG_LEVEL_4K; max_level--) {
3263 linfo = lpage_info_slot(gfn, slot, max_level);
3264 if (!linfo->disallow_lpage)
3268 if (max_level == PG_LEVEL_4K)
3271 level = host_pfn_mapping_level(vcpu, gfn, pfn, slot);
3272 if (level == PG_LEVEL_4K)
3275 level = min(level, max_level);
3278 * mmu_notifier_retry() was successful and mmu_lock is held, so
3279 * the pmd can't be split from under us.
3281 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3282 VM_BUG_ON((gfn & mask) != (pfn & mask));
3283 *pfnp = pfn & ~mask;
3288 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3289 gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3291 int level = *levelp;
3292 u64 spte = *it.sptep;
3294 if (it.level == level && level > PG_LEVEL_4K &&
3295 is_nx_huge_page_enabled() &&
3296 is_shadow_present_pte(spte) &&
3297 !is_large_pte(spte)) {
3299 * A small SPTE exists for this pfn, but FNAME(fetch)
3300 * and __direct_map would like to create a large PTE
3301 * instead: just force them to go down another level,
3302 * patching back for them into pfn the next 9 bits of
3305 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3306 *pfnp |= gfn & page_mask;
3311 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3312 int map_writable, int max_level, kvm_pfn_t pfn,
3313 bool prefault, bool account_disallowed_nx_lpage)
3315 struct kvm_shadow_walk_iterator it;
3316 struct kvm_mmu_page *sp;
3318 gfn_t gfn = gpa >> PAGE_SHIFT;
3319 gfn_t base_gfn = gfn;
3321 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
3322 return RET_PF_RETRY;
3324 level = kvm_mmu_hugepage_adjust(vcpu, gfn, max_level, &pfn);
3326 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3327 for_each_shadow_entry(vcpu, gpa, it) {
3329 * We cannot overwrite existing page tables with an NX
3330 * large page, as the leaf could be executable.
3332 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3334 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3335 if (it.level == level)
3338 drop_large_spte(vcpu, it.sptep);
3339 if (!is_shadow_present_pte(*it.sptep)) {
3340 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3341 it.level - 1, true, ACC_ALL);
3343 link_shadow_page(vcpu, it.sptep, sp);
3344 if (account_disallowed_nx_lpage)
3345 account_huge_nx_page(vcpu->kvm, sp);
3349 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3350 write, level, base_gfn, pfn, prefault,
3352 direct_pte_prefetch(vcpu, it.sptep);
3353 ++vcpu->stat.pf_fixed;
3357 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3359 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3362 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3365 * Do not cache the mmio info caused by writing the readonly gfn
3366 * into the spte otherwise read access on readonly gfn also can
3367 * caused mmio page fault and treat it as mmio access.
3369 if (pfn == KVM_PFN_ERR_RO_FAULT)
3370 return RET_PF_EMULATE;
3372 if (pfn == KVM_PFN_ERR_HWPOISON) {
3373 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3374 return RET_PF_RETRY;
3380 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3381 kvm_pfn_t pfn, unsigned int access,
3384 /* The pfn is invalid, report the error! */
3385 if (unlikely(is_error_pfn(pfn))) {
3386 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3390 if (unlikely(is_noslot_pfn(pfn)))
3391 vcpu_cache_mmio_info(vcpu, gva, gfn,
3392 access & shadow_mmio_access_mask);
3397 static bool page_fault_can_be_fast(u32 error_code)
3400 * Do not fix the mmio spte with invalid generation number which
3401 * need to be updated by slow page fault path.
3403 if (unlikely(error_code & PFERR_RSVD_MASK))
3406 /* See if the page fault is due to an NX violation */
3407 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3408 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3412 * #PF can be fast if:
3413 * 1. The shadow page table entry is not present, which could mean that
3414 * the fault is potentially caused by access tracking (if enabled).
3415 * 2. The shadow page table entry is present and the fault
3416 * is caused by write-protect, that means we just need change the W
3417 * bit of the spte which can be done out of mmu-lock.
3419 * However, if access tracking is disabled we know that a non-present
3420 * page must be a genuine page fault where we have to create a new SPTE.
3421 * So, if access tracking is disabled, we return true only for write
3422 * accesses to a present page.
3425 return shadow_acc_track_mask != 0 ||
3426 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3427 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3431 * Returns true if the SPTE was fixed successfully. Otherwise,
3432 * someone else modified the SPTE from its original value.
3435 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3436 u64 *sptep, u64 old_spte, u64 new_spte)
3440 WARN_ON(!sp->role.direct);
3443 * Theoretically we could also set dirty bit (and flush TLB) here in
3444 * order to eliminate unnecessary PML logging. See comments in
3445 * set_spte. But fast_page_fault is very unlikely to happen with PML
3446 * enabled, so we do not do this. This might result in the same GPA
3447 * to be logged in PML buffer again when the write really happens, and
3448 * eventually to be called by mark_page_dirty twice. But it's also no
3449 * harm. This also avoids the TLB flush needed after setting dirty bit
3450 * so non-PML cases won't be impacted.
3452 * Compare with set_spte where instead shadow_dirty_mask is set.
3454 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3457 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3459 * The gfn of direct spte is stable since it is
3460 * calculated by sp->gfn.
3462 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3463 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3469 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3471 if (fault_err_code & PFERR_FETCH_MASK)
3472 return is_executable_pte(spte);
3474 if (fault_err_code & PFERR_WRITE_MASK)
3475 return is_writable_pte(spte);
3477 /* Fault was on Read access */
3478 return spte & PT_PRESENT_MASK;
3483 * - true: let the vcpu to access on the same address again.
3484 * - false: let the real page fault path to fix it.
3486 static bool fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
3489 struct kvm_shadow_walk_iterator iterator;
3490 struct kvm_mmu_page *sp;
3491 bool fault_handled = false;
3493 uint retry_count = 0;
3495 if (!page_fault_can_be_fast(error_code))
3498 walk_shadow_page_lockless_begin(vcpu);
3503 for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
3504 if (!is_shadow_present_pte(spte))
3507 sp = sptep_to_sp(iterator.sptep);
3508 if (!is_last_spte(spte, sp->role.level))
3512 * Check whether the memory access that caused the fault would
3513 * still cause it if it were to be performed right now. If not,
3514 * then this is a spurious fault caused by TLB lazily flushed,
3515 * or some other CPU has already fixed the PTE after the
3516 * current CPU took the fault.
3518 * Need not check the access of upper level table entries since
3519 * they are always ACC_ALL.
3521 if (is_access_allowed(error_code, spte)) {
3522 fault_handled = true;
3528 if (is_access_track_spte(spte))
3529 new_spte = restore_acc_track_spte(new_spte);
3532 * Currently, to simplify the code, write-protection can
3533 * be removed in the fast path only if the SPTE was
3534 * write-protected for dirty-logging or access tracking.
3536 if ((error_code & PFERR_WRITE_MASK) &&
3537 spte_can_locklessly_be_made_writable(spte)) {
3538 new_spte |= PT_WRITABLE_MASK;
3541 * Do not fix write-permission on the large spte. Since
3542 * we only dirty the first page into the dirty-bitmap in
3543 * fast_pf_fix_direct_spte(), other pages are missed
3544 * if its slot has dirty logging enabled.
3546 * Instead, we let the slow page fault path create a
3547 * normal spte to fix the access.
3549 * See the comments in kvm_arch_commit_memory_region().
3551 if (sp->role.level > PG_LEVEL_4K)
3555 /* Verify that the fault can be handled in the fast path */
3556 if (new_spte == spte ||
3557 !is_access_allowed(error_code, new_spte))
3561 * Currently, fast page fault only works for direct mapping
3562 * since the gfn is not stable for indirect shadow page. See
3563 * Documentation/virt/kvm/locking.rst to get more detail.
3565 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3566 iterator.sptep, spte,
3571 if (++retry_count > 4) {
3572 printk_once(KERN_WARNING
3573 "kvm: Fast #PF retrying more than 4 times.\n");
3579 trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
3580 spte, fault_handled);
3581 walk_shadow_page_lockless_end(vcpu);
3583 return fault_handled;
3586 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3587 struct list_head *invalid_list)
3589 struct kvm_mmu_page *sp;
3591 if (!VALID_PAGE(*root_hpa))
3594 sp = to_shadow_page(*root_hpa & PT64_BASE_ADDR_MASK);
3596 if (!sp->root_count && sp->role.invalid)
3597 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3599 *root_hpa = INVALID_PAGE;
3602 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3603 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3604 ulong roots_to_free)
3607 LIST_HEAD(invalid_list);
3608 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3610 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3612 /* Before acquiring the MMU lock, see if we need to do any real work. */
3613 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3614 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3615 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3616 VALID_PAGE(mmu->prev_roots[i].hpa))
3619 if (i == KVM_MMU_NUM_PREV_ROOTS)
3623 spin_lock(&vcpu->kvm->mmu_lock);
3625 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3626 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3627 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3630 if (free_active_root) {
3631 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3632 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3633 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3636 for (i = 0; i < 4; ++i)
3637 if (mmu->pae_root[i] != 0)
3638 mmu_free_root_page(vcpu->kvm,
3641 mmu->root_hpa = INVALID_PAGE;
3646 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3647 spin_unlock(&vcpu->kvm->mmu_lock);
3649 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3651 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3655 if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3656 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3663 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
3664 u8 level, bool direct)
3666 struct kvm_mmu_page *sp;
3668 spin_lock(&vcpu->kvm->mmu_lock);
3670 if (make_mmu_pages_available(vcpu)) {
3671 spin_unlock(&vcpu->kvm->mmu_lock);
3672 return INVALID_PAGE;
3674 sp = kvm_mmu_get_page(vcpu, gfn, gva, level, direct, ACC_ALL);
3677 spin_unlock(&vcpu->kvm->mmu_lock);
3678 return __pa(sp->spt);
3681 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3683 u8 shadow_root_level = vcpu->arch.mmu->shadow_root_level;
3687 if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3688 root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
3689 if (!VALID_PAGE(root))
3691 vcpu->arch.mmu->root_hpa = root;
3692 } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3693 for (i = 0; i < 4; ++i) {
3694 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
3696 root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT),
3697 i << 30, PT32_ROOT_LEVEL, true);
3698 if (!VALID_PAGE(root))
3700 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3702 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3706 /* root_pgd is ignored for direct MMUs. */
3707 vcpu->arch.mmu->root_pgd = 0;
3712 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3715 gfn_t root_gfn, root_pgd;
3719 root_pgd = vcpu->arch.mmu->get_guest_pgd(vcpu);
3720 root_gfn = root_pgd >> PAGE_SHIFT;
3722 if (mmu_check_root(vcpu, root_gfn))
3726 * Do we shadow a long mode page table? If so we need to
3727 * write-protect the guests page table root.
3729 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3730 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->root_hpa));
3732 root = mmu_alloc_root(vcpu, root_gfn, 0,
3733 vcpu->arch.mmu->shadow_root_level, false);
3734 if (!VALID_PAGE(root))
3736 vcpu->arch.mmu->root_hpa = root;
3741 * We shadow a 32 bit page table. This may be a legacy 2-level
3742 * or a PAE 3-level page table. In either case we need to be aware that
3743 * the shadow page table may be a PAE or a long mode page table.
3745 pm_mask = PT_PRESENT_MASK;
3746 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3747 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3749 for (i = 0; i < 4; ++i) {
3750 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
3751 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3752 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3753 if (!(pdptr & PT_PRESENT_MASK)) {
3754 vcpu->arch.mmu->pae_root[i] = 0;
3757 root_gfn = pdptr >> PAGE_SHIFT;
3758 if (mmu_check_root(vcpu, root_gfn))
3762 root = mmu_alloc_root(vcpu, root_gfn, i << 30,
3763 PT32_ROOT_LEVEL, false);
3764 if (!VALID_PAGE(root))
3766 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3768 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3771 * If we shadow a 32 bit page table with a long mode page
3772 * table we enter this path.
3774 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3775 if (vcpu->arch.mmu->lm_root == NULL) {
3777 * The additional page necessary for this is only
3778 * allocated on demand.
3783 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3784 if (lm_root == NULL)
3787 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3789 vcpu->arch.mmu->lm_root = lm_root;
3792 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3796 vcpu->arch.mmu->root_pgd = root_pgd;
3801 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3803 if (vcpu->arch.mmu->direct_map)
3804 return mmu_alloc_direct_roots(vcpu);
3806 return mmu_alloc_shadow_roots(vcpu);
3809 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3812 struct kvm_mmu_page *sp;
3814 if (vcpu->arch.mmu->direct_map)
3817 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3820 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3822 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3823 hpa_t root = vcpu->arch.mmu->root_hpa;
3824 sp = to_shadow_page(root);
3827 * Even if another CPU was marking the SP as unsync-ed
3828 * simultaneously, any guest page table changes are not
3829 * guaranteed to be visible anyway until this VCPU issues a TLB
3830 * flush strictly after those changes are made. We only need to
3831 * ensure that the other CPU sets these flags before any actual
3832 * changes to the page tables are made. The comments in
3833 * mmu_need_write_protect() describe what could go wrong if this
3834 * requirement isn't satisfied.
3836 if (!smp_load_acquire(&sp->unsync) &&
3837 !smp_load_acquire(&sp->unsync_children))
3840 spin_lock(&vcpu->kvm->mmu_lock);
3841 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3843 mmu_sync_children(vcpu, sp);
3845 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3846 spin_unlock(&vcpu->kvm->mmu_lock);
3850 spin_lock(&vcpu->kvm->mmu_lock);
3851 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3853 for (i = 0; i < 4; ++i) {
3854 hpa_t root = vcpu->arch.mmu->pae_root[i];
3856 if (root && VALID_PAGE(root)) {
3857 root &= PT64_BASE_ADDR_MASK;
3858 sp = to_shadow_page(root);
3859 mmu_sync_children(vcpu, sp);
3863 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3864 spin_unlock(&vcpu->kvm->mmu_lock);
3866 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3868 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3869 u32 access, struct x86_exception *exception)
3872 exception->error_code = 0;
3876 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3878 struct x86_exception *exception)
3881 exception->error_code = 0;
3882 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3886 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3888 int bit7 = (pte >> 7) & 1;
3890 return pte & rsvd_check->rsvd_bits_mask[bit7][level-1];
3893 static bool __is_bad_mt_xwr(struct rsvd_bits_validate *rsvd_check, u64 pte)
3895 return rsvd_check->bad_mt_xwr & BIT_ULL(pte & 0x3f);
3898 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3901 * A nested guest cannot use the MMIO cache if it is using nested
3902 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3904 if (mmu_is_nested(vcpu))
3908 return vcpu_match_mmio_gpa(vcpu, addr);
3910 return vcpu_match_mmio_gva(vcpu, addr);
3913 /* return true if reserved bit is detected on spte. */
3915 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3917 struct kvm_shadow_walk_iterator iterator;
3918 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3919 struct rsvd_bits_validate *rsvd_check;
3921 bool reserved = false;
3923 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
3925 walk_shadow_page_lockless_begin(vcpu);
3927 for (shadow_walk_init(&iterator, vcpu, addr),
3928 leaf = root = iterator.level;
3929 shadow_walk_okay(&iterator);
3930 __shadow_walk_next(&iterator, spte)) {
3931 spte = mmu_spte_get_lockless(iterator.sptep);
3933 sptes[leaf - 1] = spte;
3936 if (!is_shadow_present_pte(spte))
3940 * Use a bitwise-OR instead of a logical-OR to aggregate the
3941 * reserved bit and EPT's invalid memtype/XWR checks to avoid
3942 * adding a Jcc in the loop.
3944 reserved |= __is_bad_mt_xwr(rsvd_check, spte) |
3945 __is_rsvd_bits_set(rsvd_check, spte, iterator.level);
3948 walk_shadow_page_lockless_end(vcpu);
3951 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3953 while (root > leaf) {
3954 pr_err("------ spte 0x%llx level %d.\n",
3955 sptes[root - 1], root);
3964 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3969 if (mmio_info_in_cache(vcpu, addr, direct))
3970 return RET_PF_EMULATE;
3972 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3973 if (WARN_ON(reserved))
3976 if (is_mmio_spte(spte)) {
3977 gfn_t gfn = get_mmio_spte_gfn(spte);
3978 unsigned int access = get_mmio_spte_access(spte);
3980 if (!check_mmio_spte(vcpu, spte))
3981 return RET_PF_INVALID;
3986 trace_handle_mmio_page_fault(addr, gfn, access);
3987 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3988 return RET_PF_EMULATE;
3992 * If the page table is zapped by other cpus, let CPU fault again on
3995 return RET_PF_RETRY;
3998 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3999 u32 error_code, gfn_t gfn)
4001 if (unlikely(error_code & PFERR_RSVD_MASK))
4004 if (!(error_code & PFERR_PRESENT_MASK) ||
4005 !(error_code & PFERR_WRITE_MASK))
4009 * guest is writing the page which is write tracked which can
4010 * not be fixed by page fault handler.
4012 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4018 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4020 struct kvm_shadow_walk_iterator iterator;
4023 walk_shadow_page_lockless_begin(vcpu);
4024 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4025 clear_sp_write_flooding_count(iterator.sptep);
4026 if (!is_shadow_present_pte(spte))
4029 walk_shadow_page_lockless_end(vcpu);
4032 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4035 struct kvm_arch_async_pf arch;
4037 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4039 arch.direct_map = vcpu->arch.mmu->direct_map;
4040 arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
4042 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4043 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4046 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4047 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
4050 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4053 /* Don't expose private memslots to L2. */
4054 if (is_guest_mode(vcpu) && !kvm_is_visible_memslot(slot)) {
4055 *pfn = KVM_PFN_NOSLOT;
4061 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4063 return false; /* *pfn has correct page already */
4065 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4066 trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
4067 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4068 trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
4069 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4071 } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
4075 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4079 static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4080 bool prefault, int max_level, bool is_tdp)
4082 bool write = error_code & PFERR_WRITE_MASK;
4083 bool exec = error_code & PFERR_FETCH_MASK;
4084 bool lpage_disallowed = exec && is_nx_huge_page_enabled();
4087 gfn_t gfn = gpa >> PAGE_SHIFT;
4088 unsigned long mmu_seq;
4092 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4093 return RET_PF_EMULATE;
4095 if (fast_page_fault(vcpu, gpa, error_code))
4096 return RET_PF_RETRY;
4098 r = mmu_topup_memory_caches(vcpu, false);
4102 if (lpage_disallowed)
4103 max_level = PG_LEVEL_4K;
4105 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4108 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4109 return RET_PF_RETRY;
4111 if (handle_abnormal_pfn(vcpu, is_tdp ? 0 : gpa, gfn, pfn, ACC_ALL, &r))
4115 spin_lock(&vcpu->kvm->mmu_lock);
4116 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4118 r = make_mmu_pages_available(vcpu);
4121 r = __direct_map(vcpu, gpa, write, map_writable, max_level, pfn,
4122 prefault, is_tdp && lpage_disallowed);
4125 spin_unlock(&vcpu->kvm->mmu_lock);
4126 kvm_release_pfn_clean(pfn);
4130 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
4131 u32 error_code, bool prefault)
4133 pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
4135 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4136 return direct_page_fault(vcpu, gpa & PAGE_MASK, error_code, prefault,
4137 PG_LEVEL_2M, false);
4140 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4141 u64 fault_address, char *insn, int insn_len)
4144 u32 flags = vcpu->arch.apf.host_apf_flags;
4146 #ifndef CONFIG_X86_64
4147 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4148 if (WARN_ON_ONCE(fault_address >> 32))
4152 vcpu->arch.l1tf_flush_l1d = true;
4154 trace_kvm_page_fault(fault_address, error_code);
4156 if (kvm_event_needs_reinjection(vcpu))
4157 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4158 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4160 } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
4161 vcpu->arch.apf.host_apf_flags = 0;
4162 local_irq_disable();
4163 kvm_async_pf_task_wait_schedule(fault_address);
4166 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4171 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4173 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4178 for (max_level = KVM_MAX_HUGEPAGE_LEVEL;
4179 max_level > PG_LEVEL_4K;
4181 int page_num = KVM_PAGES_PER_HPAGE(max_level);
4182 gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
4184 if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4188 return direct_page_fault(vcpu, gpa, error_code, prefault,
4192 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4193 struct kvm_mmu *context)
4195 context->page_fault = nonpaging_page_fault;
4196 context->gva_to_gpa = nonpaging_gva_to_gpa;
4197 context->sync_page = nonpaging_sync_page;
4198 context->invlpg = NULL;
4199 context->update_pte = nonpaging_update_pte;
4200 context->root_level = 0;
4201 context->shadow_root_level = PT32E_ROOT_LEVEL;
4202 context->direct_map = true;
4203 context->nx = false;
4206 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
4207 union kvm_mmu_page_role role)
4209 return (role.direct || pgd == root->pgd) &&
4210 VALID_PAGE(root->hpa) && to_shadow_page(root->hpa) &&
4211 role.word == to_shadow_page(root->hpa)->role.word;
4215 * Find out if a previously cached root matching the new pgd/role is available.
4216 * The current root is also inserted into the cache.
4217 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4219 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4220 * false is returned. This root should now be freed by the caller.
4222 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4223 union kvm_mmu_page_role new_role)
4226 struct kvm_mmu_root_info root;
4227 struct kvm_mmu *mmu = vcpu->arch.mmu;
4229 root.pgd = mmu->root_pgd;
4230 root.hpa = mmu->root_hpa;
4232 if (is_root_usable(&root, new_pgd, new_role))
4235 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4236 swap(root, mmu->prev_roots[i]);
4238 if (is_root_usable(&root, new_pgd, new_role))
4242 mmu->root_hpa = root.hpa;
4243 mmu->root_pgd = root.pgd;
4245 return i < KVM_MMU_NUM_PREV_ROOTS;
4248 static bool fast_pgd_switch(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4249 union kvm_mmu_page_role new_role)
4251 struct kvm_mmu *mmu = vcpu->arch.mmu;
4254 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4255 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4256 * later if necessary.
4258 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4259 mmu->root_level >= PT64_ROOT_4LEVEL)
4260 return cached_root_available(vcpu, new_pgd, new_role);
4265 static void __kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4266 union kvm_mmu_page_role new_role,
4267 bool skip_tlb_flush, bool skip_mmu_sync)
4269 if (!fast_pgd_switch(vcpu, new_pgd, new_role)) {
4270 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, KVM_MMU_ROOT_CURRENT);
4275 * It's possible that the cached previous root page is obsolete because
4276 * of a change in the MMU generation number. However, changing the
4277 * generation number is accompanied by KVM_REQ_MMU_RELOAD, which will
4278 * free the root set here and allocate a new one.
4280 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4282 if (!skip_mmu_sync || force_flush_and_sync_on_reuse)
4283 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4284 if (!skip_tlb_flush || force_flush_and_sync_on_reuse)
4285 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4288 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4289 * switching to a new CR3, that GVA->GPA mapping may no longer be
4290 * valid. So clear any cached MMIO info even when we don't need to sync
4291 * the shadow page tables.
4293 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4295 __clear_sp_write_flooding_count(to_shadow_page(vcpu->arch.mmu->root_hpa));
4298 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd, bool skip_tlb_flush,
4301 __kvm_mmu_new_pgd(vcpu, new_pgd, kvm_mmu_calc_root_page_role(vcpu),
4302 skip_tlb_flush, skip_mmu_sync);
4304 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4306 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4308 return kvm_read_cr3(vcpu);
4311 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4312 unsigned int access, int *nr_present)
4314 if (unlikely(is_mmio_spte(*sptep))) {
4315 if (gfn != get_mmio_spte_gfn(*sptep)) {
4316 mmu_spte_clear_no_track(sptep);
4321 mark_mmio_spte(vcpu, sptep, gfn, access);
4328 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4329 unsigned level, unsigned gpte)
4332 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4333 * If it is clear, there are no large pages at this level, so clear
4334 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4336 gpte &= level - mmu->last_nonleaf_level;
4339 * PG_LEVEL_4K always terminates. The RHS has bit 7 set
4340 * iff level <= PG_LEVEL_4K, which for our purpose means
4341 * level == PG_LEVEL_4K; set PT_PAGE_SIZE_MASK in gpte then.
4343 gpte |= level - PG_LEVEL_4K - 1;
4345 return gpte & PT_PAGE_SIZE_MASK;
4348 #define PTTYPE_EPT 18 /* arbitrary */
4349 #define PTTYPE PTTYPE_EPT
4350 #include "paging_tmpl.h"
4354 #include "paging_tmpl.h"
4358 #include "paging_tmpl.h"
4362 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4363 struct rsvd_bits_validate *rsvd_check,
4364 int maxphyaddr, int level, bool nx, bool gbpages,
4367 u64 exb_bit_rsvd = 0;
4368 u64 gbpages_bit_rsvd = 0;
4369 u64 nonleaf_bit8_rsvd = 0;
4371 rsvd_check->bad_mt_xwr = 0;
4374 exb_bit_rsvd = rsvd_bits(63, 63);
4376 gbpages_bit_rsvd = rsvd_bits(7, 7);
4379 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4380 * leaf entries) on AMD CPUs only.
4383 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4386 case PT32_ROOT_LEVEL:
4387 /* no rsvd bits for 2 level 4K page table entries */
4388 rsvd_check->rsvd_bits_mask[0][1] = 0;
4389 rsvd_check->rsvd_bits_mask[0][0] = 0;
4390 rsvd_check->rsvd_bits_mask[1][0] =
4391 rsvd_check->rsvd_bits_mask[0][0];
4394 rsvd_check->rsvd_bits_mask[1][1] = 0;
4398 if (is_cpuid_PSE36())
4399 /* 36bits PSE 4MB page */
4400 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4402 /* 32 bits PSE 4MB page */
4403 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4405 case PT32E_ROOT_LEVEL:
4406 rsvd_check->rsvd_bits_mask[0][2] =
4407 rsvd_bits(maxphyaddr, 63) |
4408 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4409 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4410 rsvd_bits(maxphyaddr, 62); /* PDE */
4411 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4412 rsvd_bits(maxphyaddr, 62); /* PTE */
4413 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4414 rsvd_bits(maxphyaddr, 62) |
4415 rsvd_bits(13, 20); /* large page */
4416 rsvd_check->rsvd_bits_mask[1][0] =
4417 rsvd_check->rsvd_bits_mask[0][0];
4419 case PT64_ROOT_5LEVEL:
4420 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4421 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4422 rsvd_bits(maxphyaddr, 51);
4423 rsvd_check->rsvd_bits_mask[1][4] =
4424 rsvd_check->rsvd_bits_mask[0][4];
4426 case PT64_ROOT_4LEVEL:
4427 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4428 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4429 rsvd_bits(maxphyaddr, 51);
4430 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4432 rsvd_bits(maxphyaddr, 51);
4433 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4434 rsvd_bits(maxphyaddr, 51);
4435 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4436 rsvd_bits(maxphyaddr, 51);
4437 rsvd_check->rsvd_bits_mask[1][3] =
4438 rsvd_check->rsvd_bits_mask[0][3];
4439 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4440 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4442 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4443 rsvd_bits(maxphyaddr, 51) |
4444 rsvd_bits(13, 20); /* large page */
4445 rsvd_check->rsvd_bits_mask[1][0] =
4446 rsvd_check->rsvd_bits_mask[0][0];
4451 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4452 struct kvm_mmu *context)
4454 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4455 cpuid_maxphyaddr(vcpu), context->root_level,
4457 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4459 guest_cpuid_is_amd_or_hygon(vcpu));
4463 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4464 int maxphyaddr, bool execonly)
4468 rsvd_check->rsvd_bits_mask[0][4] =
4469 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4470 rsvd_check->rsvd_bits_mask[0][3] =
4471 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4472 rsvd_check->rsvd_bits_mask[0][2] =
4473 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4474 rsvd_check->rsvd_bits_mask[0][1] =
4475 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4476 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4479 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4480 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4481 rsvd_check->rsvd_bits_mask[1][2] =
4482 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4483 rsvd_check->rsvd_bits_mask[1][1] =
4484 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4485 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4487 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4488 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4489 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4490 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4491 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4493 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4494 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4496 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4499 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4500 struct kvm_mmu *context, bool execonly)
4502 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4503 cpuid_maxphyaddr(vcpu), execonly);
4507 * the page table on host is the shadow page table for the page
4508 * table in guest or amd nested guest, its mmu features completely
4509 * follow the features in guest.
4512 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4514 bool uses_nx = context->nx ||
4515 context->mmu_role.base.smep_andnot_wp;
4516 struct rsvd_bits_validate *shadow_zero_check;
4520 * Passing "true" to the last argument is okay; it adds a check
4521 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4523 shadow_zero_check = &context->shadow_zero_check;
4524 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4526 context->shadow_root_level, uses_nx,
4527 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4528 is_pse(vcpu), true);
4530 if (!shadow_me_mask)
4533 for (i = context->shadow_root_level; --i >= 0;) {
4534 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4535 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4539 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4541 static inline bool boot_cpu_is_amd(void)
4543 WARN_ON_ONCE(!tdp_enabled);
4544 return shadow_x_mask == 0;
4548 * the direct page table on host, use as much mmu features as
4549 * possible, however, kvm currently does not do execution-protection.
4552 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4553 struct kvm_mmu *context)
4555 struct rsvd_bits_validate *shadow_zero_check;
4558 shadow_zero_check = &context->shadow_zero_check;
4560 if (boot_cpu_is_amd())
4561 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4563 context->shadow_root_level, false,
4564 boot_cpu_has(X86_FEATURE_GBPAGES),
4567 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4571 if (!shadow_me_mask)
4574 for (i = context->shadow_root_level; --i >= 0;) {
4575 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4576 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4581 * as the comments in reset_shadow_zero_bits_mask() except it
4582 * is the shadow page table for intel nested guest.
4585 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4586 struct kvm_mmu *context, bool execonly)
4588 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4589 shadow_phys_bits, execonly);
4592 #define BYTE_MASK(access) \
4593 ((1 & (access) ? 2 : 0) | \
4594 (2 & (access) ? 4 : 0) | \
4595 (3 & (access) ? 8 : 0) | \
4596 (4 & (access) ? 16 : 0) | \
4597 (5 & (access) ? 32 : 0) | \
4598 (6 & (access) ? 64 : 0) | \
4599 (7 & (access) ? 128 : 0))
4602 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4603 struct kvm_mmu *mmu, bool ept)
4607 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4608 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4609 const u8 u = BYTE_MASK(ACC_USER_MASK);
4611 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4612 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4613 bool cr0_wp = is_write_protection(vcpu);
4615 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4616 unsigned pfec = byte << 1;
4619 * Each "*f" variable has a 1 bit for each UWX value
4620 * that causes a fault with the given PFEC.
4623 /* Faults from writes to non-writable pages */
4624 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4625 /* Faults from user mode accesses to supervisor pages */
4626 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4627 /* Faults from fetches of non-executable pages*/
4628 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4629 /* Faults from kernel mode fetches of user pages */
4631 /* Faults from kernel mode accesses of user pages */
4635 /* Faults from kernel mode accesses to user pages */
4636 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4638 /* Not really needed: !nx will cause pte.nx to fault */
4642 /* Allow supervisor writes if !cr0.wp */
4644 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4646 /* Disallow supervisor fetches of user code if cr4.smep */
4648 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4651 * SMAP:kernel-mode data accesses from user-mode
4652 * mappings should fault. A fault is considered
4653 * as a SMAP violation if all of the following
4654 * conditions are true:
4655 * - X86_CR4_SMAP is set in CR4
4656 * - A user page is accessed
4657 * - The access is not a fetch
4658 * - Page fault in kernel mode
4659 * - if CPL = 3 or X86_EFLAGS_AC is clear
4661 * Here, we cover the first three conditions.
4662 * The fourth is computed dynamically in permission_fault();
4663 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4664 * *not* subject to SMAP restrictions.
4667 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4670 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4675 * PKU is an additional mechanism by which the paging controls access to
4676 * user-mode addresses based on the value in the PKRU register. Protection
4677 * key violations are reported through a bit in the page fault error code.
4678 * Unlike other bits of the error code, the PK bit is not known at the
4679 * call site of e.g. gva_to_gpa; it must be computed directly in
4680 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4681 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4683 * In particular the following conditions come from the error code, the
4684 * page tables and the machine state:
4685 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4686 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4687 * - PK is always zero if U=0 in the page tables
4688 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4690 * The PKRU bitmask caches the result of these four conditions. The error
4691 * code (minus the P bit) and the page table's U bit form an index into the
4692 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4693 * with the two bits of the PKRU register corresponding to the protection key.
4694 * For the first three conditions above the bits will be 00, thus masking
4695 * away both AD and WD. For all reads or if the last condition holds, WD
4696 * only will be masked away.
4698 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4709 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4710 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4715 wp = is_write_protection(vcpu);
4717 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4718 unsigned pfec, pkey_bits;
4719 bool check_pkey, check_write, ff, uf, wf, pte_user;
4722 ff = pfec & PFERR_FETCH_MASK;
4723 uf = pfec & PFERR_USER_MASK;
4724 wf = pfec & PFERR_WRITE_MASK;
4726 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4727 pte_user = pfec & PFERR_RSVD_MASK;
4730 * Only need to check the access which is not an
4731 * instruction fetch and is to a user page.
4733 check_pkey = (!ff && pte_user);
4735 * write access is controlled by PKRU if it is a
4736 * user access or CR0.WP = 1.
4738 check_write = check_pkey && wf && (uf || wp);
4740 /* PKRU.AD stops both read and write access. */
4741 pkey_bits = !!check_pkey;
4742 /* PKRU.WD stops write access. */
4743 pkey_bits |= (!!check_write) << 1;
4745 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4749 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4751 unsigned root_level = mmu->root_level;
4753 mmu->last_nonleaf_level = root_level;
4754 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4755 mmu->last_nonleaf_level++;
4758 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4759 struct kvm_mmu *context,
4762 context->nx = is_nx(vcpu);
4763 context->root_level = level;
4765 reset_rsvds_bits_mask(vcpu, context);
4766 update_permission_bitmask(vcpu, context, false);
4767 update_pkru_bitmask(vcpu, context, false);
4768 update_last_nonleaf_level(vcpu, context);
4770 MMU_WARN_ON(!is_pae(vcpu));
4771 context->page_fault = paging64_page_fault;
4772 context->gva_to_gpa = paging64_gva_to_gpa;
4773 context->sync_page = paging64_sync_page;
4774 context->invlpg = paging64_invlpg;
4775 context->update_pte = paging64_update_pte;
4776 context->shadow_root_level = level;
4777 context->direct_map = false;
4780 static void paging64_init_context(struct kvm_vcpu *vcpu,
4781 struct kvm_mmu *context)
4783 int root_level = is_la57_mode(vcpu) ?
4784 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4786 paging64_init_context_common(vcpu, context, root_level);
4789 static void paging32_init_context(struct kvm_vcpu *vcpu,
4790 struct kvm_mmu *context)
4792 context->nx = false;
4793 context->root_level = PT32_ROOT_LEVEL;
4795 reset_rsvds_bits_mask(vcpu, context);
4796 update_permission_bitmask(vcpu, context, false);
4797 update_pkru_bitmask(vcpu, context, false);
4798 update_last_nonleaf_level(vcpu, context);
4800 context->page_fault = paging32_page_fault;
4801 context->gva_to_gpa = paging32_gva_to_gpa;
4802 context->sync_page = paging32_sync_page;
4803 context->invlpg = paging32_invlpg;
4804 context->update_pte = paging32_update_pte;
4805 context->shadow_root_level = PT32E_ROOT_LEVEL;
4806 context->direct_map = false;
4809 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4810 struct kvm_mmu *context)
4812 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4815 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4817 union kvm_mmu_extended_role ext = {0};
4819 ext.cr0_pg = !!is_paging(vcpu);
4820 ext.cr4_pae = !!is_pae(vcpu);
4821 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4822 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4823 ext.cr4_pse = !!is_pse(vcpu);
4824 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4825 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4832 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4835 union kvm_mmu_role role = {0};
4837 role.base.access = ACC_ALL;
4838 role.base.nxe = !!is_nx(vcpu);
4839 role.base.cr0_wp = is_write_protection(vcpu);
4840 role.base.smm = is_smm(vcpu);
4841 role.base.guest_mode = is_guest_mode(vcpu);
4846 role.ext = kvm_calc_mmu_role_ext(vcpu);
4851 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
4853 /* Use 5-level TDP if and only if it's useful/necessary. */
4854 if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
4857 return max_tdp_level;
4860 static union kvm_mmu_role
4861 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4863 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4865 role.base.ad_disabled = (shadow_accessed_mask == 0);
4866 role.base.level = kvm_mmu_get_tdp_level(vcpu);
4867 role.base.direct = true;
4868 role.base.gpte_is_8_bytes = true;
4873 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4875 struct kvm_mmu *context = &vcpu->arch.root_mmu;
4876 union kvm_mmu_role new_role =
4877 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4879 if (new_role.as_u64 == context->mmu_role.as_u64)
4882 context->mmu_role.as_u64 = new_role.as_u64;
4883 context->page_fault = kvm_tdp_page_fault;
4884 context->sync_page = nonpaging_sync_page;
4885 context->invlpg = NULL;
4886 context->update_pte = nonpaging_update_pte;
4887 context->shadow_root_level = kvm_mmu_get_tdp_level(vcpu);
4888 context->direct_map = true;
4889 context->get_guest_pgd = get_cr3;
4890 context->get_pdptr = kvm_pdptr_read;
4891 context->inject_page_fault = kvm_inject_page_fault;
4893 if (!is_paging(vcpu)) {
4894 context->nx = false;
4895 context->gva_to_gpa = nonpaging_gva_to_gpa;
4896 context->root_level = 0;
4897 } else if (is_long_mode(vcpu)) {
4898 context->nx = is_nx(vcpu);
4899 context->root_level = is_la57_mode(vcpu) ?
4900 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4901 reset_rsvds_bits_mask(vcpu, context);
4902 context->gva_to_gpa = paging64_gva_to_gpa;
4903 } else if (is_pae(vcpu)) {
4904 context->nx = is_nx(vcpu);
4905 context->root_level = PT32E_ROOT_LEVEL;
4906 reset_rsvds_bits_mask(vcpu, context);
4907 context->gva_to_gpa = paging64_gva_to_gpa;
4909 context->nx = false;
4910 context->root_level = PT32_ROOT_LEVEL;
4911 reset_rsvds_bits_mask(vcpu, context);
4912 context->gva_to_gpa = paging32_gva_to_gpa;
4915 update_permission_bitmask(vcpu, context, false);
4916 update_pkru_bitmask(vcpu, context, false);
4917 update_last_nonleaf_level(vcpu, context);
4918 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4921 static union kvm_mmu_role
4922 kvm_calc_shadow_root_page_role_common(struct kvm_vcpu *vcpu, bool base_only)
4924 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4926 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4927 !is_write_protection(vcpu);
4928 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4929 !is_write_protection(vcpu);
4930 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4935 static union kvm_mmu_role
4936 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4938 union kvm_mmu_role role =
4939 kvm_calc_shadow_root_page_role_common(vcpu, base_only);
4941 role.base.direct = !is_paging(vcpu);
4943 if (!is_long_mode(vcpu))
4944 role.base.level = PT32E_ROOT_LEVEL;
4945 else if (is_la57_mode(vcpu))
4946 role.base.level = PT64_ROOT_5LEVEL;
4948 role.base.level = PT64_ROOT_4LEVEL;
4953 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
4954 u32 cr0, u32 cr4, u32 efer,
4955 union kvm_mmu_role new_role)
4957 if (!(cr0 & X86_CR0_PG))
4958 nonpaging_init_context(vcpu, context);
4959 else if (efer & EFER_LMA)
4960 paging64_init_context(vcpu, context);
4961 else if (cr4 & X86_CR4_PAE)
4962 paging32E_init_context(vcpu, context);
4964 paging32_init_context(vcpu, context);
4966 context->mmu_role.as_u64 = new_role.as_u64;
4967 reset_shadow_zero_bits_mask(vcpu, context);
4970 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer)
4972 struct kvm_mmu *context = &vcpu->arch.root_mmu;
4973 union kvm_mmu_role new_role =
4974 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4976 if (new_role.as_u64 != context->mmu_role.as_u64)
4977 shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
4980 static union kvm_mmu_role
4981 kvm_calc_shadow_npt_root_page_role(struct kvm_vcpu *vcpu)
4983 union kvm_mmu_role role =
4984 kvm_calc_shadow_root_page_role_common(vcpu, false);
4986 role.base.direct = false;
4987 role.base.level = kvm_mmu_get_tdp_level(vcpu);
4992 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer,
4995 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4996 union kvm_mmu_role new_role = kvm_calc_shadow_npt_root_page_role(vcpu);
4998 context->shadow_root_level = new_role.base.level;
5000 __kvm_mmu_new_pgd(vcpu, nested_cr3, new_role.base, false, false);
5002 if (new_role.as_u64 != context->mmu_role.as_u64)
5003 shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
5005 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5007 static union kvm_mmu_role
5008 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5009 bool execonly, u8 level)
5011 union kvm_mmu_role role = {0};
5013 /* SMM flag is inherited from root_mmu */
5014 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
5016 role.base.level = level;
5017 role.base.gpte_is_8_bytes = true;
5018 role.base.direct = false;
5019 role.base.ad_disabled = !accessed_dirty;
5020 role.base.guest_mode = true;
5021 role.base.access = ACC_ALL;
5024 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
5025 * SMAP variation to denote shadow EPT entries.
5027 role.base.cr0_wp = true;
5028 role.base.smap_andnot_wp = true;
5030 role.ext = kvm_calc_mmu_role_ext(vcpu);
5031 role.ext.execonly = execonly;
5036 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5037 bool accessed_dirty, gpa_t new_eptp)
5039 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5040 u8 level = vmx_eptp_page_walk_level(new_eptp);
5041 union kvm_mmu_role new_role =
5042 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5045 __kvm_mmu_new_pgd(vcpu, new_eptp, new_role.base, true, true);
5047 if (new_role.as_u64 == context->mmu_role.as_u64)
5050 context->shadow_root_level = level;
5053 context->ept_ad = accessed_dirty;
5054 context->page_fault = ept_page_fault;
5055 context->gva_to_gpa = ept_gva_to_gpa;
5056 context->sync_page = ept_sync_page;
5057 context->invlpg = ept_invlpg;
5058 context->update_pte = ept_update_pte;
5059 context->root_level = level;
5060 context->direct_map = false;
5061 context->mmu_role.as_u64 = new_role.as_u64;
5063 update_permission_bitmask(vcpu, context, true);
5064 update_pkru_bitmask(vcpu, context, true);
5065 update_last_nonleaf_level(vcpu, context);
5066 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5067 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5069 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5071 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5073 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5075 kvm_init_shadow_mmu(vcpu,
5076 kvm_read_cr0_bits(vcpu, X86_CR0_PG),
5077 kvm_read_cr4_bits(vcpu, X86_CR4_PAE),
5080 context->get_guest_pgd = get_cr3;
5081 context->get_pdptr = kvm_pdptr_read;
5082 context->inject_page_fault = kvm_inject_page_fault;
5085 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5087 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5088 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5090 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5093 g_context->mmu_role.as_u64 = new_role.as_u64;
5094 g_context->get_guest_pgd = get_cr3;
5095 g_context->get_pdptr = kvm_pdptr_read;
5096 g_context->inject_page_fault = kvm_inject_page_fault;
5099 * L2 page tables are never shadowed, so there is no need to sync
5102 g_context->invlpg = NULL;
5105 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5106 * L1's nested page tables (e.g. EPT12). The nested translation
5107 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5108 * L2's page tables as the first level of translation and L1's
5109 * nested page tables as the second level of translation. Basically
5110 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5112 if (!is_paging(vcpu)) {
5113 g_context->nx = false;
5114 g_context->root_level = 0;
5115 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5116 } else if (is_long_mode(vcpu)) {
5117 g_context->nx = is_nx(vcpu);
5118 g_context->root_level = is_la57_mode(vcpu) ?
5119 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5120 reset_rsvds_bits_mask(vcpu, g_context);
5121 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5122 } else if (is_pae(vcpu)) {
5123 g_context->nx = is_nx(vcpu);
5124 g_context->root_level = PT32E_ROOT_LEVEL;
5125 reset_rsvds_bits_mask(vcpu, g_context);
5126 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5128 g_context->nx = false;
5129 g_context->root_level = PT32_ROOT_LEVEL;
5130 reset_rsvds_bits_mask(vcpu, g_context);
5131 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5134 update_permission_bitmask(vcpu, g_context, false);
5135 update_pkru_bitmask(vcpu, g_context, false);
5136 update_last_nonleaf_level(vcpu, g_context);
5139 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5144 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5146 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5147 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5150 if (mmu_is_nested(vcpu))
5151 init_kvm_nested_mmu(vcpu);
5152 else if (tdp_enabled)
5153 init_kvm_tdp_mmu(vcpu);
5155 init_kvm_softmmu(vcpu);
5157 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5159 static union kvm_mmu_page_role
5160 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5162 union kvm_mmu_role role;
5165 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5167 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5172 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5174 kvm_mmu_unload(vcpu);
5175 kvm_init_mmu(vcpu, true);
5177 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5179 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5183 r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->direct_map);
5186 r = mmu_alloc_roots(vcpu);
5187 kvm_mmu_sync_roots(vcpu);
5190 kvm_mmu_load_pgd(vcpu);
5191 kvm_x86_ops.tlb_flush_current(vcpu);
5195 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5197 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5199 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5200 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5201 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5202 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5204 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5206 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5207 struct kvm_mmu_page *sp, u64 *spte,
5210 if (sp->role.level != PG_LEVEL_4K) {
5211 ++vcpu->kvm->stat.mmu_pde_zapped;
5215 ++vcpu->kvm->stat.mmu_pte_updated;
5216 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5219 static bool need_remote_flush(u64 old, u64 new)
5221 if (!is_shadow_present_pte(old))
5223 if (!is_shadow_present_pte(new))
5225 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5227 old ^= shadow_nx_mask;
5228 new ^= shadow_nx_mask;
5229 return (old & ~new & PT64_PERM_MASK) != 0;
5232 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5239 * Assume that the pte write on a page table of the same type
5240 * as the current vcpu paging mode since we update the sptes only
5241 * when they have the same mode.
5243 if (is_pae(vcpu) && *bytes == 4) {
5244 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5249 if (*bytes == 4 || *bytes == 8) {
5250 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5259 * If we're seeing too many writes to a page, it may no longer be a page table,
5260 * or we may be forking, in which case it is better to unmap the page.
5262 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5265 * Skip write-flooding detected for the sp whose level is 1, because
5266 * it can become unsync, then the guest page is not write-protected.
5268 if (sp->role.level == PG_LEVEL_4K)
5271 atomic_inc(&sp->write_flooding_count);
5272 return atomic_read(&sp->write_flooding_count) >= 3;
5276 * Misaligned accesses are too much trouble to fix up; also, they usually
5277 * indicate a page is not used as a page table.
5279 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5282 unsigned offset, pte_size, misaligned;
5284 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5285 gpa, bytes, sp->role.word);
5287 offset = offset_in_page(gpa);
5288 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5291 * Sometimes, the OS only writes the last one bytes to update status
5292 * bits, for example, in linux, andb instruction is used in clear_bit().
5294 if (!(offset & (pte_size - 1)) && bytes == 1)
5297 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5298 misaligned |= bytes < 4;
5303 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5305 unsigned page_offset, quadrant;
5309 page_offset = offset_in_page(gpa);
5310 level = sp->role.level;
5312 if (!sp->role.gpte_is_8_bytes) {
5313 page_offset <<= 1; /* 32->64 */
5315 * A 32-bit pde maps 4MB while the shadow pdes map
5316 * only 2MB. So we need to double the offset again
5317 * and zap two pdes instead of one.
5319 if (level == PT32_ROOT_LEVEL) {
5320 page_offset &= ~7; /* kill rounding error */
5324 quadrant = page_offset >> PAGE_SHIFT;
5325 page_offset &= ~PAGE_MASK;
5326 if (quadrant != sp->role.quadrant)
5330 spte = &sp->spt[page_offset / sizeof(*spte)];
5335 * Ignore various flags when determining if a SPTE can be immediately
5336 * overwritten for the current MMU.
5337 * - level: explicitly checked in mmu_pte_write_new_pte(), and will never
5338 * match the current MMU role, as MMU's level tracks the root level.
5339 * - access: updated based on the new guest PTE
5340 * - quadrant: handled by get_written_sptes()
5341 * - invalid: always false (loop only walks valid shadow pages)
5343 static const union kvm_mmu_page_role role_ign = {
5350 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5351 const u8 *new, int bytes,
5352 struct kvm_page_track_notifier_node *node)
5354 gfn_t gfn = gpa >> PAGE_SHIFT;
5355 struct kvm_mmu_page *sp;
5356 LIST_HEAD(invalid_list);
5357 u64 entry, gentry, *spte;
5359 bool remote_flush, local_flush;
5362 * If we don't have indirect shadow pages, it means no page is
5363 * write-protected, so we can exit simply.
5365 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5368 remote_flush = local_flush = false;
5370 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5373 * No need to care whether allocation memory is successful
5374 * or not since pte prefetch is skiped if it does not have
5375 * enough objects in the cache.
5377 mmu_topup_memory_caches(vcpu, true);
5379 spin_lock(&vcpu->kvm->mmu_lock);
5381 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5383 ++vcpu->kvm->stat.mmu_pte_write;
5384 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5386 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5387 if (detect_write_misaligned(sp, gpa, bytes) ||
5388 detect_write_flooding(sp)) {
5389 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5390 ++vcpu->kvm->stat.mmu_flooded;
5394 spte = get_written_sptes(sp, gpa, &npte);
5400 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5403 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5405 !((sp->role.word ^ base_role) & ~role_ign.word) &&
5407 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5408 if (need_remote_flush(entry, *spte))
5409 remote_flush = true;
5413 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5414 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5415 spin_unlock(&vcpu->kvm->mmu_lock);
5418 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5423 if (vcpu->arch.mmu->direct_map)
5426 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5428 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5432 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5434 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5435 void *insn, int insn_len)
5437 int r, emulation_type = EMULTYPE_PF;
5438 bool direct = vcpu->arch.mmu->direct_map;
5440 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
5441 return RET_PF_RETRY;
5444 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5445 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5446 if (r == RET_PF_EMULATE)
5450 if (r == RET_PF_INVALID) {
5451 r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5452 lower_32_bits(error_code), false);
5453 WARN_ON(r == RET_PF_INVALID);
5456 if (r == RET_PF_RETRY)
5462 * Before emulating the instruction, check if the error code
5463 * was due to a RO violation while translating the guest page.
5464 * This can occur when using nested virtualization with nested
5465 * paging in both guests. If true, we simply unprotect the page
5466 * and resume the guest.
5468 if (vcpu->arch.mmu->direct_map &&
5469 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5470 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5475 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5476 * optimistically try to just unprotect the page and let the processor
5477 * re-execute the instruction that caused the page fault. Do not allow
5478 * retrying MMIO emulation, as it's not only pointless but could also
5479 * cause us to enter an infinite loop because the processor will keep
5480 * faulting on the non-existent MMIO address. Retrying an instruction
5481 * from a nested guest is also pointless and dangerous as we are only
5482 * explicitly shadowing L1's page tables, i.e. unprotecting something
5483 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5485 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5486 emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5489 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5490 * This can happen if a guest gets a page-fault on data access but the HW
5491 * table walker is not able to read the instruction page (e.g instruction
5492 * page is not present in memory). In those cases we simply restart the
5493 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5495 if (unlikely(insn && !insn_len)) {
5496 if (!kvm_x86_ops.need_emulation_on_page_fault(vcpu))
5500 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5503 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5505 void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5506 gva_t gva, hpa_t root_hpa)
5510 /* It's actually a GPA for vcpu->arch.guest_mmu. */
5511 if (mmu != &vcpu->arch.guest_mmu) {
5512 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
5513 if (is_noncanonical_address(gva, vcpu))
5516 kvm_x86_ops.tlb_flush_gva(vcpu, gva);
5522 if (root_hpa == INVALID_PAGE) {
5523 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5526 * INVLPG is required to invalidate any global mappings for the VA,
5527 * irrespective of PCID. Since it would take us roughly similar amount
5528 * of work to determine whether any of the prev_root mappings of the VA
5529 * is marked global, or to just sync it blindly, so we might as well
5530 * just always sync it.
5532 * Mappings not reachable via the current cr3 or the prev_roots will be
5533 * synced when switching to that cr3, so nothing needs to be done here
5536 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5537 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5538 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5540 mmu->invlpg(vcpu, gva, root_hpa);
5543 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_gva);
5545 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5547 kvm_mmu_invalidate_gva(vcpu, vcpu->arch.mmu, gva, INVALID_PAGE);
5548 ++vcpu->stat.invlpg;
5550 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5553 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5555 struct kvm_mmu *mmu = vcpu->arch.mmu;
5556 bool tlb_flush = false;
5559 if (pcid == kvm_get_active_pcid(vcpu)) {
5560 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5564 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5565 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5566 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
5567 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5573 kvm_x86_ops.tlb_flush_gva(vcpu, gva);
5575 ++vcpu->stat.invlpg;
5578 * Mappings not reachable via the current cr3 or the prev_roots will be
5579 * synced when switching to that cr3, so nothing needs to be done here
5583 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5585 void kvm_configure_mmu(bool enable_tdp, int tdp_max_root_level,
5586 int tdp_huge_page_level)
5588 tdp_enabled = enable_tdp;
5589 max_tdp_level = tdp_max_root_level;
5592 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5593 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5594 * the kernel is not. But, KVM never creates a page size greater than
5595 * what is used by the kernel for any given HVA, i.e. the kernel's
5596 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5599 max_huge_page_level = tdp_huge_page_level;
5600 else if (boot_cpu_has(X86_FEATURE_GBPAGES))
5601 max_huge_page_level = PG_LEVEL_1G;
5603 max_huge_page_level = PG_LEVEL_2M;
5605 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5607 /* The return value indicates if tlb flush on all vcpus is needed. */
5608 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5610 /* The caller should hold mmu-lock before calling this function. */
5611 static __always_inline bool
5612 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5613 slot_level_handler fn, int start_level, int end_level,
5614 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5616 struct slot_rmap_walk_iterator iterator;
5619 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5620 end_gfn, &iterator) {
5622 flush |= fn(kvm, iterator.rmap);
5624 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5625 if (flush && lock_flush_tlb) {
5626 kvm_flush_remote_tlbs_with_address(kvm,
5628 iterator.gfn - start_gfn + 1);
5631 cond_resched_lock(&kvm->mmu_lock);
5635 if (flush && lock_flush_tlb) {
5636 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5637 end_gfn - start_gfn + 1);
5644 static __always_inline bool
5645 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5646 slot_level_handler fn, int start_level, int end_level,
5647 bool lock_flush_tlb)
5649 return slot_handle_level_range(kvm, memslot, fn, start_level,
5650 end_level, memslot->base_gfn,
5651 memslot->base_gfn + memslot->npages - 1,
5655 static __always_inline bool
5656 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5657 slot_level_handler fn, bool lock_flush_tlb)
5659 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5660 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5663 static __always_inline bool
5664 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5665 slot_level_handler fn, bool lock_flush_tlb)
5667 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K + 1,
5668 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5671 static __always_inline bool
5672 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5673 slot_level_handler fn, bool lock_flush_tlb)
5675 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5676 PG_LEVEL_4K, lock_flush_tlb);
5679 static void free_mmu_pages(struct kvm_mmu *mmu)
5681 free_page((unsigned long)mmu->pae_root);
5682 free_page((unsigned long)mmu->lm_root);
5685 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5691 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5692 * while the PDP table is a per-vCPU construct that's allocated at MMU
5693 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5694 * x86_64. Therefore we need to allocate the PDP table in the first
5695 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5696 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5697 * skip allocating the PDP table.
5699 if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5702 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5706 mmu->pae_root = page_address(page);
5707 for (i = 0; i < 4; ++i)
5708 mmu->pae_root[i] = INVALID_PAGE;
5713 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5718 vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
5719 vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
5721 vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
5722 vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
5724 vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
5726 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5727 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5729 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5730 vcpu->arch.root_mmu.root_pgd = 0;
5731 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5732 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5733 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5735 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5736 vcpu->arch.guest_mmu.root_pgd = 0;
5737 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5738 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5739 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5741 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5743 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5747 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5749 goto fail_allocate_root;
5753 free_mmu_pages(&vcpu->arch.guest_mmu);
5757 #define BATCH_ZAP_PAGES 10
5758 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5760 struct kvm_mmu_page *sp, *node;
5761 int nr_zapped, batch = 0;
5764 list_for_each_entry_safe_reverse(sp, node,
5765 &kvm->arch.active_mmu_pages, link) {
5767 * No obsolete valid page exists before a newly created page
5768 * since active_mmu_pages is a FIFO list.
5770 if (!is_obsolete_sp(kvm, sp))
5774 * Invalid pages should never land back on the list of active
5775 * pages. Skip the bogus page, otherwise we'll get stuck in an
5776 * infinite loop if the page gets put back on the list (again).
5778 if (WARN_ON(sp->role.invalid))
5782 * No need to flush the TLB since we're only zapping shadow
5783 * pages with an obsolete generation number and all vCPUS have
5784 * loaded a new root, i.e. the shadow pages being zapped cannot
5785 * be in active use by the guest.
5787 if (batch >= BATCH_ZAP_PAGES &&
5788 cond_resched_lock(&kvm->mmu_lock)) {
5793 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5794 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5801 * Trigger a remote TLB flush before freeing the page tables to ensure
5802 * KVM is not in the middle of a lockless shadow page table walk, which
5803 * may reference the pages.
5805 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5809 * Fast invalidate all shadow pages and use lock-break technique
5810 * to zap obsolete pages.
5812 * It's required when memslot is being deleted or VM is being
5813 * destroyed, in these cases, we should ensure that KVM MMU does
5814 * not use any resource of the being-deleted slot or all slots
5815 * after calling the function.
5817 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5819 lockdep_assert_held(&kvm->slots_lock);
5821 spin_lock(&kvm->mmu_lock);
5822 trace_kvm_mmu_zap_all_fast(kvm);
5825 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5826 * held for the entire duration of zapping obsolete pages, it's
5827 * impossible for there to be multiple invalid generations associated
5828 * with *valid* shadow pages at any given time, i.e. there is exactly
5829 * one valid generation and (at most) one invalid generation.
5831 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5834 * Notify all vcpus to reload its shadow page table and flush TLB.
5835 * Then all vcpus will switch to new shadow page table with the new
5838 * Note: we need to do this under the protection of mmu_lock,
5839 * otherwise, vcpu would purge shadow page but miss tlb flush.
5841 kvm_reload_remote_mmus(kvm);
5843 kvm_zap_obsolete_pages(kvm);
5844 spin_unlock(&kvm->mmu_lock);
5847 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5849 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5852 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5853 struct kvm_memory_slot *slot,
5854 struct kvm_page_track_notifier_node *node)
5856 kvm_mmu_zap_all_fast(kvm);
5859 void kvm_mmu_init_vm(struct kvm *kvm)
5861 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5863 node->track_write = kvm_mmu_pte_write;
5864 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5865 kvm_page_track_register_notifier(kvm, node);
5868 void kvm_mmu_uninit_vm(struct kvm *kvm)
5870 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5872 kvm_page_track_unregister_notifier(kvm, node);
5875 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5877 struct kvm_memslots *slots;
5878 struct kvm_memory_slot *memslot;
5881 spin_lock(&kvm->mmu_lock);
5882 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5883 slots = __kvm_memslots(kvm, i);
5884 kvm_for_each_memslot(memslot, slots) {
5887 start = max(gfn_start, memslot->base_gfn);
5888 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5892 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5894 KVM_MAX_HUGEPAGE_LEVEL,
5895 start, end - 1, true);
5899 spin_unlock(&kvm->mmu_lock);
5902 static bool slot_rmap_write_protect(struct kvm *kvm,
5903 struct kvm_rmap_head *rmap_head)
5905 return __rmap_write_protect(kvm, rmap_head, false);
5908 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5909 struct kvm_memory_slot *memslot,
5914 spin_lock(&kvm->mmu_lock);
5915 flush = slot_handle_level(kvm, memslot, slot_rmap_write_protect,
5916 start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
5917 spin_unlock(&kvm->mmu_lock);
5920 * We can flush all the TLBs out of the mmu lock without TLB
5921 * corruption since we just change the spte from writable to
5922 * readonly so that we only need to care the case of changing
5923 * spte from present to present (changing the spte from present
5924 * to nonpresent will flush all the TLBs immediately), in other
5925 * words, the only case we care is mmu_spte_update() where we
5926 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5927 * instead of PT_WRITABLE_MASK, that means it does not depend
5928 * on PT_WRITABLE_MASK anymore.
5931 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5934 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5935 struct kvm_rmap_head *rmap_head)
5938 struct rmap_iterator iter;
5939 int need_tlb_flush = 0;
5941 struct kvm_mmu_page *sp;
5944 for_each_rmap_spte(rmap_head, &iter, sptep) {
5945 sp = sptep_to_sp(sptep);
5946 pfn = spte_to_pfn(*sptep);
5949 * We cannot do huge page mapping for indirect shadow pages,
5950 * which are found on the last rmap (level = 1) when not using
5951 * tdp; such shadow pages are synced with the page table in
5952 * the guest, and the guest page table is using 4K page size
5953 * mapping if the indirect sp has level = 1.
5955 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5956 (kvm_is_zone_device_pfn(pfn) ||
5957 PageCompound(pfn_to_page(pfn)))) {
5958 pte_list_remove(rmap_head, sptep);
5960 if (kvm_available_flush_tlb_with_range())
5961 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5962 KVM_PAGES_PER_HPAGE(sp->role.level));
5970 return need_tlb_flush;
5973 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5974 const struct kvm_memory_slot *memslot)
5976 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5977 spin_lock(&kvm->mmu_lock);
5978 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5979 kvm_mmu_zap_collapsible_spte, true);
5980 spin_unlock(&kvm->mmu_lock);
5983 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
5984 struct kvm_memory_slot *memslot)
5987 * All current use cases for flushing the TLBs for a specific memslot
5988 * are related to dirty logging, and do the TLB flush out of mmu_lock.
5989 * The interaction between the various operations on memslot must be
5990 * serialized by slots_locks to ensure the TLB flush from one operation
5991 * is observed by any other operation on the same memslot.
5993 lockdep_assert_held(&kvm->slots_lock);
5994 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5998 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5999 struct kvm_memory_slot *memslot)
6003 spin_lock(&kvm->mmu_lock);
6004 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
6005 spin_unlock(&kvm->mmu_lock);
6008 * It's also safe to flush TLBs out of mmu lock here as currently this
6009 * function is only used for dirty logging, in which case flushing TLB
6010 * out of mmu lock also guarantees no dirty pages will be lost in
6014 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6016 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
6018 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
6019 struct kvm_memory_slot *memslot)
6023 spin_lock(&kvm->mmu_lock);
6024 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
6026 spin_unlock(&kvm->mmu_lock);
6029 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6031 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
6033 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
6034 struct kvm_memory_slot *memslot)
6038 spin_lock(&kvm->mmu_lock);
6039 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
6040 spin_unlock(&kvm->mmu_lock);
6043 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6045 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
6047 void kvm_mmu_zap_all(struct kvm *kvm)
6049 struct kvm_mmu_page *sp, *node;
6050 LIST_HEAD(invalid_list);
6053 spin_lock(&kvm->mmu_lock);
6055 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6056 if (WARN_ON(sp->role.invalid))
6058 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6060 if (cond_resched_lock(&kvm->mmu_lock))
6064 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6065 spin_unlock(&kvm->mmu_lock);
6068 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6070 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6072 gen &= MMIO_SPTE_GEN_MASK;
6075 * Generation numbers are incremented in multiples of the number of
6076 * address spaces in order to provide unique generations across all
6077 * address spaces. Strip what is effectively the address space
6078 * modifier prior to checking for a wrap of the MMIO generation so
6079 * that a wrap in any address space is detected.
6081 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6084 * The very rare case: if the MMIO generation number has wrapped,
6085 * zap all shadow pages.
6087 if (unlikely(gen == 0)) {
6088 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6089 kvm_mmu_zap_all_fast(kvm);
6093 static unsigned long
6094 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6097 int nr_to_scan = sc->nr_to_scan;
6098 unsigned long freed = 0;
6100 mutex_lock(&kvm_lock);
6102 list_for_each_entry(kvm, &vm_list, vm_list) {
6104 LIST_HEAD(invalid_list);
6107 * Never scan more than sc->nr_to_scan VM instances.
6108 * Will not hit this condition practically since we do not try
6109 * to shrink more than one VM and it is very unlikely to see
6110 * !n_used_mmu_pages so many times.
6115 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6116 * here. We may skip a VM instance errorneosly, but we do not
6117 * want to shrink a VM that only started to populate its MMU
6120 if (!kvm->arch.n_used_mmu_pages &&
6121 !kvm_has_zapped_obsolete_pages(kvm))
6124 idx = srcu_read_lock(&kvm->srcu);
6125 spin_lock(&kvm->mmu_lock);
6127 if (kvm_has_zapped_obsolete_pages(kvm)) {
6128 kvm_mmu_commit_zap_page(kvm,
6129 &kvm->arch.zapped_obsolete_pages);
6133 freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6136 spin_unlock(&kvm->mmu_lock);
6137 srcu_read_unlock(&kvm->srcu, idx);
6140 * unfair on small ones
6141 * per-vm shrinkers cry out
6142 * sadness comes quickly
6144 list_move_tail(&kvm->vm_list, &vm_list);
6148 mutex_unlock(&kvm_lock);
6152 static unsigned long
6153 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6155 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6158 static struct shrinker mmu_shrinker = {
6159 .count_objects = mmu_shrink_count,
6160 .scan_objects = mmu_shrink_scan,
6161 .seeks = DEFAULT_SEEKS * 10,
6164 static void mmu_destroy_caches(void)
6166 kmem_cache_destroy(pte_list_desc_cache);
6167 kmem_cache_destroy(mmu_page_header_cache);
6170 static void kvm_set_mmio_spte_mask(void)
6175 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
6176 * PFEC.RSVD=1 on MMIO accesses. 64-bit PTEs (PAE, x86-64, and EPT
6177 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
6178 * 52-bit physical addresses then there are no reserved PA bits in the
6179 * PTEs and so the reserved PA approach must be disabled.
6181 if (shadow_phys_bits < 52)
6182 mask = BIT_ULL(51) | PT_PRESENT_MASK;
6186 kvm_mmu_set_mmio_spte_mask(mask, ACC_WRITE_MASK | ACC_USER_MASK);
6189 static bool get_nx_auto_mode(void)
6191 /* Return true when CPU has the bug, and mitigations are ON */
6192 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6195 static void __set_nx_huge_pages(bool val)
6197 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6200 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6202 bool old_val = nx_huge_pages;
6205 /* In "auto" mode deploy workaround only if CPU has the bug. */
6206 if (sysfs_streq(val, "off"))
6208 else if (sysfs_streq(val, "force"))
6210 else if (sysfs_streq(val, "auto"))
6211 new_val = get_nx_auto_mode();
6212 else if (strtobool(val, &new_val) < 0)
6215 __set_nx_huge_pages(new_val);
6217 if (new_val != old_val) {
6220 mutex_lock(&kvm_lock);
6222 list_for_each_entry(kvm, &vm_list, vm_list) {
6223 mutex_lock(&kvm->slots_lock);
6224 kvm_mmu_zap_all_fast(kvm);
6225 mutex_unlock(&kvm->slots_lock);
6227 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6229 mutex_unlock(&kvm_lock);
6235 int kvm_mmu_module_init(void)
6239 if (nx_huge_pages == -1)
6240 __set_nx_huge_pages(get_nx_auto_mode());
6243 * MMU roles use union aliasing which is, generally speaking, an
6244 * undefined behavior. However, we supposedly know how compilers behave
6245 * and the current status quo is unlikely to change. Guardians below are
6246 * supposed to let us know if the assumption becomes false.
6248 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6249 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6250 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6252 kvm_mmu_reset_all_pte_masks();
6254 kvm_set_mmio_spte_mask();
6256 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6257 sizeof(struct pte_list_desc),
6258 0, SLAB_ACCOUNT, NULL);
6259 if (!pte_list_desc_cache)
6262 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6263 sizeof(struct kvm_mmu_page),
6264 0, SLAB_ACCOUNT, NULL);
6265 if (!mmu_page_header_cache)
6268 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6271 ret = register_shrinker(&mmu_shrinker);
6278 mmu_destroy_caches();
6283 * Calculate mmu pages needed for kvm.
6285 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6287 unsigned long nr_mmu_pages;
6288 unsigned long nr_pages = 0;
6289 struct kvm_memslots *slots;
6290 struct kvm_memory_slot *memslot;
6293 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6294 slots = __kvm_memslots(kvm, i);
6296 kvm_for_each_memslot(memslot, slots)
6297 nr_pages += memslot->npages;
6300 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6301 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6303 return nr_mmu_pages;
6306 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6308 kvm_mmu_unload(vcpu);
6309 free_mmu_pages(&vcpu->arch.root_mmu);
6310 free_mmu_pages(&vcpu->arch.guest_mmu);
6311 mmu_free_memory_caches(vcpu);
6314 void kvm_mmu_module_exit(void)
6316 mmu_destroy_caches();
6317 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6318 unregister_shrinker(&mmu_shrinker);
6319 mmu_audit_disable();
6322 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6324 unsigned int old_val;
6327 old_val = nx_huge_pages_recovery_ratio;
6328 err = param_set_uint(val, kp);
6332 if (READ_ONCE(nx_huge_pages) &&
6333 !old_val && nx_huge_pages_recovery_ratio) {
6336 mutex_lock(&kvm_lock);
6338 list_for_each_entry(kvm, &vm_list, vm_list)
6339 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6341 mutex_unlock(&kvm_lock);
6347 static void kvm_recover_nx_lpages(struct kvm *kvm)
6350 struct kvm_mmu_page *sp;
6352 LIST_HEAD(invalid_list);
6355 rcu_idx = srcu_read_lock(&kvm->srcu);
6356 spin_lock(&kvm->mmu_lock);
6358 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6359 to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
6360 while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
6362 * We use a separate list instead of just using active_mmu_pages
6363 * because the number of lpage_disallowed pages is expected to
6364 * be relatively small compared to the total.
6366 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6367 struct kvm_mmu_page,
6368 lpage_disallowed_link);
6369 WARN_ON_ONCE(!sp->lpage_disallowed);
6370 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6371 WARN_ON_ONCE(sp->lpage_disallowed);
6373 if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
6374 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6376 cond_resched_lock(&kvm->mmu_lock);
6380 spin_unlock(&kvm->mmu_lock);
6381 srcu_read_unlock(&kvm->srcu, rcu_idx);
6384 static long get_nx_lpage_recovery_timeout(u64 start_time)
6386 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6387 ? start_time + 60 * HZ - get_jiffies_64()
6388 : MAX_SCHEDULE_TIMEOUT;
6391 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6394 long remaining_time;
6397 start_time = get_jiffies_64();
6398 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6400 set_current_state(TASK_INTERRUPTIBLE);
6401 while (!kthread_should_stop() && remaining_time > 0) {
6402 schedule_timeout(remaining_time);
6403 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6404 set_current_state(TASK_INTERRUPTIBLE);
6407 set_current_state(TASK_RUNNING);
6409 if (kthread_should_stop())
6412 kvm_recover_nx_lpages(kvm);
6416 int kvm_mmu_post_init_vm(struct kvm *kvm)
6420 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6421 "kvm-nx-lpage-recovery",
6422 &kvm->arch.nx_lpage_recovery_thread);
6424 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6429 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6431 if (kvm->arch.nx_lpage_recovery_thread)
6432 kthread_stop(kvm->arch.nx_lpage_recovery_thread);