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 "kvm_cache_regs.h"
24 #include <linux/kvm_host.h>
25 #include <linux/types.h>
26 #include <linux/string.h>
28 #include <linux/highmem.h>
29 #include <linux/moduleparam.h>
30 #include <linux/export.h>
31 #include <linux/swap.h>
32 #include <linux/hugetlb.h>
33 #include <linux/compiler.h>
34 #include <linux/srcu.h>
35 #include <linux/slab.h>
36 #include <linux/sched/signal.h>
37 #include <linux/uaccess.h>
38 #include <linux/hash.h>
39 #include <linux/kern_levels.h>
40 #include <linux/kthread.h>
44 #include <asm/cmpxchg.h>
45 #include <asm/e820/api.h>
48 #include <asm/kvm_page_track.h>
51 extern bool itlb_multihit_kvm_mitigation;
53 static int __read_mostly nx_huge_pages = -1;
54 #ifdef CONFIG_PREEMPT_RT
55 /* Recovery can cause latency spikes, disable it for PREEMPT_RT. */
56 static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
58 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
61 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
62 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp);
64 static struct kernel_param_ops nx_huge_pages_ops = {
65 .set = set_nx_huge_pages,
66 .get = param_get_bool,
69 static struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
70 .set = set_nx_huge_pages_recovery_ratio,
71 .get = param_get_uint,
74 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
75 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
76 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
77 &nx_huge_pages_recovery_ratio, 0644);
78 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
81 * When setting this variable to true it enables Two-Dimensional-Paging
82 * where the hardware walks 2 page tables:
83 * 1. the guest-virtual to guest-physical
84 * 2. while doing 1. it walks guest-physical to host-physical
85 * If the hardware supports that we don't need to do shadow paging.
87 bool tdp_enabled = false;
91 AUDIT_POST_PAGE_FAULT,
102 module_param(dbg, bool, 0644);
104 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
105 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
106 #define MMU_WARN_ON(x) WARN_ON(x)
108 #define pgprintk(x...) do { } while (0)
109 #define rmap_printk(x...) do { } while (0)
110 #define MMU_WARN_ON(x) do { } while (0)
113 #define PTE_PREFETCH_NUM 8
115 #define PT_FIRST_AVAIL_BITS_SHIFT 10
116 #define PT64_SECOND_AVAIL_BITS_SHIFT 54
119 * The mask used to denote special SPTEs, which can be either MMIO SPTEs or
120 * Access Tracking SPTEs.
122 #define SPTE_SPECIAL_MASK (3ULL << 52)
123 #define SPTE_AD_ENABLED_MASK (0ULL << 52)
124 #define SPTE_AD_DISABLED_MASK (1ULL << 52)
125 #define SPTE_AD_WRPROT_ONLY_MASK (2ULL << 52)
126 #define SPTE_MMIO_MASK (3ULL << 52)
128 #define PT64_LEVEL_BITS 9
130 #define PT64_LEVEL_SHIFT(level) \
131 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
133 #define PT64_INDEX(address, level)\
134 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
137 #define PT32_LEVEL_BITS 10
139 #define PT32_LEVEL_SHIFT(level) \
140 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
142 #define PT32_LVL_OFFSET_MASK(level) \
143 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
144 * PT32_LEVEL_BITS))) - 1))
146 #define PT32_INDEX(address, level)\
147 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
150 #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
151 #define PT64_BASE_ADDR_MASK (physical_mask & ~(u64)(PAGE_SIZE-1))
153 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
155 #define PT64_LVL_ADDR_MASK(level) \
156 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
157 * PT64_LEVEL_BITS))) - 1))
158 #define PT64_LVL_OFFSET_MASK(level) \
159 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
160 * PT64_LEVEL_BITS))) - 1))
162 #define PT32_BASE_ADDR_MASK PAGE_MASK
163 #define PT32_DIR_BASE_ADDR_MASK \
164 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
165 #define PT32_LVL_ADDR_MASK(level) \
166 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
167 * PT32_LEVEL_BITS))) - 1))
169 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
170 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
172 #define ACC_EXEC_MASK 1
173 #define ACC_WRITE_MASK PT_WRITABLE_MASK
174 #define ACC_USER_MASK PT_USER_MASK
175 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
177 /* The mask for the R/X bits in EPT PTEs */
178 #define PT64_EPT_READABLE_MASK 0x1ull
179 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
181 #include <trace/events/kvm.h>
183 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
184 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
186 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
188 /* make pte_list_desc fit well in cache line */
189 #define PTE_LIST_EXT 3
192 * Return values of handle_mmio_page_fault and mmu.page_fault:
193 * RET_PF_RETRY: let CPU fault again on the address.
194 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
196 * For handle_mmio_page_fault only:
197 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
205 struct pte_list_desc {
206 u64 *sptes[PTE_LIST_EXT];
207 struct pte_list_desc *more;
210 struct kvm_shadow_walk_iterator {
218 static const union kvm_mmu_page_role mmu_base_role_mask = {
220 .gpte_is_8_bytes = 1,
229 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
230 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
232 shadow_walk_okay(&(_walker)); \
233 shadow_walk_next(&(_walker)))
235 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
236 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
237 shadow_walk_okay(&(_walker)); \
238 shadow_walk_next(&(_walker)))
240 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
241 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
242 shadow_walk_okay(&(_walker)) && \
243 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
244 __shadow_walk_next(&(_walker), spte))
246 static struct kmem_cache *pte_list_desc_cache;
247 static struct kmem_cache *mmu_page_header_cache;
248 static struct percpu_counter kvm_total_used_mmu_pages;
250 static u64 __read_mostly shadow_nx_mask;
251 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
252 static u64 __read_mostly shadow_user_mask;
253 static u64 __read_mostly shadow_accessed_mask;
254 static u64 __read_mostly shadow_dirty_mask;
255 static u64 __read_mostly shadow_mmio_mask;
256 static u64 __read_mostly shadow_mmio_value;
257 static u64 __read_mostly shadow_mmio_access_mask;
258 static u64 __read_mostly shadow_present_mask;
259 static u64 __read_mostly shadow_me_mask;
262 * SPTEs used by MMUs without A/D bits are marked with SPTE_AD_DISABLED_MASK;
263 * shadow_acc_track_mask is the set of bits to be cleared in non-accessed
266 static u64 __read_mostly shadow_acc_track_mask;
269 * The mask/shift to use for saving the original R/X bits when marking the PTE
270 * as not-present for access tracking purposes. We do not save the W bit as the
271 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
272 * restored only when a write is attempted to the page.
274 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
275 PT64_EPT_EXECUTABLE_MASK;
276 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
279 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
280 * to guard against L1TF attacks.
282 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
285 * The number of high-order 1 bits to use in the mask above.
287 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
290 * In some cases, we need to preserve the GFN of a non-present or reserved
291 * SPTE when we usurp the upper five bits of the physical address space to
292 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
293 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
294 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
295 * high and low parts. This mask covers the lower bits of the GFN.
297 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
300 * The number of non-reserved physical address bits irrespective of features
301 * that repurpose legal bits, e.g. MKTME.
303 static u8 __read_mostly shadow_phys_bits;
305 static void mmu_spte_set(u64 *sptep, u64 spte);
306 static bool is_executable_pte(u64 spte);
307 static union kvm_mmu_page_role
308 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
310 #define CREATE_TRACE_POINTS
311 #include "mmutrace.h"
314 static inline bool kvm_available_flush_tlb_with_range(void)
316 return kvm_x86_ops->tlb_remote_flush_with_range;
319 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
320 struct kvm_tlb_range *range)
324 if (range && kvm_x86_ops->tlb_remote_flush_with_range)
325 ret = kvm_x86_ops->tlb_remote_flush_with_range(kvm, range);
328 kvm_flush_remote_tlbs(kvm);
331 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
332 u64 start_gfn, u64 pages)
334 struct kvm_tlb_range range;
336 range.start_gfn = start_gfn;
339 kvm_flush_remote_tlbs_with_range(kvm, &range);
342 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value, u64 access_mask)
344 BUG_ON((u64)(unsigned)access_mask != access_mask);
345 BUG_ON((mmio_mask & mmio_value) != mmio_value);
346 shadow_mmio_value = mmio_value | SPTE_MMIO_MASK;
347 shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
348 shadow_mmio_access_mask = access_mask;
350 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
352 static bool is_mmio_spte(u64 spte)
354 return (spte & shadow_mmio_mask) == shadow_mmio_value;
357 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
359 return sp->role.ad_disabled;
362 static inline bool kvm_vcpu_ad_need_write_protect(struct kvm_vcpu *vcpu)
365 * When using the EPT page-modification log, the GPAs in the log
366 * would come from L2 rather than L1. Therefore, we need to rely
367 * on write protection to record dirty pages. This also bypasses
368 * PML, since writes now result in a vmexit.
370 return vcpu->arch.mmu == &vcpu->arch.guest_mmu;
373 static inline bool spte_ad_enabled(u64 spte)
375 MMU_WARN_ON(is_mmio_spte(spte));
376 return (spte & SPTE_SPECIAL_MASK) != SPTE_AD_DISABLED_MASK;
379 static inline bool spte_ad_need_write_protect(u64 spte)
381 MMU_WARN_ON(is_mmio_spte(spte));
382 return (spte & SPTE_SPECIAL_MASK) != SPTE_AD_ENABLED_MASK;
385 static bool is_nx_huge_page_enabled(void)
387 return READ_ONCE(nx_huge_pages);
390 static inline u64 spte_shadow_accessed_mask(u64 spte)
392 MMU_WARN_ON(is_mmio_spte(spte));
393 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
396 static inline u64 spte_shadow_dirty_mask(u64 spte)
398 MMU_WARN_ON(is_mmio_spte(spte));
399 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
402 static inline bool is_access_track_spte(u64 spte)
404 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
408 * Due to limited space in PTEs, the MMIO generation is a 19 bit subset of
409 * the memslots generation and is derived as follows:
411 * Bits 0-8 of the MMIO generation are propagated to spte bits 3-11
412 * Bits 9-18 of the MMIO generation are propagated to spte bits 52-61
414 * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
415 * the MMIO generation number, as doing so would require stealing a bit from
416 * the "real" generation number and thus effectively halve the maximum number
417 * of MMIO generations that can be handled before encountering a wrap (which
418 * requires a full MMU zap). The flag is instead explicitly queried when
419 * checking for MMIO spte cache hits.
421 #define MMIO_SPTE_GEN_MASK GENMASK_ULL(18, 0)
423 #define MMIO_SPTE_GEN_LOW_START 3
424 #define MMIO_SPTE_GEN_LOW_END 11
425 #define MMIO_SPTE_GEN_LOW_MASK GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
426 MMIO_SPTE_GEN_LOW_START)
428 #define MMIO_SPTE_GEN_HIGH_START 52
429 #define MMIO_SPTE_GEN_HIGH_END 61
430 #define MMIO_SPTE_GEN_HIGH_MASK GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
431 MMIO_SPTE_GEN_HIGH_START)
432 static u64 generation_mmio_spte_mask(u64 gen)
436 WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
438 mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
439 mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
443 static u64 get_mmio_spte_generation(u64 spte)
447 spte &= ~shadow_mmio_mask;
449 gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
450 gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
454 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
457 u64 gen = kvm_vcpu_memslots(vcpu)->generation & MMIO_SPTE_GEN_MASK;
458 u64 mask = generation_mmio_spte_mask(gen);
459 u64 gpa = gfn << PAGE_SHIFT;
461 access &= shadow_mmio_access_mask;
462 mask |= shadow_mmio_value | access;
463 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
464 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
465 << shadow_nonpresent_or_rsvd_mask_len;
467 trace_mark_mmio_spte(sptep, gfn, access, gen);
468 mmu_spte_set(sptep, mask);
471 static gfn_t get_mmio_spte_gfn(u64 spte)
473 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
475 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
476 & shadow_nonpresent_or_rsvd_mask;
478 return gpa >> PAGE_SHIFT;
481 static unsigned get_mmio_spte_access(u64 spte)
483 return spte & shadow_mmio_access_mask;
486 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
487 kvm_pfn_t pfn, unsigned access)
489 if (unlikely(is_noslot_pfn(pfn))) {
490 mark_mmio_spte(vcpu, sptep, gfn, access);
497 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
499 u64 kvm_gen, spte_gen, gen;
501 gen = kvm_vcpu_memslots(vcpu)->generation;
502 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
505 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
506 spte_gen = get_mmio_spte_generation(spte);
508 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
509 return likely(kvm_gen == spte_gen);
513 * Sets the shadow PTE masks used by the MMU.
516 * - Setting either @accessed_mask or @dirty_mask requires setting both
517 * - At least one of @accessed_mask or @acc_track_mask must be set
519 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
520 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
521 u64 acc_track_mask, u64 me_mask)
523 BUG_ON(!dirty_mask != !accessed_mask);
524 BUG_ON(!accessed_mask && !acc_track_mask);
525 BUG_ON(acc_track_mask & SPTE_SPECIAL_MASK);
527 shadow_user_mask = user_mask;
528 shadow_accessed_mask = accessed_mask;
529 shadow_dirty_mask = dirty_mask;
530 shadow_nx_mask = nx_mask;
531 shadow_x_mask = x_mask;
532 shadow_present_mask = p_mask;
533 shadow_acc_track_mask = acc_track_mask;
534 shadow_me_mask = me_mask;
536 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
538 static u8 kvm_get_shadow_phys_bits(void)
541 * boot_cpu_data.x86_phys_bits is reduced when MKTME or SME are detected
542 * in CPU detection code, but the processor treats those reduced bits as
543 * 'keyID' thus they are not reserved bits. Therefore KVM needs to look at
544 * the physical address bits reported by CPUID.
546 if (likely(boot_cpu_data.extended_cpuid_level >= 0x80000008))
547 return cpuid_eax(0x80000008) & 0xff;
550 * Quite weird to have VMX or SVM but not MAXPHYADDR; probably a VM with
551 * custom CPUID. Proceed with whatever the kernel found since these features
552 * aren't virtualizable (SME/SEV also require CPUIDs higher than 0x80000008).
554 return boot_cpu_data.x86_phys_bits;
557 static void kvm_mmu_reset_all_pte_masks(void)
561 shadow_user_mask = 0;
562 shadow_accessed_mask = 0;
563 shadow_dirty_mask = 0;
566 shadow_mmio_mask = 0;
567 shadow_present_mask = 0;
568 shadow_acc_track_mask = 0;
570 shadow_phys_bits = kvm_get_shadow_phys_bits();
573 * If the CPU has 46 or less physical address bits, then set an
574 * appropriate mask to guard against L1TF attacks. Otherwise, it is
575 * assumed that the CPU is not vulnerable to L1TF.
577 * Some Intel CPUs address the L1 cache using more PA bits than are
578 * reported by CPUID. Use the PA width of the L1 cache when possible
579 * to achieve more effective mitigation, e.g. if system RAM overlaps
580 * the most significant bits of legal physical address space.
582 shadow_nonpresent_or_rsvd_mask = 0;
583 low_phys_bits = boot_cpu_data.x86_cache_bits;
584 if (boot_cpu_data.x86_cache_bits <
585 52 - shadow_nonpresent_or_rsvd_mask_len) {
586 shadow_nonpresent_or_rsvd_mask =
587 rsvd_bits(boot_cpu_data.x86_cache_bits -
588 shadow_nonpresent_or_rsvd_mask_len,
589 boot_cpu_data.x86_cache_bits - 1);
590 low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
592 WARN_ON_ONCE(boot_cpu_has_bug(X86_BUG_L1TF));
594 shadow_nonpresent_or_rsvd_lower_gfn_mask =
595 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
598 static int is_cpuid_PSE36(void)
603 static int is_nx(struct kvm_vcpu *vcpu)
605 return vcpu->arch.efer & EFER_NX;
608 static int is_shadow_present_pte(u64 pte)
610 return (pte != 0) && !is_mmio_spte(pte);
613 static int is_large_pte(u64 pte)
615 return pte & PT_PAGE_SIZE_MASK;
618 static int is_last_spte(u64 pte, int level)
620 if (level == PT_PAGE_TABLE_LEVEL)
622 if (is_large_pte(pte))
627 static bool is_executable_pte(u64 spte)
629 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
632 static kvm_pfn_t spte_to_pfn(u64 pte)
634 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
637 static gfn_t pse36_gfn_delta(u32 gpte)
639 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
641 return (gpte & PT32_DIR_PSE36_MASK) << shift;
645 static void __set_spte(u64 *sptep, u64 spte)
647 WRITE_ONCE(*sptep, spte);
650 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
652 WRITE_ONCE(*sptep, spte);
655 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
657 return xchg(sptep, spte);
660 static u64 __get_spte_lockless(u64 *sptep)
662 return READ_ONCE(*sptep);
673 static void count_spte_clear(u64 *sptep, u64 spte)
675 struct kvm_mmu_page *sp = page_header(__pa(sptep));
677 if (is_shadow_present_pte(spte))
680 /* Ensure the spte is completely set before we increase the count */
682 sp->clear_spte_count++;
685 static void __set_spte(u64 *sptep, u64 spte)
687 union split_spte *ssptep, sspte;
689 ssptep = (union split_spte *)sptep;
690 sspte = (union split_spte)spte;
692 ssptep->spte_high = sspte.spte_high;
695 * If we map the spte from nonpresent to present, We should store
696 * the high bits firstly, then set present bit, so cpu can not
697 * fetch this spte while we are setting the spte.
701 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
704 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
706 union split_spte *ssptep, sspte;
708 ssptep = (union split_spte *)sptep;
709 sspte = (union split_spte)spte;
711 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
714 * If we map the spte from present to nonpresent, we should clear
715 * present bit firstly to avoid vcpu fetch the old high bits.
719 ssptep->spte_high = sspte.spte_high;
720 count_spte_clear(sptep, spte);
723 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
725 union split_spte *ssptep, sspte, orig;
727 ssptep = (union split_spte *)sptep;
728 sspte = (union split_spte)spte;
730 /* xchg acts as a barrier before the setting of the high bits */
731 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
732 orig.spte_high = ssptep->spte_high;
733 ssptep->spte_high = sspte.spte_high;
734 count_spte_clear(sptep, spte);
740 * The idea using the light way get the spte on x86_32 guest is from
741 * gup_get_pte (mm/gup.c).
743 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
744 * coalesces them and we are running out of the MMU lock. Therefore
745 * we need to protect against in-progress updates of the spte.
747 * Reading the spte while an update is in progress may get the old value
748 * for the high part of the spte. The race is fine for a present->non-present
749 * change (because the high part of the spte is ignored for non-present spte),
750 * but for a present->present change we must reread the spte.
752 * All such changes are done in two steps (present->non-present and
753 * non-present->present), hence it is enough to count the number of
754 * present->non-present updates: if it changed while reading the spte,
755 * we might have hit the race. This is done using clear_spte_count.
757 static u64 __get_spte_lockless(u64 *sptep)
759 struct kvm_mmu_page *sp = page_header(__pa(sptep));
760 union split_spte spte, *orig = (union split_spte *)sptep;
764 count = sp->clear_spte_count;
767 spte.spte_low = orig->spte_low;
770 spte.spte_high = orig->spte_high;
773 if (unlikely(spte.spte_low != orig->spte_low ||
774 count != sp->clear_spte_count))
781 static bool spte_can_locklessly_be_made_writable(u64 spte)
783 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
784 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
787 static bool spte_has_volatile_bits(u64 spte)
789 if (!is_shadow_present_pte(spte))
793 * Always atomically update spte if it can be updated
794 * out of mmu-lock, it can ensure dirty bit is not lost,
795 * also, it can help us to get a stable is_writable_pte()
796 * to ensure tlb flush is not missed.
798 if (spte_can_locklessly_be_made_writable(spte) ||
799 is_access_track_spte(spte))
802 if (spte_ad_enabled(spte)) {
803 if ((spte & shadow_accessed_mask) == 0 ||
804 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
811 static bool is_accessed_spte(u64 spte)
813 u64 accessed_mask = spte_shadow_accessed_mask(spte);
815 return accessed_mask ? spte & accessed_mask
816 : !is_access_track_spte(spte);
819 static bool is_dirty_spte(u64 spte)
821 u64 dirty_mask = spte_shadow_dirty_mask(spte);
823 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
826 /* Rules for using mmu_spte_set:
827 * Set the sptep from nonpresent to present.
828 * Note: the sptep being assigned *must* be either not present
829 * or in a state where the hardware will not attempt to update
832 static void mmu_spte_set(u64 *sptep, u64 new_spte)
834 WARN_ON(is_shadow_present_pte(*sptep));
835 __set_spte(sptep, new_spte);
839 * Update the SPTE (excluding the PFN), but do not track changes in its
840 * accessed/dirty status.
842 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
844 u64 old_spte = *sptep;
846 WARN_ON(!is_shadow_present_pte(new_spte));
848 if (!is_shadow_present_pte(old_spte)) {
849 mmu_spte_set(sptep, new_spte);
853 if (!spte_has_volatile_bits(old_spte))
854 __update_clear_spte_fast(sptep, new_spte);
856 old_spte = __update_clear_spte_slow(sptep, new_spte);
858 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
863 /* Rules for using mmu_spte_update:
864 * Update the state bits, it means the mapped pfn is not changed.
866 * Whenever we overwrite a writable spte with a read-only one we
867 * should flush remote TLBs. Otherwise rmap_write_protect
868 * will find a read-only spte, even though the writable spte
869 * might be cached on a CPU's TLB, the return value indicates this
872 * Returns true if the TLB needs to be flushed
874 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
877 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
879 if (!is_shadow_present_pte(old_spte))
883 * For the spte updated out of mmu-lock is safe, since
884 * we always atomically update it, see the comments in
885 * spte_has_volatile_bits().
887 if (spte_can_locklessly_be_made_writable(old_spte) &&
888 !is_writable_pte(new_spte))
892 * Flush TLB when accessed/dirty states are changed in the page tables,
893 * to guarantee consistency between TLB and page tables.
896 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
898 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
901 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
903 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
910 * Rules for using mmu_spte_clear_track_bits:
911 * It sets the sptep from present to nonpresent, and track the
912 * state bits, it is used to clear the last level sptep.
913 * Returns non-zero if the PTE was previously valid.
915 static int mmu_spte_clear_track_bits(u64 *sptep)
918 u64 old_spte = *sptep;
920 if (!spte_has_volatile_bits(old_spte))
921 __update_clear_spte_fast(sptep, 0ull);
923 old_spte = __update_clear_spte_slow(sptep, 0ull);
925 if (!is_shadow_present_pte(old_spte))
928 pfn = spte_to_pfn(old_spte);
931 * KVM does not hold the refcount of the page used by
932 * kvm mmu, before reclaiming the page, we should
933 * unmap it from mmu first.
935 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
937 if (is_accessed_spte(old_spte))
938 kvm_set_pfn_accessed(pfn);
940 if (is_dirty_spte(old_spte))
941 kvm_set_pfn_dirty(pfn);
947 * Rules for using mmu_spte_clear_no_track:
948 * Directly clear spte without caring the state bits of sptep,
949 * it is used to set the upper level spte.
951 static void mmu_spte_clear_no_track(u64 *sptep)
953 __update_clear_spte_fast(sptep, 0ull);
956 static u64 mmu_spte_get_lockless(u64 *sptep)
958 return __get_spte_lockless(sptep);
961 static u64 mark_spte_for_access_track(u64 spte)
963 if (spte_ad_enabled(spte))
964 return spte & ~shadow_accessed_mask;
966 if (is_access_track_spte(spte))
970 * Making an Access Tracking PTE will result in removal of write access
971 * from the PTE. So, verify that we will be able to restore the write
972 * access in the fast page fault path later on.
974 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
975 !spte_can_locklessly_be_made_writable(spte),
976 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
978 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
979 shadow_acc_track_saved_bits_shift),
980 "kvm: Access Tracking saved bit locations are not zero\n");
982 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
983 shadow_acc_track_saved_bits_shift;
984 spte &= ~shadow_acc_track_mask;
989 /* Restore an acc-track PTE back to a regular PTE */
990 static u64 restore_acc_track_spte(u64 spte)
993 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
994 & shadow_acc_track_saved_bits_mask;
996 WARN_ON_ONCE(spte_ad_enabled(spte));
997 WARN_ON_ONCE(!is_access_track_spte(spte));
999 new_spte &= ~shadow_acc_track_mask;
1000 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
1001 shadow_acc_track_saved_bits_shift);
1002 new_spte |= saved_bits;
1007 /* Returns the Accessed status of the PTE and resets it at the same time. */
1008 static bool mmu_spte_age(u64 *sptep)
1010 u64 spte = mmu_spte_get_lockless(sptep);
1012 if (!is_accessed_spte(spte))
1015 if (spte_ad_enabled(spte)) {
1016 clear_bit((ffs(shadow_accessed_mask) - 1),
1017 (unsigned long *)sptep);
1020 * Capture the dirty status of the page, so that it doesn't get
1021 * lost when the SPTE is marked for access tracking.
1023 if (is_writable_pte(spte))
1024 kvm_set_pfn_dirty(spte_to_pfn(spte));
1026 spte = mark_spte_for_access_track(spte);
1027 mmu_spte_update_no_track(sptep, spte);
1033 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
1036 * Prevent page table teardown by making any free-er wait during
1037 * kvm_flush_remote_tlbs() IPI to all active vcpus.
1039 local_irq_disable();
1042 * Make sure a following spte read is not reordered ahead of the write
1045 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
1048 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
1051 * Make sure the write to vcpu->mode is not reordered in front of
1052 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
1053 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
1055 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
1059 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
1060 struct kmem_cache *base_cache, int min)
1064 if (cache->nobjs >= min)
1066 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1067 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL_ACCOUNT);
1069 return cache->nobjs >= min ? 0 : -ENOMEM;
1070 cache->objects[cache->nobjs++] = obj;
1075 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
1077 return cache->nobjs;
1080 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
1081 struct kmem_cache *cache)
1084 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
1087 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1092 if (cache->nobjs >= min)
1094 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1095 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1097 return cache->nobjs >= min ? 0 : -ENOMEM;
1098 cache->objects[cache->nobjs++] = page;
1103 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1106 free_page((unsigned long)mc->objects[--mc->nobjs]);
1109 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1113 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1114 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1117 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1120 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1121 mmu_page_header_cache, 4);
1126 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1128 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1129 pte_list_desc_cache);
1130 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1131 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1132 mmu_page_header_cache);
1135 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1140 p = mc->objects[--mc->nobjs];
1144 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1146 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1149 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1151 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1154 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1156 if (!sp->role.direct)
1157 return sp->gfns[index];
1159 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1162 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1164 if (!sp->role.direct) {
1165 sp->gfns[index] = gfn;
1169 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1170 pr_err_ratelimited("gfn mismatch under direct page %llx "
1171 "(expected %llx, got %llx)\n",
1173 kvm_mmu_page_get_gfn(sp, index), gfn);
1177 * Return the pointer to the large page information for a given gfn,
1178 * handling slots that are not large page aligned.
1180 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1181 struct kvm_memory_slot *slot,
1186 idx = gfn_to_index(gfn, slot->base_gfn, level);
1187 return &slot->arch.lpage_info[level - 2][idx];
1190 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1191 gfn_t gfn, int count)
1193 struct kvm_lpage_info *linfo;
1196 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1197 linfo = lpage_info_slot(gfn, slot, i);
1198 linfo->disallow_lpage += count;
1199 WARN_ON(linfo->disallow_lpage < 0);
1203 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1205 update_gfn_disallow_lpage_count(slot, gfn, 1);
1208 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1210 update_gfn_disallow_lpage_count(slot, gfn, -1);
1213 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1215 struct kvm_memslots *slots;
1216 struct kvm_memory_slot *slot;
1219 kvm->arch.indirect_shadow_pages++;
1221 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1222 slot = __gfn_to_memslot(slots, gfn);
1224 /* the non-leaf shadow pages are keeping readonly. */
1225 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1226 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1227 KVM_PAGE_TRACK_WRITE);
1229 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1232 static void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1234 if (sp->lpage_disallowed)
1237 ++kvm->stat.nx_lpage_splits;
1238 list_add_tail(&sp->lpage_disallowed_link,
1239 &kvm->arch.lpage_disallowed_mmu_pages);
1240 sp->lpage_disallowed = true;
1243 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1245 struct kvm_memslots *slots;
1246 struct kvm_memory_slot *slot;
1249 kvm->arch.indirect_shadow_pages--;
1251 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1252 slot = __gfn_to_memslot(slots, gfn);
1253 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1254 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1255 KVM_PAGE_TRACK_WRITE);
1257 kvm_mmu_gfn_allow_lpage(slot, gfn);
1260 static void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1262 --kvm->stat.nx_lpage_splits;
1263 sp->lpage_disallowed = false;
1264 list_del(&sp->lpage_disallowed_link);
1267 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1268 struct kvm_memory_slot *slot)
1270 struct kvm_lpage_info *linfo;
1273 linfo = lpage_info_slot(gfn, slot, level);
1274 return !!linfo->disallow_lpage;
1280 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1283 struct kvm_memory_slot *slot;
1285 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1286 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1289 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1291 unsigned long page_size;
1294 page_size = kvm_host_page_size(kvm, gfn);
1296 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1297 if (page_size >= KVM_HPAGE_SIZE(i))
1306 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1309 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1311 if (no_dirty_log && slot->dirty_bitmap)
1317 static struct kvm_memory_slot *
1318 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1321 struct kvm_memory_slot *slot;
1323 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1324 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1330 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1331 bool *force_pt_level)
1333 int host_level, level, max_level;
1334 struct kvm_memory_slot *slot;
1336 if (unlikely(*force_pt_level))
1337 return PT_PAGE_TABLE_LEVEL;
1339 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1340 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1341 if (unlikely(*force_pt_level))
1342 return PT_PAGE_TABLE_LEVEL;
1344 host_level = host_mapping_level(vcpu->kvm, large_gfn);
1346 if (host_level == PT_PAGE_TABLE_LEVEL)
1349 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1351 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1352 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1359 * About rmap_head encoding:
1361 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1362 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1363 * pte_list_desc containing more mappings.
1367 * Returns the number of pointers in the rmap chain, not counting the new one.
1369 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1370 struct kvm_rmap_head *rmap_head)
1372 struct pte_list_desc *desc;
1375 if (!rmap_head->val) {
1376 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1377 rmap_head->val = (unsigned long)spte;
1378 } else if (!(rmap_head->val & 1)) {
1379 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1380 desc = mmu_alloc_pte_list_desc(vcpu);
1381 desc->sptes[0] = (u64 *)rmap_head->val;
1382 desc->sptes[1] = spte;
1383 rmap_head->val = (unsigned long)desc | 1;
1386 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1387 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1388 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1390 count += PTE_LIST_EXT;
1392 if (desc->sptes[PTE_LIST_EXT-1]) {
1393 desc->more = mmu_alloc_pte_list_desc(vcpu);
1396 for (i = 0; desc->sptes[i]; ++i)
1398 desc->sptes[i] = spte;
1404 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1405 struct pte_list_desc *desc, int i,
1406 struct pte_list_desc *prev_desc)
1410 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1412 desc->sptes[i] = desc->sptes[j];
1413 desc->sptes[j] = NULL;
1416 if (!prev_desc && !desc->more)
1420 prev_desc->more = desc->more;
1422 rmap_head->val = (unsigned long)desc->more | 1;
1423 mmu_free_pte_list_desc(desc);
1426 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1428 struct pte_list_desc *desc;
1429 struct pte_list_desc *prev_desc;
1432 if (!rmap_head->val) {
1433 pr_err("%s: %p 0->BUG\n", __func__, spte);
1435 } else if (!(rmap_head->val & 1)) {
1436 rmap_printk("%s: %p 1->0\n", __func__, spte);
1437 if ((u64 *)rmap_head->val != spte) {
1438 pr_err("%s: %p 1->BUG\n", __func__, spte);
1443 rmap_printk("%s: %p many->many\n", __func__, spte);
1444 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1447 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1448 if (desc->sptes[i] == spte) {
1449 pte_list_desc_remove_entry(rmap_head,
1450 desc, i, prev_desc);
1457 pr_err("%s: %p many->many\n", __func__, spte);
1462 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1464 mmu_spte_clear_track_bits(sptep);
1465 __pte_list_remove(sptep, rmap_head);
1468 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1469 struct kvm_memory_slot *slot)
1473 idx = gfn_to_index(gfn, slot->base_gfn, level);
1474 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1477 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1478 struct kvm_mmu_page *sp)
1480 struct kvm_memslots *slots;
1481 struct kvm_memory_slot *slot;
1483 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1484 slot = __gfn_to_memslot(slots, gfn);
1485 return __gfn_to_rmap(gfn, sp->role.level, slot);
1488 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1490 struct kvm_mmu_memory_cache *cache;
1492 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1493 return mmu_memory_cache_free_objects(cache);
1496 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1498 struct kvm_mmu_page *sp;
1499 struct kvm_rmap_head *rmap_head;
1501 sp = page_header(__pa(spte));
1502 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1503 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1504 return pte_list_add(vcpu, spte, rmap_head);
1507 static void rmap_remove(struct kvm *kvm, u64 *spte)
1509 struct kvm_mmu_page *sp;
1511 struct kvm_rmap_head *rmap_head;
1513 sp = page_header(__pa(spte));
1514 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1515 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1516 __pte_list_remove(spte, rmap_head);
1520 * Used by the following functions to iterate through the sptes linked by a
1521 * rmap. All fields are private and not assumed to be used outside.
1523 struct rmap_iterator {
1524 /* private fields */
1525 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1526 int pos; /* index of the sptep */
1530 * Iteration must be started by this function. This should also be used after
1531 * removing/dropping sptes from the rmap link because in such cases the
1532 * information in the iterator may not be valid.
1534 * Returns sptep if found, NULL otherwise.
1536 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1537 struct rmap_iterator *iter)
1541 if (!rmap_head->val)
1544 if (!(rmap_head->val & 1)) {
1546 sptep = (u64 *)rmap_head->val;
1550 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1552 sptep = iter->desc->sptes[iter->pos];
1554 BUG_ON(!is_shadow_present_pte(*sptep));
1559 * Must be used with a valid iterator: e.g. after rmap_get_first().
1561 * Returns sptep if found, NULL otherwise.
1563 static u64 *rmap_get_next(struct rmap_iterator *iter)
1568 if (iter->pos < PTE_LIST_EXT - 1) {
1570 sptep = iter->desc->sptes[iter->pos];
1575 iter->desc = iter->desc->more;
1579 /* desc->sptes[0] cannot be NULL */
1580 sptep = iter->desc->sptes[iter->pos];
1587 BUG_ON(!is_shadow_present_pte(*sptep));
1591 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1592 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1593 _spte_; _spte_ = rmap_get_next(_iter_))
1595 static void drop_spte(struct kvm *kvm, u64 *sptep)
1597 if (mmu_spte_clear_track_bits(sptep))
1598 rmap_remove(kvm, sptep);
1602 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1604 if (is_large_pte(*sptep)) {
1605 WARN_ON(page_header(__pa(sptep))->role.level ==
1606 PT_PAGE_TABLE_LEVEL);
1607 drop_spte(kvm, sptep);
1615 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1617 if (__drop_large_spte(vcpu->kvm, sptep)) {
1618 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1620 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1621 KVM_PAGES_PER_HPAGE(sp->role.level));
1626 * Write-protect on the specified @sptep, @pt_protect indicates whether
1627 * spte write-protection is caused by protecting shadow page table.
1629 * Note: write protection is difference between dirty logging and spte
1631 * - for dirty logging, the spte can be set to writable at anytime if
1632 * its dirty bitmap is properly set.
1633 * - for spte protection, the spte can be writable only after unsync-ing
1636 * Return true if tlb need be flushed.
1638 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1642 if (!is_writable_pte(spte) &&
1643 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1646 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1649 spte &= ~SPTE_MMU_WRITEABLE;
1650 spte = spte & ~PT_WRITABLE_MASK;
1652 return mmu_spte_update(sptep, spte);
1655 static bool __rmap_write_protect(struct kvm *kvm,
1656 struct kvm_rmap_head *rmap_head,
1660 struct rmap_iterator iter;
1663 for_each_rmap_spte(rmap_head, &iter, sptep)
1664 flush |= spte_write_protect(sptep, pt_protect);
1669 static bool spte_clear_dirty(u64 *sptep)
1673 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1675 MMU_WARN_ON(!spte_ad_enabled(spte));
1676 spte &= ~shadow_dirty_mask;
1677 return mmu_spte_update(sptep, spte);
1680 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1682 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1683 (unsigned long *)sptep);
1684 if (was_writable && !spte_ad_enabled(*sptep))
1685 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1687 return was_writable;
1691 * Gets the GFN ready for another round of dirty logging by clearing the
1692 * - D bit on ad-enabled SPTEs, and
1693 * - W bit on ad-disabled SPTEs.
1694 * Returns true iff any D or W bits were cleared.
1696 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1699 struct rmap_iterator iter;
1702 for_each_rmap_spte(rmap_head, &iter, sptep)
1703 if (spte_ad_need_write_protect(*sptep))
1704 flush |= spte_wrprot_for_clear_dirty(sptep);
1706 flush |= spte_clear_dirty(sptep);
1711 static bool spte_set_dirty(u64 *sptep)
1715 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1718 * Similar to the !kvm_x86_ops->slot_disable_log_dirty case,
1719 * do not bother adding back write access to pages marked
1720 * SPTE_AD_WRPROT_ONLY_MASK.
1722 spte |= shadow_dirty_mask;
1724 return mmu_spte_update(sptep, spte);
1727 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1730 struct rmap_iterator iter;
1733 for_each_rmap_spte(rmap_head, &iter, sptep)
1734 if (spte_ad_enabled(*sptep))
1735 flush |= spte_set_dirty(sptep);
1741 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1742 * @kvm: kvm instance
1743 * @slot: slot to protect
1744 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1745 * @mask: indicates which pages we should protect
1747 * Used when we do not need to care about huge page mappings: e.g. during dirty
1748 * logging we do not have any such mappings.
1750 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1751 struct kvm_memory_slot *slot,
1752 gfn_t gfn_offset, unsigned long mask)
1754 struct kvm_rmap_head *rmap_head;
1757 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1758 PT_PAGE_TABLE_LEVEL, slot);
1759 __rmap_write_protect(kvm, rmap_head, false);
1761 /* clear the first set bit */
1767 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1768 * protect the page if the D-bit isn't supported.
1769 * @kvm: kvm instance
1770 * @slot: slot to clear D-bit
1771 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1772 * @mask: indicates which pages we should clear D-bit
1774 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1776 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1777 struct kvm_memory_slot *slot,
1778 gfn_t gfn_offset, unsigned long mask)
1780 struct kvm_rmap_head *rmap_head;
1783 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1784 PT_PAGE_TABLE_LEVEL, slot);
1785 __rmap_clear_dirty(kvm, rmap_head);
1787 /* clear the first set bit */
1791 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1794 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1797 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1798 * enable dirty logging for them.
1800 * Used when we do not need to care about huge page mappings: e.g. during dirty
1801 * logging we do not have any such mappings.
1803 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1804 struct kvm_memory_slot *slot,
1805 gfn_t gfn_offset, unsigned long mask)
1807 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1808 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1811 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1815 * kvm_arch_write_log_dirty - emulate dirty page logging
1816 * @vcpu: Guest mode vcpu
1818 * Emulate arch specific page modification logging for the
1821 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1823 if (kvm_x86_ops->write_log_dirty)
1824 return kvm_x86_ops->write_log_dirty(vcpu);
1829 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1830 struct kvm_memory_slot *slot, u64 gfn)
1832 struct kvm_rmap_head *rmap_head;
1834 bool write_protected = false;
1836 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1837 rmap_head = __gfn_to_rmap(gfn, i, slot);
1838 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1841 return write_protected;
1844 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1846 struct kvm_memory_slot *slot;
1848 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1849 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1852 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1855 struct rmap_iterator iter;
1858 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1859 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1861 pte_list_remove(rmap_head, sptep);
1868 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1869 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1872 return kvm_zap_rmapp(kvm, rmap_head);
1875 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1876 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1880 struct rmap_iterator iter;
1883 pte_t *ptep = (pte_t *)data;
1886 WARN_ON(pte_huge(*ptep));
1887 new_pfn = pte_pfn(*ptep);
1890 for_each_rmap_spte(rmap_head, &iter, sptep) {
1891 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1892 sptep, *sptep, gfn, level);
1896 if (pte_write(*ptep)) {
1897 pte_list_remove(rmap_head, sptep);
1900 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1901 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1903 new_spte &= ~PT_WRITABLE_MASK;
1904 new_spte &= ~SPTE_HOST_WRITEABLE;
1906 new_spte = mark_spte_for_access_track(new_spte);
1908 mmu_spte_clear_track_bits(sptep);
1909 mmu_spte_set(sptep, new_spte);
1913 if (need_flush && kvm_available_flush_tlb_with_range()) {
1914 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1921 struct slot_rmap_walk_iterator {
1923 struct kvm_memory_slot *slot;
1929 /* output fields. */
1931 struct kvm_rmap_head *rmap;
1934 /* private field. */
1935 struct kvm_rmap_head *end_rmap;
1939 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1941 iterator->level = level;
1942 iterator->gfn = iterator->start_gfn;
1943 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1944 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1949 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1950 struct kvm_memory_slot *slot, int start_level,
1951 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1953 iterator->slot = slot;
1954 iterator->start_level = start_level;
1955 iterator->end_level = end_level;
1956 iterator->start_gfn = start_gfn;
1957 iterator->end_gfn = end_gfn;
1959 rmap_walk_init_level(iterator, iterator->start_level);
1962 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1964 return !!iterator->rmap;
1967 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1969 if (++iterator->rmap <= iterator->end_rmap) {
1970 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1974 if (++iterator->level > iterator->end_level) {
1975 iterator->rmap = NULL;
1979 rmap_walk_init_level(iterator, iterator->level);
1982 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1983 _start_gfn, _end_gfn, _iter_) \
1984 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1985 _end_level_, _start_gfn, _end_gfn); \
1986 slot_rmap_walk_okay(_iter_); \
1987 slot_rmap_walk_next(_iter_))
1989 static int kvm_handle_hva_range(struct kvm *kvm,
1990 unsigned long start,
1993 int (*handler)(struct kvm *kvm,
1994 struct kvm_rmap_head *rmap_head,
1995 struct kvm_memory_slot *slot,
1998 unsigned long data))
2000 struct kvm_memslots *slots;
2001 struct kvm_memory_slot *memslot;
2002 struct slot_rmap_walk_iterator iterator;
2006 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
2007 slots = __kvm_memslots(kvm, i);
2008 kvm_for_each_memslot(memslot, slots) {
2009 unsigned long hva_start, hva_end;
2010 gfn_t gfn_start, gfn_end;
2012 hva_start = max(start, memslot->userspace_addr);
2013 hva_end = min(end, memslot->userspace_addr +
2014 (memslot->npages << PAGE_SHIFT));
2015 if (hva_start >= hva_end)
2018 * {gfn(page) | page intersects with [hva_start, hva_end)} =
2019 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
2021 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
2022 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
2024 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
2025 PT_MAX_HUGEPAGE_LEVEL,
2026 gfn_start, gfn_end - 1,
2028 ret |= handler(kvm, iterator.rmap, memslot,
2029 iterator.gfn, iterator.level, data);
2036 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
2038 int (*handler)(struct kvm *kvm,
2039 struct kvm_rmap_head *rmap_head,
2040 struct kvm_memory_slot *slot,
2041 gfn_t gfn, int level,
2042 unsigned long data))
2044 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
2047 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
2049 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
2052 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
2054 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
2057 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
2058 struct kvm_memory_slot *slot, gfn_t gfn, int level,
2062 struct rmap_iterator uninitialized_var(iter);
2065 for_each_rmap_spte(rmap_head, &iter, sptep)
2066 young |= mmu_spte_age(sptep);
2068 trace_kvm_age_page(gfn, level, slot, young);
2072 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
2073 struct kvm_memory_slot *slot, gfn_t gfn,
2074 int level, unsigned long data)
2077 struct rmap_iterator iter;
2079 for_each_rmap_spte(rmap_head, &iter, sptep)
2080 if (is_accessed_spte(*sptep))
2085 #define RMAP_RECYCLE_THRESHOLD 1000
2087 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2089 struct kvm_rmap_head *rmap_head;
2090 struct kvm_mmu_page *sp;
2092 sp = page_header(__pa(spte));
2094 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2096 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2097 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
2098 KVM_PAGES_PER_HPAGE(sp->role.level));
2101 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2103 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2106 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2108 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2112 static int is_empty_shadow_page(u64 *spt)
2117 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2118 if (is_shadow_present_pte(*pos)) {
2119 printk(KERN_ERR "%s: %p %llx\n", __func__,
2128 * This value is the sum of all of the kvm instances's
2129 * kvm->arch.n_used_mmu_pages values. We need a global,
2130 * aggregate version in order to make the slab shrinker
2133 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2135 kvm->arch.n_used_mmu_pages += nr;
2136 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2139 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2141 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2142 hlist_del(&sp->hash_link);
2143 list_del(&sp->link);
2144 free_page((unsigned long)sp->spt);
2145 if (!sp->role.direct)
2146 free_page((unsigned long)sp->gfns);
2147 kmem_cache_free(mmu_page_header_cache, sp);
2150 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2152 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2155 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2156 struct kvm_mmu_page *sp, u64 *parent_pte)
2161 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2164 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2167 __pte_list_remove(parent_pte, &sp->parent_ptes);
2170 static void drop_parent_pte(struct kvm_mmu_page *sp,
2173 mmu_page_remove_parent_pte(sp, parent_pte);
2174 mmu_spte_clear_no_track(parent_pte);
2177 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2179 struct kvm_mmu_page *sp;
2181 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2182 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2184 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2185 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2188 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2189 * depends on valid pages being added to the head of the list. See
2190 * comments in kvm_zap_obsolete_pages().
2192 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2193 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2194 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2198 static void mark_unsync(u64 *spte);
2199 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2202 struct rmap_iterator iter;
2204 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2209 static void mark_unsync(u64 *spte)
2211 struct kvm_mmu_page *sp;
2214 sp = page_header(__pa(spte));
2215 index = spte - sp->spt;
2216 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2218 if (sp->unsync_children++)
2220 kvm_mmu_mark_parents_unsync(sp);
2223 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2224 struct kvm_mmu_page *sp)
2229 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2233 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2234 struct kvm_mmu_page *sp, u64 *spte,
2240 #define KVM_PAGE_ARRAY_NR 16
2242 struct kvm_mmu_pages {
2243 struct mmu_page_and_offset {
2244 struct kvm_mmu_page *sp;
2246 } page[KVM_PAGE_ARRAY_NR];
2250 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2256 for (i=0; i < pvec->nr; i++)
2257 if (pvec->page[i].sp == sp)
2260 pvec->page[pvec->nr].sp = sp;
2261 pvec->page[pvec->nr].idx = idx;
2263 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2266 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2268 --sp->unsync_children;
2269 WARN_ON((int)sp->unsync_children < 0);
2270 __clear_bit(idx, sp->unsync_child_bitmap);
2273 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2274 struct kvm_mmu_pages *pvec)
2276 int i, ret, nr_unsync_leaf = 0;
2278 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2279 struct kvm_mmu_page *child;
2280 u64 ent = sp->spt[i];
2282 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2283 clear_unsync_child_bit(sp, i);
2287 child = page_header(ent & PT64_BASE_ADDR_MASK);
2289 if (child->unsync_children) {
2290 if (mmu_pages_add(pvec, child, i))
2293 ret = __mmu_unsync_walk(child, pvec);
2295 clear_unsync_child_bit(sp, i);
2297 } else if (ret > 0) {
2298 nr_unsync_leaf += ret;
2301 } else if (child->unsync) {
2303 if (mmu_pages_add(pvec, child, i))
2306 clear_unsync_child_bit(sp, i);
2309 return nr_unsync_leaf;
2312 #define INVALID_INDEX (-1)
2314 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2315 struct kvm_mmu_pages *pvec)
2318 if (!sp->unsync_children)
2321 mmu_pages_add(pvec, sp, INVALID_INDEX);
2322 return __mmu_unsync_walk(sp, pvec);
2325 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2327 WARN_ON(!sp->unsync);
2328 trace_kvm_mmu_sync_page(sp);
2330 --kvm->stat.mmu_unsync;
2333 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2334 struct list_head *invalid_list);
2335 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2336 struct list_head *invalid_list);
2339 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2340 hlist_for_each_entry(_sp, \
2341 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2342 if (is_obsolete_sp((_kvm), (_sp))) { \
2345 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2346 for_each_valid_sp(_kvm, _sp, _gfn) \
2347 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2349 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2351 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2354 /* @sp->gfn should be write-protected at the call site */
2355 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2356 struct list_head *invalid_list)
2358 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2359 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2360 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2367 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2368 struct list_head *invalid_list,
2371 if (!remote_flush && list_empty(invalid_list))
2374 if (!list_empty(invalid_list))
2375 kvm_mmu_commit_zap_page(kvm, invalid_list);
2377 kvm_flush_remote_tlbs(kvm);
2381 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2382 struct list_head *invalid_list,
2383 bool remote_flush, bool local_flush)
2385 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2389 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2392 #ifdef CONFIG_KVM_MMU_AUDIT
2393 #include "mmu_audit.c"
2395 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2396 static void mmu_audit_disable(void) { }
2399 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2401 return sp->role.invalid ||
2402 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2405 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2406 struct list_head *invalid_list)
2408 kvm_unlink_unsync_page(vcpu->kvm, sp);
2409 return __kvm_sync_page(vcpu, sp, invalid_list);
2412 /* @gfn should be write-protected at the call site */
2413 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2414 struct list_head *invalid_list)
2416 struct kvm_mmu_page *s;
2419 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2423 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2424 ret |= kvm_sync_page(vcpu, s, invalid_list);
2430 struct mmu_page_path {
2431 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2432 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2435 #define for_each_sp(pvec, sp, parents, i) \
2436 for (i = mmu_pages_first(&pvec, &parents); \
2437 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2438 i = mmu_pages_next(&pvec, &parents, i))
2440 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2441 struct mmu_page_path *parents,
2446 for (n = i+1; n < pvec->nr; n++) {
2447 struct kvm_mmu_page *sp = pvec->page[n].sp;
2448 unsigned idx = pvec->page[n].idx;
2449 int level = sp->role.level;
2451 parents->idx[level-1] = idx;
2452 if (level == PT_PAGE_TABLE_LEVEL)
2455 parents->parent[level-2] = sp;
2461 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2462 struct mmu_page_path *parents)
2464 struct kvm_mmu_page *sp;
2470 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2472 sp = pvec->page[0].sp;
2473 level = sp->role.level;
2474 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2476 parents->parent[level-2] = sp;
2478 /* Also set up a sentinel. Further entries in pvec are all
2479 * children of sp, so this element is never overwritten.
2481 parents->parent[level-1] = NULL;
2482 return mmu_pages_next(pvec, parents, 0);
2485 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2487 struct kvm_mmu_page *sp;
2488 unsigned int level = 0;
2491 unsigned int idx = parents->idx[level];
2492 sp = parents->parent[level];
2496 WARN_ON(idx == INVALID_INDEX);
2497 clear_unsync_child_bit(sp, idx);
2499 } while (!sp->unsync_children);
2502 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2503 struct kvm_mmu_page *parent)
2506 struct kvm_mmu_page *sp;
2507 struct mmu_page_path parents;
2508 struct kvm_mmu_pages pages;
2509 LIST_HEAD(invalid_list);
2512 while (mmu_unsync_walk(parent, &pages)) {
2513 bool protected = false;
2515 for_each_sp(pages, sp, parents, i)
2516 protected |= rmap_write_protect(vcpu, sp->gfn);
2519 kvm_flush_remote_tlbs(vcpu->kvm);
2523 for_each_sp(pages, sp, parents, i) {
2524 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2525 mmu_pages_clear_parents(&parents);
2527 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2528 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2529 cond_resched_lock(&vcpu->kvm->mmu_lock);
2534 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2537 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2539 atomic_set(&sp->write_flooding_count, 0);
2542 static void clear_sp_write_flooding_count(u64 *spte)
2544 struct kvm_mmu_page *sp = page_header(__pa(spte));
2546 __clear_sp_write_flooding_count(sp);
2549 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2556 union kvm_mmu_page_role role;
2558 struct kvm_mmu_page *sp;
2559 bool need_sync = false;
2562 LIST_HEAD(invalid_list);
2564 role = vcpu->arch.mmu->mmu_role.base;
2566 role.direct = direct;
2568 role.gpte_is_8_bytes = true;
2569 role.access = access;
2570 if (!vcpu->arch.mmu->direct_map
2571 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2572 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2573 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2574 role.quadrant = quadrant;
2576 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2577 if (sp->gfn != gfn) {
2582 if (!need_sync && sp->unsync)
2585 if (sp->role.word != role.word)
2589 /* The page is good, but __kvm_sync_page might still end
2590 * up zapping it. If so, break in order to rebuild it.
2592 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2595 WARN_ON(!list_empty(&invalid_list));
2596 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2599 if (sp->unsync_children)
2600 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2602 __clear_sp_write_flooding_count(sp);
2603 trace_kvm_mmu_get_page(sp, false);
2607 ++vcpu->kvm->stat.mmu_cache_miss;
2609 sp = kvm_mmu_alloc_page(vcpu, direct);
2613 hlist_add_head(&sp->hash_link,
2614 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2617 * we should do write protection before syncing pages
2618 * otherwise the content of the synced shadow page may
2619 * be inconsistent with guest page table.
2621 account_shadowed(vcpu->kvm, sp);
2622 if (level == PT_PAGE_TABLE_LEVEL &&
2623 rmap_write_protect(vcpu, gfn))
2624 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2626 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2627 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2629 clear_page(sp->spt);
2630 trace_kvm_mmu_get_page(sp, true);
2632 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2634 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2635 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2639 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2640 struct kvm_vcpu *vcpu, hpa_t root,
2643 iterator->addr = addr;
2644 iterator->shadow_addr = root;
2645 iterator->level = vcpu->arch.mmu->shadow_root_level;
2647 if (iterator->level == PT64_ROOT_4LEVEL &&
2648 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2649 !vcpu->arch.mmu->direct_map)
2652 if (iterator->level == PT32E_ROOT_LEVEL) {
2654 * prev_root is currently only used for 64-bit hosts. So only
2655 * the active root_hpa is valid here.
2657 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2659 iterator->shadow_addr
2660 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2661 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2663 if (!iterator->shadow_addr)
2664 iterator->level = 0;
2668 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2669 struct kvm_vcpu *vcpu, u64 addr)
2671 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2675 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2677 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2680 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2681 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2685 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2688 if (is_last_spte(spte, iterator->level)) {
2689 iterator->level = 0;
2693 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2697 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2699 __shadow_walk_next(iterator, *iterator->sptep);
2702 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2703 struct kvm_mmu_page *sp)
2707 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2709 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2710 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2712 if (sp_ad_disabled(sp))
2713 spte |= SPTE_AD_DISABLED_MASK;
2715 spte |= shadow_accessed_mask;
2717 mmu_spte_set(sptep, spte);
2719 mmu_page_add_parent_pte(vcpu, sp, sptep);
2721 if (sp->unsync_children || sp->unsync)
2725 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2726 unsigned direct_access)
2728 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2729 struct kvm_mmu_page *child;
2732 * For the direct sp, if the guest pte's dirty bit
2733 * changed form clean to dirty, it will corrupt the
2734 * sp's access: allow writable in the read-only sp,
2735 * so we should update the spte at this point to get
2736 * a new sp with the correct access.
2738 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2739 if (child->role.access == direct_access)
2742 drop_parent_pte(child, sptep);
2743 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2747 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2751 struct kvm_mmu_page *child;
2754 if (is_shadow_present_pte(pte)) {
2755 if (is_last_spte(pte, sp->role.level)) {
2756 drop_spte(kvm, spte);
2757 if (is_large_pte(pte))
2760 child = page_header(pte & PT64_BASE_ADDR_MASK);
2761 drop_parent_pte(child, spte);
2766 if (is_mmio_spte(pte))
2767 mmu_spte_clear_no_track(spte);
2772 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2773 struct kvm_mmu_page *sp)
2777 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2778 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2781 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2784 struct rmap_iterator iter;
2786 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2787 drop_parent_pte(sp, sptep);
2790 static int mmu_zap_unsync_children(struct kvm *kvm,
2791 struct kvm_mmu_page *parent,
2792 struct list_head *invalid_list)
2795 struct mmu_page_path parents;
2796 struct kvm_mmu_pages pages;
2798 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2801 while (mmu_unsync_walk(parent, &pages)) {
2802 struct kvm_mmu_page *sp;
2804 for_each_sp(pages, sp, parents, i) {
2805 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2806 mmu_pages_clear_parents(&parents);
2814 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2815 struct kvm_mmu_page *sp,
2816 struct list_head *invalid_list,
2821 trace_kvm_mmu_prepare_zap_page(sp);
2822 ++kvm->stat.mmu_shadow_zapped;
2823 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2824 kvm_mmu_page_unlink_children(kvm, sp);
2825 kvm_mmu_unlink_parents(kvm, sp);
2827 /* Zapping children means active_mmu_pages has become unstable. */
2828 list_unstable = *nr_zapped;
2830 if (!sp->role.invalid && !sp->role.direct)
2831 unaccount_shadowed(kvm, sp);
2834 kvm_unlink_unsync_page(kvm, sp);
2835 if (!sp->root_count) {
2838 list_move(&sp->link, invalid_list);
2839 kvm_mod_used_mmu_pages(kvm, -1);
2841 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2844 * Obsolete pages cannot be used on any vCPUs, see the comment
2845 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2846 * treats invalid shadow pages as being obsolete.
2848 if (!is_obsolete_sp(kvm, sp))
2849 kvm_reload_remote_mmus(kvm);
2852 if (sp->lpage_disallowed)
2853 unaccount_huge_nx_page(kvm, sp);
2855 sp->role.invalid = 1;
2856 return list_unstable;
2859 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2860 struct list_head *invalid_list)
2864 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2868 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2869 struct list_head *invalid_list)
2871 struct kvm_mmu_page *sp, *nsp;
2873 if (list_empty(invalid_list))
2877 * We need to make sure everyone sees our modifications to
2878 * the page tables and see changes to vcpu->mode here. The barrier
2879 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2880 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2882 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2883 * guest mode and/or lockless shadow page table walks.
2885 kvm_flush_remote_tlbs(kvm);
2887 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2888 WARN_ON(!sp->role.invalid || sp->root_count);
2889 kvm_mmu_free_page(sp);
2893 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2894 struct list_head *invalid_list)
2896 struct kvm_mmu_page *sp;
2898 if (list_empty(&kvm->arch.active_mmu_pages))
2901 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2902 struct kvm_mmu_page, link);
2903 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2907 * Changing the number of mmu pages allocated to the vm
2908 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2910 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2912 LIST_HEAD(invalid_list);
2914 spin_lock(&kvm->mmu_lock);
2916 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2917 /* Need to free some mmu pages to achieve the goal. */
2918 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2919 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2922 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2923 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2926 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2928 spin_unlock(&kvm->mmu_lock);
2931 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2933 struct kvm_mmu_page *sp;
2934 LIST_HEAD(invalid_list);
2937 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2939 spin_lock(&kvm->mmu_lock);
2940 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2941 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2944 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2946 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2947 spin_unlock(&kvm->mmu_lock);
2951 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2953 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2955 trace_kvm_mmu_unsync_page(sp);
2956 ++vcpu->kvm->stat.mmu_unsync;
2959 kvm_mmu_mark_parents_unsync(sp);
2962 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2965 struct kvm_mmu_page *sp;
2967 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2970 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2977 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2978 kvm_unsync_page(vcpu, sp);
2982 * We need to ensure that the marking of unsync pages is visible
2983 * before the SPTE is updated to allow writes because
2984 * kvm_mmu_sync_roots() checks the unsync flags without holding
2985 * the MMU lock and so can race with this. If the SPTE was updated
2986 * before the page had been marked as unsync-ed, something like the
2987 * following could happen:
2990 * ---------------------------------------------------------------------
2991 * 1.2 Host updates SPTE
2993 * 2.1 Guest writes a GPTE for GVA X.
2994 * (GPTE being in the guest page table shadowed
2995 * by the SP from CPU 1.)
2996 * This reads SPTE during the page table walk.
2997 * Since SPTE.W is read as 1, there is no
3000 * 2.2 Guest issues TLB flush.
3001 * That causes a VM Exit.
3003 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
3004 * Since it is false, so it just returns.
3006 * 2.4 Guest accesses GVA X.
3007 * Since the mapping in the SP was not updated,
3008 * so the old mapping for GVA X incorrectly
3012 * (sp->unsync = true)
3014 * The write barrier below ensures that 1.1 happens before 1.2 and thus
3015 * the situation in 2.4 does not arise. The implicit barrier in 2.2
3016 * pairs with this write barrier.
3023 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
3026 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
3028 * Some reserved pages, such as those from NVDIMM
3029 * DAX devices, are not for MMIO, and can be mapped
3030 * with cached memory type for better performance.
3031 * However, the above check misconceives those pages
3032 * as MMIO, and results in KVM mapping them with UC
3033 * memory type, which would hurt the performance.
3034 * Therefore, we check the host memory type in addition
3035 * and only treat UC/UC-/WC pages as MMIO.
3037 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
3039 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
3040 pfn_to_hpa(pfn + 1) - 1,
3044 /* Bits which may be returned by set_spte() */
3045 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
3046 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
3048 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
3049 unsigned pte_access, int level,
3050 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
3051 bool can_unsync, bool host_writable)
3055 struct kvm_mmu_page *sp;
3057 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
3060 sp = page_header(__pa(sptep));
3061 if (sp_ad_disabled(sp))
3062 spte |= SPTE_AD_DISABLED_MASK;
3063 else if (kvm_vcpu_ad_need_write_protect(vcpu))
3064 spte |= SPTE_AD_WRPROT_ONLY_MASK;
3067 * For the EPT case, shadow_present_mask is 0 if hardware
3068 * supports exec-only page table entries. In that case,
3069 * ACC_USER_MASK and shadow_user_mask are used to represent
3070 * read access. See FNAME(gpte_access) in paging_tmpl.h.
3072 spte |= shadow_present_mask;
3074 spte |= spte_shadow_accessed_mask(spte);
3076 if (level > PT_PAGE_TABLE_LEVEL && (pte_access & ACC_EXEC_MASK) &&
3077 is_nx_huge_page_enabled()) {
3078 pte_access &= ~ACC_EXEC_MASK;
3081 if (pte_access & ACC_EXEC_MASK)
3082 spte |= shadow_x_mask;
3084 spte |= shadow_nx_mask;
3086 if (pte_access & ACC_USER_MASK)
3087 spte |= shadow_user_mask;
3089 if (level > PT_PAGE_TABLE_LEVEL)
3090 spte |= PT_PAGE_SIZE_MASK;
3092 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
3093 kvm_is_mmio_pfn(pfn));
3096 spte |= SPTE_HOST_WRITEABLE;
3098 pte_access &= ~ACC_WRITE_MASK;
3100 if (!kvm_is_mmio_pfn(pfn))
3101 spte |= shadow_me_mask;
3103 spte |= (u64)pfn << PAGE_SHIFT;
3105 if (pte_access & ACC_WRITE_MASK) {
3108 * Other vcpu creates new sp in the window between
3109 * mapping_level() and acquiring mmu-lock. We can
3110 * allow guest to retry the access, the mapping can
3111 * be fixed if guest refault.
3113 if (level > PT_PAGE_TABLE_LEVEL &&
3114 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3117 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3120 * Optimization: for pte sync, if spte was writable the hash
3121 * lookup is unnecessary (and expensive). Write protection
3122 * is responsibility of mmu_get_page / kvm_sync_page.
3123 * Same reasoning can be applied to dirty page accounting.
3125 if (!can_unsync && is_writable_pte(*sptep))
3128 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3129 pgprintk("%s: found shadow page for %llx, marking ro\n",
3131 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3132 pte_access &= ~ACC_WRITE_MASK;
3133 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3137 if (pte_access & ACC_WRITE_MASK) {
3138 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3139 spte |= spte_shadow_dirty_mask(spte);
3143 spte = mark_spte_for_access_track(spte);
3146 if (mmu_spte_update(sptep, spte))
3147 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3152 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3153 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3154 bool speculative, bool host_writable)
3156 int was_rmapped = 0;
3159 int ret = RET_PF_RETRY;
3162 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3163 *sptep, write_fault, gfn);
3165 if (is_shadow_present_pte(*sptep)) {
3167 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3168 * the parent of the now unreachable PTE.
3170 if (level > PT_PAGE_TABLE_LEVEL &&
3171 !is_large_pte(*sptep)) {
3172 struct kvm_mmu_page *child;
3175 child = page_header(pte & PT64_BASE_ADDR_MASK);
3176 drop_parent_pte(child, sptep);
3178 } else if (pfn != spte_to_pfn(*sptep)) {
3179 pgprintk("hfn old %llx new %llx\n",
3180 spte_to_pfn(*sptep), pfn);
3181 drop_spte(vcpu->kvm, sptep);
3187 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3188 speculative, true, host_writable);
3189 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3191 ret = RET_PF_EMULATE;
3192 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3195 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3196 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3197 KVM_PAGES_PER_HPAGE(level));
3199 if (unlikely(is_mmio_spte(*sptep)))
3200 ret = RET_PF_EMULATE;
3202 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3203 trace_kvm_mmu_set_spte(level, gfn, sptep);
3204 if (!was_rmapped && is_large_pte(*sptep))
3205 ++vcpu->kvm->stat.lpages;
3207 if (is_shadow_present_pte(*sptep)) {
3209 rmap_count = rmap_add(vcpu, sptep, gfn);
3210 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3211 rmap_recycle(vcpu, sptep, gfn);
3218 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3221 struct kvm_memory_slot *slot;
3223 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3225 return KVM_PFN_ERR_FAULT;
3227 return gfn_to_pfn_memslot_atomic(slot, gfn);
3230 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3231 struct kvm_mmu_page *sp,
3232 u64 *start, u64 *end)
3234 struct page *pages[PTE_PREFETCH_NUM];
3235 struct kvm_memory_slot *slot;
3236 unsigned access = sp->role.access;
3240 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3241 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3245 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3249 for (i = 0; i < ret; i++, gfn++, start++) {
3250 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3251 page_to_pfn(pages[i]), true, true);
3258 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3259 struct kvm_mmu_page *sp, u64 *sptep)
3261 u64 *spte, *start = NULL;
3264 WARN_ON(!sp->role.direct);
3266 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3269 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3270 if (is_shadow_present_pte(*spte) || spte == sptep) {
3273 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3281 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3283 struct kvm_mmu_page *sp;
3285 sp = page_header(__pa(sptep));
3288 * Without accessed bits, there's no way to distinguish between
3289 * actually accessed translations and prefetched, so disable pte
3290 * prefetch if accessed bits aren't available.
3292 if (sp_ad_disabled(sp))
3295 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3298 __direct_pte_prefetch(vcpu, sp, sptep);
3301 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3302 gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3304 int level = *levelp;
3305 u64 spte = *it.sptep;
3307 if (it.level == level && level > PT_PAGE_TABLE_LEVEL &&
3308 is_nx_huge_page_enabled() &&
3309 is_shadow_present_pte(spte) &&
3310 !is_large_pte(spte)) {
3312 * A small SPTE exists for this pfn, but FNAME(fetch)
3313 * and __direct_map would like to create a large PTE
3314 * instead: just force them to go down another level,
3315 * patching back for them into pfn the next 9 bits of
3318 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3319 *pfnp |= gfn & page_mask;
3324 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3325 int map_writable, int level, kvm_pfn_t pfn,
3326 bool prefault, bool lpage_disallowed)
3328 struct kvm_shadow_walk_iterator it;
3329 struct kvm_mmu_page *sp;
3331 gfn_t gfn = gpa >> PAGE_SHIFT;
3332 gfn_t base_gfn = gfn;
3334 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3335 return RET_PF_RETRY;
3337 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3338 for_each_shadow_entry(vcpu, gpa, it) {
3340 * We cannot overwrite existing page tables with an NX
3341 * large page, as the leaf could be executable.
3343 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3345 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3346 if (it.level == level)
3349 drop_large_spte(vcpu, it.sptep);
3350 if (!is_shadow_present_pte(*it.sptep)) {
3351 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3352 it.level - 1, true, ACC_ALL);
3354 link_shadow_page(vcpu, it.sptep, sp);
3355 if (lpage_disallowed)
3356 account_huge_nx_page(vcpu->kvm, sp);
3360 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3361 write, level, base_gfn, pfn, prefault,
3363 direct_pte_prefetch(vcpu, it.sptep);
3364 ++vcpu->stat.pf_fixed;
3368 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3370 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3373 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3376 * Do not cache the mmio info caused by writing the readonly gfn
3377 * into the spte otherwise read access on readonly gfn also can
3378 * caused mmio page fault and treat it as mmio access.
3380 if (pfn == KVM_PFN_ERR_RO_FAULT)
3381 return RET_PF_EMULATE;
3383 if (pfn == KVM_PFN_ERR_HWPOISON) {
3384 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3385 return RET_PF_RETRY;
3391 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3392 gfn_t gfn, kvm_pfn_t *pfnp,
3395 kvm_pfn_t pfn = *pfnp;
3396 int level = *levelp;
3399 * Check if it's a transparent hugepage. If this would be an
3400 * hugetlbfs page, level wouldn't be set to
3401 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3404 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3405 !kvm_is_zone_device_pfn(pfn) && level == PT_PAGE_TABLE_LEVEL &&
3406 PageTransCompoundMap(pfn_to_page(pfn)) &&
3407 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3410 * mmu_notifier_retry was successful and we hold the
3411 * mmu_lock here, so the pmd can't become splitting
3412 * from under us, and in turn
3413 * __split_huge_page_refcount() can't run from under
3414 * us and we can safely transfer the refcount from
3415 * PG_tail to PG_head as we switch the pfn to tail to
3418 *levelp = level = PT_DIRECTORY_LEVEL;
3419 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3420 VM_BUG_ON((gfn & mask) != (pfn & mask));
3422 kvm_release_pfn_clean(pfn);
3430 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3431 kvm_pfn_t pfn, unsigned access, int *ret_val)
3433 /* The pfn is invalid, report the error! */
3434 if (unlikely(is_error_pfn(pfn))) {
3435 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3439 if (unlikely(is_noslot_pfn(pfn)))
3440 vcpu_cache_mmio_info(vcpu, gva, gfn,
3441 access & shadow_mmio_access_mask);
3446 static bool page_fault_can_be_fast(u32 error_code)
3449 * Do not fix the mmio spte with invalid generation number which
3450 * need to be updated by slow page fault path.
3452 if (unlikely(error_code & PFERR_RSVD_MASK))
3455 /* See if the page fault is due to an NX violation */
3456 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3457 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3461 * #PF can be fast if:
3462 * 1. The shadow page table entry is not present, which could mean that
3463 * the fault is potentially caused by access tracking (if enabled).
3464 * 2. The shadow page table entry is present and the fault
3465 * is caused by write-protect, that means we just need change the W
3466 * bit of the spte which can be done out of mmu-lock.
3468 * However, if access tracking is disabled we know that a non-present
3469 * page must be a genuine page fault where we have to create a new SPTE.
3470 * So, if access tracking is disabled, we return true only for write
3471 * accesses to a present page.
3474 return shadow_acc_track_mask != 0 ||
3475 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3476 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3480 * Returns true if the SPTE was fixed successfully. Otherwise,
3481 * someone else modified the SPTE from its original value.
3484 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3485 u64 *sptep, u64 old_spte, u64 new_spte)
3489 WARN_ON(!sp->role.direct);
3492 * Theoretically we could also set dirty bit (and flush TLB) here in
3493 * order to eliminate unnecessary PML logging. See comments in
3494 * set_spte. But fast_page_fault is very unlikely to happen with PML
3495 * enabled, so we do not do this. This might result in the same GPA
3496 * to be logged in PML buffer again when the write really happens, and
3497 * eventually to be called by mark_page_dirty twice. But it's also no
3498 * harm. This also avoids the TLB flush needed after setting dirty bit
3499 * so non-PML cases won't be impacted.
3501 * Compare with set_spte where instead shadow_dirty_mask is set.
3503 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3506 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3508 * The gfn of direct spte is stable since it is
3509 * calculated by sp->gfn.
3511 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3512 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3518 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3520 if (fault_err_code & PFERR_FETCH_MASK)
3521 return is_executable_pte(spte);
3523 if (fault_err_code & PFERR_WRITE_MASK)
3524 return is_writable_pte(spte);
3526 /* Fault was on Read access */
3527 return spte & PT_PRESENT_MASK;
3532 * - true: let the vcpu to access on the same address again.
3533 * - false: let the real page fault path to fix it.
3535 static bool fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, int level,
3538 struct kvm_shadow_walk_iterator iterator;
3539 struct kvm_mmu_page *sp;
3540 bool fault_handled = false;
3542 uint retry_count = 0;
3544 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3547 if (!page_fault_can_be_fast(error_code))
3550 walk_shadow_page_lockless_begin(vcpu);
3555 for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
3556 if (!is_shadow_present_pte(spte) ||
3557 iterator.level < level)
3560 sp = page_header(__pa(iterator.sptep));
3561 if (!is_last_spte(spte, sp->role.level))
3565 * Check whether the memory access that caused the fault would
3566 * still cause it if it were to be performed right now. If not,
3567 * then this is a spurious fault caused by TLB lazily flushed,
3568 * or some other CPU has already fixed the PTE after the
3569 * current CPU took the fault.
3571 * Need not check the access of upper level table entries since
3572 * they are always ACC_ALL.
3574 if (is_access_allowed(error_code, spte)) {
3575 fault_handled = true;
3581 if (is_access_track_spte(spte))
3582 new_spte = restore_acc_track_spte(new_spte);
3585 * Currently, to simplify the code, write-protection can
3586 * be removed in the fast path only if the SPTE was
3587 * write-protected for dirty-logging or access tracking.
3589 if ((error_code & PFERR_WRITE_MASK) &&
3590 spte_can_locklessly_be_made_writable(spte))
3592 new_spte |= PT_WRITABLE_MASK;
3595 * Do not fix write-permission on the large spte. Since
3596 * we only dirty the first page into the dirty-bitmap in
3597 * fast_pf_fix_direct_spte(), other pages are missed
3598 * if its slot has dirty logging enabled.
3600 * Instead, we let the slow page fault path create a
3601 * normal spte to fix the access.
3603 * See the comments in kvm_arch_commit_memory_region().
3605 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3609 /* Verify that the fault can be handled in the fast path */
3610 if (new_spte == spte ||
3611 !is_access_allowed(error_code, new_spte))
3615 * Currently, fast page fault only works for direct mapping
3616 * since the gfn is not stable for indirect shadow page. See
3617 * Documentation/virt/kvm/locking.txt to get more detail.
3619 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3620 iterator.sptep, spte,
3625 if (++retry_count > 4) {
3626 printk_once(KERN_WARNING
3627 "kvm: Fast #PF retrying more than 4 times.\n");
3633 trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
3634 spte, fault_handled);
3635 walk_shadow_page_lockless_end(vcpu);
3637 return fault_handled;
3640 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3641 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
3643 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3645 static int nonpaging_map(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
3646 gfn_t gfn, bool prefault)
3650 bool force_pt_level;
3652 unsigned long mmu_seq;
3653 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3654 bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
3655 is_nx_huge_page_enabled();
3657 force_pt_level = lpage_disallowed;
3658 level = mapping_level(vcpu, gfn, &force_pt_level);
3659 if (likely(!force_pt_level)) {
3661 * This path builds a PAE pagetable - so we can map
3662 * 2mb pages at maximum. Therefore check if the level
3663 * is larger than that.
3665 if (level > PT_DIRECTORY_LEVEL)
3666 level = PT_DIRECTORY_LEVEL;
3668 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3671 if (fast_page_fault(vcpu, gpa, level, error_code))
3672 return RET_PF_RETRY;
3674 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3677 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
3678 return RET_PF_RETRY;
3680 if (handle_abnormal_pfn(vcpu, gpa, gfn, pfn, ACC_ALL, &r))
3684 spin_lock(&vcpu->kvm->mmu_lock);
3685 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3687 if (make_mmu_pages_available(vcpu) < 0)
3689 if (likely(!force_pt_level))
3690 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3691 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
3694 spin_unlock(&vcpu->kvm->mmu_lock);
3695 kvm_release_pfn_clean(pfn);
3699 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3700 struct list_head *invalid_list)
3702 struct kvm_mmu_page *sp;
3704 if (!VALID_PAGE(*root_hpa))
3707 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3709 if (!sp->root_count && sp->role.invalid)
3710 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3712 *root_hpa = INVALID_PAGE;
3715 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3716 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3717 ulong roots_to_free)
3720 LIST_HEAD(invalid_list);
3721 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3723 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3725 /* Before acquiring the MMU lock, see if we need to do any real work. */
3726 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3727 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3728 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3729 VALID_PAGE(mmu->prev_roots[i].hpa))
3732 if (i == KVM_MMU_NUM_PREV_ROOTS)
3736 spin_lock(&vcpu->kvm->mmu_lock);
3738 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3739 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3740 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3743 if (free_active_root) {
3744 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3745 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3746 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3749 for (i = 0; i < 4; ++i)
3750 if (mmu->pae_root[i] != 0)
3751 mmu_free_root_page(vcpu->kvm,
3754 mmu->root_hpa = INVALID_PAGE;
3759 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3760 spin_unlock(&vcpu->kvm->mmu_lock);
3762 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3764 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3768 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3769 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3776 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3778 struct kvm_mmu_page *sp;
3781 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3782 spin_lock(&vcpu->kvm->mmu_lock);
3783 if(make_mmu_pages_available(vcpu) < 0) {
3784 spin_unlock(&vcpu->kvm->mmu_lock);
3787 sp = kvm_mmu_get_page(vcpu, 0, 0,
3788 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3790 spin_unlock(&vcpu->kvm->mmu_lock);
3791 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3792 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3793 for (i = 0; i < 4; ++i) {
3794 hpa_t root = vcpu->arch.mmu->pae_root[i];
3796 MMU_WARN_ON(VALID_PAGE(root));
3797 spin_lock(&vcpu->kvm->mmu_lock);
3798 if (make_mmu_pages_available(vcpu) < 0) {
3799 spin_unlock(&vcpu->kvm->mmu_lock);
3802 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3803 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3804 root = __pa(sp->spt);
3806 spin_unlock(&vcpu->kvm->mmu_lock);
3807 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3809 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3812 vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3817 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3819 struct kvm_mmu_page *sp;
3821 gfn_t root_gfn, root_cr3;
3824 root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3825 root_gfn = root_cr3 >> PAGE_SHIFT;
3827 if (mmu_check_root(vcpu, root_gfn))
3831 * Do we shadow a long mode page table? If so we need to
3832 * write-protect the guests page table root.
3834 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3835 hpa_t root = vcpu->arch.mmu->root_hpa;
3837 MMU_WARN_ON(VALID_PAGE(root));
3839 spin_lock(&vcpu->kvm->mmu_lock);
3840 if (make_mmu_pages_available(vcpu) < 0) {
3841 spin_unlock(&vcpu->kvm->mmu_lock);
3844 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3845 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3846 root = __pa(sp->spt);
3848 spin_unlock(&vcpu->kvm->mmu_lock);
3849 vcpu->arch.mmu->root_hpa = root;
3854 * We shadow a 32 bit page table. This may be a legacy 2-level
3855 * or a PAE 3-level page table. In either case we need to be aware that
3856 * the shadow page table may be a PAE or a long mode page table.
3858 pm_mask = PT_PRESENT_MASK;
3859 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3860 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3862 for (i = 0; i < 4; ++i) {
3863 hpa_t root = vcpu->arch.mmu->pae_root[i];
3865 MMU_WARN_ON(VALID_PAGE(root));
3866 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3867 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3868 if (!(pdptr & PT_PRESENT_MASK)) {
3869 vcpu->arch.mmu->pae_root[i] = 0;
3872 root_gfn = pdptr >> PAGE_SHIFT;
3873 if (mmu_check_root(vcpu, root_gfn))
3876 spin_lock(&vcpu->kvm->mmu_lock);
3877 if (make_mmu_pages_available(vcpu) < 0) {
3878 spin_unlock(&vcpu->kvm->mmu_lock);
3881 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3883 root = __pa(sp->spt);
3885 spin_unlock(&vcpu->kvm->mmu_lock);
3887 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3889 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3892 * If we shadow a 32 bit page table with a long mode page
3893 * table we enter this path.
3895 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3896 if (vcpu->arch.mmu->lm_root == NULL) {
3898 * The additional page necessary for this is only
3899 * allocated on demand.
3904 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3905 if (lm_root == NULL)
3908 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3910 vcpu->arch.mmu->lm_root = lm_root;
3913 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3917 vcpu->arch.mmu->root_cr3 = root_cr3;
3922 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3924 if (vcpu->arch.mmu->direct_map)
3925 return mmu_alloc_direct_roots(vcpu);
3927 return mmu_alloc_shadow_roots(vcpu);
3930 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3933 struct kvm_mmu_page *sp;
3935 if (vcpu->arch.mmu->direct_map)
3938 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3941 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3943 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3944 hpa_t root = vcpu->arch.mmu->root_hpa;
3945 sp = page_header(root);
3948 * Even if another CPU was marking the SP as unsync-ed
3949 * simultaneously, any guest page table changes are not
3950 * guaranteed to be visible anyway until this VCPU issues a TLB
3951 * flush strictly after those changes are made. We only need to
3952 * ensure that the other CPU sets these flags before any actual
3953 * changes to the page tables are made. The comments in
3954 * mmu_need_write_protect() describe what could go wrong if this
3955 * requirement isn't satisfied.
3957 if (!smp_load_acquire(&sp->unsync) &&
3958 !smp_load_acquire(&sp->unsync_children))
3961 spin_lock(&vcpu->kvm->mmu_lock);
3962 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3964 mmu_sync_children(vcpu, sp);
3966 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3967 spin_unlock(&vcpu->kvm->mmu_lock);
3971 spin_lock(&vcpu->kvm->mmu_lock);
3972 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3974 for (i = 0; i < 4; ++i) {
3975 hpa_t root = vcpu->arch.mmu->pae_root[i];
3977 if (root && VALID_PAGE(root)) {
3978 root &= PT64_BASE_ADDR_MASK;
3979 sp = page_header(root);
3980 mmu_sync_children(vcpu, sp);
3984 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3985 spin_unlock(&vcpu->kvm->mmu_lock);
3987 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3989 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3990 u32 access, struct x86_exception *exception)
3993 exception->error_code = 0;
3997 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3999 struct x86_exception *exception)
4002 exception->error_code = 0;
4003 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
4007 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
4009 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
4011 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
4012 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
4015 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
4017 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
4020 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
4022 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
4025 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4028 * A nested guest cannot use the MMIO cache if it is using nested
4029 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4031 if (mmu_is_nested(vcpu))
4035 return vcpu_match_mmio_gpa(vcpu, addr);
4037 return vcpu_match_mmio_gva(vcpu, addr);
4040 /* return true if reserved bit is detected on spte. */
4042 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
4044 struct kvm_shadow_walk_iterator iterator;
4045 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
4047 bool reserved = false;
4049 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
4052 walk_shadow_page_lockless_begin(vcpu);
4054 for (shadow_walk_init(&iterator, vcpu, addr),
4055 leaf = root = iterator.level;
4056 shadow_walk_okay(&iterator);
4057 __shadow_walk_next(&iterator, spte)) {
4058 spte = mmu_spte_get_lockless(iterator.sptep);
4060 sptes[leaf - 1] = spte;
4063 if (!is_shadow_present_pte(spte))
4066 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
4070 walk_shadow_page_lockless_end(vcpu);
4073 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
4075 while (root > leaf) {
4076 pr_err("------ spte 0x%llx level %d.\n",
4077 sptes[root - 1], root);
4086 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4091 if (mmio_info_in_cache(vcpu, addr, direct))
4092 return RET_PF_EMULATE;
4094 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
4095 if (WARN_ON(reserved))
4098 if (is_mmio_spte(spte)) {
4099 gfn_t gfn = get_mmio_spte_gfn(spte);
4100 unsigned access = get_mmio_spte_access(spte);
4102 if (!check_mmio_spte(vcpu, spte))
4103 return RET_PF_INVALID;
4108 trace_handle_mmio_page_fault(addr, gfn, access);
4109 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4110 return RET_PF_EMULATE;
4114 * If the page table is zapped by other cpus, let CPU fault again on
4117 return RET_PF_RETRY;
4120 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4121 u32 error_code, gfn_t gfn)
4123 if (unlikely(error_code & PFERR_RSVD_MASK))
4126 if (!(error_code & PFERR_PRESENT_MASK) ||
4127 !(error_code & PFERR_WRITE_MASK))
4131 * guest is writing the page which is write tracked which can
4132 * not be fixed by page fault handler.
4134 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4140 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4142 struct kvm_shadow_walk_iterator iterator;
4145 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
4148 walk_shadow_page_lockless_begin(vcpu);
4149 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4150 clear_sp_write_flooding_count(iterator.sptep);
4151 if (!is_shadow_present_pte(spte))
4154 walk_shadow_page_lockless_end(vcpu);
4157 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
4158 u32 error_code, bool prefault)
4160 gfn_t gfn = gpa >> PAGE_SHIFT;
4163 /* Note, paging is disabled, ergo gva == gpa. */
4164 pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
4166 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4167 return RET_PF_EMULATE;
4169 r = mmu_topup_memory_caches(vcpu);
4173 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4176 return nonpaging_map(vcpu, gpa & PAGE_MASK,
4177 error_code, gfn, prefault);
4180 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4183 struct kvm_arch_async_pf arch;
4185 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4187 arch.direct_map = vcpu->arch.mmu->direct_map;
4188 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4190 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4191 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4194 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4195 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
4198 struct kvm_memory_slot *slot;
4202 * Don't expose private memslots to L2.
4204 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4205 *pfn = KVM_PFN_NOSLOT;
4209 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4211 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4213 return false; /* *pfn has correct page already */
4215 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4216 trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
4217 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4218 trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
4219 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4221 } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
4225 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4229 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4230 u64 fault_address, char *insn, int insn_len)
4234 #ifndef CONFIG_X86_64
4235 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4236 if (WARN_ON_ONCE(fault_address >> 32))
4240 vcpu->arch.l1tf_flush_l1d = true;
4241 switch (vcpu->arch.apf.host_apf_reason) {
4243 trace_kvm_page_fault(fault_address, error_code);
4245 if (kvm_event_needs_reinjection(vcpu))
4246 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4247 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4250 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4251 vcpu->arch.apf.host_apf_reason = 0;
4252 local_irq_disable();
4253 kvm_async_pf_task_wait(fault_address, 0);
4256 case KVM_PV_REASON_PAGE_READY:
4257 vcpu->arch.apf.host_apf_reason = 0;
4258 local_irq_disable();
4259 kvm_async_pf_task_wake(fault_address);
4265 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4268 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4270 int page_num = KVM_PAGES_PER_HPAGE(level);
4272 gfn &= ~(page_num - 1);
4274 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4277 static int tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4283 bool force_pt_level;
4284 gfn_t gfn = gpa >> PAGE_SHIFT;
4285 unsigned long mmu_seq;
4286 int write = error_code & PFERR_WRITE_MASK;
4288 bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
4289 is_nx_huge_page_enabled();
4291 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4293 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4294 return RET_PF_EMULATE;
4296 r = mmu_topup_memory_caches(vcpu);
4302 !check_hugepage_cache_consistency(vcpu, gfn, PT_DIRECTORY_LEVEL);
4303 level = mapping_level(vcpu, gfn, &force_pt_level);
4304 if (likely(!force_pt_level)) {
4305 if (level > PT_DIRECTORY_LEVEL &&
4306 !check_hugepage_cache_consistency(vcpu, gfn, level))
4307 level = PT_DIRECTORY_LEVEL;
4308 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4311 if (fast_page_fault(vcpu, gpa, level, error_code))
4312 return RET_PF_RETRY;
4314 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4317 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4318 return RET_PF_RETRY;
4320 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4324 spin_lock(&vcpu->kvm->mmu_lock);
4325 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4327 if (make_mmu_pages_available(vcpu) < 0)
4329 if (likely(!force_pt_level))
4330 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4331 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
4332 prefault, lpage_disallowed);
4334 spin_unlock(&vcpu->kvm->mmu_lock);
4335 kvm_release_pfn_clean(pfn);
4339 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4340 struct kvm_mmu *context)
4342 context->page_fault = nonpaging_page_fault;
4343 context->gva_to_gpa = nonpaging_gva_to_gpa;
4344 context->sync_page = nonpaging_sync_page;
4345 context->invlpg = nonpaging_invlpg;
4346 context->update_pte = nonpaging_update_pte;
4347 context->root_level = 0;
4348 context->shadow_root_level = PT32E_ROOT_LEVEL;
4349 context->direct_map = true;
4350 context->nx = false;
4354 * Find out if a previously cached root matching the new CR3/role is available.
4355 * The current root is also inserted into the cache.
4356 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4358 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4359 * false is returned. This root should now be freed by the caller.
4361 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4362 union kvm_mmu_page_role new_role)
4365 struct kvm_mmu_root_info root;
4366 struct kvm_mmu *mmu = vcpu->arch.mmu;
4368 root.cr3 = mmu->root_cr3;
4369 root.hpa = mmu->root_hpa;
4371 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4372 swap(root, mmu->prev_roots[i]);
4374 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4375 page_header(root.hpa) != NULL &&
4376 new_role.word == page_header(root.hpa)->role.word)
4380 mmu->root_hpa = root.hpa;
4381 mmu->root_cr3 = root.cr3;
4383 return i < KVM_MMU_NUM_PREV_ROOTS;
4386 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4387 union kvm_mmu_page_role new_role,
4388 bool skip_tlb_flush)
4390 struct kvm_mmu *mmu = vcpu->arch.mmu;
4393 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4394 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4395 * later if necessary.
4397 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4398 mmu->root_level >= PT64_ROOT_4LEVEL) {
4399 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4402 if (cached_root_available(vcpu, new_cr3, new_role)) {
4404 * It is possible that the cached previous root page is
4405 * obsolete because of a change in the MMU generation
4406 * number. However, changing the generation number is
4407 * accompanied by KVM_REQ_MMU_RELOAD, which will free
4408 * the root set here and allocate a new one.
4410 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4411 if (!skip_tlb_flush) {
4412 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4413 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4417 * The last MMIO access's GVA and GPA are cached in the
4418 * VCPU. When switching to a new CR3, that GVA->GPA
4419 * mapping may no longer be valid. So clear any cached
4420 * MMIO info even when we don't need to sync the shadow
4423 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4425 __clear_sp_write_flooding_count(
4426 page_header(mmu->root_hpa));
4435 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4436 union kvm_mmu_page_role new_role,
4437 bool skip_tlb_flush)
4439 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4440 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4441 KVM_MMU_ROOT_CURRENT);
4444 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4446 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4449 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4451 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4453 return kvm_read_cr3(vcpu);
4456 static void inject_page_fault(struct kvm_vcpu *vcpu,
4457 struct x86_exception *fault)
4459 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4462 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4463 unsigned access, int *nr_present)
4465 if (unlikely(is_mmio_spte(*sptep))) {
4466 if (gfn != get_mmio_spte_gfn(*sptep)) {
4467 mmu_spte_clear_no_track(sptep);
4472 mark_mmio_spte(vcpu, sptep, gfn, access);
4479 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4480 unsigned level, unsigned gpte)
4483 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4484 * If it is clear, there are no large pages at this level, so clear
4485 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4487 gpte &= level - mmu->last_nonleaf_level;
4490 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4491 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4492 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4494 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4496 return gpte & PT_PAGE_SIZE_MASK;
4499 #define PTTYPE_EPT 18 /* arbitrary */
4500 #define PTTYPE PTTYPE_EPT
4501 #include "paging_tmpl.h"
4505 #include "paging_tmpl.h"
4509 #include "paging_tmpl.h"
4513 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4514 struct rsvd_bits_validate *rsvd_check,
4515 int maxphyaddr, int level, bool nx, bool gbpages,
4518 u64 exb_bit_rsvd = 0;
4519 u64 gbpages_bit_rsvd = 0;
4520 u64 nonleaf_bit8_rsvd = 0;
4522 rsvd_check->bad_mt_xwr = 0;
4525 exb_bit_rsvd = rsvd_bits(63, 63);
4527 gbpages_bit_rsvd = rsvd_bits(7, 7);
4530 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4531 * leaf entries) on AMD CPUs only.
4534 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4537 case PT32_ROOT_LEVEL:
4538 /* no rsvd bits for 2 level 4K page table entries */
4539 rsvd_check->rsvd_bits_mask[0][1] = 0;
4540 rsvd_check->rsvd_bits_mask[0][0] = 0;
4541 rsvd_check->rsvd_bits_mask[1][0] =
4542 rsvd_check->rsvd_bits_mask[0][0];
4545 rsvd_check->rsvd_bits_mask[1][1] = 0;
4549 if (is_cpuid_PSE36())
4550 /* 36bits PSE 4MB page */
4551 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4553 /* 32 bits PSE 4MB page */
4554 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4556 case PT32E_ROOT_LEVEL:
4557 rsvd_check->rsvd_bits_mask[0][2] =
4558 rsvd_bits(maxphyaddr, 63) |
4559 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4560 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4561 rsvd_bits(maxphyaddr, 62); /* PDE */
4562 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4563 rsvd_bits(maxphyaddr, 62); /* PTE */
4564 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4565 rsvd_bits(maxphyaddr, 62) |
4566 rsvd_bits(13, 20); /* large page */
4567 rsvd_check->rsvd_bits_mask[1][0] =
4568 rsvd_check->rsvd_bits_mask[0][0];
4570 case PT64_ROOT_5LEVEL:
4571 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4572 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4573 rsvd_bits(maxphyaddr, 51);
4574 rsvd_check->rsvd_bits_mask[1][4] =
4575 rsvd_check->rsvd_bits_mask[0][4];
4577 case PT64_ROOT_4LEVEL:
4578 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4579 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4580 rsvd_bits(maxphyaddr, 51);
4581 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4582 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4583 rsvd_bits(maxphyaddr, 51);
4584 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4585 rsvd_bits(maxphyaddr, 51);
4586 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4587 rsvd_bits(maxphyaddr, 51);
4588 rsvd_check->rsvd_bits_mask[1][3] =
4589 rsvd_check->rsvd_bits_mask[0][3];
4590 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4591 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4593 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4594 rsvd_bits(maxphyaddr, 51) |
4595 rsvd_bits(13, 20); /* large page */
4596 rsvd_check->rsvd_bits_mask[1][0] =
4597 rsvd_check->rsvd_bits_mask[0][0];
4602 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4603 struct kvm_mmu *context)
4605 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4606 cpuid_maxphyaddr(vcpu), context->root_level,
4608 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4609 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4613 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4614 int maxphyaddr, bool execonly)
4618 rsvd_check->rsvd_bits_mask[0][4] =
4619 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4620 rsvd_check->rsvd_bits_mask[0][3] =
4621 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4622 rsvd_check->rsvd_bits_mask[0][2] =
4623 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4624 rsvd_check->rsvd_bits_mask[0][1] =
4625 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4626 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4629 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4630 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4631 rsvd_check->rsvd_bits_mask[1][2] =
4632 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4633 rsvd_check->rsvd_bits_mask[1][1] =
4634 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4635 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4637 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4638 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4639 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4640 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4641 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4643 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4644 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4646 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4649 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4650 struct kvm_mmu *context, bool execonly)
4652 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4653 cpuid_maxphyaddr(vcpu), execonly);
4657 * the page table on host is the shadow page table for the page
4658 * table in guest or amd nested guest, its mmu features completely
4659 * follow the features in guest.
4662 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4664 bool uses_nx = context->nx ||
4665 context->mmu_role.base.smep_andnot_wp;
4666 struct rsvd_bits_validate *shadow_zero_check;
4670 * Passing "true" to the last argument is okay; it adds a check
4671 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4673 shadow_zero_check = &context->shadow_zero_check;
4674 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4676 context->shadow_root_level, uses_nx,
4677 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4678 is_pse(vcpu), true);
4680 if (!shadow_me_mask)
4683 for (i = context->shadow_root_level; --i >= 0;) {
4684 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4685 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4689 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4691 static inline bool boot_cpu_is_amd(void)
4693 WARN_ON_ONCE(!tdp_enabled);
4694 return shadow_x_mask == 0;
4698 * the direct page table on host, use as much mmu features as
4699 * possible, however, kvm currently does not do execution-protection.
4702 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4703 struct kvm_mmu *context)
4705 struct rsvd_bits_validate *shadow_zero_check;
4708 shadow_zero_check = &context->shadow_zero_check;
4710 if (boot_cpu_is_amd())
4711 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4713 context->shadow_root_level, false,
4714 boot_cpu_has(X86_FEATURE_GBPAGES),
4717 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4721 if (!shadow_me_mask)
4724 for (i = context->shadow_root_level; --i >= 0;) {
4725 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4726 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4731 * as the comments in reset_shadow_zero_bits_mask() except it
4732 * is the shadow page table for intel nested guest.
4735 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4736 struct kvm_mmu *context, bool execonly)
4738 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4739 shadow_phys_bits, execonly);
4742 #define BYTE_MASK(access) \
4743 ((1 & (access) ? 2 : 0) | \
4744 (2 & (access) ? 4 : 0) | \
4745 (3 & (access) ? 8 : 0) | \
4746 (4 & (access) ? 16 : 0) | \
4747 (5 & (access) ? 32 : 0) | \
4748 (6 & (access) ? 64 : 0) | \
4749 (7 & (access) ? 128 : 0))
4752 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4753 struct kvm_mmu *mmu, bool ept)
4757 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4758 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4759 const u8 u = BYTE_MASK(ACC_USER_MASK);
4761 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4762 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4763 bool cr0_wp = is_write_protection(vcpu);
4765 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4766 unsigned pfec = byte << 1;
4769 * Each "*f" variable has a 1 bit for each UWX value
4770 * that causes a fault with the given PFEC.
4773 /* Faults from writes to non-writable pages */
4774 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4775 /* Faults from user mode accesses to supervisor pages */
4776 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4777 /* Faults from fetches of non-executable pages*/
4778 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4779 /* Faults from kernel mode fetches of user pages */
4781 /* Faults from kernel mode accesses of user pages */
4785 /* Faults from kernel mode accesses to user pages */
4786 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4788 /* Not really needed: !nx will cause pte.nx to fault */
4792 /* Allow supervisor writes if !cr0.wp */
4794 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4796 /* Disallow supervisor fetches of user code if cr4.smep */
4798 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4801 * SMAP:kernel-mode data accesses from user-mode
4802 * mappings should fault. A fault is considered
4803 * as a SMAP violation if all of the following
4804 * conditions are true:
4805 * - X86_CR4_SMAP is set in CR4
4806 * - A user page is accessed
4807 * - The access is not a fetch
4808 * - Page fault in kernel mode
4809 * - if CPL = 3 or X86_EFLAGS_AC is clear
4811 * Here, we cover the first three conditions.
4812 * The fourth is computed dynamically in permission_fault();
4813 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4814 * *not* subject to SMAP restrictions.
4817 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4820 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4825 * PKU is an additional mechanism by which the paging controls access to
4826 * user-mode addresses based on the value in the PKRU register. Protection
4827 * key violations are reported through a bit in the page fault error code.
4828 * Unlike other bits of the error code, the PK bit is not known at the
4829 * call site of e.g. gva_to_gpa; it must be computed directly in
4830 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4831 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4833 * In particular the following conditions come from the error code, the
4834 * page tables and the machine state:
4835 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4836 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4837 * - PK is always zero if U=0 in the page tables
4838 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4840 * The PKRU bitmask caches the result of these four conditions. The error
4841 * code (minus the P bit) and the page table's U bit form an index into the
4842 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4843 * with the two bits of the PKRU register corresponding to the protection key.
4844 * For the first three conditions above the bits will be 00, thus masking
4845 * away both AD and WD. For all reads or if the last condition holds, WD
4846 * only will be masked away.
4848 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4859 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4860 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4865 wp = is_write_protection(vcpu);
4867 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4868 unsigned pfec, pkey_bits;
4869 bool check_pkey, check_write, ff, uf, wf, pte_user;
4872 ff = pfec & PFERR_FETCH_MASK;
4873 uf = pfec & PFERR_USER_MASK;
4874 wf = pfec & PFERR_WRITE_MASK;
4876 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4877 pte_user = pfec & PFERR_RSVD_MASK;
4880 * Only need to check the access which is not an
4881 * instruction fetch and is to a user page.
4883 check_pkey = (!ff && pte_user);
4885 * write access is controlled by PKRU if it is a
4886 * user access or CR0.WP = 1.
4888 check_write = check_pkey && wf && (uf || wp);
4890 /* PKRU.AD stops both read and write access. */
4891 pkey_bits = !!check_pkey;
4892 /* PKRU.WD stops write access. */
4893 pkey_bits |= (!!check_write) << 1;
4895 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4899 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4901 unsigned root_level = mmu->root_level;
4903 mmu->last_nonleaf_level = root_level;
4904 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4905 mmu->last_nonleaf_level++;
4908 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4909 struct kvm_mmu *context,
4912 context->nx = is_nx(vcpu);
4913 context->root_level = level;
4915 reset_rsvds_bits_mask(vcpu, context);
4916 update_permission_bitmask(vcpu, context, false);
4917 update_pkru_bitmask(vcpu, context, false);
4918 update_last_nonleaf_level(vcpu, context);
4920 MMU_WARN_ON(!is_pae(vcpu));
4921 context->page_fault = paging64_page_fault;
4922 context->gva_to_gpa = paging64_gva_to_gpa;
4923 context->sync_page = paging64_sync_page;
4924 context->invlpg = paging64_invlpg;
4925 context->update_pte = paging64_update_pte;
4926 context->shadow_root_level = level;
4927 context->direct_map = false;
4930 static void paging64_init_context(struct kvm_vcpu *vcpu,
4931 struct kvm_mmu *context)
4933 int root_level = is_la57_mode(vcpu) ?
4934 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4936 paging64_init_context_common(vcpu, context, root_level);
4939 static void paging32_init_context(struct kvm_vcpu *vcpu,
4940 struct kvm_mmu *context)
4942 context->nx = false;
4943 context->root_level = PT32_ROOT_LEVEL;
4945 reset_rsvds_bits_mask(vcpu, context);
4946 update_permission_bitmask(vcpu, context, false);
4947 update_pkru_bitmask(vcpu, context, false);
4948 update_last_nonleaf_level(vcpu, context);
4950 context->page_fault = paging32_page_fault;
4951 context->gva_to_gpa = paging32_gva_to_gpa;
4952 context->sync_page = paging32_sync_page;
4953 context->invlpg = paging32_invlpg;
4954 context->update_pte = paging32_update_pte;
4955 context->shadow_root_level = PT32E_ROOT_LEVEL;
4956 context->direct_map = false;
4959 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4960 struct kvm_mmu *context)
4962 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4965 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4967 union kvm_mmu_extended_role ext = {0};
4969 ext.cr0_pg = !!is_paging(vcpu);
4970 ext.cr4_pae = !!is_pae(vcpu);
4971 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4972 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4973 ext.cr4_pse = !!is_pse(vcpu);
4974 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4975 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4976 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4983 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4986 union kvm_mmu_role role = {0};
4988 role.base.access = ACC_ALL;
4989 role.base.nxe = !!is_nx(vcpu);
4990 role.base.cr0_wp = is_write_protection(vcpu);
4991 role.base.smm = is_smm(vcpu);
4992 role.base.guest_mode = is_guest_mode(vcpu);
4997 role.ext = kvm_calc_mmu_role_ext(vcpu);
5002 static union kvm_mmu_role
5003 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
5005 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
5007 role.base.ad_disabled = (shadow_accessed_mask == 0);
5008 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
5009 role.base.direct = true;
5010 role.base.gpte_is_8_bytes = true;
5015 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
5017 struct kvm_mmu *context = vcpu->arch.mmu;
5018 union kvm_mmu_role new_role =
5019 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
5021 new_role.base.word &= mmu_base_role_mask.word;
5022 if (new_role.as_u64 == context->mmu_role.as_u64)
5025 context->mmu_role.as_u64 = new_role.as_u64;
5026 context->page_fault = tdp_page_fault;
5027 context->sync_page = nonpaging_sync_page;
5028 context->invlpg = nonpaging_invlpg;
5029 context->update_pte = nonpaging_update_pte;
5030 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
5031 context->direct_map = true;
5032 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
5033 context->get_cr3 = get_cr3;
5034 context->get_pdptr = kvm_pdptr_read;
5035 context->inject_page_fault = kvm_inject_page_fault;
5037 if (!is_paging(vcpu)) {
5038 context->nx = false;
5039 context->gva_to_gpa = nonpaging_gva_to_gpa;
5040 context->root_level = 0;
5041 } else if (is_long_mode(vcpu)) {
5042 context->nx = is_nx(vcpu);
5043 context->root_level = is_la57_mode(vcpu) ?
5044 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5045 reset_rsvds_bits_mask(vcpu, context);
5046 context->gva_to_gpa = paging64_gva_to_gpa;
5047 } else if (is_pae(vcpu)) {
5048 context->nx = is_nx(vcpu);
5049 context->root_level = PT32E_ROOT_LEVEL;
5050 reset_rsvds_bits_mask(vcpu, context);
5051 context->gva_to_gpa = paging64_gva_to_gpa;
5053 context->nx = false;
5054 context->root_level = PT32_ROOT_LEVEL;
5055 reset_rsvds_bits_mask(vcpu, context);
5056 context->gva_to_gpa = paging32_gva_to_gpa;
5059 update_permission_bitmask(vcpu, context, false);
5060 update_pkru_bitmask(vcpu, context, false);
5061 update_last_nonleaf_level(vcpu, context);
5062 reset_tdp_shadow_zero_bits_mask(vcpu, context);
5065 static union kvm_mmu_role
5066 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
5068 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
5070 role.base.smep_andnot_wp = role.ext.cr4_smep &&
5071 !is_write_protection(vcpu);
5072 role.base.smap_andnot_wp = role.ext.cr4_smap &&
5073 !is_write_protection(vcpu);
5074 role.base.direct = !is_paging(vcpu);
5075 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
5077 if (!is_long_mode(vcpu))
5078 role.base.level = PT32E_ROOT_LEVEL;
5079 else if (is_la57_mode(vcpu))
5080 role.base.level = PT64_ROOT_5LEVEL;
5082 role.base.level = PT64_ROOT_4LEVEL;
5087 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
5089 struct kvm_mmu *context = vcpu->arch.mmu;
5090 union kvm_mmu_role new_role =
5091 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
5093 new_role.base.word &= mmu_base_role_mask.word;
5094 if (new_role.as_u64 == context->mmu_role.as_u64)
5097 if (!is_paging(vcpu))
5098 nonpaging_init_context(vcpu, context);
5099 else if (is_long_mode(vcpu))
5100 paging64_init_context(vcpu, context);
5101 else if (is_pae(vcpu))
5102 paging32E_init_context(vcpu, context);
5104 paging32_init_context(vcpu, context);
5106 context->mmu_role.as_u64 = new_role.as_u64;
5107 reset_shadow_zero_bits_mask(vcpu, context);
5109 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
5111 static union kvm_mmu_role
5112 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5115 union kvm_mmu_role role = {0};
5117 /* SMM flag is inherited from root_mmu */
5118 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
5120 role.base.level = PT64_ROOT_4LEVEL;
5121 role.base.gpte_is_8_bytes = true;
5122 role.base.direct = false;
5123 role.base.ad_disabled = !accessed_dirty;
5124 role.base.guest_mode = true;
5125 role.base.access = ACC_ALL;
5128 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
5129 * SMAP variation to denote shadow EPT entries.
5131 role.base.cr0_wp = true;
5132 role.base.smap_andnot_wp = true;
5134 role.ext = kvm_calc_mmu_role_ext(vcpu);
5135 role.ext.execonly = execonly;
5140 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5141 bool accessed_dirty, gpa_t new_eptp)
5143 struct kvm_mmu *context = vcpu->arch.mmu;
5144 union kvm_mmu_role new_role =
5145 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5148 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
5150 new_role.base.word &= mmu_base_role_mask.word;
5151 if (new_role.as_u64 == context->mmu_role.as_u64)
5154 context->shadow_root_level = PT64_ROOT_4LEVEL;
5157 context->ept_ad = accessed_dirty;
5158 context->page_fault = ept_page_fault;
5159 context->gva_to_gpa = ept_gva_to_gpa;
5160 context->sync_page = ept_sync_page;
5161 context->invlpg = ept_invlpg;
5162 context->update_pte = ept_update_pte;
5163 context->root_level = PT64_ROOT_4LEVEL;
5164 context->direct_map = false;
5165 context->mmu_role.as_u64 = new_role.as_u64;
5167 update_permission_bitmask(vcpu, context, true);
5168 update_pkru_bitmask(vcpu, context, true);
5169 update_last_nonleaf_level(vcpu, context);
5170 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5171 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5173 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5175 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5177 struct kvm_mmu *context = vcpu->arch.mmu;
5179 kvm_init_shadow_mmu(vcpu);
5180 context->set_cr3 = kvm_x86_ops->set_cr3;
5181 context->get_cr3 = get_cr3;
5182 context->get_pdptr = kvm_pdptr_read;
5183 context->inject_page_fault = kvm_inject_page_fault;
5186 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5188 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5189 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5191 new_role.base.word &= mmu_base_role_mask.word;
5192 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5195 g_context->mmu_role.as_u64 = new_role.as_u64;
5196 g_context->get_cr3 = get_cr3;
5197 g_context->get_pdptr = kvm_pdptr_read;
5198 g_context->inject_page_fault = kvm_inject_page_fault;
5201 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5202 * L1's nested page tables (e.g. EPT12). The nested translation
5203 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5204 * L2's page tables as the first level of translation and L1's
5205 * nested page tables as the second level of translation. Basically
5206 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5208 if (!is_paging(vcpu)) {
5209 g_context->nx = false;
5210 g_context->root_level = 0;
5211 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5212 } else if (is_long_mode(vcpu)) {
5213 g_context->nx = is_nx(vcpu);
5214 g_context->root_level = is_la57_mode(vcpu) ?
5215 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5216 reset_rsvds_bits_mask(vcpu, g_context);
5217 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5218 } else if (is_pae(vcpu)) {
5219 g_context->nx = is_nx(vcpu);
5220 g_context->root_level = PT32E_ROOT_LEVEL;
5221 reset_rsvds_bits_mask(vcpu, g_context);
5222 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5224 g_context->nx = false;
5225 g_context->root_level = PT32_ROOT_LEVEL;
5226 reset_rsvds_bits_mask(vcpu, g_context);
5227 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5230 update_permission_bitmask(vcpu, g_context, false);
5231 update_pkru_bitmask(vcpu, g_context, false);
5232 update_last_nonleaf_level(vcpu, g_context);
5235 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5240 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5242 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5243 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5246 if (mmu_is_nested(vcpu))
5247 init_kvm_nested_mmu(vcpu);
5248 else if (tdp_enabled)
5249 init_kvm_tdp_mmu(vcpu);
5251 init_kvm_softmmu(vcpu);
5253 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5255 static union kvm_mmu_page_role
5256 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5258 union kvm_mmu_role role;
5261 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5263 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5268 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5270 kvm_mmu_unload(vcpu);
5271 kvm_init_mmu(vcpu, true);
5273 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5275 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5279 r = mmu_topup_memory_caches(vcpu);
5282 r = mmu_alloc_roots(vcpu);
5283 kvm_mmu_sync_roots(vcpu);
5286 kvm_mmu_load_cr3(vcpu);
5287 kvm_x86_ops->tlb_flush(vcpu, true);
5291 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5293 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5295 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5296 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5297 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5298 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5300 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5302 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5303 struct kvm_mmu_page *sp, u64 *spte,
5306 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5307 ++vcpu->kvm->stat.mmu_pde_zapped;
5311 ++vcpu->kvm->stat.mmu_pte_updated;
5312 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5315 static bool need_remote_flush(u64 old, u64 new)
5317 if (!is_shadow_present_pte(old))
5319 if (!is_shadow_present_pte(new))
5321 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5323 old ^= shadow_nx_mask;
5324 new ^= shadow_nx_mask;
5325 return (old & ~new & PT64_PERM_MASK) != 0;
5328 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5335 * Assume that the pte write on a page table of the same type
5336 * as the current vcpu paging mode since we update the sptes only
5337 * when they have the same mode.
5339 if (is_pae(vcpu) && *bytes == 4) {
5340 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5345 if (*bytes == 4 || *bytes == 8) {
5346 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5355 * If we're seeing too many writes to a page, it may no longer be a page table,
5356 * or we may be forking, in which case it is better to unmap the page.
5358 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5361 * Skip write-flooding detected for the sp whose level is 1, because
5362 * it can become unsync, then the guest page is not write-protected.
5364 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5367 atomic_inc(&sp->write_flooding_count);
5368 return atomic_read(&sp->write_flooding_count) >= 3;
5372 * Misaligned accesses are too much trouble to fix up; also, they usually
5373 * indicate a page is not used as a page table.
5375 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5378 unsigned offset, pte_size, misaligned;
5380 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5381 gpa, bytes, sp->role.word);
5383 offset = offset_in_page(gpa);
5384 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5387 * Sometimes, the OS only writes the last one bytes to update status
5388 * bits, for example, in linux, andb instruction is used in clear_bit().
5390 if (!(offset & (pte_size - 1)) && bytes == 1)
5393 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5394 misaligned |= bytes < 4;
5399 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5401 unsigned page_offset, quadrant;
5405 page_offset = offset_in_page(gpa);
5406 level = sp->role.level;
5408 if (!sp->role.gpte_is_8_bytes) {
5409 page_offset <<= 1; /* 32->64 */
5411 * A 32-bit pde maps 4MB while the shadow pdes map
5412 * only 2MB. So we need to double the offset again
5413 * and zap two pdes instead of one.
5415 if (level == PT32_ROOT_LEVEL) {
5416 page_offset &= ~7; /* kill rounding error */
5420 quadrant = page_offset >> PAGE_SHIFT;
5421 page_offset &= ~PAGE_MASK;
5422 if (quadrant != sp->role.quadrant)
5426 spte = &sp->spt[page_offset / sizeof(*spte)];
5430 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5431 const u8 *new, int bytes,
5432 struct kvm_page_track_notifier_node *node)
5434 gfn_t gfn = gpa >> PAGE_SHIFT;
5435 struct kvm_mmu_page *sp;
5436 LIST_HEAD(invalid_list);
5437 u64 entry, gentry, *spte;
5439 bool remote_flush, local_flush;
5442 * If we don't have indirect shadow pages, it means no page is
5443 * write-protected, so we can exit simply.
5445 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5448 remote_flush = local_flush = false;
5450 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5453 * No need to care whether allocation memory is successful
5454 * or not since pte prefetch is skiped if it does not have
5455 * enough objects in the cache.
5457 mmu_topup_memory_caches(vcpu);
5459 spin_lock(&vcpu->kvm->mmu_lock);
5461 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5463 ++vcpu->kvm->stat.mmu_pte_write;
5464 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5466 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5467 if (detect_write_misaligned(sp, gpa, bytes) ||
5468 detect_write_flooding(sp)) {
5469 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5470 ++vcpu->kvm->stat.mmu_flooded;
5474 spte = get_written_sptes(sp, gpa, &npte);
5480 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5483 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5485 !((sp->role.word ^ base_role)
5486 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5487 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5488 if (need_remote_flush(entry, *spte))
5489 remote_flush = true;
5493 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5494 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5495 spin_unlock(&vcpu->kvm->mmu_lock);
5498 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5503 if (vcpu->arch.mmu->direct_map)
5506 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5508 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5512 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5514 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5516 LIST_HEAD(invalid_list);
5518 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5521 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5522 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5525 ++vcpu->kvm->stat.mmu_recycled;
5527 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5529 if (!kvm_mmu_available_pages(vcpu->kvm))
5534 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5535 void *insn, int insn_len)
5537 int r, emulation_type = 0;
5538 bool direct = vcpu->arch.mmu->direct_map;
5540 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5541 if (vcpu->arch.mmu->direct_map) {
5542 vcpu->arch.gpa_available = true;
5543 vcpu->arch.gpa_val = cr2_or_gpa;
5547 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5548 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5549 if (r == RET_PF_EMULATE)
5553 if (r == RET_PF_INVALID) {
5554 r = vcpu->arch.mmu->page_fault(vcpu, cr2_or_gpa,
5555 lower_32_bits(error_code),
5557 WARN_ON(r == RET_PF_INVALID);
5560 if (r == RET_PF_RETRY)
5566 * Before emulating the instruction, check if the error code
5567 * was due to a RO violation while translating the guest page.
5568 * This can occur when using nested virtualization with nested
5569 * paging in both guests. If true, we simply unprotect the page
5570 * and resume the guest.
5572 if (vcpu->arch.mmu->direct_map &&
5573 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5574 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5579 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5580 * optimistically try to just unprotect the page and let the processor
5581 * re-execute the instruction that caused the page fault. Do not allow
5582 * retrying MMIO emulation, as it's not only pointless but could also
5583 * cause us to enter an infinite loop because the processor will keep
5584 * faulting on the non-existent MMIO address. Retrying an instruction
5585 * from a nested guest is also pointless and dangerous as we are only
5586 * explicitly shadowing L1's page tables, i.e. unprotecting something
5587 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5589 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5590 emulation_type = EMULTYPE_ALLOW_RETRY;
5593 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5594 * This can happen if a guest gets a page-fault on data access but the HW
5595 * table walker is not able to read the instruction page (e.g instruction
5596 * page is not present in memory). In those cases we simply restart the
5597 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5599 if (unlikely(insn && !insn_len)) {
5600 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5604 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5607 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5609 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5611 struct kvm_mmu *mmu = vcpu->arch.mmu;
5614 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5615 if (is_noncanonical_address(gva, vcpu))
5618 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5621 * INVLPG is required to invalidate any global mappings for the VA,
5622 * irrespective of PCID. Since it would take us roughly similar amount
5623 * of work to determine whether any of the prev_root mappings of the VA
5624 * is marked global, or to just sync it blindly, so we might as well
5625 * just always sync it.
5627 * Mappings not reachable via the current cr3 or the prev_roots will be
5628 * synced when switching to that cr3, so nothing needs to be done here
5631 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5632 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5633 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5635 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5636 ++vcpu->stat.invlpg;
5638 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5640 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5642 struct kvm_mmu *mmu = vcpu->arch.mmu;
5643 bool tlb_flush = false;
5646 if (pcid == kvm_get_active_pcid(vcpu)) {
5647 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5651 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5652 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5653 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5654 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5660 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5662 ++vcpu->stat.invlpg;
5665 * Mappings not reachable via the current cr3 or the prev_roots will be
5666 * synced when switching to that cr3, so nothing needs to be done here
5670 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5672 void kvm_enable_tdp(void)
5676 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5678 void kvm_disable_tdp(void)
5680 tdp_enabled = false;
5682 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5685 /* The return value indicates if tlb flush on all vcpus is needed. */
5686 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5688 /* The caller should hold mmu-lock before calling this function. */
5689 static __always_inline bool
5690 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5691 slot_level_handler fn, int start_level, int end_level,
5692 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5694 struct slot_rmap_walk_iterator iterator;
5697 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5698 end_gfn, &iterator) {
5700 flush |= fn(kvm, iterator.rmap);
5702 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5703 if (flush && lock_flush_tlb) {
5704 kvm_flush_remote_tlbs_with_address(kvm,
5706 iterator.gfn - start_gfn + 1);
5709 cond_resched_lock(&kvm->mmu_lock);
5713 if (flush && lock_flush_tlb) {
5714 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5715 end_gfn - start_gfn + 1);
5722 static __always_inline bool
5723 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5724 slot_level_handler fn, int start_level, int end_level,
5725 bool lock_flush_tlb)
5727 return slot_handle_level_range(kvm, memslot, fn, start_level,
5728 end_level, memslot->base_gfn,
5729 memslot->base_gfn + memslot->npages - 1,
5733 static __always_inline bool
5734 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5735 slot_level_handler fn, bool lock_flush_tlb)
5737 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5738 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5741 static __always_inline bool
5742 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5743 slot_level_handler fn, bool lock_flush_tlb)
5745 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5746 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5749 static __always_inline bool
5750 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5751 slot_level_handler fn, bool lock_flush_tlb)
5753 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5754 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5757 static void free_mmu_pages(struct kvm_mmu *mmu)
5759 free_page((unsigned long)mmu->pae_root);
5760 free_page((unsigned long)mmu->lm_root);
5763 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5769 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5770 * while the PDP table is a per-vCPU construct that's allocated at MMU
5771 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5772 * x86_64. Therefore we need to allocate the PDP table in the first
5773 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5774 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5775 * skip allocating the PDP table.
5777 if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5780 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5784 mmu->pae_root = page_address(page);
5785 for (i = 0; i < 4; ++i)
5786 mmu->pae_root[i] = INVALID_PAGE;
5791 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5796 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5797 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5799 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5800 vcpu->arch.root_mmu.root_cr3 = 0;
5801 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5802 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5803 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5805 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5806 vcpu->arch.guest_mmu.root_cr3 = 0;
5807 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5808 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5809 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5811 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5813 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5817 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5819 goto fail_allocate_root;
5823 free_mmu_pages(&vcpu->arch.guest_mmu);
5827 #define BATCH_ZAP_PAGES 10
5828 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5830 struct kvm_mmu_page *sp, *node;
5831 int nr_zapped, batch = 0;
5834 list_for_each_entry_safe_reverse(sp, node,
5835 &kvm->arch.active_mmu_pages, link) {
5837 * No obsolete valid page exists before a newly created page
5838 * since active_mmu_pages is a FIFO list.
5840 if (!is_obsolete_sp(kvm, sp))
5844 * Skip invalid pages with a non-zero root count, zapping pages
5845 * with a non-zero root count will never succeed, i.e. the page
5846 * will get thrown back on active_mmu_pages and we'll get stuck
5847 * in an infinite loop.
5849 if (sp->role.invalid && sp->root_count)
5853 * No need to flush the TLB since we're only zapping shadow
5854 * pages with an obsolete generation number and all vCPUS have
5855 * loaded a new root, i.e. the shadow pages being zapped cannot
5856 * be in active use by the guest.
5858 if (batch >= BATCH_ZAP_PAGES &&
5859 cond_resched_lock(&kvm->mmu_lock)) {
5864 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5865 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5872 * Trigger a remote TLB flush before freeing the page tables to ensure
5873 * KVM is not in the middle of a lockless shadow page table walk, which
5874 * may reference the pages.
5876 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5880 * Fast invalidate all shadow pages and use lock-break technique
5881 * to zap obsolete pages.
5883 * It's required when memslot is being deleted or VM is being
5884 * destroyed, in these cases, we should ensure that KVM MMU does
5885 * not use any resource of the being-deleted slot or all slots
5886 * after calling the function.
5888 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5890 lockdep_assert_held(&kvm->slots_lock);
5892 spin_lock(&kvm->mmu_lock);
5893 trace_kvm_mmu_zap_all_fast(kvm);
5896 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5897 * held for the entire duration of zapping obsolete pages, it's
5898 * impossible for there to be multiple invalid generations associated
5899 * with *valid* shadow pages at any given time, i.e. there is exactly
5900 * one valid generation and (at most) one invalid generation.
5902 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5905 * Notify all vcpus to reload its shadow page table and flush TLB.
5906 * Then all vcpus will switch to new shadow page table with the new
5909 * Note: we need to do this under the protection of mmu_lock,
5910 * otherwise, vcpu would purge shadow page but miss tlb flush.
5912 kvm_reload_remote_mmus(kvm);
5914 kvm_zap_obsolete_pages(kvm);
5915 spin_unlock(&kvm->mmu_lock);
5918 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5920 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5923 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5924 struct kvm_memory_slot *slot,
5925 struct kvm_page_track_notifier_node *node)
5927 kvm_mmu_zap_all_fast(kvm);
5930 void kvm_mmu_init_vm(struct kvm *kvm)
5932 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5934 node->track_write = kvm_mmu_pte_write;
5935 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5936 kvm_page_track_register_notifier(kvm, node);
5939 void kvm_mmu_uninit_vm(struct kvm *kvm)
5941 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5943 kvm_page_track_unregister_notifier(kvm, node);
5946 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5948 struct kvm_memslots *slots;
5949 struct kvm_memory_slot *memslot;
5952 spin_lock(&kvm->mmu_lock);
5953 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5954 slots = __kvm_memslots(kvm, i);
5955 kvm_for_each_memslot(memslot, slots) {
5958 start = max(gfn_start, memslot->base_gfn);
5959 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5963 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5964 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5965 start, end - 1, true);
5969 spin_unlock(&kvm->mmu_lock);
5972 static bool slot_rmap_write_protect(struct kvm *kvm,
5973 struct kvm_rmap_head *rmap_head)
5975 return __rmap_write_protect(kvm, rmap_head, false);
5978 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5979 struct kvm_memory_slot *memslot)
5983 spin_lock(&kvm->mmu_lock);
5984 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5986 spin_unlock(&kvm->mmu_lock);
5989 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5990 * which do tlb flush out of mmu-lock should be serialized by
5991 * kvm->slots_lock otherwise tlb flush would be missed.
5993 lockdep_assert_held(&kvm->slots_lock);
5996 * We can flush all the TLBs out of the mmu lock without TLB
5997 * corruption since we just change the spte from writable to
5998 * readonly so that we only need to care the case of changing
5999 * spte from present to present (changing the spte from present
6000 * to nonpresent will flush all the TLBs immediately), in other
6001 * words, the only case we care is mmu_spte_update() where we
6002 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
6003 * instead of PT_WRITABLE_MASK, that means it does not depend
6004 * on PT_WRITABLE_MASK anymore.
6007 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6011 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
6012 struct kvm_rmap_head *rmap_head)
6015 struct rmap_iterator iter;
6016 int need_tlb_flush = 0;
6018 struct kvm_mmu_page *sp;
6021 for_each_rmap_spte(rmap_head, &iter, sptep) {
6022 sp = page_header(__pa(sptep));
6023 pfn = spte_to_pfn(*sptep);
6026 * We cannot do huge page mapping for indirect shadow pages,
6027 * which are found on the last rmap (level = 1) when not using
6028 * tdp; such shadow pages are synced with the page table in
6029 * the guest, and the guest page table is using 4K page size
6030 * mapping if the indirect sp has level = 1.
6032 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
6033 !kvm_is_zone_device_pfn(pfn) &&
6034 PageTransCompoundMap(pfn_to_page(pfn))) {
6035 pte_list_remove(rmap_head, sptep);
6037 if (kvm_available_flush_tlb_with_range())
6038 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
6039 KVM_PAGES_PER_HPAGE(sp->role.level));
6047 return need_tlb_flush;
6050 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6051 const struct kvm_memory_slot *memslot)
6053 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
6054 spin_lock(&kvm->mmu_lock);
6055 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
6056 kvm_mmu_zap_collapsible_spte, true);
6057 spin_unlock(&kvm->mmu_lock);
6060 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6061 struct kvm_memory_slot *memslot)
6065 spin_lock(&kvm->mmu_lock);
6066 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
6067 spin_unlock(&kvm->mmu_lock);
6069 lockdep_assert_held(&kvm->slots_lock);
6072 * It's also safe to flush TLBs out of mmu lock here as currently this
6073 * function is only used for dirty logging, in which case flushing TLB
6074 * out of mmu lock also guarantees no dirty pages will be lost in
6078 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6081 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
6083 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
6084 struct kvm_memory_slot *memslot)
6088 spin_lock(&kvm->mmu_lock);
6089 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
6091 spin_unlock(&kvm->mmu_lock);
6093 /* see kvm_mmu_slot_remove_write_access */
6094 lockdep_assert_held(&kvm->slots_lock);
6097 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6100 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
6102 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
6103 struct kvm_memory_slot *memslot)
6107 spin_lock(&kvm->mmu_lock);
6108 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
6109 spin_unlock(&kvm->mmu_lock);
6111 lockdep_assert_held(&kvm->slots_lock);
6113 /* see kvm_mmu_slot_leaf_clear_dirty */
6115 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6118 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
6120 void kvm_mmu_zap_all(struct kvm *kvm)
6122 struct kvm_mmu_page *sp, *node;
6123 LIST_HEAD(invalid_list);
6126 spin_lock(&kvm->mmu_lock);
6128 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6129 if (sp->role.invalid && sp->root_count)
6131 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6133 if (cond_resched_lock(&kvm->mmu_lock))
6137 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6138 spin_unlock(&kvm->mmu_lock);
6141 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6143 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6145 gen &= MMIO_SPTE_GEN_MASK;
6148 * Generation numbers are incremented in multiples of the number of
6149 * address spaces in order to provide unique generations across all
6150 * address spaces. Strip what is effectively the address space
6151 * modifier prior to checking for a wrap of the MMIO generation so
6152 * that a wrap in any address space is detected.
6154 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6157 * The very rare case: if the MMIO generation number has wrapped,
6158 * zap all shadow pages.
6160 if (unlikely(gen == 0)) {
6161 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6162 kvm_mmu_zap_all_fast(kvm);
6166 static unsigned long
6167 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6170 int nr_to_scan = sc->nr_to_scan;
6171 unsigned long freed = 0;
6173 mutex_lock(&kvm_lock);
6175 list_for_each_entry(kvm, &vm_list, vm_list) {
6177 LIST_HEAD(invalid_list);
6180 * Never scan more than sc->nr_to_scan VM instances.
6181 * Will not hit this condition practically since we do not try
6182 * to shrink more than one VM and it is very unlikely to see
6183 * !n_used_mmu_pages so many times.
6188 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6189 * here. We may skip a VM instance errorneosly, but we do not
6190 * want to shrink a VM that only started to populate its MMU
6193 if (!kvm->arch.n_used_mmu_pages &&
6194 !kvm_has_zapped_obsolete_pages(kvm))
6197 idx = srcu_read_lock(&kvm->srcu);
6198 spin_lock(&kvm->mmu_lock);
6200 if (kvm_has_zapped_obsolete_pages(kvm)) {
6201 kvm_mmu_commit_zap_page(kvm,
6202 &kvm->arch.zapped_obsolete_pages);
6206 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6208 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6211 spin_unlock(&kvm->mmu_lock);
6212 srcu_read_unlock(&kvm->srcu, idx);
6215 * unfair on small ones
6216 * per-vm shrinkers cry out
6217 * sadness comes quickly
6219 list_move_tail(&kvm->vm_list, &vm_list);
6223 mutex_unlock(&kvm_lock);
6227 static unsigned long
6228 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6230 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6233 static struct shrinker mmu_shrinker = {
6234 .count_objects = mmu_shrink_count,
6235 .scan_objects = mmu_shrink_scan,
6236 .seeks = DEFAULT_SEEKS * 10,
6239 static void mmu_destroy_caches(void)
6241 kmem_cache_destroy(pte_list_desc_cache);
6242 kmem_cache_destroy(mmu_page_header_cache);
6245 static void kvm_set_mmio_spte_mask(void)
6250 * Set the reserved bits and the present bit of an paging-structure
6251 * entry to generate page fault with PFER.RSV = 1.
6255 * Mask the uppermost physical address bit, which would be reserved as
6256 * long as the supported physical address width is less than 52.
6260 /* Set the present bit. */
6264 * If reserved bit is not supported, clear the present bit to disable
6267 if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
6270 kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
6273 static bool get_nx_auto_mode(void)
6275 /* Return true when CPU has the bug, and mitigations are ON */
6276 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6279 static void __set_nx_huge_pages(bool val)
6281 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6284 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6286 bool old_val = nx_huge_pages;
6289 /* In "auto" mode deploy workaround only if CPU has the bug. */
6290 if (sysfs_streq(val, "off"))
6292 else if (sysfs_streq(val, "force"))
6294 else if (sysfs_streq(val, "auto"))
6295 new_val = get_nx_auto_mode();
6296 else if (strtobool(val, &new_val) < 0)
6299 __set_nx_huge_pages(new_val);
6301 if (new_val != old_val) {
6304 mutex_lock(&kvm_lock);
6306 list_for_each_entry(kvm, &vm_list, vm_list) {
6307 mutex_lock(&kvm->slots_lock);
6308 kvm_mmu_zap_all_fast(kvm);
6309 mutex_unlock(&kvm->slots_lock);
6311 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6313 mutex_unlock(&kvm_lock);
6319 int kvm_mmu_module_init(void)
6323 if (nx_huge_pages == -1)
6324 __set_nx_huge_pages(get_nx_auto_mode());
6327 * MMU roles use union aliasing which is, generally speaking, an
6328 * undefined behavior. However, we supposedly know how compilers behave
6329 * and the current status quo is unlikely to change. Guardians below are
6330 * supposed to let us know if the assumption becomes false.
6332 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6333 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6334 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6336 kvm_mmu_reset_all_pte_masks();
6338 kvm_set_mmio_spte_mask();
6340 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6341 sizeof(struct pte_list_desc),
6342 0, SLAB_ACCOUNT, NULL);
6343 if (!pte_list_desc_cache)
6346 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6347 sizeof(struct kvm_mmu_page),
6348 0, SLAB_ACCOUNT, NULL);
6349 if (!mmu_page_header_cache)
6352 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6355 ret = register_shrinker(&mmu_shrinker);
6362 mmu_destroy_caches();
6367 * Calculate mmu pages needed for kvm.
6369 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6371 unsigned long nr_mmu_pages;
6372 unsigned long nr_pages = 0;
6373 struct kvm_memslots *slots;
6374 struct kvm_memory_slot *memslot;
6377 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6378 slots = __kvm_memslots(kvm, i);
6380 kvm_for_each_memslot(memslot, slots)
6381 nr_pages += memslot->npages;
6384 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6385 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6387 return nr_mmu_pages;
6390 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6392 kvm_mmu_unload(vcpu);
6393 free_mmu_pages(&vcpu->arch.root_mmu);
6394 free_mmu_pages(&vcpu->arch.guest_mmu);
6395 mmu_free_memory_caches(vcpu);
6398 void kvm_mmu_module_exit(void)
6400 mmu_destroy_caches();
6401 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6402 unregister_shrinker(&mmu_shrinker);
6403 mmu_audit_disable();
6406 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6408 unsigned int old_val;
6411 old_val = nx_huge_pages_recovery_ratio;
6412 err = param_set_uint(val, kp);
6416 if (READ_ONCE(nx_huge_pages) &&
6417 !old_val && nx_huge_pages_recovery_ratio) {
6420 mutex_lock(&kvm_lock);
6422 list_for_each_entry(kvm, &vm_list, vm_list)
6423 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6425 mutex_unlock(&kvm_lock);
6431 static void kvm_recover_nx_lpages(struct kvm *kvm)
6434 struct kvm_mmu_page *sp;
6436 LIST_HEAD(invalid_list);
6439 rcu_idx = srcu_read_lock(&kvm->srcu);
6440 spin_lock(&kvm->mmu_lock);
6442 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6443 to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
6444 while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
6446 * We use a separate list instead of just using active_mmu_pages
6447 * because the number of lpage_disallowed pages is expected to
6448 * be relatively small compared to the total.
6450 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6451 struct kvm_mmu_page,
6452 lpage_disallowed_link);
6453 WARN_ON_ONCE(!sp->lpage_disallowed);
6454 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6455 WARN_ON_ONCE(sp->lpage_disallowed);
6457 if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
6458 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6460 cond_resched_lock(&kvm->mmu_lock);
6464 spin_unlock(&kvm->mmu_lock);
6465 srcu_read_unlock(&kvm->srcu, rcu_idx);
6468 static long get_nx_lpage_recovery_timeout(u64 start_time)
6470 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6471 ? start_time + 60 * HZ - get_jiffies_64()
6472 : MAX_SCHEDULE_TIMEOUT;
6475 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6478 long remaining_time;
6481 start_time = get_jiffies_64();
6482 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6484 set_current_state(TASK_INTERRUPTIBLE);
6485 while (!kthread_should_stop() && remaining_time > 0) {
6486 schedule_timeout(remaining_time);
6487 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6488 set_current_state(TASK_INTERRUPTIBLE);
6491 set_current_state(TASK_RUNNING);
6493 if (kthread_should_stop())
6496 kvm_recover_nx_lpages(kvm);
6500 int kvm_mmu_post_init_vm(struct kvm *kvm)
6504 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6505 "kvm-nx-lpage-recovery",
6506 &kvm->arch.nx_lpage_recovery_thread);
6508 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6513 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6515 if (kvm->arch.nx_lpage_recovery_thread)
6516 kthread_stop(kvm->arch.nx_lpage_recovery_thread);