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 page_header(__pa(sptep))->mmio_cached = true;
408 trace_mark_mmio_spte(sptep, gfn, access, gen);
409 mmu_spte_set(sptep, mask);
412 static gfn_t get_mmio_spte_gfn(u64 spte)
414 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
416 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
417 & shadow_nonpresent_or_rsvd_mask;
419 return gpa >> PAGE_SHIFT;
422 static unsigned get_mmio_spte_access(u64 spte)
424 return spte & shadow_mmio_access_mask;
427 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
428 kvm_pfn_t pfn, unsigned access)
430 if (unlikely(is_noslot_pfn(pfn))) {
431 mark_mmio_spte(vcpu, sptep, gfn, access);
438 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
440 u64 kvm_gen, spte_gen, gen;
442 gen = kvm_vcpu_memslots(vcpu)->generation;
443 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
446 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
447 spte_gen = get_mmio_spte_generation(spte);
449 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
450 return likely(kvm_gen == spte_gen);
454 * Sets the shadow PTE masks used by the MMU.
457 * - Setting either @accessed_mask or @dirty_mask requires setting both
458 * - At least one of @accessed_mask or @acc_track_mask must be set
460 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
461 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
462 u64 acc_track_mask, u64 me_mask)
464 BUG_ON(!dirty_mask != !accessed_mask);
465 BUG_ON(!accessed_mask && !acc_track_mask);
466 BUG_ON(acc_track_mask & shadow_acc_track_value);
468 shadow_user_mask = user_mask;
469 shadow_accessed_mask = accessed_mask;
470 shadow_dirty_mask = dirty_mask;
471 shadow_nx_mask = nx_mask;
472 shadow_x_mask = x_mask;
473 shadow_present_mask = p_mask;
474 shadow_acc_track_mask = acc_track_mask;
475 shadow_me_mask = me_mask;
477 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
479 static u8 kvm_get_shadow_phys_bits(void)
482 * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
483 * in CPU detection code, but MKTME treats those reduced bits as
484 * 'keyID' thus they are not reserved bits. Therefore for MKTME
485 * we should still return physical address bits reported by CPUID.
487 if (!boot_cpu_has(X86_FEATURE_TME) ||
488 WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
489 return boot_cpu_data.x86_phys_bits;
491 return cpuid_eax(0x80000008) & 0xff;
494 static void kvm_mmu_reset_all_pte_masks(void)
498 shadow_user_mask = 0;
499 shadow_accessed_mask = 0;
500 shadow_dirty_mask = 0;
503 shadow_mmio_mask = 0;
504 shadow_present_mask = 0;
505 shadow_acc_track_mask = 0;
507 shadow_phys_bits = kvm_get_shadow_phys_bits();
510 * If the CPU has 46 or less physical address bits, then set an
511 * appropriate mask to guard against L1TF attacks. Otherwise, it is
512 * assumed that the CPU is not vulnerable to L1TF.
514 * Some Intel CPUs address the L1 cache using more PA bits than are
515 * reported by CPUID. Use the PA width of the L1 cache when possible
516 * to achieve more effective mitigation, e.g. if system RAM overlaps
517 * the most significant bits of legal physical address space.
519 shadow_nonpresent_or_rsvd_mask = 0;
520 low_phys_bits = boot_cpu_data.x86_cache_bits;
521 if (boot_cpu_data.x86_cache_bits <
522 52 - shadow_nonpresent_or_rsvd_mask_len) {
523 shadow_nonpresent_or_rsvd_mask =
524 rsvd_bits(boot_cpu_data.x86_cache_bits -
525 shadow_nonpresent_or_rsvd_mask_len,
526 boot_cpu_data.x86_cache_bits - 1);
527 low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
529 WARN_ON_ONCE(boot_cpu_has_bug(X86_BUG_L1TF));
531 shadow_nonpresent_or_rsvd_lower_gfn_mask =
532 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
535 static int is_cpuid_PSE36(void)
540 static int is_nx(struct kvm_vcpu *vcpu)
542 return vcpu->arch.efer & EFER_NX;
545 static int is_shadow_present_pte(u64 pte)
547 return (pte != 0) && !is_mmio_spte(pte);
550 static int is_large_pte(u64 pte)
552 return pte & PT_PAGE_SIZE_MASK;
555 static int is_last_spte(u64 pte, int level)
557 if (level == PT_PAGE_TABLE_LEVEL)
559 if (is_large_pte(pte))
564 static bool is_executable_pte(u64 spte)
566 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
569 static kvm_pfn_t spte_to_pfn(u64 pte)
571 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
574 static gfn_t pse36_gfn_delta(u32 gpte)
576 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
578 return (gpte & PT32_DIR_PSE36_MASK) << shift;
582 static void __set_spte(u64 *sptep, u64 spte)
584 WRITE_ONCE(*sptep, spte);
587 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
589 WRITE_ONCE(*sptep, spte);
592 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
594 return xchg(sptep, spte);
597 static u64 __get_spte_lockless(u64 *sptep)
599 return READ_ONCE(*sptep);
610 static void count_spte_clear(u64 *sptep, u64 spte)
612 struct kvm_mmu_page *sp = page_header(__pa(sptep));
614 if (is_shadow_present_pte(spte))
617 /* Ensure the spte is completely set before we increase the count */
619 sp->clear_spte_count++;
622 static void __set_spte(u64 *sptep, u64 spte)
624 union split_spte *ssptep, sspte;
626 ssptep = (union split_spte *)sptep;
627 sspte = (union split_spte)spte;
629 ssptep->spte_high = sspte.spte_high;
632 * If we map the spte from nonpresent to present, We should store
633 * the high bits firstly, then set present bit, so cpu can not
634 * fetch this spte while we are setting the spte.
638 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
641 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
643 union split_spte *ssptep, sspte;
645 ssptep = (union split_spte *)sptep;
646 sspte = (union split_spte)spte;
648 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
651 * If we map the spte from present to nonpresent, we should clear
652 * present bit firstly to avoid vcpu fetch the old high bits.
656 ssptep->spte_high = sspte.spte_high;
657 count_spte_clear(sptep, spte);
660 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
662 union split_spte *ssptep, sspte, orig;
664 ssptep = (union split_spte *)sptep;
665 sspte = (union split_spte)spte;
667 /* xchg acts as a barrier before the setting of the high bits */
668 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
669 orig.spte_high = ssptep->spte_high;
670 ssptep->spte_high = sspte.spte_high;
671 count_spte_clear(sptep, spte);
677 * The idea using the light way get the spte on x86_32 guest is from
678 * gup_get_pte (mm/gup.c).
680 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
681 * coalesces them and we are running out of the MMU lock. Therefore
682 * we need to protect against in-progress updates of the spte.
684 * Reading the spte while an update is in progress may get the old value
685 * for the high part of the spte. The race is fine for a present->non-present
686 * change (because the high part of the spte is ignored for non-present spte),
687 * but for a present->present change we must reread the spte.
689 * All such changes are done in two steps (present->non-present and
690 * non-present->present), hence it is enough to count the number of
691 * present->non-present updates: if it changed while reading the spte,
692 * we might have hit the race. This is done using clear_spte_count.
694 static u64 __get_spte_lockless(u64 *sptep)
696 struct kvm_mmu_page *sp = page_header(__pa(sptep));
697 union split_spte spte, *orig = (union split_spte *)sptep;
701 count = sp->clear_spte_count;
704 spte.spte_low = orig->spte_low;
707 spte.spte_high = orig->spte_high;
710 if (unlikely(spte.spte_low != orig->spte_low ||
711 count != sp->clear_spte_count))
718 static bool spte_can_locklessly_be_made_writable(u64 spte)
720 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
721 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
724 static bool spte_has_volatile_bits(u64 spte)
726 if (!is_shadow_present_pte(spte))
730 * Always atomically update spte if it can be updated
731 * out of mmu-lock, it can ensure dirty bit is not lost,
732 * also, it can help us to get a stable is_writable_pte()
733 * to ensure tlb flush is not missed.
735 if (spte_can_locklessly_be_made_writable(spte) ||
736 is_access_track_spte(spte))
739 if (spte_ad_enabled(spte)) {
740 if ((spte & shadow_accessed_mask) == 0 ||
741 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
748 static bool is_accessed_spte(u64 spte)
750 u64 accessed_mask = spte_shadow_accessed_mask(spte);
752 return accessed_mask ? spte & accessed_mask
753 : !is_access_track_spte(spte);
756 static bool is_dirty_spte(u64 spte)
758 u64 dirty_mask = spte_shadow_dirty_mask(spte);
760 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
763 /* Rules for using mmu_spte_set:
764 * Set the sptep from nonpresent to present.
765 * Note: the sptep being assigned *must* be either not present
766 * or in a state where the hardware will not attempt to update
769 static void mmu_spte_set(u64 *sptep, u64 new_spte)
771 WARN_ON(is_shadow_present_pte(*sptep));
772 __set_spte(sptep, new_spte);
776 * Update the SPTE (excluding the PFN), but do not track changes in its
777 * accessed/dirty status.
779 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
781 u64 old_spte = *sptep;
783 WARN_ON(!is_shadow_present_pte(new_spte));
785 if (!is_shadow_present_pte(old_spte)) {
786 mmu_spte_set(sptep, new_spte);
790 if (!spte_has_volatile_bits(old_spte))
791 __update_clear_spte_fast(sptep, new_spte);
793 old_spte = __update_clear_spte_slow(sptep, new_spte);
795 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
800 /* Rules for using mmu_spte_update:
801 * Update the state bits, it means the mapped pfn is not changed.
803 * Whenever we overwrite a writable spte with a read-only one we
804 * should flush remote TLBs. Otherwise rmap_write_protect
805 * will find a read-only spte, even though the writable spte
806 * might be cached on a CPU's TLB, the return value indicates this
809 * Returns true if the TLB needs to be flushed
811 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
814 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
816 if (!is_shadow_present_pte(old_spte))
820 * For the spte updated out of mmu-lock is safe, since
821 * we always atomically update it, see the comments in
822 * spte_has_volatile_bits().
824 if (spte_can_locklessly_be_made_writable(old_spte) &&
825 !is_writable_pte(new_spte))
829 * Flush TLB when accessed/dirty states are changed in the page tables,
830 * to guarantee consistency between TLB and page tables.
833 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
835 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
838 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
840 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
847 * Rules for using mmu_spte_clear_track_bits:
848 * It sets the sptep from present to nonpresent, and track the
849 * state bits, it is used to clear the last level sptep.
850 * Returns non-zero if the PTE was previously valid.
852 static int mmu_spte_clear_track_bits(u64 *sptep)
855 u64 old_spte = *sptep;
857 if (!spte_has_volatile_bits(old_spte))
858 __update_clear_spte_fast(sptep, 0ull);
860 old_spte = __update_clear_spte_slow(sptep, 0ull);
862 if (!is_shadow_present_pte(old_spte))
865 pfn = spte_to_pfn(old_spte);
868 * KVM does not hold the refcount of the page used by
869 * kvm mmu, before reclaiming the page, we should
870 * unmap it from mmu first.
872 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
874 if (is_accessed_spte(old_spte))
875 kvm_set_pfn_accessed(pfn);
877 if (is_dirty_spte(old_spte))
878 kvm_set_pfn_dirty(pfn);
884 * Rules for using mmu_spte_clear_no_track:
885 * Directly clear spte without caring the state bits of sptep,
886 * it is used to set the upper level spte.
888 static void mmu_spte_clear_no_track(u64 *sptep)
890 __update_clear_spte_fast(sptep, 0ull);
893 static u64 mmu_spte_get_lockless(u64 *sptep)
895 return __get_spte_lockless(sptep);
898 static u64 mark_spte_for_access_track(u64 spte)
900 if (spte_ad_enabled(spte))
901 return spte & ~shadow_accessed_mask;
903 if (is_access_track_spte(spte))
907 * Making an Access Tracking PTE will result in removal of write access
908 * from the PTE. So, verify that we will be able to restore the write
909 * access in the fast page fault path later on.
911 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
912 !spte_can_locklessly_be_made_writable(spte),
913 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
915 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
916 shadow_acc_track_saved_bits_shift),
917 "kvm: Access Tracking saved bit locations are not zero\n");
919 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
920 shadow_acc_track_saved_bits_shift;
921 spte &= ~shadow_acc_track_mask;
926 /* Restore an acc-track PTE back to a regular PTE */
927 static u64 restore_acc_track_spte(u64 spte)
930 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
931 & shadow_acc_track_saved_bits_mask;
933 WARN_ON_ONCE(spte_ad_enabled(spte));
934 WARN_ON_ONCE(!is_access_track_spte(spte));
936 new_spte &= ~shadow_acc_track_mask;
937 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
938 shadow_acc_track_saved_bits_shift);
939 new_spte |= saved_bits;
944 /* Returns the Accessed status of the PTE and resets it at the same time. */
945 static bool mmu_spte_age(u64 *sptep)
947 u64 spte = mmu_spte_get_lockless(sptep);
949 if (!is_accessed_spte(spte))
952 if (spte_ad_enabled(spte)) {
953 clear_bit((ffs(shadow_accessed_mask) - 1),
954 (unsigned long *)sptep);
957 * Capture the dirty status of the page, so that it doesn't get
958 * lost when the SPTE is marked for access tracking.
960 if (is_writable_pte(spte))
961 kvm_set_pfn_dirty(spte_to_pfn(spte));
963 spte = mark_spte_for_access_track(spte);
964 mmu_spte_update_no_track(sptep, spte);
970 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
973 * Prevent page table teardown by making any free-er wait during
974 * kvm_flush_remote_tlbs() IPI to all active vcpus.
979 * Make sure a following spte read is not reordered ahead of the write
982 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
985 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
988 * Make sure the write to vcpu->mode is not reordered in front of
989 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
990 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
992 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
996 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
997 struct kmem_cache *base_cache, int min)
1001 if (cache->nobjs >= min)
1003 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1004 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL_ACCOUNT);
1006 return cache->nobjs >= min ? 0 : -ENOMEM;
1007 cache->objects[cache->nobjs++] = obj;
1012 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
1014 return cache->nobjs;
1017 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
1018 struct kmem_cache *cache)
1021 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
1024 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1029 if (cache->nobjs >= min)
1031 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1032 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1034 return cache->nobjs >= min ? 0 : -ENOMEM;
1035 cache->objects[cache->nobjs++] = page;
1040 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1043 free_page((unsigned long)mc->objects[--mc->nobjs]);
1046 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1050 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1051 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1054 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1057 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1058 mmu_page_header_cache, 4);
1063 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1065 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1066 pte_list_desc_cache);
1067 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1068 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1069 mmu_page_header_cache);
1072 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1077 p = mc->objects[--mc->nobjs];
1081 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1083 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1086 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1088 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1091 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1093 if (!sp->role.direct)
1094 return sp->gfns[index];
1096 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1099 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1101 if (!sp->role.direct) {
1102 sp->gfns[index] = gfn;
1106 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1107 pr_err_ratelimited("gfn mismatch under direct page %llx "
1108 "(expected %llx, got %llx)\n",
1110 kvm_mmu_page_get_gfn(sp, index), gfn);
1114 * Return the pointer to the large page information for a given gfn,
1115 * handling slots that are not large page aligned.
1117 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1118 struct kvm_memory_slot *slot,
1123 idx = gfn_to_index(gfn, slot->base_gfn, level);
1124 return &slot->arch.lpage_info[level - 2][idx];
1127 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1128 gfn_t gfn, int count)
1130 struct kvm_lpage_info *linfo;
1133 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1134 linfo = lpage_info_slot(gfn, slot, i);
1135 linfo->disallow_lpage += count;
1136 WARN_ON(linfo->disallow_lpage < 0);
1140 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1142 update_gfn_disallow_lpage_count(slot, gfn, 1);
1145 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1147 update_gfn_disallow_lpage_count(slot, gfn, -1);
1150 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1152 struct kvm_memslots *slots;
1153 struct kvm_memory_slot *slot;
1156 kvm->arch.indirect_shadow_pages++;
1158 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1159 slot = __gfn_to_memslot(slots, gfn);
1161 /* the non-leaf shadow pages are keeping readonly. */
1162 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1163 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1164 KVM_PAGE_TRACK_WRITE);
1166 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1169 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1171 struct kvm_memslots *slots;
1172 struct kvm_memory_slot *slot;
1175 kvm->arch.indirect_shadow_pages--;
1177 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1178 slot = __gfn_to_memslot(slots, gfn);
1179 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1180 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1181 KVM_PAGE_TRACK_WRITE);
1183 kvm_mmu_gfn_allow_lpage(slot, gfn);
1186 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1187 struct kvm_memory_slot *slot)
1189 struct kvm_lpage_info *linfo;
1192 linfo = lpage_info_slot(gfn, slot, level);
1193 return !!linfo->disallow_lpage;
1199 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1202 struct kvm_memory_slot *slot;
1204 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1205 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1208 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1210 unsigned long page_size;
1213 page_size = kvm_host_page_size(kvm, gfn);
1215 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1216 if (page_size >= KVM_HPAGE_SIZE(i))
1225 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1228 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1230 if (no_dirty_log && slot->dirty_bitmap)
1236 static struct kvm_memory_slot *
1237 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1240 struct kvm_memory_slot *slot;
1242 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1243 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1249 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1250 bool *force_pt_level)
1252 int host_level, level, max_level;
1253 struct kvm_memory_slot *slot;
1255 if (unlikely(*force_pt_level))
1256 return PT_PAGE_TABLE_LEVEL;
1258 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1259 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1260 if (unlikely(*force_pt_level))
1261 return PT_PAGE_TABLE_LEVEL;
1263 host_level = host_mapping_level(vcpu->kvm, large_gfn);
1265 if (host_level == PT_PAGE_TABLE_LEVEL)
1268 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1270 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1271 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1278 * About rmap_head encoding:
1280 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1281 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1282 * pte_list_desc containing more mappings.
1286 * Returns the number of pointers in the rmap chain, not counting the new one.
1288 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1289 struct kvm_rmap_head *rmap_head)
1291 struct pte_list_desc *desc;
1294 if (!rmap_head->val) {
1295 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1296 rmap_head->val = (unsigned long)spte;
1297 } else if (!(rmap_head->val & 1)) {
1298 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1299 desc = mmu_alloc_pte_list_desc(vcpu);
1300 desc->sptes[0] = (u64 *)rmap_head->val;
1301 desc->sptes[1] = spte;
1302 rmap_head->val = (unsigned long)desc | 1;
1305 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1306 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1307 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1309 count += PTE_LIST_EXT;
1311 if (desc->sptes[PTE_LIST_EXT-1]) {
1312 desc->more = mmu_alloc_pte_list_desc(vcpu);
1315 for (i = 0; desc->sptes[i]; ++i)
1317 desc->sptes[i] = spte;
1323 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1324 struct pte_list_desc *desc, int i,
1325 struct pte_list_desc *prev_desc)
1329 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1331 desc->sptes[i] = desc->sptes[j];
1332 desc->sptes[j] = NULL;
1335 if (!prev_desc && !desc->more)
1336 rmap_head->val = (unsigned long)desc->sptes[0];
1339 prev_desc->more = desc->more;
1341 rmap_head->val = (unsigned long)desc->more | 1;
1342 mmu_free_pte_list_desc(desc);
1345 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1347 struct pte_list_desc *desc;
1348 struct pte_list_desc *prev_desc;
1351 if (!rmap_head->val) {
1352 pr_err("%s: %p 0->BUG\n", __func__, spte);
1354 } else if (!(rmap_head->val & 1)) {
1355 rmap_printk("%s: %p 1->0\n", __func__, spte);
1356 if ((u64 *)rmap_head->val != spte) {
1357 pr_err("%s: %p 1->BUG\n", __func__, spte);
1362 rmap_printk("%s: %p many->many\n", __func__, spte);
1363 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1366 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1367 if (desc->sptes[i] == spte) {
1368 pte_list_desc_remove_entry(rmap_head,
1369 desc, i, prev_desc);
1376 pr_err("%s: %p many->many\n", __func__, spte);
1381 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1383 mmu_spte_clear_track_bits(sptep);
1384 __pte_list_remove(sptep, rmap_head);
1387 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1388 struct kvm_memory_slot *slot)
1392 idx = gfn_to_index(gfn, slot->base_gfn, level);
1393 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1396 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1397 struct kvm_mmu_page *sp)
1399 struct kvm_memslots *slots;
1400 struct kvm_memory_slot *slot;
1402 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1403 slot = __gfn_to_memslot(slots, gfn);
1404 return __gfn_to_rmap(gfn, sp->role.level, slot);
1407 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1409 struct kvm_mmu_memory_cache *cache;
1411 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1412 return mmu_memory_cache_free_objects(cache);
1415 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1417 struct kvm_mmu_page *sp;
1418 struct kvm_rmap_head *rmap_head;
1420 sp = page_header(__pa(spte));
1421 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1422 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1423 return pte_list_add(vcpu, spte, rmap_head);
1426 static void rmap_remove(struct kvm *kvm, u64 *spte)
1428 struct kvm_mmu_page *sp;
1430 struct kvm_rmap_head *rmap_head;
1432 sp = page_header(__pa(spte));
1433 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1434 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1435 __pte_list_remove(spte, rmap_head);
1439 * Used by the following functions to iterate through the sptes linked by a
1440 * rmap. All fields are private and not assumed to be used outside.
1442 struct rmap_iterator {
1443 /* private fields */
1444 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1445 int pos; /* index of the sptep */
1449 * Iteration must be started by this function. This should also be used after
1450 * removing/dropping sptes from the rmap link because in such cases the
1451 * information in the itererator may not be valid.
1453 * Returns sptep if found, NULL otherwise.
1455 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1456 struct rmap_iterator *iter)
1460 if (!rmap_head->val)
1463 if (!(rmap_head->val & 1)) {
1465 sptep = (u64 *)rmap_head->val;
1469 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1471 sptep = iter->desc->sptes[iter->pos];
1473 BUG_ON(!is_shadow_present_pte(*sptep));
1478 * Must be used with a valid iterator: e.g. after rmap_get_first().
1480 * Returns sptep if found, NULL otherwise.
1482 static u64 *rmap_get_next(struct rmap_iterator *iter)
1487 if (iter->pos < PTE_LIST_EXT - 1) {
1489 sptep = iter->desc->sptes[iter->pos];
1494 iter->desc = iter->desc->more;
1498 /* desc->sptes[0] cannot be NULL */
1499 sptep = iter->desc->sptes[iter->pos];
1506 BUG_ON(!is_shadow_present_pte(*sptep));
1510 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1511 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1512 _spte_; _spte_ = rmap_get_next(_iter_))
1514 static void drop_spte(struct kvm *kvm, u64 *sptep)
1516 if (mmu_spte_clear_track_bits(sptep))
1517 rmap_remove(kvm, sptep);
1521 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1523 if (is_large_pte(*sptep)) {
1524 WARN_ON(page_header(__pa(sptep))->role.level ==
1525 PT_PAGE_TABLE_LEVEL);
1526 drop_spte(kvm, sptep);
1534 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1536 if (__drop_large_spte(vcpu->kvm, sptep)) {
1537 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1539 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1540 KVM_PAGES_PER_HPAGE(sp->role.level));
1545 * Write-protect on the specified @sptep, @pt_protect indicates whether
1546 * spte write-protection is caused by protecting shadow page table.
1548 * Note: write protection is difference between dirty logging and spte
1550 * - for dirty logging, the spte can be set to writable at anytime if
1551 * its dirty bitmap is properly set.
1552 * - for spte protection, the spte can be writable only after unsync-ing
1555 * Return true if tlb need be flushed.
1557 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1561 if (!is_writable_pte(spte) &&
1562 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1565 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1568 spte &= ~SPTE_MMU_WRITEABLE;
1569 spte = spte & ~PT_WRITABLE_MASK;
1571 return mmu_spte_update(sptep, spte);
1574 static bool __rmap_write_protect(struct kvm *kvm,
1575 struct kvm_rmap_head *rmap_head,
1579 struct rmap_iterator iter;
1582 for_each_rmap_spte(rmap_head, &iter, sptep)
1583 flush |= spte_write_protect(sptep, pt_protect);
1588 static bool spte_clear_dirty(u64 *sptep)
1592 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1594 spte &= ~shadow_dirty_mask;
1596 return mmu_spte_update(sptep, spte);
1599 static bool wrprot_ad_disabled_spte(u64 *sptep)
1601 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1602 (unsigned long *)sptep);
1604 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1606 return was_writable;
1610 * Gets the GFN ready for another round of dirty logging by clearing the
1611 * - D bit on ad-enabled SPTEs, and
1612 * - W bit on ad-disabled SPTEs.
1613 * Returns true iff any D or W bits were cleared.
1615 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1618 struct rmap_iterator iter;
1621 for_each_rmap_spte(rmap_head, &iter, sptep)
1622 if (spte_ad_enabled(*sptep))
1623 flush |= spte_clear_dirty(sptep);
1625 flush |= wrprot_ad_disabled_spte(sptep);
1630 static bool spte_set_dirty(u64 *sptep)
1634 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1636 spte |= shadow_dirty_mask;
1638 return mmu_spte_update(sptep, spte);
1641 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1644 struct rmap_iterator iter;
1647 for_each_rmap_spte(rmap_head, &iter, sptep)
1648 if (spte_ad_enabled(*sptep))
1649 flush |= spte_set_dirty(sptep);
1655 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1656 * @kvm: kvm instance
1657 * @slot: slot to protect
1658 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1659 * @mask: indicates which pages we should protect
1661 * Used when we do not need to care about huge page mappings: e.g. during dirty
1662 * logging we do not have any such mappings.
1664 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1665 struct kvm_memory_slot *slot,
1666 gfn_t gfn_offset, unsigned long mask)
1668 struct kvm_rmap_head *rmap_head;
1671 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1672 PT_PAGE_TABLE_LEVEL, slot);
1673 __rmap_write_protect(kvm, rmap_head, false);
1675 /* clear the first set bit */
1681 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1682 * protect the page if the D-bit isn't supported.
1683 * @kvm: kvm instance
1684 * @slot: slot to clear D-bit
1685 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1686 * @mask: indicates which pages we should clear D-bit
1688 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1690 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1691 struct kvm_memory_slot *slot,
1692 gfn_t gfn_offset, unsigned long mask)
1694 struct kvm_rmap_head *rmap_head;
1697 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1698 PT_PAGE_TABLE_LEVEL, slot);
1699 __rmap_clear_dirty(kvm, rmap_head);
1701 /* clear the first set bit */
1705 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1708 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1711 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1712 * enable dirty logging for them.
1714 * Used when we do not need to care about huge page mappings: e.g. during dirty
1715 * logging we do not have any such mappings.
1717 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1718 struct kvm_memory_slot *slot,
1719 gfn_t gfn_offset, unsigned long mask)
1721 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1722 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1725 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1729 * kvm_arch_write_log_dirty - emulate dirty page logging
1730 * @vcpu: Guest mode vcpu
1732 * Emulate arch specific page modification logging for the
1735 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1737 if (kvm_x86_ops->write_log_dirty)
1738 return kvm_x86_ops->write_log_dirty(vcpu);
1743 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1744 struct kvm_memory_slot *slot, u64 gfn)
1746 struct kvm_rmap_head *rmap_head;
1748 bool write_protected = false;
1750 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1751 rmap_head = __gfn_to_rmap(gfn, i, slot);
1752 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1755 return write_protected;
1758 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1760 struct kvm_memory_slot *slot;
1762 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1763 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1766 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1769 struct rmap_iterator iter;
1772 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1773 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1775 pte_list_remove(rmap_head, sptep);
1782 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1783 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1786 return kvm_zap_rmapp(kvm, rmap_head);
1789 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1790 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1794 struct rmap_iterator iter;
1797 pte_t *ptep = (pte_t *)data;
1800 WARN_ON(pte_huge(*ptep));
1801 new_pfn = pte_pfn(*ptep);
1804 for_each_rmap_spte(rmap_head, &iter, sptep) {
1805 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1806 sptep, *sptep, gfn, level);
1810 if (pte_write(*ptep)) {
1811 pte_list_remove(rmap_head, sptep);
1814 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1815 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1817 new_spte &= ~PT_WRITABLE_MASK;
1818 new_spte &= ~SPTE_HOST_WRITEABLE;
1820 new_spte = mark_spte_for_access_track(new_spte);
1822 mmu_spte_clear_track_bits(sptep);
1823 mmu_spte_set(sptep, new_spte);
1827 if (need_flush && kvm_available_flush_tlb_with_range()) {
1828 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1835 struct slot_rmap_walk_iterator {
1837 struct kvm_memory_slot *slot;
1843 /* output fields. */
1845 struct kvm_rmap_head *rmap;
1848 /* private field. */
1849 struct kvm_rmap_head *end_rmap;
1853 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1855 iterator->level = level;
1856 iterator->gfn = iterator->start_gfn;
1857 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1858 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1863 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1864 struct kvm_memory_slot *slot, int start_level,
1865 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1867 iterator->slot = slot;
1868 iterator->start_level = start_level;
1869 iterator->end_level = end_level;
1870 iterator->start_gfn = start_gfn;
1871 iterator->end_gfn = end_gfn;
1873 rmap_walk_init_level(iterator, iterator->start_level);
1876 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1878 return !!iterator->rmap;
1881 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1883 if (++iterator->rmap <= iterator->end_rmap) {
1884 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1888 if (++iterator->level > iterator->end_level) {
1889 iterator->rmap = NULL;
1893 rmap_walk_init_level(iterator, iterator->level);
1896 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1897 _start_gfn, _end_gfn, _iter_) \
1898 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1899 _end_level_, _start_gfn, _end_gfn); \
1900 slot_rmap_walk_okay(_iter_); \
1901 slot_rmap_walk_next(_iter_))
1903 static int kvm_handle_hva_range(struct kvm *kvm,
1904 unsigned long start,
1907 int (*handler)(struct kvm *kvm,
1908 struct kvm_rmap_head *rmap_head,
1909 struct kvm_memory_slot *slot,
1912 unsigned long data))
1914 struct kvm_memslots *slots;
1915 struct kvm_memory_slot *memslot;
1916 struct slot_rmap_walk_iterator iterator;
1920 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1921 slots = __kvm_memslots(kvm, i);
1922 kvm_for_each_memslot(memslot, slots) {
1923 unsigned long hva_start, hva_end;
1924 gfn_t gfn_start, gfn_end;
1926 hva_start = max(start, memslot->userspace_addr);
1927 hva_end = min(end, memslot->userspace_addr +
1928 (memslot->npages << PAGE_SHIFT));
1929 if (hva_start >= hva_end)
1932 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1933 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1935 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1936 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1938 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1939 PT_MAX_HUGEPAGE_LEVEL,
1940 gfn_start, gfn_end - 1,
1942 ret |= handler(kvm, iterator.rmap, memslot,
1943 iterator.gfn, iterator.level, data);
1950 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1952 int (*handler)(struct kvm *kvm,
1953 struct kvm_rmap_head *rmap_head,
1954 struct kvm_memory_slot *slot,
1955 gfn_t gfn, int level,
1956 unsigned long data))
1958 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1961 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1963 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1966 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1968 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1971 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1972 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1976 struct rmap_iterator uninitialized_var(iter);
1979 for_each_rmap_spte(rmap_head, &iter, sptep)
1980 young |= mmu_spte_age(sptep);
1982 trace_kvm_age_page(gfn, level, slot, young);
1986 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1987 struct kvm_memory_slot *slot, gfn_t gfn,
1988 int level, unsigned long data)
1991 struct rmap_iterator iter;
1993 for_each_rmap_spte(rmap_head, &iter, sptep)
1994 if (is_accessed_spte(*sptep))
1999 #define RMAP_RECYCLE_THRESHOLD 1000
2001 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2003 struct kvm_rmap_head *rmap_head;
2004 struct kvm_mmu_page *sp;
2006 sp = page_header(__pa(spte));
2008 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2010 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2011 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
2012 KVM_PAGES_PER_HPAGE(sp->role.level));
2015 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2017 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2020 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2022 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2026 static int is_empty_shadow_page(u64 *spt)
2031 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2032 if (is_shadow_present_pte(*pos)) {
2033 printk(KERN_ERR "%s: %p %llx\n", __func__,
2042 * This value is the sum of all of the kvm instances's
2043 * kvm->arch.n_used_mmu_pages values. We need a global,
2044 * aggregate version in order to make the slab shrinker
2047 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2049 kvm->arch.n_used_mmu_pages += nr;
2050 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2053 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2055 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2056 hlist_del(&sp->hash_link);
2057 list_del(&sp->link);
2058 free_page((unsigned long)sp->spt);
2059 if (!sp->role.direct)
2060 free_page((unsigned long)sp->gfns);
2061 kmem_cache_free(mmu_page_header_cache, sp);
2064 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2066 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2069 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2070 struct kvm_mmu_page *sp, u64 *parent_pte)
2075 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2078 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2081 __pte_list_remove(parent_pte, &sp->parent_ptes);
2084 static void drop_parent_pte(struct kvm_mmu_page *sp,
2087 mmu_page_remove_parent_pte(sp, parent_pte);
2088 mmu_spte_clear_no_track(parent_pte);
2091 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2093 struct kvm_mmu_page *sp;
2095 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2096 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2098 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2099 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2102 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2103 * depends on valid pages being added to the head of the list. See
2104 * comments in kvm_zap_obsolete_pages().
2106 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2107 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2111 static void mark_unsync(u64 *spte);
2112 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2115 struct rmap_iterator iter;
2117 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2122 static void mark_unsync(u64 *spte)
2124 struct kvm_mmu_page *sp;
2127 sp = page_header(__pa(spte));
2128 index = spte - sp->spt;
2129 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2131 if (sp->unsync_children++)
2133 kvm_mmu_mark_parents_unsync(sp);
2136 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2137 struct kvm_mmu_page *sp)
2142 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2146 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2147 struct kvm_mmu_page *sp, u64 *spte,
2153 #define KVM_PAGE_ARRAY_NR 16
2155 struct kvm_mmu_pages {
2156 struct mmu_page_and_offset {
2157 struct kvm_mmu_page *sp;
2159 } page[KVM_PAGE_ARRAY_NR];
2163 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2169 for (i=0; i < pvec->nr; i++)
2170 if (pvec->page[i].sp == sp)
2173 pvec->page[pvec->nr].sp = sp;
2174 pvec->page[pvec->nr].idx = idx;
2176 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2179 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2181 --sp->unsync_children;
2182 WARN_ON((int)sp->unsync_children < 0);
2183 __clear_bit(idx, sp->unsync_child_bitmap);
2186 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2187 struct kvm_mmu_pages *pvec)
2189 int i, ret, nr_unsync_leaf = 0;
2191 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2192 struct kvm_mmu_page *child;
2193 u64 ent = sp->spt[i];
2195 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2196 clear_unsync_child_bit(sp, i);
2200 child = page_header(ent & PT64_BASE_ADDR_MASK);
2202 if (child->unsync_children) {
2203 if (mmu_pages_add(pvec, child, i))
2206 ret = __mmu_unsync_walk(child, pvec);
2208 clear_unsync_child_bit(sp, i);
2210 } else if (ret > 0) {
2211 nr_unsync_leaf += ret;
2214 } else if (child->unsync) {
2216 if (mmu_pages_add(pvec, child, i))
2219 clear_unsync_child_bit(sp, i);
2222 return nr_unsync_leaf;
2225 #define INVALID_INDEX (-1)
2227 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2228 struct kvm_mmu_pages *pvec)
2231 if (!sp->unsync_children)
2234 mmu_pages_add(pvec, sp, INVALID_INDEX);
2235 return __mmu_unsync_walk(sp, pvec);
2238 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2240 WARN_ON(!sp->unsync);
2241 trace_kvm_mmu_sync_page(sp);
2243 --kvm->stat.mmu_unsync;
2246 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2247 struct list_head *invalid_list);
2248 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2249 struct list_head *invalid_list);
2252 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2253 hlist_for_each_entry(_sp, \
2254 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2255 if (is_obsolete_sp((_kvm), (_sp))) { \
2258 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2259 for_each_valid_sp(_kvm, _sp, _gfn) \
2260 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2262 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2264 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2267 /* @sp->gfn should be write-protected at the call site */
2268 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2269 struct list_head *invalid_list)
2271 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2272 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2273 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2280 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2281 struct list_head *invalid_list,
2284 if (!remote_flush && list_empty(invalid_list))
2287 if (!list_empty(invalid_list))
2288 kvm_mmu_commit_zap_page(kvm, invalid_list);
2290 kvm_flush_remote_tlbs(kvm);
2294 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2295 struct list_head *invalid_list,
2296 bool remote_flush, bool local_flush)
2298 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2302 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2305 #ifdef CONFIG_KVM_MMU_AUDIT
2306 #include "mmu_audit.c"
2308 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2309 static void mmu_audit_disable(void) { }
2312 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2314 return sp->role.invalid ||
2315 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2318 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2319 struct list_head *invalid_list)
2321 kvm_unlink_unsync_page(vcpu->kvm, sp);
2322 return __kvm_sync_page(vcpu, sp, invalid_list);
2325 /* @gfn should be write-protected at the call site */
2326 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2327 struct list_head *invalid_list)
2329 struct kvm_mmu_page *s;
2332 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2336 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2337 ret |= kvm_sync_page(vcpu, s, invalid_list);
2343 struct mmu_page_path {
2344 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2345 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2348 #define for_each_sp(pvec, sp, parents, i) \
2349 for (i = mmu_pages_first(&pvec, &parents); \
2350 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2351 i = mmu_pages_next(&pvec, &parents, i))
2353 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2354 struct mmu_page_path *parents,
2359 for (n = i+1; n < pvec->nr; n++) {
2360 struct kvm_mmu_page *sp = pvec->page[n].sp;
2361 unsigned idx = pvec->page[n].idx;
2362 int level = sp->role.level;
2364 parents->idx[level-1] = idx;
2365 if (level == PT_PAGE_TABLE_LEVEL)
2368 parents->parent[level-2] = sp;
2374 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2375 struct mmu_page_path *parents)
2377 struct kvm_mmu_page *sp;
2383 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2385 sp = pvec->page[0].sp;
2386 level = sp->role.level;
2387 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2389 parents->parent[level-2] = sp;
2391 /* Also set up a sentinel. Further entries in pvec are all
2392 * children of sp, so this element is never overwritten.
2394 parents->parent[level-1] = NULL;
2395 return mmu_pages_next(pvec, parents, 0);
2398 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2400 struct kvm_mmu_page *sp;
2401 unsigned int level = 0;
2404 unsigned int idx = parents->idx[level];
2405 sp = parents->parent[level];
2409 WARN_ON(idx == INVALID_INDEX);
2410 clear_unsync_child_bit(sp, idx);
2412 } while (!sp->unsync_children);
2415 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2416 struct kvm_mmu_page *parent)
2419 struct kvm_mmu_page *sp;
2420 struct mmu_page_path parents;
2421 struct kvm_mmu_pages pages;
2422 LIST_HEAD(invalid_list);
2425 while (mmu_unsync_walk(parent, &pages)) {
2426 bool protected = false;
2428 for_each_sp(pages, sp, parents, i)
2429 protected |= rmap_write_protect(vcpu, sp->gfn);
2432 kvm_flush_remote_tlbs(vcpu->kvm);
2436 for_each_sp(pages, sp, parents, i) {
2437 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2438 mmu_pages_clear_parents(&parents);
2440 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2441 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2442 cond_resched_lock(&vcpu->kvm->mmu_lock);
2447 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2450 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2452 atomic_set(&sp->write_flooding_count, 0);
2455 static void clear_sp_write_flooding_count(u64 *spte)
2457 struct kvm_mmu_page *sp = page_header(__pa(spte));
2459 __clear_sp_write_flooding_count(sp);
2462 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2469 union kvm_mmu_page_role role;
2471 struct kvm_mmu_page *sp;
2472 bool need_sync = false;
2475 LIST_HEAD(invalid_list);
2477 role = vcpu->arch.mmu->mmu_role.base;
2479 role.direct = direct;
2481 role.gpte_is_8_bytes = true;
2482 role.access = access;
2483 if (!vcpu->arch.mmu->direct_map
2484 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2485 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2486 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2487 role.quadrant = quadrant;
2489 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2490 if (sp->gfn != gfn) {
2495 if (!need_sync && sp->unsync)
2498 if (sp->role.word != role.word)
2502 /* The page is good, but __kvm_sync_page might still end
2503 * up zapping it. If so, break in order to rebuild it.
2505 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2508 WARN_ON(!list_empty(&invalid_list));
2509 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2512 if (sp->unsync_children)
2513 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2515 __clear_sp_write_flooding_count(sp);
2516 trace_kvm_mmu_get_page(sp, false);
2520 ++vcpu->kvm->stat.mmu_cache_miss;
2522 sp = kvm_mmu_alloc_page(vcpu, direct);
2526 hlist_add_head(&sp->hash_link,
2527 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2530 * we should do write protection before syncing pages
2531 * otherwise the content of the synced shadow page may
2532 * be inconsistent with guest page table.
2534 account_shadowed(vcpu->kvm, sp);
2535 if (level == PT_PAGE_TABLE_LEVEL &&
2536 rmap_write_protect(vcpu, gfn))
2537 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2539 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2540 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2542 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2543 clear_page(sp->spt);
2544 trace_kvm_mmu_get_page(sp, true);
2546 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2548 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2549 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2553 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2554 struct kvm_vcpu *vcpu, hpa_t root,
2557 iterator->addr = addr;
2558 iterator->shadow_addr = root;
2559 iterator->level = vcpu->arch.mmu->shadow_root_level;
2561 if (iterator->level == PT64_ROOT_4LEVEL &&
2562 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2563 !vcpu->arch.mmu->direct_map)
2566 if (iterator->level == PT32E_ROOT_LEVEL) {
2568 * prev_root is currently only used for 64-bit hosts. So only
2569 * the active root_hpa is valid here.
2571 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2573 iterator->shadow_addr
2574 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2575 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2577 if (!iterator->shadow_addr)
2578 iterator->level = 0;
2582 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2583 struct kvm_vcpu *vcpu, u64 addr)
2585 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2589 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2591 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2594 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2595 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2599 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2602 if (is_last_spte(spte, iterator->level)) {
2603 iterator->level = 0;
2607 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2611 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2613 __shadow_walk_next(iterator, *iterator->sptep);
2616 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2617 struct kvm_mmu_page *sp)
2621 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2623 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2624 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2626 if (sp_ad_disabled(sp))
2627 spte |= shadow_acc_track_value;
2629 spte |= shadow_accessed_mask;
2631 mmu_spte_set(sptep, spte);
2633 mmu_page_add_parent_pte(vcpu, sp, sptep);
2635 if (sp->unsync_children || sp->unsync)
2639 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2640 unsigned direct_access)
2642 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2643 struct kvm_mmu_page *child;
2646 * For the direct sp, if the guest pte's dirty bit
2647 * changed form clean to dirty, it will corrupt the
2648 * sp's access: allow writable in the read-only sp,
2649 * so we should update the spte at this point to get
2650 * a new sp with the correct access.
2652 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2653 if (child->role.access == direct_access)
2656 drop_parent_pte(child, sptep);
2657 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2661 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2665 struct kvm_mmu_page *child;
2668 if (is_shadow_present_pte(pte)) {
2669 if (is_last_spte(pte, sp->role.level)) {
2670 drop_spte(kvm, spte);
2671 if (is_large_pte(pte))
2674 child = page_header(pte & PT64_BASE_ADDR_MASK);
2675 drop_parent_pte(child, spte);
2680 if (is_mmio_spte(pte))
2681 mmu_spte_clear_no_track(spte);
2686 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2687 struct kvm_mmu_page *sp)
2691 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2692 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2695 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2698 struct rmap_iterator iter;
2700 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2701 drop_parent_pte(sp, sptep);
2704 static int mmu_zap_unsync_children(struct kvm *kvm,
2705 struct kvm_mmu_page *parent,
2706 struct list_head *invalid_list)
2709 struct mmu_page_path parents;
2710 struct kvm_mmu_pages pages;
2712 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2715 while (mmu_unsync_walk(parent, &pages)) {
2716 struct kvm_mmu_page *sp;
2718 for_each_sp(pages, sp, parents, i) {
2719 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2720 mmu_pages_clear_parents(&parents);
2728 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2729 struct kvm_mmu_page *sp,
2730 struct list_head *invalid_list,
2735 trace_kvm_mmu_prepare_zap_page(sp);
2736 ++kvm->stat.mmu_shadow_zapped;
2737 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2738 kvm_mmu_page_unlink_children(kvm, sp);
2739 kvm_mmu_unlink_parents(kvm, sp);
2741 /* Zapping children means active_mmu_pages has become unstable. */
2742 list_unstable = *nr_zapped;
2744 if (!sp->role.invalid && !sp->role.direct)
2745 unaccount_shadowed(kvm, sp);
2748 kvm_unlink_unsync_page(kvm, sp);
2749 if (!sp->root_count) {
2752 list_move(&sp->link, invalid_list);
2753 kvm_mod_used_mmu_pages(kvm, -1);
2755 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2757 if (!sp->role.invalid)
2758 kvm_reload_remote_mmus(kvm);
2761 sp->role.invalid = 1;
2762 return list_unstable;
2765 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2766 struct list_head *invalid_list)
2770 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2774 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2775 struct list_head *invalid_list)
2777 struct kvm_mmu_page *sp, *nsp;
2779 if (list_empty(invalid_list))
2783 * We need to make sure everyone sees our modifications to
2784 * the page tables and see changes to vcpu->mode here. The barrier
2785 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2786 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2788 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2789 * guest mode and/or lockless shadow page table walks.
2791 kvm_flush_remote_tlbs(kvm);
2793 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2794 WARN_ON(!sp->role.invalid || sp->root_count);
2795 kvm_mmu_free_page(sp);
2799 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2800 struct list_head *invalid_list)
2802 struct kvm_mmu_page *sp;
2804 if (list_empty(&kvm->arch.active_mmu_pages))
2807 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2808 struct kvm_mmu_page, link);
2809 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2813 * Changing the number of mmu pages allocated to the vm
2814 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2816 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2818 LIST_HEAD(invalid_list);
2820 spin_lock(&kvm->mmu_lock);
2822 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2823 /* Need to free some mmu pages to achieve the goal. */
2824 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2825 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2828 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2829 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2832 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2834 spin_unlock(&kvm->mmu_lock);
2837 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2839 struct kvm_mmu_page *sp;
2840 LIST_HEAD(invalid_list);
2843 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2845 spin_lock(&kvm->mmu_lock);
2846 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2847 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2850 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2852 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2853 spin_unlock(&kvm->mmu_lock);
2857 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2859 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2861 trace_kvm_mmu_unsync_page(sp);
2862 ++vcpu->kvm->stat.mmu_unsync;
2865 kvm_mmu_mark_parents_unsync(sp);
2868 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2871 struct kvm_mmu_page *sp;
2873 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2876 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2883 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2884 kvm_unsync_page(vcpu, sp);
2888 * We need to ensure that the marking of unsync pages is visible
2889 * before the SPTE is updated to allow writes because
2890 * kvm_mmu_sync_roots() checks the unsync flags without holding
2891 * the MMU lock and so can race with this. If the SPTE was updated
2892 * before the page had been marked as unsync-ed, something like the
2893 * following could happen:
2896 * ---------------------------------------------------------------------
2897 * 1.2 Host updates SPTE
2899 * 2.1 Guest writes a GPTE for GVA X.
2900 * (GPTE being in the guest page table shadowed
2901 * by the SP from CPU 1.)
2902 * This reads SPTE during the page table walk.
2903 * Since SPTE.W is read as 1, there is no
2906 * 2.2 Guest issues TLB flush.
2907 * That causes a VM Exit.
2909 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2910 * Since it is false, so it just returns.
2912 * 2.4 Guest accesses GVA X.
2913 * Since the mapping in the SP was not updated,
2914 * so the old mapping for GVA X incorrectly
2918 * (sp->unsync = true)
2920 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2921 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2922 * pairs with this write barrier.
2929 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2932 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2934 * Some reserved pages, such as those from NVDIMM
2935 * DAX devices, are not for MMIO, and can be mapped
2936 * with cached memory type for better performance.
2937 * However, the above check misconceives those pages
2938 * as MMIO, and results in KVM mapping them with UC
2939 * memory type, which would hurt the performance.
2940 * Therefore, we check the host memory type in addition
2941 * and only treat UC/UC-/WC pages as MMIO.
2943 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2945 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2946 pfn_to_hpa(pfn + 1) - 1,
2950 /* Bits which may be returned by set_spte() */
2951 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2952 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2954 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2955 unsigned pte_access, int level,
2956 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2957 bool can_unsync, bool host_writable)
2961 struct kvm_mmu_page *sp;
2963 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2966 sp = page_header(__pa(sptep));
2967 if (sp_ad_disabled(sp))
2968 spte |= shadow_acc_track_value;
2971 * For the EPT case, shadow_present_mask is 0 if hardware
2972 * supports exec-only page table entries. In that case,
2973 * ACC_USER_MASK and shadow_user_mask are used to represent
2974 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2976 spte |= shadow_present_mask;
2978 spte |= spte_shadow_accessed_mask(spte);
2980 if (pte_access & ACC_EXEC_MASK)
2981 spte |= shadow_x_mask;
2983 spte |= shadow_nx_mask;
2985 if (pte_access & ACC_USER_MASK)
2986 spte |= shadow_user_mask;
2988 if (level > PT_PAGE_TABLE_LEVEL)
2989 spte |= PT_PAGE_SIZE_MASK;
2991 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2992 kvm_is_mmio_pfn(pfn));
2995 spte |= SPTE_HOST_WRITEABLE;
2997 pte_access &= ~ACC_WRITE_MASK;
2999 if (!kvm_is_mmio_pfn(pfn))
3000 spte |= shadow_me_mask;
3002 spte |= (u64)pfn << PAGE_SHIFT;
3004 if (pte_access & ACC_WRITE_MASK) {
3007 * Other vcpu creates new sp in the window between
3008 * mapping_level() and acquiring mmu-lock. We can
3009 * allow guest to retry the access, the mapping can
3010 * be fixed if guest refault.
3012 if (level > PT_PAGE_TABLE_LEVEL &&
3013 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3016 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3019 * Optimization: for pte sync, if spte was writable the hash
3020 * lookup is unnecessary (and expensive). Write protection
3021 * is responsibility of mmu_get_page / kvm_sync_page.
3022 * Same reasoning can be applied to dirty page accounting.
3024 if (!can_unsync && is_writable_pte(*sptep))
3027 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3028 pgprintk("%s: found shadow page for %llx, marking ro\n",
3030 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3031 pte_access &= ~ACC_WRITE_MASK;
3032 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3036 if (pte_access & ACC_WRITE_MASK) {
3037 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3038 spte |= spte_shadow_dirty_mask(spte);
3042 spte = mark_spte_for_access_track(spte);
3045 if (mmu_spte_update(sptep, spte))
3046 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3051 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3052 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3053 bool speculative, bool host_writable)
3055 int was_rmapped = 0;
3058 int ret = RET_PF_RETRY;
3061 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3062 *sptep, write_fault, gfn);
3064 if (is_shadow_present_pte(*sptep)) {
3066 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3067 * the parent of the now unreachable PTE.
3069 if (level > PT_PAGE_TABLE_LEVEL &&
3070 !is_large_pte(*sptep)) {
3071 struct kvm_mmu_page *child;
3074 child = page_header(pte & PT64_BASE_ADDR_MASK);
3075 drop_parent_pte(child, sptep);
3077 } else if (pfn != spte_to_pfn(*sptep)) {
3078 pgprintk("hfn old %llx new %llx\n",
3079 spte_to_pfn(*sptep), pfn);
3080 drop_spte(vcpu->kvm, sptep);
3086 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3087 speculative, true, host_writable);
3088 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3090 ret = RET_PF_EMULATE;
3091 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3094 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3095 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3096 KVM_PAGES_PER_HPAGE(level));
3098 if (unlikely(is_mmio_spte(*sptep)))
3099 ret = RET_PF_EMULATE;
3101 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3102 trace_kvm_mmu_set_spte(level, gfn, sptep);
3103 if (!was_rmapped && is_large_pte(*sptep))
3104 ++vcpu->kvm->stat.lpages;
3106 if (is_shadow_present_pte(*sptep)) {
3108 rmap_count = rmap_add(vcpu, sptep, gfn);
3109 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3110 rmap_recycle(vcpu, sptep, gfn);
3117 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3120 struct kvm_memory_slot *slot;
3122 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3124 return KVM_PFN_ERR_FAULT;
3126 return gfn_to_pfn_memslot_atomic(slot, gfn);
3129 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3130 struct kvm_mmu_page *sp,
3131 u64 *start, u64 *end)
3133 struct page *pages[PTE_PREFETCH_NUM];
3134 struct kvm_memory_slot *slot;
3135 unsigned access = sp->role.access;
3139 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3140 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3144 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3148 for (i = 0; i < ret; i++, gfn++, start++) {
3149 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3150 page_to_pfn(pages[i]), true, true);
3157 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3158 struct kvm_mmu_page *sp, u64 *sptep)
3160 u64 *spte, *start = NULL;
3163 WARN_ON(!sp->role.direct);
3165 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3168 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3169 if (is_shadow_present_pte(*spte) || spte == sptep) {
3172 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3180 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3182 struct kvm_mmu_page *sp;
3184 sp = page_header(__pa(sptep));
3187 * Without accessed bits, there's no way to distinguish between
3188 * actually accessed translations and prefetched, so disable pte
3189 * prefetch if accessed bits aren't available.
3191 if (sp_ad_disabled(sp))
3194 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3197 __direct_pte_prefetch(vcpu, sp, sptep);
3200 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3201 int map_writable, int level, kvm_pfn_t pfn,
3204 struct kvm_shadow_walk_iterator it;
3205 struct kvm_mmu_page *sp;
3207 gfn_t gfn = gpa >> PAGE_SHIFT;
3208 gfn_t base_gfn = gfn;
3210 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3211 return RET_PF_RETRY;
3213 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3214 for_each_shadow_entry(vcpu, gpa, it) {
3215 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3216 if (it.level == level)
3219 drop_large_spte(vcpu, it.sptep);
3220 if (!is_shadow_present_pte(*it.sptep)) {
3221 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3222 it.level - 1, true, ACC_ALL);
3224 link_shadow_page(vcpu, it.sptep, sp);
3228 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3229 write, level, base_gfn, pfn, prefault,
3231 direct_pte_prefetch(vcpu, it.sptep);
3232 ++vcpu->stat.pf_fixed;
3236 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3238 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3241 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3244 * Do not cache the mmio info caused by writing the readonly gfn
3245 * into the spte otherwise read access on readonly gfn also can
3246 * caused mmio page fault and treat it as mmio access.
3248 if (pfn == KVM_PFN_ERR_RO_FAULT)
3249 return RET_PF_EMULATE;
3251 if (pfn == KVM_PFN_ERR_HWPOISON) {
3252 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3253 return RET_PF_RETRY;
3259 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3260 gfn_t gfn, kvm_pfn_t *pfnp,
3263 kvm_pfn_t pfn = *pfnp;
3264 int level = *levelp;
3267 * Check if it's a transparent hugepage. If this would be an
3268 * hugetlbfs page, level wouldn't be set to
3269 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3272 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3273 level == PT_PAGE_TABLE_LEVEL &&
3274 PageTransCompoundMap(pfn_to_page(pfn)) &&
3275 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3278 * mmu_notifier_retry was successful and we hold the
3279 * mmu_lock here, so the pmd can't become splitting
3280 * from under us, and in turn
3281 * __split_huge_page_refcount() can't run from under
3282 * us and we can safely transfer the refcount from
3283 * PG_tail to PG_head as we switch the pfn to tail to
3286 *levelp = level = PT_DIRECTORY_LEVEL;
3287 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3288 VM_BUG_ON((gfn & mask) != (pfn & mask));
3290 kvm_release_pfn_clean(pfn);
3298 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3299 kvm_pfn_t pfn, unsigned access, int *ret_val)
3301 /* The pfn is invalid, report the error! */
3302 if (unlikely(is_error_pfn(pfn))) {
3303 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3307 if (unlikely(is_noslot_pfn(pfn)))
3308 vcpu_cache_mmio_info(vcpu, gva, gfn,
3309 access & shadow_mmio_access_mask);
3314 static bool page_fault_can_be_fast(u32 error_code)
3317 * Do not fix the mmio spte with invalid generation number which
3318 * need to be updated by slow page fault path.
3320 if (unlikely(error_code & PFERR_RSVD_MASK))
3323 /* See if the page fault is due to an NX violation */
3324 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3325 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3329 * #PF can be fast if:
3330 * 1. The shadow page table entry is not present, which could mean that
3331 * the fault is potentially caused by access tracking (if enabled).
3332 * 2. The shadow page table entry is present and the fault
3333 * is caused by write-protect, that means we just need change the W
3334 * bit of the spte which can be done out of mmu-lock.
3336 * However, if access tracking is disabled we know that a non-present
3337 * page must be a genuine page fault where we have to create a new SPTE.
3338 * So, if access tracking is disabled, we return true only for write
3339 * accesses to a present page.
3342 return shadow_acc_track_mask != 0 ||
3343 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3344 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3348 * Returns true if the SPTE was fixed successfully. Otherwise,
3349 * someone else modified the SPTE from its original value.
3352 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3353 u64 *sptep, u64 old_spte, u64 new_spte)
3357 WARN_ON(!sp->role.direct);
3360 * Theoretically we could also set dirty bit (and flush TLB) here in
3361 * order to eliminate unnecessary PML logging. See comments in
3362 * set_spte. But fast_page_fault is very unlikely to happen with PML
3363 * enabled, so we do not do this. This might result in the same GPA
3364 * to be logged in PML buffer again when the write really happens, and
3365 * eventually to be called by mark_page_dirty twice. But it's also no
3366 * harm. This also avoids the TLB flush needed after setting dirty bit
3367 * so non-PML cases won't be impacted.
3369 * Compare with set_spte where instead shadow_dirty_mask is set.
3371 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3374 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3376 * The gfn of direct spte is stable since it is
3377 * calculated by sp->gfn.
3379 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3380 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3386 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3388 if (fault_err_code & PFERR_FETCH_MASK)
3389 return is_executable_pte(spte);
3391 if (fault_err_code & PFERR_WRITE_MASK)
3392 return is_writable_pte(spte);
3394 /* Fault was on Read access */
3395 return spte & PT_PRESENT_MASK;
3400 * - true: let the vcpu to access on the same address again.
3401 * - false: let the real page fault path to fix it.
3403 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3406 struct kvm_shadow_walk_iterator iterator;
3407 struct kvm_mmu_page *sp;
3408 bool fault_handled = false;
3410 uint retry_count = 0;
3412 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3415 if (!page_fault_can_be_fast(error_code))
3418 walk_shadow_page_lockless_begin(vcpu);
3423 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3424 if (!is_shadow_present_pte(spte) ||
3425 iterator.level < level)
3428 sp = page_header(__pa(iterator.sptep));
3429 if (!is_last_spte(spte, sp->role.level))
3433 * Check whether the memory access that caused the fault would
3434 * still cause it if it were to be performed right now. If not,
3435 * then this is a spurious fault caused by TLB lazily flushed,
3436 * or some other CPU has already fixed the PTE after the
3437 * current CPU took the fault.
3439 * Need not check the access of upper level table entries since
3440 * they are always ACC_ALL.
3442 if (is_access_allowed(error_code, spte)) {
3443 fault_handled = true;
3449 if (is_access_track_spte(spte))
3450 new_spte = restore_acc_track_spte(new_spte);
3453 * Currently, to simplify the code, write-protection can
3454 * be removed in the fast path only if the SPTE was
3455 * write-protected for dirty-logging or access tracking.
3457 if ((error_code & PFERR_WRITE_MASK) &&
3458 spte_can_locklessly_be_made_writable(spte))
3460 new_spte |= PT_WRITABLE_MASK;
3463 * Do not fix write-permission on the large spte. Since
3464 * we only dirty the first page into the dirty-bitmap in
3465 * fast_pf_fix_direct_spte(), other pages are missed
3466 * if its slot has dirty logging enabled.
3468 * Instead, we let the slow page fault path create a
3469 * normal spte to fix the access.
3471 * See the comments in kvm_arch_commit_memory_region().
3473 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3477 /* Verify that the fault can be handled in the fast path */
3478 if (new_spte == spte ||
3479 !is_access_allowed(error_code, new_spte))
3483 * Currently, fast page fault only works for direct mapping
3484 * since the gfn is not stable for indirect shadow page. See
3485 * Documentation/virt/kvm/locking.txt to get more detail.
3487 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3488 iterator.sptep, spte,
3493 if (++retry_count > 4) {
3494 printk_once(KERN_WARNING
3495 "kvm: Fast #PF retrying more than 4 times.\n");
3501 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3502 spte, fault_handled);
3503 walk_shadow_page_lockless_end(vcpu);
3505 return fault_handled;
3508 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3509 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3510 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3512 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3513 gfn_t gfn, bool prefault)
3517 bool force_pt_level = false;
3519 unsigned long mmu_seq;
3520 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3522 level = mapping_level(vcpu, gfn, &force_pt_level);
3523 if (likely(!force_pt_level)) {
3525 * This path builds a PAE pagetable - so we can map
3526 * 2mb pages at maximum. Therefore check if the level
3527 * is larger than that.
3529 if (level > PT_DIRECTORY_LEVEL)
3530 level = PT_DIRECTORY_LEVEL;
3532 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3535 if (fast_page_fault(vcpu, v, level, error_code))
3536 return RET_PF_RETRY;
3538 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3541 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3542 return RET_PF_RETRY;
3544 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3548 spin_lock(&vcpu->kvm->mmu_lock);
3549 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3551 if (make_mmu_pages_available(vcpu) < 0)
3553 if (likely(!force_pt_level))
3554 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3555 r = __direct_map(vcpu, v, write, map_writable, level, pfn, prefault);
3557 spin_unlock(&vcpu->kvm->mmu_lock);
3558 kvm_release_pfn_clean(pfn);
3562 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3563 struct list_head *invalid_list)
3565 struct kvm_mmu_page *sp;
3567 if (!VALID_PAGE(*root_hpa))
3570 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3572 if (!sp->root_count && sp->role.invalid)
3573 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3575 *root_hpa = INVALID_PAGE;
3578 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3579 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3580 ulong roots_to_free)
3583 LIST_HEAD(invalid_list);
3584 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3586 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3588 /* Before acquiring the MMU lock, see if we need to do any real work. */
3589 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3590 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3591 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3592 VALID_PAGE(mmu->prev_roots[i].hpa))
3595 if (i == KVM_MMU_NUM_PREV_ROOTS)
3599 spin_lock(&vcpu->kvm->mmu_lock);
3601 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3602 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3603 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3606 if (free_active_root) {
3607 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3608 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3609 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3612 for (i = 0; i < 4; ++i)
3613 if (mmu->pae_root[i] != 0)
3614 mmu_free_root_page(vcpu->kvm,
3617 mmu->root_hpa = INVALID_PAGE;
3622 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3623 spin_unlock(&vcpu->kvm->mmu_lock);
3625 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3627 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3631 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3632 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3639 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3641 struct kvm_mmu_page *sp;
3644 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3645 spin_lock(&vcpu->kvm->mmu_lock);
3646 if(make_mmu_pages_available(vcpu) < 0) {
3647 spin_unlock(&vcpu->kvm->mmu_lock);
3650 sp = kvm_mmu_get_page(vcpu, 0, 0,
3651 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3653 spin_unlock(&vcpu->kvm->mmu_lock);
3654 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3655 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3656 for (i = 0; i < 4; ++i) {
3657 hpa_t root = vcpu->arch.mmu->pae_root[i];
3659 MMU_WARN_ON(VALID_PAGE(root));
3660 spin_lock(&vcpu->kvm->mmu_lock);
3661 if (make_mmu_pages_available(vcpu) < 0) {
3662 spin_unlock(&vcpu->kvm->mmu_lock);
3665 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3666 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3667 root = __pa(sp->spt);
3669 spin_unlock(&vcpu->kvm->mmu_lock);
3670 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3672 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3675 vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3680 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3682 struct kvm_mmu_page *sp;
3684 gfn_t root_gfn, root_cr3;
3687 root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3688 root_gfn = root_cr3 >> PAGE_SHIFT;
3690 if (mmu_check_root(vcpu, root_gfn))
3694 * Do we shadow a long mode page table? If so we need to
3695 * write-protect the guests page table root.
3697 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3698 hpa_t root = vcpu->arch.mmu->root_hpa;
3700 MMU_WARN_ON(VALID_PAGE(root));
3702 spin_lock(&vcpu->kvm->mmu_lock);
3703 if (make_mmu_pages_available(vcpu) < 0) {
3704 spin_unlock(&vcpu->kvm->mmu_lock);
3707 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3708 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3709 root = __pa(sp->spt);
3711 spin_unlock(&vcpu->kvm->mmu_lock);
3712 vcpu->arch.mmu->root_hpa = root;
3717 * We shadow a 32 bit page table. This may be a legacy 2-level
3718 * or a PAE 3-level page table. In either case we need to be aware that
3719 * the shadow page table may be a PAE or a long mode page table.
3721 pm_mask = PT_PRESENT_MASK;
3722 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3723 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3725 for (i = 0; i < 4; ++i) {
3726 hpa_t root = vcpu->arch.mmu->pae_root[i];
3728 MMU_WARN_ON(VALID_PAGE(root));
3729 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3730 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3731 if (!(pdptr & PT_PRESENT_MASK)) {
3732 vcpu->arch.mmu->pae_root[i] = 0;
3735 root_gfn = pdptr >> PAGE_SHIFT;
3736 if (mmu_check_root(vcpu, root_gfn))
3739 spin_lock(&vcpu->kvm->mmu_lock);
3740 if (make_mmu_pages_available(vcpu) < 0) {
3741 spin_unlock(&vcpu->kvm->mmu_lock);
3744 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3746 root = __pa(sp->spt);
3748 spin_unlock(&vcpu->kvm->mmu_lock);
3750 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3752 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3755 * If we shadow a 32 bit page table with a long mode page
3756 * table we enter this path.
3758 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3759 if (vcpu->arch.mmu->lm_root == NULL) {
3761 * The additional page necessary for this is only
3762 * allocated on demand.
3767 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3768 if (lm_root == NULL)
3771 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3773 vcpu->arch.mmu->lm_root = lm_root;
3776 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3780 vcpu->arch.mmu->root_cr3 = root_cr3;
3785 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3787 if (vcpu->arch.mmu->direct_map)
3788 return mmu_alloc_direct_roots(vcpu);
3790 return mmu_alloc_shadow_roots(vcpu);
3793 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3796 struct kvm_mmu_page *sp;
3798 if (vcpu->arch.mmu->direct_map)
3801 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3804 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3806 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3807 hpa_t root = vcpu->arch.mmu->root_hpa;
3808 sp = page_header(root);
3811 * Even if another CPU was marking the SP as unsync-ed
3812 * simultaneously, any guest page table changes are not
3813 * guaranteed to be visible anyway until this VCPU issues a TLB
3814 * flush strictly after those changes are made. We only need to
3815 * ensure that the other CPU sets these flags before any actual
3816 * changes to the page tables are made. The comments in
3817 * mmu_need_write_protect() describe what could go wrong if this
3818 * requirement isn't satisfied.
3820 if (!smp_load_acquire(&sp->unsync) &&
3821 !smp_load_acquire(&sp->unsync_children))
3824 spin_lock(&vcpu->kvm->mmu_lock);
3825 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3827 mmu_sync_children(vcpu, sp);
3829 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3830 spin_unlock(&vcpu->kvm->mmu_lock);
3834 spin_lock(&vcpu->kvm->mmu_lock);
3835 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3837 for (i = 0; i < 4; ++i) {
3838 hpa_t root = vcpu->arch.mmu->pae_root[i];
3840 if (root && VALID_PAGE(root)) {
3841 root &= PT64_BASE_ADDR_MASK;
3842 sp = page_header(root);
3843 mmu_sync_children(vcpu, sp);
3847 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3848 spin_unlock(&vcpu->kvm->mmu_lock);
3850 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3852 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3853 u32 access, struct x86_exception *exception)
3856 exception->error_code = 0;
3860 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3862 struct x86_exception *exception)
3865 exception->error_code = 0;
3866 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3870 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3872 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3874 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3875 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3878 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3880 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3883 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3885 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3888 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3891 * A nested guest cannot use the MMIO cache if it is using nested
3892 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3894 if (mmu_is_nested(vcpu))
3898 return vcpu_match_mmio_gpa(vcpu, addr);
3900 return vcpu_match_mmio_gva(vcpu, addr);
3903 /* return true if reserved bit is detected on spte. */
3905 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3907 struct kvm_shadow_walk_iterator iterator;
3908 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3910 bool reserved = false;
3912 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3915 walk_shadow_page_lockless_begin(vcpu);
3917 for (shadow_walk_init(&iterator, vcpu, addr),
3918 leaf = root = iterator.level;
3919 shadow_walk_okay(&iterator);
3920 __shadow_walk_next(&iterator, spte)) {
3921 spte = mmu_spte_get_lockless(iterator.sptep);
3923 sptes[leaf - 1] = spte;
3926 if (!is_shadow_present_pte(spte))
3929 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3933 walk_shadow_page_lockless_end(vcpu);
3936 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3938 while (root > leaf) {
3939 pr_err("------ spte 0x%llx level %d.\n",
3940 sptes[root - 1], root);
3949 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3954 if (mmio_info_in_cache(vcpu, addr, direct))
3955 return RET_PF_EMULATE;
3957 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3958 if (WARN_ON(reserved))
3961 if (is_mmio_spte(spte)) {
3962 gfn_t gfn = get_mmio_spte_gfn(spte);
3963 unsigned access = get_mmio_spte_access(spte);
3965 if (!check_mmio_spte(vcpu, spte))
3966 return RET_PF_INVALID;
3971 trace_handle_mmio_page_fault(addr, gfn, access);
3972 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3973 return RET_PF_EMULATE;
3977 * If the page table is zapped by other cpus, let CPU fault again on
3980 return RET_PF_RETRY;
3983 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3984 u32 error_code, gfn_t gfn)
3986 if (unlikely(error_code & PFERR_RSVD_MASK))
3989 if (!(error_code & PFERR_PRESENT_MASK) ||
3990 !(error_code & PFERR_WRITE_MASK))
3994 * guest is writing the page which is write tracked which can
3995 * not be fixed by page fault handler.
3997 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4003 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4005 struct kvm_shadow_walk_iterator iterator;
4008 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
4011 walk_shadow_page_lockless_begin(vcpu);
4012 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4013 clear_sp_write_flooding_count(iterator.sptep);
4014 if (!is_shadow_present_pte(spte))
4017 walk_shadow_page_lockless_end(vcpu);
4020 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
4021 u32 error_code, bool prefault)
4023 gfn_t gfn = gva >> PAGE_SHIFT;
4026 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
4028 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4029 return RET_PF_EMULATE;
4031 r = mmu_topup_memory_caches(vcpu);
4035 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4038 return nonpaging_map(vcpu, gva & PAGE_MASK,
4039 error_code, gfn, prefault);
4042 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
4044 struct kvm_arch_async_pf arch;
4046 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4048 arch.direct_map = vcpu->arch.mmu->direct_map;
4049 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4051 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4054 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4055 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4057 struct kvm_memory_slot *slot;
4061 * Don't expose private memslots to L2.
4063 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4064 *pfn = KVM_PFN_NOSLOT;
4068 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4070 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4072 return false; /* *pfn has correct page already */
4074 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4075 trace_kvm_try_async_get_page(gva, gfn);
4076 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4077 trace_kvm_async_pf_doublefault(gva, gfn);
4078 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4080 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4084 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4088 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4089 u64 fault_address, char *insn, int insn_len)
4093 vcpu->arch.l1tf_flush_l1d = true;
4094 switch (vcpu->arch.apf.host_apf_reason) {
4096 trace_kvm_page_fault(fault_address, error_code);
4098 if (kvm_event_needs_reinjection(vcpu))
4099 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4100 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4103 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4104 vcpu->arch.apf.host_apf_reason = 0;
4105 local_irq_disable();
4106 kvm_async_pf_task_wait(fault_address, 0);
4109 case KVM_PV_REASON_PAGE_READY:
4110 vcpu->arch.apf.host_apf_reason = 0;
4111 local_irq_disable();
4112 kvm_async_pf_task_wake(fault_address);
4118 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4121 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4123 int page_num = KVM_PAGES_PER_HPAGE(level);
4125 gfn &= ~(page_num - 1);
4127 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4130 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4136 bool force_pt_level;
4137 gfn_t gfn = gpa >> PAGE_SHIFT;
4138 unsigned long mmu_seq;
4139 int write = error_code & PFERR_WRITE_MASK;
4142 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4144 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4145 return RET_PF_EMULATE;
4147 r = mmu_topup_memory_caches(vcpu);
4151 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4152 PT_DIRECTORY_LEVEL);
4153 level = mapping_level(vcpu, gfn, &force_pt_level);
4154 if (likely(!force_pt_level)) {
4155 if (level > PT_DIRECTORY_LEVEL &&
4156 !check_hugepage_cache_consistency(vcpu, gfn, level))
4157 level = PT_DIRECTORY_LEVEL;
4158 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4161 if (fast_page_fault(vcpu, gpa, level, error_code))
4162 return RET_PF_RETRY;
4164 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4167 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4168 return RET_PF_RETRY;
4170 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4174 spin_lock(&vcpu->kvm->mmu_lock);
4175 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4177 if (make_mmu_pages_available(vcpu) < 0)
4179 if (likely(!force_pt_level))
4180 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4181 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn, prefault);
4183 spin_unlock(&vcpu->kvm->mmu_lock);
4184 kvm_release_pfn_clean(pfn);
4188 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4189 struct kvm_mmu *context)
4191 context->page_fault = nonpaging_page_fault;
4192 context->gva_to_gpa = nonpaging_gva_to_gpa;
4193 context->sync_page = nonpaging_sync_page;
4194 context->invlpg = nonpaging_invlpg;
4195 context->update_pte = nonpaging_update_pte;
4196 context->root_level = 0;
4197 context->shadow_root_level = PT32E_ROOT_LEVEL;
4198 context->direct_map = true;
4199 context->nx = false;
4203 * Find out if a previously cached root matching the new CR3/role is available.
4204 * The current root is also inserted into the cache.
4205 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4207 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4208 * false is returned. This root should now be freed by the caller.
4210 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4211 union kvm_mmu_page_role new_role)
4214 struct kvm_mmu_root_info root;
4215 struct kvm_mmu *mmu = vcpu->arch.mmu;
4217 root.cr3 = mmu->root_cr3;
4218 root.hpa = mmu->root_hpa;
4220 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4221 swap(root, mmu->prev_roots[i]);
4223 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4224 page_header(root.hpa) != NULL &&
4225 new_role.word == page_header(root.hpa)->role.word)
4229 mmu->root_hpa = root.hpa;
4230 mmu->root_cr3 = root.cr3;
4232 return i < KVM_MMU_NUM_PREV_ROOTS;
4235 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4236 union kvm_mmu_page_role new_role,
4237 bool skip_tlb_flush)
4239 struct kvm_mmu *mmu = vcpu->arch.mmu;
4242 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4243 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4244 * later if necessary.
4246 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4247 mmu->root_level >= PT64_ROOT_4LEVEL) {
4248 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4251 if (cached_root_available(vcpu, new_cr3, new_role)) {
4253 * It is possible that the cached previous root page is
4254 * obsolete because of a change in the MMU generation
4255 * number. However, changing the generation number is
4256 * accompanied by KVM_REQ_MMU_RELOAD, which will free
4257 * the root set here and allocate a new one.
4259 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4260 if (!skip_tlb_flush) {
4261 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4262 kvm_x86_ops->tlb_flush(vcpu, true);
4266 * The last MMIO access's GVA and GPA are cached in the
4267 * VCPU. When switching to a new CR3, that GVA->GPA
4268 * mapping may no longer be valid. So clear any cached
4269 * MMIO info even when we don't need to sync the shadow
4272 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4274 __clear_sp_write_flooding_count(
4275 page_header(mmu->root_hpa));
4284 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4285 union kvm_mmu_page_role new_role,
4286 bool skip_tlb_flush)
4288 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4289 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4290 KVM_MMU_ROOT_CURRENT);
4293 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4295 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4298 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4300 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4302 return kvm_read_cr3(vcpu);
4305 static void inject_page_fault(struct kvm_vcpu *vcpu,
4306 struct x86_exception *fault)
4308 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4311 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4312 unsigned access, int *nr_present)
4314 if (unlikely(is_mmio_spte(*sptep))) {
4315 if (gfn != get_mmio_spte_gfn(*sptep)) {
4316 mmu_spte_clear_no_track(sptep);
4321 mark_mmio_spte(vcpu, sptep, gfn, access);
4328 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4329 unsigned level, unsigned gpte)
4332 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4333 * If it is clear, there are no large pages at this level, so clear
4334 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4336 gpte &= level - mmu->last_nonleaf_level;
4339 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4340 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4341 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4343 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4345 return gpte & PT_PAGE_SIZE_MASK;
4348 #define PTTYPE_EPT 18 /* arbitrary */
4349 #define PTTYPE PTTYPE_EPT
4350 #include "paging_tmpl.h"
4354 #include "paging_tmpl.h"
4358 #include "paging_tmpl.h"
4362 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4363 struct rsvd_bits_validate *rsvd_check,
4364 int maxphyaddr, int level, bool nx, bool gbpages,
4367 u64 exb_bit_rsvd = 0;
4368 u64 gbpages_bit_rsvd = 0;
4369 u64 nonleaf_bit8_rsvd = 0;
4371 rsvd_check->bad_mt_xwr = 0;
4374 exb_bit_rsvd = rsvd_bits(63, 63);
4376 gbpages_bit_rsvd = rsvd_bits(7, 7);
4379 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4380 * leaf entries) on AMD CPUs only.
4383 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4386 case PT32_ROOT_LEVEL:
4387 /* no rsvd bits for 2 level 4K page table entries */
4388 rsvd_check->rsvd_bits_mask[0][1] = 0;
4389 rsvd_check->rsvd_bits_mask[0][0] = 0;
4390 rsvd_check->rsvd_bits_mask[1][0] =
4391 rsvd_check->rsvd_bits_mask[0][0];
4394 rsvd_check->rsvd_bits_mask[1][1] = 0;
4398 if (is_cpuid_PSE36())
4399 /* 36bits PSE 4MB page */
4400 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4402 /* 32 bits PSE 4MB page */
4403 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4405 case PT32E_ROOT_LEVEL:
4406 rsvd_check->rsvd_bits_mask[0][2] =
4407 rsvd_bits(maxphyaddr, 63) |
4408 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4409 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4410 rsvd_bits(maxphyaddr, 62); /* PDE */
4411 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4412 rsvd_bits(maxphyaddr, 62); /* PTE */
4413 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4414 rsvd_bits(maxphyaddr, 62) |
4415 rsvd_bits(13, 20); /* large page */
4416 rsvd_check->rsvd_bits_mask[1][0] =
4417 rsvd_check->rsvd_bits_mask[0][0];
4419 case PT64_ROOT_5LEVEL:
4420 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4421 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4422 rsvd_bits(maxphyaddr, 51);
4423 rsvd_check->rsvd_bits_mask[1][4] =
4424 rsvd_check->rsvd_bits_mask[0][4];
4426 case PT64_ROOT_4LEVEL:
4427 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4428 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4429 rsvd_bits(maxphyaddr, 51);
4430 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4431 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4432 rsvd_bits(maxphyaddr, 51);
4433 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4434 rsvd_bits(maxphyaddr, 51);
4435 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4436 rsvd_bits(maxphyaddr, 51);
4437 rsvd_check->rsvd_bits_mask[1][3] =
4438 rsvd_check->rsvd_bits_mask[0][3];
4439 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4440 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4442 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4443 rsvd_bits(maxphyaddr, 51) |
4444 rsvd_bits(13, 20); /* large page */
4445 rsvd_check->rsvd_bits_mask[1][0] =
4446 rsvd_check->rsvd_bits_mask[0][0];
4451 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4452 struct kvm_mmu *context)
4454 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4455 cpuid_maxphyaddr(vcpu), context->root_level,
4457 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4458 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4462 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4463 int maxphyaddr, bool execonly)
4467 rsvd_check->rsvd_bits_mask[0][4] =
4468 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4469 rsvd_check->rsvd_bits_mask[0][3] =
4470 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4471 rsvd_check->rsvd_bits_mask[0][2] =
4472 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4473 rsvd_check->rsvd_bits_mask[0][1] =
4474 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4475 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4478 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4479 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4480 rsvd_check->rsvd_bits_mask[1][2] =
4481 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4482 rsvd_check->rsvd_bits_mask[1][1] =
4483 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4484 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4486 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4487 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4488 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4489 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4490 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4492 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4493 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4495 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4498 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4499 struct kvm_mmu *context, bool execonly)
4501 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4502 cpuid_maxphyaddr(vcpu), execonly);
4506 * the page table on host is the shadow page table for the page
4507 * table in guest or amd nested guest, its mmu features completely
4508 * follow the features in guest.
4511 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4513 bool uses_nx = context->nx ||
4514 context->mmu_role.base.smep_andnot_wp;
4515 struct rsvd_bits_validate *shadow_zero_check;
4519 * Passing "true" to the last argument is okay; it adds a check
4520 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4522 shadow_zero_check = &context->shadow_zero_check;
4523 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4525 context->shadow_root_level, uses_nx,
4526 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4527 is_pse(vcpu), true);
4529 if (!shadow_me_mask)
4532 for (i = context->shadow_root_level; --i >= 0;) {
4533 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4534 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4538 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4540 static inline bool boot_cpu_is_amd(void)
4542 WARN_ON_ONCE(!tdp_enabled);
4543 return shadow_x_mask == 0;
4547 * the direct page table on host, use as much mmu features as
4548 * possible, however, kvm currently does not do execution-protection.
4551 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4552 struct kvm_mmu *context)
4554 struct rsvd_bits_validate *shadow_zero_check;
4557 shadow_zero_check = &context->shadow_zero_check;
4559 if (boot_cpu_is_amd())
4560 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4562 context->shadow_root_level, false,
4563 boot_cpu_has(X86_FEATURE_GBPAGES),
4566 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4570 if (!shadow_me_mask)
4573 for (i = context->shadow_root_level; --i >= 0;) {
4574 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4575 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4580 * as the comments in reset_shadow_zero_bits_mask() except it
4581 * is the shadow page table for intel nested guest.
4584 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4585 struct kvm_mmu *context, bool execonly)
4587 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4588 shadow_phys_bits, execonly);
4591 #define BYTE_MASK(access) \
4592 ((1 & (access) ? 2 : 0) | \
4593 (2 & (access) ? 4 : 0) | \
4594 (3 & (access) ? 8 : 0) | \
4595 (4 & (access) ? 16 : 0) | \
4596 (5 & (access) ? 32 : 0) | \
4597 (6 & (access) ? 64 : 0) | \
4598 (7 & (access) ? 128 : 0))
4601 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4602 struct kvm_mmu *mmu, bool ept)
4606 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4607 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4608 const u8 u = BYTE_MASK(ACC_USER_MASK);
4610 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4611 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4612 bool cr0_wp = is_write_protection(vcpu);
4614 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4615 unsigned pfec = byte << 1;
4618 * Each "*f" variable has a 1 bit for each UWX value
4619 * that causes a fault with the given PFEC.
4622 /* Faults from writes to non-writable pages */
4623 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4624 /* Faults from user mode accesses to supervisor pages */
4625 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4626 /* Faults from fetches of non-executable pages*/
4627 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4628 /* Faults from kernel mode fetches of user pages */
4630 /* Faults from kernel mode accesses of user pages */
4634 /* Faults from kernel mode accesses to user pages */
4635 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4637 /* Not really needed: !nx will cause pte.nx to fault */
4641 /* Allow supervisor writes if !cr0.wp */
4643 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4645 /* Disallow supervisor fetches of user code if cr4.smep */
4647 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4650 * SMAP:kernel-mode data accesses from user-mode
4651 * mappings should fault. A fault is considered
4652 * as a SMAP violation if all of the following
4653 * conditions are true:
4654 * - X86_CR4_SMAP is set in CR4
4655 * - A user page is accessed
4656 * - The access is not a fetch
4657 * - Page fault in kernel mode
4658 * - if CPL = 3 or X86_EFLAGS_AC is clear
4660 * Here, we cover the first three conditions.
4661 * The fourth is computed dynamically in permission_fault();
4662 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4663 * *not* subject to SMAP restrictions.
4666 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4669 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4674 * PKU is an additional mechanism by which the paging controls access to
4675 * user-mode addresses based on the value in the PKRU register. Protection
4676 * key violations are reported through a bit in the page fault error code.
4677 * Unlike other bits of the error code, the PK bit is not known at the
4678 * call site of e.g. gva_to_gpa; it must be computed directly in
4679 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4680 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4682 * In particular the following conditions come from the error code, the
4683 * page tables and the machine state:
4684 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4685 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4686 * - PK is always zero if U=0 in the page tables
4687 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4689 * The PKRU bitmask caches the result of these four conditions. The error
4690 * code (minus the P bit) and the page table's U bit form an index into the
4691 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4692 * with the two bits of the PKRU register corresponding to the protection key.
4693 * For the first three conditions above the bits will be 00, thus masking
4694 * away both AD and WD. For all reads or if the last condition holds, WD
4695 * only will be masked away.
4697 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4708 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4709 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4714 wp = is_write_protection(vcpu);
4716 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4717 unsigned pfec, pkey_bits;
4718 bool check_pkey, check_write, ff, uf, wf, pte_user;
4721 ff = pfec & PFERR_FETCH_MASK;
4722 uf = pfec & PFERR_USER_MASK;
4723 wf = pfec & PFERR_WRITE_MASK;
4725 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4726 pte_user = pfec & PFERR_RSVD_MASK;
4729 * Only need to check the access which is not an
4730 * instruction fetch and is to a user page.
4732 check_pkey = (!ff && pte_user);
4734 * write access is controlled by PKRU if it is a
4735 * user access or CR0.WP = 1.
4737 check_write = check_pkey && wf && (uf || wp);
4739 /* PKRU.AD stops both read and write access. */
4740 pkey_bits = !!check_pkey;
4741 /* PKRU.WD stops write access. */
4742 pkey_bits |= (!!check_write) << 1;
4744 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4748 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4750 unsigned root_level = mmu->root_level;
4752 mmu->last_nonleaf_level = root_level;
4753 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4754 mmu->last_nonleaf_level++;
4757 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4758 struct kvm_mmu *context,
4761 context->nx = is_nx(vcpu);
4762 context->root_level = level;
4764 reset_rsvds_bits_mask(vcpu, context);
4765 update_permission_bitmask(vcpu, context, false);
4766 update_pkru_bitmask(vcpu, context, false);
4767 update_last_nonleaf_level(vcpu, context);
4769 MMU_WARN_ON(!is_pae(vcpu));
4770 context->page_fault = paging64_page_fault;
4771 context->gva_to_gpa = paging64_gva_to_gpa;
4772 context->sync_page = paging64_sync_page;
4773 context->invlpg = paging64_invlpg;
4774 context->update_pte = paging64_update_pte;
4775 context->shadow_root_level = level;
4776 context->direct_map = false;
4779 static void paging64_init_context(struct kvm_vcpu *vcpu,
4780 struct kvm_mmu *context)
4782 int root_level = is_la57_mode(vcpu) ?
4783 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4785 paging64_init_context_common(vcpu, context, root_level);
4788 static void paging32_init_context(struct kvm_vcpu *vcpu,
4789 struct kvm_mmu *context)
4791 context->nx = false;
4792 context->root_level = PT32_ROOT_LEVEL;
4794 reset_rsvds_bits_mask(vcpu, context);
4795 update_permission_bitmask(vcpu, context, false);
4796 update_pkru_bitmask(vcpu, context, false);
4797 update_last_nonleaf_level(vcpu, context);
4799 context->page_fault = paging32_page_fault;
4800 context->gva_to_gpa = paging32_gva_to_gpa;
4801 context->sync_page = paging32_sync_page;
4802 context->invlpg = paging32_invlpg;
4803 context->update_pte = paging32_update_pte;
4804 context->shadow_root_level = PT32E_ROOT_LEVEL;
4805 context->direct_map = false;
4808 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4809 struct kvm_mmu *context)
4811 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4814 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4816 union kvm_mmu_extended_role ext = {0};
4818 ext.cr0_pg = !!is_paging(vcpu);
4819 ext.cr4_pae = !!is_pae(vcpu);
4820 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4821 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4822 ext.cr4_pse = !!is_pse(vcpu);
4823 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4824 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4825 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4832 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4835 union kvm_mmu_role role = {0};
4837 role.base.access = ACC_ALL;
4838 role.base.nxe = !!is_nx(vcpu);
4839 role.base.cr0_wp = is_write_protection(vcpu);
4840 role.base.smm = is_smm(vcpu);
4841 role.base.guest_mode = is_guest_mode(vcpu);
4846 role.ext = kvm_calc_mmu_role_ext(vcpu);
4851 static union kvm_mmu_role
4852 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4854 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4856 role.base.ad_disabled = (shadow_accessed_mask == 0);
4857 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4858 role.base.direct = true;
4859 role.base.gpte_is_8_bytes = true;
4864 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4866 struct kvm_mmu *context = vcpu->arch.mmu;
4867 union kvm_mmu_role new_role =
4868 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4870 new_role.base.word &= mmu_base_role_mask.word;
4871 if (new_role.as_u64 == context->mmu_role.as_u64)
4874 context->mmu_role.as_u64 = new_role.as_u64;
4875 context->page_fault = tdp_page_fault;
4876 context->sync_page = nonpaging_sync_page;
4877 context->invlpg = nonpaging_invlpg;
4878 context->update_pte = nonpaging_update_pte;
4879 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4880 context->direct_map = true;
4881 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4882 context->get_cr3 = get_cr3;
4883 context->get_pdptr = kvm_pdptr_read;
4884 context->inject_page_fault = kvm_inject_page_fault;
4886 if (!is_paging(vcpu)) {
4887 context->nx = false;
4888 context->gva_to_gpa = nonpaging_gva_to_gpa;
4889 context->root_level = 0;
4890 } else if (is_long_mode(vcpu)) {
4891 context->nx = is_nx(vcpu);
4892 context->root_level = is_la57_mode(vcpu) ?
4893 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4894 reset_rsvds_bits_mask(vcpu, context);
4895 context->gva_to_gpa = paging64_gva_to_gpa;
4896 } else if (is_pae(vcpu)) {
4897 context->nx = is_nx(vcpu);
4898 context->root_level = PT32E_ROOT_LEVEL;
4899 reset_rsvds_bits_mask(vcpu, context);
4900 context->gva_to_gpa = paging64_gva_to_gpa;
4902 context->nx = false;
4903 context->root_level = PT32_ROOT_LEVEL;
4904 reset_rsvds_bits_mask(vcpu, context);
4905 context->gva_to_gpa = paging32_gva_to_gpa;
4908 update_permission_bitmask(vcpu, context, false);
4909 update_pkru_bitmask(vcpu, context, false);
4910 update_last_nonleaf_level(vcpu, context);
4911 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4914 static union kvm_mmu_role
4915 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4917 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4919 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4920 !is_write_protection(vcpu);
4921 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4922 !is_write_protection(vcpu);
4923 role.base.direct = !is_paging(vcpu);
4924 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4926 if (!is_long_mode(vcpu))
4927 role.base.level = PT32E_ROOT_LEVEL;
4928 else if (is_la57_mode(vcpu))
4929 role.base.level = PT64_ROOT_5LEVEL;
4931 role.base.level = PT64_ROOT_4LEVEL;
4936 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4938 struct kvm_mmu *context = vcpu->arch.mmu;
4939 union kvm_mmu_role new_role =
4940 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4942 new_role.base.word &= mmu_base_role_mask.word;
4943 if (new_role.as_u64 == context->mmu_role.as_u64)
4946 if (!is_paging(vcpu))
4947 nonpaging_init_context(vcpu, context);
4948 else if (is_long_mode(vcpu))
4949 paging64_init_context(vcpu, context);
4950 else if (is_pae(vcpu))
4951 paging32E_init_context(vcpu, context);
4953 paging32_init_context(vcpu, context);
4955 context->mmu_role.as_u64 = new_role.as_u64;
4956 reset_shadow_zero_bits_mask(vcpu, context);
4958 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4960 static union kvm_mmu_role
4961 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4964 union kvm_mmu_role role = {0};
4966 /* SMM flag is inherited from root_mmu */
4967 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
4969 role.base.level = PT64_ROOT_4LEVEL;
4970 role.base.gpte_is_8_bytes = true;
4971 role.base.direct = false;
4972 role.base.ad_disabled = !accessed_dirty;
4973 role.base.guest_mode = true;
4974 role.base.access = ACC_ALL;
4977 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
4978 * SMAP variation to denote shadow EPT entries.
4980 role.base.cr0_wp = true;
4981 role.base.smap_andnot_wp = true;
4983 role.ext = kvm_calc_mmu_role_ext(vcpu);
4984 role.ext.execonly = execonly;
4989 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4990 bool accessed_dirty, gpa_t new_eptp)
4992 struct kvm_mmu *context = vcpu->arch.mmu;
4993 union kvm_mmu_role new_role =
4994 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4997 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
4999 new_role.base.word &= mmu_base_role_mask.word;
5000 if (new_role.as_u64 == context->mmu_role.as_u64)
5003 context->shadow_root_level = PT64_ROOT_4LEVEL;
5006 context->ept_ad = accessed_dirty;
5007 context->page_fault = ept_page_fault;
5008 context->gva_to_gpa = ept_gva_to_gpa;
5009 context->sync_page = ept_sync_page;
5010 context->invlpg = ept_invlpg;
5011 context->update_pte = ept_update_pte;
5012 context->root_level = PT64_ROOT_4LEVEL;
5013 context->direct_map = false;
5014 context->mmu_role.as_u64 = new_role.as_u64;
5016 update_permission_bitmask(vcpu, context, true);
5017 update_pkru_bitmask(vcpu, context, true);
5018 update_last_nonleaf_level(vcpu, context);
5019 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5020 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5022 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5024 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5026 struct kvm_mmu *context = vcpu->arch.mmu;
5028 kvm_init_shadow_mmu(vcpu);
5029 context->set_cr3 = kvm_x86_ops->set_cr3;
5030 context->get_cr3 = get_cr3;
5031 context->get_pdptr = kvm_pdptr_read;
5032 context->inject_page_fault = kvm_inject_page_fault;
5035 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5037 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5038 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5040 new_role.base.word &= mmu_base_role_mask.word;
5041 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5044 g_context->mmu_role.as_u64 = new_role.as_u64;
5045 g_context->get_cr3 = get_cr3;
5046 g_context->get_pdptr = kvm_pdptr_read;
5047 g_context->inject_page_fault = kvm_inject_page_fault;
5050 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5051 * L1's nested page tables (e.g. EPT12). The nested translation
5052 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5053 * L2's page tables as the first level of translation and L1's
5054 * nested page tables as the second level of translation. Basically
5055 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5057 if (!is_paging(vcpu)) {
5058 g_context->nx = false;
5059 g_context->root_level = 0;
5060 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5061 } else if (is_long_mode(vcpu)) {
5062 g_context->nx = is_nx(vcpu);
5063 g_context->root_level = is_la57_mode(vcpu) ?
5064 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5065 reset_rsvds_bits_mask(vcpu, g_context);
5066 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5067 } else if (is_pae(vcpu)) {
5068 g_context->nx = is_nx(vcpu);
5069 g_context->root_level = PT32E_ROOT_LEVEL;
5070 reset_rsvds_bits_mask(vcpu, g_context);
5071 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5073 g_context->nx = false;
5074 g_context->root_level = PT32_ROOT_LEVEL;
5075 reset_rsvds_bits_mask(vcpu, g_context);
5076 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5079 update_permission_bitmask(vcpu, g_context, false);
5080 update_pkru_bitmask(vcpu, g_context, false);
5081 update_last_nonleaf_level(vcpu, g_context);
5084 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5089 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5091 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5092 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5095 if (mmu_is_nested(vcpu))
5096 init_kvm_nested_mmu(vcpu);
5097 else if (tdp_enabled)
5098 init_kvm_tdp_mmu(vcpu);
5100 init_kvm_softmmu(vcpu);
5102 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5104 static union kvm_mmu_page_role
5105 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5107 union kvm_mmu_role role;
5110 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5112 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5117 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5119 kvm_mmu_unload(vcpu);
5120 kvm_init_mmu(vcpu, true);
5122 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5124 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5128 r = mmu_topup_memory_caches(vcpu);
5131 r = mmu_alloc_roots(vcpu);
5132 kvm_mmu_sync_roots(vcpu);
5135 kvm_mmu_load_cr3(vcpu);
5136 kvm_x86_ops->tlb_flush(vcpu, true);
5140 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5142 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5144 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5145 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5146 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5147 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5149 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5151 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5152 struct kvm_mmu_page *sp, u64 *spte,
5155 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5156 ++vcpu->kvm->stat.mmu_pde_zapped;
5160 ++vcpu->kvm->stat.mmu_pte_updated;
5161 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5164 static bool need_remote_flush(u64 old, u64 new)
5166 if (!is_shadow_present_pte(old))
5168 if (!is_shadow_present_pte(new))
5170 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5172 old ^= shadow_nx_mask;
5173 new ^= shadow_nx_mask;
5174 return (old & ~new & PT64_PERM_MASK) != 0;
5177 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5184 * Assume that the pte write on a page table of the same type
5185 * as the current vcpu paging mode since we update the sptes only
5186 * when they have the same mode.
5188 if (is_pae(vcpu) && *bytes == 4) {
5189 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5194 if (*bytes == 4 || *bytes == 8) {
5195 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5204 * If we're seeing too many writes to a page, it may no longer be a page table,
5205 * or we may be forking, in which case it is better to unmap the page.
5207 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5210 * Skip write-flooding detected for the sp whose level is 1, because
5211 * it can become unsync, then the guest page is not write-protected.
5213 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5216 atomic_inc(&sp->write_flooding_count);
5217 return atomic_read(&sp->write_flooding_count) >= 3;
5221 * Misaligned accesses are too much trouble to fix up; also, they usually
5222 * indicate a page is not used as a page table.
5224 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5227 unsigned offset, pte_size, misaligned;
5229 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5230 gpa, bytes, sp->role.word);
5232 offset = offset_in_page(gpa);
5233 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5236 * Sometimes, the OS only writes the last one bytes to update status
5237 * bits, for example, in linux, andb instruction is used in clear_bit().
5239 if (!(offset & (pte_size - 1)) && bytes == 1)
5242 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5243 misaligned |= bytes < 4;
5248 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5250 unsigned page_offset, quadrant;
5254 page_offset = offset_in_page(gpa);
5255 level = sp->role.level;
5257 if (!sp->role.gpte_is_8_bytes) {
5258 page_offset <<= 1; /* 32->64 */
5260 * A 32-bit pde maps 4MB while the shadow pdes map
5261 * only 2MB. So we need to double the offset again
5262 * and zap two pdes instead of one.
5264 if (level == PT32_ROOT_LEVEL) {
5265 page_offset &= ~7; /* kill rounding error */
5269 quadrant = page_offset >> PAGE_SHIFT;
5270 page_offset &= ~PAGE_MASK;
5271 if (quadrant != sp->role.quadrant)
5275 spte = &sp->spt[page_offset / sizeof(*spte)];
5279 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5280 const u8 *new, int bytes,
5281 struct kvm_page_track_notifier_node *node)
5283 gfn_t gfn = gpa >> PAGE_SHIFT;
5284 struct kvm_mmu_page *sp;
5285 LIST_HEAD(invalid_list);
5286 u64 entry, gentry, *spte;
5288 bool remote_flush, local_flush;
5291 * If we don't have indirect shadow pages, it means no page is
5292 * write-protected, so we can exit simply.
5294 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5297 remote_flush = local_flush = false;
5299 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5302 * No need to care whether allocation memory is successful
5303 * or not since pte prefetch is skiped if it does not have
5304 * enough objects in the cache.
5306 mmu_topup_memory_caches(vcpu);
5308 spin_lock(&vcpu->kvm->mmu_lock);
5310 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5312 ++vcpu->kvm->stat.mmu_pte_write;
5313 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5315 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5316 if (detect_write_misaligned(sp, gpa, bytes) ||
5317 detect_write_flooding(sp)) {
5318 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5319 ++vcpu->kvm->stat.mmu_flooded;
5323 spte = get_written_sptes(sp, gpa, &npte);
5329 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5332 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5334 !((sp->role.word ^ base_role)
5335 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5336 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5337 if (need_remote_flush(entry, *spte))
5338 remote_flush = true;
5342 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5343 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5344 spin_unlock(&vcpu->kvm->mmu_lock);
5347 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5352 if (vcpu->arch.mmu->direct_map)
5355 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5357 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5361 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5363 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5365 LIST_HEAD(invalid_list);
5367 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5370 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5371 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5374 ++vcpu->kvm->stat.mmu_recycled;
5376 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5378 if (!kvm_mmu_available_pages(vcpu->kvm))
5383 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5384 void *insn, int insn_len)
5386 int r, emulation_type = 0;
5387 bool direct = vcpu->arch.mmu->direct_map;
5389 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5390 if (vcpu->arch.mmu->direct_map) {
5391 vcpu->arch.gpa_available = true;
5392 vcpu->arch.gpa_val = cr2;
5396 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5397 r = handle_mmio_page_fault(vcpu, cr2, direct);
5398 if (r == RET_PF_EMULATE)
5402 if (r == RET_PF_INVALID) {
5403 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5404 lower_32_bits(error_code),
5406 WARN_ON(r == RET_PF_INVALID);
5409 if (r == RET_PF_RETRY)
5415 * Before emulating the instruction, check if the error code
5416 * was due to a RO violation while translating the guest page.
5417 * This can occur when using nested virtualization with nested
5418 * paging in both guests. If true, we simply unprotect the page
5419 * and resume the guest.
5421 if (vcpu->arch.mmu->direct_map &&
5422 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5423 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5428 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5429 * optimistically try to just unprotect the page and let the processor
5430 * re-execute the instruction that caused the page fault. Do not allow
5431 * retrying MMIO emulation, as it's not only pointless but could also
5432 * cause us to enter an infinite loop because the processor will keep
5433 * faulting on the non-existent MMIO address. Retrying an instruction
5434 * from a nested guest is also pointless and dangerous as we are only
5435 * explicitly shadowing L1's page tables, i.e. unprotecting something
5436 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5438 if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5439 emulation_type = EMULTYPE_ALLOW_RETRY;
5442 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5443 * This can happen if a guest gets a page-fault on data access but the HW
5444 * table walker is not able to read the instruction page (e.g instruction
5445 * page is not present in memory). In those cases we simply restart the
5446 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5448 if (unlikely(insn && !insn_len)) {
5449 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5453 return x86_emulate_instruction(vcpu, cr2, emulation_type, insn,
5456 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5458 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5460 struct kvm_mmu *mmu = vcpu->arch.mmu;
5463 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5464 if (is_noncanonical_address(gva, vcpu))
5467 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5470 * INVLPG is required to invalidate any global mappings for the VA,
5471 * irrespective of PCID. Since it would take us roughly similar amount
5472 * of work to determine whether any of the prev_root mappings of the VA
5473 * is marked global, or to just sync it blindly, so we might as well
5474 * just always sync it.
5476 * Mappings not reachable via the current cr3 or the prev_roots will be
5477 * synced when switching to that cr3, so nothing needs to be done here
5480 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5481 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5482 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5484 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5485 ++vcpu->stat.invlpg;
5487 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5489 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5491 struct kvm_mmu *mmu = vcpu->arch.mmu;
5492 bool tlb_flush = false;
5495 if (pcid == kvm_get_active_pcid(vcpu)) {
5496 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5500 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5501 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5502 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5503 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5509 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5511 ++vcpu->stat.invlpg;
5514 * Mappings not reachable via the current cr3 or the prev_roots will be
5515 * synced when switching to that cr3, so nothing needs to be done here
5519 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5521 void kvm_enable_tdp(void)
5525 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5527 void kvm_disable_tdp(void)
5529 tdp_enabled = false;
5531 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5534 /* The return value indicates if tlb flush on all vcpus is needed. */
5535 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5537 /* The caller should hold mmu-lock before calling this function. */
5538 static __always_inline bool
5539 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5540 slot_level_handler fn, int start_level, int end_level,
5541 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5543 struct slot_rmap_walk_iterator iterator;
5546 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5547 end_gfn, &iterator) {
5549 flush |= fn(kvm, iterator.rmap);
5551 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5552 if (flush && lock_flush_tlb) {
5553 kvm_flush_remote_tlbs_with_address(kvm,
5555 iterator.gfn - start_gfn + 1);
5558 cond_resched_lock(&kvm->mmu_lock);
5562 if (flush && lock_flush_tlb) {
5563 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5564 end_gfn - start_gfn + 1);
5571 static __always_inline bool
5572 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5573 slot_level_handler fn, int start_level, int end_level,
5574 bool lock_flush_tlb)
5576 return slot_handle_level_range(kvm, memslot, fn, start_level,
5577 end_level, memslot->base_gfn,
5578 memslot->base_gfn + memslot->npages - 1,
5582 static __always_inline bool
5583 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5584 slot_level_handler fn, bool lock_flush_tlb)
5586 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5587 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5590 static __always_inline bool
5591 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5592 slot_level_handler fn, bool lock_flush_tlb)
5594 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5595 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5598 static __always_inline bool
5599 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5600 slot_level_handler fn, bool lock_flush_tlb)
5602 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5603 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5606 static void free_mmu_pages(struct kvm_mmu *mmu)
5608 free_page((unsigned long)mmu->pae_root);
5609 free_page((unsigned long)mmu->lm_root);
5612 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5618 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5619 * while the PDP table is a per-vCPU construct that's allocated at MMU
5620 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5621 * x86_64. Therefore we need to allocate the PDP table in the first
5622 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5623 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5624 * skip allocating the PDP table.
5626 if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5629 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5633 mmu->pae_root = page_address(page);
5634 for (i = 0; i < 4; ++i)
5635 mmu->pae_root[i] = INVALID_PAGE;
5640 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5645 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5646 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5648 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5649 vcpu->arch.root_mmu.root_cr3 = 0;
5650 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5651 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5652 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5654 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5655 vcpu->arch.guest_mmu.root_cr3 = 0;
5656 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5657 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5658 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5660 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5662 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5666 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5668 goto fail_allocate_root;
5672 free_mmu_pages(&vcpu->arch.guest_mmu);
5677 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5679 struct kvm_mmu_page *sp, *node;
5680 LIST_HEAD(invalid_list);
5684 list_for_each_entry_safe_reverse(sp, node,
5685 &kvm->arch.active_mmu_pages, link) {
5687 * No obsolete valid page exists before a newly created page
5688 * since active_mmu_pages is a FIFO list.
5690 if (!is_obsolete_sp(kvm, sp))
5694 * Do not repeatedly zap a root page to avoid unnecessary
5695 * KVM_REQ_MMU_RELOAD, otherwise we may not be able to
5698 * call vcpu_enter_guest():
5699 * 1): handle KVM_REQ_MMU_RELOAD
5700 * and require mmu-lock to
5703 * 1): zap root page and
5704 * send KVM_REQ_MMU_RELOAD
5706 * 2): if (cond_resched_lock(mmu-lock))
5708 * 2): hold mmu-lock and load mmu
5710 * 3): see KVM_REQ_MMU_RELOAD bit
5711 * on vcpu->requests is set
5712 * then return 1 to call
5713 * vcpu_enter_guest() again.
5716 * Since we are reversely walking the list and the invalid
5717 * list will be moved to the head, skip the invalid page
5718 * can help us to avoid the infinity list walking.
5720 if (sp->role.invalid)
5723 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5724 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5725 cond_resched_lock(&kvm->mmu_lock);
5729 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
5733 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5737 * Fast invalidate all shadow pages and use lock-break technique
5738 * to zap obsolete pages.
5740 * It's required when memslot is being deleted or VM is being
5741 * destroyed, in these cases, we should ensure that KVM MMU does
5742 * not use any resource of the being-deleted slot or all slots
5743 * after calling the function.
5745 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5747 spin_lock(&kvm->mmu_lock);
5748 kvm->arch.mmu_valid_gen++;
5750 kvm_zap_obsolete_pages(kvm);
5751 spin_unlock(&kvm->mmu_lock);
5754 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5755 struct kvm_memory_slot *slot,
5756 struct kvm_page_track_notifier_node *node)
5758 kvm_mmu_zap_all_fast(kvm);
5761 void kvm_mmu_init_vm(struct kvm *kvm)
5763 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5765 node->track_write = kvm_mmu_pte_write;
5766 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5767 kvm_page_track_register_notifier(kvm, node);
5770 void kvm_mmu_uninit_vm(struct kvm *kvm)
5772 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5774 kvm_page_track_unregister_notifier(kvm, node);
5777 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5779 struct kvm_memslots *slots;
5780 struct kvm_memory_slot *memslot;
5783 spin_lock(&kvm->mmu_lock);
5784 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5785 slots = __kvm_memslots(kvm, i);
5786 kvm_for_each_memslot(memslot, slots) {
5789 start = max(gfn_start, memslot->base_gfn);
5790 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5794 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5795 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5796 start, end - 1, true);
5800 spin_unlock(&kvm->mmu_lock);
5803 static bool slot_rmap_write_protect(struct kvm *kvm,
5804 struct kvm_rmap_head *rmap_head)
5806 return __rmap_write_protect(kvm, rmap_head, false);
5809 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5810 struct kvm_memory_slot *memslot)
5814 spin_lock(&kvm->mmu_lock);
5815 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5817 spin_unlock(&kvm->mmu_lock);
5820 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5821 * which do tlb flush out of mmu-lock should be serialized by
5822 * kvm->slots_lock otherwise tlb flush would be missed.
5824 lockdep_assert_held(&kvm->slots_lock);
5827 * We can flush all the TLBs out of the mmu lock without TLB
5828 * corruption since we just change the spte from writable to
5829 * readonly so that we only need to care the case of changing
5830 * spte from present to present (changing the spte from present
5831 * to nonpresent will flush all the TLBs immediately), in other
5832 * words, the only case we care is mmu_spte_update() where we
5833 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5834 * instead of PT_WRITABLE_MASK, that means it does not depend
5835 * on PT_WRITABLE_MASK anymore.
5838 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5842 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5843 struct kvm_rmap_head *rmap_head)
5846 struct rmap_iterator iter;
5847 int need_tlb_flush = 0;
5849 struct kvm_mmu_page *sp;
5852 for_each_rmap_spte(rmap_head, &iter, sptep) {
5853 sp = page_header(__pa(sptep));
5854 pfn = spte_to_pfn(*sptep);
5857 * We cannot do huge page mapping for indirect shadow pages,
5858 * which are found on the last rmap (level = 1) when not using
5859 * tdp; such shadow pages are synced with the page table in
5860 * the guest, and the guest page table is using 4K page size
5861 * mapping if the indirect sp has level = 1.
5863 if (sp->role.direct &&
5864 !kvm_is_reserved_pfn(pfn) &&
5865 PageTransCompoundMap(pfn_to_page(pfn))) {
5866 pte_list_remove(rmap_head, sptep);
5868 if (kvm_available_flush_tlb_with_range())
5869 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5870 KVM_PAGES_PER_HPAGE(sp->role.level));
5878 return need_tlb_flush;
5881 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5882 const struct kvm_memory_slot *memslot)
5884 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5885 spin_lock(&kvm->mmu_lock);
5886 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5887 kvm_mmu_zap_collapsible_spte, true);
5888 spin_unlock(&kvm->mmu_lock);
5891 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5892 struct kvm_memory_slot *memslot)
5896 spin_lock(&kvm->mmu_lock);
5897 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5898 spin_unlock(&kvm->mmu_lock);
5900 lockdep_assert_held(&kvm->slots_lock);
5903 * It's also safe to flush TLBs out of mmu lock here as currently this
5904 * function is only used for dirty logging, in which case flushing TLB
5905 * out of mmu lock also guarantees no dirty pages will be lost in
5909 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5912 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5914 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5915 struct kvm_memory_slot *memslot)
5919 spin_lock(&kvm->mmu_lock);
5920 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5922 spin_unlock(&kvm->mmu_lock);
5924 /* see kvm_mmu_slot_remove_write_access */
5925 lockdep_assert_held(&kvm->slots_lock);
5928 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5931 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5933 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5934 struct kvm_memory_slot *memslot)
5938 spin_lock(&kvm->mmu_lock);
5939 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5940 spin_unlock(&kvm->mmu_lock);
5942 lockdep_assert_held(&kvm->slots_lock);
5944 /* see kvm_mmu_slot_leaf_clear_dirty */
5946 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5949 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5951 static void __kvm_mmu_zap_all(struct kvm *kvm, bool mmio_only)
5953 struct kvm_mmu_page *sp, *node;
5954 LIST_HEAD(invalid_list);
5957 spin_lock(&kvm->mmu_lock);
5959 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
5960 if (mmio_only && !sp->mmio_cached)
5962 if (sp->role.invalid && sp->root_count)
5964 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign)) {
5965 WARN_ON_ONCE(mmio_only);
5968 if (cond_resched_lock(&kvm->mmu_lock))
5972 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5973 spin_unlock(&kvm->mmu_lock);
5976 void kvm_mmu_zap_all(struct kvm *kvm)
5978 return __kvm_mmu_zap_all(kvm, false);
5981 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5983 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
5985 gen &= MMIO_SPTE_GEN_MASK;
5988 * Generation numbers are incremented in multiples of the number of
5989 * address spaces in order to provide unique generations across all
5990 * address spaces. Strip what is effectively the address space
5991 * modifier prior to checking for a wrap of the MMIO generation so
5992 * that a wrap in any address space is detected.
5994 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5997 * The very rare case: if the MMIO generation number has wrapped,
5998 * zap all shadow pages.
6000 if (unlikely(gen == 0)) {
6001 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6002 __kvm_mmu_zap_all(kvm, true);
6006 static unsigned long
6007 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6010 int nr_to_scan = sc->nr_to_scan;
6011 unsigned long freed = 0;
6013 mutex_lock(&kvm_lock);
6015 list_for_each_entry(kvm, &vm_list, vm_list) {
6017 LIST_HEAD(invalid_list);
6020 * Never scan more than sc->nr_to_scan VM instances.
6021 * Will not hit this condition practically since we do not try
6022 * to shrink more than one VM and it is very unlikely to see
6023 * !n_used_mmu_pages so many times.
6028 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6029 * here. We may skip a VM instance errorneosly, but we do not
6030 * want to shrink a VM that only started to populate its MMU
6033 if (!kvm->arch.n_used_mmu_pages)
6036 idx = srcu_read_lock(&kvm->srcu);
6037 spin_lock(&kvm->mmu_lock);
6039 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6041 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6043 spin_unlock(&kvm->mmu_lock);
6044 srcu_read_unlock(&kvm->srcu, idx);
6047 * unfair on small ones
6048 * per-vm shrinkers cry out
6049 * sadness comes quickly
6051 list_move_tail(&kvm->vm_list, &vm_list);
6055 mutex_unlock(&kvm_lock);
6059 static unsigned long
6060 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6062 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6065 static struct shrinker mmu_shrinker = {
6066 .count_objects = mmu_shrink_count,
6067 .scan_objects = mmu_shrink_scan,
6068 .seeks = DEFAULT_SEEKS * 10,
6071 static void mmu_destroy_caches(void)
6073 kmem_cache_destroy(pte_list_desc_cache);
6074 kmem_cache_destroy(mmu_page_header_cache);
6077 static void kvm_set_mmio_spte_mask(void)
6082 * Set the reserved bits and the present bit of an paging-structure
6083 * entry to generate page fault with PFER.RSV = 1.
6087 * Mask the uppermost physical address bit, which would be reserved as
6088 * long as the supported physical address width is less than 52.
6092 /* Set the present bit. */
6096 * If reserved bit is not supported, clear the present bit to disable
6099 if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
6102 kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
6105 int kvm_mmu_module_init(void)
6110 * MMU roles use union aliasing which is, generally speaking, an
6111 * undefined behavior. However, we supposedly know how compilers behave
6112 * and the current status quo is unlikely to change. Guardians below are
6113 * supposed to let us know if the assumption becomes false.
6115 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6116 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6117 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6119 kvm_mmu_reset_all_pte_masks();
6121 kvm_set_mmio_spte_mask();
6123 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6124 sizeof(struct pte_list_desc),
6125 0, SLAB_ACCOUNT, NULL);
6126 if (!pte_list_desc_cache)
6129 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6130 sizeof(struct kvm_mmu_page),
6131 0, SLAB_ACCOUNT, NULL);
6132 if (!mmu_page_header_cache)
6135 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6138 ret = register_shrinker(&mmu_shrinker);
6145 mmu_destroy_caches();
6150 * Calculate mmu pages needed for kvm.
6152 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6154 unsigned long nr_mmu_pages;
6155 unsigned long nr_pages = 0;
6156 struct kvm_memslots *slots;
6157 struct kvm_memory_slot *memslot;
6160 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6161 slots = __kvm_memslots(kvm, i);
6163 kvm_for_each_memslot(memslot, slots)
6164 nr_pages += memslot->npages;
6167 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6168 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6170 return nr_mmu_pages;
6173 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6175 kvm_mmu_unload(vcpu);
6176 free_mmu_pages(&vcpu->arch.root_mmu);
6177 free_mmu_pages(&vcpu->arch.guest_mmu);
6178 mmu_free_memory_caches(vcpu);
6181 void kvm_mmu_module_exit(void)
6183 mmu_destroy_caches();
6184 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6185 unregister_shrinker(&mmu_shrinker);
6186 mmu_audit_disable();