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>
46 #include <asm/cmpxchg.h>
49 #include <asm/kvm_page_track.h>
53 * When setting this variable to true it enables Two-Dimensional-Paging
54 * where the hardware walks 2 page tables:
55 * 1. the guest-virtual to guest-physical
56 * 2. while doing 1. it walks guest-physical to host-physical
57 * If the hardware supports that we don't need to do shadow paging.
59 bool tdp_enabled = false;
63 AUDIT_POST_PAGE_FAULT,
74 module_param(dbg, bool, 0644);
76 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
77 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
78 #define MMU_WARN_ON(x) WARN_ON(x)
80 #define pgprintk(x...) do { } while (0)
81 #define rmap_printk(x...) do { } while (0)
82 #define MMU_WARN_ON(x) do { } while (0)
85 #define PTE_PREFETCH_NUM 8
87 #define PT_FIRST_AVAIL_BITS_SHIFT 10
88 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
90 #define PT64_LEVEL_BITS 9
92 #define PT64_LEVEL_SHIFT(level) \
93 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
95 #define PT64_INDEX(address, level)\
96 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
99 #define PT32_LEVEL_BITS 10
101 #define PT32_LEVEL_SHIFT(level) \
102 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
104 #define PT32_LVL_OFFSET_MASK(level) \
105 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
106 * PT32_LEVEL_BITS))) - 1))
108 #define PT32_INDEX(address, level)\
109 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
112 #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
113 #define PT64_BASE_ADDR_MASK (physical_mask & ~(u64)(PAGE_SIZE-1))
115 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
117 #define PT64_LVL_ADDR_MASK(level) \
118 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
119 * PT64_LEVEL_BITS))) - 1))
120 #define PT64_LVL_OFFSET_MASK(level) \
121 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
122 * PT64_LEVEL_BITS))) - 1))
124 #define PT32_BASE_ADDR_MASK PAGE_MASK
125 #define PT32_DIR_BASE_ADDR_MASK \
126 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
127 #define PT32_LVL_ADDR_MASK(level) \
128 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
129 * PT32_LEVEL_BITS))) - 1))
131 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
132 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
134 #define ACC_EXEC_MASK 1
135 #define ACC_WRITE_MASK PT_WRITABLE_MASK
136 #define ACC_USER_MASK PT_USER_MASK
137 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
139 /* The mask for the R/X bits in EPT PTEs */
140 #define PT64_EPT_READABLE_MASK 0x1ull
141 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
143 #include <trace/events/kvm.h>
145 #define CREATE_TRACE_POINTS
146 #include "mmutrace.h"
148 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
149 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
151 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
153 /* make pte_list_desc fit well in cache line */
154 #define PTE_LIST_EXT 3
157 * Return values of handle_mmio_page_fault and mmu.page_fault:
158 * RET_PF_RETRY: let CPU fault again on the address.
159 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
161 * For handle_mmio_page_fault only:
162 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
170 struct pte_list_desc {
171 u64 *sptes[PTE_LIST_EXT];
172 struct pte_list_desc *more;
175 struct kvm_shadow_walk_iterator {
183 static const union kvm_mmu_page_role mmu_base_role_mask = {
185 .gpte_is_8_bytes = 1,
194 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
195 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
197 shadow_walk_okay(&(_walker)); \
198 shadow_walk_next(&(_walker)))
200 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
201 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
202 shadow_walk_okay(&(_walker)); \
203 shadow_walk_next(&(_walker)))
205 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
206 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
207 shadow_walk_okay(&(_walker)) && \
208 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
209 __shadow_walk_next(&(_walker), spte))
211 static struct kmem_cache *pte_list_desc_cache;
212 static struct kmem_cache *mmu_page_header_cache;
213 static struct percpu_counter kvm_total_used_mmu_pages;
215 static u64 __read_mostly shadow_nx_mask;
216 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
217 static u64 __read_mostly shadow_user_mask;
218 static u64 __read_mostly shadow_accessed_mask;
219 static u64 __read_mostly shadow_dirty_mask;
220 static u64 __read_mostly shadow_mmio_mask;
221 static u64 __read_mostly shadow_mmio_value;
222 static u64 __read_mostly shadow_present_mask;
223 static u64 __read_mostly shadow_me_mask;
226 * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
227 * Non-present SPTEs with shadow_acc_track_value set are in place for access
230 static u64 __read_mostly shadow_acc_track_mask;
231 static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
234 * The mask/shift to use for saving the original R/X bits when marking the PTE
235 * as not-present for access tracking purposes. We do not save the W bit as the
236 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
237 * restored only when a write is attempted to the page.
239 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
240 PT64_EPT_EXECUTABLE_MASK;
241 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
244 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
245 * to guard against L1TF attacks.
247 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
250 * The number of high-order 1 bits to use in the mask above.
252 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
255 * In some cases, we need to preserve the GFN of a non-present or reserved
256 * SPTE when we usurp the upper five bits of the physical address space to
257 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
258 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
259 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
260 * high and low parts. This mask covers the lower bits of the GFN.
262 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
265 static void mmu_spte_set(u64 *sptep, u64 spte);
266 static union kvm_mmu_page_role
267 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
270 static inline bool kvm_available_flush_tlb_with_range(void)
272 return kvm_x86_ops->tlb_remote_flush_with_range;
275 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
276 struct kvm_tlb_range *range)
280 if (range && kvm_x86_ops->tlb_remote_flush_with_range)
281 ret = kvm_x86_ops->tlb_remote_flush_with_range(kvm, range);
284 kvm_flush_remote_tlbs(kvm);
287 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
288 u64 start_gfn, u64 pages)
290 struct kvm_tlb_range range;
292 range.start_gfn = start_gfn;
295 kvm_flush_remote_tlbs_with_range(kvm, &range);
298 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
300 BUG_ON((mmio_mask & mmio_value) != mmio_value);
301 shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
302 shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
304 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
306 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
308 return sp->role.ad_disabled;
311 static inline bool spte_ad_enabled(u64 spte)
313 MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
314 return !(spte & shadow_acc_track_value);
317 static inline u64 spte_shadow_accessed_mask(u64 spte)
319 MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
320 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
323 static inline u64 spte_shadow_dirty_mask(u64 spte)
325 MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
326 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
329 static inline bool is_access_track_spte(u64 spte)
331 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
335 * Due to limited space in PTEs, the MMIO generation is a 19 bit subset of
336 * the memslots generation and is derived as follows:
338 * Bits 0-8 of the MMIO generation are propagated to spte bits 3-11
339 * Bits 9-18 of the MMIO generation are propagated to spte bits 52-61
341 * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
342 * the MMIO generation number, as doing so would require stealing a bit from
343 * the "real" generation number and thus effectively halve the maximum number
344 * of MMIO generations that can be handled before encountering a wrap (which
345 * requires a full MMU zap). The flag is instead explicitly queried when
346 * checking for MMIO spte cache hits.
348 #define MMIO_SPTE_GEN_MASK GENMASK_ULL(18, 0)
350 #define MMIO_SPTE_GEN_LOW_START 3
351 #define MMIO_SPTE_GEN_LOW_END 11
352 #define MMIO_SPTE_GEN_LOW_MASK GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
353 MMIO_SPTE_GEN_LOW_START)
355 #define MMIO_SPTE_GEN_HIGH_START 52
356 #define MMIO_SPTE_GEN_HIGH_END 61
357 #define MMIO_SPTE_GEN_HIGH_MASK GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
358 MMIO_SPTE_GEN_HIGH_START)
359 static u64 generation_mmio_spte_mask(u64 gen)
363 WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
365 mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
366 mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
370 static u64 get_mmio_spte_generation(u64 spte)
374 spte &= ~shadow_mmio_mask;
376 gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
377 gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
381 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
384 u64 gen = kvm_vcpu_memslots(vcpu)->generation & MMIO_SPTE_GEN_MASK;
385 u64 mask = generation_mmio_spte_mask(gen);
386 u64 gpa = gfn << PAGE_SHIFT;
388 access &= ACC_WRITE_MASK | ACC_USER_MASK;
389 mask |= shadow_mmio_value | access;
390 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
391 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
392 << shadow_nonpresent_or_rsvd_mask_len;
394 page_header(__pa(sptep))->mmio_cached = true;
396 trace_mark_mmio_spte(sptep, gfn, access, gen);
397 mmu_spte_set(sptep, mask);
400 static bool is_mmio_spte(u64 spte)
402 return (spte & shadow_mmio_mask) == shadow_mmio_value;
405 static gfn_t get_mmio_spte_gfn(u64 spte)
407 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
409 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
410 & shadow_nonpresent_or_rsvd_mask;
412 return gpa >> PAGE_SHIFT;
415 static unsigned get_mmio_spte_access(u64 spte)
417 u64 mask = generation_mmio_spte_mask(MMIO_SPTE_GEN_MASK) | shadow_mmio_mask;
418 return (spte & ~mask) & ~PAGE_MASK;
421 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
422 kvm_pfn_t pfn, unsigned access)
424 if (unlikely(is_noslot_pfn(pfn))) {
425 mark_mmio_spte(vcpu, sptep, gfn, access);
432 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
434 u64 kvm_gen, spte_gen, gen;
436 gen = kvm_vcpu_memslots(vcpu)->generation;
437 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
440 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
441 spte_gen = get_mmio_spte_generation(spte);
443 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
444 return likely(kvm_gen == spte_gen);
448 * Sets the shadow PTE masks used by the MMU.
451 * - Setting either @accessed_mask or @dirty_mask requires setting both
452 * - At least one of @accessed_mask or @acc_track_mask must be set
454 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
455 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
456 u64 acc_track_mask, u64 me_mask)
458 BUG_ON(!dirty_mask != !accessed_mask);
459 BUG_ON(!accessed_mask && !acc_track_mask);
460 BUG_ON(acc_track_mask & shadow_acc_track_value);
462 shadow_user_mask = user_mask;
463 shadow_accessed_mask = accessed_mask;
464 shadow_dirty_mask = dirty_mask;
465 shadow_nx_mask = nx_mask;
466 shadow_x_mask = x_mask;
467 shadow_present_mask = p_mask;
468 shadow_acc_track_mask = acc_track_mask;
469 shadow_me_mask = me_mask;
471 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
473 static void kvm_mmu_reset_all_pte_masks(void)
477 shadow_user_mask = 0;
478 shadow_accessed_mask = 0;
479 shadow_dirty_mask = 0;
482 shadow_mmio_mask = 0;
483 shadow_present_mask = 0;
484 shadow_acc_track_mask = 0;
487 * If the CPU has 46 or less physical address bits, then set an
488 * appropriate mask to guard against L1TF attacks. Otherwise, it is
489 * assumed that the CPU is not vulnerable to L1TF.
491 low_phys_bits = boot_cpu_data.x86_phys_bits;
492 if (boot_cpu_data.x86_phys_bits <
493 52 - shadow_nonpresent_or_rsvd_mask_len) {
494 shadow_nonpresent_or_rsvd_mask =
495 rsvd_bits(boot_cpu_data.x86_phys_bits -
496 shadow_nonpresent_or_rsvd_mask_len,
497 boot_cpu_data.x86_phys_bits - 1);
498 low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
500 shadow_nonpresent_or_rsvd_lower_gfn_mask =
501 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
504 static int is_cpuid_PSE36(void)
509 static int is_nx(struct kvm_vcpu *vcpu)
511 return vcpu->arch.efer & EFER_NX;
514 static int is_shadow_present_pte(u64 pte)
516 return (pte != 0) && !is_mmio_spte(pte);
519 static int is_large_pte(u64 pte)
521 return pte & PT_PAGE_SIZE_MASK;
524 static int is_last_spte(u64 pte, int level)
526 if (level == PT_PAGE_TABLE_LEVEL)
528 if (is_large_pte(pte))
533 static bool is_executable_pte(u64 spte)
535 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
538 static kvm_pfn_t spte_to_pfn(u64 pte)
540 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
543 static gfn_t pse36_gfn_delta(u32 gpte)
545 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
547 return (gpte & PT32_DIR_PSE36_MASK) << shift;
551 static void __set_spte(u64 *sptep, u64 spte)
553 WRITE_ONCE(*sptep, spte);
556 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
558 WRITE_ONCE(*sptep, spte);
561 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
563 return xchg(sptep, spte);
566 static u64 __get_spte_lockless(u64 *sptep)
568 return READ_ONCE(*sptep);
579 static void count_spte_clear(u64 *sptep, u64 spte)
581 struct kvm_mmu_page *sp = page_header(__pa(sptep));
583 if (is_shadow_present_pte(spte))
586 /* Ensure the spte is completely set before we increase the count */
588 sp->clear_spte_count++;
591 static void __set_spte(u64 *sptep, u64 spte)
593 union split_spte *ssptep, sspte;
595 ssptep = (union split_spte *)sptep;
596 sspte = (union split_spte)spte;
598 ssptep->spte_high = sspte.spte_high;
601 * If we map the spte from nonpresent to present, We should store
602 * the high bits firstly, then set present bit, so cpu can not
603 * fetch this spte while we are setting the spte.
607 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
610 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
612 union split_spte *ssptep, sspte;
614 ssptep = (union split_spte *)sptep;
615 sspte = (union split_spte)spte;
617 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
620 * If we map the spte from present to nonpresent, we should clear
621 * present bit firstly to avoid vcpu fetch the old high bits.
625 ssptep->spte_high = sspte.spte_high;
626 count_spte_clear(sptep, spte);
629 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
631 union split_spte *ssptep, sspte, orig;
633 ssptep = (union split_spte *)sptep;
634 sspte = (union split_spte)spte;
636 /* xchg acts as a barrier before the setting of the high bits */
637 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
638 orig.spte_high = ssptep->spte_high;
639 ssptep->spte_high = sspte.spte_high;
640 count_spte_clear(sptep, spte);
646 * The idea using the light way get the spte on x86_32 guest is from
647 * gup_get_pte(arch/x86/mm/gup.c).
649 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
650 * coalesces them and we are running out of the MMU lock. Therefore
651 * we need to protect against in-progress updates of the spte.
653 * Reading the spte while an update is in progress may get the old value
654 * for the high part of the spte. The race is fine for a present->non-present
655 * change (because the high part of the spte is ignored for non-present spte),
656 * but for a present->present change we must reread the spte.
658 * All such changes are done in two steps (present->non-present and
659 * non-present->present), hence it is enough to count the number of
660 * present->non-present updates: if it changed while reading the spte,
661 * we might have hit the race. This is done using clear_spte_count.
663 static u64 __get_spte_lockless(u64 *sptep)
665 struct kvm_mmu_page *sp = page_header(__pa(sptep));
666 union split_spte spte, *orig = (union split_spte *)sptep;
670 count = sp->clear_spte_count;
673 spte.spte_low = orig->spte_low;
676 spte.spte_high = orig->spte_high;
679 if (unlikely(spte.spte_low != orig->spte_low ||
680 count != sp->clear_spte_count))
687 static bool spte_can_locklessly_be_made_writable(u64 spte)
689 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
690 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
693 static bool spte_has_volatile_bits(u64 spte)
695 if (!is_shadow_present_pte(spte))
699 * Always atomically update spte if it can be updated
700 * out of mmu-lock, it can ensure dirty bit is not lost,
701 * also, it can help us to get a stable is_writable_pte()
702 * to ensure tlb flush is not missed.
704 if (spte_can_locklessly_be_made_writable(spte) ||
705 is_access_track_spte(spte))
708 if (spte_ad_enabled(spte)) {
709 if ((spte & shadow_accessed_mask) == 0 ||
710 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
717 static bool is_accessed_spte(u64 spte)
719 u64 accessed_mask = spte_shadow_accessed_mask(spte);
721 return accessed_mask ? spte & accessed_mask
722 : !is_access_track_spte(spte);
725 static bool is_dirty_spte(u64 spte)
727 u64 dirty_mask = spte_shadow_dirty_mask(spte);
729 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
732 /* Rules for using mmu_spte_set:
733 * Set the sptep from nonpresent to present.
734 * Note: the sptep being assigned *must* be either not present
735 * or in a state where the hardware will not attempt to update
738 static void mmu_spte_set(u64 *sptep, u64 new_spte)
740 WARN_ON(is_shadow_present_pte(*sptep));
741 __set_spte(sptep, new_spte);
745 * Update the SPTE (excluding the PFN), but do not track changes in its
746 * accessed/dirty status.
748 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
750 u64 old_spte = *sptep;
752 WARN_ON(!is_shadow_present_pte(new_spte));
754 if (!is_shadow_present_pte(old_spte)) {
755 mmu_spte_set(sptep, new_spte);
759 if (!spte_has_volatile_bits(old_spte))
760 __update_clear_spte_fast(sptep, new_spte);
762 old_spte = __update_clear_spte_slow(sptep, new_spte);
764 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
769 /* Rules for using mmu_spte_update:
770 * Update the state bits, it means the mapped pfn is not changed.
772 * Whenever we overwrite a writable spte with a read-only one we
773 * should flush remote TLBs. Otherwise rmap_write_protect
774 * will find a read-only spte, even though the writable spte
775 * might be cached on a CPU's TLB, the return value indicates this
778 * Returns true if the TLB needs to be flushed
780 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
783 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
785 if (!is_shadow_present_pte(old_spte))
789 * For the spte updated out of mmu-lock is safe, since
790 * we always atomically update it, see the comments in
791 * spte_has_volatile_bits().
793 if (spte_can_locklessly_be_made_writable(old_spte) &&
794 !is_writable_pte(new_spte))
798 * Flush TLB when accessed/dirty states are changed in the page tables,
799 * to guarantee consistency between TLB and page tables.
802 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
804 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
807 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
809 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
816 * Rules for using mmu_spte_clear_track_bits:
817 * It sets the sptep from present to nonpresent, and track the
818 * state bits, it is used to clear the last level sptep.
819 * Returns non-zero if the PTE was previously valid.
821 static int mmu_spte_clear_track_bits(u64 *sptep)
824 u64 old_spte = *sptep;
826 if (!spte_has_volatile_bits(old_spte))
827 __update_clear_spte_fast(sptep, 0ull);
829 old_spte = __update_clear_spte_slow(sptep, 0ull);
831 if (!is_shadow_present_pte(old_spte))
834 pfn = spte_to_pfn(old_spte);
837 * KVM does not hold the refcount of the page used by
838 * kvm mmu, before reclaiming the page, we should
839 * unmap it from mmu first.
841 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
843 if (is_accessed_spte(old_spte))
844 kvm_set_pfn_accessed(pfn);
846 if (is_dirty_spte(old_spte))
847 kvm_set_pfn_dirty(pfn);
853 * Rules for using mmu_spte_clear_no_track:
854 * Directly clear spte without caring the state bits of sptep,
855 * it is used to set the upper level spte.
857 static void mmu_spte_clear_no_track(u64 *sptep)
859 __update_clear_spte_fast(sptep, 0ull);
862 static u64 mmu_spte_get_lockless(u64 *sptep)
864 return __get_spte_lockless(sptep);
867 static u64 mark_spte_for_access_track(u64 spte)
869 if (spte_ad_enabled(spte))
870 return spte & ~shadow_accessed_mask;
872 if (is_access_track_spte(spte))
876 * Making an Access Tracking PTE will result in removal of write access
877 * from the PTE. So, verify that we will be able to restore the write
878 * access in the fast page fault path later on.
880 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
881 !spte_can_locklessly_be_made_writable(spte),
882 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
884 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
885 shadow_acc_track_saved_bits_shift),
886 "kvm: Access Tracking saved bit locations are not zero\n");
888 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
889 shadow_acc_track_saved_bits_shift;
890 spte &= ~shadow_acc_track_mask;
895 /* Restore an acc-track PTE back to a regular PTE */
896 static u64 restore_acc_track_spte(u64 spte)
899 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
900 & shadow_acc_track_saved_bits_mask;
902 WARN_ON_ONCE(spte_ad_enabled(spte));
903 WARN_ON_ONCE(!is_access_track_spte(spte));
905 new_spte &= ~shadow_acc_track_mask;
906 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
907 shadow_acc_track_saved_bits_shift);
908 new_spte |= saved_bits;
913 /* Returns the Accessed status of the PTE and resets it at the same time. */
914 static bool mmu_spte_age(u64 *sptep)
916 u64 spte = mmu_spte_get_lockless(sptep);
918 if (!is_accessed_spte(spte))
921 if (spte_ad_enabled(spte)) {
922 clear_bit((ffs(shadow_accessed_mask) - 1),
923 (unsigned long *)sptep);
926 * Capture the dirty status of the page, so that it doesn't get
927 * lost when the SPTE is marked for access tracking.
929 if (is_writable_pte(spte))
930 kvm_set_pfn_dirty(spte_to_pfn(spte));
932 spte = mark_spte_for_access_track(spte);
933 mmu_spte_update_no_track(sptep, spte);
939 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
942 * Prevent page table teardown by making any free-er wait during
943 * kvm_flush_remote_tlbs() IPI to all active vcpus.
948 * Make sure a following spte read is not reordered ahead of the write
951 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
954 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
957 * Make sure the write to vcpu->mode is not reordered in front of
958 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
959 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
961 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
965 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
966 struct kmem_cache *base_cache, int min)
970 if (cache->nobjs >= min)
972 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
973 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL_ACCOUNT);
975 return cache->nobjs >= min ? 0 : -ENOMEM;
976 cache->objects[cache->nobjs++] = obj;
981 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
986 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
987 struct kmem_cache *cache)
990 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
993 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
998 if (cache->nobjs >= min)
1000 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1001 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1003 return cache->nobjs >= min ? 0 : -ENOMEM;
1004 cache->objects[cache->nobjs++] = page;
1009 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1012 free_page((unsigned long)mc->objects[--mc->nobjs]);
1015 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1019 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1020 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1023 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1026 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1027 mmu_page_header_cache, 4);
1032 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1034 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1035 pte_list_desc_cache);
1036 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1037 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1038 mmu_page_header_cache);
1041 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1046 p = mc->objects[--mc->nobjs];
1050 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1052 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1055 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1057 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1060 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1062 if (!sp->role.direct)
1063 return sp->gfns[index];
1065 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1068 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1070 if (sp->role.direct)
1071 BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index));
1073 sp->gfns[index] = gfn;
1077 * Return the pointer to the large page information for a given gfn,
1078 * handling slots that are not large page aligned.
1080 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1081 struct kvm_memory_slot *slot,
1086 idx = gfn_to_index(gfn, slot->base_gfn, level);
1087 return &slot->arch.lpage_info[level - 2][idx];
1090 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1091 gfn_t gfn, int count)
1093 struct kvm_lpage_info *linfo;
1096 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1097 linfo = lpage_info_slot(gfn, slot, i);
1098 linfo->disallow_lpage += count;
1099 WARN_ON(linfo->disallow_lpage < 0);
1103 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1105 update_gfn_disallow_lpage_count(slot, gfn, 1);
1108 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1110 update_gfn_disallow_lpage_count(slot, gfn, -1);
1113 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1115 struct kvm_memslots *slots;
1116 struct kvm_memory_slot *slot;
1119 kvm->arch.indirect_shadow_pages++;
1121 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1122 slot = __gfn_to_memslot(slots, gfn);
1124 /* the non-leaf shadow pages are keeping readonly. */
1125 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1126 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1127 KVM_PAGE_TRACK_WRITE);
1129 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1132 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1134 struct kvm_memslots *slots;
1135 struct kvm_memory_slot *slot;
1138 kvm->arch.indirect_shadow_pages--;
1140 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1141 slot = __gfn_to_memslot(slots, gfn);
1142 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1143 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1144 KVM_PAGE_TRACK_WRITE);
1146 kvm_mmu_gfn_allow_lpage(slot, gfn);
1149 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1150 struct kvm_memory_slot *slot)
1152 struct kvm_lpage_info *linfo;
1155 linfo = lpage_info_slot(gfn, slot, level);
1156 return !!linfo->disallow_lpage;
1162 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1165 struct kvm_memory_slot *slot;
1167 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1168 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1171 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1173 unsigned long page_size;
1176 page_size = kvm_host_page_size(kvm, gfn);
1178 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1179 if (page_size >= KVM_HPAGE_SIZE(i))
1188 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1191 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1193 if (no_dirty_log && slot->dirty_bitmap)
1199 static struct kvm_memory_slot *
1200 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1203 struct kvm_memory_slot *slot;
1205 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1206 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1212 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1213 bool *force_pt_level)
1215 int host_level, level, max_level;
1216 struct kvm_memory_slot *slot;
1218 if (unlikely(*force_pt_level))
1219 return PT_PAGE_TABLE_LEVEL;
1221 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1222 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1223 if (unlikely(*force_pt_level))
1224 return PT_PAGE_TABLE_LEVEL;
1226 host_level = host_mapping_level(vcpu->kvm, large_gfn);
1228 if (host_level == PT_PAGE_TABLE_LEVEL)
1231 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1233 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1234 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1241 * About rmap_head encoding:
1243 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1244 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1245 * pte_list_desc containing more mappings.
1249 * Returns the number of pointers in the rmap chain, not counting the new one.
1251 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1252 struct kvm_rmap_head *rmap_head)
1254 struct pte_list_desc *desc;
1257 if (!rmap_head->val) {
1258 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1259 rmap_head->val = (unsigned long)spte;
1260 } else if (!(rmap_head->val & 1)) {
1261 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1262 desc = mmu_alloc_pte_list_desc(vcpu);
1263 desc->sptes[0] = (u64 *)rmap_head->val;
1264 desc->sptes[1] = spte;
1265 rmap_head->val = (unsigned long)desc | 1;
1268 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1269 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1270 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1272 count += PTE_LIST_EXT;
1274 if (desc->sptes[PTE_LIST_EXT-1]) {
1275 desc->more = mmu_alloc_pte_list_desc(vcpu);
1278 for (i = 0; desc->sptes[i]; ++i)
1280 desc->sptes[i] = spte;
1286 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1287 struct pte_list_desc *desc, int i,
1288 struct pte_list_desc *prev_desc)
1292 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1294 desc->sptes[i] = desc->sptes[j];
1295 desc->sptes[j] = NULL;
1298 if (!prev_desc && !desc->more)
1299 rmap_head->val = (unsigned long)desc->sptes[0];
1302 prev_desc->more = desc->more;
1304 rmap_head->val = (unsigned long)desc->more | 1;
1305 mmu_free_pte_list_desc(desc);
1308 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1310 struct pte_list_desc *desc;
1311 struct pte_list_desc *prev_desc;
1314 if (!rmap_head->val) {
1315 pr_err("%s: %p 0->BUG\n", __func__, spte);
1317 } else if (!(rmap_head->val & 1)) {
1318 rmap_printk("%s: %p 1->0\n", __func__, spte);
1319 if ((u64 *)rmap_head->val != spte) {
1320 pr_err("%s: %p 1->BUG\n", __func__, spte);
1325 rmap_printk("%s: %p many->many\n", __func__, spte);
1326 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1329 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1330 if (desc->sptes[i] == spte) {
1331 pte_list_desc_remove_entry(rmap_head,
1332 desc, i, prev_desc);
1339 pr_err("%s: %p many->many\n", __func__, spte);
1344 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1346 mmu_spte_clear_track_bits(sptep);
1347 __pte_list_remove(sptep, rmap_head);
1350 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1351 struct kvm_memory_slot *slot)
1355 idx = gfn_to_index(gfn, slot->base_gfn, level);
1356 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1359 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1360 struct kvm_mmu_page *sp)
1362 struct kvm_memslots *slots;
1363 struct kvm_memory_slot *slot;
1365 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1366 slot = __gfn_to_memslot(slots, gfn);
1367 return __gfn_to_rmap(gfn, sp->role.level, slot);
1370 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1372 struct kvm_mmu_memory_cache *cache;
1374 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1375 return mmu_memory_cache_free_objects(cache);
1378 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1380 struct kvm_mmu_page *sp;
1381 struct kvm_rmap_head *rmap_head;
1383 sp = page_header(__pa(spte));
1384 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1385 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1386 return pte_list_add(vcpu, spte, rmap_head);
1389 static void rmap_remove(struct kvm *kvm, u64 *spte)
1391 struct kvm_mmu_page *sp;
1393 struct kvm_rmap_head *rmap_head;
1395 sp = page_header(__pa(spte));
1396 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1397 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1398 __pte_list_remove(spte, rmap_head);
1402 * Used by the following functions to iterate through the sptes linked by a
1403 * rmap. All fields are private and not assumed to be used outside.
1405 struct rmap_iterator {
1406 /* private fields */
1407 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1408 int pos; /* index of the sptep */
1412 * Iteration must be started by this function. This should also be used after
1413 * removing/dropping sptes from the rmap link because in such cases the
1414 * information in the itererator may not be valid.
1416 * Returns sptep if found, NULL otherwise.
1418 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1419 struct rmap_iterator *iter)
1423 if (!rmap_head->val)
1426 if (!(rmap_head->val & 1)) {
1428 sptep = (u64 *)rmap_head->val;
1432 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1434 sptep = iter->desc->sptes[iter->pos];
1436 BUG_ON(!is_shadow_present_pte(*sptep));
1441 * Must be used with a valid iterator: e.g. after rmap_get_first().
1443 * Returns sptep if found, NULL otherwise.
1445 static u64 *rmap_get_next(struct rmap_iterator *iter)
1450 if (iter->pos < PTE_LIST_EXT - 1) {
1452 sptep = iter->desc->sptes[iter->pos];
1457 iter->desc = iter->desc->more;
1461 /* desc->sptes[0] cannot be NULL */
1462 sptep = iter->desc->sptes[iter->pos];
1469 BUG_ON(!is_shadow_present_pte(*sptep));
1473 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1474 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1475 _spte_; _spte_ = rmap_get_next(_iter_))
1477 static void drop_spte(struct kvm *kvm, u64 *sptep)
1479 if (mmu_spte_clear_track_bits(sptep))
1480 rmap_remove(kvm, sptep);
1484 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1486 if (is_large_pte(*sptep)) {
1487 WARN_ON(page_header(__pa(sptep))->role.level ==
1488 PT_PAGE_TABLE_LEVEL);
1489 drop_spte(kvm, sptep);
1497 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1499 if (__drop_large_spte(vcpu->kvm, sptep)) {
1500 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1502 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1503 KVM_PAGES_PER_HPAGE(sp->role.level));
1508 * Write-protect on the specified @sptep, @pt_protect indicates whether
1509 * spte write-protection is caused by protecting shadow page table.
1511 * Note: write protection is difference between dirty logging and spte
1513 * - for dirty logging, the spte can be set to writable at anytime if
1514 * its dirty bitmap is properly set.
1515 * - for spte protection, the spte can be writable only after unsync-ing
1518 * Return true if tlb need be flushed.
1520 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1524 if (!is_writable_pte(spte) &&
1525 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1528 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1531 spte &= ~SPTE_MMU_WRITEABLE;
1532 spte = spte & ~PT_WRITABLE_MASK;
1534 return mmu_spte_update(sptep, spte);
1537 static bool __rmap_write_protect(struct kvm *kvm,
1538 struct kvm_rmap_head *rmap_head,
1542 struct rmap_iterator iter;
1545 for_each_rmap_spte(rmap_head, &iter, sptep)
1546 flush |= spte_write_protect(sptep, pt_protect);
1551 static bool spte_clear_dirty(u64 *sptep)
1555 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1557 spte &= ~shadow_dirty_mask;
1559 return mmu_spte_update(sptep, spte);
1562 static bool wrprot_ad_disabled_spte(u64 *sptep)
1564 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1565 (unsigned long *)sptep);
1567 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1569 return was_writable;
1573 * Gets the GFN ready for another round of dirty logging by clearing the
1574 * - D bit on ad-enabled SPTEs, and
1575 * - W bit on ad-disabled SPTEs.
1576 * Returns true iff any D or W bits were cleared.
1578 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1581 struct rmap_iterator iter;
1584 for_each_rmap_spte(rmap_head, &iter, sptep)
1585 if (spte_ad_enabled(*sptep))
1586 flush |= spte_clear_dirty(sptep);
1588 flush |= wrprot_ad_disabled_spte(sptep);
1593 static bool spte_set_dirty(u64 *sptep)
1597 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1599 spte |= shadow_dirty_mask;
1601 return mmu_spte_update(sptep, spte);
1604 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1607 struct rmap_iterator iter;
1610 for_each_rmap_spte(rmap_head, &iter, sptep)
1611 if (spte_ad_enabled(*sptep))
1612 flush |= spte_set_dirty(sptep);
1618 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1619 * @kvm: kvm instance
1620 * @slot: slot to protect
1621 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1622 * @mask: indicates which pages we should protect
1624 * Used when we do not need to care about huge page mappings: e.g. during dirty
1625 * logging we do not have any such mappings.
1627 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1628 struct kvm_memory_slot *slot,
1629 gfn_t gfn_offset, unsigned long mask)
1631 struct kvm_rmap_head *rmap_head;
1634 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1635 PT_PAGE_TABLE_LEVEL, slot);
1636 __rmap_write_protect(kvm, rmap_head, false);
1638 /* clear the first set bit */
1644 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1645 * protect the page if the D-bit isn't supported.
1646 * @kvm: kvm instance
1647 * @slot: slot to clear D-bit
1648 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1649 * @mask: indicates which pages we should clear D-bit
1651 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1653 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1654 struct kvm_memory_slot *slot,
1655 gfn_t gfn_offset, unsigned long mask)
1657 struct kvm_rmap_head *rmap_head;
1660 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1661 PT_PAGE_TABLE_LEVEL, slot);
1662 __rmap_clear_dirty(kvm, rmap_head);
1664 /* clear the first set bit */
1668 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1671 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1674 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1675 * enable dirty logging for them.
1677 * Used when we do not need to care about huge page mappings: e.g. during dirty
1678 * logging we do not have any such mappings.
1680 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1681 struct kvm_memory_slot *slot,
1682 gfn_t gfn_offset, unsigned long mask)
1684 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1685 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1688 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1692 * kvm_arch_write_log_dirty - emulate dirty page logging
1693 * @vcpu: Guest mode vcpu
1695 * Emulate arch specific page modification logging for the
1698 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1700 if (kvm_x86_ops->write_log_dirty)
1701 return kvm_x86_ops->write_log_dirty(vcpu);
1706 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1707 struct kvm_memory_slot *slot, u64 gfn)
1709 struct kvm_rmap_head *rmap_head;
1711 bool write_protected = false;
1713 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1714 rmap_head = __gfn_to_rmap(gfn, i, slot);
1715 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1718 return write_protected;
1721 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1723 struct kvm_memory_slot *slot;
1725 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1726 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1729 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1732 struct rmap_iterator iter;
1735 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1736 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1738 pte_list_remove(rmap_head, sptep);
1745 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1746 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1749 return kvm_zap_rmapp(kvm, rmap_head);
1752 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1753 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1757 struct rmap_iterator iter;
1760 pte_t *ptep = (pte_t *)data;
1763 WARN_ON(pte_huge(*ptep));
1764 new_pfn = pte_pfn(*ptep);
1767 for_each_rmap_spte(rmap_head, &iter, sptep) {
1768 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1769 sptep, *sptep, gfn, level);
1773 if (pte_write(*ptep)) {
1774 pte_list_remove(rmap_head, sptep);
1777 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1778 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1780 new_spte &= ~PT_WRITABLE_MASK;
1781 new_spte &= ~SPTE_HOST_WRITEABLE;
1783 new_spte = mark_spte_for_access_track(new_spte);
1785 mmu_spte_clear_track_bits(sptep);
1786 mmu_spte_set(sptep, new_spte);
1790 if (need_flush && kvm_available_flush_tlb_with_range()) {
1791 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1798 struct slot_rmap_walk_iterator {
1800 struct kvm_memory_slot *slot;
1806 /* output fields. */
1808 struct kvm_rmap_head *rmap;
1811 /* private field. */
1812 struct kvm_rmap_head *end_rmap;
1816 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1818 iterator->level = level;
1819 iterator->gfn = iterator->start_gfn;
1820 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1821 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1826 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1827 struct kvm_memory_slot *slot, int start_level,
1828 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1830 iterator->slot = slot;
1831 iterator->start_level = start_level;
1832 iterator->end_level = end_level;
1833 iterator->start_gfn = start_gfn;
1834 iterator->end_gfn = end_gfn;
1836 rmap_walk_init_level(iterator, iterator->start_level);
1839 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1841 return !!iterator->rmap;
1844 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1846 if (++iterator->rmap <= iterator->end_rmap) {
1847 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1851 if (++iterator->level > iterator->end_level) {
1852 iterator->rmap = NULL;
1856 rmap_walk_init_level(iterator, iterator->level);
1859 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1860 _start_gfn, _end_gfn, _iter_) \
1861 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1862 _end_level_, _start_gfn, _end_gfn); \
1863 slot_rmap_walk_okay(_iter_); \
1864 slot_rmap_walk_next(_iter_))
1866 static int kvm_handle_hva_range(struct kvm *kvm,
1867 unsigned long start,
1870 int (*handler)(struct kvm *kvm,
1871 struct kvm_rmap_head *rmap_head,
1872 struct kvm_memory_slot *slot,
1875 unsigned long data))
1877 struct kvm_memslots *slots;
1878 struct kvm_memory_slot *memslot;
1879 struct slot_rmap_walk_iterator iterator;
1883 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1884 slots = __kvm_memslots(kvm, i);
1885 kvm_for_each_memslot(memslot, slots) {
1886 unsigned long hva_start, hva_end;
1887 gfn_t gfn_start, gfn_end;
1889 hva_start = max(start, memslot->userspace_addr);
1890 hva_end = min(end, memslot->userspace_addr +
1891 (memslot->npages << PAGE_SHIFT));
1892 if (hva_start >= hva_end)
1895 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1896 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1898 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1899 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1901 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1902 PT_MAX_HUGEPAGE_LEVEL,
1903 gfn_start, gfn_end - 1,
1905 ret |= handler(kvm, iterator.rmap, memslot,
1906 iterator.gfn, iterator.level, data);
1913 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1915 int (*handler)(struct kvm *kvm,
1916 struct kvm_rmap_head *rmap_head,
1917 struct kvm_memory_slot *slot,
1918 gfn_t gfn, int level,
1919 unsigned long data))
1921 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1924 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1926 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1929 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1931 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1934 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1935 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1939 struct rmap_iterator uninitialized_var(iter);
1942 for_each_rmap_spte(rmap_head, &iter, sptep)
1943 young |= mmu_spte_age(sptep);
1945 trace_kvm_age_page(gfn, level, slot, young);
1949 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1950 struct kvm_memory_slot *slot, gfn_t gfn,
1951 int level, unsigned long data)
1954 struct rmap_iterator iter;
1956 for_each_rmap_spte(rmap_head, &iter, sptep)
1957 if (is_accessed_spte(*sptep))
1962 #define RMAP_RECYCLE_THRESHOLD 1000
1964 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1966 struct kvm_rmap_head *rmap_head;
1967 struct kvm_mmu_page *sp;
1969 sp = page_header(__pa(spte));
1971 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1973 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1974 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1975 KVM_PAGES_PER_HPAGE(sp->role.level));
1978 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1980 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
1983 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1985 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1989 static int is_empty_shadow_page(u64 *spt)
1994 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1995 if (is_shadow_present_pte(*pos)) {
1996 printk(KERN_ERR "%s: %p %llx\n", __func__,
2005 * This value is the sum of all of the kvm instances's
2006 * kvm->arch.n_used_mmu_pages values. We need a global,
2007 * aggregate version in order to make the slab shrinker
2010 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
2012 kvm->arch.n_used_mmu_pages += nr;
2013 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2016 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2018 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2019 hlist_del(&sp->hash_link);
2020 list_del(&sp->link);
2021 free_page((unsigned long)sp->spt);
2022 if (!sp->role.direct)
2023 free_page((unsigned long)sp->gfns);
2024 kmem_cache_free(mmu_page_header_cache, sp);
2027 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2029 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2032 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2033 struct kvm_mmu_page *sp, u64 *parent_pte)
2038 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2041 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2044 __pte_list_remove(parent_pte, &sp->parent_ptes);
2047 static void drop_parent_pte(struct kvm_mmu_page *sp,
2050 mmu_page_remove_parent_pte(sp, parent_pte);
2051 mmu_spte_clear_no_track(parent_pte);
2054 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2056 struct kvm_mmu_page *sp;
2058 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2059 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2061 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2062 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2063 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2064 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2068 static void mark_unsync(u64 *spte);
2069 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2072 struct rmap_iterator iter;
2074 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2079 static void mark_unsync(u64 *spte)
2081 struct kvm_mmu_page *sp;
2084 sp = page_header(__pa(spte));
2085 index = spte - sp->spt;
2086 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2088 if (sp->unsync_children++)
2090 kvm_mmu_mark_parents_unsync(sp);
2093 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2094 struct kvm_mmu_page *sp)
2099 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2103 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2104 struct kvm_mmu_page *sp, u64 *spte,
2110 #define KVM_PAGE_ARRAY_NR 16
2112 struct kvm_mmu_pages {
2113 struct mmu_page_and_offset {
2114 struct kvm_mmu_page *sp;
2116 } page[KVM_PAGE_ARRAY_NR];
2120 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2126 for (i=0; i < pvec->nr; i++)
2127 if (pvec->page[i].sp == sp)
2130 pvec->page[pvec->nr].sp = sp;
2131 pvec->page[pvec->nr].idx = idx;
2133 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2136 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2138 --sp->unsync_children;
2139 WARN_ON((int)sp->unsync_children < 0);
2140 __clear_bit(idx, sp->unsync_child_bitmap);
2143 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2144 struct kvm_mmu_pages *pvec)
2146 int i, ret, nr_unsync_leaf = 0;
2148 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2149 struct kvm_mmu_page *child;
2150 u64 ent = sp->spt[i];
2152 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2153 clear_unsync_child_bit(sp, i);
2157 child = page_header(ent & PT64_BASE_ADDR_MASK);
2159 if (child->unsync_children) {
2160 if (mmu_pages_add(pvec, child, i))
2163 ret = __mmu_unsync_walk(child, pvec);
2165 clear_unsync_child_bit(sp, i);
2167 } else if (ret > 0) {
2168 nr_unsync_leaf += ret;
2171 } else if (child->unsync) {
2173 if (mmu_pages_add(pvec, child, i))
2176 clear_unsync_child_bit(sp, i);
2179 return nr_unsync_leaf;
2182 #define INVALID_INDEX (-1)
2184 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2185 struct kvm_mmu_pages *pvec)
2188 if (!sp->unsync_children)
2191 mmu_pages_add(pvec, sp, INVALID_INDEX);
2192 return __mmu_unsync_walk(sp, pvec);
2195 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2197 WARN_ON(!sp->unsync);
2198 trace_kvm_mmu_sync_page(sp);
2200 --kvm->stat.mmu_unsync;
2203 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2204 struct list_head *invalid_list);
2205 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2206 struct list_head *invalid_list);
2209 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2210 hlist_for_each_entry(_sp, \
2211 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2212 if ((_sp)->role.invalid) { \
2215 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2216 for_each_valid_sp(_kvm, _sp, _gfn) \
2217 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2219 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2221 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2224 /* @sp->gfn should be write-protected at the call site */
2225 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2226 struct list_head *invalid_list)
2228 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2229 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2230 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2237 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2238 struct list_head *invalid_list,
2241 if (!remote_flush && list_empty(invalid_list))
2244 if (!list_empty(invalid_list))
2245 kvm_mmu_commit_zap_page(kvm, invalid_list);
2247 kvm_flush_remote_tlbs(kvm);
2251 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2252 struct list_head *invalid_list,
2253 bool remote_flush, bool local_flush)
2255 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2259 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2262 #ifdef CONFIG_KVM_MMU_AUDIT
2263 #include "mmu_audit.c"
2265 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2266 static void mmu_audit_disable(void) { }
2269 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2270 struct list_head *invalid_list)
2272 kvm_unlink_unsync_page(vcpu->kvm, sp);
2273 return __kvm_sync_page(vcpu, sp, invalid_list);
2276 /* @gfn should be write-protected at the call site */
2277 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2278 struct list_head *invalid_list)
2280 struct kvm_mmu_page *s;
2283 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2287 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2288 ret |= kvm_sync_page(vcpu, s, invalid_list);
2294 struct mmu_page_path {
2295 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2296 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2299 #define for_each_sp(pvec, sp, parents, i) \
2300 for (i = mmu_pages_first(&pvec, &parents); \
2301 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2302 i = mmu_pages_next(&pvec, &parents, i))
2304 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2305 struct mmu_page_path *parents,
2310 for (n = i+1; n < pvec->nr; n++) {
2311 struct kvm_mmu_page *sp = pvec->page[n].sp;
2312 unsigned idx = pvec->page[n].idx;
2313 int level = sp->role.level;
2315 parents->idx[level-1] = idx;
2316 if (level == PT_PAGE_TABLE_LEVEL)
2319 parents->parent[level-2] = sp;
2325 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2326 struct mmu_page_path *parents)
2328 struct kvm_mmu_page *sp;
2334 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2336 sp = pvec->page[0].sp;
2337 level = sp->role.level;
2338 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2340 parents->parent[level-2] = sp;
2342 /* Also set up a sentinel. Further entries in pvec are all
2343 * children of sp, so this element is never overwritten.
2345 parents->parent[level-1] = NULL;
2346 return mmu_pages_next(pvec, parents, 0);
2349 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2351 struct kvm_mmu_page *sp;
2352 unsigned int level = 0;
2355 unsigned int idx = parents->idx[level];
2356 sp = parents->parent[level];
2360 WARN_ON(idx == INVALID_INDEX);
2361 clear_unsync_child_bit(sp, idx);
2363 } while (!sp->unsync_children);
2366 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2367 struct kvm_mmu_page *parent)
2370 struct kvm_mmu_page *sp;
2371 struct mmu_page_path parents;
2372 struct kvm_mmu_pages pages;
2373 LIST_HEAD(invalid_list);
2376 while (mmu_unsync_walk(parent, &pages)) {
2377 bool protected = false;
2379 for_each_sp(pages, sp, parents, i)
2380 protected |= rmap_write_protect(vcpu, sp->gfn);
2383 kvm_flush_remote_tlbs(vcpu->kvm);
2387 for_each_sp(pages, sp, parents, i) {
2388 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2389 mmu_pages_clear_parents(&parents);
2391 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2392 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2393 cond_resched_lock(&vcpu->kvm->mmu_lock);
2398 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2401 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2403 atomic_set(&sp->write_flooding_count, 0);
2406 static void clear_sp_write_flooding_count(u64 *spte)
2408 struct kvm_mmu_page *sp = page_header(__pa(spte));
2410 __clear_sp_write_flooding_count(sp);
2413 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2420 union kvm_mmu_page_role role;
2422 struct kvm_mmu_page *sp;
2423 bool need_sync = false;
2426 LIST_HEAD(invalid_list);
2428 role = vcpu->arch.mmu->mmu_role.base;
2430 role.direct = direct;
2432 role.gpte_is_8_bytes = true;
2433 role.access = access;
2434 if (!vcpu->arch.mmu->direct_map
2435 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2436 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2437 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2438 role.quadrant = quadrant;
2440 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2441 if (sp->gfn != gfn) {
2446 if (!need_sync && sp->unsync)
2449 if (sp->role.word != role.word)
2453 /* The page is good, but __kvm_sync_page might still end
2454 * up zapping it. If so, break in order to rebuild it.
2456 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2459 WARN_ON(!list_empty(&invalid_list));
2460 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2463 if (sp->unsync_children)
2464 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2466 __clear_sp_write_flooding_count(sp);
2467 trace_kvm_mmu_get_page(sp, false);
2471 ++vcpu->kvm->stat.mmu_cache_miss;
2473 sp = kvm_mmu_alloc_page(vcpu, direct);
2477 hlist_add_head(&sp->hash_link,
2478 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2481 * we should do write protection before syncing pages
2482 * otherwise the content of the synced shadow page may
2483 * be inconsistent with guest page table.
2485 account_shadowed(vcpu->kvm, sp);
2486 if (level == PT_PAGE_TABLE_LEVEL &&
2487 rmap_write_protect(vcpu, gfn))
2488 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2490 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2491 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2493 clear_page(sp->spt);
2494 trace_kvm_mmu_get_page(sp, true);
2496 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2498 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2499 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2503 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2504 struct kvm_vcpu *vcpu, hpa_t root,
2507 iterator->addr = addr;
2508 iterator->shadow_addr = root;
2509 iterator->level = vcpu->arch.mmu->shadow_root_level;
2511 if (iterator->level == PT64_ROOT_4LEVEL &&
2512 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2513 !vcpu->arch.mmu->direct_map)
2516 if (iterator->level == PT32E_ROOT_LEVEL) {
2518 * prev_root is currently only used for 64-bit hosts. So only
2519 * the active root_hpa is valid here.
2521 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2523 iterator->shadow_addr
2524 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2525 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2527 if (!iterator->shadow_addr)
2528 iterator->level = 0;
2532 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2533 struct kvm_vcpu *vcpu, u64 addr)
2535 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2539 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2541 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2544 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2545 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2549 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2552 if (is_last_spte(spte, iterator->level)) {
2553 iterator->level = 0;
2557 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2561 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2563 __shadow_walk_next(iterator, *iterator->sptep);
2566 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2567 struct kvm_mmu_page *sp)
2571 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2573 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2574 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2576 if (sp_ad_disabled(sp))
2577 spte |= shadow_acc_track_value;
2579 spte |= shadow_accessed_mask;
2581 mmu_spte_set(sptep, spte);
2583 mmu_page_add_parent_pte(vcpu, sp, sptep);
2585 if (sp->unsync_children || sp->unsync)
2589 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2590 unsigned direct_access)
2592 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2593 struct kvm_mmu_page *child;
2596 * For the direct sp, if the guest pte's dirty bit
2597 * changed form clean to dirty, it will corrupt the
2598 * sp's access: allow writable in the read-only sp,
2599 * so we should update the spte at this point to get
2600 * a new sp with the correct access.
2602 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2603 if (child->role.access == direct_access)
2606 drop_parent_pte(child, sptep);
2607 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2611 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2615 struct kvm_mmu_page *child;
2618 if (is_shadow_present_pte(pte)) {
2619 if (is_last_spte(pte, sp->role.level)) {
2620 drop_spte(kvm, spte);
2621 if (is_large_pte(pte))
2624 child = page_header(pte & PT64_BASE_ADDR_MASK);
2625 drop_parent_pte(child, spte);
2630 if (is_mmio_spte(pte))
2631 mmu_spte_clear_no_track(spte);
2636 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2637 struct kvm_mmu_page *sp)
2641 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2642 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2645 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2648 struct rmap_iterator iter;
2650 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2651 drop_parent_pte(sp, sptep);
2654 static int mmu_zap_unsync_children(struct kvm *kvm,
2655 struct kvm_mmu_page *parent,
2656 struct list_head *invalid_list)
2659 struct mmu_page_path parents;
2660 struct kvm_mmu_pages pages;
2662 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2665 while (mmu_unsync_walk(parent, &pages)) {
2666 struct kvm_mmu_page *sp;
2668 for_each_sp(pages, sp, parents, i) {
2669 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2670 mmu_pages_clear_parents(&parents);
2678 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2679 struct kvm_mmu_page *sp,
2680 struct list_head *invalid_list,
2685 trace_kvm_mmu_prepare_zap_page(sp);
2686 ++kvm->stat.mmu_shadow_zapped;
2687 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2688 kvm_mmu_page_unlink_children(kvm, sp);
2689 kvm_mmu_unlink_parents(kvm, sp);
2691 /* Zapping children means active_mmu_pages has become unstable. */
2692 list_unstable = *nr_zapped;
2694 if (!sp->role.invalid && !sp->role.direct)
2695 unaccount_shadowed(kvm, sp);
2698 kvm_unlink_unsync_page(kvm, sp);
2699 if (!sp->root_count) {
2702 list_move(&sp->link, invalid_list);
2703 kvm_mod_used_mmu_pages(kvm, -1);
2705 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2707 if (!sp->role.invalid)
2708 kvm_reload_remote_mmus(kvm);
2711 sp->role.invalid = 1;
2712 return list_unstable;
2715 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2716 struct list_head *invalid_list)
2720 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2724 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2725 struct list_head *invalid_list)
2727 struct kvm_mmu_page *sp, *nsp;
2729 if (list_empty(invalid_list))
2733 * We need to make sure everyone sees our modifications to
2734 * the page tables and see changes to vcpu->mode here. The barrier
2735 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2736 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2738 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2739 * guest mode and/or lockless shadow page table walks.
2741 kvm_flush_remote_tlbs(kvm);
2743 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2744 WARN_ON(!sp->role.invalid || sp->root_count);
2745 kvm_mmu_free_page(sp);
2749 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2750 struct list_head *invalid_list)
2752 struct kvm_mmu_page *sp;
2754 if (list_empty(&kvm->arch.active_mmu_pages))
2757 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2758 struct kvm_mmu_page, link);
2759 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2763 * Changing the number of mmu pages allocated to the vm
2764 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2766 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
2768 LIST_HEAD(invalid_list);
2770 spin_lock(&kvm->mmu_lock);
2772 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2773 /* Need to free some mmu pages to achieve the goal. */
2774 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2775 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2778 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2779 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2782 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2784 spin_unlock(&kvm->mmu_lock);
2787 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2789 struct kvm_mmu_page *sp;
2790 LIST_HEAD(invalid_list);
2793 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2795 spin_lock(&kvm->mmu_lock);
2796 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2797 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2800 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2802 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2803 spin_unlock(&kvm->mmu_lock);
2807 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2809 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2811 trace_kvm_mmu_unsync_page(sp);
2812 ++vcpu->kvm->stat.mmu_unsync;
2815 kvm_mmu_mark_parents_unsync(sp);
2818 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2821 struct kvm_mmu_page *sp;
2823 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2826 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2833 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2834 kvm_unsync_page(vcpu, sp);
2838 * We need to ensure that the marking of unsync pages is visible
2839 * before the SPTE is updated to allow writes because
2840 * kvm_mmu_sync_roots() checks the unsync flags without holding
2841 * the MMU lock and so can race with this. If the SPTE was updated
2842 * before the page had been marked as unsync-ed, something like the
2843 * following could happen:
2846 * ---------------------------------------------------------------------
2847 * 1.2 Host updates SPTE
2849 * 2.1 Guest writes a GPTE for GVA X.
2850 * (GPTE being in the guest page table shadowed
2851 * by the SP from CPU 1.)
2852 * This reads SPTE during the page table walk.
2853 * Since SPTE.W is read as 1, there is no
2856 * 2.2 Guest issues TLB flush.
2857 * That causes a VM Exit.
2859 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2860 * Since it is false, so it just returns.
2862 * 2.4 Guest accesses GVA X.
2863 * Since the mapping in the SP was not updated,
2864 * so the old mapping for GVA X incorrectly
2868 * (sp->unsync = true)
2870 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2871 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2872 * pairs with this write barrier.
2879 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2882 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2884 * Some reserved pages, such as those from NVDIMM
2885 * DAX devices, are not for MMIO, and can be mapped
2886 * with cached memory type for better performance.
2887 * However, the above check misconceives those pages
2888 * as MMIO, and results in KVM mapping them with UC
2889 * memory type, which would hurt the performance.
2890 * Therefore, we check the host memory type in addition
2891 * and only treat UC/UC-/WC pages as MMIO.
2893 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2898 /* Bits which may be returned by set_spte() */
2899 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2900 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2902 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2903 unsigned pte_access, int level,
2904 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2905 bool can_unsync, bool host_writable)
2909 struct kvm_mmu_page *sp;
2911 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2914 sp = page_header(__pa(sptep));
2915 if (sp_ad_disabled(sp))
2916 spte |= shadow_acc_track_value;
2919 * For the EPT case, shadow_present_mask is 0 if hardware
2920 * supports exec-only page table entries. In that case,
2921 * ACC_USER_MASK and shadow_user_mask are used to represent
2922 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2924 spte |= shadow_present_mask;
2926 spte |= spte_shadow_accessed_mask(spte);
2928 if (pte_access & ACC_EXEC_MASK)
2929 spte |= shadow_x_mask;
2931 spte |= shadow_nx_mask;
2933 if (pte_access & ACC_USER_MASK)
2934 spte |= shadow_user_mask;
2936 if (level > PT_PAGE_TABLE_LEVEL)
2937 spte |= PT_PAGE_SIZE_MASK;
2939 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2940 kvm_is_mmio_pfn(pfn));
2943 spte |= SPTE_HOST_WRITEABLE;
2945 pte_access &= ~ACC_WRITE_MASK;
2947 if (!kvm_is_mmio_pfn(pfn))
2948 spte |= shadow_me_mask;
2950 spte |= (u64)pfn << PAGE_SHIFT;
2952 if (pte_access & ACC_WRITE_MASK) {
2955 * Other vcpu creates new sp in the window between
2956 * mapping_level() and acquiring mmu-lock. We can
2957 * allow guest to retry the access, the mapping can
2958 * be fixed if guest refault.
2960 if (level > PT_PAGE_TABLE_LEVEL &&
2961 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
2964 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
2967 * Optimization: for pte sync, if spte was writable the hash
2968 * lookup is unnecessary (and expensive). Write protection
2969 * is responsibility of mmu_get_page / kvm_sync_page.
2970 * Same reasoning can be applied to dirty page accounting.
2972 if (!can_unsync && is_writable_pte(*sptep))
2975 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
2976 pgprintk("%s: found shadow page for %llx, marking ro\n",
2978 ret |= SET_SPTE_WRITE_PROTECTED_PT;
2979 pte_access &= ~ACC_WRITE_MASK;
2980 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
2984 if (pte_access & ACC_WRITE_MASK) {
2985 kvm_vcpu_mark_page_dirty(vcpu, gfn);
2986 spte |= spte_shadow_dirty_mask(spte);
2990 spte = mark_spte_for_access_track(spte);
2993 if (mmu_spte_update(sptep, spte))
2994 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
2999 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3000 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3001 bool speculative, bool host_writable)
3003 int was_rmapped = 0;
3006 int ret = RET_PF_RETRY;
3009 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3010 *sptep, write_fault, gfn);
3012 if (is_shadow_present_pte(*sptep)) {
3014 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3015 * the parent of the now unreachable PTE.
3017 if (level > PT_PAGE_TABLE_LEVEL &&
3018 !is_large_pte(*sptep)) {
3019 struct kvm_mmu_page *child;
3022 child = page_header(pte & PT64_BASE_ADDR_MASK);
3023 drop_parent_pte(child, sptep);
3025 } else if (pfn != spte_to_pfn(*sptep)) {
3026 pgprintk("hfn old %llx new %llx\n",
3027 spte_to_pfn(*sptep), pfn);
3028 drop_spte(vcpu->kvm, sptep);
3034 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3035 speculative, true, host_writable);
3036 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3038 ret = RET_PF_EMULATE;
3039 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3042 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3043 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3044 KVM_PAGES_PER_HPAGE(level));
3046 if (unlikely(is_mmio_spte(*sptep)))
3047 ret = RET_PF_EMULATE;
3049 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3050 pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
3051 is_large_pte(*sptep)? "2MB" : "4kB",
3052 *sptep & PT_WRITABLE_MASK ? "RW" : "R", gfn,
3054 if (!was_rmapped && is_large_pte(*sptep))
3055 ++vcpu->kvm->stat.lpages;
3057 if (is_shadow_present_pte(*sptep)) {
3059 rmap_count = rmap_add(vcpu, sptep, gfn);
3060 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3061 rmap_recycle(vcpu, sptep, gfn);
3065 kvm_release_pfn_clean(pfn);
3070 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3073 struct kvm_memory_slot *slot;
3075 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3077 return KVM_PFN_ERR_FAULT;
3079 return gfn_to_pfn_memslot_atomic(slot, gfn);
3082 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3083 struct kvm_mmu_page *sp,
3084 u64 *start, u64 *end)
3086 struct page *pages[PTE_PREFETCH_NUM];
3087 struct kvm_memory_slot *slot;
3088 unsigned access = sp->role.access;
3092 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3093 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3097 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3101 for (i = 0; i < ret; i++, gfn++, start++)
3102 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3103 page_to_pfn(pages[i]), true, true);
3108 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3109 struct kvm_mmu_page *sp, u64 *sptep)
3111 u64 *spte, *start = NULL;
3114 WARN_ON(!sp->role.direct);
3116 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3119 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3120 if (is_shadow_present_pte(*spte) || spte == sptep) {
3123 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3131 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3133 struct kvm_mmu_page *sp;
3135 sp = page_header(__pa(sptep));
3138 * Without accessed bits, there's no way to distinguish between
3139 * actually accessed translations and prefetched, so disable pte
3140 * prefetch if accessed bits aren't available.
3142 if (sp_ad_disabled(sp))
3145 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3148 __direct_pte_prefetch(vcpu, sp, sptep);
3151 static int __direct_map(struct kvm_vcpu *vcpu, int write, int map_writable,
3152 int level, gfn_t gfn, kvm_pfn_t pfn, bool prefault)
3154 struct kvm_shadow_walk_iterator iterator;
3155 struct kvm_mmu_page *sp;
3159 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3162 for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
3163 if (iterator.level == level) {
3164 emulate = mmu_set_spte(vcpu, iterator.sptep, ACC_ALL,
3165 write, level, gfn, pfn, prefault,
3167 direct_pte_prefetch(vcpu, iterator.sptep);
3168 ++vcpu->stat.pf_fixed;
3172 drop_large_spte(vcpu, iterator.sptep);
3173 if (!is_shadow_present_pte(*iterator.sptep)) {
3174 u64 base_addr = iterator.addr;
3176 base_addr &= PT64_LVL_ADDR_MASK(iterator.level);
3177 pseudo_gfn = base_addr >> PAGE_SHIFT;
3178 sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
3179 iterator.level - 1, 1, ACC_ALL);
3181 link_shadow_page(vcpu, iterator.sptep, sp);
3187 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3189 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3192 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3195 * Do not cache the mmio info caused by writing the readonly gfn
3196 * into the spte otherwise read access on readonly gfn also can
3197 * caused mmio page fault and treat it as mmio access.
3199 if (pfn == KVM_PFN_ERR_RO_FAULT)
3200 return RET_PF_EMULATE;
3202 if (pfn == KVM_PFN_ERR_HWPOISON) {
3203 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3204 return RET_PF_RETRY;
3210 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3211 gfn_t *gfnp, kvm_pfn_t *pfnp,
3214 kvm_pfn_t pfn = *pfnp;
3216 int level = *levelp;
3219 * Check if it's a transparent hugepage. If this would be an
3220 * hugetlbfs page, level wouldn't be set to
3221 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3224 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3225 level == PT_PAGE_TABLE_LEVEL &&
3226 PageTransCompoundMap(pfn_to_page(pfn)) &&
3227 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3230 * mmu_notifier_retry was successful and we hold the
3231 * mmu_lock here, so the pmd can't become splitting
3232 * from under us, and in turn
3233 * __split_huge_page_refcount() can't run from under
3234 * us and we can safely transfer the refcount from
3235 * PG_tail to PG_head as we switch the pfn to tail to
3238 *levelp = level = PT_DIRECTORY_LEVEL;
3239 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3240 VM_BUG_ON((gfn & mask) != (pfn & mask));
3244 kvm_release_pfn_clean(pfn);
3252 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3253 kvm_pfn_t pfn, unsigned access, int *ret_val)
3255 /* The pfn is invalid, report the error! */
3256 if (unlikely(is_error_pfn(pfn))) {
3257 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3261 if (unlikely(is_noslot_pfn(pfn)))
3262 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
3267 static bool page_fault_can_be_fast(u32 error_code)
3270 * Do not fix the mmio spte with invalid generation number which
3271 * need to be updated by slow page fault path.
3273 if (unlikely(error_code & PFERR_RSVD_MASK))
3276 /* See if the page fault is due to an NX violation */
3277 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3278 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3282 * #PF can be fast if:
3283 * 1. The shadow page table entry is not present, which could mean that
3284 * the fault is potentially caused by access tracking (if enabled).
3285 * 2. The shadow page table entry is present and the fault
3286 * is caused by write-protect, that means we just need change the W
3287 * bit of the spte which can be done out of mmu-lock.
3289 * However, if access tracking is disabled we know that a non-present
3290 * page must be a genuine page fault where we have to create a new SPTE.
3291 * So, if access tracking is disabled, we return true only for write
3292 * accesses to a present page.
3295 return shadow_acc_track_mask != 0 ||
3296 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3297 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3301 * Returns true if the SPTE was fixed successfully. Otherwise,
3302 * someone else modified the SPTE from its original value.
3305 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3306 u64 *sptep, u64 old_spte, u64 new_spte)
3310 WARN_ON(!sp->role.direct);
3313 * Theoretically we could also set dirty bit (and flush TLB) here in
3314 * order to eliminate unnecessary PML logging. See comments in
3315 * set_spte. But fast_page_fault is very unlikely to happen with PML
3316 * enabled, so we do not do this. This might result in the same GPA
3317 * to be logged in PML buffer again when the write really happens, and
3318 * eventually to be called by mark_page_dirty twice. But it's also no
3319 * harm. This also avoids the TLB flush needed after setting dirty bit
3320 * so non-PML cases won't be impacted.
3322 * Compare with set_spte where instead shadow_dirty_mask is set.
3324 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3327 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3329 * The gfn of direct spte is stable since it is
3330 * calculated by sp->gfn.
3332 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3333 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3339 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3341 if (fault_err_code & PFERR_FETCH_MASK)
3342 return is_executable_pte(spte);
3344 if (fault_err_code & PFERR_WRITE_MASK)
3345 return is_writable_pte(spte);
3347 /* Fault was on Read access */
3348 return spte & PT_PRESENT_MASK;
3353 * - true: let the vcpu to access on the same address again.
3354 * - false: let the real page fault path to fix it.
3356 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3359 struct kvm_shadow_walk_iterator iterator;
3360 struct kvm_mmu_page *sp;
3361 bool fault_handled = false;
3363 uint retry_count = 0;
3365 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3368 if (!page_fault_can_be_fast(error_code))
3371 walk_shadow_page_lockless_begin(vcpu);
3376 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3377 if (!is_shadow_present_pte(spte) ||
3378 iterator.level < level)
3381 sp = page_header(__pa(iterator.sptep));
3382 if (!is_last_spte(spte, sp->role.level))
3386 * Check whether the memory access that caused the fault would
3387 * still cause it if it were to be performed right now. If not,
3388 * then this is a spurious fault caused by TLB lazily flushed,
3389 * or some other CPU has already fixed the PTE after the
3390 * current CPU took the fault.
3392 * Need not check the access of upper level table entries since
3393 * they are always ACC_ALL.
3395 if (is_access_allowed(error_code, spte)) {
3396 fault_handled = true;
3402 if (is_access_track_spte(spte))
3403 new_spte = restore_acc_track_spte(new_spte);
3406 * Currently, to simplify the code, write-protection can
3407 * be removed in the fast path only if the SPTE was
3408 * write-protected for dirty-logging or access tracking.
3410 if ((error_code & PFERR_WRITE_MASK) &&
3411 spte_can_locklessly_be_made_writable(spte))
3413 new_spte |= PT_WRITABLE_MASK;
3416 * Do not fix write-permission on the large spte. Since
3417 * we only dirty the first page into the dirty-bitmap in
3418 * fast_pf_fix_direct_spte(), other pages are missed
3419 * if its slot has dirty logging enabled.
3421 * Instead, we let the slow page fault path create a
3422 * normal spte to fix the access.
3424 * See the comments in kvm_arch_commit_memory_region().
3426 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3430 /* Verify that the fault can be handled in the fast path */
3431 if (new_spte == spte ||
3432 !is_access_allowed(error_code, new_spte))
3436 * Currently, fast page fault only works for direct mapping
3437 * since the gfn is not stable for indirect shadow page. See
3438 * Documentation/virtual/kvm/locking.txt to get more detail.
3440 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3441 iterator.sptep, spte,
3446 if (++retry_count > 4) {
3447 printk_once(KERN_WARNING
3448 "kvm: Fast #PF retrying more than 4 times.\n");
3454 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3455 spte, fault_handled);
3456 walk_shadow_page_lockless_end(vcpu);
3458 return fault_handled;
3461 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3462 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3463 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3465 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3466 gfn_t gfn, bool prefault)
3470 bool force_pt_level = false;
3472 unsigned long mmu_seq;
3473 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3475 level = mapping_level(vcpu, gfn, &force_pt_level);
3476 if (likely(!force_pt_level)) {
3478 * This path builds a PAE pagetable - so we can map
3479 * 2mb pages at maximum. Therefore check if the level
3480 * is larger than that.
3482 if (level > PT_DIRECTORY_LEVEL)
3483 level = PT_DIRECTORY_LEVEL;
3485 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3488 if (fast_page_fault(vcpu, v, level, error_code))
3489 return RET_PF_RETRY;
3491 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3494 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3495 return RET_PF_RETRY;
3497 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3500 spin_lock(&vcpu->kvm->mmu_lock);
3501 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3503 if (make_mmu_pages_available(vcpu) < 0)
3505 if (likely(!force_pt_level))
3506 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
3507 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
3508 spin_unlock(&vcpu->kvm->mmu_lock);
3513 spin_unlock(&vcpu->kvm->mmu_lock);
3514 kvm_release_pfn_clean(pfn);
3515 return RET_PF_RETRY;
3518 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3519 struct list_head *invalid_list)
3521 struct kvm_mmu_page *sp;
3523 if (!VALID_PAGE(*root_hpa))
3526 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3528 if (!sp->root_count && sp->role.invalid)
3529 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3531 *root_hpa = INVALID_PAGE;
3534 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3535 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3536 ulong roots_to_free)
3539 LIST_HEAD(invalid_list);
3540 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3542 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3544 /* Before acquiring the MMU lock, see if we need to do any real work. */
3545 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3546 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3547 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3548 VALID_PAGE(mmu->prev_roots[i].hpa))
3551 if (i == KVM_MMU_NUM_PREV_ROOTS)
3555 spin_lock(&vcpu->kvm->mmu_lock);
3557 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3558 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3559 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3562 if (free_active_root) {
3563 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3564 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3565 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3568 for (i = 0; i < 4; ++i)
3569 if (mmu->pae_root[i] != 0)
3570 mmu_free_root_page(vcpu->kvm,
3573 mmu->root_hpa = INVALID_PAGE;
3578 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3579 spin_unlock(&vcpu->kvm->mmu_lock);
3581 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3583 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3587 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3588 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3595 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3597 struct kvm_mmu_page *sp;
3600 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3601 spin_lock(&vcpu->kvm->mmu_lock);
3602 if(make_mmu_pages_available(vcpu) < 0) {
3603 spin_unlock(&vcpu->kvm->mmu_lock);
3606 sp = kvm_mmu_get_page(vcpu, 0, 0,
3607 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3609 spin_unlock(&vcpu->kvm->mmu_lock);
3610 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3611 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3612 for (i = 0; i < 4; ++i) {
3613 hpa_t root = vcpu->arch.mmu->pae_root[i];
3615 MMU_WARN_ON(VALID_PAGE(root));
3616 spin_lock(&vcpu->kvm->mmu_lock);
3617 if (make_mmu_pages_available(vcpu) < 0) {
3618 spin_unlock(&vcpu->kvm->mmu_lock);
3621 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3622 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3623 root = __pa(sp->spt);
3625 spin_unlock(&vcpu->kvm->mmu_lock);
3626 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3628 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3631 vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3636 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3638 struct kvm_mmu_page *sp;
3640 gfn_t root_gfn, root_cr3;
3643 root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3644 root_gfn = root_cr3 >> PAGE_SHIFT;
3646 if (mmu_check_root(vcpu, root_gfn))
3650 * Do we shadow a long mode page table? If so we need to
3651 * write-protect the guests page table root.
3653 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3654 hpa_t root = vcpu->arch.mmu->root_hpa;
3656 MMU_WARN_ON(VALID_PAGE(root));
3658 spin_lock(&vcpu->kvm->mmu_lock);
3659 if (make_mmu_pages_available(vcpu) < 0) {
3660 spin_unlock(&vcpu->kvm->mmu_lock);
3663 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3664 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3665 root = __pa(sp->spt);
3667 spin_unlock(&vcpu->kvm->mmu_lock);
3668 vcpu->arch.mmu->root_hpa = root;
3673 * We shadow a 32 bit page table. This may be a legacy 2-level
3674 * or a PAE 3-level page table. In either case we need to be aware that
3675 * the shadow page table may be a PAE or a long mode page table.
3677 pm_mask = PT_PRESENT_MASK;
3678 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3679 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3681 for (i = 0; i < 4; ++i) {
3682 hpa_t root = vcpu->arch.mmu->pae_root[i];
3684 MMU_WARN_ON(VALID_PAGE(root));
3685 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3686 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3687 if (!(pdptr & PT_PRESENT_MASK)) {
3688 vcpu->arch.mmu->pae_root[i] = 0;
3691 root_gfn = pdptr >> PAGE_SHIFT;
3692 if (mmu_check_root(vcpu, root_gfn))
3695 spin_lock(&vcpu->kvm->mmu_lock);
3696 if (make_mmu_pages_available(vcpu) < 0) {
3697 spin_unlock(&vcpu->kvm->mmu_lock);
3700 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3702 root = __pa(sp->spt);
3704 spin_unlock(&vcpu->kvm->mmu_lock);
3706 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3708 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3711 * If we shadow a 32 bit page table with a long mode page
3712 * table we enter this path.
3714 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3715 if (vcpu->arch.mmu->lm_root == NULL) {
3717 * The additional page necessary for this is only
3718 * allocated on demand.
3723 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3724 if (lm_root == NULL)
3727 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3729 vcpu->arch.mmu->lm_root = lm_root;
3732 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3736 vcpu->arch.mmu->root_cr3 = root_cr3;
3741 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3743 if (vcpu->arch.mmu->direct_map)
3744 return mmu_alloc_direct_roots(vcpu);
3746 return mmu_alloc_shadow_roots(vcpu);
3749 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3752 struct kvm_mmu_page *sp;
3754 if (vcpu->arch.mmu->direct_map)
3757 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3760 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3762 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3763 hpa_t root = vcpu->arch.mmu->root_hpa;
3764 sp = page_header(root);
3767 * Even if another CPU was marking the SP as unsync-ed
3768 * simultaneously, any guest page table changes are not
3769 * guaranteed to be visible anyway until this VCPU issues a TLB
3770 * flush strictly after those changes are made. We only need to
3771 * ensure that the other CPU sets these flags before any actual
3772 * changes to the page tables are made. The comments in
3773 * mmu_need_write_protect() describe what could go wrong if this
3774 * requirement isn't satisfied.
3776 if (!smp_load_acquire(&sp->unsync) &&
3777 !smp_load_acquire(&sp->unsync_children))
3780 spin_lock(&vcpu->kvm->mmu_lock);
3781 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3783 mmu_sync_children(vcpu, sp);
3785 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3786 spin_unlock(&vcpu->kvm->mmu_lock);
3790 spin_lock(&vcpu->kvm->mmu_lock);
3791 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3793 for (i = 0; i < 4; ++i) {
3794 hpa_t root = vcpu->arch.mmu->pae_root[i];
3796 if (root && VALID_PAGE(root)) {
3797 root &= PT64_BASE_ADDR_MASK;
3798 sp = page_header(root);
3799 mmu_sync_children(vcpu, sp);
3803 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3804 spin_unlock(&vcpu->kvm->mmu_lock);
3806 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3808 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3809 u32 access, struct x86_exception *exception)
3812 exception->error_code = 0;
3816 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3818 struct x86_exception *exception)
3821 exception->error_code = 0;
3822 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3826 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3828 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3830 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3831 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3834 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3836 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3839 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3841 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3844 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3847 * A nested guest cannot use the MMIO cache if it is using nested
3848 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3850 if (mmu_is_nested(vcpu))
3854 return vcpu_match_mmio_gpa(vcpu, addr);
3856 return vcpu_match_mmio_gva(vcpu, addr);
3859 /* return true if reserved bit is detected on spte. */
3861 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3863 struct kvm_shadow_walk_iterator iterator;
3864 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3866 bool reserved = false;
3868 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3871 walk_shadow_page_lockless_begin(vcpu);
3873 for (shadow_walk_init(&iterator, vcpu, addr),
3874 leaf = root = iterator.level;
3875 shadow_walk_okay(&iterator);
3876 __shadow_walk_next(&iterator, spte)) {
3877 spte = mmu_spte_get_lockless(iterator.sptep);
3879 sptes[leaf - 1] = spte;
3882 if (!is_shadow_present_pte(spte))
3885 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3889 walk_shadow_page_lockless_end(vcpu);
3892 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3894 while (root > leaf) {
3895 pr_err("------ spte 0x%llx level %d.\n",
3896 sptes[root - 1], root);
3905 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3910 if (mmio_info_in_cache(vcpu, addr, direct))
3911 return RET_PF_EMULATE;
3913 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3914 if (WARN_ON(reserved))
3917 if (is_mmio_spte(spte)) {
3918 gfn_t gfn = get_mmio_spte_gfn(spte);
3919 unsigned access = get_mmio_spte_access(spte);
3921 if (!check_mmio_spte(vcpu, spte))
3922 return RET_PF_INVALID;
3927 trace_handle_mmio_page_fault(addr, gfn, access);
3928 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3929 return RET_PF_EMULATE;
3933 * If the page table is zapped by other cpus, let CPU fault again on
3936 return RET_PF_RETRY;
3939 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3940 u32 error_code, gfn_t gfn)
3942 if (unlikely(error_code & PFERR_RSVD_MASK))
3945 if (!(error_code & PFERR_PRESENT_MASK) ||
3946 !(error_code & PFERR_WRITE_MASK))
3950 * guest is writing the page which is write tracked which can
3951 * not be fixed by page fault handler.
3953 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3959 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3961 struct kvm_shadow_walk_iterator iterator;
3964 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3967 walk_shadow_page_lockless_begin(vcpu);
3968 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3969 clear_sp_write_flooding_count(iterator.sptep);
3970 if (!is_shadow_present_pte(spte))
3973 walk_shadow_page_lockless_end(vcpu);
3976 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
3977 u32 error_code, bool prefault)
3979 gfn_t gfn = gva >> PAGE_SHIFT;
3982 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
3984 if (page_fault_handle_page_track(vcpu, error_code, gfn))
3985 return RET_PF_EMULATE;
3987 r = mmu_topup_memory_caches(vcpu);
3991 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
3994 return nonpaging_map(vcpu, gva & PAGE_MASK,
3995 error_code, gfn, prefault);
3998 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
4000 struct kvm_arch_async_pf arch;
4002 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4004 arch.direct_map = vcpu->arch.mmu->direct_map;
4005 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4007 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4010 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
4012 if (unlikely(!lapic_in_kernel(vcpu) ||
4013 kvm_event_needs_reinjection(vcpu) ||
4014 vcpu->arch.exception.pending))
4017 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
4020 return kvm_x86_ops->interrupt_allowed(vcpu);
4023 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4024 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4026 struct kvm_memory_slot *slot;
4030 * Don't expose private memslots to L2.
4032 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4033 *pfn = KVM_PFN_NOSLOT;
4037 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4039 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4041 return false; /* *pfn has correct page already */
4043 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4044 trace_kvm_try_async_get_page(gva, gfn);
4045 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4046 trace_kvm_async_pf_doublefault(gva, gfn);
4047 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4049 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4053 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4057 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4058 u64 fault_address, char *insn, int insn_len)
4062 vcpu->arch.l1tf_flush_l1d = true;
4063 switch (vcpu->arch.apf.host_apf_reason) {
4065 trace_kvm_page_fault(fault_address, error_code);
4067 if (kvm_event_needs_reinjection(vcpu))
4068 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4069 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4072 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4073 vcpu->arch.apf.host_apf_reason = 0;
4074 local_irq_disable();
4075 kvm_async_pf_task_wait(fault_address, 0);
4078 case KVM_PV_REASON_PAGE_READY:
4079 vcpu->arch.apf.host_apf_reason = 0;
4080 local_irq_disable();
4081 kvm_async_pf_task_wake(fault_address);
4087 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4090 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4092 int page_num = KVM_PAGES_PER_HPAGE(level);
4094 gfn &= ~(page_num - 1);
4096 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4099 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4105 bool force_pt_level;
4106 gfn_t gfn = gpa >> PAGE_SHIFT;
4107 unsigned long mmu_seq;
4108 int write = error_code & PFERR_WRITE_MASK;
4111 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4113 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4114 return RET_PF_EMULATE;
4116 r = mmu_topup_memory_caches(vcpu);
4120 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4121 PT_DIRECTORY_LEVEL);
4122 level = mapping_level(vcpu, gfn, &force_pt_level);
4123 if (likely(!force_pt_level)) {
4124 if (level > PT_DIRECTORY_LEVEL &&
4125 !check_hugepage_cache_consistency(vcpu, gfn, level))
4126 level = PT_DIRECTORY_LEVEL;
4127 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4130 if (fast_page_fault(vcpu, gpa, level, error_code))
4131 return RET_PF_RETRY;
4133 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4136 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4137 return RET_PF_RETRY;
4139 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4142 spin_lock(&vcpu->kvm->mmu_lock);
4143 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4145 if (make_mmu_pages_available(vcpu) < 0)
4147 if (likely(!force_pt_level))
4148 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
4149 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
4150 spin_unlock(&vcpu->kvm->mmu_lock);
4155 spin_unlock(&vcpu->kvm->mmu_lock);
4156 kvm_release_pfn_clean(pfn);
4157 return RET_PF_RETRY;
4160 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4161 struct kvm_mmu *context)
4163 context->page_fault = nonpaging_page_fault;
4164 context->gva_to_gpa = nonpaging_gva_to_gpa;
4165 context->sync_page = nonpaging_sync_page;
4166 context->invlpg = nonpaging_invlpg;
4167 context->update_pte = nonpaging_update_pte;
4168 context->root_level = 0;
4169 context->shadow_root_level = PT32E_ROOT_LEVEL;
4170 context->direct_map = true;
4171 context->nx = false;
4175 * Find out if a previously cached root matching the new CR3/role is available.
4176 * The current root is also inserted into the cache.
4177 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4179 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4180 * false is returned. This root should now be freed by the caller.
4182 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4183 union kvm_mmu_page_role new_role)
4186 struct kvm_mmu_root_info root;
4187 struct kvm_mmu *mmu = vcpu->arch.mmu;
4189 root.cr3 = mmu->root_cr3;
4190 root.hpa = mmu->root_hpa;
4192 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4193 swap(root, mmu->prev_roots[i]);
4195 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4196 page_header(root.hpa) != NULL &&
4197 new_role.word == page_header(root.hpa)->role.word)
4201 mmu->root_hpa = root.hpa;
4202 mmu->root_cr3 = root.cr3;
4204 return i < KVM_MMU_NUM_PREV_ROOTS;
4207 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4208 union kvm_mmu_page_role new_role,
4209 bool skip_tlb_flush)
4211 struct kvm_mmu *mmu = vcpu->arch.mmu;
4214 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4215 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4216 * later if necessary.
4218 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4219 mmu->root_level >= PT64_ROOT_4LEVEL) {
4220 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4223 if (cached_root_available(vcpu, new_cr3, new_role)) {
4224 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4225 if (!skip_tlb_flush) {
4226 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4227 kvm_x86_ops->tlb_flush(vcpu, true);
4231 * The last MMIO access's GVA and GPA are cached in the
4232 * VCPU. When switching to a new CR3, that GVA->GPA
4233 * mapping may no longer be valid. So clear any cached
4234 * MMIO info even when we don't need to sync the shadow
4237 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4239 __clear_sp_write_flooding_count(
4240 page_header(mmu->root_hpa));
4249 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4250 union kvm_mmu_page_role new_role,
4251 bool skip_tlb_flush)
4253 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4254 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4255 KVM_MMU_ROOT_CURRENT);
4258 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4260 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4263 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4265 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4267 return kvm_read_cr3(vcpu);
4270 static void inject_page_fault(struct kvm_vcpu *vcpu,
4271 struct x86_exception *fault)
4273 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4276 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4277 unsigned access, int *nr_present)
4279 if (unlikely(is_mmio_spte(*sptep))) {
4280 if (gfn != get_mmio_spte_gfn(*sptep)) {
4281 mmu_spte_clear_no_track(sptep);
4286 mark_mmio_spte(vcpu, sptep, gfn, access);
4293 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4294 unsigned level, unsigned gpte)
4297 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4298 * If it is clear, there are no large pages at this level, so clear
4299 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4301 gpte &= level - mmu->last_nonleaf_level;
4304 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4305 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4306 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4308 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4310 return gpte & PT_PAGE_SIZE_MASK;
4313 #define PTTYPE_EPT 18 /* arbitrary */
4314 #define PTTYPE PTTYPE_EPT
4315 #include "paging_tmpl.h"
4319 #include "paging_tmpl.h"
4323 #include "paging_tmpl.h"
4327 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4328 struct rsvd_bits_validate *rsvd_check,
4329 int maxphyaddr, int level, bool nx, bool gbpages,
4332 u64 exb_bit_rsvd = 0;
4333 u64 gbpages_bit_rsvd = 0;
4334 u64 nonleaf_bit8_rsvd = 0;
4336 rsvd_check->bad_mt_xwr = 0;
4339 exb_bit_rsvd = rsvd_bits(63, 63);
4341 gbpages_bit_rsvd = rsvd_bits(7, 7);
4344 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4345 * leaf entries) on AMD CPUs only.
4348 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4351 case PT32_ROOT_LEVEL:
4352 /* no rsvd bits for 2 level 4K page table entries */
4353 rsvd_check->rsvd_bits_mask[0][1] = 0;
4354 rsvd_check->rsvd_bits_mask[0][0] = 0;
4355 rsvd_check->rsvd_bits_mask[1][0] =
4356 rsvd_check->rsvd_bits_mask[0][0];
4359 rsvd_check->rsvd_bits_mask[1][1] = 0;
4363 if (is_cpuid_PSE36())
4364 /* 36bits PSE 4MB page */
4365 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4367 /* 32 bits PSE 4MB page */
4368 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4370 case PT32E_ROOT_LEVEL:
4371 rsvd_check->rsvd_bits_mask[0][2] =
4372 rsvd_bits(maxphyaddr, 63) |
4373 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4374 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4375 rsvd_bits(maxphyaddr, 62); /* PDE */
4376 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4377 rsvd_bits(maxphyaddr, 62); /* PTE */
4378 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4379 rsvd_bits(maxphyaddr, 62) |
4380 rsvd_bits(13, 20); /* large page */
4381 rsvd_check->rsvd_bits_mask[1][0] =
4382 rsvd_check->rsvd_bits_mask[0][0];
4384 case PT64_ROOT_5LEVEL:
4385 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4386 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4387 rsvd_bits(maxphyaddr, 51);
4388 rsvd_check->rsvd_bits_mask[1][4] =
4389 rsvd_check->rsvd_bits_mask[0][4];
4391 case PT64_ROOT_4LEVEL:
4392 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4393 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4394 rsvd_bits(maxphyaddr, 51);
4395 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4396 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4397 rsvd_bits(maxphyaddr, 51);
4398 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4399 rsvd_bits(maxphyaddr, 51);
4400 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4401 rsvd_bits(maxphyaddr, 51);
4402 rsvd_check->rsvd_bits_mask[1][3] =
4403 rsvd_check->rsvd_bits_mask[0][3];
4404 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4405 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4407 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4408 rsvd_bits(maxphyaddr, 51) |
4409 rsvd_bits(13, 20); /* large page */
4410 rsvd_check->rsvd_bits_mask[1][0] =
4411 rsvd_check->rsvd_bits_mask[0][0];
4416 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4417 struct kvm_mmu *context)
4419 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4420 cpuid_maxphyaddr(vcpu), context->root_level,
4422 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4423 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4427 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4428 int maxphyaddr, bool execonly)
4432 rsvd_check->rsvd_bits_mask[0][4] =
4433 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4434 rsvd_check->rsvd_bits_mask[0][3] =
4435 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4436 rsvd_check->rsvd_bits_mask[0][2] =
4437 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4438 rsvd_check->rsvd_bits_mask[0][1] =
4439 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4440 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4443 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4444 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4445 rsvd_check->rsvd_bits_mask[1][2] =
4446 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4447 rsvd_check->rsvd_bits_mask[1][1] =
4448 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4449 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4451 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4452 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4453 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4454 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4455 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4457 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4458 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4460 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4463 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4464 struct kvm_mmu *context, bool execonly)
4466 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4467 cpuid_maxphyaddr(vcpu), execonly);
4471 * the page table on host is the shadow page table for the page
4472 * table in guest or amd nested guest, its mmu features completely
4473 * follow the features in guest.
4476 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4478 bool uses_nx = context->nx ||
4479 context->mmu_role.base.smep_andnot_wp;
4480 struct rsvd_bits_validate *shadow_zero_check;
4484 * Passing "true" to the last argument is okay; it adds a check
4485 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4487 shadow_zero_check = &context->shadow_zero_check;
4488 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4489 boot_cpu_data.x86_phys_bits,
4490 context->shadow_root_level, uses_nx,
4491 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4492 is_pse(vcpu), true);
4494 if (!shadow_me_mask)
4497 for (i = context->shadow_root_level; --i >= 0;) {
4498 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4499 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4503 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4505 static inline bool boot_cpu_is_amd(void)
4507 WARN_ON_ONCE(!tdp_enabled);
4508 return shadow_x_mask == 0;
4512 * the direct page table on host, use as much mmu features as
4513 * possible, however, kvm currently does not do execution-protection.
4516 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4517 struct kvm_mmu *context)
4519 struct rsvd_bits_validate *shadow_zero_check;
4522 shadow_zero_check = &context->shadow_zero_check;
4524 if (boot_cpu_is_amd())
4525 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4526 boot_cpu_data.x86_phys_bits,
4527 context->shadow_root_level, false,
4528 boot_cpu_has(X86_FEATURE_GBPAGES),
4531 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4532 boot_cpu_data.x86_phys_bits,
4535 if (!shadow_me_mask)
4538 for (i = context->shadow_root_level; --i >= 0;) {
4539 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4540 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4545 * as the comments in reset_shadow_zero_bits_mask() except it
4546 * is the shadow page table for intel nested guest.
4549 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4550 struct kvm_mmu *context, bool execonly)
4552 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4553 boot_cpu_data.x86_phys_bits, execonly);
4556 #define BYTE_MASK(access) \
4557 ((1 & (access) ? 2 : 0) | \
4558 (2 & (access) ? 4 : 0) | \
4559 (3 & (access) ? 8 : 0) | \
4560 (4 & (access) ? 16 : 0) | \
4561 (5 & (access) ? 32 : 0) | \
4562 (6 & (access) ? 64 : 0) | \
4563 (7 & (access) ? 128 : 0))
4566 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4567 struct kvm_mmu *mmu, bool ept)
4571 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4572 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4573 const u8 u = BYTE_MASK(ACC_USER_MASK);
4575 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4576 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4577 bool cr0_wp = is_write_protection(vcpu);
4579 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4580 unsigned pfec = byte << 1;
4583 * Each "*f" variable has a 1 bit for each UWX value
4584 * that causes a fault with the given PFEC.
4587 /* Faults from writes to non-writable pages */
4588 u8 wf = (pfec & PFERR_WRITE_MASK) ? ~w : 0;
4589 /* Faults from user mode accesses to supervisor pages */
4590 u8 uf = (pfec & PFERR_USER_MASK) ? ~u : 0;
4591 /* Faults from fetches of non-executable pages*/
4592 u8 ff = (pfec & PFERR_FETCH_MASK) ? ~x : 0;
4593 /* Faults from kernel mode fetches of user pages */
4595 /* Faults from kernel mode accesses of user pages */
4599 /* Faults from kernel mode accesses to user pages */
4600 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4602 /* Not really needed: !nx will cause pte.nx to fault */
4606 /* Allow supervisor writes if !cr0.wp */
4608 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4610 /* Disallow supervisor fetches of user code if cr4.smep */
4612 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4615 * SMAP:kernel-mode data accesses from user-mode
4616 * mappings should fault. A fault is considered
4617 * as a SMAP violation if all of the following
4618 * conditions are true:
4619 * - X86_CR4_SMAP is set in CR4
4620 * - A user page is accessed
4621 * - The access is not a fetch
4622 * - Page fault in kernel mode
4623 * - if CPL = 3 or X86_EFLAGS_AC is clear
4625 * Here, we cover the first three conditions.
4626 * The fourth is computed dynamically in permission_fault();
4627 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4628 * *not* subject to SMAP restrictions.
4631 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4634 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4639 * PKU is an additional mechanism by which the paging controls access to
4640 * user-mode addresses based on the value in the PKRU register. Protection
4641 * key violations are reported through a bit in the page fault error code.
4642 * Unlike other bits of the error code, the PK bit is not known at the
4643 * call site of e.g. gva_to_gpa; it must be computed directly in
4644 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4645 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4647 * In particular the following conditions come from the error code, the
4648 * page tables and the machine state:
4649 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4650 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4651 * - PK is always zero if U=0 in the page tables
4652 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4654 * The PKRU bitmask caches the result of these four conditions. The error
4655 * code (minus the P bit) and the page table's U bit form an index into the
4656 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4657 * with the two bits of the PKRU register corresponding to the protection key.
4658 * For the first three conditions above the bits will be 00, thus masking
4659 * away both AD and WD. For all reads or if the last condition holds, WD
4660 * only will be masked away.
4662 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4673 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4674 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4679 wp = is_write_protection(vcpu);
4681 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4682 unsigned pfec, pkey_bits;
4683 bool check_pkey, check_write, ff, uf, wf, pte_user;
4686 ff = pfec & PFERR_FETCH_MASK;
4687 uf = pfec & PFERR_USER_MASK;
4688 wf = pfec & PFERR_WRITE_MASK;
4690 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4691 pte_user = pfec & PFERR_RSVD_MASK;
4694 * Only need to check the access which is not an
4695 * instruction fetch and is to a user page.
4697 check_pkey = (!ff && pte_user);
4699 * write access is controlled by PKRU if it is a
4700 * user access or CR0.WP = 1.
4702 check_write = check_pkey && wf && (uf || wp);
4704 /* PKRU.AD stops both read and write access. */
4705 pkey_bits = !!check_pkey;
4706 /* PKRU.WD stops write access. */
4707 pkey_bits |= (!!check_write) << 1;
4709 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4713 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4715 unsigned root_level = mmu->root_level;
4717 mmu->last_nonleaf_level = root_level;
4718 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4719 mmu->last_nonleaf_level++;
4722 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4723 struct kvm_mmu *context,
4726 context->nx = is_nx(vcpu);
4727 context->root_level = level;
4729 reset_rsvds_bits_mask(vcpu, context);
4730 update_permission_bitmask(vcpu, context, false);
4731 update_pkru_bitmask(vcpu, context, false);
4732 update_last_nonleaf_level(vcpu, context);
4734 MMU_WARN_ON(!is_pae(vcpu));
4735 context->page_fault = paging64_page_fault;
4736 context->gva_to_gpa = paging64_gva_to_gpa;
4737 context->sync_page = paging64_sync_page;
4738 context->invlpg = paging64_invlpg;
4739 context->update_pte = paging64_update_pte;
4740 context->shadow_root_level = level;
4741 context->direct_map = false;
4744 static void paging64_init_context(struct kvm_vcpu *vcpu,
4745 struct kvm_mmu *context)
4747 int root_level = is_la57_mode(vcpu) ?
4748 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4750 paging64_init_context_common(vcpu, context, root_level);
4753 static void paging32_init_context(struct kvm_vcpu *vcpu,
4754 struct kvm_mmu *context)
4756 context->nx = false;
4757 context->root_level = PT32_ROOT_LEVEL;
4759 reset_rsvds_bits_mask(vcpu, context);
4760 update_permission_bitmask(vcpu, context, false);
4761 update_pkru_bitmask(vcpu, context, false);
4762 update_last_nonleaf_level(vcpu, context);
4764 context->page_fault = paging32_page_fault;
4765 context->gva_to_gpa = paging32_gva_to_gpa;
4766 context->sync_page = paging32_sync_page;
4767 context->invlpg = paging32_invlpg;
4768 context->update_pte = paging32_update_pte;
4769 context->shadow_root_level = PT32E_ROOT_LEVEL;
4770 context->direct_map = false;
4773 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4774 struct kvm_mmu *context)
4776 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4779 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4781 union kvm_mmu_extended_role ext = {0};
4783 ext.cr0_pg = !!is_paging(vcpu);
4784 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4785 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4786 ext.cr4_pse = !!is_pse(vcpu);
4787 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4788 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4789 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4796 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4799 union kvm_mmu_role role = {0};
4801 role.base.access = ACC_ALL;
4802 role.base.nxe = !!is_nx(vcpu);
4803 role.base.cr0_wp = is_write_protection(vcpu);
4804 role.base.smm = is_smm(vcpu);
4805 role.base.guest_mode = is_guest_mode(vcpu);
4810 role.ext = kvm_calc_mmu_role_ext(vcpu);
4815 static union kvm_mmu_role
4816 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4818 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4820 role.base.ad_disabled = (shadow_accessed_mask == 0);
4821 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4822 role.base.direct = true;
4823 role.base.gpte_is_8_bytes = true;
4828 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4830 struct kvm_mmu *context = vcpu->arch.mmu;
4831 union kvm_mmu_role new_role =
4832 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4834 new_role.base.word &= mmu_base_role_mask.word;
4835 if (new_role.as_u64 == context->mmu_role.as_u64)
4838 context->mmu_role.as_u64 = new_role.as_u64;
4839 context->page_fault = tdp_page_fault;
4840 context->sync_page = nonpaging_sync_page;
4841 context->invlpg = nonpaging_invlpg;
4842 context->update_pte = nonpaging_update_pte;
4843 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4844 context->direct_map = true;
4845 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4846 context->get_cr3 = get_cr3;
4847 context->get_pdptr = kvm_pdptr_read;
4848 context->inject_page_fault = kvm_inject_page_fault;
4850 if (!is_paging(vcpu)) {
4851 context->nx = false;
4852 context->gva_to_gpa = nonpaging_gva_to_gpa;
4853 context->root_level = 0;
4854 } else if (is_long_mode(vcpu)) {
4855 context->nx = is_nx(vcpu);
4856 context->root_level = is_la57_mode(vcpu) ?
4857 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4858 reset_rsvds_bits_mask(vcpu, context);
4859 context->gva_to_gpa = paging64_gva_to_gpa;
4860 } else if (is_pae(vcpu)) {
4861 context->nx = is_nx(vcpu);
4862 context->root_level = PT32E_ROOT_LEVEL;
4863 reset_rsvds_bits_mask(vcpu, context);
4864 context->gva_to_gpa = paging64_gva_to_gpa;
4866 context->nx = false;
4867 context->root_level = PT32_ROOT_LEVEL;
4868 reset_rsvds_bits_mask(vcpu, context);
4869 context->gva_to_gpa = paging32_gva_to_gpa;
4872 update_permission_bitmask(vcpu, context, false);
4873 update_pkru_bitmask(vcpu, context, false);
4874 update_last_nonleaf_level(vcpu, context);
4875 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4878 static union kvm_mmu_role
4879 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4881 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4883 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4884 !is_write_protection(vcpu);
4885 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4886 !is_write_protection(vcpu);
4887 role.base.direct = !is_paging(vcpu);
4888 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4890 if (!is_long_mode(vcpu))
4891 role.base.level = PT32E_ROOT_LEVEL;
4892 else if (is_la57_mode(vcpu))
4893 role.base.level = PT64_ROOT_5LEVEL;
4895 role.base.level = PT64_ROOT_4LEVEL;
4900 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4902 struct kvm_mmu *context = vcpu->arch.mmu;
4903 union kvm_mmu_role new_role =
4904 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4906 new_role.base.word &= mmu_base_role_mask.word;
4907 if (new_role.as_u64 == context->mmu_role.as_u64)
4910 if (!is_paging(vcpu))
4911 nonpaging_init_context(vcpu, context);
4912 else if (is_long_mode(vcpu))
4913 paging64_init_context(vcpu, context);
4914 else if (is_pae(vcpu))
4915 paging32E_init_context(vcpu, context);
4917 paging32_init_context(vcpu, context);
4919 context->mmu_role.as_u64 = new_role.as_u64;
4920 reset_shadow_zero_bits_mask(vcpu, context);
4922 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4924 static union kvm_mmu_role
4925 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4928 union kvm_mmu_role role = {0};
4930 /* SMM flag is inherited from root_mmu */
4931 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
4933 role.base.level = PT64_ROOT_4LEVEL;
4934 role.base.gpte_is_8_bytes = true;
4935 role.base.direct = false;
4936 role.base.ad_disabled = !accessed_dirty;
4937 role.base.guest_mode = true;
4938 role.base.access = ACC_ALL;
4941 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
4942 * SMAP variation to denote shadow EPT entries.
4944 role.base.cr0_wp = true;
4945 role.base.smap_andnot_wp = true;
4947 role.ext = kvm_calc_mmu_role_ext(vcpu);
4948 role.ext.execonly = execonly;
4953 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4954 bool accessed_dirty, gpa_t new_eptp)
4956 struct kvm_mmu *context = vcpu->arch.mmu;
4957 union kvm_mmu_role new_role =
4958 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4961 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
4963 new_role.base.word &= mmu_base_role_mask.word;
4964 if (new_role.as_u64 == context->mmu_role.as_u64)
4967 context->shadow_root_level = PT64_ROOT_4LEVEL;
4970 context->ept_ad = accessed_dirty;
4971 context->page_fault = ept_page_fault;
4972 context->gva_to_gpa = ept_gva_to_gpa;
4973 context->sync_page = ept_sync_page;
4974 context->invlpg = ept_invlpg;
4975 context->update_pte = ept_update_pte;
4976 context->root_level = PT64_ROOT_4LEVEL;
4977 context->direct_map = false;
4978 context->mmu_role.as_u64 = new_role.as_u64;
4980 update_permission_bitmask(vcpu, context, true);
4981 update_pkru_bitmask(vcpu, context, true);
4982 update_last_nonleaf_level(vcpu, context);
4983 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4984 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4986 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4988 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4990 struct kvm_mmu *context = vcpu->arch.mmu;
4992 kvm_init_shadow_mmu(vcpu);
4993 context->set_cr3 = kvm_x86_ops->set_cr3;
4994 context->get_cr3 = get_cr3;
4995 context->get_pdptr = kvm_pdptr_read;
4996 context->inject_page_fault = kvm_inject_page_fault;
4999 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5001 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5002 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5004 new_role.base.word &= mmu_base_role_mask.word;
5005 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5008 g_context->mmu_role.as_u64 = new_role.as_u64;
5009 g_context->get_cr3 = get_cr3;
5010 g_context->get_pdptr = kvm_pdptr_read;
5011 g_context->inject_page_fault = kvm_inject_page_fault;
5014 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5015 * L1's nested page tables (e.g. EPT12). The nested translation
5016 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5017 * L2's page tables as the first level of translation and L1's
5018 * nested page tables as the second level of translation. Basically
5019 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5021 if (!is_paging(vcpu)) {
5022 g_context->nx = false;
5023 g_context->root_level = 0;
5024 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5025 } else if (is_long_mode(vcpu)) {
5026 g_context->nx = is_nx(vcpu);
5027 g_context->root_level = is_la57_mode(vcpu) ?
5028 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5029 reset_rsvds_bits_mask(vcpu, g_context);
5030 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5031 } else if (is_pae(vcpu)) {
5032 g_context->nx = is_nx(vcpu);
5033 g_context->root_level = PT32E_ROOT_LEVEL;
5034 reset_rsvds_bits_mask(vcpu, g_context);
5035 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5037 g_context->nx = false;
5038 g_context->root_level = PT32_ROOT_LEVEL;
5039 reset_rsvds_bits_mask(vcpu, g_context);
5040 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5043 update_permission_bitmask(vcpu, g_context, false);
5044 update_pkru_bitmask(vcpu, g_context, false);
5045 update_last_nonleaf_level(vcpu, g_context);
5048 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5053 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5055 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5056 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5059 if (mmu_is_nested(vcpu))
5060 init_kvm_nested_mmu(vcpu);
5061 else if (tdp_enabled)
5062 init_kvm_tdp_mmu(vcpu);
5064 init_kvm_softmmu(vcpu);
5066 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5068 static union kvm_mmu_page_role
5069 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5071 union kvm_mmu_role role;
5074 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5076 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5081 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5083 kvm_mmu_unload(vcpu);
5084 kvm_init_mmu(vcpu, true);
5086 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5088 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5092 r = mmu_topup_memory_caches(vcpu);
5095 r = mmu_alloc_roots(vcpu);
5096 kvm_mmu_sync_roots(vcpu);
5099 kvm_mmu_load_cr3(vcpu);
5100 kvm_x86_ops->tlb_flush(vcpu, true);
5104 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5106 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5108 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5109 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5110 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5111 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5113 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5115 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5116 struct kvm_mmu_page *sp, u64 *spte,
5119 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5120 ++vcpu->kvm->stat.mmu_pde_zapped;
5124 ++vcpu->kvm->stat.mmu_pte_updated;
5125 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5128 static bool need_remote_flush(u64 old, u64 new)
5130 if (!is_shadow_present_pte(old))
5132 if (!is_shadow_present_pte(new))
5134 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5136 old ^= shadow_nx_mask;
5137 new ^= shadow_nx_mask;
5138 return (old & ~new & PT64_PERM_MASK) != 0;
5141 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5148 * Assume that the pte write on a page table of the same type
5149 * as the current vcpu paging mode since we update the sptes only
5150 * when they have the same mode.
5152 if (is_pae(vcpu) && *bytes == 4) {
5153 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5158 if (*bytes == 4 || *bytes == 8) {
5159 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5168 * If we're seeing too many writes to a page, it may no longer be a page table,
5169 * or we may be forking, in which case it is better to unmap the page.
5171 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5174 * Skip write-flooding detected for the sp whose level is 1, because
5175 * it can become unsync, then the guest page is not write-protected.
5177 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5180 atomic_inc(&sp->write_flooding_count);
5181 return atomic_read(&sp->write_flooding_count) >= 3;
5185 * Misaligned accesses are too much trouble to fix up; also, they usually
5186 * indicate a page is not used as a page table.
5188 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5191 unsigned offset, pte_size, misaligned;
5193 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5194 gpa, bytes, sp->role.word);
5196 offset = offset_in_page(gpa);
5197 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5200 * Sometimes, the OS only writes the last one bytes to update status
5201 * bits, for example, in linux, andb instruction is used in clear_bit().
5203 if (!(offset & (pte_size - 1)) && bytes == 1)
5206 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5207 misaligned |= bytes < 4;
5212 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5214 unsigned page_offset, quadrant;
5218 page_offset = offset_in_page(gpa);
5219 level = sp->role.level;
5221 if (!sp->role.gpte_is_8_bytes) {
5222 page_offset <<= 1; /* 32->64 */
5224 * A 32-bit pde maps 4MB while the shadow pdes map
5225 * only 2MB. So we need to double the offset again
5226 * and zap two pdes instead of one.
5228 if (level == PT32_ROOT_LEVEL) {
5229 page_offset &= ~7; /* kill rounding error */
5233 quadrant = page_offset >> PAGE_SHIFT;
5234 page_offset &= ~PAGE_MASK;
5235 if (quadrant != sp->role.quadrant)
5239 spte = &sp->spt[page_offset / sizeof(*spte)];
5243 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5244 const u8 *new, int bytes,
5245 struct kvm_page_track_notifier_node *node)
5247 gfn_t gfn = gpa >> PAGE_SHIFT;
5248 struct kvm_mmu_page *sp;
5249 LIST_HEAD(invalid_list);
5250 u64 entry, gentry, *spte;
5252 bool remote_flush, local_flush;
5255 * If we don't have indirect shadow pages, it means no page is
5256 * write-protected, so we can exit simply.
5258 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5261 remote_flush = local_flush = false;
5263 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5266 * No need to care whether allocation memory is successful
5267 * or not since pte prefetch is skiped if it does not have
5268 * enough objects in the cache.
5270 mmu_topup_memory_caches(vcpu);
5272 spin_lock(&vcpu->kvm->mmu_lock);
5274 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5276 ++vcpu->kvm->stat.mmu_pte_write;
5277 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5279 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5280 if (detect_write_misaligned(sp, gpa, bytes) ||
5281 detect_write_flooding(sp)) {
5282 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5283 ++vcpu->kvm->stat.mmu_flooded;
5287 spte = get_written_sptes(sp, gpa, &npte);
5293 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5296 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5298 !((sp->role.word ^ base_role)
5299 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5300 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5301 if (need_remote_flush(entry, *spte))
5302 remote_flush = true;
5306 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5307 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5308 spin_unlock(&vcpu->kvm->mmu_lock);
5311 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5316 if (vcpu->arch.mmu->direct_map)
5319 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5321 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5325 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5327 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5329 LIST_HEAD(invalid_list);
5331 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5334 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5335 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5338 ++vcpu->kvm->stat.mmu_recycled;
5340 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5342 if (!kvm_mmu_available_pages(vcpu->kvm))
5347 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5348 void *insn, int insn_len)
5350 int r, emulation_type = 0;
5351 enum emulation_result er;
5352 bool direct = vcpu->arch.mmu->direct_map;
5354 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5355 if (vcpu->arch.mmu->direct_map) {
5356 vcpu->arch.gpa_available = true;
5357 vcpu->arch.gpa_val = cr2;
5361 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5362 r = handle_mmio_page_fault(vcpu, cr2, direct);
5363 if (r == RET_PF_EMULATE)
5367 if (r == RET_PF_INVALID) {
5368 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5369 lower_32_bits(error_code),
5371 WARN_ON(r == RET_PF_INVALID);
5374 if (r == RET_PF_RETRY)
5380 * Before emulating the instruction, check if the error code
5381 * was due to a RO violation while translating the guest page.
5382 * This can occur when using nested virtualization with nested
5383 * paging in both guests. If true, we simply unprotect the page
5384 * and resume the guest.
5386 if (vcpu->arch.mmu->direct_map &&
5387 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5388 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5393 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5394 * optimistically try to just unprotect the page and let the processor
5395 * re-execute the instruction that caused the page fault. Do not allow
5396 * retrying MMIO emulation, as it's not only pointless but could also
5397 * cause us to enter an infinite loop because the processor will keep
5398 * faulting on the non-existent MMIO address. Retrying an instruction
5399 * from a nested guest is also pointless and dangerous as we are only
5400 * explicitly shadowing L1's page tables, i.e. unprotecting something
5401 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5403 if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5404 emulation_type = EMULTYPE_ALLOW_RETRY;
5407 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5408 * This can happen if a guest gets a page-fault on data access but the HW
5409 * table walker is not able to read the instruction page (e.g instruction
5410 * page is not present in memory). In those cases we simply restart the
5411 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5413 if (unlikely(insn && !insn_len)) {
5414 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5418 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
5423 case EMULATE_USER_EXIT:
5424 ++vcpu->stat.mmio_exits;
5432 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5434 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5436 struct kvm_mmu *mmu = vcpu->arch.mmu;
5439 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5440 if (is_noncanonical_address(gva, vcpu))
5443 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5446 * INVLPG is required to invalidate any global mappings for the VA,
5447 * irrespective of PCID. Since it would take us roughly similar amount
5448 * of work to determine whether any of the prev_root mappings of the VA
5449 * is marked global, or to just sync it blindly, so we might as well
5450 * just always sync it.
5452 * Mappings not reachable via the current cr3 or the prev_roots will be
5453 * synced when switching to that cr3, so nothing needs to be done here
5456 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5457 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5458 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5460 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5461 ++vcpu->stat.invlpg;
5463 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5465 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5467 struct kvm_mmu *mmu = vcpu->arch.mmu;
5468 bool tlb_flush = false;
5471 if (pcid == kvm_get_active_pcid(vcpu)) {
5472 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5476 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5477 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5478 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5479 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5485 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5487 ++vcpu->stat.invlpg;
5490 * Mappings not reachable via the current cr3 or the prev_roots will be
5491 * synced when switching to that cr3, so nothing needs to be done here
5495 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5497 void kvm_enable_tdp(void)
5501 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5503 void kvm_disable_tdp(void)
5505 tdp_enabled = false;
5507 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5510 /* The return value indicates if tlb flush on all vcpus is needed. */
5511 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5513 /* The caller should hold mmu-lock before calling this function. */
5514 static __always_inline bool
5515 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5516 slot_level_handler fn, int start_level, int end_level,
5517 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5519 struct slot_rmap_walk_iterator iterator;
5522 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5523 end_gfn, &iterator) {
5525 flush |= fn(kvm, iterator.rmap);
5527 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5528 if (flush && lock_flush_tlb) {
5529 kvm_flush_remote_tlbs_with_address(kvm,
5531 iterator.gfn - start_gfn + 1);
5534 cond_resched_lock(&kvm->mmu_lock);
5538 if (flush && lock_flush_tlb) {
5539 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5540 end_gfn - start_gfn + 1);
5547 static __always_inline bool
5548 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5549 slot_level_handler fn, int start_level, int end_level,
5550 bool lock_flush_tlb)
5552 return slot_handle_level_range(kvm, memslot, fn, start_level,
5553 end_level, memslot->base_gfn,
5554 memslot->base_gfn + memslot->npages - 1,
5558 static __always_inline bool
5559 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5560 slot_level_handler fn, bool lock_flush_tlb)
5562 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5563 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5566 static __always_inline bool
5567 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5568 slot_level_handler fn, bool lock_flush_tlb)
5570 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5571 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5574 static __always_inline bool
5575 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5576 slot_level_handler fn, bool lock_flush_tlb)
5578 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5579 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5582 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5584 free_page((unsigned long)vcpu->arch.mmu->pae_root);
5585 free_page((unsigned long)vcpu->arch.mmu->lm_root);
5588 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5597 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5598 * Therefore we need to allocate shadow page tables in the first
5599 * 4GB of memory, which happens to fit the DMA32 zone.
5601 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5605 vcpu->arch.mmu->pae_root = page_address(page);
5606 for (i = 0; i < 4; ++i)
5607 vcpu->arch.mmu->pae_root[i] = INVALID_PAGE;
5612 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5616 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5617 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5619 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5620 vcpu->arch.root_mmu.root_cr3 = 0;
5621 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5622 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5623 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5625 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5626 vcpu->arch.guest_mmu.root_cr3 = 0;
5627 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5628 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5629 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5631 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5632 return alloc_mmu_pages(vcpu);
5635 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5636 struct kvm_memory_slot *slot,
5637 struct kvm_page_track_notifier_node *node)
5639 struct kvm_mmu_page *sp;
5640 LIST_HEAD(invalid_list);
5645 spin_lock(&kvm->mmu_lock);
5647 if (list_empty(&kvm->arch.active_mmu_pages))
5650 flush = slot_handle_all_level(kvm, slot, kvm_zap_rmapp, false);
5652 for (i = 0; i < slot->npages; i++) {
5653 gfn = slot->base_gfn + i;
5655 for_each_valid_sp(kvm, sp, gfn) {
5659 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
5661 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5662 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
5664 cond_resched_lock(&kvm->mmu_lock);
5667 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
5670 spin_unlock(&kvm->mmu_lock);
5673 void kvm_mmu_init_vm(struct kvm *kvm)
5675 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5677 node->track_write = kvm_mmu_pte_write;
5678 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5679 kvm_page_track_register_notifier(kvm, node);
5682 void kvm_mmu_uninit_vm(struct kvm *kvm)
5684 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5686 kvm_page_track_unregister_notifier(kvm, node);
5689 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5691 struct kvm_memslots *slots;
5692 struct kvm_memory_slot *memslot;
5695 spin_lock(&kvm->mmu_lock);
5696 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5697 slots = __kvm_memslots(kvm, i);
5698 kvm_for_each_memslot(memslot, slots) {
5701 start = max(gfn_start, memslot->base_gfn);
5702 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5706 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5707 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5708 start, end - 1, true);
5712 spin_unlock(&kvm->mmu_lock);
5715 static bool slot_rmap_write_protect(struct kvm *kvm,
5716 struct kvm_rmap_head *rmap_head)
5718 return __rmap_write_protect(kvm, rmap_head, false);
5721 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5722 struct kvm_memory_slot *memslot)
5726 spin_lock(&kvm->mmu_lock);
5727 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5729 spin_unlock(&kvm->mmu_lock);
5732 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5733 * which do tlb flush out of mmu-lock should be serialized by
5734 * kvm->slots_lock otherwise tlb flush would be missed.
5736 lockdep_assert_held(&kvm->slots_lock);
5739 * We can flush all the TLBs out of the mmu lock without TLB
5740 * corruption since we just change the spte from writable to
5741 * readonly so that we only need to care the case of changing
5742 * spte from present to present (changing the spte from present
5743 * to nonpresent will flush all the TLBs immediately), in other
5744 * words, the only case we care is mmu_spte_update() where we
5745 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5746 * instead of PT_WRITABLE_MASK, that means it does not depend
5747 * on PT_WRITABLE_MASK anymore.
5750 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5754 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5755 struct kvm_rmap_head *rmap_head)
5758 struct rmap_iterator iter;
5759 int need_tlb_flush = 0;
5761 struct kvm_mmu_page *sp;
5764 for_each_rmap_spte(rmap_head, &iter, sptep) {
5765 sp = page_header(__pa(sptep));
5766 pfn = spte_to_pfn(*sptep);
5769 * We cannot do huge page mapping for indirect shadow pages,
5770 * which are found on the last rmap (level = 1) when not using
5771 * tdp; such shadow pages are synced with the page table in
5772 * the guest, and the guest page table is using 4K page size
5773 * mapping if the indirect sp has level = 1.
5775 if (sp->role.direct &&
5776 !kvm_is_reserved_pfn(pfn) &&
5777 PageTransCompoundMap(pfn_to_page(pfn))) {
5778 pte_list_remove(rmap_head, sptep);
5780 if (kvm_available_flush_tlb_with_range())
5781 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5782 KVM_PAGES_PER_HPAGE(sp->role.level));
5790 return need_tlb_flush;
5793 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5794 const struct kvm_memory_slot *memslot)
5796 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5797 spin_lock(&kvm->mmu_lock);
5798 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5799 kvm_mmu_zap_collapsible_spte, true);
5800 spin_unlock(&kvm->mmu_lock);
5803 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5804 struct kvm_memory_slot *memslot)
5808 spin_lock(&kvm->mmu_lock);
5809 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5810 spin_unlock(&kvm->mmu_lock);
5812 lockdep_assert_held(&kvm->slots_lock);
5815 * It's also safe to flush TLBs out of mmu lock here as currently this
5816 * function is only used for dirty logging, in which case flushing TLB
5817 * out of mmu lock also guarantees no dirty pages will be lost in
5821 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5824 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5826 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5827 struct kvm_memory_slot *memslot)
5831 spin_lock(&kvm->mmu_lock);
5832 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5834 spin_unlock(&kvm->mmu_lock);
5836 /* see kvm_mmu_slot_remove_write_access */
5837 lockdep_assert_held(&kvm->slots_lock);
5840 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5843 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5845 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5846 struct kvm_memory_slot *memslot)
5850 spin_lock(&kvm->mmu_lock);
5851 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5852 spin_unlock(&kvm->mmu_lock);
5854 lockdep_assert_held(&kvm->slots_lock);
5856 /* see kvm_mmu_slot_leaf_clear_dirty */
5858 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5861 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5863 static void __kvm_mmu_zap_all(struct kvm *kvm, bool mmio_only)
5865 struct kvm_mmu_page *sp, *node;
5866 LIST_HEAD(invalid_list);
5869 spin_lock(&kvm->mmu_lock);
5871 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
5872 if (mmio_only && !sp->mmio_cached)
5874 if (sp->role.invalid && sp->root_count)
5876 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign)) {
5877 WARN_ON_ONCE(mmio_only);
5880 if (cond_resched_lock(&kvm->mmu_lock))
5884 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5885 spin_unlock(&kvm->mmu_lock);
5888 void kvm_mmu_zap_all(struct kvm *kvm)
5890 return __kvm_mmu_zap_all(kvm, false);
5893 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5895 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
5897 gen &= MMIO_SPTE_GEN_MASK;
5900 * Generation numbers are incremented in multiples of the number of
5901 * address spaces in order to provide unique generations across all
5902 * address spaces. Strip what is effectively the address space
5903 * modifier prior to checking for a wrap of the MMIO generation so
5904 * that a wrap in any address space is detected.
5906 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5909 * The very rare case: if the MMIO generation number has wrapped,
5910 * zap all shadow pages.
5912 if (unlikely(gen == 0)) {
5913 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5914 __kvm_mmu_zap_all(kvm, true);
5918 static unsigned long
5919 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5922 int nr_to_scan = sc->nr_to_scan;
5923 unsigned long freed = 0;
5925 spin_lock(&kvm_lock);
5927 list_for_each_entry(kvm, &vm_list, vm_list) {
5929 LIST_HEAD(invalid_list);
5932 * Never scan more than sc->nr_to_scan VM instances.
5933 * Will not hit this condition practically since we do not try
5934 * to shrink more than one VM and it is very unlikely to see
5935 * !n_used_mmu_pages so many times.
5940 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5941 * here. We may skip a VM instance errorneosly, but we do not
5942 * want to shrink a VM that only started to populate its MMU
5945 if (!kvm->arch.n_used_mmu_pages)
5948 idx = srcu_read_lock(&kvm->srcu);
5949 spin_lock(&kvm->mmu_lock);
5951 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
5953 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5955 spin_unlock(&kvm->mmu_lock);
5956 srcu_read_unlock(&kvm->srcu, idx);
5959 * unfair on small ones
5960 * per-vm shrinkers cry out
5961 * sadness comes quickly
5963 list_move_tail(&kvm->vm_list, &vm_list);
5967 spin_unlock(&kvm_lock);
5971 static unsigned long
5972 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5974 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5977 static struct shrinker mmu_shrinker = {
5978 .count_objects = mmu_shrink_count,
5979 .scan_objects = mmu_shrink_scan,
5980 .seeks = DEFAULT_SEEKS * 10,
5983 static void mmu_destroy_caches(void)
5985 kmem_cache_destroy(pte_list_desc_cache);
5986 kmem_cache_destroy(mmu_page_header_cache);
5989 int kvm_mmu_module_init(void)
5994 * MMU roles use union aliasing which is, generally speaking, an
5995 * undefined behavior. However, we supposedly know how compilers behave
5996 * and the current status quo is unlikely to change. Guardians below are
5997 * supposed to let us know if the assumption becomes false.
5999 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6000 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6001 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6003 kvm_mmu_reset_all_pte_masks();
6005 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6006 sizeof(struct pte_list_desc),
6007 0, SLAB_ACCOUNT, NULL);
6008 if (!pte_list_desc_cache)
6011 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6012 sizeof(struct kvm_mmu_page),
6013 0, SLAB_ACCOUNT, NULL);
6014 if (!mmu_page_header_cache)
6017 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6020 ret = register_shrinker(&mmu_shrinker);
6027 mmu_destroy_caches();
6032 * Calculate mmu pages needed for kvm.
6034 unsigned int kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6036 unsigned int nr_mmu_pages;
6037 unsigned int nr_pages = 0;
6038 struct kvm_memslots *slots;
6039 struct kvm_memory_slot *memslot;
6042 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6043 slots = __kvm_memslots(kvm, i);
6045 kvm_for_each_memslot(memslot, slots)
6046 nr_pages += memslot->npages;
6049 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6050 nr_mmu_pages = max(nr_mmu_pages,
6051 (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
6053 return nr_mmu_pages;
6056 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6058 kvm_mmu_unload(vcpu);
6059 free_mmu_pages(vcpu);
6060 mmu_free_memory_caches(vcpu);
6063 void kvm_mmu_module_exit(void)
6065 mmu_destroy_caches();
6066 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6067 unregister_shrinker(&mmu_shrinker);
6068 mmu_audit_disable();