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(17, 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 PT64_SECOND_AVAIL_BITS_SHIFT
429 #define MMIO_SPTE_GEN_HIGH_END 62
430 #define MMIO_SPTE_GEN_HIGH_MASK GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
431 MMIO_SPTE_GEN_HIGH_START)
433 static u64 generation_mmio_spte_mask(u64 gen)
437 WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
438 BUILD_BUG_ON((MMIO_SPTE_GEN_HIGH_MASK | MMIO_SPTE_GEN_LOW_MASK) & SPTE_SPECIAL_MASK);
440 mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
441 mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
445 static u64 get_mmio_spte_generation(u64 spte)
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 inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1292 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1294 if (no_dirty_log && slot->dirty_bitmap)
1300 static struct kvm_memory_slot *
1301 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1304 struct kvm_memory_slot *slot;
1306 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1307 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1313 static int max_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn,
1316 struct kvm_memory_slot *slot;
1318 if (unlikely(max_level == PT_PAGE_TABLE_LEVEL))
1319 return PT_PAGE_TABLE_LEVEL;
1321 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1322 if (!memslot_valid_for_gpte(slot, true))
1323 return PT_PAGE_TABLE_LEVEL;
1325 max_level = min(max_level, kvm_x86_ops->get_lpage_level());
1326 for ( ; max_level > PT_PAGE_TABLE_LEVEL; max_level--) {
1327 if (!__mmu_gfn_lpage_is_disallowed(gfn, max_level, slot))
1335 * About rmap_head encoding:
1337 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1338 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1339 * pte_list_desc containing more mappings.
1343 * Returns the number of pointers in the rmap chain, not counting the new one.
1345 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1346 struct kvm_rmap_head *rmap_head)
1348 struct pte_list_desc *desc;
1351 if (!rmap_head->val) {
1352 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1353 rmap_head->val = (unsigned long)spte;
1354 } else if (!(rmap_head->val & 1)) {
1355 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1356 desc = mmu_alloc_pte_list_desc(vcpu);
1357 desc->sptes[0] = (u64 *)rmap_head->val;
1358 desc->sptes[1] = spte;
1359 rmap_head->val = (unsigned long)desc | 1;
1362 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1363 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1364 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1366 count += PTE_LIST_EXT;
1368 if (desc->sptes[PTE_LIST_EXT-1]) {
1369 desc->more = mmu_alloc_pte_list_desc(vcpu);
1372 for (i = 0; desc->sptes[i]; ++i)
1374 desc->sptes[i] = spte;
1380 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1381 struct pte_list_desc *desc, int i,
1382 struct pte_list_desc *prev_desc)
1386 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1388 desc->sptes[i] = desc->sptes[j];
1389 desc->sptes[j] = NULL;
1392 if (!prev_desc && !desc->more)
1396 prev_desc->more = desc->more;
1398 rmap_head->val = (unsigned long)desc->more | 1;
1399 mmu_free_pte_list_desc(desc);
1402 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1404 struct pte_list_desc *desc;
1405 struct pte_list_desc *prev_desc;
1408 if (!rmap_head->val) {
1409 pr_err("%s: %p 0->BUG\n", __func__, spte);
1411 } else if (!(rmap_head->val & 1)) {
1412 rmap_printk("%s: %p 1->0\n", __func__, spte);
1413 if ((u64 *)rmap_head->val != spte) {
1414 pr_err("%s: %p 1->BUG\n", __func__, spte);
1419 rmap_printk("%s: %p many->many\n", __func__, spte);
1420 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1423 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1424 if (desc->sptes[i] == spte) {
1425 pte_list_desc_remove_entry(rmap_head,
1426 desc, i, prev_desc);
1433 pr_err("%s: %p many->many\n", __func__, spte);
1438 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1440 mmu_spte_clear_track_bits(sptep);
1441 __pte_list_remove(sptep, rmap_head);
1444 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1445 struct kvm_memory_slot *slot)
1449 idx = gfn_to_index(gfn, slot->base_gfn, level);
1450 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1453 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1454 struct kvm_mmu_page *sp)
1456 struct kvm_memslots *slots;
1457 struct kvm_memory_slot *slot;
1459 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1460 slot = __gfn_to_memslot(slots, gfn);
1461 return __gfn_to_rmap(gfn, sp->role.level, slot);
1464 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1466 struct kvm_mmu_memory_cache *cache;
1468 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1469 return mmu_memory_cache_free_objects(cache);
1472 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1474 struct kvm_mmu_page *sp;
1475 struct kvm_rmap_head *rmap_head;
1477 sp = page_header(__pa(spte));
1478 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1479 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1480 return pte_list_add(vcpu, spte, rmap_head);
1483 static void rmap_remove(struct kvm *kvm, u64 *spte)
1485 struct kvm_mmu_page *sp;
1487 struct kvm_rmap_head *rmap_head;
1489 sp = page_header(__pa(spte));
1490 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1491 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1492 __pte_list_remove(spte, rmap_head);
1496 * Used by the following functions to iterate through the sptes linked by a
1497 * rmap. All fields are private and not assumed to be used outside.
1499 struct rmap_iterator {
1500 /* private fields */
1501 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1502 int pos; /* index of the sptep */
1506 * Iteration must be started by this function. This should also be used after
1507 * removing/dropping sptes from the rmap link because in such cases the
1508 * information in the iterator may not be valid.
1510 * Returns sptep if found, NULL otherwise.
1512 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1513 struct rmap_iterator *iter)
1517 if (!rmap_head->val)
1520 if (!(rmap_head->val & 1)) {
1522 sptep = (u64 *)rmap_head->val;
1526 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1528 sptep = iter->desc->sptes[iter->pos];
1530 BUG_ON(!is_shadow_present_pte(*sptep));
1535 * Must be used with a valid iterator: e.g. after rmap_get_first().
1537 * Returns sptep if found, NULL otherwise.
1539 static u64 *rmap_get_next(struct rmap_iterator *iter)
1544 if (iter->pos < PTE_LIST_EXT - 1) {
1546 sptep = iter->desc->sptes[iter->pos];
1551 iter->desc = iter->desc->more;
1555 /* desc->sptes[0] cannot be NULL */
1556 sptep = iter->desc->sptes[iter->pos];
1563 BUG_ON(!is_shadow_present_pte(*sptep));
1567 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1568 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1569 _spte_; _spte_ = rmap_get_next(_iter_))
1571 static void drop_spte(struct kvm *kvm, u64 *sptep)
1573 if (mmu_spte_clear_track_bits(sptep))
1574 rmap_remove(kvm, sptep);
1578 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1580 if (is_large_pte(*sptep)) {
1581 WARN_ON(page_header(__pa(sptep))->role.level ==
1582 PT_PAGE_TABLE_LEVEL);
1583 drop_spte(kvm, sptep);
1591 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1593 if (__drop_large_spte(vcpu->kvm, sptep)) {
1594 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1596 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1597 KVM_PAGES_PER_HPAGE(sp->role.level));
1602 * Write-protect on the specified @sptep, @pt_protect indicates whether
1603 * spte write-protection is caused by protecting shadow page table.
1605 * Note: write protection is difference between dirty logging and spte
1607 * - for dirty logging, the spte can be set to writable at anytime if
1608 * its dirty bitmap is properly set.
1609 * - for spte protection, the spte can be writable only after unsync-ing
1612 * Return true if tlb need be flushed.
1614 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1618 if (!is_writable_pte(spte) &&
1619 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1622 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1625 spte &= ~SPTE_MMU_WRITEABLE;
1626 spte = spte & ~PT_WRITABLE_MASK;
1628 return mmu_spte_update(sptep, spte);
1631 static bool __rmap_write_protect(struct kvm *kvm,
1632 struct kvm_rmap_head *rmap_head,
1636 struct rmap_iterator iter;
1639 for_each_rmap_spte(rmap_head, &iter, sptep)
1640 flush |= spte_write_protect(sptep, pt_protect);
1645 static bool spte_clear_dirty(u64 *sptep)
1649 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1651 MMU_WARN_ON(!spte_ad_enabled(spte));
1652 spte &= ~shadow_dirty_mask;
1653 return mmu_spte_update(sptep, spte);
1656 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1658 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1659 (unsigned long *)sptep);
1660 if (was_writable && !spte_ad_enabled(*sptep))
1661 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1663 return was_writable;
1667 * Gets the GFN ready for another round of dirty logging by clearing the
1668 * - D bit on ad-enabled SPTEs, and
1669 * - W bit on ad-disabled SPTEs.
1670 * Returns true iff any D or W bits were cleared.
1672 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1675 struct rmap_iterator iter;
1678 for_each_rmap_spte(rmap_head, &iter, sptep)
1679 if (spte_ad_need_write_protect(*sptep))
1680 flush |= spte_wrprot_for_clear_dirty(sptep);
1682 flush |= spte_clear_dirty(sptep);
1687 static bool spte_set_dirty(u64 *sptep)
1691 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1694 * Similar to the !kvm_x86_ops->slot_disable_log_dirty case,
1695 * do not bother adding back write access to pages marked
1696 * SPTE_AD_WRPROT_ONLY_MASK.
1698 spte |= shadow_dirty_mask;
1700 return mmu_spte_update(sptep, spte);
1703 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1706 struct rmap_iterator iter;
1709 for_each_rmap_spte(rmap_head, &iter, sptep)
1710 if (spte_ad_enabled(*sptep))
1711 flush |= spte_set_dirty(sptep);
1717 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1718 * @kvm: kvm instance
1719 * @slot: slot to protect
1720 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1721 * @mask: indicates which pages we should protect
1723 * Used when we do not need to care about huge page mappings: e.g. during dirty
1724 * logging we do not have any such mappings.
1726 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1727 struct kvm_memory_slot *slot,
1728 gfn_t gfn_offset, unsigned long mask)
1730 struct kvm_rmap_head *rmap_head;
1733 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1734 PT_PAGE_TABLE_LEVEL, slot);
1735 __rmap_write_protect(kvm, rmap_head, false);
1737 /* clear the first set bit */
1743 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1744 * protect the page if the D-bit isn't supported.
1745 * @kvm: kvm instance
1746 * @slot: slot to clear D-bit
1747 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1748 * @mask: indicates which pages we should clear D-bit
1750 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1752 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1753 struct kvm_memory_slot *slot,
1754 gfn_t gfn_offset, unsigned long mask)
1756 struct kvm_rmap_head *rmap_head;
1759 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1760 PT_PAGE_TABLE_LEVEL, slot);
1761 __rmap_clear_dirty(kvm, rmap_head);
1763 /* clear the first set bit */
1767 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1770 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1773 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1774 * enable dirty logging for them.
1776 * Used when we do not need to care about huge page mappings: e.g. during dirty
1777 * logging we do not have any such mappings.
1779 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1780 struct kvm_memory_slot *slot,
1781 gfn_t gfn_offset, unsigned long mask)
1783 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1784 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1787 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1791 * kvm_arch_write_log_dirty - emulate dirty page logging
1792 * @vcpu: Guest mode vcpu
1794 * Emulate arch specific page modification logging for the
1797 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1799 if (kvm_x86_ops->write_log_dirty)
1800 return kvm_x86_ops->write_log_dirty(vcpu);
1805 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1806 struct kvm_memory_slot *slot, u64 gfn)
1808 struct kvm_rmap_head *rmap_head;
1810 bool write_protected = false;
1812 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1813 rmap_head = __gfn_to_rmap(gfn, i, slot);
1814 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1817 return write_protected;
1820 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1822 struct kvm_memory_slot *slot;
1824 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1825 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1828 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1831 struct rmap_iterator iter;
1834 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1835 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1837 pte_list_remove(rmap_head, sptep);
1844 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1845 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1848 return kvm_zap_rmapp(kvm, rmap_head);
1851 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1852 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1856 struct rmap_iterator iter;
1859 pte_t *ptep = (pte_t *)data;
1862 WARN_ON(pte_huge(*ptep));
1863 new_pfn = pte_pfn(*ptep);
1866 for_each_rmap_spte(rmap_head, &iter, sptep) {
1867 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1868 sptep, *sptep, gfn, level);
1872 if (pte_write(*ptep)) {
1873 pte_list_remove(rmap_head, sptep);
1876 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1877 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1879 new_spte &= ~PT_WRITABLE_MASK;
1880 new_spte &= ~SPTE_HOST_WRITEABLE;
1882 new_spte = mark_spte_for_access_track(new_spte);
1884 mmu_spte_clear_track_bits(sptep);
1885 mmu_spte_set(sptep, new_spte);
1889 if (need_flush && kvm_available_flush_tlb_with_range()) {
1890 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1897 struct slot_rmap_walk_iterator {
1899 struct kvm_memory_slot *slot;
1905 /* output fields. */
1907 struct kvm_rmap_head *rmap;
1910 /* private field. */
1911 struct kvm_rmap_head *end_rmap;
1915 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1917 iterator->level = level;
1918 iterator->gfn = iterator->start_gfn;
1919 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1920 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1925 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1926 struct kvm_memory_slot *slot, int start_level,
1927 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1929 iterator->slot = slot;
1930 iterator->start_level = start_level;
1931 iterator->end_level = end_level;
1932 iterator->start_gfn = start_gfn;
1933 iterator->end_gfn = end_gfn;
1935 rmap_walk_init_level(iterator, iterator->start_level);
1938 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1940 return !!iterator->rmap;
1943 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1945 if (++iterator->rmap <= iterator->end_rmap) {
1946 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1950 if (++iterator->level > iterator->end_level) {
1951 iterator->rmap = NULL;
1955 rmap_walk_init_level(iterator, iterator->level);
1958 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1959 _start_gfn, _end_gfn, _iter_) \
1960 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1961 _end_level_, _start_gfn, _end_gfn); \
1962 slot_rmap_walk_okay(_iter_); \
1963 slot_rmap_walk_next(_iter_))
1965 static int kvm_handle_hva_range(struct kvm *kvm,
1966 unsigned long start,
1969 int (*handler)(struct kvm *kvm,
1970 struct kvm_rmap_head *rmap_head,
1971 struct kvm_memory_slot *slot,
1974 unsigned long data))
1976 struct kvm_memslots *slots;
1977 struct kvm_memory_slot *memslot;
1978 struct slot_rmap_walk_iterator iterator;
1982 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1983 slots = __kvm_memslots(kvm, i);
1984 kvm_for_each_memslot(memslot, slots) {
1985 unsigned long hva_start, hva_end;
1986 gfn_t gfn_start, gfn_end;
1988 hva_start = max(start, memslot->userspace_addr);
1989 hva_end = min(end, memslot->userspace_addr +
1990 (memslot->npages << PAGE_SHIFT));
1991 if (hva_start >= hva_end)
1994 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1995 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1997 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1998 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
2000 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
2001 PT_MAX_HUGEPAGE_LEVEL,
2002 gfn_start, gfn_end - 1,
2004 ret |= handler(kvm, iterator.rmap, memslot,
2005 iterator.gfn, iterator.level, data);
2012 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
2014 int (*handler)(struct kvm *kvm,
2015 struct kvm_rmap_head *rmap_head,
2016 struct kvm_memory_slot *slot,
2017 gfn_t gfn, int level,
2018 unsigned long data))
2020 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
2023 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
2025 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
2028 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
2030 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
2033 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
2034 struct kvm_memory_slot *slot, gfn_t gfn, int level,
2038 struct rmap_iterator uninitialized_var(iter);
2041 for_each_rmap_spte(rmap_head, &iter, sptep)
2042 young |= mmu_spte_age(sptep);
2044 trace_kvm_age_page(gfn, level, slot, young);
2048 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
2049 struct kvm_memory_slot *slot, gfn_t gfn,
2050 int level, unsigned long data)
2053 struct rmap_iterator iter;
2055 for_each_rmap_spte(rmap_head, &iter, sptep)
2056 if (is_accessed_spte(*sptep))
2061 #define RMAP_RECYCLE_THRESHOLD 1000
2063 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2065 struct kvm_rmap_head *rmap_head;
2066 struct kvm_mmu_page *sp;
2068 sp = page_header(__pa(spte));
2070 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2072 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2073 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
2074 KVM_PAGES_PER_HPAGE(sp->role.level));
2077 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2079 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2082 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2084 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2088 static int is_empty_shadow_page(u64 *spt)
2093 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2094 if (is_shadow_present_pte(*pos)) {
2095 printk(KERN_ERR "%s: %p %llx\n", __func__,
2104 * This value is the sum of all of the kvm instances's
2105 * kvm->arch.n_used_mmu_pages values. We need a global,
2106 * aggregate version in order to make the slab shrinker
2109 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2111 kvm->arch.n_used_mmu_pages += nr;
2112 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2115 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2117 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2118 hlist_del(&sp->hash_link);
2119 list_del(&sp->link);
2120 free_page((unsigned long)sp->spt);
2121 if (!sp->role.direct)
2122 free_page((unsigned long)sp->gfns);
2123 kmem_cache_free(mmu_page_header_cache, sp);
2126 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2128 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2131 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2132 struct kvm_mmu_page *sp, u64 *parent_pte)
2137 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2140 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2143 __pte_list_remove(parent_pte, &sp->parent_ptes);
2146 static void drop_parent_pte(struct kvm_mmu_page *sp,
2149 mmu_page_remove_parent_pte(sp, parent_pte);
2150 mmu_spte_clear_no_track(parent_pte);
2153 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2155 struct kvm_mmu_page *sp;
2157 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2158 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2160 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2161 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2164 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2165 * depends on valid pages being added to the head of the list. See
2166 * comments in kvm_zap_obsolete_pages().
2168 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2169 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2170 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2174 static void mark_unsync(u64 *spte);
2175 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2178 struct rmap_iterator iter;
2180 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2185 static void mark_unsync(u64 *spte)
2187 struct kvm_mmu_page *sp;
2190 sp = page_header(__pa(spte));
2191 index = spte - sp->spt;
2192 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2194 if (sp->unsync_children++)
2196 kvm_mmu_mark_parents_unsync(sp);
2199 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2200 struct kvm_mmu_page *sp)
2205 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2209 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2210 struct kvm_mmu_page *sp, u64 *spte,
2216 #define KVM_PAGE_ARRAY_NR 16
2218 struct kvm_mmu_pages {
2219 struct mmu_page_and_offset {
2220 struct kvm_mmu_page *sp;
2222 } page[KVM_PAGE_ARRAY_NR];
2226 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2232 for (i=0; i < pvec->nr; i++)
2233 if (pvec->page[i].sp == sp)
2236 pvec->page[pvec->nr].sp = sp;
2237 pvec->page[pvec->nr].idx = idx;
2239 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2242 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2244 --sp->unsync_children;
2245 WARN_ON((int)sp->unsync_children < 0);
2246 __clear_bit(idx, sp->unsync_child_bitmap);
2249 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2250 struct kvm_mmu_pages *pvec)
2252 int i, ret, nr_unsync_leaf = 0;
2254 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2255 struct kvm_mmu_page *child;
2256 u64 ent = sp->spt[i];
2258 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2259 clear_unsync_child_bit(sp, i);
2263 child = page_header(ent & PT64_BASE_ADDR_MASK);
2265 if (child->unsync_children) {
2266 if (mmu_pages_add(pvec, child, i))
2269 ret = __mmu_unsync_walk(child, pvec);
2271 clear_unsync_child_bit(sp, i);
2273 } else if (ret > 0) {
2274 nr_unsync_leaf += ret;
2277 } else if (child->unsync) {
2279 if (mmu_pages_add(pvec, child, i))
2282 clear_unsync_child_bit(sp, i);
2285 return nr_unsync_leaf;
2288 #define INVALID_INDEX (-1)
2290 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2291 struct kvm_mmu_pages *pvec)
2294 if (!sp->unsync_children)
2297 mmu_pages_add(pvec, sp, INVALID_INDEX);
2298 return __mmu_unsync_walk(sp, pvec);
2301 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2303 WARN_ON(!sp->unsync);
2304 trace_kvm_mmu_sync_page(sp);
2306 --kvm->stat.mmu_unsync;
2309 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2310 struct list_head *invalid_list);
2311 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2312 struct list_head *invalid_list);
2315 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2316 hlist_for_each_entry(_sp, \
2317 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2318 if (is_obsolete_sp((_kvm), (_sp))) { \
2321 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2322 for_each_valid_sp(_kvm, _sp, _gfn) \
2323 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2325 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2327 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2330 /* @sp->gfn should be write-protected at the call site */
2331 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2332 struct list_head *invalid_list)
2334 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2335 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2336 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2343 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2344 struct list_head *invalid_list,
2347 if (!remote_flush && list_empty(invalid_list))
2350 if (!list_empty(invalid_list))
2351 kvm_mmu_commit_zap_page(kvm, invalid_list);
2353 kvm_flush_remote_tlbs(kvm);
2357 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2358 struct list_head *invalid_list,
2359 bool remote_flush, bool local_flush)
2361 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2365 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2368 #ifdef CONFIG_KVM_MMU_AUDIT
2369 #include "mmu_audit.c"
2371 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2372 static void mmu_audit_disable(void) { }
2375 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2377 return sp->role.invalid ||
2378 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2381 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2382 struct list_head *invalid_list)
2384 kvm_unlink_unsync_page(vcpu->kvm, sp);
2385 return __kvm_sync_page(vcpu, sp, invalid_list);
2388 /* @gfn should be write-protected at the call site */
2389 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2390 struct list_head *invalid_list)
2392 struct kvm_mmu_page *s;
2395 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2399 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2400 ret |= kvm_sync_page(vcpu, s, invalid_list);
2406 struct mmu_page_path {
2407 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2408 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2411 #define for_each_sp(pvec, sp, parents, i) \
2412 for (i = mmu_pages_first(&pvec, &parents); \
2413 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2414 i = mmu_pages_next(&pvec, &parents, i))
2416 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2417 struct mmu_page_path *parents,
2422 for (n = i+1; n < pvec->nr; n++) {
2423 struct kvm_mmu_page *sp = pvec->page[n].sp;
2424 unsigned idx = pvec->page[n].idx;
2425 int level = sp->role.level;
2427 parents->idx[level-1] = idx;
2428 if (level == PT_PAGE_TABLE_LEVEL)
2431 parents->parent[level-2] = sp;
2437 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2438 struct mmu_page_path *parents)
2440 struct kvm_mmu_page *sp;
2446 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2448 sp = pvec->page[0].sp;
2449 level = sp->role.level;
2450 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2452 parents->parent[level-2] = sp;
2454 /* Also set up a sentinel. Further entries in pvec are all
2455 * children of sp, so this element is never overwritten.
2457 parents->parent[level-1] = NULL;
2458 return mmu_pages_next(pvec, parents, 0);
2461 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2463 struct kvm_mmu_page *sp;
2464 unsigned int level = 0;
2467 unsigned int idx = parents->idx[level];
2468 sp = parents->parent[level];
2472 WARN_ON(idx == INVALID_INDEX);
2473 clear_unsync_child_bit(sp, idx);
2475 } while (!sp->unsync_children);
2478 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2479 struct kvm_mmu_page *parent)
2482 struct kvm_mmu_page *sp;
2483 struct mmu_page_path parents;
2484 struct kvm_mmu_pages pages;
2485 LIST_HEAD(invalid_list);
2488 while (mmu_unsync_walk(parent, &pages)) {
2489 bool protected = false;
2491 for_each_sp(pages, sp, parents, i)
2492 protected |= rmap_write_protect(vcpu, sp->gfn);
2495 kvm_flush_remote_tlbs(vcpu->kvm);
2499 for_each_sp(pages, sp, parents, i) {
2500 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2501 mmu_pages_clear_parents(&parents);
2503 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2504 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2505 cond_resched_lock(&vcpu->kvm->mmu_lock);
2510 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2513 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2515 atomic_set(&sp->write_flooding_count, 0);
2518 static void clear_sp_write_flooding_count(u64 *spte)
2520 struct kvm_mmu_page *sp = page_header(__pa(spte));
2522 __clear_sp_write_flooding_count(sp);
2525 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2532 union kvm_mmu_page_role role;
2534 struct kvm_mmu_page *sp;
2535 bool need_sync = false;
2538 LIST_HEAD(invalid_list);
2540 role = vcpu->arch.mmu->mmu_role.base;
2542 role.direct = direct;
2544 role.gpte_is_8_bytes = true;
2545 role.access = access;
2546 if (!vcpu->arch.mmu->direct_map
2547 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2548 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2549 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2550 role.quadrant = quadrant;
2552 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2553 if (sp->gfn != gfn) {
2558 if (!need_sync && sp->unsync)
2561 if (sp->role.word != role.word)
2565 /* The page is good, but __kvm_sync_page might still end
2566 * up zapping it. If so, break in order to rebuild it.
2568 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2571 WARN_ON(!list_empty(&invalid_list));
2572 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2575 if (sp->unsync_children)
2576 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2578 __clear_sp_write_flooding_count(sp);
2579 trace_kvm_mmu_get_page(sp, false);
2583 ++vcpu->kvm->stat.mmu_cache_miss;
2585 sp = kvm_mmu_alloc_page(vcpu, direct);
2589 hlist_add_head(&sp->hash_link,
2590 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2593 * we should do write protection before syncing pages
2594 * otherwise the content of the synced shadow page may
2595 * be inconsistent with guest page table.
2597 account_shadowed(vcpu->kvm, sp);
2598 if (level == PT_PAGE_TABLE_LEVEL &&
2599 rmap_write_protect(vcpu, gfn))
2600 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2602 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2603 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2605 clear_page(sp->spt);
2606 trace_kvm_mmu_get_page(sp, true);
2608 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2610 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2611 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2615 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2616 struct kvm_vcpu *vcpu, hpa_t root,
2619 iterator->addr = addr;
2620 iterator->shadow_addr = root;
2621 iterator->level = vcpu->arch.mmu->shadow_root_level;
2623 if (iterator->level == PT64_ROOT_4LEVEL &&
2624 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2625 !vcpu->arch.mmu->direct_map)
2628 if (iterator->level == PT32E_ROOT_LEVEL) {
2630 * prev_root is currently only used for 64-bit hosts. So only
2631 * the active root_hpa is valid here.
2633 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2635 iterator->shadow_addr
2636 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2637 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2639 if (!iterator->shadow_addr)
2640 iterator->level = 0;
2644 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2645 struct kvm_vcpu *vcpu, u64 addr)
2647 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2651 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2653 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2656 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2657 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2661 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2664 if (is_last_spte(spte, iterator->level)) {
2665 iterator->level = 0;
2669 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2673 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2675 __shadow_walk_next(iterator, *iterator->sptep);
2678 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2679 struct kvm_mmu_page *sp)
2683 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2685 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2686 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2688 if (sp_ad_disabled(sp))
2689 spte |= SPTE_AD_DISABLED_MASK;
2691 spte |= shadow_accessed_mask;
2693 mmu_spte_set(sptep, spte);
2695 mmu_page_add_parent_pte(vcpu, sp, sptep);
2697 if (sp->unsync_children || sp->unsync)
2701 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2702 unsigned direct_access)
2704 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2705 struct kvm_mmu_page *child;
2708 * For the direct sp, if the guest pte's dirty bit
2709 * changed form clean to dirty, it will corrupt the
2710 * sp's access: allow writable in the read-only sp,
2711 * so we should update the spte at this point to get
2712 * a new sp with the correct access.
2714 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2715 if (child->role.access == direct_access)
2718 drop_parent_pte(child, sptep);
2719 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2723 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2727 struct kvm_mmu_page *child;
2730 if (is_shadow_present_pte(pte)) {
2731 if (is_last_spte(pte, sp->role.level)) {
2732 drop_spte(kvm, spte);
2733 if (is_large_pte(pte))
2736 child = page_header(pte & PT64_BASE_ADDR_MASK);
2737 drop_parent_pte(child, spte);
2742 if (is_mmio_spte(pte))
2743 mmu_spte_clear_no_track(spte);
2748 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2749 struct kvm_mmu_page *sp)
2753 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2754 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2757 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2760 struct rmap_iterator iter;
2762 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2763 drop_parent_pte(sp, sptep);
2766 static int mmu_zap_unsync_children(struct kvm *kvm,
2767 struct kvm_mmu_page *parent,
2768 struct list_head *invalid_list)
2771 struct mmu_page_path parents;
2772 struct kvm_mmu_pages pages;
2774 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2777 while (mmu_unsync_walk(parent, &pages)) {
2778 struct kvm_mmu_page *sp;
2780 for_each_sp(pages, sp, parents, i) {
2781 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2782 mmu_pages_clear_parents(&parents);
2790 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2791 struct kvm_mmu_page *sp,
2792 struct list_head *invalid_list,
2797 trace_kvm_mmu_prepare_zap_page(sp);
2798 ++kvm->stat.mmu_shadow_zapped;
2799 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2800 kvm_mmu_page_unlink_children(kvm, sp);
2801 kvm_mmu_unlink_parents(kvm, sp);
2803 /* Zapping children means active_mmu_pages has become unstable. */
2804 list_unstable = *nr_zapped;
2806 if (!sp->role.invalid && !sp->role.direct)
2807 unaccount_shadowed(kvm, sp);
2810 kvm_unlink_unsync_page(kvm, sp);
2811 if (!sp->root_count) {
2814 list_move(&sp->link, invalid_list);
2815 kvm_mod_used_mmu_pages(kvm, -1);
2817 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2820 * Obsolete pages cannot be used on any vCPUs, see the comment
2821 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2822 * treats invalid shadow pages as being obsolete.
2824 if (!is_obsolete_sp(kvm, sp))
2825 kvm_reload_remote_mmus(kvm);
2828 if (sp->lpage_disallowed)
2829 unaccount_huge_nx_page(kvm, sp);
2831 sp->role.invalid = 1;
2832 return list_unstable;
2835 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2836 struct list_head *invalid_list)
2840 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2844 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2845 struct list_head *invalid_list)
2847 struct kvm_mmu_page *sp, *nsp;
2849 if (list_empty(invalid_list))
2853 * We need to make sure everyone sees our modifications to
2854 * the page tables and see changes to vcpu->mode here. The barrier
2855 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2856 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2858 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2859 * guest mode and/or lockless shadow page table walks.
2861 kvm_flush_remote_tlbs(kvm);
2863 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2864 WARN_ON(!sp->role.invalid || sp->root_count);
2865 kvm_mmu_free_page(sp);
2869 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2870 struct list_head *invalid_list)
2872 struct kvm_mmu_page *sp;
2874 if (list_empty(&kvm->arch.active_mmu_pages))
2877 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2878 struct kvm_mmu_page, link);
2879 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2882 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2884 LIST_HEAD(invalid_list);
2886 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
2889 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
2890 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
2893 ++vcpu->kvm->stat.mmu_recycled;
2895 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2897 if (!kvm_mmu_available_pages(vcpu->kvm))
2903 * Changing the number of mmu pages allocated to the vm
2904 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2906 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2908 LIST_HEAD(invalid_list);
2910 spin_lock(&kvm->mmu_lock);
2912 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2913 /* Need to free some mmu pages to achieve the goal. */
2914 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2915 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2918 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2919 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2922 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2924 spin_unlock(&kvm->mmu_lock);
2927 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2929 struct kvm_mmu_page *sp;
2930 LIST_HEAD(invalid_list);
2933 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2935 spin_lock(&kvm->mmu_lock);
2936 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2937 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2940 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2942 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2943 spin_unlock(&kvm->mmu_lock);
2947 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2949 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2951 trace_kvm_mmu_unsync_page(sp);
2952 ++vcpu->kvm->stat.mmu_unsync;
2955 kvm_mmu_mark_parents_unsync(sp);
2958 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2961 struct kvm_mmu_page *sp;
2963 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2966 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2973 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2974 kvm_unsync_page(vcpu, sp);
2978 * We need to ensure that the marking of unsync pages is visible
2979 * before the SPTE is updated to allow writes because
2980 * kvm_mmu_sync_roots() checks the unsync flags without holding
2981 * the MMU lock and so can race with this. If the SPTE was updated
2982 * before the page had been marked as unsync-ed, something like the
2983 * following could happen:
2986 * ---------------------------------------------------------------------
2987 * 1.2 Host updates SPTE
2989 * 2.1 Guest writes a GPTE for GVA X.
2990 * (GPTE being in the guest page table shadowed
2991 * by the SP from CPU 1.)
2992 * This reads SPTE during the page table walk.
2993 * Since SPTE.W is read as 1, there is no
2996 * 2.2 Guest issues TLB flush.
2997 * That causes a VM Exit.
2999 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
3000 * Since it is false, so it just returns.
3002 * 2.4 Guest accesses GVA X.
3003 * Since the mapping in the SP was not updated,
3004 * so the old mapping for GVA X incorrectly
3008 * (sp->unsync = true)
3010 * The write barrier below ensures that 1.1 happens before 1.2 and thus
3011 * the situation in 2.4 does not arise. The implicit barrier in 2.2
3012 * pairs with this write barrier.
3019 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
3022 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
3024 * Some reserved pages, such as those from NVDIMM
3025 * DAX devices, are not for MMIO, and can be mapped
3026 * with cached memory type for better performance.
3027 * However, the above check misconceives those pages
3028 * as MMIO, and results in KVM mapping them with UC
3029 * memory type, which would hurt the performance.
3030 * Therefore, we check the host memory type in addition
3031 * and only treat UC/UC-/WC pages as MMIO.
3033 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
3035 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
3036 pfn_to_hpa(pfn + 1) - 1,
3040 /* Bits which may be returned by set_spte() */
3041 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
3042 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
3044 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
3045 unsigned pte_access, int level,
3046 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
3047 bool can_unsync, bool host_writable)
3051 struct kvm_mmu_page *sp;
3053 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
3056 sp = page_header(__pa(sptep));
3057 if (sp_ad_disabled(sp))
3058 spte |= SPTE_AD_DISABLED_MASK;
3059 else if (kvm_vcpu_ad_need_write_protect(vcpu))
3060 spte |= SPTE_AD_WRPROT_ONLY_MASK;
3063 * For the EPT case, shadow_present_mask is 0 if hardware
3064 * supports exec-only page table entries. In that case,
3065 * ACC_USER_MASK and shadow_user_mask are used to represent
3066 * read access. See FNAME(gpte_access) in paging_tmpl.h.
3068 spte |= shadow_present_mask;
3070 spte |= spte_shadow_accessed_mask(spte);
3072 if (level > PT_PAGE_TABLE_LEVEL && (pte_access & ACC_EXEC_MASK) &&
3073 is_nx_huge_page_enabled()) {
3074 pte_access &= ~ACC_EXEC_MASK;
3077 if (pte_access & ACC_EXEC_MASK)
3078 spte |= shadow_x_mask;
3080 spte |= shadow_nx_mask;
3082 if (pte_access & ACC_USER_MASK)
3083 spte |= shadow_user_mask;
3085 if (level > PT_PAGE_TABLE_LEVEL)
3086 spte |= PT_PAGE_SIZE_MASK;
3088 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
3089 kvm_is_mmio_pfn(pfn));
3092 spte |= SPTE_HOST_WRITEABLE;
3094 pte_access &= ~ACC_WRITE_MASK;
3096 if (!kvm_is_mmio_pfn(pfn))
3097 spte |= shadow_me_mask;
3099 spte |= (u64)pfn << PAGE_SHIFT;
3101 if (pte_access & ACC_WRITE_MASK) {
3104 * Other vcpu creates new sp in the window between
3105 * max_mapping_level() and acquiring mmu-lock. We can
3106 * allow guest to retry the access, the mapping can
3107 * be fixed if guest refault.
3109 if (level > PT_PAGE_TABLE_LEVEL &&
3110 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3113 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3116 * Optimization: for pte sync, if spte was writable the hash
3117 * lookup is unnecessary (and expensive). Write protection
3118 * is responsibility of mmu_get_page / kvm_sync_page.
3119 * Same reasoning can be applied to dirty page accounting.
3121 if (!can_unsync && is_writable_pte(*sptep))
3124 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3125 pgprintk("%s: found shadow page for %llx, marking ro\n",
3127 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3128 pte_access &= ~ACC_WRITE_MASK;
3129 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3133 if (pte_access & ACC_WRITE_MASK) {
3134 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3135 spte |= spte_shadow_dirty_mask(spte);
3139 spte = mark_spte_for_access_track(spte);
3142 if (mmu_spte_update(sptep, spte))
3143 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3148 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3149 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3150 bool speculative, bool host_writable)
3152 int was_rmapped = 0;
3155 int ret = RET_PF_RETRY;
3158 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3159 *sptep, write_fault, gfn);
3161 if (is_shadow_present_pte(*sptep)) {
3163 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3164 * the parent of the now unreachable PTE.
3166 if (level > PT_PAGE_TABLE_LEVEL &&
3167 !is_large_pte(*sptep)) {
3168 struct kvm_mmu_page *child;
3171 child = page_header(pte & PT64_BASE_ADDR_MASK);
3172 drop_parent_pte(child, sptep);
3174 } else if (pfn != spte_to_pfn(*sptep)) {
3175 pgprintk("hfn old %llx new %llx\n",
3176 spte_to_pfn(*sptep), pfn);
3177 drop_spte(vcpu->kvm, sptep);
3183 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3184 speculative, true, host_writable);
3185 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3187 ret = RET_PF_EMULATE;
3188 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3191 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3192 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3193 KVM_PAGES_PER_HPAGE(level));
3195 if (unlikely(is_mmio_spte(*sptep)))
3196 ret = RET_PF_EMULATE;
3198 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3199 trace_kvm_mmu_set_spte(level, gfn, sptep);
3200 if (!was_rmapped && is_large_pte(*sptep))
3201 ++vcpu->kvm->stat.lpages;
3203 if (is_shadow_present_pte(*sptep)) {
3205 rmap_count = rmap_add(vcpu, sptep, gfn);
3206 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3207 rmap_recycle(vcpu, sptep, gfn);
3214 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3217 struct kvm_memory_slot *slot;
3219 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3221 return KVM_PFN_ERR_FAULT;
3223 return gfn_to_pfn_memslot_atomic(slot, gfn);
3226 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3227 struct kvm_mmu_page *sp,
3228 u64 *start, u64 *end)
3230 struct page *pages[PTE_PREFETCH_NUM];
3231 struct kvm_memory_slot *slot;
3232 unsigned access = sp->role.access;
3236 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3237 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3241 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3245 for (i = 0; i < ret; i++, gfn++, start++) {
3246 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3247 page_to_pfn(pages[i]), true, true);
3254 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3255 struct kvm_mmu_page *sp, u64 *sptep)
3257 u64 *spte, *start = NULL;
3260 WARN_ON(!sp->role.direct);
3262 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3265 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3266 if (is_shadow_present_pte(*spte) || spte == sptep) {
3269 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3277 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3279 struct kvm_mmu_page *sp;
3281 sp = page_header(__pa(sptep));
3284 * Without accessed bits, there's no way to distinguish between
3285 * actually accessed translations and prefetched, so disable pte
3286 * prefetch if accessed bits aren't available.
3288 if (sp_ad_disabled(sp))
3291 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3294 __direct_pte_prefetch(vcpu, sp, sptep);
3297 static int host_pfn_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn,
3300 struct kvm_memory_slot *slot;
3305 BUILD_BUG_ON(PT_PAGE_TABLE_LEVEL != (int)PG_LEVEL_4K ||
3306 PT_DIRECTORY_LEVEL != (int)PG_LEVEL_2M ||
3307 PT_PDPE_LEVEL != (int)PG_LEVEL_1G);
3309 if (!PageCompound(pfn_to_page(pfn)))
3310 return PT_PAGE_TABLE_LEVEL;
3312 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, true);
3314 return PT_PAGE_TABLE_LEVEL;
3316 hva = __gfn_to_hva_memslot(slot, gfn);
3318 pte = lookup_address_in_mm(vcpu->kvm->mm, hva, &level);
3320 return PT_PAGE_TABLE_LEVEL;
3325 static int kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t gfn,
3326 int max_level, kvm_pfn_t *pfnp)
3328 kvm_pfn_t pfn = *pfnp;
3332 if (max_level == PT_PAGE_TABLE_LEVEL)
3333 return PT_PAGE_TABLE_LEVEL;
3335 if (is_error_noslot_pfn(pfn) || kvm_is_reserved_pfn(pfn) ||
3336 kvm_is_zone_device_pfn(pfn))
3337 return PT_PAGE_TABLE_LEVEL;
3339 level = host_pfn_mapping_level(vcpu, gfn, pfn);
3340 if (level == PT_PAGE_TABLE_LEVEL)
3343 level = min(level, max_level);
3346 * mmu_notifier_retry() was successful and mmu_lock is held, so
3347 * the pmd can't be split from under us.
3349 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3350 VM_BUG_ON((gfn & mask) != (pfn & mask));
3351 *pfnp = pfn & ~mask;
3356 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3357 gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3359 int level = *levelp;
3360 u64 spte = *it.sptep;
3362 if (it.level == level && level > PT_PAGE_TABLE_LEVEL &&
3363 is_nx_huge_page_enabled() &&
3364 is_shadow_present_pte(spte) &&
3365 !is_large_pte(spte)) {
3367 * A small SPTE exists for this pfn, but FNAME(fetch)
3368 * and __direct_map would like to create a large PTE
3369 * instead: just force them to go down another level,
3370 * patching back for them into pfn the next 9 bits of
3373 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3374 *pfnp |= gfn & page_mask;
3379 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3380 int map_writable, int max_level, kvm_pfn_t pfn,
3381 bool prefault, bool account_disallowed_nx_lpage)
3383 struct kvm_shadow_walk_iterator it;
3384 struct kvm_mmu_page *sp;
3386 gfn_t gfn = gpa >> PAGE_SHIFT;
3387 gfn_t base_gfn = gfn;
3389 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
3390 return RET_PF_RETRY;
3392 level = kvm_mmu_hugepage_adjust(vcpu, gfn, max_level, &pfn);
3394 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3395 for_each_shadow_entry(vcpu, gpa, it) {
3397 * We cannot overwrite existing page tables with an NX
3398 * large page, as the leaf could be executable.
3400 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3402 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3403 if (it.level == level)
3406 drop_large_spte(vcpu, it.sptep);
3407 if (!is_shadow_present_pte(*it.sptep)) {
3408 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3409 it.level - 1, true, ACC_ALL);
3411 link_shadow_page(vcpu, it.sptep, sp);
3412 if (account_disallowed_nx_lpage)
3413 account_huge_nx_page(vcpu->kvm, sp);
3417 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3418 write, level, base_gfn, pfn, prefault,
3420 direct_pte_prefetch(vcpu, it.sptep);
3421 ++vcpu->stat.pf_fixed;
3425 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3427 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3430 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3433 * Do not cache the mmio info caused by writing the readonly gfn
3434 * into the spte otherwise read access on readonly gfn also can
3435 * caused mmio page fault and treat it as mmio access.
3437 if (pfn == KVM_PFN_ERR_RO_FAULT)
3438 return RET_PF_EMULATE;
3440 if (pfn == KVM_PFN_ERR_HWPOISON) {
3441 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3442 return RET_PF_RETRY;
3448 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3449 kvm_pfn_t pfn, unsigned access, int *ret_val)
3451 /* The pfn is invalid, report the error! */
3452 if (unlikely(is_error_pfn(pfn))) {
3453 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3457 if (unlikely(is_noslot_pfn(pfn)))
3458 vcpu_cache_mmio_info(vcpu, gva, gfn,
3459 access & shadow_mmio_access_mask);
3464 static bool page_fault_can_be_fast(u32 error_code)
3467 * Do not fix the mmio spte with invalid generation number which
3468 * need to be updated by slow page fault path.
3470 if (unlikely(error_code & PFERR_RSVD_MASK))
3473 /* See if the page fault is due to an NX violation */
3474 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3475 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3479 * #PF can be fast if:
3480 * 1. The shadow page table entry is not present, which could mean that
3481 * the fault is potentially caused by access tracking (if enabled).
3482 * 2. The shadow page table entry is present and the fault
3483 * is caused by write-protect, that means we just need change the W
3484 * bit of the spte which can be done out of mmu-lock.
3486 * However, if access tracking is disabled we know that a non-present
3487 * page must be a genuine page fault where we have to create a new SPTE.
3488 * So, if access tracking is disabled, we return true only for write
3489 * accesses to a present page.
3492 return shadow_acc_track_mask != 0 ||
3493 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3494 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3498 * Returns true if the SPTE was fixed successfully. Otherwise,
3499 * someone else modified the SPTE from its original value.
3502 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3503 u64 *sptep, u64 old_spte, u64 new_spte)
3507 WARN_ON(!sp->role.direct);
3510 * Theoretically we could also set dirty bit (and flush TLB) here in
3511 * order to eliminate unnecessary PML logging. See comments in
3512 * set_spte. But fast_page_fault is very unlikely to happen with PML
3513 * enabled, so we do not do this. This might result in the same GPA
3514 * to be logged in PML buffer again when the write really happens, and
3515 * eventually to be called by mark_page_dirty twice. But it's also no
3516 * harm. This also avoids the TLB flush needed after setting dirty bit
3517 * so non-PML cases won't be impacted.
3519 * Compare with set_spte where instead shadow_dirty_mask is set.
3521 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3524 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3526 * The gfn of direct spte is stable since it is
3527 * calculated by sp->gfn.
3529 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3530 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3536 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3538 if (fault_err_code & PFERR_FETCH_MASK)
3539 return is_executable_pte(spte);
3541 if (fault_err_code & PFERR_WRITE_MASK)
3542 return is_writable_pte(spte);
3544 /* Fault was on Read access */
3545 return spte & PT_PRESENT_MASK;
3550 * - true: let the vcpu to access on the same address again.
3551 * - false: let the real page fault path to fix it.
3553 static bool fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
3556 struct kvm_shadow_walk_iterator iterator;
3557 struct kvm_mmu_page *sp;
3558 bool fault_handled = false;
3560 uint retry_count = 0;
3562 if (!page_fault_can_be_fast(error_code))
3565 walk_shadow_page_lockless_begin(vcpu);
3570 for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
3571 if (!is_shadow_present_pte(spte))
3574 sp = page_header(__pa(iterator.sptep));
3575 if (!is_last_spte(spte, sp->role.level))
3579 * Check whether the memory access that caused the fault would
3580 * still cause it if it were to be performed right now. If not,
3581 * then this is a spurious fault caused by TLB lazily flushed,
3582 * or some other CPU has already fixed the PTE after the
3583 * current CPU took the fault.
3585 * Need not check the access of upper level table entries since
3586 * they are always ACC_ALL.
3588 if (is_access_allowed(error_code, spte)) {
3589 fault_handled = true;
3595 if (is_access_track_spte(spte))
3596 new_spte = restore_acc_track_spte(new_spte);
3599 * Currently, to simplify the code, write-protection can
3600 * be removed in the fast path only if the SPTE was
3601 * write-protected for dirty-logging or access tracking.
3603 if ((error_code & PFERR_WRITE_MASK) &&
3604 spte_can_locklessly_be_made_writable(spte))
3606 new_spte |= PT_WRITABLE_MASK;
3609 * Do not fix write-permission on the large spte. Since
3610 * we only dirty the first page into the dirty-bitmap in
3611 * fast_pf_fix_direct_spte(), other pages are missed
3612 * if its slot has dirty logging enabled.
3614 * Instead, we let the slow page fault path create a
3615 * normal spte to fix the access.
3617 * See the comments in kvm_arch_commit_memory_region().
3619 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3623 /* Verify that the fault can be handled in the fast path */
3624 if (new_spte == spte ||
3625 !is_access_allowed(error_code, new_spte))
3629 * Currently, fast page fault only works for direct mapping
3630 * since the gfn is not stable for indirect shadow page. See
3631 * Documentation/virt/kvm/locking.txt to get more detail.
3633 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3634 iterator.sptep, spte,
3639 if (++retry_count > 4) {
3640 printk_once(KERN_WARNING
3641 "kvm: Fast #PF retrying more than 4 times.\n");
3647 trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
3648 spte, fault_handled);
3649 walk_shadow_page_lockless_end(vcpu);
3651 return fault_handled;
3654 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3655 struct list_head *invalid_list)
3657 struct kvm_mmu_page *sp;
3659 if (!VALID_PAGE(*root_hpa))
3662 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3664 if (!sp->root_count && sp->role.invalid)
3665 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3667 *root_hpa = INVALID_PAGE;
3670 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3671 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3672 ulong roots_to_free)
3675 LIST_HEAD(invalid_list);
3676 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3678 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3680 /* Before acquiring the MMU lock, see if we need to do any real work. */
3681 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3682 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3683 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3684 VALID_PAGE(mmu->prev_roots[i].hpa))
3687 if (i == KVM_MMU_NUM_PREV_ROOTS)
3691 spin_lock(&vcpu->kvm->mmu_lock);
3693 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3694 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3695 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3698 if (free_active_root) {
3699 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3700 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3701 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3704 for (i = 0; i < 4; ++i)
3705 if (mmu->pae_root[i] != 0)
3706 mmu_free_root_page(vcpu->kvm,
3709 mmu->root_hpa = INVALID_PAGE;
3714 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3715 spin_unlock(&vcpu->kvm->mmu_lock);
3717 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3719 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3723 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3724 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3731 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3733 struct kvm_mmu_page *sp;
3736 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3737 spin_lock(&vcpu->kvm->mmu_lock);
3738 if(make_mmu_pages_available(vcpu) < 0) {
3739 spin_unlock(&vcpu->kvm->mmu_lock);
3742 sp = kvm_mmu_get_page(vcpu, 0, 0,
3743 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3745 spin_unlock(&vcpu->kvm->mmu_lock);
3746 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3747 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3748 for (i = 0; i < 4; ++i) {
3749 hpa_t root = vcpu->arch.mmu->pae_root[i];
3751 MMU_WARN_ON(VALID_PAGE(root));
3752 spin_lock(&vcpu->kvm->mmu_lock);
3753 if (make_mmu_pages_available(vcpu) < 0) {
3754 spin_unlock(&vcpu->kvm->mmu_lock);
3757 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3758 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3759 root = __pa(sp->spt);
3761 spin_unlock(&vcpu->kvm->mmu_lock);
3762 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3764 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3767 vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3772 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3774 struct kvm_mmu_page *sp;
3776 gfn_t root_gfn, root_cr3;
3779 root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3780 root_gfn = root_cr3 >> PAGE_SHIFT;
3782 if (mmu_check_root(vcpu, root_gfn))
3786 * Do we shadow a long mode page table? If so we need to
3787 * write-protect the guests page table root.
3789 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3790 hpa_t root = vcpu->arch.mmu->root_hpa;
3792 MMU_WARN_ON(VALID_PAGE(root));
3794 spin_lock(&vcpu->kvm->mmu_lock);
3795 if (make_mmu_pages_available(vcpu) < 0) {
3796 spin_unlock(&vcpu->kvm->mmu_lock);
3799 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3800 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3801 root = __pa(sp->spt);
3803 spin_unlock(&vcpu->kvm->mmu_lock);
3804 vcpu->arch.mmu->root_hpa = root;
3809 * We shadow a 32 bit page table. This may be a legacy 2-level
3810 * or a PAE 3-level page table. In either case we need to be aware that
3811 * the shadow page table may be a PAE or a long mode page table.
3813 pm_mask = PT_PRESENT_MASK;
3814 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3815 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3817 for (i = 0; i < 4; ++i) {
3818 hpa_t root = vcpu->arch.mmu->pae_root[i];
3820 MMU_WARN_ON(VALID_PAGE(root));
3821 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3822 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3823 if (!(pdptr & PT_PRESENT_MASK)) {
3824 vcpu->arch.mmu->pae_root[i] = 0;
3827 root_gfn = pdptr >> PAGE_SHIFT;
3828 if (mmu_check_root(vcpu, root_gfn))
3831 spin_lock(&vcpu->kvm->mmu_lock);
3832 if (make_mmu_pages_available(vcpu) < 0) {
3833 spin_unlock(&vcpu->kvm->mmu_lock);
3836 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3838 root = __pa(sp->spt);
3840 spin_unlock(&vcpu->kvm->mmu_lock);
3842 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3844 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3847 * If we shadow a 32 bit page table with a long mode page
3848 * table we enter this path.
3850 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3851 if (vcpu->arch.mmu->lm_root == NULL) {
3853 * The additional page necessary for this is only
3854 * allocated on demand.
3859 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3860 if (lm_root == NULL)
3863 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3865 vcpu->arch.mmu->lm_root = lm_root;
3868 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3872 vcpu->arch.mmu->root_cr3 = root_cr3;
3877 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3879 if (vcpu->arch.mmu->direct_map)
3880 return mmu_alloc_direct_roots(vcpu);
3882 return mmu_alloc_shadow_roots(vcpu);
3885 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3888 struct kvm_mmu_page *sp;
3890 if (vcpu->arch.mmu->direct_map)
3893 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3896 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3898 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3899 hpa_t root = vcpu->arch.mmu->root_hpa;
3900 sp = page_header(root);
3903 * Even if another CPU was marking the SP as unsync-ed
3904 * simultaneously, any guest page table changes are not
3905 * guaranteed to be visible anyway until this VCPU issues a TLB
3906 * flush strictly after those changes are made. We only need to
3907 * ensure that the other CPU sets these flags before any actual
3908 * changes to the page tables are made. The comments in
3909 * mmu_need_write_protect() describe what could go wrong if this
3910 * requirement isn't satisfied.
3912 if (!smp_load_acquire(&sp->unsync) &&
3913 !smp_load_acquire(&sp->unsync_children))
3916 spin_lock(&vcpu->kvm->mmu_lock);
3917 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3919 mmu_sync_children(vcpu, sp);
3921 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3922 spin_unlock(&vcpu->kvm->mmu_lock);
3926 spin_lock(&vcpu->kvm->mmu_lock);
3927 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3929 for (i = 0; i < 4; ++i) {
3930 hpa_t root = vcpu->arch.mmu->pae_root[i];
3932 if (root && VALID_PAGE(root)) {
3933 root &= PT64_BASE_ADDR_MASK;
3934 sp = page_header(root);
3935 mmu_sync_children(vcpu, sp);
3939 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3940 spin_unlock(&vcpu->kvm->mmu_lock);
3942 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3944 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3945 u32 access, struct x86_exception *exception)
3948 exception->error_code = 0;
3952 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3954 struct x86_exception *exception)
3957 exception->error_code = 0;
3958 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3962 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3964 int bit7 = (pte >> 7) & 1;
3966 return pte & rsvd_check->rsvd_bits_mask[bit7][level-1];
3969 static bool __is_bad_mt_xwr(struct rsvd_bits_validate *rsvd_check, u64 pte)
3971 return rsvd_check->bad_mt_xwr & BIT_ULL(pte & 0x3f);
3974 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3977 * A nested guest cannot use the MMIO cache if it is using nested
3978 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3980 if (mmu_is_nested(vcpu))
3984 return vcpu_match_mmio_gpa(vcpu, addr);
3986 return vcpu_match_mmio_gva(vcpu, addr);
3989 /* return true if reserved bit is detected on spte. */
3991 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3993 struct kvm_shadow_walk_iterator iterator;
3994 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3995 struct rsvd_bits_validate *rsvd_check;
3997 bool reserved = false;
3999 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
4001 walk_shadow_page_lockless_begin(vcpu);
4003 for (shadow_walk_init(&iterator, vcpu, addr),
4004 leaf = root = iterator.level;
4005 shadow_walk_okay(&iterator);
4006 __shadow_walk_next(&iterator, spte)) {
4007 spte = mmu_spte_get_lockless(iterator.sptep);
4009 sptes[leaf - 1] = spte;
4012 if (!is_shadow_present_pte(spte))
4016 * Use a bitwise-OR instead of a logical-OR to aggregate the
4017 * reserved bit and EPT's invalid memtype/XWR checks to avoid
4018 * adding a Jcc in the loop.
4020 reserved |= __is_bad_mt_xwr(rsvd_check, spte) |
4021 __is_rsvd_bits_set(rsvd_check, spte, iterator.level);
4024 walk_shadow_page_lockless_end(vcpu);
4027 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
4029 while (root > leaf) {
4030 pr_err("------ spte 0x%llx level %d.\n",
4031 sptes[root - 1], root);
4040 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4045 if (mmio_info_in_cache(vcpu, addr, direct))
4046 return RET_PF_EMULATE;
4048 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
4049 if (WARN_ON(reserved))
4052 if (is_mmio_spte(spte)) {
4053 gfn_t gfn = get_mmio_spte_gfn(spte);
4054 unsigned access = get_mmio_spte_access(spte);
4056 if (!check_mmio_spte(vcpu, spte))
4057 return RET_PF_INVALID;
4062 trace_handle_mmio_page_fault(addr, gfn, access);
4063 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4064 return RET_PF_EMULATE;
4068 * If the page table is zapped by other cpus, let CPU fault again on
4071 return RET_PF_RETRY;
4074 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4075 u32 error_code, gfn_t gfn)
4077 if (unlikely(error_code & PFERR_RSVD_MASK))
4080 if (!(error_code & PFERR_PRESENT_MASK) ||
4081 !(error_code & PFERR_WRITE_MASK))
4085 * guest is writing the page which is write tracked which can
4086 * not be fixed by page fault handler.
4088 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4094 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4096 struct kvm_shadow_walk_iterator iterator;
4099 walk_shadow_page_lockless_begin(vcpu);
4100 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4101 clear_sp_write_flooding_count(iterator.sptep);
4102 if (!is_shadow_present_pte(spte))
4105 walk_shadow_page_lockless_end(vcpu);
4108 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4111 struct kvm_arch_async_pf arch;
4113 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4115 arch.direct_map = vcpu->arch.mmu->direct_map;
4116 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4118 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4119 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4122 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4123 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
4126 struct kvm_memory_slot *slot;
4130 * Don't expose private memslots to L2.
4132 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4133 *pfn = KVM_PFN_NOSLOT;
4137 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4139 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4141 return false; /* *pfn has correct page already */
4143 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4144 trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
4145 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4146 trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
4147 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4149 } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
4153 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4157 static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4158 bool prefault, int max_level, bool is_tdp)
4160 bool write = error_code & PFERR_WRITE_MASK;
4161 bool exec = error_code & PFERR_FETCH_MASK;
4162 bool lpage_disallowed = exec && is_nx_huge_page_enabled();
4165 gfn_t gfn = gpa >> PAGE_SHIFT;
4166 unsigned long mmu_seq;
4170 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4171 return RET_PF_EMULATE;
4173 r = mmu_topup_memory_caches(vcpu);
4177 if (lpage_disallowed)
4178 max_level = PT_PAGE_TABLE_LEVEL;
4180 max_level = max_mapping_level(vcpu, gfn, max_level);
4182 if (fast_page_fault(vcpu, gpa, error_code))
4183 return RET_PF_RETRY;
4185 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4188 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4189 return RET_PF_RETRY;
4191 if (handle_abnormal_pfn(vcpu, is_tdp ? 0 : gpa, gfn, pfn, ACC_ALL, &r))
4195 spin_lock(&vcpu->kvm->mmu_lock);
4196 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4198 if (make_mmu_pages_available(vcpu) < 0)
4200 r = __direct_map(vcpu, gpa, write, map_writable, max_level, pfn,
4201 prefault, is_tdp && lpage_disallowed);
4204 spin_unlock(&vcpu->kvm->mmu_lock);
4205 kvm_release_pfn_clean(pfn);
4209 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
4210 u32 error_code, bool prefault)
4212 pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
4214 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4215 return direct_page_fault(vcpu, gpa & PAGE_MASK, error_code, prefault,
4216 PT_DIRECTORY_LEVEL, false);
4219 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4220 u64 fault_address, char *insn, int insn_len)
4224 #ifndef CONFIG_X86_64
4225 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4226 if (WARN_ON_ONCE(fault_address >> 32))
4230 vcpu->arch.l1tf_flush_l1d = true;
4231 switch (vcpu->arch.apf.host_apf_reason) {
4233 trace_kvm_page_fault(fault_address, error_code);
4235 if (kvm_event_needs_reinjection(vcpu))
4236 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4237 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4240 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4241 vcpu->arch.apf.host_apf_reason = 0;
4242 local_irq_disable();
4243 kvm_async_pf_task_wait(fault_address, 0);
4246 case KVM_PV_REASON_PAGE_READY:
4247 vcpu->arch.apf.host_apf_reason = 0;
4248 local_irq_disable();
4249 kvm_async_pf_task_wake(fault_address);
4255 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4257 static int tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4262 for (max_level = PT_MAX_HUGEPAGE_LEVEL;
4263 max_level > PT_PAGE_TABLE_LEVEL;
4265 int page_num = KVM_PAGES_PER_HPAGE(max_level);
4266 gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
4268 if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4272 return direct_page_fault(vcpu, gpa, error_code, prefault,
4276 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4277 struct kvm_mmu *context)
4279 context->page_fault = nonpaging_page_fault;
4280 context->gva_to_gpa = nonpaging_gva_to_gpa;
4281 context->sync_page = nonpaging_sync_page;
4282 context->invlpg = nonpaging_invlpg;
4283 context->update_pte = nonpaging_update_pte;
4284 context->root_level = 0;
4285 context->shadow_root_level = PT32E_ROOT_LEVEL;
4286 context->direct_map = true;
4287 context->nx = false;
4291 * Find out if a previously cached root matching the new CR3/role is available.
4292 * The current root is also inserted into the cache.
4293 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4295 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4296 * false is returned. This root should now be freed by the caller.
4298 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4299 union kvm_mmu_page_role new_role)
4302 struct kvm_mmu_root_info root;
4303 struct kvm_mmu *mmu = vcpu->arch.mmu;
4305 root.cr3 = mmu->root_cr3;
4306 root.hpa = mmu->root_hpa;
4308 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4309 swap(root, mmu->prev_roots[i]);
4311 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4312 page_header(root.hpa) != NULL &&
4313 new_role.word == page_header(root.hpa)->role.word)
4317 mmu->root_hpa = root.hpa;
4318 mmu->root_cr3 = root.cr3;
4320 return i < KVM_MMU_NUM_PREV_ROOTS;
4323 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4324 union kvm_mmu_page_role new_role,
4325 bool skip_tlb_flush)
4327 struct kvm_mmu *mmu = vcpu->arch.mmu;
4330 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4331 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4332 * later if necessary.
4334 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4335 mmu->root_level >= PT64_ROOT_4LEVEL) {
4336 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4339 if (cached_root_available(vcpu, new_cr3, new_role)) {
4341 * It is possible that the cached previous root page is
4342 * obsolete because of a change in the MMU generation
4343 * number. However, changing the generation number is
4344 * accompanied by KVM_REQ_MMU_RELOAD, which will free
4345 * the root set here and allocate a new one.
4347 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4348 if (!skip_tlb_flush) {
4349 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4350 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4354 * The last MMIO access's GVA and GPA are cached in the
4355 * VCPU. When switching to a new CR3, that GVA->GPA
4356 * mapping may no longer be valid. So clear any cached
4357 * MMIO info even when we don't need to sync the shadow
4360 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4362 __clear_sp_write_flooding_count(
4363 page_header(mmu->root_hpa));
4372 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4373 union kvm_mmu_page_role new_role,
4374 bool skip_tlb_flush)
4376 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4377 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4378 KVM_MMU_ROOT_CURRENT);
4381 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4383 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4386 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4388 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4390 return kvm_read_cr3(vcpu);
4393 static void inject_page_fault(struct kvm_vcpu *vcpu,
4394 struct x86_exception *fault)
4396 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4399 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4400 unsigned access, int *nr_present)
4402 if (unlikely(is_mmio_spte(*sptep))) {
4403 if (gfn != get_mmio_spte_gfn(*sptep)) {
4404 mmu_spte_clear_no_track(sptep);
4409 mark_mmio_spte(vcpu, sptep, gfn, access);
4416 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4417 unsigned level, unsigned gpte)
4420 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4421 * If it is clear, there are no large pages at this level, so clear
4422 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4424 gpte &= level - mmu->last_nonleaf_level;
4427 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4428 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4429 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4431 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4433 return gpte & PT_PAGE_SIZE_MASK;
4436 #define PTTYPE_EPT 18 /* arbitrary */
4437 #define PTTYPE PTTYPE_EPT
4438 #include "paging_tmpl.h"
4442 #include "paging_tmpl.h"
4446 #include "paging_tmpl.h"
4450 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4451 struct rsvd_bits_validate *rsvd_check,
4452 int maxphyaddr, int level, bool nx, bool gbpages,
4455 u64 exb_bit_rsvd = 0;
4456 u64 gbpages_bit_rsvd = 0;
4457 u64 nonleaf_bit8_rsvd = 0;
4459 rsvd_check->bad_mt_xwr = 0;
4462 exb_bit_rsvd = rsvd_bits(63, 63);
4464 gbpages_bit_rsvd = rsvd_bits(7, 7);
4467 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4468 * leaf entries) on AMD CPUs only.
4471 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4474 case PT32_ROOT_LEVEL:
4475 /* no rsvd bits for 2 level 4K page table entries */
4476 rsvd_check->rsvd_bits_mask[0][1] = 0;
4477 rsvd_check->rsvd_bits_mask[0][0] = 0;
4478 rsvd_check->rsvd_bits_mask[1][0] =
4479 rsvd_check->rsvd_bits_mask[0][0];
4482 rsvd_check->rsvd_bits_mask[1][1] = 0;
4486 if (is_cpuid_PSE36())
4487 /* 36bits PSE 4MB page */
4488 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4490 /* 32 bits PSE 4MB page */
4491 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4493 case PT32E_ROOT_LEVEL:
4494 rsvd_check->rsvd_bits_mask[0][2] =
4495 rsvd_bits(maxphyaddr, 63) |
4496 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4497 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4498 rsvd_bits(maxphyaddr, 62); /* PDE */
4499 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4500 rsvd_bits(maxphyaddr, 62); /* PTE */
4501 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4502 rsvd_bits(maxphyaddr, 62) |
4503 rsvd_bits(13, 20); /* large page */
4504 rsvd_check->rsvd_bits_mask[1][0] =
4505 rsvd_check->rsvd_bits_mask[0][0];
4507 case PT64_ROOT_5LEVEL:
4508 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4509 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4510 rsvd_bits(maxphyaddr, 51);
4511 rsvd_check->rsvd_bits_mask[1][4] =
4512 rsvd_check->rsvd_bits_mask[0][4];
4514 case PT64_ROOT_4LEVEL:
4515 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4516 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4517 rsvd_bits(maxphyaddr, 51);
4518 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4519 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4520 rsvd_bits(maxphyaddr, 51);
4521 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4522 rsvd_bits(maxphyaddr, 51);
4523 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4524 rsvd_bits(maxphyaddr, 51);
4525 rsvd_check->rsvd_bits_mask[1][3] =
4526 rsvd_check->rsvd_bits_mask[0][3];
4527 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4528 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4530 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4531 rsvd_bits(maxphyaddr, 51) |
4532 rsvd_bits(13, 20); /* large page */
4533 rsvd_check->rsvd_bits_mask[1][0] =
4534 rsvd_check->rsvd_bits_mask[0][0];
4539 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4540 struct kvm_mmu *context)
4542 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4543 cpuid_maxphyaddr(vcpu), context->root_level,
4545 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4546 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4550 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4551 int maxphyaddr, bool execonly)
4555 rsvd_check->rsvd_bits_mask[0][4] =
4556 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4557 rsvd_check->rsvd_bits_mask[0][3] =
4558 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4559 rsvd_check->rsvd_bits_mask[0][2] =
4560 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4561 rsvd_check->rsvd_bits_mask[0][1] =
4562 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4563 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4566 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4567 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4568 rsvd_check->rsvd_bits_mask[1][2] =
4569 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4570 rsvd_check->rsvd_bits_mask[1][1] =
4571 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4572 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4574 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4575 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4576 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4577 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4578 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4580 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4581 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4583 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4586 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4587 struct kvm_mmu *context, bool execonly)
4589 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4590 cpuid_maxphyaddr(vcpu), execonly);
4594 * the page table on host is the shadow page table for the page
4595 * table in guest or amd nested guest, its mmu features completely
4596 * follow the features in guest.
4599 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4601 bool uses_nx = context->nx ||
4602 context->mmu_role.base.smep_andnot_wp;
4603 struct rsvd_bits_validate *shadow_zero_check;
4607 * Passing "true" to the last argument is okay; it adds a check
4608 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4610 shadow_zero_check = &context->shadow_zero_check;
4611 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4613 context->shadow_root_level, uses_nx,
4614 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4615 is_pse(vcpu), true);
4617 if (!shadow_me_mask)
4620 for (i = context->shadow_root_level; --i >= 0;) {
4621 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4622 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4626 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4628 static inline bool boot_cpu_is_amd(void)
4630 WARN_ON_ONCE(!tdp_enabled);
4631 return shadow_x_mask == 0;
4635 * the direct page table on host, use as much mmu features as
4636 * possible, however, kvm currently does not do execution-protection.
4639 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4640 struct kvm_mmu *context)
4642 struct rsvd_bits_validate *shadow_zero_check;
4645 shadow_zero_check = &context->shadow_zero_check;
4647 if (boot_cpu_is_amd())
4648 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4650 context->shadow_root_level, false,
4651 boot_cpu_has(X86_FEATURE_GBPAGES),
4654 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4658 if (!shadow_me_mask)
4661 for (i = context->shadow_root_level; --i >= 0;) {
4662 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4663 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4668 * as the comments in reset_shadow_zero_bits_mask() except it
4669 * is the shadow page table for intel nested guest.
4672 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4673 struct kvm_mmu *context, bool execonly)
4675 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4676 shadow_phys_bits, execonly);
4679 #define BYTE_MASK(access) \
4680 ((1 & (access) ? 2 : 0) | \
4681 (2 & (access) ? 4 : 0) | \
4682 (3 & (access) ? 8 : 0) | \
4683 (4 & (access) ? 16 : 0) | \
4684 (5 & (access) ? 32 : 0) | \
4685 (6 & (access) ? 64 : 0) | \
4686 (7 & (access) ? 128 : 0))
4689 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4690 struct kvm_mmu *mmu, bool ept)
4694 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4695 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4696 const u8 u = BYTE_MASK(ACC_USER_MASK);
4698 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4699 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4700 bool cr0_wp = is_write_protection(vcpu);
4702 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4703 unsigned pfec = byte << 1;
4706 * Each "*f" variable has a 1 bit for each UWX value
4707 * that causes a fault with the given PFEC.
4710 /* Faults from writes to non-writable pages */
4711 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4712 /* Faults from user mode accesses to supervisor pages */
4713 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4714 /* Faults from fetches of non-executable pages*/
4715 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4716 /* Faults from kernel mode fetches of user pages */
4718 /* Faults from kernel mode accesses of user pages */
4722 /* Faults from kernel mode accesses to user pages */
4723 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4725 /* Not really needed: !nx will cause pte.nx to fault */
4729 /* Allow supervisor writes if !cr0.wp */
4731 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4733 /* Disallow supervisor fetches of user code if cr4.smep */
4735 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4738 * SMAP:kernel-mode data accesses from user-mode
4739 * mappings should fault. A fault is considered
4740 * as a SMAP violation if all of the following
4741 * conditions are true:
4742 * - X86_CR4_SMAP is set in CR4
4743 * - A user page is accessed
4744 * - The access is not a fetch
4745 * - Page fault in kernel mode
4746 * - if CPL = 3 or X86_EFLAGS_AC is clear
4748 * Here, we cover the first three conditions.
4749 * The fourth is computed dynamically in permission_fault();
4750 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4751 * *not* subject to SMAP restrictions.
4754 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4757 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4762 * PKU is an additional mechanism by which the paging controls access to
4763 * user-mode addresses based on the value in the PKRU register. Protection
4764 * key violations are reported through a bit in the page fault error code.
4765 * Unlike other bits of the error code, the PK bit is not known at the
4766 * call site of e.g. gva_to_gpa; it must be computed directly in
4767 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4768 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4770 * In particular the following conditions come from the error code, the
4771 * page tables and the machine state:
4772 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4773 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4774 * - PK is always zero if U=0 in the page tables
4775 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4777 * The PKRU bitmask caches the result of these four conditions. The error
4778 * code (minus the P bit) and the page table's U bit form an index into the
4779 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4780 * with the two bits of the PKRU register corresponding to the protection key.
4781 * For the first three conditions above the bits will be 00, thus masking
4782 * away both AD and WD. For all reads or if the last condition holds, WD
4783 * only will be masked away.
4785 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4796 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4797 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4802 wp = is_write_protection(vcpu);
4804 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4805 unsigned pfec, pkey_bits;
4806 bool check_pkey, check_write, ff, uf, wf, pte_user;
4809 ff = pfec & PFERR_FETCH_MASK;
4810 uf = pfec & PFERR_USER_MASK;
4811 wf = pfec & PFERR_WRITE_MASK;
4813 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4814 pte_user = pfec & PFERR_RSVD_MASK;
4817 * Only need to check the access which is not an
4818 * instruction fetch and is to a user page.
4820 check_pkey = (!ff && pte_user);
4822 * write access is controlled by PKRU if it is a
4823 * user access or CR0.WP = 1.
4825 check_write = check_pkey && wf && (uf || wp);
4827 /* PKRU.AD stops both read and write access. */
4828 pkey_bits = !!check_pkey;
4829 /* PKRU.WD stops write access. */
4830 pkey_bits |= (!!check_write) << 1;
4832 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4836 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4838 unsigned root_level = mmu->root_level;
4840 mmu->last_nonleaf_level = root_level;
4841 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4842 mmu->last_nonleaf_level++;
4845 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4846 struct kvm_mmu *context,
4849 context->nx = is_nx(vcpu);
4850 context->root_level = level;
4852 reset_rsvds_bits_mask(vcpu, context);
4853 update_permission_bitmask(vcpu, context, false);
4854 update_pkru_bitmask(vcpu, context, false);
4855 update_last_nonleaf_level(vcpu, context);
4857 MMU_WARN_ON(!is_pae(vcpu));
4858 context->page_fault = paging64_page_fault;
4859 context->gva_to_gpa = paging64_gva_to_gpa;
4860 context->sync_page = paging64_sync_page;
4861 context->invlpg = paging64_invlpg;
4862 context->update_pte = paging64_update_pte;
4863 context->shadow_root_level = level;
4864 context->direct_map = false;
4867 static void paging64_init_context(struct kvm_vcpu *vcpu,
4868 struct kvm_mmu *context)
4870 int root_level = is_la57_mode(vcpu) ?
4871 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4873 paging64_init_context_common(vcpu, context, root_level);
4876 static void paging32_init_context(struct kvm_vcpu *vcpu,
4877 struct kvm_mmu *context)
4879 context->nx = false;
4880 context->root_level = PT32_ROOT_LEVEL;
4882 reset_rsvds_bits_mask(vcpu, context);
4883 update_permission_bitmask(vcpu, context, false);
4884 update_pkru_bitmask(vcpu, context, false);
4885 update_last_nonleaf_level(vcpu, context);
4887 context->page_fault = paging32_page_fault;
4888 context->gva_to_gpa = paging32_gva_to_gpa;
4889 context->sync_page = paging32_sync_page;
4890 context->invlpg = paging32_invlpg;
4891 context->update_pte = paging32_update_pte;
4892 context->shadow_root_level = PT32E_ROOT_LEVEL;
4893 context->direct_map = false;
4896 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4897 struct kvm_mmu *context)
4899 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4902 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4904 union kvm_mmu_extended_role ext = {0};
4906 ext.cr0_pg = !!is_paging(vcpu);
4907 ext.cr4_pae = !!is_pae(vcpu);
4908 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4909 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4910 ext.cr4_pse = !!is_pse(vcpu);
4911 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4912 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4913 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4920 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4923 union kvm_mmu_role role = {0};
4925 role.base.access = ACC_ALL;
4926 role.base.nxe = !!is_nx(vcpu);
4927 role.base.cr0_wp = is_write_protection(vcpu);
4928 role.base.smm = is_smm(vcpu);
4929 role.base.guest_mode = is_guest_mode(vcpu);
4934 role.ext = kvm_calc_mmu_role_ext(vcpu);
4939 static union kvm_mmu_role
4940 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4942 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4944 role.base.ad_disabled = (shadow_accessed_mask == 0);
4945 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4946 role.base.direct = true;
4947 role.base.gpte_is_8_bytes = true;
4952 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4954 struct kvm_mmu *context = vcpu->arch.mmu;
4955 union kvm_mmu_role new_role =
4956 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4958 new_role.base.word &= mmu_base_role_mask.word;
4959 if (new_role.as_u64 == context->mmu_role.as_u64)
4962 context->mmu_role.as_u64 = new_role.as_u64;
4963 context->page_fault = tdp_page_fault;
4964 context->sync_page = nonpaging_sync_page;
4965 context->invlpg = nonpaging_invlpg;
4966 context->update_pte = nonpaging_update_pte;
4967 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4968 context->direct_map = true;
4969 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4970 context->get_cr3 = get_cr3;
4971 context->get_pdptr = kvm_pdptr_read;
4972 context->inject_page_fault = kvm_inject_page_fault;
4974 if (!is_paging(vcpu)) {
4975 context->nx = false;
4976 context->gva_to_gpa = nonpaging_gva_to_gpa;
4977 context->root_level = 0;
4978 } else if (is_long_mode(vcpu)) {
4979 context->nx = is_nx(vcpu);
4980 context->root_level = is_la57_mode(vcpu) ?
4981 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4982 reset_rsvds_bits_mask(vcpu, context);
4983 context->gva_to_gpa = paging64_gva_to_gpa;
4984 } else if (is_pae(vcpu)) {
4985 context->nx = is_nx(vcpu);
4986 context->root_level = PT32E_ROOT_LEVEL;
4987 reset_rsvds_bits_mask(vcpu, context);
4988 context->gva_to_gpa = paging64_gva_to_gpa;
4990 context->nx = false;
4991 context->root_level = PT32_ROOT_LEVEL;
4992 reset_rsvds_bits_mask(vcpu, context);
4993 context->gva_to_gpa = paging32_gva_to_gpa;
4996 update_permission_bitmask(vcpu, context, false);
4997 update_pkru_bitmask(vcpu, context, false);
4998 update_last_nonleaf_level(vcpu, context);
4999 reset_tdp_shadow_zero_bits_mask(vcpu, context);
5002 static union kvm_mmu_role
5003 kvm_calc_shadow_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.smep_andnot_wp = role.ext.cr4_smep &&
5008 !is_write_protection(vcpu);
5009 role.base.smap_andnot_wp = role.ext.cr4_smap &&
5010 !is_write_protection(vcpu);
5011 role.base.direct = !is_paging(vcpu);
5012 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
5014 if (!is_long_mode(vcpu))
5015 role.base.level = PT32E_ROOT_LEVEL;
5016 else if (is_la57_mode(vcpu))
5017 role.base.level = PT64_ROOT_5LEVEL;
5019 role.base.level = PT64_ROOT_4LEVEL;
5024 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
5026 struct kvm_mmu *context = vcpu->arch.mmu;
5027 union kvm_mmu_role new_role =
5028 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
5030 new_role.base.word &= mmu_base_role_mask.word;
5031 if (new_role.as_u64 == context->mmu_role.as_u64)
5034 if (!is_paging(vcpu))
5035 nonpaging_init_context(vcpu, context);
5036 else if (is_long_mode(vcpu))
5037 paging64_init_context(vcpu, context);
5038 else if (is_pae(vcpu))
5039 paging32E_init_context(vcpu, context);
5041 paging32_init_context(vcpu, context);
5043 context->mmu_role.as_u64 = new_role.as_u64;
5044 reset_shadow_zero_bits_mask(vcpu, context);
5046 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
5048 static union kvm_mmu_role
5049 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5052 union kvm_mmu_role role = {0};
5054 /* SMM flag is inherited from root_mmu */
5055 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
5057 role.base.level = PT64_ROOT_4LEVEL;
5058 role.base.gpte_is_8_bytes = true;
5059 role.base.direct = false;
5060 role.base.ad_disabled = !accessed_dirty;
5061 role.base.guest_mode = true;
5062 role.base.access = ACC_ALL;
5065 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
5066 * SMAP variation to denote shadow EPT entries.
5068 role.base.cr0_wp = true;
5069 role.base.smap_andnot_wp = true;
5071 role.ext = kvm_calc_mmu_role_ext(vcpu);
5072 role.ext.execonly = execonly;
5077 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5078 bool accessed_dirty, gpa_t new_eptp)
5080 struct kvm_mmu *context = vcpu->arch.mmu;
5081 union kvm_mmu_role new_role =
5082 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5085 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
5087 new_role.base.word &= mmu_base_role_mask.word;
5088 if (new_role.as_u64 == context->mmu_role.as_u64)
5091 context->shadow_root_level = PT64_ROOT_4LEVEL;
5094 context->ept_ad = accessed_dirty;
5095 context->page_fault = ept_page_fault;
5096 context->gva_to_gpa = ept_gva_to_gpa;
5097 context->sync_page = ept_sync_page;
5098 context->invlpg = ept_invlpg;
5099 context->update_pte = ept_update_pte;
5100 context->root_level = PT64_ROOT_4LEVEL;
5101 context->direct_map = false;
5102 context->mmu_role.as_u64 = new_role.as_u64;
5104 update_permission_bitmask(vcpu, context, true);
5105 update_pkru_bitmask(vcpu, context, true);
5106 update_last_nonleaf_level(vcpu, context);
5107 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5108 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5110 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5112 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5114 struct kvm_mmu *context = vcpu->arch.mmu;
5116 kvm_init_shadow_mmu(vcpu);
5117 context->set_cr3 = kvm_x86_ops->set_cr3;
5118 context->get_cr3 = get_cr3;
5119 context->get_pdptr = kvm_pdptr_read;
5120 context->inject_page_fault = kvm_inject_page_fault;
5123 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5125 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5126 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5128 new_role.base.word &= mmu_base_role_mask.word;
5129 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5132 g_context->mmu_role.as_u64 = new_role.as_u64;
5133 g_context->get_cr3 = get_cr3;
5134 g_context->get_pdptr = kvm_pdptr_read;
5135 g_context->inject_page_fault = kvm_inject_page_fault;
5138 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5139 * L1's nested page tables (e.g. EPT12). The nested translation
5140 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5141 * L2's page tables as the first level of translation and L1's
5142 * nested page tables as the second level of translation. Basically
5143 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5145 if (!is_paging(vcpu)) {
5146 g_context->nx = false;
5147 g_context->root_level = 0;
5148 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5149 } else if (is_long_mode(vcpu)) {
5150 g_context->nx = is_nx(vcpu);
5151 g_context->root_level = is_la57_mode(vcpu) ?
5152 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5153 reset_rsvds_bits_mask(vcpu, g_context);
5154 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5155 } else if (is_pae(vcpu)) {
5156 g_context->nx = is_nx(vcpu);
5157 g_context->root_level = PT32E_ROOT_LEVEL;
5158 reset_rsvds_bits_mask(vcpu, g_context);
5159 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5161 g_context->nx = false;
5162 g_context->root_level = PT32_ROOT_LEVEL;
5163 reset_rsvds_bits_mask(vcpu, g_context);
5164 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5167 update_permission_bitmask(vcpu, g_context, false);
5168 update_pkru_bitmask(vcpu, g_context, false);
5169 update_last_nonleaf_level(vcpu, g_context);
5172 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5177 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5179 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5180 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5183 if (mmu_is_nested(vcpu))
5184 init_kvm_nested_mmu(vcpu);
5185 else if (tdp_enabled)
5186 init_kvm_tdp_mmu(vcpu);
5188 init_kvm_softmmu(vcpu);
5190 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5192 static union kvm_mmu_page_role
5193 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5195 union kvm_mmu_role role;
5198 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5200 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5205 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5207 kvm_mmu_unload(vcpu);
5208 kvm_init_mmu(vcpu, true);
5210 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5212 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5216 r = mmu_topup_memory_caches(vcpu);
5219 r = mmu_alloc_roots(vcpu);
5220 kvm_mmu_sync_roots(vcpu);
5223 kvm_mmu_load_cr3(vcpu);
5224 kvm_x86_ops->tlb_flush(vcpu, true);
5228 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5230 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5232 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5233 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5234 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5235 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5237 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5239 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5240 struct kvm_mmu_page *sp, u64 *spte,
5243 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5244 ++vcpu->kvm->stat.mmu_pde_zapped;
5248 ++vcpu->kvm->stat.mmu_pte_updated;
5249 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5252 static bool need_remote_flush(u64 old, u64 new)
5254 if (!is_shadow_present_pte(old))
5256 if (!is_shadow_present_pte(new))
5258 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5260 old ^= shadow_nx_mask;
5261 new ^= shadow_nx_mask;
5262 return (old & ~new & PT64_PERM_MASK) != 0;
5265 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5272 * Assume that the pte write on a page table of the same type
5273 * as the current vcpu paging mode since we update the sptes only
5274 * when they have the same mode.
5276 if (is_pae(vcpu) && *bytes == 4) {
5277 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5282 if (*bytes == 4 || *bytes == 8) {
5283 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5292 * If we're seeing too many writes to a page, it may no longer be a page table,
5293 * or we may be forking, in which case it is better to unmap the page.
5295 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5298 * Skip write-flooding detected for the sp whose level is 1, because
5299 * it can become unsync, then the guest page is not write-protected.
5301 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5304 atomic_inc(&sp->write_flooding_count);
5305 return atomic_read(&sp->write_flooding_count) >= 3;
5309 * Misaligned accesses are too much trouble to fix up; also, they usually
5310 * indicate a page is not used as a page table.
5312 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5315 unsigned offset, pte_size, misaligned;
5317 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5318 gpa, bytes, sp->role.word);
5320 offset = offset_in_page(gpa);
5321 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5324 * Sometimes, the OS only writes the last one bytes to update status
5325 * bits, for example, in linux, andb instruction is used in clear_bit().
5327 if (!(offset & (pte_size - 1)) && bytes == 1)
5330 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5331 misaligned |= bytes < 4;
5336 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5338 unsigned page_offset, quadrant;
5342 page_offset = offset_in_page(gpa);
5343 level = sp->role.level;
5345 if (!sp->role.gpte_is_8_bytes) {
5346 page_offset <<= 1; /* 32->64 */
5348 * A 32-bit pde maps 4MB while the shadow pdes map
5349 * only 2MB. So we need to double the offset again
5350 * and zap two pdes instead of one.
5352 if (level == PT32_ROOT_LEVEL) {
5353 page_offset &= ~7; /* kill rounding error */
5357 quadrant = page_offset >> PAGE_SHIFT;
5358 page_offset &= ~PAGE_MASK;
5359 if (quadrant != sp->role.quadrant)
5363 spte = &sp->spt[page_offset / sizeof(*spte)];
5367 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5368 const u8 *new, int bytes,
5369 struct kvm_page_track_notifier_node *node)
5371 gfn_t gfn = gpa >> PAGE_SHIFT;
5372 struct kvm_mmu_page *sp;
5373 LIST_HEAD(invalid_list);
5374 u64 entry, gentry, *spte;
5376 bool remote_flush, local_flush;
5379 * If we don't have indirect shadow pages, it means no page is
5380 * write-protected, so we can exit simply.
5382 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5385 remote_flush = local_flush = false;
5387 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5390 * No need to care whether allocation memory is successful
5391 * or not since pte prefetch is skiped if it does not have
5392 * enough objects in the cache.
5394 mmu_topup_memory_caches(vcpu);
5396 spin_lock(&vcpu->kvm->mmu_lock);
5398 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5400 ++vcpu->kvm->stat.mmu_pte_write;
5401 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5403 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5404 if (detect_write_misaligned(sp, gpa, bytes) ||
5405 detect_write_flooding(sp)) {
5406 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5407 ++vcpu->kvm->stat.mmu_flooded;
5411 spte = get_written_sptes(sp, gpa, &npte);
5417 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5420 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5422 !((sp->role.word ^ base_role)
5423 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5424 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5425 if (need_remote_flush(entry, *spte))
5426 remote_flush = true;
5430 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5431 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5432 spin_unlock(&vcpu->kvm->mmu_lock);
5435 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5440 if (vcpu->arch.mmu->direct_map)
5443 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5445 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5449 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5451 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5452 void *insn, int insn_len)
5454 int r, emulation_type = 0;
5455 bool direct = vcpu->arch.mmu->direct_map;
5457 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
5458 return RET_PF_RETRY;
5460 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5461 if (vcpu->arch.mmu->direct_map) {
5462 vcpu->arch.gpa_available = true;
5463 vcpu->arch.gpa_val = cr2_or_gpa;
5467 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5468 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5469 if (r == RET_PF_EMULATE)
5473 if (r == RET_PF_INVALID) {
5474 r = vcpu->arch.mmu->page_fault(vcpu, cr2_or_gpa,
5475 lower_32_bits(error_code),
5477 WARN_ON(r == RET_PF_INVALID);
5480 if (r == RET_PF_RETRY)
5486 * Before emulating the instruction, check if the error code
5487 * was due to a RO violation while translating the guest page.
5488 * This can occur when using nested virtualization with nested
5489 * paging in both guests. If true, we simply unprotect the page
5490 * and resume the guest.
5492 if (vcpu->arch.mmu->direct_map &&
5493 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5494 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5499 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5500 * optimistically try to just unprotect the page and let the processor
5501 * re-execute the instruction that caused the page fault. Do not allow
5502 * retrying MMIO emulation, as it's not only pointless but could also
5503 * cause us to enter an infinite loop because the processor will keep
5504 * faulting on the non-existent MMIO address. Retrying an instruction
5505 * from a nested guest is also pointless and dangerous as we are only
5506 * explicitly shadowing L1's page tables, i.e. unprotecting something
5507 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5509 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5510 emulation_type = EMULTYPE_ALLOW_RETRY;
5513 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5514 * This can happen if a guest gets a page-fault on data access but the HW
5515 * table walker is not able to read the instruction page (e.g instruction
5516 * page is not present in memory). In those cases we simply restart the
5517 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5519 if (unlikely(insn && !insn_len)) {
5520 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5524 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5527 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5529 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5531 struct kvm_mmu *mmu = vcpu->arch.mmu;
5534 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5535 if (is_noncanonical_address(gva, vcpu))
5538 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5541 * INVLPG is required to invalidate any global mappings for the VA,
5542 * irrespective of PCID. Since it would take us roughly similar amount
5543 * of work to determine whether any of the prev_root mappings of the VA
5544 * is marked global, or to just sync it blindly, so we might as well
5545 * just always sync it.
5547 * Mappings not reachable via the current cr3 or the prev_roots will be
5548 * synced when switching to that cr3, so nothing needs to be done here
5551 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5552 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5553 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5555 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5556 ++vcpu->stat.invlpg;
5558 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5560 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5562 struct kvm_mmu *mmu = vcpu->arch.mmu;
5563 bool tlb_flush = false;
5566 if (pcid == kvm_get_active_pcid(vcpu)) {
5567 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5571 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5572 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5573 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5574 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5580 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5582 ++vcpu->stat.invlpg;
5585 * Mappings not reachable via the current cr3 or the prev_roots will be
5586 * synced when switching to that cr3, so nothing needs to be done here
5590 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5592 void kvm_enable_tdp(void)
5596 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5598 void kvm_disable_tdp(void)
5600 tdp_enabled = false;
5602 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5605 /* The return value indicates if tlb flush on all vcpus is needed. */
5606 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5608 /* The caller should hold mmu-lock before calling this function. */
5609 static __always_inline bool
5610 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5611 slot_level_handler fn, int start_level, int end_level,
5612 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5614 struct slot_rmap_walk_iterator iterator;
5617 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5618 end_gfn, &iterator) {
5620 flush |= fn(kvm, iterator.rmap);
5622 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5623 if (flush && lock_flush_tlb) {
5624 kvm_flush_remote_tlbs_with_address(kvm,
5626 iterator.gfn - start_gfn + 1);
5629 cond_resched_lock(&kvm->mmu_lock);
5633 if (flush && lock_flush_tlb) {
5634 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5635 end_gfn - start_gfn + 1);
5642 static __always_inline bool
5643 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5644 slot_level_handler fn, int start_level, int end_level,
5645 bool lock_flush_tlb)
5647 return slot_handle_level_range(kvm, memslot, fn, start_level,
5648 end_level, memslot->base_gfn,
5649 memslot->base_gfn + memslot->npages - 1,
5653 static __always_inline bool
5654 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5655 slot_level_handler fn, bool lock_flush_tlb)
5657 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5658 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5661 static __always_inline bool
5662 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5663 slot_level_handler fn, bool lock_flush_tlb)
5665 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5666 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5669 static __always_inline bool
5670 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5671 slot_level_handler fn, bool lock_flush_tlb)
5673 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5674 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5677 static void free_mmu_pages(struct kvm_mmu *mmu)
5679 free_page((unsigned long)mmu->pae_root);
5680 free_page((unsigned long)mmu->lm_root);
5683 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5689 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5690 * while the PDP table is a per-vCPU construct that's allocated at MMU
5691 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5692 * x86_64. Therefore we need to allocate the PDP table in the first
5693 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5694 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5695 * skip allocating the PDP table.
5697 if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5700 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5704 mmu->pae_root = page_address(page);
5705 for (i = 0; i < 4; ++i)
5706 mmu->pae_root[i] = INVALID_PAGE;
5711 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5716 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5717 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5719 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5720 vcpu->arch.root_mmu.root_cr3 = 0;
5721 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5722 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5723 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5725 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5726 vcpu->arch.guest_mmu.root_cr3 = 0;
5727 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5728 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5729 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5731 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5733 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5737 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5739 goto fail_allocate_root;
5743 free_mmu_pages(&vcpu->arch.guest_mmu);
5747 #define BATCH_ZAP_PAGES 10
5748 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5750 struct kvm_mmu_page *sp, *node;
5751 int nr_zapped, batch = 0;
5754 list_for_each_entry_safe_reverse(sp, node,
5755 &kvm->arch.active_mmu_pages, link) {
5757 * No obsolete valid page exists before a newly created page
5758 * since active_mmu_pages is a FIFO list.
5760 if (!is_obsolete_sp(kvm, sp))
5764 * Skip invalid pages with a non-zero root count, zapping pages
5765 * with a non-zero root count will never succeed, i.e. the page
5766 * will get thrown back on active_mmu_pages and we'll get stuck
5767 * in an infinite loop.
5769 if (sp->role.invalid && sp->root_count)
5773 * No need to flush the TLB since we're only zapping shadow
5774 * pages with an obsolete generation number and all vCPUS have
5775 * loaded a new root, i.e. the shadow pages being zapped cannot
5776 * be in active use by the guest.
5778 if (batch >= BATCH_ZAP_PAGES &&
5779 cond_resched_lock(&kvm->mmu_lock)) {
5784 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5785 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5792 * Trigger a remote TLB flush before freeing the page tables to ensure
5793 * KVM is not in the middle of a lockless shadow page table walk, which
5794 * may reference the pages.
5796 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5800 * Fast invalidate all shadow pages and use lock-break technique
5801 * to zap obsolete pages.
5803 * It's required when memslot is being deleted or VM is being
5804 * destroyed, in these cases, we should ensure that KVM MMU does
5805 * not use any resource of the being-deleted slot or all slots
5806 * after calling the function.
5808 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5810 lockdep_assert_held(&kvm->slots_lock);
5812 spin_lock(&kvm->mmu_lock);
5813 trace_kvm_mmu_zap_all_fast(kvm);
5816 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5817 * held for the entire duration of zapping obsolete pages, it's
5818 * impossible for there to be multiple invalid generations associated
5819 * with *valid* shadow pages at any given time, i.e. there is exactly
5820 * one valid generation and (at most) one invalid generation.
5822 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5825 * Notify all vcpus to reload its shadow page table and flush TLB.
5826 * Then all vcpus will switch to new shadow page table with the new
5829 * Note: we need to do this under the protection of mmu_lock,
5830 * otherwise, vcpu would purge shadow page but miss tlb flush.
5832 kvm_reload_remote_mmus(kvm);
5834 kvm_zap_obsolete_pages(kvm);
5835 spin_unlock(&kvm->mmu_lock);
5838 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5840 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5843 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5844 struct kvm_memory_slot *slot,
5845 struct kvm_page_track_notifier_node *node)
5847 kvm_mmu_zap_all_fast(kvm);
5850 void kvm_mmu_init_vm(struct kvm *kvm)
5852 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5854 node->track_write = kvm_mmu_pte_write;
5855 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5856 kvm_page_track_register_notifier(kvm, node);
5859 void kvm_mmu_uninit_vm(struct kvm *kvm)
5861 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5863 kvm_page_track_unregister_notifier(kvm, node);
5866 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5868 struct kvm_memslots *slots;
5869 struct kvm_memory_slot *memslot;
5872 spin_lock(&kvm->mmu_lock);
5873 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5874 slots = __kvm_memslots(kvm, i);
5875 kvm_for_each_memslot(memslot, slots) {
5878 start = max(gfn_start, memslot->base_gfn);
5879 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5883 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5884 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5885 start, end - 1, true);
5889 spin_unlock(&kvm->mmu_lock);
5892 static bool slot_rmap_write_protect(struct kvm *kvm,
5893 struct kvm_rmap_head *rmap_head)
5895 return __rmap_write_protect(kvm, rmap_head, false);
5898 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5899 struct kvm_memory_slot *memslot)
5903 spin_lock(&kvm->mmu_lock);
5904 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5906 spin_unlock(&kvm->mmu_lock);
5909 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5910 * which do tlb flush out of mmu-lock should be serialized by
5911 * kvm->slots_lock otherwise tlb flush would be missed.
5913 lockdep_assert_held(&kvm->slots_lock);
5916 * We can flush all the TLBs out of the mmu lock without TLB
5917 * corruption since we just change the spte from writable to
5918 * readonly so that we only need to care the case of changing
5919 * spte from present to present (changing the spte from present
5920 * to nonpresent will flush all the TLBs immediately), in other
5921 * words, the only case we care is mmu_spte_update() where we
5922 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5923 * instead of PT_WRITABLE_MASK, that means it does not depend
5924 * on PT_WRITABLE_MASK anymore.
5927 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5931 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5932 struct kvm_rmap_head *rmap_head)
5935 struct rmap_iterator iter;
5936 int need_tlb_flush = 0;
5938 struct kvm_mmu_page *sp;
5941 for_each_rmap_spte(rmap_head, &iter, sptep) {
5942 sp = page_header(__pa(sptep));
5943 pfn = spte_to_pfn(*sptep);
5946 * We cannot do huge page mapping for indirect shadow pages,
5947 * which are found on the last rmap (level = 1) when not using
5948 * tdp; such shadow pages are synced with the page table in
5949 * the guest, and the guest page table is using 4K page size
5950 * mapping if the indirect sp has level = 1.
5952 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5953 !kvm_is_zone_device_pfn(pfn) &&
5954 kvm_is_transparent_hugepage(pfn)) {
5955 pte_list_remove(rmap_head, sptep);
5957 if (kvm_available_flush_tlb_with_range())
5958 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5959 KVM_PAGES_PER_HPAGE(sp->role.level));
5967 return need_tlb_flush;
5970 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5971 const struct kvm_memory_slot *memslot)
5973 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5974 spin_lock(&kvm->mmu_lock);
5975 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5976 kvm_mmu_zap_collapsible_spte, true);
5977 spin_unlock(&kvm->mmu_lock);
5980 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5981 struct kvm_memory_slot *memslot)
5985 spin_lock(&kvm->mmu_lock);
5986 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5987 spin_unlock(&kvm->mmu_lock);
5989 lockdep_assert_held(&kvm->slots_lock);
5992 * It's also safe to flush TLBs out of mmu lock here as currently this
5993 * function is only used for dirty logging, in which case flushing TLB
5994 * out of mmu lock also guarantees no dirty pages will be lost in
5998 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6001 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
6003 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
6004 struct kvm_memory_slot *memslot)
6008 spin_lock(&kvm->mmu_lock);
6009 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
6011 spin_unlock(&kvm->mmu_lock);
6013 /* see kvm_mmu_slot_remove_write_access */
6014 lockdep_assert_held(&kvm->slots_lock);
6017 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6020 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
6022 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
6023 struct kvm_memory_slot *memslot)
6027 spin_lock(&kvm->mmu_lock);
6028 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
6029 spin_unlock(&kvm->mmu_lock);
6031 lockdep_assert_held(&kvm->slots_lock);
6033 /* see kvm_mmu_slot_leaf_clear_dirty */
6035 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6038 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
6040 void kvm_mmu_zap_all(struct kvm *kvm)
6042 struct kvm_mmu_page *sp, *node;
6043 LIST_HEAD(invalid_list);
6046 spin_lock(&kvm->mmu_lock);
6048 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6049 if (sp->role.invalid && sp->root_count)
6051 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6053 if (cond_resched_lock(&kvm->mmu_lock))
6057 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6058 spin_unlock(&kvm->mmu_lock);
6061 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6063 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6065 gen &= MMIO_SPTE_GEN_MASK;
6068 * Generation numbers are incremented in multiples of the number of
6069 * address spaces in order to provide unique generations across all
6070 * address spaces. Strip what is effectively the address space
6071 * modifier prior to checking for a wrap of the MMIO generation so
6072 * that a wrap in any address space is detected.
6074 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6077 * The very rare case: if the MMIO generation number has wrapped,
6078 * zap all shadow pages.
6080 if (unlikely(gen == 0)) {
6081 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6082 kvm_mmu_zap_all_fast(kvm);
6086 static unsigned long
6087 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6090 int nr_to_scan = sc->nr_to_scan;
6091 unsigned long freed = 0;
6093 mutex_lock(&kvm_lock);
6095 list_for_each_entry(kvm, &vm_list, vm_list) {
6097 LIST_HEAD(invalid_list);
6100 * Never scan more than sc->nr_to_scan VM instances.
6101 * Will not hit this condition practically since we do not try
6102 * to shrink more than one VM and it is very unlikely to see
6103 * !n_used_mmu_pages so many times.
6108 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6109 * here. We may skip a VM instance errorneosly, but we do not
6110 * want to shrink a VM that only started to populate its MMU
6113 if (!kvm->arch.n_used_mmu_pages &&
6114 !kvm_has_zapped_obsolete_pages(kvm))
6117 idx = srcu_read_lock(&kvm->srcu);
6118 spin_lock(&kvm->mmu_lock);
6120 if (kvm_has_zapped_obsolete_pages(kvm)) {
6121 kvm_mmu_commit_zap_page(kvm,
6122 &kvm->arch.zapped_obsolete_pages);
6126 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6128 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6131 spin_unlock(&kvm->mmu_lock);
6132 srcu_read_unlock(&kvm->srcu, idx);
6135 * unfair on small ones
6136 * per-vm shrinkers cry out
6137 * sadness comes quickly
6139 list_move_tail(&kvm->vm_list, &vm_list);
6143 mutex_unlock(&kvm_lock);
6147 static unsigned long
6148 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6150 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6153 static struct shrinker mmu_shrinker = {
6154 .count_objects = mmu_shrink_count,
6155 .scan_objects = mmu_shrink_scan,
6156 .seeks = DEFAULT_SEEKS * 10,
6159 static void mmu_destroy_caches(void)
6161 kmem_cache_destroy(pte_list_desc_cache);
6162 kmem_cache_destroy(mmu_page_header_cache);
6165 static void kvm_set_mmio_spte_mask(void)
6170 * Set the reserved bits and the present bit of an paging-structure
6171 * entry to generate page fault with PFER.RSV = 1.
6175 * Mask the uppermost physical address bit, which would be reserved as
6176 * long as the supported physical address width is less than 52.
6180 /* Set the present bit. */
6184 * If reserved bit is not supported, clear the present bit to disable
6187 if (shadow_phys_bits == 52)
6190 kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
6193 static bool get_nx_auto_mode(void)
6195 /* Return true when CPU has the bug, and mitigations are ON */
6196 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6199 static void __set_nx_huge_pages(bool val)
6201 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6204 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6206 bool old_val = nx_huge_pages;
6209 /* In "auto" mode deploy workaround only if CPU has the bug. */
6210 if (sysfs_streq(val, "off"))
6212 else if (sysfs_streq(val, "force"))
6214 else if (sysfs_streq(val, "auto"))
6215 new_val = get_nx_auto_mode();
6216 else if (strtobool(val, &new_val) < 0)
6219 __set_nx_huge_pages(new_val);
6221 if (new_val != old_val) {
6224 mutex_lock(&kvm_lock);
6226 list_for_each_entry(kvm, &vm_list, vm_list) {
6227 mutex_lock(&kvm->slots_lock);
6228 kvm_mmu_zap_all_fast(kvm);
6229 mutex_unlock(&kvm->slots_lock);
6231 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6233 mutex_unlock(&kvm_lock);
6239 int kvm_mmu_module_init(void)
6243 if (nx_huge_pages == -1)
6244 __set_nx_huge_pages(get_nx_auto_mode());
6247 * MMU roles use union aliasing which is, generally speaking, an
6248 * undefined behavior. However, we supposedly know how compilers behave
6249 * and the current status quo is unlikely to change. Guardians below are
6250 * supposed to let us know if the assumption becomes false.
6252 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6253 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6254 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6256 kvm_mmu_reset_all_pte_masks();
6258 kvm_set_mmio_spte_mask();
6260 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6261 sizeof(struct pte_list_desc),
6262 0, SLAB_ACCOUNT, NULL);
6263 if (!pte_list_desc_cache)
6266 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6267 sizeof(struct kvm_mmu_page),
6268 0, SLAB_ACCOUNT, NULL);
6269 if (!mmu_page_header_cache)
6272 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6275 ret = register_shrinker(&mmu_shrinker);
6282 mmu_destroy_caches();
6287 * Calculate mmu pages needed for kvm.
6289 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6291 unsigned long nr_mmu_pages;
6292 unsigned long nr_pages = 0;
6293 struct kvm_memslots *slots;
6294 struct kvm_memory_slot *memslot;
6297 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6298 slots = __kvm_memslots(kvm, i);
6300 kvm_for_each_memslot(memslot, slots)
6301 nr_pages += memslot->npages;
6304 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6305 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6307 return nr_mmu_pages;
6310 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6312 kvm_mmu_unload(vcpu);
6313 free_mmu_pages(&vcpu->arch.root_mmu);
6314 free_mmu_pages(&vcpu->arch.guest_mmu);
6315 mmu_free_memory_caches(vcpu);
6318 void kvm_mmu_module_exit(void)
6320 mmu_destroy_caches();
6321 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6322 unregister_shrinker(&mmu_shrinker);
6323 mmu_audit_disable();
6326 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6328 unsigned int old_val;
6331 old_val = nx_huge_pages_recovery_ratio;
6332 err = param_set_uint(val, kp);
6336 if (READ_ONCE(nx_huge_pages) &&
6337 !old_val && nx_huge_pages_recovery_ratio) {
6340 mutex_lock(&kvm_lock);
6342 list_for_each_entry(kvm, &vm_list, vm_list)
6343 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6345 mutex_unlock(&kvm_lock);
6351 static void kvm_recover_nx_lpages(struct kvm *kvm)
6354 struct kvm_mmu_page *sp;
6356 LIST_HEAD(invalid_list);
6359 rcu_idx = srcu_read_lock(&kvm->srcu);
6360 spin_lock(&kvm->mmu_lock);
6362 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6363 to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
6364 while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
6366 * We use a separate list instead of just using active_mmu_pages
6367 * because the number of lpage_disallowed pages is expected to
6368 * be relatively small compared to the total.
6370 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6371 struct kvm_mmu_page,
6372 lpage_disallowed_link);
6373 WARN_ON_ONCE(!sp->lpage_disallowed);
6374 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6375 WARN_ON_ONCE(sp->lpage_disallowed);
6377 if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
6378 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6380 cond_resched_lock(&kvm->mmu_lock);
6384 spin_unlock(&kvm->mmu_lock);
6385 srcu_read_unlock(&kvm->srcu, rcu_idx);
6388 static long get_nx_lpage_recovery_timeout(u64 start_time)
6390 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6391 ? start_time + 60 * HZ - get_jiffies_64()
6392 : MAX_SCHEDULE_TIMEOUT;
6395 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6398 long remaining_time;
6401 start_time = get_jiffies_64();
6402 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6404 set_current_state(TASK_INTERRUPTIBLE);
6405 while (!kthread_should_stop() && remaining_time > 0) {
6406 schedule_timeout(remaining_time);
6407 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6408 set_current_state(TASK_INTERRUPTIBLE);
6411 set_current_state(TASK_RUNNING);
6413 if (kthread_should_stop())
6416 kvm_recover_nx_lpages(kvm);
6420 int kvm_mmu_post_init_vm(struct kvm *kvm)
6424 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6425 "kvm-nx-lpage-recovery",
6426 &kvm->arch.nx_lpage_recovery_thread);
6428 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6433 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6435 if (kvm->arch.nx_lpage_recovery_thread)
6436 kthread_stop(kvm->arch.nx_lpage_recovery_thread);