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 54
89 * The mask used to denote special SPTEs, which can be either MMIO SPTEs or
90 * Access Tracking SPTEs.
92 #define SPTE_SPECIAL_MASK (3ULL << 52)
93 #define SPTE_AD_ENABLED_MASK (0ULL << 52)
94 #define SPTE_AD_DISABLED_MASK (1ULL << 52)
95 #define SPTE_AD_WRPROT_ONLY_MASK (2ULL << 52)
96 #define SPTE_MMIO_MASK (3ULL << 52)
98 #define PT64_LEVEL_BITS 9
100 #define PT64_LEVEL_SHIFT(level) \
101 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
103 #define PT64_INDEX(address, level)\
104 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
107 #define PT32_LEVEL_BITS 10
109 #define PT32_LEVEL_SHIFT(level) \
110 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
112 #define PT32_LVL_OFFSET_MASK(level) \
113 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
114 * PT32_LEVEL_BITS))) - 1))
116 #define PT32_INDEX(address, level)\
117 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
120 #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
121 #define PT64_BASE_ADDR_MASK (physical_mask & ~(u64)(PAGE_SIZE-1))
123 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
125 #define PT64_LVL_ADDR_MASK(level) \
126 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
127 * PT64_LEVEL_BITS))) - 1))
128 #define PT64_LVL_OFFSET_MASK(level) \
129 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
130 * PT64_LEVEL_BITS))) - 1))
132 #define PT32_BASE_ADDR_MASK PAGE_MASK
133 #define PT32_DIR_BASE_ADDR_MASK \
134 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
135 #define PT32_LVL_ADDR_MASK(level) \
136 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
137 * PT32_LEVEL_BITS))) - 1))
139 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
140 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
142 #define ACC_EXEC_MASK 1
143 #define ACC_WRITE_MASK PT_WRITABLE_MASK
144 #define ACC_USER_MASK PT_USER_MASK
145 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
147 /* The mask for the R/X bits in EPT PTEs */
148 #define PT64_EPT_READABLE_MASK 0x1ull
149 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
151 #include <trace/events/kvm.h>
153 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
154 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
156 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
158 /* make pte_list_desc fit well in cache line */
159 #define PTE_LIST_EXT 3
162 * Return values of handle_mmio_page_fault and mmu.page_fault:
163 * RET_PF_RETRY: let CPU fault again on the address.
164 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
166 * For handle_mmio_page_fault only:
167 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
175 struct pte_list_desc {
176 u64 *sptes[PTE_LIST_EXT];
177 struct pte_list_desc *more;
180 struct kvm_shadow_walk_iterator {
188 static const union kvm_mmu_page_role mmu_base_role_mask = {
190 .gpte_is_8_bytes = 1,
199 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
200 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
202 shadow_walk_okay(&(_walker)); \
203 shadow_walk_next(&(_walker)))
205 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
206 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
207 shadow_walk_okay(&(_walker)); \
208 shadow_walk_next(&(_walker)))
210 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
211 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
212 shadow_walk_okay(&(_walker)) && \
213 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
214 __shadow_walk_next(&(_walker), spte))
216 static struct kmem_cache *pte_list_desc_cache;
217 static struct kmem_cache *mmu_page_header_cache;
218 static struct percpu_counter kvm_total_used_mmu_pages;
220 static u64 __read_mostly shadow_nx_mask;
221 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
222 static u64 __read_mostly shadow_user_mask;
223 static u64 __read_mostly shadow_accessed_mask;
224 static u64 __read_mostly shadow_dirty_mask;
225 static u64 __read_mostly shadow_mmio_mask;
226 static u64 __read_mostly shadow_mmio_value;
227 static u64 __read_mostly shadow_mmio_access_mask;
228 static u64 __read_mostly shadow_present_mask;
229 static u64 __read_mostly shadow_me_mask;
232 * SPTEs used by MMUs without A/D bits are marked with SPTE_AD_DISABLED_MASK;
233 * shadow_acc_track_mask is the set of bits to be cleared in non-accessed
236 static u64 __read_mostly shadow_acc_track_mask;
239 * The mask/shift to use for saving the original R/X bits when marking the PTE
240 * as not-present for access tracking purposes. We do not save the W bit as the
241 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
242 * restored only when a write is attempted to the page.
244 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
245 PT64_EPT_EXECUTABLE_MASK;
246 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
249 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
250 * to guard against L1TF attacks.
252 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
255 * The number of high-order 1 bits to use in the mask above.
257 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
260 * In some cases, we need to preserve the GFN of a non-present or reserved
261 * SPTE when we usurp the upper five bits of the physical address space to
262 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
263 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
264 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
265 * high and low parts. This mask covers the lower bits of the GFN.
267 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
270 * The number of non-reserved physical address bits irrespective of features
271 * that repurpose legal bits, e.g. MKTME.
273 static u8 __read_mostly shadow_phys_bits;
275 static void mmu_spte_set(u64 *sptep, u64 spte);
276 static bool is_executable_pte(u64 spte);
277 static union kvm_mmu_page_role
278 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
280 #define CREATE_TRACE_POINTS
281 #include "mmutrace.h"
284 static inline bool kvm_available_flush_tlb_with_range(void)
286 return kvm_x86_ops->tlb_remote_flush_with_range;
289 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
290 struct kvm_tlb_range *range)
294 if (range && kvm_x86_ops->tlb_remote_flush_with_range)
295 ret = kvm_x86_ops->tlb_remote_flush_with_range(kvm, range);
298 kvm_flush_remote_tlbs(kvm);
301 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
302 u64 start_gfn, u64 pages)
304 struct kvm_tlb_range range;
306 range.start_gfn = start_gfn;
309 kvm_flush_remote_tlbs_with_range(kvm, &range);
312 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value, u64 access_mask)
314 BUG_ON((u64)(unsigned)access_mask != access_mask);
315 BUG_ON((mmio_mask & mmio_value) != mmio_value);
316 shadow_mmio_value = mmio_value | SPTE_MMIO_MASK;
317 shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
318 shadow_mmio_access_mask = access_mask;
320 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
322 static bool is_mmio_spte(u64 spte)
324 return (spte & shadow_mmio_mask) == shadow_mmio_value;
327 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
329 return sp->role.ad_disabled;
332 static inline bool kvm_vcpu_ad_need_write_protect(struct kvm_vcpu *vcpu)
335 * When using the EPT page-modification log, the GPAs in the log
336 * would come from L2 rather than L1. Therefore, we need to rely
337 * on write protection to record dirty pages. This also bypasses
338 * PML, since writes now result in a vmexit.
340 return vcpu->arch.mmu == &vcpu->arch.guest_mmu;
343 static inline bool spte_ad_enabled(u64 spte)
345 MMU_WARN_ON(is_mmio_spte(spte));
346 return (spte & SPTE_SPECIAL_MASK) != SPTE_AD_DISABLED_MASK;
349 static inline bool spte_ad_need_write_protect(u64 spte)
351 MMU_WARN_ON(is_mmio_spte(spte));
352 return (spte & SPTE_SPECIAL_MASK) != SPTE_AD_ENABLED_MASK;
355 static inline u64 spte_shadow_accessed_mask(u64 spte)
357 MMU_WARN_ON(is_mmio_spte(spte));
358 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
361 static inline u64 spte_shadow_dirty_mask(u64 spte)
363 MMU_WARN_ON(is_mmio_spte(spte));
364 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
367 static inline bool is_access_track_spte(u64 spte)
369 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
373 * Due to limited space in PTEs, the MMIO generation is a 19 bit subset of
374 * the memslots generation and is derived as follows:
376 * Bits 0-8 of the MMIO generation are propagated to spte bits 3-11
377 * Bits 9-18 of the MMIO generation are propagated to spte bits 52-61
379 * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
380 * the MMIO generation number, as doing so would require stealing a bit from
381 * the "real" generation number and thus effectively halve the maximum number
382 * of MMIO generations that can be handled before encountering a wrap (which
383 * requires a full MMU zap). The flag is instead explicitly queried when
384 * checking for MMIO spte cache hits.
386 #define MMIO_SPTE_GEN_MASK GENMASK_ULL(18, 0)
388 #define MMIO_SPTE_GEN_LOW_START 3
389 #define MMIO_SPTE_GEN_LOW_END 11
390 #define MMIO_SPTE_GEN_LOW_MASK GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
391 MMIO_SPTE_GEN_LOW_START)
393 #define MMIO_SPTE_GEN_HIGH_START 52
394 #define MMIO_SPTE_GEN_HIGH_END 61
395 #define MMIO_SPTE_GEN_HIGH_MASK GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
396 MMIO_SPTE_GEN_HIGH_START)
397 static u64 generation_mmio_spte_mask(u64 gen)
401 WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
403 mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
404 mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
408 static u64 get_mmio_spte_generation(u64 spte)
412 spte &= ~shadow_mmio_mask;
414 gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
415 gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
419 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
422 u64 gen = kvm_vcpu_memslots(vcpu)->generation & MMIO_SPTE_GEN_MASK;
423 u64 mask = generation_mmio_spte_mask(gen);
424 u64 gpa = gfn << PAGE_SHIFT;
426 access &= shadow_mmio_access_mask;
427 mask |= shadow_mmio_value | access;
428 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
429 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
430 << shadow_nonpresent_or_rsvd_mask_len;
432 trace_mark_mmio_spte(sptep, gfn, access, gen);
433 mmu_spte_set(sptep, mask);
436 static gfn_t get_mmio_spte_gfn(u64 spte)
438 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
440 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
441 & shadow_nonpresent_or_rsvd_mask;
443 return gpa >> PAGE_SHIFT;
446 static unsigned get_mmio_spte_access(u64 spte)
448 return spte & shadow_mmio_access_mask;
451 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
452 kvm_pfn_t pfn, unsigned access)
454 if (unlikely(is_noslot_pfn(pfn))) {
455 mark_mmio_spte(vcpu, sptep, gfn, access);
462 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
464 u64 kvm_gen, spte_gen, gen;
466 gen = kvm_vcpu_memslots(vcpu)->generation;
467 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
470 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
471 spte_gen = get_mmio_spte_generation(spte);
473 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
474 return likely(kvm_gen == spte_gen);
478 * Sets the shadow PTE masks used by the MMU.
481 * - Setting either @accessed_mask or @dirty_mask requires setting both
482 * - At least one of @accessed_mask or @acc_track_mask must be set
484 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
485 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
486 u64 acc_track_mask, u64 me_mask)
488 BUG_ON(!dirty_mask != !accessed_mask);
489 BUG_ON(!accessed_mask && !acc_track_mask);
490 BUG_ON(acc_track_mask & SPTE_SPECIAL_MASK);
492 shadow_user_mask = user_mask;
493 shadow_accessed_mask = accessed_mask;
494 shadow_dirty_mask = dirty_mask;
495 shadow_nx_mask = nx_mask;
496 shadow_x_mask = x_mask;
497 shadow_present_mask = p_mask;
498 shadow_acc_track_mask = acc_track_mask;
499 shadow_me_mask = me_mask;
501 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
503 static u8 kvm_get_shadow_phys_bits(void)
506 * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
507 * in CPU detection code, but MKTME treats those reduced bits as
508 * 'keyID' thus they are not reserved bits. Therefore for MKTME
509 * we should still return physical address bits reported by CPUID.
511 if (!boot_cpu_has(X86_FEATURE_TME) ||
512 WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
513 return boot_cpu_data.x86_phys_bits;
515 return cpuid_eax(0x80000008) & 0xff;
518 static void kvm_mmu_reset_all_pte_masks(void)
522 shadow_user_mask = 0;
523 shadow_accessed_mask = 0;
524 shadow_dirty_mask = 0;
527 shadow_mmio_mask = 0;
528 shadow_present_mask = 0;
529 shadow_acc_track_mask = 0;
531 shadow_phys_bits = kvm_get_shadow_phys_bits();
534 * If the CPU has 46 or less physical address bits, then set an
535 * appropriate mask to guard against L1TF attacks. Otherwise, it is
536 * assumed that the CPU is not vulnerable to L1TF.
538 * Some Intel CPUs address the L1 cache using more PA bits than are
539 * reported by CPUID. Use the PA width of the L1 cache when possible
540 * to achieve more effective mitigation, e.g. if system RAM overlaps
541 * the most significant bits of legal physical address space.
543 shadow_nonpresent_or_rsvd_mask = 0;
544 low_phys_bits = boot_cpu_data.x86_cache_bits;
545 if (boot_cpu_data.x86_cache_bits <
546 52 - shadow_nonpresent_or_rsvd_mask_len) {
547 shadow_nonpresent_or_rsvd_mask =
548 rsvd_bits(boot_cpu_data.x86_cache_bits -
549 shadow_nonpresent_or_rsvd_mask_len,
550 boot_cpu_data.x86_cache_bits - 1);
551 low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
553 WARN_ON_ONCE(boot_cpu_has_bug(X86_BUG_L1TF));
555 shadow_nonpresent_or_rsvd_lower_gfn_mask =
556 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
559 static int is_cpuid_PSE36(void)
564 static int is_nx(struct kvm_vcpu *vcpu)
566 return vcpu->arch.efer & EFER_NX;
569 static int is_shadow_present_pte(u64 pte)
571 return (pte != 0) && !is_mmio_spte(pte);
574 static int is_large_pte(u64 pte)
576 return pte & PT_PAGE_SIZE_MASK;
579 static int is_last_spte(u64 pte, int level)
581 if (level == PT_PAGE_TABLE_LEVEL)
583 if (is_large_pte(pte))
588 static bool is_executable_pte(u64 spte)
590 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
593 static kvm_pfn_t spte_to_pfn(u64 pte)
595 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
598 static gfn_t pse36_gfn_delta(u32 gpte)
600 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
602 return (gpte & PT32_DIR_PSE36_MASK) << shift;
606 static void __set_spte(u64 *sptep, u64 spte)
608 WRITE_ONCE(*sptep, spte);
611 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
613 WRITE_ONCE(*sptep, spte);
616 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
618 return xchg(sptep, spte);
621 static u64 __get_spte_lockless(u64 *sptep)
623 return READ_ONCE(*sptep);
634 static void count_spte_clear(u64 *sptep, u64 spte)
636 struct kvm_mmu_page *sp = page_header(__pa(sptep));
638 if (is_shadow_present_pte(spte))
641 /* Ensure the spte is completely set before we increase the count */
643 sp->clear_spte_count++;
646 static void __set_spte(u64 *sptep, u64 spte)
648 union split_spte *ssptep, sspte;
650 ssptep = (union split_spte *)sptep;
651 sspte = (union split_spte)spte;
653 ssptep->spte_high = sspte.spte_high;
656 * If we map the spte from nonpresent to present, We should store
657 * the high bits firstly, then set present bit, so cpu can not
658 * fetch this spte while we are setting the spte.
662 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
665 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
667 union split_spte *ssptep, sspte;
669 ssptep = (union split_spte *)sptep;
670 sspte = (union split_spte)spte;
672 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
675 * If we map the spte from present to nonpresent, we should clear
676 * present bit firstly to avoid vcpu fetch the old high bits.
680 ssptep->spte_high = sspte.spte_high;
681 count_spte_clear(sptep, spte);
684 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
686 union split_spte *ssptep, sspte, orig;
688 ssptep = (union split_spte *)sptep;
689 sspte = (union split_spte)spte;
691 /* xchg acts as a barrier before the setting of the high bits */
692 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
693 orig.spte_high = ssptep->spte_high;
694 ssptep->spte_high = sspte.spte_high;
695 count_spte_clear(sptep, spte);
701 * The idea using the light way get the spte on x86_32 guest is from
702 * gup_get_pte (mm/gup.c).
704 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
705 * coalesces them and we are running out of the MMU lock. Therefore
706 * we need to protect against in-progress updates of the spte.
708 * Reading the spte while an update is in progress may get the old value
709 * for the high part of the spte. The race is fine for a present->non-present
710 * change (because the high part of the spte is ignored for non-present spte),
711 * but for a present->present change we must reread the spte.
713 * All such changes are done in two steps (present->non-present and
714 * non-present->present), hence it is enough to count the number of
715 * present->non-present updates: if it changed while reading the spte,
716 * we might have hit the race. This is done using clear_spte_count.
718 static u64 __get_spte_lockless(u64 *sptep)
720 struct kvm_mmu_page *sp = page_header(__pa(sptep));
721 union split_spte spte, *orig = (union split_spte *)sptep;
725 count = sp->clear_spte_count;
728 spte.spte_low = orig->spte_low;
731 spte.spte_high = orig->spte_high;
734 if (unlikely(spte.spte_low != orig->spte_low ||
735 count != sp->clear_spte_count))
742 static bool spte_can_locklessly_be_made_writable(u64 spte)
744 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
745 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
748 static bool spte_has_volatile_bits(u64 spte)
750 if (!is_shadow_present_pte(spte))
754 * Always atomically update spte if it can be updated
755 * out of mmu-lock, it can ensure dirty bit is not lost,
756 * also, it can help us to get a stable is_writable_pte()
757 * to ensure tlb flush is not missed.
759 if (spte_can_locklessly_be_made_writable(spte) ||
760 is_access_track_spte(spte))
763 if (spte_ad_enabled(spte)) {
764 if ((spte & shadow_accessed_mask) == 0 ||
765 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
772 static bool is_accessed_spte(u64 spte)
774 u64 accessed_mask = spte_shadow_accessed_mask(spte);
776 return accessed_mask ? spte & accessed_mask
777 : !is_access_track_spte(spte);
780 static bool is_dirty_spte(u64 spte)
782 u64 dirty_mask = spte_shadow_dirty_mask(spte);
784 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
787 /* Rules for using mmu_spte_set:
788 * Set the sptep from nonpresent to present.
789 * Note: the sptep being assigned *must* be either not present
790 * or in a state where the hardware will not attempt to update
793 static void mmu_spte_set(u64 *sptep, u64 new_spte)
795 WARN_ON(is_shadow_present_pte(*sptep));
796 __set_spte(sptep, new_spte);
800 * Update the SPTE (excluding the PFN), but do not track changes in its
801 * accessed/dirty status.
803 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
805 u64 old_spte = *sptep;
807 WARN_ON(!is_shadow_present_pte(new_spte));
809 if (!is_shadow_present_pte(old_spte)) {
810 mmu_spte_set(sptep, new_spte);
814 if (!spte_has_volatile_bits(old_spte))
815 __update_clear_spte_fast(sptep, new_spte);
817 old_spte = __update_clear_spte_slow(sptep, new_spte);
819 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
824 /* Rules for using mmu_spte_update:
825 * Update the state bits, it means the mapped pfn is not changed.
827 * Whenever we overwrite a writable spte with a read-only one we
828 * should flush remote TLBs. Otherwise rmap_write_protect
829 * will find a read-only spte, even though the writable spte
830 * might be cached on a CPU's TLB, the return value indicates this
833 * Returns true if the TLB needs to be flushed
835 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
838 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
840 if (!is_shadow_present_pte(old_spte))
844 * For the spte updated out of mmu-lock is safe, since
845 * we always atomically update it, see the comments in
846 * spte_has_volatile_bits().
848 if (spte_can_locklessly_be_made_writable(old_spte) &&
849 !is_writable_pte(new_spte))
853 * Flush TLB when accessed/dirty states are changed in the page tables,
854 * to guarantee consistency between TLB and page tables.
857 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
859 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
862 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
864 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
871 * Rules for using mmu_spte_clear_track_bits:
872 * It sets the sptep from present to nonpresent, and track the
873 * state bits, it is used to clear the last level sptep.
874 * Returns non-zero if the PTE was previously valid.
876 static int mmu_spte_clear_track_bits(u64 *sptep)
879 u64 old_spte = *sptep;
881 if (!spte_has_volatile_bits(old_spte))
882 __update_clear_spte_fast(sptep, 0ull);
884 old_spte = __update_clear_spte_slow(sptep, 0ull);
886 if (!is_shadow_present_pte(old_spte))
889 pfn = spte_to_pfn(old_spte);
892 * KVM does not hold the refcount of the page used by
893 * kvm mmu, before reclaiming the page, we should
894 * unmap it from mmu first.
896 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
898 if (is_accessed_spte(old_spte))
899 kvm_set_pfn_accessed(pfn);
901 if (is_dirty_spte(old_spte))
902 kvm_set_pfn_dirty(pfn);
908 * Rules for using mmu_spte_clear_no_track:
909 * Directly clear spte without caring the state bits of sptep,
910 * it is used to set the upper level spte.
912 static void mmu_spte_clear_no_track(u64 *sptep)
914 __update_clear_spte_fast(sptep, 0ull);
917 static u64 mmu_spte_get_lockless(u64 *sptep)
919 return __get_spte_lockless(sptep);
922 static u64 mark_spte_for_access_track(u64 spte)
924 if (spte_ad_enabled(spte))
925 return spte & ~shadow_accessed_mask;
927 if (is_access_track_spte(spte))
931 * Making an Access Tracking PTE will result in removal of write access
932 * from the PTE. So, verify that we will be able to restore the write
933 * access in the fast page fault path later on.
935 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
936 !spte_can_locklessly_be_made_writable(spte),
937 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
939 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
940 shadow_acc_track_saved_bits_shift),
941 "kvm: Access Tracking saved bit locations are not zero\n");
943 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
944 shadow_acc_track_saved_bits_shift;
945 spte &= ~shadow_acc_track_mask;
950 /* Restore an acc-track PTE back to a regular PTE */
951 static u64 restore_acc_track_spte(u64 spte)
954 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
955 & shadow_acc_track_saved_bits_mask;
957 WARN_ON_ONCE(spte_ad_enabled(spte));
958 WARN_ON_ONCE(!is_access_track_spte(spte));
960 new_spte &= ~shadow_acc_track_mask;
961 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
962 shadow_acc_track_saved_bits_shift);
963 new_spte |= saved_bits;
968 /* Returns the Accessed status of the PTE and resets it at the same time. */
969 static bool mmu_spte_age(u64 *sptep)
971 u64 spte = mmu_spte_get_lockless(sptep);
973 if (!is_accessed_spte(spte))
976 if (spte_ad_enabled(spte)) {
977 clear_bit((ffs(shadow_accessed_mask) - 1),
978 (unsigned long *)sptep);
981 * Capture the dirty status of the page, so that it doesn't get
982 * lost when the SPTE is marked for access tracking.
984 if (is_writable_pte(spte))
985 kvm_set_pfn_dirty(spte_to_pfn(spte));
987 spte = mark_spte_for_access_track(spte);
988 mmu_spte_update_no_track(sptep, spte);
994 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
997 * Prevent page table teardown by making any free-er wait during
998 * kvm_flush_remote_tlbs() IPI to all active vcpus.
1000 local_irq_disable();
1003 * Make sure a following spte read is not reordered ahead of the write
1006 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
1009 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
1012 * Make sure the write to vcpu->mode is not reordered in front of
1013 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
1014 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
1016 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
1020 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
1021 struct kmem_cache *base_cache, int min)
1025 if (cache->nobjs >= min)
1027 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1028 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL_ACCOUNT);
1030 return cache->nobjs >= min ? 0 : -ENOMEM;
1031 cache->objects[cache->nobjs++] = obj;
1036 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
1038 return cache->nobjs;
1041 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
1042 struct kmem_cache *cache)
1045 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
1048 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1053 if (cache->nobjs >= min)
1055 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1056 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1058 return cache->nobjs >= min ? 0 : -ENOMEM;
1059 cache->objects[cache->nobjs++] = page;
1064 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1067 free_page((unsigned long)mc->objects[--mc->nobjs]);
1070 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1074 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1075 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1078 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1081 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1082 mmu_page_header_cache, 4);
1087 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1089 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1090 pte_list_desc_cache);
1091 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1092 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1093 mmu_page_header_cache);
1096 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1101 p = mc->objects[--mc->nobjs];
1105 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1107 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1110 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1112 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1115 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1117 if (!sp->role.direct)
1118 return sp->gfns[index];
1120 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1123 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1125 if (!sp->role.direct) {
1126 sp->gfns[index] = gfn;
1130 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1131 pr_err_ratelimited("gfn mismatch under direct page %llx "
1132 "(expected %llx, got %llx)\n",
1134 kvm_mmu_page_get_gfn(sp, index), gfn);
1138 * Return the pointer to the large page information for a given gfn,
1139 * handling slots that are not large page aligned.
1141 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1142 struct kvm_memory_slot *slot,
1147 idx = gfn_to_index(gfn, slot->base_gfn, level);
1148 return &slot->arch.lpage_info[level - 2][idx];
1151 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1152 gfn_t gfn, int count)
1154 struct kvm_lpage_info *linfo;
1157 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1158 linfo = lpage_info_slot(gfn, slot, i);
1159 linfo->disallow_lpage += count;
1160 WARN_ON(linfo->disallow_lpage < 0);
1164 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1166 update_gfn_disallow_lpage_count(slot, gfn, 1);
1169 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1171 update_gfn_disallow_lpage_count(slot, gfn, -1);
1174 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1176 struct kvm_memslots *slots;
1177 struct kvm_memory_slot *slot;
1180 kvm->arch.indirect_shadow_pages++;
1182 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1183 slot = __gfn_to_memslot(slots, gfn);
1185 /* the non-leaf shadow pages are keeping readonly. */
1186 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1187 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1188 KVM_PAGE_TRACK_WRITE);
1190 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1193 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1195 struct kvm_memslots *slots;
1196 struct kvm_memory_slot *slot;
1199 kvm->arch.indirect_shadow_pages--;
1201 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1202 slot = __gfn_to_memslot(slots, gfn);
1203 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1204 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1205 KVM_PAGE_TRACK_WRITE);
1207 kvm_mmu_gfn_allow_lpage(slot, gfn);
1210 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1211 struct kvm_memory_slot *slot)
1213 struct kvm_lpage_info *linfo;
1216 linfo = lpage_info_slot(gfn, slot, level);
1217 return !!linfo->disallow_lpage;
1223 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1226 struct kvm_memory_slot *slot;
1228 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1229 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1232 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1234 unsigned long page_size;
1237 page_size = kvm_host_page_size(kvm, gfn);
1239 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1240 if (page_size >= KVM_HPAGE_SIZE(i))
1249 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1252 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1254 if (no_dirty_log && slot->dirty_bitmap)
1260 static struct kvm_memory_slot *
1261 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1264 struct kvm_memory_slot *slot;
1266 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1267 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1273 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1274 bool *force_pt_level)
1276 int host_level, level, max_level;
1277 struct kvm_memory_slot *slot;
1279 if (unlikely(*force_pt_level))
1280 return PT_PAGE_TABLE_LEVEL;
1282 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1283 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1284 if (unlikely(*force_pt_level))
1285 return PT_PAGE_TABLE_LEVEL;
1287 host_level = host_mapping_level(vcpu->kvm, large_gfn);
1289 if (host_level == PT_PAGE_TABLE_LEVEL)
1292 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1294 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1295 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1302 * About rmap_head encoding:
1304 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1305 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1306 * pte_list_desc containing more mappings.
1310 * Returns the number of pointers in the rmap chain, not counting the new one.
1312 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1313 struct kvm_rmap_head *rmap_head)
1315 struct pte_list_desc *desc;
1318 if (!rmap_head->val) {
1319 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1320 rmap_head->val = (unsigned long)spte;
1321 } else if (!(rmap_head->val & 1)) {
1322 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1323 desc = mmu_alloc_pte_list_desc(vcpu);
1324 desc->sptes[0] = (u64 *)rmap_head->val;
1325 desc->sptes[1] = spte;
1326 rmap_head->val = (unsigned long)desc | 1;
1329 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1330 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1331 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1333 count += PTE_LIST_EXT;
1335 if (desc->sptes[PTE_LIST_EXT-1]) {
1336 desc->more = mmu_alloc_pte_list_desc(vcpu);
1339 for (i = 0; desc->sptes[i]; ++i)
1341 desc->sptes[i] = spte;
1347 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1348 struct pte_list_desc *desc, int i,
1349 struct pte_list_desc *prev_desc)
1353 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1355 desc->sptes[i] = desc->sptes[j];
1356 desc->sptes[j] = NULL;
1359 if (!prev_desc && !desc->more)
1360 rmap_head->val = (unsigned long)desc->sptes[0];
1363 prev_desc->more = desc->more;
1365 rmap_head->val = (unsigned long)desc->more | 1;
1366 mmu_free_pte_list_desc(desc);
1369 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1371 struct pte_list_desc *desc;
1372 struct pte_list_desc *prev_desc;
1375 if (!rmap_head->val) {
1376 pr_err("%s: %p 0->BUG\n", __func__, spte);
1378 } else if (!(rmap_head->val & 1)) {
1379 rmap_printk("%s: %p 1->0\n", __func__, spte);
1380 if ((u64 *)rmap_head->val != spte) {
1381 pr_err("%s: %p 1->BUG\n", __func__, spte);
1386 rmap_printk("%s: %p many->many\n", __func__, spte);
1387 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1390 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1391 if (desc->sptes[i] == spte) {
1392 pte_list_desc_remove_entry(rmap_head,
1393 desc, i, prev_desc);
1400 pr_err("%s: %p many->many\n", __func__, spte);
1405 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1407 mmu_spte_clear_track_bits(sptep);
1408 __pte_list_remove(sptep, rmap_head);
1411 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1412 struct kvm_memory_slot *slot)
1416 idx = gfn_to_index(gfn, slot->base_gfn, level);
1417 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1420 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1421 struct kvm_mmu_page *sp)
1423 struct kvm_memslots *slots;
1424 struct kvm_memory_slot *slot;
1426 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1427 slot = __gfn_to_memslot(slots, gfn);
1428 return __gfn_to_rmap(gfn, sp->role.level, slot);
1431 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1433 struct kvm_mmu_memory_cache *cache;
1435 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1436 return mmu_memory_cache_free_objects(cache);
1439 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1441 struct kvm_mmu_page *sp;
1442 struct kvm_rmap_head *rmap_head;
1444 sp = page_header(__pa(spte));
1445 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1446 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1447 return pte_list_add(vcpu, spte, rmap_head);
1450 static void rmap_remove(struct kvm *kvm, u64 *spte)
1452 struct kvm_mmu_page *sp;
1454 struct kvm_rmap_head *rmap_head;
1456 sp = page_header(__pa(spte));
1457 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1458 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1459 __pte_list_remove(spte, rmap_head);
1463 * Used by the following functions to iterate through the sptes linked by a
1464 * rmap. All fields are private and not assumed to be used outside.
1466 struct rmap_iterator {
1467 /* private fields */
1468 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1469 int pos; /* index of the sptep */
1473 * Iteration must be started by this function. This should also be used after
1474 * removing/dropping sptes from the rmap link because in such cases the
1475 * information in the itererator may not be valid.
1477 * Returns sptep if found, NULL otherwise.
1479 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1480 struct rmap_iterator *iter)
1484 if (!rmap_head->val)
1487 if (!(rmap_head->val & 1)) {
1489 sptep = (u64 *)rmap_head->val;
1493 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1495 sptep = iter->desc->sptes[iter->pos];
1497 BUG_ON(!is_shadow_present_pte(*sptep));
1502 * Must be used with a valid iterator: e.g. after rmap_get_first().
1504 * Returns sptep if found, NULL otherwise.
1506 static u64 *rmap_get_next(struct rmap_iterator *iter)
1511 if (iter->pos < PTE_LIST_EXT - 1) {
1513 sptep = iter->desc->sptes[iter->pos];
1518 iter->desc = iter->desc->more;
1522 /* desc->sptes[0] cannot be NULL */
1523 sptep = iter->desc->sptes[iter->pos];
1530 BUG_ON(!is_shadow_present_pte(*sptep));
1534 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1535 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1536 _spte_; _spte_ = rmap_get_next(_iter_))
1538 static void drop_spte(struct kvm *kvm, u64 *sptep)
1540 if (mmu_spte_clear_track_bits(sptep))
1541 rmap_remove(kvm, sptep);
1545 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1547 if (is_large_pte(*sptep)) {
1548 WARN_ON(page_header(__pa(sptep))->role.level ==
1549 PT_PAGE_TABLE_LEVEL);
1550 drop_spte(kvm, sptep);
1558 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1560 if (__drop_large_spte(vcpu->kvm, sptep)) {
1561 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1563 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1564 KVM_PAGES_PER_HPAGE(sp->role.level));
1569 * Write-protect on the specified @sptep, @pt_protect indicates whether
1570 * spte write-protection is caused by protecting shadow page table.
1572 * Note: write protection is difference between dirty logging and spte
1574 * - for dirty logging, the spte can be set to writable at anytime if
1575 * its dirty bitmap is properly set.
1576 * - for spte protection, the spte can be writable only after unsync-ing
1579 * Return true if tlb need be flushed.
1581 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1585 if (!is_writable_pte(spte) &&
1586 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1589 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1592 spte &= ~SPTE_MMU_WRITEABLE;
1593 spte = spte & ~PT_WRITABLE_MASK;
1595 return mmu_spte_update(sptep, spte);
1598 static bool __rmap_write_protect(struct kvm *kvm,
1599 struct kvm_rmap_head *rmap_head,
1603 struct rmap_iterator iter;
1606 for_each_rmap_spte(rmap_head, &iter, sptep)
1607 flush |= spte_write_protect(sptep, pt_protect);
1612 static bool spte_clear_dirty(u64 *sptep)
1616 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1618 MMU_WARN_ON(!spte_ad_enabled(spte));
1619 spte &= ~shadow_dirty_mask;
1620 return mmu_spte_update(sptep, spte);
1623 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1625 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1626 (unsigned long *)sptep);
1627 if (was_writable && !spte_ad_enabled(*sptep))
1628 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1630 return was_writable;
1634 * Gets the GFN ready for another round of dirty logging by clearing the
1635 * - D bit on ad-enabled SPTEs, and
1636 * - W bit on ad-disabled SPTEs.
1637 * Returns true iff any D or W bits were cleared.
1639 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1642 struct rmap_iterator iter;
1645 for_each_rmap_spte(rmap_head, &iter, sptep)
1646 if (spte_ad_need_write_protect(*sptep))
1647 flush |= spte_wrprot_for_clear_dirty(sptep);
1649 flush |= spte_clear_dirty(sptep);
1654 static bool spte_set_dirty(u64 *sptep)
1658 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1661 * Similar to the !kvm_x86_ops->slot_disable_log_dirty case,
1662 * do not bother adding back write access to pages marked
1663 * SPTE_AD_WRPROT_ONLY_MASK.
1665 spte |= shadow_dirty_mask;
1667 return mmu_spte_update(sptep, spte);
1670 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1673 struct rmap_iterator iter;
1676 for_each_rmap_spte(rmap_head, &iter, sptep)
1677 if (spte_ad_enabled(*sptep))
1678 flush |= spte_set_dirty(sptep);
1684 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1685 * @kvm: kvm instance
1686 * @slot: slot to protect
1687 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1688 * @mask: indicates which pages we should protect
1690 * Used when we do not need to care about huge page mappings: e.g. during dirty
1691 * logging we do not have any such mappings.
1693 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1694 struct kvm_memory_slot *slot,
1695 gfn_t gfn_offset, unsigned long mask)
1697 struct kvm_rmap_head *rmap_head;
1700 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1701 PT_PAGE_TABLE_LEVEL, slot);
1702 __rmap_write_protect(kvm, rmap_head, false);
1704 /* clear the first set bit */
1710 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1711 * protect the page if the D-bit isn't supported.
1712 * @kvm: kvm instance
1713 * @slot: slot to clear D-bit
1714 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1715 * @mask: indicates which pages we should clear D-bit
1717 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1719 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1720 struct kvm_memory_slot *slot,
1721 gfn_t gfn_offset, unsigned long mask)
1723 struct kvm_rmap_head *rmap_head;
1726 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1727 PT_PAGE_TABLE_LEVEL, slot);
1728 __rmap_clear_dirty(kvm, rmap_head);
1730 /* clear the first set bit */
1734 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1737 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1740 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1741 * enable dirty logging for them.
1743 * Used when we do not need to care about huge page mappings: e.g. during dirty
1744 * logging we do not have any such mappings.
1746 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1747 struct kvm_memory_slot *slot,
1748 gfn_t gfn_offset, unsigned long mask)
1750 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1751 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1754 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1758 * kvm_arch_write_log_dirty - emulate dirty page logging
1759 * @vcpu: Guest mode vcpu
1761 * Emulate arch specific page modification logging for the
1764 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1766 if (kvm_x86_ops->write_log_dirty)
1767 return kvm_x86_ops->write_log_dirty(vcpu);
1772 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1773 struct kvm_memory_slot *slot, u64 gfn)
1775 struct kvm_rmap_head *rmap_head;
1777 bool write_protected = false;
1779 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1780 rmap_head = __gfn_to_rmap(gfn, i, slot);
1781 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1784 return write_protected;
1787 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1789 struct kvm_memory_slot *slot;
1791 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1792 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1795 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1798 struct rmap_iterator iter;
1801 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1802 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1804 pte_list_remove(rmap_head, sptep);
1811 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1812 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1815 return kvm_zap_rmapp(kvm, rmap_head);
1818 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1819 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1823 struct rmap_iterator iter;
1826 pte_t *ptep = (pte_t *)data;
1829 WARN_ON(pte_huge(*ptep));
1830 new_pfn = pte_pfn(*ptep);
1833 for_each_rmap_spte(rmap_head, &iter, sptep) {
1834 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1835 sptep, *sptep, gfn, level);
1839 if (pte_write(*ptep)) {
1840 pte_list_remove(rmap_head, sptep);
1843 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1844 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1846 new_spte &= ~PT_WRITABLE_MASK;
1847 new_spte &= ~SPTE_HOST_WRITEABLE;
1849 new_spte = mark_spte_for_access_track(new_spte);
1851 mmu_spte_clear_track_bits(sptep);
1852 mmu_spte_set(sptep, new_spte);
1856 if (need_flush && kvm_available_flush_tlb_with_range()) {
1857 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1864 struct slot_rmap_walk_iterator {
1866 struct kvm_memory_slot *slot;
1872 /* output fields. */
1874 struct kvm_rmap_head *rmap;
1877 /* private field. */
1878 struct kvm_rmap_head *end_rmap;
1882 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1884 iterator->level = level;
1885 iterator->gfn = iterator->start_gfn;
1886 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1887 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1892 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1893 struct kvm_memory_slot *slot, int start_level,
1894 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1896 iterator->slot = slot;
1897 iterator->start_level = start_level;
1898 iterator->end_level = end_level;
1899 iterator->start_gfn = start_gfn;
1900 iterator->end_gfn = end_gfn;
1902 rmap_walk_init_level(iterator, iterator->start_level);
1905 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1907 return !!iterator->rmap;
1910 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1912 if (++iterator->rmap <= iterator->end_rmap) {
1913 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1917 if (++iterator->level > iterator->end_level) {
1918 iterator->rmap = NULL;
1922 rmap_walk_init_level(iterator, iterator->level);
1925 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1926 _start_gfn, _end_gfn, _iter_) \
1927 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1928 _end_level_, _start_gfn, _end_gfn); \
1929 slot_rmap_walk_okay(_iter_); \
1930 slot_rmap_walk_next(_iter_))
1932 static int kvm_handle_hva_range(struct kvm *kvm,
1933 unsigned long start,
1936 int (*handler)(struct kvm *kvm,
1937 struct kvm_rmap_head *rmap_head,
1938 struct kvm_memory_slot *slot,
1941 unsigned long data))
1943 struct kvm_memslots *slots;
1944 struct kvm_memory_slot *memslot;
1945 struct slot_rmap_walk_iterator iterator;
1949 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1950 slots = __kvm_memslots(kvm, i);
1951 kvm_for_each_memslot(memslot, slots) {
1952 unsigned long hva_start, hva_end;
1953 gfn_t gfn_start, gfn_end;
1955 hva_start = max(start, memslot->userspace_addr);
1956 hva_end = min(end, memslot->userspace_addr +
1957 (memslot->npages << PAGE_SHIFT));
1958 if (hva_start >= hva_end)
1961 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1962 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1964 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1965 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1967 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1968 PT_MAX_HUGEPAGE_LEVEL,
1969 gfn_start, gfn_end - 1,
1971 ret |= handler(kvm, iterator.rmap, memslot,
1972 iterator.gfn, iterator.level, data);
1979 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1981 int (*handler)(struct kvm *kvm,
1982 struct kvm_rmap_head *rmap_head,
1983 struct kvm_memory_slot *slot,
1984 gfn_t gfn, int level,
1985 unsigned long data))
1987 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1990 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1992 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1995 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1997 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
2000 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
2001 struct kvm_memory_slot *slot, gfn_t gfn, int level,
2005 struct rmap_iterator uninitialized_var(iter);
2008 for_each_rmap_spte(rmap_head, &iter, sptep)
2009 young |= mmu_spte_age(sptep);
2011 trace_kvm_age_page(gfn, level, slot, young);
2015 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
2016 struct kvm_memory_slot *slot, gfn_t gfn,
2017 int level, unsigned long data)
2020 struct rmap_iterator iter;
2022 for_each_rmap_spte(rmap_head, &iter, sptep)
2023 if (is_accessed_spte(*sptep))
2028 #define RMAP_RECYCLE_THRESHOLD 1000
2030 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2032 struct kvm_rmap_head *rmap_head;
2033 struct kvm_mmu_page *sp;
2035 sp = page_header(__pa(spte));
2037 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2039 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2040 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
2041 KVM_PAGES_PER_HPAGE(sp->role.level));
2044 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2046 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2049 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2051 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2055 static int is_empty_shadow_page(u64 *spt)
2060 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2061 if (is_shadow_present_pte(*pos)) {
2062 printk(KERN_ERR "%s: %p %llx\n", __func__,
2071 * This value is the sum of all of the kvm instances's
2072 * kvm->arch.n_used_mmu_pages values. We need a global,
2073 * aggregate version in order to make the slab shrinker
2076 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2078 kvm->arch.n_used_mmu_pages += nr;
2079 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2082 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2084 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2085 hlist_del(&sp->hash_link);
2086 list_del(&sp->link);
2087 free_page((unsigned long)sp->spt);
2088 if (!sp->role.direct)
2089 free_page((unsigned long)sp->gfns);
2090 kmem_cache_free(mmu_page_header_cache, sp);
2093 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2095 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2098 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2099 struct kvm_mmu_page *sp, u64 *parent_pte)
2104 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2107 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2110 __pte_list_remove(parent_pte, &sp->parent_ptes);
2113 static void drop_parent_pte(struct kvm_mmu_page *sp,
2116 mmu_page_remove_parent_pte(sp, parent_pte);
2117 mmu_spte_clear_no_track(parent_pte);
2120 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2122 struct kvm_mmu_page *sp;
2124 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2125 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2127 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2128 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2131 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2132 * depends on valid pages being added to the head of the list. See
2133 * comments in kvm_zap_obsolete_pages().
2135 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2136 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2137 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2141 static void mark_unsync(u64 *spte);
2142 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2145 struct rmap_iterator iter;
2147 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2152 static void mark_unsync(u64 *spte)
2154 struct kvm_mmu_page *sp;
2157 sp = page_header(__pa(spte));
2158 index = spte - sp->spt;
2159 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2161 if (sp->unsync_children++)
2163 kvm_mmu_mark_parents_unsync(sp);
2166 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2167 struct kvm_mmu_page *sp)
2172 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2176 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2177 struct kvm_mmu_page *sp, u64 *spte,
2183 #define KVM_PAGE_ARRAY_NR 16
2185 struct kvm_mmu_pages {
2186 struct mmu_page_and_offset {
2187 struct kvm_mmu_page *sp;
2189 } page[KVM_PAGE_ARRAY_NR];
2193 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2199 for (i=0; i < pvec->nr; i++)
2200 if (pvec->page[i].sp == sp)
2203 pvec->page[pvec->nr].sp = sp;
2204 pvec->page[pvec->nr].idx = idx;
2206 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2209 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2211 --sp->unsync_children;
2212 WARN_ON((int)sp->unsync_children < 0);
2213 __clear_bit(idx, sp->unsync_child_bitmap);
2216 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2217 struct kvm_mmu_pages *pvec)
2219 int i, ret, nr_unsync_leaf = 0;
2221 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2222 struct kvm_mmu_page *child;
2223 u64 ent = sp->spt[i];
2225 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2226 clear_unsync_child_bit(sp, i);
2230 child = page_header(ent & PT64_BASE_ADDR_MASK);
2232 if (child->unsync_children) {
2233 if (mmu_pages_add(pvec, child, i))
2236 ret = __mmu_unsync_walk(child, pvec);
2238 clear_unsync_child_bit(sp, i);
2240 } else if (ret > 0) {
2241 nr_unsync_leaf += ret;
2244 } else if (child->unsync) {
2246 if (mmu_pages_add(pvec, child, i))
2249 clear_unsync_child_bit(sp, i);
2252 return nr_unsync_leaf;
2255 #define INVALID_INDEX (-1)
2257 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2258 struct kvm_mmu_pages *pvec)
2261 if (!sp->unsync_children)
2264 mmu_pages_add(pvec, sp, INVALID_INDEX);
2265 return __mmu_unsync_walk(sp, pvec);
2268 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2270 WARN_ON(!sp->unsync);
2271 trace_kvm_mmu_sync_page(sp);
2273 --kvm->stat.mmu_unsync;
2276 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2277 struct list_head *invalid_list);
2278 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2279 struct list_head *invalid_list);
2282 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2283 hlist_for_each_entry(_sp, \
2284 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2285 if (is_obsolete_sp((_kvm), (_sp))) { \
2288 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2289 for_each_valid_sp(_kvm, _sp, _gfn) \
2290 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2292 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2294 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2297 /* @sp->gfn should be write-protected at the call site */
2298 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2299 struct list_head *invalid_list)
2301 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2302 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2303 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2310 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2311 struct list_head *invalid_list,
2314 if (!remote_flush && list_empty(invalid_list))
2317 if (!list_empty(invalid_list))
2318 kvm_mmu_commit_zap_page(kvm, invalid_list);
2320 kvm_flush_remote_tlbs(kvm);
2324 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2325 struct list_head *invalid_list,
2326 bool remote_flush, bool local_flush)
2328 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2332 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2335 #ifdef CONFIG_KVM_MMU_AUDIT
2336 #include "mmu_audit.c"
2338 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2339 static void mmu_audit_disable(void) { }
2342 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2344 return sp->role.invalid ||
2345 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2348 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2349 struct list_head *invalid_list)
2351 kvm_unlink_unsync_page(vcpu->kvm, sp);
2352 return __kvm_sync_page(vcpu, sp, invalid_list);
2355 /* @gfn should be write-protected at the call site */
2356 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2357 struct list_head *invalid_list)
2359 struct kvm_mmu_page *s;
2362 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2366 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2367 ret |= kvm_sync_page(vcpu, s, invalid_list);
2373 struct mmu_page_path {
2374 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2375 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2378 #define for_each_sp(pvec, sp, parents, i) \
2379 for (i = mmu_pages_first(&pvec, &parents); \
2380 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2381 i = mmu_pages_next(&pvec, &parents, i))
2383 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2384 struct mmu_page_path *parents,
2389 for (n = i+1; n < pvec->nr; n++) {
2390 struct kvm_mmu_page *sp = pvec->page[n].sp;
2391 unsigned idx = pvec->page[n].idx;
2392 int level = sp->role.level;
2394 parents->idx[level-1] = idx;
2395 if (level == PT_PAGE_TABLE_LEVEL)
2398 parents->parent[level-2] = sp;
2404 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2405 struct mmu_page_path *parents)
2407 struct kvm_mmu_page *sp;
2413 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2415 sp = pvec->page[0].sp;
2416 level = sp->role.level;
2417 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2419 parents->parent[level-2] = sp;
2421 /* Also set up a sentinel. Further entries in pvec are all
2422 * children of sp, so this element is never overwritten.
2424 parents->parent[level-1] = NULL;
2425 return mmu_pages_next(pvec, parents, 0);
2428 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2430 struct kvm_mmu_page *sp;
2431 unsigned int level = 0;
2434 unsigned int idx = parents->idx[level];
2435 sp = parents->parent[level];
2439 WARN_ON(idx == INVALID_INDEX);
2440 clear_unsync_child_bit(sp, idx);
2442 } while (!sp->unsync_children);
2445 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2446 struct kvm_mmu_page *parent)
2449 struct kvm_mmu_page *sp;
2450 struct mmu_page_path parents;
2451 struct kvm_mmu_pages pages;
2452 LIST_HEAD(invalid_list);
2455 while (mmu_unsync_walk(parent, &pages)) {
2456 bool protected = false;
2458 for_each_sp(pages, sp, parents, i)
2459 protected |= rmap_write_protect(vcpu, sp->gfn);
2462 kvm_flush_remote_tlbs(vcpu->kvm);
2466 for_each_sp(pages, sp, parents, i) {
2467 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2468 mmu_pages_clear_parents(&parents);
2470 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2471 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2472 cond_resched_lock(&vcpu->kvm->mmu_lock);
2477 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2480 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2482 atomic_set(&sp->write_flooding_count, 0);
2485 static void clear_sp_write_flooding_count(u64 *spte)
2487 struct kvm_mmu_page *sp = page_header(__pa(spte));
2489 __clear_sp_write_flooding_count(sp);
2492 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2499 union kvm_mmu_page_role role;
2501 struct kvm_mmu_page *sp;
2502 bool need_sync = false;
2505 LIST_HEAD(invalid_list);
2507 role = vcpu->arch.mmu->mmu_role.base;
2509 role.direct = direct;
2511 role.gpte_is_8_bytes = true;
2512 role.access = access;
2513 if (!vcpu->arch.mmu->direct_map
2514 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2515 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2516 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2517 role.quadrant = quadrant;
2519 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2520 if (sp->gfn != gfn) {
2525 if (!need_sync && sp->unsync)
2528 if (sp->role.word != role.word)
2532 /* The page is good, but __kvm_sync_page might still end
2533 * up zapping it. If so, break in order to rebuild it.
2535 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2538 WARN_ON(!list_empty(&invalid_list));
2539 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2542 if (sp->unsync_children)
2543 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2545 __clear_sp_write_flooding_count(sp);
2546 trace_kvm_mmu_get_page(sp, false);
2550 ++vcpu->kvm->stat.mmu_cache_miss;
2552 sp = kvm_mmu_alloc_page(vcpu, direct);
2556 hlist_add_head(&sp->hash_link,
2557 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2560 * we should do write protection before syncing pages
2561 * otherwise the content of the synced shadow page may
2562 * be inconsistent with guest page table.
2564 account_shadowed(vcpu->kvm, sp);
2565 if (level == PT_PAGE_TABLE_LEVEL &&
2566 rmap_write_protect(vcpu, gfn))
2567 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2569 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2570 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2572 clear_page(sp->spt);
2573 trace_kvm_mmu_get_page(sp, true);
2575 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2577 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2578 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2582 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2583 struct kvm_vcpu *vcpu, hpa_t root,
2586 iterator->addr = addr;
2587 iterator->shadow_addr = root;
2588 iterator->level = vcpu->arch.mmu->shadow_root_level;
2590 if (iterator->level == PT64_ROOT_4LEVEL &&
2591 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2592 !vcpu->arch.mmu->direct_map)
2595 if (iterator->level == PT32E_ROOT_LEVEL) {
2597 * prev_root is currently only used for 64-bit hosts. So only
2598 * the active root_hpa is valid here.
2600 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2602 iterator->shadow_addr
2603 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2604 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2606 if (!iterator->shadow_addr)
2607 iterator->level = 0;
2611 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2612 struct kvm_vcpu *vcpu, u64 addr)
2614 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2618 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2620 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2623 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2624 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2628 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2631 if (is_last_spte(spte, iterator->level)) {
2632 iterator->level = 0;
2636 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2640 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2642 __shadow_walk_next(iterator, *iterator->sptep);
2645 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2646 struct kvm_mmu_page *sp)
2650 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2652 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2653 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2655 if (sp_ad_disabled(sp))
2656 spte |= SPTE_AD_DISABLED_MASK;
2658 spte |= shadow_accessed_mask;
2660 mmu_spte_set(sptep, spte);
2662 mmu_page_add_parent_pte(vcpu, sp, sptep);
2664 if (sp->unsync_children || sp->unsync)
2668 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2669 unsigned direct_access)
2671 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2672 struct kvm_mmu_page *child;
2675 * For the direct sp, if the guest pte's dirty bit
2676 * changed form clean to dirty, it will corrupt the
2677 * sp's access: allow writable in the read-only sp,
2678 * so we should update the spte at this point to get
2679 * a new sp with the correct access.
2681 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2682 if (child->role.access == direct_access)
2685 drop_parent_pte(child, sptep);
2686 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2690 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2694 struct kvm_mmu_page *child;
2697 if (is_shadow_present_pte(pte)) {
2698 if (is_last_spte(pte, sp->role.level)) {
2699 drop_spte(kvm, spte);
2700 if (is_large_pte(pte))
2703 child = page_header(pte & PT64_BASE_ADDR_MASK);
2704 drop_parent_pte(child, spte);
2709 if (is_mmio_spte(pte))
2710 mmu_spte_clear_no_track(spte);
2715 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2716 struct kvm_mmu_page *sp)
2720 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2721 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2724 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2727 struct rmap_iterator iter;
2729 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2730 drop_parent_pte(sp, sptep);
2733 static int mmu_zap_unsync_children(struct kvm *kvm,
2734 struct kvm_mmu_page *parent,
2735 struct list_head *invalid_list)
2738 struct mmu_page_path parents;
2739 struct kvm_mmu_pages pages;
2741 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2744 while (mmu_unsync_walk(parent, &pages)) {
2745 struct kvm_mmu_page *sp;
2747 for_each_sp(pages, sp, parents, i) {
2748 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2749 mmu_pages_clear_parents(&parents);
2757 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2758 struct kvm_mmu_page *sp,
2759 struct list_head *invalid_list,
2764 trace_kvm_mmu_prepare_zap_page(sp);
2765 ++kvm->stat.mmu_shadow_zapped;
2766 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2767 kvm_mmu_page_unlink_children(kvm, sp);
2768 kvm_mmu_unlink_parents(kvm, sp);
2770 /* Zapping children means active_mmu_pages has become unstable. */
2771 list_unstable = *nr_zapped;
2773 if (!sp->role.invalid && !sp->role.direct)
2774 unaccount_shadowed(kvm, sp);
2777 kvm_unlink_unsync_page(kvm, sp);
2778 if (!sp->root_count) {
2781 list_move(&sp->link, invalid_list);
2782 kvm_mod_used_mmu_pages(kvm, -1);
2784 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2787 * Obsolete pages cannot be used on any vCPUs, see the comment
2788 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2789 * treats invalid shadow pages as being obsolete.
2791 if (!is_obsolete_sp(kvm, sp))
2792 kvm_reload_remote_mmus(kvm);
2795 sp->role.invalid = 1;
2796 return list_unstable;
2799 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2800 struct list_head *invalid_list)
2804 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2808 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2809 struct list_head *invalid_list)
2811 struct kvm_mmu_page *sp, *nsp;
2813 if (list_empty(invalid_list))
2817 * We need to make sure everyone sees our modifications to
2818 * the page tables and see changes to vcpu->mode here. The barrier
2819 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2820 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2822 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2823 * guest mode and/or lockless shadow page table walks.
2825 kvm_flush_remote_tlbs(kvm);
2827 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2828 WARN_ON(!sp->role.invalid || sp->root_count);
2829 kvm_mmu_free_page(sp);
2833 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2834 struct list_head *invalid_list)
2836 struct kvm_mmu_page *sp;
2838 if (list_empty(&kvm->arch.active_mmu_pages))
2841 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2842 struct kvm_mmu_page, link);
2843 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2847 * Changing the number of mmu pages allocated to the vm
2848 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2850 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2852 LIST_HEAD(invalid_list);
2854 spin_lock(&kvm->mmu_lock);
2856 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2857 /* Need to free some mmu pages to achieve the goal. */
2858 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2859 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2862 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2863 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2866 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2868 spin_unlock(&kvm->mmu_lock);
2871 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2873 struct kvm_mmu_page *sp;
2874 LIST_HEAD(invalid_list);
2877 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2879 spin_lock(&kvm->mmu_lock);
2880 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2881 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2884 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2886 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2887 spin_unlock(&kvm->mmu_lock);
2891 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2893 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2895 trace_kvm_mmu_unsync_page(sp);
2896 ++vcpu->kvm->stat.mmu_unsync;
2899 kvm_mmu_mark_parents_unsync(sp);
2902 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2905 struct kvm_mmu_page *sp;
2907 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2910 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2917 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2918 kvm_unsync_page(vcpu, sp);
2922 * We need to ensure that the marking of unsync pages is visible
2923 * before the SPTE is updated to allow writes because
2924 * kvm_mmu_sync_roots() checks the unsync flags without holding
2925 * the MMU lock and so can race with this. If the SPTE was updated
2926 * before the page had been marked as unsync-ed, something like the
2927 * following could happen:
2930 * ---------------------------------------------------------------------
2931 * 1.2 Host updates SPTE
2933 * 2.1 Guest writes a GPTE for GVA X.
2934 * (GPTE being in the guest page table shadowed
2935 * by the SP from CPU 1.)
2936 * This reads SPTE during the page table walk.
2937 * Since SPTE.W is read as 1, there is no
2940 * 2.2 Guest issues TLB flush.
2941 * That causes a VM Exit.
2943 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2944 * Since it is false, so it just returns.
2946 * 2.4 Guest accesses GVA X.
2947 * Since the mapping in the SP was not updated,
2948 * so the old mapping for GVA X incorrectly
2952 * (sp->unsync = true)
2954 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2955 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2956 * pairs with this write barrier.
2963 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2966 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2968 * Some reserved pages, such as those from NVDIMM
2969 * DAX devices, are not for MMIO, and can be mapped
2970 * with cached memory type for better performance.
2971 * However, the above check misconceives those pages
2972 * as MMIO, and results in KVM mapping them with UC
2973 * memory type, which would hurt the performance.
2974 * Therefore, we check the host memory type in addition
2975 * and only treat UC/UC-/WC pages as MMIO.
2977 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2979 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2980 pfn_to_hpa(pfn + 1) - 1,
2984 /* Bits which may be returned by set_spte() */
2985 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2986 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2988 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2989 unsigned pte_access, int level,
2990 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2991 bool can_unsync, bool host_writable)
2995 struct kvm_mmu_page *sp;
2997 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
3000 sp = page_header(__pa(sptep));
3001 if (sp_ad_disabled(sp))
3002 spte |= SPTE_AD_DISABLED_MASK;
3003 else if (kvm_vcpu_ad_need_write_protect(vcpu))
3004 spte |= SPTE_AD_WRPROT_ONLY_MASK;
3007 * For the EPT case, shadow_present_mask is 0 if hardware
3008 * supports exec-only page table entries. In that case,
3009 * ACC_USER_MASK and shadow_user_mask are used to represent
3010 * read access. See FNAME(gpte_access) in paging_tmpl.h.
3012 spte |= shadow_present_mask;
3014 spte |= spte_shadow_accessed_mask(spte);
3016 if (pte_access & ACC_EXEC_MASK)
3017 spte |= shadow_x_mask;
3019 spte |= shadow_nx_mask;
3021 if (pte_access & ACC_USER_MASK)
3022 spte |= shadow_user_mask;
3024 if (level > PT_PAGE_TABLE_LEVEL)
3025 spte |= PT_PAGE_SIZE_MASK;
3027 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
3028 kvm_is_mmio_pfn(pfn));
3031 spte |= SPTE_HOST_WRITEABLE;
3033 pte_access &= ~ACC_WRITE_MASK;
3035 if (!kvm_is_mmio_pfn(pfn))
3036 spte |= shadow_me_mask;
3038 spte |= (u64)pfn << PAGE_SHIFT;
3040 if (pte_access & ACC_WRITE_MASK) {
3043 * Other vcpu creates new sp in the window between
3044 * mapping_level() and acquiring mmu-lock. We can
3045 * allow guest to retry the access, the mapping can
3046 * be fixed if guest refault.
3048 if (level > PT_PAGE_TABLE_LEVEL &&
3049 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3052 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3055 * Optimization: for pte sync, if spte was writable the hash
3056 * lookup is unnecessary (and expensive). Write protection
3057 * is responsibility of mmu_get_page / kvm_sync_page.
3058 * Same reasoning can be applied to dirty page accounting.
3060 if (!can_unsync && is_writable_pte(*sptep))
3063 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3064 pgprintk("%s: found shadow page for %llx, marking ro\n",
3066 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3067 pte_access &= ~ACC_WRITE_MASK;
3068 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3072 if (pte_access & ACC_WRITE_MASK) {
3073 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3074 spte |= spte_shadow_dirty_mask(spte);
3078 spte = mark_spte_for_access_track(spte);
3081 if (mmu_spte_update(sptep, spte))
3082 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3087 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3088 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3089 bool speculative, bool host_writable)
3091 int was_rmapped = 0;
3094 int ret = RET_PF_RETRY;
3097 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3098 *sptep, write_fault, gfn);
3100 if (is_shadow_present_pte(*sptep)) {
3102 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3103 * the parent of the now unreachable PTE.
3105 if (level > PT_PAGE_TABLE_LEVEL &&
3106 !is_large_pte(*sptep)) {
3107 struct kvm_mmu_page *child;
3110 child = page_header(pte & PT64_BASE_ADDR_MASK);
3111 drop_parent_pte(child, sptep);
3113 } else if (pfn != spte_to_pfn(*sptep)) {
3114 pgprintk("hfn old %llx new %llx\n",
3115 spte_to_pfn(*sptep), pfn);
3116 drop_spte(vcpu->kvm, sptep);
3122 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3123 speculative, true, host_writable);
3124 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3126 ret = RET_PF_EMULATE;
3127 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3130 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3131 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3132 KVM_PAGES_PER_HPAGE(level));
3134 if (unlikely(is_mmio_spte(*sptep)))
3135 ret = RET_PF_EMULATE;
3137 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3138 trace_kvm_mmu_set_spte(level, gfn, sptep);
3139 if (!was_rmapped && is_large_pte(*sptep))
3140 ++vcpu->kvm->stat.lpages;
3142 if (is_shadow_present_pte(*sptep)) {
3144 rmap_count = rmap_add(vcpu, sptep, gfn);
3145 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3146 rmap_recycle(vcpu, sptep, gfn);
3153 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3156 struct kvm_memory_slot *slot;
3158 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3160 return KVM_PFN_ERR_FAULT;
3162 return gfn_to_pfn_memslot_atomic(slot, gfn);
3165 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3166 struct kvm_mmu_page *sp,
3167 u64 *start, u64 *end)
3169 struct page *pages[PTE_PREFETCH_NUM];
3170 struct kvm_memory_slot *slot;
3171 unsigned access = sp->role.access;
3175 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3176 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3180 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3184 for (i = 0; i < ret; i++, gfn++, start++) {
3185 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3186 page_to_pfn(pages[i]), true, true);
3193 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3194 struct kvm_mmu_page *sp, u64 *sptep)
3196 u64 *spte, *start = NULL;
3199 WARN_ON(!sp->role.direct);
3201 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3204 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3205 if (is_shadow_present_pte(*spte) || spte == sptep) {
3208 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3216 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3218 struct kvm_mmu_page *sp;
3220 sp = page_header(__pa(sptep));
3223 * Without accessed bits, there's no way to distinguish between
3224 * actually accessed translations and prefetched, so disable pte
3225 * prefetch if accessed bits aren't available.
3227 if (sp_ad_disabled(sp))
3230 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3233 __direct_pte_prefetch(vcpu, sp, sptep);
3236 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3237 int map_writable, int level, kvm_pfn_t pfn,
3240 struct kvm_shadow_walk_iterator it;
3241 struct kvm_mmu_page *sp;
3243 gfn_t gfn = gpa >> PAGE_SHIFT;
3244 gfn_t base_gfn = gfn;
3246 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3247 return RET_PF_RETRY;
3249 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3250 for_each_shadow_entry(vcpu, gpa, it) {
3251 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3252 if (it.level == level)
3255 drop_large_spte(vcpu, it.sptep);
3256 if (!is_shadow_present_pte(*it.sptep)) {
3257 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3258 it.level - 1, true, ACC_ALL);
3260 link_shadow_page(vcpu, it.sptep, sp);
3264 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3265 write, level, base_gfn, pfn, prefault,
3267 direct_pte_prefetch(vcpu, it.sptep);
3268 ++vcpu->stat.pf_fixed;
3272 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3274 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3277 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3280 * Do not cache the mmio info caused by writing the readonly gfn
3281 * into the spte otherwise read access on readonly gfn also can
3282 * caused mmio page fault and treat it as mmio access.
3284 if (pfn == KVM_PFN_ERR_RO_FAULT)
3285 return RET_PF_EMULATE;
3287 if (pfn == KVM_PFN_ERR_HWPOISON) {
3288 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3289 return RET_PF_RETRY;
3295 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3296 gfn_t gfn, kvm_pfn_t *pfnp,
3299 kvm_pfn_t pfn = *pfnp;
3300 int level = *levelp;
3303 * Check if it's a transparent hugepage. If this would be an
3304 * hugetlbfs page, level wouldn't be set to
3305 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3308 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3309 level == PT_PAGE_TABLE_LEVEL &&
3310 PageTransCompoundMap(pfn_to_page(pfn)) &&
3311 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3314 * mmu_notifier_retry was successful and we hold the
3315 * mmu_lock here, so the pmd can't become splitting
3316 * from under us, and in turn
3317 * __split_huge_page_refcount() can't run from under
3318 * us and we can safely transfer the refcount from
3319 * PG_tail to PG_head as we switch the pfn to tail to
3322 *levelp = level = PT_DIRECTORY_LEVEL;
3323 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3324 VM_BUG_ON((gfn & mask) != (pfn & mask));
3326 kvm_release_pfn_clean(pfn);
3334 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3335 kvm_pfn_t pfn, unsigned access, int *ret_val)
3337 /* The pfn is invalid, report the error! */
3338 if (unlikely(is_error_pfn(pfn))) {
3339 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3343 if (unlikely(is_noslot_pfn(pfn)))
3344 vcpu_cache_mmio_info(vcpu, gva, gfn,
3345 access & shadow_mmio_access_mask);
3350 static bool page_fault_can_be_fast(u32 error_code)
3353 * Do not fix the mmio spte with invalid generation number which
3354 * need to be updated by slow page fault path.
3356 if (unlikely(error_code & PFERR_RSVD_MASK))
3359 /* See if the page fault is due to an NX violation */
3360 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3361 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3365 * #PF can be fast if:
3366 * 1. The shadow page table entry is not present, which could mean that
3367 * the fault is potentially caused by access tracking (if enabled).
3368 * 2. The shadow page table entry is present and the fault
3369 * is caused by write-protect, that means we just need change the W
3370 * bit of the spte which can be done out of mmu-lock.
3372 * However, if access tracking is disabled we know that a non-present
3373 * page must be a genuine page fault where we have to create a new SPTE.
3374 * So, if access tracking is disabled, we return true only for write
3375 * accesses to a present page.
3378 return shadow_acc_track_mask != 0 ||
3379 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3380 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3384 * Returns true if the SPTE was fixed successfully. Otherwise,
3385 * someone else modified the SPTE from its original value.
3388 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3389 u64 *sptep, u64 old_spte, u64 new_spte)
3393 WARN_ON(!sp->role.direct);
3396 * Theoretically we could also set dirty bit (and flush TLB) here in
3397 * order to eliminate unnecessary PML logging. See comments in
3398 * set_spte. But fast_page_fault is very unlikely to happen with PML
3399 * enabled, so we do not do this. This might result in the same GPA
3400 * to be logged in PML buffer again when the write really happens, and
3401 * eventually to be called by mark_page_dirty twice. But it's also no
3402 * harm. This also avoids the TLB flush needed after setting dirty bit
3403 * so non-PML cases won't be impacted.
3405 * Compare with set_spte where instead shadow_dirty_mask is set.
3407 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3410 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3412 * The gfn of direct spte is stable since it is
3413 * calculated by sp->gfn.
3415 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3416 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3422 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3424 if (fault_err_code & PFERR_FETCH_MASK)
3425 return is_executable_pte(spte);
3427 if (fault_err_code & PFERR_WRITE_MASK)
3428 return is_writable_pte(spte);
3430 /* Fault was on Read access */
3431 return spte & PT_PRESENT_MASK;
3436 * - true: let the vcpu to access on the same address again.
3437 * - false: let the real page fault path to fix it.
3439 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3442 struct kvm_shadow_walk_iterator iterator;
3443 struct kvm_mmu_page *sp;
3444 bool fault_handled = false;
3446 uint retry_count = 0;
3448 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3451 if (!page_fault_can_be_fast(error_code))
3454 walk_shadow_page_lockless_begin(vcpu);
3459 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3460 if (!is_shadow_present_pte(spte) ||
3461 iterator.level < level)
3464 sp = page_header(__pa(iterator.sptep));
3465 if (!is_last_spte(spte, sp->role.level))
3469 * Check whether the memory access that caused the fault would
3470 * still cause it if it were to be performed right now. If not,
3471 * then this is a spurious fault caused by TLB lazily flushed,
3472 * or some other CPU has already fixed the PTE after the
3473 * current CPU took the fault.
3475 * Need not check the access of upper level table entries since
3476 * they are always ACC_ALL.
3478 if (is_access_allowed(error_code, spte)) {
3479 fault_handled = true;
3485 if (is_access_track_spte(spte))
3486 new_spte = restore_acc_track_spte(new_spte);
3489 * Currently, to simplify the code, write-protection can
3490 * be removed in the fast path only if the SPTE was
3491 * write-protected for dirty-logging or access tracking.
3493 if ((error_code & PFERR_WRITE_MASK) &&
3494 spte_can_locklessly_be_made_writable(spte))
3496 new_spte |= PT_WRITABLE_MASK;
3499 * Do not fix write-permission on the large spte. Since
3500 * we only dirty the first page into the dirty-bitmap in
3501 * fast_pf_fix_direct_spte(), other pages are missed
3502 * if its slot has dirty logging enabled.
3504 * Instead, we let the slow page fault path create a
3505 * normal spte to fix the access.
3507 * See the comments in kvm_arch_commit_memory_region().
3509 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3513 /* Verify that the fault can be handled in the fast path */
3514 if (new_spte == spte ||
3515 !is_access_allowed(error_code, new_spte))
3519 * Currently, fast page fault only works for direct mapping
3520 * since the gfn is not stable for indirect shadow page. See
3521 * Documentation/virt/kvm/locking.txt to get more detail.
3523 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3524 iterator.sptep, spte,
3529 if (++retry_count > 4) {
3530 printk_once(KERN_WARNING
3531 "kvm: Fast #PF retrying more than 4 times.\n");
3537 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3538 spte, fault_handled);
3539 walk_shadow_page_lockless_end(vcpu);
3541 return fault_handled;
3544 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3545 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3546 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3548 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3549 gfn_t gfn, bool prefault)
3553 bool force_pt_level = false;
3555 unsigned long mmu_seq;
3556 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3558 level = mapping_level(vcpu, gfn, &force_pt_level);
3559 if (likely(!force_pt_level)) {
3561 * This path builds a PAE pagetable - so we can map
3562 * 2mb pages at maximum. Therefore check if the level
3563 * is larger than that.
3565 if (level > PT_DIRECTORY_LEVEL)
3566 level = PT_DIRECTORY_LEVEL;
3568 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3571 if (fast_page_fault(vcpu, v, level, error_code))
3572 return RET_PF_RETRY;
3574 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3577 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3578 return RET_PF_RETRY;
3580 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3584 spin_lock(&vcpu->kvm->mmu_lock);
3585 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3587 if (make_mmu_pages_available(vcpu) < 0)
3589 if (likely(!force_pt_level))
3590 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3591 r = __direct_map(vcpu, v, write, map_writable, level, pfn, prefault);
3593 spin_unlock(&vcpu->kvm->mmu_lock);
3594 kvm_release_pfn_clean(pfn);
3598 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3599 struct list_head *invalid_list)
3601 struct kvm_mmu_page *sp;
3603 if (!VALID_PAGE(*root_hpa))
3606 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3608 if (!sp->root_count && sp->role.invalid)
3609 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3611 *root_hpa = INVALID_PAGE;
3614 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3615 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3616 ulong roots_to_free)
3619 LIST_HEAD(invalid_list);
3620 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3622 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3624 /* Before acquiring the MMU lock, see if we need to do any real work. */
3625 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3626 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3627 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3628 VALID_PAGE(mmu->prev_roots[i].hpa))
3631 if (i == KVM_MMU_NUM_PREV_ROOTS)
3635 spin_lock(&vcpu->kvm->mmu_lock);
3637 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3638 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3639 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3642 if (free_active_root) {
3643 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3644 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3645 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3648 for (i = 0; i < 4; ++i)
3649 if (mmu->pae_root[i] != 0)
3650 mmu_free_root_page(vcpu->kvm,
3653 mmu->root_hpa = INVALID_PAGE;
3658 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3659 spin_unlock(&vcpu->kvm->mmu_lock);
3661 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3663 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3667 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3668 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3675 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3677 struct kvm_mmu_page *sp;
3680 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3681 spin_lock(&vcpu->kvm->mmu_lock);
3682 if(make_mmu_pages_available(vcpu) < 0) {
3683 spin_unlock(&vcpu->kvm->mmu_lock);
3686 sp = kvm_mmu_get_page(vcpu, 0, 0,
3687 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3689 spin_unlock(&vcpu->kvm->mmu_lock);
3690 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3691 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3692 for (i = 0; i < 4; ++i) {
3693 hpa_t root = vcpu->arch.mmu->pae_root[i];
3695 MMU_WARN_ON(VALID_PAGE(root));
3696 spin_lock(&vcpu->kvm->mmu_lock);
3697 if (make_mmu_pages_available(vcpu) < 0) {
3698 spin_unlock(&vcpu->kvm->mmu_lock);
3701 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3702 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3703 root = __pa(sp->spt);
3705 spin_unlock(&vcpu->kvm->mmu_lock);
3706 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3708 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3711 vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3716 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3718 struct kvm_mmu_page *sp;
3720 gfn_t root_gfn, root_cr3;
3723 root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3724 root_gfn = root_cr3 >> PAGE_SHIFT;
3726 if (mmu_check_root(vcpu, root_gfn))
3730 * Do we shadow a long mode page table? If so we need to
3731 * write-protect the guests page table root.
3733 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3734 hpa_t root = vcpu->arch.mmu->root_hpa;
3736 MMU_WARN_ON(VALID_PAGE(root));
3738 spin_lock(&vcpu->kvm->mmu_lock);
3739 if (make_mmu_pages_available(vcpu) < 0) {
3740 spin_unlock(&vcpu->kvm->mmu_lock);
3743 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3744 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3745 root = __pa(sp->spt);
3747 spin_unlock(&vcpu->kvm->mmu_lock);
3748 vcpu->arch.mmu->root_hpa = root;
3753 * We shadow a 32 bit page table. This may be a legacy 2-level
3754 * or a PAE 3-level page table. In either case we need to be aware that
3755 * the shadow page table may be a PAE or a long mode page table.
3757 pm_mask = PT_PRESENT_MASK;
3758 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3759 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3761 for (i = 0; i < 4; ++i) {
3762 hpa_t root = vcpu->arch.mmu->pae_root[i];
3764 MMU_WARN_ON(VALID_PAGE(root));
3765 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3766 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3767 if (!(pdptr & PT_PRESENT_MASK)) {
3768 vcpu->arch.mmu->pae_root[i] = 0;
3771 root_gfn = pdptr >> PAGE_SHIFT;
3772 if (mmu_check_root(vcpu, root_gfn))
3775 spin_lock(&vcpu->kvm->mmu_lock);
3776 if (make_mmu_pages_available(vcpu) < 0) {
3777 spin_unlock(&vcpu->kvm->mmu_lock);
3780 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3782 root = __pa(sp->spt);
3784 spin_unlock(&vcpu->kvm->mmu_lock);
3786 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3788 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3791 * If we shadow a 32 bit page table with a long mode page
3792 * table we enter this path.
3794 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3795 if (vcpu->arch.mmu->lm_root == NULL) {
3797 * The additional page necessary for this is only
3798 * allocated on demand.
3803 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3804 if (lm_root == NULL)
3807 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3809 vcpu->arch.mmu->lm_root = lm_root;
3812 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3816 vcpu->arch.mmu->root_cr3 = root_cr3;
3821 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3823 if (vcpu->arch.mmu->direct_map)
3824 return mmu_alloc_direct_roots(vcpu);
3826 return mmu_alloc_shadow_roots(vcpu);
3829 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3832 struct kvm_mmu_page *sp;
3834 if (vcpu->arch.mmu->direct_map)
3837 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3840 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3842 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3843 hpa_t root = vcpu->arch.mmu->root_hpa;
3844 sp = page_header(root);
3847 * Even if another CPU was marking the SP as unsync-ed
3848 * simultaneously, any guest page table changes are not
3849 * guaranteed to be visible anyway until this VCPU issues a TLB
3850 * flush strictly after those changes are made. We only need to
3851 * ensure that the other CPU sets these flags before any actual
3852 * changes to the page tables are made. The comments in
3853 * mmu_need_write_protect() describe what could go wrong if this
3854 * requirement isn't satisfied.
3856 if (!smp_load_acquire(&sp->unsync) &&
3857 !smp_load_acquire(&sp->unsync_children))
3860 spin_lock(&vcpu->kvm->mmu_lock);
3861 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3863 mmu_sync_children(vcpu, sp);
3865 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3866 spin_unlock(&vcpu->kvm->mmu_lock);
3870 spin_lock(&vcpu->kvm->mmu_lock);
3871 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3873 for (i = 0; i < 4; ++i) {
3874 hpa_t root = vcpu->arch.mmu->pae_root[i];
3876 if (root && VALID_PAGE(root)) {
3877 root &= PT64_BASE_ADDR_MASK;
3878 sp = page_header(root);
3879 mmu_sync_children(vcpu, sp);
3883 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3884 spin_unlock(&vcpu->kvm->mmu_lock);
3886 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3888 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3889 u32 access, struct x86_exception *exception)
3892 exception->error_code = 0;
3896 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3898 struct x86_exception *exception)
3901 exception->error_code = 0;
3902 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3906 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3908 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3910 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3911 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3914 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3916 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3919 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3921 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3924 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3927 * A nested guest cannot use the MMIO cache if it is using nested
3928 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3930 if (mmu_is_nested(vcpu))
3934 return vcpu_match_mmio_gpa(vcpu, addr);
3936 return vcpu_match_mmio_gva(vcpu, addr);
3939 /* return true if reserved bit is detected on spte. */
3941 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3943 struct kvm_shadow_walk_iterator iterator;
3944 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3946 bool reserved = false;
3948 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3951 walk_shadow_page_lockless_begin(vcpu);
3953 for (shadow_walk_init(&iterator, vcpu, addr),
3954 leaf = root = iterator.level;
3955 shadow_walk_okay(&iterator);
3956 __shadow_walk_next(&iterator, spte)) {
3957 spte = mmu_spte_get_lockless(iterator.sptep);
3959 sptes[leaf - 1] = spte;
3962 if (!is_shadow_present_pte(spte))
3965 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3969 walk_shadow_page_lockless_end(vcpu);
3972 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3974 while (root > leaf) {
3975 pr_err("------ spte 0x%llx level %d.\n",
3976 sptes[root - 1], root);
3985 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3990 if (mmio_info_in_cache(vcpu, addr, direct))
3991 return RET_PF_EMULATE;
3993 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3994 if (WARN_ON(reserved))
3997 if (is_mmio_spte(spte)) {
3998 gfn_t gfn = get_mmio_spte_gfn(spte);
3999 unsigned access = get_mmio_spte_access(spte);
4001 if (!check_mmio_spte(vcpu, spte))
4002 return RET_PF_INVALID;
4007 trace_handle_mmio_page_fault(addr, gfn, access);
4008 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4009 return RET_PF_EMULATE;
4013 * If the page table is zapped by other cpus, let CPU fault again on
4016 return RET_PF_RETRY;
4019 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4020 u32 error_code, gfn_t gfn)
4022 if (unlikely(error_code & PFERR_RSVD_MASK))
4025 if (!(error_code & PFERR_PRESENT_MASK) ||
4026 !(error_code & PFERR_WRITE_MASK))
4030 * guest is writing the page which is write tracked which can
4031 * not be fixed by page fault handler.
4033 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4039 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4041 struct kvm_shadow_walk_iterator iterator;
4044 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
4047 walk_shadow_page_lockless_begin(vcpu);
4048 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4049 clear_sp_write_flooding_count(iterator.sptep);
4050 if (!is_shadow_present_pte(spte))
4053 walk_shadow_page_lockless_end(vcpu);
4056 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
4057 u32 error_code, bool prefault)
4059 gfn_t gfn = gva >> PAGE_SHIFT;
4062 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
4064 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4065 return RET_PF_EMULATE;
4067 r = mmu_topup_memory_caches(vcpu);
4071 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4074 return nonpaging_map(vcpu, gva & PAGE_MASK,
4075 error_code, gfn, prefault);
4078 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
4080 struct kvm_arch_async_pf arch;
4082 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4084 arch.direct_map = vcpu->arch.mmu->direct_map;
4085 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4087 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4090 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4091 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4093 struct kvm_memory_slot *slot;
4097 * Don't expose private memslots to L2.
4099 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4100 *pfn = KVM_PFN_NOSLOT;
4104 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4106 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4108 return false; /* *pfn has correct page already */
4110 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4111 trace_kvm_try_async_get_page(gva, gfn);
4112 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4113 trace_kvm_async_pf_doublefault(gva, gfn);
4114 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4116 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4120 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4124 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4125 u64 fault_address, char *insn, int insn_len)
4129 vcpu->arch.l1tf_flush_l1d = true;
4130 switch (vcpu->arch.apf.host_apf_reason) {
4132 trace_kvm_page_fault(fault_address, error_code);
4134 if (kvm_event_needs_reinjection(vcpu))
4135 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4136 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4139 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4140 vcpu->arch.apf.host_apf_reason = 0;
4141 local_irq_disable();
4142 kvm_async_pf_task_wait(fault_address, 0);
4145 case KVM_PV_REASON_PAGE_READY:
4146 vcpu->arch.apf.host_apf_reason = 0;
4147 local_irq_disable();
4148 kvm_async_pf_task_wake(fault_address);
4154 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4157 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4159 int page_num = KVM_PAGES_PER_HPAGE(level);
4161 gfn &= ~(page_num - 1);
4163 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4166 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4172 bool force_pt_level;
4173 gfn_t gfn = gpa >> PAGE_SHIFT;
4174 unsigned long mmu_seq;
4175 int write = error_code & PFERR_WRITE_MASK;
4178 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4180 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4181 return RET_PF_EMULATE;
4183 r = mmu_topup_memory_caches(vcpu);
4187 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4188 PT_DIRECTORY_LEVEL);
4189 level = mapping_level(vcpu, gfn, &force_pt_level);
4190 if (likely(!force_pt_level)) {
4191 if (level > PT_DIRECTORY_LEVEL &&
4192 !check_hugepage_cache_consistency(vcpu, gfn, level))
4193 level = PT_DIRECTORY_LEVEL;
4194 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4197 if (fast_page_fault(vcpu, gpa, level, error_code))
4198 return RET_PF_RETRY;
4200 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4203 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4204 return RET_PF_RETRY;
4206 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4210 spin_lock(&vcpu->kvm->mmu_lock);
4211 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4213 if (make_mmu_pages_available(vcpu) < 0)
4215 if (likely(!force_pt_level))
4216 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4217 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn, prefault);
4219 spin_unlock(&vcpu->kvm->mmu_lock);
4220 kvm_release_pfn_clean(pfn);
4224 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4225 struct kvm_mmu *context)
4227 context->page_fault = nonpaging_page_fault;
4228 context->gva_to_gpa = nonpaging_gva_to_gpa;
4229 context->sync_page = nonpaging_sync_page;
4230 context->invlpg = nonpaging_invlpg;
4231 context->update_pte = nonpaging_update_pte;
4232 context->root_level = 0;
4233 context->shadow_root_level = PT32E_ROOT_LEVEL;
4234 context->direct_map = true;
4235 context->nx = false;
4239 * Find out if a previously cached root matching the new CR3/role is available.
4240 * The current root is also inserted into the cache.
4241 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4243 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4244 * false is returned. This root should now be freed by the caller.
4246 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4247 union kvm_mmu_page_role new_role)
4250 struct kvm_mmu_root_info root;
4251 struct kvm_mmu *mmu = vcpu->arch.mmu;
4253 root.cr3 = mmu->root_cr3;
4254 root.hpa = mmu->root_hpa;
4256 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4257 swap(root, mmu->prev_roots[i]);
4259 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4260 page_header(root.hpa) != NULL &&
4261 new_role.word == page_header(root.hpa)->role.word)
4265 mmu->root_hpa = root.hpa;
4266 mmu->root_cr3 = root.cr3;
4268 return i < KVM_MMU_NUM_PREV_ROOTS;
4271 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4272 union kvm_mmu_page_role new_role,
4273 bool skip_tlb_flush)
4275 struct kvm_mmu *mmu = vcpu->arch.mmu;
4278 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4279 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4280 * later if necessary.
4282 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4283 mmu->root_level >= PT64_ROOT_4LEVEL) {
4284 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4287 if (cached_root_available(vcpu, new_cr3, new_role)) {
4289 * It is possible that the cached previous root page is
4290 * obsolete because of a change in the MMU generation
4291 * number. However, changing the generation number is
4292 * accompanied by KVM_REQ_MMU_RELOAD, which will free
4293 * the root set here and allocate a new one.
4295 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4296 if (!skip_tlb_flush) {
4297 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4298 kvm_x86_ops->tlb_flush(vcpu, true);
4302 * The last MMIO access's GVA and GPA are cached in the
4303 * VCPU. When switching to a new CR3, that GVA->GPA
4304 * mapping may no longer be valid. So clear any cached
4305 * MMIO info even when we don't need to sync the shadow
4308 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4310 __clear_sp_write_flooding_count(
4311 page_header(mmu->root_hpa));
4320 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4321 union kvm_mmu_page_role new_role,
4322 bool skip_tlb_flush)
4324 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4325 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4326 KVM_MMU_ROOT_CURRENT);
4329 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4331 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4334 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4336 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4338 return kvm_read_cr3(vcpu);
4341 static void inject_page_fault(struct kvm_vcpu *vcpu,
4342 struct x86_exception *fault)
4344 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4347 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4348 unsigned access, int *nr_present)
4350 if (unlikely(is_mmio_spte(*sptep))) {
4351 if (gfn != get_mmio_spte_gfn(*sptep)) {
4352 mmu_spte_clear_no_track(sptep);
4357 mark_mmio_spte(vcpu, sptep, gfn, access);
4364 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4365 unsigned level, unsigned gpte)
4368 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4369 * If it is clear, there are no large pages at this level, so clear
4370 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4372 gpte &= level - mmu->last_nonleaf_level;
4375 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4376 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4377 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4379 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4381 return gpte & PT_PAGE_SIZE_MASK;
4384 #define PTTYPE_EPT 18 /* arbitrary */
4385 #define PTTYPE PTTYPE_EPT
4386 #include "paging_tmpl.h"
4390 #include "paging_tmpl.h"
4394 #include "paging_tmpl.h"
4398 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4399 struct rsvd_bits_validate *rsvd_check,
4400 int maxphyaddr, int level, bool nx, bool gbpages,
4403 u64 exb_bit_rsvd = 0;
4404 u64 gbpages_bit_rsvd = 0;
4405 u64 nonleaf_bit8_rsvd = 0;
4407 rsvd_check->bad_mt_xwr = 0;
4410 exb_bit_rsvd = rsvd_bits(63, 63);
4412 gbpages_bit_rsvd = rsvd_bits(7, 7);
4415 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4416 * leaf entries) on AMD CPUs only.
4419 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4422 case PT32_ROOT_LEVEL:
4423 /* no rsvd bits for 2 level 4K page table entries */
4424 rsvd_check->rsvd_bits_mask[0][1] = 0;
4425 rsvd_check->rsvd_bits_mask[0][0] = 0;
4426 rsvd_check->rsvd_bits_mask[1][0] =
4427 rsvd_check->rsvd_bits_mask[0][0];
4430 rsvd_check->rsvd_bits_mask[1][1] = 0;
4434 if (is_cpuid_PSE36())
4435 /* 36bits PSE 4MB page */
4436 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4438 /* 32 bits PSE 4MB page */
4439 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4441 case PT32E_ROOT_LEVEL:
4442 rsvd_check->rsvd_bits_mask[0][2] =
4443 rsvd_bits(maxphyaddr, 63) |
4444 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4445 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4446 rsvd_bits(maxphyaddr, 62); /* PDE */
4447 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4448 rsvd_bits(maxphyaddr, 62); /* PTE */
4449 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4450 rsvd_bits(maxphyaddr, 62) |
4451 rsvd_bits(13, 20); /* large page */
4452 rsvd_check->rsvd_bits_mask[1][0] =
4453 rsvd_check->rsvd_bits_mask[0][0];
4455 case PT64_ROOT_5LEVEL:
4456 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4457 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4458 rsvd_bits(maxphyaddr, 51);
4459 rsvd_check->rsvd_bits_mask[1][4] =
4460 rsvd_check->rsvd_bits_mask[0][4];
4462 case PT64_ROOT_4LEVEL:
4463 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4464 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4465 rsvd_bits(maxphyaddr, 51);
4466 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4467 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4468 rsvd_bits(maxphyaddr, 51);
4469 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4470 rsvd_bits(maxphyaddr, 51);
4471 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4472 rsvd_bits(maxphyaddr, 51);
4473 rsvd_check->rsvd_bits_mask[1][3] =
4474 rsvd_check->rsvd_bits_mask[0][3];
4475 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4476 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4478 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4479 rsvd_bits(maxphyaddr, 51) |
4480 rsvd_bits(13, 20); /* large page */
4481 rsvd_check->rsvd_bits_mask[1][0] =
4482 rsvd_check->rsvd_bits_mask[0][0];
4487 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4488 struct kvm_mmu *context)
4490 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4491 cpuid_maxphyaddr(vcpu), context->root_level,
4493 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4494 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4498 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4499 int maxphyaddr, bool execonly)
4503 rsvd_check->rsvd_bits_mask[0][4] =
4504 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4505 rsvd_check->rsvd_bits_mask[0][3] =
4506 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4507 rsvd_check->rsvd_bits_mask[0][2] =
4508 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4509 rsvd_check->rsvd_bits_mask[0][1] =
4510 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4511 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4514 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4515 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4516 rsvd_check->rsvd_bits_mask[1][2] =
4517 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4518 rsvd_check->rsvd_bits_mask[1][1] =
4519 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4520 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4522 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4523 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4524 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4525 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4526 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4528 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4529 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4531 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4534 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4535 struct kvm_mmu *context, bool execonly)
4537 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4538 cpuid_maxphyaddr(vcpu), execonly);
4542 * the page table on host is the shadow page table for the page
4543 * table in guest or amd nested guest, its mmu features completely
4544 * follow the features in guest.
4547 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4549 bool uses_nx = context->nx ||
4550 context->mmu_role.base.smep_andnot_wp;
4551 struct rsvd_bits_validate *shadow_zero_check;
4555 * Passing "true" to the last argument is okay; it adds a check
4556 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4558 shadow_zero_check = &context->shadow_zero_check;
4559 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4561 context->shadow_root_level, uses_nx,
4562 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4563 is_pse(vcpu), true);
4565 if (!shadow_me_mask)
4568 for (i = context->shadow_root_level; --i >= 0;) {
4569 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4570 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4574 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4576 static inline bool boot_cpu_is_amd(void)
4578 WARN_ON_ONCE(!tdp_enabled);
4579 return shadow_x_mask == 0;
4583 * the direct page table on host, use as much mmu features as
4584 * possible, however, kvm currently does not do execution-protection.
4587 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4588 struct kvm_mmu *context)
4590 struct rsvd_bits_validate *shadow_zero_check;
4593 shadow_zero_check = &context->shadow_zero_check;
4595 if (boot_cpu_is_amd())
4596 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4598 context->shadow_root_level, false,
4599 boot_cpu_has(X86_FEATURE_GBPAGES),
4602 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4606 if (!shadow_me_mask)
4609 for (i = context->shadow_root_level; --i >= 0;) {
4610 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4611 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4616 * as the comments in reset_shadow_zero_bits_mask() except it
4617 * is the shadow page table for intel nested guest.
4620 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4621 struct kvm_mmu *context, bool execonly)
4623 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4624 shadow_phys_bits, execonly);
4627 #define BYTE_MASK(access) \
4628 ((1 & (access) ? 2 : 0) | \
4629 (2 & (access) ? 4 : 0) | \
4630 (3 & (access) ? 8 : 0) | \
4631 (4 & (access) ? 16 : 0) | \
4632 (5 & (access) ? 32 : 0) | \
4633 (6 & (access) ? 64 : 0) | \
4634 (7 & (access) ? 128 : 0))
4637 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4638 struct kvm_mmu *mmu, bool ept)
4642 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4643 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4644 const u8 u = BYTE_MASK(ACC_USER_MASK);
4646 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4647 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4648 bool cr0_wp = is_write_protection(vcpu);
4650 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4651 unsigned pfec = byte << 1;
4654 * Each "*f" variable has a 1 bit for each UWX value
4655 * that causes a fault with the given PFEC.
4658 /* Faults from writes to non-writable pages */
4659 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4660 /* Faults from user mode accesses to supervisor pages */
4661 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4662 /* Faults from fetches of non-executable pages*/
4663 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4664 /* Faults from kernel mode fetches of user pages */
4666 /* Faults from kernel mode accesses of user pages */
4670 /* Faults from kernel mode accesses to user pages */
4671 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4673 /* Not really needed: !nx will cause pte.nx to fault */
4677 /* Allow supervisor writes if !cr0.wp */
4679 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4681 /* Disallow supervisor fetches of user code if cr4.smep */
4683 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4686 * SMAP:kernel-mode data accesses from user-mode
4687 * mappings should fault. A fault is considered
4688 * as a SMAP violation if all of the following
4689 * conditions are true:
4690 * - X86_CR4_SMAP is set in CR4
4691 * - A user page is accessed
4692 * - The access is not a fetch
4693 * - Page fault in kernel mode
4694 * - if CPL = 3 or X86_EFLAGS_AC is clear
4696 * Here, we cover the first three conditions.
4697 * The fourth is computed dynamically in permission_fault();
4698 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4699 * *not* subject to SMAP restrictions.
4702 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4705 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4710 * PKU is an additional mechanism by which the paging controls access to
4711 * user-mode addresses based on the value in the PKRU register. Protection
4712 * key violations are reported through a bit in the page fault error code.
4713 * Unlike other bits of the error code, the PK bit is not known at the
4714 * call site of e.g. gva_to_gpa; it must be computed directly in
4715 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4716 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4718 * In particular the following conditions come from the error code, the
4719 * page tables and the machine state:
4720 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4721 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4722 * - PK is always zero if U=0 in the page tables
4723 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4725 * The PKRU bitmask caches the result of these four conditions. The error
4726 * code (minus the P bit) and the page table's U bit form an index into the
4727 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4728 * with the two bits of the PKRU register corresponding to the protection key.
4729 * For the first three conditions above the bits will be 00, thus masking
4730 * away both AD and WD. For all reads or if the last condition holds, WD
4731 * only will be masked away.
4733 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4744 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4745 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4750 wp = is_write_protection(vcpu);
4752 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4753 unsigned pfec, pkey_bits;
4754 bool check_pkey, check_write, ff, uf, wf, pte_user;
4757 ff = pfec & PFERR_FETCH_MASK;
4758 uf = pfec & PFERR_USER_MASK;
4759 wf = pfec & PFERR_WRITE_MASK;
4761 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4762 pte_user = pfec & PFERR_RSVD_MASK;
4765 * Only need to check the access which is not an
4766 * instruction fetch and is to a user page.
4768 check_pkey = (!ff && pte_user);
4770 * write access is controlled by PKRU if it is a
4771 * user access or CR0.WP = 1.
4773 check_write = check_pkey && wf && (uf || wp);
4775 /* PKRU.AD stops both read and write access. */
4776 pkey_bits = !!check_pkey;
4777 /* PKRU.WD stops write access. */
4778 pkey_bits |= (!!check_write) << 1;
4780 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4784 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4786 unsigned root_level = mmu->root_level;
4788 mmu->last_nonleaf_level = root_level;
4789 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4790 mmu->last_nonleaf_level++;
4793 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4794 struct kvm_mmu *context,
4797 context->nx = is_nx(vcpu);
4798 context->root_level = level;
4800 reset_rsvds_bits_mask(vcpu, context);
4801 update_permission_bitmask(vcpu, context, false);
4802 update_pkru_bitmask(vcpu, context, false);
4803 update_last_nonleaf_level(vcpu, context);
4805 MMU_WARN_ON(!is_pae(vcpu));
4806 context->page_fault = paging64_page_fault;
4807 context->gva_to_gpa = paging64_gva_to_gpa;
4808 context->sync_page = paging64_sync_page;
4809 context->invlpg = paging64_invlpg;
4810 context->update_pte = paging64_update_pte;
4811 context->shadow_root_level = level;
4812 context->direct_map = false;
4815 static void paging64_init_context(struct kvm_vcpu *vcpu,
4816 struct kvm_mmu *context)
4818 int root_level = is_la57_mode(vcpu) ?
4819 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4821 paging64_init_context_common(vcpu, context, root_level);
4824 static void paging32_init_context(struct kvm_vcpu *vcpu,
4825 struct kvm_mmu *context)
4827 context->nx = false;
4828 context->root_level = PT32_ROOT_LEVEL;
4830 reset_rsvds_bits_mask(vcpu, context);
4831 update_permission_bitmask(vcpu, context, false);
4832 update_pkru_bitmask(vcpu, context, false);
4833 update_last_nonleaf_level(vcpu, context);
4835 context->page_fault = paging32_page_fault;
4836 context->gva_to_gpa = paging32_gva_to_gpa;
4837 context->sync_page = paging32_sync_page;
4838 context->invlpg = paging32_invlpg;
4839 context->update_pte = paging32_update_pte;
4840 context->shadow_root_level = PT32E_ROOT_LEVEL;
4841 context->direct_map = false;
4844 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4845 struct kvm_mmu *context)
4847 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4850 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4852 union kvm_mmu_extended_role ext = {0};
4854 ext.cr0_pg = !!is_paging(vcpu);
4855 ext.cr4_pae = !!is_pae(vcpu);
4856 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4857 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4858 ext.cr4_pse = !!is_pse(vcpu);
4859 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4860 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4861 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4868 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4871 union kvm_mmu_role role = {0};
4873 role.base.access = ACC_ALL;
4874 role.base.nxe = !!is_nx(vcpu);
4875 role.base.cr0_wp = is_write_protection(vcpu);
4876 role.base.smm = is_smm(vcpu);
4877 role.base.guest_mode = is_guest_mode(vcpu);
4882 role.ext = kvm_calc_mmu_role_ext(vcpu);
4887 static union kvm_mmu_role
4888 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4890 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4892 role.base.ad_disabled = (shadow_accessed_mask == 0);
4893 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4894 role.base.direct = true;
4895 role.base.gpte_is_8_bytes = true;
4900 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4902 struct kvm_mmu *context = vcpu->arch.mmu;
4903 union kvm_mmu_role new_role =
4904 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4906 new_role.base.word &= mmu_base_role_mask.word;
4907 if (new_role.as_u64 == context->mmu_role.as_u64)
4910 context->mmu_role.as_u64 = new_role.as_u64;
4911 context->page_fault = tdp_page_fault;
4912 context->sync_page = nonpaging_sync_page;
4913 context->invlpg = nonpaging_invlpg;
4914 context->update_pte = nonpaging_update_pte;
4915 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4916 context->direct_map = true;
4917 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4918 context->get_cr3 = get_cr3;
4919 context->get_pdptr = kvm_pdptr_read;
4920 context->inject_page_fault = kvm_inject_page_fault;
4922 if (!is_paging(vcpu)) {
4923 context->nx = false;
4924 context->gva_to_gpa = nonpaging_gva_to_gpa;
4925 context->root_level = 0;
4926 } else if (is_long_mode(vcpu)) {
4927 context->nx = is_nx(vcpu);
4928 context->root_level = is_la57_mode(vcpu) ?
4929 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4930 reset_rsvds_bits_mask(vcpu, context);
4931 context->gva_to_gpa = paging64_gva_to_gpa;
4932 } else if (is_pae(vcpu)) {
4933 context->nx = is_nx(vcpu);
4934 context->root_level = PT32E_ROOT_LEVEL;
4935 reset_rsvds_bits_mask(vcpu, context);
4936 context->gva_to_gpa = paging64_gva_to_gpa;
4938 context->nx = false;
4939 context->root_level = PT32_ROOT_LEVEL;
4940 reset_rsvds_bits_mask(vcpu, context);
4941 context->gva_to_gpa = paging32_gva_to_gpa;
4944 update_permission_bitmask(vcpu, context, false);
4945 update_pkru_bitmask(vcpu, context, false);
4946 update_last_nonleaf_level(vcpu, context);
4947 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4950 static union kvm_mmu_role
4951 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4953 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4955 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4956 !is_write_protection(vcpu);
4957 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4958 !is_write_protection(vcpu);
4959 role.base.direct = !is_paging(vcpu);
4960 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4962 if (!is_long_mode(vcpu))
4963 role.base.level = PT32E_ROOT_LEVEL;
4964 else if (is_la57_mode(vcpu))
4965 role.base.level = PT64_ROOT_5LEVEL;
4967 role.base.level = PT64_ROOT_4LEVEL;
4972 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4974 struct kvm_mmu *context = vcpu->arch.mmu;
4975 union kvm_mmu_role new_role =
4976 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4978 new_role.base.word &= mmu_base_role_mask.word;
4979 if (new_role.as_u64 == context->mmu_role.as_u64)
4982 if (!is_paging(vcpu))
4983 nonpaging_init_context(vcpu, context);
4984 else if (is_long_mode(vcpu))
4985 paging64_init_context(vcpu, context);
4986 else if (is_pae(vcpu))
4987 paging32E_init_context(vcpu, context);
4989 paging32_init_context(vcpu, context);
4991 context->mmu_role.as_u64 = new_role.as_u64;
4992 reset_shadow_zero_bits_mask(vcpu, context);
4994 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4996 static union kvm_mmu_role
4997 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5000 union kvm_mmu_role role = {0};
5002 /* SMM flag is inherited from root_mmu */
5003 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
5005 role.base.level = PT64_ROOT_4LEVEL;
5006 role.base.gpte_is_8_bytes = true;
5007 role.base.direct = false;
5008 role.base.ad_disabled = !accessed_dirty;
5009 role.base.guest_mode = true;
5010 role.base.access = ACC_ALL;
5013 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
5014 * SMAP variation to denote shadow EPT entries.
5016 role.base.cr0_wp = true;
5017 role.base.smap_andnot_wp = true;
5019 role.ext = kvm_calc_mmu_role_ext(vcpu);
5020 role.ext.execonly = execonly;
5025 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5026 bool accessed_dirty, gpa_t new_eptp)
5028 struct kvm_mmu *context = vcpu->arch.mmu;
5029 union kvm_mmu_role new_role =
5030 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5033 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
5035 new_role.base.word &= mmu_base_role_mask.word;
5036 if (new_role.as_u64 == context->mmu_role.as_u64)
5039 context->shadow_root_level = PT64_ROOT_4LEVEL;
5042 context->ept_ad = accessed_dirty;
5043 context->page_fault = ept_page_fault;
5044 context->gva_to_gpa = ept_gva_to_gpa;
5045 context->sync_page = ept_sync_page;
5046 context->invlpg = ept_invlpg;
5047 context->update_pte = ept_update_pte;
5048 context->root_level = PT64_ROOT_4LEVEL;
5049 context->direct_map = false;
5050 context->mmu_role.as_u64 = new_role.as_u64;
5052 update_permission_bitmask(vcpu, context, true);
5053 update_pkru_bitmask(vcpu, context, true);
5054 update_last_nonleaf_level(vcpu, context);
5055 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5056 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5058 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5060 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5062 struct kvm_mmu *context = vcpu->arch.mmu;
5064 kvm_init_shadow_mmu(vcpu);
5065 context->set_cr3 = kvm_x86_ops->set_cr3;
5066 context->get_cr3 = get_cr3;
5067 context->get_pdptr = kvm_pdptr_read;
5068 context->inject_page_fault = kvm_inject_page_fault;
5071 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5073 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5074 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5076 new_role.base.word &= mmu_base_role_mask.word;
5077 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5080 g_context->mmu_role.as_u64 = new_role.as_u64;
5081 g_context->get_cr3 = get_cr3;
5082 g_context->get_pdptr = kvm_pdptr_read;
5083 g_context->inject_page_fault = kvm_inject_page_fault;
5086 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5087 * L1's nested page tables (e.g. EPT12). The nested translation
5088 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5089 * L2's page tables as the first level of translation and L1's
5090 * nested page tables as the second level of translation. Basically
5091 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5093 if (!is_paging(vcpu)) {
5094 g_context->nx = false;
5095 g_context->root_level = 0;
5096 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5097 } else if (is_long_mode(vcpu)) {
5098 g_context->nx = is_nx(vcpu);
5099 g_context->root_level = is_la57_mode(vcpu) ?
5100 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5101 reset_rsvds_bits_mask(vcpu, g_context);
5102 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5103 } else if (is_pae(vcpu)) {
5104 g_context->nx = is_nx(vcpu);
5105 g_context->root_level = PT32E_ROOT_LEVEL;
5106 reset_rsvds_bits_mask(vcpu, g_context);
5107 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5109 g_context->nx = false;
5110 g_context->root_level = PT32_ROOT_LEVEL;
5111 reset_rsvds_bits_mask(vcpu, g_context);
5112 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5115 update_permission_bitmask(vcpu, g_context, false);
5116 update_pkru_bitmask(vcpu, g_context, false);
5117 update_last_nonleaf_level(vcpu, g_context);
5120 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5125 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5127 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5128 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5131 if (mmu_is_nested(vcpu))
5132 init_kvm_nested_mmu(vcpu);
5133 else if (tdp_enabled)
5134 init_kvm_tdp_mmu(vcpu);
5136 init_kvm_softmmu(vcpu);
5138 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5140 static union kvm_mmu_page_role
5141 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5143 union kvm_mmu_role role;
5146 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5148 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5153 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5155 kvm_mmu_unload(vcpu);
5156 kvm_init_mmu(vcpu, true);
5158 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5160 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5164 r = mmu_topup_memory_caches(vcpu);
5167 r = mmu_alloc_roots(vcpu);
5168 kvm_mmu_sync_roots(vcpu);
5171 kvm_mmu_load_cr3(vcpu);
5172 kvm_x86_ops->tlb_flush(vcpu, true);
5176 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5178 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5180 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5181 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5182 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5183 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5185 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5187 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5188 struct kvm_mmu_page *sp, u64 *spte,
5191 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5192 ++vcpu->kvm->stat.mmu_pde_zapped;
5196 ++vcpu->kvm->stat.mmu_pte_updated;
5197 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5200 static bool need_remote_flush(u64 old, u64 new)
5202 if (!is_shadow_present_pte(old))
5204 if (!is_shadow_present_pte(new))
5206 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5208 old ^= shadow_nx_mask;
5209 new ^= shadow_nx_mask;
5210 return (old & ~new & PT64_PERM_MASK) != 0;
5213 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5220 * Assume that the pte write on a page table of the same type
5221 * as the current vcpu paging mode since we update the sptes only
5222 * when they have the same mode.
5224 if (is_pae(vcpu) && *bytes == 4) {
5225 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5230 if (*bytes == 4 || *bytes == 8) {
5231 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5240 * If we're seeing too many writes to a page, it may no longer be a page table,
5241 * or we may be forking, in which case it is better to unmap the page.
5243 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5246 * Skip write-flooding detected for the sp whose level is 1, because
5247 * it can become unsync, then the guest page is not write-protected.
5249 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5252 atomic_inc(&sp->write_flooding_count);
5253 return atomic_read(&sp->write_flooding_count) >= 3;
5257 * Misaligned accesses are too much trouble to fix up; also, they usually
5258 * indicate a page is not used as a page table.
5260 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5263 unsigned offset, pte_size, misaligned;
5265 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5266 gpa, bytes, sp->role.word);
5268 offset = offset_in_page(gpa);
5269 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5272 * Sometimes, the OS only writes the last one bytes to update status
5273 * bits, for example, in linux, andb instruction is used in clear_bit().
5275 if (!(offset & (pte_size - 1)) && bytes == 1)
5278 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5279 misaligned |= bytes < 4;
5284 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5286 unsigned page_offset, quadrant;
5290 page_offset = offset_in_page(gpa);
5291 level = sp->role.level;
5293 if (!sp->role.gpte_is_8_bytes) {
5294 page_offset <<= 1; /* 32->64 */
5296 * A 32-bit pde maps 4MB while the shadow pdes map
5297 * only 2MB. So we need to double the offset again
5298 * and zap two pdes instead of one.
5300 if (level == PT32_ROOT_LEVEL) {
5301 page_offset &= ~7; /* kill rounding error */
5305 quadrant = page_offset >> PAGE_SHIFT;
5306 page_offset &= ~PAGE_MASK;
5307 if (quadrant != sp->role.quadrant)
5311 spte = &sp->spt[page_offset / sizeof(*spte)];
5315 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5316 const u8 *new, int bytes,
5317 struct kvm_page_track_notifier_node *node)
5319 gfn_t gfn = gpa >> PAGE_SHIFT;
5320 struct kvm_mmu_page *sp;
5321 LIST_HEAD(invalid_list);
5322 u64 entry, gentry, *spte;
5324 bool remote_flush, local_flush;
5327 * If we don't have indirect shadow pages, it means no page is
5328 * write-protected, so we can exit simply.
5330 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5333 remote_flush = local_flush = false;
5335 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5338 * No need to care whether allocation memory is successful
5339 * or not since pte prefetch is skiped if it does not have
5340 * enough objects in the cache.
5342 mmu_topup_memory_caches(vcpu);
5344 spin_lock(&vcpu->kvm->mmu_lock);
5346 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5348 ++vcpu->kvm->stat.mmu_pte_write;
5349 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5351 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5352 if (detect_write_misaligned(sp, gpa, bytes) ||
5353 detect_write_flooding(sp)) {
5354 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5355 ++vcpu->kvm->stat.mmu_flooded;
5359 spte = get_written_sptes(sp, gpa, &npte);
5365 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5368 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5370 !((sp->role.word ^ base_role)
5371 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5372 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5373 if (need_remote_flush(entry, *spte))
5374 remote_flush = true;
5378 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5379 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5380 spin_unlock(&vcpu->kvm->mmu_lock);
5383 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5388 if (vcpu->arch.mmu->direct_map)
5391 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5393 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5397 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5399 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5401 LIST_HEAD(invalid_list);
5403 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5406 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5407 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5410 ++vcpu->kvm->stat.mmu_recycled;
5412 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5414 if (!kvm_mmu_available_pages(vcpu->kvm))
5419 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5420 void *insn, int insn_len)
5422 int r, emulation_type = 0;
5423 bool direct = vcpu->arch.mmu->direct_map;
5425 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5426 if (vcpu->arch.mmu->direct_map) {
5427 vcpu->arch.gpa_available = true;
5428 vcpu->arch.gpa_val = cr2;
5432 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5433 r = handle_mmio_page_fault(vcpu, cr2, direct);
5434 if (r == RET_PF_EMULATE)
5438 if (r == RET_PF_INVALID) {
5439 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5440 lower_32_bits(error_code),
5442 WARN_ON(r == RET_PF_INVALID);
5445 if (r == RET_PF_RETRY)
5451 * Before emulating the instruction, check if the error code
5452 * was due to a RO violation while translating the guest page.
5453 * This can occur when using nested virtualization with nested
5454 * paging in both guests. If true, we simply unprotect the page
5455 * and resume the guest.
5457 if (vcpu->arch.mmu->direct_map &&
5458 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5459 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5464 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5465 * optimistically try to just unprotect the page and let the processor
5466 * re-execute the instruction that caused the page fault. Do not allow
5467 * retrying MMIO emulation, as it's not only pointless but could also
5468 * cause us to enter an infinite loop because the processor will keep
5469 * faulting on the non-existent MMIO address. Retrying an instruction
5470 * from a nested guest is also pointless and dangerous as we are only
5471 * explicitly shadowing L1's page tables, i.e. unprotecting something
5472 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5474 if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5475 emulation_type = EMULTYPE_ALLOW_RETRY;
5478 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5479 * This can happen if a guest gets a page-fault on data access but the HW
5480 * table walker is not able to read the instruction page (e.g instruction
5481 * page is not present in memory). In those cases we simply restart the
5482 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5484 if (unlikely(insn && !insn_len)) {
5485 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5489 return x86_emulate_instruction(vcpu, cr2, emulation_type, insn,
5492 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5494 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5496 struct kvm_mmu *mmu = vcpu->arch.mmu;
5499 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5500 if (is_noncanonical_address(gva, vcpu))
5503 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5506 * INVLPG is required to invalidate any global mappings for the VA,
5507 * irrespective of PCID. Since it would take us roughly similar amount
5508 * of work to determine whether any of the prev_root mappings of the VA
5509 * is marked global, or to just sync it blindly, so we might as well
5510 * just always sync it.
5512 * Mappings not reachable via the current cr3 or the prev_roots will be
5513 * synced when switching to that cr3, so nothing needs to be done here
5516 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5517 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5518 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5520 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5521 ++vcpu->stat.invlpg;
5523 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5525 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5527 struct kvm_mmu *mmu = vcpu->arch.mmu;
5528 bool tlb_flush = false;
5531 if (pcid == kvm_get_active_pcid(vcpu)) {
5532 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5536 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5537 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5538 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5539 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5545 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5547 ++vcpu->stat.invlpg;
5550 * Mappings not reachable via the current cr3 or the prev_roots will be
5551 * synced when switching to that cr3, so nothing needs to be done here
5555 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5557 void kvm_enable_tdp(void)
5561 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5563 void kvm_disable_tdp(void)
5565 tdp_enabled = false;
5567 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5570 /* The return value indicates if tlb flush on all vcpus is needed. */
5571 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5573 /* The caller should hold mmu-lock before calling this function. */
5574 static __always_inline bool
5575 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5576 slot_level_handler fn, int start_level, int end_level,
5577 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5579 struct slot_rmap_walk_iterator iterator;
5582 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5583 end_gfn, &iterator) {
5585 flush |= fn(kvm, iterator.rmap);
5587 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5588 if (flush && lock_flush_tlb) {
5589 kvm_flush_remote_tlbs_with_address(kvm,
5591 iterator.gfn - start_gfn + 1);
5594 cond_resched_lock(&kvm->mmu_lock);
5598 if (flush && lock_flush_tlb) {
5599 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5600 end_gfn - start_gfn + 1);
5607 static __always_inline bool
5608 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5609 slot_level_handler fn, int start_level, int end_level,
5610 bool lock_flush_tlb)
5612 return slot_handle_level_range(kvm, memslot, fn, start_level,
5613 end_level, memslot->base_gfn,
5614 memslot->base_gfn + memslot->npages - 1,
5618 static __always_inline bool
5619 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5620 slot_level_handler fn, bool lock_flush_tlb)
5622 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5623 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5626 static __always_inline bool
5627 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5628 slot_level_handler fn, bool lock_flush_tlb)
5630 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5631 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5634 static __always_inline bool
5635 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5636 slot_level_handler fn, bool lock_flush_tlb)
5638 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5639 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5642 static void free_mmu_pages(struct kvm_mmu *mmu)
5644 free_page((unsigned long)mmu->pae_root);
5645 free_page((unsigned long)mmu->lm_root);
5648 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5654 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5655 * while the PDP table is a per-vCPU construct that's allocated at MMU
5656 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5657 * x86_64. Therefore we need to allocate the PDP table in the first
5658 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5659 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5660 * skip allocating the PDP table.
5662 if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5665 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5669 mmu->pae_root = page_address(page);
5670 for (i = 0; i < 4; ++i)
5671 mmu->pae_root[i] = INVALID_PAGE;
5676 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5681 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5682 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5684 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5685 vcpu->arch.root_mmu.root_cr3 = 0;
5686 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5687 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5688 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5690 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5691 vcpu->arch.guest_mmu.root_cr3 = 0;
5692 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5693 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5694 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5696 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5698 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5702 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5704 goto fail_allocate_root;
5708 free_mmu_pages(&vcpu->arch.guest_mmu);
5712 #define BATCH_ZAP_PAGES 10
5713 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5715 struct kvm_mmu_page *sp, *node;
5716 int nr_zapped, batch = 0;
5719 list_for_each_entry_safe_reverse(sp, node,
5720 &kvm->arch.active_mmu_pages, link) {
5722 * No obsolete valid page exists before a newly created page
5723 * since active_mmu_pages is a FIFO list.
5725 if (!is_obsolete_sp(kvm, sp))
5729 * Skip invalid pages with a non-zero root count, zapping pages
5730 * with a non-zero root count will never succeed, i.e. the page
5731 * will get thrown back on active_mmu_pages and we'll get stuck
5732 * in an infinite loop.
5734 if (sp->role.invalid && sp->root_count)
5738 * No need to flush the TLB since we're only zapping shadow
5739 * pages with an obsolete generation number and all vCPUS have
5740 * loaded a new root, i.e. the shadow pages being zapped cannot
5741 * be in active use by the guest.
5743 if (batch >= BATCH_ZAP_PAGES &&
5744 cond_resched_lock(&kvm->mmu_lock)) {
5749 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5750 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5757 * Trigger a remote TLB flush before freeing the page tables to ensure
5758 * KVM is not in the middle of a lockless shadow page table walk, which
5759 * may reference the pages.
5761 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5765 * Fast invalidate all shadow pages and use lock-break technique
5766 * to zap obsolete pages.
5768 * It's required when memslot is being deleted or VM is being
5769 * destroyed, in these cases, we should ensure that KVM MMU does
5770 * not use any resource of the being-deleted slot or all slots
5771 * after calling the function.
5773 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5775 lockdep_assert_held(&kvm->slots_lock);
5777 spin_lock(&kvm->mmu_lock);
5778 trace_kvm_mmu_zap_all_fast(kvm);
5781 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5782 * held for the entire duration of zapping obsolete pages, it's
5783 * impossible for there to be multiple invalid generations associated
5784 * with *valid* shadow pages at any given time, i.e. there is exactly
5785 * one valid generation and (at most) one invalid generation.
5787 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5790 * Notify all vcpus to reload its shadow page table and flush TLB.
5791 * Then all vcpus will switch to new shadow page table with the new
5794 * Note: we need to do this under the protection of mmu_lock,
5795 * otherwise, vcpu would purge shadow page but miss tlb flush.
5797 kvm_reload_remote_mmus(kvm);
5799 kvm_zap_obsolete_pages(kvm);
5800 spin_unlock(&kvm->mmu_lock);
5803 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5805 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5808 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5809 struct kvm_memory_slot *slot,
5810 struct kvm_page_track_notifier_node *node)
5812 kvm_mmu_zap_all_fast(kvm);
5815 void kvm_mmu_init_vm(struct kvm *kvm)
5817 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5819 node->track_write = kvm_mmu_pte_write;
5820 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5821 kvm_page_track_register_notifier(kvm, node);
5824 void kvm_mmu_uninit_vm(struct kvm *kvm)
5826 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5828 kvm_page_track_unregister_notifier(kvm, node);
5831 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5833 struct kvm_memslots *slots;
5834 struct kvm_memory_slot *memslot;
5837 spin_lock(&kvm->mmu_lock);
5838 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5839 slots = __kvm_memslots(kvm, i);
5840 kvm_for_each_memslot(memslot, slots) {
5843 start = max(gfn_start, memslot->base_gfn);
5844 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5848 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5849 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5850 start, end - 1, true);
5854 spin_unlock(&kvm->mmu_lock);
5857 static bool slot_rmap_write_protect(struct kvm *kvm,
5858 struct kvm_rmap_head *rmap_head)
5860 return __rmap_write_protect(kvm, rmap_head, false);
5863 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5864 struct kvm_memory_slot *memslot)
5868 spin_lock(&kvm->mmu_lock);
5869 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5871 spin_unlock(&kvm->mmu_lock);
5874 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5875 * which do tlb flush out of mmu-lock should be serialized by
5876 * kvm->slots_lock otherwise tlb flush would be missed.
5878 lockdep_assert_held(&kvm->slots_lock);
5881 * We can flush all the TLBs out of the mmu lock without TLB
5882 * corruption since we just change the spte from writable to
5883 * readonly so that we only need to care the case of changing
5884 * spte from present to present (changing the spte from present
5885 * to nonpresent will flush all the TLBs immediately), in other
5886 * words, the only case we care is mmu_spte_update() where we
5887 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5888 * instead of PT_WRITABLE_MASK, that means it does not depend
5889 * on PT_WRITABLE_MASK anymore.
5892 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5896 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5897 struct kvm_rmap_head *rmap_head)
5900 struct rmap_iterator iter;
5901 int need_tlb_flush = 0;
5903 struct kvm_mmu_page *sp;
5906 for_each_rmap_spte(rmap_head, &iter, sptep) {
5907 sp = page_header(__pa(sptep));
5908 pfn = spte_to_pfn(*sptep);
5911 * We cannot do huge page mapping for indirect shadow pages,
5912 * which are found on the last rmap (level = 1) when not using
5913 * tdp; such shadow pages are synced with the page table in
5914 * the guest, and the guest page table is using 4K page size
5915 * mapping if the indirect sp has level = 1.
5917 if (sp->role.direct &&
5918 !kvm_is_reserved_pfn(pfn) &&
5919 PageTransCompoundMap(pfn_to_page(pfn))) {
5920 pte_list_remove(rmap_head, sptep);
5922 if (kvm_available_flush_tlb_with_range())
5923 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5924 KVM_PAGES_PER_HPAGE(sp->role.level));
5932 return need_tlb_flush;
5935 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5936 const struct kvm_memory_slot *memslot)
5938 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5939 spin_lock(&kvm->mmu_lock);
5940 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5941 kvm_mmu_zap_collapsible_spte, true);
5942 spin_unlock(&kvm->mmu_lock);
5945 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5946 struct kvm_memory_slot *memslot)
5950 spin_lock(&kvm->mmu_lock);
5951 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5952 spin_unlock(&kvm->mmu_lock);
5954 lockdep_assert_held(&kvm->slots_lock);
5957 * It's also safe to flush TLBs out of mmu lock here as currently this
5958 * function is only used for dirty logging, in which case flushing TLB
5959 * out of mmu lock also guarantees no dirty pages will be lost in
5963 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5966 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5968 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5969 struct kvm_memory_slot *memslot)
5973 spin_lock(&kvm->mmu_lock);
5974 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5976 spin_unlock(&kvm->mmu_lock);
5978 /* see kvm_mmu_slot_remove_write_access */
5979 lockdep_assert_held(&kvm->slots_lock);
5982 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5985 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5987 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5988 struct kvm_memory_slot *memslot)
5992 spin_lock(&kvm->mmu_lock);
5993 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5994 spin_unlock(&kvm->mmu_lock);
5996 lockdep_assert_held(&kvm->slots_lock);
5998 /* see kvm_mmu_slot_leaf_clear_dirty */
6000 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6003 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
6005 void kvm_mmu_zap_all(struct kvm *kvm)
6007 struct kvm_mmu_page *sp, *node;
6008 LIST_HEAD(invalid_list);
6011 spin_lock(&kvm->mmu_lock);
6013 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6014 if (sp->role.invalid && sp->root_count)
6016 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6018 if (cond_resched_lock(&kvm->mmu_lock))
6022 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6023 spin_unlock(&kvm->mmu_lock);
6026 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6028 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6030 gen &= MMIO_SPTE_GEN_MASK;
6033 * Generation numbers are incremented in multiples of the number of
6034 * address spaces in order to provide unique generations across all
6035 * address spaces. Strip what is effectively the address space
6036 * modifier prior to checking for a wrap of the MMIO generation so
6037 * that a wrap in any address space is detected.
6039 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6042 * The very rare case: if the MMIO generation number has wrapped,
6043 * zap all shadow pages.
6045 if (unlikely(gen == 0)) {
6046 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6047 kvm_mmu_zap_all_fast(kvm);
6051 static unsigned long
6052 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6055 int nr_to_scan = sc->nr_to_scan;
6056 unsigned long freed = 0;
6058 mutex_lock(&kvm_lock);
6060 list_for_each_entry(kvm, &vm_list, vm_list) {
6062 LIST_HEAD(invalid_list);
6065 * Never scan more than sc->nr_to_scan VM instances.
6066 * Will not hit this condition practically since we do not try
6067 * to shrink more than one VM and it is very unlikely to see
6068 * !n_used_mmu_pages so many times.
6073 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6074 * here. We may skip a VM instance errorneosly, but we do not
6075 * want to shrink a VM that only started to populate its MMU
6078 if (!kvm->arch.n_used_mmu_pages &&
6079 !kvm_has_zapped_obsolete_pages(kvm))
6082 idx = srcu_read_lock(&kvm->srcu);
6083 spin_lock(&kvm->mmu_lock);
6085 if (kvm_has_zapped_obsolete_pages(kvm)) {
6086 kvm_mmu_commit_zap_page(kvm,
6087 &kvm->arch.zapped_obsolete_pages);
6091 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6093 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6096 spin_unlock(&kvm->mmu_lock);
6097 srcu_read_unlock(&kvm->srcu, idx);
6100 * unfair on small ones
6101 * per-vm shrinkers cry out
6102 * sadness comes quickly
6104 list_move_tail(&kvm->vm_list, &vm_list);
6108 mutex_unlock(&kvm_lock);
6112 static unsigned long
6113 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6115 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6118 static struct shrinker mmu_shrinker = {
6119 .count_objects = mmu_shrink_count,
6120 .scan_objects = mmu_shrink_scan,
6121 .seeks = DEFAULT_SEEKS * 10,
6124 static void mmu_destroy_caches(void)
6126 kmem_cache_destroy(pte_list_desc_cache);
6127 kmem_cache_destroy(mmu_page_header_cache);
6130 static void kvm_set_mmio_spte_mask(void)
6135 * Set the reserved bits and the present bit of an paging-structure
6136 * entry to generate page fault with PFER.RSV = 1.
6140 * Mask the uppermost physical address bit, which would be reserved as
6141 * long as the supported physical address width is less than 52.
6145 /* Set the present bit. */
6149 * If reserved bit is not supported, clear the present bit to disable
6152 if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
6155 kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
6158 int kvm_mmu_module_init(void)
6163 * MMU roles use union aliasing which is, generally speaking, an
6164 * undefined behavior. However, we supposedly know how compilers behave
6165 * and the current status quo is unlikely to change. Guardians below are
6166 * supposed to let us know if the assumption becomes false.
6168 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6169 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6170 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6172 kvm_mmu_reset_all_pte_masks();
6174 kvm_set_mmio_spte_mask();
6176 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6177 sizeof(struct pte_list_desc),
6178 0, SLAB_ACCOUNT, NULL);
6179 if (!pte_list_desc_cache)
6182 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6183 sizeof(struct kvm_mmu_page),
6184 0, SLAB_ACCOUNT, NULL);
6185 if (!mmu_page_header_cache)
6188 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6191 ret = register_shrinker(&mmu_shrinker);
6198 mmu_destroy_caches();
6203 * Calculate mmu pages needed for kvm.
6205 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6207 unsigned long nr_mmu_pages;
6208 unsigned long nr_pages = 0;
6209 struct kvm_memslots *slots;
6210 struct kvm_memory_slot *memslot;
6213 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6214 slots = __kvm_memslots(kvm, i);
6216 kvm_for_each_memslot(memslot, slots)
6217 nr_pages += memslot->npages;
6220 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6221 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6223 return nr_mmu_pages;
6226 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6228 kvm_mmu_unload(vcpu);
6229 free_mmu_pages(&vcpu->arch.root_mmu);
6230 free_mmu_pages(&vcpu->arch.guest_mmu);
6231 mmu_free_memory_caches(vcpu);
6234 void kvm_mmu_module_exit(void)
6236 mmu_destroy_caches();
6237 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6238 unregister_shrinker(&mmu_shrinker);
6239 mmu_audit_disable();