1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
10 * Copyright (C) 2006 Qumranet, Inc.
11 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Avi Kivity <avi@qumranet.com>
21 #include "kvm_cache_regs.h"
24 #include <linux/kvm_host.h>
25 #include <linux/types.h>
26 #include <linux/string.h>
28 #include <linux/highmem.h>
29 #include <linux/moduleparam.h>
30 #include <linux/export.h>
31 #include <linux/swap.h>
32 #include <linux/hugetlb.h>
33 #include <linux/compiler.h>
34 #include <linux/srcu.h>
35 #include <linux/slab.h>
36 #include <linux/sched/signal.h>
37 #include <linux/uaccess.h>
38 #include <linux/hash.h>
39 #include <linux/kern_levels.h>
43 #include <asm/cmpxchg.h>
44 #include <asm/e820/api.h>
47 #include <asm/kvm_page_track.h>
51 * When setting this variable to true it enables Two-Dimensional-Paging
52 * where the hardware walks 2 page tables:
53 * 1. the guest-virtual to guest-physical
54 * 2. while doing 1. it walks guest-physical to host-physical
55 * If the hardware supports that we don't need to do shadow paging.
57 bool tdp_enabled = false;
61 AUDIT_POST_PAGE_FAULT,
72 module_param(dbg, bool, 0644);
74 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
75 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
76 #define MMU_WARN_ON(x) WARN_ON(x)
78 #define pgprintk(x...) do { } while (0)
79 #define rmap_printk(x...) do { } while (0)
80 #define MMU_WARN_ON(x) do { } while (0)
83 #define PTE_PREFETCH_NUM 8
85 #define PT_FIRST_AVAIL_BITS_SHIFT 10
86 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
88 #define PT64_LEVEL_BITS 9
90 #define PT64_LEVEL_SHIFT(level) \
91 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
93 #define PT64_INDEX(address, level)\
94 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
97 #define PT32_LEVEL_BITS 10
99 #define PT32_LEVEL_SHIFT(level) \
100 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
102 #define PT32_LVL_OFFSET_MASK(level) \
103 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
104 * PT32_LEVEL_BITS))) - 1))
106 #define PT32_INDEX(address, level)\
107 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
110 #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
111 #define PT64_BASE_ADDR_MASK (physical_mask & ~(u64)(PAGE_SIZE-1))
113 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
115 #define PT64_LVL_ADDR_MASK(level) \
116 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
117 * PT64_LEVEL_BITS))) - 1))
118 #define PT64_LVL_OFFSET_MASK(level) \
119 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
120 * PT64_LEVEL_BITS))) - 1))
122 #define PT32_BASE_ADDR_MASK PAGE_MASK
123 #define PT32_DIR_BASE_ADDR_MASK \
124 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
125 #define PT32_LVL_ADDR_MASK(level) \
126 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
127 * PT32_LEVEL_BITS))) - 1))
129 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
130 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
132 #define ACC_EXEC_MASK 1
133 #define ACC_WRITE_MASK PT_WRITABLE_MASK
134 #define ACC_USER_MASK PT_USER_MASK
135 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
137 /* The mask for the R/X bits in EPT PTEs */
138 #define PT64_EPT_READABLE_MASK 0x1ull
139 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
141 #include <trace/events/kvm.h>
143 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
144 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
146 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
148 /* make pte_list_desc fit well in cache line */
149 #define PTE_LIST_EXT 3
152 * Return values of handle_mmio_page_fault and mmu.page_fault:
153 * RET_PF_RETRY: let CPU fault again on the address.
154 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
156 * For handle_mmio_page_fault only:
157 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
165 struct pte_list_desc {
166 u64 *sptes[PTE_LIST_EXT];
167 struct pte_list_desc *more;
170 struct kvm_shadow_walk_iterator {
178 static const union kvm_mmu_page_role mmu_base_role_mask = {
180 .gpte_is_8_bytes = 1,
189 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
190 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
192 shadow_walk_okay(&(_walker)); \
193 shadow_walk_next(&(_walker)))
195 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
196 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
197 shadow_walk_okay(&(_walker)); \
198 shadow_walk_next(&(_walker)))
200 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
201 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
202 shadow_walk_okay(&(_walker)) && \
203 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
204 __shadow_walk_next(&(_walker), spte))
206 static struct kmem_cache *pte_list_desc_cache;
207 static struct kmem_cache *mmu_page_header_cache;
208 static struct percpu_counter kvm_total_used_mmu_pages;
210 static u64 __read_mostly shadow_nx_mask;
211 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
212 static u64 __read_mostly shadow_user_mask;
213 static u64 __read_mostly shadow_accessed_mask;
214 static u64 __read_mostly shadow_dirty_mask;
215 static u64 __read_mostly shadow_mmio_mask;
216 static u64 __read_mostly shadow_mmio_value;
217 static u64 __read_mostly shadow_mmio_access_mask;
218 static u64 __read_mostly shadow_present_mask;
219 static u64 __read_mostly shadow_me_mask;
222 * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
223 * Non-present SPTEs with shadow_acc_track_value set are in place for access
226 static u64 __read_mostly shadow_acc_track_mask;
227 static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
230 * The mask/shift to use for saving the original R/X bits when marking the PTE
231 * as not-present for access tracking purposes. We do not save the W bit as the
232 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
233 * restored only when a write is attempted to the page.
235 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
236 PT64_EPT_EXECUTABLE_MASK;
237 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
240 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
241 * to guard against L1TF attacks.
243 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
246 * The number of high-order 1 bits to use in the mask above.
248 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
251 * In some cases, we need to preserve the GFN of a non-present or reserved
252 * SPTE when we usurp the upper five bits of the physical address space to
253 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
254 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
255 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
256 * high and low parts. This mask covers the lower bits of the GFN.
258 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
261 * The number of non-reserved physical address bits irrespective of features
262 * that repurpose legal bits, e.g. MKTME.
264 static u8 __read_mostly shadow_phys_bits;
266 static void mmu_spte_set(u64 *sptep, u64 spte);
267 static bool is_executable_pte(u64 spte);
268 static union kvm_mmu_page_role
269 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
271 #define CREATE_TRACE_POINTS
272 #include "mmutrace.h"
275 static inline bool kvm_available_flush_tlb_with_range(void)
277 return kvm_x86_ops->tlb_remote_flush_with_range;
280 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
281 struct kvm_tlb_range *range)
285 if (range && kvm_x86_ops->tlb_remote_flush_with_range)
286 ret = kvm_x86_ops->tlb_remote_flush_with_range(kvm, range);
289 kvm_flush_remote_tlbs(kvm);
292 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
293 u64 start_gfn, u64 pages)
295 struct kvm_tlb_range range;
297 range.start_gfn = start_gfn;
300 kvm_flush_remote_tlbs_with_range(kvm, &range);
303 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value, u64 access_mask)
305 BUG_ON((u64)(unsigned)access_mask != access_mask);
306 BUG_ON((mmio_mask & mmio_value) != mmio_value);
307 shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
308 shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
309 shadow_mmio_access_mask = access_mask;
311 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
313 static bool is_mmio_spte(u64 spte)
315 return (spte & shadow_mmio_mask) == shadow_mmio_value;
318 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
320 return sp->role.ad_disabled;
323 static inline bool spte_ad_enabled(u64 spte)
325 MMU_WARN_ON(is_mmio_spte(spte));
326 return !(spte & shadow_acc_track_value);
329 static inline u64 spte_shadow_accessed_mask(u64 spte)
331 MMU_WARN_ON(is_mmio_spte(spte));
332 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
335 static inline u64 spte_shadow_dirty_mask(u64 spte)
337 MMU_WARN_ON(is_mmio_spte(spte));
338 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
341 static inline bool is_access_track_spte(u64 spte)
343 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
347 * Due to limited space in PTEs, the MMIO generation is a 19 bit subset of
348 * the memslots generation and is derived as follows:
350 * Bits 0-8 of the MMIO generation are propagated to spte bits 3-11
351 * Bits 9-18 of the MMIO generation are propagated to spte bits 52-61
353 * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
354 * the MMIO generation number, as doing so would require stealing a bit from
355 * the "real" generation number and thus effectively halve the maximum number
356 * of MMIO generations that can be handled before encountering a wrap (which
357 * requires a full MMU zap). The flag is instead explicitly queried when
358 * checking for MMIO spte cache hits.
360 #define MMIO_SPTE_GEN_MASK GENMASK_ULL(18, 0)
362 #define MMIO_SPTE_GEN_LOW_START 3
363 #define MMIO_SPTE_GEN_LOW_END 11
364 #define MMIO_SPTE_GEN_LOW_MASK GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
365 MMIO_SPTE_GEN_LOW_START)
367 #define MMIO_SPTE_GEN_HIGH_START 52
368 #define MMIO_SPTE_GEN_HIGH_END 61
369 #define MMIO_SPTE_GEN_HIGH_MASK GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
370 MMIO_SPTE_GEN_HIGH_START)
371 static u64 generation_mmio_spte_mask(u64 gen)
375 WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
377 mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
378 mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
382 static u64 get_mmio_spte_generation(u64 spte)
386 spte &= ~shadow_mmio_mask;
388 gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
389 gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
393 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
396 u64 gen = kvm_vcpu_memslots(vcpu)->generation & MMIO_SPTE_GEN_MASK;
397 u64 mask = generation_mmio_spte_mask(gen);
398 u64 gpa = gfn << PAGE_SHIFT;
400 access &= shadow_mmio_access_mask;
401 mask |= shadow_mmio_value | access;
402 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
403 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
404 << shadow_nonpresent_or_rsvd_mask_len;
406 trace_mark_mmio_spte(sptep, gfn, access, gen);
407 mmu_spte_set(sptep, mask);
410 static gfn_t get_mmio_spte_gfn(u64 spte)
412 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
414 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
415 & shadow_nonpresent_or_rsvd_mask;
417 return gpa >> PAGE_SHIFT;
420 static unsigned get_mmio_spte_access(u64 spte)
422 return spte & shadow_mmio_access_mask;
425 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
426 kvm_pfn_t pfn, unsigned access)
428 if (unlikely(is_noslot_pfn(pfn))) {
429 mark_mmio_spte(vcpu, sptep, gfn, access);
436 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
438 u64 kvm_gen, spte_gen, gen;
440 gen = kvm_vcpu_memslots(vcpu)->generation;
441 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
444 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
445 spte_gen = get_mmio_spte_generation(spte);
447 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
448 return likely(kvm_gen == spte_gen);
452 * Sets the shadow PTE masks used by the MMU.
455 * - Setting either @accessed_mask or @dirty_mask requires setting both
456 * - At least one of @accessed_mask or @acc_track_mask must be set
458 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
459 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
460 u64 acc_track_mask, u64 me_mask)
462 BUG_ON(!dirty_mask != !accessed_mask);
463 BUG_ON(!accessed_mask && !acc_track_mask);
464 BUG_ON(acc_track_mask & shadow_acc_track_value);
466 shadow_user_mask = user_mask;
467 shadow_accessed_mask = accessed_mask;
468 shadow_dirty_mask = dirty_mask;
469 shadow_nx_mask = nx_mask;
470 shadow_x_mask = x_mask;
471 shadow_present_mask = p_mask;
472 shadow_acc_track_mask = acc_track_mask;
473 shadow_me_mask = me_mask;
475 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
477 static u8 kvm_get_shadow_phys_bits(void)
480 * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
481 * in CPU detection code, but MKTME treats those reduced bits as
482 * 'keyID' thus they are not reserved bits. Therefore for MKTME
483 * we should still return physical address bits reported by CPUID.
485 if (!boot_cpu_has(X86_FEATURE_TME) ||
486 WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
487 return boot_cpu_data.x86_phys_bits;
489 return cpuid_eax(0x80000008) & 0xff;
492 static void kvm_mmu_reset_all_pte_masks(void)
496 shadow_user_mask = 0;
497 shadow_accessed_mask = 0;
498 shadow_dirty_mask = 0;
501 shadow_mmio_mask = 0;
502 shadow_present_mask = 0;
503 shadow_acc_track_mask = 0;
505 shadow_phys_bits = kvm_get_shadow_phys_bits();
508 * If the CPU has 46 or less physical address bits, then set an
509 * appropriate mask to guard against L1TF attacks. Otherwise, it is
510 * assumed that the CPU is not vulnerable to L1TF.
512 * Some Intel CPUs address the L1 cache using more PA bits than are
513 * reported by CPUID. Use the PA width of the L1 cache when possible
514 * to achieve more effective mitigation, e.g. if system RAM overlaps
515 * the most significant bits of legal physical address space.
517 shadow_nonpresent_or_rsvd_mask = 0;
518 low_phys_bits = boot_cpu_data.x86_cache_bits;
519 if (boot_cpu_data.x86_cache_bits <
520 52 - shadow_nonpresent_or_rsvd_mask_len) {
521 shadow_nonpresent_or_rsvd_mask =
522 rsvd_bits(boot_cpu_data.x86_cache_bits -
523 shadow_nonpresent_or_rsvd_mask_len,
524 boot_cpu_data.x86_cache_bits - 1);
525 low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
527 WARN_ON_ONCE(boot_cpu_has_bug(X86_BUG_L1TF));
529 shadow_nonpresent_or_rsvd_lower_gfn_mask =
530 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
533 static int is_cpuid_PSE36(void)
538 static int is_nx(struct kvm_vcpu *vcpu)
540 return vcpu->arch.efer & EFER_NX;
543 static int is_shadow_present_pte(u64 pte)
545 return (pte != 0) && !is_mmio_spte(pte);
548 static int is_large_pte(u64 pte)
550 return pte & PT_PAGE_SIZE_MASK;
553 static int is_last_spte(u64 pte, int level)
555 if (level == PT_PAGE_TABLE_LEVEL)
557 if (is_large_pte(pte))
562 static bool is_executable_pte(u64 spte)
564 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
567 static kvm_pfn_t spte_to_pfn(u64 pte)
569 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
572 static gfn_t pse36_gfn_delta(u32 gpte)
574 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
576 return (gpte & PT32_DIR_PSE36_MASK) << shift;
580 static void __set_spte(u64 *sptep, u64 spte)
582 WRITE_ONCE(*sptep, spte);
585 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
587 WRITE_ONCE(*sptep, spte);
590 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
592 return xchg(sptep, spte);
595 static u64 __get_spte_lockless(u64 *sptep)
597 return READ_ONCE(*sptep);
608 static void count_spte_clear(u64 *sptep, u64 spte)
610 struct kvm_mmu_page *sp = page_header(__pa(sptep));
612 if (is_shadow_present_pte(spte))
615 /* Ensure the spte is completely set before we increase the count */
617 sp->clear_spte_count++;
620 static void __set_spte(u64 *sptep, u64 spte)
622 union split_spte *ssptep, sspte;
624 ssptep = (union split_spte *)sptep;
625 sspte = (union split_spte)spte;
627 ssptep->spte_high = sspte.spte_high;
630 * If we map the spte from nonpresent to present, We should store
631 * the high bits firstly, then set present bit, so cpu can not
632 * fetch this spte while we are setting the spte.
636 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
639 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
641 union split_spte *ssptep, sspte;
643 ssptep = (union split_spte *)sptep;
644 sspte = (union split_spte)spte;
646 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
649 * If we map the spte from present to nonpresent, we should clear
650 * present bit firstly to avoid vcpu fetch the old high bits.
654 ssptep->spte_high = sspte.spte_high;
655 count_spte_clear(sptep, spte);
658 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
660 union split_spte *ssptep, sspte, orig;
662 ssptep = (union split_spte *)sptep;
663 sspte = (union split_spte)spte;
665 /* xchg acts as a barrier before the setting of the high bits */
666 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
667 orig.spte_high = ssptep->spte_high;
668 ssptep->spte_high = sspte.spte_high;
669 count_spte_clear(sptep, spte);
675 * The idea using the light way get the spte on x86_32 guest is from
676 * gup_get_pte (mm/gup.c).
678 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
679 * coalesces them and we are running out of the MMU lock. Therefore
680 * we need to protect against in-progress updates of the spte.
682 * Reading the spte while an update is in progress may get the old value
683 * for the high part of the spte. The race is fine for a present->non-present
684 * change (because the high part of the spte is ignored for non-present spte),
685 * but for a present->present change we must reread the spte.
687 * All such changes are done in two steps (present->non-present and
688 * non-present->present), hence it is enough to count the number of
689 * present->non-present updates: if it changed while reading the spte,
690 * we might have hit the race. This is done using clear_spte_count.
692 static u64 __get_spte_lockless(u64 *sptep)
694 struct kvm_mmu_page *sp = page_header(__pa(sptep));
695 union split_spte spte, *orig = (union split_spte *)sptep;
699 count = sp->clear_spte_count;
702 spte.spte_low = orig->spte_low;
705 spte.spte_high = orig->spte_high;
708 if (unlikely(spte.spte_low != orig->spte_low ||
709 count != sp->clear_spte_count))
716 static bool spte_can_locklessly_be_made_writable(u64 spte)
718 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
719 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
722 static bool spte_has_volatile_bits(u64 spte)
724 if (!is_shadow_present_pte(spte))
728 * Always atomically update spte if it can be updated
729 * out of mmu-lock, it can ensure dirty bit is not lost,
730 * also, it can help us to get a stable is_writable_pte()
731 * to ensure tlb flush is not missed.
733 if (spte_can_locklessly_be_made_writable(spte) ||
734 is_access_track_spte(spte))
737 if (spte_ad_enabled(spte)) {
738 if ((spte & shadow_accessed_mask) == 0 ||
739 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
746 static bool is_accessed_spte(u64 spte)
748 u64 accessed_mask = spte_shadow_accessed_mask(spte);
750 return accessed_mask ? spte & accessed_mask
751 : !is_access_track_spte(spte);
754 static bool is_dirty_spte(u64 spte)
756 u64 dirty_mask = spte_shadow_dirty_mask(spte);
758 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
761 /* Rules for using mmu_spte_set:
762 * Set the sptep from nonpresent to present.
763 * Note: the sptep being assigned *must* be either not present
764 * or in a state where the hardware will not attempt to update
767 static void mmu_spte_set(u64 *sptep, u64 new_spte)
769 WARN_ON(is_shadow_present_pte(*sptep));
770 __set_spte(sptep, new_spte);
774 * Update the SPTE (excluding the PFN), but do not track changes in its
775 * accessed/dirty status.
777 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
779 u64 old_spte = *sptep;
781 WARN_ON(!is_shadow_present_pte(new_spte));
783 if (!is_shadow_present_pte(old_spte)) {
784 mmu_spte_set(sptep, new_spte);
788 if (!spte_has_volatile_bits(old_spte))
789 __update_clear_spte_fast(sptep, new_spte);
791 old_spte = __update_clear_spte_slow(sptep, new_spte);
793 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
798 /* Rules for using mmu_spte_update:
799 * Update the state bits, it means the mapped pfn is not changed.
801 * Whenever we overwrite a writable spte with a read-only one we
802 * should flush remote TLBs. Otherwise rmap_write_protect
803 * will find a read-only spte, even though the writable spte
804 * might be cached on a CPU's TLB, the return value indicates this
807 * Returns true if the TLB needs to be flushed
809 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
812 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
814 if (!is_shadow_present_pte(old_spte))
818 * For the spte updated out of mmu-lock is safe, since
819 * we always atomically update it, see the comments in
820 * spte_has_volatile_bits().
822 if (spte_can_locklessly_be_made_writable(old_spte) &&
823 !is_writable_pte(new_spte))
827 * Flush TLB when accessed/dirty states are changed in the page tables,
828 * to guarantee consistency between TLB and page tables.
831 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
833 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
836 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
838 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
845 * Rules for using mmu_spte_clear_track_bits:
846 * It sets the sptep from present to nonpresent, and track the
847 * state bits, it is used to clear the last level sptep.
848 * Returns non-zero if the PTE was previously valid.
850 static int mmu_spte_clear_track_bits(u64 *sptep)
853 u64 old_spte = *sptep;
855 if (!spte_has_volatile_bits(old_spte))
856 __update_clear_spte_fast(sptep, 0ull);
858 old_spte = __update_clear_spte_slow(sptep, 0ull);
860 if (!is_shadow_present_pte(old_spte))
863 pfn = spte_to_pfn(old_spte);
866 * KVM does not hold the refcount of the page used by
867 * kvm mmu, before reclaiming the page, we should
868 * unmap it from mmu first.
870 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
872 if (is_accessed_spte(old_spte))
873 kvm_set_pfn_accessed(pfn);
875 if (is_dirty_spte(old_spte))
876 kvm_set_pfn_dirty(pfn);
882 * Rules for using mmu_spte_clear_no_track:
883 * Directly clear spte without caring the state bits of sptep,
884 * it is used to set the upper level spte.
886 static void mmu_spte_clear_no_track(u64 *sptep)
888 __update_clear_spte_fast(sptep, 0ull);
891 static u64 mmu_spte_get_lockless(u64 *sptep)
893 return __get_spte_lockless(sptep);
896 static u64 mark_spte_for_access_track(u64 spte)
898 if (spte_ad_enabled(spte))
899 return spte & ~shadow_accessed_mask;
901 if (is_access_track_spte(spte))
905 * Making an Access Tracking PTE will result in removal of write access
906 * from the PTE. So, verify that we will be able to restore the write
907 * access in the fast page fault path later on.
909 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
910 !spte_can_locklessly_be_made_writable(spte),
911 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
913 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
914 shadow_acc_track_saved_bits_shift),
915 "kvm: Access Tracking saved bit locations are not zero\n");
917 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
918 shadow_acc_track_saved_bits_shift;
919 spte &= ~shadow_acc_track_mask;
924 /* Restore an acc-track PTE back to a regular PTE */
925 static u64 restore_acc_track_spte(u64 spte)
928 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
929 & shadow_acc_track_saved_bits_mask;
931 WARN_ON_ONCE(spte_ad_enabled(spte));
932 WARN_ON_ONCE(!is_access_track_spte(spte));
934 new_spte &= ~shadow_acc_track_mask;
935 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
936 shadow_acc_track_saved_bits_shift);
937 new_spte |= saved_bits;
942 /* Returns the Accessed status of the PTE and resets it at the same time. */
943 static bool mmu_spte_age(u64 *sptep)
945 u64 spte = mmu_spte_get_lockless(sptep);
947 if (!is_accessed_spte(spte))
950 if (spte_ad_enabled(spte)) {
951 clear_bit((ffs(shadow_accessed_mask) - 1),
952 (unsigned long *)sptep);
955 * Capture the dirty status of the page, so that it doesn't get
956 * lost when the SPTE is marked for access tracking.
958 if (is_writable_pte(spte))
959 kvm_set_pfn_dirty(spte_to_pfn(spte));
961 spte = mark_spte_for_access_track(spte);
962 mmu_spte_update_no_track(sptep, spte);
968 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
971 * Prevent page table teardown by making any free-er wait during
972 * kvm_flush_remote_tlbs() IPI to all active vcpus.
977 * Make sure a following spte read is not reordered ahead of the write
980 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
983 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
986 * Make sure the write to vcpu->mode is not reordered in front of
987 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
988 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
990 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
994 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
995 struct kmem_cache *base_cache, int min)
999 if (cache->nobjs >= min)
1001 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1002 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL_ACCOUNT);
1004 return cache->nobjs >= min ? 0 : -ENOMEM;
1005 cache->objects[cache->nobjs++] = obj;
1010 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
1012 return cache->nobjs;
1015 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
1016 struct kmem_cache *cache)
1019 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
1022 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1027 if (cache->nobjs >= min)
1029 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1030 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1032 return cache->nobjs >= min ? 0 : -ENOMEM;
1033 cache->objects[cache->nobjs++] = page;
1038 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1041 free_page((unsigned long)mc->objects[--mc->nobjs]);
1044 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1048 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1049 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1052 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1055 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1056 mmu_page_header_cache, 4);
1061 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1063 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1064 pte_list_desc_cache);
1065 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1066 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1067 mmu_page_header_cache);
1070 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1075 p = mc->objects[--mc->nobjs];
1079 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1081 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1084 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1086 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1089 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1091 if (!sp->role.direct)
1092 return sp->gfns[index];
1094 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1097 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1099 if (!sp->role.direct) {
1100 sp->gfns[index] = gfn;
1104 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1105 pr_err_ratelimited("gfn mismatch under direct page %llx "
1106 "(expected %llx, got %llx)\n",
1108 kvm_mmu_page_get_gfn(sp, index), gfn);
1112 * Return the pointer to the large page information for a given gfn,
1113 * handling slots that are not large page aligned.
1115 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1116 struct kvm_memory_slot *slot,
1121 idx = gfn_to_index(gfn, slot->base_gfn, level);
1122 return &slot->arch.lpage_info[level - 2][idx];
1125 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1126 gfn_t gfn, int count)
1128 struct kvm_lpage_info *linfo;
1131 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1132 linfo = lpage_info_slot(gfn, slot, i);
1133 linfo->disallow_lpage += count;
1134 WARN_ON(linfo->disallow_lpage < 0);
1138 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1140 update_gfn_disallow_lpage_count(slot, gfn, 1);
1143 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1145 update_gfn_disallow_lpage_count(slot, gfn, -1);
1148 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1150 struct kvm_memslots *slots;
1151 struct kvm_memory_slot *slot;
1154 kvm->arch.indirect_shadow_pages++;
1156 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1157 slot = __gfn_to_memslot(slots, gfn);
1159 /* the non-leaf shadow pages are keeping readonly. */
1160 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1161 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1162 KVM_PAGE_TRACK_WRITE);
1164 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1167 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1169 struct kvm_memslots *slots;
1170 struct kvm_memory_slot *slot;
1173 kvm->arch.indirect_shadow_pages--;
1175 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1176 slot = __gfn_to_memslot(slots, gfn);
1177 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1178 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1179 KVM_PAGE_TRACK_WRITE);
1181 kvm_mmu_gfn_allow_lpage(slot, gfn);
1184 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1185 struct kvm_memory_slot *slot)
1187 struct kvm_lpage_info *linfo;
1190 linfo = lpage_info_slot(gfn, slot, level);
1191 return !!linfo->disallow_lpage;
1197 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1200 struct kvm_memory_slot *slot;
1202 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1203 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1206 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1208 unsigned long page_size;
1211 page_size = kvm_host_page_size(kvm, gfn);
1213 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1214 if (page_size >= KVM_HPAGE_SIZE(i))
1223 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1226 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1228 if (no_dirty_log && slot->dirty_bitmap)
1234 static struct kvm_memory_slot *
1235 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1238 struct kvm_memory_slot *slot;
1240 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1241 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1247 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1248 bool *force_pt_level)
1250 int host_level, level, max_level;
1251 struct kvm_memory_slot *slot;
1253 if (unlikely(*force_pt_level))
1254 return PT_PAGE_TABLE_LEVEL;
1256 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1257 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1258 if (unlikely(*force_pt_level))
1259 return PT_PAGE_TABLE_LEVEL;
1261 host_level = host_mapping_level(vcpu->kvm, large_gfn);
1263 if (host_level == PT_PAGE_TABLE_LEVEL)
1266 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1268 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1269 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1276 * About rmap_head encoding:
1278 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1279 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1280 * pte_list_desc containing more mappings.
1284 * Returns the number of pointers in the rmap chain, not counting the new one.
1286 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1287 struct kvm_rmap_head *rmap_head)
1289 struct pte_list_desc *desc;
1292 if (!rmap_head->val) {
1293 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1294 rmap_head->val = (unsigned long)spte;
1295 } else if (!(rmap_head->val & 1)) {
1296 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1297 desc = mmu_alloc_pte_list_desc(vcpu);
1298 desc->sptes[0] = (u64 *)rmap_head->val;
1299 desc->sptes[1] = spte;
1300 rmap_head->val = (unsigned long)desc | 1;
1303 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1304 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1305 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1307 count += PTE_LIST_EXT;
1309 if (desc->sptes[PTE_LIST_EXT-1]) {
1310 desc->more = mmu_alloc_pte_list_desc(vcpu);
1313 for (i = 0; desc->sptes[i]; ++i)
1315 desc->sptes[i] = spte;
1321 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1322 struct pte_list_desc *desc, int i,
1323 struct pte_list_desc *prev_desc)
1327 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1329 desc->sptes[i] = desc->sptes[j];
1330 desc->sptes[j] = NULL;
1333 if (!prev_desc && !desc->more)
1334 rmap_head->val = (unsigned long)desc->sptes[0];
1337 prev_desc->more = desc->more;
1339 rmap_head->val = (unsigned long)desc->more | 1;
1340 mmu_free_pte_list_desc(desc);
1343 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1345 struct pte_list_desc *desc;
1346 struct pte_list_desc *prev_desc;
1349 if (!rmap_head->val) {
1350 pr_err("%s: %p 0->BUG\n", __func__, spte);
1352 } else if (!(rmap_head->val & 1)) {
1353 rmap_printk("%s: %p 1->0\n", __func__, spte);
1354 if ((u64 *)rmap_head->val != spte) {
1355 pr_err("%s: %p 1->BUG\n", __func__, spte);
1360 rmap_printk("%s: %p many->many\n", __func__, spte);
1361 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1364 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1365 if (desc->sptes[i] == spte) {
1366 pte_list_desc_remove_entry(rmap_head,
1367 desc, i, prev_desc);
1374 pr_err("%s: %p many->many\n", __func__, spte);
1379 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1381 mmu_spte_clear_track_bits(sptep);
1382 __pte_list_remove(sptep, rmap_head);
1385 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1386 struct kvm_memory_slot *slot)
1390 idx = gfn_to_index(gfn, slot->base_gfn, level);
1391 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1394 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1395 struct kvm_mmu_page *sp)
1397 struct kvm_memslots *slots;
1398 struct kvm_memory_slot *slot;
1400 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1401 slot = __gfn_to_memslot(slots, gfn);
1402 return __gfn_to_rmap(gfn, sp->role.level, slot);
1405 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1407 struct kvm_mmu_memory_cache *cache;
1409 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1410 return mmu_memory_cache_free_objects(cache);
1413 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1415 struct kvm_mmu_page *sp;
1416 struct kvm_rmap_head *rmap_head;
1418 sp = page_header(__pa(spte));
1419 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1420 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1421 return pte_list_add(vcpu, spte, rmap_head);
1424 static void rmap_remove(struct kvm *kvm, u64 *spte)
1426 struct kvm_mmu_page *sp;
1428 struct kvm_rmap_head *rmap_head;
1430 sp = page_header(__pa(spte));
1431 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1432 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1433 __pte_list_remove(spte, rmap_head);
1437 * Used by the following functions to iterate through the sptes linked by a
1438 * rmap. All fields are private and not assumed to be used outside.
1440 struct rmap_iterator {
1441 /* private fields */
1442 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1443 int pos; /* index of the sptep */
1447 * Iteration must be started by this function. This should also be used after
1448 * removing/dropping sptes from the rmap link because in such cases the
1449 * information in the itererator may not be valid.
1451 * Returns sptep if found, NULL otherwise.
1453 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1454 struct rmap_iterator *iter)
1458 if (!rmap_head->val)
1461 if (!(rmap_head->val & 1)) {
1463 sptep = (u64 *)rmap_head->val;
1467 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1469 sptep = iter->desc->sptes[iter->pos];
1471 BUG_ON(!is_shadow_present_pte(*sptep));
1476 * Must be used with a valid iterator: e.g. after rmap_get_first().
1478 * Returns sptep if found, NULL otherwise.
1480 static u64 *rmap_get_next(struct rmap_iterator *iter)
1485 if (iter->pos < PTE_LIST_EXT - 1) {
1487 sptep = iter->desc->sptes[iter->pos];
1492 iter->desc = iter->desc->more;
1496 /* desc->sptes[0] cannot be NULL */
1497 sptep = iter->desc->sptes[iter->pos];
1504 BUG_ON(!is_shadow_present_pte(*sptep));
1508 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1509 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1510 _spte_; _spte_ = rmap_get_next(_iter_))
1512 static void drop_spte(struct kvm *kvm, u64 *sptep)
1514 if (mmu_spte_clear_track_bits(sptep))
1515 rmap_remove(kvm, sptep);
1519 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1521 if (is_large_pte(*sptep)) {
1522 WARN_ON(page_header(__pa(sptep))->role.level ==
1523 PT_PAGE_TABLE_LEVEL);
1524 drop_spte(kvm, sptep);
1532 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1534 if (__drop_large_spte(vcpu->kvm, sptep)) {
1535 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1537 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1538 KVM_PAGES_PER_HPAGE(sp->role.level));
1543 * Write-protect on the specified @sptep, @pt_protect indicates whether
1544 * spte write-protection is caused by protecting shadow page table.
1546 * Note: write protection is difference between dirty logging and spte
1548 * - for dirty logging, the spte can be set to writable at anytime if
1549 * its dirty bitmap is properly set.
1550 * - for spte protection, the spte can be writable only after unsync-ing
1553 * Return true if tlb need be flushed.
1555 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1559 if (!is_writable_pte(spte) &&
1560 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1563 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1566 spte &= ~SPTE_MMU_WRITEABLE;
1567 spte = spte & ~PT_WRITABLE_MASK;
1569 return mmu_spte_update(sptep, spte);
1572 static bool __rmap_write_protect(struct kvm *kvm,
1573 struct kvm_rmap_head *rmap_head,
1577 struct rmap_iterator iter;
1580 for_each_rmap_spte(rmap_head, &iter, sptep)
1581 flush |= spte_write_protect(sptep, pt_protect);
1586 static bool spte_clear_dirty(u64 *sptep)
1590 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1592 spte &= ~shadow_dirty_mask;
1594 return mmu_spte_update(sptep, spte);
1597 static bool wrprot_ad_disabled_spte(u64 *sptep)
1599 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1600 (unsigned long *)sptep);
1602 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1604 return was_writable;
1608 * Gets the GFN ready for another round of dirty logging by clearing the
1609 * - D bit on ad-enabled SPTEs, and
1610 * - W bit on ad-disabled SPTEs.
1611 * Returns true iff any D or W bits were cleared.
1613 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1616 struct rmap_iterator iter;
1619 for_each_rmap_spte(rmap_head, &iter, sptep)
1620 if (spte_ad_enabled(*sptep))
1621 flush |= spte_clear_dirty(sptep);
1623 flush |= wrprot_ad_disabled_spte(sptep);
1628 static bool spte_set_dirty(u64 *sptep)
1632 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1634 spte |= shadow_dirty_mask;
1636 return mmu_spte_update(sptep, spte);
1639 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1642 struct rmap_iterator iter;
1645 for_each_rmap_spte(rmap_head, &iter, sptep)
1646 if (spte_ad_enabled(*sptep))
1647 flush |= spte_set_dirty(sptep);
1653 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1654 * @kvm: kvm instance
1655 * @slot: slot to protect
1656 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1657 * @mask: indicates which pages we should protect
1659 * Used when we do not need to care about huge page mappings: e.g. during dirty
1660 * logging we do not have any such mappings.
1662 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1663 struct kvm_memory_slot *slot,
1664 gfn_t gfn_offset, unsigned long mask)
1666 struct kvm_rmap_head *rmap_head;
1669 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1670 PT_PAGE_TABLE_LEVEL, slot);
1671 __rmap_write_protect(kvm, rmap_head, false);
1673 /* clear the first set bit */
1679 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1680 * protect the page if the D-bit isn't supported.
1681 * @kvm: kvm instance
1682 * @slot: slot to clear D-bit
1683 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1684 * @mask: indicates which pages we should clear D-bit
1686 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1688 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1689 struct kvm_memory_slot *slot,
1690 gfn_t gfn_offset, unsigned long mask)
1692 struct kvm_rmap_head *rmap_head;
1695 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1696 PT_PAGE_TABLE_LEVEL, slot);
1697 __rmap_clear_dirty(kvm, rmap_head);
1699 /* clear the first set bit */
1703 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1706 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1709 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1710 * enable dirty logging for them.
1712 * Used when we do not need to care about huge page mappings: e.g. during dirty
1713 * logging we do not have any such mappings.
1715 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1716 struct kvm_memory_slot *slot,
1717 gfn_t gfn_offset, unsigned long mask)
1719 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1720 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1723 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1727 * kvm_arch_write_log_dirty - emulate dirty page logging
1728 * @vcpu: Guest mode vcpu
1730 * Emulate arch specific page modification logging for the
1733 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1735 if (kvm_x86_ops->write_log_dirty)
1736 return kvm_x86_ops->write_log_dirty(vcpu);
1741 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1742 struct kvm_memory_slot *slot, u64 gfn)
1744 struct kvm_rmap_head *rmap_head;
1746 bool write_protected = false;
1748 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1749 rmap_head = __gfn_to_rmap(gfn, i, slot);
1750 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1753 return write_protected;
1756 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1758 struct kvm_memory_slot *slot;
1760 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1761 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1764 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1767 struct rmap_iterator iter;
1770 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1771 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1773 pte_list_remove(rmap_head, sptep);
1780 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1781 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1784 return kvm_zap_rmapp(kvm, rmap_head);
1787 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1788 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1792 struct rmap_iterator iter;
1795 pte_t *ptep = (pte_t *)data;
1798 WARN_ON(pte_huge(*ptep));
1799 new_pfn = pte_pfn(*ptep);
1802 for_each_rmap_spte(rmap_head, &iter, sptep) {
1803 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1804 sptep, *sptep, gfn, level);
1808 if (pte_write(*ptep)) {
1809 pte_list_remove(rmap_head, sptep);
1812 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1813 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1815 new_spte &= ~PT_WRITABLE_MASK;
1816 new_spte &= ~SPTE_HOST_WRITEABLE;
1818 new_spte = mark_spte_for_access_track(new_spte);
1820 mmu_spte_clear_track_bits(sptep);
1821 mmu_spte_set(sptep, new_spte);
1825 if (need_flush && kvm_available_flush_tlb_with_range()) {
1826 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
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)
1961 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1964 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1966 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1969 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1970 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1974 struct rmap_iterator uninitialized_var(iter);
1977 for_each_rmap_spte(rmap_head, &iter, sptep)
1978 young |= mmu_spte_age(sptep);
1980 trace_kvm_age_page(gfn, level, slot, young);
1984 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1985 struct kvm_memory_slot *slot, gfn_t gfn,
1986 int level, unsigned long data)
1989 struct rmap_iterator iter;
1991 for_each_rmap_spte(rmap_head, &iter, sptep)
1992 if (is_accessed_spte(*sptep))
1997 #define RMAP_RECYCLE_THRESHOLD 1000
1999 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2001 struct kvm_rmap_head *rmap_head;
2002 struct kvm_mmu_page *sp;
2004 sp = page_header(__pa(spte));
2006 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2008 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2009 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
2010 KVM_PAGES_PER_HPAGE(sp->role.level));
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, unsigned 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 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2101 * depends on valid pages being added to the head of the list. See
2102 * 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 bool 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 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2251 hlist_for_each_entry(_sp, \
2252 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2253 if (is_obsolete_sp((_kvm), (_sp))) { \
2256 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2257 for_each_valid_sp(_kvm, _sp, _gfn) \
2258 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2260 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2262 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2265 /* @sp->gfn should be write-protected at the call site */
2266 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2267 struct list_head *invalid_list)
2269 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2270 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2271 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2278 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2279 struct list_head *invalid_list,
2282 if (!remote_flush && list_empty(invalid_list))
2285 if (!list_empty(invalid_list))
2286 kvm_mmu_commit_zap_page(kvm, invalid_list);
2288 kvm_flush_remote_tlbs(kvm);
2292 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2293 struct list_head *invalid_list,
2294 bool remote_flush, bool local_flush)
2296 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2300 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2303 #ifdef CONFIG_KVM_MMU_AUDIT
2304 #include "mmu_audit.c"
2306 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2307 static void mmu_audit_disable(void) { }
2310 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2312 return sp->role.invalid ||
2313 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2316 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2317 struct list_head *invalid_list)
2319 kvm_unlink_unsync_page(vcpu->kvm, sp);
2320 return __kvm_sync_page(vcpu, sp, invalid_list);
2323 /* @gfn should be write-protected at the call site */
2324 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2325 struct list_head *invalid_list)
2327 struct kvm_mmu_page *s;
2330 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2334 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2335 ret |= kvm_sync_page(vcpu, s, invalid_list);
2341 struct mmu_page_path {
2342 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2343 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2346 #define for_each_sp(pvec, sp, parents, i) \
2347 for (i = mmu_pages_first(&pvec, &parents); \
2348 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2349 i = mmu_pages_next(&pvec, &parents, i))
2351 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2352 struct mmu_page_path *parents,
2357 for (n = i+1; n < pvec->nr; n++) {
2358 struct kvm_mmu_page *sp = pvec->page[n].sp;
2359 unsigned idx = pvec->page[n].idx;
2360 int level = sp->role.level;
2362 parents->idx[level-1] = idx;
2363 if (level == PT_PAGE_TABLE_LEVEL)
2366 parents->parent[level-2] = sp;
2372 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2373 struct mmu_page_path *parents)
2375 struct kvm_mmu_page *sp;
2381 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2383 sp = pvec->page[0].sp;
2384 level = sp->role.level;
2385 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2387 parents->parent[level-2] = sp;
2389 /* Also set up a sentinel. Further entries in pvec are all
2390 * children of sp, so this element is never overwritten.
2392 parents->parent[level-1] = NULL;
2393 return mmu_pages_next(pvec, parents, 0);
2396 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2398 struct kvm_mmu_page *sp;
2399 unsigned int level = 0;
2402 unsigned int idx = parents->idx[level];
2403 sp = parents->parent[level];
2407 WARN_ON(idx == INVALID_INDEX);
2408 clear_unsync_child_bit(sp, idx);
2410 } while (!sp->unsync_children);
2413 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2414 struct kvm_mmu_page *parent)
2417 struct kvm_mmu_page *sp;
2418 struct mmu_page_path parents;
2419 struct kvm_mmu_pages pages;
2420 LIST_HEAD(invalid_list);
2423 while (mmu_unsync_walk(parent, &pages)) {
2424 bool protected = false;
2426 for_each_sp(pages, sp, parents, i)
2427 protected |= rmap_write_protect(vcpu, sp->gfn);
2430 kvm_flush_remote_tlbs(vcpu->kvm);
2434 for_each_sp(pages, sp, parents, i) {
2435 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2436 mmu_pages_clear_parents(&parents);
2438 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2439 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2440 cond_resched_lock(&vcpu->kvm->mmu_lock);
2445 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2448 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2450 atomic_set(&sp->write_flooding_count, 0);
2453 static void clear_sp_write_flooding_count(u64 *spte)
2455 struct kvm_mmu_page *sp = page_header(__pa(spte));
2457 __clear_sp_write_flooding_count(sp);
2460 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2467 union kvm_mmu_page_role role;
2469 struct kvm_mmu_page *sp;
2470 bool need_sync = false;
2473 LIST_HEAD(invalid_list);
2475 role = vcpu->arch.mmu->mmu_role.base;
2477 role.direct = direct;
2479 role.gpte_is_8_bytes = true;
2480 role.access = access;
2481 if (!vcpu->arch.mmu->direct_map
2482 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2483 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2484 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2485 role.quadrant = quadrant;
2487 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2488 if (sp->gfn != gfn) {
2493 if (!need_sync && sp->unsync)
2496 if (sp->role.word != role.word)
2500 /* The page is good, but __kvm_sync_page might still end
2501 * up zapping it. If so, break in order to rebuild it.
2503 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2506 WARN_ON(!list_empty(&invalid_list));
2507 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2510 if (sp->unsync_children)
2511 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2513 __clear_sp_write_flooding_count(sp);
2514 trace_kvm_mmu_get_page(sp, false);
2518 ++vcpu->kvm->stat.mmu_cache_miss;
2520 sp = kvm_mmu_alloc_page(vcpu, direct);
2524 hlist_add_head(&sp->hash_link,
2525 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2528 * we should do write protection before syncing pages
2529 * otherwise the content of the synced shadow page may
2530 * be inconsistent with guest page table.
2532 account_shadowed(vcpu->kvm, sp);
2533 if (level == PT_PAGE_TABLE_LEVEL &&
2534 rmap_write_protect(vcpu, gfn))
2535 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2537 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2538 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2540 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2541 clear_page(sp->spt);
2542 trace_kvm_mmu_get_page(sp, true);
2544 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2546 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2547 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2551 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2552 struct kvm_vcpu *vcpu, hpa_t root,
2555 iterator->addr = addr;
2556 iterator->shadow_addr = root;
2557 iterator->level = vcpu->arch.mmu->shadow_root_level;
2559 if (iterator->level == PT64_ROOT_4LEVEL &&
2560 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2561 !vcpu->arch.mmu->direct_map)
2564 if (iterator->level == PT32E_ROOT_LEVEL) {
2566 * prev_root is currently only used for 64-bit hosts. So only
2567 * the active root_hpa is valid here.
2569 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2571 iterator->shadow_addr
2572 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2573 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2575 if (!iterator->shadow_addr)
2576 iterator->level = 0;
2580 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2581 struct kvm_vcpu *vcpu, u64 addr)
2583 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2587 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2589 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2592 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2593 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2597 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2600 if (is_last_spte(spte, iterator->level)) {
2601 iterator->level = 0;
2605 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2609 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2611 __shadow_walk_next(iterator, *iterator->sptep);
2614 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2615 struct kvm_mmu_page *sp)
2619 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2621 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2622 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2624 if (sp_ad_disabled(sp))
2625 spte |= shadow_acc_track_value;
2627 spte |= shadow_accessed_mask;
2629 mmu_spte_set(sptep, spte);
2631 mmu_page_add_parent_pte(vcpu, sp, sptep);
2633 if (sp->unsync_children || sp->unsync)
2637 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2638 unsigned direct_access)
2640 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2641 struct kvm_mmu_page *child;
2644 * For the direct sp, if the guest pte's dirty bit
2645 * changed form clean to dirty, it will corrupt the
2646 * sp's access: allow writable in the read-only sp,
2647 * so we should update the spte at this point to get
2648 * a new sp with the correct access.
2650 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2651 if (child->role.access == direct_access)
2654 drop_parent_pte(child, sptep);
2655 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2659 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2663 struct kvm_mmu_page *child;
2666 if (is_shadow_present_pte(pte)) {
2667 if (is_last_spte(pte, sp->role.level)) {
2668 drop_spte(kvm, spte);
2669 if (is_large_pte(pte))
2672 child = page_header(pte & PT64_BASE_ADDR_MASK);
2673 drop_parent_pte(child, spte);
2678 if (is_mmio_spte(pte))
2679 mmu_spte_clear_no_track(spte);
2684 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2685 struct kvm_mmu_page *sp)
2689 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2690 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2693 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2696 struct rmap_iterator iter;
2698 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2699 drop_parent_pte(sp, sptep);
2702 static int mmu_zap_unsync_children(struct kvm *kvm,
2703 struct kvm_mmu_page *parent,
2704 struct list_head *invalid_list)
2707 struct mmu_page_path parents;
2708 struct kvm_mmu_pages pages;
2710 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2713 while (mmu_unsync_walk(parent, &pages)) {
2714 struct kvm_mmu_page *sp;
2716 for_each_sp(pages, sp, parents, i) {
2717 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2718 mmu_pages_clear_parents(&parents);
2726 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2727 struct kvm_mmu_page *sp,
2728 struct list_head *invalid_list,
2733 trace_kvm_mmu_prepare_zap_page(sp);
2734 ++kvm->stat.mmu_shadow_zapped;
2735 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2736 kvm_mmu_page_unlink_children(kvm, sp);
2737 kvm_mmu_unlink_parents(kvm, sp);
2739 /* Zapping children means active_mmu_pages has become unstable. */
2740 list_unstable = *nr_zapped;
2742 if (!sp->role.invalid && !sp->role.direct)
2743 unaccount_shadowed(kvm, sp);
2746 kvm_unlink_unsync_page(kvm, sp);
2747 if (!sp->root_count) {
2750 list_move(&sp->link, invalid_list);
2751 kvm_mod_used_mmu_pages(kvm, -1);
2753 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2755 if (!sp->role.invalid)
2756 kvm_reload_remote_mmus(kvm);
2759 sp->role.invalid = 1;
2760 return list_unstable;
2763 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2764 struct list_head *invalid_list)
2768 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2772 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2773 struct list_head *invalid_list)
2775 struct kvm_mmu_page *sp, *nsp;
2777 if (list_empty(invalid_list))
2781 * We need to make sure everyone sees our modifications to
2782 * the page tables and see changes to vcpu->mode here. The barrier
2783 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2784 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2786 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2787 * guest mode and/or lockless shadow page table walks.
2789 kvm_flush_remote_tlbs(kvm);
2791 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2792 WARN_ON(!sp->role.invalid || sp->root_count);
2793 kvm_mmu_free_page(sp);
2797 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2798 struct list_head *invalid_list)
2800 struct kvm_mmu_page *sp;
2802 if (list_empty(&kvm->arch.active_mmu_pages))
2805 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2806 struct kvm_mmu_page, link);
2807 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2811 * Changing the number of mmu pages allocated to the vm
2812 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2814 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2816 LIST_HEAD(invalid_list);
2818 spin_lock(&kvm->mmu_lock);
2820 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2821 /* Need to free some mmu pages to achieve the goal. */
2822 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2823 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2826 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2827 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2830 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2832 spin_unlock(&kvm->mmu_lock);
2835 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2837 struct kvm_mmu_page *sp;
2838 LIST_HEAD(invalid_list);
2841 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2843 spin_lock(&kvm->mmu_lock);
2844 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2845 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2848 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2850 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2851 spin_unlock(&kvm->mmu_lock);
2855 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2857 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2859 trace_kvm_mmu_unsync_page(sp);
2860 ++vcpu->kvm->stat.mmu_unsync;
2863 kvm_mmu_mark_parents_unsync(sp);
2866 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2869 struct kvm_mmu_page *sp;
2871 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2874 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2881 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2882 kvm_unsync_page(vcpu, sp);
2886 * We need to ensure that the marking of unsync pages is visible
2887 * before the SPTE is updated to allow writes because
2888 * kvm_mmu_sync_roots() checks the unsync flags without holding
2889 * the MMU lock and so can race with this. If the SPTE was updated
2890 * before the page had been marked as unsync-ed, something like the
2891 * following could happen:
2894 * ---------------------------------------------------------------------
2895 * 1.2 Host updates SPTE
2897 * 2.1 Guest writes a GPTE for GVA X.
2898 * (GPTE being in the guest page table shadowed
2899 * by the SP from CPU 1.)
2900 * This reads SPTE during the page table walk.
2901 * Since SPTE.W is read as 1, there is no
2904 * 2.2 Guest issues TLB flush.
2905 * That causes a VM Exit.
2907 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2908 * Since it is false, so it just returns.
2910 * 2.4 Guest accesses GVA X.
2911 * Since the mapping in the SP was not updated,
2912 * so the old mapping for GVA X incorrectly
2916 * (sp->unsync = true)
2918 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2919 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2920 * pairs with this write barrier.
2927 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2930 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2932 * Some reserved pages, such as those from NVDIMM
2933 * DAX devices, are not for MMIO, and can be mapped
2934 * with cached memory type for better performance.
2935 * However, the above check misconceives those pages
2936 * as MMIO, and results in KVM mapping them with UC
2937 * memory type, which would hurt the performance.
2938 * Therefore, we check the host memory type in addition
2939 * and only treat UC/UC-/WC pages as MMIO.
2941 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2943 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2944 pfn_to_hpa(pfn + 1) - 1,
2948 /* Bits which may be returned by set_spte() */
2949 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2950 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2952 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2953 unsigned pte_access, int level,
2954 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2955 bool can_unsync, bool host_writable)
2959 struct kvm_mmu_page *sp;
2961 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2964 sp = page_header(__pa(sptep));
2965 if (sp_ad_disabled(sp))
2966 spte |= shadow_acc_track_value;
2969 * For the EPT case, shadow_present_mask is 0 if hardware
2970 * supports exec-only page table entries. In that case,
2971 * ACC_USER_MASK and shadow_user_mask are used to represent
2972 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2974 spte |= shadow_present_mask;
2976 spte |= spte_shadow_accessed_mask(spte);
2978 if (pte_access & ACC_EXEC_MASK)
2979 spte |= shadow_x_mask;
2981 spte |= shadow_nx_mask;
2983 if (pte_access & ACC_USER_MASK)
2984 spte |= shadow_user_mask;
2986 if (level > PT_PAGE_TABLE_LEVEL)
2987 spte |= PT_PAGE_SIZE_MASK;
2989 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2990 kvm_is_mmio_pfn(pfn));
2993 spte |= SPTE_HOST_WRITEABLE;
2995 pte_access &= ~ACC_WRITE_MASK;
2997 if (!kvm_is_mmio_pfn(pfn))
2998 spte |= shadow_me_mask;
3000 spte |= (u64)pfn << PAGE_SHIFT;
3002 if (pte_access & ACC_WRITE_MASK) {
3005 * Other vcpu creates new sp in the window between
3006 * mapping_level() and acquiring mmu-lock. We can
3007 * allow guest to retry the access, the mapping can
3008 * be fixed if guest refault.
3010 if (level > PT_PAGE_TABLE_LEVEL &&
3011 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3014 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3017 * Optimization: for pte sync, if spte was writable the hash
3018 * lookup is unnecessary (and expensive). Write protection
3019 * is responsibility of mmu_get_page / kvm_sync_page.
3020 * Same reasoning can be applied to dirty page accounting.
3022 if (!can_unsync && is_writable_pte(*sptep))
3025 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3026 pgprintk("%s: found shadow page for %llx, marking ro\n",
3028 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3029 pte_access &= ~ACC_WRITE_MASK;
3030 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3034 if (pte_access & ACC_WRITE_MASK) {
3035 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3036 spte |= spte_shadow_dirty_mask(spte);
3040 spte = mark_spte_for_access_track(spte);
3043 if (mmu_spte_update(sptep, spte))
3044 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3049 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3050 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3051 bool speculative, bool host_writable)
3053 int was_rmapped = 0;
3056 int ret = RET_PF_RETRY;
3059 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3060 *sptep, write_fault, gfn);
3062 if (is_shadow_present_pte(*sptep)) {
3064 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3065 * the parent of the now unreachable PTE.
3067 if (level > PT_PAGE_TABLE_LEVEL &&
3068 !is_large_pte(*sptep)) {
3069 struct kvm_mmu_page *child;
3072 child = page_header(pte & PT64_BASE_ADDR_MASK);
3073 drop_parent_pte(child, sptep);
3075 } else if (pfn != spte_to_pfn(*sptep)) {
3076 pgprintk("hfn old %llx new %llx\n",
3077 spte_to_pfn(*sptep), pfn);
3078 drop_spte(vcpu->kvm, sptep);
3084 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3085 speculative, true, host_writable);
3086 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3088 ret = RET_PF_EMULATE;
3089 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3092 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3093 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3094 KVM_PAGES_PER_HPAGE(level));
3096 if (unlikely(is_mmio_spte(*sptep)))
3097 ret = RET_PF_EMULATE;
3099 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3100 trace_kvm_mmu_set_spte(level, gfn, sptep);
3101 if (!was_rmapped && is_large_pte(*sptep))
3102 ++vcpu->kvm->stat.lpages;
3104 if (is_shadow_present_pte(*sptep)) {
3106 rmap_count = rmap_add(vcpu, sptep, gfn);
3107 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3108 rmap_recycle(vcpu, sptep, gfn);
3115 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3118 struct kvm_memory_slot *slot;
3120 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3122 return KVM_PFN_ERR_FAULT;
3124 return gfn_to_pfn_memslot_atomic(slot, gfn);
3127 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3128 struct kvm_mmu_page *sp,
3129 u64 *start, u64 *end)
3131 struct page *pages[PTE_PREFETCH_NUM];
3132 struct kvm_memory_slot *slot;
3133 unsigned access = sp->role.access;
3137 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3138 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3142 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3146 for (i = 0; i < ret; i++, gfn++, start++) {
3147 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3148 page_to_pfn(pages[i]), true, true);
3155 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3156 struct kvm_mmu_page *sp, u64 *sptep)
3158 u64 *spte, *start = NULL;
3161 WARN_ON(!sp->role.direct);
3163 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3166 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3167 if (is_shadow_present_pte(*spte) || spte == sptep) {
3170 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3178 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3180 struct kvm_mmu_page *sp;
3182 sp = page_header(__pa(sptep));
3185 * Without accessed bits, there's no way to distinguish between
3186 * actually accessed translations and prefetched, so disable pte
3187 * prefetch if accessed bits aren't available.
3189 if (sp_ad_disabled(sp))
3192 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3195 __direct_pte_prefetch(vcpu, sp, sptep);
3198 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3199 int map_writable, int level, kvm_pfn_t pfn,
3202 struct kvm_shadow_walk_iterator it;
3203 struct kvm_mmu_page *sp;
3205 gfn_t gfn = gpa >> PAGE_SHIFT;
3206 gfn_t base_gfn = gfn;
3208 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3209 return RET_PF_RETRY;
3211 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3212 for_each_shadow_entry(vcpu, gpa, it) {
3213 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3214 if (it.level == level)
3217 drop_large_spte(vcpu, it.sptep);
3218 if (!is_shadow_present_pte(*it.sptep)) {
3219 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3220 it.level - 1, true, ACC_ALL);
3222 link_shadow_page(vcpu, it.sptep, sp);
3226 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3227 write, level, base_gfn, pfn, prefault,
3229 direct_pte_prefetch(vcpu, it.sptep);
3230 ++vcpu->stat.pf_fixed;
3234 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3236 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3239 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3242 * Do not cache the mmio info caused by writing the readonly gfn
3243 * into the spte otherwise read access on readonly gfn also can
3244 * caused mmio page fault and treat it as mmio access.
3246 if (pfn == KVM_PFN_ERR_RO_FAULT)
3247 return RET_PF_EMULATE;
3249 if (pfn == KVM_PFN_ERR_HWPOISON) {
3250 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3251 return RET_PF_RETRY;
3257 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3258 gfn_t gfn, kvm_pfn_t *pfnp,
3261 kvm_pfn_t pfn = *pfnp;
3262 int level = *levelp;
3265 * Check if it's a transparent hugepage. If this would be an
3266 * hugetlbfs page, level wouldn't be set to
3267 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3270 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3271 level == PT_PAGE_TABLE_LEVEL &&
3272 PageTransCompoundMap(pfn_to_page(pfn)) &&
3273 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3276 * mmu_notifier_retry was successful and we hold the
3277 * mmu_lock here, so the pmd can't become splitting
3278 * from under us, and in turn
3279 * __split_huge_page_refcount() can't run from under
3280 * us and we can safely transfer the refcount from
3281 * PG_tail to PG_head as we switch the pfn to tail to
3284 *levelp = level = PT_DIRECTORY_LEVEL;
3285 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3286 VM_BUG_ON((gfn & mask) != (pfn & mask));
3288 kvm_release_pfn_clean(pfn);
3296 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3297 kvm_pfn_t pfn, unsigned access, int *ret_val)
3299 /* The pfn is invalid, report the error! */
3300 if (unlikely(is_error_pfn(pfn))) {
3301 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3305 if (unlikely(is_noslot_pfn(pfn)))
3306 vcpu_cache_mmio_info(vcpu, gva, gfn,
3307 access & shadow_mmio_access_mask);
3312 static bool page_fault_can_be_fast(u32 error_code)
3315 * Do not fix the mmio spte with invalid generation number which
3316 * need to be updated by slow page fault path.
3318 if (unlikely(error_code & PFERR_RSVD_MASK))
3321 /* See if the page fault is due to an NX violation */
3322 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3323 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3327 * #PF can be fast if:
3328 * 1. The shadow page table entry is not present, which could mean that
3329 * the fault is potentially caused by access tracking (if enabled).
3330 * 2. The shadow page table entry is present and the fault
3331 * is caused by write-protect, that means we just need change the W
3332 * bit of the spte which can be done out of mmu-lock.
3334 * However, if access tracking is disabled we know that a non-present
3335 * page must be a genuine page fault where we have to create a new SPTE.
3336 * So, if access tracking is disabled, we return true only for write
3337 * accesses to a present page.
3340 return shadow_acc_track_mask != 0 ||
3341 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3342 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3346 * Returns true if the SPTE was fixed successfully. Otherwise,
3347 * someone else modified the SPTE from its original value.
3350 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3351 u64 *sptep, u64 old_spte, u64 new_spte)
3355 WARN_ON(!sp->role.direct);
3358 * Theoretically we could also set dirty bit (and flush TLB) here in
3359 * order to eliminate unnecessary PML logging. See comments in
3360 * set_spte. But fast_page_fault is very unlikely to happen with PML
3361 * enabled, so we do not do this. This might result in the same GPA
3362 * to be logged in PML buffer again when the write really happens, and
3363 * eventually to be called by mark_page_dirty twice. But it's also no
3364 * harm. This also avoids the TLB flush needed after setting dirty bit
3365 * so non-PML cases won't be impacted.
3367 * Compare with set_spte where instead shadow_dirty_mask is set.
3369 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3372 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3374 * The gfn of direct spte is stable since it is
3375 * calculated by sp->gfn.
3377 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3378 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3384 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3386 if (fault_err_code & PFERR_FETCH_MASK)
3387 return is_executable_pte(spte);
3389 if (fault_err_code & PFERR_WRITE_MASK)
3390 return is_writable_pte(spte);
3392 /* Fault was on Read access */
3393 return spte & PT_PRESENT_MASK;
3398 * - true: let the vcpu to access on the same address again.
3399 * - false: let the real page fault path to fix it.
3401 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3404 struct kvm_shadow_walk_iterator iterator;
3405 struct kvm_mmu_page *sp;
3406 bool fault_handled = false;
3408 uint retry_count = 0;
3410 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3413 if (!page_fault_can_be_fast(error_code))
3416 walk_shadow_page_lockless_begin(vcpu);
3421 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3422 if (!is_shadow_present_pte(spte) ||
3423 iterator.level < level)
3426 sp = page_header(__pa(iterator.sptep));
3427 if (!is_last_spte(spte, sp->role.level))
3431 * Check whether the memory access that caused the fault would
3432 * still cause it if it were to be performed right now. If not,
3433 * then this is a spurious fault caused by TLB lazily flushed,
3434 * or some other CPU has already fixed the PTE after the
3435 * current CPU took the fault.
3437 * Need not check the access of upper level table entries since
3438 * they are always ACC_ALL.
3440 if (is_access_allowed(error_code, spte)) {
3441 fault_handled = true;
3447 if (is_access_track_spte(spte))
3448 new_spte = restore_acc_track_spte(new_spte);
3451 * Currently, to simplify the code, write-protection can
3452 * be removed in the fast path only if the SPTE was
3453 * write-protected for dirty-logging or access tracking.
3455 if ((error_code & PFERR_WRITE_MASK) &&
3456 spte_can_locklessly_be_made_writable(spte))
3458 new_spte |= PT_WRITABLE_MASK;
3461 * Do not fix write-permission on the large spte. Since
3462 * we only dirty the first page into the dirty-bitmap in
3463 * fast_pf_fix_direct_spte(), other pages are missed
3464 * if its slot has dirty logging enabled.
3466 * Instead, we let the slow page fault path create a
3467 * normal spte to fix the access.
3469 * See the comments in kvm_arch_commit_memory_region().
3471 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3475 /* Verify that the fault can be handled in the fast path */
3476 if (new_spte == spte ||
3477 !is_access_allowed(error_code, new_spte))
3481 * Currently, fast page fault only works for direct mapping
3482 * since the gfn is not stable for indirect shadow page. See
3483 * Documentation/virt/kvm/locking.txt to get more detail.
3485 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3486 iterator.sptep, spte,
3491 if (++retry_count > 4) {
3492 printk_once(KERN_WARNING
3493 "kvm: Fast #PF retrying more than 4 times.\n");
3499 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3500 spte, fault_handled);
3501 walk_shadow_page_lockless_end(vcpu);
3503 return fault_handled;
3506 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3507 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3508 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3510 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3511 gfn_t gfn, bool prefault)
3515 bool force_pt_level = false;
3517 unsigned long mmu_seq;
3518 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3520 level = mapping_level(vcpu, gfn, &force_pt_level);
3521 if (likely(!force_pt_level)) {
3523 * This path builds a PAE pagetable - so we can map
3524 * 2mb pages at maximum. Therefore check if the level
3525 * is larger than that.
3527 if (level > PT_DIRECTORY_LEVEL)
3528 level = PT_DIRECTORY_LEVEL;
3530 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3533 if (fast_page_fault(vcpu, v, level, error_code))
3534 return RET_PF_RETRY;
3536 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3539 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3540 return RET_PF_RETRY;
3542 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3546 spin_lock(&vcpu->kvm->mmu_lock);
3547 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3549 if (make_mmu_pages_available(vcpu) < 0)
3551 if (likely(!force_pt_level))
3552 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3553 r = __direct_map(vcpu, v, write, map_writable, level, pfn, prefault);
3555 spin_unlock(&vcpu->kvm->mmu_lock);
3556 kvm_release_pfn_clean(pfn);
3560 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3561 struct list_head *invalid_list)
3563 struct kvm_mmu_page *sp;
3565 if (!VALID_PAGE(*root_hpa))
3568 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3570 if (!sp->root_count && sp->role.invalid)
3571 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3573 *root_hpa = INVALID_PAGE;
3576 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3577 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3578 ulong roots_to_free)
3581 LIST_HEAD(invalid_list);
3582 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3584 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3586 /* Before acquiring the MMU lock, see if we need to do any real work. */
3587 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3588 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3589 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3590 VALID_PAGE(mmu->prev_roots[i].hpa))
3593 if (i == KVM_MMU_NUM_PREV_ROOTS)
3597 spin_lock(&vcpu->kvm->mmu_lock);
3599 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3600 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3601 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3604 if (free_active_root) {
3605 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3606 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3607 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3610 for (i = 0; i < 4; ++i)
3611 if (mmu->pae_root[i] != 0)
3612 mmu_free_root_page(vcpu->kvm,
3615 mmu->root_hpa = INVALID_PAGE;
3620 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3621 spin_unlock(&vcpu->kvm->mmu_lock);
3623 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3625 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3629 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3630 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3637 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3639 struct kvm_mmu_page *sp;
3642 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3643 spin_lock(&vcpu->kvm->mmu_lock);
3644 if(make_mmu_pages_available(vcpu) < 0) {
3645 spin_unlock(&vcpu->kvm->mmu_lock);
3648 sp = kvm_mmu_get_page(vcpu, 0, 0,
3649 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3651 spin_unlock(&vcpu->kvm->mmu_lock);
3652 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3653 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3654 for (i = 0; i < 4; ++i) {
3655 hpa_t root = vcpu->arch.mmu->pae_root[i];
3657 MMU_WARN_ON(VALID_PAGE(root));
3658 spin_lock(&vcpu->kvm->mmu_lock);
3659 if (make_mmu_pages_available(vcpu) < 0) {
3660 spin_unlock(&vcpu->kvm->mmu_lock);
3663 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3664 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3665 root = __pa(sp->spt);
3667 spin_unlock(&vcpu->kvm->mmu_lock);
3668 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3670 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3673 vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3678 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3680 struct kvm_mmu_page *sp;
3682 gfn_t root_gfn, root_cr3;
3685 root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3686 root_gfn = root_cr3 >> PAGE_SHIFT;
3688 if (mmu_check_root(vcpu, root_gfn))
3692 * Do we shadow a long mode page table? If so we need to
3693 * write-protect the guests page table root.
3695 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3696 hpa_t root = vcpu->arch.mmu->root_hpa;
3698 MMU_WARN_ON(VALID_PAGE(root));
3700 spin_lock(&vcpu->kvm->mmu_lock);
3701 if (make_mmu_pages_available(vcpu) < 0) {
3702 spin_unlock(&vcpu->kvm->mmu_lock);
3705 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3706 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3707 root = __pa(sp->spt);
3709 spin_unlock(&vcpu->kvm->mmu_lock);
3710 vcpu->arch.mmu->root_hpa = root;
3715 * We shadow a 32 bit page table. This may be a legacy 2-level
3716 * or a PAE 3-level page table. In either case we need to be aware that
3717 * the shadow page table may be a PAE or a long mode page table.
3719 pm_mask = PT_PRESENT_MASK;
3720 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3721 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3723 for (i = 0; i < 4; ++i) {
3724 hpa_t root = vcpu->arch.mmu->pae_root[i];
3726 MMU_WARN_ON(VALID_PAGE(root));
3727 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3728 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3729 if (!(pdptr & PT_PRESENT_MASK)) {
3730 vcpu->arch.mmu->pae_root[i] = 0;
3733 root_gfn = pdptr >> PAGE_SHIFT;
3734 if (mmu_check_root(vcpu, root_gfn))
3737 spin_lock(&vcpu->kvm->mmu_lock);
3738 if (make_mmu_pages_available(vcpu) < 0) {
3739 spin_unlock(&vcpu->kvm->mmu_lock);
3742 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3744 root = __pa(sp->spt);
3746 spin_unlock(&vcpu->kvm->mmu_lock);
3748 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3750 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3753 * If we shadow a 32 bit page table with a long mode page
3754 * table we enter this path.
3756 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3757 if (vcpu->arch.mmu->lm_root == NULL) {
3759 * The additional page necessary for this is only
3760 * allocated on demand.
3765 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3766 if (lm_root == NULL)
3769 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3771 vcpu->arch.mmu->lm_root = lm_root;
3774 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3778 vcpu->arch.mmu->root_cr3 = root_cr3;
3783 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3785 if (vcpu->arch.mmu->direct_map)
3786 return mmu_alloc_direct_roots(vcpu);
3788 return mmu_alloc_shadow_roots(vcpu);
3791 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3794 struct kvm_mmu_page *sp;
3796 if (vcpu->arch.mmu->direct_map)
3799 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3802 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3804 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3805 hpa_t root = vcpu->arch.mmu->root_hpa;
3806 sp = page_header(root);
3809 * Even if another CPU was marking the SP as unsync-ed
3810 * simultaneously, any guest page table changes are not
3811 * guaranteed to be visible anyway until this VCPU issues a TLB
3812 * flush strictly after those changes are made. We only need to
3813 * ensure that the other CPU sets these flags before any actual
3814 * changes to the page tables are made. The comments in
3815 * mmu_need_write_protect() describe what could go wrong if this
3816 * requirement isn't satisfied.
3818 if (!smp_load_acquire(&sp->unsync) &&
3819 !smp_load_acquire(&sp->unsync_children))
3822 spin_lock(&vcpu->kvm->mmu_lock);
3823 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3825 mmu_sync_children(vcpu, sp);
3827 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3828 spin_unlock(&vcpu->kvm->mmu_lock);
3832 spin_lock(&vcpu->kvm->mmu_lock);
3833 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3835 for (i = 0; i < 4; ++i) {
3836 hpa_t root = vcpu->arch.mmu->pae_root[i];
3838 if (root && VALID_PAGE(root)) {
3839 root &= PT64_BASE_ADDR_MASK;
3840 sp = page_header(root);
3841 mmu_sync_children(vcpu, sp);
3845 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3846 spin_unlock(&vcpu->kvm->mmu_lock);
3848 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3850 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3851 u32 access, struct x86_exception *exception)
3854 exception->error_code = 0;
3858 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3860 struct x86_exception *exception)
3863 exception->error_code = 0;
3864 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3868 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3870 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3872 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3873 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3876 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3878 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3881 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3883 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3886 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3889 * A nested guest cannot use the MMIO cache if it is using nested
3890 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3892 if (mmu_is_nested(vcpu))
3896 return vcpu_match_mmio_gpa(vcpu, addr);
3898 return vcpu_match_mmio_gva(vcpu, addr);
3901 /* return true if reserved bit is detected on spte. */
3903 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3905 struct kvm_shadow_walk_iterator iterator;
3906 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3908 bool reserved = false;
3910 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3913 walk_shadow_page_lockless_begin(vcpu);
3915 for (shadow_walk_init(&iterator, vcpu, addr),
3916 leaf = root = iterator.level;
3917 shadow_walk_okay(&iterator);
3918 __shadow_walk_next(&iterator, spte)) {
3919 spte = mmu_spte_get_lockless(iterator.sptep);
3921 sptes[leaf - 1] = spte;
3924 if (!is_shadow_present_pte(spte))
3927 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3931 walk_shadow_page_lockless_end(vcpu);
3934 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3936 while (root > leaf) {
3937 pr_err("------ spte 0x%llx level %d.\n",
3938 sptes[root - 1], root);
3947 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3952 if (mmio_info_in_cache(vcpu, addr, direct))
3953 return RET_PF_EMULATE;
3955 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3956 if (WARN_ON(reserved))
3959 if (is_mmio_spte(spte)) {
3960 gfn_t gfn = get_mmio_spte_gfn(spte);
3961 unsigned access = get_mmio_spte_access(spte);
3963 if (!check_mmio_spte(vcpu, spte))
3964 return RET_PF_INVALID;
3969 trace_handle_mmio_page_fault(addr, gfn, access);
3970 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3971 return RET_PF_EMULATE;
3975 * If the page table is zapped by other cpus, let CPU fault again on
3978 return RET_PF_RETRY;
3981 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3982 u32 error_code, gfn_t gfn)
3984 if (unlikely(error_code & PFERR_RSVD_MASK))
3987 if (!(error_code & PFERR_PRESENT_MASK) ||
3988 !(error_code & PFERR_WRITE_MASK))
3992 * guest is writing the page which is write tracked which can
3993 * not be fixed by page fault handler.
3995 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4001 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4003 struct kvm_shadow_walk_iterator iterator;
4006 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
4009 walk_shadow_page_lockless_begin(vcpu);
4010 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4011 clear_sp_write_flooding_count(iterator.sptep);
4012 if (!is_shadow_present_pte(spte))
4015 walk_shadow_page_lockless_end(vcpu);
4018 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
4019 u32 error_code, bool prefault)
4021 gfn_t gfn = gva >> PAGE_SHIFT;
4024 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
4026 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4027 return RET_PF_EMULATE;
4029 r = mmu_topup_memory_caches(vcpu);
4033 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4036 return nonpaging_map(vcpu, gva & PAGE_MASK,
4037 error_code, gfn, prefault);
4040 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
4042 struct kvm_arch_async_pf arch;
4044 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4046 arch.direct_map = vcpu->arch.mmu->direct_map;
4047 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4049 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4052 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4053 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4055 struct kvm_memory_slot *slot;
4059 * Don't expose private memslots to L2.
4061 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4062 *pfn = KVM_PFN_NOSLOT;
4066 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4068 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4070 return false; /* *pfn has correct page already */
4072 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4073 trace_kvm_try_async_get_page(gva, gfn);
4074 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4075 trace_kvm_async_pf_doublefault(gva, gfn);
4076 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4078 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4082 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4086 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4087 u64 fault_address, char *insn, int insn_len)
4091 vcpu->arch.l1tf_flush_l1d = true;
4092 switch (vcpu->arch.apf.host_apf_reason) {
4094 trace_kvm_page_fault(fault_address, error_code);
4096 if (kvm_event_needs_reinjection(vcpu))
4097 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4098 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4101 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4102 vcpu->arch.apf.host_apf_reason = 0;
4103 local_irq_disable();
4104 kvm_async_pf_task_wait(fault_address, 0);
4107 case KVM_PV_REASON_PAGE_READY:
4108 vcpu->arch.apf.host_apf_reason = 0;
4109 local_irq_disable();
4110 kvm_async_pf_task_wake(fault_address);
4116 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4119 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4121 int page_num = KVM_PAGES_PER_HPAGE(level);
4123 gfn &= ~(page_num - 1);
4125 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4128 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4134 bool force_pt_level;
4135 gfn_t gfn = gpa >> PAGE_SHIFT;
4136 unsigned long mmu_seq;
4137 int write = error_code & PFERR_WRITE_MASK;
4140 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4142 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4143 return RET_PF_EMULATE;
4145 r = mmu_topup_memory_caches(vcpu);
4149 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4150 PT_DIRECTORY_LEVEL);
4151 level = mapping_level(vcpu, gfn, &force_pt_level);
4152 if (likely(!force_pt_level)) {
4153 if (level > PT_DIRECTORY_LEVEL &&
4154 !check_hugepage_cache_consistency(vcpu, gfn, level))
4155 level = PT_DIRECTORY_LEVEL;
4156 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4159 if (fast_page_fault(vcpu, gpa, level, error_code))
4160 return RET_PF_RETRY;
4162 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4165 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4166 return RET_PF_RETRY;
4168 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4172 spin_lock(&vcpu->kvm->mmu_lock);
4173 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4175 if (make_mmu_pages_available(vcpu) < 0)
4177 if (likely(!force_pt_level))
4178 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4179 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn, prefault);
4181 spin_unlock(&vcpu->kvm->mmu_lock);
4182 kvm_release_pfn_clean(pfn);
4186 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4187 struct kvm_mmu *context)
4189 context->page_fault = nonpaging_page_fault;
4190 context->gva_to_gpa = nonpaging_gva_to_gpa;
4191 context->sync_page = nonpaging_sync_page;
4192 context->invlpg = nonpaging_invlpg;
4193 context->update_pte = nonpaging_update_pte;
4194 context->root_level = 0;
4195 context->shadow_root_level = PT32E_ROOT_LEVEL;
4196 context->direct_map = true;
4197 context->nx = false;
4201 * Find out if a previously cached root matching the new CR3/role is available.
4202 * The current root is also inserted into the cache.
4203 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4205 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4206 * false is returned. This root should now be freed by the caller.
4208 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4209 union kvm_mmu_page_role new_role)
4212 struct kvm_mmu_root_info root;
4213 struct kvm_mmu *mmu = vcpu->arch.mmu;
4215 root.cr3 = mmu->root_cr3;
4216 root.hpa = mmu->root_hpa;
4218 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4219 swap(root, mmu->prev_roots[i]);
4221 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4222 page_header(root.hpa) != NULL &&
4223 new_role.word == page_header(root.hpa)->role.word)
4227 mmu->root_hpa = root.hpa;
4228 mmu->root_cr3 = root.cr3;
4230 return i < KVM_MMU_NUM_PREV_ROOTS;
4233 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4234 union kvm_mmu_page_role new_role,
4235 bool skip_tlb_flush)
4237 struct kvm_mmu *mmu = vcpu->arch.mmu;
4240 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4241 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4242 * later if necessary.
4244 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4245 mmu->root_level >= PT64_ROOT_4LEVEL) {
4246 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4249 if (cached_root_available(vcpu, new_cr3, new_role)) {
4251 * It is possible that the cached previous root page is
4252 * obsolete because of a change in the MMU generation
4253 * number. However, changing the generation number is
4254 * accompanied by KVM_REQ_MMU_RELOAD, which will free
4255 * the root set here and allocate a new one.
4257 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4258 if (!skip_tlb_flush) {
4259 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4260 kvm_x86_ops->tlb_flush(vcpu, true);
4264 * The last MMIO access's GVA and GPA are cached in the
4265 * VCPU. When switching to a new CR3, that GVA->GPA
4266 * mapping may no longer be valid. So clear any cached
4267 * MMIO info even when we don't need to sync the shadow
4270 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4272 __clear_sp_write_flooding_count(
4273 page_header(mmu->root_hpa));
4282 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4283 union kvm_mmu_page_role new_role,
4284 bool skip_tlb_flush)
4286 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4287 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4288 KVM_MMU_ROOT_CURRENT);
4291 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4293 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4296 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4298 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4300 return kvm_read_cr3(vcpu);
4303 static void inject_page_fault(struct kvm_vcpu *vcpu,
4304 struct x86_exception *fault)
4306 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4309 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4310 unsigned access, int *nr_present)
4312 if (unlikely(is_mmio_spte(*sptep))) {
4313 if (gfn != get_mmio_spte_gfn(*sptep)) {
4314 mmu_spte_clear_no_track(sptep);
4319 mark_mmio_spte(vcpu, sptep, gfn, access);
4326 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4327 unsigned level, unsigned gpte)
4330 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4331 * If it is clear, there are no large pages at this level, so clear
4332 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4334 gpte &= level - mmu->last_nonleaf_level;
4337 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4338 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4339 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4341 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4343 return gpte & PT_PAGE_SIZE_MASK;
4346 #define PTTYPE_EPT 18 /* arbitrary */
4347 #define PTTYPE PTTYPE_EPT
4348 #include "paging_tmpl.h"
4352 #include "paging_tmpl.h"
4356 #include "paging_tmpl.h"
4360 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4361 struct rsvd_bits_validate *rsvd_check,
4362 int maxphyaddr, int level, bool nx, bool gbpages,
4365 u64 exb_bit_rsvd = 0;
4366 u64 gbpages_bit_rsvd = 0;
4367 u64 nonleaf_bit8_rsvd = 0;
4369 rsvd_check->bad_mt_xwr = 0;
4372 exb_bit_rsvd = rsvd_bits(63, 63);
4374 gbpages_bit_rsvd = rsvd_bits(7, 7);
4377 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4378 * leaf entries) on AMD CPUs only.
4381 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4384 case PT32_ROOT_LEVEL:
4385 /* no rsvd bits for 2 level 4K page table entries */
4386 rsvd_check->rsvd_bits_mask[0][1] = 0;
4387 rsvd_check->rsvd_bits_mask[0][0] = 0;
4388 rsvd_check->rsvd_bits_mask[1][0] =
4389 rsvd_check->rsvd_bits_mask[0][0];
4392 rsvd_check->rsvd_bits_mask[1][1] = 0;
4396 if (is_cpuid_PSE36())
4397 /* 36bits PSE 4MB page */
4398 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4400 /* 32 bits PSE 4MB page */
4401 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4403 case PT32E_ROOT_LEVEL:
4404 rsvd_check->rsvd_bits_mask[0][2] =
4405 rsvd_bits(maxphyaddr, 63) |
4406 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4407 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4408 rsvd_bits(maxphyaddr, 62); /* PDE */
4409 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4410 rsvd_bits(maxphyaddr, 62); /* PTE */
4411 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4412 rsvd_bits(maxphyaddr, 62) |
4413 rsvd_bits(13, 20); /* large page */
4414 rsvd_check->rsvd_bits_mask[1][0] =
4415 rsvd_check->rsvd_bits_mask[0][0];
4417 case PT64_ROOT_5LEVEL:
4418 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4419 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4420 rsvd_bits(maxphyaddr, 51);
4421 rsvd_check->rsvd_bits_mask[1][4] =
4422 rsvd_check->rsvd_bits_mask[0][4];
4424 case PT64_ROOT_4LEVEL:
4425 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4426 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4427 rsvd_bits(maxphyaddr, 51);
4428 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4429 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4430 rsvd_bits(maxphyaddr, 51);
4431 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4432 rsvd_bits(maxphyaddr, 51);
4433 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4434 rsvd_bits(maxphyaddr, 51);
4435 rsvd_check->rsvd_bits_mask[1][3] =
4436 rsvd_check->rsvd_bits_mask[0][3];
4437 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4438 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4440 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4441 rsvd_bits(maxphyaddr, 51) |
4442 rsvd_bits(13, 20); /* large page */
4443 rsvd_check->rsvd_bits_mask[1][0] =
4444 rsvd_check->rsvd_bits_mask[0][0];
4449 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4450 struct kvm_mmu *context)
4452 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4453 cpuid_maxphyaddr(vcpu), context->root_level,
4455 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4456 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4460 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4461 int maxphyaddr, bool execonly)
4465 rsvd_check->rsvd_bits_mask[0][4] =
4466 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4467 rsvd_check->rsvd_bits_mask[0][3] =
4468 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4469 rsvd_check->rsvd_bits_mask[0][2] =
4470 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4471 rsvd_check->rsvd_bits_mask[0][1] =
4472 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4473 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4476 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4477 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4478 rsvd_check->rsvd_bits_mask[1][2] =
4479 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4480 rsvd_check->rsvd_bits_mask[1][1] =
4481 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4482 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4484 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4485 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4486 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4487 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4488 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4490 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4491 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4493 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4496 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4497 struct kvm_mmu *context, bool execonly)
4499 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4500 cpuid_maxphyaddr(vcpu), execonly);
4504 * the page table on host is the shadow page table for the page
4505 * table in guest or amd nested guest, its mmu features completely
4506 * follow the features in guest.
4509 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4511 bool uses_nx = context->nx ||
4512 context->mmu_role.base.smep_andnot_wp;
4513 struct rsvd_bits_validate *shadow_zero_check;
4517 * Passing "true" to the last argument is okay; it adds a check
4518 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4520 shadow_zero_check = &context->shadow_zero_check;
4521 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4523 context->shadow_root_level, uses_nx,
4524 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4525 is_pse(vcpu), true);
4527 if (!shadow_me_mask)
4530 for (i = context->shadow_root_level; --i >= 0;) {
4531 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4532 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4536 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4538 static inline bool boot_cpu_is_amd(void)
4540 WARN_ON_ONCE(!tdp_enabled);
4541 return shadow_x_mask == 0;
4545 * the direct page table on host, use as much mmu features as
4546 * possible, however, kvm currently does not do execution-protection.
4549 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4550 struct kvm_mmu *context)
4552 struct rsvd_bits_validate *shadow_zero_check;
4555 shadow_zero_check = &context->shadow_zero_check;
4557 if (boot_cpu_is_amd())
4558 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4560 context->shadow_root_level, false,
4561 boot_cpu_has(X86_FEATURE_GBPAGES),
4564 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4568 if (!shadow_me_mask)
4571 for (i = context->shadow_root_level; --i >= 0;) {
4572 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4573 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4578 * as the comments in reset_shadow_zero_bits_mask() except it
4579 * is the shadow page table for intel nested guest.
4582 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4583 struct kvm_mmu *context, bool execonly)
4585 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4586 shadow_phys_bits, execonly);
4589 #define BYTE_MASK(access) \
4590 ((1 & (access) ? 2 : 0) | \
4591 (2 & (access) ? 4 : 0) | \
4592 (3 & (access) ? 8 : 0) | \
4593 (4 & (access) ? 16 : 0) | \
4594 (5 & (access) ? 32 : 0) | \
4595 (6 & (access) ? 64 : 0) | \
4596 (7 & (access) ? 128 : 0))
4599 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4600 struct kvm_mmu *mmu, bool ept)
4604 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4605 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4606 const u8 u = BYTE_MASK(ACC_USER_MASK);
4608 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4609 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4610 bool cr0_wp = is_write_protection(vcpu);
4612 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4613 unsigned pfec = byte << 1;
4616 * Each "*f" variable has a 1 bit for each UWX value
4617 * that causes a fault with the given PFEC.
4620 /* Faults from writes to non-writable pages */
4621 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4622 /* Faults from user mode accesses to supervisor pages */
4623 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4624 /* Faults from fetches of non-executable pages*/
4625 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4626 /* Faults from kernel mode fetches of user pages */
4628 /* Faults from kernel mode accesses of user pages */
4632 /* Faults from kernel mode accesses to user pages */
4633 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4635 /* Not really needed: !nx will cause pte.nx to fault */
4639 /* Allow supervisor writes if !cr0.wp */
4641 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4643 /* Disallow supervisor fetches of user code if cr4.smep */
4645 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4648 * SMAP:kernel-mode data accesses from user-mode
4649 * mappings should fault. A fault is considered
4650 * as a SMAP violation if all of the following
4651 * conditions are true:
4652 * - X86_CR4_SMAP is set in CR4
4653 * - A user page is accessed
4654 * - The access is not a fetch
4655 * - Page fault in kernel mode
4656 * - if CPL = 3 or X86_EFLAGS_AC is clear
4658 * Here, we cover the first three conditions.
4659 * The fourth is computed dynamically in permission_fault();
4660 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4661 * *not* subject to SMAP restrictions.
4664 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4667 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4672 * PKU is an additional mechanism by which the paging controls access to
4673 * user-mode addresses based on the value in the PKRU register. Protection
4674 * key violations are reported through a bit in the page fault error code.
4675 * Unlike other bits of the error code, the PK bit is not known at the
4676 * call site of e.g. gva_to_gpa; it must be computed directly in
4677 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4678 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4680 * In particular the following conditions come from the error code, the
4681 * page tables and the machine state:
4682 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4683 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4684 * - PK is always zero if U=0 in the page tables
4685 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4687 * The PKRU bitmask caches the result of these four conditions. The error
4688 * code (minus the P bit) and the page table's U bit form an index into the
4689 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4690 * with the two bits of the PKRU register corresponding to the protection key.
4691 * For the first three conditions above the bits will be 00, thus masking
4692 * away both AD and WD. For all reads or if the last condition holds, WD
4693 * only will be masked away.
4695 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4706 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4707 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4712 wp = is_write_protection(vcpu);
4714 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4715 unsigned pfec, pkey_bits;
4716 bool check_pkey, check_write, ff, uf, wf, pte_user;
4719 ff = pfec & PFERR_FETCH_MASK;
4720 uf = pfec & PFERR_USER_MASK;
4721 wf = pfec & PFERR_WRITE_MASK;
4723 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4724 pte_user = pfec & PFERR_RSVD_MASK;
4727 * Only need to check the access which is not an
4728 * instruction fetch and is to a user page.
4730 check_pkey = (!ff && pte_user);
4732 * write access is controlled by PKRU if it is a
4733 * user access or CR0.WP = 1.
4735 check_write = check_pkey && wf && (uf || wp);
4737 /* PKRU.AD stops both read and write access. */
4738 pkey_bits = !!check_pkey;
4739 /* PKRU.WD stops write access. */
4740 pkey_bits |= (!!check_write) << 1;
4742 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4746 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4748 unsigned root_level = mmu->root_level;
4750 mmu->last_nonleaf_level = root_level;
4751 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4752 mmu->last_nonleaf_level++;
4755 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4756 struct kvm_mmu *context,
4759 context->nx = is_nx(vcpu);
4760 context->root_level = level;
4762 reset_rsvds_bits_mask(vcpu, context);
4763 update_permission_bitmask(vcpu, context, false);
4764 update_pkru_bitmask(vcpu, context, false);
4765 update_last_nonleaf_level(vcpu, context);
4767 MMU_WARN_ON(!is_pae(vcpu));
4768 context->page_fault = paging64_page_fault;
4769 context->gva_to_gpa = paging64_gva_to_gpa;
4770 context->sync_page = paging64_sync_page;
4771 context->invlpg = paging64_invlpg;
4772 context->update_pte = paging64_update_pte;
4773 context->shadow_root_level = level;
4774 context->direct_map = false;
4777 static void paging64_init_context(struct kvm_vcpu *vcpu,
4778 struct kvm_mmu *context)
4780 int root_level = is_la57_mode(vcpu) ?
4781 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4783 paging64_init_context_common(vcpu, context, root_level);
4786 static void paging32_init_context(struct kvm_vcpu *vcpu,
4787 struct kvm_mmu *context)
4789 context->nx = false;
4790 context->root_level = PT32_ROOT_LEVEL;
4792 reset_rsvds_bits_mask(vcpu, context);
4793 update_permission_bitmask(vcpu, context, false);
4794 update_pkru_bitmask(vcpu, context, false);
4795 update_last_nonleaf_level(vcpu, context);
4797 context->page_fault = paging32_page_fault;
4798 context->gva_to_gpa = paging32_gva_to_gpa;
4799 context->sync_page = paging32_sync_page;
4800 context->invlpg = paging32_invlpg;
4801 context->update_pte = paging32_update_pte;
4802 context->shadow_root_level = PT32E_ROOT_LEVEL;
4803 context->direct_map = false;
4806 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4807 struct kvm_mmu *context)
4809 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4812 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4814 union kvm_mmu_extended_role ext = {0};
4816 ext.cr0_pg = !!is_paging(vcpu);
4817 ext.cr4_pae = !!is_pae(vcpu);
4818 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4819 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4820 ext.cr4_pse = !!is_pse(vcpu);
4821 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4822 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4823 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4830 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4833 union kvm_mmu_role role = {0};
4835 role.base.access = ACC_ALL;
4836 role.base.nxe = !!is_nx(vcpu);
4837 role.base.cr0_wp = is_write_protection(vcpu);
4838 role.base.smm = is_smm(vcpu);
4839 role.base.guest_mode = is_guest_mode(vcpu);
4844 role.ext = kvm_calc_mmu_role_ext(vcpu);
4849 static union kvm_mmu_role
4850 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4852 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4854 role.base.ad_disabled = (shadow_accessed_mask == 0);
4855 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4856 role.base.direct = true;
4857 role.base.gpte_is_8_bytes = true;
4862 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4864 struct kvm_mmu *context = vcpu->arch.mmu;
4865 union kvm_mmu_role new_role =
4866 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4868 new_role.base.word &= mmu_base_role_mask.word;
4869 if (new_role.as_u64 == context->mmu_role.as_u64)
4872 context->mmu_role.as_u64 = new_role.as_u64;
4873 context->page_fault = tdp_page_fault;
4874 context->sync_page = nonpaging_sync_page;
4875 context->invlpg = nonpaging_invlpg;
4876 context->update_pte = nonpaging_update_pte;
4877 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4878 context->direct_map = true;
4879 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4880 context->get_cr3 = get_cr3;
4881 context->get_pdptr = kvm_pdptr_read;
4882 context->inject_page_fault = kvm_inject_page_fault;
4884 if (!is_paging(vcpu)) {
4885 context->nx = false;
4886 context->gva_to_gpa = nonpaging_gva_to_gpa;
4887 context->root_level = 0;
4888 } else if (is_long_mode(vcpu)) {
4889 context->nx = is_nx(vcpu);
4890 context->root_level = is_la57_mode(vcpu) ?
4891 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4892 reset_rsvds_bits_mask(vcpu, context);
4893 context->gva_to_gpa = paging64_gva_to_gpa;
4894 } else if (is_pae(vcpu)) {
4895 context->nx = is_nx(vcpu);
4896 context->root_level = PT32E_ROOT_LEVEL;
4897 reset_rsvds_bits_mask(vcpu, context);
4898 context->gva_to_gpa = paging64_gva_to_gpa;
4900 context->nx = false;
4901 context->root_level = PT32_ROOT_LEVEL;
4902 reset_rsvds_bits_mask(vcpu, context);
4903 context->gva_to_gpa = paging32_gva_to_gpa;
4906 update_permission_bitmask(vcpu, context, false);
4907 update_pkru_bitmask(vcpu, context, false);
4908 update_last_nonleaf_level(vcpu, context);
4909 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4912 static union kvm_mmu_role
4913 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4915 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4917 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4918 !is_write_protection(vcpu);
4919 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4920 !is_write_protection(vcpu);
4921 role.base.direct = !is_paging(vcpu);
4922 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4924 if (!is_long_mode(vcpu))
4925 role.base.level = PT32E_ROOT_LEVEL;
4926 else if (is_la57_mode(vcpu))
4927 role.base.level = PT64_ROOT_5LEVEL;
4929 role.base.level = PT64_ROOT_4LEVEL;
4934 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4936 struct kvm_mmu *context = vcpu->arch.mmu;
4937 union kvm_mmu_role new_role =
4938 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4940 new_role.base.word &= mmu_base_role_mask.word;
4941 if (new_role.as_u64 == context->mmu_role.as_u64)
4944 if (!is_paging(vcpu))
4945 nonpaging_init_context(vcpu, context);
4946 else if (is_long_mode(vcpu))
4947 paging64_init_context(vcpu, context);
4948 else if (is_pae(vcpu))
4949 paging32E_init_context(vcpu, context);
4951 paging32_init_context(vcpu, context);
4953 context->mmu_role.as_u64 = new_role.as_u64;
4954 reset_shadow_zero_bits_mask(vcpu, context);
4956 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4958 static union kvm_mmu_role
4959 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4962 union kvm_mmu_role role = {0};
4964 /* SMM flag is inherited from root_mmu */
4965 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
4967 role.base.level = PT64_ROOT_4LEVEL;
4968 role.base.gpte_is_8_bytes = true;
4969 role.base.direct = false;
4970 role.base.ad_disabled = !accessed_dirty;
4971 role.base.guest_mode = true;
4972 role.base.access = ACC_ALL;
4975 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
4976 * SMAP variation to denote shadow EPT entries.
4978 role.base.cr0_wp = true;
4979 role.base.smap_andnot_wp = true;
4981 role.ext = kvm_calc_mmu_role_ext(vcpu);
4982 role.ext.execonly = execonly;
4987 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4988 bool accessed_dirty, gpa_t new_eptp)
4990 struct kvm_mmu *context = vcpu->arch.mmu;
4991 union kvm_mmu_role new_role =
4992 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4995 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
4997 new_role.base.word &= mmu_base_role_mask.word;
4998 if (new_role.as_u64 == context->mmu_role.as_u64)
5001 context->shadow_root_level = PT64_ROOT_4LEVEL;
5004 context->ept_ad = accessed_dirty;
5005 context->page_fault = ept_page_fault;
5006 context->gva_to_gpa = ept_gva_to_gpa;
5007 context->sync_page = ept_sync_page;
5008 context->invlpg = ept_invlpg;
5009 context->update_pte = ept_update_pte;
5010 context->root_level = PT64_ROOT_4LEVEL;
5011 context->direct_map = false;
5012 context->mmu_role.as_u64 = new_role.as_u64;
5014 update_permission_bitmask(vcpu, context, true);
5015 update_pkru_bitmask(vcpu, context, true);
5016 update_last_nonleaf_level(vcpu, context);
5017 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5018 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5020 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5022 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5024 struct kvm_mmu *context = vcpu->arch.mmu;
5026 kvm_init_shadow_mmu(vcpu);
5027 context->set_cr3 = kvm_x86_ops->set_cr3;
5028 context->get_cr3 = get_cr3;
5029 context->get_pdptr = kvm_pdptr_read;
5030 context->inject_page_fault = kvm_inject_page_fault;
5033 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5035 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5036 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5038 new_role.base.word &= mmu_base_role_mask.word;
5039 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5042 g_context->mmu_role.as_u64 = new_role.as_u64;
5043 g_context->get_cr3 = get_cr3;
5044 g_context->get_pdptr = kvm_pdptr_read;
5045 g_context->inject_page_fault = kvm_inject_page_fault;
5048 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5049 * L1's nested page tables (e.g. EPT12). The nested translation
5050 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5051 * L2's page tables as the first level of translation and L1's
5052 * nested page tables as the second level of translation. Basically
5053 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5055 if (!is_paging(vcpu)) {
5056 g_context->nx = false;
5057 g_context->root_level = 0;
5058 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5059 } else if (is_long_mode(vcpu)) {
5060 g_context->nx = is_nx(vcpu);
5061 g_context->root_level = is_la57_mode(vcpu) ?
5062 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5063 reset_rsvds_bits_mask(vcpu, g_context);
5064 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5065 } else if (is_pae(vcpu)) {
5066 g_context->nx = is_nx(vcpu);
5067 g_context->root_level = PT32E_ROOT_LEVEL;
5068 reset_rsvds_bits_mask(vcpu, g_context);
5069 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5071 g_context->nx = false;
5072 g_context->root_level = PT32_ROOT_LEVEL;
5073 reset_rsvds_bits_mask(vcpu, g_context);
5074 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5077 update_permission_bitmask(vcpu, g_context, false);
5078 update_pkru_bitmask(vcpu, g_context, false);
5079 update_last_nonleaf_level(vcpu, g_context);
5082 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5087 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5089 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5090 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5093 if (mmu_is_nested(vcpu))
5094 init_kvm_nested_mmu(vcpu);
5095 else if (tdp_enabled)
5096 init_kvm_tdp_mmu(vcpu);
5098 init_kvm_softmmu(vcpu);
5100 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5102 static union kvm_mmu_page_role
5103 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5105 union kvm_mmu_role role;
5108 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5110 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5115 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5117 kvm_mmu_unload(vcpu);
5118 kvm_init_mmu(vcpu, true);
5120 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5122 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5126 r = mmu_topup_memory_caches(vcpu);
5129 r = mmu_alloc_roots(vcpu);
5130 kvm_mmu_sync_roots(vcpu);
5133 kvm_mmu_load_cr3(vcpu);
5134 kvm_x86_ops->tlb_flush(vcpu, true);
5138 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5140 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5142 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5143 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5144 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5145 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5147 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5149 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5150 struct kvm_mmu_page *sp, u64 *spte,
5153 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5154 ++vcpu->kvm->stat.mmu_pde_zapped;
5158 ++vcpu->kvm->stat.mmu_pte_updated;
5159 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5162 static bool need_remote_flush(u64 old, u64 new)
5164 if (!is_shadow_present_pte(old))
5166 if (!is_shadow_present_pte(new))
5168 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5170 old ^= shadow_nx_mask;
5171 new ^= shadow_nx_mask;
5172 return (old & ~new & PT64_PERM_MASK) != 0;
5175 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5182 * Assume that the pte write on a page table of the same type
5183 * as the current vcpu paging mode since we update the sptes only
5184 * when they have the same mode.
5186 if (is_pae(vcpu) && *bytes == 4) {
5187 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5192 if (*bytes == 4 || *bytes == 8) {
5193 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5202 * If we're seeing too many writes to a page, it may no longer be a page table,
5203 * or we may be forking, in which case it is better to unmap the page.
5205 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5208 * Skip write-flooding detected for the sp whose level is 1, because
5209 * it can become unsync, then the guest page is not write-protected.
5211 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5214 atomic_inc(&sp->write_flooding_count);
5215 return atomic_read(&sp->write_flooding_count) >= 3;
5219 * Misaligned accesses are too much trouble to fix up; also, they usually
5220 * indicate a page is not used as a page table.
5222 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5225 unsigned offset, pte_size, misaligned;
5227 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5228 gpa, bytes, sp->role.word);
5230 offset = offset_in_page(gpa);
5231 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5234 * Sometimes, the OS only writes the last one bytes to update status
5235 * bits, for example, in linux, andb instruction is used in clear_bit().
5237 if (!(offset & (pte_size - 1)) && bytes == 1)
5240 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5241 misaligned |= bytes < 4;
5246 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5248 unsigned page_offset, quadrant;
5252 page_offset = offset_in_page(gpa);
5253 level = sp->role.level;
5255 if (!sp->role.gpte_is_8_bytes) {
5256 page_offset <<= 1; /* 32->64 */
5258 * A 32-bit pde maps 4MB while the shadow pdes map
5259 * only 2MB. So we need to double the offset again
5260 * and zap two pdes instead of one.
5262 if (level == PT32_ROOT_LEVEL) {
5263 page_offset &= ~7; /* kill rounding error */
5267 quadrant = page_offset >> PAGE_SHIFT;
5268 page_offset &= ~PAGE_MASK;
5269 if (quadrant != sp->role.quadrant)
5273 spte = &sp->spt[page_offset / sizeof(*spte)];
5277 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5278 const u8 *new, int bytes,
5279 struct kvm_page_track_notifier_node *node)
5281 gfn_t gfn = gpa >> PAGE_SHIFT;
5282 struct kvm_mmu_page *sp;
5283 LIST_HEAD(invalid_list);
5284 u64 entry, gentry, *spte;
5286 bool remote_flush, local_flush;
5289 * If we don't have indirect shadow pages, it means no page is
5290 * write-protected, so we can exit simply.
5292 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5295 remote_flush = local_flush = false;
5297 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5300 * No need to care whether allocation memory is successful
5301 * or not since pte prefetch is skiped if it does not have
5302 * enough objects in the cache.
5304 mmu_topup_memory_caches(vcpu);
5306 spin_lock(&vcpu->kvm->mmu_lock);
5308 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5310 ++vcpu->kvm->stat.mmu_pte_write;
5311 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5313 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5314 if (detect_write_misaligned(sp, gpa, bytes) ||
5315 detect_write_flooding(sp)) {
5316 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5317 ++vcpu->kvm->stat.mmu_flooded;
5321 spte = get_written_sptes(sp, gpa, &npte);
5327 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5330 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5332 !((sp->role.word ^ base_role)
5333 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5334 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5335 if (need_remote_flush(entry, *spte))
5336 remote_flush = true;
5340 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5341 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5342 spin_unlock(&vcpu->kvm->mmu_lock);
5345 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5350 if (vcpu->arch.mmu->direct_map)
5353 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5355 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5359 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5361 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5363 LIST_HEAD(invalid_list);
5365 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5368 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5369 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5372 ++vcpu->kvm->stat.mmu_recycled;
5374 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5376 if (!kvm_mmu_available_pages(vcpu->kvm))
5381 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5382 void *insn, int insn_len)
5384 int r, emulation_type = 0;
5385 bool direct = vcpu->arch.mmu->direct_map;
5387 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5388 if (vcpu->arch.mmu->direct_map) {
5389 vcpu->arch.gpa_available = true;
5390 vcpu->arch.gpa_val = cr2;
5394 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5395 r = handle_mmio_page_fault(vcpu, cr2, direct);
5396 if (r == RET_PF_EMULATE)
5400 if (r == RET_PF_INVALID) {
5401 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5402 lower_32_bits(error_code),
5404 WARN_ON(r == RET_PF_INVALID);
5407 if (r == RET_PF_RETRY)
5413 * Before emulating the instruction, check if the error code
5414 * was due to a RO violation while translating the guest page.
5415 * This can occur when using nested virtualization with nested
5416 * paging in both guests. If true, we simply unprotect the page
5417 * and resume the guest.
5419 if (vcpu->arch.mmu->direct_map &&
5420 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5421 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5426 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5427 * optimistically try to just unprotect the page and let the processor
5428 * re-execute the instruction that caused the page fault. Do not allow
5429 * retrying MMIO emulation, as it's not only pointless but could also
5430 * cause us to enter an infinite loop because the processor will keep
5431 * faulting on the non-existent MMIO address. Retrying an instruction
5432 * from a nested guest is also pointless and dangerous as we are only
5433 * explicitly shadowing L1's page tables, i.e. unprotecting something
5434 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5436 if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5437 emulation_type = EMULTYPE_ALLOW_RETRY;
5440 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5441 * This can happen if a guest gets a page-fault on data access but the HW
5442 * table walker is not able to read the instruction page (e.g instruction
5443 * page is not present in memory). In those cases we simply restart the
5444 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5446 if (unlikely(insn && !insn_len)) {
5447 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5451 return x86_emulate_instruction(vcpu, cr2, emulation_type, insn,
5454 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5456 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5458 struct kvm_mmu *mmu = vcpu->arch.mmu;
5461 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5462 if (is_noncanonical_address(gva, vcpu))
5465 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5468 * INVLPG is required to invalidate any global mappings for the VA,
5469 * irrespective of PCID. Since it would take us roughly similar amount
5470 * of work to determine whether any of the prev_root mappings of the VA
5471 * is marked global, or to just sync it blindly, so we might as well
5472 * just always sync it.
5474 * Mappings not reachable via the current cr3 or the prev_roots will be
5475 * synced when switching to that cr3, so nothing needs to be done here
5478 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5479 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5480 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5482 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5483 ++vcpu->stat.invlpg;
5485 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5487 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5489 struct kvm_mmu *mmu = vcpu->arch.mmu;
5490 bool tlb_flush = false;
5493 if (pcid == kvm_get_active_pcid(vcpu)) {
5494 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5498 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5499 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5500 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5501 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5507 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5509 ++vcpu->stat.invlpg;
5512 * Mappings not reachable via the current cr3 or the prev_roots will be
5513 * synced when switching to that cr3, so nothing needs to be done here
5517 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5519 void kvm_enable_tdp(void)
5523 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5525 void kvm_disable_tdp(void)
5527 tdp_enabled = false;
5529 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5532 /* The return value indicates if tlb flush on all vcpus is needed. */
5533 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5535 /* The caller should hold mmu-lock before calling this function. */
5536 static __always_inline bool
5537 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5538 slot_level_handler fn, int start_level, int end_level,
5539 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5541 struct slot_rmap_walk_iterator iterator;
5544 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5545 end_gfn, &iterator) {
5547 flush |= fn(kvm, iterator.rmap);
5549 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5550 if (flush && lock_flush_tlb) {
5551 kvm_flush_remote_tlbs_with_address(kvm,
5553 iterator.gfn - start_gfn + 1);
5556 cond_resched_lock(&kvm->mmu_lock);
5560 if (flush && lock_flush_tlb) {
5561 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5562 end_gfn - start_gfn + 1);
5569 static __always_inline bool
5570 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5571 slot_level_handler fn, int start_level, int end_level,
5572 bool lock_flush_tlb)
5574 return slot_handle_level_range(kvm, memslot, fn, start_level,
5575 end_level, memslot->base_gfn,
5576 memslot->base_gfn + memslot->npages - 1,
5580 static __always_inline bool
5581 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5582 slot_level_handler fn, bool lock_flush_tlb)
5584 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5585 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5588 static __always_inline bool
5589 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5590 slot_level_handler fn, bool lock_flush_tlb)
5592 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5593 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5596 static __always_inline bool
5597 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5598 slot_level_handler fn, bool lock_flush_tlb)
5600 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5601 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5604 static void free_mmu_pages(struct kvm_mmu *mmu)
5606 free_page((unsigned long)mmu->pae_root);
5607 free_page((unsigned long)mmu->lm_root);
5610 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5616 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5617 * while the PDP table is a per-vCPU construct that's allocated at MMU
5618 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5619 * x86_64. Therefore we need to allocate the PDP table in the first
5620 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5621 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5622 * skip allocating the PDP table.
5624 if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5627 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5631 mmu->pae_root = page_address(page);
5632 for (i = 0; i < 4; ++i)
5633 mmu->pae_root[i] = INVALID_PAGE;
5638 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5643 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5644 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5646 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5647 vcpu->arch.root_mmu.root_cr3 = 0;
5648 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5649 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5650 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5652 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5653 vcpu->arch.guest_mmu.root_cr3 = 0;
5654 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5655 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5656 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5658 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5660 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5664 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5666 goto fail_allocate_root;
5670 free_mmu_pages(&vcpu->arch.guest_mmu);
5675 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5677 struct kvm_mmu_page *sp, *node;
5678 LIST_HEAD(invalid_list);
5682 list_for_each_entry_safe_reverse(sp, node,
5683 &kvm->arch.active_mmu_pages, link) {
5685 * No obsolete valid page exists before a newly created page
5686 * since active_mmu_pages is a FIFO list.
5688 if (!is_obsolete_sp(kvm, sp))
5692 * Do not repeatedly zap a root page to avoid unnecessary
5693 * KVM_REQ_MMU_RELOAD, otherwise we may not be able to
5696 * call vcpu_enter_guest():
5697 * 1): handle KVM_REQ_MMU_RELOAD
5698 * and require mmu-lock to
5701 * 1): zap root page and
5702 * send KVM_REQ_MMU_RELOAD
5704 * 2): if (cond_resched_lock(mmu-lock))
5706 * 2): hold mmu-lock and load mmu
5708 * 3): see KVM_REQ_MMU_RELOAD bit
5709 * on vcpu->requests is set
5710 * then return 1 to call
5711 * vcpu_enter_guest() again.
5714 * Since we are reversely walking the list and the invalid
5715 * list will be moved to the head, skip the invalid page
5716 * can help us to avoid the infinity list walking.
5718 if (sp->role.invalid)
5721 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5722 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5723 cond_resched_lock(&kvm->mmu_lock);
5727 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
5731 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5735 * Fast invalidate all shadow pages and use lock-break technique
5736 * to zap obsolete pages.
5738 * It's required when memslot is being deleted or VM is being
5739 * destroyed, in these cases, we should ensure that KVM MMU does
5740 * not use any resource of the being-deleted slot or all slots
5741 * after calling the function.
5743 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5745 spin_lock(&kvm->mmu_lock);
5746 trace_kvm_mmu_zap_all_fast(kvm);
5747 kvm->arch.mmu_valid_gen++;
5749 kvm_zap_obsolete_pages(kvm);
5750 spin_unlock(&kvm->mmu_lock);
5753 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5754 struct kvm_memory_slot *slot,
5755 struct kvm_page_track_notifier_node *node)
5757 kvm_mmu_zap_all_fast(kvm);
5760 void kvm_mmu_init_vm(struct kvm *kvm)
5762 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5764 node->track_write = kvm_mmu_pte_write;
5765 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5766 kvm_page_track_register_notifier(kvm, node);
5769 void kvm_mmu_uninit_vm(struct kvm *kvm)
5771 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5773 kvm_page_track_unregister_notifier(kvm, node);
5776 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5778 struct kvm_memslots *slots;
5779 struct kvm_memory_slot *memslot;
5782 spin_lock(&kvm->mmu_lock);
5783 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5784 slots = __kvm_memslots(kvm, i);
5785 kvm_for_each_memslot(memslot, slots) {
5788 start = max(gfn_start, memslot->base_gfn);
5789 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5793 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5794 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5795 start, end - 1, true);
5799 spin_unlock(&kvm->mmu_lock);
5802 static bool slot_rmap_write_protect(struct kvm *kvm,
5803 struct kvm_rmap_head *rmap_head)
5805 return __rmap_write_protect(kvm, rmap_head, false);
5808 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5809 struct kvm_memory_slot *memslot)
5813 spin_lock(&kvm->mmu_lock);
5814 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5816 spin_unlock(&kvm->mmu_lock);
5819 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5820 * which do tlb flush out of mmu-lock should be serialized by
5821 * kvm->slots_lock otherwise tlb flush would be missed.
5823 lockdep_assert_held(&kvm->slots_lock);
5826 * We can flush all the TLBs out of the mmu lock without TLB
5827 * corruption since we just change the spte from writable to
5828 * readonly so that we only need to care the case of changing
5829 * spte from present to present (changing the spte from present
5830 * to nonpresent will flush all the TLBs immediately), in other
5831 * words, the only case we care is mmu_spte_update() where we
5832 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5833 * instead of PT_WRITABLE_MASK, that means it does not depend
5834 * on PT_WRITABLE_MASK anymore.
5837 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5841 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5842 struct kvm_rmap_head *rmap_head)
5845 struct rmap_iterator iter;
5846 int need_tlb_flush = 0;
5848 struct kvm_mmu_page *sp;
5851 for_each_rmap_spte(rmap_head, &iter, sptep) {
5852 sp = page_header(__pa(sptep));
5853 pfn = spte_to_pfn(*sptep);
5856 * We cannot do huge page mapping for indirect shadow pages,
5857 * which are found on the last rmap (level = 1) when not using
5858 * tdp; such shadow pages are synced with the page table in
5859 * the guest, and the guest page table is using 4K page size
5860 * mapping if the indirect sp has level = 1.
5862 if (sp->role.direct &&
5863 !kvm_is_reserved_pfn(pfn) &&
5864 PageTransCompoundMap(pfn_to_page(pfn))) {
5865 pte_list_remove(rmap_head, sptep);
5867 if (kvm_available_flush_tlb_with_range())
5868 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5869 KVM_PAGES_PER_HPAGE(sp->role.level));
5877 return need_tlb_flush;
5880 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5881 const struct kvm_memory_slot *memslot)
5883 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5884 spin_lock(&kvm->mmu_lock);
5885 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5886 kvm_mmu_zap_collapsible_spte, true);
5887 spin_unlock(&kvm->mmu_lock);
5890 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5891 struct kvm_memory_slot *memslot)
5895 spin_lock(&kvm->mmu_lock);
5896 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5897 spin_unlock(&kvm->mmu_lock);
5899 lockdep_assert_held(&kvm->slots_lock);
5902 * It's also safe to flush TLBs out of mmu lock here as currently this
5903 * function is only used for dirty logging, in which case flushing TLB
5904 * out of mmu lock also guarantees no dirty pages will be lost in
5908 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5911 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5913 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5914 struct kvm_memory_slot *memslot)
5918 spin_lock(&kvm->mmu_lock);
5919 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5921 spin_unlock(&kvm->mmu_lock);
5923 /* see kvm_mmu_slot_remove_write_access */
5924 lockdep_assert_held(&kvm->slots_lock);
5927 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5930 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5932 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5933 struct kvm_memory_slot *memslot)
5937 spin_lock(&kvm->mmu_lock);
5938 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5939 spin_unlock(&kvm->mmu_lock);
5941 lockdep_assert_held(&kvm->slots_lock);
5943 /* see kvm_mmu_slot_leaf_clear_dirty */
5945 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5948 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5950 void kvm_mmu_zap_all(struct kvm *kvm)
5952 struct kvm_mmu_page *sp, *node;
5953 LIST_HEAD(invalid_list);
5956 spin_lock(&kvm->mmu_lock);
5958 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
5959 if (sp->role.invalid && sp->root_count)
5961 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
5963 if (cond_resched_lock(&kvm->mmu_lock))
5967 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5968 spin_unlock(&kvm->mmu_lock);
5971 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5973 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
5975 gen &= MMIO_SPTE_GEN_MASK;
5978 * Generation numbers are incremented in multiples of the number of
5979 * address spaces in order to provide unique generations across all
5980 * address spaces. Strip what is effectively the address space
5981 * modifier prior to checking for a wrap of the MMIO generation so
5982 * that a wrap in any address space is detected.
5984 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5987 * The very rare case: if the MMIO generation number has wrapped,
5988 * zap all shadow pages.
5990 if (unlikely(gen == 0)) {
5991 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5992 kvm_mmu_zap_all_fast(kvm);
5996 static unsigned long
5997 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6000 int nr_to_scan = sc->nr_to_scan;
6001 unsigned long freed = 0;
6003 mutex_lock(&kvm_lock);
6005 list_for_each_entry(kvm, &vm_list, vm_list) {
6007 LIST_HEAD(invalid_list);
6010 * Never scan more than sc->nr_to_scan VM instances.
6011 * Will not hit this condition practically since we do not try
6012 * to shrink more than one VM and it is very unlikely to see
6013 * !n_used_mmu_pages so many times.
6018 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6019 * here. We may skip a VM instance errorneosly, but we do not
6020 * want to shrink a VM that only started to populate its MMU
6023 if (!kvm->arch.n_used_mmu_pages)
6026 idx = srcu_read_lock(&kvm->srcu);
6027 spin_lock(&kvm->mmu_lock);
6029 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6031 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6033 spin_unlock(&kvm->mmu_lock);
6034 srcu_read_unlock(&kvm->srcu, idx);
6037 * unfair on small ones
6038 * per-vm shrinkers cry out
6039 * sadness comes quickly
6041 list_move_tail(&kvm->vm_list, &vm_list);
6045 mutex_unlock(&kvm_lock);
6049 static unsigned long
6050 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6052 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6055 static struct shrinker mmu_shrinker = {
6056 .count_objects = mmu_shrink_count,
6057 .scan_objects = mmu_shrink_scan,
6058 .seeks = DEFAULT_SEEKS * 10,
6061 static void mmu_destroy_caches(void)
6063 kmem_cache_destroy(pte_list_desc_cache);
6064 kmem_cache_destroy(mmu_page_header_cache);
6067 static void kvm_set_mmio_spte_mask(void)
6072 * Set the reserved bits and the present bit of an paging-structure
6073 * entry to generate page fault with PFER.RSV = 1.
6077 * Mask the uppermost physical address bit, which would be reserved as
6078 * long as the supported physical address width is less than 52.
6082 /* Set the present bit. */
6086 * If reserved bit is not supported, clear the present bit to disable
6089 if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
6092 kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
6095 int kvm_mmu_module_init(void)
6100 * MMU roles use union aliasing which is, generally speaking, an
6101 * undefined behavior. However, we supposedly know how compilers behave
6102 * and the current status quo is unlikely to change. Guardians below are
6103 * supposed to let us know if the assumption becomes false.
6105 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6106 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6107 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6109 kvm_mmu_reset_all_pte_masks();
6111 kvm_set_mmio_spte_mask();
6113 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6114 sizeof(struct pte_list_desc),
6115 0, SLAB_ACCOUNT, NULL);
6116 if (!pte_list_desc_cache)
6119 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6120 sizeof(struct kvm_mmu_page),
6121 0, SLAB_ACCOUNT, NULL);
6122 if (!mmu_page_header_cache)
6125 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6128 ret = register_shrinker(&mmu_shrinker);
6135 mmu_destroy_caches();
6140 * Calculate mmu pages needed for kvm.
6142 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6144 unsigned long nr_mmu_pages;
6145 unsigned long nr_pages = 0;
6146 struct kvm_memslots *slots;
6147 struct kvm_memory_slot *memslot;
6150 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6151 slots = __kvm_memslots(kvm, i);
6153 kvm_for_each_memslot(memslot, slots)
6154 nr_pages += memslot->npages;
6157 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6158 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6160 return nr_mmu_pages;
6163 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6165 kvm_mmu_unload(vcpu);
6166 free_mmu_pages(&vcpu->arch.root_mmu);
6167 free_mmu_pages(&vcpu->arch.guest_mmu);
6168 mmu_free_memory_caches(vcpu);
6171 void kvm_mmu_module_exit(void)
6173 mmu_destroy_caches();
6174 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6175 unregister_shrinker(&mmu_shrinker);
6176 mmu_audit_disable();