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);
2100 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2101 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2105 static void mark_unsync(u64 *spte);
2106 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2109 struct rmap_iterator iter;
2111 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2116 static void mark_unsync(u64 *spte)
2118 struct kvm_mmu_page *sp;
2121 sp = page_header(__pa(spte));
2122 index = spte - sp->spt;
2123 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2125 if (sp->unsync_children++)
2127 kvm_mmu_mark_parents_unsync(sp);
2130 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2131 struct kvm_mmu_page *sp)
2136 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2140 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2141 struct kvm_mmu_page *sp, u64 *spte,
2147 #define KVM_PAGE_ARRAY_NR 16
2149 struct kvm_mmu_pages {
2150 struct mmu_page_and_offset {
2151 struct kvm_mmu_page *sp;
2153 } page[KVM_PAGE_ARRAY_NR];
2157 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2163 for (i=0; i < pvec->nr; i++)
2164 if (pvec->page[i].sp == sp)
2167 pvec->page[pvec->nr].sp = sp;
2168 pvec->page[pvec->nr].idx = idx;
2170 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2173 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2175 --sp->unsync_children;
2176 WARN_ON((int)sp->unsync_children < 0);
2177 __clear_bit(idx, sp->unsync_child_bitmap);
2180 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2181 struct kvm_mmu_pages *pvec)
2183 int i, ret, nr_unsync_leaf = 0;
2185 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2186 struct kvm_mmu_page *child;
2187 u64 ent = sp->spt[i];
2189 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2190 clear_unsync_child_bit(sp, i);
2194 child = page_header(ent & PT64_BASE_ADDR_MASK);
2196 if (child->unsync_children) {
2197 if (mmu_pages_add(pvec, child, i))
2200 ret = __mmu_unsync_walk(child, pvec);
2202 clear_unsync_child_bit(sp, i);
2204 } else if (ret > 0) {
2205 nr_unsync_leaf += ret;
2208 } else if (child->unsync) {
2210 if (mmu_pages_add(pvec, child, i))
2213 clear_unsync_child_bit(sp, i);
2216 return nr_unsync_leaf;
2219 #define INVALID_INDEX (-1)
2221 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2222 struct kvm_mmu_pages *pvec)
2225 if (!sp->unsync_children)
2228 mmu_pages_add(pvec, sp, INVALID_INDEX);
2229 return __mmu_unsync_walk(sp, pvec);
2232 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2234 WARN_ON(!sp->unsync);
2235 trace_kvm_mmu_sync_page(sp);
2237 --kvm->stat.mmu_unsync;
2240 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2241 struct list_head *invalid_list);
2242 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2243 struct list_head *invalid_list);
2246 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2247 hlist_for_each_entry(_sp, \
2248 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2249 if ((_sp)->role.invalid) { \
2252 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2253 for_each_valid_sp(_kvm, _sp, _gfn) \
2254 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2256 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2258 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2261 /* @sp->gfn should be write-protected at the call site */
2262 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2263 struct list_head *invalid_list)
2265 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2266 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2267 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2274 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2275 struct list_head *invalid_list,
2278 if (!remote_flush && list_empty(invalid_list))
2281 if (!list_empty(invalid_list))
2282 kvm_mmu_commit_zap_page(kvm, invalid_list);
2284 kvm_flush_remote_tlbs(kvm);
2288 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2289 struct list_head *invalid_list,
2290 bool remote_flush, bool local_flush)
2292 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2296 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2299 #ifdef CONFIG_KVM_MMU_AUDIT
2300 #include "mmu_audit.c"
2302 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2303 static void mmu_audit_disable(void) { }
2306 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2307 struct list_head *invalid_list)
2309 kvm_unlink_unsync_page(vcpu->kvm, sp);
2310 return __kvm_sync_page(vcpu, sp, invalid_list);
2313 /* @gfn should be write-protected at the call site */
2314 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2315 struct list_head *invalid_list)
2317 struct kvm_mmu_page *s;
2320 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2324 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2325 ret |= kvm_sync_page(vcpu, s, invalid_list);
2331 struct mmu_page_path {
2332 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2333 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2336 #define for_each_sp(pvec, sp, parents, i) \
2337 for (i = mmu_pages_first(&pvec, &parents); \
2338 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2339 i = mmu_pages_next(&pvec, &parents, i))
2341 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2342 struct mmu_page_path *parents,
2347 for (n = i+1; n < pvec->nr; n++) {
2348 struct kvm_mmu_page *sp = pvec->page[n].sp;
2349 unsigned idx = pvec->page[n].idx;
2350 int level = sp->role.level;
2352 parents->idx[level-1] = idx;
2353 if (level == PT_PAGE_TABLE_LEVEL)
2356 parents->parent[level-2] = sp;
2362 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2363 struct mmu_page_path *parents)
2365 struct kvm_mmu_page *sp;
2371 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2373 sp = pvec->page[0].sp;
2374 level = sp->role.level;
2375 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2377 parents->parent[level-2] = sp;
2379 /* Also set up a sentinel. Further entries in pvec are all
2380 * children of sp, so this element is never overwritten.
2382 parents->parent[level-1] = NULL;
2383 return mmu_pages_next(pvec, parents, 0);
2386 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2388 struct kvm_mmu_page *sp;
2389 unsigned int level = 0;
2392 unsigned int idx = parents->idx[level];
2393 sp = parents->parent[level];
2397 WARN_ON(idx == INVALID_INDEX);
2398 clear_unsync_child_bit(sp, idx);
2400 } while (!sp->unsync_children);
2403 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2404 struct kvm_mmu_page *parent)
2407 struct kvm_mmu_page *sp;
2408 struct mmu_page_path parents;
2409 struct kvm_mmu_pages pages;
2410 LIST_HEAD(invalid_list);
2413 while (mmu_unsync_walk(parent, &pages)) {
2414 bool protected = false;
2416 for_each_sp(pages, sp, parents, i)
2417 protected |= rmap_write_protect(vcpu, sp->gfn);
2420 kvm_flush_remote_tlbs(vcpu->kvm);
2424 for_each_sp(pages, sp, parents, i) {
2425 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2426 mmu_pages_clear_parents(&parents);
2428 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2429 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2430 cond_resched_lock(&vcpu->kvm->mmu_lock);
2435 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2438 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2440 atomic_set(&sp->write_flooding_count, 0);
2443 static void clear_sp_write_flooding_count(u64 *spte)
2445 struct kvm_mmu_page *sp = page_header(__pa(spte));
2447 __clear_sp_write_flooding_count(sp);
2450 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2457 union kvm_mmu_page_role role;
2459 struct kvm_mmu_page *sp;
2460 bool need_sync = false;
2463 LIST_HEAD(invalid_list);
2465 role = vcpu->arch.mmu->mmu_role.base;
2467 role.direct = direct;
2469 role.gpte_is_8_bytes = true;
2470 role.access = access;
2471 if (!vcpu->arch.mmu->direct_map
2472 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2473 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2474 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2475 role.quadrant = quadrant;
2477 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2478 if (sp->gfn != gfn) {
2483 if (!need_sync && sp->unsync)
2486 if (sp->role.word != role.word)
2490 /* The page is good, but __kvm_sync_page might still end
2491 * up zapping it. If so, break in order to rebuild it.
2493 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2496 WARN_ON(!list_empty(&invalid_list));
2497 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2500 if (sp->unsync_children)
2501 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2503 __clear_sp_write_flooding_count(sp);
2504 trace_kvm_mmu_get_page(sp, false);
2508 ++vcpu->kvm->stat.mmu_cache_miss;
2510 sp = kvm_mmu_alloc_page(vcpu, direct);
2514 hlist_add_head(&sp->hash_link,
2515 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2518 * we should do write protection before syncing pages
2519 * otherwise the content of the synced shadow page may
2520 * be inconsistent with guest page table.
2522 account_shadowed(vcpu->kvm, sp);
2523 if (level == PT_PAGE_TABLE_LEVEL &&
2524 rmap_write_protect(vcpu, gfn))
2525 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2527 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2528 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2530 clear_page(sp->spt);
2531 trace_kvm_mmu_get_page(sp, true);
2533 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2535 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2536 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2540 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2541 struct kvm_vcpu *vcpu, hpa_t root,
2544 iterator->addr = addr;
2545 iterator->shadow_addr = root;
2546 iterator->level = vcpu->arch.mmu->shadow_root_level;
2548 if (iterator->level == PT64_ROOT_4LEVEL &&
2549 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2550 !vcpu->arch.mmu->direct_map)
2553 if (iterator->level == PT32E_ROOT_LEVEL) {
2555 * prev_root is currently only used for 64-bit hosts. So only
2556 * the active root_hpa is valid here.
2558 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2560 iterator->shadow_addr
2561 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2562 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2564 if (!iterator->shadow_addr)
2565 iterator->level = 0;
2569 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2570 struct kvm_vcpu *vcpu, u64 addr)
2572 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2576 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2578 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2581 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2582 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2586 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2589 if (is_last_spte(spte, iterator->level)) {
2590 iterator->level = 0;
2594 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2598 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2600 __shadow_walk_next(iterator, *iterator->sptep);
2603 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2604 struct kvm_mmu_page *sp)
2608 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2610 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2611 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2613 if (sp_ad_disabled(sp))
2614 spte |= shadow_acc_track_value;
2616 spte |= shadow_accessed_mask;
2618 mmu_spte_set(sptep, spte);
2620 mmu_page_add_parent_pte(vcpu, sp, sptep);
2622 if (sp->unsync_children || sp->unsync)
2626 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2627 unsigned direct_access)
2629 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2630 struct kvm_mmu_page *child;
2633 * For the direct sp, if the guest pte's dirty bit
2634 * changed form clean to dirty, it will corrupt the
2635 * sp's access: allow writable in the read-only sp,
2636 * so we should update the spte at this point to get
2637 * a new sp with the correct access.
2639 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2640 if (child->role.access == direct_access)
2643 drop_parent_pte(child, sptep);
2644 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2648 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2652 struct kvm_mmu_page *child;
2655 if (is_shadow_present_pte(pte)) {
2656 if (is_last_spte(pte, sp->role.level)) {
2657 drop_spte(kvm, spte);
2658 if (is_large_pte(pte))
2661 child = page_header(pte & PT64_BASE_ADDR_MASK);
2662 drop_parent_pte(child, spte);
2667 if (is_mmio_spte(pte))
2668 mmu_spte_clear_no_track(spte);
2673 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2674 struct kvm_mmu_page *sp)
2678 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2679 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2682 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2685 struct rmap_iterator iter;
2687 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2688 drop_parent_pte(sp, sptep);
2691 static int mmu_zap_unsync_children(struct kvm *kvm,
2692 struct kvm_mmu_page *parent,
2693 struct list_head *invalid_list)
2696 struct mmu_page_path parents;
2697 struct kvm_mmu_pages pages;
2699 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2702 while (mmu_unsync_walk(parent, &pages)) {
2703 struct kvm_mmu_page *sp;
2705 for_each_sp(pages, sp, parents, i) {
2706 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2707 mmu_pages_clear_parents(&parents);
2715 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2716 struct kvm_mmu_page *sp,
2717 struct list_head *invalid_list,
2722 trace_kvm_mmu_prepare_zap_page(sp);
2723 ++kvm->stat.mmu_shadow_zapped;
2724 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2725 kvm_mmu_page_unlink_children(kvm, sp);
2726 kvm_mmu_unlink_parents(kvm, sp);
2728 /* Zapping children means active_mmu_pages has become unstable. */
2729 list_unstable = *nr_zapped;
2731 if (!sp->role.invalid && !sp->role.direct)
2732 unaccount_shadowed(kvm, sp);
2735 kvm_unlink_unsync_page(kvm, sp);
2736 if (!sp->root_count) {
2739 list_move(&sp->link, invalid_list);
2740 kvm_mod_used_mmu_pages(kvm, -1);
2742 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2744 if (!sp->role.invalid)
2745 kvm_reload_remote_mmus(kvm);
2748 sp->role.invalid = 1;
2749 return list_unstable;
2752 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2753 struct list_head *invalid_list)
2757 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2761 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2762 struct list_head *invalid_list)
2764 struct kvm_mmu_page *sp, *nsp;
2766 if (list_empty(invalid_list))
2770 * We need to make sure everyone sees our modifications to
2771 * the page tables and see changes to vcpu->mode here. The barrier
2772 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2773 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2775 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2776 * guest mode and/or lockless shadow page table walks.
2778 kvm_flush_remote_tlbs(kvm);
2780 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2781 WARN_ON(!sp->role.invalid || sp->root_count);
2782 kvm_mmu_free_page(sp);
2786 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2787 struct list_head *invalid_list)
2789 struct kvm_mmu_page *sp;
2791 if (list_empty(&kvm->arch.active_mmu_pages))
2794 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2795 struct kvm_mmu_page, link);
2796 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2800 * Changing the number of mmu pages allocated to the vm
2801 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2803 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2805 LIST_HEAD(invalid_list);
2807 spin_lock(&kvm->mmu_lock);
2809 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2810 /* Need to free some mmu pages to achieve the goal. */
2811 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2812 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2815 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2816 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2819 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2821 spin_unlock(&kvm->mmu_lock);
2824 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2826 struct kvm_mmu_page *sp;
2827 LIST_HEAD(invalid_list);
2830 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2832 spin_lock(&kvm->mmu_lock);
2833 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2834 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2837 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2839 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2840 spin_unlock(&kvm->mmu_lock);
2844 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2846 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2848 trace_kvm_mmu_unsync_page(sp);
2849 ++vcpu->kvm->stat.mmu_unsync;
2852 kvm_mmu_mark_parents_unsync(sp);
2855 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2858 struct kvm_mmu_page *sp;
2860 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2863 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2870 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2871 kvm_unsync_page(vcpu, sp);
2875 * We need to ensure that the marking of unsync pages is visible
2876 * before the SPTE is updated to allow writes because
2877 * kvm_mmu_sync_roots() checks the unsync flags without holding
2878 * the MMU lock and so can race with this. If the SPTE was updated
2879 * before the page had been marked as unsync-ed, something like the
2880 * following could happen:
2883 * ---------------------------------------------------------------------
2884 * 1.2 Host updates SPTE
2886 * 2.1 Guest writes a GPTE for GVA X.
2887 * (GPTE being in the guest page table shadowed
2888 * by the SP from CPU 1.)
2889 * This reads SPTE during the page table walk.
2890 * Since SPTE.W is read as 1, there is no
2893 * 2.2 Guest issues TLB flush.
2894 * That causes a VM Exit.
2896 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2897 * Since it is false, so it just returns.
2899 * 2.4 Guest accesses GVA X.
2900 * Since the mapping in the SP was not updated,
2901 * so the old mapping for GVA X incorrectly
2905 * (sp->unsync = true)
2907 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2908 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2909 * pairs with this write barrier.
2916 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2919 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2921 * Some reserved pages, such as those from NVDIMM
2922 * DAX devices, are not for MMIO, and can be mapped
2923 * with cached memory type for better performance.
2924 * However, the above check misconceives those pages
2925 * as MMIO, and results in KVM mapping them with UC
2926 * memory type, which would hurt the performance.
2927 * Therefore, we check the host memory type in addition
2928 * and only treat UC/UC-/WC pages as MMIO.
2930 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2932 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2933 pfn_to_hpa(pfn + 1) - 1,
2937 /* Bits which may be returned by set_spte() */
2938 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2939 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2941 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2942 unsigned pte_access, int level,
2943 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2944 bool can_unsync, bool host_writable)
2948 struct kvm_mmu_page *sp;
2950 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2953 sp = page_header(__pa(sptep));
2954 if (sp_ad_disabled(sp))
2955 spte |= shadow_acc_track_value;
2958 * For the EPT case, shadow_present_mask is 0 if hardware
2959 * supports exec-only page table entries. In that case,
2960 * ACC_USER_MASK and shadow_user_mask are used to represent
2961 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2963 spte |= shadow_present_mask;
2965 spte |= spte_shadow_accessed_mask(spte);
2967 if (pte_access & ACC_EXEC_MASK)
2968 spte |= shadow_x_mask;
2970 spte |= shadow_nx_mask;
2972 if (pte_access & ACC_USER_MASK)
2973 spte |= shadow_user_mask;
2975 if (level > PT_PAGE_TABLE_LEVEL)
2976 spte |= PT_PAGE_SIZE_MASK;
2978 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2979 kvm_is_mmio_pfn(pfn));
2982 spte |= SPTE_HOST_WRITEABLE;
2984 pte_access &= ~ACC_WRITE_MASK;
2986 if (!kvm_is_mmio_pfn(pfn))
2987 spte |= shadow_me_mask;
2989 spte |= (u64)pfn << PAGE_SHIFT;
2991 if (pte_access & ACC_WRITE_MASK) {
2994 * Other vcpu creates new sp in the window between
2995 * mapping_level() and acquiring mmu-lock. We can
2996 * allow guest to retry the access, the mapping can
2997 * be fixed if guest refault.
2999 if (level > PT_PAGE_TABLE_LEVEL &&
3000 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3003 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3006 * Optimization: for pte sync, if spte was writable the hash
3007 * lookup is unnecessary (and expensive). Write protection
3008 * is responsibility of mmu_get_page / kvm_sync_page.
3009 * Same reasoning can be applied to dirty page accounting.
3011 if (!can_unsync && is_writable_pte(*sptep))
3014 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3015 pgprintk("%s: found shadow page for %llx, marking ro\n",
3017 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3018 pte_access &= ~ACC_WRITE_MASK;
3019 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3023 if (pte_access & ACC_WRITE_MASK) {
3024 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3025 spte |= spte_shadow_dirty_mask(spte);
3029 spte = mark_spte_for_access_track(spte);
3032 if (mmu_spte_update(sptep, spte))
3033 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3038 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3039 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3040 bool speculative, bool host_writable)
3042 int was_rmapped = 0;
3045 int ret = RET_PF_RETRY;
3048 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3049 *sptep, write_fault, gfn);
3051 if (is_shadow_present_pte(*sptep)) {
3053 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3054 * the parent of the now unreachable PTE.
3056 if (level > PT_PAGE_TABLE_LEVEL &&
3057 !is_large_pte(*sptep)) {
3058 struct kvm_mmu_page *child;
3061 child = page_header(pte & PT64_BASE_ADDR_MASK);
3062 drop_parent_pte(child, sptep);
3064 } else if (pfn != spte_to_pfn(*sptep)) {
3065 pgprintk("hfn old %llx new %llx\n",
3066 spte_to_pfn(*sptep), pfn);
3067 drop_spte(vcpu->kvm, sptep);
3073 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3074 speculative, true, host_writable);
3075 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3077 ret = RET_PF_EMULATE;
3078 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3081 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3082 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3083 KVM_PAGES_PER_HPAGE(level));
3085 if (unlikely(is_mmio_spte(*sptep)))
3086 ret = RET_PF_EMULATE;
3088 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3089 trace_kvm_mmu_set_spte(level, gfn, sptep);
3090 if (!was_rmapped && is_large_pte(*sptep))
3091 ++vcpu->kvm->stat.lpages;
3093 if (is_shadow_present_pte(*sptep)) {
3095 rmap_count = rmap_add(vcpu, sptep, gfn);
3096 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3097 rmap_recycle(vcpu, sptep, gfn);
3104 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3107 struct kvm_memory_slot *slot;
3109 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3111 return KVM_PFN_ERR_FAULT;
3113 return gfn_to_pfn_memslot_atomic(slot, gfn);
3116 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3117 struct kvm_mmu_page *sp,
3118 u64 *start, u64 *end)
3120 struct page *pages[PTE_PREFETCH_NUM];
3121 struct kvm_memory_slot *slot;
3122 unsigned access = sp->role.access;
3126 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3127 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3131 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3135 for (i = 0; i < ret; i++, gfn++, start++) {
3136 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3137 page_to_pfn(pages[i]), true, true);
3144 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3145 struct kvm_mmu_page *sp, u64 *sptep)
3147 u64 *spte, *start = NULL;
3150 WARN_ON(!sp->role.direct);
3152 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3155 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3156 if (is_shadow_present_pte(*spte) || spte == sptep) {
3159 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3167 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3169 struct kvm_mmu_page *sp;
3171 sp = page_header(__pa(sptep));
3174 * Without accessed bits, there's no way to distinguish between
3175 * actually accessed translations and prefetched, so disable pte
3176 * prefetch if accessed bits aren't available.
3178 if (sp_ad_disabled(sp))
3181 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3184 __direct_pte_prefetch(vcpu, sp, sptep);
3187 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3188 int map_writable, int level, kvm_pfn_t pfn,
3191 struct kvm_shadow_walk_iterator it;
3192 struct kvm_mmu_page *sp;
3194 gfn_t gfn = gpa >> PAGE_SHIFT;
3195 gfn_t base_gfn = gfn;
3197 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3198 return RET_PF_RETRY;
3200 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3201 for_each_shadow_entry(vcpu, gpa, it) {
3202 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3203 if (it.level == level)
3206 drop_large_spte(vcpu, it.sptep);
3207 if (!is_shadow_present_pte(*it.sptep)) {
3208 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3209 it.level - 1, true, ACC_ALL);
3211 link_shadow_page(vcpu, it.sptep, sp);
3215 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3216 write, level, base_gfn, pfn, prefault,
3218 direct_pte_prefetch(vcpu, it.sptep);
3219 ++vcpu->stat.pf_fixed;
3223 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3225 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3228 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3231 * Do not cache the mmio info caused by writing the readonly gfn
3232 * into the spte otherwise read access on readonly gfn also can
3233 * caused mmio page fault and treat it as mmio access.
3235 if (pfn == KVM_PFN_ERR_RO_FAULT)
3236 return RET_PF_EMULATE;
3238 if (pfn == KVM_PFN_ERR_HWPOISON) {
3239 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3240 return RET_PF_RETRY;
3246 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3247 gfn_t gfn, kvm_pfn_t *pfnp,
3250 kvm_pfn_t pfn = *pfnp;
3251 int level = *levelp;
3254 * Check if it's a transparent hugepage. If this would be an
3255 * hugetlbfs page, level wouldn't be set to
3256 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3259 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3260 level == PT_PAGE_TABLE_LEVEL &&
3261 PageTransCompoundMap(pfn_to_page(pfn)) &&
3262 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3265 * mmu_notifier_retry was successful and we hold the
3266 * mmu_lock here, so the pmd can't become splitting
3267 * from under us, and in turn
3268 * __split_huge_page_refcount() can't run from under
3269 * us and we can safely transfer the refcount from
3270 * PG_tail to PG_head as we switch the pfn to tail to
3273 *levelp = level = PT_DIRECTORY_LEVEL;
3274 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3275 VM_BUG_ON((gfn & mask) != (pfn & mask));
3277 kvm_release_pfn_clean(pfn);
3285 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3286 kvm_pfn_t pfn, unsigned access, int *ret_val)
3288 /* The pfn is invalid, report the error! */
3289 if (unlikely(is_error_pfn(pfn))) {
3290 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3294 if (unlikely(is_noslot_pfn(pfn)))
3295 vcpu_cache_mmio_info(vcpu, gva, gfn,
3296 access & shadow_mmio_access_mask);
3301 static bool page_fault_can_be_fast(u32 error_code)
3304 * Do not fix the mmio spte with invalid generation number which
3305 * need to be updated by slow page fault path.
3307 if (unlikely(error_code & PFERR_RSVD_MASK))
3310 /* See if the page fault is due to an NX violation */
3311 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3312 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3316 * #PF can be fast if:
3317 * 1. The shadow page table entry is not present, which could mean that
3318 * the fault is potentially caused by access tracking (if enabled).
3319 * 2. The shadow page table entry is present and the fault
3320 * is caused by write-protect, that means we just need change the W
3321 * bit of the spte which can be done out of mmu-lock.
3323 * However, if access tracking is disabled we know that a non-present
3324 * page must be a genuine page fault where we have to create a new SPTE.
3325 * So, if access tracking is disabled, we return true only for write
3326 * accesses to a present page.
3329 return shadow_acc_track_mask != 0 ||
3330 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3331 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3335 * Returns true if the SPTE was fixed successfully. Otherwise,
3336 * someone else modified the SPTE from its original value.
3339 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3340 u64 *sptep, u64 old_spte, u64 new_spte)
3344 WARN_ON(!sp->role.direct);
3347 * Theoretically we could also set dirty bit (and flush TLB) here in
3348 * order to eliminate unnecessary PML logging. See comments in
3349 * set_spte. But fast_page_fault is very unlikely to happen with PML
3350 * enabled, so we do not do this. This might result in the same GPA
3351 * to be logged in PML buffer again when the write really happens, and
3352 * eventually to be called by mark_page_dirty twice. But it's also no
3353 * harm. This also avoids the TLB flush needed after setting dirty bit
3354 * so non-PML cases won't be impacted.
3356 * Compare with set_spte where instead shadow_dirty_mask is set.
3358 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3361 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3363 * The gfn of direct spte is stable since it is
3364 * calculated by sp->gfn.
3366 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3367 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3373 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3375 if (fault_err_code & PFERR_FETCH_MASK)
3376 return is_executable_pte(spte);
3378 if (fault_err_code & PFERR_WRITE_MASK)
3379 return is_writable_pte(spte);
3381 /* Fault was on Read access */
3382 return spte & PT_PRESENT_MASK;
3387 * - true: let the vcpu to access on the same address again.
3388 * - false: let the real page fault path to fix it.
3390 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3393 struct kvm_shadow_walk_iterator iterator;
3394 struct kvm_mmu_page *sp;
3395 bool fault_handled = false;
3397 uint retry_count = 0;
3399 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3402 if (!page_fault_can_be_fast(error_code))
3405 walk_shadow_page_lockless_begin(vcpu);
3410 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3411 if (!is_shadow_present_pte(spte) ||
3412 iterator.level < level)
3415 sp = page_header(__pa(iterator.sptep));
3416 if (!is_last_spte(spte, sp->role.level))
3420 * Check whether the memory access that caused the fault would
3421 * still cause it if it were to be performed right now. If not,
3422 * then this is a spurious fault caused by TLB lazily flushed,
3423 * or some other CPU has already fixed the PTE after the
3424 * current CPU took the fault.
3426 * Need not check the access of upper level table entries since
3427 * they are always ACC_ALL.
3429 if (is_access_allowed(error_code, spte)) {
3430 fault_handled = true;
3436 if (is_access_track_spte(spte))
3437 new_spte = restore_acc_track_spte(new_spte);
3440 * Currently, to simplify the code, write-protection can
3441 * be removed in the fast path only if the SPTE was
3442 * write-protected for dirty-logging or access tracking.
3444 if ((error_code & PFERR_WRITE_MASK) &&
3445 spte_can_locklessly_be_made_writable(spte))
3447 new_spte |= PT_WRITABLE_MASK;
3450 * Do not fix write-permission on the large spte. Since
3451 * we only dirty the first page into the dirty-bitmap in
3452 * fast_pf_fix_direct_spte(), other pages are missed
3453 * if its slot has dirty logging enabled.
3455 * Instead, we let the slow page fault path create a
3456 * normal spte to fix the access.
3458 * See the comments in kvm_arch_commit_memory_region().
3460 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3464 /* Verify that the fault can be handled in the fast path */
3465 if (new_spte == spte ||
3466 !is_access_allowed(error_code, new_spte))
3470 * Currently, fast page fault only works for direct mapping
3471 * since the gfn is not stable for indirect shadow page. See
3472 * Documentation/virt/kvm/locking.txt to get more detail.
3474 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3475 iterator.sptep, spte,
3480 if (++retry_count > 4) {
3481 printk_once(KERN_WARNING
3482 "kvm: Fast #PF retrying more than 4 times.\n");
3488 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3489 spte, fault_handled);
3490 walk_shadow_page_lockless_end(vcpu);
3492 return fault_handled;
3495 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3496 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3497 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3499 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3500 gfn_t gfn, bool prefault)
3504 bool force_pt_level = false;
3506 unsigned long mmu_seq;
3507 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3509 level = mapping_level(vcpu, gfn, &force_pt_level);
3510 if (likely(!force_pt_level)) {
3512 * This path builds a PAE pagetable - so we can map
3513 * 2mb pages at maximum. Therefore check if the level
3514 * is larger than that.
3516 if (level > PT_DIRECTORY_LEVEL)
3517 level = PT_DIRECTORY_LEVEL;
3519 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3522 if (fast_page_fault(vcpu, v, level, error_code))
3523 return RET_PF_RETRY;
3525 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3528 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3529 return RET_PF_RETRY;
3531 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3535 spin_lock(&vcpu->kvm->mmu_lock);
3536 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3538 if (make_mmu_pages_available(vcpu) < 0)
3540 if (likely(!force_pt_level))
3541 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3542 r = __direct_map(vcpu, v, write, map_writable, level, pfn, prefault);
3544 spin_unlock(&vcpu->kvm->mmu_lock);
3545 kvm_release_pfn_clean(pfn);
3549 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3550 struct list_head *invalid_list)
3552 struct kvm_mmu_page *sp;
3554 if (!VALID_PAGE(*root_hpa))
3557 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3559 if (!sp->root_count && sp->role.invalid)
3560 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3562 *root_hpa = INVALID_PAGE;
3565 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3566 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3567 ulong roots_to_free)
3570 LIST_HEAD(invalid_list);
3571 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3573 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3575 /* Before acquiring the MMU lock, see if we need to do any real work. */
3576 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3577 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3578 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3579 VALID_PAGE(mmu->prev_roots[i].hpa))
3582 if (i == KVM_MMU_NUM_PREV_ROOTS)
3586 spin_lock(&vcpu->kvm->mmu_lock);
3588 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3589 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3590 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3593 if (free_active_root) {
3594 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3595 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3596 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3599 for (i = 0; i < 4; ++i)
3600 if (mmu->pae_root[i] != 0)
3601 mmu_free_root_page(vcpu->kvm,
3604 mmu->root_hpa = INVALID_PAGE;
3609 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3610 spin_unlock(&vcpu->kvm->mmu_lock);
3612 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3614 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3618 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3619 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3626 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3628 struct kvm_mmu_page *sp;
3631 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3632 spin_lock(&vcpu->kvm->mmu_lock);
3633 if(make_mmu_pages_available(vcpu) < 0) {
3634 spin_unlock(&vcpu->kvm->mmu_lock);
3637 sp = kvm_mmu_get_page(vcpu, 0, 0,
3638 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3640 spin_unlock(&vcpu->kvm->mmu_lock);
3641 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3642 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3643 for (i = 0; i < 4; ++i) {
3644 hpa_t root = vcpu->arch.mmu->pae_root[i];
3646 MMU_WARN_ON(VALID_PAGE(root));
3647 spin_lock(&vcpu->kvm->mmu_lock);
3648 if (make_mmu_pages_available(vcpu) < 0) {
3649 spin_unlock(&vcpu->kvm->mmu_lock);
3652 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3653 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3654 root = __pa(sp->spt);
3656 spin_unlock(&vcpu->kvm->mmu_lock);
3657 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3659 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3662 vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3667 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3669 struct kvm_mmu_page *sp;
3671 gfn_t root_gfn, root_cr3;
3674 root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3675 root_gfn = root_cr3 >> PAGE_SHIFT;
3677 if (mmu_check_root(vcpu, root_gfn))
3681 * Do we shadow a long mode page table? If so we need to
3682 * write-protect the guests page table root.
3684 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3685 hpa_t root = vcpu->arch.mmu->root_hpa;
3687 MMU_WARN_ON(VALID_PAGE(root));
3689 spin_lock(&vcpu->kvm->mmu_lock);
3690 if (make_mmu_pages_available(vcpu) < 0) {
3691 spin_unlock(&vcpu->kvm->mmu_lock);
3694 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3695 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3696 root = __pa(sp->spt);
3698 spin_unlock(&vcpu->kvm->mmu_lock);
3699 vcpu->arch.mmu->root_hpa = root;
3704 * We shadow a 32 bit page table. This may be a legacy 2-level
3705 * or a PAE 3-level page table. In either case we need to be aware that
3706 * the shadow page table may be a PAE or a long mode page table.
3708 pm_mask = PT_PRESENT_MASK;
3709 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3710 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3712 for (i = 0; i < 4; ++i) {
3713 hpa_t root = vcpu->arch.mmu->pae_root[i];
3715 MMU_WARN_ON(VALID_PAGE(root));
3716 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3717 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3718 if (!(pdptr & PT_PRESENT_MASK)) {
3719 vcpu->arch.mmu->pae_root[i] = 0;
3722 root_gfn = pdptr >> PAGE_SHIFT;
3723 if (mmu_check_root(vcpu, root_gfn))
3726 spin_lock(&vcpu->kvm->mmu_lock);
3727 if (make_mmu_pages_available(vcpu) < 0) {
3728 spin_unlock(&vcpu->kvm->mmu_lock);
3731 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3733 root = __pa(sp->spt);
3735 spin_unlock(&vcpu->kvm->mmu_lock);
3737 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3739 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3742 * If we shadow a 32 bit page table with a long mode page
3743 * table we enter this path.
3745 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3746 if (vcpu->arch.mmu->lm_root == NULL) {
3748 * The additional page necessary for this is only
3749 * allocated on demand.
3754 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3755 if (lm_root == NULL)
3758 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3760 vcpu->arch.mmu->lm_root = lm_root;
3763 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3767 vcpu->arch.mmu->root_cr3 = root_cr3;
3772 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3774 if (vcpu->arch.mmu->direct_map)
3775 return mmu_alloc_direct_roots(vcpu);
3777 return mmu_alloc_shadow_roots(vcpu);
3780 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3783 struct kvm_mmu_page *sp;
3785 if (vcpu->arch.mmu->direct_map)
3788 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3791 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3793 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3794 hpa_t root = vcpu->arch.mmu->root_hpa;
3795 sp = page_header(root);
3798 * Even if another CPU was marking the SP as unsync-ed
3799 * simultaneously, any guest page table changes are not
3800 * guaranteed to be visible anyway until this VCPU issues a TLB
3801 * flush strictly after those changes are made. We only need to
3802 * ensure that the other CPU sets these flags before any actual
3803 * changes to the page tables are made. The comments in
3804 * mmu_need_write_protect() describe what could go wrong if this
3805 * requirement isn't satisfied.
3807 if (!smp_load_acquire(&sp->unsync) &&
3808 !smp_load_acquire(&sp->unsync_children))
3811 spin_lock(&vcpu->kvm->mmu_lock);
3812 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3814 mmu_sync_children(vcpu, sp);
3816 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3817 spin_unlock(&vcpu->kvm->mmu_lock);
3821 spin_lock(&vcpu->kvm->mmu_lock);
3822 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3824 for (i = 0; i < 4; ++i) {
3825 hpa_t root = vcpu->arch.mmu->pae_root[i];
3827 if (root && VALID_PAGE(root)) {
3828 root &= PT64_BASE_ADDR_MASK;
3829 sp = page_header(root);
3830 mmu_sync_children(vcpu, sp);
3834 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3835 spin_unlock(&vcpu->kvm->mmu_lock);
3837 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3839 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3840 u32 access, struct x86_exception *exception)
3843 exception->error_code = 0;
3847 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3849 struct x86_exception *exception)
3852 exception->error_code = 0;
3853 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3857 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3859 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3861 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3862 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3865 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3867 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3870 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3872 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3875 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3878 * A nested guest cannot use the MMIO cache if it is using nested
3879 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3881 if (mmu_is_nested(vcpu))
3885 return vcpu_match_mmio_gpa(vcpu, addr);
3887 return vcpu_match_mmio_gva(vcpu, addr);
3890 /* return true if reserved bit is detected on spte. */
3892 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3894 struct kvm_shadow_walk_iterator iterator;
3895 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3897 bool reserved = false;
3899 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3902 walk_shadow_page_lockless_begin(vcpu);
3904 for (shadow_walk_init(&iterator, vcpu, addr),
3905 leaf = root = iterator.level;
3906 shadow_walk_okay(&iterator);
3907 __shadow_walk_next(&iterator, spte)) {
3908 spte = mmu_spte_get_lockless(iterator.sptep);
3910 sptes[leaf - 1] = spte;
3913 if (!is_shadow_present_pte(spte))
3916 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3920 walk_shadow_page_lockless_end(vcpu);
3923 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3925 while (root > leaf) {
3926 pr_err("------ spte 0x%llx level %d.\n",
3927 sptes[root - 1], root);
3936 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3941 if (mmio_info_in_cache(vcpu, addr, direct))
3942 return RET_PF_EMULATE;
3944 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3945 if (WARN_ON(reserved))
3948 if (is_mmio_spte(spte)) {
3949 gfn_t gfn = get_mmio_spte_gfn(spte);
3950 unsigned access = get_mmio_spte_access(spte);
3952 if (!check_mmio_spte(vcpu, spte))
3953 return RET_PF_INVALID;
3958 trace_handle_mmio_page_fault(addr, gfn, access);
3959 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3960 return RET_PF_EMULATE;
3964 * If the page table is zapped by other cpus, let CPU fault again on
3967 return RET_PF_RETRY;
3970 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3971 u32 error_code, gfn_t gfn)
3973 if (unlikely(error_code & PFERR_RSVD_MASK))
3976 if (!(error_code & PFERR_PRESENT_MASK) ||
3977 !(error_code & PFERR_WRITE_MASK))
3981 * guest is writing the page which is write tracked which can
3982 * not be fixed by page fault handler.
3984 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3990 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3992 struct kvm_shadow_walk_iterator iterator;
3995 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3998 walk_shadow_page_lockless_begin(vcpu);
3999 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4000 clear_sp_write_flooding_count(iterator.sptep);
4001 if (!is_shadow_present_pte(spte))
4004 walk_shadow_page_lockless_end(vcpu);
4007 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
4008 u32 error_code, bool prefault)
4010 gfn_t gfn = gva >> PAGE_SHIFT;
4013 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
4015 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4016 return RET_PF_EMULATE;
4018 r = mmu_topup_memory_caches(vcpu);
4022 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4025 return nonpaging_map(vcpu, gva & PAGE_MASK,
4026 error_code, gfn, prefault);
4029 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
4031 struct kvm_arch_async_pf arch;
4033 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4035 arch.direct_map = vcpu->arch.mmu->direct_map;
4036 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4038 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4041 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4042 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4044 struct kvm_memory_slot *slot;
4048 * Don't expose private memslots to L2.
4050 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4051 *pfn = KVM_PFN_NOSLOT;
4055 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4057 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4059 return false; /* *pfn has correct page already */
4061 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4062 trace_kvm_try_async_get_page(gva, gfn);
4063 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4064 trace_kvm_async_pf_doublefault(gva, gfn);
4065 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4067 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4071 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4075 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4076 u64 fault_address, char *insn, int insn_len)
4080 vcpu->arch.l1tf_flush_l1d = true;
4081 switch (vcpu->arch.apf.host_apf_reason) {
4083 trace_kvm_page_fault(fault_address, error_code);
4085 if (kvm_event_needs_reinjection(vcpu))
4086 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4087 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4090 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4091 vcpu->arch.apf.host_apf_reason = 0;
4092 local_irq_disable();
4093 kvm_async_pf_task_wait(fault_address, 0);
4096 case KVM_PV_REASON_PAGE_READY:
4097 vcpu->arch.apf.host_apf_reason = 0;
4098 local_irq_disable();
4099 kvm_async_pf_task_wake(fault_address);
4105 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4108 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4110 int page_num = KVM_PAGES_PER_HPAGE(level);
4112 gfn &= ~(page_num - 1);
4114 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4117 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4123 bool force_pt_level;
4124 gfn_t gfn = gpa >> PAGE_SHIFT;
4125 unsigned long mmu_seq;
4126 int write = error_code & PFERR_WRITE_MASK;
4129 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4131 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4132 return RET_PF_EMULATE;
4134 r = mmu_topup_memory_caches(vcpu);
4138 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4139 PT_DIRECTORY_LEVEL);
4140 level = mapping_level(vcpu, gfn, &force_pt_level);
4141 if (likely(!force_pt_level)) {
4142 if (level > PT_DIRECTORY_LEVEL &&
4143 !check_hugepage_cache_consistency(vcpu, gfn, level))
4144 level = PT_DIRECTORY_LEVEL;
4145 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4148 if (fast_page_fault(vcpu, gpa, level, error_code))
4149 return RET_PF_RETRY;
4151 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4154 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4155 return RET_PF_RETRY;
4157 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4161 spin_lock(&vcpu->kvm->mmu_lock);
4162 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4164 if (make_mmu_pages_available(vcpu) < 0)
4166 if (likely(!force_pt_level))
4167 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4168 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn, prefault);
4170 spin_unlock(&vcpu->kvm->mmu_lock);
4171 kvm_release_pfn_clean(pfn);
4175 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4176 struct kvm_mmu *context)
4178 context->page_fault = nonpaging_page_fault;
4179 context->gva_to_gpa = nonpaging_gva_to_gpa;
4180 context->sync_page = nonpaging_sync_page;
4181 context->invlpg = nonpaging_invlpg;
4182 context->update_pte = nonpaging_update_pte;
4183 context->root_level = 0;
4184 context->shadow_root_level = PT32E_ROOT_LEVEL;
4185 context->direct_map = true;
4186 context->nx = false;
4190 * Find out if a previously cached root matching the new CR3/role is available.
4191 * The current root is also inserted into the cache.
4192 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4194 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4195 * false is returned. This root should now be freed by the caller.
4197 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4198 union kvm_mmu_page_role new_role)
4201 struct kvm_mmu_root_info root;
4202 struct kvm_mmu *mmu = vcpu->arch.mmu;
4204 root.cr3 = mmu->root_cr3;
4205 root.hpa = mmu->root_hpa;
4207 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4208 swap(root, mmu->prev_roots[i]);
4210 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4211 page_header(root.hpa) != NULL &&
4212 new_role.word == page_header(root.hpa)->role.word)
4216 mmu->root_hpa = root.hpa;
4217 mmu->root_cr3 = root.cr3;
4219 return i < KVM_MMU_NUM_PREV_ROOTS;
4222 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4223 union kvm_mmu_page_role new_role,
4224 bool skip_tlb_flush)
4226 struct kvm_mmu *mmu = vcpu->arch.mmu;
4229 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4230 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4231 * later if necessary.
4233 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4234 mmu->root_level >= PT64_ROOT_4LEVEL) {
4235 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4238 if (cached_root_available(vcpu, new_cr3, new_role)) {
4239 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4240 if (!skip_tlb_flush) {
4241 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4242 kvm_x86_ops->tlb_flush(vcpu, true);
4246 * The last MMIO access's GVA and GPA are cached in the
4247 * VCPU. When switching to a new CR3, that GVA->GPA
4248 * mapping may no longer be valid. So clear any cached
4249 * MMIO info even when we don't need to sync the shadow
4252 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4254 __clear_sp_write_flooding_count(
4255 page_header(mmu->root_hpa));
4264 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4265 union kvm_mmu_page_role new_role,
4266 bool skip_tlb_flush)
4268 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4269 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4270 KVM_MMU_ROOT_CURRENT);
4273 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4275 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4278 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4280 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4282 return kvm_read_cr3(vcpu);
4285 static void inject_page_fault(struct kvm_vcpu *vcpu,
4286 struct x86_exception *fault)
4288 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4291 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4292 unsigned access, int *nr_present)
4294 if (unlikely(is_mmio_spte(*sptep))) {
4295 if (gfn != get_mmio_spte_gfn(*sptep)) {
4296 mmu_spte_clear_no_track(sptep);
4301 mark_mmio_spte(vcpu, sptep, gfn, access);
4308 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4309 unsigned level, unsigned gpte)
4312 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4313 * If it is clear, there are no large pages at this level, so clear
4314 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4316 gpte &= level - mmu->last_nonleaf_level;
4319 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4320 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4321 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4323 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4325 return gpte & PT_PAGE_SIZE_MASK;
4328 #define PTTYPE_EPT 18 /* arbitrary */
4329 #define PTTYPE PTTYPE_EPT
4330 #include "paging_tmpl.h"
4334 #include "paging_tmpl.h"
4338 #include "paging_tmpl.h"
4342 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4343 struct rsvd_bits_validate *rsvd_check,
4344 int maxphyaddr, int level, bool nx, bool gbpages,
4347 u64 exb_bit_rsvd = 0;
4348 u64 gbpages_bit_rsvd = 0;
4349 u64 nonleaf_bit8_rsvd = 0;
4351 rsvd_check->bad_mt_xwr = 0;
4354 exb_bit_rsvd = rsvd_bits(63, 63);
4356 gbpages_bit_rsvd = rsvd_bits(7, 7);
4359 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4360 * leaf entries) on AMD CPUs only.
4363 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4366 case PT32_ROOT_LEVEL:
4367 /* no rsvd bits for 2 level 4K page table entries */
4368 rsvd_check->rsvd_bits_mask[0][1] = 0;
4369 rsvd_check->rsvd_bits_mask[0][0] = 0;
4370 rsvd_check->rsvd_bits_mask[1][0] =
4371 rsvd_check->rsvd_bits_mask[0][0];
4374 rsvd_check->rsvd_bits_mask[1][1] = 0;
4378 if (is_cpuid_PSE36())
4379 /* 36bits PSE 4MB page */
4380 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4382 /* 32 bits PSE 4MB page */
4383 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4385 case PT32E_ROOT_LEVEL:
4386 rsvd_check->rsvd_bits_mask[0][2] =
4387 rsvd_bits(maxphyaddr, 63) |
4388 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4389 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4390 rsvd_bits(maxphyaddr, 62); /* PDE */
4391 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4392 rsvd_bits(maxphyaddr, 62); /* PTE */
4393 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4394 rsvd_bits(maxphyaddr, 62) |
4395 rsvd_bits(13, 20); /* large page */
4396 rsvd_check->rsvd_bits_mask[1][0] =
4397 rsvd_check->rsvd_bits_mask[0][0];
4399 case PT64_ROOT_5LEVEL:
4400 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4401 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4402 rsvd_bits(maxphyaddr, 51);
4403 rsvd_check->rsvd_bits_mask[1][4] =
4404 rsvd_check->rsvd_bits_mask[0][4];
4406 case PT64_ROOT_4LEVEL:
4407 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4408 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4409 rsvd_bits(maxphyaddr, 51);
4410 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4411 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4412 rsvd_bits(maxphyaddr, 51);
4413 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4414 rsvd_bits(maxphyaddr, 51);
4415 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4416 rsvd_bits(maxphyaddr, 51);
4417 rsvd_check->rsvd_bits_mask[1][3] =
4418 rsvd_check->rsvd_bits_mask[0][3];
4419 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4420 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4422 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4423 rsvd_bits(maxphyaddr, 51) |
4424 rsvd_bits(13, 20); /* large page */
4425 rsvd_check->rsvd_bits_mask[1][0] =
4426 rsvd_check->rsvd_bits_mask[0][0];
4431 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4432 struct kvm_mmu *context)
4434 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4435 cpuid_maxphyaddr(vcpu), context->root_level,
4437 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4438 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4442 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4443 int maxphyaddr, bool execonly)
4447 rsvd_check->rsvd_bits_mask[0][4] =
4448 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4449 rsvd_check->rsvd_bits_mask[0][3] =
4450 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4451 rsvd_check->rsvd_bits_mask[0][2] =
4452 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4453 rsvd_check->rsvd_bits_mask[0][1] =
4454 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4455 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4458 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4459 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4460 rsvd_check->rsvd_bits_mask[1][2] =
4461 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4462 rsvd_check->rsvd_bits_mask[1][1] =
4463 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4464 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4466 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4467 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4468 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4469 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4470 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4472 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4473 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4475 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4478 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4479 struct kvm_mmu *context, bool execonly)
4481 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4482 cpuid_maxphyaddr(vcpu), execonly);
4486 * the page table on host is the shadow page table for the page
4487 * table in guest or amd nested guest, its mmu features completely
4488 * follow the features in guest.
4491 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4493 bool uses_nx = context->nx ||
4494 context->mmu_role.base.smep_andnot_wp;
4495 struct rsvd_bits_validate *shadow_zero_check;
4499 * Passing "true" to the last argument is okay; it adds a check
4500 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4502 shadow_zero_check = &context->shadow_zero_check;
4503 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4505 context->shadow_root_level, uses_nx,
4506 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4507 is_pse(vcpu), true);
4509 if (!shadow_me_mask)
4512 for (i = context->shadow_root_level; --i >= 0;) {
4513 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4514 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4518 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4520 static inline bool boot_cpu_is_amd(void)
4522 WARN_ON_ONCE(!tdp_enabled);
4523 return shadow_x_mask == 0;
4527 * the direct page table on host, use as much mmu features as
4528 * possible, however, kvm currently does not do execution-protection.
4531 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4532 struct kvm_mmu *context)
4534 struct rsvd_bits_validate *shadow_zero_check;
4537 shadow_zero_check = &context->shadow_zero_check;
4539 if (boot_cpu_is_amd())
4540 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4542 context->shadow_root_level, false,
4543 boot_cpu_has(X86_FEATURE_GBPAGES),
4546 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4550 if (!shadow_me_mask)
4553 for (i = context->shadow_root_level; --i >= 0;) {
4554 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4555 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4560 * as the comments in reset_shadow_zero_bits_mask() except it
4561 * is the shadow page table for intel nested guest.
4564 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4565 struct kvm_mmu *context, bool execonly)
4567 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4568 shadow_phys_bits, execonly);
4571 #define BYTE_MASK(access) \
4572 ((1 & (access) ? 2 : 0) | \
4573 (2 & (access) ? 4 : 0) | \
4574 (3 & (access) ? 8 : 0) | \
4575 (4 & (access) ? 16 : 0) | \
4576 (5 & (access) ? 32 : 0) | \
4577 (6 & (access) ? 64 : 0) | \
4578 (7 & (access) ? 128 : 0))
4581 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4582 struct kvm_mmu *mmu, bool ept)
4586 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4587 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4588 const u8 u = BYTE_MASK(ACC_USER_MASK);
4590 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4591 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4592 bool cr0_wp = is_write_protection(vcpu);
4594 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4595 unsigned pfec = byte << 1;
4598 * Each "*f" variable has a 1 bit for each UWX value
4599 * that causes a fault with the given PFEC.
4602 /* Faults from writes to non-writable pages */
4603 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4604 /* Faults from user mode accesses to supervisor pages */
4605 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4606 /* Faults from fetches of non-executable pages*/
4607 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4608 /* Faults from kernel mode fetches of user pages */
4610 /* Faults from kernel mode accesses of user pages */
4614 /* Faults from kernel mode accesses to user pages */
4615 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4617 /* Not really needed: !nx will cause pte.nx to fault */
4621 /* Allow supervisor writes if !cr0.wp */
4623 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4625 /* Disallow supervisor fetches of user code if cr4.smep */
4627 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4630 * SMAP:kernel-mode data accesses from user-mode
4631 * mappings should fault. A fault is considered
4632 * as a SMAP violation if all of the following
4633 * conditions are true:
4634 * - X86_CR4_SMAP is set in CR4
4635 * - A user page is accessed
4636 * - The access is not a fetch
4637 * - Page fault in kernel mode
4638 * - if CPL = 3 or X86_EFLAGS_AC is clear
4640 * Here, we cover the first three conditions.
4641 * The fourth is computed dynamically in permission_fault();
4642 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4643 * *not* subject to SMAP restrictions.
4646 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4649 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4654 * PKU is an additional mechanism by which the paging controls access to
4655 * user-mode addresses based on the value in the PKRU register. Protection
4656 * key violations are reported through a bit in the page fault error code.
4657 * Unlike other bits of the error code, the PK bit is not known at the
4658 * call site of e.g. gva_to_gpa; it must be computed directly in
4659 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4660 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4662 * In particular the following conditions come from the error code, the
4663 * page tables and the machine state:
4664 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4665 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4666 * - PK is always zero if U=0 in the page tables
4667 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4669 * The PKRU bitmask caches the result of these four conditions. The error
4670 * code (minus the P bit) and the page table's U bit form an index into the
4671 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4672 * with the two bits of the PKRU register corresponding to the protection key.
4673 * For the first three conditions above the bits will be 00, thus masking
4674 * away both AD and WD. For all reads or if the last condition holds, WD
4675 * only will be masked away.
4677 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4688 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4689 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4694 wp = is_write_protection(vcpu);
4696 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4697 unsigned pfec, pkey_bits;
4698 bool check_pkey, check_write, ff, uf, wf, pte_user;
4701 ff = pfec & PFERR_FETCH_MASK;
4702 uf = pfec & PFERR_USER_MASK;
4703 wf = pfec & PFERR_WRITE_MASK;
4705 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4706 pte_user = pfec & PFERR_RSVD_MASK;
4709 * Only need to check the access which is not an
4710 * instruction fetch and is to a user page.
4712 check_pkey = (!ff && pte_user);
4714 * write access is controlled by PKRU if it is a
4715 * user access or CR0.WP = 1.
4717 check_write = check_pkey && wf && (uf || wp);
4719 /* PKRU.AD stops both read and write access. */
4720 pkey_bits = !!check_pkey;
4721 /* PKRU.WD stops write access. */
4722 pkey_bits |= (!!check_write) << 1;
4724 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4728 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4730 unsigned root_level = mmu->root_level;
4732 mmu->last_nonleaf_level = root_level;
4733 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4734 mmu->last_nonleaf_level++;
4737 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4738 struct kvm_mmu *context,
4741 context->nx = is_nx(vcpu);
4742 context->root_level = level;
4744 reset_rsvds_bits_mask(vcpu, context);
4745 update_permission_bitmask(vcpu, context, false);
4746 update_pkru_bitmask(vcpu, context, false);
4747 update_last_nonleaf_level(vcpu, context);
4749 MMU_WARN_ON(!is_pae(vcpu));
4750 context->page_fault = paging64_page_fault;
4751 context->gva_to_gpa = paging64_gva_to_gpa;
4752 context->sync_page = paging64_sync_page;
4753 context->invlpg = paging64_invlpg;
4754 context->update_pte = paging64_update_pte;
4755 context->shadow_root_level = level;
4756 context->direct_map = false;
4759 static void paging64_init_context(struct kvm_vcpu *vcpu,
4760 struct kvm_mmu *context)
4762 int root_level = is_la57_mode(vcpu) ?
4763 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4765 paging64_init_context_common(vcpu, context, root_level);
4768 static void paging32_init_context(struct kvm_vcpu *vcpu,
4769 struct kvm_mmu *context)
4771 context->nx = false;
4772 context->root_level = PT32_ROOT_LEVEL;
4774 reset_rsvds_bits_mask(vcpu, context);
4775 update_permission_bitmask(vcpu, context, false);
4776 update_pkru_bitmask(vcpu, context, false);
4777 update_last_nonleaf_level(vcpu, context);
4779 context->page_fault = paging32_page_fault;
4780 context->gva_to_gpa = paging32_gva_to_gpa;
4781 context->sync_page = paging32_sync_page;
4782 context->invlpg = paging32_invlpg;
4783 context->update_pte = paging32_update_pte;
4784 context->shadow_root_level = PT32E_ROOT_LEVEL;
4785 context->direct_map = false;
4788 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4789 struct kvm_mmu *context)
4791 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4794 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4796 union kvm_mmu_extended_role ext = {0};
4798 ext.cr0_pg = !!is_paging(vcpu);
4799 ext.cr4_pae = !!is_pae(vcpu);
4800 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4801 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4802 ext.cr4_pse = !!is_pse(vcpu);
4803 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4804 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4805 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4812 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4815 union kvm_mmu_role role = {0};
4817 role.base.access = ACC_ALL;
4818 role.base.nxe = !!is_nx(vcpu);
4819 role.base.cr0_wp = is_write_protection(vcpu);
4820 role.base.smm = is_smm(vcpu);
4821 role.base.guest_mode = is_guest_mode(vcpu);
4826 role.ext = kvm_calc_mmu_role_ext(vcpu);
4831 static union kvm_mmu_role
4832 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4834 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4836 role.base.ad_disabled = (shadow_accessed_mask == 0);
4837 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4838 role.base.direct = true;
4839 role.base.gpte_is_8_bytes = true;
4844 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4846 struct kvm_mmu *context = vcpu->arch.mmu;
4847 union kvm_mmu_role new_role =
4848 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4850 new_role.base.word &= mmu_base_role_mask.word;
4851 if (new_role.as_u64 == context->mmu_role.as_u64)
4854 context->mmu_role.as_u64 = new_role.as_u64;
4855 context->page_fault = tdp_page_fault;
4856 context->sync_page = nonpaging_sync_page;
4857 context->invlpg = nonpaging_invlpg;
4858 context->update_pte = nonpaging_update_pte;
4859 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4860 context->direct_map = true;
4861 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4862 context->get_cr3 = get_cr3;
4863 context->get_pdptr = kvm_pdptr_read;
4864 context->inject_page_fault = kvm_inject_page_fault;
4866 if (!is_paging(vcpu)) {
4867 context->nx = false;
4868 context->gva_to_gpa = nonpaging_gva_to_gpa;
4869 context->root_level = 0;
4870 } else if (is_long_mode(vcpu)) {
4871 context->nx = is_nx(vcpu);
4872 context->root_level = is_la57_mode(vcpu) ?
4873 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4874 reset_rsvds_bits_mask(vcpu, context);
4875 context->gva_to_gpa = paging64_gva_to_gpa;
4876 } else if (is_pae(vcpu)) {
4877 context->nx = is_nx(vcpu);
4878 context->root_level = PT32E_ROOT_LEVEL;
4879 reset_rsvds_bits_mask(vcpu, context);
4880 context->gva_to_gpa = paging64_gva_to_gpa;
4882 context->nx = false;
4883 context->root_level = PT32_ROOT_LEVEL;
4884 reset_rsvds_bits_mask(vcpu, context);
4885 context->gva_to_gpa = paging32_gva_to_gpa;
4888 update_permission_bitmask(vcpu, context, false);
4889 update_pkru_bitmask(vcpu, context, false);
4890 update_last_nonleaf_level(vcpu, context);
4891 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4894 static union kvm_mmu_role
4895 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4897 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4899 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4900 !is_write_protection(vcpu);
4901 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4902 !is_write_protection(vcpu);
4903 role.base.direct = !is_paging(vcpu);
4904 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4906 if (!is_long_mode(vcpu))
4907 role.base.level = PT32E_ROOT_LEVEL;
4908 else if (is_la57_mode(vcpu))
4909 role.base.level = PT64_ROOT_5LEVEL;
4911 role.base.level = PT64_ROOT_4LEVEL;
4916 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4918 struct kvm_mmu *context = vcpu->arch.mmu;
4919 union kvm_mmu_role new_role =
4920 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4922 new_role.base.word &= mmu_base_role_mask.word;
4923 if (new_role.as_u64 == context->mmu_role.as_u64)
4926 if (!is_paging(vcpu))
4927 nonpaging_init_context(vcpu, context);
4928 else if (is_long_mode(vcpu))
4929 paging64_init_context(vcpu, context);
4930 else if (is_pae(vcpu))
4931 paging32E_init_context(vcpu, context);
4933 paging32_init_context(vcpu, context);
4935 context->mmu_role.as_u64 = new_role.as_u64;
4936 reset_shadow_zero_bits_mask(vcpu, context);
4938 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4940 static union kvm_mmu_role
4941 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4944 union kvm_mmu_role role = {0};
4946 /* SMM flag is inherited from root_mmu */
4947 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
4949 role.base.level = PT64_ROOT_4LEVEL;
4950 role.base.gpte_is_8_bytes = true;
4951 role.base.direct = false;
4952 role.base.ad_disabled = !accessed_dirty;
4953 role.base.guest_mode = true;
4954 role.base.access = ACC_ALL;
4957 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
4958 * SMAP variation to denote shadow EPT entries.
4960 role.base.cr0_wp = true;
4961 role.base.smap_andnot_wp = true;
4963 role.ext = kvm_calc_mmu_role_ext(vcpu);
4964 role.ext.execonly = execonly;
4969 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4970 bool accessed_dirty, gpa_t new_eptp)
4972 struct kvm_mmu *context = vcpu->arch.mmu;
4973 union kvm_mmu_role new_role =
4974 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4977 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
4979 new_role.base.word &= mmu_base_role_mask.word;
4980 if (new_role.as_u64 == context->mmu_role.as_u64)
4983 context->shadow_root_level = PT64_ROOT_4LEVEL;
4986 context->ept_ad = accessed_dirty;
4987 context->page_fault = ept_page_fault;
4988 context->gva_to_gpa = ept_gva_to_gpa;
4989 context->sync_page = ept_sync_page;
4990 context->invlpg = ept_invlpg;
4991 context->update_pte = ept_update_pte;
4992 context->root_level = PT64_ROOT_4LEVEL;
4993 context->direct_map = false;
4994 context->mmu_role.as_u64 = new_role.as_u64;
4996 update_permission_bitmask(vcpu, context, true);
4997 update_pkru_bitmask(vcpu, context, true);
4998 update_last_nonleaf_level(vcpu, context);
4999 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5000 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5002 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5004 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5006 struct kvm_mmu *context = vcpu->arch.mmu;
5008 kvm_init_shadow_mmu(vcpu);
5009 context->set_cr3 = kvm_x86_ops->set_cr3;
5010 context->get_cr3 = get_cr3;
5011 context->get_pdptr = kvm_pdptr_read;
5012 context->inject_page_fault = kvm_inject_page_fault;
5015 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5017 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5018 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5020 new_role.base.word &= mmu_base_role_mask.word;
5021 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5024 g_context->mmu_role.as_u64 = new_role.as_u64;
5025 g_context->get_cr3 = get_cr3;
5026 g_context->get_pdptr = kvm_pdptr_read;
5027 g_context->inject_page_fault = kvm_inject_page_fault;
5030 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5031 * L1's nested page tables (e.g. EPT12). The nested translation
5032 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5033 * L2's page tables as the first level of translation and L1's
5034 * nested page tables as the second level of translation. Basically
5035 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5037 if (!is_paging(vcpu)) {
5038 g_context->nx = false;
5039 g_context->root_level = 0;
5040 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5041 } else if (is_long_mode(vcpu)) {
5042 g_context->nx = is_nx(vcpu);
5043 g_context->root_level = is_la57_mode(vcpu) ?
5044 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5045 reset_rsvds_bits_mask(vcpu, g_context);
5046 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5047 } else if (is_pae(vcpu)) {
5048 g_context->nx = is_nx(vcpu);
5049 g_context->root_level = PT32E_ROOT_LEVEL;
5050 reset_rsvds_bits_mask(vcpu, g_context);
5051 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5053 g_context->nx = false;
5054 g_context->root_level = PT32_ROOT_LEVEL;
5055 reset_rsvds_bits_mask(vcpu, g_context);
5056 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5059 update_permission_bitmask(vcpu, g_context, false);
5060 update_pkru_bitmask(vcpu, g_context, false);
5061 update_last_nonleaf_level(vcpu, g_context);
5064 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5069 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5071 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5072 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5075 if (mmu_is_nested(vcpu))
5076 init_kvm_nested_mmu(vcpu);
5077 else if (tdp_enabled)
5078 init_kvm_tdp_mmu(vcpu);
5080 init_kvm_softmmu(vcpu);
5082 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5084 static union kvm_mmu_page_role
5085 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5087 union kvm_mmu_role role;
5090 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5092 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5097 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5099 kvm_mmu_unload(vcpu);
5100 kvm_init_mmu(vcpu, true);
5102 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5104 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5108 r = mmu_topup_memory_caches(vcpu);
5111 r = mmu_alloc_roots(vcpu);
5112 kvm_mmu_sync_roots(vcpu);
5115 kvm_mmu_load_cr3(vcpu);
5116 kvm_x86_ops->tlb_flush(vcpu, true);
5120 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5122 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5124 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5125 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5126 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5127 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5129 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5131 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5132 struct kvm_mmu_page *sp, u64 *spte,
5135 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5136 ++vcpu->kvm->stat.mmu_pde_zapped;
5140 ++vcpu->kvm->stat.mmu_pte_updated;
5141 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5144 static bool need_remote_flush(u64 old, u64 new)
5146 if (!is_shadow_present_pte(old))
5148 if (!is_shadow_present_pte(new))
5150 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5152 old ^= shadow_nx_mask;
5153 new ^= shadow_nx_mask;
5154 return (old & ~new & PT64_PERM_MASK) != 0;
5157 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5164 * Assume that the pte write on a page table of the same type
5165 * as the current vcpu paging mode since we update the sptes only
5166 * when they have the same mode.
5168 if (is_pae(vcpu) && *bytes == 4) {
5169 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5174 if (*bytes == 4 || *bytes == 8) {
5175 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5184 * If we're seeing too many writes to a page, it may no longer be a page table,
5185 * or we may be forking, in which case it is better to unmap the page.
5187 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5190 * Skip write-flooding detected for the sp whose level is 1, because
5191 * it can become unsync, then the guest page is not write-protected.
5193 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5196 atomic_inc(&sp->write_flooding_count);
5197 return atomic_read(&sp->write_flooding_count) >= 3;
5201 * Misaligned accesses are too much trouble to fix up; also, they usually
5202 * indicate a page is not used as a page table.
5204 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5207 unsigned offset, pte_size, misaligned;
5209 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5210 gpa, bytes, sp->role.word);
5212 offset = offset_in_page(gpa);
5213 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5216 * Sometimes, the OS only writes the last one bytes to update status
5217 * bits, for example, in linux, andb instruction is used in clear_bit().
5219 if (!(offset & (pte_size - 1)) && bytes == 1)
5222 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5223 misaligned |= bytes < 4;
5228 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5230 unsigned page_offset, quadrant;
5234 page_offset = offset_in_page(gpa);
5235 level = sp->role.level;
5237 if (!sp->role.gpte_is_8_bytes) {
5238 page_offset <<= 1; /* 32->64 */
5240 * A 32-bit pde maps 4MB while the shadow pdes map
5241 * only 2MB. So we need to double the offset again
5242 * and zap two pdes instead of one.
5244 if (level == PT32_ROOT_LEVEL) {
5245 page_offset &= ~7; /* kill rounding error */
5249 quadrant = page_offset >> PAGE_SHIFT;
5250 page_offset &= ~PAGE_MASK;
5251 if (quadrant != sp->role.quadrant)
5255 spte = &sp->spt[page_offset / sizeof(*spte)];
5259 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5260 const u8 *new, int bytes,
5261 struct kvm_page_track_notifier_node *node)
5263 gfn_t gfn = gpa >> PAGE_SHIFT;
5264 struct kvm_mmu_page *sp;
5265 LIST_HEAD(invalid_list);
5266 u64 entry, gentry, *spte;
5268 bool remote_flush, local_flush;
5271 * If we don't have indirect shadow pages, it means no page is
5272 * write-protected, so we can exit simply.
5274 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5277 remote_flush = local_flush = false;
5279 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5282 * No need to care whether allocation memory is successful
5283 * or not since pte prefetch is skiped if it does not have
5284 * enough objects in the cache.
5286 mmu_topup_memory_caches(vcpu);
5288 spin_lock(&vcpu->kvm->mmu_lock);
5290 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5292 ++vcpu->kvm->stat.mmu_pte_write;
5293 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5295 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5296 if (detect_write_misaligned(sp, gpa, bytes) ||
5297 detect_write_flooding(sp)) {
5298 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5299 ++vcpu->kvm->stat.mmu_flooded;
5303 spte = get_written_sptes(sp, gpa, &npte);
5309 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5312 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5314 !((sp->role.word ^ base_role)
5315 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5316 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5317 if (need_remote_flush(entry, *spte))
5318 remote_flush = true;
5322 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5323 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5324 spin_unlock(&vcpu->kvm->mmu_lock);
5327 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5332 if (vcpu->arch.mmu->direct_map)
5335 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5337 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5341 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5343 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5345 LIST_HEAD(invalid_list);
5347 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5350 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5351 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5354 ++vcpu->kvm->stat.mmu_recycled;
5356 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5358 if (!kvm_mmu_available_pages(vcpu->kvm))
5363 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5364 void *insn, int insn_len)
5366 int r, emulation_type = 0;
5367 enum emulation_result er;
5368 bool direct = vcpu->arch.mmu->direct_map;
5370 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5371 if (vcpu->arch.mmu->direct_map) {
5372 vcpu->arch.gpa_available = true;
5373 vcpu->arch.gpa_val = cr2;
5377 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5378 r = handle_mmio_page_fault(vcpu, cr2, direct);
5379 if (r == RET_PF_EMULATE)
5383 if (r == RET_PF_INVALID) {
5384 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5385 lower_32_bits(error_code),
5387 WARN_ON(r == RET_PF_INVALID);
5390 if (r == RET_PF_RETRY)
5396 * Before emulating the instruction, check if the error code
5397 * was due to a RO violation while translating the guest page.
5398 * This can occur when using nested virtualization with nested
5399 * paging in both guests. If true, we simply unprotect the page
5400 * and resume the guest.
5402 if (vcpu->arch.mmu->direct_map &&
5403 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5404 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5409 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5410 * optimistically try to just unprotect the page and let the processor
5411 * re-execute the instruction that caused the page fault. Do not allow
5412 * retrying MMIO emulation, as it's not only pointless but could also
5413 * cause us to enter an infinite loop because the processor will keep
5414 * faulting on the non-existent MMIO address. Retrying an instruction
5415 * from a nested guest is also pointless and dangerous as we are only
5416 * explicitly shadowing L1's page tables, i.e. unprotecting something
5417 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5419 if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5420 emulation_type = EMULTYPE_ALLOW_RETRY;
5423 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5424 * This can happen if a guest gets a page-fault on data access but the HW
5425 * table walker is not able to read the instruction page (e.g instruction
5426 * page is not present in memory). In those cases we simply restart the
5427 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5429 if (unlikely(insn && !insn_len)) {
5430 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5434 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
5439 case EMULATE_USER_EXIT:
5440 ++vcpu->stat.mmio_exits;
5448 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5450 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5452 struct kvm_mmu *mmu = vcpu->arch.mmu;
5455 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5456 if (is_noncanonical_address(gva, vcpu))
5459 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5462 * INVLPG is required to invalidate any global mappings for the VA,
5463 * irrespective of PCID. Since it would take us roughly similar amount
5464 * of work to determine whether any of the prev_root mappings of the VA
5465 * is marked global, or to just sync it blindly, so we might as well
5466 * just always sync it.
5468 * Mappings not reachable via the current cr3 or the prev_roots will be
5469 * synced when switching to that cr3, so nothing needs to be done here
5472 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5473 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5474 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5476 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5477 ++vcpu->stat.invlpg;
5479 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5481 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5483 struct kvm_mmu *mmu = vcpu->arch.mmu;
5484 bool tlb_flush = false;
5487 if (pcid == kvm_get_active_pcid(vcpu)) {
5488 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5492 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5493 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5494 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5495 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5501 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5503 ++vcpu->stat.invlpg;
5506 * Mappings not reachable via the current cr3 or the prev_roots will be
5507 * synced when switching to that cr3, so nothing needs to be done here
5511 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5513 void kvm_enable_tdp(void)
5517 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5519 void kvm_disable_tdp(void)
5521 tdp_enabled = false;
5523 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5526 /* The return value indicates if tlb flush on all vcpus is needed. */
5527 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5529 /* The caller should hold mmu-lock before calling this function. */
5530 static __always_inline bool
5531 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5532 slot_level_handler fn, int start_level, int end_level,
5533 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5535 struct slot_rmap_walk_iterator iterator;
5538 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5539 end_gfn, &iterator) {
5541 flush |= fn(kvm, iterator.rmap);
5543 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5544 if (flush && lock_flush_tlb) {
5545 kvm_flush_remote_tlbs_with_address(kvm,
5547 iterator.gfn - start_gfn + 1);
5550 cond_resched_lock(&kvm->mmu_lock);
5554 if (flush && lock_flush_tlb) {
5555 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5556 end_gfn - start_gfn + 1);
5563 static __always_inline bool
5564 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5565 slot_level_handler fn, int start_level, int end_level,
5566 bool lock_flush_tlb)
5568 return slot_handle_level_range(kvm, memslot, fn, start_level,
5569 end_level, memslot->base_gfn,
5570 memslot->base_gfn + memslot->npages - 1,
5574 static __always_inline bool
5575 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5576 slot_level_handler fn, bool lock_flush_tlb)
5578 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5579 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5582 static __always_inline bool
5583 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5584 slot_level_handler fn, bool lock_flush_tlb)
5586 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5587 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5590 static __always_inline bool
5591 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5592 slot_level_handler fn, bool lock_flush_tlb)
5594 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5595 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5598 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5600 free_page((unsigned long)vcpu->arch.mmu->pae_root);
5601 free_page((unsigned long)vcpu->arch.mmu->lm_root);
5604 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5610 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5611 * while the PDP table is a per-vCPU construct that's allocated at MMU
5612 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5613 * x86_64. Therefore we need to allocate the PDP table in the first
5614 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5615 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5616 * skip allocating the PDP table.
5618 if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5621 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5625 vcpu->arch.mmu->pae_root = page_address(page);
5626 for (i = 0; i < 4; ++i)
5627 vcpu->arch.mmu->pae_root[i] = INVALID_PAGE;
5632 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5636 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5637 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5639 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5640 vcpu->arch.root_mmu.root_cr3 = 0;
5641 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5642 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5643 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5645 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5646 vcpu->arch.guest_mmu.root_cr3 = 0;
5647 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5648 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5649 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5651 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5652 return alloc_mmu_pages(vcpu);
5655 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5656 struct kvm_memory_slot *slot,
5657 struct kvm_page_track_notifier_node *node)
5659 kvm_mmu_zap_all(kvm);
5662 void kvm_mmu_init_vm(struct kvm *kvm)
5664 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5666 node->track_write = kvm_mmu_pte_write;
5667 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5668 kvm_page_track_register_notifier(kvm, node);
5671 void kvm_mmu_uninit_vm(struct kvm *kvm)
5673 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5675 kvm_page_track_unregister_notifier(kvm, node);
5678 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5680 struct kvm_memslots *slots;
5681 struct kvm_memory_slot *memslot;
5684 spin_lock(&kvm->mmu_lock);
5685 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5686 slots = __kvm_memslots(kvm, i);
5687 kvm_for_each_memslot(memslot, slots) {
5690 start = max(gfn_start, memslot->base_gfn);
5691 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5695 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5696 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5697 start, end - 1, true);
5701 spin_unlock(&kvm->mmu_lock);
5704 static bool slot_rmap_write_protect(struct kvm *kvm,
5705 struct kvm_rmap_head *rmap_head)
5707 return __rmap_write_protect(kvm, rmap_head, false);
5710 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5711 struct kvm_memory_slot *memslot)
5715 spin_lock(&kvm->mmu_lock);
5716 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5718 spin_unlock(&kvm->mmu_lock);
5721 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5722 * which do tlb flush out of mmu-lock should be serialized by
5723 * kvm->slots_lock otherwise tlb flush would be missed.
5725 lockdep_assert_held(&kvm->slots_lock);
5728 * We can flush all the TLBs out of the mmu lock without TLB
5729 * corruption since we just change the spte from writable to
5730 * readonly so that we only need to care the case of changing
5731 * spte from present to present (changing the spte from present
5732 * to nonpresent will flush all the TLBs immediately), in other
5733 * words, the only case we care is mmu_spte_update() where we
5734 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5735 * instead of PT_WRITABLE_MASK, that means it does not depend
5736 * on PT_WRITABLE_MASK anymore.
5739 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5743 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5744 struct kvm_rmap_head *rmap_head)
5747 struct rmap_iterator iter;
5748 int need_tlb_flush = 0;
5750 struct kvm_mmu_page *sp;
5753 for_each_rmap_spte(rmap_head, &iter, sptep) {
5754 sp = page_header(__pa(sptep));
5755 pfn = spte_to_pfn(*sptep);
5758 * We cannot do huge page mapping for indirect shadow pages,
5759 * which are found on the last rmap (level = 1) when not using
5760 * tdp; such shadow pages are synced with the page table in
5761 * the guest, and the guest page table is using 4K page size
5762 * mapping if the indirect sp has level = 1.
5764 if (sp->role.direct &&
5765 !kvm_is_reserved_pfn(pfn) &&
5766 PageTransCompoundMap(pfn_to_page(pfn))) {
5767 pte_list_remove(rmap_head, sptep);
5769 if (kvm_available_flush_tlb_with_range())
5770 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5771 KVM_PAGES_PER_HPAGE(sp->role.level));
5779 return need_tlb_flush;
5782 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5783 const struct kvm_memory_slot *memslot)
5785 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5786 spin_lock(&kvm->mmu_lock);
5787 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5788 kvm_mmu_zap_collapsible_spte, true);
5789 spin_unlock(&kvm->mmu_lock);
5792 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5793 struct kvm_memory_slot *memslot)
5797 spin_lock(&kvm->mmu_lock);
5798 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5799 spin_unlock(&kvm->mmu_lock);
5801 lockdep_assert_held(&kvm->slots_lock);
5804 * It's also safe to flush TLBs out of mmu lock here as currently this
5805 * function is only used for dirty logging, in which case flushing TLB
5806 * out of mmu lock also guarantees no dirty pages will be lost in
5810 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5813 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5815 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5816 struct kvm_memory_slot *memslot)
5820 spin_lock(&kvm->mmu_lock);
5821 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5823 spin_unlock(&kvm->mmu_lock);
5825 /* see kvm_mmu_slot_remove_write_access */
5826 lockdep_assert_held(&kvm->slots_lock);
5829 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5832 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5834 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5835 struct kvm_memory_slot *memslot)
5839 spin_lock(&kvm->mmu_lock);
5840 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5841 spin_unlock(&kvm->mmu_lock);
5843 lockdep_assert_held(&kvm->slots_lock);
5845 /* see kvm_mmu_slot_leaf_clear_dirty */
5847 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5850 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5852 static void __kvm_mmu_zap_all(struct kvm *kvm, bool mmio_only)
5854 struct kvm_mmu_page *sp, *node;
5855 LIST_HEAD(invalid_list);
5858 spin_lock(&kvm->mmu_lock);
5860 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
5861 if (mmio_only && !sp->mmio_cached)
5863 if (sp->role.invalid && sp->root_count)
5865 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign)) {
5866 WARN_ON_ONCE(mmio_only);
5869 if (cond_resched_lock(&kvm->mmu_lock))
5873 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5874 spin_unlock(&kvm->mmu_lock);
5877 void kvm_mmu_zap_all(struct kvm *kvm)
5879 return __kvm_mmu_zap_all(kvm, false);
5882 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5884 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
5886 gen &= MMIO_SPTE_GEN_MASK;
5889 * Generation numbers are incremented in multiples of the number of
5890 * address spaces in order to provide unique generations across all
5891 * address spaces. Strip what is effectively the address space
5892 * modifier prior to checking for a wrap of the MMIO generation so
5893 * that a wrap in any address space is detected.
5895 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5898 * The very rare case: if the MMIO generation number has wrapped,
5899 * zap all shadow pages.
5901 if (unlikely(gen == 0)) {
5902 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5903 __kvm_mmu_zap_all(kvm, true);
5907 static unsigned long
5908 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5911 int nr_to_scan = sc->nr_to_scan;
5912 unsigned long freed = 0;
5914 mutex_lock(&kvm_lock);
5916 list_for_each_entry(kvm, &vm_list, vm_list) {
5918 LIST_HEAD(invalid_list);
5921 * Never scan more than sc->nr_to_scan VM instances.
5922 * Will not hit this condition practically since we do not try
5923 * to shrink more than one VM and it is very unlikely to see
5924 * !n_used_mmu_pages so many times.
5929 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5930 * here. We may skip a VM instance errorneosly, but we do not
5931 * want to shrink a VM that only started to populate its MMU
5934 if (!kvm->arch.n_used_mmu_pages)
5937 idx = srcu_read_lock(&kvm->srcu);
5938 spin_lock(&kvm->mmu_lock);
5940 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
5942 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5944 spin_unlock(&kvm->mmu_lock);
5945 srcu_read_unlock(&kvm->srcu, idx);
5948 * unfair on small ones
5949 * per-vm shrinkers cry out
5950 * sadness comes quickly
5952 list_move_tail(&kvm->vm_list, &vm_list);
5956 mutex_unlock(&kvm_lock);
5960 static unsigned long
5961 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5963 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5966 static struct shrinker mmu_shrinker = {
5967 .count_objects = mmu_shrink_count,
5968 .scan_objects = mmu_shrink_scan,
5969 .seeks = DEFAULT_SEEKS * 10,
5972 static void mmu_destroy_caches(void)
5974 kmem_cache_destroy(pte_list_desc_cache);
5975 kmem_cache_destroy(mmu_page_header_cache);
5978 static void kvm_set_mmio_spte_mask(void)
5983 * Set the reserved bits and the present bit of an paging-structure
5984 * entry to generate page fault with PFER.RSV = 1.
5988 * Mask the uppermost physical address bit, which would be reserved as
5989 * long as the supported physical address width is less than 52.
5993 /* Set the present bit. */
5997 * If reserved bit is not supported, clear the present bit to disable
6000 if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
6003 kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
6006 int kvm_mmu_module_init(void)
6011 * MMU roles use union aliasing which is, generally speaking, an
6012 * undefined behavior. However, we supposedly know how compilers behave
6013 * and the current status quo is unlikely to change. Guardians below are
6014 * supposed to let us know if the assumption becomes false.
6016 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6017 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6018 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6020 kvm_mmu_reset_all_pte_masks();
6022 kvm_set_mmio_spte_mask();
6024 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6025 sizeof(struct pte_list_desc),
6026 0, SLAB_ACCOUNT, NULL);
6027 if (!pte_list_desc_cache)
6030 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6031 sizeof(struct kvm_mmu_page),
6032 0, SLAB_ACCOUNT, NULL);
6033 if (!mmu_page_header_cache)
6036 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6039 ret = register_shrinker(&mmu_shrinker);
6046 mmu_destroy_caches();
6051 * Calculate mmu pages needed for kvm.
6053 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6055 unsigned long nr_mmu_pages;
6056 unsigned long nr_pages = 0;
6057 struct kvm_memslots *slots;
6058 struct kvm_memory_slot *memslot;
6061 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6062 slots = __kvm_memslots(kvm, i);
6064 kvm_for_each_memslot(memslot, slots)
6065 nr_pages += memslot->npages;
6068 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6069 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6071 return nr_mmu_pages;
6074 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6076 kvm_mmu_unload(vcpu);
6077 free_mmu_pages(vcpu);
6078 mmu_free_memory_caches(vcpu);
6081 void kvm_mmu_module_exit(void)
6083 mmu_destroy_caches();
6084 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6085 unregister_shrinker(&mmu_shrinker);
6086 mmu_audit_disable();