2 * Kernel-based Virtual Machine driver for Linux
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
9 * Copyright (C) 2006 Qumranet, Inc.
10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Avi Kivity <avi@qumranet.com>
16 * This work is licensed under the terms of the GNU GPL, version 2. See
17 * the COPYING file in the top-level directory.
24 #include "kvm_cache_regs.h"
27 #include <linux/kvm_host.h>
28 #include <linux/types.h>
29 #include <linux/string.h>
31 #include <linux/highmem.h>
32 #include <linux/moduleparam.h>
33 #include <linux/export.h>
34 #include <linux/swap.h>
35 #include <linux/hugetlb.h>
36 #include <linux/compiler.h>
37 #include <linux/srcu.h>
38 #include <linux/slab.h>
39 #include <linux/sched/signal.h>
40 #include <linux/uaccess.h>
41 #include <linux/hash.h>
42 #include <linux/kern_levels.h>
43 #include <linux/kthread.h>
46 #include <asm/cmpxchg.h>
49 #include <asm/kvm_page_track.h>
52 extern bool itlb_multihit_kvm_mitigation;
54 static int __read_mostly nx_huge_pages = -1;
55 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
57 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
58 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp);
60 static struct kernel_param_ops nx_huge_pages_ops = {
61 .set = set_nx_huge_pages,
62 .get = param_get_bool,
65 static struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
66 .set = set_nx_huge_pages_recovery_ratio,
67 .get = param_get_uint,
70 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
71 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
72 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
73 &nx_huge_pages_recovery_ratio, 0644);
74 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
77 * When setting this variable to true it enables Two-Dimensional-Paging
78 * where the hardware walks 2 page tables:
79 * 1. the guest-virtual to guest-physical
80 * 2. while doing 1. it walks guest-physical to host-physical
81 * If the hardware supports that we don't need to do shadow paging.
83 bool tdp_enabled = false;
87 AUDIT_POST_PAGE_FAULT,
98 module_param(dbg, bool, 0644);
100 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
101 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
102 #define MMU_WARN_ON(x) WARN_ON(x)
104 #define pgprintk(x...) do { } while (0)
105 #define rmap_printk(x...) do { } while (0)
106 #define MMU_WARN_ON(x) do { } while (0)
109 #define PTE_PREFETCH_NUM 8
111 #define PT_FIRST_AVAIL_BITS_SHIFT 10
112 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
114 #define PT64_LEVEL_BITS 9
116 #define PT64_LEVEL_SHIFT(level) \
117 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
119 #define PT64_INDEX(address, level)\
120 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
123 #define PT32_LEVEL_BITS 10
125 #define PT32_LEVEL_SHIFT(level) \
126 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
128 #define PT32_LVL_OFFSET_MASK(level) \
129 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
130 * PT32_LEVEL_BITS))) - 1))
132 #define PT32_INDEX(address, level)\
133 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
136 #define PT64_BASE_ADDR_MASK __sme_clr((((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)))
137 #define PT64_DIR_BASE_ADDR_MASK \
138 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
139 #define PT64_LVL_ADDR_MASK(level) \
140 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
141 * PT64_LEVEL_BITS))) - 1))
142 #define PT64_LVL_OFFSET_MASK(level) \
143 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
144 * PT64_LEVEL_BITS))) - 1))
146 #define PT32_BASE_ADDR_MASK PAGE_MASK
147 #define PT32_DIR_BASE_ADDR_MASK \
148 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
149 #define PT32_LVL_ADDR_MASK(level) \
150 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
151 * PT32_LEVEL_BITS))) - 1))
153 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
154 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
156 #define ACC_EXEC_MASK 1
157 #define ACC_WRITE_MASK PT_WRITABLE_MASK
158 #define ACC_USER_MASK PT_USER_MASK
159 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
161 /* The mask for the R/X bits in EPT PTEs */
162 #define PT64_EPT_READABLE_MASK 0x1ull
163 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
165 #include <trace/events/kvm.h>
167 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
168 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
170 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
172 /* make pte_list_desc fit well in cache line */
173 #define PTE_LIST_EXT 3
176 * Return values of handle_mmio_page_fault and mmu.page_fault:
177 * RET_PF_RETRY: let CPU fault again on the address.
178 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
180 * For handle_mmio_page_fault only:
181 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
189 struct pte_list_desc {
190 u64 *sptes[PTE_LIST_EXT];
191 struct pte_list_desc *more;
194 struct kvm_shadow_walk_iterator {
202 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
203 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
204 shadow_walk_okay(&(_walker)); \
205 shadow_walk_next(&(_walker)))
207 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
208 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
209 shadow_walk_okay(&(_walker)) && \
210 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
211 __shadow_walk_next(&(_walker), spte))
213 static struct kmem_cache *pte_list_desc_cache;
214 static struct kmem_cache *mmu_page_header_cache;
215 static struct percpu_counter kvm_total_used_mmu_pages;
217 static u64 __read_mostly shadow_nx_mask;
218 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
219 static u64 __read_mostly shadow_user_mask;
220 static u64 __read_mostly shadow_accessed_mask;
221 static u64 __read_mostly shadow_dirty_mask;
222 static u64 __read_mostly shadow_mmio_mask;
223 static u64 __read_mostly shadow_mmio_value;
224 static u64 __read_mostly shadow_present_mask;
225 static u64 __read_mostly shadow_me_mask;
228 * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
229 * Non-present SPTEs with shadow_acc_track_value set are in place for access
232 static u64 __read_mostly shadow_acc_track_mask;
233 static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
236 * The mask/shift to use for saving the original R/X bits when marking the PTE
237 * as not-present for access tracking purposes. We do not save the W bit as the
238 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
239 * restored only when a write is attempted to the page.
241 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
242 PT64_EPT_EXECUTABLE_MASK;
243 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
246 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
247 * to guard against L1TF attacks.
249 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
252 * The number of high-order 1 bits to use in the mask above.
254 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
257 * In some cases, we need to preserve the GFN of a non-present or reserved
258 * SPTE when we usurp the upper five bits of the physical address space to
259 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
260 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
261 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
262 * high and low parts. This mask covers the lower bits of the GFN.
264 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
267 * The number of non-reserved physical address bits irrespective of features
268 * that repurpose legal bits, e.g. MKTME.
270 static u8 __read_mostly shadow_phys_bits;
272 static void mmu_spte_set(u64 *sptep, u64 spte);
273 static void mmu_free_roots(struct kvm_vcpu *vcpu);
274 static bool is_executable_pte(u64 spte);
276 #define CREATE_TRACE_POINTS
277 #include "mmutrace.h"
280 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
282 BUG_ON((mmio_mask & mmio_value) != mmio_value);
283 WARN_ON(mmio_value & (shadow_nonpresent_or_rsvd_mask << shadow_nonpresent_or_rsvd_mask_len));
284 WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);
285 shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
286 shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
288 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
290 static bool is_mmio_spte(u64 spte)
292 return (spte & shadow_mmio_mask) == shadow_mmio_value;
295 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
297 return sp->role.ad_disabled;
300 static inline bool spte_ad_enabled(u64 spte)
302 MMU_WARN_ON(is_mmio_spte(spte));
303 return !(spte & shadow_acc_track_value);
306 static bool is_nx_huge_page_enabled(void)
308 return READ_ONCE(nx_huge_pages);
311 static inline u64 spte_shadow_accessed_mask(u64 spte)
313 MMU_WARN_ON(is_mmio_spte(spte));
314 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
317 static inline u64 spte_shadow_dirty_mask(u64 spte)
319 MMU_WARN_ON(is_mmio_spte(spte));
320 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
323 static inline bool is_access_track_spte(u64 spte)
325 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
329 * the low bit of the generation number is always presumed to be zero.
330 * This disables mmio caching during memslot updates. The concept is
331 * similar to a seqcount but instead of retrying the access we just punt
332 * and ignore the cache.
334 * spte bits 3-11 are used as bits 1-9 of the generation number,
335 * the bits 52-61 are used as bits 10-19 of the generation number.
337 #define MMIO_SPTE_GEN_LOW_SHIFT 2
338 #define MMIO_SPTE_GEN_HIGH_SHIFT 52
340 #define MMIO_GEN_SHIFT 20
341 #define MMIO_GEN_LOW_SHIFT 10
342 #define MMIO_GEN_LOW_MASK ((1 << MMIO_GEN_LOW_SHIFT) - 2)
343 #define MMIO_GEN_MASK ((1 << MMIO_GEN_SHIFT) - 1)
345 static u64 generation_mmio_spte_mask(unsigned int gen)
349 WARN_ON(gen & ~MMIO_GEN_MASK);
351 mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
352 mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
356 static unsigned int get_mmio_spte_generation(u64 spte)
360 spte &= ~shadow_mmio_mask;
362 gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
363 gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
367 static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
369 return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
372 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
375 unsigned int gen = kvm_current_mmio_generation(vcpu);
376 u64 mask = generation_mmio_spte_mask(gen);
377 u64 gpa = gfn << PAGE_SHIFT;
379 access &= ACC_WRITE_MASK | ACC_USER_MASK;
380 mask |= shadow_mmio_value | access;
381 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
382 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
383 << shadow_nonpresent_or_rsvd_mask_len;
385 trace_mark_mmio_spte(sptep, gfn, access, gen);
386 mmu_spte_set(sptep, mask);
389 static gfn_t get_mmio_spte_gfn(u64 spte)
391 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
393 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
394 & shadow_nonpresent_or_rsvd_mask;
396 return gpa >> PAGE_SHIFT;
399 static unsigned get_mmio_spte_access(u64 spte)
401 u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
402 return (spte & ~mask) & ~PAGE_MASK;
405 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
406 kvm_pfn_t pfn, unsigned access)
408 if (unlikely(is_noslot_pfn(pfn))) {
409 mark_mmio_spte(vcpu, sptep, gfn, access);
416 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
418 unsigned int kvm_gen, spte_gen;
420 kvm_gen = kvm_current_mmio_generation(vcpu);
421 spte_gen = get_mmio_spte_generation(spte);
423 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
424 return likely(kvm_gen == spte_gen);
428 * Sets the shadow PTE masks used by the MMU.
431 * - Setting either @accessed_mask or @dirty_mask requires setting both
432 * - At least one of @accessed_mask or @acc_track_mask must be set
434 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
435 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
436 u64 acc_track_mask, u64 me_mask)
438 BUG_ON(!dirty_mask != !accessed_mask);
439 BUG_ON(!accessed_mask && !acc_track_mask);
440 BUG_ON(acc_track_mask & shadow_acc_track_value);
442 shadow_user_mask = user_mask;
443 shadow_accessed_mask = accessed_mask;
444 shadow_dirty_mask = dirty_mask;
445 shadow_nx_mask = nx_mask;
446 shadow_x_mask = x_mask;
447 shadow_present_mask = p_mask;
448 shadow_acc_track_mask = acc_track_mask;
449 shadow_me_mask = me_mask;
451 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
453 static u8 kvm_get_shadow_phys_bits(void)
456 * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
457 * in CPU detection code, but MKTME treats those reduced bits as
458 * 'keyID' thus they are not reserved bits. Therefore for MKTME
459 * we should still return physical address bits reported by CPUID.
461 if (!boot_cpu_has(X86_FEATURE_TME) ||
462 WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
463 return boot_cpu_data.x86_phys_bits;
465 return cpuid_eax(0x80000008) & 0xff;
468 static void kvm_mmu_reset_all_pte_masks(void)
472 shadow_user_mask = 0;
473 shadow_accessed_mask = 0;
474 shadow_dirty_mask = 0;
477 shadow_mmio_mask = 0;
478 shadow_present_mask = 0;
479 shadow_acc_track_mask = 0;
481 shadow_phys_bits = kvm_get_shadow_phys_bits();
484 * If the CPU has 46 or less physical address bits, then set an
485 * appropriate mask to guard against L1TF attacks. Otherwise, it is
486 * assumed that the CPU is not vulnerable to L1TF.
488 * Some Intel CPUs address the L1 cache using more PA bits than are
489 * reported by CPUID. Use the PA width of the L1 cache when possible
490 * to achieve more effective mitigation, e.g. if system RAM overlaps
491 * the most significant bits of legal physical address space.
493 shadow_nonpresent_or_rsvd_mask = 0;
494 low_phys_bits = boot_cpu_data.x86_phys_bits;
495 if (boot_cpu_has_bug(X86_BUG_L1TF) &&
496 !WARN_ON_ONCE(boot_cpu_data.x86_cache_bits >=
497 52 - shadow_nonpresent_or_rsvd_mask_len)) {
498 low_phys_bits = boot_cpu_data.x86_cache_bits
499 - shadow_nonpresent_or_rsvd_mask_len;
500 shadow_nonpresent_or_rsvd_mask =
501 rsvd_bits(low_phys_bits, boot_cpu_data.x86_cache_bits - 1);
504 shadow_nonpresent_or_rsvd_lower_gfn_mask =
505 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
508 static int is_cpuid_PSE36(void)
513 static int is_nx(struct kvm_vcpu *vcpu)
515 return vcpu->arch.efer & EFER_NX;
518 static int is_shadow_present_pte(u64 pte)
520 return (pte != 0) && !is_mmio_spte(pte);
523 static int is_large_pte(u64 pte)
525 return pte & PT_PAGE_SIZE_MASK;
528 static int is_last_spte(u64 pte, int level)
530 if (level == PT_PAGE_TABLE_LEVEL)
532 if (is_large_pte(pte))
537 static bool is_executable_pte(u64 spte)
539 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
542 static kvm_pfn_t spte_to_pfn(u64 pte)
544 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
547 static gfn_t pse36_gfn_delta(u32 gpte)
549 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
551 return (gpte & PT32_DIR_PSE36_MASK) << shift;
555 static void __set_spte(u64 *sptep, u64 spte)
557 WRITE_ONCE(*sptep, spte);
560 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
562 WRITE_ONCE(*sptep, spte);
565 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
567 return xchg(sptep, spte);
570 static u64 __get_spte_lockless(u64 *sptep)
572 return ACCESS_ONCE(*sptep);
583 static void count_spte_clear(u64 *sptep, u64 spte)
585 struct kvm_mmu_page *sp = page_header(__pa(sptep));
587 if (is_shadow_present_pte(spte))
590 /* Ensure the spte is completely set before we increase the count */
592 sp->clear_spte_count++;
595 static void __set_spte(u64 *sptep, u64 spte)
597 union split_spte *ssptep, sspte;
599 ssptep = (union split_spte *)sptep;
600 sspte = (union split_spte)spte;
602 ssptep->spte_high = sspte.spte_high;
605 * If we map the spte from nonpresent to present, We should store
606 * the high bits firstly, then set present bit, so cpu can not
607 * fetch this spte while we are setting the spte.
611 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
614 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
616 union split_spte *ssptep, sspte;
618 ssptep = (union split_spte *)sptep;
619 sspte = (union split_spte)spte;
621 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
624 * If we map the spte from present to nonpresent, we should clear
625 * present bit firstly to avoid vcpu fetch the old high bits.
629 ssptep->spte_high = sspte.spte_high;
630 count_spte_clear(sptep, spte);
633 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
635 union split_spte *ssptep, sspte, orig;
637 ssptep = (union split_spte *)sptep;
638 sspte = (union split_spte)spte;
640 /* xchg acts as a barrier before the setting of the high bits */
641 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
642 orig.spte_high = ssptep->spte_high;
643 ssptep->spte_high = sspte.spte_high;
644 count_spte_clear(sptep, spte);
650 * The idea using the light way get the spte on x86_32 guest is from
651 * gup_get_pte(arch/x86/mm/gup.c).
653 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
654 * coalesces them and we are running out of the MMU lock. Therefore
655 * we need to protect against in-progress updates of the spte.
657 * Reading the spte while an update is in progress may get the old value
658 * for the high part of the spte. The race is fine for a present->non-present
659 * change (because the high part of the spte is ignored for non-present spte),
660 * but for a present->present change we must reread the spte.
662 * All such changes are done in two steps (present->non-present and
663 * non-present->present), hence it is enough to count the number of
664 * present->non-present updates: if it changed while reading the spte,
665 * we might have hit the race. This is done using clear_spte_count.
667 static u64 __get_spte_lockless(u64 *sptep)
669 struct kvm_mmu_page *sp = page_header(__pa(sptep));
670 union split_spte spte, *orig = (union split_spte *)sptep;
674 count = sp->clear_spte_count;
677 spte.spte_low = orig->spte_low;
680 spte.spte_high = orig->spte_high;
683 if (unlikely(spte.spte_low != orig->spte_low ||
684 count != sp->clear_spte_count))
691 static bool spte_can_locklessly_be_made_writable(u64 spte)
693 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
694 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
697 static bool spte_has_volatile_bits(u64 spte)
699 if (!is_shadow_present_pte(spte))
703 * Always atomically update spte if it can be updated
704 * out of mmu-lock, it can ensure dirty bit is not lost,
705 * also, it can help us to get a stable is_writable_pte()
706 * to ensure tlb flush is not missed.
708 if (spte_can_locklessly_be_made_writable(spte) ||
709 is_access_track_spte(spte))
712 if (spte_ad_enabled(spte)) {
713 if ((spte & shadow_accessed_mask) == 0 ||
714 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
721 static bool is_accessed_spte(u64 spte)
723 u64 accessed_mask = spte_shadow_accessed_mask(spte);
725 return accessed_mask ? spte & accessed_mask
726 : !is_access_track_spte(spte);
729 static bool is_dirty_spte(u64 spte)
731 u64 dirty_mask = spte_shadow_dirty_mask(spte);
733 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
736 /* Rules for using mmu_spte_set:
737 * Set the sptep from nonpresent to present.
738 * Note: the sptep being assigned *must* be either not present
739 * or in a state where the hardware will not attempt to update
742 static void mmu_spte_set(u64 *sptep, u64 new_spte)
744 WARN_ON(is_shadow_present_pte(*sptep));
745 __set_spte(sptep, new_spte);
749 * Update the SPTE (excluding the PFN), but do not track changes in its
750 * accessed/dirty status.
752 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
754 u64 old_spte = *sptep;
756 WARN_ON(!is_shadow_present_pte(new_spte));
758 if (!is_shadow_present_pte(old_spte)) {
759 mmu_spte_set(sptep, new_spte);
763 if (!spte_has_volatile_bits(old_spte))
764 __update_clear_spte_fast(sptep, new_spte);
766 old_spte = __update_clear_spte_slow(sptep, new_spte);
768 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
773 /* Rules for using mmu_spte_update:
774 * Update the state bits, it means the mapped pfn is not changed.
776 * Whenever we overwrite a writable spte with a read-only one we
777 * should flush remote TLBs. Otherwise rmap_write_protect
778 * will find a read-only spte, even though the writable spte
779 * might be cached on a CPU's TLB, the return value indicates this
782 * Returns true if the TLB needs to be flushed
784 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
787 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
789 if (!is_shadow_present_pte(old_spte))
793 * For the spte updated out of mmu-lock is safe, since
794 * we always atomically update it, see the comments in
795 * spte_has_volatile_bits().
797 if (spte_can_locklessly_be_made_writable(old_spte) &&
798 !is_writable_pte(new_spte))
802 * Flush TLB when accessed/dirty states are changed in the page tables,
803 * to guarantee consistency between TLB and page tables.
806 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
808 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
811 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
813 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
820 * Rules for using mmu_spte_clear_track_bits:
821 * It sets the sptep from present to nonpresent, and track the
822 * state bits, it is used to clear the last level sptep.
823 * Returns non-zero if the PTE was previously valid.
825 static int mmu_spte_clear_track_bits(u64 *sptep)
828 u64 old_spte = *sptep;
830 if (!spte_has_volatile_bits(old_spte))
831 __update_clear_spte_fast(sptep, 0ull);
833 old_spte = __update_clear_spte_slow(sptep, 0ull);
835 if (!is_shadow_present_pte(old_spte))
838 pfn = spte_to_pfn(old_spte);
841 * KVM does not hold the refcount of the page used by
842 * kvm mmu, before reclaiming the page, we should
843 * unmap it from mmu first.
845 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
847 if (is_accessed_spte(old_spte))
848 kvm_set_pfn_accessed(pfn);
850 if (is_dirty_spte(old_spte))
851 kvm_set_pfn_dirty(pfn);
857 * Rules for using mmu_spte_clear_no_track:
858 * Directly clear spte without caring the state bits of sptep,
859 * it is used to set the upper level spte.
861 static void mmu_spte_clear_no_track(u64 *sptep)
863 __update_clear_spte_fast(sptep, 0ull);
866 static u64 mmu_spte_get_lockless(u64 *sptep)
868 return __get_spte_lockless(sptep);
871 static u64 mark_spte_for_access_track(u64 spte)
873 if (spte_ad_enabled(spte))
874 return spte & ~shadow_accessed_mask;
876 if (is_access_track_spte(spte))
880 * Making an Access Tracking PTE will result in removal of write access
881 * from the PTE. So, verify that we will be able to restore the write
882 * access in the fast page fault path later on.
884 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
885 !spte_can_locklessly_be_made_writable(spte),
886 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
888 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
889 shadow_acc_track_saved_bits_shift),
890 "kvm: Access Tracking saved bit locations are not zero\n");
892 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
893 shadow_acc_track_saved_bits_shift;
894 spte &= ~shadow_acc_track_mask;
899 /* Restore an acc-track PTE back to a regular PTE */
900 static u64 restore_acc_track_spte(u64 spte)
903 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
904 & shadow_acc_track_saved_bits_mask;
906 WARN_ON_ONCE(spte_ad_enabled(spte));
907 WARN_ON_ONCE(!is_access_track_spte(spte));
909 new_spte &= ~shadow_acc_track_mask;
910 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
911 shadow_acc_track_saved_bits_shift);
912 new_spte |= saved_bits;
917 /* Returns the Accessed status of the PTE and resets it at the same time. */
918 static bool mmu_spte_age(u64 *sptep)
920 u64 spte = mmu_spte_get_lockless(sptep);
922 if (!is_accessed_spte(spte))
925 if (spte_ad_enabled(spte)) {
926 clear_bit((ffs(shadow_accessed_mask) - 1),
927 (unsigned long *)sptep);
930 * Capture the dirty status of the page, so that it doesn't get
931 * lost when the SPTE is marked for access tracking.
933 if (is_writable_pte(spte))
934 kvm_set_pfn_dirty(spte_to_pfn(spte));
936 spte = mark_spte_for_access_track(spte);
937 mmu_spte_update_no_track(sptep, spte);
943 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
946 * Prevent page table teardown by making any free-er wait during
947 * kvm_flush_remote_tlbs() IPI to all active vcpus.
952 * Make sure a following spte read is not reordered ahead of the write
955 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
958 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
961 * Make sure the write to vcpu->mode is not reordered in front of
962 * reads to sptes. If it does, kvm_commit_zap_page() can see us
963 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
965 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
969 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
970 struct kmem_cache *base_cache, int min)
974 if (cache->nobjs >= min)
976 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
977 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
980 cache->objects[cache->nobjs++] = obj;
985 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
990 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
991 struct kmem_cache *cache)
994 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
997 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1002 if (cache->nobjs >= min)
1004 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1005 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1008 cache->objects[cache->nobjs++] = page;
1013 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1016 free_page((unsigned long)mc->objects[--mc->nobjs]);
1019 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1023 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1024 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1027 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1030 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1031 mmu_page_header_cache, 4);
1036 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1038 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1039 pte_list_desc_cache);
1040 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1041 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1042 mmu_page_header_cache);
1045 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1050 p = mc->objects[--mc->nobjs];
1054 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1056 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1059 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1061 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1064 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1066 if (!sp->role.direct)
1067 return sp->gfns[index];
1069 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1072 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1074 if (!sp->role.direct) {
1075 sp->gfns[index] = gfn;
1079 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1080 pr_err_ratelimited("gfn mismatch under direct page %llx "
1081 "(expected %llx, got %llx)\n",
1083 kvm_mmu_page_get_gfn(sp, index), gfn);
1087 * Return the pointer to the large page information for a given gfn,
1088 * handling slots that are not large page aligned.
1090 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1091 struct kvm_memory_slot *slot,
1096 idx = gfn_to_index(gfn, slot->base_gfn, level);
1097 return &slot->arch.lpage_info[level - 2][idx];
1100 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1101 gfn_t gfn, int count)
1103 struct kvm_lpage_info *linfo;
1106 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1107 linfo = lpage_info_slot(gfn, slot, i);
1108 linfo->disallow_lpage += count;
1109 WARN_ON(linfo->disallow_lpage < 0);
1113 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1115 update_gfn_disallow_lpage_count(slot, gfn, 1);
1118 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1120 update_gfn_disallow_lpage_count(slot, gfn, -1);
1123 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1125 struct kvm_memslots *slots;
1126 struct kvm_memory_slot *slot;
1129 kvm->arch.indirect_shadow_pages++;
1131 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1132 slot = __gfn_to_memslot(slots, gfn);
1134 /* the non-leaf shadow pages are keeping readonly. */
1135 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1136 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1137 KVM_PAGE_TRACK_WRITE);
1139 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1142 static void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1144 if (sp->lpage_disallowed)
1147 ++kvm->stat.nx_lpage_splits;
1148 list_add_tail(&sp->lpage_disallowed_link,
1149 &kvm->arch.lpage_disallowed_mmu_pages);
1150 sp->lpage_disallowed = true;
1153 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1155 struct kvm_memslots *slots;
1156 struct kvm_memory_slot *slot;
1159 kvm->arch.indirect_shadow_pages--;
1161 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1162 slot = __gfn_to_memslot(slots, gfn);
1163 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1164 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1165 KVM_PAGE_TRACK_WRITE);
1167 kvm_mmu_gfn_allow_lpage(slot, gfn);
1170 static void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1172 --kvm->stat.nx_lpage_splits;
1173 sp->lpage_disallowed = false;
1174 list_del(&sp->lpage_disallowed_link);
1177 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1178 struct kvm_memory_slot *slot)
1180 struct kvm_lpage_info *linfo;
1183 linfo = lpage_info_slot(gfn, slot, level);
1184 return !!linfo->disallow_lpage;
1190 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1193 struct kvm_memory_slot *slot;
1195 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1196 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1199 static int host_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn)
1201 unsigned long page_size;
1204 page_size = kvm_host_page_size(vcpu, gfn);
1206 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1207 if (page_size >= KVM_HPAGE_SIZE(i))
1216 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1219 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1221 if (no_dirty_log && slot->dirty_bitmap)
1227 static struct kvm_memory_slot *
1228 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1231 struct kvm_memory_slot *slot;
1233 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1234 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1240 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1241 bool *force_pt_level)
1243 int host_level, level, max_level;
1244 struct kvm_memory_slot *slot;
1246 if (unlikely(*force_pt_level))
1247 return PT_PAGE_TABLE_LEVEL;
1249 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1250 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1251 if (unlikely(*force_pt_level))
1252 return PT_PAGE_TABLE_LEVEL;
1254 host_level = host_mapping_level(vcpu, large_gfn);
1256 if (host_level == PT_PAGE_TABLE_LEVEL)
1259 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1261 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1262 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1269 * About rmap_head encoding:
1271 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1272 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1273 * pte_list_desc containing more mappings.
1277 * Returns the number of pointers in the rmap chain, not counting the new one.
1279 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1280 struct kvm_rmap_head *rmap_head)
1282 struct pte_list_desc *desc;
1285 if (!rmap_head->val) {
1286 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1287 rmap_head->val = (unsigned long)spte;
1288 } else if (!(rmap_head->val & 1)) {
1289 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1290 desc = mmu_alloc_pte_list_desc(vcpu);
1291 desc->sptes[0] = (u64 *)rmap_head->val;
1292 desc->sptes[1] = spte;
1293 rmap_head->val = (unsigned long)desc | 1;
1296 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1297 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1298 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1300 count += PTE_LIST_EXT;
1302 if (desc->sptes[PTE_LIST_EXT-1]) {
1303 desc->more = mmu_alloc_pte_list_desc(vcpu);
1306 for (i = 0; desc->sptes[i]; ++i)
1308 desc->sptes[i] = spte;
1314 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1315 struct pte_list_desc *desc, int i,
1316 struct pte_list_desc *prev_desc)
1320 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1322 desc->sptes[i] = desc->sptes[j];
1323 desc->sptes[j] = NULL;
1326 if (!prev_desc && !desc->more)
1327 rmap_head->val = (unsigned long)desc->sptes[0];
1330 prev_desc->more = desc->more;
1332 rmap_head->val = (unsigned long)desc->more | 1;
1333 mmu_free_pte_list_desc(desc);
1336 static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1338 struct pte_list_desc *desc;
1339 struct pte_list_desc *prev_desc;
1342 if (!rmap_head->val) {
1343 printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
1345 } else if (!(rmap_head->val & 1)) {
1346 rmap_printk("pte_list_remove: %p 1->0\n", spte);
1347 if ((u64 *)rmap_head->val != spte) {
1348 printk(KERN_ERR "pte_list_remove: %p 1->BUG\n", spte);
1353 rmap_printk("pte_list_remove: %p many->many\n", spte);
1354 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1357 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1358 if (desc->sptes[i] == spte) {
1359 pte_list_desc_remove_entry(rmap_head,
1360 desc, i, prev_desc);
1367 pr_err("pte_list_remove: %p many->many\n", spte);
1372 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1373 struct kvm_memory_slot *slot)
1377 idx = gfn_to_index(gfn, slot->base_gfn, level);
1378 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1381 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1382 struct kvm_mmu_page *sp)
1384 struct kvm_memslots *slots;
1385 struct kvm_memory_slot *slot;
1387 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1388 slot = __gfn_to_memslot(slots, gfn);
1389 return __gfn_to_rmap(gfn, sp->role.level, slot);
1392 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1394 struct kvm_mmu_memory_cache *cache;
1396 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1397 return mmu_memory_cache_free_objects(cache);
1400 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1402 struct kvm_mmu_page *sp;
1403 struct kvm_rmap_head *rmap_head;
1405 sp = page_header(__pa(spte));
1406 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1407 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1408 return pte_list_add(vcpu, spte, rmap_head);
1411 static void rmap_remove(struct kvm *kvm, u64 *spte)
1413 struct kvm_mmu_page *sp;
1415 struct kvm_rmap_head *rmap_head;
1417 sp = page_header(__pa(spte));
1418 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1419 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1420 pte_list_remove(spte, rmap_head);
1424 * Used by the following functions to iterate through the sptes linked by a
1425 * rmap. All fields are private and not assumed to be used outside.
1427 struct rmap_iterator {
1428 /* private fields */
1429 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1430 int pos; /* index of the sptep */
1434 * Iteration must be started by this function. This should also be used after
1435 * removing/dropping sptes from the rmap link because in such cases the
1436 * information in the itererator may not be valid.
1438 * Returns sptep if found, NULL otherwise.
1440 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1441 struct rmap_iterator *iter)
1445 if (!rmap_head->val)
1448 if (!(rmap_head->val & 1)) {
1450 sptep = (u64 *)rmap_head->val;
1454 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1456 sptep = iter->desc->sptes[iter->pos];
1458 BUG_ON(!is_shadow_present_pte(*sptep));
1463 * Must be used with a valid iterator: e.g. after rmap_get_first().
1465 * Returns sptep if found, NULL otherwise.
1467 static u64 *rmap_get_next(struct rmap_iterator *iter)
1472 if (iter->pos < PTE_LIST_EXT - 1) {
1474 sptep = iter->desc->sptes[iter->pos];
1479 iter->desc = iter->desc->more;
1483 /* desc->sptes[0] cannot be NULL */
1484 sptep = iter->desc->sptes[iter->pos];
1491 BUG_ON(!is_shadow_present_pte(*sptep));
1495 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1496 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1497 _spte_; _spte_ = rmap_get_next(_iter_))
1499 static void drop_spte(struct kvm *kvm, u64 *sptep)
1501 if (mmu_spte_clear_track_bits(sptep))
1502 rmap_remove(kvm, sptep);
1506 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1508 if (is_large_pte(*sptep)) {
1509 WARN_ON(page_header(__pa(sptep))->role.level ==
1510 PT_PAGE_TABLE_LEVEL);
1511 drop_spte(kvm, sptep);
1519 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1521 if (__drop_large_spte(vcpu->kvm, sptep))
1522 kvm_flush_remote_tlbs(vcpu->kvm);
1526 * Write-protect on the specified @sptep, @pt_protect indicates whether
1527 * spte write-protection is caused by protecting shadow page table.
1529 * Note: write protection is difference between dirty logging and spte
1531 * - for dirty logging, the spte can be set to writable at anytime if
1532 * its dirty bitmap is properly set.
1533 * - for spte protection, the spte can be writable only after unsync-ing
1536 * Return true if tlb need be flushed.
1538 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1542 if (!is_writable_pte(spte) &&
1543 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1546 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1549 spte &= ~SPTE_MMU_WRITEABLE;
1550 spte = spte & ~PT_WRITABLE_MASK;
1552 return mmu_spte_update(sptep, spte);
1555 static bool __rmap_write_protect(struct kvm *kvm,
1556 struct kvm_rmap_head *rmap_head,
1560 struct rmap_iterator iter;
1563 for_each_rmap_spte(rmap_head, &iter, sptep)
1564 flush |= spte_write_protect(sptep, pt_protect);
1569 static bool spte_clear_dirty(u64 *sptep)
1573 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1575 spte &= ~shadow_dirty_mask;
1577 return mmu_spte_update(sptep, spte);
1580 static bool wrprot_ad_disabled_spte(u64 *sptep)
1582 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1583 (unsigned long *)sptep);
1585 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1587 return was_writable;
1591 * Gets the GFN ready for another round of dirty logging by clearing the
1592 * - D bit on ad-enabled SPTEs, and
1593 * - W bit on ad-disabled SPTEs.
1594 * Returns true iff any D or W bits were cleared.
1596 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1599 struct rmap_iterator iter;
1602 for_each_rmap_spte(rmap_head, &iter, sptep)
1603 if (spte_ad_enabled(*sptep))
1604 flush |= spte_clear_dirty(sptep);
1606 flush |= wrprot_ad_disabled_spte(sptep);
1611 static bool spte_set_dirty(u64 *sptep)
1615 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1617 spte |= shadow_dirty_mask;
1619 return mmu_spte_update(sptep, spte);
1622 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1625 struct rmap_iterator iter;
1628 for_each_rmap_spte(rmap_head, &iter, sptep)
1629 if (spte_ad_enabled(*sptep))
1630 flush |= spte_set_dirty(sptep);
1636 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1637 * @kvm: kvm instance
1638 * @slot: slot to protect
1639 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1640 * @mask: indicates which pages we should protect
1642 * Used when we do not need to care about huge page mappings: e.g. during dirty
1643 * logging we do not have any such mappings.
1645 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1646 struct kvm_memory_slot *slot,
1647 gfn_t gfn_offset, unsigned long mask)
1649 struct kvm_rmap_head *rmap_head;
1652 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1653 PT_PAGE_TABLE_LEVEL, slot);
1654 __rmap_write_protect(kvm, rmap_head, false);
1656 /* clear the first set bit */
1662 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1663 * protect the page if the D-bit isn't supported.
1664 * @kvm: kvm instance
1665 * @slot: slot to clear D-bit
1666 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1667 * @mask: indicates which pages we should clear D-bit
1669 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1671 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1672 struct kvm_memory_slot *slot,
1673 gfn_t gfn_offset, unsigned long mask)
1675 struct kvm_rmap_head *rmap_head;
1678 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1679 PT_PAGE_TABLE_LEVEL, slot);
1680 __rmap_clear_dirty(kvm, rmap_head);
1682 /* clear the first set bit */
1686 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1689 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1692 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1693 * enable dirty logging for them.
1695 * Used when we do not need to care about huge page mappings: e.g. during dirty
1696 * logging we do not have any such mappings.
1698 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1699 struct kvm_memory_slot *slot,
1700 gfn_t gfn_offset, unsigned long mask)
1702 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1703 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1706 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1710 * kvm_arch_write_log_dirty - emulate dirty page logging
1711 * @vcpu: Guest mode vcpu
1713 * Emulate arch specific page modification logging for the
1716 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu, gpa_t l2_gpa)
1718 if (kvm_x86_ops->write_log_dirty)
1719 return kvm_x86_ops->write_log_dirty(vcpu, l2_gpa);
1724 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1725 struct kvm_memory_slot *slot, u64 gfn)
1727 struct kvm_rmap_head *rmap_head;
1729 bool write_protected = false;
1731 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1732 rmap_head = __gfn_to_rmap(gfn, i, slot);
1733 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1736 return write_protected;
1739 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1741 struct kvm_memory_slot *slot;
1743 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1744 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1747 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1750 struct rmap_iterator iter;
1753 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1754 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1756 drop_spte(kvm, sptep);
1763 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1764 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1767 return kvm_zap_rmapp(kvm, rmap_head);
1770 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1771 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1775 struct rmap_iterator iter;
1778 pte_t *ptep = (pte_t *)data;
1781 WARN_ON(pte_huge(*ptep));
1782 new_pfn = pte_pfn(*ptep);
1785 for_each_rmap_spte(rmap_head, &iter, sptep) {
1786 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1787 sptep, *sptep, gfn, level);
1791 if (pte_write(*ptep)) {
1792 drop_spte(kvm, sptep);
1795 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1796 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1798 new_spte &= ~PT_WRITABLE_MASK;
1799 new_spte &= ~SPTE_HOST_WRITEABLE;
1801 new_spte = mark_spte_for_access_track(new_spte);
1803 mmu_spte_clear_track_bits(sptep);
1804 mmu_spte_set(sptep, new_spte);
1809 kvm_flush_remote_tlbs(kvm);
1814 struct slot_rmap_walk_iterator {
1816 struct kvm_memory_slot *slot;
1822 /* output fields. */
1824 struct kvm_rmap_head *rmap;
1827 /* private field. */
1828 struct kvm_rmap_head *end_rmap;
1832 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1834 iterator->level = level;
1835 iterator->gfn = iterator->start_gfn;
1836 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1837 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1842 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1843 struct kvm_memory_slot *slot, int start_level,
1844 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1846 iterator->slot = slot;
1847 iterator->start_level = start_level;
1848 iterator->end_level = end_level;
1849 iterator->start_gfn = start_gfn;
1850 iterator->end_gfn = end_gfn;
1852 rmap_walk_init_level(iterator, iterator->start_level);
1855 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1857 return !!iterator->rmap;
1860 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1862 if (++iterator->rmap <= iterator->end_rmap) {
1863 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1867 if (++iterator->level > iterator->end_level) {
1868 iterator->rmap = NULL;
1872 rmap_walk_init_level(iterator, iterator->level);
1875 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1876 _start_gfn, _end_gfn, _iter_) \
1877 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1878 _end_level_, _start_gfn, _end_gfn); \
1879 slot_rmap_walk_okay(_iter_); \
1880 slot_rmap_walk_next(_iter_))
1882 static int kvm_handle_hva_range(struct kvm *kvm,
1883 unsigned long start,
1886 int (*handler)(struct kvm *kvm,
1887 struct kvm_rmap_head *rmap_head,
1888 struct kvm_memory_slot *slot,
1891 unsigned long data))
1893 struct kvm_memslots *slots;
1894 struct kvm_memory_slot *memslot;
1895 struct slot_rmap_walk_iterator iterator;
1899 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1900 slots = __kvm_memslots(kvm, i);
1901 kvm_for_each_memslot(memslot, slots) {
1902 unsigned long hva_start, hva_end;
1903 gfn_t gfn_start, gfn_end;
1905 hva_start = max(start, memslot->userspace_addr);
1906 hva_end = min(end, memslot->userspace_addr +
1907 (memslot->npages << PAGE_SHIFT));
1908 if (hva_start >= hva_end)
1911 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1912 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1914 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1915 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1917 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1918 PT_MAX_HUGEPAGE_LEVEL,
1919 gfn_start, gfn_end - 1,
1921 ret |= handler(kvm, iterator.rmap, memslot,
1922 iterator.gfn, iterator.level, data);
1929 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1931 int (*handler)(struct kvm *kvm,
1932 struct kvm_rmap_head *rmap_head,
1933 struct kvm_memory_slot *slot,
1934 gfn_t gfn, int level,
1935 unsigned long data))
1937 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1940 int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
1942 return kvm_handle_hva(kvm, hva, 0, kvm_unmap_rmapp);
1945 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1947 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1950 void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1952 kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1955 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1956 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1960 struct rmap_iterator uninitialized_var(iter);
1963 for_each_rmap_spte(rmap_head, &iter, sptep)
1964 young |= mmu_spte_age(sptep);
1966 trace_kvm_age_page(gfn, level, slot, young);
1970 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1971 struct kvm_memory_slot *slot, gfn_t gfn,
1972 int level, unsigned long data)
1975 struct rmap_iterator iter;
1977 for_each_rmap_spte(rmap_head, &iter, sptep)
1978 if (is_accessed_spte(*sptep))
1983 #define RMAP_RECYCLE_THRESHOLD 1000
1985 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1987 struct kvm_rmap_head *rmap_head;
1988 struct kvm_mmu_page *sp;
1990 sp = page_header(__pa(spte));
1992 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1994 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1995 kvm_flush_remote_tlbs(vcpu->kvm);
1998 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2000 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2003 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2005 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2009 static int is_empty_shadow_page(u64 *spt)
2014 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2015 if (is_shadow_present_pte(*pos)) {
2016 printk(KERN_ERR "%s: %p %llx\n", __func__,
2025 * This value is the sum of all of the kvm instances's
2026 * kvm->arch.n_used_mmu_pages values. We need a global,
2027 * aggregate version in order to make the slab shrinker
2030 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
2032 kvm->arch.n_used_mmu_pages += nr;
2033 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2036 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2038 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2039 hlist_del(&sp->hash_link);
2040 list_del(&sp->link);
2041 free_page((unsigned long)sp->spt);
2042 if (!sp->role.direct)
2043 free_page((unsigned long)sp->gfns);
2044 kmem_cache_free(mmu_page_header_cache, sp);
2047 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2049 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2052 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2053 struct kvm_mmu_page *sp, u64 *parent_pte)
2058 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2061 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2064 pte_list_remove(parent_pte, &sp->parent_ptes);
2067 static void drop_parent_pte(struct kvm_mmu_page *sp,
2070 mmu_page_remove_parent_pte(sp, parent_pte);
2071 mmu_spte_clear_no_track(parent_pte);
2074 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2076 struct kvm_mmu_page *sp;
2078 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2079 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2081 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2082 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2085 * The active_mmu_pages list is the FIFO list, do not move the
2086 * page until it is zapped. kvm_zap_obsolete_pages depends on
2087 * this feature. See the comments in kvm_zap_obsolete_pages().
2089 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2090 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2094 static void mark_unsync(u64 *spte);
2095 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2098 struct rmap_iterator iter;
2100 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2105 static void mark_unsync(u64 *spte)
2107 struct kvm_mmu_page *sp;
2110 sp = page_header(__pa(spte));
2111 index = spte - sp->spt;
2112 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2114 if (sp->unsync_children++)
2116 kvm_mmu_mark_parents_unsync(sp);
2119 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2120 struct kvm_mmu_page *sp)
2125 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
2129 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2130 struct kvm_mmu_page *sp, u64 *spte,
2136 #define KVM_PAGE_ARRAY_NR 16
2138 struct kvm_mmu_pages {
2139 struct mmu_page_and_offset {
2140 struct kvm_mmu_page *sp;
2142 } page[KVM_PAGE_ARRAY_NR];
2146 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2152 for (i=0; i < pvec->nr; i++)
2153 if (pvec->page[i].sp == sp)
2156 pvec->page[pvec->nr].sp = sp;
2157 pvec->page[pvec->nr].idx = idx;
2159 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2162 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2164 --sp->unsync_children;
2165 WARN_ON((int)sp->unsync_children < 0);
2166 __clear_bit(idx, sp->unsync_child_bitmap);
2169 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2170 struct kvm_mmu_pages *pvec)
2172 int i, ret, nr_unsync_leaf = 0;
2174 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2175 struct kvm_mmu_page *child;
2176 u64 ent = sp->spt[i];
2178 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2179 clear_unsync_child_bit(sp, i);
2183 child = page_header(ent & PT64_BASE_ADDR_MASK);
2185 if (child->unsync_children) {
2186 if (mmu_pages_add(pvec, child, i))
2189 ret = __mmu_unsync_walk(child, pvec);
2191 clear_unsync_child_bit(sp, i);
2193 } else if (ret > 0) {
2194 nr_unsync_leaf += ret;
2197 } else if (child->unsync) {
2199 if (mmu_pages_add(pvec, child, i))
2202 clear_unsync_child_bit(sp, i);
2205 return nr_unsync_leaf;
2208 #define INVALID_INDEX (-1)
2210 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2211 struct kvm_mmu_pages *pvec)
2214 if (!sp->unsync_children)
2217 mmu_pages_add(pvec, sp, INVALID_INDEX);
2218 return __mmu_unsync_walk(sp, pvec);
2221 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2223 WARN_ON(!sp->unsync);
2224 trace_kvm_mmu_sync_page(sp);
2226 --kvm->stat.mmu_unsync;
2229 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2230 struct list_head *invalid_list);
2231 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2232 struct list_head *invalid_list);
2235 * NOTE: we should pay more attention on the zapped-obsolete page
2236 * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
2237 * since it has been deleted from active_mmu_pages but still can be found
2240 * for_each_valid_sp() has skipped that kind of pages.
2242 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2243 hlist_for_each_entry(_sp, \
2244 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2245 if (is_obsolete_sp((_kvm), (_sp)) || (_sp)->role.invalid) { \
2248 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2249 for_each_valid_sp(_kvm, _sp, _gfn) \
2250 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2252 /* @sp->gfn should be write-protected at the call site */
2253 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2254 struct list_head *invalid_list)
2256 if (sp->role.cr4_pae != !!is_pae(vcpu)) {
2257 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2261 if (vcpu->arch.mmu.sync_page(vcpu, sp) == 0) {
2262 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2269 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2270 struct list_head *invalid_list,
2271 bool remote_flush, bool local_flush)
2273 if (!list_empty(invalid_list)) {
2274 kvm_mmu_commit_zap_page(vcpu->kvm, invalid_list);
2279 kvm_flush_remote_tlbs(vcpu->kvm);
2280 else if (local_flush)
2281 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2284 #ifdef CONFIG_KVM_MMU_AUDIT
2285 #include "mmu_audit.c"
2287 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2288 static void mmu_audit_disable(void) { }
2291 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2293 return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2296 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2297 struct list_head *invalid_list)
2299 kvm_unlink_unsync_page(vcpu->kvm, sp);
2300 return __kvm_sync_page(vcpu, sp, invalid_list);
2303 /* @gfn should be write-protected at the call site */
2304 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2305 struct list_head *invalid_list)
2307 struct kvm_mmu_page *s;
2310 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2314 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2315 ret |= kvm_sync_page(vcpu, s, invalid_list);
2321 struct mmu_page_path {
2322 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2323 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2326 #define for_each_sp(pvec, sp, parents, i) \
2327 for (i = mmu_pages_first(&pvec, &parents); \
2328 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2329 i = mmu_pages_next(&pvec, &parents, i))
2331 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2332 struct mmu_page_path *parents,
2337 for (n = i+1; n < pvec->nr; n++) {
2338 struct kvm_mmu_page *sp = pvec->page[n].sp;
2339 unsigned idx = pvec->page[n].idx;
2340 int level = sp->role.level;
2342 parents->idx[level-1] = idx;
2343 if (level == PT_PAGE_TABLE_LEVEL)
2346 parents->parent[level-2] = sp;
2352 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2353 struct mmu_page_path *parents)
2355 struct kvm_mmu_page *sp;
2361 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2363 sp = pvec->page[0].sp;
2364 level = sp->role.level;
2365 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2367 parents->parent[level-2] = sp;
2369 /* Also set up a sentinel. Further entries in pvec are all
2370 * children of sp, so this element is never overwritten.
2372 parents->parent[level-1] = NULL;
2373 return mmu_pages_next(pvec, parents, 0);
2376 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2378 struct kvm_mmu_page *sp;
2379 unsigned int level = 0;
2382 unsigned int idx = parents->idx[level];
2383 sp = parents->parent[level];
2387 WARN_ON(idx == INVALID_INDEX);
2388 clear_unsync_child_bit(sp, idx);
2390 } while (!sp->unsync_children);
2393 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2394 struct kvm_mmu_page *parent)
2397 struct kvm_mmu_page *sp;
2398 struct mmu_page_path parents;
2399 struct kvm_mmu_pages pages;
2400 LIST_HEAD(invalid_list);
2403 while (mmu_unsync_walk(parent, &pages)) {
2404 bool protected = false;
2406 for_each_sp(pages, sp, parents, i)
2407 protected |= rmap_write_protect(vcpu, sp->gfn);
2410 kvm_flush_remote_tlbs(vcpu->kvm);
2414 for_each_sp(pages, sp, parents, i) {
2415 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2416 mmu_pages_clear_parents(&parents);
2418 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2419 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2420 cond_resched_lock(&vcpu->kvm->mmu_lock);
2425 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2428 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2430 atomic_set(&sp->write_flooding_count, 0);
2433 static void clear_sp_write_flooding_count(u64 *spte)
2435 struct kvm_mmu_page *sp = page_header(__pa(spte));
2437 __clear_sp_write_flooding_count(sp);
2440 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2447 union kvm_mmu_page_role role;
2449 struct kvm_mmu_page *sp;
2450 bool need_sync = false;
2453 LIST_HEAD(invalid_list);
2455 role = vcpu->arch.mmu.base_role;
2457 role.direct = direct;
2460 role.access = access;
2461 if (!vcpu->arch.mmu.direct_map
2462 && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
2463 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2464 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2465 role.quadrant = quadrant;
2467 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2468 if (sp->gfn != gfn) {
2473 if (!need_sync && sp->unsync)
2476 if (sp->role.word != role.word)
2480 /* The page is good, but __kvm_sync_page might still end
2481 * up zapping it. If so, break in order to rebuild it.
2483 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2486 WARN_ON(!list_empty(&invalid_list));
2487 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2490 if (sp->unsync_children)
2491 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2493 __clear_sp_write_flooding_count(sp);
2494 trace_kvm_mmu_get_page(sp, false);
2498 ++vcpu->kvm->stat.mmu_cache_miss;
2500 sp = kvm_mmu_alloc_page(vcpu, direct);
2504 hlist_add_head(&sp->hash_link,
2505 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2508 * we should do write protection before syncing pages
2509 * otherwise the content of the synced shadow page may
2510 * be inconsistent with guest page table.
2512 account_shadowed(vcpu->kvm, sp);
2513 if (level == PT_PAGE_TABLE_LEVEL &&
2514 rmap_write_protect(vcpu, gfn))
2515 kvm_flush_remote_tlbs(vcpu->kvm);
2517 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2518 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2520 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2521 clear_page(sp->spt);
2522 trace_kvm_mmu_get_page(sp, true);
2524 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2526 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2527 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2531 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2532 struct kvm_vcpu *vcpu, u64 addr)
2534 iterator->addr = addr;
2535 iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
2536 iterator->level = vcpu->arch.mmu.shadow_root_level;
2538 if (iterator->level == PT64_ROOT_4LEVEL &&
2539 vcpu->arch.mmu.root_level < PT64_ROOT_4LEVEL &&
2540 !vcpu->arch.mmu.direct_map)
2543 if (iterator->level == PT32E_ROOT_LEVEL) {
2544 iterator->shadow_addr
2545 = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
2546 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2548 if (!iterator->shadow_addr)
2549 iterator->level = 0;
2553 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2555 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2558 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2559 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2563 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2566 if (is_last_spte(spte, iterator->level)) {
2567 iterator->level = 0;
2571 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2575 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2577 return __shadow_walk_next(iterator, *iterator->sptep);
2580 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2581 struct kvm_mmu_page *sp)
2585 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2587 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2588 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2590 if (sp_ad_disabled(sp))
2591 spte |= shadow_acc_track_value;
2593 spte |= shadow_accessed_mask;
2595 mmu_spte_set(sptep, spte);
2597 mmu_page_add_parent_pte(vcpu, sp, sptep);
2599 if (sp->unsync_children || sp->unsync)
2603 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2604 unsigned direct_access)
2606 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2607 struct kvm_mmu_page *child;
2610 * For the direct sp, if the guest pte's dirty bit
2611 * changed form clean to dirty, it will corrupt the
2612 * sp's access: allow writable in the read-only sp,
2613 * so we should update the spte at this point to get
2614 * a new sp with the correct access.
2616 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2617 if (child->role.access == direct_access)
2620 drop_parent_pte(child, sptep);
2621 kvm_flush_remote_tlbs(vcpu->kvm);
2625 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2629 struct kvm_mmu_page *child;
2632 if (is_shadow_present_pte(pte)) {
2633 if (is_last_spte(pte, sp->role.level)) {
2634 drop_spte(kvm, spte);
2635 if (is_large_pte(pte))
2638 child = page_header(pte & PT64_BASE_ADDR_MASK);
2639 drop_parent_pte(child, spte);
2644 if (is_mmio_spte(pte))
2645 mmu_spte_clear_no_track(spte);
2650 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2651 struct kvm_mmu_page *sp)
2655 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2656 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2659 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2662 struct rmap_iterator iter;
2664 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2665 drop_parent_pte(sp, sptep);
2668 static int mmu_zap_unsync_children(struct kvm *kvm,
2669 struct kvm_mmu_page *parent,
2670 struct list_head *invalid_list)
2673 struct mmu_page_path parents;
2674 struct kvm_mmu_pages pages;
2676 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2679 while (mmu_unsync_walk(parent, &pages)) {
2680 struct kvm_mmu_page *sp;
2682 for_each_sp(pages, sp, parents, i) {
2683 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2684 mmu_pages_clear_parents(&parents);
2692 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2693 struct list_head *invalid_list)
2697 trace_kvm_mmu_prepare_zap_page(sp);
2698 ++kvm->stat.mmu_shadow_zapped;
2699 ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
2700 kvm_mmu_page_unlink_children(kvm, sp);
2701 kvm_mmu_unlink_parents(kvm, sp);
2703 if (!sp->role.invalid && !sp->role.direct)
2704 unaccount_shadowed(kvm, sp);
2707 kvm_unlink_unsync_page(kvm, sp);
2708 if (!sp->root_count) {
2711 list_move(&sp->link, invalid_list);
2712 kvm_mod_used_mmu_pages(kvm, -1);
2714 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2717 * The obsolete pages can not be used on any vcpus.
2718 * See the comments in kvm_mmu_invalidate_zap_all_pages().
2720 if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
2721 kvm_reload_remote_mmus(kvm);
2724 if (sp->lpage_disallowed)
2725 unaccount_huge_nx_page(kvm, sp);
2727 sp->role.invalid = 1;
2731 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2732 struct list_head *invalid_list)
2734 struct kvm_mmu_page *sp, *nsp;
2736 if (list_empty(invalid_list))
2740 * We need to make sure everyone sees our modifications to
2741 * the page tables and see changes to vcpu->mode here. The barrier
2742 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2743 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2745 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2746 * guest mode and/or lockless shadow page table walks.
2748 kvm_flush_remote_tlbs(kvm);
2750 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2751 WARN_ON(!sp->role.invalid || sp->root_count);
2752 kvm_mmu_free_page(sp);
2756 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2757 struct list_head *invalid_list)
2759 struct kvm_mmu_page *sp;
2761 if (list_empty(&kvm->arch.active_mmu_pages))
2764 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2765 struct kvm_mmu_page, link);
2766 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2770 * Changing the number of mmu pages allocated to the vm
2771 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2773 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
2775 LIST_HEAD(invalid_list);
2777 spin_lock(&kvm->mmu_lock);
2779 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2780 /* Need to free some mmu pages to achieve the goal. */
2781 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2782 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2785 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2786 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2789 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2791 spin_unlock(&kvm->mmu_lock);
2794 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2796 struct kvm_mmu_page *sp;
2797 LIST_HEAD(invalid_list);
2800 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2802 spin_lock(&kvm->mmu_lock);
2803 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2804 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2807 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2809 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2810 spin_unlock(&kvm->mmu_lock);
2814 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2816 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2818 trace_kvm_mmu_unsync_page(sp);
2819 ++vcpu->kvm->stat.mmu_unsync;
2822 kvm_mmu_mark_parents_unsync(sp);
2825 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2828 struct kvm_mmu_page *sp;
2830 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2833 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2840 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2841 kvm_unsync_page(vcpu, sp);
2847 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2850 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn));
2855 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2856 unsigned pte_access, int level,
2857 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2858 bool can_unsync, bool host_writable)
2862 struct kvm_mmu_page *sp;
2864 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2867 sp = page_header(__pa(sptep));
2868 if (sp_ad_disabled(sp))
2869 spte |= shadow_acc_track_value;
2872 * For the EPT case, shadow_present_mask is 0 if hardware
2873 * supports exec-only page table entries. In that case,
2874 * ACC_USER_MASK and shadow_user_mask are used to represent
2875 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2877 spte |= shadow_present_mask;
2879 spte |= spte_shadow_accessed_mask(spte);
2881 if (level > PT_PAGE_TABLE_LEVEL && (pte_access & ACC_EXEC_MASK) &&
2882 is_nx_huge_page_enabled()) {
2883 pte_access &= ~ACC_EXEC_MASK;
2886 if (pte_access & ACC_EXEC_MASK)
2887 spte |= shadow_x_mask;
2889 spte |= shadow_nx_mask;
2891 if (pte_access & ACC_USER_MASK)
2892 spte |= shadow_user_mask;
2894 if (level > PT_PAGE_TABLE_LEVEL)
2895 spte |= PT_PAGE_SIZE_MASK;
2897 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2898 kvm_is_mmio_pfn(pfn));
2901 spte |= SPTE_HOST_WRITEABLE;
2903 pte_access &= ~ACC_WRITE_MASK;
2905 if (!kvm_is_mmio_pfn(pfn))
2906 spte |= shadow_me_mask;
2908 spte |= (u64)pfn << PAGE_SHIFT;
2910 if (pte_access & ACC_WRITE_MASK) {
2913 * Other vcpu creates new sp in the window between
2914 * mapping_level() and acquiring mmu-lock. We can
2915 * allow guest to retry the access, the mapping can
2916 * be fixed if guest refault.
2918 if (level > PT_PAGE_TABLE_LEVEL &&
2919 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
2922 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
2925 * Optimization: for pte sync, if spte was writable the hash
2926 * lookup is unnecessary (and expensive). Write protection
2927 * is responsibility of mmu_get_page / kvm_sync_page.
2928 * Same reasoning can be applied to dirty page accounting.
2930 if (!can_unsync && is_writable_pte(*sptep))
2933 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
2934 pgprintk("%s: found shadow page for %llx, marking ro\n",
2937 pte_access &= ~ACC_WRITE_MASK;
2938 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
2942 if (pte_access & ACC_WRITE_MASK) {
2943 kvm_vcpu_mark_page_dirty(vcpu, gfn);
2944 spte |= spte_shadow_dirty_mask(spte);
2948 spte = mark_spte_for_access_track(spte);
2951 if (mmu_spte_update(sptep, spte))
2952 kvm_flush_remote_tlbs(vcpu->kvm);
2957 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
2958 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
2959 bool speculative, bool host_writable)
2961 int was_rmapped = 0;
2963 int ret = RET_PF_RETRY;
2965 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2966 *sptep, write_fault, gfn);
2968 if (is_shadow_present_pte(*sptep)) {
2970 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2971 * the parent of the now unreachable PTE.
2973 if (level > PT_PAGE_TABLE_LEVEL &&
2974 !is_large_pte(*sptep)) {
2975 struct kvm_mmu_page *child;
2978 child = page_header(pte & PT64_BASE_ADDR_MASK);
2979 drop_parent_pte(child, sptep);
2980 kvm_flush_remote_tlbs(vcpu->kvm);
2981 } else if (pfn != spte_to_pfn(*sptep)) {
2982 pgprintk("hfn old %llx new %llx\n",
2983 spte_to_pfn(*sptep), pfn);
2984 drop_spte(vcpu->kvm, sptep);
2985 kvm_flush_remote_tlbs(vcpu->kvm);
2990 if (set_spte(vcpu, sptep, pte_access, level, gfn, pfn, speculative,
2991 true, host_writable)) {
2993 ret = RET_PF_EMULATE;
2994 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2997 if (unlikely(is_mmio_spte(*sptep)))
2998 ret = RET_PF_EMULATE;
3000 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3001 trace_kvm_mmu_set_spte(level, gfn, sptep);
3002 if (!was_rmapped && is_large_pte(*sptep))
3003 ++vcpu->kvm->stat.lpages;
3005 if (is_shadow_present_pte(*sptep)) {
3007 rmap_count = rmap_add(vcpu, sptep, gfn);
3008 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3009 rmap_recycle(vcpu, sptep, gfn);
3016 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3019 struct kvm_memory_slot *slot;
3021 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3023 return KVM_PFN_ERR_FAULT;
3025 return gfn_to_pfn_memslot_atomic(slot, gfn);
3028 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3029 struct kvm_mmu_page *sp,
3030 u64 *start, u64 *end)
3032 struct page *pages[PTE_PREFETCH_NUM];
3033 struct kvm_memory_slot *slot;
3034 unsigned access = sp->role.access;
3038 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3039 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3043 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3047 for (i = 0; i < ret; i++, gfn++, start++) {
3048 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3049 page_to_pfn(pages[i]), true, true);
3056 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3057 struct kvm_mmu_page *sp, u64 *sptep)
3059 u64 *spte, *start = NULL;
3062 WARN_ON(!sp->role.direct);
3064 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3067 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3068 if (is_shadow_present_pte(*spte) || spte == sptep) {
3071 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3079 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3081 struct kvm_mmu_page *sp;
3083 sp = page_header(__pa(sptep));
3086 * Without accessed bits, there's no way to distinguish between
3087 * actually accessed translations and prefetched, so disable pte
3088 * prefetch if accessed bits aren't available.
3090 if (sp_ad_disabled(sp))
3093 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3096 __direct_pte_prefetch(vcpu, sp, sptep);
3099 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3100 gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3102 int level = *levelp;
3103 u64 spte = *it.sptep;
3105 if (it.level == level && level > PT_PAGE_TABLE_LEVEL &&
3106 is_nx_huge_page_enabled() &&
3107 is_shadow_present_pte(spte) &&
3108 !is_large_pte(spte)) {
3110 * A small SPTE exists for this pfn, but FNAME(fetch)
3111 * and __direct_map would like to create a large PTE
3112 * instead: just force them to go down another level,
3113 * patching back for them into pfn the next 9 bits of
3116 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3117 *pfnp |= gfn & page_mask;
3122 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3123 int map_writable, int level, kvm_pfn_t pfn,
3124 bool prefault, bool lpage_disallowed)
3126 struct kvm_shadow_walk_iterator it;
3127 struct kvm_mmu_page *sp;
3129 gfn_t gfn = gpa >> PAGE_SHIFT;
3130 gfn_t base_gfn = gfn;
3132 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3133 return RET_PF_RETRY;
3135 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3136 for_each_shadow_entry(vcpu, gpa, it) {
3138 * We cannot overwrite existing page tables with an NX
3139 * large page, as the leaf could be executable.
3141 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3143 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3144 if (it.level == level)
3147 drop_large_spte(vcpu, it.sptep);
3148 if (!is_shadow_present_pte(*it.sptep)) {
3149 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3150 it.level - 1, true, ACC_ALL);
3152 link_shadow_page(vcpu, it.sptep, sp);
3153 if (lpage_disallowed)
3154 account_huge_nx_page(vcpu->kvm, sp);
3158 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3159 write, level, base_gfn, pfn, prefault,
3161 direct_pte_prefetch(vcpu, it.sptep);
3162 ++vcpu->stat.pf_fixed;
3166 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3170 info.si_signo = SIGBUS;
3172 info.si_code = BUS_MCEERR_AR;
3173 info.si_addr = (void __user *)address;
3174 info.si_addr_lsb = PAGE_SHIFT;
3176 send_sig_info(SIGBUS, &info, tsk);
3179 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3182 * Do not cache the mmio info caused by writing the readonly gfn
3183 * into the spte otherwise read access on readonly gfn also can
3184 * caused mmio page fault and treat it as mmio access.
3186 if (pfn == KVM_PFN_ERR_RO_FAULT)
3187 return RET_PF_EMULATE;
3189 if (pfn == KVM_PFN_ERR_HWPOISON) {
3190 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3191 return RET_PF_RETRY;
3197 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3198 gfn_t gfn, kvm_pfn_t *pfnp,
3201 kvm_pfn_t pfn = *pfnp;
3202 int level = *levelp;
3205 * Check if it's a transparent hugepage. If this would be an
3206 * hugetlbfs page, level wouldn't be set to
3207 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3210 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3211 !kvm_is_zone_device_pfn(pfn) && level == PT_PAGE_TABLE_LEVEL &&
3212 PageTransCompoundMap(pfn_to_page(pfn)) &&
3213 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3216 * mmu_notifier_retry was successful and we hold the
3217 * mmu_lock here, so the pmd can't become splitting
3218 * from under us, and in turn
3219 * __split_huge_page_refcount() can't run from under
3220 * us and we can safely transfer the refcount from
3221 * PG_tail to PG_head as we switch the pfn to tail to
3224 *levelp = level = PT_DIRECTORY_LEVEL;
3225 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3226 VM_BUG_ON((gfn & mask) != (pfn & mask));
3228 kvm_release_pfn_clean(pfn);
3236 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3237 kvm_pfn_t pfn, unsigned access, int *ret_val)
3239 /* The pfn is invalid, report the error! */
3240 if (unlikely(is_error_pfn(pfn))) {
3241 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3245 if (unlikely(is_noslot_pfn(pfn)))
3246 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
3251 static bool page_fault_can_be_fast(u32 error_code)
3254 * Do not fix the mmio spte with invalid generation number which
3255 * need to be updated by slow page fault path.
3257 if (unlikely(error_code & PFERR_RSVD_MASK))
3260 /* See if the page fault is due to an NX violation */
3261 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3262 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3266 * #PF can be fast if:
3267 * 1. The shadow page table entry is not present, which could mean that
3268 * the fault is potentially caused by access tracking (if enabled).
3269 * 2. The shadow page table entry is present and the fault
3270 * is caused by write-protect, that means we just need change the W
3271 * bit of the spte which can be done out of mmu-lock.
3273 * However, if access tracking is disabled we know that a non-present
3274 * page must be a genuine page fault where we have to create a new SPTE.
3275 * So, if access tracking is disabled, we return true only for write
3276 * accesses to a present page.
3279 return shadow_acc_track_mask != 0 ||
3280 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3281 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3285 * Returns true if the SPTE was fixed successfully. Otherwise,
3286 * someone else modified the SPTE from its original value.
3289 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3290 u64 *sptep, u64 old_spte, u64 new_spte)
3294 WARN_ON(!sp->role.direct);
3297 * Theoretically we could also set dirty bit (and flush TLB) here in
3298 * order to eliminate unnecessary PML logging. See comments in
3299 * set_spte. But fast_page_fault is very unlikely to happen with PML
3300 * enabled, so we do not do this. This might result in the same GPA
3301 * to be logged in PML buffer again when the write really happens, and
3302 * eventually to be called by mark_page_dirty twice. But it's also no
3303 * harm. This also avoids the TLB flush needed after setting dirty bit
3304 * so non-PML cases won't be impacted.
3306 * Compare with set_spte where instead shadow_dirty_mask is set.
3308 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3311 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3313 * The gfn of direct spte is stable since it is
3314 * calculated by sp->gfn.
3316 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3317 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3323 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3325 if (fault_err_code & PFERR_FETCH_MASK)
3326 return is_executable_pte(spte);
3328 if (fault_err_code & PFERR_WRITE_MASK)
3329 return is_writable_pte(spte);
3331 /* Fault was on Read access */
3332 return spte & PT_PRESENT_MASK;
3337 * - true: let the vcpu to access on the same address again.
3338 * - false: let the real page fault path to fix it.
3340 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3343 struct kvm_shadow_walk_iterator iterator;
3344 struct kvm_mmu_page *sp;
3345 bool fault_handled = false;
3347 uint retry_count = 0;
3349 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3352 if (!page_fault_can_be_fast(error_code))
3355 walk_shadow_page_lockless_begin(vcpu);
3360 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3361 if (!is_shadow_present_pte(spte) ||
3362 iterator.level < level)
3365 sp = page_header(__pa(iterator.sptep));
3366 if (!is_last_spte(spte, sp->role.level))
3370 * Check whether the memory access that caused the fault would
3371 * still cause it if it were to be performed right now. If not,
3372 * then this is a spurious fault caused by TLB lazily flushed,
3373 * or some other CPU has already fixed the PTE after the
3374 * current CPU took the fault.
3376 * Need not check the access of upper level table entries since
3377 * they are always ACC_ALL.
3379 if (is_access_allowed(error_code, spte)) {
3380 fault_handled = true;
3386 if (is_access_track_spte(spte))
3387 new_spte = restore_acc_track_spte(new_spte);
3390 * Currently, to simplify the code, write-protection can
3391 * be removed in the fast path only if the SPTE was
3392 * write-protected for dirty-logging or access tracking.
3394 if ((error_code & PFERR_WRITE_MASK) &&
3395 spte_can_locklessly_be_made_writable(spte))
3397 new_spte |= PT_WRITABLE_MASK;
3400 * Do not fix write-permission on the large spte. Since
3401 * we only dirty the first page into the dirty-bitmap in
3402 * fast_pf_fix_direct_spte(), other pages are missed
3403 * if its slot has dirty logging enabled.
3405 * Instead, we let the slow page fault path create a
3406 * normal spte to fix the access.
3408 * See the comments in kvm_arch_commit_memory_region().
3410 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3414 /* Verify that the fault can be handled in the fast path */
3415 if (new_spte == spte ||
3416 !is_access_allowed(error_code, new_spte))
3420 * Currently, fast page fault only works for direct mapping
3421 * since the gfn is not stable for indirect shadow page. See
3422 * Documentation/virtual/kvm/locking.txt to get more detail.
3424 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3425 iterator.sptep, spte,
3430 if (++retry_count > 4) {
3431 printk_once(KERN_WARNING
3432 "kvm: Fast #PF retrying more than 4 times.\n");
3438 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3439 spte, fault_handled);
3440 walk_shadow_page_lockless_end(vcpu);
3442 return fault_handled;
3445 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3446 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3447 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3449 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3450 gfn_t gfn, bool prefault)
3454 bool force_pt_level;
3456 unsigned long mmu_seq;
3457 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3458 bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
3459 is_nx_huge_page_enabled();
3461 force_pt_level = lpage_disallowed;
3462 level = mapping_level(vcpu, gfn, &force_pt_level);
3463 if (likely(!force_pt_level)) {
3465 * This path builds a PAE pagetable - so we can map
3466 * 2mb pages at maximum. Therefore check if the level
3467 * is larger than that.
3469 if (level > PT_DIRECTORY_LEVEL)
3470 level = PT_DIRECTORY_LEVEL;
3472 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3475 if (fast_page_fault(vcpu, v, level, error_code))
3476 return RET_PF_RETRY;
3478 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3481 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3482 return RET_PF_RETRY;
3484 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3488 spin_lock(&vcpu->kvm->mmu_lock);
3489 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3491 if (make_mmu_pages_available(vcpu) < 0)
3493 if (likely(!force_pt_level))
3494 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3495 r = __direct_map(vcpu, v, write, map_writable, level, pfn,
3498 spin_unlock(&vcpu->kvm->mmu_lock);
3499 kvm_release_pfn_clean(pfn);
3504 static void mmu_free_roots(struct kvm_vcpu *vcpu)
3507 struct kvm_mmu_page *sp;
3508 LIST_HEAD(invalid_list);
3510 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3513 if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL &&
3514 (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL ||
3515 vcpu->arch.mmu.direct_map)) {
3516 hpa_t root = vcpu->arch.mmu.root_hpa;
3518 spin_lock(&vcpu->kvm->mmu_lock);
3519 sp = page_header(root);
3521 if (!sp->root_count && sp->role.invalid) {
3522 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
3523 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3525 spin_unlock(&vcpu->kvm->mmu_lock);
3526 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3530 spin_lock(&vcpu->kvm->mmu_lock);
3531 for (i = 0; i < 4; ++i) {
3532 hpa_t root = vcpu->arch.mmu.pae_root[i];
3535 root &= PT64_BASE_ADDR_MASK;
3536 sp = page_header(root);
3538 if (!sp->root_count && sp->role.invalid)
3539 kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
3542 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
3544 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3545 spin_unlock(&vcpu->kvm->mmu_lock);
3546 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3549 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3553 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3554 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3561 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3563 struct kvm_mmu_page *sp;
3566 if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL) {
3567 spin_lock(&vcpu->kvm->mmu_lock);
3568 if(make_mmu_pages_available(vcpu) < 0) {
3569 spin_unlock(&vcpu->kvm->mmu_lock);
3572 sp = kvm_mmu_get_page(vcpu, 0, 0,
3573 vcpu->arch.mmu.shadow_root_level, 1, ACC_ALL);
3575 spin_unlock(&vcpu->kvm->mmu_lock);
3576 vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3577 } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3578 for (i = 0; i < 4; ++i) {
3579 hpa_t root = vcpu->arch.mmu.pae_root[i];
3581 MMU_WARN_ON(VALID_PAGE(root));
3582 spin_lock(&vcpu->kvm->mmu_lock);
3583 if (make_mmu_pages_available(vcpu) < 0) {
3584 spin_unlock(&vcpu->kvm->mmu_lock);
3587 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3588 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3589 root = __pa(sp->spt);
3591 spin_unlock(&vcpu->kvm->mmu_lock);
3592 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
3594 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3601 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3603 struct kvm_mmu_page *sp;
3608 root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
3610 if (mmu_check_root(vcpu, root_gfn))
3614 * Do we shadow a long mode page table? If so we need to
3615 * write-protect the guests page table root.
3617 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3618 hpa_t root = vcpu->arch.mmu.root_hpa;
3620 MMU_WARN_ON(VALID_PAGE(root));
3622 spin_lock(&vcpu->kvm->mmu_lock);
3623 if (make_mmu_pages_available(vcpu) < 0) {
3624 spin_unlock(&vcpu->kvm->mmu_lock);
3627 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3628 vcpu->arch.mmu.shadow_root_level, 0, ACC_ALL);
3629 root = __pa(sp->spt);
3631 spin_unlock(&vcpu->kvm->mmu_lock);
3632 vcpu->arch.mmu.root_hpa = root;
3637 * We shadow a 32 bit page table. This may be a legacy 2-level
3638 * or a PAE 3-level page table. In either case we need to be aware that
3639 * the shadow page table may be a PAE or a long mode page table.
3641 pm_mask = PT_PRESENT_MASK;
3642 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL)
3643 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3645 for (i = 0; i < 4; ++i) {
3646 hpa_t root = vcpu->arch.mmu.pae_root[i];
3648 MMU_WARN_ON(VALID_PAGE(root));
3649 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
3650 pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
3651 if (!(pdptr & PT_PRESENT_MASK)) {
3652 vcpu->arch.mmu.pae_root[i] = 0;
3655 root_gfn = pdptr >> PAGE_SHIFT;
3656 if (mmu_check_root(vcpu, root_gfn))
3659 spin_lock(&vcpu->kvm->mmu_lock);
3660 if (make_mmu_pages_available(vcpu) < 0) {
3661 spin_unlock(&vcpu->kvm->mmu_lock);
3664 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3666 root = __pa(sp->spt);
3668 spin_unlock(&vcpu->kvm->mmu_lock);
3670 vcpu->arch.mmu.pae_root[i] = root | pm_mask;
3672 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3675 * If we shadow a 32 bit page table with a long mode page
3676 * table we enter this path.
3678 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL) {
3679 if (vcpu->arch.mmu.lm_root == NULL) {
3681 * The additional page necessary for this is only
3682 * allocated on demand.
3687 lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3688 if (lm_root == NULL)
3691 lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3693 vcpu->arch.mmu.lm_root = lm_root;
3696 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3702 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3704 if (vcpu->arch.mmu.direct_map)
3705 return mmu_alloc_direct_roots(vcpu);
3707 return mmu_alloc_shadow_roots(vcpu);
3710 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
3713 struct kvm_mmu_page *sp;
3715 if (vcpu->arch.mmu.direct_map)
3718 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3721 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3722 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3723 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3724 hpa_t root = vcpu->arch.mmu.root_hpa;
3725 sp = page_header(root);
3726 mmu_sync_children(vcpu, sp);
3727 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3730 for (i = 0; i < 4; ++i) {
3731 hpa_t root = vcpu->arch.mmu.pae_root[i];
3733 if (root && VALID_PAGE(root)) {
3734 root &= PT64_BASE_ADDR_MASK;
3735 sp = page_header(root);
3736 mmu_sync_children(vcpu, sp);
3739 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3742 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3744 spin_lock(&vcpu->kvm->mmu_lock);
3745 mmu_sync_roots(vcpu);
3746 spin_unlock(&vcpu->kvm->mmu_lock);
3748 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3750 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3751 u32 access, struct x86_exception *exception)
3754 exception->error_code = 0;
3758 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3760 struct x86_exception *exception)
3763 exception->error_code = 0;
3764 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3768 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3770 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3772 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3773 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3776 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3778 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3781 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3783 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3786 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3789 * A nested guest cannot use the MMIO cache if it is using nested
3790 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3792 if (mmu_is_nested(vcpu))
3796 return vcpu_match_mmio_gpa(vcpu, addr);
3798 return vcpu_match_mmio_gva(vcpu, addr);
3801 /* return true if reserved bit is detected on spte. */
3803 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3805 struct kvm_shadow_walk_iterator iterator;
3806 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3808 bool reserved = false;
3810 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3813 walk_shadow_page_lockless_begin(vcpu);
3815 for (shadow_walk_init(&iterator, vcpu, addr),
3816 leaf = root = iterator.level;
3817 shadow_walk_okay(&iterator);
3818 __shadow_walk_next(&iterator, spte)) {
3819 spte = mmu_spte_get_lockless(iterator.sptep);
3821 sptes[leaf - 1] = spte;
3824 if (!is_shadow_present_pte(spte))
3827 reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
3831 walk_shadow_page_lockless_end(vcpu);
3834 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3836 while (root > leaf) {
3837 pr_err("------ spte 0x%llx level %d.\n",
3838 sptes[root - 1], root);
3847 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3852 if (mmio_info_in_cache(vcpu, addr, direct))
3853 return RET_PF_EMULATE;
3855 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3856 if (WARN_ON(reserved))
3859 if (is_mmio_spte(spte)) {
3860 gfn_t gfn = get_mmio_spte_gfn(spte);
3861 unsigned access = get_mmio_spte_access(spte);
3863 if (!check_mmio_spte(vcpu, spte))
3864 return RET_PF_INVALID;
3869 trace_handle_mmio_page_fault(addr, gfn, access);
3870 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3871 return RET_PF_EMULATE;
3875 * If the page table is zapped by other cpus, let CPU fault again on
3878 return RET_PF_RETRY;
3880 EXPORT_SYMBOL_GPL(handle_mmio_page_fault);
3882 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3883 u32 error_code, gfn_t gfn)
3885 if (unlikely(error_code & PFERR_RSVD_MASK))
3888 if (!(error_code & PFERR_PRESENT_MASK) ||
3889 !(error_code & PFERR_WRITE_MASK))
3893 * guest is writing the page which is write tracked which can
3894 * not be fixed by page fault handler.
3896 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3902 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3904 struct kvm_shadow_walk_iterator iterator;
3907 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3910 walk_shadow_page_lockless_begin(vcpu);
3911 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3912 clear_sp_write_flooding_count(iterator.sptep);
3913 if (!is_shadow_present_pte(spte))
3916 walk_shadow_page_lockless_end(vcpu);
3919 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
3920 u32 error_code, bool prefault)
3922 gfn_t gfn = gva >> PAGE_SHIFT;
3925 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
3927 if (page_fault_handle_page_track(vcpu, error_code, gfn))
3928 return RET_PF_EMULATE;
3930 r = mmu_topup_memory_caches(vcpu);
3934 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3937 return nonpaging_map(vcpu, gva & PAGE_MASK,
3938 error_code, gfn, prefault);
3941 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
3943 struct kvm_arch_async_pf arch;
3945 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3947 arch.direct_map = vcpu->arch.mmu.direct_map;
3948 arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
3950 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3953 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
3955 if (unlikely(!lapic_in_kernel(vcpu) ||
3956 kvm_event_needs_reinjection(vcpu) ||
3957 vcpu->arch.exception.pending))
3960 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
3963 return kvm_x86_ops->interrupt_allowed(vcpu);
3966 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3967 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
3969 struct kvm_memory_slot *slot;
3972 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3974 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
3976 return false; /* *pfn has correct page already */
3978 if (!prefault && kvm_can_do_async_pf(vcpu)) {
3979 trace_kvm_try_async_get_page(gva, gfn);
3980 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
3981 trace_kvm_async_pf_doublefault(gva, gfn);
3982 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3984 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
3988 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
3992 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
3993 u64 fault_address, char *insn, int insn_len,
3994 bool need_unprotect)
3998 vcpu->arch.l1tf_flush_l1d = true;
3999 switch (vcpu->arch.apf.host_apf_reason) {
4001 trace_kvm_page_fault(fault_address, error_code);
4003 if (need_unprotect && kvm_event_needs_reinjection(vcpu))
4004 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4005 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4008 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4009 vcpu->arch.apf.host_apf_reason = 0;
4010 local_irq_disable();
4011 kvm_async_pf_task_wait(fault_address, 0);
4014 case KVM_PV_REASON_PAGE_READY:
4015 vcpu->arch.apf.host_apf_reason = 0;
4016 local_irq_disable();
4017 kvm_async_pf_task_wake(fault_address);
4023 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4026 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4028 int page_num = KVM_PAGES_PER_HPAGE(level);
4030 gfn &= ~(page_num - 1);
4032 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4035 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4041 bool force_pt_level;
4042 gfn_t gfn = gpa >> PAGE_SHIFT;
4043 unsigned long mmu_seq;
4044 int write = error_code & PFERR_WRITE_MASK;
4046 bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
4047 is_nx_huge_page_enabled();
4049 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
4051 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4052 return RET_PF_EMULATE;
4054 r = mmu_topup_memory_caches(vcpu);
4060 !check_hugepage_cache_consistency(vcpu, gfn, PT_DIRECTORY_LEVEL);
4061 level = mapping_level(vcpu, gfn, &force_pt_level);
4062 if (likely(!force_pt_level)) {
4063 if (level > PT_DIRECTORY_LEVEL &&
4064 !check_hugepage_cache_consistency(vcpu, gfn, level))
4065 level = PT_DIRECTORY_LEVEL;
4066 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4069 if (fast_page_fault(vcpu, gpa, level, error_code))
4070 return RET_PF_RETRY;
4072 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4075 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4076 return RET_PF_RETRY;
4078 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4082 spin_lock(&vcpu->kvm->mmu_lock);
4083 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4085 if (make_mmu_pages_available(vcpu) < 0)
4087 if (likely(!force_pt_level))
4088 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4089 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
4090 prefault, lpage_disallowed);
4092 spin_unlock(&vcpu->kvm->mmu_lock);
4093 kvm_release_pfn_clean(pfn);
4097 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4098 struct kvm_mmu *context)
4100 context->page_fault = nonpaging_page_fault;
4101 context->gva_to_gpa = nonpaging_gva_to_gpa;
4102 context->sync_page = nonpaging_sync_page;
4103 context->invlpg = nonpaging_invlpg;
4104 context->update_pte = nonpaging_update_pte;
4105 context->root_level = 0;
4106 context->shadow_root_level = PT32E_ROOT_LEVEL;
4107 context->root_hpa = INVALID_PAGE;
4108 context->direct_map = true;
4109 context->nx = false;
4112 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu)
4114 mmu_free_roots(vcpu);
4117 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4119 return kvm_read_cr3(vcpu);
4122 static void inject_page_fault(struct kvm_vcpu *vcpu,
4123 struct x86_exception *fault)
4125 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
4128 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4129 unsigned access, int *nr_present)
4131 if (unlikely(is_mmio_spte(*sptep))) {
4132 if (gfn != get_mmio_spte_gfn(*sptep)) {
4133 mmu_spte_clear_no_track(sptep);
4138 mark_mmio_spte(vcpu, sptep, gfn, access);
4145 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4146 unsigned level, unsigned gpte)
4149 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4150 * If it is clear, there are no large pages at this level, so clear
4151 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4153 gpte &= level - mmu->last_nonleaf_level;
4156 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4157 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4158 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4160 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4162 return gpte & PT_PAGE_SIZE_MASK;
4165 #define PTTYPE_EPT 18 /* arbitrary */
4166 #define PTTYPE PTTYPE_EPT
4167 #include "paging_tmpl.h"
4171 #include "paging_tmpl.h"
4175 #include "paging_tmpl.h"
4179 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4180 struct rsvd_bits_validate *rsvd_check,
4181 int maxphyaddr, int level, bool nx, bool gbpages,
4184 u64 exb_bit_rsvd = 0;
4185 u64 gbpages_bit_rsvd = 0;
4186 u64 nonleaf_bit8_rsvd = 0;
4188 rsvd_check->bad_mt_xwr = 0;
4191 exb_bit_rsvd = rsvd_bits(63, 63);
4193 gbpages_bit_rsvd = rsvd_bits(7, 7);
4196 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4197 * leaf entries) on AMD CPUs only.
4200 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4203 case PT32_ROOT_LEVEL:
4204 /* no rsvd bits for 2 level 4K page table entries */
4205 rsvd_check->rsvd_bits_mask[0][1] = 0;
4206 rsvd_check->rsvd_bits_mask[0][0] = 0;
4207 rsvd_check->rsvd_bits_mask[1][0] =
4208 rsvd_check->rsvd_bits_mask[0][0];
4211 rsvd_check->rsvd_bits_mask[1][1] = 0;
4215 if (is_cpuid_PSE36())
4216 /* 36bits PSE 4MB page */
4217 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4219 /* 32 bits PSE 4MB page */
4220 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4222 case PT32E_ROOT_LEVEL:
4223 rsvd_check->rsvd_bits_mask[0][2] =
4224 rsvd_bits(maxphyaddr, 63) |
4225 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4226 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4227 rsvd_bits(maxphyaddr, 62); /* PDE */
4228 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4229 rsvd_bits(maxphyaddr, 62); /* PTE */
4230 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4231 rsvd_bits(maxphyaddr, 62) |
4232 rsvd_bits(13, 20); /* large page */
4233 rsvd_check->rsvd_bits_mask[1][0] =
4234 rsvd_check->rsvd_bits_mask[0][0];
4236 case PT64_ROOT_5LEVEL:
4237 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4238 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4239 rsvd_bits(maxphyaddr, 51);
4240 rsvd_check->rsvd_bits_mask[1][4] =
4241 rsvd_check->rsvd_bits_mask[0][4];
4242 case PT64_ROOT_4LEVEL:
4243 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4244 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4245 rsvd_bits(maxphyaddr, 51);
4246 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4248 rsvd_bits(maxphyaddr, 51);
4249 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4250 rsvd_bits(maxphyaddr, 51);
4251 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4252 rsvd_bits(maxphyaddr, 51);
4253 rsvd_check->rsvd_bits_mask[1][3] =
4254 rsvd_check->rsvd_bits_mask[0][3];
4255 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4256 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4258 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4259 rsvd_bits(maxphyaddr, 51) |
4260 rsvd_bits(13, 20); /* large page */
4261 rsvd_check->rsvd_bits_mask[1][0] =
4262 rsvd_check->rsvd_bits_mask[0][0];
4267 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4268 struct kvm_mmu *context)
4270 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4271 cpuid_maxphyaddr(vcpu), context->root_level,
4273 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4274 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4278 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4279 int maxphyaddr, bool execonly)
4283 rsvd_check->rsvd_bits_mask[0][4] =
4284 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4285 rsvd_check->rsvd_bits_mask[0][3] =
4286 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4287 rsvd_check->rsvd_bits_mask[0][2] =
4288 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4289 rsvd_check->rsvd_bits_mask[0][1] =
4290 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4291 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4294 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4295 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4296 rsvd_check->rsvd_bits_mask[1][2] =
4297 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4298 rsvd_check->rsvd_bits_mask[1][1] =
4299 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4300 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4302 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4303 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4304 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4305 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4306 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4308 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4309 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4311 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4314 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4315 struct kvm_mmu *context, bool execonly)
4317 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4318 cpuid_maxphyaddr(vcpu), execonly);
4322 * the page table on host is the shadow page table for the page
4323 * table in guest or amd nested guest, its mmu features completely
4324 * follow the features in guest.
4327 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4330 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
4331 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
4332 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
4333 * The iTLB multi-hit workaround can be toggled at any time, so assume
4334 * NX can be used by any non-nested shadow MMU to avoid having to reset
4335 * MMU contexts. Note, KVM forces EFER.NX=1 when TDP is disabled.
4337 bool uses_nx = context->nx || !tdp_enabled ||
4338 context->base_role.smep_andnot_wp;
4339 struct rsvd_bits_validate *shadow_zero_check;
4343 * Passing "true" to the last argument is okay; it adds a check
4344 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4346 shadow_zero_check = &context->shadow_zero_check;
4347 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4349 context->shadow_root_level, uses_nx,
4350 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4351 is_pse(vcpu), true);
4353 if (!shadow_me_mask)
4356 for (i = context->shadow_root_level; --i >= 0;) {
4357 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4358 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4362 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4364 static inline bool boot_cpu_is_amd(void)
4366 WARN_ON_ONCE(!tdp_enabled);
4367 return shadow_x_mask == 0;
4371 * the direct page table on host, use as much mmu features as
4372 * possible, however, kvm currently does not do execution-protection.
4375 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4376 struct kvm_mmu *context)
4378 struct rsvd_bits_validate *shadow_zero_check;
4381 shadow_zero_check = &context->shadow_zero_check;
4383 if (boot_cpu_is_amd())
4384 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4386 context->shadow_root_level, false,
4387 boot_cpu_has(X86_FEATURE_GBPAGES),
4390 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4394 if (!shadow_me_mask)
4397 for (i = context->shadow_root_level; --i >= 0;) {
4398 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4399 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4404 * as the comments in reset_shadow_zero_bits_mask() except it
4405 * is the shadow page table for intel nested guest.
4408 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4409 struct kvm_mmu *context, bool execonly)
4411 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4412 shadow_phys_bits, execonly);
4415 #define BYTE_MASK(access) \
4416 ((1 & (access) ? 2 : 0) | \
4417 (2 & (access) ? 4 : 0) | \
4418 (3 & (access) ? 8 : 0) | \
4419 (4 & (access) ? 16 : 0) | \
4420 (5 & (access) ? 32 : 0) | \
4421 (6 & (access) ? 64 : 0) | \
4422 (7 & (access) ? 128 : 0))
4425 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4426 struct kvm_mmu *mmu, bool ept)
4430 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4431 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4432 const u8 u = BYTE_MASK(ACC_USER_MASK);
4434 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4435 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4436 bool cr0_wp = is_write_protection(vcpu);
4438 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4439 unsigned pfec = byte << 1;
4442 * Each "*f" variable has a 1 bit for each UWX value
4443 * that causes a fault with the given PFEC.
4446 /* Faults from writes to non-writable pages */
4447 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4448 /* Faults from user mode accesses to supervisor pages */
4449 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4450 /* Faults from fetches of non-executable pages*/
4451 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4452 /* Faults from kernel mode fetches of user pages */
4454 /* Faults from kernel mode accesses of user pages */
4458 /* Faults from kernel mode accesses to user pages */
4459 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4461 /* Not really needed: !nx will cause pte.nx to fault */
4465 /* Allow supervisor writes if !cr0.wp */
4467 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4469 /* Disallow supervisor fetches of user code if cr4.smep */
4471 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4474 * SMAP:kernel-mode data accesses from user-mode
4475 * mappings should fault. A fault is considered
4476 * as a SMAP violation if all of the following
4477 * conditions are ture:
4478 * - X86_CR4_SMAP is set in CR4
4479 * - A user page is accessed
4480 * - The access is not a fetch
4481 * - Page fault in kernel mode
4482 * - if CPL = 3 or X86_EFLAGS_AC is clear
4484 * Here, we cover the first three conditions.
4485 * The fourth is computed dynamically in permission_fault();
4486 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4487 * *not* subject to SMAP restrictions.
4490 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4493 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4498 * PKU is an additional mechanism by which the paging controls access to
4499 * user-mode addresses based on the value in the PKRU register. Protection
4500 * key violations are reported through a bit in the page fault error code.
4501 * Unlike other bits of the error code, the PK bit is not known at the
4502 * call site of e.g. gva_to_gpa; it must be computed directly in
4503 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4504 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4506 * In particular the following conditions come from the error code, the
4507 * page tables and the machine state:
4508 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4509 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4510 * - PK is always zero if U=0 in the page tables
4511 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4513 * The PKRU bitmask caches the result of these four conditions. The error
4514 * code (minus the P bit) and the page table's U bit form an index into the
4515 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4516 * with the two bits of the PKRU register corresponding to the protection key.
4517 * For the first three conditions above the bits will be 00, thus masking
4518 * away both AD and WD. For all reads or if the last condition holds, WD
4519 * only will be masked away.
4521 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4532 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4533 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4538 wp = is_write_protection(vcpu);
4540 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4541 unsigned pfec, pkey_bits;
4542 bool check_pkey, check_write, ff, uf, wf, pte_user;
4545 ff = pfec & PFERR_FETCH_MASK;
4546 uf = pfec & PFERR_USER_MASK;
4547 wf = pfec & PFERR_WRITE_MASK;
4549 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4550 pte_user = pfec & PFERR_RSVD_MASK;
4553 * Only need to check the access which is not an
4554 * instruction fetch and is to a user page.
4556 check_pkey = (!ff && pte_user);
4558 * write access is controlled by PKRU if it is a
4559 * user access or CR0.WP = 1.
4561 check_write = check_pkey && wf && (uf || wp);
4563 /* PKRU.AD stops both read and write access. */
4564 pkey_bits = !!check_pkey;
4565 /* PKRU.WD stops write access. */
4566 pkey_bits |= (!!check_write) << 1;
4568 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4572 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4574 unsigned root_level = mmu->root_level;
4576 mmu->last_nonleaf_level = root_level;
4577 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4578 mmu->last_nonleaf_level++;
4581 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4582 struct kvm_mmu *context,
4585 context->nx = is_nx(vcpu);
4586 context->root_level = level;
4588 reset_rsvds_bits_mask(vcpu, context);
4589 update_permission_bitmask(vcpu, context, false);
4590 update_pkru_bitmask(vcpu, context, false);
4591 update_last_nonleaf_level(vcpu, context);
4593 MMU_WARN_ON(!is_pae(vcpu));
4594 context->page_fault = paging64_page_fault;
4595 context->gva_to_gpa = paging64_gva_to_gpa;
4596 context->sync_page = paging64_sync_page;
4597 context->invlpg = paging64_invlpg;
4598 context->update_pte = paging64_update_pte;
4599 context->shadow_root_level = level;
4600 context->root_hpa = INVALID_PAGE;
4601 context->direct_map = false;
4604 static void paging64_init_context(struct kvm_vcpu *vcpu,
4605 struct kvm_mmu *context)
4607 int root_level = is_la57_mode(vcpu) ?
4608 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4610 paging64_init_context_common(vcpu, context, root_level);
4613 static void paging32_init_context(struct kvm_vcpu *vcpu,
4614 struct kvm_mmu *context)
4616 context->nx = false;
4617 context->root_level = PT32_ROOT_LEVEL;
4619 reset_rsvds_bits_mask(vcpu, context);
4620 update_permission_bitmask(vcpu, context, false);
4621 update_pkru_bitmask(vcpu, context, false);
4622 update_last_nonleaf_level(vcpu, context);
4624 context->page_fault = paging32_page_fault;
4625 context->gva_to_gpa = paging32_gva_to_gpa;
4626 context->sync_page = paging32_sync_page;
4627 context->invlpg = paging32_invlpg;
4628 context->update_pte = paging32_update_pte;
4629 context->shadow_root_level = PT32E_ROOT_LEVEL;
4630 context->root_hpa = INVALID_PAGE;
4631 context->direct_map = false;
4634 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4635 struct kvm_mmu *context)
4637 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4640 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4642 struct kvm_mmu *context = &vcpu->arch.mmu;
4644 context->base_role.word = 0;
4645 context->base_role.smm = is_smm(vcpu);
4646 context->base_role.ad_disabled = (shadow_accessed_mask == 0);
4647 context->page_fault = tdp_page_fault;
4648 context->sync_page = nonpaging_sync_page;
4649 context->invlpg = nonpaging_invlpg;
4650 context->update_pte = nonpaging_update_pte;
4651 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4652 context->root_hpa = INVALID_PAGE;
4653 context->direct_map = true;
4654 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4655 context->get_cr3 = get_cr3;
4656 context->get_pdptr = kvm_pdptr_read;
4657 context->inject_page_fault = kvm_inject_page_fault;
4659 if (!is_paging(vcpu)) {
4660 context->nx = false;
4661 context->gva_to_gpa = nonpaging_gva_to_gpa;
4662 context->root_level = 0;
4663 } else if (is_long_mode(vcpu)) {
4664 context->nx = is_nx(vcpu);
4665 context->root_level = is_la57_mode(vcpu) ?
4666 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4667 reset_rsvds_bits_mask(vcpu, context);
4668 context->gva_to_gpa = paging64_gva_to_gpa;
4669 } else if (is_pae(vcpu)) {
4670 context->nx = is_nx(vcpu);
4671 context->root_level = PT32E_ROOT_LEVEL;
4672 reset_rsvds_bits_mask(vcpu, context);
4673 context->gva_to_gpa = paging64_gva_to_gpa;
4675 context->nx = false;
4676 context->root_level = PT32_ROOT_LEVEL;
4677 reset_rsvds_bits_mask(vcpu, context);
4678 context->gva_to_gpa = paging32_gva_to_gpa;
4681 update_permission_bitmask(vcpu, context, false);
4682 update_pkru_bitmask(vcpu, context, false);
4683 update_last_nonleaf_level(vcpu, context);
4684 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4687 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4689 bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4690 bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4691 struct kvm_mmu *context = &vcpu->arch.mmu;
4693 MMU_WARN_ON(VALID_PAGE(context->root_hpa));
4695 if (!is_paging(vcpu))
4696 nonpaging_init_context(vcpu, context);
4697 else if (is_long_mode(vcpu))
4698 paging64_init_context(vcpu, context);
4699 else if (is_pae(vcpu))
4700 paging32E_init_context(vcpu, context);
4702 paging32_init_context(vcpu, context);
4704 context->base_role.nxe = is_nx(vcpu);
4705 context->base_role.cr4_pae = !!is_pae(vcpu);
4706 context->base_role.cr0_wp = is_write_protection(vcpu);
4707 context->base_role.smep_andnot_wp
4708 = smep && !is_write_protection(vcpu);
4709 context->base_role.smap_andnot_wp
4710 = smap && !is_write_protection(vcpu);
4711 context->base_role.smm = is_smm(vcpu);
4712 reset_shadow_zero_bits_mask(vcpu, context);
4714 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4716 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4717 bool accessed_dirty)
4719 struct kvm_mmu *context = &vcpu->arch.mmu;
4721 MMU_WARN_ON(VALID_PAGE(context->root_hpa));
4723 context->shadow_root_level = PT64_ROOT_4LEVEL;
4726 context->ept_ad = accessed_dirty;
4727 context->page_fault = ept_page_fault;
4728 context->gva_to_gpa = ept_gva_to_gpa;
4729 context->sync_page = ept_sync_page;
4730 context->invlpg = ept_invlpg;
4731 context->update_pte = ept_update_pte;
4732 context->root_level = PT64_ROOT_4LEVEL;
4733 context->root_hpa = INVALID_PAGE;
4734 context->direct_map = false;
4735 context->base_role.ad_disabled = !accessed_dirty;
4737 update_permission_bitmask(vcpu, context, true);
4738 update_pkru_bitmask(vcpu, context, true);
4739 update_last_nonleaf_level(vcpu, context);
4740 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4741 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4743 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4745 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4747 struct kvm_mmu *context = &vcpu->arch.mmu;
4749 kvm_init_shadow_mmu(vcpu);
4750 context->set_cr3 = kvm_x86_ops->set_cr3;
4751 context->get_cr3 = get_cr3;
4752 context->get_pdptr = kvm_pdptr_read;
4753 context->inject_page_fault = kvm_inject_page_fault;
4756 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4758 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4760 g_context->get_cr3 = get_cr3;
4761 g_context->get_pdptr = kvm_pdptr_read;
4762 g_context->inject_page_fault = kvm_inject_page_fault;
4765 * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
4766 * L1's nested page tables (e.g. EPT12). The nested translation
4767 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4768 * L2's page tables as the first level of translation and L1's
4769 * nested page tables as the second level of translation. Basically
4770 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
4772 if (!is_paging(vcpu)) {
4773 g_context->nx = false;
4774 g_context->root_level = 0;
4775 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4776 } else if (is_long_mode(vcpu)) {
4777 g_context->nx = is_nx(vcpu);
4778 g_context->root_level = is_la57_mode(vcpu) ?
4779 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4780 reset_rsvds_bits_mask(vcpu, g_context);
4781 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4782 } else if (is_pae(vcpu)) {
4783 g_context->nx = is_nx(vcpu);
4784 g_context->root_level = PT32E_ROOT_LEVEL;
4785 reset_rsvds_bits_mask(vcpu, g_context);
4786 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4788 g_context->nx = false;
4789 g_context->root_level = PT32_ROOT_LEVEL;
4790 reset_rsvds_bits_mask(vcpu, g_context);
4791 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
4794 update_permission_bitmask(vcpu, g_context, false);
4795 update_pkru_bitmask(vcpu, g_context, false);
4796 update_last_nonleaf_level(vcpu, g_context);
4799 static void init_kvm_mmu(struct kvm_vcpu *vcpu)
4801 if (mmu_is_nested(vcpu))
4802 init_kvm_nested_mmu(vcpu);
4803 else if (tdp_enabled)
4804 init_kvm_tdp_mmu(vcpu);
4806 init_kvm_softmmu(vcpu);
4809 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
4811 kvm_mmu_unload(vcpu);
4814 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
4816 int kvm_mmu_load(struct kvm_vcpu *vcpu)
4820 r = mmu_topup_memory_caches(vcpu);
4823 r = mmu_alloc_roots(vcpu);
4824 kvm_mmu_sync_roots(vcpu);
4827 /* set_cr3() should ensure TLB has been flushed */
4828 vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
4832 EXPORT_SYMBOL_GPL(kvm_mmu_load);
4834 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4836 mmu_free_roots(vcpu);
4837 WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
4839 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
4841 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
4842 struct kvm_mmu_page *sp, u64 *spte,
4845 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
4846 ++vcpu->kvm->stat.mmu_pde_zapped;
4850 ++vcpu->kvm->stat.mmu_pte_updated;
4851 vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
4854 static bool need_remote_flush(u64 old, u64 new)
4856 if (!is_shadow_present_pte(old))
4858 if (!is_shadow_present_pte(new))
4860 if ((old ^ new) & PT64_BASE_ADDR_MASK)
4862 old ^= shadow_nx_mask;
4863 new ^= shadow_nx_mask;
4864 return (old & ~new & PT64_PERM_MASK) != 0;
4867 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
4874 * Assume that the pte write on a page table of the same type
4875 * as the current vcpu paging mode since we update the sptes only
4876 * when they have the same mode.
4878 if (is_pae(vcpu) && *bytes == 4) {
4879 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
4884 if (*bytes == 4 || *bytes == 8) {
4885 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
4894 * If we're seeing too many writes to a page, it may no longer be a page table,
4895 * or we may be forking, in which case it is better to unmap the page.
4897 static bool detect_write_flooding(struct kvm_mmu_page *sp)
4900 * Skip write-flooding detected for the sp whose level is 1, because
4901 * it can become unsync, then the guest page is not write-protected.
4903 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
4906 atomic_inc(&sp->write_flooding_count);
4907 return atomic_read(&sp->write_flooding_count) >= 3;
4911 * Misaligned accesses are too much trouble to fix up; also, they usually
4912 * indicate a page is not used as a page table.
4914 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
4917 unsigned offset, pte_size, misaligned;
4919 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
4920 gpa, bytes, sp->role.word);
4922 offset = offset_in_page(gpa);
4923 pte_size = sp->role.cr4_pae ? 8 : 4;
4926 * Sometimes, the OS only writes the last one bytes to update status
4927 * bits, for example, in linux, andb instruction is used in clear_bit().
4929 if (!(offset & (pte_size - 1)) && bytes == 1)
4932 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
4933 misaligned |= bytes < 4;
4938 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
4940 unsigned page_offset, quadrant;
4944 page_offset = offset_in_page(gpa);
4945 level = sp->role.level;
4947 if (!sp->role.cr4_pae) {
4948 page_offset <<= 1; /* 32->64 */
4950 * A 32-bit pde maps 4MB while the shadow pdes map
4951 * only 2MB. So we need to double the offset again
4952 * and zap two pdes instead of one.
4954 if (level == PT32_ROOT_LEVEL) {
4955 page_offset &= ~7; /* kill rounding error */
4959 quadrant = page_offset >> PAGE_SHIFT;
4960 page_offset &= ~PAGE_MASK;
4961 if (quadrant != sp->role.quadrant)
4965 spte = &sp->spt[page_offset / sizeof(*spte)];
4969 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
4970 const u8 *new, int bytes,
4971 struct kvm_page_track_notifier_node *node)
4973 gfn_t gfn = gpa >> PAGE_SHIFT;
4974 struct kvm_mmu_page *sp;
4975 LIST_HEAD(invalid_list);
4976 u64 entry, gentry, *spte;
4978 bool remote_flush, local_flush;
4979 union kvm_mmu_page_role mask = { };
4984 mask.smep_andnot_wp = 1;
4985 mask.smap_andnot_wp = 1;
4987 mask.ad_disabled = 1;
4990 * If we don't have indirect shadow pages, it means no page is
4991 * write-protected, so we can exit simply.
4993 if (!ACCESS_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
4996 remote_flush = local_flush = false;
4998 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5001 * No need to care whether allocation memory is successful
5002 * or not since pte prefetch is skiped if it does not have
5003 * enough objects in the cache.
5005 mmu_topup_memory_caches(vcpu);
5007 spin_lock(&vcpu->kvm->mmu_lock);
5009 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5011 ++vcpu->kvm->stat.mmu_pte_write;
5012 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5014 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5015 if (detect_write_misaligned(sp, gpa, bytes) ||
5016 detect_write_flooding(sp)) {
5017 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5018 ++vcpu->kvm->stat.mmu_flooded;
5022 spte = get_written_sptes(sp, gpa, &npte);
5029 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5031 !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
5032 & mask.word) && rmap_can_add(vcpu))
5033 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5034 if (need_remote_flush(entry, *spte))
5035 remote_flush = true;
5039 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5040 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5041 spin_unlock(&vcpu->kvm->mmu_lock);
5044 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5049 if (vcpu->arch.mmu.direct_map)
5052 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5054 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5058 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5060 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5062 LIST_HEAD(invalid_list);
5064 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5067 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5068 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5071 ++vcpu->kvm->stat.mmu_recycled;
5073 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5075 if (!kvm_mmu_available_pages(vcpu->kvm))
5080 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5081 void *insn, int insn_len)
5083 int r, emulation_type = EMULTYPE_RETRY;
5084 enum emulation_result er;
5085 bool direct = vcpu->arch.mmu.direct_map;
5087 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5088 if (vcpu->arch.mmu.direct_map) {
5089 vcpu->arch.gpa_available = true;
5090 vcpu->arch.gpa_val = cr2;
5094 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5095 r = handle_mmio_page_fault(vcpu, cr2, direct);
5096 if (r == RET_PF_EMULATE) {
5102 if (r == RET_PF_INVALID) {
5103 r = vcpu->arch.mmu.page_fault(vcpu, cr2, lower_32_bits(error_code),
5105 WARN_ON(r == RET_PF_INVALID);
5108 if (r == RET_PF_RETRY)
5114 * Before emulating the instruction, check if the error code
5115 * was due to a RO violation while translating the guest page.
5116 * This can occur when using nested virtualization with nested
5117 * paging in both guests. If true, we simply unprotect the page
5118 * and resume the guest.
5120 if (vcpu->arch.mmu.direct_map &&
5121 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5122 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5126 if (mmio_info_in_cache(vcpu, cr2, direct))
5129 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
5134 case EMULATE_USER_EXIT:
5135 ++vcpu->stat.mmio_exits;
5143 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5145 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5147 vcpu->arch.mmu.invlpg(vcpu, gva);
5148 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5149 ++vcpu->stat.invlpg;
5151 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5153 void kvm_enable_tdp(void)
5157 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5159 void kvm_disable_tdp(void)
5161 tdp_enabled = false;
5163 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5165 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5167 free_page((unsigned long)vcpu->arch.mmu.pae_root);
5168 if (vcpu->arch.mmu.lm_root != NULL)
5169 free_page((unsigned long)vcpu->arch.mmu.lm_root);
5172 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5178 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5179 * Therefore we need to allocate shadow page tables in the first
5180 * 4GB of memory, which happens to fit the DMA32 zone.
5182 page = alloc_page(GFP_KERNEL | __GFP_DMA32);
5186 vcpu->arch.mmu.pae_root = page_address(page);
5187 for (i = 0; i < 4; ++i)
5188 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
5193 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5195 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
5196 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5197 vcpu->arch.mmu.translate_gpa = translate_gpa;
5198 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5200 return alloc_mmu_pages(vcpu);
5203 void kvm_mmu_setup(struct kvm_vcpu *vcpu)
5205 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
5210 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5211 struct kvm_memory_slot *slot,
5212 struct kvm_page_track_notifier_node *node)
5214 kvm_mmu_invalidate_zap_all_pages(kvm);
5217 void kvm_mmu_init_vm(struct kvm *kvm)
5219 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5221 node->track_write = kvm_mmu_pte_write;
5222 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5223 kvm_page_track_register_notifier(kvm, node);
5226 void kvm_mmu_uninit_vm(struct kvm *kvm)
5228 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5230 kvm_page_track_unregister_notifier(kvm, node);
5233 /* The return value indicates if tlb flush on all vcpus is needed. */
5234 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5236 /* The caller should hold mmu-lock before calling this function. */
5237 static __always_inline bool
5238 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5239 slot_level_handler fn, int start_level, int end_level,
5240 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5242 struct slot_rmap_walk_iterator iterator;
5245 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5246 end_gfn, &iterator) {
5248 flush |= fn(kvm, iterator.rmap);
5250 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5251 if (flush && lock_flush_tlb) {
5252 kvm_flush_remote_tlbs(kvm);
5255 cond_resched_lock(&kvm->mmu_lock);
5259 if (flush && lock_flush_tlb) {
5260 kvm_flush_remote_tlbs(kvm);
5267 static __always_inline bool
5268 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5269 slot_level_handler fn, int start_level, int end_level,
5270 bool lock_flush_tlb)
5272 return slot_handle_level_range(kvm, memslot, fn, start_level,
5273 end_level, memslot->base_gfn,
5274 memslot->base_gfn + memslot->npages - 1,
5278 static __always_inline bool
5279 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5280 slot_level_handler fn, bool lock_flush_tlb)
5282 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5283 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5286 static __always_inline bool
5287 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5288 slot_level_handler fn, bool lock_flush_tlb)
5290 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5291 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5294 static __always_inline bool
5295 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5296 slot_level_handler fn, bool lock_flush_tlb)
5298 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5299 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5302 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5304 struct kvm_memslots *slots;
5305 struct kvm_memory_slot *memslot;
5308 spin_lock(&kvm->mmu_lock);
5309 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5310 slots = __kvm_memslots(kvm, i);
5311 kvm_for_each_memslot(memslot, slots) {
5314 start = max(gfn_start, memslot->base_gfn);
5315 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5319 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5320 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5321 start, end - 1, true);
5325 spin_unlock(&kvm->mmu_lock);
5328 static bool slot_rmap_write_protect(struct kvm *kvm,
5329 struct kvm_rmap_head *rmap_head)
5331 return __rmap_write_protect(kvm, rmap_head, false);
5334 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5335 struct kvm_memory_slot *memslot)
5339 spin_lock(&kvm->mmu_lock);
5340 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5342 spin_unlock(&kvm->mmu_lock);
5345 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5346 * which do tlb flush out of mmu-lock should be serialized by
5347 * kvm->slots_lock otherwise tlb flush would be missed.
5349 lockdep_assert_held(&kvm->slots_lock);
5352 * We can flush all the TLBs out of the mmu lock without TLB
5353 * corruption since we just change the spte from writable to
5354 * readonly so that we only need to care the case of changing
5355 * spte from present to present (changing the spte from present
5356 * to nonpresent will flush all the TLBs immediately), in other
5357 * words, the only case we care is mmu_spte_update() where we
5358 * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5359 * instead of PT_WRITABLE_MASK, that means it does not depend
5360 * on PT_WRITABLE_MASK anymore.
5363 kvm_flush_remote_tlbs(kvm);
5366 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5367 struct kvm_rmap_head *rmap_head)
5370 struct rmap_iterator iter;
5371 int need_tlb_flush = 0;
5373 struct kvm_mmu_page *sp;
5376 for_each_rmap_spte(rmap_head, &iter, sptep) {
5377 sp = page_header(__pa(sptep));
5378 pfn = spte_to_pfn(*sptep);
5381 * We cannot do huge page mapping for indirect shadow pages,
5382 * which are found on the last rmap (level = 1) when not using
5383 * tdp; such shadow pages are synced with the page table in
5384 * the guest, and the guest page table is using 4K page size
5385 * mapping if the indirect sp has level = 1.
5387 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5388 !kvm_is_zone_device_pfn(pfn) &&
5389 PageTransCompoundMap(pfn_to_page(pfn))) {
5390 drop_spte(kvm, sptep);
5396 return need_tlb_flush;
5399 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5400 const struct kvm_memory_slot *memslot)
5402 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5403 spin_lock(&kvm->mmu_lock);
5404 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5405 kvm_mmu_zap_collapsible_spte, true);
5406 spin_unlock(&kvm->mmu_lock);
5409 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5410 struct kvm_memory_slot *memslot)
5414 spin_lock(&kvm->mmu_lock);
5415 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5416 spin_unlock(&kvm->mmu_lock);
5418 lockdep_assert_held(&kvm->slots_lock);
5421 * It's also safe to flush TLBs out of mmu lock here as currently this
5422 * function is only used for dirty logging, in which case flushing TLB
5423 * out of mmu lock also guarantees no dirty pages will be lost in
5427 kvm_flush_remote_tlbs(kvm);
5429 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5431 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5432 struct kvm_memory_slot *memslot)
5436 spin_lock(&kvm->mmu_lock);
5437 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5439 spin_unlock(&kvm->mmu_lock);
5441 /* see kvm_mmu_slot_remove_write_access */
5442 lockdep_assert_held(&kvm->slots_lock);
5445 kvm_flush_remote_tlbs(kvm);
5447 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5449 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5450 struct kvm_memory_slot *memslot)
5454 spin_lock(&kvm->mmu_lock);
5455 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5456 spin_unlock(&kvm->mmu_lock);
5458 lockdep_assert_held(&kvm->slots_lock);
5460 /* see kvm_mmu_slot_leaf_clear_dirty */
5462 kvm_flush_remote_tlbs(kvm);
5464 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5466 #define BATCH_ZAP_PAGES 10
5467 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5469 struct kvm_mmu_page *sp, *node;
5473 list_for_each_entry_safe_reverse(sp, node,
5474 &kvm->arch.active_mmu_pages, link) {
5478 * No obsolete page exists before new created page since
5479 * active_mmu_pages is the FIFO list.
5481 if (!is_obsolete_sp(kvm, sp))
5485 * Since we are reversely walking the list and the invalid
5486 * list will be moved to the head, skip the invalid page
5487 * can help us to avoid the infinity list walking.
5489 if (sp->role.invalid)
5493 * Need not flush tlb since we only zap the sp with invalid
5494 * generation number.
5496 if (batch >= BATCH_ZAP_PAGES &&
5497 cond_resched_lock(&kvm->mmu_lock)) {
5502 ret = kvm_mmu_prepare_zap_page(kvm, sp,
5503 &kvm->arch.zapped_obsolete_pages);
5511 * Should flush tlb before free page tables since lockless-walking
5512 * may use the pages.
5514 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5518 * Fast invalidate all shadow pages and use lock-break technique
5519 * to zap obsolete pages.
5521 * It's required when memslot is being deleted or VM is being
5522 * destroyed, in these cases, we should ensure that KVM MMU does
5523 * not use any resource of the being-deleted slot or all slots
5524 * after calling the function.
5526 void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
5528 spin_lock(&kvm->mmu_lock);
5529 trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5530 kvm->arch.mmu_valid_gen++;
5533 * Notify all vcpus to reload its shadow page table
5534 * and flush TLB. Then all vcpus will switch to new
5535 * shadow page table with the new mmu_valid_gen.
5537 * Note: we should do this under the protection of
5538 * mmu-lock, otherwise, vcpu would purge shadow page
5539 * but miss tlb flush.
5541 kvm_reload_remote_mmus(kvm);
5543 kvm_zap_obsolete_pages(kvm);
5544 spin_unlock(&kvm->mmu_lock);
5547 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5549 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5552 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5554 gen &= MMIO_GEN_MASK;
5557 * Shift to eliminate the "update in-progress" flag, which isn't
5558 * included in the spte's generation number.
5563 * Generation numbers are incremented in multiples of the number of
5564 * address spaces in order to provide unique generations across all
5565 * address spaces. Strip what is effectively the address space
5566 * modifier prior to checking for a wrap of the MMIO generation so
5567 * that a wrap in any address space is detected.
5569 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5572 * The very rare case: if the MMIO generation number has wrapped,
5573 * zap all shadow pages.
5575 if (unlikely(gen == 0)) {
5576 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5577 kvm_mmu_invalidate_zap_all_pages(kvm);
5581 static unsigned long
5582 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5585 int nr_to_scan = sc->nr_to_scan;
5586 unsigned long freed = 0;
5588 mutex_lock(&kvm_lock);
5590 list_for_each_entry(kvm, &vm_list, vm_list) {
5592 LIST_HEAD(invalid_list);
5595 * Never scan more than sc->nr_to_scan VM instances.
5596 * Will not hit this condition practically since we do not try
5597 * to shrink more than one VM and it is very unlikely to see
5598 * !n_used_mmu_pages so many times.
5603 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5604 * here. We may skip a VM instance errorneosly, but we do not
5605 * want to shrink a VM that only started to populate its MMU
5608 if (!kvm->arch.n_used_mmu_pages &&
5609 !kvm_has_zapped_obsolete_pages(kvm))
5612 idx = srcu_read_lock(&kvm->srcu);
5613 spin_lock(&kvm->mmu_lock);
5615 if (kvm_has_zapped_obsolete_pages(kvm)) {
5616 kvm_mmu_commit_zap_page(kvm,
5617 &kvm->arch.zapped_obsolete_pages);
5621 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
5623 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5626 spin_unlock(&kvm->mmu_lock);
5627 srcu_read_unlock(&kvm->srcu, idx);
5630 * unfair on small ones
5631 * per-vm shrinkers cry out
5632 * sadness comes quickly
5634 list_move_tail(&kvm->vm_list, &vm_list);
5638 mutex_unlock(&kvm_lock);
5642 static unsigned long
5643 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5645 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5648 static struct shrinker mmu_shrinker = {
5649 .count_objects = mmu_shrink_count,
5650 .scan_objects = mmu_shrink_scan,
5651 .seeks = DEFAULT_SEEKS * 10,
5654 static void mmu_destroy_caches(void)
5656 if (pte_list_desc_cache)
5657 kmem_cache_destroy(pte_list_desc_cache);
5658 if (mmu_page_header_cache)
5659 kmem_cache_destroy(mmu_page_header_cache);
5662 static bool get_nx_auto_mode(void)
5664 /* Return true when CPU has the bug, and mitigations are ON */
5665 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
5668 static void __set_nx_huge_pages(bool val)
5670 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
5673 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
5675 bool old_val = nx_huge_pages;
5678 /* In "auto" mode deploy workaround only if CPU has the bug. */
5679 if (sysfs_streq(val, "off"))
5681 else if (sysfs_streq(val, "force"))
5683 else if (sysfs_streq(val, "auto"))
5684 new_val = get_nx_auto_mode();
5685 else if (strtobool(val, &new_val) < 0)
5688 __set_nx_huge_pages(new_val);
5690 if (new_val != old_val) {
5694 mutex_lock(&kvm_lock);
5696 list_for_each_entry(kvm, &vm_list, vm_list) {
5697 idx = srcu_read_lock(&kvm->srcu);
5698 kvm_mmu_invalidate_zap_all_pages(kvm);
5699 srcu_read_unlock(&kvm->srcu, idx);
5701 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
5703 mutex_unlock(&kvm_lock);
5709 static void kvm_set_mmio_spte_mask(void)
5714 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
5715 * PFEC.RSVD=1 on MMIO accesses. 64-bit PTEs (PAE, x86-64, and EPT
5716 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
5717 * 52-bit physical addresses then there are no reserved PA bits in the
5718 * PTEs and so the reserved PA approach must be disabled.
5720 if (shadow_phys_bits < 52)
5721 mask = BIT_ULL(51) | PT_PRESENT_MASK;
5725 kvm_mmu_set_mmio_spte_mask(mask, mask);
5728 int kvm_mmu_module_init(void)
5730 if (nx_huge_pages == -1)
5731 __set_nx_huge_pages(get_nx_auto_mode());
5733 kvm_mmu_reset_all_pte_masks();
5735 kvm_set_mmio_spte_mask();
5737 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
5738 sizeof(struct pte_list_desc),
5739 0, SLAB_ACCOUNT, NULL);
5740 if (!pte_list_desc_cache)
5743 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
5744 sizeof(struct kvm_mmu_page),
5745 0, SLAB_ACCOUNT, NULL);
5746 if (!mmu_page_header_cache)
5749 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
5752 register_shrinker(&mmu_shrinker);
5757 mmu_destroy_caches();
5762 * Caculate mmu pages needed for kvm.
5764 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
5766 unsigned int nr_mmu_pages;
5767 unsigned int nr_pages = 0;
5768 struct kvm_memslots *slots;
5769 struct kvm_memory_slot *memslot;
5772 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5773 slots = __kvm_memslots(kvm, i);
5775 kvm_for_each_memslot(memslot, slots)
5776 nr_pages += memslot->npages;
5779 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
5780 nr_mmu_pages = max(nr_mmu_pages,
5781 (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
5783 return nr_mmu_pages;
5786 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
5788 kvm_mmu_unload(vcpu);
5789 free_mmu_pages(vcpu);
5790 mmu_free_memory_caches(vcpu);
5793 void kvm_mmu_module_exit(void)
5795 mmu_destroy_caches();
5796 percpu_counter_destroy(&kvm_total_used_mmu_pages);
5797 unregister_shrinker(&mmu_shrinker);
5798 mmu_audit_disable();
5801 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
5803 unsigned int old_val;
5806 old_val = nx_huge_pages_recovery_ratio;
5807 err = param_set_uint(val, kp);
5811 if (READ_ONCE(nx_huge_pages) &&
5812 !old_val && nx_huge_pages_recovery_ratio) {
5815 mutex_lock(&kvm_lock);
5817 list_for_each_entry(kvm, &vm_list, vm_list)
5818 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
5820 mutex_unlock(&kvm_lock);
5826 static void kvm_recover_nx_lpages(struct kvm *kvm)
5829 struct kvm_mmu_page *sp;
5831 LIST_HEAD(invalid_list);
5834 rcu_idx = srcu_read_lock(&kvm->srcu);
5835 spin_lock(&kvm->mmu_lock);
5837 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
5838 to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
5839 while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
5841 * We use a separate list instead of just using active_mmu_pages
5842 * because the number of lpage_disallowed pages is expected to
5843 * be relatively small compared to the total.
5845 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
5846 struct kvm_mmu_page,
5847 lpage_disallowed_link);
5848 WARN_ON_ONCE(!sp->lpage_disallowed);
5849 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
5850 WARN_ON_ONCE(sp->lpage_disallowed);
5852 if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5853 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5855 cond_resched_lock(&kvm->mmu_lock);
5858 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5860 spin_unlock(&kvm->mmu_lock);
5861 srcu_read_unlock(&kvm->srcu, rcu_idx);
5864 static long get_nx_lpage_recovery_timeout(u64 start_time)
5866 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
5867 ? start_time + 60 * HZ - get_jiffies_64()
5868 : MAX_SCHEDULE_TIMEOUT;
5871 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
5874 long remaining_time;
5877 start_time = get_jiffies_64();
5878 remaining_time = get_nx_lpage_recovery_timeout(start_time);
5880 set_current_state(TASK_INTERRUPTIBLE);
5881 while (!kthread_should_stop() && remaining_time > 0) {
5882 schedule_timeout(remaining_time);
5883 remaining_time = get_nx_lpage_recovery_timeout(start_time);
5884 set_current_state(TASK_INTERRUPTIBLE);
5887 set_current_state(TASK_RUNNING);
5889 if (kthread_should_stop())
5892 kvm_recover_nx_lpages(kvm);
5896 int kvm_mmu_post_init_vm(struct kvm *kvm)
5900 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
5901 "kvm-nx-lpage-recovery",
5902 &kvm->arch.nx_lpage_recovery_thread);
5904 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
5909 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
5911 if (kvm->arch.nx_lpage_recovery_thread)
5912 kthread_stop(kvm->arch.nx_lpage_recovery_thread);