1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
10 * Copyright (C) 2006 Qumranet, Inc.
11 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Avi Kivity <avi@qumranet.com>
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)
1921 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1924 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1926 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1929 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1930 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1934 struct rmap_iterator iter;
1937 for_each_rmap_spte(rmap_head, &iter, sptep)
1938 young |= mmu_spte_age(sptep);
1940 trace_kvm_age_page(gfn, level, slot, young);
1944 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1945 struct kvm_memory_slot *slot, gfn_t gfn,
1946 int level, unsigned long data)
1949 struct rmap_iterator iter;
1951 for_each_rmap_spte(rmap_head, &iter, sptep)
1952 if (is_accessed_spte(*sptep))
1957 #define RMAP_RECYCLE_THRESHOLD 1000
1959 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1961 struct kvm_rmap_head *rmap_head;
1962 struct kvm_mmu_page *sp;
1964 sp = sptep_to_sp(spte);
1966 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1968 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1969 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1970 KVM_PAGES_PER_HPAGE(sp->role.level));
1973 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1975 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
1978 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1980 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1984 static int is_empty_shadow_page(u64 *spt)
1989 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1990 if (is_shadow_present_pte(*pos)) {
1991 printk(KERN_ERR "%s: %p %llx\n", __func__,
2000 * This value is the sum of all of the kvm instances's
2001 * kvm->arch.n_used_mmu_pages values. We need a global,
2002 * aggregate version in order to make the slab shrinker
2005 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2007 kvm->arch.n_used_mmu_pages += nr;
2008 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2011 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2013 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2014 hlist_del(&sp->hash_link);
2015 list_del(&sp->link);
2016 free_page((unsigned long)sp->spt);
2017 if (!sp->role.direct)
2018 free_page((unsigned long)sp->gfns);
2019 kmem_cache_free(mmu_page_header_cache, sp);
2022 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2024 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2027 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2028 struct kvm_mmu_page *sp, u64 *parent_pte)
2033 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2036 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2039 __pte_list_remove(parent_pte, &sp->parent_ptes);
2042 static void drop_parent_pte(struct kvm_mmu_page *sp,
2045 mmu_page_remove_parent_pte(sp, parent_pte);
2046 mmu_spte_clear_no_track(parent_pte);
2049 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2051 struct kvm_mmu_page *sp;
2053 sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2054 sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
2056 sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
2057 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2060 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2061 * depends on valid pages being added to the head of the list. See
2062 * comments in kvm_zap_obsolete_pages().
2064 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2065 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2066 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2070 static void mark_unsync(u64 *spte);
2071 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2074 struct rmap_iterator iter;
2076 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2081 static void mark_unsync(u64 *spte)
2083 struct kvm_mmu_page *sp;
2086 sp = sptep_to_sp(spte);
2087 index = spte - sp->spt;
2088 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2090 if (sp->unsync_children++)
2092 kvm_mmu_mark_parents_unsync(sp);
2095 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2096 struct kvm_mmu_page *sp)
2101 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2102 struct kvm_mmu_page *sp, u64 *spte,
2108 #define KVM_PAGE_ARRAY_NR 16
2110 struct kvm_mmu_pages {
2111 struct mmu_page_and_offset {
2112 struct kvm_mmu_page *sp;
2114 } page[KVM_PAGE_ARRAY_NR];
2118 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2124 for (i=0; i < pvec->nr; i++)
2125 if (pvec->page[i].sp == sp)
2128 pvec->page[pvec->nr].sp = sp;
2129 pvec->page[pvec->nr].idx = idx;
2131 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2134 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2136 --sp->unsync_children;
2137 WARN_ON((int)sp->unsync_children < 0);
2138 __clear_bit(idx, sp->unsync_child_bitmap);
2141 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2142 struct kvm_mmu_pages *pvec)
2144 int i, ret, nr_unsync_leaf = 0;
2146 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2147 struct kvm_mmu_page *child;
2148 u64 ent = sp->spt[i];
2150 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2151 clear_unsync_child_bit(sp, i);
2155 child = to_shadow_page(ent & PT64_BASE_ADDR_MASK);
2157 if (child->unsync_children) {
2158 if (mmu_pages_add(pvec, child, i))
2161 ret = __mmu_unsync_walk(child, pvec);
2163 clear_unsync_child_bit(sp, i);
2165 } else if (ret > 0) {
2166 nr_unsync_leaf += ret;
2169 } else if (child->unsync) {
2171 if (mmu_pages_add(pvec, child, i))
2174 clear_unsync_child_bit(sp, i);
2177 return nr_unsync_leaf;
2180 #define INVALID_INDEX (-1)
2182 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2183 struct kvm_mmu_pages *pvec)
2186 if (!sp->unsync_children)
2189 mmu_pages_add(pvec, sp, INVALID_INDEX);
2190 return __mmu_unsync_walk(sp, pvec);
2193 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2195 WARN_ON(!sp->unsync);
2196 trace_kvm_mmu_sync_page(sp);
2198 --kvm->stat.mmu_unsync;
2201 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2202 struct list_head *invalid_list);
2203 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2204 struct list_head *invalid_list);
2206 #define for_each_valid_sp(_kvm, _sp, _list) \
2207 hlist_for_each_entry(_sp, _list, hash_link) \
2208 if (is_obsolete_sp((_kvm), (_sp))) { \
2211 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2212 for_each_valid_sp(_kvm, _sp, \
2213 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
2214 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2216 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2218 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2221 /* @sp->gfn should be write-protected at the call site */
2222 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2223 struct list_head *invalid_list)
2225 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2226 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2227 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2234 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2235 struct list_head *invalid_list,
2238 if (!remote_flush && list_empty(invalid_list))
2241 if (!list_empty(invalid_list))
2242 kvm_mmu_commit_zap_page(kvm, invalid_list);
2244 kvm_flush_remote_tlbs(kvm);
2248 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2249 struct list_head *invalid_list,
2250 bool remote_flush, bool local_flush)
2252 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2256 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2259 #ifdef CONFIG_KVM_MMU_AUDIT
2260 #include "mmu_audit.c"
2262 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2263 static void mmu_audit_disable(void) { }
2266 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2268 return sp->role.invalid ||
2269 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2272 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2273 struct list_head *invalid_list)
2275 kvm_unlink_unsync_page(vcpu->kvm, sp);
2276 return __kvm_sync_page(vcpu, sp, invalid_list);
2279 /* @gfn should be write-protected at the call site */
2280 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2281 struct list_head *invalid_list)
2283 struct kvm_mmu_page *s;
2286 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2290 WARN_ON(s->role.level != PG_LEVEL_4K);
2291 ret |= kvm_sync_page(vcpu, s, invalid_list);
2297 struct mmu_page_path {
2298 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2299 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2302 #define for_each_sp(pvec, sp, parents, i) \
2303 for (i = mmu_pages_first(&pvec, &parents); \
2304 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2305 i = mmu_pages_next(&pvec, &parents, i))
2307 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2308 struct mmu_page_path *parents,
2313 for (n = i+1; n < pvec->nr; n++) {
2314 struct kvm_mmu_page *sp = pvec->page[n].sp;
2315 unsigned idx = pvec->page[n].idx;
2316 int level = sp->role.level;
2318 parents->idx[level-1] = idx;
2319 if (level == PG_LEVEL_4K)
2322 parents->parent[level-2] = sp;
2328 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2329 struct mmu_page_path *parents)
2331 struct kvm_mmu_page *sp;
2337 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2339 sp = pvec->page[0].sp;
2340 level = sp->role.level;
2341 WARN_ON(level == PG_LEVEL_4K);
2343 parents->parent[level-2] = sp;
2345 /* Also set up a sentinel. Further entries in pvec are all
2346 * children of sp, so this element is never overwritten.
2348 parents->parent[level-1] = NULL;
2349 return mmu_pages_next(pvec, parents, 0);
2352 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2354 struct kvm_mmu_page *sp;
2355 unsigned int level = 0;
2358 unsigned int idx = parents->idx[level];
2359 sp = parents->parent[level];
2363 WARN_ON(idx == INVALID_INDEX);
2364 clear_unsync_child_bit(sp, idx);
2366 } while (!sp->unsync_children);
2369 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2370 struct kvm_mmu_page *parent)
2373 struct kvm_mmu_page *sp;
2374 struct mmu_page_path parents;
2375 struct kvm_mmu_pages pages;
2376 LIST_HEAD(invalid_list);
2379 while (mmu_unsync_walk(parent, &pages)) {
2380 bool protected = false;
2382 for_each_sp(pages, sp, parents, i)
2383 protected |= rmap_write_protect(vcpu, sp->gfn);
2386 kvm_flush_remote_tlbs(vcpu->kvm);
2390 for_each_sp(pages, sp, parents, i) {
2391 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2392 mmu_pages_clear_parents(&parents);
2394 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2395 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2396 cond_resched_lock(&vcpu->kvm->mmu_lock);
2401 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2404 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2406 atomic_set(&sp->write_flooding_count, 0);
2409 static void clear_sp_write_flooding_count(u64 *spte)
2411 __clear_sp_write_flooding_count(sptep_to_sp(spte));
2414 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2419 unsigned int access)
2421 bool direct_mmu = vcpu->arch.mmu->direct_map;
2422 union kvm_mmu_page_role role;
2423 struct hlist_head *sp_list;
2425 struct kvm_mmu_page *sp;
2426 bool need_sync = false;
2429 LIST_HEAD(invalid_list);
2431 role = vcpu->arch.mmu->mmu_role.base;
2433 role.direct = direct;
2435 role.gpte_is_8_bytes = true;
2436 role.access = access;
2437 if (!direct_mmu && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2438 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2439 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2440 role.quadrant = quadrant;
2443 sp_list = &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2444 for_each_valid_sp(vcpu->kvm, sp, sp_list) {
2445 if (sp->gfn != gfn) {
2450 if (!need_sync && sp->unsync)
2453 if (sp->role.word != role.word)
2457 goto trace_get_page;
2460 /* The page is good, but __kvm_sync_page might still end
2461 * up zapping it. If so, break in order to rebuild it.
2463 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2466 WARN_ON(!list_empty(&invalid_list));
2467 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2470 if (sp->unsync_children)
2471 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2473 __clear_sp_write_flooding_count(sp);
2476 trace_kvm_mmu_get_page(sp, false);
2480 ++vcpu->kvm->stat.mmu_cache_miss;
2482 sp = kvm_mmu_alloc_page(vcpu, direct);
2486 hlist_add_head(&sp->hash_link, sp_list);
2489 * we should do write protection before syncing pages
2490 * otherwise the content of the synced shadow page may
2491 * be inconsistent with guest page table.
2493 account_shadowed(vcpu->kvm, sp);
2494 if (level == PG_LEVEL_4K && rmap_write_protect(vcpu, gfn))
2495 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2497 if (level > PG_LEVEL_4K && need_sync)
2498 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2500 trace_kvm_mmu_get_page(sp, true);
2502 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2504 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2505 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2509 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2510 struct kvm_vcpu *vcpu, hpa_t root,
2513 iterator->addr = addr;
2514 iterator->shadow_addr = root;
2515 iterator->level = vcpu->arch.mmu->shadow_root_level;
2517 if (iterator->level == PT64_ROOT_4LEVEL &&
2518 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2519 !vcpu->arch.mmu->direct_map)
2522 if (iterator->level == PT32E_ROOT_LEVEL) {
2524 * prev_root is currently only used for 64-bit hosts. So only
2525 * the active root_hpa is valid here.
2527 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2529 iterator->shadow_addr
2530 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2531 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2533 if (!iterator->shadow_addr)
2534 iterator->level = 0;
2538 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2539 struct kvm_vcpu *vcpu, u64 addr)
2541 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2545 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2547 if (iterator->level < PG_LEVEL_4K)
2550 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2551 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2555 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2558 if (is_last_spte(spte, iterator->level)) {
2559 iterator->level = 0;
2563 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2567 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2569 __shadow_walk_next(iterator, *iterator->sptep);
2572 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2573 struct kvm_mmu_page *sp)
2577 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2579 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2580 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2582 if (sp_ad_disabled(sp))
2583 spte |= SPTE_AD_DISABLED_MASK;
2585 spte |= shadow_accessed_mask;
2587 mmu_spte_set(sptep, spte);
2589 mmu_page_add_parent_pte(vcpu, sp, sptep);
2591 if (sp->unsync_children || sp->unsync)
2595 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2596 unsigned direct_access)
2598 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2599 struct kvm_mmu_page *child;
2602 * For the direct sp, if the guest pte's dirty bit
2603 * changed form clean to dirty, it will corrupt the
2604 * sp's access: allow writable in the read-only sp,
2605 * so we should update the spte at this point to get
2606 * a new sp with the correct access.
2608 child = to_shadow_page(*sptep & PT64_BASE_ADDR_MASK);
2609 if (child->role.access == direct_access)
2612 drop_parent_pte(child, sptep);
2613 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2617 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2621 struct kvm_mmu_page *child;
2624 if (is_shadow_present_pte(pte)) {
2625 if (is_last_spte(pte, sp->role.level)) {
2626 drop_spte(kvm, spte);
2627 if (is_large_pte(pte))
2630 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
2631 drop_parent_pte(child, spte);
2636 if (is_mmio_spte(pte))
2637 mmu_spte_clear_no_track(spte);
2642 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2643 struct kvm_mmu_page *sp)
2647 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2648 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2651 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2654 struct rmap_iterator iter;
2656 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2657 drop_parent_pte(sp, sptep);
2660 static int mmu_zap_unsync_children(struct kvm *kvm,
2661 struct kvm_mmu_page *parent,
2662 struct list_head *invalid_list)
2665 struct mmu_page_path parents;
2666 struct kvm_mmu_pages pages;
2668 if (parent->role.level == PG_LEVEL_4K)
2671 while (mmu_unsync_walk(parent, &pages)) {
2672 struct kvm_mmu_page *sp;
2674 for_each_sp(pages, sp, parents, i) {
2675 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2676 mmu_pages_clear_parents(&parents);
2684 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2685 struct kvm_mmu_page *sp,
2686 struct list_head *invalid_list,
2691 trace_kvm_mmu_prepare_zap_page(sp);
2692 ++kvm->stat.mmu_shadow_zapped;
2693 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2694 kvm_mmu_page_unlink_children(kvm, sp);
2695 kvm_mmu_unlink_parents(kvm, sp);
2697 /* Zapping children means active_mmu_pages has become unstable. */
2698 list_unstable = *nr_zapped;
2700 if (!sp->role.invalid && !sp->role.direct)
2701 unaccount_shadowed(kvm, sp);
2704 kvm_unlink_unsync_page(kvm, sp);
2705 if (!sp->root_count) {
2710 * Already invalid pages (previously active roots) are not on
2711 * the active page list. See list_del() in the "else" case of
2714 if (sp->role.invalid)
2715 list_add(&sp->link, invalid_list);
2717 list_move(&sp->link, invalid_list);
2718 kvm_mod_used_mmu_pages(kvm, -1);
2721 * Remove the active root from the active page list, the root
2722 * will be explicitly freed when the root_count hits zero.
2724 list_del(&sp->link);
2727 * Obsolete pages cannot be used on any vCPUs, see the comment
2728 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2729 * treats invalid shadow pages as being obsolete.
2731 if (!is_obsolete_sp(kvm, sp))
2732 kvm_reload_remote_mmus(kvm);
2735 if (sp->lpage_disallowed)
2736 unaccount_huge_nx_page(kvm, sp);
2738 sp->role.invalid = 1;
2739 return list_unstable;
2742 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2743 struct list_head *invalid_list)
2747 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2751 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2752 struct list_head *invalid_list)
2754 struct kvm_mmu_page *sp, *nsp;
2756 if (list_empty(invalid_list))
2760 * We need to make sure everyone sees our modifications to
2761 * the page tables and see changes to vcpu->mode here. The barrier
2762 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2763 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2765 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2766 * guest mode and/or lockless shadow page table walks.
2768 kvm_flush_remote_tlbs(kvm);
2770 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2771 WARN_ON(!sp->role.invalid || sp->root_count);
2772 kvm_mmu_free_page(sp);
2776 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2777 unsigned long nr_to_zap)
2779 unsigned long total_zapped = 0;
2780 struct kvm_mmu_page *sp, *tmp;
2781 LIST_HEAD(invalid_list);
2785 if (list_empty(&kvm->arch.active_mmu_pages))
2789 list_for_each_entry_safe(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2791 * Don't zap active root pages, the page itself can't be freed
2792 * and zapping it will just force vCPUs to realloc and reload.
2797 unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2799 total_zapped += nr_zapped;
2800 if (total_zapped >= nr_to_zap)
2807 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2809 kvm->stat.mmu_recycled += total_zapped;
2810 return total_zapped;
2813 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2815 if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2816 return kvm->arch.n_max_mmu_pages -
2817 kvm->arch.n_used_mmu_pages;
2822 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2824 unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2826 if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2829 kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2831 if (!kvm_mmu_available_pages(vcpu->kvm))
2837 * Changing the number of mmu pages allocated to the vm
2838 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2840 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2842 spin_lock(&kvm->mmu_lock);
2844 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2845 kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2848 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2851 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2853 spin_unlock(&kvm->mmu_lock);
2856 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2858 struct kvm_mmu_page *sp;
2859 LIST_HEAD(invalid_list);
2862 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2864 spin_lock(&kvm->mmu_lock);
2865 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2866 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2869 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2871 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2872 spin_unlock(&kvm->mmu_lock);
2876 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2878 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2880 trace_kvm_mmu_unsync_page(sp);
2881 ++vcpu->kvm->stat.mmu_unsync;
2884 kvm_mmu_mark_parents_unsync(sp);
2887 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2890 struct kvm_mmu_page *sp;
2892 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2895 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2902 WARN_ON(sp->role.level != PG_LEVEL_4K);
2903 kvm_unsync_page(vcpu, sp);
2907 * We need to ensure that the marking of unsync pages is visible
2908 * before the SPTE is updated to allow writes because
2909 * kvm_mmu_sync_roots() checks the unsync flags without holding
2910 * the MMU lock and so can race with this. If the SPTE was updated
2911 * before the page had been marked as unsync-ed, something like the
2912 * following could happen:
2915 * ---------------------------------------------------------------------
2916 * 1.2 Host updates SPTE
2918 * 2.1 Guest writes a GPTE for GVA X.
2919 * (GPTE being in the guest page table shadowed
2920 * by the SP from CPU 1.)
2921 * This reads SPTE during the page table walk.
2922 * Since SPTE.W is read as 1, there is no
2925 * 2.2 Guest issues TLB flush.
2926 * That causes a VM Exit.
2928 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2929 * Since it is false, so it just returns.
2931 * 2.4 Guest accesses GVA X.
2932 * Since the mapping in the SP was not updated,
2933 * so the old mapping for GVA X incorrectly
2937 * (sp->unsync = true)
2939 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2940 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2941 * pairs with this write barrier.
2948 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2951 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2953 * Some reserved pages, such as those from NVDIMM
2954 * DAX devices, are not for MMIO, and can be mapped
2955 * with cached memory type for better performance.
2956 * However, the above check misconceives those pages
2957 * as MMIO, and results in KVM mapping them with UC
2958 * memory type, which would hurt the performance.
2959 * Therefore, we check the host memory type in addition
2960 * and only treat UC/UC-/WC pages as MMIO.
2962 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2964 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2965 pfn_to_hpa(pfn + 1) - 1,
2969 /* Bits which may be returned by set_spte() */
2970 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2971 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2973 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2974 unsigned int pte_access, int level,
2975 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2976 bool can_unsync, bool host_writable)
2980 struct kvm_mmu_page *sp;
2982 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2985 sp = sptep_to_sp(sptep);
2986 if (sp_ad_disabled(sp))
2987 spte |= SPTE_AD_DISABLED_MASK;
2988 else if (kvm_vcpu_ad_need_write_protect(vcpu))
2989 spte |= SPTE_AD_WRPROT_ONLY_MASK;
2992 * For the EPT case, shadow_present_mask is 0 if hardware
2993 * supports exec-only page table entries. In that case,
2994 * ACC_USER_MASK and shadow_user_mask are used to represent
2995 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2997 spte |= shadow_present_mask;
2999 spte |= spte_shadow_accessed_mask(spte);
3001 if (level > PG_LEVEL_4K && (pte_access & ACC_EXEC_MASK) &&
3002 is_nx_huge_page_enabled()) {
3003 pte_access &= ~ACC_EXEC_MASK;
3006 if (pte_access & ACC_EXEC_MASK)
3007 spte |= shadow_x_mask;
3009 spte |= shadow_nx_mask;
3011 if (pte_access & ACC_USER_MASK)
3012 spte |= shadow_user_mask;
3014 if (level > PG_LEVEL_4K)
3015 spte |= PT_PAGE_SIZE_MASK;
3017 spte |= kvm_x86_ops.get_mt_mask(vcpu, gfn,
3018 kvm_is_mmio_pfn(pfn));
3021 spte |= SPTE_HOST_WRITEABLE;
3023 pte_access &= ~ACC_WRITE_MASK;
3025 if (!kvm_is_mmio_pfn(pfn))
3026 spte |= shadow_me_mask;
3028 spte |= (u64)pfn << PAGE_SHIFT;
3030 if (pte_access & ACC_WRITE_MASK) {
3031 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3034 * Optimization: for pte sync, if spte was writable the hash
3035 * lookup is unnecessary (and expensive). Write protection
3036 * is responsibility of mmu_get_page / kvm_sync_page.
3037 * Same reasoning can be applied to dirty page accounting.
3039 if (!can_unsync && is_writable_pte(*sptep))
3042 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3043 pgprintk("%s: found shadow page for %llx, marking ro\n",
3045 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3046 pte_access &= ~ACC_WRITE_MASK;
3047 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3051 if (pte_access & ACC_WRITE_MASK) {
3052 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3053 spte |= spte_shadow_dirty_mask(spte);
3057 spte = mark_spte_for_access_track(spte);
3060 if (mmu_spte_update(sptep, spte))
3061 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3065 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
3066 unsigned int pte_access, int write_fault, int level,
3067 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
3070 int was_rmapped = 0;
3073 int ret = RET_PF_RETRY;
3076 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3077 *sptep, write_fault, gfn);
3079 if (is_shadow_present_pte(*sptep)) {
3081 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3082 * the parent of the now unreachable PTE.
3084 if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
3085 struct kvm_mmu_page *child;
3088 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
3089 drop_parent_pte(child, sptep);
3091 } else if (pfn != spte_to_pfn(*sptep)) {
3092 pgprintk("hfn old %llx new %llx\n",
3093 spte_to_pfn(*sptep), pfn);
3094 drop_spte(vcpu->kvm, sptep);
3100 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3101 speculative, true, host_writable);
3102 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3104 ret = RET_PF_EMULATE;
3105 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3108 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3109 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3110 KVM_PAGES_PER_HPAGE(level));
3112 if (unlikely(is_mmio_spte(*sptep)))
3113 ret = RET_PF_EMULATE;
3115 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3116 trace_kvm_mmu_set_spte(level, gfn, sptep);
3117 if (!was_rmapped && is_large_pte(*sptep))
3118 ++vcpu->kvm->stat.lpages;
3120 if (is_shadow_present_pte(*sptep)) {
3122 rmap_count = rmap_add(vcpu, sptep, gfn);
3123 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3124 rmap_recycle(vcpu, sptep, gfn);
3131 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3134 struct kvm_memory_slot *slot;
3136 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3138 return KVM_PFN_ERR_FAULT;
3140 return gfn_to_pfn_memslot_atomic(slot, gfn);
3143 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3144 struct kvm_mmu_page *sp,
3145 u64 *start, u64 *end)
3147 struct page *pages[PTE_PREFETCH_NUM];
3148 struct kvm_memory_slot *slot;
3149 unsigned int access = sp->role.access;
3153 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3154 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3158 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3162 for (i = 0; i < ret; i++, gfn++, start++) {
3163 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3164 page_to_pfn(pages[i]), true, true);
3171 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3172 struct kvm_mmu_page *sp, u64 *sptep)
3174 u64 *spte, *start = NULL;
3177 WARN_ON(!sp->role.direct);
3179 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3182 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3183 if (is_shadow_present_pte(*spte) || spte == sptep) {
3186 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3194 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3196 struct kvm_mmu_page *sp;
3198 sp = sptep_to_sp(sptep);
3201 * Without accessed bits, there's no way to distinguish between
3202 * actually accessed translations and prefetched, so disable pte
3203 * prefetch if accessed bits aren't available.
3205 if (sp_ad_disabled(sp))
3208 if (sp->role.level > PG_LEVEL_4K)
3211 __direct_pte_prefetch(vcpu, sp, sptep);
3214 static int host_pfn_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn,
3215 kvm_pfn_t pfn, struct kvm_memory_slot *slot)
3221 if (!PageCompound(pfn_to_page(pfn)) && !kvm_is_zone_device_pfn(pfn))
3225 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3226 * is not solely for performance, it's also necessary to avoid the
3227 * "writable" check in __gfn_to_hva_many(), which will always fail on
3228 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
3229 * page fault steps have already verified the guest isn't writing a
3230 * read-only memslot.
3232 hva = __gfn_to_hva_memslot(slot, gfn);
3234 pte = lookup_address_in_mm(vcpu->kvm->mm, hva, &level);
3241 static int kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t gfn,
3242 int max_level, kvm_pfn_t *pfnp)
3244 struct kvm_memory_slot *slot;
3245 struct kvm_lpage_info *linfo;
3246 kvm_pfn_t pfn = *pfnp;
3250 if (unlikely(max_level == PG_LEVEL_4K))
3253 if (is_error_noslot_pfn(pfn) || kvm_is_reserved_pfn(pfn))
3256 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, true);
3260 max_level = min(max_level, max_huge_page_level);
3261 for ( ; max_level > PG_LEVEL_4K; max_level--) {
3262 linfo = lpage_info_slot(gfn, slot, max_level);
3263 if (!linfo->disallow_lpage)
3267 if (max_level == PG_LEVEL_4K)
3270 level = host_pfn_mapping_level(vcpu, gfn, pfn, slot);
3271 if (level == PG_LEVEL_4K)
3274 level = min(level, max_level);
3277 * mmu_notifier_retry() was successful and mmu_lock is held, so
3278 * the pmd can't be split from under us.
3280 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3281 VM_BUG_ON((gfn & mask) != (pfn & mask));
3282 *pfnp = pfn & ~mask;
3287 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3288 gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3290 int level = *levelp;
3291 u64 spte = *it.sptep;
3293 if (it.level == level && level > PG_LEVEL_4K &&
3294 is_nx_huge_page_enabled() &&
3295 is_shadow_present_pte(spte) &&
3296 !is_large_pte(spte)) {
3298 * A small SPTE exists for this pfn, but FNAME(fetch)
3299 * and __direct_map would like to create a large PTE
3300 * instead: just force them to go down another level,
3301 * patching back for them into pfn the next 9 bits of
3304 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3305 *pfnp |= gfn & page_mask;
3310 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3311 int map_writable, int max_level, kvm_pfn_t pfn,
3312 bool prefault, bool account_disallowed_nx_lpage)
3314 struct kvm_shadow_walk_iterator it;
3315 struct kvm_mmu_page *sp;
3317 gfn_t gfn = gpa >> PAGE_SHIFT;
3318 gfn_t base_gfn = gfn;
3320 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
3321 return RET_PF_RETRY;
3323 level = kvm_mmu_hugepage_adjust(vcpu, gfn, max_level, &pfn);
3325 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3326 for_each_shadow_entry(vcpu, gpa, it) {
3328 * We cannot overwrite existing page tables with an NX
3329 * large page, as the leaf could be executable.
3331 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3333 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3334 if (it.level == level)
3337 drop_large_spte(vcpu, it.sptep);
3338 if (!is_shadow_present_pte(*it.sptep)) {
3339 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3340 it.level - 1, true, ACC_ALL);
3342 link_shadow_page(vcpu, it.sptep, sp);
3343 if (account_disallowed_nx_lpage)
3344 account_huge_nx_page(vcpu->kvm, sp);
3348 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3349 write, level, base_gfn, pfn, prefault,
3351 direct_pte_prefetch(vcpu, it.sptep);
3352 ++vcpu->stat.pf_fixed;
3356 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3358 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3361 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3364 * Do not cache the mmio info caused by writing the readonly gfn
3365 * into the spte otherwise read access on readonly gfn also can
3366 * caused mmio page fault and treat it as mmio access.
3368 if (pfn == KVM_PFN_ERR_RO_FAULT)
3369 return RET_PF_EMULATE;
3371 if (pfn == KVM_PFN_ERR_HWPOISON) {
3372 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3373 return RET_PF_RETRY;
3379 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3380 kvm_pfn_t pfn, unsigned int access,
3383 /* The pfn is invalid, report the error! */
3384 if (unlikely(is_error_pfn(pfn))) {
3385 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3389 if (unlikely(is_noslot_pfn(pfn)))
3390 vcpu_cache_mmio_info(vcpu, gva, gfn,
3391 access & shadow_mmio_access_mask);
3396 static bool page_fault_can_be_fast(u32 error_code)
3399 * Do not fix the mmio spte with invalid generation number which
3400 * need to be updated by slow page fault path.
3402 if (unlikely(error_code & PFERR_RSVD_MASK))
3405 /* See if the page fault is due to an NX violation */
3406 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3407 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3411 * #PF can be fast if:
3412 * 1. The shadow page table entry is not present, which could mean that
3413 * the fault is potentially caused by access tracking (if enabled).
3414 * 2. The shadow page table entry is present and the fault
3415 * is caused by write-protect, that means we just need change the W
3416 * bit of the spte which can be done out of mmu-lock.
3418 * However, if access tracking is disabled we know that a non-present
3419 * page must be a genuine page fault where we have to create a new SPTE.
3420 * So, if access tracking is disabled, we return true only for write
3421 * accesses to a present page.
3424 return shadow_acc_track_mask != 0 ||
3425 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3426 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3430 * Returns true if the SPTE was fixed successfully. Otherwise,
3431 * someone else modified the SPTE from its original value.
3434 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3435 u64 *sptep, u64 old_spte, u64 new_spte)
3439 WARN_ON(!sp->role.direct);
3442 * Theoretically we could also set dirty bit (and flush TLB) here in
3443 * order to eliminate unnecessary PML logging. See comments in
3444 * set_spte. But fast_page_fault is very unlikely to happen with PML
3445 * enabled, so we do not do this. This might result in the same GPA
3446 * to be logged in PML buffer again when the write really happens, and
3447 * eventually to be called by mark_page_dirty twice. But it's also no
3448 * harm. This also avoids the TLB flush needed after setting dirty bit
3449 * so non-PML cases won't be impacted.
3451 * Compare with set_spte where instead shadow_dirty_mask is set.
3453 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3456 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3458 * The gfn of direct spte is stable since it is
3459 * calculated by sp->gfn.
3461 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3462 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3468 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3470 if (fault_err_code & PFERR_FETCH_MASK)
3471 return is_executable_pte(spte);
3473 if (fault_err_code & PFERR_WRITE_MASK)
3474 return is_writable_pte(spte);
3476 /* Fault was on Read access */
3477 return spte & PT_PRESENT_MASK;
3482 * - true: let the vcpu to access on the same address again.
3483 * - false: let the real page fault path to fix it.
3485 static bool fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
3488 struct kvm_shadow_walk_iterator iterator;
3489 struct kvm_mmu_page *sp;
3490 bool fault_handled = false;
3492 uint retry_count = 0;
3494 if (!page_fault_can_be_fast(error_code))
3497 walk_shadow_page_lockless_begin(vcpu);
3502 for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
3503 if (!is_shadow_present_pte(spte))
3506 sp = sptep_to_sp(iterator.sptep);
3507 if (!is_last_spte(spte, sp->role.level))
3511 * Check whether the memory access that caused the fault would
3512 * still cause it if it were to be performed right now. If not,
3513 * then this is a spurious fault caused by TLB lazily flushed,
3514 * or some other CPU has already fixed the PTE after the
3515 * current CPU took the fault.
3517 * Need not check the access of upper level table entries since
3518 * they are always ACC_ALL.
3520 if (is_access_allowed(error_code, spte)) {
3521 fault_handled = true;
3527 if (is_access_track_spte(spte))
3528 new_spte = restore_acc_track_spte(new_spte);
3531 * Currently, to simplify the code, write-protection can
3532 * be removed in the fast path only if the SPTE was
3533 * write-protected for dirty-logging or access tracking.
3535 if ((error_code & PFERR_WRITE_MASK) &&
3536 spte_can_locklessly_be_made_writable(spte)) {
3537 new_spte |= PT_WRITABLE_MASK;
3540 * Do not fix write-permission on the large spte. Since
3541 * we only dirty the first page into the dirty-bitmap in
3542 * fast_pf_fix_direct_spte(), other pages are missed
3543 * if its slot has dirty logging enabled.
3545 * Instead, we let the slow page fault path create a
3546 * normal spte to fix the access.
3548 * See the comments in kvm_arch_commit_memory_region().
3550 if (sp->role.level > PG_LEVEL_4K)
3554 /* Verify that the fault can be handled in the fast path */
3555 if (new_spte == spte ||
3556 !is_access_allowed(error_code, new_spte))
3560 * Currently, fast page fault only works for direct mapping
3561 * since the gfn is not stable for indirect shadow page. See
3562 * Documentation/virt/kvm/locking.rst to get more detail.
3564 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3565 iterator.sptep, spte,
3570 if (++retry_count > 4) {
3571 printk_once(KERN_WARNING
3572 "kvm: Fast #PF retrying more than 4 times.\n");
3578 trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
3579 spte, fault_handled);
3580 walk_shadow_page_lockless_end(vcpu);
3582 return fault_handled;
3585 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3586 struct list_head *invalid_list)
3588 struct kvm_mmu_page *sp;
3590 if (!VALID_PAGE(*root_hpa))
3593 sp = to_shadow_page(*root_hpa & PT64_BASE_ADDR_MASK);
3595 if (!sp->root_count && sp->role.invalid)
3596 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3598 *root_hpa = INVALID_PAGE;
3601 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3602 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3603 ulong roots_to_free)
3606 LIST_HEAD(invalid_list);
3607 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3609 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3611 /* Before acquiring the MMU lock, see if we need to do any real work. */
3612 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3613 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3614 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3615 VALID_PAGE(mmu->prev_roots[i].hpa))
3618 if (i == KVM_MMU_NUM_PREV_ROOTS)
3622 spin_lock(&vcpu->kvm->mmu_lock);
3624 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3625 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3626 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3629 if (free_active_root) {
3630 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3631 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3632 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3635 for (i = 0; i < 4; ++i)
3636 if (mmu->pae_root[i] != 0)
3637 mmu_free_root_page(vcpu->kvm,
3640 mmu->root_hpa = INVALID_PAGE;
3645 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3646 spin_unlock(&vcpu->kvm->mmu_lock);
3648 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3650 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3654 if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3655 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3662 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
3663 u8 level, bool direct)
3665 struct kvm_mmu_page *sp;
3667 spin_lock(&vcpu->kvm->mmu_lock);
3669 if (make_mmu_pages_available(vcpu)) {
3670 spin_unlock(&vcpu->kvm->mmu_lock);
3671 return INVALID_PAGE;
3673 sp = kvm_mmu_get_page(vcpu, gfn, gva, level, direct, ACC_ALL);
3676 spin_unlock(&vcpu->kvm->mmu_lock);
3677 return __pa(sp->spt);
3680 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3682 u8 shadow_root_level = vcpu->arch.mmu->shadow_root_level;
3686 if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3687 root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
3688 if (!VALID_PAGE(root))
3690 vcpu->arch.mmu->root_hpa = root;
3691 } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3692 for (i = 0; i < 4; ++i) {
3693 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
3695 root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT),
3696 i << 30, PT32_ROOT_LEVEL, true);
3697 if (!VALID_PAGE(root))
3699 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3701 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3705 /* root_pgd is ignored for direct MMUs. */
3706 vcpu->arch.mmu->root_pgd = 0;
3711 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3714 gfn_t root_gfn, root_pgd;
3718 root_pgd = vcpu->arch.mmu->get_guest_pgd(vcpu);
3719 root_gfn = root_pgd >> PAGE_SHIFT;
3721 if (mmu_check_root(vcpu, root_gfn))
3725 * Do we shadow a long mode page table? If so we need to
3726 * write-protect the guests page table root.
3728 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3729 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->root_hpa));
3731 root = mmu_alloc_root(vcpu, root_gfn, 0,
3732 vcpu->arch.mmu->shadow_root_level, false);
3733 if (!VALID_PAGE(root))
3735 vcpu->arch.mmu->root_hpa = root;
3740 * We shadow a 32 bit page table. This may be a legacy 2-level
3741 * or a PAE 3-level page table. In either case we need to be aware that
3742 * the shadow page table may be a PAE or a long mode page table.
3744 pm_mask = PT_PRESENT_MASK;
3745 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3746 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3748 for (i = 0; i < 4; ++i) {
3749 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
3750 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3751 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3752 if (!(pdptr & PT_PRESENT_MASK)) {
3753 vcpu->arch.mmu->pae_root[i] = 0;
3756 root_gfn = pdptr >> PAGE_SHIFT;
3757 if (mmu_check_root(vcpu, root_gfn))
3761 root = mmu_alloc_root(vcpu, root_gfn, i << 30,
3762 PT32_ROOT_LEVEL, false);
3763 if (!VALID_PAGE(root))
3765 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3767 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3770 * If we shadow a 32 bit page table with a long mode page
3771 * table we enter this path.
3773 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3774 if (vcpu->arch.mmu->lm_root == NULL) {
3776 * The additional page necessary for this is only
3777 * allocated on demand.
3782 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3783 if (lm_root == NULL)
3786 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3788 vcpu->arch.mmu->lm_root = lm_root;
3791 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3795 vcpu->arch.mmu->root_pgd = root_pgd;
3800 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3802 if (vcpu->arch.mmu->direct_map)
3803 return mmu_alloc_direct_roots(vcpu);
3805 return mmu_alloc_shadow_roots(vcpu);
3808 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3811 struct kvm_mmu_page *sp;
3813 if (vcpu->arch.mmu->direct_map)
3816 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3819 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3821 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3822 hpa_t root = vcpu->arch.mmu->root_hpa;
3823 sp = to_shadow_page(root);
3826 * Even if another CPU was marking the SP as unsync-ed
3827 * simultaneously, any guest page table changes are not
3828 * guaranteed to be visible anyway until this VCPU issues a TLB
3829 * flush strictly after those changes are made. We only need to
3830 * ensure that the other CPU sets these flags before any actual
3831 * changes to the page tables are made. The comments in
3832 * mmu_need_write_protect() describe what could go wrong if this
3833 * requirement isn't satisfied.
3835 if (!smp_load_acquire(&sp->unsync) &&
3836 !smp_load_acquire(&sp->unsync_children))
3839 spin_lock(&vcpu->kvm->mmu_lock);
3840 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3842 mmu_sync_children(vcpu, sp);
3844 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3845 spin_unlock(&vcpu->kvm->mmu_lock);
3849 spin_lock(&vcpu->kvm->mmu_lock);
3850 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3852 for (i = 0; i < 4; ++i) {
3853 hpa_t root = vcpu->arch.mmu->pae_root[i];
3855 if (root && VALID_PAGE(root)) {
3856 root &= PT64_BASE_ADDR_MASK;
3857 sp = to_shadow_page(root);
3858 mmu_sync_children(vcpu, sp);
3862 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3863 spin_unlock(&vcpu->kvm->mmu_lock);
3865 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3867 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3868 u32 access, struct x86_exception *exception)
3871 exception->error_code = 0;
3875 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3877 struct x86_exception *exception)
3880 exception->error_code = 0;
3881 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3885 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3887 int bit7 = (pte >> 7) & 1;
3889 return pte & rsvd_check->rsvd_bits_mask[bit7][level-1];
3892 static bool __is_bad_mt_xwr(struct rsvd_bits_validate *rsvd_check, u64 pte)
3894 return rsvd_check->bad_mt_xwr & BIT_ULL(pte & 0x3f);
3897 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3900 * A nested guest cannot use the MMIO cache if it is using nested
3901 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3903 if (mmu_is_nested(vcpu))
3907 return vcpu_match_mmio_gpa(vcpu, addr);
3909 return vcpu_match_mmio_gva(vcpu, addr);
3912 /* return true if reserved bit is detected on spte. */
3914 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3916 struct kvm_shadow_walk_iterator iterator;
3917 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3918 struct rsvd_bits_validate *rsvd_check;
3920 bool reserved = false;
3922 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
3924 walk_shadow_page_lockless_begin(vcpu);
3926 for (shadow_walk_init(&iterator, vcpu, addr),
3927 leaf = root = iterator.level;
3928 shadow_walk_okay(&iterator);
3929 __shadow_walk_next(&iterator, spte)) {
3930 spte = mmu_spte_get_lockless(iterator.sptep);
3932 sptes[leaf - 1] = spte;
3935 if (!is_shadow_present_pte(spte))
3939 * Use a bitwise-OR instead of a logical-OR to aggregate the
3940 * reserved bit and EPT's invalid memtype/XWR checks to avoid
3941 * adding a Jcc in the loop.
3943 reserved |= __is_bad_mt_xwr(rsvd_check, spte) |
3944 __is_rsvd_bits_set(rsvd_check, spte, iterator.level);
3947 walk_shadow_page_lockless_end(vcpu);
3950 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3952 while (root > leaf) {
3953 pr_err("------ spte 0x%llx level %d.\n",
3954 sptes[root - 1], root);
3963 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3968 if (mmio_info_in_cache(vcpu, addr, direct))
3969 return RET_PF_EMULATE;
3971 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3972 if (WARN_ON(reserved))
3975 if (is_mmio_spte(spte)) {
3976 gfn_t gfn = get_mmio_spte_gfn(spte);
3977 unsigned int access = get_mmio_spte_access(spte);
3979 if (!check_mmio_spte(vcpu, spte))
3980 return RET_PF_INVALID;
3985 trace_handle_mmio_page_fault(addr, gfn, access);
3986 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3987 return RET_PF_EMULATE;
3991 * If the page table is zapped by other cpus, let CPU fault again on
3994 return RET_PF_RETRY;
3997 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3998 u32 error_code, gfn_t gfn)
4000 if (unlikely(error_code & PFERR_RSVD_MASK))
4003 if (!(error_code & PFERR_PRESENT_MASK) ||
4004 !(error_code & PFERR_WRITE_MASK))
4008 * guest is writing the page which is write tracked which can
4009 * not be fixed by page fault handler.
4011 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4017 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4019 struct kvm_shadow_walk_iterator iterator;
4022 walk_shadow_page_lockless_begin(vcpu);
4023 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4024 clear_sp_write_flooding_count(iterator.sptep);
4025 if (!is_shadow_present_pte(spte))
4028 walk_shadow_page_lockless_end(vcpu);
4031 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4034 struct kvm_arch_async_pf arch;
4036 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4038 arch.direct_map = vcpu->arch.mmu->direct_map;
4039 arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
4041 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4042 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4045 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4046 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
4049 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4052 /* Don't expose private memslots to L2. */
4053 if (is_guest_mode(vcpu) && !kvm_is_visible_memslot(slot)) {
4054 *pfn = KVM_PFN_NOSLOT;
4060 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4062 return false; /* *pfn has correct page already */
4064 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4065 trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
4066 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4067 trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
4068 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4070 } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
4074 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4078 static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4079 bool prefault, int max_level, bool is_tdp)
4081 bool write = error_code & PFERR_WRITE_MASK;
4082 bool exec = error_code & PFERR_FETCH_MASK;
4083 bool lpage_disallowed = exec && is_nx_huge_page_enabled();
4086 gfn_t gfn = gpa >> PAGE_SHIFT;
4087 unsigned long mmu_seq;
4091 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4092 return RET_PF_EMULATE;
4094 if (fast_page_fault(vcpu, gpa, error_code))
4095 return RET_PF_RETRY;
4097 r = mmu_topup_memory_caches(vcpu, false);
4101 if (lpage_disallowed)
4102 max_level = PG_LEVEL_4K;
4104 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4107 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4108 return RET_PF_RETRY;
4110 if (handle_abnormal_pfn(vcpu, is_tdp ? 0 : gpa, gfn, pfn, ACC_ALL, &r))
4114 spin_lock(&vcpu->kvm->mmu_lock);
4115 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4117 r = make_mmu_pages_available(vcpu);
4120 r = __direct_map(vcpu, gpa, write, map_writable, max_level, pfn,
4121 prefault, is_tdp && lpage_disallowed);
4124 spin_unlock(&vcpu->kvm->mmu_lock);
4125 kvm_release_pfn_clean(pfn);
4129 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
4130 u32 error_code, bool prefault)
4132 pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
4134 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4135 return direct_page_fault(vcpu, gpa & PAGE_MASK, error_code, prefault,
4136 PG_LEVEL_2M, false);
4139 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4140 u64 fault_address, char *insn, int insn_len)
4143 u32 flags = vcpu->arch.apf.host_apf_flags;
4145 #ifndef CONFIG_X86_64
4146 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4147 if (WARN_ON_ONCE(fault_address >> 32))
4151 vcpu->arch.l1tf_flush_l1d = true;
4153 trace_kvm_page_fault(fault_address, error_code);
4155 if (kvm_event_needs_reinjection(vcpu))
4156 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4157 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4159 } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
4160 vcpu->arch.apf.host_apf_flags = 0;
4161 local_irq_disable();
4162 kvm_async_pf_task_wait_schedule(fault_address);
4165 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4170 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4172 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4177 for (max_level = KVM_MAX_HUGEPAGE_LEVEL;
4178 max_level > PG_LEVEL_4K;
4180 int page_num = KVM_PAGES_PER_HPAGE(max_level);
4181 gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
4183 if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4187 return direct_page_fault(vcpu, gpa, error_code, prefault,
4191 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4192 struct kvm_mmu *context)
4194 context->page_fault = nonpaging_page_fault;
4195 context->gva_to_gpa = nonpaging_gva_to_gpa;
4196 context->sync_page = nonpaging_sync_page;
4197 context->invlpg = NULL;
4198 context->update_pte = nonpaging_update_pte;
4199 context->root_level = 0;
4200 context->shadow_root_level = PT32E_ROOT_LEVEL;
4201 context->direct_map = true;
4202 context->nx = false;
4205 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
4206 union kvm_mmu_page_role role)
4208 return (role.direct || pgd == root->pgd) &&
4209 VALID_PAGE(root->hpa) && to_shadow_page(root->hpa) &&
4210 role.word == to_shadow_page(root->hpa)->role.word;
4214 * Find out if a previously cached root matching the new pgd/role is available.
4215 * The current root is also inserted into the cache.
4216 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4218 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4219 * false is returned. This root should now be freed by the caller.
4221 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4222 union kvm_mmu_page_role new_role)
4225 struct kvm_mmu_root_info root;
4226 struct kvm_mmu *mmu = vcpu->arch.mmu;
4228 root.pgd = mmu->root_pgd;
4229 root.hpa = mmu->root_hpa;
4231 if (is_root_usable(&root, new_pgd, new_role))
4234 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4235 swap(root, mmu->prev_roots[i]);
4237 if (is_root_usable(&root, new_pgd, new_role))
4241 mmu->root_hpa = root.hpa;
4242 mmu->root_pgd = root.pgd;
4244 return i < KVM_MMU_NUM_PREV_ROOTS;
4247 static bool fast_pgd_switch(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4248 union kvm_mmu_page_role new_role)
4250 struct kvm_mmu *mmu = vcpu->arch.mmu;
4253 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4254 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4255 * later if necessary.
4257 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4258 mmu->root_level >= PT64_ROOT_4LEVEL)
4259 return cached_root_available(vcpu, new_pgd, new_role);
4264 static void __kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4265 union kvm_mmu_page_role new_role,
4266 bool skip_tlb_flush, bool skip_mmu_sync)
4268 if (!fast_pgd_switch(vcpu, new_pgd, new_role)) {
4269 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, KVM_MMU_ROOT_CURRENT);
4274 * It's possible that the cached previous root page is obsolete because
4275 * of a change in the MMU generation number. However, changing the
4276 * generation number is accompanied by KVM_REQ_MMU_RELOAD, which will
4277 * free the root set here and allocate a new one.
4279 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4281 if (!skip_mmu_sync || force_flush_and_sync_on_reuse)
4282 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4283 if (!skip_tlb_flush || force_flush_and_sync_on_reuse)
4284 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4287 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4288 * switching to a new CR3, that GVA->GPA mapping may no longer be
4289 * valid. So clear any cached MMIO info even when we don't need to sync
4290 * the shadow page tables.
4292 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4294 __clear_sp_write_flooding_count(to_shadow_page(vcpu->arch.mmu->root_hpa));
4297 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd, bool skip_tlb_flush,
4300 __kvm_mmu_new_pgd(vcpu, new_pgd, kvm_mmu_calc_root_page_role(vcpu),
4301 skip_tlb_flush, skip_mmu_sync);
4303 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4305 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4307 return kvm_read_cr3(vcpu);
4310 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4311 unsigned int access, int *nr_present)
4313 if (unlikely(is_mmio_spte(*sptep))) {
4314 if (gfn != get_mmio_spte_gfn(*sptep)) {
4315 mmu_spte_clear_no_track(sptep);
4320 mark_mmio_spte(vcpu, sptep, gfn, access);
4327 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4328 unsigned level, unsigned gpte)
4331 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4332 * If it is clear, there are no large pages at this level, so clear
4333 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4335 gpte &= level - mmu->last_nonleaf_level;
4338 * PG_LEVEL_4K always terminates. The RHS has bit 7 set
4339 * iff level <= PG_LEVEL_4K, which for our purpose means
4340 * level == PG_LEVEL_4K; set PT_PAGE_SIZE_MASK in gpte then.
4342 gpte |= level - PG_LEVEL_4K - 1;
4344 return gpte & PT_PAGE_SIZE_MASK;
4347 #define PTTYPE_EPT 18 /* arbitrary */
4348 #define PTTYPE PTTYPE_EPT
4349 #include "paging_tmpl.h"
4353 #include "paging_tmpl.h"
4357 #include "paging_tmpl.h"
4361 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4362 struct rsvd_bits_validate *rsvd_check,
4363 int maxphyaddr, int level, bool nx, bool gbpages,
4366 u64 exb_bit_rsvd = 0;
4367 u64 gbpages_bit_rsvd = 0;
4368 u64 nonleaf_bit8_rsvd = 0;
4370 rsvd_check->bad_mt_xwr = 0;
4373 exb_bit_rsvd = rsvd_bits(63, 63);
4375 gbpages_bit_rsvd = rsvd_bits(7, 7);
4378 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4379 * leaf entries) on AMD CPUs only.
4382 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4385 case PT32_ROOT_LEVEL:
4386 /* no rsvd bits for 2 level 4K page table entries */
4387 rsvd_check->rsvd_bits_mask[0][1] = 0;
4388 rsvd_check->rsvd_bits_mask[0][0] = 0;
4389 rsvd_check->rsvd_bits_mask[1][0] =
4390 rsvd_check->rsvd_bits_mask[0][0];
4393 rsvd_check->rsvd_bits_mask[1][1] = 0;
4397 if (is_cpuid_PSE36())
4398 /* 36bits PSE 4MB page */
4399 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4401 /* 32 bits PSE 4MB page */
4402 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4404 case PT32E_ROOT_LEVEL:
4405 rsvd_check->rsvd_bits_mask[0][2] =
4406 rsvd_bits(maxphyaddr, 63) |
4407 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4408 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4409 rsvd_bits(maxphyaddr, 62); /* PDE */
4410 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4411 rsvd_bits(maxphyaddr, 62); /* PTE */
4412 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4413 rsvd_bits(maxphyaddr, 62) |
4414 rsvd_bits(13, 20); /* large page */
4415 rsvd_check->rsvd_bits_mask[1][0] =
4416 rsvd_check->rsvd_bits_mask[0][0];
4418 case PT64_ROOT_5LEVEL:
4419 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4420 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4421 rsvd_bits(maxphyaddr, 51);
4422 rsvd_check->rsvd_bits_mask[1][4] =
4423 rsvd_check->rsvd_bits_mask[0][4];
4425 case PT64_ROOT_4LEVEL:
4426 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4427 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4428 rsvd_bits(maxphyaddr, 51);
4429 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4431 rsvd_bits(maxphyaddr, 51);
4432 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4433 rsvd_bits(maxphyaddr, 51);
4434 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4435 rsvd_bits(maxphyaddr, 51);
4436 rsvd_check->rsvd_bits_mask[1][3] =
4437 rsvd_check->rsvd_bits_mask[0][3];
4438 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4439 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4441 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4442 rsvd_bits(maxphyaddr, 51) |
4443 rsvd_bits(13, 20); /* large page */
4444 rsvd_check->rsvd_bits_mask[1][0] =
4445 rsvd_check->rsvd_bits_mask[0][0];
4450 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4451 struct kvm_mmu *context)
4453 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4454 cpuid_maxphyaddr(vcpu), context->root_level,
4456 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4458 guest_cpuid_is_amd_or_hygon(vcpu));
4462 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4463 int maxphyaddr, bool execonly)
4467 rsvd_check->rsvd_bits_mask[0][4] =
4468 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4469 rsvd_check->rsvd_bits_mask[0][3] =
4470 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4471 rsvd_check->rsvd_bits_mask[0][2] =
4472 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4473 rsvd_check->rsvd_bits_mask[0][1] =
4474 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4475 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4478 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4479 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4480 rsvd_check->rsvd_bits_mask[1][2] =
4481 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4482 rsvd_check->rsvd_bits_mask[1][1] =
4483 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4484 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4486 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4487 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4488 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4489 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4490 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4492 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4493 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4495 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4498 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4499 struct kvm_mmu *context, bool execonly)
4501 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4502 cpuid_maxphyaddr(vcpu), execonly);
4506 * the page table on host is the shadow page table for the page
4507 * table in guest or amd nested guest, its mmu features completely
4508 * follow the features in guest.
4511 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4513 bool uses_nx = context->nx ||
4514 context->mmu_role.base.smep_andnot_wp;
4515 struct rsvd_bits_validate *shadow_zero_check;
4519 * Passing "true" to the last argument is okay; it adds a check
4520 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4522 shadow_zero_check = &context->shadow_zero_check;
4523 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4525 context->shadow_root_level, uses_nx,
4526 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4527 is_pse(vcpu), true);
4529 if (!shadow_me_mask)
4532 for (i = context->shadow_root_level; --i >= 0;) {
4533 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4534 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4538 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4540 static inline bool boot_cpu_is_amd(void)
4542 WARN_ON_ONCE(!tdp_enabled);
4543 return shadow_x_mask == 0;
4547 * the direct page table on host, use as much mmu features as
4548 * possible, however, kvm currently does not do execution-protection.
4551 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4552 struct kvm_mmu *context)
4554 struct rsvd_bits_validate *shadow_zero_check;
4557 shadow_zero_check = &context->shadow_zero_check;
4559 if (boot_cpu_is_amd())
4560 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4562 context->shadow_root_level, false,
4563 boot_cpu_has(X86_FEATURE_GBPAGES),
4566 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4570 if (!shadow_me_mask)
4573 for (i = context->shadow_root_level; --i >= 0;) {
4574 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4575 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4580 * as the comments in reset_shadow_zero_bits_mask() except it
4581 * is the shadow page table for intel nested guest.
4584 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4585 struct kvm_mmu *context, bool execonly)
4587 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4588 shadow_phys_bits, execonly);
4591 #define BYTE_MASK(access) \
4592 ((1 & (access) ? 2 : 0) | \
4593 (2 & (access) ? 4 : 0) | \
4594 (3 & (access) ? 8 : 0) | \
4595 (4 & (access) ? 16 : 0) | \
4596 (5 & (access) ? 32 : 0) | \
4597 (6 & (access) ? 64 : 0) | \
4598 (7 & (access) ? 128 : 0))
4601 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4602 struct kvm_mmu *mmu, bool ept)
4606 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4607 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4608 const u8 u = BYTE_MASK(ACC_USER_MASK);
4610 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4611 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4612 bool cr0_wp = is_write_protection(vcpu);
4614 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4615 unsigned pfec = byte << 1;
4618 * Each "*f" variable has a 1 bit for each UWX value
4619 * that causes a fault with the given PFEC.
4622 /* Faults from writes to non-writable pages */
4623 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4624 /* Faults from user mode accesses to supervisor pages */
4625 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4626 /* Faults from fetches of non-executable pages*/
4627 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4628 /* Faults from kernel mode fetches of user pages */
4630 /* Faults from kernel mode accesses of user pages */
4634 /* Faults from kernel mode accesses to user pages */
4635 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4637 /* Not really needed: !nx will cause pte.nx to fault */
4641 /* Allow supervisor writes if !cr0.wp */
4643 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4645 /* Disallow supervisor fetches of user code if cr4.smep */
4647 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4650 * SMAP:kernel-mode data accesses from user-mode
4651 * mappings should fault. A fault is considered
4652 * as a SMAP violation if all of the following
4653 * conditions are true:
4654 * - X86_CR4_SMAP is set in CR4
4655 * - A user page is accessed
4656 * - The access is not a fetch
4657 * - Page fault in kernel mode
4658 * - if CPL = 3 or X86_EFLAGS_AC is clear
4660 * Here, we cover the first three conditions.
4661 * The fourth is computed dynamically in permission_fault();
4662 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4663 * *not* subject to SMAP restrictions.
4666 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4669 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4674 * PKU is an additional mechanism by which the paging controls access to
4675 * user-mode addresses based on the value in the PKRU register. Protection
4676 * key violations are reported through a bit in the page fault error code.
4677 * Unlike other bits of the error code, the PK bit is not known at the
4678 * call site of e.g. gva_to_gpa; it must be computed directly in
4679 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4680 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4682 * In particular the following conditions come from the error code, the
4683 * page tables and the machine state:
4684 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4685 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4686 * - PK is always zero if U=0 in the page tables
4687 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4689 * The PKRU bitmask caches the result of these four conditions. The error
4690 * code (minus the P bit) and the page table's U bit form an index into the
4691 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4692 * with the two bits of the PKRU register corresponding to the protection key.
4693 * For the first three conditions above the bits will be 00, thus masking
4694 * away both AD and WD. For all reads or if the last condition holds, WD
4695 * only will be masked away.
4697 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4708 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4709 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4714 wp = is_write_protection(vcpu);
4716 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4717 unsigned pfec, pkey_bits;
4718 bool check_pkey, check_write, ff, uf, wf, pte_user;
4721 ff = pfec & PFERR_FETCH_MASK;
4722 uf = pfec & PFERR_USER_MASK;
4723 wf = pfec & PFERR_WRITE_MASK;
4725 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4726 pte_user = pfec & PFERR_RSVD_MASK;
4729 * Only need to check the access which is not an
4730 * instruction fetch and is to a user page.
4732 check_pkey = (!ff && pte_user);
4734 * write access is controlled by PKRU if it is a
4735 * user access or CR0.WP = 1.
4737 check_write = check_pkey && wf && (uf || wp);
4739 /* PKRU.AD stops both read and write access. */
4740 pkey_bits = !!check_pkey;
4741 /* PKRU.WD stops write access. */
4742 pkey_bits |= (!!check_write) << 1;
4744 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4748 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4750 unsigned root_level = mmu->root_level;
4752 mmu->last_nonleaf_level = root_level;
4753 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4754 mmu->last_nonleaf_level++;
4757 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4758 struct kvm_mmu *context,
4761 context->nx = is_nx(vcpu);
4762 context->root_level = level;
4764 reset_rsvds_bits_mask(vcpu, context);
4765 update_permission_bitmask(vcpu, context, false);
4766 update_pkru_bitmask(vcpu, context, false);
4767 update_last_nonleaf_level(vcpu, context);
4769 MMU_WARN_ON(!is_pae(vcpu));
4770 context->page_fault = paging64_page_fault;
4771 context->gva_to_gpa = paging64_gva_to_gpa;
4772 context->sync_page = paging64_sync_page;
4773 context->invlpg = paging64_invlpg;
4774 context->update_pte = paging64_update_pte;
4775 context->shadow_root_level = level;
4776 context->direct_map = false;
4779 static void paging64_init_context(struct kvm_vcpu *vcpu,
4780 struct kvm_mmu *context)
4782 int root_level = is_la57_mode(vcpu) ?
4783 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4785 paging64_init_context_common(vcpu, context, root_level);
4788 static void paging32_init_context(struct kvm_vcpu *vcpu,
4789 struct kvm_mmu *context)
4791 context->nx = false;
4792 context->root_level = PT32_ROOT_LEVEL;
4794 reset_rsvds_bits_mask(vcpu, context);
4795 update_permission_bitmask(vcpu, context, false);
4796 update_pkru_bitmask(vcpu, context, false);
4797 update_last_nonleaf_level(vcpu, context);
4799 context->page_fault = paging32_page_fault;
4800 context->gva_to_gpa = paging32_gva_to_gpa;
4801 context->sync_page = paging32_sync_page;
4802 context->invlpg = paging32_invlpg;
4803 context->update_pte = paging32_update_pte;
4804 context->shadow_root_level = PT32E_ROOT_LEVEL;
4805 context->direct_map = false;
4808 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4809 struct kvm_mmu *context)
4811 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4814 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4816 union kvm_mmu_extended_role ext = {0};
4818 ext.cr0_pg = !!is_paging(vcpu);
4819 ext.cr4_pae = !!is_pae(vcpu);
4820 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4821 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4822 ext.cr4_pse = !!is_pse(vcpu);
4823 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4824 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4831 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4834 union kvm_mmu_role role = {0};
4836 role.base.access = ACC_ALL;
4837 role.base.nxe = !!is_nx(vcpu);
4838 role.base.cr0_wp = is_write_protection(vcpu);
4839 role.base.smm = is_smm(vcpu);
4840 role.base.guest_mode = is_guest_mode(vcpu);
4845 role.ext = kvm_calc_mmu_role_ext(vcpu);
4850 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
4852 /* Use 5-level TDP if and only if it's useful/necessary. */
4853 if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
4856 return max_tdp_level;
4859 static union kvm_mmu_role
4860 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4862 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4864 role.base.ad_disabled = (shadow_accessed_mask == 0);
4865 role.base.level = kvm_mmu_get_tdp_level(vcpu);
4866 role.base.direct = true;
4867 role.base.gpte_is_8_bytes = true;
4872 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4874 struct kvm_mmu *context = &vcpu->arch.root_mmu;
4875 union kvm_mmu_role new_role =
4876 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4878 if (new_role.as_u64 == context->mmu_role.as_u64)
4881 context->mmu_role.as_u64 = new_role.as_u64;
4882 context->page_fault = kvm_tdp_page_fault;
4883 context->sync_page = nonpaging_sync_page;
4884 context->invlpg = NULL;
4885 context->update_pte = nonpaging_update_pte;
4886 context->shadow_root_level = kvm_mmu_get_tdp_level(vcpu);
4887 context->direct_map = true;
4888 context->get_guest_pgd = get_cr3;
4889 context->get_pdptr = kvm_pdptr_read;
4890 context->inject_page_fault = kvm_inject_page_fault;
4892 if (!is_paging(vcpu)) {
4893 context->nx = false;
4894 context->gva_to_gpa = nonpaging_gva_to_gpa;
4895 context->root_level = 0;
4896 } else if (is_long_mode(vcpu)) {
4897 context->nx = is_nx(vcpu);
4898 context->root_level = is_la57_mode(vcpu) ?
4899 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4900 reset_rsvds_bits_mask(vcpu, context);
4901 context->gva_to_gpa = paging64_gva_to_gpa;
4902 } else if (is_pae(vcpu)) {
4903 context->nx = is_nx(vcpu);
4904 context->root_level = PT32E_ROOT_LEVEL;
4905 reset_rsvds_bits_mask(vcpu, context);
4906 context->gva_to_gpa = paging64_gva_to_gpa;
4908 context->nx = false;
4909 context->root_level = PT32_ROOT_LEVEL;
4910 reset_rsvds_bits_mask(vcpu, context);
4911 context->gva_to_gpa = paging32_gva_to_gpa;
4914 update_permission_bitmask(vcpu, context, false);
4915 update_pkru_bitmask(vcpu, context, false);
4916 update_last_nonleaf_level(vcpu, context);
4917 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4920 static union kvm_mmu_role
4921 kvm_calc_shadow_root_page_role_common(struct kvm_vcpu *vcpu, bool base_only)
4923 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4925 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4926 !is_write_protection(vcpu);
4927 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4928 !is_write_protection(vcpu);
4929 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4934 static union kvm_mmu_role
4935 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4937 union kvm_mmu_role role =
4938 kvm_calc_shadow_root_page_role_common(vcpu, base_only);
4940 role.base.direct = !is_paging(vcpu);
4942 if (!is_long_mode(vcpu))
4943 role.base.level = PT32E_ROOT_LEVEL;
4944 else if (is_la57_mode(vcpu))
4945 role.base.level = PT64_ROOT_5LEVEL;
4947 role.base.level = PT64_ROOT_4LEVEL;
4952 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
4953 u32 cr0, u32 cr4, u32 efer,
4954 union kvm_mmu_role new_role)
4956 if (!(cr0 & X86_CR0_PG))
4957 nonpaging_init_context(vcpu, context);
4958 else if (efer & EFER_LMA)
4959 paging64_init_context(vcpu, context);
4960 else if (cr4 & X86_CR4_PAE)
4961 paging32E_init_context(vcpu, context);
4963 paging32_init_context(vcpu, context);
4965 context->mmu_role.as_u64 = new_role.as_u64;
4966 reset_shadow_zero_bits_mask(vcpu, context);
4969 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer)
4971 struct kvm_mmu *context = &vcpu->arch.root_mmu;
4972 union kvm_mmu_role new_role =
4973 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4975 if (new_role.as_u64 != context->mmu_role.as_u64)
4976 shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
4979 static union kvm_mmu_role
4980 kvm_calc_shadow_npt_root_page_role(struct kvm_vcpu *vcpu)
4982 union kvm_mmu_role role =
4983 kvm_calc_shadow_root_page_role_common(vcpu, false);
4985 role.base.direct = false;
4986 role.base.level = kvm_mmu_get_tdp_level(vcpu);
4991 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer,
4994 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4995 union kvm_mmu_role new_role = kvm_calc_shadow_npt_root_page_role(vcpu);
4997 context->shadow_root_level = new_role.base.level;
4999 __kvm_mmu_new_pgd(vcpu, nested_cr3, new_role.base, false, false);
5001 if (new_role.as_u64 != context->mmu_role.as_u64)
5002 shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
5004 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5006 static union kvm_mmu_role
5007 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5008 bool execonly, u8 level)
5010 union kvm_mmu_role role = {0};
5012 /* SMM flag is inherited from root_mmu */
5013 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
5015 role.base.level = level;
5016 role.base.gpte_is_8_bytes = true;
5017 role.base.direct = false;
5018 role.base.ad_disabled = !accessed_dirty;
5019 role.base.guest_mode = true;
5020 role.base.access = ACC_ALL;
5023 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
5024 * SMAP variation to denote shadow EPT entries.
5026 role.base.cr0_wp = true;
5027 role.base.smap_andnot_wp = true;
5029 role.ext = kvm_calc_mmu_role_ext(vcpu);
5030 role.ext.execonly = execonly;
5035 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5036 bool accessed_dirty, gpa_t new_eptp)
5038 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5039 u8 level = vmx_eptp_page_walk_level(new_eptp);
5040 union kvm_mmu_role new_role =
5041 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5044 __kvm_mmu_new_pgd(vcpu, new_eptp, new_role.base, true, true);
5046 if (new_role.as_u64 == context->mmu_role.as_u64)
5049 context->shadow_root_level = level;
5052 context->ept_ad = accessed_dirty;
5053 context->page_fault = ept_page_fault;
5054 context->gva_to_gpa = ept_gva_to_gpa;
5055 context->sync_page = ept_sync_page;
5056 context->invlpg = ept_invlpg;
5057 context->update_pte = ept_update_pte;
5058 context->root_level = level;
5059 context->direct_map = false;
5060 context->mmu_role.as_u64 = new_role.as_u64;
5062 update_permission_bitmask(vcpu, context, true);
5063 update_pkru_bitmask(vcpu, context, true);
5064 update_last_nonleaf_level(vcpu, context);
5065 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5066 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5068 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5070 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5072 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5074 kvm_init_shadow_mmu(vcpu,
5075 kvm_read_cr0_bits(vcpu, X86_CR0_PG),
5076 kvm_read_cr4_bits(vcpu, X86_CR4_PAE),
5079 context->get_guest_pgd = get_cr3;
5080 context->get_pdptr = kvm_pdptr_read;
5081 context->inject_page_fault = kvm_inject_page_fault;
5084 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5086 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5087 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5089 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5092 g_context->mmu_role.as_u64 = new_role.as_u64;
5093 g_context->get_guest_pgd = get_cr3;
5094 g_context->get_pdptr = kvm_pdptr_read;
5095 g_context->inject_page_fault = kvm_inject_page_fault;
5098 * L2 page tables are never shadowed, so there is no need to sync
5101 g_context->invlpg = NULL;
5104 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5105 * L1's nested page tables (e.g. EPT12). The nested translation
5106 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5107 * L2's page tables as the first level of translation and L1's
5108 * nested page tables as the second level of translation. Basically
5109 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5111 if (!is_paging(vcpu)) {
5112 g_context->nx = false;
5113 g_context->root_level = 0;
5114 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5115 } else if (is_long_mode(vcpu)) {
5116 g_context->nx = is_nx(vcpu);
5117 g_context->root_level = is_la57_mode(vcpu) ?
5118 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5119 reset_rsvds_bits_mask(vcpu, g_context);
5120 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5121 } else if (is_pae(vcpu)) {
5122 g_context->nx = is_nx(vcpu);
5123 g_context->root_level = PT32E_ROOT_LEVEL;
5124 reset_rsvds_bits_mask(vcpu, g_context);
5125 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5127 g_context->nx = false;
5128 g_context->root_level = PT32_ROOT_LEVEL;
5129 reset_rsvds_bits_mask(vcpu, g_context);
5130 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5133 update_permission_bitmask(vcpu, g_context, false);
5134 update_pkru_bitmask(vcpu, g_context, false);
5135 update_last_nonleaf_level(vcpu, g_context);
5138 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5143 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5145 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5146 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5149 if (mmu_is_nested(vcpu))
5150 init_kvm_nested_mmu(vcpu);
5151 else if (tdp_enabled)
5152 init_kvm_tdp_mmu(vcpu);
5154 init_kvm_softmmu(vcpu);
5156 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5158 static union kvm_mmu_page_role
5159 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5161 union kvm_mmu_role role;
5164 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5166 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5171 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5173 kvm_mmu_unload(vcpu);
5174 kvm_init_mmu(vcpu, true);
5176 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5178 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5182 r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->direct_map);
5185 r = mmu_alloc_roots(vcpu);
5186 kvm_mmu_sync_roots(vcpu);
5189 kvm_mmu_load_pgd(vcpu);
5190 kvm_x86_ops.tlb_flush_current(vcpu);
5194 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5196 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5198 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5199 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5200 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5201 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5203 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5205 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5206 struct kvm_mmu_page *sp, u64 *spte,
5209 if (sp->role.level != PG_LEVEL_4K) {
5210 ++vcpu->kvm->stat.mmu_pde_zapped;
5214 ++vcpu->kvm->stat.mmu_pte_updated;
5215 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5218 static bool need_remote_flush(u64 old, u64 new)
5220 if (!is_shadow_present_pte(old))
5222 if (!is_shadow_present_pte(new))
5224 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5226 old ^= shadow_nx_mask;
5227 new ^= shadow_nx_mask;
5228 return (old & ~new & PT64_PERM_MASK) != 0;
5231 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5238 * Assume that the pte write on a page table of the same type
5239 * as the current vcpu paging mode since we update the sptes only
5240 * when they have the same mode.
5242 if (is_pae(vcpu) && *bytes == 4) {
5243 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5248 if (*bytes == 4 || *bytes == 8) {
5249 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5258 * If we're seeing too many writes to a page, it may no longer be a page table,
5259 * or we may be forking, in which case it is better to unmap the page.
5261 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5264 * Skip write-flooding detected for the sp whose level is 1, because
5265 * it can become unsync, then the guest page is not write-protected.
5267 if (sp->role.level == PG_LEVEL_4K)
5270 atomic_inc(&sp->write_flooding_count);
5271 return atomic_read(&sp->write_flooding_count) >= 3;
5275 * Misaligned accesses are too much trouble to fix up; also, they usually
5276 * indicate a page is not used as a page table.
5278 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5281 unsigned offset, pte_size, misaligned;
5283 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5284 gpa, bytes, sp->role.word);
5286 offset = offset_in_page(gpa);
5287 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5290 * Sometimes, the OS only writes the last one bytes to update status
5291 * bits, for example, in linux, andb instruction is used in clear_bit().
5293 if (!(offset & (pte_size - 1)) && bytes == 1)
5296 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5297 misaligned |= bytes < 4;
5302 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5304 unsigned page_offset, quadrant;
5308 page_offset = offset_in_page(gpa);
5309 level = sp->role.level;
5311 if (!sp->role.gpte_is_8_bytes) {
5312 page_offset <<= 1; /* 32->64 */
5314 * A 32-bit pde maps 4MB while the shadow pdes map
5315 * only 2MB. So we need to double the offset again
5316 * and zap two pdes instead of one.
5318 if (level == PT32_ROOT_LEVEL) {
5319 page_offset &= ~7; /* kill rounding error */
5323 quadrant = page_offset >> PAGE_SHIFT;
5324 page_offset &= ~PAGE_MASK;
5325 if (quadrant != sp->role.quadrant)
5329 spte = &sp->spt[page_offset / sizeof(*spte)];
5334 * Ignore various flags when determining if a SPTE can be immediately
5335 * overwritten for the current MMU.
5336 * - level: explicitly checked in mmu_pte_write_new_pte(), and will never
5337 * match the current MMU role, as MMU's level tracks the root level.
5338 * - access: updated based on the new guest PTE
5339 * - quadrant: handled by get_written_sptes()
5340 * - invalid: always false (loop only walks valid shadow pages)
5342 static const union kvm_mmu_page_role role_ign = {
5349 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5350 const u8 *new, int bytes,
5351 struct kvm_page_track_notifier_node *node)
5353 gfn_t gfn = gpa >> PAGE_SHIFT;
5354 struct kvm_mmu_page *sp;
5355 LIST_HEAD(invalid_list);
5356 u64 entry, gentry, *spte;
5358 bool remote_flush, local_flush;
5361 * If we don't have indirect shadow pages, it means no page is
5362 * write-protected, so we can exit simply.
5364 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5367 remote_flush = local_flush = false;
5369 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5372 * No need to care whether allocation memory is successful
5373 * or not since pte prefetch is skiped if it does not have
5374 * enough objects in the cache.
5376 mmu_topup_memory_caches(vcpu, true);
5378 spin_lock(&vcpu->kvm->mmu_lock);
5380 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5382 ++vcpu->kvm->stat.mmu_pte_write;
5383 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5385 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5386 if (detect_write_misaligned(sp, gpa, bytes) ||
5387 detect_write_flooding(sp)) {
5388 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5389 ++vcpu->kvm->stat.mmu_flooded;
5393 spte = get_written_sptes(sp, gpa, &npte);
5399 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5402 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5404 !((sp->role.word ^ base_role) & ~role_ign.word) &&
5406 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5407 if (need_remote_flush(entry, *spte))
5408 remote_flush = true;
5412 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5413 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5414 spin_unlock(&vcpu->kvm->mmu_lock);
5417 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5422 if (vcpu->arch.mmu->direct_map)
5425 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5427 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5431 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5433 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5434 void *insn, int insn_len)
5436 int r, emulation_type = EMULTYPE_PF;
5437 bool direct = vcpu->arch.mmu->direct_map;
5439 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
5440 return RET_PF_RETRY;
5443 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5444 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5445 if (r == RET_PF_EMULATE)
5449 if (r == RET_PF_INVALID) {
5450 r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5451 lower_32_bits(error_code), false);
5452 WARN_ON(r == RET_PF_INVALID);
5455 if (r == RET_PF_RETRY)
5461 * Before emulating the instruction, check if the error code
5462 * was due to a RO violation while translating the guest page.
5463 * This can occur when using nested virtualization with nested
5464 * paging in both guests. If true, we simply unprotect the page
5465 * and resume the guest.
5467 if (vcpu->arch.mmu->direct_map &&
5468 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5469 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5474 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5475 * optimistically try to just unprotect the page and let the processor
5476 * re-execute the instruction that caused the page fault. Do not allow
5477 * retrying MMIO emulation, as it's not only pointless but could also
5478 * cause us to enter an infinite loop because the processor will keep
5479 * faulting on the non-existent MMIO address. Retrying an instruction
5480 * from a nested guest is also pointless and dangerous as we are only
5481 * explicitly shadowing L1's page tables, i.e. unprotecting something
5482 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5484 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5485 emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5488 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5489 * This can happen if a guest gets a page-fault on data access but the HW
5490 * table walker is not able to read the instruction page (e.g instruction
5491 * page is not present in memory). In those cases we simply restart the
5492 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5494 if (unlikely(insn && !insn_len)) {
5495 if (!kvm_x86_ops.need_emulation_on_page_fault(vcpu))
5499 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5502 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5504 void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5505 gva_t gva, hpa_t root_hpa)
5509 /* It's actually a GPA for vcpu->arch.guest_mmu. */
5510 if (mmu != &vcpu->arch.guest_mmu) {
5511 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
5512 if (is_noncanonical_address(gva, vcpu))
5515 kvm_x86_ops.tlb_flush_gva(vcpu, gva);
5521 if (root_hpa == INVALID_PAGE) {
5522 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5525 * INVLPG is required to invalidate any global mappings for the VA,
5526 * irrespective of PCID. Since it would take us roughly similar amount
5527 * of work to determine whether any of the prev_root mappings of the VA
5528 * is marked global, or to just sync it blindly, so we might as well
5529 * just always sync it.
5531 * Mappings not reachable via the current cr3 or the prev_roots will be
5532 * synced when switching to that cr3, so nothing needs to be done here
5535 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5536 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5537 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5539 mmu->invlpg(vcpu, gva, root_hpa);
5542 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_gva);
5544 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5546 kvm_mmu_invalidate_gva(vcpu, vcpu->arch.mmu, gva, INVALID_PAGE);
5547 ++vcpu->stat.invlpg;
5549 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5552 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5554 struct kvm_mmu *mmu = vcpu->arch.mmu;
5555 bool tlb_flush = false;
5558 if (pcid == kvm_get_active_pcid(vcpu)) {
5559 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5563 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5564 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5565 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
5566 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5572 kvm_x86_ops.tlb_flush_gva(vcpu, gva);
5574 ++vcpu->stat.invlpg;
5577 * Mappings not reachable via the current cr3 or the prev_roots will be
5578 * synced when switching to that cr3, so nothing needs to be done here
5582 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5584 void kvm_configure_mmu(bool enable_tdp, int tdp_max_root_level,
5585 int tdp_huge_page_level)
5587 tdp_enabled = enable_tdp;
5588 max_tdp_level = tdp_max_root_level;
5591 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5592 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5593 * the kernel is not. But, KVM never creates a page size greater than
5594 * what is used by the kernel for any given HVA, i.e. the kernel's
5595 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5598 max_huge_page_level = tdp_huge_page_level;
5599 else if (boot_cpu_has(X86_FEATURE_GBPAGES))
5600 max_huge_page_level = PG_LEVEL_1G;
5602 max_huge_page_level = PG_LEVEL_2M;
5604 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5606 /* The return value indicates if tlb flush on all vcpus is needed. */
5607 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5609 /* The caller should hold mmu-lock before calling this function. */
5610 static __always_inline bool
5611 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5612 slot_level_handler fn, int start_level, int end_level,
5613 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5615 struct slot_rmap_walk_iterator iterator;
5618 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5619 end_gfn, &iterator) {
5621 flush |= fn(kvm, iterator.rmap);
5623 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5624 if (flush && lock_flush_tlb) {
5625 kvm_flush_remote_tlbs_with_address(kvm,
5627 iterator.gfn - start_gfn + 1);
5630 cond_resched_lock(&kvm->mmu_lock);
5634 if (flush && lock_flush_tlb) {
5635 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5636 end_gfn - start_gfn + 1);
5643 static __always_inline bool
5644 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5645 slot_level_handler fn, int start_level, int end_level,
5646 bool lock_flush_tlb)
5648 return slot_handle_level_range(kvm, memslot, fn, start_level,
5649 end_level, memslot->base_gfn,
5650 memslot->base_gfn + memslot->npages - 1,
5654 static __always_inline bool
5655 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5656 slot_level_handler fn, bool lock_flush_tlb)
5658 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5659 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5662 static __always_inline bool
5663 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5664 slot_level_handler fn, bool lock_flush_tlb)
5666 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K + 1,
5667 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5670 static __always_inline bool
5671 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5672 slot_level_handler fn, bool lock_flush_tlb)
5674 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5675 PG_LEVEL_4K, lock_flush_tlb);
5678 static void free_mmu_pages(struct kvm_mmu *mmu)
5680 free_page((unsigned long)mmu->pae_root);
5681 free_page((unsigned long)mmu->lm_root);
5684 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5690 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5691 * while the PDP table is a per-vCPU construct that's allocated at MMU
5692 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5693 * x86_64. Therefore we need to allocate the PDP table in the first
5694 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5695 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5696 * skip allocating the PDP table.
5698 if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5701 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5705 mmu->pae_root = page_address(page);
5706 for (i = 0; i < 4; ++i)
5707 mmu->pae_root[i] = INVALID_PAGE;
5712 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5717 vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
5718 vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
5720 vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
5721 vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
5723 vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
5725 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5726 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5728 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5729 vcpu->arch.root_mmu.root_pgd = 0;
5730 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5731 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5732 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5734 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5735 vcpu->arch.guest_mmu.root_pgd = 0;
5736 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5737 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5738 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5740 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5742 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5746 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5748 goto fail_allocate_root;
5752 free_mmu_pages(&vcpu->arch.guest_mmu);
5756 #define BATCH_ZAP_PAGES 10
5757 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5759 struct kvm_mmu_page *sp, *node;
5760 int nr_zapped, batch = 0;
5763 list_for_each_entry_safe_reverse(sp, node,
5764 &kvm->arch.active_mmu_pages, link) {
5766 * No obsolete valid page exists before a newly created page
5767 * since active_mmu_pages is a FIFO list.
5769 if (!is_obsolete_sp(kvm, sp))
5773 * Invalid pages should never land back on the list of active
5774 * pages. Skip the bogus page, otherwise we'll get stuck in an
5775 * infinite loop if the page gets put back on the list (again).
5777 if (WARN_ON(sp->role.invalid))
5781 * No need to flush the TLB since we're only zapping shadow
5782 * pages with an obsolete generation number and all vCPUS have
5783 * loaded a new root, i.e. the shadow pages being zapped cannot
5784 * be in active use by the guest.
5786 if (batch >= BATCH_ZAP_PAGES &&
5787 cond_resched_lock(&kvm->mmu_lock)) {
5792 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5793 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5800 * Trigger a remote TLB flush before freeing the page tables to ensure
5801 * KVM is not in the middle of a lockless shadow page table walk, which
5802 * may reference the pages.
5804 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5808 * Fast invalidate all shadow pages and use lock-break technique
5809 * to zap obsolete pages.
5811 * It's required when memslot is being deleted or VM is being
5812 * destroyed, in these cases, we should ensure that KVM MMU does
5813 * not use any resource of the being-deleted slot or all slots
5814 * after calling the function.
5816 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5818 lockdep_assert_held(&kvm->slots_lock);
5820 spin_lock(&kvm->mmu_lock);
5821 trace_kvm_mmu_zap_all_fast(kvm);
5824 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5825 * held for the entire duration of zapping obsolete pages, it's
5826 * impossible for there to be multiple invalid generations associated
5827 * with *valid* shadow pages at any given time, i.e. there is exactly
5828 * one valid generation and (at most) one invalid generation.
5830 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5833 * Notify all vcpus to reload its shadow page table and flush TLB.
5834 * Then all vcpus will switch to new shadow page table with the new
5837 * Note: we need to do this under the protection of mmu_lock,
5838 * otherwise, vcpu would purge shadow page but miss tlb flush.
5840 kvm_reload_remote_mmus(kvm);
5842 kvm_zap_obsolete_pages(kvm);
5843 spin_unlock(&kvm->mmu_lock);
5846 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5848 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5851 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5852 struct kvm_memory_slot *slot,
5853 struct kvm_page_track_notifier_node *node)
5855 kvm_mmu_zap_all_fast(kvm);
5858 void kvm_mmu_init_vm(struct kvm *kvm)
5860 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5862 node->track_write = kvm_mmu_pte_write;
5863 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5864 kvm_page_track_register_notifier(kvm, node);
5867 void kvm_mmu_uninit_vm(struct kvm *kvm)
5869 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5871 kvm_page_track_unregister_notifier(kvm, node);
5874 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5876 struct kvm_memslots *slots;
5877 struct kvm_memory_slot *memslot;
5880 spin_lock(&kvm->mmu_lock);
5881 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5882 slots = __kvm_memslots(kvm, i);
5883 kvm_for_each_memslot(memslot, slots) {
5886 start = max(gfn_start, memslot->base_gfn);
5887 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5891 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5893 KVM_MAX_HUGEPAGE_LEVEL,
5894 start, end - 1, true);
5898 spin_unlock(&kvm->mmu_lock);
5901 static bool slot_rmap_write_protect(struct kvm *kvm,
5902 struct kvm_rmap_head *rmap_head)
5904 return __rmap_write_protect(kvm, rmap_head, false);
5907 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5908 struct kvm_memory_slot *memslot,
5913 spin_lock(&kvm->mmu_lock);
5914 flush = slot_handle_level(kvm, memslot, slot_rmap_write_protect,
5915 start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
5916 spin_unlock(&kvm->mmu_lock);
5919 * We can flush all the TLBs out of the mmu lock without TLB
5920 * corruption since we just change the spte from writable to
5921 * readonly so that we only need to care the case of changing
5922 * spte from present to present (changing the spte from present
5923 * to nonpresent will flush all the TLBs immediately), in other
5924 * words, the only case we care is mmu_spte_update() where we
5925 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5926 * instead of PT_WRITABLE_MASK, that means it does not depend
5927 * on PT_WRITABLE_MASK anymore.
5930 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5933 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5934 struct kvm_rmap_head *rmap_head)
5937 struct rmap_iterator iter;
5938 int need_tlb_flush = 0;
5940 struct kvm_mmu_page *sp;
5943 for_each_rmap_spte(rmap_head, &iter, sptep) {
5944 sp = sptep_to_sp(sptep);
5945 pfn = spte_to_pfn(*sptep);
5948 * We cannot do huge page mapping for indirect shadow pages,
5949 * which are found on the last rmap (level = 1) when not using
5950 * tdp; such shadow pages are synced with the page table in
5951 * the guest, and the guest page table is using 4K page size
5952 * mapping if the indirect sp has level = 1.
5954 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5955 (kvm_is_zone_device_pfn(pfn) ||
5956 PageCompound(pfn_to_page(pfn)))) {
5957 pte_list_remove(rmap_head, sptep);
5959 if (kvm_available_flush_tlb_with_range())
5960 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5961 KVM_PAGES_PER_HPAGE(sp->role.level));
5969 return need_tlb_flush;
5972 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5973 const struct kvm_memory_slot *memslot)
5975 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5976 spin_lock(&kvm->mmu_lock);
5977 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5978 kvm_mmu_zap_collapsible_spte, true);
5979 spin_unlock(&kvm->mmu_lock);
5982 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
5983 struct kvm_memory_slot *memslot)
5986 * All current use cases for flushing the TLBs for a specific memslot
5987 * are related to dirty logging, and do the TLB flush out of mmu_lock.
5988 * The interaction between the various operations on memslot must be
5989 * serialized by slots_locks to ensure the TLB flush from one operation
5990 * is observed by any other operation on the same memslot.
5992 lockdep_assert_held(&kvm->slots_lock);
5993 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5997 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5998 struct kvm_memory_slot *memslot)
6002 spin_lock(&kvm->mmu_lock);
6003 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
6004 spin_unlock(&kvm->mmu_lock);
6007 * It's also safe to flush TLBs out of mmu lock here as currently this
6008 * function is only used for dirty logging, in which case flushing TLB
6009 * out of mmu lock also guarantees no dirty pages will be lost in
6013 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6015 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
6017 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
6018 struct kvm_memory_slot *memslot)
6022 spin_lock(&kvm->mmu_lock);
6023 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
6025 spin_unlock(&kvm->mmu_lock);
6028 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6030 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
6032 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
6033 struct kvm_memory_slot *memslot)
6037 spin_lock(&kvm->mmu_lock);
6038 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
6039 spin_unlock(&kvm->mmu_lock);
6042 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6044 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
6046 void kvm_mmu_zap_all(struct kvm *kvm)
6048 struct kvm_mmu_page *sp, *node;
6049 LIST_HEAD(invalid_list);
6052 spin_lock(&kvm->mmu_lock);
6054 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6055 if (WARN_ON(sp->role.invalid))
6057 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6059 if (cond_resched_lock(&kvm->mmu_lock))
6063 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6064 spin_unlock(&kvm->mmu_lock);
6067 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6069 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6071 gen &= MMIO_SPTE_GEN_MASK;
6074 * Generation numbers are incremented in multiples of the number of
6075 * address spaces in order to provide unique generations across all
6076 * address spaces. Strip what is effectively the address space
6077 * modifier prior to checking for a wrap of the MMIO generation so
6078 * that a wrap in any address space is detected.
6080 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6083 * The very rare case: if the MMIO generation number has wrapped,
6084 * zap all shadow pages.
6086 if (unlikely(gen == 0)) {
6087 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6088 kvm_mmu_zap_all_fast(kvm);
6092 static unsigned long
6093 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6096 int nr_to_scan = sc->nr_to_scan;
6097 unsigned long freed = 0;
6099 mutex_lock(&kvm_lock);
6101 list_for_each_entry(kvm, &vm_list, vm_list) {
6103 LIST_HEAD(invalid_list);
6106 * Never scan more than sc->nr_to_scan VM instances.
6107 * Will not hit this condition practically since we do not try
6108 * to shrink more than one VM and it is very unlikely to see
6109 * !n_used_mmu_pages so many times.
6114 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6115 * here. We may skip a VM instance errorneosly, but we do not
6116 * want to shrink a VM that only started to populate its MMU
6119 if (!kvm->arch.n_used_mmu_pages &&
6120 !kvm_has_zapped_obsolete_pages(kvm))
6123 idx = srcu_read_lock(&kvm->srcu);
6124 spin_lock(&kvm->mmu_lock);
6126 if (kvm_has_zapped_obsolete_pages(kvm)) {
6127 kvm_mmu_commit_zap_page(kvm,
6128 &kvm->arch.zapped_obsolete_pages);
6132 freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6135 spin_unlock(&kvm->mmu_lock);
6136 srcu_read_unlock(&kvm->srcu, idx);
6139 * unfair on small ones
6140 * per-vm shrinkers cry out
6141 * sadness comes quickly
6143 list_move_tail(&kvm->vm_list, &vm_list);
6147 mutex_unlock(&kvm_lock);
6151 static unsigned long
6152 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6154 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6157 static struct shrinker mmu_shrinker = {
6158 .count_objects = mmu_shrink_count,
6159 .scan_objects = mmu_shrink_scan,
6160 .seeks = DEFAULT_SEEKS * 10,
6163 static void mmu_destroy_caches(void)
6165 kmem_cache_destroy(pte_list_desc_cache);
6166 kmem_cache_destroy(mmu_page_header_cache);
6169 static void kvm_set_mmio_spte_mask(void)
6174 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
6175 * PFEC.RSVD=1 on MMIO accesses. 64-bit PTEs (PAE, x86-64, and EPT
6176 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
6177 * 52-bit physical addresses then there are no reserved PA bits in the
6178 * PTEs and so the reserved PA approach must be disabled.
6180 if (shadow_phys_bits < 52)
6181 mask = BIT_ULL(51) | PT_PRESENT_MASK;
6185 kvm_mmu_set_mmio_spte_mask(mask, ACC_WRITE_MASK | ACC_USER_MASK);
6188 static bool get_nx_auto_mode(void)
6190 /* Return true when CPU has the bug, and mitigations are ON */
6191 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6194 static void __set_nx_huge_pages(bool val)
6196 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6199 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6201 bool old_val = nx_huge_pages;
6204 /* In "auto" mode deploy workaround only if CPU has the bug. */
6205 if (sysfs_streq(val, "off"))
6207 else if (sysfs_streq(val, "force"))
6209 else if (sysfs_streq(val, "auto"))
6210 new_val = get_nx_auto_mode();
6211 else if (strtobool(val, &new_val) < 0)
6214 __set_nx_huge_pages(new_val);
6216 if (new_val != old_val) {
6219 mutex_lock(&kvm_lock);
6221 list_for_each_entry(kvm, &vm_list, vm_list) {
6222 mutex_lock(&kvm->slots_lock);
6223 kvm_mmu_zap_all_fast(kvm);
6224 mutex_unlock(&kvm->slots_lock);
6226 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6228 mutex_unlock(&kvm_lock);
6234 int kvm_mmu_module_init(void)
6238 if (nx_huge_pages == -1)
6239 __set_nx_huge_pages(get_nx_auto_mode());
6242 * MMU roles use union aliasing which is, generally speaking, an
6243 * undefined behavior. However, we supposedly know how compilers behave
6244 * and the current status quo is unlikely to change. Guardians below are
6245 * supposed to let us know if the assumption becomes false.
6247 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6248 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6249 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6251 kvm_mmu_reset_all_pte_masks();
6253 kvm_set_mmio_spte_mask();
6255 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6256 sizeof(struct pte_list_desc),
6257 0, SLAB_ACCOUNT, NULL);
6258 if (!pte_list_desc_cache)
6261 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6262 sizeof(struct kvm_mmu_page),
6263 0, SLAB_ACCOUNT, NULL);
6264 if (!mmu_page_header_cache)
6267 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6270 ret = register_shrinker(&mmu_shrinker);
6277 mmu_destroy_caches();
6282 * Calculate mmu pages needed for kvm.
6284 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6286 unsigned long nr_mmu_pages;
6287 unsigned long nr_pages = 0;
6288 struct kvm_memslots *slots;
6289 struct kvm_memory_slot *memslot;
6292 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6293 slots = __kvm_memslots(kvm, i);
6295 kvm_for_each_memslot(memslot, slots)
6296 nr_pages += memslot->npages;
6299 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6300 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6302 return nr_mmu_pages;
6305 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6307 kvm_mmu_unload(vcpu);
6308 free_mmu_pages(&vcpu->arch.root_mmu);
6309 free_mmu_pages(&vcpu->arch.guest_mmu);
6310 mmu_free_memory_caches(vcpu);
6313 void kvm_mmu_module_exit(void)
6315 mmu_destroy_caches();
6316 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6317 unregister_shrinker(&mmu_shrinker);
6318 mmu_audit_disable();
6321 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6323 unsigned int old_val;
6326 old_val = nx_huge_pages_recovery_ratio;
6327 err = param_set_uint(val, kp);
6331 if (READ_ONCE(nx_huge_pages) &&
6332 !old_val && nx_huge_pages_recovery_ratio) {
6335 mutex_lock(&kvm_lock);
6337 list_for_each_entry(kvm, &vm_list, vm_list)
6338 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6340 mutex_unlock(&kvm_lock);
6346 static void kvm_recover_nx_lpages(struct kvm *kvm)
6349 struct kvm_mmu_page *sp;
6351 LIST_HEAD(invalid_list);
6354 rcu_idx = srcu_read_lock(&kvm->srcu);
6355 spin_lock(&kvm->mmu_lock);
6357 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6358 to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
6359 while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
6361 * We use a separate list instead of just using active_mmu_pages
6362 * because the number of lpage_disallowed pages is expected to
6363 * be relatively small compared to the total.
6365 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6366 struct kvm_mmu_page,
6367 lpage_disallowed_link);
6368 WARN_ON_ONCE(!sp->lpage_disallowed);
6369 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6370 WARN_ON_ONCE(sp->lpage_disallowed);
6372 if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
6373 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6375 cond_resched_lock(&kvm->mmu_lock);
6379 spin_unlock(&kvm->mmu_lock);
6380 srcu_read_unlock(&kvm->srcu, rcu_idx);
6383 static long get_nx_lpage_recovery_timeout(u64 start_time)
6385 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6386 ? start_time + 60 * HZ - get_jiffies_64()
6387 : MAX_SCHEDULE_TIMEOUT;
6390 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6393 long remaining_time;
6396 start_time = get_jiffies_64();
6397 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6399 set_current_state(TASK_INTERRUPTIBLE);
6400 while (!kthread_should_stop() && remaining_time > 0) {
6401 schedule_timeout(remaining_time);
6402 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6403 set_current_state(TASK_INTERRUPTIBLE);
6406 set_current_state(TASK_RUNNING);
6408 if (kthread_should_stop())
6411 kvm_recover_nx_lpages(kvm);
6415 int kvm_mmu_post_init_vm(struct kvm *kvm)
6419 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6420 "kvm-nx-lpage-recovery",
6421 &kvm->arch.nx_lpage_recovery_thread);
6423 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6428 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6430 if (kvm->arch.nx_lpage_recovery_thread)
6431 kthread_stop(kvm->arch.nx_lpage_recovery_thread);