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 #define PT64_BASE_ADDR_MASK __sme_clr((((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)))
113 #define PT64_DIR_BASE_ADDR_MASK \
114 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
115 #define PT64_LVL_ADDR_MASK(level) \
116 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
117 * PT64_LEVEL_BITS))) - 1))
118 #define PT64_LVL_OFFSET_MASK(level) \
119 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
120 * PT64_LEVEL_BITS))) - 1))
122 #define PT32_BASE_ADDR_MASK PAGE_MASK
123 #define PT32_DIR_BASE_ADDR_MASK \
124 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
125 #define PT32_LVL_ADDR_MASK(level) \
126 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
127 * PT32_LEVEL_BITS))) - 1))
129 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
130 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
132 #define ACC_EXEC_MASK 1
133 #define ACC_WRITE_MASK PT_WRITABLE_MASK
134 #define ACC_USER_MASK PT_USER_MASK
135 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
137 /* The mask for the R/X bits in EPT PTEs */
138 #define PT64_EPT_READABLE_MASK 0x1ull
139 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
141 #include <trace/events/kvm.h>
143 #define CREATE_TRACE_POINTS
144 #include "mmutrace.h"
146 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
147 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
149 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
151 /* make pte_list_desc fit well in cache line */
152 #define PTE_LIST_EXT 3
155 * Return values of handle_mmio_page_fault and mmu.page_fault:
156 * RET_PF_RETRY: let CPU fault again on the address.
157 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
159 * For handle_mmio_page_fault only:
160 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
168 struct pte_list_desc {
169 u64 *sptes[PTE_LIST_EXT];
170 struct pte_list_desc *more;
173 struct kvm_shadow_walk_iterator {
181 static const union kvm_mmu_page_role mmu_base_role_mask = {
192 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
193 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
195 shadow_walk_okay(&(_walker)); \
196 shadow_walk_next(&(_walker)))
198 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
199 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
200 shadow_walk_okay(&(_walker)); \
201 shadow_walk_next(&(_walker)))
203 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
204 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
205 shadow_walk_okay(&(_walker)) && \
206 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
207 __shadow_walk_next(&(_walker), spte))
209 static struct kmem_cache *pte_list_desc_cache;
210 static struct kmem_cache *mmu_page_header_cache;
211 static struct percpu_counter kvm_total_used_mmu_pages;
213 static u64 __read_mostly shadow_nx_mask;
214 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
215 static u64 __read_mostly shadow_user_mask;
216 static u64 __read_mostly shadow_accessed_mask;
217 static u64 __read_mostly shadow_dirty_mask;
218 static u64 __read_mostly shadow_mmio_mask;
219 static u64 __read_mostly shadow_mmio_value;
220 static u64 __read_mostly shadow_present_mask;
221 static u64 __read_mostly shadow_me_mask;
224 * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
225 * Non-present SPTEs with shadow_acc_track_value set are in place for access
228 static u64 __read_mostly shadow_acc_track_mask;
229 static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
232 * The mask/shift to use for saving the original R/X bits when marking the PTE
233 * as not-present for access tracking purposes. We do not save the W bit as the
234 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
235 * restored only when a write is attempted to the page.
237 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
238 PT64_EPT_EXECUTABLE_MASK;
239 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
242 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
243 * to guard against L1TF attacks.
245 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
248 * The number of high-order 1 bits to use in the mask above.
250 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
253 * In some cases, we need to preserve the GFN of a non-present or reserved
254 * SPTE when we usurp the upper five bits of the physical address space to
255 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
256 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
257 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
258 * high and low parts. This mask covers the lower bits of the GFN.
260 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
263 static void mmu_spte_set(u64 *sptep, u64 spte);
264 static union kvm_mmu_page_role
265 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
268 static inline bool kvm_available_flush_tlb_with_range(void)
270 return kvm_x86_ops->tlb_remote_flush_with_range;
273 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
274 struct kvm_tlb_range *range)
278 if (range && kvm_x86_ops->tlb_remote_flush_with_range)
279 ret = kvm_x86_ops->tlb_remote_flush_with_range(kvm, range);
282 kvm_flush_remote_tlbs(kvm);
285 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
286 u64 start_gfn, u64 pages)
288 struct kvm_tlb_range range;
290 range.start_gfn = start_gfn;
293 kvm_flush_remote_tlbs_with_range(kvm, &range);
296 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
298 BUG_ON((mmio_mask & mmio_value) != mmio_value);
299 shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
300 shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
302 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
304 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
306 return sp->role.ad_disabled;
309 static inline bool spte_ad_enabled(u64 spte)
311 MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
312 return !(spte & shadow_acc_track_value);
315 static inline u64 spte_shadow_accessed_mask(u64 spte)
317 MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
318 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
321 static inline u64 spte_shadow_dirty_mask(u64 spte)
323 MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
324 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
327 static inline bool is_access_track_spte(u64 spte)
329 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
333 * the low bit of the generation number is always presumed to be zero.
334 * This disables mmio caching during memslot updates. The concept is
335 * similar to a seqcount but instead of retrying the access we just punt
336 * and ignore the cache.
338 * spte bits 3-11 are used as bits 1-9 of the generation number,
339 * the bits 52-61 are used as bits 10-19 of the generation number.
341 #define MMIO_SPTE_GEN_LOW_SHIFT 2
342 #define MMIO_SPTE_GEN_HIGH_SHIFT 52
344 #define MMIO_GEN_SHIFT 20
345 #define MMIO_GEN_LOW_SHIFT 10
346 #define MMIO_GEN_LOW_MASK ((1 << MMIO_GEN_LOW_SHIFT) - 2)
347 #define MMIO_GEN_MASK ((1 << MMIO_GEN_SHIFT) - 1)
349 static u64 generation_mmio_spte_mask(unsigned int gen)
353 WARN_ON(gen & ~MMIO_GEN_MASK);
355 mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
356 mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
360 static unsigned int get_mmio_spte_generation(u64 spte)
364 spte &= ~shadow_mmio_mask;
366 gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
367 gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
371 static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
373 return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
376 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
379 unsigned int gen = kvm_current_mmio_generation(vcpu);
380 u64 mask = generation_mmio_spte_mask(gen);
381 u64 gpa = gfn << PAGE_SHIFT;
383 access &= ACC_WRITE_MASK | ACC_USER_MASK;
384 mask |= shadow_mmio_value | access;
385 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
386 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
387 << shadow_nonpresent_or_rsvd_mask_len;
389 trace_mark_mmio_spte(sptep, gfn, access, gen);
390 mmu_spte_set(sptep, mask);
393 static bool is_mmio_spte(u64 spte)
395 return (spte & shadow_mmio_mask) == shadow_mmio_value;
398 static gfn_t get_mmio_spte_gfn(u64 spte)
400 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
402 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
403 & shadow_nonpresent_or_rsvd_mask;
405 return gpa >> PAGE_SHIFT;
408 static unsigned get_mmio_spte_access(u64 spte)
410 u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
411 return (spte & ~mask) & ~PAGE_MASK;
414 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
415 kvm_pfn_t pfn, unsigned access)
417 if (unlikely(is_noslot_pfn(pfn))) {
418 mark_mmio_spte(vcpu, sptep, gfn, access);
425 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
427 unsigned int kvm_gen, spte_gen;
429 kvm_gen = kvm_current_mmio_generation(vcpu);
430 spte_gen = get_mmio_spte_generation(spte);
432 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
433 return likely(kvm_gen == spte_gen);
437 * Sets the shadow PTE masks used by the MMU.
440 * - Setting either @accessed_mask or @dirty_mask requires setting both
441 * - At least one of @accessed_mask or @acc_track_mask must be set
443 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
444 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
445 u64 acc_track_mask, u64 me_mask)
447 BUG_ON(!dirty_mask != !accessed_mask);
448 BUG_ON(!accessed_mask && !acc_track_mask);
449 BUG_ON(acc_track_mask & shadow_acc_track_value);
451 shadow_user_mask = user_mask;
452 shadow_accessed_mask = accessed_mask;
453 shadow_dirty_mask = dirty_mask;
454 shadow_nx_mask = nx_mask;
455 shadow_x_mask = x_mask;
456 shadow_present_mask = p_mask;
457 shadow_acc_track_mask = acc_track_mask;
458 shadow_me_mask = me_mask;
460 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
462 static void kvm_mmu_reset_all_pte_masks(void)
466 shadow_user_mask = 0;
467 shadow_accessed_mask = 0;
468 shadow_dirty_mask = 0;
471 shadow_mmio_mask = 0;
472 shadow_present_mask = 0;
473 shadow_acc_track_mask = 0;
476 * If the CPU has 46 or less physical address bits, then set an
477 * appropriate mask to guard against L1TF attacks. Otherwise, it is
478 * assumed that the CPU is not vulnerable to L1TF.
480 low_phys_bits = boot_cpu_data.x86_phys_bits;
481 if (boot_cpu_data.x86_phys_bits <
482 52 - shadow_nonpresent_or_rsvd_mask_len) {
483 shadow_nonpresent_or_rsvd_mask =
484 rsvd_bits(boot_cpu_data.x86_phys_bits -
485 shadow_nonpresent_or_rsvd_mask_len,
486 boot_cpu_data.x86_phys_bits - 1);
487 low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
489 shadow_nonpresent_or_rsvd_lower_gfn_mask =
490 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
493 static int is_cpuid_PSE36(void)
498 static int is_nx(struct kvm_vcpu *vcpu)
500 return vcpu->arch.efer & EFER_NX;
503 static int is_shadow_present_pte(u64 pte)
505 return (pte != 0) && !is_mmio_spte(pte);
508 static int is_large_pte(u64 pte)
510 return pte & PT_PAGE_SIZE_MASK;
513 static int is_last_spte(u64 pte, int level)
515 if (level == PT_PAGE_TABLE_LEVEL)
517 if (is_large_pte(pte))
522 static bool is_executable_pte(u64 spte)
524 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
527 static kvm_pfn_t spte_to_pfn(u64 pte)
529 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
532 static gfn_t pse36_gfn_delta(u32 gpte)
534 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
536 return (gpte & PT32_DIR_PSE36_MASK) << shift;
540 static void __set_spte(u64 *sptep, u64 spte)
542 WRITE_ONCE(*sptep, spte);
545 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
547 WRITE_ONCE(*sptep, spte);
550 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
552 return xchg(sptep, spte);
555 static u64 __get_spte_lockless(u64 *sptep)
557 return READ_ONCE(*sptep);
568 static void count_spte_clear(u64 *sptep, u64 spte)
570 struct kvm_mmu_page *sp = page_header(__pa(sptep));
572 if (is_shadow_present_pte(spte))
575 /* Ensure the spte is completely set before we increase the count */
577 sp->clear_spte_count++;
580 static void __set_spte(u64 *sptep, u64 spte)
582 union split_spte *ssptep, sspte;
584 ssptep = (union split_spte *)sptep;
585 sspte = (union split_spte)spte;
587 ssptep->spte_high = sspte.spte_high;
590 * If we map the spte from nonpresent to present, We should store
591 * the high bits firstly, then set present bit, so cpu can not
592 * fetch this spte while we are setting the spte.
596 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
599 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
601 union split_spte *ssptep, sspte;
603 ssptep = (union split_spte *)sptep;
604 sspte = (union split_spte)spte;
606 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
609 * If we map the spte from present to nonpresent, we should clear
610 * present bit firstly to avoid vcpu fetch the old high bits.
614 ssptep->spte_high = sspte.spte_high;
615 count_spte_clear(sptep, spte);
618 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
620 union split_spte *ssptep, sspte, orig;
622 ssptep = (union split_spte *)sptep;
623 sspte = (union split_spte)spte;
625 /* xchg acts as a barrier before the setting of the high bits */
626 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
627 orig.spte_high = ssptep->spte_high;
628 ssptep->spte_high = sspte.spte_high;
629 count_spte_clear(sptep, spte);
635 * The idea using the light way get the spte on x86_32 guest is from
636 * gup_get_pte(arch/x86/mm/gup.c).
638 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
639 * coalesces them and we are running out of the MMU lock. Therefore
640 * we need to protect against in-progress updates of the spte.
642 * Reading the spte while an update is in progress may get the old value
643 * for the high part of the spte. The race is fine for a present->non-present
644 * change (because the high part of the spte is ignored for non-present spte),
645 * but for a present->present change we must reread the spte.
647 * All such changes are done in two steps (present->non-present and
648 * non-present->present), hence it is enough to count the number of
649 * present->non-present updates: if it changed while reading the spte,
650 * we might have hit the race. This is done using clear_spte_count.
652 static u64 __get_spte_lockless(u64 *sptep)
654 struct kvm_mmu_page *sp = page_header(__pa(sptep));
655 union split_spte spte, *orig = (union split_spte *)sptep;
659 count = sp->clear_spte_count;
662 spte.spte_low = orig->spte_low;
665 spte.spte_high = orig->spte_high;
668 if (unlikely(spte.spte_low != orig->spte_low ||
669 count != sp->clear_spte_count))
676 static bool spte_can_locklessly_be_made_writable(u64 spte)
678 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
679 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
682 static bool spte_has_volatile_bits(u64 spte)
684 if (!is_shadow_present_pte(spte))
688 * Always atomically update spte if it can be updated
689 * out of mmu-lock, it can ensure dirty bit is not lost,
690 * also, it can help us to get a stable is_writable_pte()
691 * to ensure tlb flush is not missed.
693 if (spte_can_locklessly_be_made_writable(spte) ||
694 is_access_track_spte(spte))
697 if (spte_ad_enabled(spte)) {
698 if ((spte & shadow_accessed_mask) == 0 ||
699 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
706 static bool is_accessed_spte(u64 spte)
708 u64 accessed_mask = spte_shadow_accessed_mask(spte);
710 return accessed_mask ? spte & accessed_mask
711 : !is_access_track_spte(spte);
714 static bool is_dirty_spte(u64 spte)
716 u64 dirty_mask = spte_shadow_dirty_mask(spte);
718 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
721 /* Rules for using mmu_spte_set:
722 * Set the sptep from nonpresent to present.
723 * Note: the sptep being assigned *must* be either not present
724 * or in a state where the hardware will not attempt to update
727 static void mmu_spte_set(u64 *sptep, u64 new_spte)
729 WARN_ON(is_shadow_present_pte(*sptep));
730 __set_spte(sptep, new_spte);
734 * Update the SPTE (excluding the PFN), but do not track changes in its
735 * accessed/dirty status.
737 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
739 u64 old_spte = *sptep;
741 WARN_ON(!is_shadow_present_pte(new_spte));
743 if (!is_shadow_present_pte(old_spte)) {
744 mmu_spte_set(sptep, new_spte);
748 if (!spte_has_volatile_bits(old_spte))
749 __update_clear_spte_fast(sptep, new_spte);
751 old_spte = __update_clear_spte_slow(sptep, new_spte);
753 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
758 /* Rules for using mmu_spte_update:
759 * Update the state bits, it means the mapped pfn is not changed.
761 * Whenever we overwrite a writable spte with a read-only one we
762 * should flush remote TLBs. Otherwise rmap_write_protect
763 * will find a read-only spte, even though the writable spte
764 * might be cached on a CPU's TLB, the return value indicates this
767 * Returns true if the TLB needs to be flushed
769 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
772 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
774 if (!is_shadow_present_pte(old_spte))
778 * For the spte updated out of mmu-lock is safe, since
779 * we always atomically update it, see the comments in
780 * spte_has_volatile_bits().
782 if (spte_can_locklessly_be_made_writable(old_spte) &&
783 !is_writable_pte(new_spte))
787 * Flush TLB when accessed/dirty states are changed in the page tables,
788 * to guarantee consistency between TLB and page tables.
791 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
793 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
796 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
798 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
805 * Rules for using mmu_spte_clear_track_bits:
806 * It sets the sptep from present to nonpresent, and track the
807 * state bits, it is used to clear the last level sptep.
808 * Returns non-zero if the PTE was previously valid.
810 static int mmu_spte_clear_track_bits(u64 *sptep)
813 u64 old_spte = *sptep;
815 if (!spte_has_volatile_bits(old_spte))
816 __update_clear_spte_fast(sptep, 0ull);
818 old_spte = __update_clear_spte_slow(sptep, 0ull);
820 if (!is_shadow_present_pte(old_spte))
823 pfn = spte_to_pfn(old_spte);
826 * KVM does not hold the refcount of the page used by
827 * kvm mmu, before reclaiming the page, we should
828 * unmap it from mmu first.
830 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
832 if (is_accessed_spte(old_spte))
833 kvm_set_pfn_accessed(pfn);
835 if (is_dirty_spte(old_spte))
836 kvm_set_pfn_dirty(pfn);
842 * Rules for using mmu_spte_clear_no_track:
843 * Directly clear spte without caring the state bits of sptep,
844 * it is used to set the upper level spte.
846 static void mmu_spte_clear_no_track(u64 *sptep)
848 __update_clear_spte_fast(sptep, 0ull);
851 static u64 mmu_spte_get_lockless(u64 *sptep)
853 return __get_spte_lockless(sptep);
856 static u64 mark_spte_for_access_track(u64 spte)
858 if (spte_ad_enabled(spte))
859 return spte & ~shadow_accessed_mask;
861 if (is_access_track_spte(spte))
865 * Making an Access Tracking PTE will result in removal of write access
866 * from the PTE. So, verify that we will be able to restore the write
867 * access in the fast page fault path later on.
869 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
870 !spte_can_locklessly_be_made_writable(spte),
871 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
873 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
874 shadow_acc_track_saved_bits_shift),
875 "kvm: Access Tracking saved bit locations are not zero\n");
877 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
878 shadow_acc_track_saved_bits_shift;
879 spte &= ~shadow_acc_track_mask;
884 /* Restore an acc-track PTE back to a regular PTE */
885 static u64 restore_acc_track_spte(u64 spte)
888 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
889 & shadow_acc_track_saved_bits_mask;
891 WARN_ON_ONCE(spte_ad_enabled(spte));
892 WARN_ON_ONCE(!is_access_track_spte(spte));
894 new_spte &= ~shadow_acc_track_mask;
895 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
896 shadow_acc_track_saved_bits_shift);
897 new_spte |= saved_bits;
902 /* Returns the Accessed status of the PTE and resets it at the same time. */
903 static bool mmu_spte_age(u64 *sptep)
905 u64 spte = mmu_spte_get_lockless(sptep);
907 if (!is_accessed_spte(spte))
910 if (spte_ad_enabled(spte)) {
911 clear_bit((ffs(shadow_accessed_mask) - 1),
912 (unsigned long *)sptep);
915 * Capture the dirty status of the page, so that it doesn't get
916 * lost when the SPTE is marked for access tracking.
918 if (is_writable_pte(spte))
919 kvm_set_pfn_dirty(spte_to_pfn(spte));
921 spte = mark_spte_for_access_track(spte);
922 mmu_spte_update_no_track(sptep, spte);
928 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
931 * Prevent page table teardown by making any free-er wait during
932 * kvm_flush_remote_tlbs() IPI to all active vcpus.
937 * Make sure a following spte read is not reordered ahead of the write
940 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
943 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
946 * Make sure the write to vcpu->mode is not reordered in front of
947 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
948 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
950 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
954 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
955 struct kmem_cache *base_cache, int min)
959 if (cache->nobjs >= min)
961 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
962 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
964 return cache->nobjs >= min ? 0 : -ENOMEM;
965 cache->objects[cache->nobjs++] = obj;
970 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
975 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
976 struct kmem_cache *cache)
979 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
982 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
987 if (cache->nobjs >= min)
989 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
990 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
992 return cache->nobjs >= min ? 0 : -ENOMEM;
993 cache->objects[cache->nobjs++] = page;
998 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1001 free_page((unsigned long)mc->objects[--mc->nobjs]);
1004 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1008 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1009 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1012 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1015 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1016 mmu_page_header_cache, 4);
1021 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1023 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1024 pte_list_desc_cache);
1025 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1026 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1027 mmu_page_header_cache);
1030 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1035 p = mc->objects[--mc->nobjs];
1039 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1041 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1044 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1046 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1049 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1051 if (!sp->role.direct)
1052 return sp->gfns[index];
1054 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1057 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1059 if (sp->role.direct)
1060 BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index));
1062 sp->gfns[index] = gfn;
1066 * Return the pointer to the large page information for a given gfn,
1067 * handling slots that are not large page aligned.
1069 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1070 struct kvm_memory_slot *slot,
1075 idx = gfn_to_index(gfn, slot->base_gfn, level);
1076 return &slot->arch.lpage_info[level - 2][idx];
1079 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1080 gfn_t gfn, int count)
1082 struct kvm_lpage_info *linfo;
1085 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1086 linfo = lpage_info_slot(gfn, slot, i);
1087 linfo->disallow_lpage += count;
1088 WARN_ON(linfo->disallow_lpage < 0);
1092 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1094 update_gfn_disallow_lpage_count(slot, gfn, 1);
1097 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1099 update_gfn_disallow_lpage_count(slot, gfn, -1);
1102 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1104 struct kvm_memslots *slots;
1105 struct kvm_memory_slot *slot;
1108 kvm->arch.indirect_shadow_pages++;
1110 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1111 slot = __gfn_to_memslot(slots, gfn);
1113 /* the non-leaf shadow pages are keeping readonly. */
1114 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1115 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1116 KVM_PAGE_TRACK_WRITE);
1118 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1121 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1123 struct kvm_memslots *slots;
1124 struct kvm_memory_slot *slot;
1127 kvm->arch.indirect_shadow_pages--;
1129 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1130 slot = __gfn_to_memslot(slots, gfn);
1131 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1132 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1133 KVM_PAGE_TRACK_WRITE);
1135 kvm_mmu_gfn_allow_lpage(slot, gfn);
1138 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1139 struct kvm_memory_slot *slot)
1141 struct kvm_lpage_info *linfo;
1144 linfo = lpage_info_slot(gfn, slot, level);
1145 return !!linfo->disallow_lpage;
1151 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1154 struct kvm_memory_slot *slot;
1156 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1157 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1160 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1162 unsigned long page_size;
1165 page_size = kvm_host_page_size(kvm, gfn);
1167 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1168 if (page_size >= KVM_HPAGE_SIZE(i))
1177 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1180 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1182 if (no_dirty_log && slot->dirty_bitmap)
1188 static struct kvm_memory_slot *
1189 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1192 struct kvm_memory_slot *slot;
1194 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1195 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1201 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1202 bool *force_pt_level)
1204 int host_level, level, max_level;
1205 struct kvm_memory_slot *slot;
1207 if (unlikely(*force_pt_level))
1208 return PT_PAGE_TABLE_LEVEL;
1210 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1211 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1212 if (unlikely(*force_pt_level))
1213 return PT_PAGE_TABLE_LEVEL;
1215 host_level = host_mapping_level(vcpu->kvm, large_gfn);
1217 if (host_level == PT_PAGE_TABLE_LEVEL)
1220 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1222 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1223 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1230 * About rmap_head encoding:
1232 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1233 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1234 * pte_list_desc containing more mappings.
1238 * Returns the number of pointers in the rmap chain, not counting the new one.
1240 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1241 struct kvm_rmap_head *rmap_head)
1243 struct pte_list_desc *desc;
1246 if (!rmap_head->val) {
1247 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1248 rmap_head->val = (unsigned long)spte;
1249 } else if (!(rmap_head->val & 1)) {
1250 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1251 desc = mmu_alloc_pte_list_desc(vcpu);
1252 desc->sptes[0] = (u64 *)rmap_head->val;
1253 desc->sptes[1] = spte;
1254 rmap_head->val = (unsigned long)desc | 1;
1257 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1258 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1259 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1261 count += PTE_LIST_EXT;
1263 if (desc->sptes[PTE_LIST_EXT-1]) {
1264 desc->more = mmu_alloc_pte_list_desc(vcpu);
1267 for (i = 0; desc->sptes[i]; ++i)
1269 desc->sptes[i] = spte;
1275 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1276 struct pte_list_desc *desc, int i,
1277 struct pte_list_desc *prev_desc)
1281 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1283 desc->sptes[i] = desc->sptes[j];
1284 desc->sptes[j] = NULL;
1287 if (!prev_desc && !desc->more)
1288 rmap_head->val = (unsigned long)desc->sptes[0];
1291 prev_desc->more = desc->more;
1293 rmap_head->val = (unsigned long)desc->more | 1;
1294 mmu_free_pte_list_desc(desc);
1297 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1299 struct pte_list_desc *desc;
1300 struct pte_list_desc *prev_desc;
1303 if (!rmap_head->val) {
1304 pr_err("%s: %p 0->BUG\n", __func__, spte);
1306 } else if (!(rmap_head->val & 1)) {
1307 rmap_printk("%s: %p 1->0\n", __func__, spte);
1308 if ((u64 *)rmap_head->val != spte) {
1309 pr_err("%s: %p 1->BUG\n", __func__, spte);
1314 rmap_printk("%s: %p many->many\n", __func__, spte);
1315 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1318 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1319 if (desc->sptes[i] == spte) {
1320 pte_list_desc_remove_entry(rmap_head,
1321 desc, i, prev_desc);
1328 pr_err("%s: %p many->many\n", __func__, spte);
1333 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1335 mmu_spte_clear_track_bits(sptep);
1336 __pte_list_remove(sptep, rmap_head);
1339 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1340 struct kvm_memory_slot *slot)
1344 idx = gfn_to_index(gfn, slot->base_gfn, level);
1345 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1348 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1349 struct kvm_mmu_page *sp)
1351 struct kvm_memslots *slots;
1352 struct kvm_memory_slot *slot;
1354 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1355 slot = __gfn_to_memslot(slots, gfn);
1356 return __gfn_to_rmap(gfn, sp->role.level, slot);
1359 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1361 struct kvm_mmu_memory_cache *cache;
1363 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1364 return mmu_memory_cache_free_objects(cache);
1367 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1369 struct kvm_mmu_page *sp;
1370 struct kvm_rmap_head *rmap_head;
1372 sp = page_header(__pa(spte));
1373 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1374 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1375 return pte_list_add(vcpu, spte, rmap_head);
1378 static void rmap_remove(struct kvm *kvm, u64 *spte)
1380 struct kvm_mmu_page *sp;
1382 struct kvm_rmap_head *rmap_head;
1384 sp = page_header(__pa(spte));
1385 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1386 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1387 __pte_list_remove(spte, rmap_head);
1391 * Used by the following functions to iterate through the sptes linked by a
1392 * rmap. All fields are private and not assumed to be used outside.
1394 struct rmap_iterator {
1395 /* private fields */
1396 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1397 int pos; /* index of the sptep */
1401 * Iteration must be started by this function. This should also be used after
1402 * removing/dropping sptes from the rmap link because in such cases the
1403 * information in the itererator may not be valid.
1405 * Returns sptep if found, NULL otherwise.
1407 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1408 struct rmap_iterator *iter)
1412 if (!rmap_head->val)
1415 if (!(rmap_head->val & 1)) {
1417 sptep = (u64 *)rmap_head->val;
1421 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1423 sptep = iter->desc->sptes[iter->pos];
1425 BUG_ON(!is_shadow_present_pte(*sptep));
1430 * Must be used with a valid iterator: e.g. after rmap_get_first().
1432 * Returns sptep if found, NULL otherwise.
1434 static u64 *rmap_get_next(struct rmap_iterator *iter)
1439 if (iter->pos < PTE_LIST_EXT - 1) {
1441 sptep = iter->desc->sptes[iter->pos];
1446 iter->desc = iter->desc->more;
1450 /* desc->sptes[0] cannot be NULL */
1451 sptep = iter->desc->sptes[iter->pos];
1458 BUG_ON(!is_shadow_present_pte(*sptep));
1462 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1463 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1464 _spte_; _spte_ = rmap_get_next(_iter_))
1466 static void drop_spte(struct kvm *kvm, u64 *sptep)
1468 if (mmu_spte_clear_track_bits(sptep))
1469 rmap_remove(kvm, sptep);
1473 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1475 if (is_large_pte(*sptep)) {
1476 WARN_ON(page_header(__pa(sptep))->role.level ==
1477 PT_PAGE_TABLE_LEVEL);
1478 drop_spte(kvm, sptep);
1486 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1488 if (__drop_large_spte(vcpu->kvm, sptep)) {
1489 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1491 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1492 KVM_PAGES_PER_HPAGE(sp->role.level));
1497 * Write-protect on the specified @sptep, @pt_protect indicates whether
1498 * spte write-protection is caused by protecting shadow page table.
1500 * Note: write protection is difference between dirty logging and spte
1502 * - for dirty logging, the spte can be set to writable at anytime if
1503 * its dirty bitmap is properly set.
1504 * - for spte protection, the spte can be writable only after unsync-ing
1507 * Return true if tlb need be flushed.
1509 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1513 if (!is_writable_pte(spte) &&
1514 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1517 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1520 spte &= ~SPTE_MMU_WRITEABLE;
1521 spte = spte & ~PT_WRITABLE_MASK;
1523 return mmu_spte_update(sptep, spte);
1526 static bool __rmap_write_protect(struct kvm *kvm,
1527 struct kvm_rmap_head *rmap_head,
1531 struct rmap_iterator iter;
1534 for_each_rmap_spte(rmap_head, &iter, sptep)
1535 flush |= spte_write_protect(sptep, pt_protect);
1540 static bool spte_clear_dirty(u64 *sptep)
1544 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1546 spte &= ~shadow_dirty_mask;
1548 return mmu_spte_update(sptep, spte);
1551 static bool wrprot_ad_disabled_spte(u64 *sptep)
1553 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1554 (unsigned long *)sptep);
1556 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1558 return was_writable;
1562 * Gets the GFN ready for another round of dirty logging by clearing the
1563 * - D bit on ad-enabled SPTEs, and
1564 * - W bit on ad-disabled SPTEs.
1565 * Returns true iff any D or W bits were cleared.
1567 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1570 struct rmap_iterator iter;
1573 for_each_rmap_spte(rmap_head, &iter, sptep)
1574 if (spte_ad_enabled(*sptep))
1575 flush |= spte_clear_dirty(sptep);
1577 flush |= wrprot_ad_disabled_spte(sptep);
1582 static bool spte_set_dirty(u64 *sptep)
1586 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1588 spte |= shadow_dirty_mask;
1590 return mmu_spte_update(sptep, spte);
1593 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1596 struct rmap_iterator iter;
1599 for_each_rmap_spte(rmap_head, &iter, sptep)
1600 if (spte_ad_enabled(*sptep))
1601 flush |= spte_set_dirty(sptep);
1607 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1608 * @kvm: kvm instance
1609 * @slot: slot to protect
1610 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1611 * @mask: indicates which pages we should protect
1613 * Used when we do not need to care about huge page mappings: e.g. during dirty
1614 * logging we do not have any such mappings.
1616 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1617 struct kvm_memory_slot *slot,
1618 gfn_t gfn_offset, unsigned long mask)
1620 struct kvm_rmap_head *rmap_head;
1623 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1624 PT_PAGE_TABLE_LEVEL, slot);
1625 __rmap_write_protect(kvm, rmap_head, false);
1627 /* clear the first set bit */
1633 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1634 * protect the page if the D-bit isn't supported.
1635 * @kvm: kvm instance
1636 * @slot: slot to clear D-bit
1637 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1638 * @mask: indicates which pages we should clear D-bit
1640 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1642 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1643 struct kvm_memory_slot *slot,
1644 gfn_t gfn_offset, unsigned long mask)
1646 struct kvm_rmap_head *rmap_head;
1649 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1650 PT_PAGE_TABLE_LEVEL, slot);
1651 __rmap_clear_dirty(kvm, rmap_head);
1653 /* clear the first set bit */
1657 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1660 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1663 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1664 * enable dirty logging for them.
1666 * Used when we do not need to care about huge page mappings: e.g. during dirty
1667 * logging we do not have any such mappings.
1669 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1670 struct kvm_memory_slot *slot,
1671 gfn_t gfn_offset, unsigned long mask)
1673 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1674 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1677 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1681 * kvm_arch_write_log_dirty - emulate dirty page logging
1682 * @vcpu: Guest mode vcpu
1684 * Emulate arch specific page modification logging for the
1687 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1689 if (kvm_x86_ops->write_log_dirty)
1690 return kvm_x86_ops->write_log_dirty(vcpu);
1695 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1696 struct kvm_memory_slot *slot, u64 gfn)
1698 struct kvm_rmap_head *rmap_head;
1700 bool write_protected = false;
1702 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1703 rmap_head = __gfn_to_rmap(gfn, i, slot);
1704 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1707 return write_protected;
1710 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1712 struct kvm_memory_slot *slot;
1714 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1715 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1718 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1721 struct rmap_iterator iter;
1724 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1725 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1727 pte_list_remove(rmap_head, sptep);
1734 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1735 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1738 return kvm_zap_rmapp(kvm, rmap_head);
1741 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1742 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1746 struct rmap_iterator iter;
1749 pte_t *ptep = (pte_t *)data;
1752 WARN_ON(pte_huge(*ptep));
1753 new_pfn = pte_pfn(*ptep);
1756 for_each_rmap_spte(rmap_head, &iter, sptep) {
1757 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1758 sptep, *sptep, gfn, level);
1762 if (pte_write(*ptep)) {
1763 pte_list_remove(rmap_head, sptep);
1766 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1767 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1769 new_spte &= ~PT_WRITABLE_MASK;
1770 new_spte &= ~SPTE_HOST_WRITEABLE;
1772 new_spte = mark_spte_for_access_track(new_spte);
1774 mmu_spte_clear_track_bits(sptep);
1775 mmu_spte_set(sptep, new_spte);
1779 if (need_flush && kvm_available_flush_tlb_with_range()) {
1780 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1787 struct slot_rmap_walk_iterator {
1789 struct kvm_memory_slot *slot;
1795 /* output fields. */
1797 struct kvm_rmap_head *rmap;
1800 /* private field. */
1801 struct kvm_rmap_head *end_rmap;
1805 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1807 iterator->level = level;
1808 iterator->gfn = iterator->start_gfn;
1809 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1810 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1815 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1816 struct kvm_memory_slot *slot, int start_level,
1817 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1819 iterator->slot = slot;
1820 iterator->start_level = start_level;
1821 iterator->end_level = end_level;
1822 iterator->start_gfn = start_gfn;
1823 iterator->end_gfn = end_gfn;
1825 rmap_walk_init_level(iterator, iterator->start_level);
1828 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1830 return !!iterator->rmap;
1833 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1835 if (++iterator->rmap <= iterator->end_rmap) {
1836 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1840 if (++iterator->level > iterator->end_level) {
1841 iterator->rmap = NULL;
1845 rmap_walk_init_level(iterator, iterator->level);
1848 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1849 _start_gfn, _end_gfn, _iter_) \
1850 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1851 _end_level_, _start_gfn, _end_gfn); \
1852 slot_rmap_walk_okay(_iter_); \
1853 slot_rmap_walk_next(_iter_))
1855 static int kvm_handle_hva_range(struct kvm *kvm,
1856 unsigned long start,
1859 int (*handler)(struct kvm *kvm,
1860 struct kvm_rmap_head *rmap_head,
1861 struct kvm_memory_slot *slot,
1864 unsigned long data))
1866 struct kvm_memslots *slots;
1867 struct kvm_memory_slot *memslot;
1868 struct slot_rmap_walk_iterator iterator;
1872 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1873 slots = __kvm_memslots(kvm, i);
1874 kvm_for_each_memslot(memslot, slots) {
1875 unsigned long hva_start, hva_end;
1876 gfn_t gfn_start, gfn_end;
1878 hva_start = max(start, memslot->userspace_addr);
1879 hva_end = min(end, memslot->userspace_addr +
1880 (memslot->npages << PAGE_SHIFT));
1881 if (hva_start >= hva_end)
1884 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1885 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1887 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1888 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1890 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1891 PT_MAX_HUGEPAGE_LEVEL,
1892 gfn_start, gfn_end - 1,
1894 ret |= handler(kvm, iterator.rmap, memslot,
1895 iterator.gfn, iterator.level, data);
1902 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1904 int (*handler)(struct kvm *kvm,
1905 struct kvm_rmap_head *rmap_head,
1906 struct kvm_memory_slot *slot,
1907 gfn_t gfn, int level,
1908 unsigned long data))
1910 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1913 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1915 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1918 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1920 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1923 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1924 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1928 struct rmap_iterator uninitialized_var(iter);
1931 for_each_rmap_spte(rmap_head, &iter, sptep)
1932 young |= mmu_spte_age(sptep);
1934 trace_kvm_age_page(gfn, level, slot, young);
1938 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1939 struct kvm_memory_slot *slot, gfn_t gfn,
1940 int level, unsigned long data)
1943 struct rmap_iterator iter;
1945 for_each_rmap_spte(rmap_head, &iter, sptep)
1946 if (is_accessed_spte(*sptep))
1951 #define RMAP_RECYCLE_THRESHOLD 1000
1953 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1955 struct kvm_rmap_head *rmap_head;
1956 struct kvm_mmu_page *sp;
1958 sp = page_header(__pa(spte));
1960 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1962 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1963 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1964 KVM_PAGES_PER_HPAGE(sp->role.level));
1967 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1969 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
1972 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1974 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1978 static int is_empty_shadow_page(u64 *spt)
1983 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1984 if (is_shadow_present_pte(*pos)) {
1985 printk(KERN_ERR "%s: %p %llx\n", __func__,
1994 * This value is the sum of all of the kvm instances's
1995 * kvm->arch.n_used_mmu_pages values. We need a global,
1996 * aggregate version in order to make the slab shrinker
1999 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
2001 kvm->arch.n_used_mmu_pages += nr;
2002 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2005 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2007 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2008 hlist_del(&sp->hash_link);
2009 list_del(&sp->link);
2010 free_page((unsigned long)sp->spt);
2011 if (!sp->role.direct)
2012 free_page((unsigned long)sp->gfns);
2013 kmem_cache_free(mmu_page_header_cache, sp);
2016 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2018 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2021 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2022 struct kvm_mmu_page *sp, u64 *parent_pte)
2027 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2030 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2033 __pte_list_remove(parent_pte, &sp->parent_ptes);
2036 static void drop_parent_pte(struct kvm_mmu_page *sp,
2039 mmu_page_remove_parent_pte(sp, parent_pte);
2040 mmu_spte_clear_no_track(parent_pte);
2043 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2045 struct kvm_mmu_page *sp;
2047 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2048 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2050 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2051 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2054 * The active_mmu_pages list is the FIFO list, do not move the
2055 * page until it is zapped. kvm_zap_obsolete_pages depends on
2056 * this feature. See the comments in kvm_zap_obsolete_pages().
2058 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2059 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2063 static void mark_unsync(u64 *spte);
2064 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2067 struct rmap_iterator iter;
2069 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2074 static void mark_unsync(u64 *spte)
2076 struct kvm_mmu_page *sp;
2079 sp = page_header(__pa(spte));
2080 index = spte - sp->spt;
2081 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2083 if (sp->unsync_children++)
2085 kvm_mmu_mark_parents_unsync(sp);
2088 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2089 struct kvm_mmu_page *sp)
2094 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2098 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2099 struct kvm_mmu_page *sp, u64 *spte,
2105 #define KVM_PAGE_ARRAY_NR 16
2107 struct kvm_mmu_pages {
2108 struct mmu_page_and_offset {
2109 struct kvm_mmu_page *sp;
2111 } page[KVM_PAGE_ARRAY_NR];
2115 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2121 for (i=0; i < pvec->nr; i++)
2122 if (pvec->page[i].sp == sp)
2125 pvec->page[pvec->nr].sp = sp;
2126 pvec->page[pvec->nr].idx = idx;
2128 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2131 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2133 --sp->unsync_children;
2134 WARN_ON((int)sp->unsync_children < 0);
2135 __clear_bit(idx, sp->unsync_child_bitmap);
2138 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2139 struct kvm_mmu_pages *pvec)
2141 int i, ret, nr_unsync_leaf = 0;
2143 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2144 struct kvm_mmu_page *child;
2145 u64 ent = sp->spt[i];
2147 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2148 clear_unsync_child_bit(sp, i);
2152 child = page_header(ent & PT64_BASE_ADDR_MASK);
2154 if (child->unsync_children) {
2155 if (mmu_pages_add(pvec, child, i))
2158 ret = __mmu_unsync_walk(child, pvec);
2160 clear_unsync_child_bit(sp, i);
2162 } else if (ret > 0) {
2163 nr_unsync_leaf += ret;
2166 } else if (child->unsync) {
2168 if (mmu_pages_add(pvec, child, i))
2171 clear_unsync_child_bit(sp, i);
2174 return nr_unsync_leaf;
2177 #define INVALID_INDEX (-1)
2179 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2180 struct kvm_mmu_pages *pvec)
2183 if (!sp->unsync_children)
2186 mmu_pages_add(pvec, sp, INVALID_INDEX);
2187 return __mmu_unsync_walk(sp, pvec);
2190 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2192 WARN_ON(!sp->unsync);
2193 trace_kvm_mmu_sync_page(sp);
2195 --kvm->stat.mmu_unsync;
2198 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2199 struct list_head *invalid_list);
2200 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2201 struct list_head *invalid_list);
2204 * NOTE: we should pay more attention on the zapped-obsolete page
2205 * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
2206 * since it has been deleted from active_mmu_pages but still can be found
2209 * for_each_valid_sp() has skipped that kind of pages.
2211 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2212 hlist_for_each_entry(_sp, \
2213 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2214 if (is_obsolete_sp((_kvm), (_sp)) || (_sp)->role.invalid) { \
2217 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2218 for_each_valid_sp(_kvm, _sp, _gfn) \
2219 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2221 /* @sp->gfn should be write-protected at the call site */
2222 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2223 struct list_head *invalid_list)
2225 if (sp->role.cr4_pae != !!is_pae(vcpu)
2226 || vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2227 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2234 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2235 struct list_head *invalid_list,
2236 bool remote_flush, bool local_flush)
2238 if (!list_empty(invalid_list)) {
2239 kvm_mmu_commit_zap_page(vcpu->kvm, invalid_list);
2244 kvm_flush_remote_tlbs(vcpu->kvm);
2245 else if (local_flush)
2246 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2249 #ifdef CONFIG_KVM_MMU_AUDIT
2250 #include "mmu_audit.c"
2252 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2253 static void mmu_audit_disable(void) { }
2256 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2258 return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2261 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2262 struct list_head *invalid_list)
2264 kvm_unlink_unsync_page(vcpu->kvm, sp);
2265 return __kvm_sync_page(vcpu, sp, invalid_list);
2268 /* @gfn should be write-protected at the call site */
2269 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2270 struct list_head *invalid_list)
2272 struct kvm_mmu_page *s;
2275 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2279 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2280 ret |= kvm_sync_page(vcpu, s, invalid_list);
2286 struct mmu_page_path {
2287 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2288 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2291 #define for_each_sp(pvec, sp, parents, i) \
2292 for (i = mmu_pages_first(&pvec, &parents); \
2293 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2294 i = mmu_pages_next(&pvec, &parents, i))
2296 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2297 struct mmu_page_path *parents,
2302 for (n = i+1; n < pvec->nr; n++) {
2303 struct kvm_mmu_page *sp = pvec->page[n].sp;
2304 unsigned idx = pvec->page[n].idx;
2305 int level = sp->role.level;
2307 parents->idx[level-1] = idx;
2308 if (level == PT_PAGE_TABLE_LEVEL)
2311 parents->parent[level-2] = sp;
2317 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2318 struct mmu_page_path *parents)
2320 struct kvm_mmu_page *sp;
2326 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2328 sp = pvec->page[0].sp;
2329 level = sp->role.level;
2330 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2332 parents->parent[level-2] = sp;
2334 /* Also set up a sentinel. Further entries in pvec are all
2335 * children of sp, so this element is never overwritten.
2337 parents->parent[level-1] = NULL;
2338 return mmu_pages_next(pvec, parents, 0);
2341 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2343 struct kvm_mmu_page *sp;
2344 unsigned int level = 0;
2347 unsigned int idx = parents->idx[level];
2348 sp = parents->parent[level];
2352 WARN_ON(idx == INVALID_INDEX);
2353 clear_unsync_child_bit(sp, idx);
2355 } while (!sp->unsync_children);
2358 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2359 struct kvm_mmu_page *parent)
2362 struct kvm_mmu_page *sp;
2363 struct mmu_page_path parents;
2364 struct kvm_mmu_pages pages;
2365 LIST_HEAD(invalid_list);
2368 while (mmu_unsync_walk(parent, &pages)) {
2369 bool protected = false;
2371 for_each_sp(pages, sp, parents, i)
2372 protected |= rmap_write_protect(vcpu, sp->gfn);
2375 kvm_flush_remote_tlbs(vcpu->kvm);
2379 for_each_sp(pages, sp, parents, i) {
2380 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2381 mmu_pages_clear_parents(&parents);
2383 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2384 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2385 cond_resched_lock(&vcpu->kvm->mmu_lock);
2390 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2393 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2395 atomic_set(&sp->write_flooding_count, 0);
2398 static void clear_sp_write_flooding_count(u64 *spte)
2400 struct kvm_mmu_page *sp = page_header(__pa(spte));
2402 __clear_sp_write_flooding_count(sp);
2405 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2412 union kvm_mmu_page_role role;
2414 struct kvm_mmu_page *sp;
2415 bool need_sync = false;
2418 LIST_HEAD(invalid_list);
2420 role = vcpu->arch.mmu->mmu_role.base;
2422 role.direct = direct;
2425 role.access = access;
2426 if (!vcpu->arch.mmu->direct_map
2427 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2428 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2429 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2430 role.quadrant = quadrant;
2432 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2433 if (sp->gfn != gfn) {
2438 if (!need_sync && sp->unsync)
2441 if (sp->role.word != role.word)
2445 /* The page is good, but __kvm_sync_page might still end
2446 * up zapping it. If so, break in order to rebuild it.
2448 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2451 WARN_ON(!list_empty(&invalid_list));
2452 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2455 if (sp->unsync_children)
2456 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2458 __clear_sp_write_flooding_count(sp);
2459 trace_kvm_mmu_get_page(sp, false);
2463 ++vcpu->kvm->stat.mmu_cache_miss;
2465 sp = kvm_mmu_alloc_page(vcpu, direct);
2469 hlist_add_head(&sp->hash_link,
2470 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2473 * we should do write protection before syncing pages
2474 * otherwise the content of the synced shadow page may
2475 * be inconsistent with guest page table.
2477 account_shadowed(vcpu->kvm, sp);
2478 if (level == PT_PAGE_TABLE_LEVEL &&
2479 rmap_write_protect(vcpu, gfn))
2480 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2482 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2483 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2485 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2486 clear_page(sp->spt);
2487 trace_kvm_mmu_get_page(sp, true);
2489 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2491 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2492 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2496 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2497 struct kvm_vcpu *vcpu, hpa_t root,
2500 iterator->addr = addr;
2501 iterator->shadow_addr = root;
2502 iterator->level = vcpu->arch.mmu->shadow_root_level;
2504 if (iterator->level == PT64_ROOT_4LEVEL &&
2505 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2506 !vcpu->arch.mmu->direct_map)
2509 if (iterator->level == PT32E_ROOT_LEVEL) {
2511 * prev_root is currently only used for 64-bit hosts. So only
2512 * the active root_hpa is valid here.
2514 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2516 iterator->shadow_addr
2517 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2518 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2520 if (!iterator->shadow_addr)
2521 iterator->level = 0;
2525 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2526 struct kvm_vcpu *vcpu, u64 addr)
2528 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2532 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2534 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2537 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2538 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2542 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2545 if (is_last_spte(spte, iterator->level)) {
2546 iterator->level = 0;
2550 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2554 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2556 __shadow_walk_next(iterator, *iterator->sptep);
2559 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2560 struct kvm_mmu_page *sp)
2564 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2566 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2567 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2569 if (sp_ad_disabled(sp))
2570 spte |= shadow_acc_track_value;
2572 spte |= shadow_accessed_mask;
2574 mmu_spte_set(sptep, spte);
2576 mmu_page_add_parent_pte(vcpu, sp, sptep);
2578 if (sp->unsync_children || sp->unsync)
2582 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2583 unsigned direct_access)
2585 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2586 struct kvm_mmu_page *child;
2589 * For the direct sp, if the guest pte's dirty bit
2590 * changed form clean to dirty, it will corrupt the
2591 * sp's access: allow writable in the read-only sp,
2592 * so we should update the spte at this point to get
2593 * a new sp with the correct access.
2595 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2596 if (child->role.access == direct_access)
2599 drop_parent_pte(child, sptep);
2600 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2604 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2608 struct kvm_mmu_page *child;
2611 if (is_shadow_present_pte(pte)) {
2612 if (is_last_spte(pte, sp->role.level)) {
2613 drop_spte(kvm, spte);
2614 if (is_large_pte(pte))
2617 child = page_header(pte & PT64_BASE_ADDR_MASK);
2618 drop_parent_pte(child, spte);
2623 if (is_mmio_spte(pte))
2624 mmu_spte_clear_no_track(spte);
2629 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2630 struct kvm_mmu_page *sp)
2634 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2635 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2638 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2641 struct rmap_iterator iter;
2643 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2644 drop_parent_pte(sp, sptep);
2647 static int mmu_zap_unsync_children(struct kvm *kvm,
2648 struct kvm_mmu_page *parent,
2649 struct list_head *invalid_list)
2652 struct mmu_page_path parents;
2653 struct kvm_mmu_pages pages;
2655 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2658 while (mmu_unsync_walk(parent, &pages)) {
2659 struct kvm_mmu_page *sp;
2661 for_each_sp(pages, sp, parents, i) {
2662 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2663 mmu_pages_clear_parents(&parents);
2671 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2672 struct list_head *invalid_list)
2676 trace_kvm_mmu_prepare_zap_page(sp);
2677 ++kvm->stat.mmu_shadow_zapped;
2678 ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
2679 kvm_mmu_page_unlink_children(kvm, sp);
2680 kvm_mmu_unlink_parents(kvm, sp);
2682 if (!sp->role.invalid && !sp->role.direct)
2683 unaccount_shadowed(kvm, sp);
2686 kvm_unlink_unsync_page(kvm, sp);
2687 if (!sp->root_count) {
2690 list_move(&sp->link, invalid_list);
2691 kvm_mod_used_mmu_pages(kvm, -1);
2693 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2696 * The obsolete pages can not be used on any vcpus.
2697 * See the comments in kvm_mmu_invalidate_zap_all_pages().
2699 if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
2700 kvm_reload_remote_mmus(kvm);
2703 sp->role.invalid = 1;
2707 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2708 struct list_head *invalid_list)
2710 struct kvm_mmu_page *sp, *nsp;
2712 if (list_empty(invalid_list))
2716 * We need to make sure everyone sees our modifications to
2717 * the page tables and see changes to vcpu->mode here. The barrier
2718 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2719 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2721 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2722 * guest mode and/or lockless shadow page table walks.
2724 kvm_flush_remote_tlbs(kvm);
2726 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2727 WARN_ON(!sp->role.invalid || sp->root_count);
2728 kvm_mmu_free_page(sp);
2732 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2733 struct list_head *invalid_list)
2735 struct kvm_mmu_page *sp;
2737 if (list_empty(&kvm->arch.active_mmu_pages))
2740 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2741 struct kvm_mmu_page, link);
2742 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2746 * Changing the number of mmu pages allocated to the vm
2747 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2749 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
2751 LIST_HEAD(invalid_list);
2753 spin_lock(&kvm->mmu_lock);
2755 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2756 /* Need to free some mmu pages to achieve the goal. */
2757 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2758 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2761 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2762 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2765 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2767 spin_unlock(&kvm->mmu_lock);
2770 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2772 struct kvm_mmu_page *sp;
2773 LIST_HEAD(invalid_list);
2776 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2778 spin_lock(&kvm->mmu_lock);
2779 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2780 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2783 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2785 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2786 spin_unlock(&kvm->mmu_lock);
2790 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2792 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2794 trace_kvm_mmu_unsync_page(sp);
2795 ++vcpu->kvm->stat.mmu_unsync;
2798 kvm_mmu_mark_parents_unsync(sp);
2801 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2804 struct kvm_mmu_page *sp;
2806 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2809 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2816 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2817 kvm_unsync_page(vcpu, sp);
2821 * We need to ensure that the marking of unsync pages is visible
2822 * before the SPTE is updated to allow writes because
2823 * kvm_mmu_sync_roots() checks the unsync flags without holding
2824 * the MMU lock and so can race with this. If the SPTE was updated
2825 * before the page had been marked as unsync-ed, something like the
2826 * following could happen:
2829 * ---------------------------------------------------------------------
2830 * 1.2 Host updates SPTE
2832 * 2.1 Guest writes a GPTE for GVA X.
2833 * (GPTE being in the guest page table shadowed
2834 * by the SP from CPU 1.)
2835 * This reads SPTE during the page table walk.
2836 * Since SPTE.W is read as 1, there is no
2839 * 2.2 Guest issues TLB flush.
2840 * That causes a VM Exit.
2842 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2843 * Since it is false, so it just returns.
2845 * 2.4 Guest accesses GVA X.
2846 * Since the mapping in the SP was not updated,
2847 * so the old mapping for GVA X incorrectly
2851 * (sp->unsync = true)
2853 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2854 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2855 * pairs with this write barrier.
2862 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2865 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2867 * Some reserved pages, such as those from NVDIMM
2868 * DAX devices, are not for MMIO, and can be mapped
2869 * with cached memory type for better performance.
2870 * However, the above check misconceives those pages
2871 * as MMIO, and results in KVM mapping them with UC
2872 * memory type, which would hurt the performance.
2873 * Therefore, we check the host memory type in addition
2874 * and only treat UC/UC-/WC pages as MMIO.
2876 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2881 /* Bits which may be returned by set_spte() */
2882 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2883 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2885 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2886 unsigned pte_access, int level,
2887 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2888 bool can_unsync, bool host_writable)
2892 struct kvm_mmu_page *sp;
2894 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2897 sp = page_header(__pa(sptep));
2898 if (sp_ad_disabled(sp))
2899 spte |= shadow_acc_track_value;
2902 * For the EPT case, shadow_present_mask is 0 if hardware
2903 * supports exec-only page table entries. In that case,
2904 * ACC_USER_MASK and shadow_user_mask are used to represent
2905 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2907 spte |= shadow_present_mask;
2909 spte |= spte_shadow_accessed_mask(spte);
2911 if (pte_access & ACC_EXEC_MASK)
2912 spte |= shadow_x_mask;
2914 spte |= shadow_nx_mask;
2916 if (pte_access & ACC_USER_MASK)
2917 spte |= shadow_user_mask;
2919 if (level > PT_PAGE_TABLE_LEVEL)
2920 spte |= PT_PAGE_SIZE_MASK;
2922 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2923 kvm_is_mmio_pfn(pfn));
2926 spte |= SPTE_HOST_WRITEABLE;
2928 pte_access &= ~ACC_WRITE_MASK;
2930 if (!kvm_is_mmio_pfn(pfn))
2931 spte |= shadow_me_mask;
2933 spte |= (u64)pfn << PAGE_SHIFT;
2935 if (pte_access & ACC_WRITE_MASK) {
2938 * Other vcpu creates new sp in the window between
2939 * mapping_level() and acquiring mmu-lock. We can
2940 * allow guest to retry the access, the mapping can
2941 * be fixed if guest refault.
2943 if (level > PT_PAGE_TABLE_LEVEL &&
2944 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
2947 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
2950 * Optimization: for pte sync, if spte was writable the hash
2951 * lookup is unnecessary (and expensive). Write protection
2952 * is responsibility of mmu_get_page / kvm_sync_page.
2953 * Same reasoning can be applied to dirty page accounting.
2955 if (!can_unsync && is_writable_pte(*sptep))
2958 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
2959 pgprintk("%s: found shadow page for %llx, marking ro\n",
2961 ret |= SET_SPTE_WRITE_PROTECTED_PT;
2962 pte_access &= ~ACC_WRITE_MASK;
2963 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
2967 if (pte_access & ACC_WRITE_MASK) {
2968 kvm_vcpu_mark_page_dirty(vcpu, gfn);
2969 spte |= spte_shadow_dirty_mask(spte);
2973 spte = mark_spte_for_access_track(spte);
2976 if (mmu_spte_update(sptep, spte))
2977 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
2982 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
2983 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
2984 bool speculative, bool host_writable)
2986 int was_rmapped = 0;
2989 int ret = RET_PF_RETRY;
2992 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2993 *sptep, write_fault, gfn);
2995 if (is_shadow_present_pte(*sptep)) {
2997 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2998 * the parent of the now unreachable PTE.
3000 if (level > PT_PAGE_TABLE_LEVEL &&
3001 !is_large_pte(*sptep)) {
3002 struct kvm_mmu_page *child;
3005 child = page_header(pte & PT64_BASE_ADDR_MASK);
3006 drop_parent_pte(child, sptep);
3008 } else if (pfn != spte_to_pfn(*sptep)) {
3009 pgprintk("hfn old %llx new %llx\n",
3010 spte_to_pfn(*sptep), pfn);
3011 drop_spte(vcpu->kvm, sptep);
3017 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3018 speculative, true, host_writable);
3019 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3021 ret = RET_PF_EMULATE;
3022 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3025 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3026 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3027 KVM_PAGES_PER_HPAGE(level));
3029 if (unlikely(is_mmio_spte(*sptep)))
3030 ret = RET_PF_EMULATE;
3032 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3033 pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
3034 is_large_pte(*sptep)? "2MB" : "4kB",
3035 *sptep & PT_WRITABLE_MASK ? "RW" : "R", gfn,
3037 if (!was_rmapped && is_large_pte(*sptep))
3038 ++vcpu->kvm->stat.lpages;
3040 if (is_shadow_present_pte(*sptep)) {
3042 rmap_count = rmap_add(vcpu, sptep, gfn);
3043 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3044 rmap_recycle(vcpu, sptep, gfn);
3048 kvm_release_pfn_clean(pfn);
3053 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3056 struct kvm_memory_slot *slot;
3058 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3060 return KVM_PFN_ERR_FAULT;
3062 return gfn_to_pfn_memslot_atomic(slot, gfn);
3065 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3066 struct kvm_mmu_page *sp,
3067 u64 *start, u64 *end)
3069 struct page *pages[PTE_PREFETCH_NUM];
3070 struct kvm_memory_slot *slot;
3071 unsigned access = sp->role.access;
3075 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3076 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3080 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3084 for (i = 0; i < ret; i++, gfn++, start++)
3085 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3086 page_to_pfn(pages[i]), true, true);
3091 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3092 struct kvm_mmu_page *sp, u64 *sptep)
3094 u64 *spte, *start = NULL;
3097 WARN_ON(!sp->role.direct);
3099 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3102 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3103 if (is_shadow_present_pte(*spte) || spte == sptep) {
3106 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3114 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3116 struct kvm_mmu_page *sp;
3118 sp = page_header(__pa(sptep));
3121 * Without accessed bits, there's no way to distinguish between
3122 * actually accessed translations and prefetched, so disable pte
3123 * prefetch if accessed bits aren't available.
3125 if (sp_ad_disabled(sp))
3128 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3131 __direct_pte_prefetch(vcpu, sp, sptep);
3134 static int __direct_map(struct kvm_vcpu *vcpu, int write, int map_writable,
3135 int level, gfn_t gfn, kvm_pfn_t pfn, bool prefault)
3137 struct kvm_shadow_walk_iterator iterator;
3138 struct kvm_mmu_page *sp;
3142 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3145 for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
3146 if (iterator.level == level) {
3147 emulate = mmu_set_spte(vcpu, iterator.sptep, ACC_ALL,
3148 write, level, gfn, pfn, prefault,
3150 direct_pte_prefetch(vcpu, iterator.sptep);
3151 ++vcpu->stat.pf_fixed;
3155 drop_large_spte(vcpu, iterator.sptep);
3156 if (!is_shadow_present_pte(*iterator.sptep)) {
3157 u64 base_addr = iterator.addr;
3159 base_addr &= PT64_LVL_ADDR_MASK(iterator.level);
3160 pseudo_gfn = base_addr >> PAGE_SHIFT;
3161 sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
3162 iterator.level - 1, 1, ACC_ALL);
3164 link_shadow_page(vcpu, iterator.sptep, sp);
3170 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3172 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3175 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3178 * Do not cache the mmio info caused by writing the readonly gfn
3179 * into the spte otherwise read access on readonly gfn also can
3180 * caused mmio page fault and treat it as mmio access.
3182 if (pfn == KVM_PFN_ERR_RO_FAULT)
3183 return RET_PF_EMULATE;
3185 if (pfn == KVM_PFN_ERR_HWPOISON) {
3186 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3187 return RET_PF_RETRY;
3193 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3194 gfn_t *gfnp, kvm_pfn_t *pfnp,
3197 kvm_pfn_t pfn = *pfnp;
3199 int level = *levelp;
3202 * Check if it's a transparent hugepage. If this would be an
3203 * hugetlbfs page, level wouldn't be set to
3204 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3207 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3208 level == PT_PAGE_TABLE_LEVEL &&
3209 PageTransCompoundMap(pfn_to_page(pfn)) &&
3210 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3213 * mmu_notifier_retry was successful and we hold the
3214 * mmu_lock here, so the pmd can't become splitting
3215 * from under us, and in turn
3216 * __split_huge_page_refcount() can't run from under
3217 * us and we can safely transfer the refcount from
3218 * PG_tail to PG_head as we switch the pfn to tail to
3221 *levelp = level = PT_DIRECTORY_LEVEL;
3222 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3223 VM_BUG_ON((gfn & mask) != (pfn & mask));
3227 kvm_release_pfn_clean(pfn);
3235 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3236 kvm_pfn_t pfn, unsigned access, int *ret_val)
3238 /* The pfn is invalid, report the error! */
3239 if (unlikely(is_error_pfn(pfn))) {
3240 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3244 if (unlikely(is_noslot_pfn(pfn)))
3245 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
3250 static bool page_fault_can_be_fast(u32 error_code)
3253 * Do not fix the mmio spte with invalid generation number which
3254 * need to be updated by slow page fault path.
3256 if (unlikely(error_code & PFERR_RSVD_MASK))
3259 /* See if the page fault is due to an NX violation */
3260 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3261 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3265 * #PF can be fast if:
3266 * 1. The shadow page table entry is not present, which could mean that
3267 * the fault is potentially caused by access tracking (if enabled).
3268 * 2. The shadow page table entry is present and the fault
3269 * is caused by write-protect, that means we just need change the W
3270 * bit of the spte which can be done out of mmu-lock.
3272 * However, if access tracking is disabled we know that a non-present
3273 * page must be a genuine page fault where we have to create a new SPTE.
3274 * So, if access tracking is disabled, we return true only for write
3275 * accesses to a present page.
3278 return shadow_acc_track_mask != 0 ||
3279 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3280 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3284 * Returns true if the SPTE was fixed successfully. Otherwise,
3285 * someone else modified the SPTE from its original value.
3288 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3289 u64 *sptep, u64 old_spte, u64 new_spte)
3293 WARN_ON(!sp->role.direct);
3296 * Theoretically we could also set dirty bit (and flush TLB) here in
3297 * order to eliminate unnecessary PML logging. See comments in
3298 * set_spte. But fast_page_fault is very unlikely to happen with PML
3299 * enabled, so we do not do this. This might result in the same GPA
3300 * to be logged in PML buffer again when the write really happens, and
3301 * eventually to be called by mark_page_dirty twice. But it's also no
3302 * harm. This also avoids the TLB flush needed after setting dirty bit
3303 * so non-PML cases won't be impacted.
3305 * Compare with set_spte where instead shadow_dirty_mask is set.
3307 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3310 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3312 * The gfn of direct spte is stable since it is
3313 * calculated by sp->gfn.
3315 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3316 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3322 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3324 if (fault_err_code & PFERR_FETCH_MASK)
3325 return is_executable_pte(spte);
3327 if (fault_err_code & PFERR_WRITE_MASK)
3328 return is_writable_pte(spte);
3330 /* Fault was on Read access */
3331 return spte & PT_PRESENT_MASK;
3336 * - true: let the vcpu to access on the same address again.
3337 * - false: let the real page fault path to fix it.
3339 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3342 struct kvm_shadow_walk_iterator iterator;
3343 struct kvm_mmu_page *sp;
3344 bool fault_handled = false;
3346 uint retry_count = 0;
3348 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3351 if (!page_fault_can_be_fast(error_code))
3354 walk_shadow_page_lockless_begin(vcpu);
3359 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3360 if (!is_shadow_present_pte(spte) ||
3361 iterator.level < level)
3364 sp = page_header(__pa(iterator.sptep));
3365 if (!is_last_spte(spte, sp->role.level))
3369 * Check whether the memory access that caused the fault would
3370 * still cause it if it were to be performed right now. If not,
3371 * then this is a spurious fault caused by TLB lazily flushed,
3372 * or some other CPU has already fixed the PTE after the
3373 * current CPU took the fault.
3375 * Need not check the access of upper level table entries since
3376 * they are always ACC_ALL.
3378 if (is_access_allowed(error_code, spte)) {
3379 fault_handled = true;
3385 if (is_access_track_spte(spte))
3386 new_spte = restore_acc_track_spte(new_spte);
3389 * Currently, to simplify the code, write-protection can
3390 * be removed in the fast path only if the SPTE was
3391 * write-protected for dirty-logging or access tracking.
3393 if ((error_code & PFERR_WRITE_MASK) &&
3394 spte_can_locklessly_be_made_writable(spte))
3396 new_spte |= PT_WRITABLE_MASK;
3399 * Do not fix write-permission on the large spte. Since
3400 * we only dirty the first page into the dirty-bitmap in
3401 * fast_pf_fix_direct_spte(), other pages are missed
3402 * if its slot has dirty logging enabled.
3404 * Instead, we let the slow page fault path create a
3405 * normal spte to fix the access.
3407 * See the comments in kvm_arch_commit_memory_region().
3409 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3413 /* Verify that the fault can be handled in the fast path */
3414 if (new_spte == spte ||
3415 !is_access_allowed(error_code, new_spte))
3419 * Currently, fast page fault only works for direct mapping
3420 * since the gfn is not stable for indirect shadow page. See
3421 * Documentation/virtual/kvm/locking.txt to get more detail.
3423 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3424 iterator.sptep, spte,
3429 if (++retry_count > 4) {
3430 printk_once(KERN_WARNING
3431 "kvm: Fast #PF retrying more than 4 times.\n");
3437 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3438 spte, fault_handled);
3439 walk_shadow_page_lockless_end(vcpu);
3441 return fault_handled;
3444 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3445 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3446 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3448 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3449 gfn_t gfn, bool prefault)
3453 bool force_pt_level = false;
3455 unsigned long mmu_seq;
3456 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3458 level = mapping_level(vcpu, gfn, &force_pt_level);
3459 if (likely(!force_pt_level)) {
3461 * This path builds a PAE pagetable - so we can map
3462 * 2mb pages at maximum. Therefore check if the level
3463 * is larger than that.
3465 if (level > PT_DIRECTORY_LEVEL)
3466 level = PT_DIRECTORY_LEVEL;
3468 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3471 if (fast_page_fault(vcpu, v, level, error_code))
3472 return RET_PF_RETRY;
3474 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3477 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3478 return RET_PF_RETRY;
3480 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3483 spin_lock(&vcpu->kvm->mmu_lock);
3484 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3486 if (make_mmu_pages_available(vcpu) < 0)
3488 if (likely(!force_pt_level))
3489 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
3490 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
3491 spin_unlock(&vcpu->kvm->mmu_lock);
3496 spin_unlock(&vcpu->kvm->mmu_lock);
3497 kvm_release_pfn_clean(pfn);
3498 return RET_PF_RETRY;
3501 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3502 struct list_head *invalid_list)
3504 struct kvm_mmu_page *sp;
3506 if (!VALID_PAGE(*root_hpa))
3509 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3511 if (!sp->root_count && sp->role.invalid)
3512 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3514 *root_hpa = INVALID_PAGE;
3517 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3518 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3519 ulong roots_to_free)
3522 LIST_HEAD(invalid_list);
3523 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3525 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3527 /* Before acquiring the MMU lock, see if we need to do any real work. */
3528 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3529 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3530 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3531 VALID_PAGE(mmu->prev_roots[i].hpa))
3534 if (i == KVM_MMU_NUM_PREV_ROOTS)
3538 spin_lock(&vcpu->kvm->mmu_lock);
3540 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3541 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3542 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3545 if (free_active_root) {
3546 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3547 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3548 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3551 for (i = 0; i < 4; ++i)
3552 if (mmu->pae_root[i] != 0)
3553 mmu_free_root_page(vcpu->kvm,
3556 mmu->root_hpa = INVALID_PAGE;
3560 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3561 spin_unlock(&vcpu->kvm->mmu_lock);
3563 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3565 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3569 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3570 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3577 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3579 struct kvm_mmu_page *sp;
3582 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3583 spin_lock(&vcpu->kvm->mmu_lock);
3584 if(make_mmu_pages_available(vcpu) < 0) {
3585 spin_unlock(&vcpu->kvm->mmu_lock);
3588 sp = kvm_mmu_get_page(vcpu, 0, 0,
3589 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3591 spin_unlock(&vcpu->kvm->mmu_lock);
3592 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3593 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3594 for (i = 0; i < 4; ++i) {
3595 hpa_t root = vcpu->arch.mmu->pae_root[i];
3597 MMU_WARN_ON(VALID_PAGE(root));
3598 spin_lock(&vcpu->kvm->mmu_lock);
3599 if (make_mmu_pages_available(vcpu) < 0) {
3600 spin_unlock(&vcpu->kvm->mmu_lock);
3603 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3604 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3605 root = __pa(sp->spt);
3607 spin_unlock(&vcpu->kvm->mmu_lock);
3608 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3610 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3617 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3619 struct kvm_mmu_page *sp;
3624 root_gfn = vcpu->arch.mmu->get_cr3(vcpu) >> PAGE_SHIFT;
3626 if (mmu_check_root(vcpu, root_gfn))
3630 * Do we shadow a long mode page table? If so we need to
3631 * write-protect the guests page table root.
3633 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3634 hpa_t root = vcpu->arch.mmu->root_hpa;
3636 MMU_WARN_ON(VALID_PAGE(root));
3638 spin_lock(&vcpu->kvm->mmu_lock);
3639 if (make_mmu_pages_available(vcpu) < 0) {
3640 spin_unlock(&vcpu->kvm->mmu_lock);
3643 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3644 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3645 root = __pa(sp->spt);
3647 spin_unlock(&vcpu->kvm->mmu_lock);
3648 vcpu->arch.mmu->root_hpa = root;
3653 * We shadow a 32 bit page table. This may be a legacy 2-level
3654 * or a PAE 3-level page table. In either case we need to be aware that
3655 * the shadow page table may be a PAE or a long mode page table.
3657 pm_mask = PT_PRESENT_MASK;
3658 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3659 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3661 for (i = 0; i < 4; ++i) {
3662 hpa_t root = vcpu->arch.mmu->pae_root[i];
3664 MMU_WARN_ON(VALID_PAGE(root));
3665 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3666 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3667 if (!(pdptr & PT_PRESENT_MASK)) {
3668 vcpu->arch.mmu->pae_root[i] = 0;
3671 root_gfn = pdptr >> PAGE_SHIFT;
3672 if (mmu_check_root(vcpu, root_gfn))
3675 spin_lock(&vcpu->kvm->mmu_lock);
3676 if (make_mmu_pages_available(vcpu) < 0) {
3677 spin_unlock(&vcpu->kvm->mmu_lock);
3680 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3682 root = __pa(sp->spt);
3684 spin_unlock(&vcpu->kvm->mmu_lock);
3686 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3688 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3691 * If we shadow a 32 bit page table with a long mode page
3692 * table we enter this path.
3694 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3695 if (vcpu->arch.mmu->lm_root == NULL) {
3697 * The additional page necessary for this is only
3698 * allocated on demand.
3703 lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3704 if (lm_root == NULL)
3707 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3709 vcpu->arch.mmu->lm_root = lm_root;
3712 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3718 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3720 if (vcpu->arch.mmu->direct_map)
3721 return mmu_alloc_direct_roots(vcpu);
3723 return mmu_alloc_shadow_roots(vcpu);
3726 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3729 struct kvm_mmu_page *sp;
3731 if (vcpu->arch.mmu->direct_map)
3734 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3737 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3739 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3740 hpa_t root = vcpu->arch.mmu->root_hpa;
3741 sp = page_header(root);
3744 * Even if another CPU was marking the SP as unsync-ed
3745 * simultaneously, any guest page table changes are not
3746 * guaranteed to be visible anyway until this VCPU issues a TLB
3747 * flush strictly after those changes are made. We only need to
3748 * ensure that the other CPU sets these flags before any actual
3749 * changes to the page tables are made. The comments in
3750 * mmu_need_write_protect() describe what could go wrong if this
3751 * requirement isn't satisfied.
3753 if (!smp_load_acquire(&sp->unsync) &&
3754 !smp_load_acquire(&sp->unsync_children))
3757 spin_lock(&vcpu->kvm->mmu_lock);
3758 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3760 mmu_sync_children(vcpu, sp);
3762 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3763 spin_unlock(&vcpu->kvm->mmu_lock);
3767 spin_lock(&vcpu->kvm->mmu_lock);
3768 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3770 for (i = 0; i < 4; ++i) {
3771 hpa_t root = vcpu->arch.mmu->pae_root[i];
3773 if (root && VALID_PAGE(root)) {
3774 root &= PT64_BASE_ADDR_MASK;
3775 sp = page_header(root);
3776 mmu_sync_children(vcpu, sp);
3780 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3781 spin_unlock(&vcpu->kvm->mmu_lock);
3783 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3785 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3786 u32 access, struct x86_exception *exception)
3789 exception->error_code = 0;
3793 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3795 struct x86_exception *exception)
3798 exception->error_code = 0;
3799 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3803 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3805 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3807 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3808 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3811 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3813 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3816 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3818 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3821 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3824 * A nested guest cannot use the MMIO cache if it is using nested
3825 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3827 if (mmu_is_nested(vcpu))
3831 return vcpu_match_mmio_gpa(vcpu, addr);
3833 return vcpu_match_mmio_gva(vcpu, addr);
3836 /* return true if reserved bit is detected on spte. */
3838 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3840 struct kvm_shadow_walk_iterator iterator;
3841 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3843 bool reserved = false;
3845 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3848 walk_shadow_page_lockless_begin(vcpu);
3850 for (shadow_walk_init(&iterator, vcpu, addr),
3851 leaf = root = iterator.level;
3852 shadow_walk_okay(&iterator);
3853 __shadow_walk_next(&iterator, spte)) {
3854 spte = mmu_spte_get_lockless(iterator.sptep);
3856 sptes[leaf - 1] = spte;
3859 if (!is_shadow_present_pte(spte))
3862 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3866 walk_shadow_page_lockless_end(vcpu);
3869 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3871 while (root > leaf) {
3872 pr_err("------ spte 0x%llx level %d.\n",
3873 sptes[root - 1], root);
3882 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3887 if (mmio_info_in_cache(vcpu, addr, direct))
3888 return RET_PF_EMULATE;
3890 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3891 if (WARN_ON(reserved))
3894 if (is_mmio_spte(spte)) {
3895 gfn_t gfn = get_mmio_spte_gfn(spte);
3896 unsigned access = get_mmio_spte_access(spte);
3898 if (!check_mmio_spte(vcpu, spte))
3899 return RET_PF_INVALID;
3904 trace_handle_mmio_page_fault(addr, gfn, access);
3905 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3906 return RET_PF_EMULATE;
3910 * If the page table is zapped by other cpus, let CPU fault again on
3913 return RET_PF_RETRY;
3916 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3917 u32 error_code, gfn_t gfn)
3919 if (unlikely(error_code & PFERR_RSVD_MASK))
3922 if (!(error_code & PFERR_PRESENT_MASK) ||
3923 !(error_code & PFERR_WRITE_MASK))
3927 * guest is writing the page which is write tracked which can
3928 * not be fixed by page fault handler.
3930 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3936 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3938 struct kvm_shadow_walk_iterator iterator;
3941 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3944 walk_shadow_page_lockless_begin(vcpu);
3945 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3946 clear_sp_write_flooding_count(iterator.sptep);
3947 if (!is_shadow_present_pte(spte))
3950 walk_shadow_page_lockless_end(vcpu);
3953 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
3954 u32 error_code, bool prefault)
3956 gfn_t gfn = gva >> PAGE_SHIFT;
3959 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
3961 if (page_fault_handle_page_track(vcpu, error_code, gfn))
3962 return RET_PF_EMULATE;
3964 r = mmu_topup_memory_caches(vcpu);
3968 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
3971 return nonpaging_map(vcpu, gva & PAGE_MASK,
3972 error_code, gfn, prefault);
3975 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
3977 struct kvm_arch_async_pf arch;
3979 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3981 arch.direct_map = vcpu->arch.mmu->direct_map;
3982 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3984 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3987 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
3989 if (unlikely(!lapic_in_kernel(vcpu) ||
3990 kvm_event_needs_reinjection(vcpu) ||
3991 vcpu->arch.exception.pending))
3994 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
3997 return kvm_x86_ops->interrupt_allowed(vcpu);
4000 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4001 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4003 struct kvm_memory_slot *slot;
4007 * Don't expose private memslots to L2.
4009 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4010 *pfn = KVM_PFN_NOSLOT;
4014 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4016 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4018 return false; /* *pfn has correct page already */
4020 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4021 trace_kvm_try_async_get_page(gva, gfn);
4022 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4023 trace_kvm_async_pf_doublefault(gva, gfn);
4024 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4026 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4030 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4034 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4035 u64 fault_address, char *insn, int insn_len)
4039 vcpu->arch.l1tf_flush_l1d = true;
4040 switch (vcpu->arch.apf.host_apf_reason) {
4042 trace_kvm_page_fault(fault_address, error_code);
4044 if (kvm_event_needs_reinjection(vcpu))
4045 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4046 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4049 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4050 vcpu->arch.apf.host_apf_reason = 0;
4051 local_irq_disable();
4052 kvm_async_pf_task_wait(fault_address, 0);
4055 case KVM_PV_REASON_PAGE_READY:
4056 vcpu->arch.apf.host_apf_reason = 0;
4057 local_irq_disable();
4058 kvm_async_pf_task_wake(fault_address);
4064 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4067 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4069 int page_num = KVM_PAGES_PER_HPAGE(level);
4071 gfn &= ~(page_num - 1);
4073 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4076 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4082 bool force_pt_level;
4083 gfn_t gfn = gpa >> PAGE_SHIFT;
4084 unsigned long mmu_seq;
4085 int write = error_code & PFERR_WRITE_MASK;
4088 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4090 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4091 return RET_PF_EMULATE;
4093 r = mmu_topup_memory_caches(vcpu);
4097 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4098 PT_DIRECTORY_LEVEL);
4099 level = mapping_level(vcpu, gfn, &force_pt_level);
4100 if (likely(!force_pt_level)) {
4101 if (level > PT_DIRECTORY_LEVEL &&
4102 !check_hugepage_cache_consistency(vcpu, gfn, level))
4103 level = PT_DIRECTORY_LEVEL;
4104 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4107 if (fast_page_fault(vcpu, gpa, level, error_code))
4108 return RET_PF_RETRY;
4110 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4113 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4114 return RET_PF_RETRY;
4116 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4119 spin_lock(&vcpu->kvm->mmu_lock);
4120 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4122 if (make_mmu_pages_available(vcpu) < 0)
4124 if (likely(!force_pt_level))
4125 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
4126 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
4127 spin_unlock(&vcpu->kvm->mmu_lock);
4132 spin_unlock(&vcpu->kvm->mmu_lock);
4133 kvm_release_pfn_clean(pfn);
4134 return RET_PF_RETRY;
4137 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4138 struct kvm_mmu *context)
4140 context->page_fault = nonpaging_page_fault;
4141 context->gva_to_gpa = nonpaging_gva_to_gpa;
4142 context->sync_page = nonpaging_sync_page;
4143 context->invlpg = nonpaging_invlpg;
4144 context->update_pte = nonpaging_update_pte;
4145 context->root_level = 0;
4146 context->shadow_root_level = PT32E_ROOT_LEVEL;
4147 context->direct_map = true;
4148 context->nx = false;
4152 * Find out if a previously cached root matching the new CR3/role is available.
4153 * The current root is also inserted into the cache.
4154 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4156 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4157 * false is returned. This root should now be freed by the caller.
4159 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4160 union kvm_mmu_page_role new_role)
4163 struct kvm_mmu_root_info root;
4164 struct kvm_mmu *mmu = vcpu->arch.mmu;
4166 root.cr3 = mmu->get_cr3(vcpu);
4167 root.hpa = mmu->root_hpa;
4169 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4170 swap(root, mmu->prev_roots[i]);
4172 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4173 page_header(root.hpa) != NULL &&
4174 new_role.word == page_header(root.hpa)->role.word)
4178 mmu->root_hpa = root.hpa;
4180 return i < KVM_MMU_NUM_PREV_ROOTS;
4183 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4184 union kvm_mmu_page_role new_role,
4185 bool skip_tlb_flush)
4187 struct kvm_mmu *mmu = vcpu->arch.mmu;
4190 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4191 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4192 * later if necessary.
4194 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4195 mmu->root_level >= PT64_ROOT_4LEVEL) {
4196 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4199 if (cached_root_available(vcpu, new_cr3, new_role)) {
4201 * It is possible that the cached previous root page is
4202 * obsolete because of a change in the MMU
4203 * generation number. However, that is accompanied by
4204 * KVM_REQ_MMU_RELOAD, which will free the root that we
4205 * have set here and allocate a new one.
4208 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4209 if (!skip_tlb_flush) {
4210 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4211 kvm_x86_ops->tlb_flush(vcpu, true);
4215 * The last MMIO access's GVA and GPA are cached in the
4216 * VCPU. When switching to a new CR3, that GVA->GPA
4217 * mapping may no longer be valid. So clear any cached
4218 * MMIO info even when we don't need to sync the shadow
4221 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4223 __clear_sp_write_flooding_count(
4224 page_header(mmu->root_hpa));
4233 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4234 union kvm_mmu_page_role new_role,
4235 bool skip_tlb_flush)
4237 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4238 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4239 KVM_MMU_ROOT_CURRENT);
4242 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4244 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4247 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4249 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4251 return kvm_read_cr3(vcpu);
4254 static void inject_page_fault(struct kvm_vcpu *vcpu,
4255 struct x86_exception *fault)
4257 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4260 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4261 unsigned access, int *nr_present)
4263 if (unlikely(is_mmio_spte(*sptep))) {
4264 if (gfn != get_mmio_spte_gfn(*sptep)) {
4265 mmu_spte_clear_no_track(sptep);
4270 mark_mmio_spte(vcpu, sptep, gfn, access);
4277 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4278 unsigned level, unsigned gpte)
4281 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4282 * If it is clear, there are no large pages at this level, so clear
4283 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4285 gpte &= level - mmu->last_nonleaf_level;
4288 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4289 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4290 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4292 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4294 return gpte & PT_PAGE_SIZE_MASK;
4297 #define PTTYPE_EPT 18 /* arbitrary */
4298 #define PTTYPE PTTYPE_EPT
4299 #include "paging_tmpl.h"
4303 #include "paging_tmpl.h"
4307 #include "paging_tmpl.h"
4311 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4312 struct rsvd_bits_validate *rsvd_check,
4313 int maxphyaddr, int level, bool nx, bool gbpages,
4316 u64 exb_bit_rsvd = 0;
4317 u64 gbpages_bit_rsvd = 0;
4318 u64 nonleaf_bit8_rsvd = 0;
4320 rsvd_check->bad_mt_xwr = 0;
4323 exb_bit_rsvd = rsvd_bits(63, 63);
4325 gbpages_bit_rsvd = rsvd_bits(7, 7);
4328 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4329 * leaf entries) on AMD CPUs only.
4332 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4335 case PT32_ROOT_LEVEL:
4336 /* no rsvd bits for 2 level 4K page table entries */
4337 rsvd_check->rsvd_bits_mask[0][1] = 0;
4338 rsvd_check->rsvd_bits_mask[0][0] = 0;
4339 rsvd_check->rsvd_bits_mask[1][0] =
4340 rsvd_check->rsvd_bits_mask[0][0];
4343 rsvd_check->rsvd_bits_mask[1][1] = 0;
4347 if (is_cpuid_PSE36())
4348 /* 36bits PSE 4MB page */
4349 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4351 /* 32 bits PSE 4MB page */
4352 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4354 case PT32E_ROOT_LEVEL:
4355 rsvd_check->rsvd_bits_mask[0][2] =
4356 rsvd_bits(maxphyaddr, 63) |
4357 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4358 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4359 rsvd_bits(maxphyaddr, 62); /* PDE */
4360 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4361 rsvd_bits(maxphyaddr, 62); /* PTE */
4362 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4363 rsvd_bits(maxphyaddr, 62) |
4364 rsvd_bits(13, 20); /* large page */
4365 rsvd_check->rsvd_bits_mask[1][0] =
4366 rsvd_check->rsvd_bits_mask[0][0];
4368 case PT64_ROOT_5LEVEL:
4369 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4370 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4371 rsvd_bits(maxphyaddr, 51);
4372 rsvd_check->rsvd_bits_mask[1][4] =
4373 rsvd_check->rsvd_bits_mask[0][4];
4374 case PT64_ROOT_4LEVEL:
4375 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4376 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4377 rsvd_bits(maxphyaddr, 51);
4378 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4379 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4380 rsvd_bits(maxphyaddr, 51);
4381 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4382 rsvd_bits(maxphyaddr, 51);
4383 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4384 rsvd_bits(maxphyaddr, 51);
4385 rsvd_check->rsvd_bits_mask[1][3] =
4386 rsvd_check->rsvd_bits_mask[0][3];
4387 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4388 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4390 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4391 rsvd_bits(maxphyaddr, 51) |
4392 rsvd_bits(13, 20); /* large page */
4393 rsvd_check->rsvd_bits_mask[1][0] =
4394 rsvd_check->rsvd_bits_mask[0][0];
4399 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4400 struct kvm_mmu *context)
4402 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4403 cpuid_maxphyaddr(vcpu), context->root_level,
4405 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4406 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4410 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4411 int maxphyaddr, bool execonly)
4415 rsvd_check->rsvd_bits_mask[0][4] =
4416 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4417 rsvd_check->rsvd_bits_mask[0][3] =
4418 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4419 rsvd_check->rsvd_bits_mask[0][2] =
4420 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4421 rsvd_check->rsvd_bits_mask[0][1] =
4422 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4423 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4426 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4427 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4428 rsvd_check->rsvd_bits_mask[1][2] =
4429 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4430 rsvd_check->rsvd_bits_mask[1][1] =
4431 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4432 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4434 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4435 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4436 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4437 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4438 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4440 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4441 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4443 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4446 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4447 struct kvm_mmu *context, bool execonly)
4449 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4450 cpuid_maxphyaddr(vcpu), execonly);
4454 * the page table on host is the shadow page table for the page
4455 * table in guest or amd nested guest, its mmu features completely
4456 * follow the features in guest.
4459 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4461 bool uses_nx = context->nx ||
4462 context->mmu_role.base.smep_andnot_wp;
4463 struct rsvd_bits_validate *shadow_zero_check;
4467 * Passing "true" to the last argument is okay; it adds a check
4468 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4470 shadow_zero_check = &context->shadow_zero_check;
4471 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4472 boot_cpu_data.x86_phys_bits,
4473 context->shadow_root_level, uses_nx,
4474 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4475 is_pse(vcpu), true);
4477 if (!shadow_me_mask)
4480 for (i = context->shadow_root_level; --i >= 0;) {
4481 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4482 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4486 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4488 static inline bool boot_cpu_is_amd(void)
4490 WARN_ON_ONCE(!tdp_enabled);
4491 return shadow_x_mask == 0;
4495 * the direct page table on host, use as much mmu features as
4496 * possible, however, kvm currently does not do execution-protection.
4499 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4500 struct kvm_mmu *context)
4502 struct rsvd_bits_validate *shadow_zero_check;
4505 shadow_zero_check = &context->shadow_zero_check;
4507 if (boot_cpu_is_amd())
4508 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4509 boot_cpu_data.x86_phys_bits,
4510 context->shadow_root_level, false,
4511 boot_cpu_has(X86_FEATURE_GBPAGES),
4514 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4515 boot_cpu_data.x86_phys_bits,
4518 if (!shadow_me_mask)
4521 for (i = context->shadow_root_level; --i >= 0;) {
4522 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4523 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4528 * as the comments in reset_shadow_zero_bits_mask() except it
4529 * is the shadow page table for intel nested guest.
4532 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4533 struct kvm_mmu *context, bool execonly)
4535 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4536 boot_cpu_data.x86_phys_bits, execonly);
4539 #define BYTE_MASK(access) \
4540 ((1 & (access) ? 2 : 0) | \
4541 (2 & (access) ? 4 : 0) | \
4542 (3 & (access) ? 8 : 0) | \
4543 (4 & (access) ? 16 : 0) | \
4544 (5 & (access) ? 32 : 0) | \
4545 (6 & (access) ? 64 : 0) | \
4546 (7 & (access) ? 128 : 0))
4549 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4550 struct kvm_mmu *mmu, bool ept)
4554 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4555 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4556 const u8 u = BYTE_MASK(ACC_USER_MASK);
4558 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4559 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4560 bool cr0_wp = is_write_protection(vcpu);
4562 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4563 unsigned pfec = byte << 1;
4566 * Each "*f" variable has a 1 bit for each UWX value
4567 * that causes a fault with the given PFEC.
4570 /* Faults from writes to non-writable pages */
4571 u8 wf = (pfec & PFERR_WRITE_MASK) ? ~w : 0;
4572 /* Faults from user mode accesses to supervisor pages */
4573 u8 uf = (pfec & PFERR_USER_MASK) ? ~u : 0;
4574 /* Faults from fetches of non-executable pages*/
4575 u8 ff = (pfec & PFERR_FETCH_MASK) ? ~x : 0;
4576 /* Faults from kernel mode fetches of user pages */
4578 /* Faults from kernel mode accesses of user pages */
4582 /* Faults from kernel mode accesses to user pages */
4583 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4585 /* Not really needed: !nx will cause pte.nx to fault */
4589 /* Allow supervisor writes if !cr0.wp */
4591 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4593 /* Disallow supervisor fetches of user code if cr4.smep */
4595 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4598 * SMAP:kernel-mode data accesses from user-mode
4599 * mappings should fault. A fault is considered
4600 * as a SMAP violation if all of the following
4601 * conditions are true:
4602 * - X86_CR4_SMAP is set in CR4
4603 * - A user page is accessed
4604 * - The access is not a fetch
4605 * - Page fault in kernel mode
4606 * - if CPL = 3 or X86_EFLAGS_AC is clear
4608 * Here, we cover the first three conditions.
4609 * The fourth is computed dynamically in permission_fault();
4610 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4611 * *not* subject to SMAP restrictions.
4614 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4617 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4622 * PKU is an additional mechanism by which the paging controls access to
4623 * user-mode addresses based on the value in the PKRU register. Protection
4624 * key violations are reported through a bit in the page fault error code.
4625 * Unlike other bits of the error code, the PK bit is not known at the
4626 * call site of e.g. gva_to_gpa; it must be computed directly in
4627 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4628 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4630 * In particular the following conditions come from the error code, the
4631 * page tables and the machine state:
4632 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4633 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4634 * - PK is always zero if U=0 in the page tables
4635 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4637 * The PKRU bitmask caches the result of these four conditions. The error
4638 * code (minus the P bit) and the page table's U bit form an index into the
4639 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4640 * with the two bits of the PKRU register corresponding to the protection key.
4641 * For the first three conditions above the bits will be 00, thus masking
4642 * away both AD and WD. For all reads or if the last condition holds, WD
4643 * only will be masked away.
4645 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4656 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4657 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4662 wp = is_write_protection(vcpu);
4664 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4665 unsigned pfec, pkey_bits;
4666 bool check_pkey, check_write, ff, uf, wf, pte_user;
4669 ff = pfec & PFERR_FETCH_MASK;
4670 uf = pfec & PFERR_USER_MASK;
4671 wf = pfec & PFERR_WRITE_MASK;
4673 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4674 pte_user = pfec & PFERR_RSVD_MASK;
4677 * Only need to check the access which is not an
4678 * instruction fetch and is to a user page.
4680 check_pkey = (!ff && pte_user);
4682 * write access is controlled by PKRU if it is a
4683 * user access or CR0.WP = 1.
4685 check_write = check_pkey && wf && (uf || wp);
4687 /* PKRU.AD stops both read and write access. */
4688 pkey_bits = !!check_pkey;
4689 /* PKRU.WD stops write access. */
4690 pkey_bits |= (!!check_write) << 1;
4692 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4696 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4698 unsigned root_level = mmu->root_level;
4700 mmu->last_nonleaf_level = root_level;
4701 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4702 mmu->last_nonleaf_level++;
4705 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4706 struct kvm_mmu *context,
4709 context->nx = is_nx(vcpu);
4710 context->root_level = level;
4712 reset_rsvds_bits_mask(vcpu, context);
4713 update_permission_bitmask(vcpu, context, false);
4714 update_pkru_bitmask(vcpu, context, false);
4715 update_last_nonleaf_level(vcpu, context);
4717 MMU_WARN_ON(!is_pae(vcpu));
4718 context->page_fault = paging64_page_fault;
4719 context->gva_to_gpa = paging64_gva_to_gpa;
4720 context->sync_page = paging64_sync_page;
4721 context->invlpg = paging64_invlpg;
4722 context->update_pte = paging64_update_pte;
4723 context->shadow_root_level = level;
4724 context->direct_map = false;
4727 static void paging64_init_context(struct kvm_vcpu *vcpu,
4728 struct kvm_mmu *context)
4730 int root_level = is_la57_mode(vcpu) ?
4731 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4733 paging64_init_context_common(vcpu, context, root_level);
4736 static void paging32_init_context(struct kvm_vcpu *vcpu,
4737 struct kvm_mmu *context)
4739 context->nx = false;
4740 context->root_level = PT32_ROOT_LEVEL;
4742 reset_rsvds_bits_mask(vcpu, context);
4743 update_permission_bitmask(vcpu, context, false);
4744 update_pkru_bitmask(vcpu, context, false);
4745 update_last_nonleaf_level(vcpu, context);
4747 context->page_fault = paging32_page_fault;
4748 context->gva_to_gpa = paging32_gva_to_gpa;
4749 context->sync_page = paging32_sync_page;
4750 context->invlpg = paging32_invlpg;
4751 context->update_pte = paging32_update_pte;
4752 context->shadow_root_level = PT32E_ROOT_LEVEL;
4753 context->direct_map = false;
4756 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4757 struct kvm_mmu *context)
4759 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4762 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4764 union kvm_mmu_extended_role ext = {0};
4766 ext.cr0_pg = !!is_paging(vcpu);
4767 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4768 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4769 ext.cr4_pse = !!is_pse(vcpu);
4770 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4771 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4778 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4781 union kvm_mmu_role role = {0};
4783 role.base.access = ACC_ALL;
4784 role.base.nxe = !!is_nx(vcpu);
4785 role.base.cr4_pae = !!is_pae(vcpu);
4786 role.base.cr0_wp = is_write_protection(vcpu);
4787 role.base.smm = is_smm(vcpu);
4788 role.base.guest_mode = is_guest_mode(vcpu);
4793 role.ext = kvm_calc_mmu_role_ext(vcpu);
4798 static union kvm_mmu_role
4799 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4801 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4803 role.base.ad_disabled = (shadow_accessed_mask == 0);
4804 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4805 role.base.direct = true;
4810 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4812 struct kvm_mmu *context = vcpu->arch.mmu;
4813 union kvm_mmu_role new_role =
4814 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4816 new_role.base.word &= mmu_base_role_mask.word;
4817 if (new_role.as_u64 == context->mmu_role.as_u64)
4820 context->mmu_role.as_u64 = new_role.as_u64;
4821 context->page_fault = tdp_page_fault;
4822 context->sync_page = nonpaging_sync_page;
4823 context->invlpg = nonpaging_invlpg;
4824 context->update_pte = nonpaging_update_pte;
4825 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4826 context->direct_map = true;
4827 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4828 context->get_cr3 = get_cr3;
4829 context->get_pdptr = kvm_pdptr_read;
4830 context->inject_page_fault = kvm_inject_page_fault;
4832 if (!is_paging(vcpu)) {
4833 context->nx = false;
4834 context->gva_to_gpa = nonpaging_gva_to_gpa;
4835 context->root_level = 0;
4836 } else if (is_long_mode(vcpu)) {
4837 context->nx = is_nx(vcpu);
4838 context->root_level = is_la57_mode(vcpu) ?
4839 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4840 reset_rsvds_bits_mask(vcpu, context);
4841 context->gva_to_gpa = paging64_gva_to_gpa;
4842 } else if (is_pae(vcpu)) {
4843 context->nx = is_nx(vcpu);
4844 context->root_level = PT32E_ROOT_LEVEL;
4845 reset_rsvds_bits_mask(vcpu, context);
4846 context->gva_to_gpa = paging64_gva_to_gpa;
4848 context->nx = false;
4849 context->root_level = PT32_ROOT_LEVEL;
4850 reset_rsvds_bits_mask(vcpu, context);
4851 context->gva_to_gpa = paging32_gva_to_gpa;
4854 update_permission_bitmask(vcpu, context, false);
4855 update_pkru_bitmask(vcpu, context, false);
4856 update_last_nonleaf_level(vcpu, context);
4857 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4860 static union kvm_mmu_role
4861 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4863 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4865 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4866 !is_write_protection(vcpu);
4867 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4868 !is_write_protection(vcpu);
4869 role.base.direct = !is_paging(vcpu);
4871 if (!is_long_mode(vcpu))
4872 role.base.level = PT32E_ROOT_LEVEL;
4873 else if (is_la57_mode(vcpu))
4874 role.base.level = PT64_ROOT_5LEVEL;
4876 role.base.level = PT64_ROOT_4LEVEL;
4881 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4883 struct kvm_mmu *context = vcpu->arch.mmu;
4884 union kvm_mmu_role new_role =
4885 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4887 new_role.base.word &= mmu_base_role_mask.word;
4888 if (new_role.as_u64 == context->mmu_role.as_u64)
4891 if (!is_paging(vcpu))
4892 nonpaging_init_context(vcpu, context);
4893 else if (is_long_mode(vcpu))
4894 paging64_init_context(vcpu, context);
4895 else if (is_pae(vcpu))
4896 paging32E_init_context(vcpu, context);
4898 paging32_init_context(vcpu, context);
4900 context->mmu_role.as_u64 = new_role.as_u64;
4901 reset_shadow_zero_bits_mask(vcpu, context);
4903 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4905 static union kvm_mmu_role
4906 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4909 union kvm_mmu_role role;
4911 /* Base role is inherited from root_mmu */
4912 role.base.word = vcpu->arch.root_mmu.mmu_role.base.word;
4913 role.ext = kvm_calc_mmu_role_ext(vcpu);
4915 role.base.level = PT64_ROOT_4LEVEL;
4916 role.base.direct = false;
4917 role.base.ad_disabled = !accessed_dirty;
4918 role.base.guest_mode = true;
4919 role.base.access = ACC_ALL;
4921 role.ext.execonly = execonly;
4926 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4927 bool accessed_dirty, gpa_t new_eptp)
4929 struct kvm_mmu *context = vcpu->arch.mmu;
4930 union kvm_mmu_role new_role =
4931 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4934 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
4936 new_role.base.word &= mmu_base_role_mask.word;
4937 if (new_role.as_u64 == context->mmu_role.as_u64)
4940 context->shadow_root_level = PT64_ROOT_4LEVEL;
4943 context->ept_ad = accessed_dirty;
4944 context->page_fault = ept_page_fault;
4945 context->gva_to_gpa = ept_gva_to_gpa;
4946 context->sync_page = ept_sync_page;
4947 context->invlpg = ept_invlpg;
4948 context->update_pte = ept_update_pte;
4949 context->root_level = PT64_ROOT_4LEVEL;
4950 context->direct_map = false;
4951 context->mmu_role.as_u64 = new_role.as_u64;
4953 update_permission_bitmask(vcpu, context, true);
4954 update_pkru_bitmask(vcpu, context, true);
4955 update_last_nonleaf_level(vcpu, context);
4956 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4957 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4959 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4961 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4963 struct kvm_mmu *context = vcpu->arch.mmu;
4965 kvm_init_shadow_mmu(vcpu);
4966 context->set_cr3 = kvm_x86_ops->set_cr3;
4967 context->get_cr3 = get_cr3;
4968 context->get_pdptr = kvm_pdptr_read;
4969 context->inject_page_fault = kvm_inject_page_fault;
4972 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4974 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
4975 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4977 new_role.base.word &= mmu_base_role_mask.word;
4978 if (new_role.as_u64 == g_context->mmu_role.as_u64)
4981 g_context->mmu_role.as_u64 = new_role.as_u64;
4982 g_context->get_cr3 = get_cr3;
4983 g_context->get_pdptr = kvm_pdptr_read;
4984 g_context->inject_page_fault = kvm_inject_page_fault;
4987 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
4988 * L1's nested page tables (e.g. EPT12). The nested translation
4989 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4990 * L2's page tables as the first level of translation and L1's
4991 * nested page tables as the second level of translation. Basically
4992 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
4994 if (!is_paging(vcpu)) {
4995 g_context->nx = false;
4996 g_context->root_level = 0;
4997 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4998 } else if (is_long_mode(vcpu)) {
4999 g_context->nx = is_nx(vcpu);
5000 g_context->root_level = is_la57_mode(vcpu) ?
5001 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5002 reset_rsvds_bits_mask(vcpu, g_context);
5003 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5004 } else if (is_pae(vcpu)) {
5005 g_context->nx = is_nx(vcpu);
5006 g_context->root_level = PT32E_ROOT_LEVEL;
5007 reset_rsvds_bits_mask(vcpu, g_context);
5008 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5010 g_context->nx = false;
5011 g_context->root_level = PT32_ROOT_LEVEL;
5012 reset_rsvds_bits_mask(vcpu, g_context);
5013 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5016 update_permission_bitmask(vcpu, g_context, false);
5017 update_pkru_bitmask(vcpu, g_context, false);
5018 update_last_nonleaf_level(vcpu, g_context);
5021 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5026 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5028 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5029 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5032 if (mmu_is_nested(vcpu))
5033 init_kvm_nested_mmu(vcpu);
5034 else if (tdp_enabled)
5035 init_kvm_tdp_mmu(vcpu);
5037 init_kvm_softmmu(vcpu);
5039 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5041 static union kvm_mmu_page_role
5042 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5044 union kvm_mmu_role role;
5047 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5049 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5054 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5056 kvm_mmu_unload(vcpu);
5057 kvm_init_mmu(vcpu, true);
5059 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5061 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5065 r = mmu_topup_memory_caches(vcpu);
5068 r = mmu_alloc_roots(vcpu);
5069 kvm_mmu_sync_roots(vcpu);
5072 kvm_mmu_load_cr3(vcpu);
5073 kvm_x86_ops->tlb_flush(vcpu, true);
5077 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5079 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5081 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5082 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5083 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5084 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5086 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5088 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5089 struct kvm_mmu_page *sp, u64 *spte,
5092 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5093 ++vcpu->kvm->stat.mmu_pde_zapped;
5097 ++vcpu->kvm->stat.mmu_pte_updated;
5098 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5101 static bool need_remote_flush(u64 old, u64 new)
5103 if (!is_shadow_present_pte(old))
5105 if (!is_shadow_present_pte(new))
5107 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5109 old ^= shadow_nx_mask;
5110 new ^= shadow_nx_mask;
5111 return (old & ~new & PT64_PERM_MASK) != 0;
5114 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5121 * Assume that the pte write on a page table of the same type
5122 * as the current vcpu paging mode since we update the sptes only
5123 * when they have the same mode.
5125 if (is_pae(vcpu) && *bytes == 4) {
5126 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5131 if (*bytes == 4 || *bytes == 8) {
5132 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5141 * If we're seeing too many writes to a page, it may no longer be a page table,
5142 * or we may be forking, in which case it is better to unmap the page.
5144 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5147 * Skip write-flooding detected for the sp whose level is 1, because
5148 * it can become unsync, then the guest page is not write-protected.
5150 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5153 atomic_inc(&sp->write_flooding_count);
5154 return atomic_read(&sp->write_flooding_count) >= 3;
5158 * Misaligned accesses are too much trouble to fix up; also, they usually
5159 * indicate a page is not used as a page table.
5161 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5164 unsigned offset, pte_size, misaligned;
5166 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5167 gpa, bytes, sp->role.word);
5169 offset = offset_in_page(gpa);
5170 pte_size = sp->role.cr4_pae ? 8 : 4;
5173 * Sometimes, the OS only writes the last one bytes to update status
5174 * bits, for example, in linux, andb instruction is used in clear_bit().
5176 if (!(offset & (pte_size - 1)) && bytes == 1)
5179 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5180 misaligned |= bytes < 4;
5185 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5187 unsigned page_offset, quadrant;
5191 page_offset = offset_in_page(gpa);
5192 level = sp->role.level;
5194 if (!sp->role.cr4_pae) {
5195 page_offset <<= 1; /* 32->64 */
5197 * A 32-bit pde maps 4MB while the shadow pdes map
5198 * only 2MB. So we need to double the offset again
5199 * and zap two pdes instead of one.
5201 if (level == PT32_ROOT_LEVEL) {
5202 page_offset &= ~7; /* kill rounding error */
5206 quadrant = page_offset >> PAGE_SHIFT;
5207 page_offset &= ~PAGE_MASK;
5208 if (quadrant != sp->role.quadrant)
5212 spte = &sp->spt[page_offset / sizeof(*spte)];
5216 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5217 const u8 *new, int bytes,
5218 struct kvm_page_track_notifier_node *node)
5220 gfn_t gfn = gpa >> PAGE_SHIFT;
5221 struct kvm_mmu_page *sp;
5222 LIST_HEAD(invalid_list);
5223 u64 entry, gentry, *spte;
5225 bool remote_flush, local_flush;
5228 * If we don't have indirect shadow pages, it means no page is
5229 * write-protected, so we can exit simply.
5231 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5234 remote_flush = local_flush = false;
5236 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5239 * No need to care whether allocation memory is successful
5240 * or not since pte prefetch is skiped if it does not have
5241 * enough objects in the cache.
5243 mmu_topup_memory_caches(vcpu);
5245 spin_lock(&vcpu->kvm->mmu_lock);
5247 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5249 ++vcpu->kvm->stat.mmu_pte_write;
5250 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5252 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5253 if (detect_write_misaligned(sp, gpa, bytes) ||
5254 detect_write_flooding(sp)) {
5255 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5256 ++vcpu->kvm->stat.mmu_flooded;
5260 spte = get_written_sptes(sp, gpa, &npte);
5266 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5269 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5271 !((sp->role.word ^ base_role)
5272 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5273 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5274 if (need_remote_flush(entry, *spte))
5275 remote_flush = true;
5279 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5280 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5281 spin_unlock(&vcpu->kvm->mmu_lock);
5284 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5289 if (vcpu->arch.mmu->direct_map)
5292 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5294 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5298 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5300 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5302 LIST_HEAD(invalid_list);
5304 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5307 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5308 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5311 ++vcpu->kvm->stat.mmu_recycled;
5313 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5315 if (!kvm_mmu_available_pages(vcpu->kvm))
5320 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5321 void *insn, int insn_len)
5323 int r, emulation_type = 0;
5324 enum emulation_result er;
5325 bool direct = vcpu->arch.mmu->direct_map;
5327 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5328 if (vcpu->arch.mmu->direct_map) {
5329 vcpu->arch.gpa_available = true;
5330 vcpu->arch.gpa_val = cr2;
5334 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5335 r = handle_mmio_page_fault(vcpu, cr2, direct);
5336 if (r == RET_PF_EMULATE)
5340 if (r == RET_PF_INVALID) {
5341 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5342 lower_32_bits(error_code),
5344 WARN_ON(r == RET_PF_INVALID);
5347 if (r == RET_PF_RETRY)
5353 * Before emulating the instruction, check if the error code
5354 * was due to a RO violation while translating the guest page.
5355 * This can occur when using nested virtualization with nested
5356 * paging in both guests. If true, we simply unprotect the page
5357 * and resume the guest.
5359 if (vcpu->arch.mmu->direct_map &&
5360 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5361 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5366 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5367 * optimistically try to just unprotect the page and let the processor
5368 * re-execute the instruction that caused the page fault. Do not allow
5369 * retrying MMIO emulation, as it's not only pointless but could also
5370 * cause us to enter an infinite loop because the processor will keep
5371 * faulting on the non-existent MMIO address. Retrying an instruction
5372 * from a nested guest is also pointless and dangerous as we are only
5373 * explicitly shadowing L1's page tables, i.e. unprotecting something
5374 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5376 if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5377 emulation_type = EMULTYPE_ALLOW_RETRY;
5380 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5381 * This can happen if a guest gets a page-fault on data access but the HW
5382 * table walker is not able to read the instruction page (e.g instruction
5383 * page is not present in memory). In those cases we simply restart the
5386 if (unlikely(insn && !insn_len))
5389 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
5394 case EMULATE_USER_EXIT:
5395 ++vcpu->stat.mmio_exits;
5403 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5405 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5407 struct kvm_mmu *mmu = vcpu->arch.mmu;
5410 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5411 if (is_noncanonical_address(gva, vcpu))
5414 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5417 * INVLPG is required to invalidate any global mappings for the VA,
5418 * irrespective of PCID. Since it would take us roughly similar amount
5419 * of work to determine whether any of the prev_root mappings of the VA
5420 * is marked global, or to just sync it blindly, so we might as well
5421 * just always sync it.
5423 * Mappings not reachable via the current cr3 or the prev_roots will be
5424 * synced when switching to that cr3, so nothing needs to be done here
5427 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5428 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5429 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5431 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5432 ++vcpu->stat.invlpg;
5434 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5436 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5438 struct kvm_mmu *mmu = vcpu->arch.mmu;
5439 bool tlb_flush = false;
5442 if (pcid == kvm_get_active_pcid(vcpu)) {
5443 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5447 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5448 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5449 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5450 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5456 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5458 ++vcpu->stat.invlpg;
5461 * Mappings not reachable via the current cr3 or the prev_roots will be
5462 * synced when switching to that cr3, so nothing needs to be done here
5466 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5468 void kvm_enable_tdp(void)
5472 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5474 void kvm_disable_tdp(void)
5476 tdp_enabled = false;
5478 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5480 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5482 free_page((unsigned long)vcpu->arch.mmu->pae_root);
5483 free_page((unsigned long)vcpu->arch.mmu->lm_root);
5486 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5495 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5496 * Therefore we need to allocate shadow page tables in the first
5497 * 4GB of memory, which happens to fit the DMA32 zone.
5499 page = alloc_page(GFP_KERNEL | __GFP_DMA32);
5503 vcpu->arch.mmu->pae_root = page_address(page);
5504 for (i = 0; i < 4; ++i)
5505 vcpu->arch.mmu->pae_root[i] = INVALID_PAGE;
5510 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5514 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5515 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5517 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5518 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5519 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5520 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5522 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5523 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5524 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5525 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5527 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5528 return alloc_mmu_pages(vcpu);
5531 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5532 struct kvm_memory_slot *slot,
5533 struct kvm_page_track_notifier_node *node)
5535 kvm_mmu_invalidate_zap_all_pages(kvm);
5538 void kvm_mmu_init_vm(struct kvm *kvm)
5540 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5542 node->track_write = kvm_mmu_pte_write;
5543 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5544 kvm_page_track_register_notifier(kvm, node);
5547 void kvm_mmu_uninit_vm(struct kvm *kvm)
5549 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5551 kvm_page_track_unregister_notifier(kvm, node);
5554 /* The return value indicates if tlb flush on all vcpus is needed. */
5555 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5557 /* The caller should hold mmu-lock before calling this function. */
5558 static __always_inline bool
5559 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5560 slot_level_handler fn, int start_level, int end_level,
5561 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5563 struct slot_rmap_walk_iterator iterator;
5566 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5567 end_gfn, &iterator) {
5569 flush |= fn(kvm, iterator.rmap);
5571 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5572 if (flush && lock_flush_tlb) {
5573 kvm_flush_remote_tlbs(kvm);
5576 cond_resched_lock(&kvm->mmu_lock);
5580 if (flush && lock_flush_tlb) {
5581 kvm_flush_remote_tlbs(kvm);
5588 static __always_inline bool
5589 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5590 slot_level_handler fn, int start_level, int end_level,
5591 bool lock_flush_tlb)
5593 return slot_handle_level_range(kvm, memslot, fn, start_level,
5594 end_level, memslot->base_gfn,
5595 memslot->base_gfn + memslot->npages - 1,
5599 static __always_inline bool
5600 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5601 slot_level_handler fn, bool lock_flush_tlb)
5603 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5604 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5607 static __always_inline bool
5608 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5609 slot_level_handler fn, bool lock_flush_tlb)
5611 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5612 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5615 static __always_inline bool
5616 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5617 slot_level_handler fn, bool lock_flush_tlb)
5619 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5620 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5623 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5625 struct kvm_memslots *slots;
5626 struct kvm_memory_slot *memslot;
5627 bool flush_tlb = true;
5631 if (kvm_available_flush_tlb_with_range())
5634 spin_lock(&kvm->mmu_lock);
5635 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5636 slots = __kvm_memslots(kvm, i);
5637 kvm_for_each_memslot(memslot, slots) {
5640 start = max(gfn_start, memslot->base_gfn);
5641 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5645 flush |= slot_handle_level_range(kvm, memslot,
5646 kvm_zap_rmapp, PT_PAGE_TABLE_LEVEL,
5647 PT_MAX_HUGEPAGE_LEVEL, start,
5648 end - 1, flush_tlb);
5653 kvm_flush_remote_tlbs_with_address(kvm, gfn_start,
5654 gfn_end - gfn_start + 1);
5656 spin_unlock(&kvm->mmu_lock);
5659 static bool slot_rmap_write_protect(struct kvm *kvm,
5660 struct kvm_rmap_head *rmap_head)
5662 return __rmap_write_protect(kvm, rmap_head, false);
5665 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5666 struct kvm_memory_slot *memslot)
5670 spin_lock(&kvm->mmu_lock);
5671 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5673 spin_unlock(&kvm->mmu_lock);
5676 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5677 * which do tlb flush out of mmu-lock should be serialized by
5678 * kvm->slots_lock otherwise tlb flush would be missed.
5680 lockdep_assert_held(&kvm->slots_lock);
5683 * We can flush all the TLBs out of the mmu lock without TLB
5684 * corruption since we just change the spte from writable to
5685 * readonly so that we only need to care the case of changing
5686 * spte from present to present (changing the spte from present
5687 * to nonpresent will flush all the TLBs immediately), in other
5688 * words, the only case we care is mmu_spte_update() where we
5689 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5690 * instead of PT_WRITABLE_MASK, that means it does not depend
5691 * on PT_WRITABLE_MASK anymore.
5694 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5698 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5699 struct kvm_rmap_head *rmap_head)
5702 struct rmap_iterator iter;
5703 int need_tlb_flush = 0;
5705 struct kvm_mmu_page *sp;
5708 for_each_rmap_spte(rmap_head, &iter, sptep) {
5709 sp = page_header(__pa(sptep));
5710 pfn = spte_to_pfn(*sptep);
5713 * We cannot do huge page mapping for indirect shadow pages,
5714 * which are found on the last rmap (level = 1) when not using
5715 * tdp; such shadow pages are synced with the page table in
5716 * the guest, and the guest page table is using 4K page size
5717 * mapping if the indirect sp has level = 1.
5719 if (sp->role.direct &&
5720 !kvm_is_reserved_pfn(pfn) &&
5721 PageTransCompoundMap(pfn_to_page(pfn))) {
5722 pte_list_remove(rmap_head, sptep);
5724 if (kvm_available_flush_tlb_with_range())
5725 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5726 KVM_PAGES_PER_HPAGE(sp->role.level));
5734 return need_tlb_flush;
5737 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5738 const struct kvm_memory_slot *memslot)
5740 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5741 spin_lock(&kvm->mmu_lock);
5742 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5743 kvm_mmu_zap_collapsible_spte, true);
5744 spin_unlock(&kvm->mmu_lock);
5747 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5748 struct kvm_memory_slot *memslot)
5752 spin_lock(&kvm->mmu_lock);
5753 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5754 spin_unlock(&kvm->mmu_lock);
5756 lockdep_assert_held(&kvm->slots_lock);
5759 * It's also safe to flush TLBs out of mmu lock here as currently this
5760 * function is only used for dirty logging, in which case flushing TLB
5761 * out of mmu lock also guarantees no dirty pages will be lost in
5765 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5768 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5770 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5771 struct kvm_memory_slot *memslot)
5775 spin_lock(&kvm->mmu_lock);
5776 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5778 spin_unlock(&kvm->mmu_lock);
5780 /* see kvm_mmu_slot_remove_write_access */
5781 lockdep_assert_held(&kvm->slots_lock);
5784 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5787 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5789 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5790 struct kvm_memory_slot *memslot)
5794 spin_lock(&kvm->mmu_lock);
5795 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5796 spin_unlock(&kvm->mmu_lock);
5798 lockdep_assert_held(&kvm->slots_lock);
5800 /* see kvm_mmu_slot_leaf_clear_dirty */
5802 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5805 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5807 #define BATCH_ZAP_PAGES 10
5808 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5810 struct kvm_mmu_page *sp, *node;
5814 list_for_each_entry_safe_reverse(sp, node,
5815 &kvm->arch.active_mmu_pages, link) {
5819 * No obsolete page exists before new created page since
5820 * active_mmu_pages is the FIFO list.
5822 if (!is_obsolete_sp(kvm, sp))
5826 * Since we are reversely walking the list and the invalid
5827 * list will be moved to the head, skip the invalid page
5828 * can help us to avoid the infinity list walking.
5830 if (sp->role.invalid)
5834 * Need not flush tlb since we only zap the sp with invalid
5835 * generation number.
5837 if (batch >= BATCH_ZAP_PAGES &&
5838 cond_resched_lock(&kvm->mmu_lock)) {
5843 ret = kvm_mmu_prepare_zap_page(kvm, sp,
5844 &kvm->arch.zapped_obsolete_pages);
5852 * Should flush tlb before free page tables since lockless-walking
5853 * may use the pages.
5855 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5859 * Fast invalidate all shadow pages and use lock-break technique
5860 * to zap obsolete pages.
5862 * It's required when memslot is being deleted or VM is being
5863 * destroyed, in these cases, we should ensure that KVM MMU does
5864 * not use any resource of the being-deleted slot or all slots
5865 * after calling the function.
5867 void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
5869 spin_lock(&kvm->mmu_lock);
5870 trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5871 kvm->arch.mmu_valid_gen++;
5874 * Notify all vcpus to reload its shadow page table
5875 * and flush TLB. Then all vcpus will switch to new
5876 * shadow page table with the new mmu_valid_gen.
5878 * Note: we should do this under the protection of
5879 * mmu-lock, otherwise, vcpu would purge shadow page
5880 * but miss tlb flush.
5882 kvm_reload_remote_mmus(kvm);
5884 kvm_zap_obsolete_pages(kvm);
5885 spin_unlock(&kvm->mmu_lock);
5888 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5890 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5893 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, struct kvm_memslots *slots)
5896 * The very rare case: if the generation-number is round,
5897 * zap all shadow pages.
5899 if (unlikely((slots->generation & MMIO_GEN_MASK) == 0)) {
5900 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5901 kvm_mmu_invalidate_zap_all_pages(kvm);
5905 static unsigned long
5906 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5909 int nr_to_scan = sc->nr_to_scan;
5910 unsigned long freed = 0;
5912 spin_lock(&kvm_lock);
5914 list_for_each_entry(kvm, &vm_list, vm_list) {
5916 LIST_HEAD(invalid_list);
5919 * Never scan more than sc->nr_to_scan VM instances.
5920 * Will not hit this condition practically since we do not try
5921 * to shrink more than one VM and it is very unlikely to see
5922 * !n_used_mmu_pages so many times.
5927 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5928 * here. We may skip a VM instance errorneosly, but we do not
5929 * want to shrink a VM that only started to populate its MMU
5932 if (!kvm->arch.n_used_mmu_pages &&
5933 !kvm_has_zapped_obsolete_pages(kvm))
5936 idx = srcu_read_lock(&kvm->srcu);
5937 spin_lock(&kvm->mmu_lock);
5939 if (kvm_has_zapped_obsolete_pages(kvm)) {
5940 kvm_mmu_commit_zap_page(kvm,
5941 &kvm->arch.zapped_obsolete_pages);
5945 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
5947 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5950 spin_unlock(&kvm->mmu_lock);
5951 srcu_read_unlock(&kvm->srcu, idx);
5954 * unfair on small ones
5955 * per-vm shrinkers cry out
5956 * sadness comes quickly
5958 list_move_tail(&kvm->vm_list, &vm_list);
5962 spin_unlock(&kvm_lock);
5966 static unsigned long
5967 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5969 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5972 static struct shrinker mmu_shrinker = {
5973 .count_objects = mmu_shrink_count,
5974 .scan_objects = mmu_shrink_scan,
5975 .seeks = DEFAULT_SEEKS * 10,
5978 static void mmu_destroy_caches(void)
5980 kmem_cache_destroy(pte_list_desc_cache);
5981 kmem_cache_destroy(mmu_page_header_cache);
5984 int kvm_mmu_module_init(void)
5989 * MMU roles use union aliasing which is, generally speaking, an
5990 * undefined behavior. However, we supposedly know how compilers behave
5991 * and the current status quo is unlikely to change. Guardians below are
5992 * supposed to let us know if the assumption becomes false.
5994 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
5995 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
5996 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
5998 kvm_mmu_reset_all_pte_masks();
6000 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6001 sizeof(struct pte_list_desc),
6002 0, SLAB_ACCOUNT, NULL);
6003 if (!pte_list_desc_cache)
6006 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6007 sizeof(struct kvm_mmu_page),
6008 0, SLAB_ACCOUNT, NULL);
6009 if (!mmu_page_header_cache)
6012 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6015 ret = register_shrinker(&mmu_shrinker);
6022 mmu_destroy_caches();
6027 * Calculate mmu pages needed for kvm.
6029 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
6031 unsigned int nr_mmu_pages;
6032 unsigned int nr_pages = 0;
6033 struct kvm_memslots *slots;
6034 struct kvm_memory_slot *memslot;
6037 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6038 slots = __kvm_memslots(kvm, i);
6040 kvm_for_each_memslot(memslot, slots)
6041 nr_pages += memslot->npages;
6044 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6045 nr_mmu_pages = max(nr_mmu_pages,
6046 (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
6048 return nr_mmu_pages;
6051 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6053 kvm_mmu_unload(vcpu);
6054 free_mmu_pages(vcpu);
6055 mmu_free_memory_caches(vcpu);
6058 void kvm_mmu_module_exit(void)
6060 mmu_destroy_caches();
6061 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6062 unregister_shrinker(&mmu_shrinker);
6063 mmu_audit_disable();