2 * Kernel-based Virtual Machine driver for Linux
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
9 * Copyright (C) 2006 Qumranet, Inc.
10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Avi Kivity <avi@qumranet.com>
16 * This work is licensed under the terms of the GNU GPL, version 2. See
17 * the COPYING file in the top-level directory.
24 #include "kvm_cache_regs.h"
27 #include <linux/kvm_host.h>
28 #include <linux/types.h>
29 #include <linux/string.h>
31 #include <linux/highmem.h>
32 #include <linux/moduleparam.h>
33 #include <linux/export.h>
34 #include <linux/swap.h>
35 #include <linux/hugetlb.h>
36 #include <linux/compiler.h>
37 #include <linux/srcu.h>
38 #include <linux/slab.h>
39 #include <linux/sched/signal.h>
40 #include <linux/uaccess.h>
41 #include <linux/hash.h>
42 #include <linux/kern_levels.h>
43 #include <linux/kthread.h>
47 #include <asm/cmpxchg.h>
50 #include <asm/kvm_page_track.h>
53 extern bool itlb_multihit_kvm_mitigation;
55 static int __read_mostly nx_huge_pages = -1;
56 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
58 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
59 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp);
61 static struct kernel_param_ops nx_huge_pages_ops = {
62 .set = set_nx_huge_pages,
63 .get = param_get_bool,
66 static struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
67 .set = set_nx_huge_pages_recovery_ratio,
68 .get = param_get_uint,
71 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
72 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
73 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
74 &nx_huge_pages_recovery_ratio, 0644);
75 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
78 * When setting this variable to true it enables Two-Dimensional-Paging
79 * where the hardware walks 2 page tables:
80 * 1. the guest-virtual to guest-physical
81 * 2. while doing 1. it walks guest-physical to host-physical
82 * If the hardware supports that we don't need to do shadow paging.
84 bool tdp_enabled = false;
88 AUDIT_POST_PAGE_FAULT,
99 module_param(dbg, bool, 0644);
101 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
102 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
103 #define MMU_WARN_ON(x) WARN_ON(x)
105 #define pgprintk(x...) do { } while (0)
106 #define rmap_printk(x...) do { } while (0)
107 #define MMU_WARN_ON(x) do { } while (0)
110 #define PTE_PREFETCH_NUM 8
112 #define PT_FIRST_AVAIL_BITS_SHIFT 10
113 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
115 #define PT64_LEVEL_BITS 9
117 #define PT64_LEVEL_SHIFT(level) \
118 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
120 #define PT64_INDEX(address, level)\
121 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
124 #define PT32_LEVEL_BITS 10
126 #define PT32_LEVEL_SHIFT(level) \
127 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
129 #define PT32_LVL_OFFSET_MASK(level) \
130 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
131 * PT32_LEVEL_BITS))) - 1))
133 #define PT32_INDEX(address, level)\
134 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
137 #define PT64_BASE_ADDR_MASK __sme_clr((((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)))
138 #define PT64_DIR_BASE_ADDR_MASK \
139 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
140 #define PT64_LVL_ADDR_MASK(level) \
141 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
142 * PT64_LEVEL_BITS))) - 1))
143 #define PT64_LVL_OFFSET_MASK(level) \
144 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
145 * PT64_LEVEL_BITS))) - 1))
147 #define PT32_BASE_ADDR_MASK PAGE_MASK
148 #define PT32_DIR_BASE_ADDR_MASK \
149 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
150 #define PT32_LVL_ADDR_MASK(level) \
151 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
152 * PT32_LEVEL_BITS))) - 1))
154 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
155 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
157 #define ACC_EXEC_MASK 1
158 #define ACC_WRITE_MASK PT_WRITABLE_MASK
159 #define ACC_USER_MASK PT_USER_MASK
160 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
162 /* The mask for the R/X bits in EPT PTEs */
163 #define PT64_EPT_READABLE_MASK 0x1ull
164 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
166 #include <trace/events/kvm.h>
168 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
169 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
171 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
173 /* make pte_list_desc fit well in cache line */
174 #define PTE_LIST_EXT 3
177 * Return values of handle_mmio_page_fault and mmu.page_fault:
178 * RET_PF_RETRY: let CPU fault again on the address.
179 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
181 * For handle_mmio_page_fault only:
182 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
190 struct pte_list_desc {
191 u64 *sptes[PTE_LIST_EXT];
192 struct pte_list_desc *more;
195 struct kvm_shadow_walk_iterator {
203 static const union kvm_mmu_page_role mmu_base_role_mask = {
214 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
215 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
217 shadow_walk_okay(&(_walker)); \
218 shadow_walk_next(&(_walker)))
220 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
221 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
222 shadow_walk_okay(&(_walker)); \
223 shadow_walk_next(&(_walker)))
225 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
226 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
227 shadow_walk_okay(&(_walker)) && \
228 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
229 __shadow_walk_next(&(_walker), spte))
231 static struct kmem_cache *pte_list_desc_cache;
232 static struct kmem_cache *mmu_page_header_cache;
233 static struct percpu_counter kvm_total_used_mmu_pages;
235 static u64 __read_mostly shadow_nx_mask;
236 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
237 static u64 __read_mostly shadow_user_mask;
238 static u64 __read_mostly shadow_accessed_mask;
239 static u64 __read_mostly shadow_dirty_mask;
240 static u64 __read_mostly shadow_mmio_mask;
241 static u64 __read_mostly shadow_mmio_value;
242 static u64 __read_mostly shadow_present_mask;
243 static u64 __read_mostly shadow_me_mask;
246 * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
247 * Non-present SPTEs with shadow_acc_track_value set are in place for access
250 static u64 __read_mostly shadow_acc_track_mask;
251 static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
254 * The mask/shift to use for saving the original R/X bits when marking the PTE
255 * as not-present for access tracking purposes. We do not save the W bit as the
256 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
257 * restored only when a write is attempted to the page.
259 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
260 PT64_EPT_EXECUTABLE_MASK;
261 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
264 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
265 * to guard against L1TF attacks.
267 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
270 * The number of high-order 1 bits to use in the mask above.
272 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
275 * In some cases, we need to preserve the GFN of a non-present or reserved
276 * SPTE when we usurp the upper five bits of the physical address space to
277 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
278 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
279 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
280 * high and low parts. This mask covers the lower bits of the GFN.
282 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
285 * The number of non-reserved physical address bits irrespective of features
286 * that repurpose legal bits, e.g. MKTME.
288 static u8 __read_mostly shadow_phys_bits;
290 static void mmu_spte_set(u64 *sptep, u64 spte);
291 static bool is_executable_pte(u64 spte);
292 static union kvm_mmu_page_role
293 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
295 #define CREATE_TRACE_POINTS
296 #include "mmutrace.h"
299 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
301 BUG_ON((mmio_mask & mmio_value) != mmio_value);
302 WARN_ON(mmio_value & (shadow_nonpresent_or_rsvd_mask << shadow_nonpresent_or_rsvd_mask_len));
303 WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);
304 shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
305 shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
307 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
309 static bool is_mmio_spte(u64 spte)
311 return (spte & shadow_mmio_mask) == shadow_mmio_value;
314 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
316 return sp->role.ad_disabled;
319 static inline bool spte_ad_enabled(u64 spte)
321 MMU_WARN_ON(is_mmio_spte(spte));
322 return !(spte & shadow_acc_track_value);
325 static bool is_nx_huge_page_enabled(void)
327 return READ_ONCE(nx_huge_pages);
330 static inline u64 spte_shadow_accessed_mask(u64 spte)
332 MMU_WARN_ON(is_mmio_spte(spte));
333 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
336 static inline u64 spte_shadow_dirty_mask(u64 spte)
338 MMU_WARN_ON(is_mmio_spte(spte));
339 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
342 static inline bool is_access_track_spte(u64 spte)
344 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
348 * the low bit of the generation number is always presumed to be zero.
349 * This disables mmio caching during memslot updates. The concept is
350 * similar to a seqcount but instead of retrying the access we just punt
351 * and ignore the cache.
353 * spte bits 3-11 are used as bits 1-9 of the generation number,
354 * the bits 52-61 are used as bits 10-19 of the generation number.
356 #define MMIO_SPTE_GEN_LOW_SHIFT 2
357 #define MMIO_SPTE_GEN_HIGH_SHIFT 52
359 #define MMIO_GEN_SHIFT 20
360 #define MMIO_GEN_LOW_SHIFT 10
361 #define MMIO_GEN_LOW_MASK ((1 << MMIO_GEN_LOW_SHIFT) - 2)
362 #define MMIO_GEN_MASK ((1 << MMIO_GEN_SHIFT) - 1)
364 static u64 generation_mmio_spte_mask(unsigned int gen)
368 WARN_ON(gen & ~MMIO_GEN_MASK);
370 mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
371 mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
375 static unsigned int get_mmio_spte_generation(u64 spte)
379 spte &= ~shadow_mmio_mask;
381 gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
382 gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
386 static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
388 return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
391 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
394 unsigned int gen = kvm_current_mmio_generation(vcpu);
395 u64 mask = generation_mmio_spte_mask(gen);
396 u64 gpa = gfn << PAGE_SHIFT;
398 access &= ACC_WRITE_MASK | ACC_USER_MASK;
399 mask |= shadow_mmio_value | access;
400 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
401 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
402 << shadow_nonpresent_or_rsvd_mask_len;
404 trace_mark_mmio_spte(sptep, gfn, access, gen);
405 mmu_spte_set(sptep, mask);
408 static gfn_t get_mmio_spte_gfn(u64 spte)
410 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
412 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
413 & shadow_nonpresent_or_rsvd_mask;
415 return gpa >> PAGE_SHIFT;
418 static unsigned get_mmio_spte_access(u64 spte)
420 u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
421 return (spte & ~mask) & ~PAGE_MASK;
424 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
425 kvm_pfn_t pfn, unsigned access)
427 if (unlikely(is_noslot_pfn(pfn))) {
428 mark_mmio_spte(vcpu, sptep, gfn, access);
435 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
437 unsigned int kvm_gen, spte_gen;
439 kvm_gen = kvm_current_mmio_generation(vcpu);
440 spte_gen = get_mmio_spte_generation(spte);
442 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
443 return likely(kvm_gen == spte_gen);
447 * Sets the shadow PTE masks used by the MMU.
450 * - Setting either @accessed_mask or @dirty_mask requires setting both
451 * - At least one of @accessed_mask or @acc_track_mask must be set
453 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
454 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
455 u64 acc_track_mask, u64 me_mask)
457 BUG_ON(!dirty_mask != !accessed_mask);
458 BUG_ON(!accessed_mask && !acc_track_mask);
459 BUG_ON(acc_track_mask & shadow_acc_track_value);
461 shadow_user_mask = user_mask;
462 shadow_accessed_mask = accessed_mask;
463 shadow_dirty_mask = dirty_mask;
464 shadow_nx_mask = nx_mask;
465 shadow_x_mask = x_mask;
466 shadow_present_mask = p_mask;
467 shadow_acc_track_mask = acc_track_mask;
468 shadow_me_mask = me_mask;
470 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
472 static u8 kvm_get_shadow_phys_bits(void)
475 * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
476 * in CPU detection code, but MKTME treats those reduced bits as
477 * 'keyID' thus they are not reserved bits. Therefore for MKTME
478 * we should still return physical address bits reported by CPUID.
480 if (!boot_cpu_has(X86_FEATURE_TME) ||
481 WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
482 return boot_cpu_data.x86_phys_bits;
484 return cpuid_eax(0x80000008) & 0xff;
487 static void kvm_mmu_reset_all_pte_masks(void)
491 shadow_user_mask = 0;
492 shadow_accessed_mask = 0;
493 shadow_dirty_mask = 0;
496 shadow_mmio_mask = 0;
497 shadow_present_mask = 0;
498 shadow_acc_track_mask = 0;
500 shadow_phys_bits = kvm_get_shadow_phys_bits();
503 * If the CPU has 46 or less physical address bits, then set an
504 * appropriate mask to guard against L1TF attacks. Otherwise, it is
505 * assumed that the CPU is not vulnerable to L1TF.
507 * Some Intel CPUs address the L1 cache using more PA bits than are
508 * reported by CPUID. Use the PA width of the L1 cache when possible
509 * to achieve more effective mitigation, e.g. if system RAM overlaps
510 * the most significant bits of legal physical address space.
512 shadow_nonpresent_or_rsvd_mask = 0;
513 low_phys_bits = boot_cpu_data.x86_phys_bits;
514 if (boot_cpu_has_bug(X86_BUG_L1TF) &&
515 !WARN_ON_ONCE(boot_cpu_data.x86_cache_bits >=
516 52 - shadow_nonpresent_or_rsvd_mask_len)) {
517 low_phys_bits = boot_cpu_data.x86_cache_bits
518 - shadow_nonpresent_or_rsvd_mask_len;
519 shadow_nonpresent_or_rsvd_mask =
520 rsvd_bits(low_phys_bits, boot_cpu_data.x86_cache_bits - 1);
523 shadow_nonpresent_or_rsvd_lower_gfn_mask =
524 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
527 static int is_cpuid_PSE36(void)
532 static int is_nx(struct kvm_vcpu *vcpu)
534 return vcpu->arch.efer & EFER_NX;
537 static int is_shadow_present_pte(u64 pte)
539 return (pte != 0) && !is_mmio_spte(pte);
542 static int is_large_pte(u64 pte)
544 return pte & PT_PAGE_SIZE_MASK;
547 static int is_last_spte(u64 pte, int level)
549 if (level == PT_PAGE_TABLE_LEVEL)
551 if (is_large_pte(pte))
556 static bool is_executable_pte(u64 spte)
558 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
561 static kvm_pfn_t spte_to_pfn(u64 pte)
563 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
566 static gfn_t pse36_gfn_delta(u32 gpte)
568 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
570 return (gpte & PT32_DIR_PSE36_MASK) << shift;
574 static void __set_spte(u64 *sptep, u64 spte)
576 WRITE_ONCE(*sptep, spte);
579 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
581 WRITE_ONCE(*sptep, spte);
584 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
586 return xchg(sptep, spte);
589 static u64 __get_spte_lockless(u64 *sptep)
591 return READ_ONCE(*sptep);
602 static void count_spte_clear(u64 *sptep, u64 spte)
604 struct kvm_mmu_page *sp = page_header(__pa(sptep));
606 if (is_shadow_present_pte(spte))
609 /* Ensure the spte is completely set before we increase the count */
611 sp->clear_spte_count++;
614 static void __set_spte(u64 *sptep, u64 spte)
616 union split_spte *ssptep, sspte;
618 ssptep = (union split_spte *)sptep;
619 sspte = (union split_spte)spte;
621 ssptep->spte_high = sspte.spte_high;
624 * If we map the spte from nonpresent to present, We should store
625 * the high bits firstly, then set present bit, so cpu can not
626 * fetch this spte while we are setting the spte.
630 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
633 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
635 union split_spte *ssptep, sspte;
637 ssptep = (union split_spte *)sptep;
638 sspte = (union split_spte)spte;
640 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
643 * If we map the spte from present to nonpresent, we should clear
644 * present bit firstly to avoid vcpu fetch the old high bits.
648 ssptep->spte_high = sspte.spte_high;
649 count_spte_clear(sptep, spte);
652 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
654 union split_spte *ssptep, sspte, orig;
656 ssptep = (union split_spte *)sptep;
657 sspte = (union split_spte)spte;
659 /* xchg acts as a barrier before the setting of the high bits */
660 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
661 orig.spte_high = ssptep->spte_high;
662 ssptep->spte_high = sspte.spte_high;
663 count_spte_clear(sptep, spte);
669 * The idea using the light way get the spte on x86_32 guest is from
670 * gup_get_pte(arch/x86/mm/gup.c).
672 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
673 * coalesces them and we are running out of the MMU lock. Therefore
674 * we need to protect against in-progress updates of the spte.
676 * Reading the spte while an update is in progress may get the old value
677 * for the high part of the spte. The race is fine for a present->non-present
678 * change (because the high part of the spte is ignored for non-present spte),
679 * but for a present->present change we must reread the spte.
681 * All such changes are done in two steps (present->non-present and
682 * non-present->present), hence it is enough to count the number of
683 * present->non-present updates: if it changed while reading the spte,
684 * we might have hit the race. This is done using clear_spte_count.
686 static u64 __get_spte_lockless(u64 *sptep)
688 struct kvm_mmu_page *sp = page_header(__pa(sptep));
689 union split_spte spte, *orig = (union split_spte *)sptep;
693 count = sp->clear_spte_count;
696 spte.spte_low = orig->spte_low;
699 spte.spte_high = orig->spte_high;
702 if (unlikely(spte.spte_low != orig->spte_low ||
703 count != sp->clear_spte_count))
710 static bool spte_can_locklessly_be_made_writable(u64 spte)
712 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
713 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
716 static bool spte_has_volatile_bits(u64 spte)
718 if (!is_shadow_present_pte(spte))
722 * Always atomically update spte if it can be updated
723 * out of mmu-lock, it can ensure dirty bit is not lost,
724 * also, it can help us to get a stable is_writable_pte()
725 * to ensure tlb flush is not missed.
727 if (spte_can_locklessly_be_made_writable(spte) ||
728 is_access_track_spte(spte))
731 if (spte_ad_enabled(spte)) {
732 if ((spte & shadow_accessed_mask) == 0 ||
733 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
740 static bool is_accessed_spte(u64 spte)
742 u64 accessed_mask = spte_shadow_accessed_mask(spte);
744 return accessed_mask ? spte & accessed_mask
745 : !is_access_track_spte(spte);
748 static bool is_dirty_spte(u64 spte)
750 u64 dirty_mask = spte_shadow_dirty_mask(spte);
752 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
755 /* Rules for using mmu_spte_set:
756 * Set the sptep from nonpresent to present.
757 * Note: the sptep being assigned *must* be either not present
758 * or in a state where the hardware will not attempt to update
761 static void mmu_spte_set(u64 *sptep, u64 new_spte)
763 WARN_ON(is_shadow_present_pte(*sptep));
764 __set_spte(sptep, new_spte);
768 * Update the SPTE (excluding the PFN), but do not track changes in its
769 * accessed/dirty status.
771 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
773 u64 old_spte = *sptep;
775 WARN_ON(!is_shadow_present_pte(new_spte));
777 if (!is_shadow_present_pte(old_spte)) {
778 mmu_spte_set(sptep, new_spte);
782 if (!spte_has_volatile_bits(old_spte))
783 __update_clear_spte_fast(sptep, new_spte);
785 old_spte = __update_clear_spte_slow(sptep, new_spte);
787 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
792 /* Rules for using mmu_spte_update:
793 * Update the state bits, it means the mapped pfn is not changed.
795 * Whenever we overwrite a writable spte with a read-only one we
796 * should flush remote TLBs. Otherwise rmap_write_protect
797 * will find a read-only spte, even though the writable spte
798 * might be cached on a CPU's TLB, the return value indicates this
801 * Returns true if the TLB needs to be flushed
803 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
806 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
808 if (!is_shadow_present_pte(old_spte))
812 * For the spte updated out of mmu-lock is safe, since
813 * we always atomically update it, see the comments in
814 * spte_has_volatile_bits().
816 if (spte_can_locklessly_be_made_writable(old_spte) &&
817 !is_writable_pte(new_spte))
821 * Flush TLB when accessed/dirty states are changed in the page tables,
822 * to guarantee consistency between TLB and page tables.
825 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
827 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
830 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
832 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
839 * Rules for using mmu_spte_clear_track_bits:
840 * It sets the sptep from present to nonpresent, and track the
841 * state bits, it is used to clear the last level sptep.
842 * Returns non-zero if the PTE was previously valid.
844 static int mmu_spte_clear_track_bits(u64 *sptep)
847 u64 old_spte = *sptep;
849 if (!spte_has_volatile_bits(old_spte))
850 __update_clear_spte_fast(sptep, 0ull);
852 old_spte = __update_clear_spte_slow(sptep, 0ull);
854 if (!is_shadow_present_pte(old_spte))
857 pfn = spte_to_pfn(old_spte);
860 * KVM does not hold the refcount of the page used by
861 * kvm mmu, before reclaiming the page, we should
862 * unmap it from mmu first.
864 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
866 if (is_accessed_spte(old_spte))
867 kvm_set_pfn_accessed(pfn);
869 if (is_dirty_spte(old_spte))
870 kvm_set_pfn_dirty(pfn);
876 * Rules for using mmu_spte_clear_no_track:
877 * Directly clear spte without caring the state bits of sptep,
878 * it is used to set the upper level spte.
880 static void mmu_spte_clear_no_track(u64 *sptep)
882 __update_clear_spte_fast(sptep, 0ull);
885 static u64 mmu_spte_get_lockless(u64 *sptep)
887 return __get_spte_lockless(sptep);
890 static u64 mark_spte_for_access_track(u64 spte)
892 if (spte_ad_enabled(spte))
893 return spte & ~shadow_accessed_mask;
895 if (is_access_track_spte(spte))
899 * Making an Access Tracking PTE will result in removal of write access
900 * from the PTE. So, verify that we will be able to restore the write
901 * access in the fast page fault path later on.
903 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
904 !spte_can_locklessly_be_made_writable(spte),
905 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
907 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
908 shadow_acc_track_saved_bits_shift),
909 "kvm: Access Tracking saved bit locations are not zero\n");
911 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
912 shadow_acc_track_saved_bits_shift;
913 spte &= ~shadow_acc_track_mask;
918 /* Restore an acc-track PTE back to a regular PTE */
919 static u64 restore_acc_track_spte(u64 spte)
922 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
923 & shadow_acc_track_saved_bits_mask;
925 WARN_ON_ONCE(spte_ad_enabled(spte));
926 WARN_ON_ONCE(!is_access_track_spte(spte));
928 new_spte &= ~shadow_acc_track_mask;
929 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
930 shadow_acc_track_saved_bits_shift);
931 new_spte |= saved_bits;
936 /* Returns the Accessed status of the PTE and resets it at the same time. */
937 static bool mmu_spte_age(u64 *sptep)
939 u64 spte = mmu_spte_get_lockless(sptep);
941 if (!is_accessed_spte(spte))
944 if (spte_ad_enabled(spte)) {
945 clear_bit((ffs(shadow_accessed_mask) - 1),
946 (unsigned long *)sptep);
949 * Capture the dirty status of the page, so that it doesn't get
950 * lost when the SPTE is marked for access tracking.
952 if (is_writable_pte(spte))
953 kvm_set_pfn_dirty(spte_to_pfn(spte));
955 spte = mark_spte_for_access_track(spte);
956 mmu_spte_update_no_track(sptep, spte);
962 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
965 * Prevent page table teardown by making any free-er wait during
966 * kvm_flush_remote_tlbs() IPI to all active vcpus.
971 * Make sure a following spte read is not reordered ahead of the write
974 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
977 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
980 * Make sure the write to vcpu->mode is not reordered in front of
981 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
982 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
984 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
988 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
989 struct kmem_cache *base_cache, int min)
993 if (cache->nobjs >= min)
995 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
996 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
999 cache->objects[cache->nobjs++] = obj;
1004 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
1006 return cache->nobjs;
1009 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
1010 struct kmem_cache *cache)
1013 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
1016 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1021 if (cache->nobjs >= min)
1023 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1024 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1027 cache->objects[cache->nobjs++] = page;
1032 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1035 free_page((unsigned long)mc->objects[--mc->nobjs]);
1038 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1042 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1043 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1046 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1049 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1050 mmu_page_header_cache, 4);
1055 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1057 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1058 pte_list_desc_cache);
1059 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1060 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1061 mmu_page_header_cache);
1064 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1069 p = mc->objects[--mc->nobjs];
1073 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1075 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1078 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1080 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1083 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1085 if (!sp->role.direct)
1086 return sp->gfns[index];
1088 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1091 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1093 if (!sp->role.direct) {
1094 sp->gfns[index] = gfn;
1098 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1099 pr_err_ratelimited("gfn mismatch under direct page %llx "
1100 "(expected %llx, got %llx)\n",
1102 kvm_mmu_page_get_gfn(sp, index), gfn);
1106 * Return the pointer to the large page information for a given gfn,
1107 * handling slots that are not large page aligned.
1109 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1110 struct kvm_memory_slot *slot,
1115 idx = gfn_to_index(gfn, slot->base_gfn, level);
1116 return &slot->arch.lpage_info[level - 2][idx];
1119 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1120 gfn_t gfn, int count)
1122 struct kvm_lpage_info *linfo;
1125 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1126 linfo = lpage_info_slot(gfn, slot, i);
1127 linfo->disallow_lpage += count;
1128 WARN_ON(linfo->disallow_lpage < 0);
1132 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1134 update_gfn_disallow_lpage_count(slot, gfn, 1);
1137 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1139 update_gfn_disallow_lpage_count(slot, gfn, -1);
1142 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1144 struct kvm_memslots *slots;
1145 struct kvm_memory_slot *slot;
1148 kvm->arch.indirect_shadow_pages++;
1150 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1151 slot = __gfn_to_memslot(slots, gfn);
1153 /* the non-leaf shadow pages are keeping readonly. */
1154 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1155 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1156 KVM_PAGE_TRACK_WRITE);
1158 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1161 static void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1163 if (sp->lpage_disallowed)
1166 ++kvm->stat.nx_lpage_splits;
1167 list_add_tail(&sp->lpage_disallowed_link,
1168 &kvm->arch.lpage_disallowed_mmu_pages);
1169 sp->lpage_disallowed = true;
1172 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1174 struct kvm_memslots *slots;
1175 struct kvm_memory_slot *slot;
1178 kvm->arch.indirect_shadow_pages--;
1180 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1181 slot = __gfn_to_memslot(slots, gfn);
1182 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1183 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1184 KVM_PAGE_TRACK_WRITE);
1186 kvm_mmu_gfn_allow_lpage(slot, gfn);
1189 static void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1191 --kvm->stat.nx_lpage_splits;
1192 sp->lpage_disallowed = false;
1193 list_del(&sp->lpage_disallowed_link);
1196 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1197 struct kvm_memory_slot *slot)
1199 struct kvm_lpage_info *linfo;
1202 linfo = lpage_info_slot(gfn, slot, level);
1203 return !!linfo->disallow_lpage;
1209 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1212 struct kvm_memory_slot *slot;
1214 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1215 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1218 static int host_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn)
1220 unsigned long page_size;
1223 page_size = kvm_host_page_size(vcpu, gfn);
1225 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1226 if (page_size >= KVM_HPAGE_SIZE(i))
1235 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1238 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1240 if (no_dirty_log && slot->dirty_bitmap)
1246 static struct kvm_memory_slot *
1247 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1250 struct kvm_memory_slot *slot;
1252 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1253 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1259 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1260 bool *force_pt_level)
1262 int host_level, level, max_level;
1263 struct kvm_memory_slot *slot;
1265 if (unlikely(*force_pt_level))
1266 return PT_PAGE_TABLE_LEVEL;
1268 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1269 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1270 if (unlikely(*force_pt_level))
1271 return PT_PAGE_TABLE_LEVEL;
1273 host_level = host_mapping_level(vcpu, large_gfn);
1275 if (host_level == PT_PAGE_TABLE_LEVEL)
1278 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1280 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1281 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1288 * About rmap_head encoding:
1290 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1291 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1292 * pte_list_desc containing more mappings.
1296 * Returns the number of pointers in the rmap chain, not counting the new one.
1298 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1299 struct kvm_rmap_head *rmap_head)
1301 struct pte_list_desc *desc;
1304 if (!rmap_head->val) {
1305 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1306 rmap_head->val = (unsigned long)spte;
1307 } else if (!(rmap_head->val & 1)) {
1308 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1309 desc = mmu_alloc_pte_list_desc(vcpu);
1310 desc->sptes[0] = (u64 *)rmap_head->val;
1311 desc->sptes[1] = spte;
1312 rmap_head->val = (unsigned long)desc | 1;
1315 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1316 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1317 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1319 count += PTE_LIST_EXT;
1321 if (desc->sptes[PTE_LIST_EXT-1]) {
1322 desc->more = mmu_alloc_pte_list_desc(vcpu);
1325 for (i = 0; desc->sptes[i]; ++i)
1327 desc->sptes[i] = spte;
1333 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1334 struct pte_list_desc *desc, int i,
1335 struct pte_list_desc *prev_desc)
1339 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1341 desc->sptes[i] = desc->sptes[j];
1342 desc->sptes[j] = NULL;
1345 if (!prev_desc && !desc->more)
1346 rmap_head->val = (unsigned long)desc->sptes[0];
1349 prev_desc->more = desc->more;
1351 rmap_head->val = (unsigned long)desc->more | 1;
1352 mmu_free_pte_list_desc(desc);
1355 static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1357 struct pte_list_desc *desc;
1358 struct pte_list_desc *prev_desc;
1361 if (!rmap_head->val) {
1362 printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
1364 } else if (!(rmap_head->val & 1)) {
1365 rmap_printk("pte_list_remove: %p 1->0\n", spte);
1366 if ((u64 *)rmap_head->val != spte) {
1367 printk(KERN_ERR "pte_list_remove: %p 1->BUG\n", spte);
1372 rmap_printk("pte_list_remove: %p many->many\n", spte);
1373 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1376 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1377 if (desc->sptes[i] == spte) {
1378 pte_list_desc_remove_entry(rmap_head,
1379 desc, i, prev_desc);
1386 pr_err("pte_list_remove: %p many->many\n", spte);
1391 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1392 struct kvm_memory_slot *slot)
1396 idx = gfn_to_index(gfn, slot->base_gfn, level);
1397 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1400 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1401 struct kvm_mmu_page *sp)
1403 struct kvm_memslots *slots;
1404 struct kvm_memory_slot *slot;
1406 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1407 slot = __gfn_to_memslot(slots, gfn);
1408 return __gfn_to_rmap(gfn, sp->role.level, slot);
1411 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1413 struct kvm_mmu_memory_cache *cache;
1415 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1416 return mmu_memory_cache_free_objects(cache);
1419 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1421 struct kvm_mmu_page *sp;
1422 struct kvm_rmap_head *rmap_head;
1424 sp = page_header(__pa(spte));
1425 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1426 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1427 return pte_list_add(vcpu, spte, rmap_head);
1430 static void rmap_remove(struct kvm *kvm, u64 *spte)
1432 struct kvm_mmu_page *sp;
1434 struct kvm_rmap_head *rmap_head;
1436 sp = page_header(__pa(spte));
1437 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1438 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1439 pte_list_remove(spte, rmap_head);
1443 * Used by the following functions to iterate through the sptes linked by a
1444 * rmap. All fields are private and not assumed to be used outside.
1446 struct rmap_iterator {
1447 /* private fields */
1448 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1449 int pos; /* index of the sptep */
1453 * Iteration must be started by this function. This should also be used after
1454 * removing/dropping sptes from the rmap link because in such cases the
1455 * information in the itererator may not be valid.
1457 * Returns sptep if found, NULL otherwise.
1459 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1460 struct rmap_iterator *iter)
1464 if (!rmap_head->val)
1467 if (!(rmap_head->val & 1)) {
1469 sptep = (u64 *)rmap_head->val;
1473 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1475 sptep = iter->desc->sptes[iter->pos];
1477 BUG_ON(!is_shadow_present_pte(*sptep));
1482 * Must be used with a valid iterator: e.g. after rmap_get_first().
1484 * Returns sptep if found, NULL otherwise.
1486 static u64 *rmap_get_next(struct rmap_iterator *iter)
1491 if (iter->pos < PTE_LIST_EXT - 1) {
1493 sptep = iter->desc->sptes[iter->pos];
1498 iter->desc = iter->desc->more;
1502 /* desc->sptes[0] cannot be NULL */
1503 sptep = iter->desc->sptes[iter->pos];
1510 BUG_ON(!is_shadow_present_pte(*sptep));
1514 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1515 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1516 _spte_; _spte_ = rmap_get_next(_iter_))
1518 static void drop_spte(struct kvm *kvm, u64 *sptep)
1520 if (mmu_spte_clear_track_bits(sptep))
1521 rmap_remove(kvm, sptep);
1525 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1527 if (is_large_pte(*sptep)) {
1528 WARN_ON(page_header(__pa(sptep))->role.level ==
1529 PT_PAGE_TABLE_LEVEL);
1530 drop_spte(kvm, sptep);
1538 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1540 if (__drop_large_spte(vcpu->kvm, sptep))
1541 kvm_flush_remote_tlbs(vcpu->kvm);
1545 * Write-protect on the specified @sptep, @pt_protect indicates whether
1546 * spte write-protection is caused by protecting shadow page table.
1548 * Note: write protection is difference between dirty logging and spte
1550 * - for dirty logging, the spte can be set to writable at anytime if
1551 * its dirty bitmap is properly set.
1552 * - for spte protection, the spte can be writable only after unsync-ing
1555 * Return true if tlb need be flushed.
1557 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1561 if (!is_writable_pte(spte) &&
1562 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1565 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1568 spte &= ~SPTE_MMU_WRITEABLE;
1569 spte = spte & ~PT_WRITABLE_MASK;
1571 return mmu_spte_update(sptep, spte);
1574 static bool __rmap_write_protect(struct kvm *kvm,
1575 struct kvm_rmap_head *rmap_head,
1579 struct rmap_iterator iter;
1582 for_each_rmap_spte(rmap_head, &iter, sptep)
1583 flush |= spte_write_protect(sptep, pt_protect);
1588 static bool spte_clear_dirty(u64 *sptep)
1592 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1594 spte &= ~shadow_dirty_mask;
1596 return mmu_spte_update(sptep, spte);
1599 static bool wrprot_ad_disabled_spte(u64 *sptep)
1601 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1602 (unsigned long *)sptep);
1604 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1606 return was_writable;
1610 * Gets the GFN ready for another round of dirty logging by clearing the
1611 * - D bit on ad-enabled SPTEs, and
1612 * - W bit on ad-disabled SPTEs.
1613 * Returns true iff any D or W bits were cleared.
1615 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1618 struct rmap_iterator iter;
1621 for_each_rmap_spte(rmap_head, &iter, sptep)
1622 if (spte_ad_enabled(*sptep))
1623 flush |= spte_clear_dirty(sptep);
1625 flush |= wrprot_ad_disabled_spte(sptep);
1630 static bool spte_set_dirty(u64 *sptep)
1634 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1636 spte |= shadow_dirty_mask;
1638 return mmu_spte_update(sptep, spte);
1641 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1644 struct rmap_iterator iter;
1647 for_each_rmap_spte(rmap_head, &iter, sptep)
1648 if (spte_ad_enabled(*sptep))
1649 flush |= spte_set_dirty(sptep);
1655 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1656 * @kvm: kvm instance
1657 * @slot: slot to protect
1658 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1659 * @mask: indicates which pages we should protect
1661 * Used when we do not need to care about huge page mappings: e.g. during dirty
1662 * logging we do not have any such mappings.
1664 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1665 struct kvm_memory_slot *slot,
1666 gfn_t gfn_offset, unsigned long mask)
1668 struct kvm_rmap_head *rmap_head;
1671 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1672 PT_PAGE_TABLE_LEVEL, slot);
1673 __rmap_write_protect(kvm, rmap_head, false);
1675 /* clear the first set bit */
1681 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1682 * protect the page if the D-bit isn't supported.
1683 * @kvm: kvm instance
1684 * @slot: slot to clear D-bit
1685 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1686 * @mask: indicates which pages we should clear D-bit
1688 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1690 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1691 struct kvm_memory_slot *slot,
1692 gfn_t gfn_offset, unsigned long mask)
1694 struct kvm_rmap_head *rmap_head;
1697 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1698 PT_PAGE_TABLE_LEVEL, slot);
1699 __rmap_clear_dirty(kvm, rmap_head);
1701 /* clear the first set bit */
1705 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1708 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1711 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1712 * enable dirty logging for them.
1714 * Used when we do not need to care about huge page mappings: e.g. during dirty
1715 * logging we do not have any such mappings.
1717 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1718 struct kvm_memory_slot *slot,
1719 gfn_t gfn_offset, unsigned long mask)
1721 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1722 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1725 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1729 * kvm_arch_write_log_dirty - emulate dirty page logging
1730 * @vcpu: Guest mode vcpu
1732 * Emulate arch specific page modification logging for the
1735 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu, gpa_t l2_gpa)
1737 if (kvm_x86_ops->write_log_dirty)
1738 return kvm_x86_ops->write_log_dirty(vcpu, l2_gpa);
1743 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1744 struct kvm_memory_slot *slot, u64 gfn)
1746 struct kvm_rmap_head *rmap_head;
1748 bool write_protected = false;
1750 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1751 rmap_head = __gfn_to_rmap(gfn, i, slot);
1752 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1755 return write_protected;
1758 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1760 struct kvm_memory_slot *slot;
1762 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1763 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1766 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1769 struct rmap_iterator iter;
1772 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1773 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1775 drop_spte(kvm, sptep);
1782 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1783 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1786 return kvm_zap_rmapp(kvm, rmap_head);
1789 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1790 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1794 struct rmap_iterator iter;
1797 pte_t *ptep = (pte_t *)data;
1800 WARN_ON(pte_huge(*ptep));
1801 new_pfn = pte_pfn(*ptep);
1804 for_each_rmap_spte(rmap_head, &iter, sptep) {
1805 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1806 sptep, *sptep, gfn, level);
1810 if (pte_write(*ptep)) {
1811 drop_spte(kvm, sptep);
1814 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1815 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1817 new_spte &= ~PT_WRITABLE_MASK;
1818 new_spte &= ~SPTE_HOST_WRITEABLE;
1820 new_spte = mark_spte_for_access_track(new_spte);
1822 mmu_spte_clear_track_bits(sptep);
1823 mmu_spte_set(sptep, new_spte);
1828 kvm_flush_remote_tlbs(kvm);
1833 struct slot_rmap_walk_iterator {
1835 struct kvm_memory_slot *slot;
1841 /* output fields. */
1843 struct kvm_rmap_head *rmap;
1846 /* private field. */
1847 struct kvm_rmap_head *end_rmap;
1851 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1853 iterator->level = level;
1854 iterator->gfn = iterator->start_gfn;
1855 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1856 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1861 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1862 struct kvm_memory_slot *slot, int start_level,
1863 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1865 iterator->slot = slot;
1866 iterator->start_level = start_level;
1867 iterator->end_level = end_level;
1868 iterator->start_gfn = start_gfn;
1869 iterator->end_gfn = end_gfn;
1871 rmap_walk_init_level(iterator, iterator->start_level);
1874 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1876 return !!iterator->rmap;
1879 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1881 if (++iterator->rmap <= iterator->end_rmap) {
1882 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1886 if (++iterator->level > iterator->end_level) {
1887 iterator->rmap = NULL;
1891 rmap_walk_init_level(iterator, iterator->level);
1894 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1895 _start_gfn, _end_gfn, _iter_) \
1896 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1897 _end_level_, _start_gfn, _end_gfn); \
1898 slot_rmap_walk_okay(_iter_); \
1899 slot_rmap_walk_next(_iter_))
1901 static int kvm_handle_hva_range(struct kvm *kvm,
1902 unsigned long start,
1905 int (*handler)(struct kvm *kvm,
1906 struct kvm_rmap_head *rmap_head,
1907 struct kvm_memory_slot *slot,
1910 unsigned long data))
1912 struct kvm_memslots *slots;
1913 struct kvm_memory_slot *memslot;
1914 struct slot_rmap_walk_iterator iterator;
1918 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1919 slots = __kvm_memslots(kvm, i);
1920 kvm_for_each_memslot(memslot, slots) {
1921 unsigned long hva_start, hva_end;
1922 gfn_t gfn_start, gfn_end;
1924 hva_start = max(start, memslot->userspace_addr);
1925 hva_end = min(end, memslot->userspace_addr +
1926 (memslot->npages << PAGE_SHIFT));
1927 if (hva_start >= hva_end)
1930 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1931 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1933 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1934 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1936 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1937 PT_MAX_HUGEPAGE_LEVEL,
1938 gfn_start, gfn_end - 1,
1940 ret |= handler(kvm, iterator.rmap, memslot,
1941 iterator.gfn, iterator.level, data);
1948 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1950 int (*handler)(struct kvm *kvm,
1951 struct kvm_rmap_head *rmap_head,
1952 struct kvm_memory_slot *slot,
1953 gfn_t gfn, int level,
1954 unsigned long data))
1956 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1959 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end,
1962 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1965 void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1967 kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1970 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1971 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1975 struct rmap_iterator uninitialized_var(iter);
1978 for_each_rmap_spte(rmap_head, &iter, sptep)
1979 young |= mmu_spte_age(sptep);
1981 trace_kvm_age_page(gfn, level, slot, young);
1985 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1986 struct kvm_memory_slot *slot, gfn_t gfn,
1987 int level, unsigned long data)
1990 struct rmap_iterator iter;
1992 for_each_rmap_spte(rmap_head, &iter, sptep)
1993 if (is_accessed_spte(*sptep))
1998 #define RMAP_RECYCLE_THRESHOLD 1000
2000 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2002 struct kvm_rmap_head *rmap_head;
2003 struct kvm_mmu_page *sp;
2005 sp = page_header(__pa(spte));
2007 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2009 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2010 kvm_flush_remote_tlbs(vcpu->kvm);
2013 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2015 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2018 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2020 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2024 static int is_empty_shadow_page(u64 *spt)
2029 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2030 if (is_shadow_present_pte(*pos)) {
2031 printk(KERN_ERR "%s: %p %llx\n", __func__,
2040 * This value is the sum of all of the kvm instances's
2041 * kvm->arch.n_used_mmu_pages values. We need a global,
2042 * aggregate version in order to make the slab shrinker
2045 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
2047 kvm->arch.n_used_mmu_pages += nr;
2048 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2051 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2053 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2054 hlist_del(&sp->hash_link);
2055 list_del(&sp->link);
2056 free_page((unsigned long)sp->spt);
2057 if (!sp->role.direct)
2058 free_page((unsigned long)sp->gfns);
2059 kmem_cache_free(mmu_page_header_cache, sp);
2062 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2064 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2067 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2068 struct kvm_mmu_page *sp, u64 *parent_pte)
2073 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2076 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2079 pte_list_remove(parent_pte, &sp->parent_ptes);
2082 static void drop_parent_pte(struct kvm_mmu_page *sp,
2085 mmu_page_remove_parent_pte(sp, parent_pte);
2086 mmu_spte_clear_no_track(parent_pte);
2089 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2091 struct kvm_mmu_page *sp;
2093 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2094 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2096 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2097 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2100 * The active_mmu_pages list is the FIFO list, do not move the
2101 * page until it is zapped. kvm_zap_obsolete_pages depends on
2102 * this feature. See the comments in kvm_zap_obsolete_pages().
2104 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2105 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2109 static void mark_unsync(u64 *spte);
2110 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2113 struct rmap_iterator iter;
2115 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2120 static void mark_unsync(u64 *spte)
2122 struct kvm_mmu_page *sp;
2125 sp = page_header(__pa(spte));
2126 index = spte - sp->spt;
2127 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2129 if (sp->unsync_children++)
2131 kvm_mmu_mark_parents_unsync(sp);
2134 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2135 struct kvm_mmu_page *sp)
2140 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2144 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2145 struct kvm_mmu_page *sp, u64 *spte,
2151 #define KVM_PAGE_ARRAY_NR 16
2153 struct kvm_mmu_pages {
2154 struct mmu_page_and_offset {
2155 struct kvm_mmu_page *sp;
2157 } page[KVM_PAGE_ARRAY_NR];
2161 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2167 for (i=0; i < pvec->nr; i++)
2168 if (pvec->page[i].sp == sp)
2171 pvec->page[pvec->nr].sp = sp;
2172 pvec->page[pvec->nr].idx = idx;
2174 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2177 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2179 --sp->unsync_children;
2180 WARN_ON((int)sp->unsync_children < 0);
2181 __clear_bit(idx, sp->unsync_child_bitmap);
2184 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2185 struct kvm_mmu_pages *pvec)
2187 int i, ret, nr_unsync_leaf = 0;
2189 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2190 struct kvm_mmu_page *child;
2191 u64 ent = sp->spt[i];
2193 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2194 clear_unsync_child_bit(sp, i);
2198 child = page_header(ent & PT64_BASE_ADDR_MASK);
2200 if (child->unsync_children) {
2201 if (mmu_pages_add(pvec, child, i))
2204 ret = __mmu_unsync_walk(child, pvec);
2206 clear_unsync_child_bit(sp, i);
2208 } else if (ret > 0) {
2209 nr_unsync_leaf += ret;
2212 } else if (child->unsync) {
2214 if (mmu_pages_add(pvec, child, i))
2217 clear_unsync_child_bit(sp, i);
2220 return nr_unsync_leaf;
2223 #define INVALID_INDEX (-1)
2225 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2226 struct kvm_mmu_pages *pvec)
2229 if (!sp->unsync_children)
2232 mmu_pages_add(pvec, sp, INVALID_INDEX);
2233 return __mmu_unsync_walk(sp, pvec);
2236 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2238 WARN_ON(!sp->unsync);
2239 trace_kvm_mmu_sync_page(sp);
2241 --kvm->stat.mmu_unsync;
2244 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2245 struct list_head *invalid_list);
2246 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2247 struct list_head *invalid_list);
2250 * NOTE: we should pay more attention on the zapped-obsolete page
2251 * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
2252 * since it has been deleted from active_mmu_pages but still can be found
2255 * for_each_valid_sp() has skipped that kind of pages.
2257 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2258 hlist_for_each_entry(_sp, \
2259 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2260 if (is_obsolete_sp((_kvm), (_sp)) || (_sp)->role.invalid) { \
2263 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2264 for_each_valid_sp(_kvm, _sp, _gfn) \
2265 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2267 /* @sp->gfn should be write-protected at the call site */
2268 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2269 struct list_head *invalid_list)
2271 if (sp->role.cr4_pae != !!is_pae(vcpu)
2272 || vcpu->arch.mmu.sync_page(vcpu, sp) == 0) {
2273 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2280 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2281 struct list_head *invalid_list,
2282 bool remote_flush, bool local_flush)
2284 if (!list_empty(invalid_list)) {
2285 kvm_mmu_commit_zap_page(vcpu->kvm, invalid_list);
2290 kvm_flush_remote_tlbs(vcpu->kvm);
2291 else if (local_flush)
2292 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2295 #ifdef CONFIG_KVM_MMU_AUDIT
2296 #include "mmu_audit.c"
2298 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2299 static void mmu_audit_disable(void) { }
2302 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2304 return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2307 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2308 struct list_head *invalid_list)
2310 kvm_unlink_unsync_page(vcpu->kvm, sp);
2311 return __kvm_sync_page(vcpu, sp, invalid_list);
2314 /* @gfn should be write-protected at the call site */
2315 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2316 struct list_head *invalid_list)
2318 struct kvm_mmu_page *s;
2321 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2325 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2326 ret |= kvm_sync_page(vcpu, s, invalid_list);
2332 struct mmu_page_path {
2333 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2334 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2337 #define for_each_sp(pvec, sp, parents, i) \
2338 for (i = mmu_pages_first(&pvec, &parents); \
2339 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2340 i = mmu_pages_next(&pvec, &parents, i))
2342 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2343 struct mmu_page_path *parents,
2348 for (n = i+1; n < pvec->nr; n++) {
2349 struct kvm_mmu_page *sp = pvec->page[n].sp;
2350 unsigned idx = pvec->page[n].idx;
2351 int level = sp->role.level;
2353 parents->idx[level-1] = idx;
2354 if (level == PT_PAGE_TABLE_LEVEL)
2357 parents->parent[level-2] = sp;
2363 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2364 struct mmu_page_path *parents)
2366 struct kvm_mmu_page *sp;
2372 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2374 sp = pvec->page[0].sp;
2375 level = sp->role.level;
2376 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2378 parents->parent[level-2] = sp;
2380 /* Also set up a sentinel. Further entries in pvec are all
2381 * children of sp, so this element is never overwritten.
2383 parents->parent[level-1] = NULL;
2384 return mmu_pages_next(pvec, parents, 0);
2387 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2389 struct kvm_mmu_page *sp;
2390 unsigned int level = 0;
2393 unsigned int idx = parents->idx[level];
2394 sp = parents->parent[level];
2398 WARN_ON(idx == INVALID_INDEX);
2399 clear_unsync_child_bit(sp, idx);
2401 } while (!sp->unsync_children);
2404 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2405 struct kvm_mmu_page *parent)
2408 struct kvm_mmu_page *sp;
2409 struct mmu_page_path parents;
2410 struct kvm_mmu_pages pages;
2411 LIST_HEAD(invalid_list);
2414 while (mmu_unsync_walk(parent, &pages)) {
2415 bool protected = false;
2417 for_each_sp(pages, sp, parents, i)
2418 protected |= rmap_write_protect(vcpu, sp->gfn);
2421 kvm_flush_remote_tlbs(vcpu->kvm);
2425 for_each_sp(pages, sp, parents, i) {
2426 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2427 mmu_pages_clear_parents(&parents);
2429 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2430 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2431 cond_resched_lock(&vcpu->kvm->mmu_lock);
2436 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2439 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2441 atomic_set(&sp->write_flooding_count, 0);
2444 static void clear_sp_write_flooding_count(u64 *spte)
2446 struct kvm_mmu_page *sp = page_header(__pa(spte));
2448 __clear_sp_write_flooding_count(sp);
2451 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2458 union kvm_mmu_page_role role;
2460 struct kvm_mmu_page *sp;
2461 bool need_sync = false;
2464 LIST_HEAD(invalid_list);
2466 role = vcpu->arch.mmu.base_role;
2468 role.direct = direct;
2471 role.access = access;
2472 if (!vcpu->arch.mmu.direct_map
2473 && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
2474 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2475 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2476 role.quadrant = quadrant;
2478 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2479 if (sp->gfn != gfn) {
2484 if (!need_sync && sp->unsync)
2487 if (sp->role.word != role.word)
2491 /* The page is good, but __kvm_sync_page might still end
2492 * up zapping it. If so, break in order to rebuild it.
2494 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2497 WARN_ON(!list_empty(&invalid_list));
2498 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2501 if (sp->unsync_children)
2502 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2504 __clear_sp_write_flooding_count(sp);
2505 trace_kvm_mmu_get_page(sp, false);
2509 ++vcpu->kvm->stat.mmu_cache_miss;
2511 sp = kvm_mmu_alloc_page(vcpu, direct);
2515 hlist_add_head(&sp->hash_link,
2516 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2519 * we should do write protection before syncing pages
2520 * otherwise the content of the synced shadow page may
2521 * be inconsistent with guest page table.
2523 account_shadowed(vcpu->kvm, sp);
2524 if (level == PT_PAGE_TABLE_LEVEL &&
2525 rmap_write_protect(vcpu, gfn))
2526 kvm_flush_remote_tlbs(vcpu->kvm);
2528 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2529 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2531 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2532 clear_page(sp->spt);
2533 trace_kvm_mmu_get_page(sp, true);
2535 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2537 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2538 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2542 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2543 struct kvm_vcpu *vcpu, hpa_t root,
2546 iterator->addr = addr;
2547 iterator->shadow_addr = root;
2548 iterator->level = vcpu->arch.mmu.shadow_root_level;
2550 if (iterator->level == PT64_ROOT_4LEVEL &&
2551 vcpu->arch.mmu.root_level < PT64_ROOT_4LEVEL &&
2552 !vcpu->arch.mmu.direct_map)
2555 if (iterator->level == PT32E_ROOT_LEVEL) {
2557 * prev_root is currently only used for 64-bit hosts. So only
2558 * the active root_hpa is valid here.
2560 BUG_ON(root != vcpu->arch.mmu.root_hpa);
2562 iterator->shadow_addr
2563 = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
2564 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2566 if (!iterator->shadow_addr)
2567 iterator->level = 0;
2571 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2572 struct kvm_vcpu *vcpu, u64 addr)
2574 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu.root_hpa,
2578 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2580 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2583 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2584 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2588 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2591 if (is_last_spte(spte, iterator->level)) {
2592 iterator->level = 0;
2596 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2600 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2602 __shadow_walk_next(iterator, *iterator->sptep);
2605 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2606 struct kvm_mmu_page *sp)
2610 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2612 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2613 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2615 if (sp_ad_disabled(sp))
2616 spte |= shadow_acc_track_value;
2618 spte |= shadow_accessed_mask;
2620 mmu_spte_set(sptep, spte);
2622 mmu_page_add_parent_pte(vcpu, sp, sptep);
2624 if (sp->unsync_children || sp->unsync)
2628 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2629 unsigned direct_access)
2631 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2632 struct kvm_mmu_page *child;
2635 * For the direct sp, if the guest pte's dirty bit
2636 * changed form clean to dirty, it will corrupt the
2637 * sp's access: allow writable in the read-only sp,
2638 * so we should update the spte at this point to get
2639 * a new sp with the correct access.
2641 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2642 if (child->role.access == direct_access)
2645 drop_parent_pte(child, sptep);
2646 kvm_flush_remote_tlbs(vcpu->kvm);
2650 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2654 struct kvm_mmu_page *child;
2657 if (is_shadow_present_pte(pte)) {
2658 if (is_last_spte(pte, sp->role.level)) {
2659 drop_spte(kvm, spte);
2660 if (is_large_pte(pte))
2663 child = page_header(pte & PT64_BASE_ADDR_MASK);
2664 drop_parent_pte(child, spte);
2669 if (is_mmio_spte(pte))
2670 mmu_spte_clear_no_track(spte);
2675 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2676 struct kvm_mmu_page *sp)
2680 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2681 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2684 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2687 struct rmap_iterator iter;
2689 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2690 drop_parent_pte(sp, sptep);
2693 static int mmu_zap_unsync_children(struct kvm *kvm,
2694 struct kvm_mmu_page *parent,
2695 struct list_head *invalid_list)
2698 struct mmu_page_path parents;
2699 struct kvm_mmu_pages pages;
2701 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2704 while (mmu_unsync_walk(parent, &pages)) {
2705 struct kvm_mmu_page *sp;
2707 for_each_sp(pages, sp, parents, i) {
2708 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2709 mmu_pages_clear_parents(&parents);
2717 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2718 struct list_head *invalid_list)
2722 trace_kvm_mmu_prepare_zap_page(sp);
2723 ++kvm->stat.mmu_shadow_zapped;
2724 ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
2725 kvm_mmu_page_unlink_children(kvm, sp);
2726 kvm_mmu_unlink_parents(kvm, sp);
2728 if (!sp->role.invalid && !sp->role.direct)
2729 unaccount_shadowed(kvm, sp);
2732 kvm_unlink_unsync_page(kvm, sp);
2733 if (!sp->root_count) {
2736 list_move(&sp->link, invalid_list);
2737 kvm_mod_used_mmu_pages(kvm, -1);
2739 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2742 * The obsolete pages can not be used on any vcpus.
2743 * See the comments in kvm_mmu_invalidate_zap_all_pages().
2745 if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
2746 kvm_reload_remote_mmus(kvm);
2749 if (sp->lpage_disallowed)
2750 unaccount_huge_nx_page(kvm, sp);
2752 sp->role.invalid = 1;
2756 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2757 struct list_head *invalid_list)
2759 struct kvm_mmu_page *sp, *nsp;
2761 if (list_empty(invalid_list))
2765 * We need to make sure everyone sees our modifications to
2766 * the page tables and see changes to vcpu->mode here. The barrier
2767 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2768 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2770 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2771 * guest mode and/or lockless shadow page table walks.
2773 kvm_flush_remote_tlbs(kvm);
2775 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2776 WARN_ON(!sp->role.invalid || sp->root_count);
2777 kvm_mmu_free_page(sp);
2781 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2782 struct list_head *invalid_list)
2784 struct kvm_mmu_page *sp;
2786 if (list_empty(&kvm->arch.active_mmu_pages))
2789 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2790 struct kvm_mmu_page, link);
2791 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2795 * Changing the number of mmu pages allocated to the vm
2796 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2798 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2800 LIST_HEAD(invalid_list);
2802 spin_lock(&kvm->mmu_lock);
2804 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2805 /* Need to free some mmu pages to achieve the goal. */
2806 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2807 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2810 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2811 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2814 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2816 spin_unlock(&kvm->mmu_lock);
2819 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2821 struct kvm_mmu_page *sp;
2822 LIST_HEAD(invalid_list);
2825 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2827 spin_lock(&kvm->mmu_lock);
2828 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2829 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2832 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2834 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2835 spin_unlock(&kvm->mmu_lock);
2839 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2841 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2843 trace_kvm_mmu_unsync_page(sp);
2844 ++vcpu->kvm->stat.mmu_unsync;
2847 kvm_mmu_mark_parents_unsync(sp);
2850 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2853 struct kvm_mmu_page *sp;
2855 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2858 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2865 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2866 kvm_unsync_page(vcpu, sp);
2870 * We need to ensure that the marking of unsync pages is visible
2871 * before the SPTE is updated to allow writes because
2872 * kvm_mmu_sync_roots() checks the unsync flags without holding
2873 * the MMU lock and so can race with this. If the SPTE was updated
2874 * before the page had been marked as unsync-ed, something like the
2875 * following could happen:
2878 * ---------------------------------------------------------------------
2879 * 1.2 Host updates SPTE
2881 * 2.1 Guest writes a GPTE for GVA X.
2882 * (GPTE being in the guest page table shadowed
2883 * by the SP from CPU 1.)
2884 * This reads SPTE during the page table walk.
2885 * Since SPTE.W is read as 1, there is no
2888 * 2.2 Guest issues TLB flush.
2889 * That causes a VM Exit.
2891 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2892 * Since it is false, so it just returns.
2894 * 2.4 Guest accesses GVA X.
2895 * Since the mapping in the SP was not updated,
2896 * so the old mapping for GVA X incorrectly
2900 * (sp->unsync = true)
2902 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2903 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2904 * pairs with this write barrier.
2911 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2914 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2916 * Some reserved pages, such as those from NVDIMM
2917 * DAX devices, are not for MMIO, and can be mapped
2918 * with cached memory type for better performance.
2919 * However, the above check misconceives those pages
2920 * as MMIO, and results in KVM mapping them with UC
2921 * memory type, which would hurt the performance.
2922 * Therefore, we check the host memory type in addition
2923 * and only treat UC/UC-/WC pages as MMIO.
2925 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2930 /* Bits which may be returned by set_spte() */
2931 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2932 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2934 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2935 unsigned pte_access, int level,
2936 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2937 bool can_unsync, bool host_writable)
2941 struct kvm_mmu_page *sp;
2943 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2946 sp = page_header(__pa(sptep));
2947 if (sp_ad_disabled(sp))
2948 spte |= shadow_acc_track_value;
2951 * For the EPT case, shadow_present_mask is 0 if hardware
2952 * supports exec-only page table entries. In that case,
2953 * ACC_USER_MASK and shadow_user_mask are used to represent
2954 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2956 spte |= shadow_present_mask;
2958 spte |= spte_shadow_accessed_mask(spte);
2960 if (level > PT_PAGE_TABLE_LEVEL && (pte_access & ACC_EXEC_MASK) &&
2961 is_nx_huge_page_enabled()) {
2962 pte_access &= ~ACC_EXEC_MASK;
2965 if (pte_access & ACC_EXEC_MASK)
2966 spte |= shadow_x_mask;
2968 spte |= shadow_nx_mask;
2970 if (pte_access & ACC_USER_MASK)
2971 spte |= shadow_user_mask;
2973 if (level > PT_PAGE_TABLE_LEVEL)
2974 spte |= PT_PAGE_SIZE_MASK;
2976 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2977 kvm_is_mmio_pfn(pfn));
2980 spte |= SPTE_HOST_WRITEABLE;
2982 pte_access &= ~ACC_WRITE_MASK;
2984 if (!kvm_is_mmio_pfn(pfn))
2985 spte |= shadow_me_mask;
2987 spte |= (u64)pfn << PAGE_SHIFT;
2989 if (pte_access & ACC_WRITE_MASK) {
2992 * Other vcpu creates new sp in the window between
2993 * mapping_level() and acquiring mmu-lock. We can
2994 * allow guest to retry the access, the mapping can
2995 * be fixed if guest refault.
2997 if (level > PT_PAGE_TABLE_LEVEL &&
2998 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3001 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3004 * Optimization: for pte sync, if spte was writable the hash
3005 * lookup is unnecessary (and expensive). Write protection
3006 * is responsibility of mmu_get_page / kvm_sync_page.
3007 * Same reasoning can be applied to dirty page accounting.
3009 if (!can_unsync && is_writable_pte(*sptep))
3012 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3013 pgprintk("%s: found shadow page for %llx, marking ro\n",
3015 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3016 pte_access &= ~ACC_WRITE_MASK;
3017 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3021 if (pte_access & ACC_WRITE_MASK) {
3022 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3023 spte |= spte_shadow_dirty_mask(spte);
3027 spte = mark_spte_for_access_track(spte);
3030 if (mmu_spte_update(sptep, spte))
3031 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3036 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3037 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3038 bool speculative, bool host_writable)
3040 int was_rmapped = 0;
3043 int ret = RET_PF_RETRY;
3046 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3047 *sptep, write_fault, gfn);
3049 if (is_shadow_present_pte(*sptep)) {
3051 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3052 * the parent of the now unreachable PTE.
3054 if (level > PT_PAGE_TABLE_LEVEL &&
3055 !is_large_pte(*sptep)) {
3056 struct kvm_mmu_page *child;
3059 child = page_header(pte & PT64_BASE_ADDR_MASK);
3060 drop_parent_pte(child, sptep);
3062 } else if (pfn != spte_to_pfn(*sptep)) {
3063 pgprintk("hfn old %llx new %llx\n",
3064 spte_to_pfn(*sptep), pfn);
3065 drop_spte(vcpu->kvm, sptep);
3071 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3072 speculative, true, host_writable);
3073 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3075 ret = RET_PF_EMULATE;
3076 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3078 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3079 kvm_flush_remote_tlbs(vcpu->kvm);
3081 if (unlikely(is_mmio_spte(*sptep)))
3082 ret = RET_PF_EMULATE;
3084 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3085 trace_kvm_mmu_set_spte(level, gfn, sptep);
3086 if (!was_rmapped && is_large_pte(*sptep))
3087 ++vcpu->kvm->stat.lpages;
3089 if (is_shadow_present_pte(*sptep)) {
3091 rmap_count = rmap_add(vcpu, sptep, gfn);
3092 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3093 rmap_recycle(vcpu, sptep, gfn);
3100 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3103 struct kvm_memory_slot *slot;
3105 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3107 return KVM_PFN_ERR_FAULT;
3109 return gfn_to_pfn_memslot_atomic(slot, gfn);
3112 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3113 struct kvm_mmu_page *sp,
3114 u64 *start, u64 *end)
3116 struct page *pages[PTE_PREFETCH_NUM];
3117 struct kvm_memory_slot *slot;
3118 unsigned access = sp->role.access;
3122 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3123 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3127 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3131 for (i = 0; i < ret; i++, gfn++, start++) {
3132 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3133 page_to_pfn(pages[i]), true, true);
3140 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3141 struct kvm_mmu_page *sp, u64 *sptep)
3143 u64 *spte, *start = NULL;
3146 WARN_ON(!sp->role.direct);
3148 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3151 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3152 if (is_shadow_present_pte(*spte) || spte == sptep) {
3155 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3163 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3165 struct kvm_mmu_page *sp;
3167 sp = page_header(__pa(sptep));
3170 * Without accessed bits, there's no way to distinguish between
3171 * actually accessed translations and prefetched, so disable pte
3172 * prefetch if accessed bits aren't available.
3174 if (sp_ad_disabled(sp))
3177 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3180 __direct_pte_prefetch(vcpu, sp, sptep);
3183 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3184 gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3186 int level = *levelp;
3187 u64 spte = *it.sptep;
3189 if (it.level == level && level > PT_PAGE_TABLE_LEVEL &&
3190 is_nx_huge_page_enabled() &&
3191 is_shadow_present_pte(spte) &&
3192 !is_large_pte(spte)) {
3194 * A small SPTE exists for this pfn, but FNAME(fetch)
3195 * and __direct_map would like to create a large PTE
3196 * instead: just force them to go down another level,
3197 * patching back for them into pfn the next 9 bits of
3200 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3201 *pfnp |= gfn & page_mask;
3206 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3207 int map_writable, int level, kvm_pfn_t pfn,
3208 bool prefault, bool lpage_disallowed)
3210 struct kvm_shadow_walk_iterator it;
3211 struct kvm_mmu_page *sp;
3213 gfn_t gfn = gpa >> PAGE_SHIFT;
3214 gfn_t base_gfn = gfn;
3216 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3217 return RET_PF_RETRY;
3219 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3220 for_each_shadow_entry(vcpu, gpa, it) {
3222 * We cannot overwrite existing page tables with an NX
3223 * large page, as the leaf could be executable.
3225 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3227 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3228 if (it.level == level)
3231 drop_large_spte(vcpu, it.sptep);
3232 if (!is_shadow_present_pte(*it.sptep)) {
3233 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3234 it.level - 1, true, ACC_ALL);
3236 link_shadow_page(vcpu, it.sptep, sp);
3237 if (lpage_disallowed)
3238 account_huge_nx_page(vcpu->kvm, sp);
3242 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3243 write, level, base_gfn, pfn, prefault,
3245 direct_pte_prefetch(vcpu, it.sptep);
3246 ++vcpu->stat.pf_fixed;
3250 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3254 clear_siginfo(&info);
3255 info.si_signo = SIGBUS;
3257 info.si_code = BUS_MCEERR_AR;
3258 info.si_addr = (void __user *)address;
3259 info.si_addr_lsb = PAGE_SHIFT;
3261 send_sig_info(SIGBUS, &info, tsk);
3264 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3267 * Do not cache the mmio info caused by writing the readonly gfn
3268 * into the spte otherwise read access on readonly gfn also can
3269 * caused mmio page fault and treat it as mmio access.
3271 if (pfn == KVM_PFN_ERR_RO_FAULT)
3272 return RET_PF_EMULATE;
3274 if (pfn == KVM_PFN_ERR_HWPOISON) {
3275 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3276 return RET_PF_RETRY;
3282 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3283 gfn_t gfn, kvm_pfn_t *pfnp,
3286 kvm_pfn_t pfn = *pfnp;
3287 int level = *levelp;
3290 * Check if it's a transparent hugepage. If this would be an
3291 * hugetlbfs page, level wouldn't be set to
3292 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3295 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3296 !kvm_is_zone_device_pfn(pfn) && level == PT_PAGE_TABLE_LEVEL &&
3297 PageTransCompoundMap(pfn_to_page(pfn)) &&
3298 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3301 * mmu_notifier_retry was successful and we hold the
3302 * mmu_lock here, so the pmd can't become splitting
3303 * from under us, and in turn
3304 * __split_huge_page_refcount() can't run from under
3305 * us and we can safely transfer the refcount from
3306 * PG_tail to PG_head as we switch the pfn to tail to
3309 *levelp = level = PT_DIRECTORY_LEVEL;
3310 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3311 VM_BUG_ON((gfn & mask) != (pfn & mask));
3313 kvm_release_pfn_clean(pfn);
3321 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3322 kvm_pfn_t pfn, unsigned access, int *ret_val)
3324 /* The pfn is invalid, report the error! */
3325 if (unlikely(is_error_pfn(pfn))) {
3326 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3330 if (unlikely(is_noslot_pfn(pfn)))
3331 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
3336 static bool page_fault_can_be_fast(u32 error_code)
3339 * Do not fix the mmio spte with invalid generation number which
3340 * need to be updated by slow page fault path.
3342 if (unlikely(error_code & PFERR_RSVD_MASK))
3345 /* See if the page fault is due to an NX violation */
3346 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3347 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3351 * #PF can be fast if:
3352 * 1. The shadow page table entry is not present, which could mean that
3353 * the fault is potentially caused by access tracking (if enabled).
3354 * 2. The shadow page table entry is present and the fault
3355 * is caused by write-protect, that means we just need change the W
3356 * bit of the spte which can be done out of mmu-lock.
3358 * However, if access tracking is disabled we know that a non-present
3359 * page must be a genuine page fault where we have to create a new SPTE.
3360 * So, if access tracking is disabled, we return true only for write
3361 * accesses to a present page.
3364 return shadow_acc_track_mask != 0 ||
3365 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3366 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3370 * Returns true if the SPTE was fixed successfully. Otherwise,
3371 * someone else modified the SPTE from its original value.
3374 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3375 u64 *sptep, u64 old_spte, u64 new_spte)
3379 WARN_ON(!sp->role.direct);
3382 * Theoretically we could also set dirty bit (and flush TLB) here in
3383 * order to eliminate unnecessary PML logging. See comments in
3384 * set_spte. But fast_page_fault is very unlikely to happen with PML
3385 * enabled, so we do not do this. This might result in the same GPA
3386 * to be logged in PML buffer again when the write really happens, and
3387 * eventually to be called by mark_page_dirty twice. But it's also no
3388 * harm. This also avoids the TLB flush needed after setting dirty bit
3389 * so non-PML cases won't be impacted.
3391 * Compare with set_spte where instead shadow_dirty_mask is set.
3393 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3396 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3398 * The gfn of direct spte is stable since it is
3399 * calculated by sp->gfn.
3401 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3402 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3408 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3410 if (fault_err_code & PFERR_FETCH_MASK)
3411 return is_executable_pte(spte);
3413 if (fault_err_code & PFERR_WRITE_MASK)
3414 return is_writable_pte(spte);
3416 /* Fault was on Read access */
3417 return spte & PT_PRESENT_MASK;
3422 * - true: let the vcpu to access on the same address again.
3423 * - false: let the real page fault path to fix it.
3425 static bool fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, int level,
3428 struct kvm_shadow_walk_iterator iterator;
3429 struct kvm_mmu_page *sp;
3430 bool fault_handled = false;
3432 uint retry_count = 0;
3434 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3437 if (!page_fault_can_be_fast(error_code))
3440 walk_shadow_page_lockless_begin(vcpu);
3445 for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
3446 if (!is_shadow_present_pte(spte) ||
3447 iterator.level < level)
3450 sp = page_header(__pa(iterator.sptep));
3451 if (!is_last_spte(spte, sp->role.level))
3455 * Check whether the memory access that caused the fault would
3456 * still cause it if it were to be performed right now. If not,
3457 * then this is a spurious fault caused by TLB lazily flushed,
3458 * or some other CPU has already fixed the PTE after the
3459 * current CPU took the fault.
3461 * Need not check the access of upper level table entries since
3462 * they are always ACC_ALL.
3464 if (is_access_allowed(error_code, spte)) {
3465 fault_handled = true;
3471 if (is_access_track_spte(spte))
3472 new_spte = restore_acc_track_spte(new_spte);
3475 * Currently, to simplify the code, write-protection can
3476 * be removed in the fast path only if the SPTE was
3477 * write-protected for dirty-logging or access tracking.
3479 if ((error_code & PFERR_WRITE_MASK) &&
3480 spte_can_locklessly_be_made_writable(spte))
3482 new_spte |= PT_WRITABLE_MASK;
3485 * Do not fix write-permission on the large spte. Since
3486 * we only dirty the first page into the dirty-bitmap in
3487 * fast_pf_fix_direct_spte(), other pages are missed
3488 * if its slot has dirty logging enabled.
3490 * Instead, we let the slow page fault path create a
3491 * normal spte to fix the access.
3493 * See the comments in kvm_arch_commit_memory_region().
3495 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3499 /* Verify that the fault can be handled in the fast path */
3500 if (new_spte == spte ||
3501 !is_access_allowed(error_code, new_spte))
3505 * Currently, fast page fault only works for direct mapping
3506 * since the gfn is not stable for indirect shadow page. See
3507 * Documentation/virtual/kvm/locking.txt to get more detail.
3509 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3510 iterator.sptep, spte,
3515 if (++retry_count > 4) {
3516 printk_once(KERN_WARNING
3517 "kvm: Fast #PF retrying more than 4 times.\n");
3523 trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
3524 spte, fault_handled);
3525 walk_shadow_page_lockless_end(vcpu);
3527 return fault_handled;
3530 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3531 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
3533 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3535 static int nonpaging_map(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
3536 gfn_t gfn, bool prefault)
3540 bool force_pt_level;
3542 unsigned long mmu_seq;
3543 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3544 bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
3545 is_nx_huge_page_enabled();
3547 force_pt_level = lpage_disallowed;
3548 level = mapping_level(vcpu, gfn, &force_pt_level);
3549 if (likely(!force_pt_level)) {
3551 * This path builds a PAE pagetable - so we can map
3552 * 2mb pages at maximum. Therefore check if the level
3553 * is larger than that.
3555 if (level > PT_DIRECTORY_LEVEL)
3556 level = PT_DIRECTORY_LEVEL;
3558 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3561 if (fast_page_fault(vcpu, gpa, level, error_code))
3562 return RET_PF_RETRY;
3564 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3567 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
3568 return RET_PF_RETRY;
3570 if (handle_abnormal_pfn(vcpu, gpa, gfn, pfn, ACC_ALL, &r))
3574 spin_lock(&vcpu->kvm->mmu_lock);
3575 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3577 if (make_mmu_pages_available(vcpu) < 0)
3579 if (likely(!force_pt_level))
3580 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3581 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
3584 spin_unlock(&vcpu->kvm->mmu_lock);
3585 kvm_release_pfn_clean(pfn);
3589 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3590 struct list_head *invalid_list)
3592 struct kvm_mmu_page *sp;
3594 if (!VALID_PAGE(*root_hpa))
3597 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3599 if (!sp->root_count && sp->role.invalid)
3600 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3602 *root_hpa = INVALID_PAGE;
3605 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3606 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, ulong roots_to_free)
3609 LIST_HEAD(invalid_list);
3610 struct kvm_mmu *mmu = &vcpu->arch.mmu;
3611 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3613 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3615 /* Before acquiring the MMU lock, see if we need to do any real work. */
3616 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3617 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3618 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3619 VALID_PAGE(mmu->prev_roots[i].hpa))
3622 if (i == KVM_MMU_NUM_PREV_ROOTS)
3626 spin_lock(&vcpu->kvm->mmu_lock);
3628 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3629 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3630 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3633 if (free_active_root) {
3634 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3635 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3636 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3639 for (i = 0; i < 4; ++i)
3640 if (mmu->pae_root[i] != 0)
3641 mmu_free_root_page(vcpu->kvm,
3644 mmu->root_hpa = INVALID_PAGE;
3648 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3649 spin_unlock(&vcpu->kvm->mmu_lock);
3651 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3653 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3657 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3658 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3665 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3667 struct kvm_mmu_page *sp;
3670 if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL) {
3671 spin_lock(&vcpu->kvm->mmu_lock);
3672 if(make_mmu_pages_available(vcpu) < 0) {
3673 spin_unlock(&vcpu->kvm->mmu_lock);
3676 sp = kvm_mmu_get_page(vcpu, 0, 0,
3677 vcpu->arch.mmu.shadow_root_level, 1, ACC_ALL);
3679 spin_unlock(&vcpu->kvm->mmu_lock);
3680 vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3681 } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3682 for (i = 0; i < 4; ++i) {
3683 hpa_t root = vcpu->arch.mmu.pae_root[i];
3685 MMU_WARN_ON(VALID_PAGE(root));
3686 spin_lock(&vcpu->kvm->mmu_lock);
3687 if (make_mmu_pages_available(vcpu) < 0) {
3688 spin_unlock(&vcpu->kvm->mmu_lock);
3691 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3692 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3693 root = __pa(sp->spt);
3695 spin_unlock(&vcpu->kvm->mmu_lock);
3696 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
3698 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3705 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3707 struct kvm_mmu_page *sp;
3712 root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
3714 if (mmu_check_root(vcpu, root_gfn))
3718 * Do we shadow a long mode page table? If so we need to
3719 * write-protect the guests page table root.
3721 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3722 hpa_t root = vcpu->arch.mmu.root_hpa;
3724 MMU_WARN_ON(VALID_PAGE(root));
3726 spin_lock(&vcpu->kvm->mmu_lock);
3727 if (make_mmu_pages_available(vcpu) < 0) {
3728 spin_unlock(&vcpu->kvm->mmu_lock);
3731 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3732 vcpu->arch.mmu.shadow_root_level, 0, ACC_ALL);
3733 root = __pa(sp->spt);
3735 spin_unlock(&vcpu->kvm->mmu_lock);
3736 vcpu->arch.mmu.root_hpa = root;
3741 * We shadow a 32 bit page table. This may be a legacy 2-level
3742 * or a PAE 3-level page table. In either case we need to be aware that
3743 * the shadow page table may be a PAE or a long mode page table.
3745 pm_mask = PT_PRESENT_MASK;
3746 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL)
3747 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3749 for (i = 0; i < 4; ++i) {
3750 hpa_t root = vcpu->arch.mmu.pae_root[i];
3752 MMU_WARN_ON(VALID_PAGE(root));
3753 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
3754 pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
3755 if (!(pdptr & PT_PRESENT_MASK)) {
3756 vcpu->arch.mmu.pae_root[i] = 0;
3759 root_gfn = pdptr >> PAGE_SHIFT;
3760 if (mmu_check_root(vcpu, root_gfn))
3763 spin_lock(&vcpu->kvm->mmu_lock);
3764 if (make_mmu_pages_available(vcpu) < 0) {
3765 spin_unlock(&vcpu->kvm->mmu_lock);
3768 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3770 root = __pa(sp->spt);
3772 spin_unlock(&vcpu->kvm->mmu_lock);
3774 vcpu->arch.mmu.pae_root[i] = root | pm_mask;
3776 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3779 * If we shadow a 32 bit page table with a long mode page
3780 * table we enter this path.
3782 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL) {
3783 if (vcpu->arch.mmu.lm_root == NULL) {
3785 * The additional page necessary for this is only
3786 * allocated on demand.
3791 lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3792 if (lm_root == NULL)
3795 lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3797 vcpu->arch.mmu.lm_root = lm_root;
3800 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3806 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3808 if (vcpu->arch.mmu.direct_map)
3809 return mmu_alloc_direct_roots(vcpu);
3811 return mmu_alloc_shadow_roots(vcpu);
3814 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3817 struct kvm_mmu_page *sp;
3819 if (vcpu->arch.mmu.direct_map)
3822 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3825 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3827 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3828 hpa_t root = vcpu->arch.mmu.root_hpa;
3830 sp = page_header(root);
3833 * Even if another CPU was marking the SP as unsync-ed
3834 * simultaneously, any guest page table changes are not
3835 * guaranteed to be visible anyway until this VCPU issues a TLB
3836 * flush strictly after those changes are made. We only need to
3837 * ensure that the other CPU sets these flags before any actual
3838 * changes to the page tables are made. The comments in
3839 * mmu_need_write_protect() describe what could go wrong if this
3840 * requirement isn't satisfied.
3842 if (!smp_load_acquire(&sp->unsync) &&
3843 !smp_load_acquire(&sp->unsync_children))
3846 spin_lock(&vcpu->kvm->mmu_lock);
3847 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3849 mmu_sync_children(vcpu, sp);
3851 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3852 spin_unlock(&vcpu->kvm->mmu_lock);
3856 spin_lock(&vcpu->kvm->mmu_lock);
3857 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3859 for (i = 0; i < 4; ++i) {
3860 hpa_t root = vcpu->arch.mmu.pae_root[i];
3862 if (root && VALID_PAGE(root)) {
3863 root &= PT64_BASE_ADDR_MASK;
3864 sp = page_header(root);
3865 mmu_sync_children(vcpu, sp);
3869 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3870 spin_unlock(&vcpu->kvm->mmu_lock);
3872 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3874 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3875 u32 access, struct x86_exception *exception)
3878 exception->error_code = 0;
3882 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3884 struct x86_exception *exception)
3887 exception->error_code = 0;
3888 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3892 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3894 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3896 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3897 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3900 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3902 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3905 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3907 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3910 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3913 * A nested guest cannot use the MMIO cache if it is using nested
3914 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3916 if (mmu_is_nested(vcpu))
3920 return vcpu_match_mmio_gpa(vcpu, addr);
3922 return vcpu_match_mmio_gva(vcpu, addr);
3925 /* return true if reserved bit is detected on spte. */
3927 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3929 struct kvm_shadow_walk_iterator iterator;
3930 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3932 bool reserved = false;
3934 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3937 walk_shadow_page_lockless_begin(vcpu);
3939 for (shadow_walk_init(&iterator, vcpu, addr),
3940 leaf = root = iterator.level;
3941 shadow_walk_okay(&iterator);
3942 __shadow_walk_next(&iterator, spte)) {
3943 spte = mmu_spte_get_lockless(iterator.sptep);
3945 sptes[leaf - 1] = spte;
3948 if (!is_shadow_present_pte(spte))
3951 reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
3955 walk_shadow_page_lockless_end(vcpu);
3958 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3960 while (root > leaf) {
3961 pr_err("------ spte 0x%llx level %d.\n",
3962 sptes[root - 1], root);
3971 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3976 if (mmio_info_in_cache(vcpu, addr, direct))
3977 return RET_PF_EMULATE;
3979 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3980 if (WARN_ON(reserved))
3983 if (is_mmio_spte(spte)) {
3984 gfn_t gfn = get_mmio_spte_gfn(spte);
3985 unsigned access = get_mmio_spte_access(spte);
3987 if (!check_mmio_spte(vcpu, spte))
3988 return RET_PF_INVALID;
3993 trace_handle_mmio_page_fault(addr, gfn, access);
3994 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3995 return RET_PF_EMULATE;
3999 * If the page table is zapped by other cpus, let CPU fault again on
4002 return RET_PF_RETRY;
4005 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4006 u32 error_code, gfn_t gfn)
4008 if (unlikely(error_code & PFERR_RSVD_MASK))
4011 if (!(error_code & PFERR_PRESENT_MASK) ||
4012 !(error_code & PFERR_WRITE_MASK))
4016 * guest is writing the page which is write tracked which can
4017 * not be fixed by page fault handler.
4019 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4025 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4027 struct kvm_shadow_walk_iterator iterator;
4030 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4033 walk_shadow_page_lockless_begin(vcpu);
4034 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4035 clear_sp_write_flooding_count(iterator.sptep);
4036 if (!is_shadow_present_pte(spte))
4039 walk_shadow_page_lockless_end(vcpu);
4042 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
4043 u32 error_code, bool prefault)
4045 gfn_t gfn = gpa >> PAGE_SHIFT;
4048 /* Note, paging is disabled, ergo gva == gpa. */
4049 pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
4051 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4052 return RET_PF_EMULATE;
4054 r = mmu_topup_memory_caches(vcpu);
4058 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
4061 return nonpaging_map(vcpu, gpa & PAGE_MASK,
4062 error_code, gfn, prefault);
4065 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4068 struct kvm_arch_async_pf arch;
4070 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4072 arch.direct_map = vcpu->arch.mmu.direct_map;
4073 arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
4075 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4076 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4079 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
4081 if (unlikely(!lapic_in_kernel(vcpu) ||
4082 kvm_event_needs_reinjection(vcpu) ||
4083 vcpu->arch.exception.pending))
4086 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
4089 return kvm_x86_ops->interrupt_allowed(vcpu);
4092 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4093 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
4096 struct kvm_memory_slot *slot;
4100 * Don't expose private memslots to L2.
4102 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4103 *pfn = KVM_PFN_NOSLOT;
4107 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4109 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4111 return false; /* *pfn has correct page already */
4113 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4114 trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
4115 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4116 trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
4117 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4119 } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
4123 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4127 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4128 u64 fault_address, char *insn, int insn_len)
4132 #ifndef CONFIG_X86_64
4133 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4134 if (WARN_ON_ONCE(fault_address >> 32))
4138 vcpu->arch.l1tf_flush_l1d = true;
4139 switch (vcpu->arch.apf.host_apf_reason) {
4141 trace_kvm_page_fault(fault_address, error_code);
4143 if (kvm_event_needs_reinjection(vcpu))
4144 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4145 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4148 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4149 vcpu->arch.apf.host_apf_reason = 0;
4150 local_irq_disable();
4151 kvm_async_pf_task_wait(fault_address, 0);
4154 case KVM_PV_REASON_PAGE_READY:
4155 vcpu->arch.apf.host_apf_reason = 0;
4156 local_irq_disable();
4157 kvm_async_pf_task_wake(fault_address);
4163 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4166 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4168 int page_num = KVM_PAGES_PER_HPAGE(level);
4170 gfn &= ~(page_num - 1);
4172 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4175 static int tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4181 bool force_pt_level;
4182 gfn_t gfn = gpa >> PAGE_SHIFT;
4183 unsigned long mmu_seq;
4184 int write = error_code & PFERR_WRITE_MASK;
4186 bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
4187 is_nx_huge_page_enabled();
4189 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
4191 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4192 return RET_PF_EMULATE;
4194 r = mmu_topup_memory_caches(vcpu);
4200 !check_hugepage_cache_consistency(vcpu, gfn, PT_DIRECTORY_LEVEL);
4201 level = mapping_level(vcpu, gfn, &force_pt_level);
4202 if (likely(!force_pt_level)) {
4203 if (level > PT_DIRECTORY_LEVEL &&
4204 !check_hugepage_cache_consistency(vcpu, gfn, level))
4205 level = PT_DIRECTORY_LEVEL;
4206 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4209 if (fast_page_fault(vcpu, gpa, level, error_code))
4210 return RET_PF_RETRY;
4212 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4215 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4216 return RET_PF_RETRY;
4218 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4222 spin_lock(&vcpu->kvm->mmu_lock);
4223 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4225 if (make_mmu_pages_available(vcpu) < 0)
4227 if (likely(!force_pt_level))
4228 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4229 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
4230 prefault, lpage_disallowed);
4232 spin_unlock(&vcpu->kvm->mmu_lock);
4233 kvm_release_pfn_clean(pfn);
4237 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4238 struct kvm_mmu *context)
4240 context->page_fault = nonpaging_page_fault;
4241 context->gva_to_gpa = nonpaging_gva_to_gpa;
4242 context->sync_page = nonpaging_sync_page;
4243 context->invlpg = nonpaging_invlpg;
4244 context->update_pte = nonpaging_update_pte;
4245 context->root_level = 0;
4246 context->shadow_root_level = PT32E_ROOT_LEVEL;
4247 context->direct_map = true;
4248 context->nx = false;
4252 * Find out if a previously cached root matching the new CR3/role is available.
4253 * The current root is also inserted into the cache.
4254 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4256 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4257 * false is returned. This root should now be freed by the caller.
4259 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4260 union kvm_mmu_page_role new_role)
4263 struct kvm_mmu_root_info root;
4264 struct kvm_mmu *mmu = &vcpu->arch.mmu;
4266 root.cr3 = mmu->get_cr3(vcpu);
4267 root.hpa = mmu->root_hpa;
4269 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4270 swap(root, mmu->prev_roots[i]);
4272 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4273 page_header(root.hpa) != NULL &&
4274 new_role.word == page_header(root.hpa)->role.word)
4278 mmu->root_hpa = root.hpa;
4280 return i < KVM_MMU_NUM_PREV_ROOTS;
4283 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4284 union kvm_mmu_page_role new_role,
4285 bool skip_tlb_flush)
4287 struct kvm_mmu *mmu = &vcpu->arch.mmu;
4290 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4291 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4292 * later if necessary.
4294 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4295 mmu->root_level >= PT64_ROOT_4LEVEL) {
4296 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4299 if (cached_root_available(vcpu, new_cr3, new_role)) {
4301 * It is possible that the cached previous root page is
4302 * obsolete because of a change in the MMU
4303 * generation number. However, that is accompanied by
4304 * KVM_REQ_MMU_RELOAD, which will free the root that we
4305 * have set here and allocate a new one.
4308 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4309 if (!skip_tlb_flush) {
4310 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4311 kvm_x86_ops->tlb_flush(vcpu, true);
4315 * The last MMIO access's GVA and GPA are cached in the
4316 * VCPU. When switching to a new CR3, that GVA->GPA
4317 * mapping may no longer be valid. So clear any cached
4318 * MMIO info even when we don't need to sync the shadow
4321 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4323 __clear_sp_write_flooding_count(
4324 page_header(mmu->root_hpa));
4333 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4334 union kvm_mmu_page_role new_role,
4335 bool skip_tlb_flush)
4337 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4338 kvm_mmu_free_roots(vcpu, KVM_MMU_ROOT_CURRENT);
4341 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4343 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4346 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4348 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4350 return kvm_read_cr3(vcpu);
4353 static void inject_page_fault(struct kvm_vcpu *vcpu,
4354 struct x86_exception *fault)
4356 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
4359 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4360 unsigned access, int *nr_present)
4362 if (unlikely(is_mmio_spte(*sptep))) {
4363 if (gfn != get_mmio_spte_gfn(*sptep)) {
4364 mmu_spte_clear_no_track(sptep);
4369 mark_mmio_spte(vcpu, sptep, gfn, access);
4376 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4377 unsigned level, unsigned gpte)
4380 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4381 * If it is clear, there are no large pages at this level, so clear
4382 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4384 gpte &= level - mmu->last_nonleaf_level;
4387 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4388 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4389 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4391 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4393 return gpte & PT_PAGE_SIZE_MASK;
4396 #define PTTYPE_EPT 18 /* arbitrary */
4397 #define PTTYPE PTTYPE_EPT
4398 #include "paging_tmpl.h"
4402 #include "paging_tmpl.h"
4406 #include "paging_tmpl.h"
4410 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4411 struct rsvd_bits_validate *rsvd_check,
4412 int maxphyaddr, int level, bool nx, bool gbpages,
4415 u64 exb_bit_rsvd = 0;
4416 u64 gbpages_bit_rsvd = 0;
4417 u64 nonleaf_bit8_rsvd = 0;
4419 rsvd_check->bad_mt_xwr = 0;
4422 exb_bit_rsvd = rsvd_bits(63, 63);
4424 gbpages_bit_rsvd = rsvd_bits(7, 7);
4427 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4428 * leaf entries) on AMD CPUs only.
4431 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4434 case PT32_ROOT_LEVEL:
4435 /* no rsvd bits for 2 level 4K page table entries */
4436 rsvd_check->rsvd_bits_mask[0][1] = 0;
4437 rsvd_check->rsvd_bits_mask[0][0] = 0;
4438 rsvd_check->rsvd_bits_mask[1][0] =
4439 rsvd_check->rsvd_bits_mask[0][0];
4442 rsvd_check->rsvd_bits_mask[1][1] = 0;
4446 if (is_cpuid_PSE36())
4447 /* 36bits PSE 4MB page */
4448 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4450 /* 32 bits PSE 4MB page */
4451 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4453 case PT32E_ROOT_LEVEL:
4454 rsvd_check->rsvd_bits_mask[0][2] =
4455 rsvd_bits(maxphyaddr, 63) |
4456 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4457 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4458 rsvd_bits(maxphyaddr, 62); /* PDE */
4459 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4460 rsvd_bits(maxphyaddr, 62); /* PTE */
4461 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4462 rsvd_bits(maxphyaddr, 62) |
4463 rsvd_bits(13, 20); /* large page */
4464 rsvd_check->rsvd_bits_mask[1][0] =
4465 rsvd_check->rsvd_bits_mask[0][0];
4467 case PT64_ROOT_5LEVEL:
4468 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4469 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4470 rsvd_bits(maxphyaddr, 51);
4471 rsvd_check->rsvd_bits_mask[1][4] =
4472 rsvd_check->rsvd_bits_mask[0][4];
4473 case PT64_ROOT_4LEVEL:
4474 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4475 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4476 rsvd_bits(maxphyaddr, 51);
4477 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4479 rsvd_bits(maxphyaddr, 51);
4480 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4481 rsvd_bits(maxphyaddr, 51);
4482 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4483 rsvd_bits(maxphyaddr, 51);
4484 rsvd_check->rsvd_bits_mask[1][3] =
4485 rsvd_check->rsvd_bits_mask[0][3];
4486 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4487 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4489 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4490 rsvd_bits(maxphyaddr, 51) |
4491 rsvd_bits(13, 20); /* large page */
4492 rsvd_check->rsvd_bits_mask[1][0] =
4493 rsvd_check->rsvd_bits_mask[0][0];
4498 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4499 struct kvm_mmu *context)
4501 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4502 cpuid_maxphyaddr(vcpu), context->root_level,
4504 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4505 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4509 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4510 int maxphyaddr, bool execonly)
4514 rsvd_check->rsvd_bits_mask[0][4] =
4515 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4516 rsvd_check->rsvd_bits_mask[0][3] =
4517 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4518 rsvd_check->rsvd_bits_mask[0][2] =
4519 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4520 rsvd_check->rsvd_bits_mask[0][1] =
4521 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4522 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4525 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4526 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4527 rsvd_check->rsvd_bits_mask[1][2] =
4528 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4529 rsvd_check->rsvd_bits_mask[1][1] =
4530 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4531 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4533 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4534 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4535 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4536 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4537 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4539 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4540 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4542 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4545 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4546 struct kvm_mmu *context, bool execonly)
4548 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4549 cpuid_maxphyaddr(vcpu), execonly);
4553 * the page table on host is the shadow page table for the page
4554 * table in guest or amd nested guest, its mmu features completely
4555 * follow the features in guest.
4558 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4561 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
4562 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
4563 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
4564 * The iTLB multi-hit workaround can be toggled at any time, so assume
4565 * NX can be used by any non-nested shadow MMU to avoid having to reset
4566 * MMU contexts. Note, KVM forces EFER.NX=1 when TDP is disabled.
4568 bool uses_nx = context->nx || !tdp_enabled ||
4569 context->base_role.smep_andnot_wp;
4570 struct rsvd_bits_validate *shadow_zero_check;
4574 * Passing "true" to the last argument is okay; it adds a check
4575 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4577 shadow_zero_check = &context->shadow_zero_check;
4578 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4580 context->shadow_root_level, uses_nx,
4581 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4582 is_pse(vcpu), true);
4584 if (!shadow_me_mask)
4587 for (i = context->shadow_root_level; --i >= 0;) {
4588 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4589 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4593 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4595 static inline bool boot_cpu_is_amd(void)
4597 WARN_ON_ONCE(!tdp_enabled);
4598 return shadow_x_mask == 0;
4602 * the direct page table on host, use as much mmu features as
4603 * possible, however, kvm currently does not do execution-protection.
4606 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4607 struct kvm_mmu *context)
4609 struct rsvd_bits_validate *shadow_zero_check;
4612 shadow_zero_check = &context->shadow_zero_check;
4614 if (boot_cpu_is_amd())
4615 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4617 context->shadow_root_level, false,
4618 boot_cpu_has(X86_FEATURE_GBPAGES),
4621 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4625 if (!shadow_me_mask)
4628 for (i = context->shadow_root_level; --i >= 0;) {
4629 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4630 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4635 * as the comments in reset_shadow_zero_bits_mask() except it
4636 * is the shadow page table for intel nested guest.
4639 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4640 struct kvm_mmu *context, bool execonly)
4642 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4643 shadow_phys_bits, execonly);
4646 #define BYTE_MASK(access) \
4647 ((1 & (access) ? 2 : 0) | \
4648 (2 & (access) ? 4 : 0) | \
4649 (3 & (access) ? 8 : 0) | \
4650 (4 & (access) ? 16 : 0) | \
4651 (5 & (access) ? 32 : 0) | \
4652 (6 & (access) ? 64 : 0) | \
4653 (7 & (access) ? 128 : 0))
4656 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4657 struct kvm_mmu *mmu, bool ept)
4661 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4662 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4663 const u8 u = BYTE_MASK(ACC_USER_MASK);
4665 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4666 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4667 bool cr0_wp = is_write_protection(vcpu);
4669 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4670 unsigned pfec = byte << 1;
4673 * Each "*f" variable has a 1 bit for each UWX value
4674 * that causes a fault with the given PFEC.
4677 /* Faults from writes to non-writable pages */
4678 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4679 /* Faults from user mode accesses to supervisor pages */
4680 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4681 /* Faults from fetches of non-executable pages*/
4682 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4683 /* Faults from kernel mode fetches of user pages */
4685 /* Faults from kernel mode accesses of user pages */
4689 /* Faults from kernel mode accesses to user pages */
4690 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4692 /* Not really needed: !nx will cause pte.nx to fault */
4696 /* Allow supervisor writes if !cr0.wp */
4698 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4700 /* Disallow supervisor fetches of user code if cr4.smep */
4702 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4705 * SMAP:kernel-mode data accesses from user-mode
4706 * mappings should fault. A fault is considered
4707 * as a SMAP violation if all of the following
4708 * conditions are ture:
4709 * - X86_CR4_SMAP is set in CR4
4710 * - A user page is accessed
4711 * - The access is not a fetch
4712 * - Page fault in kernel mode
4713 * - if CPL = 3 or X86_EFLAGS_AC is clear
4715 * Here, we cover the first three conditions.
4716 * The fourth is computed dynamically in permission_fault();
4717 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4718 * *not* subject to SMAP restrictions.
4721 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4724 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4729 * PKU is an additional mechanism by which the paging controls access to
4730 * user-mode addresses based on the value in the PKRU register. Protection
4731 * key violations are reported through a bit in the page fault error code.
4732 * Unlike other bits of the error code, the PK bit is not known at the
4733 * call site of e.g. gva_to_gpa; it must be computed directly in
4734 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4735 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4737 * In particular the following conditions come from the error code, the
4738 * page tables and the machine state:
4739 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4740 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4741 * - PK is always zero if U=0 in the page tables
4742 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4744 * The PKRU bitmask caches the result of these four conditions. The error
4745 * code (minus the P bit) and the page table's U bit form an index into the
4746 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4747 * with the two bits of the PKRU register corresponding to the protection key.
4748 * For the first three conditions above the bits will be 00, thus masking
4749 * away both AD and WD. For all reads or if the last condition holds, WD
4750 * only will be masked away.
4752 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4763 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4764 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4769 wp = is_write_protection(vcpu);
4771 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4772 unsigned pfec, pkey_bits;
4773 bool check_pkey, check_write, ff, uf, wf, pte_user;
4776 ff = pfec & PFERR_FETCH_MASK;
4777 uf = pfec & PFERR_USER_MASK;
4778 wf = pfec & PFERR_WRITE_MASK;
4780 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4781 pte_user = pfec & PFERR_RSVD_MASK;
4784 * Only need to check the access which is not an
4785 * instruction fetch and is to a user page.
4787 check_pkey = (!ff && pte_user);
4789 * write access is controlled by PKRU if it is a
4790 * user access or CR0.WP = 1.
4792 check_write = check_pkey && wf && (uf || wp);
4794 /* PKRU.AD stops both read and write access. */
4795 pkey_bits = !!check_pkey;
4796 /* PKRU.WD stops write access. */
4797 pkey_bits |= (!!check_write) << 1;
4799 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4803 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4805 unsigned root_level = mmu->root_level;
4807 mmu->last_nonleaf_level = root_level;
4808 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4809 mmu->last_nonleaf_level++;
4812 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4813 struct kvm_mmu *context,
4816 context->nx = is_nx(vcpu);
4817 context->root_level = level;
4819 reset_rsvds_bits_mask(vcpu, context);
4820 update_permission_bitmask(vcpu, context, false);
4821 update_pkru_bitmask(vcpu, context, false);
4822 update_last_nonleaf_level(vcpu, context);
4824 MMU_WARN_ON(!is_pae(vcpu));
4825 context->page_fault = paging64_page_fault;
4826 context->gva_to_gpa = paging64_gva_to_gpa;
4827 context->sync_page = paging64_sync_page;
4828 context->invlpg = paging64_invlpg;
4829 context->update_pte = paging64_update_pte;
4830 context->shadow_root_level = level;
4831 context->direct_map = false;
4834 static void paging64_init_context(struct kvm_vcpu *vcpu,
4835 struct kvm_mmu *context)
4837 int root_level = is_la57_mode(vcpu) ?
4838 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4840 paging64_init_context_common(vcpu, context, root_level);
4843 static void paging32_init_context(struct kvm_vcpu *vcpu,
4844 struct kvm_mmu *context)
4846 context->nx = false;
4847 context->root_level = PT32_ROOT_LEVEL;
4849 reset_rsvds_bits_mask(vcpu, context);
4850 update_permission_bitmask(vcpu, context, false);
4851 update_pkru_bitmask(vcpu, context, false);
4852 update_last_nonleaf_level(vcpu, context);
4854 context->page_fault = paging32_page_fault;
4855 context->gva_to_gpa = paging32_gva_to_gpa;
4856 context->sync_page = paging32_sync_page;
4857 context->invlpg = paging32_invlpg;
4858 context->update_pte = paging32_update_pte;
4859 context->shadow_root_level = PT32E_ROOT_LEVEL;
4860 context->direct_map = false;
4863 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4864 struct kvm_mmu *context)
4866 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4869 static union kvm_mmu_page_role
4870 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu)
4872 union kvm_mmu_page_role role = {0};
4874 role.guest_mode = is_guest_mode(vcpu);
4875 role.smm = is_smm(vcpu);
4876 role.ad_disabled = (shadow_accessed_mask == 0);
4877 role.level = kvm_x86_ops->get_tdp_level(vcpu);
4879 role.access = ACC_ALL;
4884 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4886 struct kvm_mmu *context = &vcpu->arch.mmu;
4888 context->base_role.word = mmu_base_role_mask.word &
4889 kvm_calc_tdp_mmu_root_page_role(vcpu).word;
4890 context->page_fault = tdp_page_fault;
4891 context->sync_page = nonpaging_sync_page;
4892 context->invlpg = nonpaging_invlpg;
4893 context->update_pte = nonpaging_update_pte;
4894 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4895 context->direct_map = true;
4896 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4897 context->get_cr3 = get_cr3;
4898 context->get_pdptr = kvm_pdptr_read;
4899 context->inject_page_fault = kvm_inject_page_fault;
4901 if (!is_paging(vcpu)) {
4902 context->nx = false;
4903 context->gva_to_gpa = nonpaging_gva_to_gpa;
4904 context->root_level = 0;
4905 } else if (is_long_mode(vcpu)) {
4906 context->nx = is_nx(vcpu);
4907 context->root_level = is_la57_mode(vcpu) ?
4908 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4909 reset_rsvds_bits_mask(vcpu, context);
4910 context->gva_to_gpa = paging64_gva_to_gpa;
4911 } else if (is_pae(vcpu)) {
4912 context->nx = is_nx(vcpu);
4913 context->root_level = PT32E_ROOT_LEVEL;
4914 reset_rsvds_bits_mask(vcpu, context);
4915 context->gva_to_gpa = paging64_gva_to_gpa;
4917 context->nx = false;
4918 context->root_level = PT32_ROOT_LEVEL;
4919 reset_rsvds_bits_mask(vcpu, context);
4920 context->gva_to_gpa = paging32_gva_to_gpa;
4923 update_permission_bitmask(vcpu, context, false);
4924 update_pkru_bitmask(vcpu, context, false);
4925 update_last_nonleaf_level(vcpu, context);
4926 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4929 static union kvm_mmu_page_role
4930 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu)
4932 union kvm_mmu_page_role role = {0};
4933 bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4934 bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4936 role.nxe = is_nx(vcpu);
4937 role.cr4_pae = !!is_pae(vcpu);
4938 role.cr0_wp = is_write_protection(vcpu);
4939 role.smep_andnot_wp = smep && !is_write_protection(vcpu);
4940 role.smap_andnot_wp = smap && !is_write_protection(vcpu);
4941 role.guest_mode = is_guest_mode(vcpu);
4942 role.smm = is_smm(vcpu);
4943 role.direct = !is_paging(vcpu);
4944 role.access = ACC_ALL;
4946 if (!is_long_mode(vcpu))
4947 role.level = PT32E_ROOT_LEVEL;
4948 else if (is_la57_mode(vcpu))
4949 role.level = PT64_ROOT_5LEVEL;
4951 role.level = PT64_ROOT_4LEVEL;
4956 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4958 struct kvm_mmu *context = &vcpu->arch.mmu;
4960 if (!is_paging(vcpu))
4961 nonpaging_init_context(vcpu, context);
4962 else if (is_long_mode(vcpu))
4963 paging64_init_context(vcpu, context);
4964 else if (is_pae(vcpu))
4965 paging32E_init_context(vcpu, context);
4967 paging32_init_context(vcpu, context);
4969 context->base_role.word = mmu_base_role_mask.word &
4970 kvm_calc_shadow_mmu_root_page_role(vcpu).word;
4971 reset_shadow_zero_bits_mask(vcpu, context);
4973 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4975 static union kvm_mmu_page_role
4976 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty)
4978 union kvm_mmu_page_role role = vcpu->arch.mmu.base_role;
4980 role.level = PT64_ROOT_4LEVEL;
4981 role.direct = false;
4982 role.ad_disabled = !accessed_dirty;
4983 role.guest_mode = true;
4984 role.access = ACC_ALL;
4989 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4990 bool accessed_dirty, gpa_t new_eptp)
4992 struct kvm_mmu *context = &vcpu->arch.mmu;
4993 union kvm_mmu_page_role root_page_role =
4994 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty);
4996 __kvm_mmu_new_cr3(vcpu, new_eptp, root_page_role, false);
4997 context->shadow_root_level = PT64_ROOT_4LEVEL;
5000 context->ept_ad = accessed_dirty;
5001 context->page_fault = ept_page_fault;
5002 context->gva_to_gpa = ept_gva_to_gpa;
5003 context->sync_page = ept_sync_page;
5004 context->invlpg = ept_invlpg;
5005 context->update_pte = ept_update_pte;
5006 context->root_level = PT64_ROOT_4LEVEL;
5007 context->direct_map = false;
5008 context->base_role.word = root_page_role.word & mmu_base_role_mask.word;
5009 update_permission_bitmask(vcpu, context, true);
5010 update_pkru_bitmask(vcpu, context, true);
5011 update_last_nonleaf_level(vcpu, context);
5012 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5013 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5015 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5017 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5019 struct kvm_mmu *context = &vcpu->arch.mmu;
5021 kvm_init_shadow_mmu(vcpu);
5022 context->set_cr3 = kvm_x86_ops->set_cr3;
5023 context->get_cr3 = get_cr3;
5024 context->get_pdptr = kvm_pdptr_read;
5025 context->inject_page_fault = kvm_inject_page_fault;
5028 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5030 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5032 g_context->get_cr3 = get_cr3;
5033 g_context->get_pdptr = kvm_pdptr_read;
5034 g_context->inject_page_fault = kvm_inject_page_fault;
5037 * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
5038 * L1's nested page tables (e.g. EPT12). The nested translation
5039 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5040 * L2's page tables as the first level of translation and L1's
5041 * nested page tables as the second level of translation. Basically
5042 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5044 if (!is_paging(vcpu)) {
5045 g_context->nx = false;
5046 g_context->root_level = 0;
5047 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5048 } else if (is_long_mode(vcpu)) {
5049 g_context->nx = is_nx(vcpu);
5050 g_context->root_level = is_la57_mode(vcpu) ?
5051 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5052 reset_rsvds_bits_mask(vcpu, g_context);
5053 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5054 } else if (is_pae(vcpu)) {
5055 g_context->nx = is_nx(vcpu);
5056 g_context->root_level = PT32E_ROOT_LEVEL;
5057 reset_rsvds_bits_mask(vcpu, g_context);
5058 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5060 g_context->nx = false;
5061 g_context->root_level = PT32_ROOT_LEVEL;
5062 reset_rsvds_bits_mask(vcpu, g_context);
5063 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5066 update_permission_bitmask(vcpu, g_context, false);
5067 update_pkru_bitmask(vcpu, g_context, false);
5068 update_last_nonleaf_level(vcpu, g_context);
5071 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5076 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5078 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5079 vcpu->arch.mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5082 if (mmu_is_nested(vcpu))
5083 init_kvm_nested_mmu(vcpu);
5084 else if (tdp_enabled)
5085 init_kvm_tdp_mmu(vcpu);
5087 init_kvm_softmmu(vcpu);
5089 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5091 static union kvm_mmu_page_role
5092 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5095 return kvm_calc_tdp_mmu_root_page_role(vcpu);
5097 return kvm_calc_shadow_mmu_root_page_role(vcpu);
5100 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5102 kvm_mmu_unload(vcpu);
5103 kvm_init_mmu(vcpu, true);
5105 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5107 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5111 r = mmu_topup_memory_caches(vcpu);
5114 r = mmu_alloc_roots(vcpu);
5115 kvm_mmu_sync_roots(vcpu);
5118 kvm_mmu_load_cr3(vcpu);
5119 kvm_x86_ops->tlb_flush(vcpu, true);
5123 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5125 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5127 kvm_mmu_free_roots(vcpu, KVM_MMU_ROOTS_ALL);
5128 WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
5130 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5132 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5133 struct kvm_mmu_page *sp, u64 *spte,
5136 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5137 ++vcpu->kvm->stat.mmu_pde_zapped;
5141 ++vcpu->kvm->stat.mmu_pte_updated;
5142 vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
5145 static bool need_remote_flush(u64 old, u64 new)
5147 if (!is_shadow_present_pte(old))
5149 if (!is_shadow_present_pte(new))
5151 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5153 old ^= shadow_nx_mask;
5154 new ^= shadow_nx_mask;
5155 return (old & ~new & PT64_PERM_MASK) != 0;
5158 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5165 * Assume that the pte write on a page table of the same type
5166 * as the current vcpu paging mode since we update the sptes only
5167 * when they have the same mode.
5169 if (is_pae(vcpu) && *bytes == 4) {
5170 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5175 if (*bytes == 4 || *bytes == 8) {
5176 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5185 * If we're seeing too many writes to a page, it may no longer be a page table,
5186 * or we may be forking, in which case it is better to unmap the page.
5188 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5191 * Skip write-flooding detected for the sp whose level is 1, because
5192 * it can become unsync, then the guest page is not write-protected.
5194 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5197 atomic_inc(&sp->write_flooding_count);
5198 return atomic_read(&sp->write_flooding_count) >= 3;
5202 * Misaligned accesses are too much trouble to fix up; also, they usually
5203 * indicate a page is not used as a page table.
5205 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5208 unsigned offset, pte_size, misaligned;
5210 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5211 gpa, bytes, sp->role.word);
5213 offset = offset_in_page(gpa);
5214 pte_size = sp->role.cr4_pae ? 8 : 4;
5217 * Sometimes, the OS only writes the last one bytes to update status
5218 * bits, for example, in linux, andb instruction is used in clear_bit().
5220 if (!(offset & (pte_size - 1)) && bytes == 1)
5223 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5224 misaligned |= bytes < 4;
5229 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5231 unsigned page_offset, quadrant;
5235 page_offset = offset_in_page(gpa);
5236 level = sp->role.level;
5238 if (!sp->role.cr4_pae) {
5239 page_offset <<= 1; /* 32->64 */
5241 * A 32-bit pde maps 4MB while the shadow pdes map
5242 * only 2MB. So we need to double the offset again
5243 * and zap two pdes instead of one.
5245 if (level == PT32_ROOT_LEVEL) {
5246 page_offset &= ~7; /* kill rounding error */
5250 quadrant = page_offset >> PAGE_SHIFT;
5251 page_offset &= ~PAGE_MASK;
5252 if (quadrant != sp->role.quadrant)
5256 spte = &sp->spt[page_offset / sizeof(*spte)];
5260 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5261 const u8 *new, int bytes,
5262 struct kvm_page_track_notifier_node *node)
5264 gfn_t gfn = gpa >> PAGE_SHIFT;
5265 struct kvm_mmu_page *sp;
5266 LIST_HEAD(invalid_list);
5267 u64 entry, gentry, *spte;
5269 bool remote_flush, local_flush;
5272 * If we don't have indirect shadow pages, it means no page is
5273 * write-protected, so we can exit simply.
5275 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5278 remote_flush = local_flush = false;
5280 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5283 * No need to care whether allocation memory is successful
5284 * or not since pte prefetch is skiped if it does not have
5285 * enough objects in the cache.
5287 mmu_topup_memory_caches(vcpu);
5289 spin_lock(&vcpu->kvm->mmu_lock);
5291 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5293 ++vcpu->kvm->stat.mmu_pte_write;
5294 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5296 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5297 if (detect_write_misaligned(sp, gpa, bytes) ||
5298 detect_write_flooding(sp)) {
5299 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5300 ++vcpu->kvm->stat.mmu_flooded;
5304 spte = get_written_sptes(sp, gpa, &npte);
5311 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5313 !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
5314 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5315 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5316 if (need_remote_flush(entry, *spte))
5317 remote_flush = true;
5321 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5322 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5323 spin_unlock(&vcpu->kvm->mmu_lock);
5326 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5331 if (vcpu->arch.mmu.direct_map)
5334 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5336 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5340 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5342 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5344 LIST_HEAD(invalid_list);
5346 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5349 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5350 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5353 ++vcpu->kvm->stat.mmu_recycled;
5355 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5357 if (!kvm_mmu_available_pages(vcpu->kvm))
5362 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5363 void *insn, int insn_len)
5365 int r, emulation_type = 0;
5366 enum emulation_result er;
5367 bool direct = vcpu->arch.mmu.direct_map;
5369 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5370 if (vcpu->arch.mmu.direct_map) {
5371 vcpu->arch.gpa_available = true;
5372 vcpu->arch.gpa_val = cr2_or_gpa;
5376 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5377 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5378 if (r == RET_PF_EMULATE)
5382 if (r == RET_PF_INVALID) {
5383 r = vcpu->arch.mmu.page_fault(vcpu, cr2_or_gpa,
5384 lower_32_bits(error_code),
5386 WARN_ON(r == RET_PF_INVALID);
5389 if (r == RET_PF_RETRY)
5395 * Before emulating the instruction, check if the error code
5396 * was due to a RO violation while translating the guest page.
5397 * This can occur when using nested virtualization with nested
5398 * paging in both guests. If true, we simply unprotect the page
5399 * and resume the guest.
5401 if (vcpu->arch.mmu.direct_map &&
5402 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5403 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5408 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5409 * optimistically try to just unprotect the page and let the processor
5410 * re-execute the instruction that caused the page fault. Do not allow
5411 * retrying MMIO emulation, as it's not only pointless but could also
5412 * cause us to enter an infinite loop because the processor will keep
5413 * faulting on the non-existent MMIO address. Retrying an instruction
5414 * from a nested guest is also pointless and dangerous as we are only
5415 * explicitly shadowing L1's page tables, i.e. unprotecting something
5416 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5418 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5419 emulation_type = EMULTYPE_ALLOW_RETRY;
5422 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5423 * This can happen if a guest gets a page-fault on data access but the HW
5424 * table walker is not able to read the instruction page (e.g instruction
5425 * page is not present in memory). In those cases we simply restart the
5428 if (unlikely(insn && !insn_len))
5431 er = x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn, insn_len);
5436 case EMULATE_USER_EXIT:
5437 ++vcpu->stat.mmio_exits;
5445 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5447 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5449 struct kvm_mmu *mmu = &vcpu->arch.mmu;
5452 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5453 if (is_noncanonical_address(gva, vcpu))
5456 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5459 * INVLPG is required to invalidate any global mappings for the VA,
5460 * irrespective of PCID. Since it would take us roughly similar amount
5461 * of work to determine whether any of the prev_root mappings of the VA
5462 * is marked global, or to just sync it blindly, so we might as well
5463 * just always sync it.
5465 * Mappings not reachable via the current cr3 or the prev_roots will be
5466 * synced when switching to that cr3, so nothing needs to be done here
5469 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5470 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5471 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5473 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5474 ++vcpu->stat.invlpg;
5476 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5478 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5480 struct kvm_mmu *mmu = &vcpu->arch.mmu;
5481 bool tlb_flush = false;
5484 if (pcid == kvm_get_active_pcid(vcpu)) {
5485 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5489 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5490 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5491 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5492 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5498 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5500 ++vcpu->stat.invlpg;
5503 * Mappings not reachable via the current cr3 or the prev_roots will be
5504 * synced when switching to that cr3, so nothing needs to be done here
5508 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5510 void kvm_enable_tdp(void)
5514 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5516 void kvm_disable_tdp(void)
5518 tdp_enabled = false;
5520 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5522 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5524 free_page((unsigned long)vcpu->arch.mmu.pae_root);
5525 free_page((unsigned long)vcpu->arch.mmu.lm_root);
5528 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5534 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5535 * while the PDP table is a per-vCPU construct that's allocated at MMU
5536 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5537 * x86_64. Therefore we need to allocate the PDP table in the first
5538 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5539 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5540 * skip allocating the PDP table.
5542 if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5546 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5547 * Therefore we need to allocate shadow page tables in the first
5548 * 4GB of memory, which happens to fit the DMA32 zone.
5550 page = alloc_page(GFP_KERNEL | __GFP_DMA32);
5554 vcpu->arch.mmu.pae_root = page_address(page);
5555 for (i = 0; i < 4; ++i)
5556 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
5561 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5565 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
5566 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5567 vcpu->arch.mmu.translate_gpa = translate_gpa;
5568 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5570 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5571 vcpu->arch.mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5573 return alloc_mmu_pages(vcpu);
5576 void kvm_mmu_setup(struct kvm_vcpu *vcpu)
5578 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
5581 * kvm_mmu_setup() is called only on vCPU initialization.
5582 * Therefore, no need to reset mmu roots as they are not yet
5585 kvm_init_mmu(vcpu, false);
5588 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5589 struct kvm_memory_slot *slot,
5590 struct kvm_page_track_notifier_node *node)
5592 kvm_mmu_invalidate_zap_all_pages(kvm);
5595 void kvm_mmu_init_vm(struct kvm *kvm)
5597 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5599 node->track_write = kvm_mmu_pte_write;
5600 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5601 kvm_page_track_register_notifier(kvm, node);
5604 void kvm_mmu_uninit_vm(struct kvm *kvm)
5606 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5608 kvm_page_track_unregister_notifier(kvm, node);
5611 /* The return value indicates if tlb flush on all vcpus is needed. */
5612 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5614 /* The caller should hold mmu-lock before calling this function. */
5615 static __always_inline bool
5616 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5617 slot_level_handler fn, int start_level, int end_level,
5618 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5620 struct slot_rmap_walk_iterator iterator;
5623 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5624 end_gfn, &iterator) {
5626 flush |= fn(kvm, iterator.rmap);
5628 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5629 if (flush && lock_flush_tlb) {
5630 kvm_flush_remote_tlbs(kvm);
5633 cond_resched_lock(&kvm->mmu_lock);
5637 if (flush && lock_flush_tlb) {
5638 kvm_flush_remote_tlbs(kvm);
5645 static __always_inline bool
5646 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5647 slot_level_handler fn, int start_level, int end_level,
5648 bool lock_flush_tlb)
5650 return slot_handle_level_range(kvm, memslot, fn, start_level,
5651 end_level, memslot->base_gfn,
5652 memslot->base_gfn + memslot->npages - 1,
5656 static __always_inline bool
5657 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5658 slot_level_handler fn, bool lock_flush_tlb)
5660 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5661 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5664 static __always_inline bool
5665 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5666 slot_level_handler fn, bool lock_flush_tlb)
5668 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5669 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5672 static __always_inline bool
5673 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5674 slot_level_handler fn, bool lock_flush_tlb)
5676 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5677 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5680 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5682 struct kvm_memslots *slots;
5683 struct kvm_memory_slot *memslot;
5686 spin_lock(&kvm->mmu_lock);
5687 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5688 slots = __kvm_memslots(kvm, i);
5689 kvm_for_each_memslot(memslot, slots) {
5692 start = max(gfn_start, memslot->base_gfn);
5693 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5697 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5698 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5699 start, end - 1, true);
5703 spin_unlock(&kvm->mmu_lock);
5706 static bool slot_rmap_write_protect(struct kvm *kvm,
5707 struct kvm_rmap_head *rmap_head)
5709 return __rmap_write_protect(kvm, rmap_head, false);
5712 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5713 struct kvm_memory_slot *memslot)
5717 spin_lock(&kvm->mmu_lock);
5718 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5720 spin_unlock(&kvm->mmu_lock);
5723 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5724 * which do tlb flush out of mmu-lock should be serialized by
5725 * kvm->slots_lock otherwise tlb flush would be missed.
5727 lockdep_assert_held(&kvm->slots_lock);
5730 * We can flush all the TLBs out of the mmu lock without TLB
5731 * corruption since we just change the spte from writable to
5732 * readonly so that we only need to care the case of changing
5733 * spte from present to present (changing the spte from present
5734 * to nonpresent will flush all the TLBs immediately), in other
5735 * words, the only case we care is mmu_spte_update() where we
5736 * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5737 * instead of PT_WRITABLE_MASK, that means it does not depend
5738 * on PT_WRITABLE_MASK anymore.
5741 kvm_flush_remote_tlbs(kvm);
5744 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5745 struct kvm_rmap_head *rmap_head)
5748 struct rmap_iterator iter;
5749 int need_tlb_flush = 0;
5751 struct kvm_mmu_page *sp;
5754 for_each_rmap_spte(rmap_head, &iter, sptep) {
5755 sp = page_header(__pa(sptep));
5756 pfn = spte_to_pfn(*sptep);
5759 * We cannot do huge page mapping for indirect shadow pages,
5760 * which are found on the last rmap (level = 1) when not using
5761 * tdp; such shadow pages are synced with the page table in
5762 * the guest, and the guest page table is using 4K page size
5763 * mapping if the indirect sp has level = 1.
5765 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5766 !kvm_is_zone_device_pfn(pfn) &&
5767 PageTransCompoundMap(pfn_to_page(pfn))) {
5768 drop_spte(kvm, sptep);
5774 return need_tlb_flush;
5777 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5778 const struct kvm_memory_slot *memslot)
5780 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5781 spin_lock(&kvm->mmu_lock);
5782 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5783 kvm_mmu_zap_collapsible_spte, true);
5784 spin_unlock(&kvm->mmu_lock);
5787 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5788 struct kvm_memory_slot *memslot)
5792 spin_lock(&kvm->mmu_lock);
5793 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5794 spin_unlock(&kvm->mmu_lock);
5796 lockdep_assert_held(&kvm->slots_lock);
5799 * It's also safe to flush TLBs out of mmu lock here as currently this
5800 * function is only used for dirty logging, in which case flushing TLB
5801 * out of mmu lock also guarantees no dirty pages will be lost in
5805 kvm_flush_remote_tlbs(kvm);
5807 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5809 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5810 struct kvm_memory_slot *memslot)
5814 spin_lock(&kvm->mmu_lock);
5815 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5817 spin_unlock(&kvm->mmu_lock);
5819 /* see kvm_mmu_slot_remove_write_access */
5820 lockdep_assert_held(&kvm->slots_lock);
5823 kvm_flush_remote_tlbs(kvm);
5825 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5827 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5828 struct kvm_memory_slot *memslot)
5832 spin_lock(&kvm->mmu_lock);
5833 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5834 spin_unlock(&kvm->mmu_lock);
5836 lockdep_assert_held(&kvm->slots_lock);
5838 /* see kvm_mmu_slot_leaf_clear_dirty */
5840 kvm_flush_remote_tlbs(kvm);
5842 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5844 #define BATCH_ZAP_PAGES 10
5845 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5847 struct kvm_mmu_page *sp, *node;
5851 list_for_each_entry_safe_reverse(sp, node,
5852 &kvm->arch.active_mmu_pages, link) {
5856 * No obsolete page exists before new created page since
5857 * active_mmu_pages is the FIFO list.
5859 if (!is_obsolete_sp(kvm, sp))
5863 * Since we are reversely walking the list and the invalid
5864 * list will be moved to the head, skip the invalid page
5865 * can help us to avoid the infinity list walking.
5867 if (sp->role.invalid)
5871 * Need not flush tlb since we only zap the sp with invalid
5872 * generation number.
5874 if (batch >= BATCH_ZAP_PAGES &&
5875 cond_resched_lock(&kvm->mmu_lock)) {
5880 ret = kvm_mmu_prepare_zap_page(kvm, sp,
5881 &kvm->arch.zapped_obsolete_pages);
5889 * Should flush tlb before free page tables since lockless-walking
5890 * may use the pages.
5892 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5896 * Fast invalidate all shadow pages and use lock-break technique
5897 * to zap obsolete pages.
5899 * It's required when memslot is being deleted or VM is being
5900 * destroyed, in these cases, we should ensure that KVM MMU does
5901 * not use any resource of the being-deleted slot or all slots
5902 * after calling the function.
5904 void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
5906 spin_lock(&kvm->mmu_lock);
5907 trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5908 kvm->arch.mmu_valid_gen++;
5911 * Notify all vcpus to reload its shadow page table
5912 * and flush TLB. Then all vcpus will switch to new
5913 * shadow page table with the new mmu_valid_gen.
5915 * Note: we should do this under the protection of
5916 * mmu-lock, otherwise, vcpu would purge shadow page
5917 * but miss tlb flush.
5919 kvm_reload_remote_mmus(kvm);
5921 kvm_zap_obsolete_pages(kvm);
5922 spin_unlock(&kvm->mmu_lock);
5925 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5927 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5930 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5932 gen &= MMIO_GEN_MASK;
5935 * Shift to eliminate the "update in-progress" flag, which isn't
5936 * included in the spte's generation number.
5941 * Generation numbers are incremented in multiples of the number of
5942 * address spaces in order to provide unique generations across all
5943 * address spaces. Strip what is effectively the address space
5944 * modifier prior to checking for a wrap of the MMIO generation so
5945 * that a wrap in any address space is detected.
5947 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5950 * The very rare case: if the MMIO generation number has wrapped,
5951 * zap all shadow pages.
5953 if (unlikely(gen == 0)) {
5954 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5955 kvm_mmu_invalidate_zap_all_pages(kvm);
5959 static unsigned long
5960 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5963 int nr_to_scan = sc->nr_to_scan;
5964 unsigned long freed = 0;
5966 mutex_lock(&kvm_lock);
5968 list_for_each_entry(kvm, &vm_list, vm_list) {
5970 LIST_HEAD(invalid_list);
5973 * Never scan more than sc->nr_to_scan VM instances.
5974 * Will not hit this condition practically since we do not try
5975 * to shrink more than one VM and it is very unlikely to see
5976 * !n_used_mmu_pages so many times.
5981 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5982 * here. We may skip a VM instance errorneosly, but we do not
5983 * want to shrink a VM that only started to populate its MMU
5986 if (!kvm->arch.n_used_mmu_pages &&
5987 !kvm_has_zapped_obsolete_pages(kvm))
5990 idx = srcu_read_lock(&kvm->srcu);
5991 spin_lock(&kvm->mmu_lock);
5993 if (kvm_has_zapped_obsolete_pages(kvm)) {
5994 kvm_mmu_commit_zap_page(kvm,
5995 &kvm->arch.zapped_obsolete_pages);
5999 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6001 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6004 spin_unlock(&kvm->mmu_lock);
6005 srcu_read_unlock(&kvm->srcu, idx);
6008 * unfair on small ones
6009 * per-vm shrinkers cry out
6010 * sadness comes quickly
6012 list_move_tail(&kvm->vm_list, &vm_list);
6016 mutex_unlock(&kvm_lock);
6020 static unsigned long
6021 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6023 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6026 static struct shrinker mmu_shrinker = {
6027 .count_objects = mmu_shrink_count,
6028 .scan_objects = mmu_shrink_scan,
6029 .seeks = DEFAULT_SEEKS * 10,
6032 static void mmu_destroy_caches(void)
6034 kmem_cache_destroy(pte_list_desc_cache);
6035 kmem_cache_destroy(mmu_page_header_cache);
6038 static bool get_nx_auto_mode(void)
6040 /* Return true when CPU has the bug, and mitigations are ON */
6041 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6044 static void __set_nx_huge_pages(bool val)
6046 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6049 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6051 bool old_val = nx_huge_pages;
6054 /* In "auto" mode deploy workaround only if CPU has the bug. */
6055 if (sysfs_streq(val, "off"))
6057 else if (sysfs_streq(val, "force"))
6059 else if (sysfs_streq(val, "auto"))
6060 new_val = get_nx_auto_mode();
6061 else if (strtobool(val, &new_val) < 0)
6064 __set_nx_huge_pages(new_val);
6066 if (new_val != old_val) {
6070 mutex_lock(&kvm_lock);
6072 list_for_each_entry(kvm, &vm_list, vm_list) {
6073 idx = srcu_read_lock(&kvm->srcu);
6074 kvm_mmu_invalidate_zap_all_pages(kvm);
6075 srcu_read_unlock(&kvm->srcu, idx);
6077 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6079 mutex_unlock(&kvm_lock);
6085 static void kvm_set_mmio_spte_mask(void)
6090 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
6091 * PFEC.RSVD=1 on MMIO accesses. 64-bit PTEs (PAE, x86-64, and EPT
6092 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
6093 * 52-bit physical addresses then there are no reserved PA bits in the
6094 * PTEs and so the reserved PA approach must be disabled.
6096 if (shadow_phys_bits < 52)
6097 mask = BIT_ULL(51) | PT_PRESENT_MASK;
6101 kvm_mmu_set_mmio_spte_mask(mask, mask);
6104 int kvm_mmu_module_init(void)
6108 if (nx_huge_pages == -1)
6109 __set_nx_huge_pages(get_nx_auto_mode());
6111 kvm_mmu_reset_all_pte_masks();
6113 kvm_set_mmio_spte_mask();
6115 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6116 sizeof(struct pte_list_desc),
6117 0, SLAB_ACCOUNT, NULL);
6118 if (!pte_list_desc_cache)
6121 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6122 sizeof(struct kvm_mmu_page),
6123 0, SLAB_ACCOUNT, NULL);
6124 if (!mmu_page_header_cache)
6127 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6130 ret = register_shrinker(&mmu_shrinker);
6137 mmu_destroy_caches();
6142 * Caculate mmu pages needed for kvm.
6144 unsigned long kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
6146 unsigned long nr_mmu_pages;
6147 unsigned long nr_pages = 0;
6148 struct kvm_memslots *slots;
6149 struct kvm_memory_slot *memslot;
6152 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6153 slots = __kvm_memslots(kvm, i);
6155 kvm_for_each_memslot(memslot, slots)
6156 nr_pages += memslot->npages;
6159 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6160 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6162 return nr_mmu_pages;
6165 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6167 kvm_mmu_unload(vcpu);
6168 free_mmu_pages(vcpu);
6169 mmu_free_memory_caches(vcpu);
6172 void kvm_mmu_module_exit(void)
6174 mmu_destroy_caches();
6175 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6176 unregister_shrinker(&mmu_shrinker);
6177 mmu_audit_disable();
6180 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6182 unsigned int old_val;
6185 old_val = nx_huge_pages_recovery_ratio;
6186 err = param_set_uint(val, kp);
6190 if (READ_ONCE(nx_huge_pages) &&
6191 !old_val && nx_huge_pages_recovery_ratio) {
6194 mutex_lock(&kvm_lock);
6196 list_for_each_entry(kvm, &vm_list, vm_list)
6197 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6199 mutex_unlock(&kvm_lock);
6205 static void kvm_recover_nx_lpages(struct kvm *kvm)
6208 struct kvm_mmu_page *sp;
6210 LIST_HEAD(invalid_list);
6213 rcu_idx = srcu_read_lock(&kvm->srcu);
6214 spin_lock(&kvm->mmu_lock);
6216 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6217 to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
6218 while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
6220 * We use a separate list instead of just using active_mmu_pages
6221 * because the number of lpage_disallowed pages is expected to
6222 * be relatively small compared to the total.
6224 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6225 struct kvm_mmu_page,
6226 lpage_disallowed_link);
6227 WARN_ON_ONCE(!sp->lpage_disallowed);
6228 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6229 WARN_ON_ONCE(sp->lpage_disallowed);
6231 if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
6232 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6234 cond_resched_lock(&kvm->mmu_lock);
6237 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6239 spin_unlock(&kvm->mmu_lock);
6240 srcu_read_unlock(&kvm->srcu, rcu_idx);
6243 static long get_nx_lpage_recovery_timeout(u64 start_time)
6245 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6246 ? start_time + 60 * HZ - get_jiffies_64()
6247 : MAX_SCHEDULE_TIMEOUT;
6250 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6253 long remaining_time;
6256 start_time = get_jiffies_64();
6257 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6259 set_current_state(TASK_INTERRUPTIBLE);
6260 while (!kthread_should_stop() && remaining_time > 0) {
6261 schedule_timeout(remaining_time);
6262 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6263 set_current_state(TASK_INTERRUPTIBLE);
6266 set_current_state(TASK_RUNNING);
6268 if (kthread_should_stop())
6271 kvm_recover_nx_lpages(kvm);
6275 int kvm_mmu_post_init_vm(struct kvm *kvm)
6279 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6280 "kvm-nx-lpage-recovery",
6281 &kvm->arch.nx_lpage_recovery_thread);
6283 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6288 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6290 if (kvm->arch.nx_lpage_recovery_thread)
6291 kthread_stop(kvm->arch.nx_lpage_recovery_thread);