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_MMIO_MASK (3ULL << 52)
97 #define PT64_LEVEL_BITS 9
99 #define PT64_LEVEL_SHIFT(level) \
100 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
102 #define PT64_INDEX(address, level)\
103 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
106 #define PT32_LEVEL_BITS 10
108 #define PT32_LEVEL_SHIFT(level) \
109 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
111 #define PT32_LVL_OFFSET_MASK(level) \
112 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
113 * PT32_LEVEL_BITS))) - 1))
115 #define PT32_INDEX(address, level)\
116 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
119 #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
120 #define PT64_BASE_ADDR_MASK (physical_mask & ~(u64)(PAGE_SIZE-1))
122 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
124 #define PT64_LVL_ADDR_MASK(level) \
125 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
126 * PT64_LEVEL_BITS))) - 1))
127 #define PT64_LVL_OFFSET_MASK(level) \
128 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
129 * PT64_LEVEL_BITS))) - 1))
131 #define PT32_BASE_ADDR_MASK PAGE_MASK
132 #define PT32_DIR_BASE_ADDR_MASK \
133 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
134 #define PT32_LVL_ADDR_MASK(level) \
135 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
136 * PT32_LEVEL_BITS))) - 1))
138 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
139 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
141 #define ACC_EXEC_MASK 1
142 #define ACC_WRITE_MASK PT_WRITABLE_MASK
143 #define ACC_USER_MASK PT_USER_MASK
144 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
146 /* The mask for the R/X bits in EPT PTEs */
147 #define PT64_EPT_READABLE_MASK 0x1ull
148 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
150 #include <trace/events/kvm.h>
152 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
153 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
155 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
157 /* make pte_list_desc fit well in cache line */
158 #define PTE_LIST_EXT 3
161 * Return values of handle_mmio_page_fault and mmu.page_fault:
162 * RET_PF_RETRY: let CPU fault again on the address.
163 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
165 * For handle_mmio_page_fault only:
166 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
174 struct pte_list_desc {
175 u64 *sptes[PTE_LIST_EXT];
176 struct pte_list_desc *more;
179 struct kvm_shadow_walk_iterator {
187 static const union kvm_mmu_page_role mmu_base_role_mask = {
189 .gpte_is_8_bytes = 1,
198 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
199 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
201 shadow_walk_okay(&(_walker)); \
202 shadow_walk_next(&(_walker)))
204 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
205 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
206 shadow_walk_okay(&(_walker)); \
207 shadow_walk_next(&(_walker)))
209 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
210 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
211 shadow_walk_okay(&(_walker)) && \
212 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
213 __shadow_walk_next(&(_walker), spte))
215 static struct kmem_cache *pte_list_desc_cache;
216 static struct kmem_cache *mmu_page_header_cache;
217 static struct percpu_counter kvm_total_used_mmu_pages;
219 static u64 __read_mostly shadow_nx_mask;
220 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
221 static u64 __read_mostly shadow_user_mask;
222 static u64 __read_mostly shadow_accessed_mask;
223 static u64 __read_mostly shadow_dirty_mask;
224 static u64 __read_mostly shadow_mmio_mask;
225 static u64 __read_mostly shadow_mmio_value;
226 static u64 __read_mostly shadow_mmio_access_mask;
227 static u64 __read_mostly shadow_present_mask;
228 static u64 __read_mostly shadow_me_mask;
231 * SPTEs used by MMUs without A/D bits are marked with SPTE_AD_DISABLED_MASK;
232 * shadow_acc_track_mask is the set of bits to be cleared in non-accessed
235 static u64 __read_mostly shadow_acc_track_mask;
238 * The mask/shift to use for saving the original R/X bits when marking the PTE
239 * as not-present for access tracking purposes. We do not save the W bit as the
240 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
241 * restored only when a write is attempted to the page.
243 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
244 PT64_EPT_EXECUTABLE_MASK;
245 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
248 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
249 * to guard against L1TF attacks.
251 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
254 * The number of high-order 1 bits to use in the mask above.
256 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
259 * In some cases, we need to preserve the GFN of a non-present or reserved
260 * SPTE when we usurp the upper five bits of the physical address space to
261 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
262 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
263 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
264 * high and low parts. This mask covers the lower bits of the GFN.
266 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
269 * The number of non-reserved physical address bits irrespective of features
270 * that repurpose legal bits, e.g. MKTME.
272 static u8 __read_mostly shadow_phys_bits;
274 static void mmu_spte_set(u64 *sptep, u64 spte);
275 static bool is_executable_pte(u64 spte);
276 static union kvm_mmu_page_role
277 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
279 #define CREATE_TRACE_POINTS
280 #include "mmutrace.h"
283 static inline bool kvm_available_flush_tlb_with_range(void)
285 return kvm_x86_ops->tlb_remote_flush_with_range;
288 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
289 struct kvm_tlb_range *range)
293 if (range && kvm_x86_ops->tlb_remote_flush_with_range)
294 ret = kvm_x86_ops->tlb_remote_flush_with_range(kvm, range);
297 kvm_flush_remote_tlbs(kvm);
300 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
301 u64 start_gfn, u64 pages)
303 struct kvm_tlb_range range;
305 range.start_gfn = start_gfn;
308 kvm_flush_remote_tlbs_with_range(kvm, &range);
311 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value, u64 access_mask)
313 BUG_ON((u64)(unsigned)access_mask != access_mask);
314 BUG_ON((mmio_mask & mmio_value) != mmio_value);
315 shadow_mmio_value = mmio_value | SPTE_MMIO_MASK;
316 shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
317 shadow_mmio_access_mask = access_mask;
319 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
321 static bool is_mmio_spte(u64 spte)
323 return (spte & shadow_mmio_mask) == shadow_mmio_value;
326 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
328 return sp->role.ad_disabled;
331 static inline bool spte_ad_enabled(u64 spte)
333 MMU_WARN_ON(is_mmio_spte(spte));
334 return (spte & SPTE_SPECIAL_MASK) == SPTE_AD_ENABLED_MASK;
337 static inline u64 spte_shadow_accessed_mask(u64 spte)
339 MMU_WARN_ON(is_mmio_spte(spte));
340 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
343 static inline u64 spte_shadow_dirty_mask(u64 spte)
345 MMU_WARN_ON(is_mmio_spte(spte));
346 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
349 static inline bool is_access_track_spte(u64 spte)
351 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
355 * Due to limited space in PTEs, the MMIO generation is a 19 bit subset of
356 * the memslots generation and is derived as follows:
358 * Bits 0-8 of the MMIO generation are propagated to spte bits 3-11
359 * Bits 9-18 of the MMIO generation are propagated to spte bits 52-61
361 * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
362 * the MMIO generation number, as doing so would require stealing a bit from
363 * the "real" generation number and thus effectively halve the maximum number
364 * of MMIO generations that can be handled before encountering a wrap (which
365 * requires a full MMU zap). The flag is instead explicitly queried when
366 * checking for MMIO spte cache hits.
368 #define MMIO_SPTE_GEN_MASK GENMASK_ULL(18, 0)
370 #define MMIO_SPTE_GEN_LOW_START 3
371 #define MMIO_SPTE_GEN_LOW_END 11
372 #define MMIO_SPTE_GEN_LOW_MASK GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
373 MMIO_SPTE_GEN_LOW_START)
375 #define MMIO_SPTE_GEN_HIGH_START 52
376 #define MMIO_SPTE_GEN_HIGH_END 61
377 #define MMIO_SPTE_GEN_HIGH_MASK GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
378 MMIO_SPTE_GEN_HIGH_START)
379 static u64 generation_mmio_spte_mask(u64 gen)
383 WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
385 mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
386 mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
390 static u64 get_mmio_spte_generation(u64 spte)
394 spte &= ~shadow_mmio_mask;
396 gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
397 gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
401 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
404 u64 gen = kvm_vcpu_memslots(vcpu)->generation & MMIO_SPTE_GEN_MASK;
405 u64 mask = generation_mmio_spte_mask(gen);
406 u64 gpa = gfn << PAGE_SHIFT;
408 access &= shadow_mmio_access_mask;
409 mask |= shadow_mmio_value | access;
410 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
411 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
412 << shadow_nonpresent_or_rsvd_mask_len;
414 trace_mark_mmio_spte(sptep, gfn, access, gen);
415 mmu_spte_set(sptep, mask);
418 static gfn_t get_mmio_spte_gfn(u64 spte)
420 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
422 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
423 & shadow_nonpresent_or_rsvd_mask;
425 return gpa >> PAGE_SHIFT;
428 static unsigned get_mmio_spte_access(u64 spte)
430 return spte & shadow_mmio_access_mask;
433 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
434 kvm_pfn_t pfn, unsigned access)
436 if (unlikely(is_noslot_pfn(pfn))) {
437 mark_mmio_spte(vcpu, sptep, gfn, access);
444 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
446 u64 kvm_gen, spte_gen, gen;
448 gen = kvm_vcpu_memslots(vcpu)->generation;
449 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
452 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
453 spte_gen = get_mmio_spte_generation(spte);
455 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
456 return likely(kvm_gen == spte_gen);
460 * Sets the shadow PTE masks used by the MMU.
463 * - Setting either @accessed_mask or @dirty_mask requires setting both
464 * - At least one of @accessed_mask or @acc_track_mask must be set
466 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
467 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
468 u64 acc_track_mask, u64 me_mask)
470 BUG_ON(!dirty_mask != !accessed_mask);
471 BUG_ON(!accessed_mask && !acc_track_mask);
472 BUG_ON(acc_track_mask & SPTE_SPECIAL_MASK);
474 shadow_user_mask = user_mask;
475 shadow_accessed_mask = accessed_mask;
476 shadow_dirty_mask = dirty_mask;
477 shadow_nx_mask = nx_mask;
478 shadow_x_mask = x_mask;
479 shadow_present_mask = p_mask;
480 shadow_acc_track_mask = acc_track_mask;
481 shadow_me_mask = me_mask;
483 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
485 static u8 kvm_get_shadow_phys_bits(void)
488 * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
489 * in CPU detection code, but MKTME treats those reduced bits as
490 * 'keyID' thus they are not reserved bits. Therefore for MKTME
491 * we should still return physical address bits reported by CPUID.
493 if (!boot_cpu_has(X86_FEATURE_TME) ||
494 WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
495 return boot_cpu_data.x86_phys_bits;
497 return cpuid_eax(0x80000008) & 0xff;
500 static void kvm_mmu_reset_all_pte_masks(void)
504 shadow_user_mask = 0;
505 shadow_accessed_mask = 0;
506 shadow_dirty_mask = 0;
509 shadow_mmio_mask = 0;
510 shadow_present_mask = 0;
511 shadow_acc_track_mask = 0;
513 shadow_phys_bits = kvm_get_shadow_phys_bits();
516 * If the CPU has 46 or less physical address bits, then set an
517 * appropriate mask to guard against L1TF attacks. Otherwise, it is
518 * assumed that the CPU is not vulnerable to L1TF.
520 * Some Intel CPUs address the L1 cache using more PA bits than are
521 * reported by CPUID. Use the PA width of the L1 cache when possible
522 * to achieve more effective mitigation, e.g. if system RAM overlaps
523 * the most significant bits of legal physical address space.
525 shadow_nonpresent_or_rsvd_mask = 0;
526 low_phys_bits = boot_cpu_data.x86_cache_bits;
527 if (boot_cpu_data.x86_cache_bits <
528 52 - shadow_nonpresent_or_rsvd_mask_len) {
529 shadow_nonpresent_or_rsvd_mask =
530 rsvd_bits(boot_cpu_data.x86_cache_bits -
531 shadow_nonpresent_or_rsvd_mask_len,
532 boot_cpu_data.x86_cache_bits - 1);
533 low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
535 WARN_ON_ONCE(boot_cpu_has_bug(X86_BUG_L1TF));
537 shadow_nonpresent_or_rsvd_lower_gfn_mask =
538 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
541 static int is_cpuid_PSE36(void)
546 static int is_nx(struct kvm_vcpu *vcpu)
548 return vcpu->arch.efer & EFER_NX;
551 static int is_shadow_present_pte(u64 pte)
553 return (pte != 0) && !is_mmio_spte(pte);
556 static int is_large_pte(u64 pte)
558 return pte & PT_PAGE_SIZE_MASK;
561 static int is_last_spte(u64 pte, int level)
563 if (level == PT_PAGE_TABLE_LEVEL)
565 if (is_large_pte(pte))
570 static bool is_executable_pte(u64 spte)
572 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
575 static kvm_pfn_t spte_to_pfn(u64 pte)
577 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
580 static gfn_t pse36_gfn_delta(u32 gpte)
582 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
584 return (gpte & PT32_DIR_PSE36_MASK) << shift;
588 static void __set_spte(u64 *sptep, u64 spte)
590 WRITE_ONCE(*sptep, spte);
593 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
595 WRITE_ONCE(*sptep, spte);
598 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
600 return xchg(sptep, spte);
603 static u64 __get_spte_lockless(u64 *sptep)
605 return READ_ONCE(*sptep);
616 static void count_spte_clear(u64 *sptep, u64 spte)
618 struct kvm_mmu_page *sp = page_header(__pa(sptep));
620 if (is_shadow_present_pte(spte))
623 /* Ensure the spte is completely set before we increase the count */
625 sp->clear_spte_count++;
628 static void __set_spte(u64 *sptep, u64 spte)
630 union split_spte *ssptep, sspte;
632 ssptep = (union split_spte *)sptep;
633 sspte = (union split_spte)spte;
635 ssptep->spte_high = sspte.spte_high;
638 * If we map the spte from nonpresent to present, We should store
639 * the high bits firstly, then set present bit, so cpu can not
640 * fetch this spte while we are setting the spte.
644 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
647 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
649 union split_spte *ssptep, sspte;
651 ssptep = (union split_spte *)sptep;
652 sspte = (union split_spte)spte;
654 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
657 * If we map the spte from present to nonpresent, we should clear
658 * present bit firstly to avoid vcpu fetch the old high bits.
662 ssptep->spte_high = sspte.spte_high;
663 count_spte_clear(sptep, spte);
666 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
668 union split_spte *ssptep, sspte, orig;
670 ssptep = (union split_spte *)sptep;
671 sspte = (union split_spte)spte;
673 /* xchg acts as a barrier before the setting of the high bits */
674 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
675 orig.spte_high = ssptep->spte_high;
676 ssptep->spte_high = sspte.spte_high;
677 count_spte_clear(sptep, spte);
683 * The idea using the light way get the spte on x86_32 guest is from
684 * gup_get_pte (mm/gup.c).
686 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
687 * coalesces them and we are running out of the MMU lock. Therefore
688 * we need to protect against in-progress updates of the spte.
690 * Reading the spte while an update is in progress may get the old value
691 * for the high part of the spte. The race is fine for a present->non-present
692 * change (because the high part of the spte is ignored for non-present spte),
693 * but for a present->present change we must reread the spte.
695 * All such changes are done in two steps (present->non-present and
696 * non-present->present), hence it is enough to count the number of
697 * present->non-present updates: if it changed while reading the spte,
698 * we might have hit the race. This is done using clear_spte_count.
700 static u64 __get_spte_lockless(u64 *sptep)
702 struct kvm_mmu_page *sp = page_header(__pa(sptep));
703 union split_spte spte, *orig = (union split_spte *)sptep;
707 count = sp->clear_spte_count;
710 spte.spte_low = orig->spte_low;
713 spte.spte_high = orig->spte_high;
716 if (unlikely(spte.spte_low != orig->spte_low ||
717 count != sp->clear_spte_count))
724 static bool spte_can_locklessly_be_made_writable(u64 spte)
726 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
727 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
730 static bool spte_has_volatile_bits(u64 spte)
732 if (!is_shadow_present_pte(spte))
736 * Always atomically update spte if it can be updated
737 * out of mmu-lock, it can ensure dirty bit is not lost,
738 * also, it can help us to get a stable is_writable_pte()
739 * to ensure tlb flush is not missed.
741 if (spte_can_locklessly_be_made_writable(spte) ||
742 is_access_track_spte(spte))
745 if (spte_ad_enabled(spte)) {
746 if ((spte & shadow_accessed_mask) == 0 ||
747 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
754 static bool is_accessed_spte(u64 spte)
756 u64 accessed_mask = spte_shadow_accessed_mask(spte);
758 return accessed_mask ? spte & accessed_mask
759 : !is_access_track_spte(spte);
762 static bool is_dirty_spte(u64 spte)
764 u64 dirty_mask = spte_shadow_dirty_mask(spte);
766 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
769 /* Rules for using mmu_spte_set:
770 * Set the sptep from nonpresent to present.
771 * Note: the sptep being assigned *must* be either not present
772 * or in a state where the hardware will not attempt to update
775 static void mmu_spte_set(u64 *sptep, u64 new_spte)
777 WARN_ON(is_shadow_present_pte(*sptep));
778 __set_spte(sptep, new_spte);
782 * Update the SPTE (excluding the PFN), but do not track changes in its
783 * accessed/dirty status.
785 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
787 u64 old_spte = *sptep;
789 WARN_ON(!is_shadow_present_pte(new_spte));
791 if (!is_shadow_present_pte(old_spte)) {
792 mmu_spte_set(sptep, new_spte);
796 if (!spte_has_volatile_bits(old_spte))
797 __update_clear_spte_fast(sptep, new_spte);
799 old_spte = __update_clear_spte_slow(sptep, new_spte);
801 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
806 /* Rules for using mmu_spte_update:
807 * Update the state bits, it means the mapped pfn is not changed.
809 * Whenever we overwrite a writable spte with a read-only one we
810 * should flush remote TLBs. Otherwise rmap_write_protect
811 * will find a read-only spte, even though the writable spte
812 * might be cached on a CPU's TLB, the return value indicates this
815 * Returns true if the TLB needs to be flushed
817 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
820 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
822 if (!is_shadow_present_pte(old_spte))
826 * For the spte updated out of mmu-lock is safe, since
827 * we always atomically update it, see the comments in
828 * spte_has_volatile_bits().
830 if (spte_can_locklessly_be_made_writable(old_spte) &&
831 !is_writable_pte(new_spte))
835 * Flush TLB when accessed/dirty states are changed in the page tables,
836 * to guarantee consistency between TLB and page tables.
839 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
841 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
844 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
846 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
853 * Rules for using mmu_spte_clear_track_bits:
854 * It sets the sptep from present to nonpresent, and track the
855 * state bits, it is used to clear the last level sptep.
856 * Returns non-zero if the PTE was previously valid.
858 static int mmu_spte_clear_track_bits(u64 *sptep)
861 u64 old_spte = *sptep;
863 if (!spte_has_volatile_bits(old_spte))
864 __update_clear_spte_fast(sptep, 0ull);
866 old_spte = __update_clear_spte_slow(sptep, 0ull);
868 if (!is_shadow_present_pte(old_spte))
871 pfn = spte_to_pfn(old_spte);
874 * KVM does not hold the refcount of the page used by
875 * kvm mmu, before reclaiming the page, we should
876 * unmap it from mmu first.
878 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
880 if (is_accessed_spte(old_spte))
881 kvm_set_pfn_accessed(pfn);
883 if (is_dirty_spte(old_spte))
884 kvm_set_pfn_dirty(pfn);
890 * Rules for using mmu_spte_clear_no_track:
891 * Directly clear spte without caring the state bits of sptep,
892 * it is used to set the upper level spte.
894 static void mmu_spte_clear_no_track(u64 *sptep)
896 __update_clear_spte_fast(sptep, 0ull);
899 static u64 mmu_spte_get_lockless(u64 *sptep)
901 return __get_spte_lockless(sptep);
904 static u64 mark_spte_for_access_track(u64 spte)
906 if (spte_ad_enabled(spte))
907 return spte & ~shadow_accessed_mask;
909 if (is_access_track_spte(spte))
913 * Making an Access Tracking PTE will result in removal of write access
914 * from the PTE. So, verify that we will be able to restore the write
915 * access in the fast page fault path later on.
917 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
918 !spte_can_locklessly_be_made_writable(spte),
919 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
921 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
922 shadow_acc_track_saved_bits_shift),
923 "kvm: Access Tracking saved bit locations are not zero\n");
925 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
926 shadow_acc_track_saved_bits_shift;
927 spte &= ~shadow_acc_track_mask;
932 /* Restore an acc-track PTE back to a regular PTE */
933 static u64 restore_acc_track_spte(u64 spte)
936 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
937 & shadow_acc_track_saved_bits_mask;
939 WARN_ON_ONCE(spte_ad_enabled(spte));
940 WARN_ON_ONCE(!is_access_track_spte(spte));
942 new_spte &= ~shadow_acc_track_mask;
943 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
944 shadow_acc_track_saved_bits_shift);
945 new_spte |= saved_bits;
950 /* Returns the Accessed status of the PTE and resets it at the same time. */
951 static bool mmu_spte_age(u64 *sptep)
953 u64 spte = mmu_spte_get_lockless(sptep);
955 if (!is_accessed_spte(spte))
958 if (spte_ad_enabled(spte)) {
959 clear_bit((ffs(shadow_accessed_mask) - 1),
960 (unsigned long *)sptep);
963 * Capture the dirty status of the page, so that it doesn't get
964 * lost when the SPTE is marked for access tracking.
966 if (is_writable_pte(spte))
967 kvm_set_pfn_dirty(spte_to_pfn(spte));
969 spte = mark_spte_for_access_track(spte);
970 mmu_spte_update_no_track(sptep, spte);
976 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
979 * Prevent page table teardown by making any free-er wait during
980 * kvm_flush_remote_tlbs() IPI to all active vcpus.
985 * Make sure a following spte read is not reordered ahead of the write
988 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
991 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
994 * Make sure the write to vcpu->mode is not reordered in front of
995 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
996 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
998 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
1002 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
1003 struct kmem_cache *base_cache, int min)
1007 if (cache->nobjs >= min)
1009 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1010 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL_ACCOUNT);
1012 return cache->nobjs >= min ? 0 : -ENOMEM;
1013 cache->objects[cache->nobjs++] = obj;
1018 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
1020 return cache->nobjs;
1023 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
1024 struct kmem_cache *cache)
1027 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
1030 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1035 if (cache->nobjs >= min)
1037 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1038 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1040 return cache->nobjs >= min ? 0 : -ENOMEM;
1041 cache->objects[cache->nobjs++] = page;
1046 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1049 free_page((unsigned long)mc->objects[--mc->nobjs]);
1052 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1056 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1057 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1060 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1063 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1064 mmu_page_header_cache, 4);
1069 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1071 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1072 pte_list_desc_cache);
1073 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1074 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1075 mmu_page_header_cache);
1078 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1083 p = mc->objects[--mc->nobjs];
1087 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1089 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1092 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1094 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1097 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1099 if (!sp->role.direct)
1100 return sp->gfns[index];
1102 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1105 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1107 if (!sp->role.direct) {
1108 sp->gfns[index] = gfn;
1112 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1113 pr_err_ratelimited("gfn mismatch under direct page %llx "
1114 "(expected %llx, got %llx)\n",
1116 kvm_mmu_page_get_gfn(sp, index), gfn);
1120 * Return the pointer to the large page information for a given gfn,
1121 * handling slots that are not large page aligned.
1123 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1124 struct kvm_memory_slot *slot,
1129 idx = gfn_to_index(gfn, slot->base_gfn, level);
1130 return &slot->arch.lpage_info[level - 2][idx];
1133 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1134 gfn_t gfn, int count)
1136 struct kvm_lpage_info *linfo;
1139 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1140 linfo = lpage_info_slot(gfn, slot, i);
1141 linfo->disallow_lpage += count;
1142 WARN_ON(linfo->disallow_lpage < 0);
1146 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1148 update_gfn_disallow_lpage_count(slot, gfn, 1);
1151 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1153 update_gfn_disallow_lpage_count(slot, gfn, -1);
1156 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1158 struct kvm_memslots *slots;
1159 struct kvm_memory_slot *slot;
1162 kvm->arch.indirect_shadow_pages++;
1164 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1165 slot = __gfn_to_memslot(slots, gfn);
1167 /* the non-leaf shadow pages are keeping readonly. */
1168 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1169 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1170 KVM_PAGE_TRACK_WRITE);
1172 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1175 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1177 struct kvm_memslots *slots;
1178 struct kvm_memory_slot *slot;
1181 kvm->arch.indirect_shadow_pages--;
1183 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1184 slot = __gfn_to_memslot(slots, gfn);
1185 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1186 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1187 KVM_PAGE_TRACK_WRITE);
1189 kvm_mmu_gfn_allow_lpage(slot, gfn);
1192 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1193 struct kvm_memory_slot *slot)
1195 struct kvm_lpage_info *linfo;
1198 linfo = lpage_info_slot(gfn, slot, level);
1199 return !!linfo->disallow_lpage;
1205 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1208 struct kvm_memory_slot *slot;
1210 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1211 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1214 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1216 unsigned long page_size;
1219 page_size = kvm_host_page_size(kvm, gfn);
1221 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1222 if (page_size >= KVM_HPAGE_SIZE(i))
1231 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1234 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1236 if (no_dirty_log && slot->dirty_bitmap)
1242 static struct kvm_memory_slot *
1243 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1246 struct kvm_memory_slot *slot;
1248 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1249 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1255 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1256 bool *force_pt_level)
1258 int host_level, level, max_level;
1259 struct kvm_memory_slot *slot;
1261 if (unlikely(*force_pt_level))
1262 return PT_PAGE_TABLE_LEVEL;
1264 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1265 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1266 if (unlikely(*force_pt_level))
1267 return PT_PAGE_TABLE_LEVEL;
1269 host_level = host_mapping_level(vcpu->kvm, large_gfn);
1271 if (host_level == PT_PAGE_TABLE_LEVEL)
1274 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1276 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1277 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1284 * About rmap_head encoding:
1286 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1287 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1288 * pte_list_desc containing more mappings.
1292 * Returns the number of pointers in the rmap chain, not counting the new one.
1294 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1295 struct kvm_rmap_head *rmap_head)
1297 struct pte_list_desc *desc;
1300 if (!rmap_head->val) {
1301 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1302 rmap_head->val = (unsigned long)spte;
1303 } else if (!(rmap_head->val & 1)) {
1304 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1305 desc = mmu_alloc_pte_list_desc(vcpu);
1306 desc->sptes[0] = (u64 *)rmap_head->val;
1307 desc->sptes[1] = spte;
1308 rmap_head->val = (unsigned long)desc | 1;
1311 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1312 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1313 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1315 count += PTE_LIST_EXT;
1317 if (desc->sptes[PTE_LIST_EXT-1]) {
1318 desc->more = mmu_alloc_pte_list_desc(vcpu);
1321 for (i = 0; desc->sptes[i]; ++i)
1323 desc->sptes[i] = spte;
1329 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1330 struct pte_list_desc *desc, int i,
1331 struct pte_list_desc *prev_desc)
1335 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1337 desc->sptes[i] = desc->sptes[j];
1338 desc->sptes[j] = NULL;
1341 if (!prev_desc && !desc->more)
1342 rmap_head->val = (unsigned long)desc->sptes[0];
1345 prev_desc->more = desc->more;
1347 rmap_head->val = (unsigned long)desc->more | 1;
1348 mmu_free_pte_list_desc(desc);
1351 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1353 struct pte_list_desc *desc;
1354 struct pte_list_desc *prev_desc;
1357 if (!rmap_head->val) {
1358 pr_err("%s: %p 0->BUG\n", __func__, spte);
1360 } else if (!(rmap_head->val & 1)) {
1361 rmap_printk("%s: %p 1->0\n", __func__, spte);
1362 if ((u64 *)rmap_head->val != spte) {
1363 pr_err("%s: %p 1->BUG\n", __func__, spte);
1368 rmap_printk("%s: %p many->many\n", __func__, spte);
1369 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1372 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1373 if (desc->sptes[i] == spte) {
1374 pte_list_desc_remove_entry(rmap_head,
1375 desc, i, prev_desc);
1382 pr_err("%s: %p many->many\n", __func__, spte);
1387 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1389 mmu_spte_clear_track_bits(sptep);
1390 __pte_list_remove(sptep, rmap_head);
1393 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1394 struct kvm_memory_slot *slot)
1398 idx = gfn_to_index(gfn, slot->base_gfn, level);
1399 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1402 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1403 struct kvm_mmu_page *sp)
1405 struct kvm_memslots *slots;
1406 struct kvm_memory_slot *slot;
1408 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1409 slot = __gfn_to_memslot(slots, gfn);
1410 return __gfn_to_rmap(gfn, sp->role.level, slot);
1413 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1415 struct kvm_mmu_memory_cache *cache;
1417 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1418 return mmu_memory_cache_free_objects(cache);
1421 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1423 struct kvm_mmu_page *sp;
1424 struct kvm_rmap_head *rmap_head;
1426 sp = page_header(__pa(spte));
1427 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1428 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1429 return pte_list_add(vcpu, spte, rmap_head);
1432 static void rmap_remove(struct kvm *kvm, u64 *spte)
1434 struct kvm_mmu_page *sp;
1436 struct kvm_rmap_head *rmap_head;
1438 sp = page_header(__pa(spte));
1439 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1440 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1441 __pte_list_remove(spte, rmap_head);
1445 * Used by the following functions to iterate through the sptes linked by a
1446 * rmap. All fields are private and not assumed to be used outside.
1448 struct rmap_iterator {
1449 /* private fields */
1450 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1451 int pos; /* index of the sptep */
1455 * Iteration must be started by this function. This should also be used after
1456 * removing/dropping sptes from the rmap link because in such cases the
1457 * information in the itererator may not be valid.
1459 * Returns sptep if found, NULL otherwise.
1461 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1462 struct rmap_iterator *iter)
1466 if (!rmap_head->val)
1469 if (!(rmap_head->val & 1)) {
1471 sptep = (u64 *)rmap_head->val;
1475 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1477 sptep = iter->desc->sptes[iter->pos];
1479 BUG_ON(!is_shadow_present_pte(*sptep));
1484 * Must be used with a valid iterator: e.g. after rmap_get_first().
1486 * Returns sptep if found, NULL otherwise.
1488 static u64 *rmap_get_next(struct rmap_iterator *iter)
1493 if (iter->pos < PTE_LIST_EXT - 1) {
1495 sptep = iter->desc->sptes[iter->pos];
1500 iter->desc = iter->desc->more;
1504 /* desc->sptes[0] cannot be NULL */
1505 sptep = iter->desc->sptes[iter->pos];
1512 BUG_ON(!is_shadow_present_pte(*sptep));
1516 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1517 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1518 _spte_; _spte_ = rmap_get_next(_iter_))
1520 static void drop_spte(struct kvm *kvm, u64 *sptep)
1522 if (mmu_spte_clear_track_bits(sptep))
1523 rmap_remove(kvm, sptep);
1527 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1529 if (is_large_pte(*sptep)) {
1530 WARN_ON(page_header(__pa(sptep))->role.level ==
1531 PT_PAGE_TABLE_LEVEL);
1532 drop_spte(kvm, sptep);
1540 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1542 if (__drop_large_spte(vcpu->kvm, sptep)) {
1543 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1545 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1546 KVM_PAGES_PER_HPAGE(sp->role.level));
1551 * Write-protect on the specified @sptep, @pt_protect indicates whether
1552 * spte write-protection is caused by protecting shadow page table.
1554 * Note: write protection is difference between dirty logging and spte
1556 * - for dirty logging, the spte can be set to writable at anytime if
1557 * its dirty bitmap is properly set.
1558 * - for spte protection, the spte can be writable only after unsync-ing
1561 * Return true if tlb need be flushed.
1563 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1567 if (!is_writable_pte(spte) &&
1568 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1571 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1574 spte &= ~SPTE_MMU_WRITEABLE;
1575 spte = spte & ~PT_WRITABLE_MASK;
1577 return mmu_spte_update(sptep, spte);
1580 static bool __rmap_write_protect(struct kvm *kvm,
1581 struct kvm_rmap_head *rmap_head,
1585 struct rmap_iterator iter;
1588 for_each_rmap_spte(rmap_head, &iter, sptep)
1589 flush |= spte_write_protect(sptep, pt_protect);
1594 static bool spte_clear_dirty(u64 *sptep)
1598 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1600 spte &= ~shadow_dirty_mask;
1602 return mmu_spte_update(sptep, spte);
1605 static bool wrprot_ad_disabled_spte(u64 *sptep)
1607 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1608 (unsigned long *)sptep);
1610 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1612 return was_writable;
1616 * Gets the GFN ready for another round of dirty logging by clearing the
1617 * - D bit on ad-enabled SPTEs, and
1618 * - W bit on ad-disabled SPTEs.
1619 * Returns true iff any D or W bits were cleared.
1621 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1624 struct rmap_iterator iter;
1627 for_each_rmap_spte(rmap_head, &iter, sptep)
1628 if (spte_ad_enabled(*sptep))
1629 flush |= spte_clear_dirty(sptep);
1631 flush |= wrprot_ad_disabled_spte(sptep);
1636 static bool spte_set_dirty(u64 *sptep)
1640 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1642 spte |= shadow_dirty_mask;
1644 return mmu_spte_update(sptep, spte);
1647 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1650 struct rmap_iterator iter;
1653 for_each_rmap_spte(rmap_head, &iter, sptep)
1654 if (spte_ad_enabled(*sptep))
1655 flush |= spte_set_dirty(sptep);
1661 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1662 * @kvm: kvm instance
1663 * @slot: slot to protect
1664 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1665 * @mask: indicates which pages we should protect
1667 * Used when we do not need to care about huge page mappings: e.g. during dirty
1668 * logging we do not have any such mappings.
1670 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1671 struct kvm_memory_slot *slot,
1672 gfn_t gfn_offset, unsigned long mask)
1674 struct kvm_rmap_head *rmap_head;
1677 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1678 PT_PAGE_TABLE_LEVEL, slot);
1679 __rmap_write_protect(kvm, rmap_head, false);
1681 /* clear the first set bit */
1687 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1688 * protect the page if the D-bit isn't supported.
1689 * @kvm: kvm instance
1690 * @slot: slot to clear D-bit
1691 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1692 * @mask: indicates which pages we should clear D-bit
1694 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1696 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1697 struct kvm_memory_slot *slot,
1698 gfn_t gfn_offset, unsigned long mask)
1700 struct kvm_rmap_head *rmap_head;
1703 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1704 PT_PAGE_TABLE_LEVEL, slot);
1705 __rmap_clear_dirty(kvm, rmap_head);
1707 /* clear the first set bit */
1711 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1714 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1717 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1718 * enable dirty logging for them.
1720 * Used when we do not need to care about huge page mappings: e.g. during dirty
1721 * logging we do not have any such mappings.
1723 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1724 struct kvm_memory_slot *slot,
1725 gfn_t gfn_offset, unsigned long mask)
1727 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1728 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1731 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1735 * kvm_arch_write_log_dirty - emulate dirty page logging
1736 * @vcpu: Guest mode vcpu
1738 * Emulate arch specific page modification logging for the
1741 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1743 if (kvm_x86_ops->write_log_dirty)
1744 return kvm_x86_ops->write_log_dirty(vcpu);
1749 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1750 struct kvm_memory_slot *slot, u64 gfn)
1752 struct kvm_rmap_head *rmap_head;
1754 bool write_protected = false;
1756 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1757 rmap_head = __gfn_to_rmap(gfn, i, slot);
1758 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1761 return write_protected;
1764 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1766 struct kvm_memory_slot *slot;
1768 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1769 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1772 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1775 struct rmap_iterator iter;
1778 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1779 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1781 pte_list_remove(rmap_head, sptep);
1788 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1789 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1792 return kvm_zap_rmapp(kvm, rmap_head);
1795 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1796 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1800 struct rmap_iterator iter;
1803 pte_t *ptep = (pte_t *)data;
1806 WARN_ON(pte_huge(*ptep));
1807 new_pfn = pte_pfn(*ptep);
1810 for_each_rmap_spte(rmap_head, &iter, sptep) {
1811 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1812 sptep, *sptep, gfn, level);
1816 if (pte_write(*ptep)) {
1817 pte_list_remove(rmap_head, sptep);
1820 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1821 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1823 new_spte &= ~PT_WRITABLE_MASK;
1824 new_spte &= ~SPTE_HOST_WRITEABLE;
1826 new_spte = mark_spte_for_access_track(new_spte);
1828 mmu_spte_clear_track_bits(sptep);
1829 mmu_spte_set(sptep, new_spte);
1833 if (need_flush && kvm_available_flush_tlb_with_range()) {
1834 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1841 struct slot_rmap_walk_iterator {
1843 struct kvm_memory_slot *slot;
1849 /* output fields. */
1851 struct kvm_rmap_head *rmap;
1854 /* private field. */
1855 struct kvm_rmap_head *end_rmap;
1859 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1861 iterator->level = level;
1862 iterator->gfn = iterator->start_gfn;
1863 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1864 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1869 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1870 struct kvm_memory_slot *slot, int start_level,
1871 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1873 iterator->slot = slot;
1874 iterator->start_level = start_level;
1875 iterator->end_level = end_level;
1876 iterator->start_gfn = start_gfn;
1877 iterator->end_gfn = end_gfn;
1879 rmap_walk_init_level(iterator, iterator->start_level);
1882 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1884 return !!iterator->rmap;
1887 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1889 if (++iterator->rmap <= iterator->end_rmap) {
1890 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1894 if (++iterator->level > iterator->end_level) {
1895 iterator->rmap = NULL;
1899 rmap_walk_init_level(iterator, iterator->level);
1902 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1903 _start_gfn, _end_gfn, _iter_) \
1904 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1905 _end_level_, _start_gfn, _end_gfn); \
1906 slot_rmap_walk_okay(_iter_); \
1907 slot_rmap_walk_next(_iter_))
1909 static int kvm_handle_hva_range(struct kvm *kvm,
1910 unsigned long start,
1913 int (*handler)(struct kvm *kvm,
1914 struct kvm_rmap_head *rmap_head,
1915 struct kvm_memory_slot *slot,
1918 unsigned long data))
1920 struct kvm_memslots *slots;
1921 struct kvm_memory_slot *memslot;
1922 struct slot_rmap_walk_iterator iterator;
1926 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1927 slots = __kvm_memslots(kvm, i);
1928 kvm_for_each_memslot(memslot, slots) {
1929 unsigned long hva_start, hva_end;
1930 gfn_t gfn_start, gfn_end;
1932 hva_start = max(start, memslot->userspace_addr);
1933 hva_end = min(end, memslot->userspace_addr +
1934 (memslot->npages << PAGE_SHIFT));
1935 if (hva_start >= hva_end)
1938 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1939 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1941 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1942 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1944 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1945 PT_MAX_HUGEPAGE_LEVEL,
1946 gfn_start, gfn_end - 1,
1948 ret |= handler(kvm, iterator.rmap, memslot,
1949 iterator.gfn, iterator.level, data);
1956 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1958 int (*handler)(struct kvm *kvm,
1959 struct kvm_rmap_head *rmap_head,
1960 struct kvm_memory_slot *slot,
1961 gfn_t gfn, int level,
1962 unsigned long data))
1964 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1967 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1969 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1972 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1974 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1977 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1978 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1982 struct rmap_iterator uninitialized_var(iter);
1985 for_each_rmap_spte(rmap_head, &iter, sptep)
1986 young |= mmu_spte_age(sptep);
1988 trace_kvm_age_page(gfn, level, slot, young);
1992 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1993 struct kvm_memory_slot *slot, gfn_t gfn,
1994 int level, unsigned long data)
1997 struct rmap_iterator iter;
1999 for_each_rmap_spte(rmap_head, &iter, sptep)
2000 if (is_accessed_spte(*sptep))
2005 #define RMAP_RECYCLE_THRESHOLD 1000
2007 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2009 struct kvm_rmap_head *rmap_head;
2010 struct kvm_mmu_page *sp;
2012 sp = page_header(__pa(spte));
2014 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2016 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2017 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
2018 KVM_PAGES_PER_HPAGE(sp->role.level));
2021 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2023 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2026 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2028 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2032 static int is_empty_shadow_page(u64 *spt)
2037 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2038 if (is_shadow_present_pte(*pos)) {
2039 printk(KERN_ERR "%s: %p %llx\n", __func__,
2048 * This value is the sum of all of the kvm instances's
2049 * kvm->arch.n_used_mmu_pages values. We need a global,
2050 * aggregate version in order to make the slab shrinker
2053 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2055 kvm->arch.n_used_mmu_pages += nr;
2056 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2059 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2061 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2062 hlist_del(&sp->hash_link);
2063 list_del(&sp->link);
2064 free_page((unsigned long)sp->spt);
2065 if (!sp->role.direct)
2066 free_page((unsigned long)sp->gfns);
2067 kmem_cache_free(mmu_page_header_cache, sp);
2070 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2072 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2075 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2076 struct kvm_mmu_page *sp, u64 *parent_pte)
2081 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2084 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2087 __pte_list_remove(parent_pte, &sp->parent_ptes);
2090 static void drop_parent_pte(struct kvm_mmu_page *sp,
2093 mmu_page_remove_parent_pte(sp, parent_pte);
2094 mmu_spte_clear_no_track(parent_pte);
2097 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2099 struct kvm_mmu_page *sp;
2101 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2102 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2104 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2105 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2108 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2109 * depends on valid pages being added to the head of the list. See
2110 * comments in kvm_zap_obsolete_pages().
2112 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2113 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2114 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2118 static void mark_unsync(u64 *spte);
2119 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2122 struct rmap_iterator iter;
2124 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2129 static void mark_unsync(u64 *spte)
2131 struct kvm_mmu_page *sp;
2134 sp = page_header(__pa(spte));
2135 index = spte - sp->spt;
2136 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2138 if (sp->unsync_children++)
2140 kvm_mmu_mark_parents_unsync(sp);
2143 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2144 struct kvm_mmu_page *sp)
2149 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2153 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2154 struct kvm_mmu_page *sp, u64 *spte,
2160 #define KVM_PAGE_ARRAY_NR 16
2162 struct kvm_mmu_pages {
2163 struct mmu_page_and_offset {
2164 struct kvm_mmu_page *sp;
2166 } page[KVM_PAGE_ARRAY_NR];
2170 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2176 for (i=0; i < pvec->nr; i++)
2177 if (pvec->page[i].sp == sp)
2180 pvec->page[pvec->nr].sp = sp;
2181 pvec->page[pvec->nr].idx = idx;
2183 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2186 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2188 --sp->unsync_children;
2189 WARN_ON((int)sp->unsync_children < 0);
2190 __clear_bit(idx, sp->unsync_child_bitmap);
2193 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2194 struct kvm_mmu_pages *pvec)
2196 int i, ret, nr_unsync_leaf = 0;
2198 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2199 struct kvm_mmu_page *child;
2200 u64 ent = sp->spt[i];
2202 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2203 clear_unsync_child_bit(sp, i);
2207 child = page_header(ent & PT64_BASE_ADDR_MASK);
2209 if (child->unsync_children) {
2210 if (mmu_pages_add(pvec, child, i))
2213 ret = __mmu_unsync_walk(child, pvec);
2215 clear_unsync_child_bit(sp, i);
2217 } else if (ret > 0) {
2218 nr_unsync_leaf += ret;
2221 } else if (child->unsync) {
2223 if (mmu_pages_add(pvec, child, i))
2226 clear_unsync_child_bit(sp, i);
2229 return nr_unsync_leaf;
2232 #define INVALID_INDEX (-1)
2234 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2235 struct kvm_mmu_pages *pvec)
2238 if (!sp->unsync_children)
2241 mmu_pages_add(pvec, sp, INVALID_INDEX);
2242 return __mmu_unsync_walk(sp, pvec);
2245 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2247 WARN_ON(!sp->unsync);
2248 trace_kvm_mmu_sync_page(sp);
2250 --kvm->stat.mmu_unsync;
2253 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2254 struct list_head *invalid_list);
2255 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2256 struct list_head *invalid_list);
2259 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2260 hlist_for_each_entry(_sp, \
2261 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2262 if (is_obsolete_sp((_kvm), (_sp))) { \
2265 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2266 for_each_valid_sp(_kvm, _sp, _gfn) \
2267 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2269 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2271 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2274 /* @sp->gfn should be write-protected at the call site */
2275 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2276 struct list_head *invalid_list)
2278 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2279 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2280 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2287 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2288 struct list_head *invalid_list,
2291 if (!remote_flush && list_empty(invalid_list))
2294 if (!list_empty(invalid_list))
2295 kvm_mmu_commit_zap_page(kvm, invalid_list);
2297 kvm_flush_remote_tlbs(kvm);
2301 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2302 struct list_head *invalid_list,
2303 bool remote_flush, bool local_flush)
2305 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2309 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2312 #ifdef CONFIG_KVM_MMU_AUDIT
2313 #include "mmu_audit.c"
2315 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2316 static void mmu_audit_disable(void) { }
2319 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2321 return sp->role.invalid ||
2322 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2325 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2326 struct list_head *invalid_list)
2328 kvm_unlink_unsync_page(vcpu->kvm, sp);
2329 return __kvm_sync_page(vcpu, sp, invalid_list);
2332 /* @gfn should be write-protected at the call site */
2333 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2334 struct list_head *invalid_list)
2336 struct kvm_mmu_page *s;
2339 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2343 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2344 ret |= kvm_sync_page(vcpu, s, invalid_list);
2350 struct mmu_page_path {
2351 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2352 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2355 #define for_each_sp(pvec, sp, parents, i) \
2356 for (i = mmu_pages_first(&pvec, &parents); \
2357 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2358 i = mmu_pages_next(&pvec, &parents, i))
2360 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2361 struct mmu_page_path *parents,
2366 for (n = i+1; n < pvec->nr; n++) {
2367 struct kvm_mmu_page *sp = pvec->page[n].sp;
2368 unsigned idx = pvec->page[n].idx;
2369 int level = sp->role.level;
2371 parents->idx[level-1] = idx;
2372 if (level == PT_PAGE_TABLE_LEVEL)
2375 parents->parent[level-2] = sp;
2381 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2382 struct mmu_page_path *parents)
2384 struct kvm_mmu_page *sp;
2390 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2392 sp = pvec->page[0].sp;
2393 level = sp->role.level;
2394 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2396 parents->parent[level-2] = sp;
2398 /* Also set up a sentinel. Further entries in pvec are all
2399 * children of sp, so this element is never overwritten.
2401 parents->parent[level-1] = NULL;
2402 return mmu_pages_next(pvec, parents, 0);
2405 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2407 struct kvm_mmu_page *sp;
2408 unsigned int level = 0;
2411 unsigned int idx = parents->idx[level];
2412 sp = parents->parent[level];
2416 WARN_ON(idx == INVALID_INDEX);
2417 clear_unsync_child_bit(sp, idx);
2419 } while (!sp->unsync_children);
2422 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2423 struct kvm_mmu_page *parent)
2426 struct kvm_mmu_page *sp;
2427 struct mmu_page_path parents;
2428 struct kvm_mmu_pages pages;
2429 LIST_HEAD(invalid_list);
2432 while (mmu_unsync_walk(parent, &pages)) {
2433 bool protected = false;
2435 for_each_sp(pages, sp, parents, i)
2436 protected |= rmap_write_protect(vcpu, sp->gfn);
2439 kvm_flush_remote_tlbs(vcpu->kvm);
2443 for_each_sp(pages, sp, parents, i) {
2444 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2445 mmu_pages_clear_parents(&parents);
2447 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2448 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2449 cond_resched_lock(&vcpu->kvm->mmu_lock);
2454 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2457 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2459 atomic_set(&sp->write_flooding_count, 0);
2462 static void clear_sp_write_flooding_count(u64 *spte)
2464 struct kvm_mmu_page *sp = page_header(__pa(spte));
2466 __clear_sp_write_flooding_count(sp);
2469 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2476 union kvm_mmu_page_role role;
2478 struct kvm_mmu_page *sp;
2479 bool need_sync = false;
2482 LIST_HEAD(invalid_list);
2484 role = vcpu->arch.mmu->mmu_role.base;
2486 role.direct = direct;
2488 role.gpte_is_8_bytes = true;
2489 role.access = access;
2490 if (!vcpu->arch.mmu->direct_map
2491 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2492 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2493 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2494 role.quadrant = quadrant;
2496 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2497 if (sp->gfn != gfn) {
2502 if (!need_sync && sp->unsync)
2505 if (sp->role.word != role.word)
2509 /* The page is good, but __kvm_sync_page might still end
2510 * up zapping it. If so, break in order to rebuild it.
2512 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2515 WARN_ON(!list_empty(&invalid_list));
2516 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2519 if (sp->unsync_children)
2520 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2522 __clear_sp_write_flooding_count(sp);
2523 trace_kvm_mmu_get_page(sp, false);
2527 ++vcpu->kvm->stat.mmu_cache_miss;
2529 sp = kvm_mmu_alloc_page(vcpu, direct);
2533 hlist_add_head(&sp->hash_link,
2534 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2537 * we should do write protection before syncing pages
2538 * otherwise the content of the synced shadow page may
2539 * be inconsistent with guest page table.
2541 account_shadowed(vcpu->kvm, sp);
2542 if (level == PT_PAGE_TABLE_LEVEL &&
2543 rmap_write_protect(vcpu, gfn))
2544 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2546 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2547 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2549 clear_page(sp->spt);
2550 trace_kvm_mmu_get_page(sp, true);
2552 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2554 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2555 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2559 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2560 struct kvm_vcpu *vcpu, hpa_t root,
2563 iterator->addr = addr;
2564 iterator->shadow_addr = root;
2565 iterator->level = vcpu->arch.mmu->shadow_root_level;
2567 if (iterator->level == PT64_ROOT_4LEVEL &&
2568 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2569 !vcpu->arch.mmu->direct_map)
2572 if (iterator->level == PT32E_ROOT_LEVEL) {
2574 * prev_root is currently only used for 64-bit hosts. So only
2575 * the active root_hpa is valid here.
2577 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2579 iterator->shadow_addr
2580 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2581 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2583 if (!iterator->shadow_addr)
2584 iterator->level = 0;
2588 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2589 struct kvm_vcpu *vcpu, u64 addr)
2591 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2595 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2597 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2600 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2601 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2605 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2608 if (is_last_spte(spte, iterator->level)) {
2609 iterator->level = 0;
2613 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2617 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2619 __shadow_walk_next(iterator, *iterator->sptep);
2622 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2623 struct kvm_mmu_page *sp)
2627 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2629 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2630 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2632 if (sp_ad_disabled(sp))
2633 spte |= SPTE_AD_DISABLED_MASK;
2635 spte |= shadow_accessed_mask;
2637 mmu_spte_set(sptep, spte);
2639 mmu_page_add_parent_pte(vcpu, sp, sptep);
2641 if (sp->unsync_children || sp->unsync)
2645 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2646 unsigned direct_access)
2648 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2649 struct kvm_mmu_page *child;
2652 * For the direct sp, if the guest pte's dirty bit
2653 * changed form clean to dirty, it will corrupt the
2654 * sp's access: allow writable in the read-only sp,
2655 * so we should update the spte at this point to get
2656 * a new sp with the correct access.
2658 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2659 if (child->role.access == direct_access)
2662 drop_parent_pte(child, sptep);
2663 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2667 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2671 struct kvm_mmu_page *child;
2674 if (is_shadow_present_pte(pte)) {
2675 if (is_last_spte(pte, sp->role.level)) {
2676 drop_spte(kvm, spte);
2677 if (is_large_pte(pte))
2680 child = page_header(pte & PT64_BASE_ADDR_MASK);
2681 drop_parent_pte(child, spte);
2686 if (is_mmio_spte(pte))
2687 mmu_spte_clear_no_track(spte);
2692 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2693 struct kvm_mmu_page *sp)
2697 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2698 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2701 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2704 struct rmap_iterator iter;
2706 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2707 drop_parent_pte(sp, sptep);
2710 static int mmu_zap_unsync_children(struct kvm *kvm,
2711 struct kvm_mmu_page *parent,
2712 struct list_head *invalid_list)
2715 struct mmu_page_path parents;
2716 struct kvm_mmu_pages pages;
2718 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2721 while (mmu_unsync_walk(parent, &pages)) {
2722 struct kvm_mmu_page *sp;
2724 for_each_sp(pages, sp, parents, i) {
2725 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2726 mmu_pages_clear_parents(&parents);
2734 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2735 struct kvm_mmu_page *sp,
2736 struct list_head *invalid_list,
2741 trace_kvm_mmu_prepare_zap_page(sp);
2742 ++kvm->stat.mmu_shadow_zapped;
2743 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2744 kvm_mmu_page_unlink_children(kvm, sp);
2745 kvm_mmu_unlink_parents(kvm, sp);
2747 /* Zapping children means active_mmu_pages has become unstable. */
2748 list_unstable = *nr_zapped;
2750 if (!sp->role.invalid && !sp->role.direct)
2751 unaccount_shadowed(kvm, sp);
2754 kvm_unlink_unsync_page(kvm, sp);
2755 if (!sp->root_count) {
2758 list_move(&sp->link, invalid_list);
2759 kvm_mod_used_mmu_pages(kvm, -1);
2761 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2764 * Obsolete pages cannot be used on any vCPUs, see the comment
2765 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2766 * treats invalid shadow pages as being obsolete.
2768 if (!is_obsolete_sp(kvm, sp))
2769 kvm_reload_remote_mmus(kvm);
2772 sp->role.invalid = 1;
2773 return list_unstable;
2776 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2777 struct list_head *invalid_list)
2781 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2785 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2786 struct list_head *invalid_list)
2788 struct kvm_mmu_page *sp, *nsp;
2790 if (list_empty(invalid_list))
2794 * We need to make sure everyone sees our modifications to
2795 * the page tables and see changes to vcpu->mode here. The barrier
2796 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2797 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2799 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2800 * guest mode and/or lockless shadow page table walks.
2802 kvm_flush_remote_tlbs(kvm);
2804 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2805 WARN_ON(!sp->role.invalid || sp->root_count);
2806 kvm_mmu_free_page(sp);
2810 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2811 struct list_head *invalid_list)
2813 struct kvm_mmu_page *sp;
2815 if (list_empty(&kvm->arch.active_mmu_pages))
2818 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2819 struct kvm_mmu_page, link);
2820 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2824 * Changing the number of mmu pages allocated to the vm
2825 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2827 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2829 LIST_HEAD(invalid_list);
2831 spin_lock(&kvm->mmu_lock);
2833 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2834 /* Need to free some mmu pages to achieve the goal. */
2835 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2836 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2839 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2840 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2843 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2845 spin_unlock(&kvm->mmu_lock);
2848 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2850 struct kvm_mmu_page *sp;
2851 LIST_HEAD(invalid_list);
2854 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2856 spin_lock(&kvm->mmu_lock);
2857 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2858 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2861 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2863 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2864 spin_unlock(&kvm->mmu_lock);
2868 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2870 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2872 trace_kvm_mmu_unsync_page(sp);
2873 ++vcpu->kvm->stat.mmu_unsync;
2876 kvm_mmu_mark_parents_unsync(sp);
2879 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2882 struct kvm_mmu_page *sp;
2884 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2887 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2894 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2895 kvm_unsync_page(vcpu, sp);
2899 * We need to ensure that the marking of unsync pages is visible
2900 * before the SPTE is updated to allow writes because
2901 * kvm_mmu_sync_roots() checks the unsync flags without holding
2902 * the MMU lock and so can race with this. If the SPTE was updated
2903 * before the page had been marked as unsync-ed, something like the
2904 * following could happen:
2907 * ---------------------------------------------------------------------
2908 * 1.2 Host updates SPTE
2910 * 2.1 Guest writes a GPTE for GVA X.
2911 * (GPTE being in the guest page table shadowed
2912 * by the SP from CPU 1.)
2913 * This reads SPTE during the page table walk.
2914 * Since SPTE.W is read as 1, there is no
2917 * 2.2 Guest issues TLB flush.
2918 * That causes a VM Exit.
2920 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2921 * Since it is false, so it just returns.
2923 * 2.4 Guest accesses GVA X.
2924 * Since the mapping in the SP was not updated,
2925 * so the old mapping for GVA X incorrectly
2929 * (sp->unsync = true)
2931 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2932 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2933 * pairs with this write barrier.
2940 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2943 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2945 * Some reserved pages, such as those from NVDIMM
2946 * DAX devices, are not for MMIO, and can be mapped
2947 * with cached memory type for better performance.
2948 * However, the above check misconceives those pages
2949 * as MMIO, and results in KVM mapping them with UC
2950 * memory type, which would hurt the performance.
2951 * Therefore, we check the host memory type in addition
2952 * and only treat UC/UC-/WC pages as MMIO.
2954 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2956 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2957 pfn_to_hpa(pfn + 1) - 1,
2961 /* Bits which may be returned by set_spte() */
2962 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2963 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2965 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2966 unsigned pte_access, int level,
2967 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2968 bool can_unsync, bool host_writable)
2972 struct kvm_mmu_page *sp;
2974 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2977 sp = page_header(__pa(sptep));
2978 if (sp_ad_disabled(sp))
2979 spte |= SPTE_AD_DISABLED_MASK;
2982 * For the EPT case, shadow_present_mask is 0 if hardware
2983 * supports exec-only page table entries. In that case,
2984 * ACC_USER_MASK and shadow_user_mask are used to represent
2985 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2987 spte |= shadow_present_mask;
2989 spte |= spte_shadow_accessed_mask(spte);
2991 if (pte_access & ACC_EXEC_MASK)
2992 spte |= shadow_x_mask;
2994 spte |= shadow_nx_mask;
2996 if (pte_access & ACC_USER_MASK)
2997 spte |= shadow_user_mask;
2999 if (level > PT_PAGE_TABLE_LEVEL)
3000 spte |= PT_PAGE_SIZE_MASK;
3002 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
3003 kvm_is_mmio_pfn(pfn));
3006 spte |= SPTE_HOST_WRITEABLE;
3008 pte_access &= ~ACC_WRITE_MASK;
3010 if (!kvm_is_mmio_pfn(pfn))
3011 spte |= shadow_me_mask;
3013 spte |= (u64)pfn << PAGE_SHIFT;
3015 if (pte_access & ACC_WRITE_MASK) {
3018 * Other vcpu creates new sp in the window between
3019 * mapping_level() and acquiring mmu-lock. We can
3020 * allow guest to retry the access, the mapping can
3021 * be fixed if guest refault.
3023 if (level > PT_PAGE_TABLE_LEVEL &&
3024 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3027 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3030 * Optimization: for pte sync, if spte was writable the hash
3031 * lookup is unnecessary (and expensive). Write protection
3032 * is responsibility of mmu_get_page / kvm_sync_page.
3033 * Same reasoning can be applied to dirty page accounting.
3035 if (!can_unsync && is_writable_pte(*sptep))
3038 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3039 pgprintk("%s: found shadow page for %llx, marking ro\n",
3041 ret |= SET_SPTE_WRITE_PROTECTED_PT;
3042 pte_access &= ~ACC_WRITE_MASK;
3043 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3047 if (pte_access & ACC_WRITE_MASK) {
3048 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3049 spte |= spte_shadow_dirty_mask(spte);
3053 spte = mark_spte_for_access_track(spte);
3056 if (mmu_spte_update(sptep, spte))
3057 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3062 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3063 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3064 bool speculative, bool host_writable)
3066 int was_rmapped = 0;
3069 int ret = RET_PF_RETRY;
3072 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3073 *sptep, write_fault, gfn);
3075 if (is_shadow_present_pte(*sptep)) {
3077 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3078 * the parent of the now unreachable PTE.
3080 if (level > PT_PAGE_TABLE_LEVEL &&
3081 !is_large_pte(*sptep)) {
3082 struct kvm_mmu_page *child;
3085 child = page_header(pte & PT64_BASE_ADDR_MASK);
3086 drop_parent_pte(child, sptep);
3088 } else if (pfn != spte_to_pfn(*sptep)) {
3089 pgprintk("hfn old %llx new %llx\n",
3090 spte_to_pfn(*sptep), pfn);
3091 drop_spte(vcpu->kvm, sptep);
3097 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3098 speculative, true, host_writable);
3099 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3101 ret = RET_PF_EMULATE;
3102 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3105 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3106 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3107 KVM_PAGES_PER_HPAGE(level));
3109 if (unlikely(is_mmio_spte(*sptep)))
3110 ret = RET_PF_EMULATE;
3112 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3113 trace_kvm_mmu_set_spte(level, gfn, sptep);
3114 if (!was_rmapped && is_large_pte(*sptep))
3115 ++vcpu->kvm->stat.lpages;
3117 if (is_shadow_present_pte(*sptep)) {
3119 rmap_count = rmap_add(vcpu, sptep, gfn);
3120 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3121 rmap_recycle(vcpu, sptep, gfn);
3128 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3131 struct kvm_memory_slot *slot;
3133 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3135 return KVM_PFN_ERR_FAULT;
3137 return gfn_to_pfn_memslot_atomic(slot, gfn);
3140 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3141 struct kvm_mmu_page *sp,
3142 u64 *start, u64 *end)
3144 struct page *pages[PTE_PREFETCH_NUM];
3145 struct kvm_memory_slot *slot;
3146 unsigned access = sp->role.access;
3150 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3151 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3155 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3159 for (i = 0; i < ret; i++, gfn++, start++) {
3160 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3161 page_to_pfn(pages[i]), true, true);
3168 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3169 struct kvm_mmu_page *sp, u64 *sptep)
3171 u64 *spte, *start = NULL;
3174 WARN_ON(!sp->role.direct);
3176 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3179 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3180 if (is_shadow_present_pte(*spte) || spte == sptep) {
3183 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3191 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3193 struct kvm_mmu_page *sp;
3195 sp = page_header(__pa(sptep));
3198 * Without accessed bits, there's no way to distinguish between
3199 * actually accessed translations and prefetched, so disable pte
3200 * prefetch if accessed bits aren't available.
3202 if (sp_ad_disabled(sp))
3205 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3208 __direct_pte_prefetch(vcpu, sp, sptep);
3211 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3212 int map_writable, int level, kvm_pfn_t pfn,
3215 struct kvm_shadow_walk_iterator it;
3216 struct kvm_mmu_page *sp;
3218 gfn_t gfn = gpa >> PAGE_SHIFT;
3219 gfn_t base_gfn = gfn;
3221 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3222 return RET_PF_RETRY;
3224 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3225 for_each_shadow_entry(vcpu, gpa, it) {
3226 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3227 if (it.level == level)
3230 drop_large_spte(vcpu, it.sptep);
3231 if (!is_shadow_present_pte(*it.sptep)) {
3232 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3233 it.level - 1, true, ACC_ALL);
3235 link_shadow_page(vcpu, it.sptep, sp);
3239 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3240 write, level, base_gfn, pfn, prefault,
3242 direct_pte_prefetch(vcpu, it.sptep);
3243 ++vcpu->stat.pf_fixed;
3247 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3249 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3252 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3255 * Do not cache the mmio info caused by writing the readonly gfn
3256 * into the spte otherwise read access on readonly gfn also can
3257 * caused mmio page fault and treat it as mmio access.
3259 if (pfn == KVM_PFN_ERR_RO_FAULT)
3260 return RET_PF_EMULATE;
3262 if (pfn == KVM_PFN_ERR_HWPOISON) {
3263 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3264 return RET_PF_RETRY;
3270 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3271 gfn_t gfn, kvm_pfn_t *pfnp,
3274 kvm_pfn_t pfn = *pfnp;
3275 int level = *levelp;
3278 * Check if it's a transparent hugepage. If this would be an
3279 * hugetlbfs page, level wouldn't be set to
3280 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3283 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3284 level == PT_PAGE_TABLE_LEVEL &&
3285 PageTransCompoundMap(pfn_to_page(pfn)) &&
3286 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3289 * mmu_notifier_retry was successful and we hold the
3290 * mmu_lock here, so the pmd can't become splitting
3291 * from under us, and in turn
3292 * __split_huge_page_refcount() can't run from under
3293 * us and we can safely transfer the refcount from
3294 * PG_tail to PG_head as we switch the pfn to tail to
3297 *levelp = level = PT_DIRECTORY_LEVEL;
3298 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3299 VM_BUG_ON((gfn & mask) != (pfn & mask));
3301 kvm_release_pfn_clean(pfn);
3309 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3310 kvm_pfn_t pfn, unsigned access, int *ret_val)
3312 /* The pfn is invalid, report the error! */
3313 if (unlikely(is_error_pfn(pfn))) {
3314 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3318 if (unlikely(is_noslot_pfn(pfn)))
3319 vcpu_cache_mmio_info(vcpu, gva, gfn,
3320 access & shadow_mmio_access_mask);
3325 static bool page_fault_can_be_fast(u32 error_code)
3328 * Do not fix the mmio spte with invalid generation number which
3329 * need to be updated by slow page fault path.
3331 if (unlikely(error_code & PFERR_RSVD_MASK))
3334 /* See if the page fault is due to an NX violation */
3335 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3336 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3340 * #PF can be fast if:
3341 * 1. The shadow page table entry is not present, which could mean that
3342 * the fault is potentially caused by access tracking (if enabled).
3343 * 2. The shadow page table entry is present and the fault
3344 * is caused by write-protect, that means we just need change the W
3345 * bit of the spte which can be done out of mmu-lock.
3347 * However, if access tracking is disabled we know that a non-present
3348 * page must be a genuine page fault where we have to create a new SPTE.
3349 * So, if access tracking is disabled, we return true only for write
3350 * accesses to a present page.
3353 return shadow_acc_track_mask != 0 ||
3354 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3355 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3359 * Returns true if the SPTE was fixed successfully. Otherwise,
3360 * someone else modified the SPTE from its original value.
3363 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3364 u64 *sptep, u64 old_spte, u64 new_spte)
3368 WARN_ON(!sp->role.direct);
3371 * Theoretically we could also set dirty bit (and flush TLB) here in
3372 * order to eliminate unnecessary PML logging. See comments in
3373 * set_spte. But fast_page_fault is very unlikely to happen with PML
3374 * enabled, so we do not do this. This might result in the same GPA
3375 * to be logged in PML buffer again when the write really happens, and
3376 * eventually to be called by mark_page_dirty twice. But it's also no
3377 * harm. This also avoids the TLB flush needed after setting dirty bit
3378 * so non-PML cases won't be impacted.
3380 * Compare with set_spte where instead shadow_dirty_mask is set.
3382 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3385 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3387 * The gfn of direct spte is stable since it is
3388 * calculated by sp->gfn.
3390 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3391 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3397 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3399 if (fault_err_code & PFERR_FETCH_MASK)
3400 return is_executable_pte(spte);
3402 if (fault_err_code & PFERR_WRITE_MASK)
3403 return is_writable_pte(spte);
3405 /* Fault was on Read access */
3406 return spte & PT_PRESENT_MASK;
3411 * - true: let the vcpu to access on the same address again.
3412 * - false: let the real page fault path to fix it.
3414 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3417 struct kvm_shadow_walk_iterator iterator;
3418 struct kvm_mmu_page *sp;
3419 bool fault_handled = false;
3421 uint retry_count = 0;
3423 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3426 if (!page_fault_can_be_fast(error_code))
3429 walk_shadow_page_lockless_begin(vcpu);
3434 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3435 if (!is_shadow_present_pte(spte) ||
3436 iterator.level < level)
3439 sp = page_header(__pa(iterator.sptep));
3440 if (!is_last_spte(spte, sp->role.level))
3444 * Check whether the memory access that caused the fault would
3445 * still cause it if it were to be performed right now. If not,
3446 * then this is a spurious fault caused by TLB lazily flushed,
3447 * or some other CPU has already fixed the PTE after the
3448 * current CPU took the fault.
3450 * Need not check the access of upper level table entries since
3451 * they are always ACC_ALL.
3453 if (is_access_allowed(error_code, spte)) {
3454 fault_handled = true;
3460 if (is_access_track_spte(spte))
3461 new_spte = restore_acc_track_spte(new_spte);
3464 * Currently, to simplify the code, write-protection can
3465 * be removed in the fast path only if the SPTE was
3466 * write-protected for dirty-logging or access tracking.
3468 if ((error_code & PFERR_WRITE_MASK) &&
3469 spte_can_locklessly_be_made_writable(spte))
3471 new_spte |= PT_WRITABLE_MASK;
3474 * Do not fix write-permission on the large spte. Since
3475 * we only dirty the first page into the dirty-bitmap in
3476 * fast_pf_fix_direct_spte(), other pages are missed
3477 * if its slot has dirty logging enabled.
3479 * Instead, we let the slow page fault path create a
3480 * normal spte to fix the access.
3482 * See the comments in kvm_arch_commit_memory_region().
3484 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3488 /* Verify that the fault can be handled in the fast path */
3489 if (new_spte == spte ||
3490 !is_access_allowed(error_code, new_spte))
3494 * Currently, fast page fault only works for direct mapping
3495 * since the gfn is not stable for indirect shadow page. See
3496 * Documentation/virt/kvm/locking.txt to get more detail.
3498 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3499 iterator.sptep, spte,
3504 if (++retry_count > 4) {
3505 printk_once(KERN_WARNING
3506 "kvm: Fast #PF retrying more than 4 times.\n");
3512 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3513 spte, fault_handled);
3514 walk_shadow_page_lockless_end(vcpu);
3516 return fault_handled;
3519 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3520 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3521 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3523 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3524 gfn_t gfn, bool prefault)
3528 bool force_pt_level = false;
3530 unsigned long mmu_seq;
3531 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3533 level = mapping_level(vcpu, gfn, &force_pt_level);
3534 if (likely(!force_pt_level)) {
3536 * This path builds a PAE pagetable - so we can map
3537 * 2mb pages at maximum. Therefore check if the level
3538 * is larger than that.
3540 if (level > PT_DIRECTORY_LEVEL)
3541 level = PT_DIRECTORY_LEVEL;
3543 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3546 if (fast_page_fault(vcpu, v, level, error_code))
3547 return RET_PF_RETRY;
3549 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3552 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3553 return RET_PF_RETRY;
3555 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3559 spin_lock(&vcpu->kvm->mmu_lock);
3560 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3562 if (make_mmu_pages_available(vcpu) < 0)
3564 if (likely(!force_pt_level))
3565 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3566 r = __direct_map(vcpu, v, write, map_writable, level, pfn, prefault);
3568 spin_unlock(&vcpu->kvm->mmu_lock);
3569 kvm_release_pfn_clean(pfn);
3573 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3574 struct list_head *invalid_list)
3576 struct kvm_mmu_page *sp;
3578 if (!VALID_PAGE(*root_hpa))
3581 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3583 if (!sp->root_count && sp->role.invalid)
3584 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3586 *root_hpa = INVALID_PAGE;
3589 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3590 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3591 ulong roots_to_free)
3594 LIST_HEAD(invalid_list);
3595 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3597 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3599 /* Before acquiring the MMU lock, see if we need to do any real work. */
3600 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3601 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3602 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3603 VALID_PAGE(mmu->prev_roots[i].hpa))
3606 if (i == KVM_MMU_NUM_PREV_ROOTS)
3610 spin_lock(&vcpu->kvm->mmu_lock);
3612 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3613 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3614 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3617 if (free_active_root) {
3618 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3619 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3620 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3623 for (i = 0; i < 4; ++i)
3624 if (mmu->pae_root[i] != 0)
3625 mmu_free_root_page(vcpu->kvm,
3628 mmu->root_hpa = INVALID_PAGE;
3633 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3634 spin_unlock(&vcpu->kvm->mmu_lock);
3636 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3638 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3642 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3643 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3650 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3652 struct kvm_mmu_page *sp;
3655 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3656 spin_lock(&vcpu->kvm->mmu_lock);
3657 if(make_mmu_pages_available(vcpu) < 0) {
3658 spin_unlock(&vcpu->kvm->mmu_lock);
3661 sp = kvm_mmu_get_page(vcpu, 0, 0,
3662 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3664 spin_unlock(&vcpu->kvm->mmu_lock);
3665 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3666 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3667 for (i = 0; i < 4; ++i) {
3668 hpa_t root = vcpu->arch.mmu->pae_root[i];
3670 MMU_WARN_ON(VALID_PAGE(root));
3671 spin_lock(&vcpu->kvm->mmu_lock);
3672 if (make_mmu_pages_available(vcpu) < 0) {
3673 spin_unlock(&vcpu->kvm->mmu_lock);
3676 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3677 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3678 root = __pa(sp->spt);
3680 spin_unlock(&vcpu->kvm->mmu_lock);
3681 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3683 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3686 vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3691 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3693 struct kvm_mmu_page *sp;
3695 gfn_t root_gfn, root_cr3;
3698 root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3699 root_gfn = root_cr3 >> PAGE_SHIFT;
3701 if (mmu_check_root(vcpu, root_gfn))
3705 * Do we shadow a long mode page table? If so we need to
3706 * write-protect the guests page table root.
3708 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3709 hpa_t root = vcpu->arch.mmu->root_hpa;
3711 MMU_WARN_ON(VALID_PAGE(root));
3713 spin_lock(&vcpu->kvm->mmu_lock);
3714 if (make_mmu_pages_available(vcpu) < 0) {
3715 spin_unlock(&vcpu->kvm->mmu_lock);
3718 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3719 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3720 root = __pa(sp->spt);
3722 spin_unlock(&vcpu->kvm->mmu_lock);
3723 vcpu->arch.mmu->root_hpa = root;
3728 * We shadow a 32 bit page table. This may be a legacy 2-level
3729 * or a PAE 3-level page table. In either case we need to be aware that
3730 * the shadow page table may be a PAE or a long mode page table.
3732 pm_mask = PT_PRESENT_MASK;
3733 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3734 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3736 for (i = 0; i < 4; ++i) {
3737 hpa_t root = vcpu->arch.mmu->pae_root[i];
3739 MMU_WARN_ON(VALID_PAGE(root));
3740 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3741 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3742 if (!(pdptr & PT_PRESENT_MASK)) {
3743 vcpu->arch.mmu->pae_root[i] = 0;
3746 root_gfn = pdptr >> PAGE_SHIFT;
3747 if (mmu_check_root(vcpu, root_gfn))
3750 spin_lock(&vcpu->kvm->mmu_lock);
3751 if (make_mmu_pages_available(vcpu) < 0) {
3752 spin_unlock(&vcpu->kvm->mmu_lock);
3755 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3757 root = __pa(sp->spt);
3759 spin_unlock(&vcpu->kvm->mmu_lock);
3761 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3763 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3766 * If we shadow a 32 bit page table with a long mode page
3767 * table we enter this path.
3769 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3770 if (vcpu->arch.mmu->lm_root == NULL) {
3772 * The additional page necessary for this is only
3773 * allocated on demand.
3778 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3779 if (lm_root == NULL)
3782 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3784 vcpu->arch.mmu->lm_root = lm_root;
3787 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3791 vcpu->arch.mmu->root_cr3 = root_cr3;
3796 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3798 if (vcpu->arch.mmu->direct_map)
3799 return mmu_alloc_direct_roots(vcpu);
3801 return mmu_alloc_shadow_roots(vcpu);
3804 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3807 struct kvm_mmu_page *sp;
3809 if (vcpu->arch.mmu->direct_map)
3812 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3815 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3817 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3818 hpa_t root = vcpu->arch.mmu->root_hpa;
3819 sp = page_header(root);
3822 * Even if another CPU was marking the SP as unsync-ed
3823 * simultaneously, any guest page table changes are not
3824 * guaranteed to be visible anyway until this VCPU issues a TLB
3825 * flush strictly after those changes are made. We only need to
3826 * ensure that the other CPU sets these flags before any actual
3827 * changes to the page tables are made. The comments in
3828 * mmu_need_write_protect() describe what could go wrong if this
3829 * requirement isn't satisfied.
3831 if (!smp_load_acquire(&sp->unsync) &&
3832 !smp_load_acquire(&sp->unsync_children))
3835 spin_lock(&vcpu->kvm->mmu_lock);
3836 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3838 mmu_sync_children(vcpu, sp);
3840 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3841 spin_unlock(&vcpu->kvm->mmu_lock);
3845 spin_lock(&vcpu->kvm->mmu_lock);
3846 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3848 for (i = 0; i < 4; ++i) {
3849 hpa_t root = vcpu->arch.mmu->pae_root[i];
3851 if (root && VALID_PAGE(root)) {
3852 root &= PT64_BASE_ADDR_MASK;
3853 sp = page_header(root);
3854 mmu_sync_children(vcpu, sp);
3858 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3859 spin_unlock(&vcpu->kvm->mmu_lock);
3861 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3863 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3864 u32 access, struct x86_exception *exception)
3867 exception->error_code = 0;
3871 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3873 struct x86_exception *exception)
3876 exception->error_code = 0;
3877 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3881 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3883 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3885 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3886 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3889 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3891 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3894 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3896 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3899 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3902 * A nested guest cannot use the MMIO cache if it is using nested
3903 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3905 if (mmu_is_nested(vcpu))
3909 return vcpu_match_mmio_gpa(vcpu, addr);
3911 return vcpu_match_mmio_gva(vcpu, addr);
3914 /* return true if reserved bit is detected on spte. */
3916 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3918 struct kvm_shadow_walk_iterator iterator;
3919 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3921 bool reserved = false;
3923 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3926 walk_shadow_page_lockless_begin(vcpu);
3928 for (shadow_walk_init(&iterator, vcpu, addr),
3929 leaf = root = iterator.level;
3930 shadow_walk_okay(&iterator);
3931 __shadow_walk_next(&iterator, spte)) {
3932 spte = mmu_spte_get_lockless(iterator.sptep);
3934 sptes[leaf - 1] = spte;
3937 if (!is_shadow_present_pte(spte))
3940 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3944 walk_shadow_page_lockless_end(vcpu);
3947 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3949 while (root > leaf) {
3950 pr_err("------ spte 0x%llx level %d.\n",
3951 sptes[root - 1], root);
3960 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3965 if (mmio_info_in_cache(vcpu, addr, direct))
3966 return RET_PF_EMULATE;
3968 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3969 if (WARN_ON(reserved))
3972 if (is_mmio_spte(spte)) {
3973 gfn_t gfn = get_mmio_spte_gfn(spte);
3974 unsigned access = get_mmio_spte_access(spte);
3976 if (!check_mmio_spte(vcpu, spte))
3977 return RET_PF_INVALID;
3982 trace_handle_mmio_page_fault(addr, gfn, access);
3983 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3984 return RET_PF_EMULATE;
3988 * If the page table is zapped by other cpus, let CPU fault again on
3991 return RET_PF_RETRY;
3994 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3995 u32 error_code, gfn_t gfn)
3997 if (unlikely(error_code & PFERR_RSVD_MASK))
4000 if (!(error_code & PFERR_PRESENT_MASK) ||
4001 !(error_code & PFERR_WRITE_MASK))
4005 * guest is writing the page which is write tracked which can
4006 * not be fixed by page fault handler.
4008 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4014 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4016 struct kvm_shadow_walk_iterator iterator;
4019 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
4022 walk_shadow_page_lockless_begin(vcpu);
4023 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4024 clear_sp_write_flooding_count(iterator.sptep);
4025 if (!is_shadow_present_pte(spte))
4028 walk_shadow_page_lockless_end(vcpu);
4031 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
4032 u32 error_code, bool prefault)
4034 gfn_t gfn = gva >> PAGE_SHIFT;
4037 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
4039 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4040 return RET_PF_EMULATE;
4042 r = mmu_topup_memory_caches(vcpu);
4046 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4049 return nonpaging_map(vcpu, gva & PAGE_MASK,
4050 error_code, gfn, prefault);
4053 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
4055 struct kvm_arch_async_pf arch;
4057 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4059 arch.direct_map = vcpu->arch.mmu->direct_map;
4060 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4062 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4065 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4066 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4068 struct kvm_memory_slot *slot;
4072 * Don't expose private memslots to L2.
4074 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4075 *pfn = KVM_PFN_NOSLOT;
4079 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4081 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4083 return false; /* *pfn has correct page already */
4085 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4086 trace_kvm_try_async_get_page(gva, gfn);
4087 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4088 trace_kvm_async_pf_doublefault(gva, gfn);
4089 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4091 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4095 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4099 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4100 u64 fault_address, char *insn, int insn_len)
4104 vcpu->arch.l1tf_flush_l1d = true;
4105 switch (vcpu->arch.apf.host_apf_reason) {
4107 trace_kvm_page_fault(fault_address, error_code);
4109 if (kvm_event_needs_reinjection(vcpu))
4110 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4111 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4114 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4115 vcpu->arch.apf.host_apf_reason = 0;
4116 local_irq_disable();
4117 kvm_async_pf_task_wait(fault_address, 0);
4120 case KVM_PV_REASON_PAGE_READY:
4121 vcpu->arch.apf.host_apf_reason = 0;
4122 local_irq_disable();
4123 kvm_async_pf_task_wake(fault_address);
4129 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4132 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4134 int page_num = KVM_PAGES_PER_HPAGE(level);
4136 gfn &= ~(page_num - 1);
4138 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4141 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4147 bool force_pt_level;
4148 gfn_t gfn = gpa >> PAGE_SHIFT;
4149 unsigned long mmu_seq;
4150 int write = error_code & PFERR_WRITE_MASK;
4153 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4155 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4156 return RET_PF_EMULATE;
4158 r = mmu_topup_memory_caches(vcpu);
4162 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4163 PT_DIRECTORY_LEVEL);
4164 level = mapping_level(vcpu, gfn, &force_pt_level);
4165 if (likely(!force_pt_level)) {
4166 if (level > PT_DIRECTORY_LEVEL &&
4167 !check_hugepage_cache_consistency(vcpu, gfn, level))
4168 level = PT_DIRECTORY_LEVEL;
4169 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4172 if (fast_page_fault(vcpu, gpa, level, error_code))
4173 return RET_PF_RETRY;
4175 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4178 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4179 return RET_PF_RETRY;
4181 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4185 spin_lock(&vcpu->kvm->mmu_lock);
4186 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4188 if (make_mmu_pages_available(vcpu) < 0)
4190 if (likely(!force_pt_level))
4191 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4192 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn, prefault);
4194 spin_unlock(&vcpu->kvm->mmu_lock);
4195 kvm_release_pfn_clean(pfn);
4199 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4200 struct kvm_mmu *context)
4202 context->page_fault = nonpaging_page_fault;
4203 context->gva_to_gpa = nonpaging_gva_to_gpa;
4204 context->sync_page = nonpaging_sync_page;
4205 context->invlpg = nonpaging_invlpg;
4206 context->update_pte = nonpaging_update_pte;
4207 context->root_level = 0;
4208 context->shadow_root_level = PT32E_ROOT_LEVEL;
4209 context->direct_map = true;
4210 context->nx = false;
4214 * Find out if a previously cached root matching the new CR3/role is available.
4215 * The current root is also inserted into the cache.
4216 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4218 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4219 * false is returned. This root should now be freed by the caller.
4221 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4222 union kvm_mmu_page_role new_role)
4225 struct kvm_mmu_root_info root;
4226 struct kvm_mmu *mmu = vcpu->arch.mmu;
4228 root.cr3 = mmu->root_cr3;
4229 root.hpa = mmu->root_hpa;
4231 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4232 swap(root, mmu->prev_roots[i]);
4234 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4235 page_header(root.hpa) != NULL &&
4236 new_role.word == page_header(root.hpa)->role.word)
4240 mmu->root_hpa = root.hpa;
4241 mmu->root_cr3 = root.cr3;
4243 return i < KVM_MMU_NUM_PREV_ROOTS;
4246 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4247 union kvm_mmu_page_role new_role,
4248 bool skip_tlb_flush)
4250 struct kvm_mmu *mmu = vcpu->arch.mmu;
4253 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4254 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4255 * later if necessary.
4257 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4258 mmu->root_level >= PT64_ROOT_4LEVEL) {
4259 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4262 if (cached_root_available(vcpu, new_cr3, new_role)) {
4264 * It is possible that the cached previous root page is
4265 * obsolete because of a change in the MMU generation
4266 * number. However, changing the generation number is
4267 * accompanied by KVM_REQ_MMU_RELOAD, which will free
4268 * the root set here and allocate a new one.
4270 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4271 if (!skip_tlb_flush) {
4272 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4273 kvm_x86_ops->tlb_flush(vcpu, true);
4277 * The last MMIO access's GVA and GPA are cached in the
4278 * VCPU. When switching to a new CR3, that GVA->GPA
4279 * mapping may no longer be valid. So clear any cached
4280 * MMIO info even when we don't need to sync the shadow
4283 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4285 __clear_sp_write_flooding_count(
4286 page_header(mmu->root_hpa));
4295 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4296 union kvm_mmu_page_role new_role,
4297 bool skip_tlb_flush)
4299 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4300 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4301 KVM_MMU_ROOT_CURRENT);
4304 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4306 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4309 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4311 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4313 return kvm_read_cr3(vcpu);
4316 static void inject_page_fault(struct kvm_vcpu *vcpu,
4317 struct x86_exception *fault)
4319 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4322 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4323 unsigned access, int *nr_present)
4325 if (unlikely(is_mmio_spte(*sptep))) {
4326 if (gfn != get_mmio_spte_gfn(*sptep)) {
4327 mmu_spte_clear_no_track(sptep);
4332 mark_mmio_spte(vcpu, sptep, gfn, access);
4339 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4340 unsigned level, unsigned gpte)
4343 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4344 * If it is clear, there are no large pages at this level, so clear
4345 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4347 gpte &= level - mmu->last_nonleaf_level;
4350 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4351 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4352 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4354 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4356 return gpte & PT_PAGE_SIZE_MASK;
4359 #define PTTYPE_EPT 18 /* arbitrary */
4360 #define PTTYPE PTTYPE_EPT
4361 #include "paging_tmpl.h"
4365 #include "paging_tmpl.h"
4369 #include "paging_tmpl.h"
4373 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4374 struct rsvd_bits_validate *rsvd_check,
4375 int maxphyaddr, int level, bool nx, bool gbpages,
4378 u64 exb_bit_rsvd = 0;
4379 u64 gbpages_bit_rsvd = 0;
4380 u64 nonleaf_bit8_rsvd = 0;
4382 rsvd_check->bad_mt_xwr = 0;
4385 exb_bit_rsvd = rsvd_bits(63, 63);
4387 gbpages_bit_rsvd = rsvd_bits(7, 7);
4390 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4391 * leaf entries) on AMD CPUs only.
4394 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4397 case PT32_ROOT_LEVEL:
4398 /* no rsvd bits for 2 level 4K page table entries */
4399 rsvd_check->rsvd_bits_mask[0][1] = 0;
4400 rsvd_check->rsvd_bits_mask[0][0] = 0;
4401 rsvd_check->rsvd_bits_mask[1][0] =
4402 rsvd_check->rsvd_bits_mask[0][0];
4405 rsvd_check->rsvd_bits_mask[1][1] = 0;
4409 if (is_cpuid_PSE36())
4410 /* 36bits PSE 4MB page */
4411 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4413 /* 32 bits PSE 4MB page */
4414 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4416 case PT32E_ROOT_LEVEL:
4417 rsvd_check->rsvd_bits_mask[0][2] =
4418 rsvd_bits(maxphyaddr, 63) |
4419 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4420 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4421 rsvd_bits(maxphyaddr, 62); /* PDE */
4422 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4423 rsvd_bits(maxphyaddr, 62); /* PTE */
4424 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4425 rsvd_bits(maxphyaddr, 62) |
4426 rsvd_bits(13, 20); /* large page */
4427 rsvd_check->rsvd_bits_mask[1][0] =
4428 rsvd_check->rsvd_bits_mask[0][0];
4430 case PT64_ROOT_5LEVEL:
4431 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4432 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4433 rsvd_bits(maxphyaddr, 51);
4434 rsvd_check->rsvd_bits_mask[1][4] =
4435 rsvd_check->rsvd_bits_mask[0][4];
4437 case PT64_ROOT_4LEVEL:
4438 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4439 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4440 rsvd_bits(maxphyaddr, 51);
4441 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4442 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4443 rsvd_bits(maxphyaddr, 51);
4444 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4445 rsvd_bits(maxphyaddr, 51);
4446 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4447 rsvd_bits(maxphyaddr, 51);
4448 rsvd_check->rsvd_bits_mask[1][3] =
4449 rsvd_check->rsvd_bits_mask[0][3];
4450 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4451 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4453 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4454 rsvd_bits(maxphyaddr, 51) |
4455 rsvd_bits(13, 20); /* large page */
4456 rsvd_check->rsvd_bits_mask[1][0] =
4457 rsvd_check->rsvd_bits_mask[0][0];
4462 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4463 struct kvm_mmu *context)
4465 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4466 cpuid_maxphyaddr(vcpu), context->root_level,
4468 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4469 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4473 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4474 int maxphyaddr, bool execonly)
4478 rsvd_check->rsvd_bits_mask[0][4] =
4479 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4480 rsvd_check->rsvd_bits_mask[0][3] =
4481 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4482 rsvd_check->rsvd_bits_mask[0][2] =
4483 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4484 rsvd_check->rsvd_bits_mask[0][1] =
4485 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4486 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4489 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4490 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4491 rsvd_check->rsvd_bits_mask[1][2] =
4492 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4493 rsvd_check->rsvd_bits_mask[1][1] =
4494 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4495 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4497 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4498 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4499 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4500 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4501 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4503 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4504 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4506 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4509 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4510 struct kvm_mmu *context, bool execonly)
4512 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4513 cpuid_maxphyaddr(vcpu), execonly);
4517 * the page table on host is the shadow page table for the page
4518 * table in guest or amd nested guest, its mmu features completely
4519 * follow the features in guest.
4522 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4524 bool uses_nx = context->nx ||
4525 context->mmu_role.base.smep_andnot_wp;
4526 struct rsvd_bits_validate *shadow_zero_check;
4530 * Passing "true" to the last argument is okay; it adds a check
4531 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4533 shadow_zero_check = &context->shadow_zero_check;
4534 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4536 context->shadow_root_level, uses_nx,
4537 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4538 is_pse(vcpu), true);
4540 if (!shadow_me_mask)
4543 for (i = context->shadow_root_level; --i >= 0;) {
4544 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4545 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4549 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4551 static inline bool boot_cpu_is_amd(void)
4553 WARN_ON_ONCE(!tdp_enabled);
4554 return shadow_x_mask == 0;
4558 * the direct page table on host, use as much mmu features as
4559 * possible, however, kvm currently does not do execution-protection.
4562 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4563 struct kvm_mmu *context)
4565 struct rsvd_bits_validate *shadow_zero_check;
4568 shadow_zero_check = &context->shadow_zero_check;
4570 if (boot_cpu_is_amd())
4571 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4573 context->shadow_root_level, false,
4574 boot_cpu_has(X86_FEATURE_GBPAGES),
4577 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4581 if (!shadow_me_mask)
4584 for (i = context->shadow_root_level; --i >= 0;) {
4585 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4586 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4591 * as the comments in reset_shadow_zero_bits_mask() except it
4592 * is the shadow page table for intel nested guest.
4595 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4596 struct kvm_mmu *context, bool execonly)
4598 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4599 shadow_phys_bits, execonly);
4602 #define BYTE_MASK(access) \
4603 ((1 & (access) ? 2 : 0) | \
4604 (2 & (access) ? 4 : 0) | \
4605 (3 & (access) ? 8 : 0) | \
4606 (4 & (access) ? 16 : 0) | \
4607 (5 & (access) ? 32 : 0) | \
4608 (6 & (access) ? 64 : 0) | \
4609 (7 & (access) ? 128 : 0))
4612 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4613 struct kvm_mmu *mmu, bool ept)
4617 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4618 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4619 const u8 u = BYTE_MASK(ACC_USER_MASK);
4621 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4622 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4623 bool cr0_wp = is_write_protection(vcpu);
4625 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4626 unsigned pfec = byte << 1;
4629 * Each "*f" variable has a 1 bit for each UWX value
4630 * that causes a fault with the given PFEC.
4633 /* Faults from writes to non-writable pages */
4634 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4635 /* Faults from user mode accesses to supervisor pages */
4636 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4637 /* Faults from fetches of non-executable pages*/
4638 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4639 /* Faults from kernel mode fetches of user pages */
4641 /* Faults from kernel mode accesses of user pages */
4645 /* Faults from kernel mode accesses to user pages */
4646 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4648 /* Not really needed: !nx will cause pte.nx to fault */
4652 /* Allow supervisor writes if !cr0.wp */
4654 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4656 /* Disallow supervisor fetches of user code if cr4.smep */
4658 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4661 * SMAP:kernel-mode data accesses from user-mode
4662 * mappings should fault. A fault is considered
4663 * as a SMAP violation if all of the following
4664 * conditions are true:
4665 * - X86_CR4_SMAP is set in CR4
4666 * - A user page is accessed
4667 * - The access is not a fetch
4668 * - Page fault in kernel mode
4669 * - if CPL = 3 or X86_EFLAGS_AC is clear
4671 * Here, we cover the first three conditions.
4672 * The fourth is computed dynamically in permission_fault();
4673 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4674 * *not* subject to SMAP restrictions.
4677 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4680 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4685 * PKU is an additional mechanism by which the paging controls access to
4686 * user-mode addresses based on the value in the PKRU register. Protection
4687 * key violations are reported through a bit in the page fault error code.
4688 * Unlike other bits of the error code, the PK bit is not known at the
4689 * call site of e.g. gva_to_gpa; it must be computed directly in
4690 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4691 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4693 * In particular the following conditions come from the error code, the
4694 * page tables and the machine state:
4695 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4696 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4697 * - PK is always zero if U=0 in the page tables
4698 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4700 * The PKRU bitmask caches the result of these four conditions. The error
4701 * code (minus the P bit) and the page table's U bit form an index into the
4702 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4703 * with the two bits of the PKRU register corresponding to the protection key.
4704 * For the first three conditions above the bits will be 00, thus masking
4705 * away both AD and WD. For all reads or if the last condition holds, WD
4706 * only will be masked away.
4708 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4719 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4720 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4725 wp = is_write_protection(vcpu);
4727 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4728 unsigned pfec, pkey_bits;
4729 bool check_pkey, check_write, ff, uf, wf, pte_user;
4732 ff = pfec & PFERR_FETCH_MASK;
4733 uf = pfec & PFERR_USER_MASK;
4734 wf = pfec & PFERR_WRITE_MASK;
4736 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4737 pte_user = pfec & PFERR_RSVD_MASK;
4740 * Only need to check the access which is not an
4741 * instruction fetch and is to a user page.
4743 check_pkey = (!ff && pte_user);
4745 * write access is controlled by PKRU if it is a
4746 * user access or CR0.WP = 1.
4748 check_write = check_pkey && wf && (uf || wp);
4750 /* PKRU.AD stops both read and write access. */
4751 pkey_bits = !!check_pkey;
4752 /* PKRU.WD stops write access. */
4753 pkey_bits |= (!!check_write) << 1;
4755 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4759 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4761 unsigned root_level = mmu->root_level;
4763 mmu->last_nonleaf_level = root_level;
4764 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4765 mmu->last_nonleaf_level++;
4768 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4769 struct kvm_mmu *context,
4772 context->nx = is_nx(vcpu);
4773 context->root_level = level;
4775 reset_rsvds_bits_mask(vcpu, context);
4776 update_permission_bitmask(vcpu, context, false);
4777 update_pkru_bitmask(vcpu, context, false);
4778 update_last_nonleaf_level(vcpu, context);
4780 MMU_WARN_ON(!is_pae(vcpu));
4781 context->page_fault = paging64_page_fault;
4782 context->gva_to_gpa = paging64_gva_to_gpa;
4783 context->sync_page = paging64_sync_page;
4784 context->invlpg = paging64_invlpg;
4785 context->update_pte = paging64_update_pte;
4786 context->shadow_root_level = level;
4787 context->direct_map = false;
4790 static void paging64_init_context(struct kvm_vcpu *vcpu,
4791 struct kvm_mmu *context)
4793 int root_level = is_la57_mode(vcpu) ?
4794 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4796 paging64_init_context_common(vcpu, context, root_level);
4799 static void paging32_init_context(struct kvm_vcpu *vcpu,
4800 struct kvm_mmu *context)
4802 context->nx = false;
4803 context->root_level = PT32_ROOT_LEVEL;
4805 reset_rsvds_bits_mask(vcpu, context);
4806 update_permission_bitmask(vcpu, context, false);
4807 update_pkru_bitmask(vcpu, context, false);
4808 update_last_nonleaf_level(vcpu, context);
4810 context->page_fault = paging32_page_fault;
4811 context->gva_to_gpa = paging32_gva_to_gpa;
4812 context->sync_page = paging32_sync_page;
4813 context->invlpg = paging32_invlpg;
4814 context->update_pte = paging32_update_pte;
4815 context->shadow_root_level = PT32E_ROOT_LEVEL;
4816 context->direct_map = false;
4819 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4820 struct kvm_mmu *context)
4822 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4825 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4827 union kvm_mmu_extended_role ext = {0};
4829 ext.cr0_pg = !!is_paging(vcpu);
4830 ext.cr4_pae = !!is_pae(vcpu);
4831 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4832 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4833 ext.cr4_pse = !!is_pse(vcpu);
4834 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4835 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4836 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4843 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4846 union kvm_mmu_role role = {0};
4848 role.base.access = ACC_ALL;
4849 role.base.nxe = !!is_nx(vcpu);
4850 role.base.cr0_wp = is_write_protection(vcpu);
4851 role.base.smm = is_smm(vcpu);
4852 role.base.guest_mode = is_guest_mode(vcpu);
4857 role.ext = kvm_calc_mmu_role_ext(vcpu);
4862 static union kvm_mmu_role
4863 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4865 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4867 role.base.ad_disabled = (shadow_accessed_mask == 0);
4868 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4869 role.base.direct = true;
4870 role.base.gpte_is_8_bytes = true;
4875 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4877 struct kvm_mmu *context = vcpu->arch.mmu;
4878 union kvm_mmu_role new_role =
4879 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4881 new_role.base.word &= mmu_base_role_mask.word;
4882 if (new_role.as_u64 == context->mmu_role.as_u64)
4885 context->mmu_role.as_u64 = new_role.as_u64;
4886 context->page_fault = tdp_page_fault;
4887 context->sync_page = nonpaging_sync_page;
4888 context->invlpg = nonpaging_invlpg;
4889 context->update_pte = nonpaging_update_pte;
4890 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4891 context->direct_map = true;
4892 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4893 context->get_cr3 = get_cr3;
4894 context->get_pdptr = kvm_pdptr_read;
4895 context->inject_page_fault = kvm_inject_page_fault;
4897 if (!is_paging(vcpu)) {
4898 context->nx = false;
4899 context->gva_to_gpa = nonpaging_gva_to_gpa;
4900 context->root_level = 0;
4901 } else if (is_long_mode(vcpu)) {
4902 context->nx = is_nx(vcpu);
4903 context->root_level = is_la57_mode(vcpu) ?
4904 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4905 reset_rsvds_bits_mask(vcpu, context);
4906 context->gva_to_gpa = paging64_gva_to_gpa;
4907 } else if (is_pae(vcpu)) {
4908 context->nx = is_nx(vcpu);
4909 context->root_level = PT32E_ROOT_LEVEL;
4910 reset_rsvds_bits_mask(vcpu, context);
4911 context->gva_to_gpa = paging64_gva_to_gpa;
4913 context->nx = false;
4914 context->root_level = PT32_ROOT_LEVEL;
4915 reset_rsvds_bits_mask(vcpu, context);
4916 context->gva_to_gpa = paging32_gva_to_gpa;
4919 update_permission_bitmask(vcpu, context, false);
4920 update_pkru_bitmask(vcpu, context, false);
4921 update_last_nonleaf_level(vcpu, context);
4922 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4925 static union kvm_mmu_role
4926 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4928 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4930 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4931 !is_write_protection(vcpu);
4932 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4933 !is_write_protection(vcpu);
4934 role.base.direct = !is_paging(vcpu);
4935 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4937 if (!is_long_mode(vcpu))
4938 role.base.level = PT32E_ROOT_LEVEL;
4939 else if (is_la57_mode(vcpu))
4940 role.base.level = PT64_ROOT_5LEVEL;
4942 role.base.level = PT64_ROOT_4LEVEL;
4947 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4949 struct kvm_mmu *context = vcpu->arch.mmu;
4950 union kvm_mmu_role new_role =
4951 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4953 new_role.base.word &= mmu_base_role_mask.word;
4954 if (new_role.as_u64 == context->mmu_role.as_u64)
4957 if (!is_paging(vcpu))
4958 nonpaging_init_context(vcpu, context);
4959 else if (is_long_mode(vcpu))
4960 paging64_init_context(vcpu, context);
4961 else if (is_pae(vcpu))
4962 paging32E_init_context(vcpu, context);
4964 paging32_init_context(vcpu, context);
4966 context->mmu_role.as_u64 = new_role.as_u64;
4967 reset_shadow_zero_bits_mask(vcpu, context);
4969 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4971 static union kvm_mmu_role
4972 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4975 union kvm_mmu_role role = {0};
4977 /* SMM flag is inherited from root_mmu */
4978 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
4980 role.base.level = PT64_ROOT_4LEVEL;
4981 role.base.gpte_is_8_bytes = true;
4982 role.base.direct = false;
4983 role.base.ad_disabled = !accessed_dirty;
4984 role.base.guest_mode = true;
4985 role.base.access = ACC_ALL;
4988 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
4989 * SMAP variation to denote shadow EPT entries.
4991 role.base.cr0_wp = true;
4992 role.base.smap_andnot_wp = true;
4994 role.ext = kvm_calc_mmu_role_ext(vcpu);
4995 role.ext.execonly = execonly;
5000 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5001 bool accessed_dirty, gpa_t new_eptp)
5003 struct kvm_mmu *context = vcpu->arch.mmu;
5004 union kvm_mmu_role new_role =
5005 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5008 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
5010 new_role.base.word &= mmu_base_role_mask.word;
5011 if (new_role.as_u64 == context->mmu_role.as_u64)
5014 context->shadow_root_level = PT64_ROOT_4LEVEL;
5017 context->ept_ad = accessed_dirty;
5018 context->page_fault = ept_page_fault;
5019 context->gva_to_gpa = ept_gva_to_gpa;
5020 context->sync_page = ept_sync_page;
5021 context->invlpg = ept_invlpg;
5022 context->update_pte = ept_update_pte;
5023 context->root_level = PT64_ROOT_4LEVEL;
5024 context->direct_map = false;
5025 context->mmu_role.as_u64 = new_role.as_u64;
5027 update_permission_bitmask(vcpu, context, true);
5028 update_pkru_bitmask(vcpu, context, true);
5029 update_last_nonleaf_level(vcpu, context);
5030 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5031 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5033 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5035 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5037 struct kvm_mmu *context = vcpu->arch.mmu;
5039 kvm_init_shadow_mmu(vcpu);
5040 context->set_cr3 = kvm_x86_ops->set_cr3;
5041 context->get_cr3 = get_cr3;
5042 context->get_pdptr = kvm_pdptr_read;
5043 context->inject_page_fault = kvm_inject_page_fault;
5046 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5048 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5049 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5051 new_role.base.word &= mmu_base_role_mask.word;
5052 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5055 g_context->mmu_role.as_u64 = new_role.as_u64;
5056 g_context->get_cr3 = get_cr3;
5057 g_context->get_pdptr = kvm_pdptr_read;
5058 g_context->inject_page_fault = kvm_inject_page_fault;
5061 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5062 * L1's nested page tables (e.g. EPT12). The nested translation
5063 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5064 * L2's page tables as the first level of translation and L1's
5065 * nested page tables as the second level of translation. Basically
5066 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5068 if (!is_paging(vcpu)) {
5069 g_context->nx = false;
5070 g_context->root_level = 0;
5071 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5072 } else if (is_long_mode(vcpu)) {
5073 g_context->nx = is_nx(vcpu);
5074 g_context->root_level = is_la57_mode(vcpu) ?
5075 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5076 reset_rsvds_bits_mask(vcpu, g_context);
5077 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5078 } else if (is_pae(vcpu)) {
5079 g_context->nx = is_nx(vcpu);
5080 g_context->root_level = PT32E_ROOT_LEVEL;
5081 reset_rsvds_bits_mask(vcpu, g_context);
5082 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5084 g_context->nx = false;
5085 g_context->root_level = PT32_ROOT_LEVEL;
5086 reset_rsvds_bits_mask(vcpu, g_context);
5087 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5090 update_permission_bitmask(vcpu, g_context, false);
5091 update_pkru_bitmask(vcpu, g_context, false);
5092 update_last_nonleaf_level(vcpu, g_context);
5095 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5100 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5102 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5103 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5106 if (mmu_is_nested(vcpu))
5107 init_kvm_nested_mmu(vcpu);
5108 else if (tdp_enabled)
5109 init_kvm_tdp_mmu(vcpu);
5111 init_kvm_softmmu(vcpu);
5113 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5115 static union kvm_mmu_page_role
5116 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5118 union kvm_mmu_role role;
5121 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5123 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5128 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5130 kvm_mmu_unload(vcpu);
5131 kvm_init_mmu(vcpu, true);
5133 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5135 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5139 r = mmu_topup_memory_caches(vcpu);
5142 r = mmu_alloc_roots(vcpu);
5143 kvm_mmu_sync_roots(vcpu);
5146 kvm_mmu_load_cr3(vcpu);
5147 kvm_x86_ops->tlb_flush(vcpu, true);
5151 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5153 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5155 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5156 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5157 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5158 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5160 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5162 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5163 struct kvm_mmu_page *sp, u64 *spte,
5166 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5167 ++vcpu->kvm->stat.mmu_pde_zapped;
5171 ++vcpu->kvm->stat.mmu_pte_updated;
5172 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5175 static bool need_remote_flush(u64 old, u64 new)
5177 if (!is_shadow_present_pte(old))
5179 if (!is_shadow_present_pte(new))
5181 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5183 old ^= shadow_nx_mask;
5184 new ^= shadow_nx_mask;
5185 return (old & ~new & PT64_PERM_MASK) != 0;
5188 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5195 * Assume that the pte write on a page table of the same type
5196 * as the current vcpu paging mode since we update the sptes only
5197 * when they have the same mode.
5199 if (is_pae(vcpu) && *bytes == 4) {
5200 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5205 if (*bytes == 4 || *bytes == 8) {
5206 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5215 * If we're seeing too many writes to a page, it may no longer be a page table,
5216 * or we may be forking, in which case it is better to unmap the page.
5218 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5221 * Skip write-flooding detected for the sp whose level is 1, because
5222 * it can become unsync, then the guest page is not write-protected.
5224 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5227 atomic_inc(&sp->write_flooding_count);
5228 return atomic_read(&sp->write_flooding_count) >= 3;
5232 * Misaligned accesses are too much trouble to fix up; also, they usually
5233 * indicate a page is not used as a page table.
5235 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5238 unsigned offset, pte_size, misaligned;
5240 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5241 gpa, bytes, sp->role.word);
5243 offset = offset_in_page(gpa);
5244 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5247 * Sometimes, the OS only writes the last one bytes to update status
5248 * bits, for example, in linux, andb instruction is used in clear_bit().
5250 if (!(offset & (pte_size - 1)) && bytes == 1)
5253 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5254 misaligned |= bytes < 4;
5259 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5261 unsigned page_offset, quadrant;
5265 page_offset = offset_in_page(gpa);
5266 level = sp->role.level;
5268 if (!sp->role.gpte_is_8_bytes) {
5269 page_offset <<= 1; /* 32->64 */
5271 * A 32-bit pde maps 4MB while the shadow pdes map
5272 * only 2MB. So we need to double the offset again
5273 * and zap two pdes instead of one.
5275 if (level == PT32_ROOT_LEVEL) {
5276 page_offset &= ~7; /* kill rounding error */
5280 quadrant = page_offset >> PAGE_SHIFT;
5281 page_offset &= ~PAGE_MASK;
5282 if (quadrant != sp->role.quadrant)
5286 spte = &sp->spt[page_offset / sizeof(*spte)];
5290 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5291 const u8 *new, int bytes,
5292 struct kvm_page_track_notifier_node *node)
5294 gfn_t gfn = gpa >> PAGE_SHIFT;
5295 struct kvm_mmu_page *sp;
5296 LIST_HEAD(invalid_list);
5297 u64 entry, gentry, *spte;
5299 bool remote_flush, local_flush;
5302 * If we don't have indirect shadow pages, it means no page is
5303 * write-protected, so we can exit simply.
5305 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5308 remote_flush = local_flush = false;
5310 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5313 * No need to care whether allocation memory is successful
5314 * or not since pte prefetch is skiped if it does not have
5315 * enough objects in the cache.
5317 mmu_topup_memory_caches(vcpu);
5319 spin_lock(&vcpu->kvm->mmu_lock);
5321 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5323 ++vcpu->kvm->stat.mmu_pte_write;
5324 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5326 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5327 if (detect_write_misaligned(sp, gpa, bytes) ||
5328 detect_write_flooding(sp)) {
5329 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5330 ++vcpu->kvm->stat.mmu_flooded;
5334 spte = get_written_sptes(sp, gpa, &npte);
5340 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5343 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5345 !((sp->role.word ^ base_role)
5346 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5347 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5348 if (need_remote_flush(entry, *spte))
5349 remote_flush = true;
5353 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5354 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5355 spin_unlock(&vcpu->kvm->mmu_lock);
5358 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5363 if (vcpu->arch.mmu->direct_map)
5366 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5368 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5372 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5374 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5376 LIST_HEAD(invalid_list);
5378 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5381 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5382 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5385 ++vcpu->kvm->stat.mmu_recycled;
5387 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5389 if (!kvm_mmu_available_pages(vcpu->kvm))
5394 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5395 void *insn, int insn_len)
5397 int r, emulation_type = 0;
5398 bool direct = vcpu->arch.mmu->direct_map;
5400 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5401 if (vcpu->arch.mmu->direct_map) {
5402 vcpu->arch.gpa_available = true;
5403 vcpu->arch.gpa_val = cr2;
5407 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5408 r = handle_mmio_page_fault(vcpu, cr2, direct);
5409 if (r == RET_PF_EMULATE)
5413 if (r == RET_PF_INVALID) {
5414 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5415 lower_32_bits(error_code),
5417 WARN_ON(r == RET_PF_INVALID);
5420 if (r == RET_PF_RETRY)
5426 * Before emulating the instruction, check if the error code
5427 * was due to a RO violation while translating the guest page.
5428 * This can occur when using nested virtualization with nested
5429 * paging in both guests. If true, we simply unprotect the page
5430 * and resume the guest.
5432 if (vcpu->arch.mmu->direct_map &&
5433 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5434 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5439 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5440 * optimistically try to just unprotect the page and let the processor
5441 * re-execute the instruction that caused the page fault. Do not allow
5442 * retrying MMIO emulation, as it's not only pointless but could also
5443 * cause us to enter an infinite loop because the processor will keep
5444 * faulting on the non-existent MMIO address. Retrying an instruction
5445 * from a nested guest is also pointless and dangerous as we are only
5446 * explicitly shadowing L1's page tables, i.e. unprotecting something
5447 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5449 if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5450 emulation_type = EMULTYPE_ALLOW_RETRY;
5453 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5454 * This can happen if a guest gets a page-fault on data access but the HW
5455 * table walker is not able to read the instruction page (e.g instruction
5456 * page is not present in memory). In those cases we simply restart the
5457 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5459 if (unlikely(insn && !insn_len)) {
5460 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5464 return x86_emulate_instruction(vcpu, cr2, emulation_type, insn,
5467 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5469 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5471 struct kvm_mmu *mmu = vcpu->arch.mmu;
5474 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5475 if (is_noncanonical_address(gva, vcpu))
5478 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5481 * INVLPG is required to invalidate any global mappings for the VA,
5482 * irrespective of PCID. Since it would take us roughly similar amount
5483 * of work to determine whether any of the prev_root mappings of the VA
5484 * is marked global, or to just sync it blindly, so we might as well
5485 * just always sync it.
5487 * Mappings not reachable via the current cr3 or the prev_roots will be
5488 * synced when switching to that cr3, so nothing needs to be done here
5491 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5492 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5493 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5495 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5496 ++vcpu->stat.invlpg;
5498 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5500 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5502 struct kvm_mmu *mmu = vcpu->arch.mmu;
5503 bool tlb_flush = false;
5506 if (pcid == kvm_get_active_pcid(vcpu)) {
5507 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5511 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5512 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5513 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5514 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5520 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5522 ++vcpu->stat.invlpg;
5525 * Mappings not reachable via the current cr3 or the prev_roots will be
5526 * synced when switching to that cr3, so nothing needs to be done here
5530 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5532 void kvm_enable_tdp(void)
5536 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5538 void kvm_disable_tdp(void)
5540 tdp_enabled = false;
5542 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5545 /* The return value indicates if tlb flush on all vcpus is needed. */
5546 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5548 /* The caller should hold mmu-lock before calling this function. */
5549 static __always_inline bool
5550 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5551 slot_level_handler fn, int start_level, int end_level,
5552 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5554 struct slot_rmap_walk_iterator iterator;
5557 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5558 end_gfn, &iterator) {
5560 flush |= fn(kvm, iterator.rmap);
5562 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5563 if (flush && lock_flush_tlb) {
5564 kvm_flush_remote_tlbs_with_address(kvm,
5566 iterator.gfn - start_gfn + 1);
5569 cond_resched_lock(&kvm->mmu_lock);
5573 if (flush && lock_flush_tlb) {
5574 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5575 end_gfn - start_gfn + 1);
5582 static __always_inline bool
5583 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5584 slot_level_handler fn, int start_level, int end_level,
5585 bool lock_flush_tlb)
5587 return slot_handle_level_range(kvm, memslot, fn, start_level,
5588 end_level, memslot->base_gfn,
5589 memslot->base_gfn + memslot->npages - 1,
5593 static __always_inline bool
5594 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5595 slot_level_handler fn, bool lock_flush_tlb)
5597 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5598 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5601 static __always_inline bool
5602 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5603 slot_level_handler fn, bool lock_flush_tlb)
5605 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5606 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5609 static __always_inline bool
5610 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5611 slot_level_handler fn, bool lock_flush_tlb)
5613 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5614 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5617 static void free_mmu_pages(struct kvm_mmu *mmu)
5619 free_page((unsigned long)mmu->pae_root);
5620 free_page((unsigned long)mmu->lm_root);
5623 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5629 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5630 * while the PDP table is a per-vCPU construct that's allocated at MMU
5631 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5632 * x86_64. Therefore we need to allocate the PDP table in the first
5633 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5634 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5635 * skip allocating the PDP table.
5637 if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5640 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5644 mmu->pae_root = page_address(page);
5645 for (i = 0; i < 4; ++i)
5646 mmu->pae_root[i] = INVALID_PAGE;
5651 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5656 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5657 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5659 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5660 vcpu->arch.root_mmu.root_cr3 = 0;
5661 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5662 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5663 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5665 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5666 vcpu->arch.guest_mmu.root_cr3 = 0;
5667 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5668 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5669 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5671 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5673 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5677 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5679 goto fail_allocate_root;
5683 free_mmu_pages(&vcpu->arch.guest_mmu);
5687 #define BATCH_ZAP_PAGES 10
5688 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5690 struct kvm_mmu_page *sp, *node;
5691 int nr_zapped, batch = 0;
5694 list_for_each_entry_safe_reverse(sp, node,
5695 &kvm->arch.active_mmu_pages, link) {
5697 * No obsolete valid page exists before a newly created page
5698 * since active_mmu_pages is a FIFO list.
5700 if (!is_obsolete_sp(kvm, sp))
5704 * Skip invalid pages with a non-zero root count, zapping pages
5705 * with a non-zero root count will never succeed, i.e. the page
5706 * will get thrown back on active_mmu_pages and we'll get stuck
5707 * in an infinite loop.
5709 if (sp->role.invalid && sp->root_count)
5713 * No need to flush the TLB since we're only zapping shadow
5714 * pages with an obsolete generation number and all vCPUS have
5715 * loaded a new root, i.e. the shadow pages being zapped cannot
5716 * be in active use by the guest.
5718 if (batch >= BATCH_ZAP_PAGES &&
5719 cond_resched_lock(&kvm->mmu_lock)) {
5724 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5725 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5732 * Trigger a remote TLB flush before freeing the page tables to ensure
5733 * KVM is not in the middle of a lockless shadow page table walk, which
5734 * may reference the pages.
5736 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5740 * Fast invalidate all shadow pages and use lock-break technique
5741 * to zap obsolete pages.
5743 * It's required when memslot is being deleted or VM is being
5744 * destroyed, in these cases, we should ensure that KVM MMU does
5745 * not use any resource of the being-deleted slot or all slots
5746 * after calling the function.
5748 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5750 lockdep_assert_held(&kvm->slots_lock);
5752 spin_lock(&kvm->mmu_lock);
5753 trace_kvm_mmu_zap_all_fast(kvm);
5756 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5757 * held for the entire duration of zapping obsolete pages, it's
5758 * impossible for there to be multiple invalid generations associated
5759 * with *valid* shadow pages at any given time, i.e. there is exactly
5760 * one valid generation and (at most) one invalid generation.
5762 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5765 * Notify all vcpus to reload its shadow page table and flush TLB.
5766 * Then all vcpus will switch to new shadow page table with the new
5769 * Note: we need to do this under the protection of mmu_lock,
5770 * otherwise, vcpu would purge shadow page but miss tlb flush.
5772 kvm_reload_remote_mmus(kvm);
5774 kvm_zap_obsolete_pages(kvm);
5775 spin_unlock(&kvm->mmu_lock);
5778 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5780 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5783 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5784 struct kvm_memory_slot *slot,
5785 struct kvm_page_track_notifier_node *node)
5787 kvm_mmu_zap_all_fast(kvm);
5790 void kvm_mmu_init_vm(struct kvm *kvm)
5792 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5794 node->track_write = kvm_mmu_pte_write;
5795 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5796 kvm_page_track_register_notifier(kvm, node);
5799 void kvm_mmu_uninit_vm(struct kvm *kvm)
5801 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5803 kvm_page_track_unregister_notifier(kvm, node);
5806 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5808 struct kvm_memslots *slots;
5809 struct kvm_memory_slot *memslot;
5812 spin_lock(&kvm->mmu_lock);
5813 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5814 slots = __kvm_memslots(kvm, i);
5815 kvm_for_each_memslot(memslot, slots) {
5818 start = max(gfn_start, memslot->base_gfn);
5819 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5823 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5824 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5825 start, end - 1, true);
5829 spin_unlock(&kvm->mmu_lock);
5832 static bool slot_rmap_write_protect(struct kvm *kvm,
5833 struct kvm_rmap_head *rmap_head)
5835 return __rmap_write_protect(kvm, rmap_head, false);
5838 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5839 struct kvm_memory_slot *memslot)
5843 spin_lock(&kvm->mmu_lock);
5844 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5846 spin_unlock(&kvm->mmu_lock);
5849 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5850 * which do tlb flush out of mmu-lock should be serialized by
5851 * kvm->slots_lock otherwise tlb flush would be missed.
5853 lockdep_assert_held(&kvm->slots_lock);
5856 * We can flush all the TLBs out of the mmu lock without TLB
5857 * corruption since we just change the spte from writable to
5858 * readonly so that we only need to care the case of changing
5859 * spte from present to present (changing the spte from present
5860 * to nonpresent will flush all the TLBs immediately), in other
5861 * words, the only case we care is mmu_spte_update() where we
5862 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5863 * instead of PT_WRITABLE_MASK, that means it does not depend
5864 * on PT_WRITABLE_MASK anymore.
5867 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5871 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5872 struct kvm_rmap_head *rmap_head)
5875 struct rmap_iterator iter;
5876 int need_tlb_flush = 0;
5878 struct kvm_mmu_page *sp;
5881 for_each_rmap_spte(rmap_head, &iter, sptep) {
5882 sp = page_header(__pa(sptep));
5883 pfn = spte_to_pfn(*sptep);
5886 * We cannot do huge page mapping for indirect shadow pages,
5887 * which are found on the last rmap (level = 1) when not using
5888 * tdp; such shadow pages are synced with the page table in
5889 * the guest, and the guest page table is using 4K page size
5890 * mapping if the indirect sp has level = 1.
5892 if (sp->role.direct &&
5893 !kvm_is_reserved_pfn(pfn) &&
5894 PageTransCompoundMap(pfn_to_page(pfn))) {
5895 pte_list_remove(rmap_head, sptep);
5897 if (kvm_available_flush_tlb_with_range())
5898 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5899 KVM_PAGES_PER_HPAGE(sp->role.level));
5907 return need_tlb_flush;
5910 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5911 const struct kvm_memory_slot *memslot)
5913 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5914 spin_lock(&kvm->mmu_lock);
5915 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5916 kvm_mmu_zap_collapsible_spte, true);
5917 spin_unlock(&kvm->mmu_lock);
5920 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5921 struct kvm_memory_slot *memslot)
5925 spin_lock(&kvm->mmu_lock);
5926 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5927 spin_unlock(&kvm->mmu_lock);
5929 lockdep_assert_held(&kvm->slots_lock);
5932 * It's also safe to flush TLBs out of mmu lock here as currently this
5933 * function is only used for dirty logging, in which case flushing TLB
5934 * out of mmu lock also guarantees no dirty pages will be lost in
5938 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5941 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5943 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5944 struct kvm_memory_slot *memslot)
5948 spin_lock(&kvm->mmu_lock);
5949 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5951 spin_unlock(&kvm->mmu_lock);
5953 /* see kvm_mmu_slot_remove_write_access */
5954 lockdep_assert_held(&kvm->slots_lock);
5957 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5960 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5962 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5963 struct kvm_memory_slot *memslot)
5967 spin_lock(&kvm->mmu_lock);
5968 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5969 spin_unlock(&kvm->mmu_lock);
5971 lockdep_assert_held(&kvm->slots_lock);
5973 /* see kvm_mmu_slot_leaf_clear_dirty */
5975 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5978 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5980 void kvm_mmu_zap_all(struct kvm *kvm)
5982 struct kvm_mmu_page *sp, *node;
5983 LIST_HEAD(invalid_list);
5986 spin_lock(&kvm->mmu_lock);
5988 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
5989 if (sp->role.invalid && sp->root_count)
5991 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
5993 if (cond_resched_lock(&kvm->mmu_lock))
5997 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5998 spin_unlock(&kvm->mmu_lock);
6001 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6003 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6005 gen &= MMIO_SPTE_GEN_MASK;
6008 * Generation numbers are incremented in multiples of the number of
6009 * address spaces in order to provide unique generations across all
6010 * address spaces. Strip what is effectively the address space
6011 * modifier prior to checking for a wrap of the MMIO generation so
6012 * that a wrap in any address space is detected.
6014 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6017 * The very rare case: if the MMIO generation number has wrapped,
6018 * zap all shadow pages.
6020 if (unlikely(gen == 0)) {
6021 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6022 kvm_mmu_zap_all_fast(kvm);
6026 static unsigned long
6027 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6030 int nr_to_scan = sc->nr_to_scan;
6031 unsigned long freed = 0;
6033 mutex_lock(&kvm_lock);
6035 list_for_each_entry(kvm, &vm_list, vm_list) {
6037 LIST_HEAD(invalid_list);
6040 * Never scan more than sc->nr_to_scan VM instances.
6041 * Will not hit this condition practically since we do not try
6042 * to shrink more than one VM and it is very unlikely to see
6043 * !n_used_mmu_pages so many times.
6048 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6049 * here. We may skip a VM instance errorneosly, but we do not
6050 * want to shrink a VM that only started to populate its MMU
6053 if (!kvm->arch.n_used_mmu_pages &&
6054 !kvm_has_zapped_obsolete_pages(kvm))
6057 idx = srcu_read_lock(&kvm->srcu);
6058 spin_lock(&kvm->mmu_lock);
6060 if (kvm_has_zapped_obsolete_pages(kvm)) {
6061 kvm_mmu_commit_zap_page(kvm,
6062 &kvm->arch.zapped_obsolete_pages);
6066 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6068 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6071 spin_unlock(&kvm->mmu_lock);
6072 srcu_read_unlock(&kvm->srcu, idx);
6075 * unfair on small ones
6076 * per-vm shrinkers cry out
6077 * sadness comes quickly
6079 list_move_tail(&kvm->vm_list, &vm_list);
6083 mutex_unlock(&kvm_lock);
6087 static unsigned long
6088 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6090 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6093 static struct shrinker mmu_shrinker = {
6094 .count_objects = mmu_shrink_count,
6095 .scan_objects = mmu_shrink_scan,
6096 .seeks = DEFAULT_SEEKS * 10,
6099 static void mmu_destroy_caches(void)
6101 kmem_cache_destroy(pte_list_desc_cache);
6102 kmem_cache_destroy(mmu_page_header_cache);
6105 static void kvm_set_mmio_spte_mask(void)
6110 * Set the reserved bits and the present bit of an paging-structure
6111 * entry to generate page fault with PFER.RSV = 1.
6115 * Mask the uppermost physical address bit, which would be reserved as
6116 * long as the supported physical address width is less than 52.
6120 /* Set the present bit. */
6124 * If reserved bit is not supported, clear the present bit to disable
6127 if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
6130 kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
6133 int kvm_mmu_module_init(void)
6138 * MMU roles use union aliasing which is, generally speaking, an
6139 * undefined behavior. However, we supposedly know how compilers behave
6140 * and the current status quo is unlikely to change. Guardians below are
6141 * supposed to let us know if the assumption becomes false.
6143 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6144 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6145 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6147 kvm_mmu_reset_all_pte_masks();
6149 kvm_set_mmio_spte_mask();
6151 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6152 sizeof(struct pte_list_desc),
6153 0, SLAB_ACCOUNT, NULL);
6154 if (!pte_list_desc_cache)
6157 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6158 sizeof(struct kvm_mmu_page),
6159 0, SLAB_ACCOUNT, NULL);
6160 if (!mmu_page_header_cache)
6163 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6166 ret = register_shrinker(&mmu_shrinker);
6173 mmu_destroy_caches();
6178 * Calculate mmu pages needed for kvm.
6180 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6182 unsigned long nr_mmu_pages;
6183 unsigned long nr_pages = 0;
6184 struct kvm_memslots *slots;
6185 struct kvm_memory_slot *memslot;
6188 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6189 slots = __kvm_memslots(kvm, i);
6191 kvm_for_each_memslot(memslot, slots)
6192 nr_pages += memslot->npages;
6195 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6196 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6198 return nr_mmu_pages;
6201 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6203 kvm_mmu_unload(vcpu);
6204 free_mmu_pages(&vcpu->arch.root_mmu);
6205 free_mmu_pages(&vcpu->arch.guest_mmu);
6206 mmu_free_memory_caches(vcpu);
6209 void kvm_mmu_module_exit(void)
6211 mmu_destroy_caches();
6212 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6213 unregister_shrinker(&mmu_shrinker);
6214 mmu_audit_disable();