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)) || (_sp)->role.invalid) { \
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 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2317 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2318 struct list_head *invalid_list)
2320 kvm_unlink_unsync_page(vcpu->kvm, sp);
2321 return __kvm_sync_page(vcpu, sp, invalid_list);
2324 /* @gfn should be write-protected at the call site */
2325 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2326 struct list_head *invalid_list)
2328 struct kvm_mmu_page *s;
2331 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2335 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2336 ret |= kvm_sync_page(vcpu, s, invalid_list);
2342 struct mmu_page_path {
2343 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2344 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2347 #define for_each_sp(pvec, sp, parents, i) \
2348 for (i = mmu_pages_first(&pvec, &parents); \
2349 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2350 i = mmu_pages_next(&pvec, &parents, i))
2352 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2353 struct mmu_page_path *parents,
2358 for (n = i+1; n < pvec->nr; n++) {
2359 struct kvm_mmu_page *sp = pvec->page[n].sp;
2360 unsigned idx = pvec->page[n].idx;
2361 int level = sp->role.level;
2363 parents->idx[level-1] = idx;
2364 if (level == PT_PAGE_TABLE_LEVEL)
2367 parents->parent[level-2] = sp;
2373 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2374 struct mmu_page_path *parents)
2376 struct kvm_mmu_page *sp;
2382 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2384 sp = pvec->page[0].sp;
2385 level = sp->role.level;
2386 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2388 parents->parent[level-2] = sp;
2390 /* Also set up a sentinel. Further entries in pvec are all
2391 * children of sp, so this element is never overwritten.
2393 parents->parent[level-1] = NULL;
2394 return mmu_pages_next(pvec, parents, 0);
2397 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2399 struct kvm_mmu_page *sp;
2400 unsigned int level = 0;
2403 unsigned int idx = parents->idx[level];
2404 sp = parents->parent[level];
2408 WARN_ON(idx == INVALID_INDEX);
2409 clear_unsync_child_bit(sp, idx);
2411 } while (!sp->unsync_children);
2414 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2415 struct kvm_mmu_page *parent)
2418 struct kvm_mmu_page *sp;
2419 struct mmu_page_path parents;
2420 struct kvm_mmu_pages pages;
2421 LIST_HEAD(invalid_list);
2424 while (mmu_unsync_walk(parent, &pages)) {
2425 bool protected = false;
2427 for_each_sp(pages, sp, parents, i)
2428 protected |= rmap_write_protect(vcpu, sp->gfn);
2431 kvm_flush_remote_tlbs(vcpu->kvm);
2435 for_each_sp(pages, sp, parents, i) {
2436 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2437 mmu_pages_clear_parents(&parents);
2439 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2440 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2441 cond_resched_lock(&vcpu->kvm->mmu_lock);
2446 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2449 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2451 atomic_set(&sp->write_flooding_count, 0);
2454 static void clear_sp_write_flooding_count(u64 *spte)
2456 struct kvm_mmu_page *sp = page_header(__pa(spte));
2458 __clear_sp_write_flooding_count(sp);
2461 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2468 union kvm_mmu_page_role role;
2470 struct kvm_mmu_page *sp;
2471 bool need_sync = false;
2474 LIST_HEAD(invalid_list);
2476 role = vcpu->arch.mmu->mmu_role.base;
2478 role.direct = direct;
2480 role.gpte_is_8_bytes = true;
2481 role.access = access;
2482 if (!vcpu->arch.mmu->direct_map
2483 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2484 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2485 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2486 role.quadrant = quadrant;
2488 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2489 if (sp->gfn != gfn) {
2494 if (!need_sync && sp->unsync)
2497 if (sp->role.word != role.word)
2501 /* The page is good, but __kvm_sync_page might still end
2502 * up zapping it. If so, break in order to rebuild it.
2504 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2507 WARN_ON(!list_empty(&invalid_list));
2508 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2511 if (sp->unsync_children)
2512 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2514 __clear_sp_write_flooding_count(sp);
2515 trace_kvm_mmu_get_page(sp, false);
2519 ++vcpu->kvm->stat.mmu_cache_miss;
2521 sp = kvm_mmu_alloc_page(vcpu, direct);
2525 hlist_add_head(&sp->hash_link,
2526 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2529 * we should do write protection before syncing pages
2530 * otherwise the content of the synced shadow page may
2531 * be inconsistent with guest page table.
2533 account_shadowed(vcpu->kvm, sp);
2534 if (level == PT_PAGE_TABLE_LEVEL &&
2535 rmap_write_protect(vcpu, gfn))
2536 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2538 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2539 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2541 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2542 clear_page(sp->spt);
2543 trace_kvm_mmu_get_page(sp, true);
2545 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2547 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2548 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2552 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2553 struct kvm_vcpu *vcpu, hpa_t root,
2556 iterator->addr = addr;
2557 iterator->shadow_addr = root;
2558 iterator->level = vcpu->arch.mmu->shadow_root_level;
2560 if (iterator->level == PT64_ROOT_4LEVEL &&
2561 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2562 !vcpu->arch.mmu->direct_map)
2565 if (iterator->level == PT32E_ROOT_LEVEL) {
2567 * prev_root is currently only used for 64-bit hosts. So only
2568 * the active root_hpa is valid here.
2570 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2572 iterator->shadow_addr
2573 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2574 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2576 if (!iterator->shadow_addr)
2577 iterator->level = 0;
2581 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2582 struct kvm_vcpu *vcpu, u64 addr)
2584 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2588 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2590 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2593 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2594 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2598 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2601 if (is_last_spte(spte, iterator->level)) {
2602 iterator->level = 0;
2606 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2610 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2612 __shadow_walk_next(iterator, *iterator->sptep);
2615 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2616 struct kvm_mmu_page *sp)
2620 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2622 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2623 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2625 if (sp_ad_disabled(sp))
2626 spte |= shadow_acc_track_value;
2628 spte |= shadow_accessed_mask;
2630 mmu_spte_set(sptep, spte);
2632 mmu_page_add_parent_pte(vcpu, sp, sptep);
2634 if (sp->unsync_children || sp->unsync)
2638 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2639 unsigned direct_access)
2641 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2642 struct kvm_mmu_page *child;
2645 * For the direct sp, if the guest pte's dirty bit
2646 * changed form clean to dirty, it will corrupt the
2647 * sp's access: allow writable in the read-only sp,
2648 * so we should update the spte at this point to get
2649 * a new sp with the correct access.
2651 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2652 if (child->role.access == direct_access)
2655 drop_parent_pte(child, sptep);
2656 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2660 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2664 struct kvm_mmu_page *child;
2667 if (is_shadow_present_pte(pte)) {
2668 if (is_last_spte(pte, sp->role.level)) {
2669 drop_spte(kvm, spte);
2670 if (is_large_pte(pte))
2673 child = page_header(pte & PT64_BASE_ADDR_MASK);
2674 drop_parent_pte(child, spte);
2679 if (is_mmio_spte(pte))
2680 mmu_spte_clear_no_track(spte);
2685 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2686 struct kvm_mmu_page *sp)
2690 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2691 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2694 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2697 struct rmap_iterator iter;
2699 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2700 drop_parent_pte(sp, sptep);
2703 static int mmu_zap_unsync_children(struct kvm *kvm,
2704 struct kvm_mmu_page *parent,
2705 struct list_head *invalid_list)
2708 struct mmu_page_path parents;
2709 struct kvm_mmu_pages pages;
2711 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2714 while (mmu_unsync_walk(parent, &pages)) {
2715 struct kvm_mmu_page *sp;
2717 for_each_sp(pages, sp, parents, i) {
2718 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2719 mmu_pages_clear_parents(&parents);
2727 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2728 struct kvm_mmu_page *sp,
2729 struct list_head *invalid_list,
2734 trace_kvm_mmu_prepare_zap_page(sp);
2735 ++kvm->stat.mmu_shadow_zapped;
2736 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2737 kvm_mmu_page_unlink_children(kvm, sp);
2738 kvm_mmu_unlink_parents(kvm, sp);
2740 /* Zapping children means active_mmu_pages has become unstable. */
2741 list_unstable = *nr_zapped;
2743 if (!sp->role.invalid && !sp->role.direct)
2744 unaccount_shadowed(kvm, sp);
2747 kvm_unlink_unsync_page(kvm, sp);
2748 if (!sp->root_count) {
2751 list_move(&sp->link, invalid_list);
2752 kvm_mod_used_mmu_pages(kvm, -1);
2754 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2756 if (!sp->role.invalid)
2757 kvm_reload_remote_mmus(kvm);
2760 sp->role.invalid = 1;
2761 return list_unstable;
2764 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2765 struct list_head *invalid_list)
2769 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2773 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2774 struct list_head *invalid_list)
2776 struct kvm_mmu_page *sp, *nsp;
2778 if (list_empty(invalid_list))
2782 * We need to make sure everyone sees our modifications to
2783 * the page tables and see changes to vcpu->mode here. The barrier
2784 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2785 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2787 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2788 * guest mode and/or lockless shadow page table walks.
2790 kvm_flush_remote_tlbs(kvm);
2792 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2793 WARN_ON(!sp->role.invalid || sp->root_count);
2794 kvm_mmu_free_page(sp);
2798 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2799 struct list_head *invalid_list)
2801 struct kvm_mmu_page *sp;
2803 if (list_empty(&kvm->arch.active_mmu_pages))
2806 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2807 struct kvm_mmu_page, link);
2808 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2812 * Changing the number of mmu pages allocated to the vm
2813 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2815 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2817 LIST_HEAD(invalid_list);
2819 spin_lock(&kvm->mmu_lock);
2821 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2822 /* Need to free some mmu pages to achieve the goal. */
2823 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2824 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2827 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2828 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2831 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2833 spin_unlock(&kvm->mmu_lock);
2836 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2838 struct kvm_mmu_page *sp;
2839 LIST_HEAD(invalid_list);
2842 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2844 spin_lock(&kvm->mmu_lock);
2845 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2846 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2849 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2851 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2852 spin_unlock(&kvm->mmu_lock);
2856 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2858 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2860 trace_kvm_mmu_unsync_page(sp);
2861 ++vcpu->kvm->stat.mmu_unsync;
2864 kvm_mmu_mark_parents_unsync(sp);
2867 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2870 struct kvm_mmu_page *sp;
2872 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2875 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2882 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2883 kvm_unsync_page(vcpu, sp);
2887 * We need to ensure that the marking of unsync pages is visible
2888 * before the SPTE is updated to allow writes because
2889 * kvm_mmu_sync_roots() checks the unsync flags without holding
2890 * the MMU lock and so can race with this. If the SPTE was updated
2891 * before the page had been marked as unsync-ed, something like the
2892 * following could happen:
2895 * ---------------------------------------------------------------------
2896 * 1.2 Host updates SPTE
2898 * 2.1 Guest writes a GPTE for GVA X.
2899 * (GPTE being in the guest page table shadowed
2900 * by the SP from CPU 1.)
2901 * This reads SPTE during the page table walk.
2902 * Since SPTE.W is read as 1, there is no
2905 * 2.2 Guest issues TLB flush.
2906 * That causes a VM Exit.
2908 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2909 * Since it is false, so it just returns.
2911 * 2.4 Guest accesses GVA X.
2912 * Since the mapping in the SP was not updated,
2913 * so the old mapping for GVA X incorrectly
2917 * (sp->unsync = true)
2919 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2920 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2921 * pairs with this write barrier.
2928 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2931 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2933 * Some reserved pages, such as those from NVDIMM
2934 * DAX devices, are not for MMIO, and can be mapped
2935 * with cached memory type for better performance.
2936 * However, the above check misconceives those pages
2937 * as MMIO, and results in KVM mapping them with UC
2938 * memory type, which would hurt the performance.
2939 * Therefore, we check the host memory type in addition
2940 * and only treat UC/UC-/WC pages as MMIO.
2942 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2944 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2945 pfn_to_hpa(pfn + 1) - 1,
2949 /* Bits which may be returned by set_spte() */
2950 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2951 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2953 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2954 unsigned pte_access, int level,
2955 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2956 bool can_unsync, bool host_writable)
2960 struct kvm_mmu_page *sp;
2962 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2965 sp = page_header(__pa(sptep));
2966 if (sp_ad_disabled(sp))
2967 spte |= shadow_acc_track_value;
2970 * For the EPT case, shadow_present_mask is 0 if hardware
2971 * supports exec-only page table entries. In that case,
2972 * ACC_USER_MASK and shadow_user_mask are used to represent
2973 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2975 spte |= shadow_present_mask;
2977 spte |= spte_shadow_accessed_mask(spte);
2979 if (pte_access & ACC_EXEC_MASK)
2980 spte |= shadow_x_mask;
2982 spte |= shadow_nx_mask;
2984 if (pte_access & ACC_USER_MASK)
2985 spte |= shadow_user_mask;
2987 if (level > PT_PAGE_TABLE_LEVEL)
2988 spte |= PT_PAGE_SIZE_MASK;
2990 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2991 kvm_is_mmio_pfn(pfn));
2994 spte |= SPTE_HOST_WRITEABLE;
2996 pte_access &= ~ACC_WRITE_MASK;
2998 if (!kvm_is_mmio_pfn(pfn))
2999 spte |= shadow_me_mask;
3001 spte |= (u64)pfn << PAGE_SHIFT;
3003 if (pte_access & ACC_WRITE_MASK) {
3006 * Other vcpu creates new sp in the window between
3007 * mapping_level() and acquiring mmu-lock. We can
3008 * allow guest to retry the access, the mapping can
3009 * be fixed if guest refault.
3011 if (level > PT_PAGE_TABLE_LEVEL &&
3012 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3015 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3018 * Optimization: for pte sync, if spte was writable the hash
3019 * lookup is unnecessary (and expensive). Write protection
3020 * is responsibility of mmu_get_page / kvm_sync_page.
3021 * Same reasoning can be applied to dirty page accounting.
3023 if (!can_unsync && is_writable_pte(*sptep))
3026 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3027 pgprintk("%s: found shadow page for %llx, marking ro\n",
3029 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3030 pte_access &= ~ACC_WRITE_MASK;
3031 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3035 if (pte_access & ACC_WRITE_MASK) {
3036 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3037 spte |= spte_shadow_dirty_mask(spte);
3041 spte = mark_spte_for_access_track(spte);
3044 if (mmu_spte_update(sptep, spte))
3045 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3050 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3051 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3052 bool speculative, bool host_writable)
3054 int was_rmapped = 0;
3057 int ret = RET_PF_RETRY;
3060 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3061 *sptep, write_fault, gfn);
3063 if (is_shadow_present_pte(*sptep)) {
3065 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3066 * the parent of the now unreachable PTE.
3068 if (level > PT_PAGE_TABLE_LEVEL &&
3069 !is_large_pte(*sptep)) {
3070 struct kvm_mmu_page *child;
3073 child = page_header(pte & PT64_BASE_ADDR_MASK);
3074 drop_parent_pte(child, sptep);
3076 } else if (pfn != spte_to_pfn(*sptep)) {
3077 pgprintk("hfn old %llx new %llx\n",
3078 spte_to_pfn(*sptep), pfn);
3079 drop_spte(vcpu->kvm, sptep);
3085 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3086 speculative, true, host_writable);
3087 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3089 ret = RET_PF_EMULATE;
3090 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3093 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3094 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3095 KVM_PAGES_PER_HPAGE(level));
3097 if (unlikely(is_mmio_spte(*sptep)))
3098 ret = RET_PF_EMULATE;
3100 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3101 trace_kvm_mmu_set_spte(level, gfn, sptep);
3102 if (!was_rmapped && is_large_pte(*sptep))
3103 ++vcpu->kvm->stat.lpages;
3105 if (is_shadow_present_pte(*sptep)) {
3107 rmap_count = rmap_add(vcpu, sptep, gfn);
3108 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3109 rmap_recycle(vcpu, sptep, gfn);
3116 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3119 struct kvm_memory_slot *slot;
3121 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3123 return KVM_PFN_ERR_FAULT;
3125 return gfn_to_pfn_memslot_atomic(slot, gfn);
3128 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3129 struct kvm_mmu_page *sp,
3130 u64 *start, u64 *end)
3132 struct page *pages[PTE_PREFETCH_NUM];
3133 struct kvm_memory_slot *slot;
3134 unsigned access = sp->role.access;
3138 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3139 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3143 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3147 for (i = 0; i < ret; i++, gfn++, start++) {
3148 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3149 page_to_pfn(pages[i]), true, true);
3156 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3157 struct kvm_mmu_page *sp, u64 *sptep)
3159 u64 *spte, *start = NULL;
3162 WARN_ON(!sp->role.direct);
3164 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3167 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3168 if (is_shadow_present_pte(*spte) || spte == sptep) {
3171 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3179 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3181 struct kvm_mmu_page *sp;
3183 sp = page_header(__pa(sptep));
3186 * Without accessed bits, there's no way to distinguish between
3187 * actually accessed translations and prefetched, so disable pte
3188 * prefetch if accessed bits aren't available.
3190 if (sp_ad_disabled(sp))
3193 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3196 __direct_pte_prefetch(vcpu, sp, sptep);
3199 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3200 int map_writable, int level, kvm_pfn_t pfn,
3203 struct kvm_shadow_walk_iterator it;
3204 struct kvm_mmu_page *sp;
3206 gfn_t gfn = gpa >> PAGE_SHIFT;
3207 gfn_t base_gfn = gfn;
3209 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3210 return RET_PF_RETRY;
3212 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3213 for_each_shadow_entry(vcpu, gpa, it) {
3214 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3215 if (it.level == level)
3218 drop_large_spte(vcpu, it.sptep);
3219 if (!is_shadow_present_pte(*it.sptep)) {
3220 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3221 it.level - 1, true, ACC_ALL);
3223 link_shadow_page(vcpu, it.sptep, sp);
3227 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3228 write, level, base_gfn, pfn, prefault,
3230 direct_pte_prefetch(vcpu, it.sptep);
3231 ++vcpu->stat.pf_fixed;
3235 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3237 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3240 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3243 * Do not cache the mmio info caused by writing the readonly gfn
3244 * into the spte otherwise read access on readonly gfn also can
3245 * caused mmio page fault and treat it as mmio access.
3247 if (pfn == KVM_PFN_ERR_RO_FAULT)
3248 return RET_PF_EMULATE;
3250 if (pfn == KVM_PFN_ERR_HWPOISON) {
3251 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3252 return RET_PF_RETRY;
3258 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3259 gfn_t gfn, kvm_pfn_t *pfnp,
3262 kvm_pfn_t pfn = *pfnp;
3263 int level = *levelp;
3266 * Check if it's a transparent hugepage. If this would be an
3267 * hugetlbfs page, level wouldn't be set to
3268 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3271 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3272 level == PT_PAGE_TABLE_LEVEL &&
3273 PageTransCompoundMap(pfn_to_page(pfn)) &&
3274 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3277 * mmu_notifier_retry was successful and we hold the
3278 * mmu_lock here, so the pmd can't become splitting
3279 * from under us, and in turn
3280 * __split_huge_page_refcount() can't run from under
3281 * us and we can safely transfer the refcount from
3282 * PG_tail to PG_head as we switch the pfn to tail to
3285 *levelp = level = PT_DIRECTORY_LEVEL;
3286 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3287 VM_BUG_ON((gfn & mask) != (pfn & mask));
3289 kvm_release_pfn_clean(pfn);
3297 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3298 kvm_pfn_t pfn, unsigned access, int *ret_val)
3300 /* The pfn is invalid, report the error! */
3301 if (unlikely(is_error_pfn(pfn))) {
3302 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3306 if (unlikely(is_noslot_pfn(pfn)))
3307 vcpu_cache_mmio_info(vcpu, gva, gfn,
3308 access & shadow_mmio_access_mask);
3313 static bool page_fault_can_be_fast(u32 error_code)
3316 * Do not fix the mmio spte with invalid generation number which
3317 * need to be updated by slow page fault path.
3319 if (unlikely(error_code & PFERR_RSVD_MASK))
3322 /* See if the page fault is due to an NX violation */
3323 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3324 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3328 * #PF can be fast if:
3329 * 1. The shadow page table entry is not present, which could mean that
3330 * the fault is potentially caused by access tracking (if enabled).
3331 * 2. The shadow page table entry is present and the fault
3332 * is caused by write-protect, that means we just need change the W
3333 * bit of the spte which can be done out of mmu-lock.
3335 * However, if access tracking is disabled we know that a non-present
3336 * page must be a genuine page fault where we have to create a new SPTE.
3337 * So, if access tracking is disabled, we return true only for write
3338 * accesses to a present page.
3341 return shadow_acc_track_mask != 0 ||
3342 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3343 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3347 * Returns true if the SPTE was fixed successfully. Otherwise,
3348 * someone else modified the SPTE from its original value.
3351 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3352 u64 *sptep, u64 old_spte, u64 new_spte)
3356 WARN_ON(!sp->role.direct);
3359 * Theoretically we could also set dirty bit (and flush TLB) here in
3360 * order to eliminate unnecessary PML logging. See comments in
3361 * set_spte. But fast_page_fault is very unlikely to happen with PML
3362 * enabled, so we do not do this. This might result in the same GPA
3363 * to be logged in PML buffer again when the write really happens, and
3364 * eventually to be called by mark_page_dirty twice. But it's also no
3365 * harm. This also avoids the TLB flush needed after setting dirty bit
3366 * so non-PML cases won't be impacted.
3368 * Compare with set_spte where instead shadow_dirty_mask is set.
3370 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3373 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3375 * The gfn of direct spte is stable since it is
3376 * calculated by sp->gfn.
3378 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3379 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3385 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3387 if (fault_err_code & PFERR_FETCH_MASK)
3388 return is_executable_pte(spte);
3390 if (fault_err_code & PFERR_WRITE_MASK)
3391 return is_writable_pte(spte);
3393 /* Fault was on Read access */
3394 return spte & PT_PRESENT_MASK;
3399 * - true: let the vcpu to access on the same address again.
3400 * - false: let the real page fault path to fix it.
3402 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3405 struct kvm_shadow_walk_iterator iterator;
3406 struct kvm_mmu_page *sp;
3407 bool fault_handled = false;
3409 uint retry_count = 0;
3411 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3414 if (!page_fault_can_be_fast(error_code))
3417 walk_shadow_page_lockless_begin(vcpu);
3422 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3423 if (!is_shadow_present_pte(spte) ||
3424 iterator.level < level)
3427 sp = page_header(__pa(iterator.sptep));
3428 if (!is_last_spte(spte, sp->role.level))
3432 * Check whether the memory access that caused the fault would
3433 * still cause it if it were to be performed right now. If not,
3434 * then this is a spurious fault caused by TLB lazily flushed,
3435 * or some other CPU has already fixed the PTE after the
3436 * current CPU took the fault.
3438 * Need not check the access of upper level table entries since
3439 * they are always ACC_ALL.
3441 if (is_access_allowed(error_code, spte)) {
3442 fault_handled = true;
3448 if (is_access_track_spte(spte))
3449 new_spte = restore_acc_track_spte(new_spte);
3452 * Currently, to simplify the code, write-protection can
3453 * be removed in the fast path only if the SPTE was
3454 * write-protected for dirty-logging or access tracking.
3456 if ((error_code & PFERR_WRITE_MASK) &&
3457 spte_can_locklessly_be_made_writable(spte))
3459 new_spte |= PT_WRITABLE_MASK;
3462 * Do not fix write-permission on the large spte. Since
3463 * we only dirty the first page into the dirty-bitmap in
3464 * fast_pf_fix_direct_spte(), other pages are missed
3465 * if its slot has dirty logging enabled.
3467 * Instead, we let the slow page fault path create a
3468 * normal spte to fix the access.
3470 * See the comments in kvm_arch_commit_memory_region().
3472 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3476 /* Verify that the fault can be handled in the fast path */
3477 if (new_spte == spte ||
3478 !is_access_allowed(error_code, new_spte))
3482 * Currently, fast page fault only works for direct mapping
3483 * since the gfn is not stable for indirect shadow page. See
3484 * Documentation/virt/kvm/locking.txt to get more detail.
3486 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3487 iterator.sptep, spte,
3492 if (++retry_count > 4) {
3493 printk_once(KERN_WARNING
3494 "kvm: Fast #PF retrying more than 4 times.\n");
3500 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3501 spte, fault_handled);
3502 walk_shadow_page_lockless_end(vcpu);
3504 return fault_handled;
3507 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3508 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3509 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3511 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3512 gfn_t gfn, bool prefault)
3516 bool force_pt_level = false;
3518 unsigned long mmu_seq;
3519 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3521 level = mapping_level(vcpu, gfn, &force_pt_level);
3522 if (likely(!force_pt_level)) {
3524 * This path builds a PAE pagetable - so we can map
3525 * 2mb pages at maximum. Therefore check if the level
3526 * is larger than that.
3528 if (level > PT_DIRECTORY_LEVEL)
3529 level = PT_DIRECTORY_LEVEL;
3531 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3534 if (fast_page_fault(vcpu, v, level, error_code))
3535 return RET_PF_RETRY;
3537 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3540 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3541 return RET_PF_RETRY;
3543 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3547 spin_lock(&vcpu->kvm->mmu_lock);
3548 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3550 if (make_mmu_pages_available(vcpu) < 0)
3552 if (likely(!force_pt_level))
3553 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3554 r = __direct_map(vcpu, v, write, map_writable, level, pfn, prefault);
3556 spin_unlock(&vcpu->kvm->mmu_lock);
3557 kvm_release_pfn_clean(pfn);
3561 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3562 struct list_head *invalid_list)
3564 struct kvm_mmu_page *sp;
3566 if (!VALID_PAGE(*root_hpa))
3569 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3571 if (!sp->root_count && sp->role.invalid)
3572 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3574 *root_hpa = INVALID_PAGE;
3577 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3578 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3579 ulong roots_to_free)
3582 LIST_HEAD(invalid_list);
3583 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3585 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3587 /* Before acquiring the MMU lock, see if we need to do any real work. */
3588 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3589 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3590 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3591 VALID_PAGE(mmu->prev_roots[i].hpa))
3594 if (i == KVM_MMU_NUM_PREV_ROOTS)
3598 spin_lock(&vcpu->kvm->mmu_lock);
3600 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3601 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3602 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3605 if (free_active_root) {
3606 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3607 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3608 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3611 for (i = 0; i < 4; ++i)
3612 if (mmu->pae_root[i] != 0)
3613 mmu_free_root_page(vcpu->kvm,
3616 mmu->root_hpa = INVALID_PAGE;
3621 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3622 spin_unlock(&vcpu->kvm->mmu_lock);
3624 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3626 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3630 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3631 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3638 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3640 struct kvm_mmu_page *sp;
3643 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3644 spin_lock(&vcpu->kvm->mmu_lock);
3645 if(make_mmu_pages_available(vcpu) < 0) {
3646 spin_unlock(&vcpu->kvm->mmu_lock);
3649 sp = kvm_mmu_get_page(vcpu, 0, 0,
3650 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3652 spin_unlock(&vcpu->kvm->mmu_lock);
3653 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3654 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3655 for (i = 0; i < 4; ++i) {
3656 hpa_t root = vcpu->arch.mmu->pae_root[i];
3658 MMU_WARN_ON(VALID_PAGE(root));
3659 spin_lock(&vcpu->kvm->mmu_lock);
3660 if (make_mmu_pages_available(vcpu) < 0) {
3661 spin_unlock(&vcpu->kvm->mmu_lock);
3664 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3665 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3666 root = __pa(sp->spt);
3668 spin_unlock(&vcpu->kvm->mmu_lock);
3669 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3671 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3674 vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3679 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3681 struct kvm_mmu_page *sp;
3683 gfn_t root_gfn, root_cr3;
3686 root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3687 root_gfn = root_cr3 >> PAGE_SHIFT;
3689 if (mmu_check_root(vcpu, root_gfn))
3693 * Do we shadow a long mode page table? If so we need to
3694 * write-protect the guests page table root.
3696 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3697 hpa_t root = vcpu->arch.mmu->root_hpa;
3699 MMU_WARN_ON(VALID_PAGE(root));
3701 spin_lock(&vcpu->kvm->mmu_lock);
3702 if (make_mmu_pages_available(vcpu) < 0) {
3703 spin_unlock(&vcpu->kvm->mmu_lock);
3706 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3707 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3708 root = __pa(sp->spt);
3710 spin_unlock(&vcpu->kvm->mmu_lock);
3711 vcpu->arch.mmu->root_hpa = root;
3716 * We shadow a 32 bit page table. This may be a legacy 2-level
3717 * or a PAE 3-level page table. In either case we need to be aware that
3718 * the shadow page table may be a PAE or a long mode page table.
3720 pm_mask = PT_PRESENT_MASK;
3721 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3722 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3724 for (i = 0; i < 4; ++i) {
3725 hpa_t root = vcpu->arch.mmu->pae_root[i];
3727 MMU_WARN_ON(VALID_PAGE(root));
3728 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3729 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3730 if (!(pdptr & PT_PRESENT_MASK)) {
3731 vcpu->arch.mmu->pae_root[i] = 0;
3734 root_gfn = pdptr >> PAGE_SHIFT;
3735 if (mmu_check_root(vcpu, root_gfn))
3738 spin_lock(&vcpu->kvm->mmu_lock);
3739 if (make_mmu_pages_available(vcpu) < 0) {
3740 spin_unlock(&vcpu->kvm->mmu_lock);
3743 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3745 root = __pa(sp->spt);
3747 spin_unlock(&vcpu->kvm->mmu_lock);
3749 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3751 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3754 * If we shadow a 32 bit page table with a long mode page
3755 * table we enter this path.
3757 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3758 if (vcpu->arch.mmu->lm_root == NULL) {
3760 * The additional page necessary for this is only
3761 * allocated on demand.
3766 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3767 if (lm_root == NULL)
3770 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3772 vcpu->arch.mmu->lm_root = lm_root;
3775 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3779 vcpu->arch.mmu->root_cr3 = root_cr3;
3784 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3786 if (vcpu->arch.mmu->direct_map)
3787 return mmu_alloc_direct_roots(vcpu);
3789 return mmu_alloc_shadow_roots(vcpu);
3792 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3795 struct kvm_mmu_page *sp;
3797 if (vcpu->arch.mmu->direct_map)
3800 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3803 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3805 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3806 hpa_t root = vcpu->arch.mmu->root_hpa;
3807 sp = page_header(root);
3810 * Even if another CPU was marking the SP as unsync-ed
3811 * simultaneously, any guest page table changes are not
3812 * guaranteed to be visible anyway until this VCPU issues a TLB
3813 * flush strictly after those changes are made. We only need to
3814 * ensure that the other CPU sets these flags before any actual
3815 * changes to the page tables are made. The comments in
3816 * mmu_need_write_protect() describe what could go wrong if this
3817 * requirement isn't satisfied.
3819 if (!smp_load_acquire(&sp->unsync) &&
3820 !smp_load_acquire(&sp->unsync_children))
3823 spin_lock(&vcpu->kvm->mmu_lock);
3824 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3826 mmu_sync_children(vcpu, sp);
3828 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3829 spin_unlock(&vcpu->kvm->mmu_lock);
3833 spin_lock(&vcpu->kvm->mmu_lock);
3834 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3836 for (i = 0; i < 4; ++i) {
3837 hpa_t root = vcpu->arch.mmu->pae_root[i];
3839 if (root && VALID_PAGE(root)) {
3840 root &= PT64_BASE_ADDR_MASK;
3841 sp = page_header(root);
3842 mmu_sync_children(vcpu, sp);
3846 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3847 spin_unlock(&vcpu->kvm->mmu_lock);
3849 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3851 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3852 u32 access, struct x86_exception *exception)
3855 exception->error_code = 0;
3859 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3861 struct x86_exception *exception)
3864 exception->error_code = 0;
3865 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3869 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3871 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3873 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3874 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3877 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3879 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3882 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3884 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3887 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3890 * A nested guest cannot use the MMIO cache if it is using nested
3891 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3893 if (mmu_is_nested(vcpu))
3897 return vcpu_match_mmio_gpa(vcpu, addr);
3899 return vcpu_match_mmio_gva(vcpu, addr);
3902 /* return true if reserved bit is detected on spte. */
3904 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3906 struct kvm_shadow_walk_iterator iterator;
3907 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3909 bool reserved = false;
3911 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3914 walk_shadow_page_lockless_begin(vcpu);
3916 for (shadow_walk_init(&iterator, vcpu, addr),
3917 leaf = root = iterator.level;
3918 shadow_walk_okay(&iterator);
3919 __shadow_walk_next(&iterator, spte)) {
3920 spte = mmu_spte_get_lockless(iterator.sptep);
3922 sptes[leaf - 1] = spte;
3925 if (!is_shadow_present_pte(spte))
3928 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3932 walk_shadow_page_lockless_end(vcpu);
3935 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3937 while (root > leaf) {
3938 pr_err("------ spte 0x%llx level %d.\n",
3939 sptes[root - 1], root);
3948 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3953 if (mmio_info_in_cache(vcpu, addr, direct))
3954 return RET_PF_EMULATE;
3956 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3957 if (WARN_ON(reserved))
3960 if (is_mmio_spte(spte)) {
3961 gfn_t gfn = get_mmio_spte_gfn(spte);
3962 unsigned access = get_mmio_spte_access(spte);
3964 if (!check_mmio_spte(vcpu, spte))
3965 return RET_PF_INVALID;
3970 trace_handle_mmio_page_fault(addr, gfn, access);
3971 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3972 return RET_PF_EMULATE;
3976 * If the page table is zapped by other cpus, let CPU fault again on
3979 return RET_PF_RETRY;
3982 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3983 u32 error_code, gfn_t gfn)
3985 if (unlikely(error_code & PFERR_RSVD_MASK))
3988 if (!(error_code & PFERR_PRESENT_MASK) ||
3989 !(error_code & PFERR_WRITE_MASK))
3993 * guest is writing the page which is write tracked which can
3994 * not be fixed by page fault handler.
3996 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4002 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4004 struct kvm_shadow_walk_iterator iterator;
4007 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
4010 walk_shadow_page_lockless_begin(vcpu);
4011 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4012 clear_sp_write_flooding_count(iterator.sptep);
4013 if (!is_shadow_present_pte(spte))
4016 walk_shadow_page_lockless_end(vcpu);
4019 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
4020 u32 error_code, bool prefault)
4022 gfn_t gfn = gva >> PAGE_SHIFT;
4025 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
4027 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4028 return RET_PF_EMULATE;
4030 r = mmu_topup_memory_caches(vcpu);
4034 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4037 return nonpaging_map(vcpu, gva & PAGE_MASK,
4038 error_code, gfn, prefault);
4041 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
4043 struct kvm_arch_async_pf arch;
4045 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4047 arch.direct_map = vcpu->arch.mmu->direct_map;
4048 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4050 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4053 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4054 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4056 struct kvm_memory_slot *slot;
4060 * Don't expose private memslots to L2.
4062 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4063 *pfn = KVM_PFN_NOSLOT;
4067 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4069 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4071 return false; /* *pfn has correct page already */
4073 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4074 trace_kvm_try_async_get_page(gva, gfn);
4075 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4076 trace_kvm_async_pf_doublefault(gva, gfn);
4077 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4079 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4083 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4087 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4088 u64 fault_address, char *insn, int insn_len)
4092 vcpu->arch.l1tf_flush_l1d = true;
4093 switch (vcpu->arch.apf.host_apf_reason) {
4095 trace_kvm_page_fault(fault_address, error_code);
4097 if (kvm_event_needs_reinjection(vcpu))
4098 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4099 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4102 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4103 vcpu->arch.apf.host_apf_reason = 0;
4104 local_irq_disable();
4105 kvm_async_pf_task_wait(fault_address, 0);
4108 case KVM_PV_REASON_PAGE_READY:
4109 vcpu->arch.apf.host_apf_reason = 0;
4110 local_irq_disable();
4111 kvm_async_pf_task_wake(fault_address);
4117 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4120 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4122 int page_num = KVM_PAGES_PER_HPAGE(level);
4124 gfn &= ~(page_num - 1);
4126 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4129 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4135 bool force_pt_level;
4136 gfn_t gfn = gpa >> PAGE_SHIFT;
4137 unsigned long mmu_seq;
4138 int write = error_code & PFERR_WRITE_MASK;
4141 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4143 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4144 return RET_PF_EMULATE;
4146 r = mmu_topup_memory_caches(vcpu);
4150 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4151 PT_DIRECTORY_LEVEL);
4152 level = mapping_level(vcpu, gfn, &force_pt_level);
4153 if (likely(!force_pt_level)) {
4154 if (level > PT_DIRECTORY_LEVEL &&
4155 !check_hugepage_cache_consistency(vcpu, gfn, level))
4156 level = PT_DIRECTORY_LEVEL;
4157 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4160 if (fast_page_fault(vcpu, gpa, level, error_code))
4161 return RET_PF_RETRY;
4163 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4166 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4167 return RET_PF_RETRY;
4169 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4173 spin_lock(&vcpu->kvm->mmu_lock);
4174 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4176 if (make_mmu_pages_available(vcpu) < 0)
4178 if (likely(!force_pt_level))
4179 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4180 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn, prefault);
4182 spin_unlock(&vcpu->kvm->mmu_lock);
4183 kvm_release_pfn_clean(pfn);
4187 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4188 struct kvm_mmu *context)
4190 context->page_fault = nonpaging_page_fault;
4191 context->gva_to_gpa = nonpaging_gva_to_gpa;
4192 context->sync_page = nonpaging_sync_page;
4193 context->invlpg = nonpaging_invlpg;
4194 context->update_pte = nonpaging_update_pte;
4195 context->root_level = 0;
4196 context->shadow_root_level = PT32E_ROOT_LEVEL;
4197 context->direct_map = true;
4198 context->nx = false;
4202 * Find out if a previously cached root matching the new CR3/role is available.
4203 * The current root is also inserted into the cache.
4204 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4206 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4207 * false is returned. This root should now be freed by the caller.
4209 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4210 union kvm_mmu_page_role new_role)
4213 struct kvm_mmu_root_info root;
4214 struct kvm_mmu *mmu = vcpu->arch.mmu;
4216 root.cr3 = mmu->root_cr3;
4217 root.hpa = mmu->root_hpa;
4219 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4220 swap(root, mmu->prev_roots[i]);
4222 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4223 page_header(root.hpa) != NULL &&
4224 new_role.word == page_header(root.hpa)->role.word)
4228 mmu->root_hpa = root.hpa;
4229 mmu->root_cr3 = root.cr3;
4231 return i < KVM_MMU_NUM_PREV_ROOTS;
4234 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4235 union kvm_mmu_page_role new_role,
4236 bool skip_tlb_flush)
4238 struct kvm_mmu *mmu = vcpu->arch.mmu;
4241 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4242 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4243 * later if necessary.
4245 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4246 mmu->root_level >= PT64_ROOT_4LEVEL) {
4247 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4250 if (cached_root_available(vcpu, new_cr3, new_role)) {
4252 * It is possible that the cached previous root page is
4253 * obsolete because of a change in the MMU generation
4254 * number. However, changing the generation number is
4255 * accompanied by KVM_REQ_MMU_RELOAD, which will free
4256 * the root set here and allocate a new one.
4258 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4259 if (!skip_tlb_flush) {
4260 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4261 kvm_x86_ops->tlb_flush(vcpu, true);
4265 * The last MMIO access's GVA and GPA are cached in the
4266 * VCPU. When switching to a new CR3, that GVA->GPA
4267 * mapping may no longer be valid. So clear any cached
4268 * MMIO info even when we don't need to sync the shadow
4271 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4273 __clear_sp_write_flooding_count(
4274 page_header(mmu->root_hpa));
4283 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4284 union kvm_mmu_page_role new_role,
4285 bool skip_tlb_flush)
4287 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4288 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4289 KVM_MMU_ROOT_CURRENT);
4292 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4294 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4297 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4299 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4301 return kvm_read_cr3(vcpu);
4304 static void inject_page_fault(struct kvm_vcpu *vcpu,
4305 struct x86_exception *fault)
4307 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4310 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4311 unsigned access, int *nr_present)
4313 if (unlikely(is_mmio_spte(*sptep))) {
4314 if (gfn != get_mmio_spte_gfn(*sptep)) {
4315 mmu_spte_clear_no_track(sptep);
4320 mark_mmio_spte(vcpu, sptep, gfn, access);
4327 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4328 unsigned level, unsigned gpte)
4331 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4332 * If it is clear, there are no large pages at this level, so clear
4333 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4335 gpte &= level - mmu->last_nonleaf_level;
4338 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4339 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4340 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4342 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4344 return gpte & PT_PAGE_SIZE_MASK;
4347 #define PTTYPE_EPT 18 /* arbitrary */
4348 #define PTTYPE PTTYPE_EPT
4349 #include "paging_tmpl.h"
4353 #include "paging_tmpl.h"
4357 #include "paging_tmpl.h"
4361 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4362 struct rsvd_bits_validate *rsvd_check,
4363 int maxphyaddr, int level, bool nx, bool gbpages,
4366 u64 exb_bit_rsvd = 0;
4367 u64 gbpages_bit_rsvd = 0;
4368 u64 nonleaf_bit8_rsvd = 0;
4370 rsvd_check->bad_mt_xwr = 0;
4373 exb_bit_rsvd = rsvd_bits(63, 63);
4375 gbpages_bit_rsvd = rsvd_bits(7, 7);
4378 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4379 * leaf entries) on AMD CPUs only.
4382 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4385 case PT32_ROOT_LEVEL:
4386 /* no rsvd bits for 2 level 4K page table entries */
4387 rsvd_check->rsvd_bits_mask[0][1] = 0;
4388 rsvd_check->rsvd_bits_mask[0][0] = 0;
4389 rsvd_check->rsvd_bits_mask[1][0] =
4390 rsvd_check->rsvd_bits_mask[0][0];
4393 rsvd_check->rsvd_bits_mask[1][1] = 0;
4397 if (is_cpuid_PSE36())
4398 /* 36bits PSE 4MB page */
4399 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4401 /* 32 bits PSE 4MB page */
4402 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4404 case PT32E_ROOT_LEVEL:
4405 rsvd_check->rsvd_bits_mask[0][2] =
4406 rsvd_bits(maxphyaddr, 63) |
4407 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4408 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4409 rsvd_bits(maxphyaddr, 62); /* PDE */
4410 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4411 rsvd_bits(maxphyaddr, 62); /* PTE */
4412 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4413 rsvd_bits(maxphyaddr, 62) |
4414 rsvd_bits(13, 20); /* large page */
4415 rsvd_check->rsvd_bits_mask[1][0] =
4416 rsvd_check->rsvd_bits_mask[0][0];
4418 case PT64_ROOT_5LEVEL:
4419 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4420 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4421 rsvd_bits(maxphyaddr, 51);
4422 rsvd_check->rsvd_bits_mask[1][4] =
4423 rsvd_check->rsvd_bits_mask[0][4];
4425 case PT64_ROOT_4LEVEL:
4426 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4427 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4428 rsvd_bits(maxphyaddr, 51);
4429 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4430 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4431 rsvd_bits(maxphyaddr, 51);
4432 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4433 rsvd_bits(maxphyaddr, 51);
4434 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4435 rsvd_bits(maxphyaddr, 51);
4436 rsvd_check->rsvd_bits_mask[1][3] =
4437 rsvd_check->rsvd_bits_mask[0][3];
4438 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4439 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4441 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4442 rsvd_bits(maxphyaddr, 51) |
4443 rsvd_bits(13, 20); /* large page */
4444 rsvd_check->rsvd_bits_mask[1][0] =
4445 rsvd_check->rsvd_bits_mask[0][0];
4450 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4451 struct kvm_mmu *context)
4453 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4454 cpuid_maxphyaddr(vcpu), context->root_level,
4456 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4457 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4461 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4462 int maxphyaddr, bool execonly)
4466 rsvd_check->rsvd_bits_mask[0][4] =
4467 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4468 rsvd_check->rsvd_bits_mask[0][3] =
4469 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4470 rsvd_check->rsvd_bits_mask[0][2] =
4471 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4472 rsvd_check->rsvd_bits_mask[0][1] =
4473 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4474 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4477 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4478 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4479 rsvd_check->rsvd_bits_mask[1][2] =
4480 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4481 rsvd_check->rsvd_bits_mask[1][1] =
4482 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4483 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4485 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4486 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4487 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4488 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4489 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4491 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4492 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4494 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4497 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4498 struct kvm_mmu *context, bool execonly)
4500 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4501 cpuid_maxphyaddr(vcpu), execonly);
4505 * the page table on host is the shadow page table for the page
4506 * table in guest or amd nested guest, its mmu features completely
4507 * follow the features in guest.
4510 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4512 bool uses_nx = context->nx ||
4513 context->mmu_role.base.smep_andnot_wp;
4514 struct rsvd_bits_validate *shadow_zero_check;
4518 * Passing "true" to the last argument is okay; it adds a check
4519 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4521 shadow_zero_check = &context->shadow_zero_check;
4522 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4524 context->shadow_root_level, uses_nx,
4525 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4526 is_pse(vcpu), true);
4528 if (!shadow_me_mask)
4531 for (i = context->shadow_root_level; --i >= 0;) {
4532 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4533 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4537 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4539 static inline bool boot_cpu_is_amd(void)
4541 WARN_ON_ONCE(!tdp_enabled);
4542 return shadow_x_mask == 0;
4546 * the direct page table on host, use as much mmu features as
4547 * possible, however, kvm currently does not do execution-protection.
4550 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4551 struct kvm_mmu *context)
4553 struct rsvd_bits_validate *shadow_zero_check;
4556 shadow_zero_check = &context->shadow_zero_check;
4558 if (boot_cpu_is_amd())
4559 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4561 context->shadow_root_level, false,
4562 boot_cpu_has(X86_FEATURE_GBPAGES),
4565 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4569 if (!shadow_me_mask)
4572 for (i = context->shadow_root_level; --i >= 0;) {
4573 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4574 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4579 * as the comments in reset_shadow_zero_bits_mask() except it
4580 * is the shadow page table for intel nested guest.
4583 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4584 struct kvm_mmu *context, bool execonly)
4586 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4587 shadow_phys_bits, execonly);
4590 #define BYTE_MASK(access) \
4591 ((1 & (access) ? 2 : 0) | \
4592 (2 & (access) ? 4 : 0) | \
4593 (3 & (access) ? 8 : 0) | \
4594 (4 & (access) ? 16 : 0) | \
4595 (5 & (access) ? 32 : 0) | \
4596 (6 & (access) ? 64 : 0) | \
4597 (7 & (access) ? 128 : 0))
4600 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4601 struct kvm_mmu *mmu, bool ept)
4605 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4606 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4607 const u8 u = BYTE_MASK(ACC_USER_MASK);
4609 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4610 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4611 bool cr0_wp = is_write_protection(vcpu);
4613 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4614 unsigned pfec = byte << 1;
4617 * Each "*f" variable has a 1 bit for each UWX value
4618 * that causes a fault with the given PFEC.
4621 /* Faults from writes to non-writable pages */
4622 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4623 /* Faults from user mode accesses to supervisor pages */
4624 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4625 /* Faults from fetches of non-executable pages*/
4626 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4627 /* Faults from kernel mode fetches of user pages */
4629 /* Faults from kernel mode accesses of user pages */
4633 /* Faults from kernel mode accesses to user pages */
4634 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4636 /* Not really needed: !nx will cause pte.nx to fault */
4640 /* Allow supervisor writes if !cr0.wp */
4642 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4644 /* Disallow supervisor fetches of user code if cr4.smep */
4646 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4649 * SMAP:kernel-mode data accesses from user-mode
4650 * mappings should fault. A fault is considered
4651 * as a SMAP violation if all of the following
4652 * conditions are true:
4653 * - X86_CR4_SMAP is set in CR4
4654 * - A user page is accessed
4655 * - The access is not a fetch
4656 * - Page fault in kernel mode
4657 * - if CPL = 3 or X86_EFLAGS_AC is clear
4659 * Here, we cover the first three conditions.
4660 * The fourth is computed dynamically in permission_fault();
4661 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4662 * *not* subject to SMAP restrictions.
4665 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4668 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4673 * PKU is an additional mechanism by which the paging controls access to
4674 * user-mode addresses based on the value in the PKRU register. Protection
4675 * key violations are reported through a bit in the page fault error code.
4676 * Unlike other bits of the error code, the PK bit is not known at the
4677 * call site of e.g. gva_to_gpa; it must be computed directly in
4678 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4679 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4681 * In particular the following conditions come from the error code, the
4682 * page tables and the machine state:
4683 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4684 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4685 * - PK is always zero if U=0 in the page tables
4686 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4688 * The PKRU bitmask caches the result of these four conditions. The error
4689 * code (minus the P bit) and the page table's U bit form an index into the
4690 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4691 * with the two bits of the PKRU register corresponding to the protection key.
4692 * For the first three conditions above the bits will be 00, thus masking
4693 * away both AD and WD. For all reads or if the last condition holds, WD
4694 * only will be masked away.
4696 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4707 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4708 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4713 wp = is_write_protection(vcpu);
4715 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4716 unsigned pfec, pkey_bits;
4717 bool check_pkey, check_write, ff, uf, wf, pte_user;
4720 ff = pfec & PFERR_FETCH_MASK;
4721 uf = pfec & PFERR_USER_MASK;
4722 wf = pfec & PFERR_WRITE_MASK;
4724 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4725 pte_user = pfec & PFERR_RSVD_MASK;
4728 * Only need to check the access which is not an
4729 * instruction fetch and is to a user page.
4731 check_pkey = (!ff && pte_user);
4733 * write access is controlled by PKRU if it is a
4734 * user access or CR0.WP = 1.
4736 check_write = check_pkey && wf && (uf || wp);
4738 /* PKRU.AD stops both read and write access. */
4739 pkey_bits = !!check_pkey;
4740 /* PKRU.WD stops write access. */
4741 pkey_bits |= (!!check_write) << 1;
4743 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4747 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4749 unsigned root_level = mmu->root_level;
4751 mmu->last_nonleaf_level = root_level;
4752 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4753 mmu->last_nonleaf_level++;
4756 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4757 struct kvm_mmu *context,
4760 context->nx = is_nx(vcpu);
4761 context->root_level = level;
4763 reset_rsvds_bits_mask(vcpu, context);
4764 update_permission_bitmask(vcpu, context, false);
4765 update_pkru_bitmask(vcpu, context, false);
4766 update_last_nonleaf_level(vcpu, context);
4768 MMU_WARN_ON(!is_pae(vcpu));
4769 context->page_fault = paging64_page_fault;
4770 context->gva_to_gpa = paging64_gva_to_gpa;
4771 context->sync_page = paging64_sync_page;
4772 context->invlpg = paging64_invlpg;
4773 context->update_pte = paging64_update_pte;
4774 context->shadow_root_level = level;
4775 context->direct_map = false;
4778 static void paging64_init_context(struct kvm_vcpu *vcpu,
4779 struct kvm_mmu *context)
4781 int root_level = is_la57_mode(vcpu) ?
4782 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4784 paging64_init_context_common(vcpu, context, root_level);
4787 static void paging32_init_context(struct kvm_vcpu *vcpu,
4788 struct kvm_mmu *context)
4790 context->nx = false;
4791 context->root_level = PT32_ROOT_LEVEL;
4793 reset_rsvds_bits_mask(vcpu, context);
4794 update_permission_bitmask(vcpu, context, false);
4795 update_pkru_bitmask(vcpu, context, false);
4796 update_last_nonleaf_level(vcpu, context);
4798 context->page_fault = paging32_page_fault;
4799 context->gva_to_gpa = paging32_gva_to_gpa;
4800 context->sync_page = paging32_sync_page;
4801 context->invlpg = paging32_invlpg;
4802 context->update_pte = paging32_update_pte;
4803 context->shadow_root_level = PT32E_ROOT_LEVEL;
4804 context->direct_map = false;
4807 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4808 struct kvm_mmu *context)
4810 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4813 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4815 union kvm_mmu_extended_role ext = {0};
4817 ext.cr0_pg = !!is_paging(vcpu);
4818 ext.cr4_pae = !!is_pae(vcpu);
4819 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4820 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4821 ext.cr4_pse = !!is_pse(vcpu);
4822 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4823 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4824 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4831 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4834 union kvm_mmu_role role = {0};
4836 role.base.access = ACC_ALL;
4837 role.base.nxe = !!is_nx(vcpu);
4838 role.base.cr0_wp = is_write_protection(vcpu);
4839 role.base.smm = is_smm(vcpu);
4840 role.base.guest_mode = is_guest_mode(vcpu);
4845 role.ext = kvm_calc_mmu_role_ext(vcpu);
4850 static union kvm_mmu_role
4851 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4853 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4855 role.base.ad_disabled = (shadow_accessed_mask == 0);
4856 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4857 role.base.direct = true;
4858 role.base.gpte_is_8_bytes = true;
4863 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4865 struct kvm_mmu *context = vcpu->arch.mmu;
4866 union kvm_mmu_role new_role =
4867 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4869 new_role.base.word &= mmu_base_role_mask.word;
4870 if (new_role.as_u64 == context->mmu_role.as_u64)
4873 context->mmu_role.as_u64 = new_role.as_u64;
4874 context->page_fault = tdp_page_fault;
4875 context->sync_page = nonpaging_sync_page;
4876 context->invlpg = nonpaging_invlpg;
4877 context->update_pte = nonpaging_update_pte;
4878 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4879 context->direct_map = true;
4880 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4881 context->get_cr3 = get_cr3;
4882 context->get_pdptr = kvm_pdptr_read;
4883 context->inject_page_fault = kvm_inject_page_fault;
4885 if (!is_paging(vcpu)) {
4886 context->nx = false;
4887 context->gva_to_gpa = nonpaging_gva_to_gpa;
4888 context->root_level = 0;
4889 } else if (is_long_mode(vcpu)) {
4890 context->nx = is_nx(vcpu);
4891 context->root_level = is_la57_mode(vcpu) ?
4892 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4893 reset_rsvds_bits_mask(vcpu, context);
4894 context->gva_to_gpa = paging64_gva_to_gpa;
4895 } else if (is_pae(vcpu)) {
4896 context->nx = is_nx(vcpu);
4897 context->root_level = PT32E_ROOT_LEVEL;
4898 reset_rsvds_bits_mask(vcpu, context);
4899 context->gva_to_gpa = paging64_gva_to_gpa;
4901 context->nx = false;
4902 context->root_level = PT32_ROOT_LEVEL;
4903 reset_rsvds_bits_mask(vcpu, context);
4904 context->gva_to_gpa = paging32_gva_to_gpa;
4907 update_permission_bitmask(vcpu, context, false);
4908 update_pkru_bitmask(vcpu, context, false);
4909 update_last_nonleaf_level(vcpu, context);
4910 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4913 static union kvm_mmu_role
4914 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4916 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4918 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4919 !is_write_protection(vcpu);
4920 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4921 !is_write_protection(vcpu);
4922 role.base.direct = !is_paging(vcpu);
4923 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4925 if (!is_long_mode(vcpu))
4926 role.base.level = PT32E_ROOT_LEVEL;
4927 else if (is_la57_mode(vcpu))
4928 role.base.level = PT64_ROOT_5LEVEL;
4930 role.base.level = PT64_ROOT_4LEVEL;
4935 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4937 struct kvm_mmu *context = vcpu->arch.mmu;
4938 union kvm_mmu_role new_role =
4939 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4941 new_role.base.word &= mmu_base_role_mask.word;
4942 if (new_role.as_u64 == context->mmu_role.as_u64)
4945 if (!is_paging(vcpu))
4946 nonpaging_init_context(vcpu, context);
4947 else if (is_long_mode(vcpu))
4948 paging64_init_context(vcpu, context);
4949 else if (is_pae(vcpu))
4950 paging32E_init_context(vcpu, context);
4952 paging32_init_context(vcpu, context);
4954 context->mmu_role.as_u64 = new_role.as_u64;
4955 reset_shadow_zero_bits_mask(vcpu, context);
4957 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4959 static union kvm_mmu_role
4960 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4963 union kvm_mmu_role role = {0};
4965 /* SMM flag is inherited from root_mmu */
4966 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
4968 role.base.level = PT64_ROOT_4LEVEL;
4969 role.base.gpte_is_8_bytes = true;
4970 role.base.direct = false;
4971 role.base.ad_disabled = !accessed_dirty;
4972 role.base.guest_mode = true;
4973 role.base.access = ACC_ALL;
4976 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
4977 * SMAP variation to denote shadow EPT entries.
4979 role.base.cr0_wp = true;
4980 role.base.smap_andnot_wp = true;
4982 role.ext = kvm_calc_mmu_role_ext(vcpu);
4983 role.ext.execonly = execonly;
4988 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4989 bool accessed_dirty, gpa_t new_eptp)
4991 struct kvm_mmu *context = vcpu->arch.mmu;
4992 union kvm_mmu_role new_role =
4993 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4996 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
4998 new_role.base.word &= mmu_base_role_mask.word;
4999 if (new_role.as_u64 == context->mmu_role.as_u64)
5002 context->shadow_root_level = PT64_ROOT_4LEVEL;
5005 context->ept_ad = accessed_dirty;
5006 context->page_fault = ept_page_fault;
5007 context->gva_to_gpa = ept_gva_to_gpa;
5008 context->sync_page = ept_sync_page;
5009 context->invlpg = ept_invlpg;
5010 context->update_pte = ept_update_pte;
5011 context->root_level = PT64_ROOT_4LEVEL;
5012 context->direct_map = false;
5013 context->mmu_role.as_u64 = new_role.as_u64;
5015 update_permission_bitmask(vcpu, context, true);
5016 update_pkru_bitmask(vcpu, context, true);
5017 update_last_nonleaf_level(vcpu, context);
5018 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5019 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5021 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5023 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5025 struct kvm_mmu *context = vcpu->arch.mmu;
5027 kvm_init_shadow_mmu(vcpu);
5028 context->set_cr3 = kvm_x86_ops->set_cr3;
5029 context->get_cr3 = get_cr3;
5030 context->get_pdptr = kvm_pdptr_read;
5031 context->inject_page_fault = kvm_inject_page_fault;
5034 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5036 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5037 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5039 new_role.base.word &= mmu_base_role_mask.word;
5040 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5043 g_context->mmu_role.as_u64 = new_role.as_u64;
5044 g_context->get_cr3 = get_cr3;
5045 g_context->get_pdptr = kvm_pdptr_read;
5046 g_context->inject_page_fault = kvm_inject_page_fault;
5049 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5050 * L1's nested page tables (e.g. EPT12). The nested translation
5051 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5052 * L2's page tables as the first level of translation and L1's
5053 * nested page tables as the second level of translation. Basically
5054 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5056 if (!is_paging(vcpu)) {
5057 g_context->nx = false;
5058 g_context->root_level = 0;
5059 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5060 } else if (is_long_mode(vcpu)) {
5061 g_context->nx = is_nx(vcpu);
5062 g_context->root_level = is_la57_mode(vcpu) ?
5063 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5064 reset_rsvds_bits_mask(vcpu, g_context);
5065 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5066 } else if (is_pae(vcpu)) {
5067 g_context->nx = is_nx(vcpu);
5068 g_context->root_level = PT32E_ROOT_LEVEL;
5069 reset_rsvds_bits_mask(vcpu, g_context);
5070 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5072 g_context->nx = false;
5073 g_context->root_level = PT32_ROOT_LEVEL;
5074 reset_rsvds_bits_mask(vcpu, g_context);
5075 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5078 update_permission_bitmask(vcpu, g_context, false);
5079 update_pkru_bitmask(vcpu, g_context, false);
5080 update_last_nonleaf_level(vcpu, g_context);
5083 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5088 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5090 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5091 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5094 if (mmu_is_nested(vcpu))
5095 init_kvm_nested_mmu(vcpu);
5096 else if (tdp_enabled)
5097 init_kvm_tdp_mmu(vcpu);
5099 init_kvm_softmmu(vcpu);
5101 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5103 static union kvm_mmu_page_role
5104 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5106 union kvm_mmu_role role;
5109 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5111 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5116 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5118 kvm_mmu_unload(vcpu);
5119 kvm_init_mmu(vcpu, true);
5121 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5123 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5127 r = mmu_topup_memory_caches(vcpu);
5130 r = mmu_alloc_roots(vcpu);
5131 kvm_mmu_sync_roots(vcpu);
5134 kvm_mmu_load_cr3(vcpu);
5135 kvm_x86_ops->tlb_flush(vcpu, true);
5139 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5141 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5143 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5144 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5145 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5146 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5148 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5150 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5151 struct kvm_mmu_page *sp, u64 *spte,
5154 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5155 ++vcpu->kvm->stat.mmu_pde_zapped;
5159 ++vcpu->kvm->stat.mmu_pte_updated;
5160 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5163 static bool need_remote_flush(u64 old, u64 new)
5165 if (!is_shadow_present_pte(old))
5167 if (!is_shadow_present_pte(new))
5169 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5171 old ^= shadow_nx_mask;
5172 new ^= shadow_nx_mask;
5173 return (old & ~new & PT64_PERM_MASK) != 0;
5176 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5183 * Assume that the pte write on a page table of the same type
5184 * as the current vcpu paging mode since we update the sptes only
5185 * when they have the same mode.
5187 if (is_pae(vcpu) && *bytes == 4) {
5188 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5193 if (*bytes == 4 || *bytes == 8) {
5194 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5203 * If we're seeing too many writes to a page, it may no longer be a page table,
5204 * or we may be forking, in which case it is better to unmap the page.
5206 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5209 * Skip write-flooding detected for the sp whose level is 1, because
5210 * it can become unsync, then the guest page is not write-protected.
5212 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5215 atomic_inc(&sp->write_flooding_count);
5216 return atomic_read(&sp->write_flooding_count) >= 3;
5220 * Misaligned accesses are too much trouble to fix up; also, they usually
5221 * indicate a page is not used as a page table.
5223 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5226 unsigned offset, pte_size, misaligned;
5228 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5229 gpa, bytes, sp->role.word);
5231 offset = offset_in_page(gpa);
5232 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5235 * Sometimes, the OS only writes the last one bytes to update status
5236 * bits, for example, in linux, andb instruction is used in clear_bit().
5238 if (!(offset & (pte_size - 1)) && bytes == 1)
5241 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5242 misaligned |= bytes < 4;
5247 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5249 unsigned page_offset, quadrant;
5253 page_offset = offset_in_page(gpa);
5254 level = sp->role.level;
5256 if (!sp->role.gpte_is_8_bytes) {
5257 page_offset <<= 1; /* 32->64 */
5259 * A 32-bit pde maps 4MB while the shadow pdes map
5260 * only 2MB. So we need to double the offset again
5261 * and zap two pdes instead of one.
5263 if (level == PT32_ROOT_LEVEL) {
5264 page_offset &= ~7; /* kill rounding error */
5268 quadrant = page_offset >> PAGE_SHIFT;
5269 page_offset &= ~PAGE_MASK;
5270 if (quadrant != sp->role.quadrant)
5274 spte = &sp->spt[page_offset / sizeof(*spte)];
5278 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5279 const u8 *new, int bytes,
5280 struct kvm_page_track_notifier_node *node)
5282 gfn_t gfn = gpa >> PAGE_SHIFT;
5283 struct kvm_mmu_page *sp;
5284 LIST_HEAD(invalid_list);
5285 u64 entry, gentry, *spte;
5287 bool remote_flush, local_flush;
5290 * If we don't have indirect shadow pages, it means no page is
5291 * write-protected, so we can exit simply.
5293 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5296 remote_flush = local_flush = false;
5298 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5301 * No need to care whether allocation memory is successful
5302 * or not since pte prefetch is skiped if it does not have
5303 * enough objects in the cache.
5305 mmu_topup_memory_caches(vcpu);
5307 spin_lock(&vcpu->kvm->mmu_lock);
5309 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5311 ++vcpu->kvm->stat.mmu_pte_write;
5312 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5314 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5315 if (detect_write_misaligned(sp, gpa, bytes) ||
5316 detect_write_flooding(sp)) {
5317 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5318 ++vcpu->kvm->stat.mmu_flooded;
5322 spte = get_written_sptes(sp, gpa, &npte);
5328 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5331 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5333 !((sp->role.word ^ base_role)
5334 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5335 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5336 if (need_remote_flush(entry, *spte))
5337 remote_flush = true;
5341 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5342 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5343 spin_unlock(&vcpu->kvm->mmu_lock);
5346 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5351 if (vcpu->arch.mmu->direct_map)
5354 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5356 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5360 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5362 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5364 LIST_HEAD(invalid_list);
5366 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5369 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5370 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5373 ++vcpu->kvm->stat.mmu_recycled;
5375 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5377 if (!kvm_mmu_available_pages(vcpu->kvm))
5382 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5383 void *insn, int insn_len)
5385 int r, emulation_type = 0;
5386 enum emulation_result er;
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 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
5458 case EMULATE_USER_EXIT:
5459 ++vcpu->stat.mmio_exits;
5467 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5469 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5471 struct kvm_mmu *mmu = vcpu->arch.mmu;
5474 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5475 if (is_noncanonical_address(gva, vcpu))
5478 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5481 * INVLPG is required to invalidate any global mappings for the VA,
5482 * irrespective of PCID. Since it would take us roughly similar amount
5483 * of work to determine whether any of the prev_root mappings of the VA
5484 * is marked global, or to just sync it blindly, so we might as well
5485 * just always sync it.
5487 * Mappings not reachable via the current cr3 or the prev_roots will be
5488 * synced when switching to that cr3, so nothing needs to be done here
5491 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5492 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5493 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5495 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5496 ++vcpu->stat.invlpg;
5498 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5500 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5502 struct kvm_mmu *mmu = vcpu->arch.mmu;
5503 bool tlb_flush = false;
5506 if (pcid == kvm_get_active_pcid(vcpu)) {
5507 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5511 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5512 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5513 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5514 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5520 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5522 ++vcpu->stat.invlpg;
5525 * Mappings not reachable via the current cr3 or the prev_roots will be
5526 * synced when switching to that cr3, so nothing needs to be done here
5530 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5532 void kvm_enable_tdp(void)
5536 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5538 void kvm_disable_tdp(void)
5540 tdp_enabled = false;
5542 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5545 /* The return value indicates if tlb flush on all vcpus is needed. */
5546 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5548 /* The caller should hold mmu-lock before calling this function. */
5549 static __always_inline bool
5550 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5551 slot_level_handler fn, int start_level, int end_level,
5552 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5554 struct slot_rmap_walk_iterator iterator;
5557 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5558 end_gfn, &iterator) {
5560 flush |= fn(kvm, iterator.rmap);
5562 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5563 if (flush && lock_flush_tlb) {
5564 kvm_flush_remote_tlbs_with_address(kvm,
5566 iterator.gfn - start_gfn + 1);
5569 cond_resched_lock(&kvm->mmu_lock);
5573 if (flush && lock_flush_tlb) {
5574 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5575 end_gfn - start_gfn + 1);
5582 static __always_inline bool
5583 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5584 slot_level_handler fn, int start_level, int end_level,
5585 bool lock_flush_tlb)
5587 return slot_handle_level_range(kvm, memslot, fn, start_level,
5588 end_level, memslot->base_gfn,
5589 memslot->base_gfn + memslot->npages - 1,
5593 static __always_inline bool
5594 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5595 slot_level_handler fn, bool lock_flush_tlb)
5597 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5598 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5601 static __always_inline bool
5602 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5603 slot_level_handler fn, bool lock_flush_tlb)
5605 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5606 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5609 static __always_inline bool
5610 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5611 slot_level_handler fn, bool lock_flush_tlb)
5613 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5614 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5617 static void free_mmu_pages(struct kvm_mmu *mmu)
5619 free_page((unsigned long)mmu->pae_root);
5620 free_page((unsigned long)mmu->lm_root);
5623 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5629 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5630 * while the PDP table is a per-vCPU construct that's allocated at MMU
5631 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5632 * x86_64. Therefore we need to allocate the PDP table in the first
5633 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5634 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5635 * skip allocating the PDP table.
5637 if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5640 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5644 mmu->pae_root = page_address(page);
5645 for (i = 0; i < 4; ++i)
5646 mmu->pae_root[i] = INVALID_PAGE;
5651 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5656 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5657 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5659 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5660 vcpu->arch.root_mmu.root_cr3 = 0;
5661 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5662 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5663 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5665 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5666 vcpu->arch.guest_mmu.root_cr3 = 0;
5667 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5668 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5669 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5671 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5673 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5677 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5679 goto fail_allocate_root;
5683 free_mmu_pages(&vcpu->arch.guest_mmu);
5688 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5690 struct kvm_mmu_page *sp, *node;
5691 LIST_HEAD(invalid_list);
5695 list_for_each_entry_safe_reverse(sp, node,
5696 &kvm->arch.active_mmu_pages, link) {
5698 * No obsolete valid page exists before a newly created page
5699 * since active_mmu_pages is a FIFO list.
5701 if (!is_obsolete_sp(kvm, sp))
5705 * Do not repeatedly zap a root page to avoid unnecessary
5706 * KVM_REQ_MMU_RELOAD, otherwise we may not be able to
5709 * call vcpu_enter_guest():
5710 * 1): handle KVM_REQ_MMU_RELOAD
5711 * and require mmu-lock to
5714 * 1): zap root page and
5715 * send KVM_REQ_MMU_RELOAD
5717 * 2): if (cond_resched_lock(mmu-lock))
5719 * 2): hold mmu-lock and load mmu
5721 * 3): see KVM_REQ_MMU_RELOAD bit
5722 * on vcpu->requests is set
5723 * then return 1 to call
5724 * vcpu_enter_guest() again.
5727 * Since we are reversely walking the list and the invalid
5728 * list will be moved to the head, skip the invalid page
5729 * can help us to avoid the infinity list walking.
5731 if (sp->role.invalid)
5734 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5735 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5736 cond_resched_lock(&kvm->mmu_lock);
5740 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
5744 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5748 * Fast invalidate all shadow pages and use lock-break technique
5749 * to zap obsolete pages.
5751 * It's required when memslot is being deleted or VM is being
5752 * destroyed, in these cases, we should ensure that KVM MMU does
5753 * not use any resource of the being-deleted slot or all slots
5754 * after calling the function.
5756 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5758 spin_lock(&kvm->mmu_lock);
5759 kvm->arch.mmu_valid_gen++;
5761 kvm_zap_obsolete_pages(kvm);
5762 spin_unlock(&kvm->mmu_lock);
5765 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5766 struct kvm_memory_slot *slot,
5767 struct kvm_page_track_notifier_node *node)
5769 kvm_mmu_zap_all_fast(kvm);
5772 void kvm_mmu_init_vm(struct kvm *kvm)
5774 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5776 node->track_write = kvm_mmu_pte_write;
5777 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5778 kvm_page_track_register_notifier(kvm, node);
5781 void kvm_mmu_uninit_vm(struct kvm *kvm)
5783 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5785 kvm_page_track_unregister_notifier(kvm, node);
5788 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5790 struct kvm_memslots *slots;
5791 struct kvm_memory_slot *memslot;
5794 spin_lock(&kvm->mmu_lock);
5795 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5796 slots = __kvm_memslots(kvm, i);
5797 kvm_for_each_memslot(memslot, slots) {
5800 start = max(gfn_start, memslot->base_gfn);
5801 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5805 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5806 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5807 start, end - 1, true);
5811 spin_unlock(&kvm->mmu_lock);
5814 static bool slot_rmap_write_protect(struct kvm *kvm,
5815 struct kvm_rmap_head *rmap_head)
5817 return __rmap_write_protect(kvm, rmap_head, false);
5820 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5821 struct kvm_memory_slot *memslot)
5825 spin_lock(&kvm->mmu_lock);
5826 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5828 spin_unlock(&kvm->mmu_lock);
5831 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5832 * which do tlb flush out of mmu-lock should be serialized by
5833 * kvm->slots_lock otherwise tlb flush would be missed.
5835 lockdep_assert_held(&kvm->slots_lock);
5838 * We can flush all the TLBs out of the mmu lock without TLB
5839 * corruption since we just change the spte from writable to
5840 * readonly so that we only need to care the case of changing
5841 * spte from present to present (changing the spte from present
5842 * to nonpresent will flush all the TLBs immediately), in other
5843 * words, the only case we care is mmu_spte_update() where we
5844 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5845 * instead of PT_WRITABLE_MASK, that means it does not depend
5846 * on PT_WRITABLE_MASK anymore.
5849 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5853 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5854 struct kvm_rmap_head *rmap_head)
5857 struct rmap_iterator iter;
5858 int need_tlb_flush = 0;
5860 struct kvm_mmu_page *sp;
5863 for_each_rmap_spte(rmap_head, &iter, sptep) {
5864 sp = page_header(__pa(sptep));
5865 pfn = spte_to_pfn(*sptep);
5868 * We cannot do huge page mapping for indirect shadow pages,
5869 * which are found on the last rmap (level = 1) when not using
5870 * tdp; such shadow pages are synced with the page table in
5871 * the guest, and the guest page table is using 4K page size
5872 * mapping if the indirect sp has level = 1.
5874 if (sp->role.direct &&
5875 !kvm_is_reserved_pfn(pfn) &&
5876 PageTransCompoundMap(pfn_to_page(pfn))) {
5877 pte_list_remove(rmap_head, sptep);
5879 if (kvm_available_flush_tlb_with_range())
5880 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5881 KVM_PAGES_PER_HPAGE(sp->role.level));
5889 return need_tlb_flush;
5892 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5893 const struct kvm_memory_slot *memslot)
5895 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5896 spin_lock(&kvm->mmu_lock);
5897 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5898 kvm_mmu_zap_collapsible_spte, true);
5899 spin_unlock(&kvm->mmu_lock);
5902 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5903 struct kvm_memory_slot *memslot)
5907 spin_lock(&kvm->mmu_lock);
5908 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5909 spin_unlock(&kvm->mmu_lock);
5911 lockdep_assert_held(&kvm->slots_lock);
5914 * It's also safe to flush TLBs out of mmu lock here as currently this
5915 * function is only used for dirty logging, in which case flushing TLB
5916 * out of mmu lock also guarantees no dirty pages will be lost in
5920 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5923 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5925 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5926 struct kvm_memory_slot *memslot)
5930 spin_lock(&kvm->mmu_lock);
5931 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5933 spin_unlock(&kvm->mmu_lock);
5935 /* see kvm_mmu_slot_remove_write_access */
5936 lockdep_assert_held(&kvm->slots_lock);
5939 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5942 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5944 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5945 struct kvm_memory_slot *memslot)
5949 spin_lock(&kvm->mmu_lock);
5950 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5951 spin_unlock(&kvm->mmu_lock);
5953 lockdep_assert_held(&kvm->slots_lock);
5955 /* see kvm_mmu_slot_leaf_clear_dirty */
5957 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5960 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5962 static void __kvm_mmu_zap_all(struct kvm *kvm, bool mmio_only)
5964 struct kvm_mmu_page *sp, *node;
5965 LIST_HEAD(invalid_list);
5968 spin_lock(&kvm->mmu_lock);
5970 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
5971 if (mmio_only && !sp->mmio_cached)
5973 if (sp->role.invalid && sp->root_count)
5975 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign)) {
5976 WARN_ON_ONCE(mmio_only);
5979 if (cond_resched_lock(&kvm->mmu_lock))
5983 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5984 spin_unlock(&kvm->mmu_lock);
5987 void kvm_mmu_zap_all(struct kvm *kvm)
5989 return __kvm_mmu_zap_all(kvm, false);
5992 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5994 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
5996 gen &= MMIO_SPTE_GEN_MASK;
5999 * Generation numbers are incremented in multiples of the number of
6000 * address spaces in order to provide unique generations across all
6001 * address spaces. Strip what is effectively the address space
6002 * modifier prior to checking for a wrap of the MMIO generation so
6003 * that a wrap in any address space is detected.
6005 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6008 * The very rare case: if the MMIO generation number has wrapped,
6009 * zap all shadow pages.
6011 if (unlikely(gen == 0)) {
6012 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6013 __kvm_mmu_zap_all(kvm, true);
6017 static unsigned long
6018 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6021 int nr_to_scan = sc->nr_to_scan;
6022 unsigned long freed = 0;
6024 mutex_lock(&kvm_lock);
6026 list_for_each_entry(kvm, &vm_list, vm_list) {
6028 LIST_HEAD(invalid_list);
6031 * Never scan more than sc->nr_to_scan VM instances.
6032 * Will not hit this condition practically since we do not try
6033 * to shrink more than one VM and it is very unlikely to see
6034 * !n_used_mmu_pages so many times.
6039 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6040 * here. We may skip a VM instance errorneosly, but we do not
6041 * want to shrink a VM that only started to populate its MMU
6044 if (!kvm->arch.n_used_mmu_pages)
6047 idx = srcu_read_lock(&kvm->srcu);
6048 spin_lock(&kvm->mmu_lock);
6050 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6052 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6054 spin_unlock(&kvm->mmu_lock);
6055 srcu_read_unlock(&kvm->srcu, idx);
6058 * unfair on small ones
6059 * per-vm shrinkers cry out
6060 * sadness comes quickly
6062 list_move_tail(&kvm->vm_list, &vm_list);
6066 mutex_unlock(&kvm_lock);
6070 static unsigned long
6071 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6073 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6076 static struct shrinker mmu_shrinker = {
6077 .count_objects = mmu_shrink_count,
6078 .scan_objects = mmu_shrink_scan,
6079 .seeks = DEFAULT_SEEKS * 10,
6082 static void mmu_destroy_caches(void)
6084 kmem_cache_destroy(pte_list_desc_cache);
6085 kmem_cache_destroy(mmu_page_header_cache);
6088 static void kvm_set_mmio_spte_mask(void)
6093 * Set the reserved bits and the present bit of an paging-structure
6094 * entry to generate page fault with PFER.RSV = 1.
6098 * Mask the uppermost physical address bit, which would be reserved as
6099 * long as the supported physical address width is less than 52.
6103 /* Set the present bit. */
6107 * If reserved bit is not supported, clear the present bit to disable
6110 if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
6113 kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
6116 int kvm_mmu_module_init(void)
6121 * MMU roles use union aliasing which is, generally speaking, an
6122 * undefined behavior. However, we supposedly know how compilers behave
6123 * and the current status quo is unlikely to change. Guardians below are
6124 * supposed to let us know if the assumption becomes false.
6126 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6127 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6128 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6130 kvm_mmu_reset_all_pte_masks();
6132 kvm_set_mmio_spte_mask();
6134 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6135 sizeof(struct pte_list_desc),
6136 0, SLAB_ACCOUNT, NULL);
6137 if (!pte_list_desc_cache)
6140 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6141 sizeof(struct kvm_mmu_page),
6142 0, SLAB_ACCOUNT, NULL);
6143 if (!mmu_page_header_cache)
6146 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6149 ret = register_shrinker(&mmu_shrinker);
6156 mmu_destroy_caches();
6161 * Calculate mmu pages needed for kvm.
6163 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6165 unsigned long nr_mmu_pages;
6166 unsigned long nr_pages = 0;
6167 struct kvm_memslots *slots;
6168 struct kvm_memory_slot *memslot;
6171 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6172 slots = __kvm_memslots(kvm, i);
6174 kvm_for_each_memslot(memslot, slots)
6175 nr_pages += memslot->npages;
6178 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6179 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6181 return nr_mmu_pages;
6184 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6186 kvm_mmu_unload(vcpu);
6187 free_mmu_pages(&vcpu->arch.root_mmu);
6188 free_mmu_pages(&vcpu->arch.guest_mmu);
6189 mmu_free_memory_caches(vcpu);
6192 void kvm_mmu_module_exit(void)
6194 mmu_destroy_caches();
6195 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6196 unregister_shrinker(&mmu_shrinker);
6197 mmu_audit_disable();