2 * Kernel-based Virtual Machine driver for Linux
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
9 * Copyright (C) 2006 Qumranet, Inc.
10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Avi Kivity <avi@qumranet.com>
16 * This work is licensed under the terms of the GNU GPL, version 2. See
17 * the COPYING file in the top-level directory.
24 #include "kvm_cache_regs.h"
27 #include <linux/kvm_host.h>
28 #include <linux/types.h>
29 #include <linux/string.h>
31 #include <linux/highmem.h>
32 #include <linux/moduleparam.h>
33 #include <linux/export.h>
34 #include <linux/swap.h>
35 #include <linux/hugetlb.h>
36 #include <linux/compiler.h>
37 #include <linux/srcu.h>
38 #include <linux/slab.h>
39 #include <linux/sched/signal.h>
40 #include <linux/uaccess.h>
41 #include <linux/hash.h>
42 #include <linux/kern_levels.h>
46 #include <asm/cmpxchg.h>
49 #include <asm/kvm_page_track.h>
53 * When setting this variable to true it enables Two-Dimensional-Paging
54 * where the hardware walks 2 page tables:
55 * 1. the guest-virtual to guest-physical
56 * 2. while doing 1. it walks guest-physical to host-physical
57 * If the hardware supports that we don't need to do shadow paging.
59 bool tdp_enabled = false;
63 AUDIT_POST_PAGE_FAULT,
74 module_param(dbg, bool, 0644);
76 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
77 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
78 #define MMU_WARN_ON(x) WARN_ON(x)
80 #define pgprintk(x...) do { } while (0)
81 #define rmap_printk(x...) do { } while (0)
82 #define MMU_WARN_ON(x) do { } while (0)
85 #define PTE_PREFETCH_NUM 8
87 #define PT_FIRST_AVAIL_BITS_SHIFT 10
88 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
90 #define PT64_LEVEL_BITS 9
92 #define PT64_LEVEL_SHIFT(level) \
93 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
95 #define PT64_INDEX(address, level)\
96 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
99 #define PT32_LEVEL_BITS 10
101 #define PT32_LEVEL_SHIFT(level) \
102 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
104 #define PT32_LVL_OFFSET_MASK(level) \
105 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
106 * PT32_LEVEL_BITS))) - 1))
108 #define PT32_INDEX(address, level)\
109 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
112 #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
113 #define PT64_BASE_ADDR_MASK (physical_mask & ~(u64)(PAGE_SIZE-1))
115 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
117 #define PT64_LVL_ADDR_MASK(level) \
118 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
119 * PT64_LEVEL_BITS))) - 1))
120 #define PT64_LVL_OFFSET_MASK(level) \
121 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
122 * PT64_LEVEL_BITS))) - 1))
124 #define PT32_BASE_ADDR_MASK PAGE_MASK
125 #define PT32_DIR_BASE_ADDR_MASK \
126 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
127 #define PT32_LVL_ADDR_MASK(level) \
128 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
129 * PT32_LEVEL_BITS))) - 1))
131 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
132 | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
134 #define ACC_EXEC_MASK 1
135 #define ACC_WRITE_MASK PT_WRITABLE_MASK
136 #define ACC_USER_MASK PT_USER_MASK
137 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
139 /* The mask for the R/X bits in EPT PTEs */
140 #define PT64_EPT_READABLE_MASK 0x1ull
141 #define PT64_EPT_EXECUTABLE_MASK 0x4ull
143 #include <trace/events/kvm.h>
145 #define CREATE_TRACE_POINTS
146 #include "mmutrace.h"
148 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
149 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
151 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
153 /* make pte_list_desc fit well in cache line */
154 #define PTE_LIST_EXT 3
157 * Return values of handle_mmio_page_fault and mmu.page_fault:
158 * RET_PF_RETRY: let CPU fault again on the address.
159 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
161 * For handle_mmio_page_fault only:
162 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
170 struct pte_list_desc {
171 u64 *sptes[PTE_LIST_EXT];
172 struct pte_list_desc *more;
175 struct kvm_shadow_walk_iterator {
183 static const union kvm_mmu_page_role mmu_base_role_mask = {
194 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
195 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
197 shadow_walk_okay(&(_walker)); \
198 shadow_walk_next(&(_walker)))
200 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
201 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
202 shadow_walk_okay(&(_walker)); \
203 shadow_walk_next(&(_walker)))
205 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
206 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
207 shadow_walk_okay(&(_walker)) && \
208 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
209 __shadow_walk_next(&(_walker), spte))
211 static struct kmem_cache *pte_list_desc_cache;
212 static struct kmem_cache *mmu_page_header_cache;
213 static struct percpu_counter kvm_total_used_mmu_pages;
215 static u64 __read_mostly shadow_nx_mask;
216 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
217 static u64 __read_mostly shadow_user_mask;
218 static u64 __read_mostly shadow_accessed_mask;
219 static u64 __read_mostly shadow_dirty_mask;
220 static u64 __read_mostly shadow_mmio_mask;
221 static u64 __read_mostly shadow_mmio_value;
222 static u64 __read_mostly shadow_present_mask;
223 static u64 __read_mostly shadow_me_mask;
226 * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
227 * Non-present SPTEs with shadow_acc_track_value set are in place for access
230 static u64 __read_mostly shadow_acc_track_mask;
231 static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
234 * The mask/shift to use for saving the original R/X bits when marking the PTE
235 * as not-present for access tracking purposes. We do not save the W bit as the
236 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
237 * restored only when a write is attempted to the page.
239 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
240 PT64_EPT_EXECUTABLE_MASK;
241 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
244 * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
245 * to guard against L1TF attacks.
247 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
250 * The number of high-order 1 bits to use in the mask above.
252 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
255 * In some cases, we need to preserve the GFN of a non-present or reserved
256 * SPTE when we usurp the upper five bits of the physical address space to
257 * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
258 * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
259 * left into the reserved bits, i.e. the GFN in the SPTE will be split into
260 * high and low parts. This mask covers the lower bits of the GFN.
262 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
265 static void mmu_spte_set(u64 *sptep, u64 spte);
266 static union kvm_mmu_page_role
267 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
270 static inline bool kvm_available_flush_tlb_with_range(void)
272 return kvm_x86_ops->tlb_remote_flush_with_range;
275 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
276 struct kvm_tlb_range *range)
280 if (range && kvm_x86_ops->tlb_remote_flush_with_range)
281 ret = kvm_x86_ops->tlb_remote_flush_with_range(kvm, range);
284 kvm_flush_remote_tlbs(kvm);
287 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
288 u64 start_gfn, u64 pages)
290 struct kvm_tlb_range range;
292 range.start_gfn = start_gfn;
295 kvm_flush_remote_tlbs_with_range(kvm, &range);
298 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
300 BUG_ON((mmio_mask & mmio_value) != mmio_value);
301 shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
302 shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
304 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
306 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
308 return sp->role.ad_disabled;
311 static inline bool spte_ad_enabled(u64 spte)
313 MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
314 return !(spte & shadow_acc_track_value);
317 static inline u64 spte_shadow_accessed_mask(u64 spte)
319 MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
320 return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
323 static inline u64 spte_shadow_dirty_mask(u64 spte)
325 MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
326 return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
329 static inline bool is_access_track_spte(u64 spte)
331 return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
335 * Due to limited space in PTEs, the MMIO generation is a 19 bit subset of
336 * the memslots generation and is derived as follows:
338 * Bits 0-8 of the MMIO generation are propagated to spte bits 3-11
339 * Bits 9-18 of the MMIO generation are propagated to spte bits 52-61
341 * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
342 * the MMIO generation number, as doing so would require stealing a bit from
343 * the "real" generation number and thus effectively halve the maximum number
344 * of MMIO generations that can be handled before encountering a wrap (which
345 * requires a full MMU zap). The flag is instead explicitly queried when
346 * checking for MMIO spte cache hits.
348 #define MMIO_SPTE_GEN_MASK GENMASK_ULL(18, 0)
350 #define MMIO_SPTE_GEN_LOW_START 3
351 #define MMIO_SPTE_GEN_LOW_END 11
352 #define MMIO_SPTE_GEN_LOW_MASK GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
353 MMIO_SPTE_GEN_LOW_START)
355 #define MMIO_SPTE_GEN_HIGH_START 52
356 #define MMIO_SPTE_GEN_HIGH_END 61
357 #define MMIO_SPTE_GEN_HIGH_MASK GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
358 MMIO_SPTE_GEN_HIGH_START)
359 static u64 generation_mmio_spte_mask(u64 gen)
363 WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
365 mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
366 mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
370 static u64 get_mmio_spte_generation(u64 spte)
374 spte &= ~shadow_mmio_mask;
376 gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
377 gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
381 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
384 u64 gen = kvm_vcpu_memslots(vcpu)->generation & MMIO_SPTE_GEN_MASK;
385 u64 mask = generation_mmio_spte_mask(gen);
386 u64 gpa = gfn << PAGE_SHIFT;
388 access &= ACC_WRITE_MASK | ACC_USER_MASK;
389 mask |= shadow_mmio_value | access;
390 mask |= gpa | shadow_nonpresent_or_rsvd_mask;
391 mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
392 << shadow_nonpresent_or_rsvd_mask_len;
394 trace_mark_mmio_spte(sptep, gfn, access, gen);
395 mmu_spte_set(sptep, mask);
398 static bool is_mmio_spte(u64 spte)
400 return (spte & shadow_mmio_mask) == shadow_mmio_value;
403 static gfn_t get_mmio_spte_gfn(u64 spte)
405 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
407 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
408 & shadow_nonpresent_or_rsvd_mask;
410 return gpa >> PAGE_SHIFT;
413 static unsigned get_mmio_spte_access(u64 spte)
415 u64 mask = generation_mmio_spte_mask(MMIO_SPTE_GEN_MASK) | shadow_mmio_mask;
416 return (spte & ~mask) & ~PAGE_MASK;
419 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
420 kvm_pfn_t pfn, unsigned access)
422 if (unlikely(is_noslot_pfn(pfn))) {
423 mark_mmio_spte(vcpu, sptep, gfn, access);
430 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
432 u64 kvm_gen, spte_gen, gen;
434 gen = kvm_vcpu_memslots(vcpu)->generation;
435 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
438 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
439 spte_gen = get_mmio_spte_generation(spte);
441 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
442 return likely(kvm_gen == spte_gen);
446 * Sets the shadow PTE masks used by the MMU.
449 * - Setting either @accessed_mask or @dirty_mask requires setting both
450 * - At least one of @accessed_mask or @acc_track_mask must be set
452 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
453 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
454 u64 acc_track_mask, u64 me_mask)
456 BUG_ON(!dirty_mask != !accessed_mask);
457 BUG_ON(!accessed_mask && !acc_track_mask);
458 BUG_ON(acc_track_mask & shadow_acc_track_value);
460 shadow_user_mask = user_mask;
461 shadow_accessed_mask = accessed_mask;
462 shadow_dirty_mask = dirty_mask;
463 shadow_nx_mask = nx_mask;
464 shadow_x_mask = x_mask;
465 shadow_present_mask = p_mask;
466 shadow_acc_track_mask = acc_track_mask;
467 shadow_me_mask = me_mask;
469 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
471 static void kvm_mmu_reset_all_pte_masks(void)
475 shadow_user_mask = 0;
476 shadow_accessed_mask = 0;
477 shadow_dirty_mask = 0;
480 shadow_mmio_mask = 0;
481 shadow_present_mask = 0;
482 shadow_acc_track_mask = 0;
485 * If the CPU has 46 or less physical address bits, then set an
486 * appropriate mask to guard against L1TF attacks. Otherwise, it is
487 * assumed that the CPU is not vulnerable to L1TF.
489 low_phys_bits = boot_cpu_data.x86_phys_bits;
490 if (boot_cpu_data.x86_phys_bits <
491 52 - shadow_nonpresent_or_rsvd_mask_len) {
492 shadow_nonpresent_or_rsvd_mask =
493 rsvd_bits(boot_cpu_data.x86_phys_bits -
494 shadow_nonpresent_or_rsvd_mask_len,
495 boot_cpu_data.x86_phys_bits - 1);
496 low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
498 shadow_nonpresent_or_rsvd_lower_gfn_mask =
499 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
502 static int is_cpuid_PSE36(void)
507 static int is_nx(struct kvm_vcpu *vcpu)
509 return vcpu->arch.efer & EFER_NX;
512 static int is_shadow_present_pte(u64 pte)
514 return (pte != 0) && !is_mmio_spte(pte);
517 static int is_large_pte(u64 pte)
519 return pte & PT_PAGE_SIZE_MASK;
522 static int is_last_spte(u64 pte, int level)
524 if (level == PT_PAGE_TABLE_LEVEL)
526 if (is_large_pte(pte))
531 static bool is_executable_pte(u64 spte)
533 return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
536 static kvm_pfn_t spte_to_pfn(u64 pte)
538 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
541 static gfn_t pse36_gfn_delta(u32 gpte)
543 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
545 return (gpte & PT32_DIR_PSE36_MASK) << shift;
549 static void __set_spte(u64 *sptep, u64 spte)
551 WRITE_ONCE(*sptep, spte);
554 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
556 WRITE_ONCE(*sptep, spte);
559 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
561 return xchg(sptep, spte);
564 static u64 __get_spte_lockless(u64 *sptep)
566 return READ_ONCE(*sptep);
577 static void count_spte_clear(u64 *sptep, u64 spte)
579 struct kvm_mmu_page *sp = page_header(__pa(sptep));
581 if (is_shadow_present_pte(spte))
584 /* Ensure the spte is completely set before we increase the count */
586 sp->clear_spte_count++;
589 static void __set_spte(u64 *sptep, u64 spte)
591 union split_spte *ssptep, sspte;
593 ssptep = (union split_spte *)sptep;
594 sspte = (union split_spte)spte;
596 ssptep->spte_high = sspte.spte_high;
599 * If we map the spte from nonpresent to present, We should store
600 * the high bits firstly, then set present bit, so cpu can not
601 * fetch this spte while we are setting the spte.
605 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
608 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
610 union split_spte *ssptep, sspte;
612 ssptep = (union split_spte *)sptep;
613 sspte = (union split_spte)spte;
615 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
618 * If we map the spte from present to nonpresent, we should clear
619 * present bit firstly to avoid vcpu fetch the old high bits.
623 ssptep->spte_high = sspte.spte_high;
624 count_spte_clear(sptep, spte);
627 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
629 union split_spte *ssptep, sspte, orig;
631 ssptep = (union split_spte *)sptep;
632 sspte = (union split_spte)spte;
634 /* xchg acts as a barrier before the setting of the high bits */
635 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
636 orig.spte_high = ssptep->spte_high;
637 ssptep->spte_high = sspte.spte_high;
638 count_spte_clear(sptep, spte);
644 * The idea using the light way get the spte on x86_32 guest is from
645 * gup_get_pte(arch/x86/mm/gup.c).
647 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
648 * coalesces them and we are running out of the MMU lock. Therefore
649 * we need to protect against in-progress updates of the spte.
651 * Reading the spte while an update is in progress may get the old value
652 * for the high part of the spte. The race is fine for a present->non-present
653 * change (because the high part of the spte is ignored for non-present spte),
654 * but for a present->present change we must reread the spte.
656 * All such changes are done in two steps (present->non-present and
657 * non-present->present), hence it is enough to count the number of
658 * present->non-present updates: if it changed while reading the spte,
659 * we might have hit the race. This is done using clear_spte_count.
661 static u64 __get_spte_lockless(u64 *sptep)
663 struct kvm_mmu_page *sp = page_header(__pa(sptep));
664 union split_spte spte, *orig = (union split_spte *)sptep;
668 count = sp->clear_spte_count;
671 spte.spte_low = orig->spte_low;
674 spte.spte_high = orig->spte_high;
677 if (unlikely(spte.spte_low != orig->spte_low ||
678 count != sp->clear_spte_count))
685 static bool spte_can_locklessly_be_made_writable(u64 spte)
687 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
688 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
691 static bool spte_has_volatile_bits(u64 spte)
693 if (!is_shadow_present_pte(spte))
697 * Always atomically update spte if it can be updated
698 * out of mmu-lock, it can ensure dirty bit is not lost,
699 * also, it can help us to get a stable is_writable_pte()
700 * to ensure tlb flush is not missed.
702 if (spte_can_locklessly_be_made_writable(spte) ||
703 is_access_track_spte(spte))
706 if (spte_ad_enabled(spte)) {
707 if ((spte & shadow_accessed_mask) == 0 ||
708 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
715 static bool is_accessed_spte(u64 spte)
717 u64 accessed_mask = spte_shadow_accessed_mask(spte);
719 return accessed_mask ? spte & accessed_mask
720 : !is_access_track_spte(spte);
723 static bool is_dirty_spte(u64 spte)
725 u64 dirty_mask = spte_shadow_dirty_mask(spte);
727 return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
730 /* Rules for using mmu_spte_set:
731 * Set the sptep from nonpresent to present.
732 * Note: the sptep being assigned *must* be either not present
733 * or in a state where the hardware will not attempt to update
736 static void mmu_spte_set(u64 *sptep, u64 new_spte)
738 WARN_ON(is_shadow_present_pte(*sptep));
739 __set_spte(sptep, new_spte);
743 * Update the SPTE (excluding the PFN), but do not track changes in its
744 * accessed/dirty status.
746 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
748 u64 old_spte = *sptep;
750 WARN_ON(!is_shadow_present_pte(new_spte));
752 if (!is_shadow_present_pte(old_spte)) {
753 mmu_spte_set(sptep, new_spte);
757 if (!spte_has_volatile_bits(old_spte))
758 __update_clear_spte_fast(sptep, new_spte);
760 old_spte = __update_clear_spte_slow(sptep, new_spte);
762 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
767 /* Rules for using mmu_spte_update:
768 * Update the state bits, it means the mapped pfn is not changed.
770 * Whenever we overwrite a writable spte with a read-only one we
771 * should flush remote TLBs. Otherwise rmap_write_protect
772 * will find a read-only spte, even though the writable spte
773 * might be cached on a CPU's TLB, the return value indicates this
776 * Returns true if the TLB needs to be flushed
778 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
781 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
783 if (!is_shadow_present_pte(old_spte))
787 * For the spte updated out of mmu-lock is safe, since
788 * we always atomically update it, see the comments in
789 * spte_has_volatile_bits().
791 if (spte_can_locklessly_be_made_writable(old_spte) &&
792 !is_writable_pte(new_spte))
796 * Flush TLB when accessed/dirty states are changed in the page tables,
797 * to guarantee consistency between TLB and page tables.
800 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
802 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
805 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
807 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
814 * Rules for using mmu_spte_clear_track_bits:
815 * It sets the sptep from present to nonpresent, and track the
816 * state bits, it is used to clear the last level sptep.
817 * Returns non-zero if the PTE was previously valid.
819 static int mmu_spte_clear_track_bits(u64 *sptep)
822 u64 old_spte = *sptep;
824 if (!spte_has_volatile_bits(old_spte))
825 __update_clear_spte_fast(sptep, 0ull);
827 old_spte = __update_clear_spte_slow(sptep, 0ull);
829 if (!is_shadow_present_pte(old_spte))
832 pfn = spte_to_pfn(old_spte);
835 * KVM does not hold the refcount of the page used by
836 * kvm mmu, before reclaiming the page, we should
837 * unmap it from mmu first.
839 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
841 if (is_accessed_spte(old_spte))
842 kvm_set_pfn_accessed(pfn);
844 if (is_dirty_spte(old_spte))
845 kvm_set_pfn_dirty(pfn);
851 * Rules for using mmu_spte_clear_no_track:
852 * Directly clear spte without caring the state bits of sptep,
853 * it is used to set the upper level spte.
855 static void mmu_spte_clear_no_track(u64 *sptep)
857 __update_clear_spte_fast(sptep, 0ull);
860 static u64 mmu_spte_get_lockless(u64 *sptep)
862 return __get_spte_lockless(sptep);
865 static u64 mark_spte_for_access_track(u64 spte)
867 if (spte_ad_enabled(spte))
868 return spte & ~shadow_accessed_mask;
870 if (is_access_track_spte(spte))
874 * Making an Access Tracking PTE will result in removal of write access
875 * from the PTE. So, verify that we will be able to restore the write
876 * access in the fast page fault path later on.
878 WARN_ONCE((spte & PT_WRITABLE_MASK) &&
879 !spte_can_locklessly_be_made_writable(spte),
880 "kvm: Writable SPTE is not locklessly dirty-trackable\n");
882 WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
883 shadow_acc_track_saved_bits_shift),
884 "kvm: Access Tracking saved bit locations are not zero\n");
886 spte |= (spte & shadow_acc_track_saved_bits_mask) <<
887 shadow_acc_track_saved_bits_shift;
888 spte &= ~shadow_acc_track_mask;
893 /* Restore an acc-track PTE back to a regular PTE */
894 static u64 restore_acc_track_spte(u64 spte)
897 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
898 & shadow_acc_track_saved_bits_mask;
900 WARN_ON_ONCE(spte_ad_enabled(spte));
901 WARN_ON_ONCE(!is_access_track_spte(spte));
903 new_spte &= ~shadow_acc_track_mask;
904 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
905 shadow_acc_track_saved_bits_shift);
906 new_spte |= saved_bits;
911 /* Returns the Accessed status of the PTE and resets it at the same time. */
912 static bool mmu_spte_age(u64 *sptep)
914 u64 spte = mmu_spte_get_lockless(sptep);
916 if (!is_accessed_spte(spte))
919 if (spte_ad_enabled(spte)) {
920 clear_bit((ffs(shadow_accessed_mask) - 1),
921 (unsigned long *)sptep);
924 * Capture the dirty status of the page, so that it doesn't get
925 * lost when the SPTE is marked for access tracking.
927 if (is_writable_pte(spte))
928 kvm_set_pfn_dirty(spte_to_pfn(spte));
930 spte = mark_spte_for_access_track(spte);
931 mmu_spte_update_no_track(sptep, spte);
937 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
940 * Prevent page table teardown by making any free-er wait during
941 * kvm_flush_remote_tlbs() IPI to all active vcpus.
946 * Make sure a following spte read is not reordered ahead of the write
949 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
952 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
955 * Make sure the write to vcpu->mode is not reordered in front of
956 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
957 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
959 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
963 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
964 struct kmem_cache *base_cache, int min)
968 if (cache->nobjs >= min)
970 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
971 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL_ACCOUNT);
973 return cache->nobjs >= min ? 0 : -ENOMEM;
974 cache->objects[cache->nobjs++] = obj;
979 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
984 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
985 struct kmem_cache *cache)
988 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
991 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
996 if (cache->nobjs >= min)
998 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
999 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1001 return cache->nobjs >= min ? 0 : -ENOMEM;
1002 cache->objects[cache->nobjs++] = page;
1007 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1010 free_page((unsigned long)mc->objects[--mc->nobjs]);
1013 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1017 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1018 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1021 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1024 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1025 mmu_page_header_cache, 4);
1030 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1032 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1033 pte_list_desc_cache);
1034 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1035 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1036 mmu_page_header_cache);
1039 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1044 p = mc->objects[--mc->nobjs];
1048 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1050 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1053 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1055 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1058 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1060 if (!sp->role.direct)
1061 return sp->gfns[index];
1063 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1066 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1068 if (sp->role.direct)
1069 BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index));
1071 sp->gfns[index] = gfn;
1075 * Return the pointer to the large page information for a given gfn,
1076 * handling slots that are not large page aligned.
1078 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1079 struct kvm_memory_slot *slot,
1084 idx = gfn_to_index(gfn, slot->base_gfn, level);
1085 return &slot->arch.lpage_info[level - 2][idx];
1088 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1089 gfn_t gfn, int count)
1091 struct kvm_lpage_info *linfo;
1094 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1095 linfo = lpage_info_slot(gfn, slot, i);
1096 linfo->disallow_lpage += count;
1097 WARN_ON(linfo->disallow_lpage < 0);
1101 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1103 update_gfn_disallow_lpage_count(slot, gfn, 1);
1106 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1108 update_gfn_disallow_lpage_count(slot, gfn, -1);
1111 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1113 struct kvm_memslots *slots;
1114 struct kvm_memory_slot *slot;
1117 kvm->arch.indirect_shadow_pages++;
1119 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1120 slot = __gfn_to_memslot(slots, gfn);
1122 /* the non-leaf shadow pages are keeping readonly. */
1123 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1124 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1125 KVM_PAGE_TRACK_WRITE);
1127 kvm_mmu_gfn_disallow_lpage(slot, gfn);
1130 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1132 struct kvm_memslots *slots;
1133 struct kvm_memory_slot *slot;
1136 kvm->arch.indirect_shadow_pages--;
1138 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1139 slot = __gfn_to_memslot(slots, gfn);
1140 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1141 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1142 KVM_PAGE_TRACK_WRITE);
1144 kvm_mmu_gfn_allow_lpage(slot, gfn);
1147 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1148 struct kvm_memory_slot *slot)
1150 struct kvm_lpage_info *linfo;
1153 linfo = lpage_info_slot(gfn, slot, level);
1154 return !!linfo->disallow_lpage;
1160 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1163 struct kvm_memory_slot *slot;
1165 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1166 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1169 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1171 unsigned long page_size;
1174 page_size = kvm_host_page_size(kvm, gfn);
1176 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1177 if (page_size >= KVM_HPAGE_SIZE(i))
1186 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1189 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1191 if (no_dirty_log && slot->dirty_bitmap)
1197 static struct kvm_memory_slot *
1198 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1201 struct kvm_memory_slot *slot;
1203 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1204 if (!memslot_valid_for_gpte(slot, no_dirty_log))
1210 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1211 bool *force_pt_level)
1213 int host_level, level, max_level;
1214 struct kvm_memory_slot *slot;
1216 if (unlikely(*force_pt_level))
1217 return PT_PAGE_TABLE_LEVEL;
1219 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1220 *force_pt_level = !memslot_valid_for_gpte(slot, true);
1221 if (unlikely(*force_pt_level))
1222 return PT_PAGE_TABLE_LEVEL;
1224 host_level = host_mapping_level(vcpu->kvm, large_gfn);
1226 if (host_level == PT_PAGE_TABLE_LEVEL)
1229 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1231 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1232 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1239 * About rmap_head encoding:
1241 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1242 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1243 * pte_list_desc containing more mappings.
1247 * Returns the number of pointers in the rmap chain, not counting the new one.
1249 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1250 struct kvm_rmap_head *rmap_head)
1252 struct pte_list_desc *desc;
1255 if (!rmap_head->val) {
1256 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1257 rmap_head->val = (unsigned long)spte;
1258 } else if (!(rmap_head->val & 1)) {
1259 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1260 desc = mmu_alloc_pte_list_desc(vcpu);
1261 desc->sptes[0] = (u64 *)rmap_head->val;
1262 desc->sptes[1] = spte;
1263 rmap_head->val = (unsigned long)desc | 1;
1266 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1267 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1268 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1270 count += PTE_LIST_EXT;
1272 if (desc->sptes[PTE_LIST_EXT-1]) {
1273 desc->more = mmu_alloc_pte_list_desc(vcpu);
1276 for (i = 0; desc->sptes[i]; ++i)
1278 desc->sptes[i] = spte;
1284 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1285 struct pte_list_desc *desc, int i,
1286 struct pte_list_desc *prev_desc)
1290 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1292 desc->sptes[i] = desc->sptes[j];
1293 desc->sptes[j] = NULL;
1296 if (!prev_desc && !desc->more)
1297 rmap_head->val = (unsigned long)desc->sptes[0];
1300 prev_desc->more = desc->more;
1302 rmap_head->val = (unsigned long)desc->more | 1;
1303 mmu_free_pte_list_desc(desc);
1306 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1308 struct pte_list_desc *desc;
1309 struct pte_list_desc *prev_desc;
1312 if (!rmap_head->val) {
1313 pr_err("%s: %p 0->BUG\n", __func__, spte);
1315 } else if (!(rmap_head->val & 1)) {
1316 rmap_printk("%s: %p 1->0\n", __func__, spte);
1317 if ((u64 *)rmap_head->val != spte) {
1318 pr_err("%s: %p 1->BUG\n", __func__, spte);
1323 rmap_printk("%s: %p many->many\n", __func__, spte);
1324 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1327 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1328 if (desc->sptes[i] == spte) {
1329 pte_list_desc_remove_entry(rmap_head,
1330 desc, i, prev_desc);
1337 pr_err("%s: %p many->many\n", __func__, spte);
1342 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1344 mmu_spte_clear_track_bits(sptep);
1345 __pte_list_remove(sptep, rmap_head);
1348 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1349 struct kvm_memory_slot *slot)
1353 idx = gfn_to_index(gfn, slot->base_gfn, level);
1354 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1357 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1358 struct kvm_mmu_page *sp)
1360 struct kvm_memslots *slots;
1361 struct kvm_memory_slot *slot;
1363 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1364 slot = __gfn_to_memslot(slots, gfn);
1365 return __gfn_to_rmap(gfn, sp->role.level, slot);
1368 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1370 struct kvm_mmu_memory_cache *cache;
1372 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1373 return mmu_memory_cache_free_objects(cache);
1376 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1378 struct kvm_mmu_page *sp;
1379 struct kvm_rmap_head *rmap_head;
1381 sp = page_header(__pa(spte));
1382 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1383 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1384 return pte_list_add(vcpu, spte, rmap_head);
1387 static void rmap_remove(struct kvm *kvm, u64 *spte)
1389 struct kvm_mmu_page *sp;
1391 struct kvm_rmap_head *rmap_head;
1393 sp = page_header(__pa(spte));
1394 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1395 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1396 __pte_list_remove(spte, rmap_head);
1400 * Used by the following functions to iterate through the sptes linked by a
1401 * rmap. All fields are private and not assumed to be used outside.
1403 struct rmap_iterator {
1404 /* private fields */
1405 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1406 int pos; /* index of the sptep */
1410 * Iteration must be started by this function. This should also be used after
1411 * removing/dropping sptes from the rmap link because in such cases the
1412 * information in the itererator may not be valid.
1414 * Returns sptep if found, NULL otherwise.
1416 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1417 struct rmap_iterator *iter)
1421 if (!rmap_head->val)
1424 if (!(rmap_head->val & 1)) {
1426 sptep = (u64 *)rmap_head->val;
1430 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1432 sptep = iter->desc->sptes[iter->pos];
1434 BUG_ON(!is_shadow_present_pte(*sptep));
1439 * Must be used with a valid iterator: e.g. after rmap_get_first().
1441 * Returns sptep if found, NULL otherwise.
1443 static u64 *rmap_get_next(struct rmap_iterator *iter)
1448 if (iter->pos < PTE_LIST_EXT - 1) {
1450 sptep = iter->desc->sptes[iter->pos];
1455 iter->desc = iter->desc->more;
1459 /* desc->sptes[0] cannot be NULL */
1460 sptep = iter->desc->sptes[iter->pos];
1467 BUG_ON(!is_shadow_present_pte(*sptep));
1471 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1472 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1473 _spte_; _spte_ = rmap_get_next(_iter_))
1475 static void drop_spte(struct kvm *kvm, u64 *sptep)
1477 if (mmu_spte_clear_track_bits(sptep))
1478 rmap_remove(kvm, sptep);
1482 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1484 if (is_large_pte(*sptep)) {
1485 WARN_ON(page_header(__pa(sptep))->role.level ==
1486 PT_PAGE_TABLE_LEVEL);
1487 drop_spte(kvm, sptep);
1495 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1497 if (__drop_large_spte(vcpu->kvm, sptep)) {
1498 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1500 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1501 KVM_PAGES_PER_HPAGE(sp->role.level));
1506 * Write-protect on the specified @sptep, @pt_protect indicates whether
1507 * spte write-protection is caused by protecting shadow page table.
1509 * Note: write protection is difference between dirty logging and spte
1511 * - for dirty logging, the spte can be set to writable at anytime if
1512 * its dirty bitmap is properly set.
1513 * - for spte protection, the spte can be writable only after unsync-ing
1516 * Return true if tlb need be flushed.
1518 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1522 if (!is_writable_pte(spte) &&
1523 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1526 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1529 spte &= ~SPTE_MMU_WRITEABLE;
1530 spte = spte & ~PT_WRITABLE_MASK;
1532 return mmu_spte_update(sptep, spte);
1535 static bool __rmap_write_protect(struct kvm *kvm,
1536 struct kvm_rmap_head *rmap_head,
1540 struct rmap_iterator iter;
1543 for_each_rmap_spte(rmap_head, &iter, sptep)
1544 flush |= spte_write_protect(sptep, pt_protect);
1549 static bool spte_clear_dirty(u64 *sptep)
1553 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1555 spte &= ~shadow_dirty_mask;
1557 return mmu_spte_update(sptep, spte);
1560 static bool wrprot_ad_disabled_spte(u64 *sptep)
1562 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1563 (unsigned long *)sptep);
1565 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1567 return was_writable;
1571 * Gets the GFN ready for another round of dirty logging by clearing the
1572 * - D bit on ad-enabled SPTEs, and
1573 * - W bit on ad-disabled SPTEs.
1574 * Returns true iff any D or W bits were cleared.
1576 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1579 struct rmap_iterator iter;
1582 for_each_rmap_spte(rmap_head, &iter, sptep)
1583 if (spte_ad_enabled(*sptep))
1584 flush |= spte_clear_dirty(sptep);
1586 flush |= wrprot_ad_disabled_spte(sptep);
1591 static bool spte_set_dirty(u64 *sptep)
1595 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1597 spte |= shadow_dirty_mask;
1599 return mmu_spte_update(sptep, spte);
1602 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1605 struct rmap_iterator iter;
1608 for_each_rmap_spte(rmap_head, &iter, sptep)
1609 if (spte_ad_enabled(*sptep))
1610 flush |= spte_set_dirty(sptep);
1616 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1617 * @kvm: kvm instance
1618 * @slot: slot to protect
1619 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1620 * @mask: indicates which pages we should protect
1622 * Used when we do not need to care about huge page mappings: e.g. during dirty
1623 * logging we do not have any such mappings.
1625 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1626 struct kvm_memory_slot *slot,
1627 gfn_t gfn_offset, unsigned long mask)
1629 struct kvm_rmap_head *rmap_head;
1632 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1633 PT_PAGE_TABLE_LEVEL, slot);
1634 __rmap_write_protect(kvm, rmap_head, false);
1636 /* clear the first set bit */
1642 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1643 * protect the page if the D-bit isn't supported.
1644 * @kvm: kvm instance
1645 * @slot: slot to clear D-bit
1646 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1647 * @mask: indicates which pages we should clear D-bit
1649 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1651 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1652 struct kvm_memory_slot *slot,
1653 gfn_t gfn_offset, unsigned long mask)
1655 struct kvm_rmap_head *rmap_head;
1658 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1659 PT_PAGE_TABLE_LEVEL, slot);
1660 __rmap_clear_dirty(kvm, rmap_head);
1662 /* clear the first set bit */
1666 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1669 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1672 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1673 * enable dirty logging for them.
1675 * Used when we do not need to care about huge page mappings: e.g. during dirty
1676 * logging we do not have any such mappings.
1678 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1679 struct kvm_memory_slot *slot,
1680 gfn_t gfn_offset, unsigned long mask)
1682 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1683 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1686 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1690 * kvm_arch_write_log_dirty - emulate dirty page logging
1691 * @vcpu: Guest mode vcpu
1693 * Emulate arch specific page modification logging for the
1696 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1698 if (kvm_x86_ops->write_log_dirty)
1699 return kvm_x86_ops->write_log_dirty(vcpu);
1704 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1705 struct kvm_memory_slot *slot, u64 gfn)
1707 struct kvm_rmap_head *rmap_head;
1709 bool write_protected = false;
1711 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1712 rmap_head = __gfn_to_rmap(gfn, i, slot);
1713 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1716 return write_protected;
1719 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1721 struct kvm_memory_slot *slot;
1723 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1724 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1727 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1730 struct rmap_iterator iter;
1733 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1734 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1736 pte_list_remove(rmap_head, sptep);
1743 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1744 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1747 return kvm_zap_rmapp(kvm, rmap_head);
1750 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1751 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1755 struct rmap_iterator iter;
1758 pte_t *ptep = (pte_t *)data;
1761 WARN_ON(pte_huge(*ptep));
1762 new_pfn = pte_pfn(*ptep);
1765 for_each_rmap_spte(rmap_head, &iter, sptep) {
1766 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1767 sptep, *sptep, gfn, level);
1771 if (pte_write(*ptep)) {
1772 pte_list_remove(rmap_head, sptep);
1775 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1776 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1778 new_spte &= ~PT_WRITABLE_MASK;
1779 new_spte &= ~SPTE_HOST_WRITEABLE;
1781 new_spte = mark_spte_for_access_track(new_spte);
1783 mmu_spte_clear_track_bits(sptep);
1784 mmu_spte_set(sptep, new_spte);
1788 if (need_flush && kvm_available_flush_tlb_with_range()) {
1789 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1796 struct slot_rmap_walk_iterator {
1798 struct kvm_memory_slot *slot;
1804 /* output fields. */
1806 struct kvm_rmap_head *rmap;
1809 /* private field. */
1810 struct kvm_rmap_head *end_rmap;
1814 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1816 iterator->level = level;
1817 iterator->gfn = iterator->start_gfn;
1818 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1819 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1824 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1825 struct kvm_memory_slot *slot, int start_level,
1826 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1828 iterator->slot = slot;
1829 iterator->start_level = start_level;
1830 iterator->end_level = end_level;
1831 iterator->start_gfn = start_gfn;
1832 iterator->end_gfn = end_gfn;
1834 rmap_walk_init_level(iterator, iterator->start_level);
1837 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1839 return !!iterator->rmap;
1842 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1844 if (++iterator->rmap <= iterator->end_rmap) {
1845 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1849 if (++iterator->level > iterator->end_level) {
1850 iterator->rmap = NULL;
1854 rmap_walk_init_level(iterator, iterator->level);
1857 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1858 _start_gfn, _end_gfn, _iter_) \
1859 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1860 _end_level_, _start_gfn, _end_gfn); \
1861 slot_rmap_walk_okay(_iter_); \
1862 slot_rmap_walk_next(_iter_))
1864 static int kvm_handle_hva_range(struct kvm *kvm,
1865 unsigned long start,
1868 int (*handler)(struct kvm *kvm,
1869 struct kvm_rmap_head *rmap_head,
1870 struct kvm_memory_slot *slot,
1873 unsigned long data))
1875 struct kvm_memslots *slots;
1876 struct kvm_memory_slot *memslot;
1877 struct slot_rmap_walk_iterator iterator;
1881 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1882 slots = __kvm_memslots(kvm, i);
1883 kvm_for_each_memslot(memslot, slots) {
1884 unsigned long hva_start, hva_end;
1885 gfn_t gfn_start, gfn_end;
1887 hva_start = max(start, memslot->userspace_addr);
1888 hva_end = min(end, memslot->userspace_addr +
1889 (memslot->npages << PAGE_SHIFT));
1890 if (hva_start >= hva_end)
1893 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1894 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1896 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1897 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1899 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1900 PT_MAX_HUGEPAGE_LEVEL,
1901 gfn_start, gfn_end - 1,
1903 ret |= handler(kvm, iterator.rmap, memslot,
1904 iterator.gfn, iterator.level, data);
1911 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1913 int (*handler)(struct kvm *kvm,
1914 struct kvm_rmap_head *rmap_head,
1915 struct kvm_memory_slot *slot,
1916 gfn_t gfn, int level,
1917 unsigned long data))
1919 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1922 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1924 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1927 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1929 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1932 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1933 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1937 struct rmap_iterator uninitialized_var(iter);
1940 for_each_rmap_spte(rmap_head, &iter, sptep)
1941 young |= mmu_spte_age(sptep);
1943 trace_kvm_age_page(gfn, level, slot, young);
1947 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1948 struct kvm_memory_slot *slot, gfn_t gfn,
1949 int level, unsigned long data)
1952 struct rmap_iterator iter;
1954 for_each_rmap_spte(rmap_head, &iter, sptep)
1955 if (is_accessed_spte(*sptep))
1960 #define RMAP_RECYCLE_THRESHOLD 1000
1962 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1964 struct kvm_rmap_head *rmap_head;
1965 struct kvm_mmu_page *sp;
1967 sp = page_header(__pa(spte));
1969 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1971 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1972 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1973 KVM_PAGES_PER_HPAGE(sp->role.level));
1976 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1978 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
1981 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1983 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1987 static int is_empty_shadow_page(u64 *spt)
1992 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1993 if (is_shadow_present_pte(*pos)) {
1994 printk(KERN_ERR "%s: %p %llx\n", __func__,
2003 * This value is the sum of all of the kvm instances's
2004 * kvm->arch.n_used_mmu_pages values. We need a global,
2005 * aggregate version in order to make the slab shrinker
2008 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
2010 kvm->arch.n_used_mmu_pages += nr;
2011 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2014 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2016 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2017 hlist_del(&sp->hash_link);
2018 list_del(&sp->link);
2019 free_page((unsigned long)sp->spt);
2020 if (!sp->role.direct)
2021 free_page((unsigned long)sp->gfns);
2022 kmem_cache_free(mmu_page_header_cache, sp);
2025 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2027 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2030 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2031 struct kvm_mmu_page *sp, u64 *parent_pte)
2036 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2039 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2042 __pte_list_remove(parent_pte, &sp->parent_ptes);
2045 static void drop_parent_pte(struct kvm_mmu_page *sp,
2048 mmu_page_remove_parent_pte(sp, parent_pte);
2049 mmu_spte_clear_no_track(parent_pte);
2052 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2054 struct kvm_mmu_page *sp;
2056 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2057 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2059 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2060 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2063 * The active_mmu_pages list is the FIFO list, do not move the
2064 * page until it is zapped. kvm_zap_obsolete_pages depends on
2065 * this feature. See the comments in kvm_zap_obsolete_pages().
2067 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2068 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2072 static void mark_unsync(u64 *spte);
2073 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2076 struct rmap_iterator iter;
2078 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2083 static void mark_unsync(u64 *spte)
2085 struct kvm_mmu_page *sp;
2088 sp = page_header(__pa(spte));
2089 index = spte - sp->spt;
2090 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2092 if (sp->unsync_children++)
2094 kvm_mmu_mark_parents_unsync(sp);
2097 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2098 struct kvm_mmu_page *sp)
2103 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2107 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2108 struct kvm_mmu_page *sp, u64 *spte,
2114 #define KVM_PAGE_ARRAY_NR 16
2116 struct kvm_mmu_pages {
2117 struct mmu_page_and_offset {
2118 struct kvm_mmu_page *sp;
2120 } page[KVM_PAGE_ARRAY_NR];
2124 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2130 for (i=0; i < pvec->nr; i++)
2131 if (pvec->page[i].sp == sp)
2134 pvec->page[pvec->nr].sp = sp;
2135 pvec->page[pvec->nr].idx = idx;
2137 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2140 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2142 --sp->unsync_children;
2143 WARN_ON((int)sp->unsync_children < 0);
2144 __clear_bit(idx, sp->unsync_child_bitmap);
2147 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2148 struct kvm_mmu_pages *pvec)
2150 int i, ret, nr_unsync_leaf = 0;
2152 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2153 struct kvm_mmu_page *child;
2154 u64 ent = sp->spt[i];
2156 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2157 clear_unsync_child_bit(sp, i);
2161 child = page_header(ent & PT64_BASE_ADDR_MASK);
2163 if (child->unsync_children) {
2164 if (mmu_pages_add(pvec, child, i))
2167 ret = __mmu_unsync_walk(child, pvec);
2169 clear_unsync_child_bit(sp, i);
2171 } else if (ret > 0) {
2172 nr_unsync_leaf += ret;
2175 } else if (child->unsync) {
2177 if (mmu_pages_add(pvec, child, i))
2180 clear_unsync_child_bit(sp, i);
2183 return nr_unsync_leaf;
2186 #define INVALID_INDEX (-1)
2188 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2189 struct kvm_mmu_pages *pvec)
2192 if (!sp->unsync_children)
2195 mmu_pages_add(pvec, sp, INVALID_INDEX);
2196 return __mmu_unsync_walk(sp, pvec);
2199 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2201 WARN_ON(!sp->unsync);
2202 trace_kvm_mmu_sync_page(sp);
2204 --kvm->stat.mmu_unsync;
2207 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2208 struct list_head *invalid_list);
2209 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2210 struct list_head *invalid_list);
2213 * NOTE: we should pay more attention on the zapped-obsolete page
2214 * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
2215 * since it has been deleted from active_mmu_pages but still can be found
2218 * for_each_valid_sp() has skipped that kind of pages.
2220 #define for_each_valid_sp(_kvm, _sp, _gfn) \
2221 hlist_for_each_entry(_sp, \
2222 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2223 if (is_obsolete_sp((_kvm), (_sp)) || (_sp)->role.invalid) { \
2226 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
2227 for_each_valid_sp(_kvm, _sp, _gfn) \
2228 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2230 /* @sp->gfn should be write-protected at the call site */
2231 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2232 struct list_head *invalid_list)
2234 if (sp->role.cr4_pae != !!is_pae(vcpu)
2235 || vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2236 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2243 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2244 struct list_head *invalid_list,
2245 bool remote_flush, bool local_flush)
2247 if (!list_empty(invalid_list)) {
2248 kvm_mmu_commit_zap_page(vcpu->kvm, invalid_list);
2253 kvm_flush_remote_tlbs(vcpu->kvm);
2254 else if (local_flush)
2255 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2258 #ifdef CONFIG_KVM_MMU_AUDIT
2259 #include "mmu_audit.c"
2261 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2262 static void mmu_audit_disable(void) { }
2265 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2267 return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2270 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2271 struct list_head *invalid_list)
2273 kvm_unlink_unsync_page(vcpu->kvm, sp);
2274 return __kvm_sync_page(vcpu, sp, invalid_list);
2277 /* @gfn should be write-protected at the call site */
2278 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2279 struct list_head *invalid_list)
2281 struct kvm_mmu_page *s;
2284 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2288 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2289 ret |= kvm_sync_page(vcpu, s, invalid_list);
2295 struct mmu_page_path {
2296 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2297 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2300 #define for_each_sp(pvec, sp, parents, i) \
2301 for (i = mmu_pages_first(&pvec, &parents); \
2302 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2303 i = mmu_pages_next(&pvec, &parents, i))
2305 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2306 struct mmu_page_path *parents,
2311 for (n = i+1; n < pvec->nr; n++) {
2312 struct kvm_mmu_page *sp = pvec->page[n].sp;
2313 unsigned idx = pvec->page[n].idx;
2314 int level = sp->role.level;
2316 parents->idx[level-1] = idx;
2317 if (level == PT_PAGE_TABLE_LEVEL)
2320 parents->parent[level-2] = sp;
2326 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2327 struct mmu_page_path *parents)
2329 struct kvm_mmu_page *sp;
2335 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2337 sp = pvec->page[0].sp;
2338 level = sp->role.level;
2339 WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2341 parents->parent[level-2] = sp;
2343 /* Also set up a sentinel. Further entries in pvec are all
2344 * children of sp, so this element is never overwritten.
2346 parents->parent[level-1] = NULL;
2347 return mmu_pages_next(pvec, parents, 0);
2350 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2352 struct kvm_mmu_page *sp;
2353 unsigned int level = 0;
2356 unsigned int idx = parents->idx[level];
2357 sp = parents->parent[level];
2361 WARN_ON(idx == INVALID_INDEX);
2362 clear_unsync_child_bit(sp, idx);
2364 } while (!sp->unsync_children);
2367 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2368 struct kvm_mmu_page *parent)
2371 struct kvm_mmu_page *sp;
2372 struct mmu_page_path parents;
2373 struct kvm_mmu_pages pages;
2374 LIST_HEAD(invalid_list);
2377 while (mmu_unsync_walk(parent, &pages)) {
2378 bool protected = false;
2380 for_each_sp(pages, sp, parents, i)
2381 protected |= rmap_write_protect(vcpu, sp->gfn);
2384 kvm_flush_remote_tlbs(vcpu->kvm);
2388 for_each_sp(pages, sp, parents, i) {
2389 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2390 mmu_pages_clear_parents(&parents);
2392 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2393 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2394 cond_resched_lock(&vcpu->kvm->mmu_lock);
2399 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2402 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2404 atomic_set(&sp->write_flooding_count, 0);
2407 static void clear_sp_write_flooding_count(u64 *spte)
2409 struct kvm_mmu_page *sp = page_header(__pa(spte));
2411 __clear_sp_write_flooding_count(sp);
2414 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2421 union kvm_mmu_page_role role;
2423 struct kvm_mmu_page *sp;
2424 bool need_sync = false;
2427 LIST_HEAD(invalid_list);
2429 role = vcpu->arch.mmu->mmu_role.base;
2431 role.direct = direct;
2434 role.access = access;
2435 if (!vcpu->arch.mmu->direct_map
2436 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2437 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2438 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2439 role.quadrant = quadrant;
2441 for_each_valid_sp(vcpu->kvm, sp, gfn) {
2442 if (sp->gfn != gfn) {
2447 if (!need_sync && sp->unsync)
2450 if (sp->role.word != role.word)
2454 /* The page is good, but __kvm_sync_page might still end
2455 * up zapping it. If so, break in order to rebuild it.
2457 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2460 WARN_ON(!list_empty(&invalid_list));
2461 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2464 if (sp->unsync_children)
2465 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2467 __clear_sp_write_flooding_count(sp);
2468 trace_kvm_mmu_get_page(sp, false);
2472 ++vcpu->kvm->stat.mmu_cache_miss;
2474 sp = kvm_mmu_alloc_page(vcpu, direct);
2478 hlist_add_head(&sp->hash_link,
2479 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2482 * we should do write protection before syncing pages
2483 * otherwise the content of the synced shadow page may
2484 * be inconsistent with guest page table.
2486 account_shadowed(vcpu->kvm, sp);
2487 if (level == PT_PAGE_TABLE_LEVEL &&
2488 rmap_write_protect(vcpu, gfn))
2489 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2491 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2492 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2494 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2495 clear_page(sp->spt);
2496 trace_kvm_mmu_get_page(sp, true);
2498 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2500 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2501 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2505 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2506 struct kvm_vcpu *vcpu, hpa_t root,
2509 iterator->addr = addr;
2510 iterator->shadow_addr = root;
2511 iterator->level = vcpu->arch.mmu->shadow_root_level;
2513 if (iterator->level == PT64_ROOT_4LEVEL &&
2514 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2515 !vcpu->arch.mmu->direct_map)
2518 if (iterator->level == PT32E_ROOT_LEVEL) {
2520 * prev_root is currently only used for 64-bit hosts. So only
2521 * the active root_hpa is valid here.
2523 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2525 iterator->shadow_addr
2526 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2527 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2529 if (!iterator->shadow_addr)
2530 iterator->level = 0;
2534 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2535 struct kvm_vcpu *vcpu, u64 addr)
2537 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2541 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2543 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2546 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2547 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2551 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2554 if (is_last_spte(spte, iterator->level)) {
2555 iterator->level = 0;
2559 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2563 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2565 __shadow_walk_next(iterator, *iterator->sptep);
2568 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2569 struct kvm_mmu_page *sp)
2573 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2575 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2576 shadow_user_mask | shadow_x_mask | shadow_me_mask;
2578 if (sp_ad_disabled(sp))
2579 spte |= shadow_acc_track_value;
2581 spte |= shadow_accessed_mask;
2583 mmu_spte_set(sptep, spte);
2585 mmu_page_add_parent_pte(vcpu, sp, sptep);
2587 if (sp->unsync_children || sp->unsync)
2591 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2592 unsigned direct_access)
2594 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2595 struct kvm_mmu_page *child;
2598 * For the direct sp, if the guest pte's dirty bit
2599 * changed form clean to dirty, it will corrupt the
2600 * sp's access: allow writable in the read-only sp,
2601 * so we should update the spte at this point to get
2602 * a new sp with the correct access.
2604 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2605 if (child->role.access == direct_access)
2608 drop_parent_pte(child, sptep);
2609 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2613 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2617 struct kvm_mmu_page *child;
2620 if (is_shadow_present_pte(pte)) {
2621 if (is_last_spte(pte, sp->role.level)) {
2622 drop_spte(kvm, spte);
2623 if (is_large_pte(pte))
2626 child = page_header(pte & PT64_BASE_ADDR_MASK);
2627 drop_parent_pte(child, spte);
2632 if (is_mmio_spte(pte))
2633 mmu_spte_clear_no_track(spte);
2638 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2639 struct kvm_mmu_page *sp)
2643 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2644 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2647 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2650 struct rmap_iterator iter;
2652 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2653 drop_parent_pte(sp, sptep);
2656 static int mmu_zap_unsync_children(struct kvm *kvm,
2657 struct kvm_mmu_page *parent,
2658 struct list_head *invalid_list)
2661 struct mmu_page_path parents;
2662 struct kvm_mmu_pages pages;
2664 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2667 while (mmu_unsync_walk(parent, &pages)) {
2668 struct kvm_mmu_page *sp;
2670 for_each_sp(pages, sp, parents, i) {
2671 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2672 mmu_pages_clear_parents(&parents);
2680 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2681 struct list_head *invalid_list)
2685 trace_kvm_mmu_prepare_zap_page(sp);
2686 ++kvm->stat.mmu_shadow_zapped;
2687 ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
2688 kvm_mmu_page_unlink_children(kvm, sp);
2689 kvm_mmu_unlink_parents(kvm, sp);
2691 if (!sp->role.invalid && !sp->role.direct)
2692 unaccount_shadowed(kvm, sp);
2695 kvm_unlink_unsync_page(kvm, sp);
2696 if (!sp->root_count) {
2699 list_move(&sp->link, invalid_list);
2700 kvm_mod_used_mmu_pages(kvm, -1);
2702 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2705 * The obsolete pages can not be used on any vcpus.
2706 * See the comments in kvm_mmu_invalidate_zap_all_pages().
2708 if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
2709 kvm_reload_remote_mmus(kvm);
2712 sp->role.invalid = 1;
2716 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2717 struct list_head *invalid_list)
2719 struct kvm_mmu_page *sp, *nsp;
2721 if (list_empty(invalid_list))
2725 * We need to make sure everyone sees our modifications to
2726 * the page tables and see changes to vcpu->mode here. The barrier
2727 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2728 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2730 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2731 * guest mode and/or lockless shadow page table walks.
2733 kvm_flush_remote_tlbs(kvm);
2735 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2736 WARN_ON(!sp->role.invalid || sp->root_count);
2737 kvm_mmu_free_page(sp);
2741 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2742 struct list_head *invalid_list)
2744 struct kvm_mmu_page *sp;
2746 if (list_empty(&kvm->arch.active_mmu_pages))
2749 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2750 struct kvm_mmu_page, link);
2751 return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2755 * Changing the number of mmu pages allocated to the vm
2756 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2758 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
2760 LIST_HEAD(invalid_list);
2762 spin_lock(&kvm->mmu_lock);
2764 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2765 /* Need to free some mmu pages to achieve the goal. */
2766 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2767 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2770 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2771 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2774 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2776 spin_unlock(&kvm->mmu_lock);
2779 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2781 struct kvm_mmu_page *sp;
2782 LIST_HEAD(invalid_list);
2785 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2787 spin_lock(&kvm->mmu_lock);
2788 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2789 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2792 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2794 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2795 spin_unlock(&kvm->mmu_lock);
2799 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2801 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2803 trace_kvm_mmu_unsync_page(sp);
2804 ++vcpu->kvm->stat.mmu_unsync;
2807 kvm_mmu_mark_parents_unsync(sp);
2810 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2813 struct kvm_mmu_page *sp;
2815 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2818 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2825 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2826 kvm_unsync_page(vcpu, sp);
2830 * We need to ensure that the marking of unsync pages is visible
2831 * before the SPTE is updated to allow writes because
2832 * kvm_mmu_sync_roots() checks the unsync flags without holding
2833 * the MMU lock and so can race with this. If the SPTE was updated
2834 * before the page had been marked as unsync-ed, something like the
2835 * following could happen:
2838 * ---------------------------------------------------------------------
2839 * 1.2 Host updates SPTE
2841 * 2.1 Guest writes a GPTE for GVA X.
2842 * (GPTE being in the guest page table shadowed
2843 * by the SP from CPU 1.)
2844 * This reads SPTE during the page table walk.
2845 * Since SPTE.W is read as 1, there is no
2848 * 2.2 Guest issues TLB flush.
2849 * That causes a VM Exit.
2851 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2852 * Since it is false, so it just returns.
2854 * 2.4 Guest accesses GVA X.
2855 * Since the mapping in the SP was not updated,
2856 * so the old mapping for GVA X incorrectly
2860 * (sp->unsync = true)
2862 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2863 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2864 * pairs with this write barrier.
2871 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2874 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2876 * Some reserved pages, such as those from NVDIMM
2877 * DAX devices, are not for MMIO, and can be mapped
2878 * with cached memory type for better performance.
2879 * However, the above check misconceives those pages
2880 * as MMIO, and results in KVM mapping them with UC
2881 * memory type, which would hurt the performance.
2882 * Therefore, we check the host memory type in addition
2883 * and only treat UC/UC-/WC pages as MMIO.
2885 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2890 /* Bits which may be returned by set_spte() */
2891 #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2892 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
2894 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2895 unsigned pte_access, int level,
2896 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2897 bool can_unsync, bool host_writable)
2901 struct kvm_mmu_page *sp;
2903 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2906 sp = page_header(__pa(sptep));
2907 if (sp_ad_disabled(sp))
2908 spte |= shadow_acc_track_value;
2911 * For the EPT case, shadow_present_mask is 0 if hardware
2912 * supports exec-only page table entries. In that case,
2913 * ACC_USER_MASK and shadow_user_mask are used to represent
2914 * read access. See FNAME(gpte_access) in paging_tmpl.h.
2916 spte |= shadow_present_mask;
2918 spte |= spte_shadow_accessed_mask(spte);
2920 if (pte_access & ACC_EXEC_MASK)
2921 spte |= shadow_x_mask;
2923 spte |= shadow_nx_mask;
2925 if (pte_access & ACC_USER_MASK)
2926 spte |= shadow_user_mask;
2928 if (level > PT_PAGE_TABLE_LEVEL)
2929 spte |= PT_PAGE_SIZE_MASK;
2931 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2932 kvm_is_mmio_pfn(pfn));
2935 spte |= SPTE_HOST_WRITEABLE;
2937 pte_access &= ~ACC_WRITE_MASK;
2939 if (!kvm_is_mmio_pfn(pfn))
2940 spte |= shadow_me_mask;
2942 spte |= (u64)pfn << PAGE_SHIFT;
2944 if (pte_access & ACC_WRITE_MASK) {
2947 * Other vcpu creates new sp in the window between
2948 * mapping_level() and acquiring mmu-lock. We can
2949 * allow guest to retry the access, the mapping can
2950 * be fixed if guest refault.
2952 if (level > PT_PAGE_TABLE_LEVEL &&
2953 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
2956 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
2959 * Optimization: for pte sync, if spte was writable the hash
2960 * lookup is unnecessary (and expensive). Write protection
2961 * is responsibility of mmu_get_page / kvm_sync_page.
2962 * Same reasoning can be applied to dirty page accounting.
2964 if (!can_unsync && is_writable_pte(*sptep))
2967 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
2968 pgprintk("%s: found shadow page for %llx, marking ro\n",
2970 ret |= SET_SPTE_WRITE_PROTECTED_PT;
2971 pte_access &= ~ACC_WRITE_MASK;
2972 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
2976 if (pte_access & ACC_WRITE_MASK) {
2977 kvm_vcpu_mark_page_dirty(vcpu, gfn);
2978 spte |= spte_shadow_dirty_mask(spte);
2982 spte = mark_spte_for_access_track(spte);
2985 if (mmu_spte_update(sptep, spte))
2986 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
2991 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
2992 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
2993 bool speculative, bool host_writable)
2995 int was_rmapped = 0;
2998 int ret = RET_PF_RETRY;
3001 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3002 *sptep, write_fault, gfn);
3004 if (is_shadow_present_pte(*sptep)) {
3006 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3007 * the parent of the now unreachable PTE.
3009 if (level > PT_PAGE_TABLE_LEVEL &&
3010 !is_large_pte(*sptep)) {
3011 struct kvm_mmu_page *child;
3014 child = page_header(pte & PT64_BASE_ADDR_MASK);
3015 drop_parent_pte(child, sptep);
3017 } else if (pfn != spte_to_pfn(*sptep)) {
3018 pgprintk("hfn old %llx new %llx\n",
3019 spte_to_pfn(*sptep), pfn);
3020 drop_spte(vcpu->kvm, sptep);
3026 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3027 speculative, true, host_writable);
3028 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3030 ret = RET_PF_EMULATE;
3031 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3034 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3035 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3036 KVM_PAGES_PER_HPAGE(level));
3038 if (unlikely(is_mmio_spte(*sptep)))
3039 ret = RET_PF_EMULATE;
3041 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3042 pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
3043 is_large_pte(*sptep)? "2MB" : "4kB",
3044 *sptep & PT_WRITABLE_MASK ? "RW" : "R", gfn,
3046 if (!was_rmapped && is_large_pte(*sptep))
3047 ++vcpu->kvm->stat.lpages;
3049 if (is_shadow_present_pte(*sptep)) {
3051 rmap_count = rmap_add(vcpu, sptep, gfn);
3052 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3053 rmap_recycle(vcpu, sptep, gfn);
3057 kvm_release_pfn_clean(pfn);
3062 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3065 struct kvm_memory_slot *slot;
3067 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3069 return KVM_PFN_ERR_FAULT;
3071 return gfn_to_pfn_memslot_atomic(slot, gfn);
3074 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3075 struct kvm_mmu_page *sp,
3076 u64 *start, u64 *end)
3078 struct page *pages[PTE_PREFETCH_NUM];
3079 struct kvm_memory_slot *slot;
3080 unsigned access = sp->role.access;
3084 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3085 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3089 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3093 for (i = 0; i < ret; i++, gfn++, start++)
3094 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3095 page_to_pfn(pages[i]), true, true);
3100 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3101 struct kvm_mmu_page *sp, u64 *sptep)
3103 u64 *spte, *start = NULL;
3106 WARN_ON(!sp->role.direct);
3108 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3111 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3112 if (is_shadow_present_pte(*spte) || spte == sptep) {
3115 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3123 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3125 struct kvm_mmu_page *sp;
3127 sp = page_header(__pa(sptep));
3130 * Without accessed bits, there's no way to distinguish between
3131 * actually accessed translations and prefetched, so disable pte
3132 * prefetch if accessed bits aren't available.
3134 if (sp_ad_disabled(sp))
3137 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3140 __direct_pte_prefetch(vcpu, sp, sptep);
3143 static int __direct_map(struct kvm_vcpu *vcpu, int write, int map_writable,
3144 int level, gfn_t gfn, kvm_pfn_t pfn, bool prefault)
3146 struct kvm_shadow_walk_iterator iterator;
3147 struct kvm_mmu_page *sp;
3151 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3154 for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
3155 if (iterator.level == level) {
3156 emulate = mmu_set_spte(vcpu, iterator.sptep, ACC_ALL,
3157 write, level, gfn, pfn, prefault,
3159 direct_pte_prefetch(vcpu, iterator.sptep);
3160 ++vcpu->stat.pf_fixed;
3164 drop_large_spte(vcpu, iterator.sptep);
3165 if (!is_shadow_present_pte(*iterator.sptep)) {
3166 u64 base_addr = iterator.addr;
3168 base_addr &= PT64_LVL_ADDR_MASK(iterator.level);
3169 pseudo_gfn = base_addr >> PAGE_SHIFT;
3170 sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
3171 iterator.level - 1, 1, ACC_ALL);
3173 link_shadow_page(vcpu, iterator.sptep, sp);
3179 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3181 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3184 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3187 * Do not cache the mmio info caused by writing the readonly gfn
3188 * into the spte otherwise read access on readonly gfn also can
3189 * caused mmio page fault and treat it as mmio access.
3191 if (pfn == KVM_PFN_ERR_RO_FAULT)
3192 return RET_PF_EMULATE;
3194 if (pfn == KVM_PFN_ERR_HWPOISON) {
3195 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3196 return RET_PF_RETRY;
3202 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3203 gfn_t *gfnp, kvm_pfn_t *pfnp,
3206 kvm_pfn_t pfn = *pfnp;
3208 int level = *levelp;
3211 * Check if it's a transparent hugepage. If this would be an
3212 * hugetlbfs page, level wouldn't be set to
3213 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3216 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3217 level == PT_PAGE_TABLE_LEVEL &&
3218 PageTransCompoundMap(pfn_to_page(pfn)) &&
3219 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3222 * mmu_notifier_retry was successful and we hold the
3223 * mmu_lock here, so the pmd can't become splitting
3224 * from under us, and in turn
3225 * __split_huge_page_refcount() can't run from under
3226 * us and we can safely transfer the refcount from
3227 * PG_tail to PG_head as we switch the pfn to tail to
3230 *levelp = level = PT_DIRECTORY_LEVEL;
3231 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3232 VM_BUG_ON((gfn & mask) != (pfn & mask));
3236 kvm_release_pfn_clean(pfn);
3244 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3245 kvm_pfn_t pfn, unsigned access, int *ret_val)
3247 /* The pfn is invalid, report the error! */
3248 if (unlikely(is_error_pfn(pfn))) {
3249 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3253 if (unlikely(is_noslot_pfn(pfn)))
3254 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
3259 static bool page_fault_can_be_fast(u32 error_code)
3262 * Do not fix the mmio spte with invalid generation number which
3263 * need to be updated by slow page fault path.
3265 if (unlikely(error_code & PFERR_RSVD_MASK))
3268 /* See if the page fault is due to an NX violation */
3269 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3270 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3274 * #PF can be fast if:
3275 * 1. The shadow page table entry is not present, which could mean that
3276 * the fault is potentially caused by access tracking (if enabled).
3277 * 2. The shadow page table entry is present and the fault
3278 * is caused by write-protect, that means we just need change the W
3279 * bit of the spte which can be done out of mmu-lock.
3281 * However, if access tracking is disabled we know that a non-present
3282 * page must be a genuine page fault where we have to create a new SPTE.
3283 * So, if access tracking is disabled, we return true only for write
3284 * accesses to a present page.
3287 return shadow_acc_track_mask != 0 ||
3288 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3289 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3293 * Returns true if the SPTE was fixed successfully. Otherwise,
3294 * someone else modified the SPTE from its original value.
3297 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3298 u64 *sptep, u64 old_spte, u64 new_spte)
3302 WARN_ON(!sp->role.direct);
3305 * Theoretically we could also set dirty bit (and flush TLB) here in
3306 * order to eliminate unnecessary PML logging. See comments in
3307 * set_spte. But fast_page_fault is very unlikely to happen with PML
3308 * enabled, so we do not do this. This might result in the same GPA
3309 * to be logged in PML buffer again when the write really happens, and
3310 * eventually to be called by mark_page_dirty twice. But it's also no
3311 * harm. This also avoids the TLB flush needed after setting dirty bit
3312 * so non-PML cases won't be impacted.
3314 * Compare with set_spte where instead shadow_dirty_mask is set.
3316 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3319 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3321 * The gfn of direct spte is stable since it is
3322 * calculated by sp->gfn.
3324 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3325 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3331 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3333 if (fault_err_code & PFERR_FETCH_MASK)
3334 return is_executable_pte(spte);
3336 if (fault_err_code & PFERR_WRITE_MASK)
3337 return is_writable_pte(spte);
3339 /* Fault was on Read access */
3340 return spte & PT_PRESENT_MASK;
3345 * - true: let the vcpu to access on the same address again.
3346 * - false: let the real page fault path to fix it.
3348 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3351 struct kvm_shadow_walk_iterator iterator;
3352 struct kvm_mmu_page *sp;
3353 bool fault_handled = false;
3355 uint retry_count = 0;
3357 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3360 if (!page_fault_can_be_fast(error_code))
3363 walk_shadow_page_lockless_begin(vcpu);
3368 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3369 if (!is_shadow_present_pte(spte) ||
3370 iterator.level < level)
3373 sp = page_header(__pa(iterator.sptep));
3374 if (!is_last_spte(spte, sp->role.level))
3378 * Check whether the memory access that caused the fault would
3379 * still cause it if it were to be performed right now. If not,
3380 * then this is a spurious fault caused by TLB lazily flushed,
3381 * or some other CPU has already fixed the PTE after the
3382 * current CPU took the fault.
3384 * Need not check the access of upper level table entries since
3385 * they are always ACC_ALL.
3387 if (is_access_allowed(error_code, spte)) {
3388 fault_handled = true;
3394 if (is_access_track_spte(spte))
3395 new_spte = restore_acc_track_spte(new_spte);
3398 * Currently, to simplify the code, write-protection can
3399 * be removed in the fast path only if the SPTE was
3400 * write-protected for dirty-logging or access tracking.
3402 if ((error_code & PFERR_WRITE_MASK) &&
3403 spte_can_locklessly_be_made_writable(spte))
3405 new_spte |= PT_WRITABLE_MASK;
3408 * Do not fix write-permission on the large spte. Since
3409 * we only dirty the first page into the dirty-bitmap in
3410 * fast_pf_fix_direct_spte(), other pages are missed
3411 * if its slot has dirty logging enabled.
3413 * Instead, we let the slow page fault path create a
3414 * normal spte to fix the access.
3416 * See the comments in kvm_arch_commit_memory_region().
3418 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3422 /* Verify that the fault can be handled in the fast path */
3423 if (new_spte == spte ||
3424 !is_access_allowed(error_code, new_spte))
3428 * Currently, fast page fault only works for direct mapping
3429 * since the gfn is not stable for indirect shadow page. See
3430 * Documentation/virtual/kvm/locking.txt to get more detail.
3432 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3433 iterator.sptep, spte,
3438 if (++retry_count > 4) {
3439 printk_once(KERN_WARNING
3440 "kvm: Fast #PF retrying more than 4 times.\n");
3446 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3447 spte, fault_handled);
3448 walk_shadow_page_lockless_end(vcpu);
3450 return fault_handled;
3453 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3454 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3455 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3457 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3458 gfn_t gfn, bool prefault)
3462 bool force_pt_level = false;
3464 unsigned long mmu_seq;
3465 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3467 level = mapping_level(vcpu, gfn, &force_pt_level);
3468 if (likely(!force_pt_level)) {
3470 * This path builds a PAE pagetable - so we can map
3471 * 2mb pages at maximum. Therefore check if the level
3472 * is larger than that.
3474 if (level > PT_DIRECTORY_LEVEL)
3475 level = PT_DIRECTORY_LEVEL;
3477 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3480 if (fast_page_fault(vcpu, v, level, error_code))
3481 return RET_PF_RETRY;
3483 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3486 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3487 return RET_PF_RETRY;
3489 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3492 spin_lock(&vcpu->kvm->mmu_lock);
3493 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3495 if (make_mmu_pages_available(vcpu) < 0)
3497 if (likely(!force_pt_level))
3498 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
3499 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
3500 spin_unlock(&vcpu->kvm->mmu_lock);
3505 spin_unlock(&vcpu->kvm->mmu_lock);
3506 kvm_release_pfn_clean(pfn);
3507 return RET_PF_RETRY;
3510 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3511 struct list_head *invalid_list)
3513 struct kvm_mmu_page *sp;
3515 if (!VALID_PAGE(*root_hpa))
3518 sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3520 if (!sp->root_count && sp->role.invalid)
3521 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3523 *root_hpa = INVALID_PAGE;
3526 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3527 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3528 ulong roots_to_free)
3531 LIST_HEAD(invalid_list);
3532 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3534 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3536 /* Before acquiring the MMU lock, see if we need to do any real work. */
3537 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3538 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3539 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3540 VALID_PAGE(mmu->prev_roots[i].hpa))
3543 if (i == KVM_MMU_NUM_PREV_ROOTS)
3547 spin_lock(&vcpu->kvm->mmu_lock);
3549 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3550 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3551 mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3554 if (free_active_root) {
3555 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3556 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3557 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3560 for (i = 0; i < 4; ++i)
3561 if (mmu->pae_root[i] != 0)
3562 mmu_free_root_page(vcpu->kvm,
3565 mmu->root_hpa = INVALID_PAGE;
3569 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3570 spin_unlock(&vcpu->kvm->mmu_lock);
3572 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3574 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3578 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3579 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3586 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3588 struct kvm_mmu_page *sp;
3591 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3592 spin_lock(&vcpu->kvm->mmu_lock);
3593 if(make_mmu_pages_available(vcpu) < 0) {
3594 spin_unlock(&vcpu->kvm->mmu_lock);
3597 sp = kvm_mmu_get_page(vcpu, 0, 0,
3598 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3600 spin_unlock(&vcpu->kvm->mmu_lock);
3601 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3602 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3603 for (i = 0; i < 4; ++i) {
3604 hpa_t root = vcpu->arch.mmu->pae_root[i];
3606 MMU_WARN_ON(VALID_PAGE(root));
3607 spin_lock(&vcpu->kvm->mmu_lock);
3608 if (make_mmu_pages_available(vcpu) < 0) {
3609 spin_unlock(&vcpu->kvm->mmu_lock);
3612 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3613 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3614 root = __pa(sp->spt);
3616 spin_unlock(&vcpu->kvm->mmu_lock);
3617 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3619 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3626 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3628 struct kvm_mmu_page *sp;
3633 root_gfn = vcpu->arch.mmu->get_cr3(vcpu) >> PAGE_SHIFT;
3635 if (mmu_check_root(vcpu, root_gfn))
3639 * Do we shadow a long mode page table? If so we need to
3640 * write-protect the guests page table root.
3642 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3643 hpa_t root = vcpu->arch.mmu->root_hpa;
3645 MMU_WARN_ON(VALID_PAGE(root));
3647 spin_lock(&vcpu->kvm->mmu_lock);
3648 if (make_mmu_pages_available(vcpu) < 0) {
3649 spin_unlock(&vcpu->kvm->mmu_lock);
3652 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3653 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3654 root = __pa(sp->spt);
3656 spin_unlock(&vcpu->kvm->mmu_lock);
3657 vcpu->arch.mmu->root_hpa = root;
3662 * We shadow a 32 bit page table. This may be a legacy 2-level
3663 * or a PAE 3-level page table. In either case we need to be aware that
3664 * the shadow page table may be a PAE or a long mode page table.
3666 pm_mask = PT_PRESENT_MASK;
3667 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3668 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3670 for (i = 0; i < 4; ++i) {
3671 hpa_t root = vcpu->arch.mmu->pae_root[i];
3673 MMU_WARN_ON(VALID_PAGE(root));
3674 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3675 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3676 if (!(pdptr & PT_PRESENT_MASK)) {
3677 vcpu->arch.mmu->pae_root[i] = 0;
3680 root_gfn = pdptr >> PAGE_SHIFT;
3681 if (mmu_check_root(vcpu, root_gfn))
3684 spin_lock(&vcpu->kvm->mmu_lock);
3685 if (make_mmu_pages_available(vcpu) < 0) {
3686 spin_unlock(&vcpu->kvm->mmu_lock);
3689 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3691 root = __pa(sp->spt);
3693 spin_unlock(&vcpu->kvm->mmu_lock);
3695 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3697 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3700 * If we shadow a 32 bit page table with a long mode page
3701 * table we enter this path.
3703 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3704 if (vcpu->arch.mmu->lm_root == NULL) {
3706 * The additional page necessary for this is only
3707 * allocated on demand.
3712 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3713 if (lm_root == NULL)
3716 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3718 vcpu->arch.mmu->lm_root = lm_root;
3721 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3727 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3729 if (vcpu->arch.mmu->direct_map)
3730 return mmu_alloc_direct_roots(vcpu);
3732 return mmu_alloc_shadow_roots(vcpu);
3735 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3738 struct kvm_mmu_page *sp;
3740 if (vcpu->arch.mmu->direct_map)
3743 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3746 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3748 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3749 hpa_t root = vcpu->arch.mmu->root_hpa;
3750 sp = page_header(root);
3753 * Even if another CPU was marking the SP as unsync-ed
3754 * simultaneously, any guest page table changes are not
3755 * guaranteed to be visible anyway until this VCPU issues a TLB
3756 * flush strictly after those changes are made. We only need to
3757 * ensure that the other CPU sets these flags before any actual
3758 * changes to the page tables are made. The comments in
3759 * mmu_need_write_protect() describe what could go wrong if this
3760 * requirement isn't satisfied.
3762 if (!smp_load_acquire(&sp->unsync) &&
3763 !smp_load_acquire(&sp->unsync_children))
3766 spin_lock(&vcpu->kvm->mmu_lock);
3767 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3769 mmu_sync_children(vcpu, sp);
3771 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3772 spin_unlock(&vcpu->kvm->mmu_lock);
3776 spin_lock(&vcpu->kvm->mmu_lock);
3777 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3779 for (i = 0; i < 4; ++i) {
3780 hpa_t root = vcpu->arch.mmu->pae_root[i];
3782 if (root && VALID_PAGE(root)) {
3783 root &= PT64_BASE_ADDR_MASK;
3784 sp = page_header(root);
3785 mmu_sync_children(vcpu, sp);
3789 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3790 spin_unlock(&vcpu->kvm->mmu_lock);
3792 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3794 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3795 u32 access, struct x86_exception *exception)
3798 exception->error_code = 0;
3802 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3804 struct x86_exception *exception)
3807 exception->error_code = 0;
3808 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3812 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3814 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3816 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3817 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3820 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3822 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3825 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3827 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3830 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3833 * A nested guest cannot use the MMIO cache if it is using nested
3834 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3836 if (mmu_is_nested(vcpu))
3840 return vcpu_match_mmio_gpa(vcpu, addr);
3842 return vcpu_match_mmio_gva(vcpu, addr);
3845 /* return true if reserved bit is detected on spte. */
3847 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3849 struct kvm_shadow_walk_iterator iterator;
3850 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3852 bool reserved = false;
3854 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3857 walk_shadow_page_lockless_begin(vcpu);
3859 for (shadow_walk_init(&iterator, vcpu, addr),
3860 leaf = root = iterator.level;
3861 shadow_walk_okay(&iterator);
3862 __shadow_walk_next(&iterator, spte)) {
3863 spte = mmu_spte_get_lockless(iterator.sptep);
3865 sptes[leaf - 1] = spte;
3868 if (!is_shadow_present_pte(spte))
3871 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3875 walk_shadow_page_lockless_end(vcpu);
3878 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3880 while (root > leaf) {
3881 pr_err("------ spte 0x%llx level %d.\n",
3882 sptes[root - 1], root);
3891 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3896 if (mmio_info_in_cache(vcpu, addr, direct))
3897 return RET_PF_EMULATE;
3899 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3900 if (WARN_ON(reserved))
3903 if (is_mmio_spte(spte)) {
3904 gfn_t gfn = get_mmio_spte_gfn(spte);
3905 unsigned access = get_mmio_spte_access(spte);
3907 if (!check_mmio_spte(vcpu, spte))
3908 return RET_PF_INVALID;
3913 trace_handle_mmio_page_fault(addr, gfn, access);
3914 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3915 return RET_PF_EMULATE;
3919 * If the page table is zapped by other cpus, let CPU fault again on
3922 return RET_PF_RETRY;
3925 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3926 u32 error_code, gfn_t gfn)
3928 if (unlikely(error_code & PFERR_RSVD_MASK))
3931 if (!(error_code & PFERR_PRESENT_MASK) ||
3932 !(error_code & PFERR_WRITE_MASK))
3936 * guest is writing the page which is write tracked which can
3937 * not be fixed by page fault handler.
3939 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3945 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3947 struct kvm_shadow_walk_iterator iterator;
3950 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3953 walk_shadow_page_lockless_begin(vcpu);
3954 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3955 clear_sp_write_flooding_count(iterator.sptep);
3956 if (!is_shadow_present_pte(spte))
3959 walk_shadow_page_lockless_end(vcpu);
3962 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
3963 u32 error_code, bool prefault)
3965 gfn_t gfn = gva >> PAGE_SHIFT;
3968 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
3970 if (page_fault_handle_page_track(vcpu, error_code, gfn))
3971 return RET_PF_EMULATE;
3973 r = mmu_topup_memory_caches(vcpu);
3977 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
3980 return nonpaging_map(vcpu, gva & PAGE_MASK,
3981 error_code, gfn, prefault);
3984 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
3986 struct kvm_arch_async_pf arch;
3988 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3990 arch.direct_map = vcpu->arch.mmu->direct_map;
3991 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3993 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3996 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
3998 if (unlikely(!lapic_in_kernel(vcpu) ||
3999 kvm_event_needs_reinjection(vcpu) ||
4000 vcpu->arch.exception.pending))
4003 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
4006 return kvm_x86_ops->interrupt_allowed(vcpu);
4009 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4010 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4012 struct kvm_memory_slot *slot;
4016 * Don't expose private memslots to L2.
4018 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4019 *pfn = KVM_PFN_NOSLOT;
4023 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4025 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4027 return false; /* *pfn has correct page already */
4029 if (!prefault && kvm_can_do_async_pf(vcpu)) {
4030 trace_kvm_try_async_get_page(gva, gfn);
4031 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4032 trace_kvm_async_pf_doublefault(gva, gfn);
4033 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4035 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4039 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4043 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4044 u64 fault_address, char *insn, int insn_len)
4048 vcpu->arch.l1tf_flush_l1d = true;
4049 switch (vcpu->arch.apf.host_apf_reason) {
4051 trace_kvm_page_fault(fault_address, error_code);
4053 if (kvm_event_needs_reinjection(vcpu))
4054 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4055 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4058 case KVM_PV_REASON_PAGE_NOT_PRESENT:
4059 vcpu->arch.apf.host_apf_reason = 0;
4060 local_irq_disable();
4061 kvm_async_pf_task_wait(fault_address, 0);
4064 case KVM_PV_REASON_PAGE_READY:
4065 vcpu->arch.apf.host_apf_reason = 0;
4066 local_irq_disable();
4067 kvm_async_pf_task_wake(fault_address);
4073 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4076 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4078 int page_num = KVM_PAGES_PER_HPAGE(level);
4080 gfn &= ~(page_num - 1);
4082 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4085 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4091 bool force_pt_level;
4092 gfn_t gfn = gpa >> PAGE_SHIFT;
4093 unsigned long mmu_seq;
4094 int write = error_code & PFERR_WRITE_MASK;
4097 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4099 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4100 return RET_PF_EMULATE;
4102 r = mmu_topup_memory_caches(vcpu);
4106 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4107 PT_DIRECTORY_LEVEL);
4108 level = mapping_level(vcpu, gfn, &force_pt_level);
4109 if (likely(!force_pt_level)) {
4110 if (level > PT_DIRECTORY_LEVEL &&
4111 !check_hugepage_cache_consistency(vcpu, gfn, level))
4112 level = PT_DIRECTORY_LEVEL;
4113 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4116 if (fast_page_fault(vcpu, gpa, level, error_code))
4117 return RET_PF_RETRY;
4119 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4122 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4123 return RET_PF_RETRY;
4125 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4128 spin_lock(&vcpu->kvm->mmu_lock);
4129 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4131 if (make_mmu_pages_available(vcpu) < 0)
4133 if (likely(!force_pt_level))
4134 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
4135 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
4136 spin_unlock(&vcpu->kvm->mmu_lock);
4141 spin_unlock(&vcpu->kvm->mmu_lock);
4142 kvm_release_pfn_clean(pfn);
4143 return RET_PF_RETRY;
4146 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4147 struct kvm_mmu *context)
4149 context->page_fault = nonpaging_page_fault;
4150 context->gva_to_gpa = nonpaging_gva_to_gpa;
4151 context->sync_page = nonpaging_sync_page;
4152 context->invlpg = nonpaging_invlpg;
4153 context->update_pte = nonpaging_update_pte;
4154 context->root_level = 0;
4155 context->shadow_root_level = PT32E_ROOT_LEVEL;
4156 context->direct_map = true;
4157 context->nx = false;
4161 * Find out if a previously cached root matching the new CR3/role is available.
4162 * The current root is also inserted into the cache.
4163 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4165 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4166 * false is returned. This root should now be freed by the caller.
4168 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4169 union kvm_mmu_page_role new_role)
4172 struct kvm_mmu_root_info root;
4173 struct kvm_mmu *mmu = vcpu->arch.mmu;
4175 root.cr3 = mmu->get_cr3(vcpu);
4176 root.hpa = mmu->root_hpa;
4178 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4179 swap(root, mmu->prev_roots[i]);
4181 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4182 page_header(root.hpa) != NULL &&
4183 new_role.word == page_header(root.hpa)->role.word)
4187 mmu->root_hpa = root.hpa;
4189 return i < KVM_MMU_NUM_PREV_ROOTS;
4192 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4193 union kvm_mmu_page_role new_role,
4194 bool skip_tlb_flush)
4196 struct kvm_mmu *mmu = vcpu->arch.mmu;
4199 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4200 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4201 * later if necessary.
4203 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4204 mmu->root_level >= PT64_ROOT_4LEVEL) {
4205 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4208 if (cached_root_available(vcpu, new_cr3, new_role)) {
4210 * It is possible that the cached previous root page is
4211 * obsolete because of a change in the MMU
4212 * generation number. However, that is accompanied by
4213 * KVM_REQ_MMU_RELOAD, which will free the root that we
4214 * have set here and allocate a new one.
4217 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4218 if (!skip_tlb_flush) {
4219 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4220 kvm_x86_ops->tlb_flush(vcpu, true);
4224 * The last MMIO access's GVA and GPA are cached in the
4225 * VCPU. When switching to a new CR3, that GVA->GPA
4226 * mapping may no longer be valid. So clear any cached
4227 * MMIO info even when we don't need to sync the shadow
4230 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4232 __clear_sp_write_flooding_count(
4233 page_header(mmu->root_hpa));
4242 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4243 union kvm_mmu_page_role new_role,
4244 bool skip_tlb_flush)
4246 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4247 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4248 KVM_MMU_ROOT_CURRENT);
4251 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4253 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4256 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4258 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4260 return kvm_read_cr3(vcpu);
4263 static void inject_page_fault(struct kvm_vcpu *vcpu,
4264 struct x86_exception *fault)
4266 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4269 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4270 unsigned access, int *nr_present)
4272 if (unlikely(is_mmio_spte(*sptep))) {
4273 if (gfn != get_mmio_spte_gfn(*sptep)) {
4274 mmu_spte_clear_no_track(sptep);
4279 mark_mmio_spte(vcpu, sptep, gfn, access);
4286 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4287 unsigned level, unsigned gpte)
4290 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4291 * If it is clear, there are no large pages at this level, so clear
4292 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4294 gpte &= level - mmu->last_nonleaf_level;
4297 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4298 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4299 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4301 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4303 return gpte & PT_PAGE_SIZE_MASK;
4306 #define PTTYPE_EPT 18 /* arbitrary */
4307 #define PTTYPE PTTYPE_EPT
4308 #include "paging_tmpl.h"
4312 #include "paging_tmpl.h"
4316 #include "paging_tmpl.h"
4320 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4321 struct rsvd_bits_validate *rsvd_check,
4322 int maxphyaddr, int level, bool nx, bool gbpages,
4325 u64 exb_bit_rsvd = 0;
4326 u64 gbpages_bit_rsvd = 0;
4327 u64 nonleaf_bit8_rsvd = 0;
4329 rsvd_check->bad_mt_xwr = 0;
4332 exb_bit_rsvd = rsvd_bits(63, 63);
4334 gbpages_bit_rsvd = rsvd_bits(7, 7);
4337 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4338 * leaf entries) on AMD CPUs only.
4341 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4344 case PT32_ROOT_LEVEL:
4345 /* no rsvd bits for 2 level 4K page table entries */
4346 rsvd_check->rsvd_bits_mask[0][1] = 0;
4347 rsvd_check->rsvd_bits_mask[0][0] = 0;
4348 rsvd_check->rsvd_bits_mask[1][0] =
4349 rsvd_check->rsvd_bits_mask[0][0];
4352 rsvd_check->rsvd_bits_mask[1][1] = 0;
4356 if (is_cpuid_PSE36())
4357 /* 36bits PSE 4MB page */
4358 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4360 /* 32 bits PSE 4MB page */
4361 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4363 case PT32E_ROOT_LEVEL:
4364 rsvd_check->rsvd_bits_mask[0][2] =
4365 rsvd_bits(maxphyaddr, 63) |
4366 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4367 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4368 rsvd_bits(maxphyaddr, 62); /* PDE */
4369 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4370 rsvd_bits(maxphyaddr, 62); /* PTE */
4371 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4372 rsvd_bits(maxphyaddr, 62) |
4373 rsvd_bits(13, 20); /* large page */
4374 rsvd_check->rsvd_bits_mask[1][0] =
4375 rsvd_check->rsvd_bits_mask[0][0];
4377 case PT64_ROOT_5LEVEL:
4378 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4379 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4380 rsvd_bits(maxphyaddr, 51);
4381 rsvd_check->rsvd_bits_mask[1][4] =
4382 rsvd_check->rsvd_bits_mask[0][4];
4384 case PT64_ROOT_4LEVEL:
4385 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4386 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4387 rsvd_bits(maxphyaddr, 51);
4388 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4389 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4390 rsvd_bits(maxphyaddr, 51);
4391 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4392 rsvd_bits(maxphyaddr, 51);
4393 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4394 rsvd_bits(maxphyaddr, 51);
4395 rsvd_check->rsvd_bits_mask[1][3] =
4396 rsvd_check->rsvd_bits_mask[0][3];
4397 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4398 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4400 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4401 rsvd_bits(maxphyaddr, 51) |
4402 rsvd_bits(13, 20); /* large page */
4403 rsvd_check->rsvd_bits_mask[1][0] =
4404 rsvd_check->rsvd_bits_mask[0][0];
4409 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4410 struct kvm_mmu *context)
4412 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4413 cpuid_maxphyaddr(vcpu), context->root_level,
4415 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4416 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4420 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4421 int maxphyaddr, bool execonly)
4425 rsvd_check->rsvd_bits_mask[0][4] =
4426 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4427 rsvd_check->rsvd_bits_mask[0][3] =
4428 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4429 rsvd_check->rsvd_bits_mask[0][2] =
4430 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4431 rsvd_check->rsvd_bits_mask[0][1] =
4432 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4433 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4436 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4437 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4438 rsvd_check->rsvd_bits_mask[1][2] =
4439 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4440 rsvd_check->rsvd_bits_mask[1][1] =
4441 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4442 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4444 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4445 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4446 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4447 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4448 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4450 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4451 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4453 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4456 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4457 struct kvm_mmu *context, bool execonly)
4459 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4460 cpuid_maxphyaddr(vcpu), execonly);
4464 * the page table on host is the shadow page table for the page
4465 * table in guest or amd nested guest, its mmu features completely
4466 * follow the features in guest.
4469 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4471 bool uses_nx = context->nx ||
4472 context->mmu_role.base.smep_andnot_wp;
4473 struct rsvd_bits_validate *shadow_zero_check;
4477 * Passing "true" to the last argument is okay; it adds a check
4478 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4480 shadow_zero_check = &context->shadow_zero_check;
4481 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4482 boot_cpu_data.x86_phys_bits,
4483 context->shadow_root_level, uses_nx,
4484 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4485 is_pse(vcpu), true);
4487 if (!shadow_me_mask)
4490 for (i = context->shadow_root_level; --i >= 0;) {
4491 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4492 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4496 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4498 static inline bool boot_cpu_is_amd(void)
4500 WARN_ON_ONCE(!tdp_enabled);
4501 return shadow_x_mask == 0;
4505 * the direct page table on host, use as much mmu features as
4506 * possible, however, kvm currently does not do execution-protection.
4509 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4510 struct kvm_mmu *context)
4512 struct rsvd_bits_validate *shadow_zero_check;
4515 shadow_zero_check = &context->shadow_zero_check;
4517 if (boot_cpu_is_amd())
4518 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4519 boot_cpu_data.x86_phys_bits,
4520 context->shadow_root_level, false,
4521 boot_cpu_has(X86_FEATURE_GBPAGES),
4524 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4525 boot_cpu_data.x86_phys_bits,
4528 if (!shadow_me_mask)
4531 for (i = context->shadow_root_level; --i >= 0;) {
4532 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4533 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4538 * as the comments in reset_shadow_zero_bits_mask() except it
4539 * is the shadow page table for intel nested guest.
4542 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4543 struct kvm_mmu *context, bool execonly)
4545 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4546 boot_cpu_data.x86_phys_bits, execonly);
4549 #define BYTE_MASK(access) \
4550 ((1 & (access) ? 2 : 0) | \
4551 (2 & (access) ? 4 : 0) | \
4552 (3 & (access) ? 8 : 0) | \
4553 (4 & (access) ? 16 : 0) | \
4554 (5 & (access) ? 32 : 0) | \
4555 (6 & (access) ? 64 : 0) | \
4556 (7 & (access) ? 128 : 0))
4559 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4560 struct kvm_mmu *mmu, bool ept)
4564 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4565 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4566 const u8 u = BYTE_MASK(ACC_USER_MASK);
4568 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4569 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4570 bool cr0_wp = is_write_protection(vcpu);
4572 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4573 unsigned pfec = byte << 1;
4576 * Each "*f" variable has a 1 bit for each UWX value
4577 * that causes a fault with the given PFEC.
4580 /* Faults from writes to non-writable pages */
4581 u8 wf = (pfec & PFERR_WRITE_MASK) ? ~w : 0;
4582 /* Faults from user mode accesses to supervisor pages */
4583 u8 uf = (pfec & PFERR_USER_MASK) ? ~u : 0;
4584 /* Faults from fetches of non-executable pages*/
4585 u8 ff = (pfec & PFERR_FETCH_MASK) ? ~x : 0;
4586 /* Faults from kernel mode fetches of user pages */
4588 /* Faults from kernel mode accesses of user pages */
4592 /* Faults from kernel mode accesses to user pages */
4593 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4595 /* Not really needed: !nx will cause pte.nx to fault */
4599 /* Allow supervisor writes if !cr0.wp */
4601 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4603 /* Disallow supervisor fetches of user code if cr4.smep */
4605 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4608 * SMAP:kernel-mode data accesses from user-mode
4609 * mappings should fault. A fault is considered
4610 * as a SMAP violation if all of the following
4611 * conditions are true:
4612 * - X86_CR4_SMAP is set in CR4
4613 * - A user page is accessed
4614 * - The access is not a fetch
4615 * - Page fault in kernel mode
4616 * - if CPL = 3 or X86_EFLAGS_AC is clear
4618 * Here, we cover the first three conditions.
4619 * The fourth is computed dynamically in permission_fault();
4620 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4621 * *not* subject to SMAP restrictions.
4624 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4627 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4632 * PKU is an additional mechanism by which the paging controls access to
4633 * user-mode addresses based on the value in the PKRU register. Protection
4634 * key violations are reported through a bit in the page fault error code.
4635 * Unlike other bits of the error code, the PK bit is not known at the
4636 * call site of e.g. gva_to_gpa; it must be computed directly in
4637 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4638 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4640 * In particular the following conditions come from the error code, the
4641 * page tables and the machine state:
4642 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4643 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4644 * - PK is always zero if U=0 in the page tables
4645 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4647 * The PKRU bitmask caches the result of these four conditions. The error
4648 * code (minus the P bit) and the page table's U bit form an index into the
4649 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4650 * with the two bits of the PKRU register corresponding to the protection key.
4651 * For the first three conditions above the bits will be 00, thus masking
4652 * away both AD and WD. For all reads or if the last condition holds, WD
4653 * only will be masked away.
4655 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4666 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4667 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4672 wp = is_write_protection(vcpu);
4674 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4675 unsigned pfec, pkey_bits;
4676 bool check_pkey, check_write, ff, uf, wf, pte_user;
4679 ff = pfec & PFERR_FETCH_MASK;
4680 uf = pfec & PFERR_USER_MASK;
4681 wf = pfec & PFERR_WRITE_MASK;
4683 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4684 pte_user = pfec & PFERR_RSVD_MASK;
4687 * Only need to check the access which is not an
4688 * instruction fetch and is to a user page.
4690 check_pkey = (!ff && pte_user);
4692 * write access is controlled by PKRU if it is a
4693 * user access or CR0.WP = 1.
4695 check_write = check_pkey && wf && (uf || wp);
4697 /* PKRU.AD stops both read and write access. */
4698 pkey_bits = !!check_pkey;
4699 /* PKRU.WD stops write access. */
4700 pkey_bits |= (!!check_write) << 1;
4702 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4706 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4708 unsigned root_level = mmu->root_level;
4710 mmu->last_nonleaf_level = root_level;
4711 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4712 mmu->last_nonleaf_level++;
4715 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4716 struct kvm_mmu *context,
4719 context->nx = is_nx(vcpu);
4720 context->root_level = level;
4722 reset_rsvds_bits_mask(vcpu, context);
4723 update_permission_bitmask(vcpu, context, false);
4724 update_pkru_bitmask(vcpu, context, false);
4725 update_last_nonleaf_level(vcpu, context);
4727 MMU_WARN_ON(!is_pae(vcpu));
4728 context->page_fault = paging64_page_fault;
4729 context->gva_to_gpa = paging64_gva_to_gpa;
4730 context->sync_page = paging64_sync_page;
4731 context->invlpg = paging64_invlpg;
4732 context->update_pte = paging64_update_pte;
4733 context->shadow_root_level = level;
4734 context->direct_map = false;
4737 static void paging64_init_context(struct kvm_vcpu *vcpu,
4738 struct kvm_mmu *context)
4740 int root_level = is_la57_mode(vcpu) ?
4741 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4743 paging64_init_context_common(vcpu, context, root_level);
4746 static void paging32_init_context(struct kvm_vcpu *vcpu,
4747 struct kvm_mmu *context)
4749 context->nx = false;
4750 context->root_level = PT32_ROOT_LEVEL;
4752 reset_rsvds_bits_mask(vcpu, context);
4753 update_permission_bitmask(vcpu, context, false);
4754 update_pkru_bitmask(vcpu, context, false);
4755 update_last_nonleaf_level(vcpu, context);
4757 context->page_fault = paging32_page_fault;
4758 context->gva_to_gpa = paging32_gva_to_gpa;
4759 context->sync_page = paging32_sync_page;
4760 context->invlpg = paging32_invlpg;
4761 context->update_pte = paging32_update_pte;
4762 context->shadow_root_level = PT32E_ROOT_LEVEL;
4763 context->direct_map = false;
4766 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4767 struct kvm_mmu *context)
4769 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4772 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4774 union kvm_mmu_extended_role ext = {0};
4776 ext.cr0_pg = !!is_paging(vcpu);
4777 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4778 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4779 ext.cr4_pse = !!is_pse(vcpu);
4780 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4781 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4788 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4791 union kvm_mmu_role role = {0};
4793 role.base.access = ACC_ALL;
4794 role.base.nxe = !!is_nx(vcpu);
4795 role.base.cr4_pae = !!is_pae(vcpu);
4796 role.base.cr0_wp = is_write_protection(vcpu);
4797 role.base.smm = is_smm(vcpu);
4798 role.base.guest_mode = is_guest_mode(vcpu);
4803 role.ext = kvm_calc_mmu_role_ext(vcpu);
4808 static union kvm_mmu_role
4809 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4811 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4813 role.base.ad_disabled = (shadow_accessed_mask == 0);
4814 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4815 role.base.direct = true;
4820 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4822 struct kvm_mmu *context = vcpu->arch.mmu;
4823 union kvm_mmu_role new_role =
4824 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4826 new_role.base.word &= mmu_base_role_mask.word;
4827 if (new_role.as_u64 == context->mmu_role.as_u64)
4830 context->mmu_role.as_u64 = new_role.as_u64;
4831 context->page_fault = tdp_page_fault;
4832 context->sync_page = nonpaging_sync_page;
4833 context->invlpg = nonpaging_invlpg;
4834 context->update_pte = nonpaging_update_pte;
4835 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4836 context->direct_map = true;
4837 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4838 context->get_cr3 = get_cr3;
4839 context->get_pdptr = kvm_pdptr_read;
4840 context->inject_page_fault = kvm_inject_page_fault;
4842 if (!is_paging(vcpu)) {
4843 context->nx = false;
4844 context->gva_to_gpa = nonpaging_gva_to_gpa;
4845 context->root_level = 0;
4846 } else if (is_long_mode(vcpu)) {
4847 context->nx = is_nx(vcpu);
4848 context->root_level = is_la57_mode(vcpu) ?
4849 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4850 reset_rsvds_bits_mask(vcpu, context);
4851 context->gva_to_gpa = paging64_gva_to_gpa;
4852 } else if (is_pae(vcpu)) {
4853 context->nx = is_nx(vcpu);
4854 context->root_level = PT32E_ROOT_LEVEL;
4855 reset_rsvds_bits_mask(vcpu, context);
4856 context->gva_to_gpa = paging64_gva_to_gpa;
4858 context->nx = false;
4859 context->root_level = PT32_ROOT_LEVEL;
4860 reset_rsvds_bits_mask(vcpu, context);
4861 context->gva_to_gpa = paging32_gva_to_gpa;
4864 update_permission_bitmask(vcpu, context, false);
4865 update_pkru_bitmask(vcpu, context, false);
4866 update_last_nonleaf_level(vcpu, context);
4867 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4870 static union kvm_mmu_role
4871 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4873 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4875 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4876 !is_write_protection(vcpu);
4877 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4878 !is_write_protection(vcpu);
4879 role.base.direct = !is_paging(vcpu);
4881 if (!is_long_mode(vcpu))
4882 role.base.level = PT32E_ROOT_LEVEL;
4883 else if (is_la57_mode(vcpu))
4884 role.base.level = PT64_ROOT_5LEVEL;
4886 role.base.level = PT64_ROOT_4LEVEL;
4891 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4893 struct kvm_mmu *context = vcpu->arch.mmu;
4894 union kvm_mmu_role new_role =
4895 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4897 new_role.base.word &= mmu_base_role_mask.word;
4898 if (new_role.as_u64 == context->mmu_role.as_u64)
4901 if (!is_paging(vcpu))
4902 nonpaging_init_context(vcpu, context);
4903 else if (is_long_mode(vcpu))
4904 paging64_init_context(vcpu, context);
4905 else if (is_pae(vcpu))
4906 paging32E_init_context(vcpu, context);
4908 paging32_init_context(vcpu, context);
4910 context->mmu_role.as_u64 = new_role.as_u64;
4911 reset_shadow_zero_bits_mask(vcpu, context);
4913 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4915 static union kvm_mmu_role
4916 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4919 union kvm_mmu_role role;
4921 /* Base role is inherited from root_mmu */
4922 role.base.word = vcpu->arch.root_mmu.mmu_role.base.word;
4923 role.ext = kvm_calc_mmu_role_ext(vcpu);
4925 role.base.level = PT64_ROOT_4LEVEL;
4926 role.base.direct = false;
4927 role.base.ad_disabled = !accessed_dirty;
4928 role.base.guest_mode = true;
4929 role.base.access = ACC_ALL;
4931 role.ext.execonly = execonly;
4936 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4937 bool accessed_dirty, gpa_t new_eptp)
4939 struct kvm_mmu *context = vcpu->arch.mmu;
4940 union kvm_mmu_role new_role =
4941 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4944 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
4946 new_role.base.word &= mmu_base_role_mask.word;
4947 if (new_role.as_u64 == context->mmu_role.as_u64)
4950 context->shadow_root_level = PT64_ROOT_4LEVEL;
4953 context->ept_ad = accessed_dirty;
4954 context->page_fault = ept_page_fault;
4955 context->gva_to_gpa = ept_gva_to_gpa;
4956 context->sync_page = ept_sync_page;
4957 context->invlpg = ept_invlpg;
4958 context->update_pte = ept_update_pte;
4959 context->root_level = PT64_ROOT_4LEVEL;
4960 context->direct_map = false;
4961 context->mmu_role.as_u64 = new_role.as_u64;
4963 update_permission_bitmask(vcpu, context, true);
4964 update_pkru_bitmask(vcpu, context, true);
4965 update_last_nonleaf_level(vcpu, context);
4966 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4967 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4969 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4971 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4973 struct kvm_mmu *context = vcpu->arch.mmu;
4975 kvm_init_shadow_mmu(vcpu);
4976 context->set_cr3 = kvm_x86_ops->set_cr3;
4977 context->get_cr3 = get_cr3;
4978 context->get_pdptr = kvm_pdptr_read;
4979 context->inject_page_fault = kvm_inject_page_fault;
4982 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4984 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
4985 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4987 new_role.base.word &= mmu_base_role_mask.word;
4988 if (new_role.as_u64 == g_context->mmu_role.as_u64)
4991 g_context->mmu_role.as_u64 = new_role.as_u64;
4992 g_context->get_cr3 = get_cr3;
4993 g_context->get_pdptr = kvm_pdptr_read;
4994 g_context->inject_page_fault = kvm_inject_page_fault;
4997 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
4998 * L1's nested page tables (e.g. EPT12). The nested translation
4999 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5000 * L2's page tables as the first level of translation and L1's
5001 * nested page tables as the second level of translation. Basically
5002 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5004 if (!is_paging(vcpu)) {
5005 g_context->nx = false;
5006 g_context->root_level = 0;
5007 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5008 } else if (is_long_mode(vcpu)) {
5009 g_context->nx = is_nx(vcpu);
5010 g_context->root_level = is_la57_mode(vcpu) ?
5011 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5012 reset_rsvds_bits_mask(vcpu, g_context);
5013 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5014 } else if (is_pae(vcpu)) {
5015 g_context->nx = is_nx(vcpu);
5016 g_context->root_level = PT32E_ROOT_LEVEL;
5017 reset_rsvds_bits_mask(vcpu, g_context);
5018 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5020 g_context->nx = false;
5021 g_context->root_level = PT32_ROOT_LEVEL;
5022 reset_rsvds_bits_mask(vcpu, g_context);
5023 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5026 update_permission_bitmask(vcpu, g_context, false);
5027 update_pkru_bitmask(vcpu, g_context, false);
5028 update_last_nonleaf_level(vcpu, g_context);
5031 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5036 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5038 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5039 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5042 if (mmu_is_nested(vcpu))
5043 init_kvm_nested_mmu(vcpu);
5044 else if (tdp_enabled)
5045 init_kvm_tdp_mmu(vcpu);
5047 init_kvm_softmmu(vcpu);
5049 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5051 static union kvm_mmu_page_role
5052 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5054 union kvm_mmu_role role;
5057 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5059 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5064 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5066 kvm_mmu_unload(vcpu);
5067 kvm_init_mmu(vcpu, true);
5069 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5071 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5075 r = mmu_topup_memory_caches(vcpu);
5078 r = mmu_alloc_roots(vcpu);
5079 kvm_mmu_sync_roots(vcpu);
5082 kvm_mmu_load_cr3(vcpu);
5083 kvm_x86_ops->tlb_flush(vcpu, true);
5087 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5089 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5091 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5092 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5093 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5094 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5096 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5098 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5099 struct kvm_mmu_page *sp, u64 *spte,
5102 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5103 ++vcpu->kvm->stat.mmu_pde_zapped;
5107 ++vcpu->kvm->stat.mmu_pte_updated;
5108 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5111 static bool need_remote_flush(u64 old, u64 new)
5113 if (!is_shadow_present_pte(old))
5115 if (!is_shadow_present_pte(new))
5117 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5119 old ^= shadow_nx_mask;
5120 new ^= shadow_nx_mask;
5121 return (old & ~new & PT64_PERM_MASK) != 0;
5124 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5131 * Assume that the pte write on a page table of the same type
5132 * as the current vcpu paging mode since we update the sptes only
5133 * when they have the same mode.
5135 if (is_pae(vcpu) && *bytes == 4) {
5136 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5141 if (*bytes == 4 || *bytes == 8) {
5142 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5151 * If we're seeing too many writes to a page, it may no longer be a page table,
5152 * or we may be forking, in which case it is better to unmap the page.
5154 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5157 * Skip write-flooding detected for the sp whose level is 1, because
5158 * it can become unsync, then the guest page is not write-protected.
5160 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5163 atomic_inc(&sp->write_flooding_count);
5164 return atomic_read(&sp->write_flooding_count) >= 3;
5168 * Misaligned accesses are too much trouble to fix up; also, they usually
5169 * indicate a page is not used as a page table.
5171 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5174 unsigned offset, pte_size, misaligned;
5176 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5177 gpa, bytes, sp->role.word);
5179 offset = offset_in_page(gpa);
5180 pte_size = sp->role.cr4_pae ? 8 : 4;
5183 * Sometimes, the OS only writes the last one bytes to update status
5184 * bits, for example, in linux, andb instruction is used in clear_bit().
5186 if (!(offset & (pte_size - 1)) && bytes == 1)
5189 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5190 misaligned |= bytes < 4;
5195 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5197 unsigned page_offset, quadrant;
5201 page_offset = offset_in_page(gpa);
5202 level = sp->role.level;
5204 if (!sp->role.cr4_pae) {
5205 page_offset <<= 1; /* 32->64 */
5207 * A 32-bit pde maps 4MB while the shadow pdes map
5208 * only 2MB. So we need to double the offset again
5209 * and zap two pdes instead of one.
5211 if (level == PT32_ROOT_LEVEL) {
5212 page_offset &= ~7; /* kill rounding error */
5216 quadrant = page_offset >> PAGE_SHIFT;
5217 page_offset &= ~PAGE_MASK;
5218 if (quadrant != sp->role.quadrant)
5222 spte = &sp->spt[page_offset / sizeof(*spte)];
5226 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5227 const u8 *new, int bytes,
5228 struct kvm_page_track_notifier_node *node)
5230 gfn_t gfn = gpa >> PAGE_SHIFT;
5231 struct kvm_mmu_page *sp;
5232 LIST_HEAD(invalid_list);
5233 u64 entry, gentry, *spte;
5235 bool remote_flush, local_flush;
5238 * If we don't have indirect shadow pages, it means no page is
5239 * write-protected, so we can exit simply.
5241 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5244 remote_flush = local_flush = false;
5246 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5249 * No need to care whether allocation memory is successful
5250 * or not since pte prefetch is skiped if it does not have
5251 * enough objects in the cache.
5253 mmu_topup_memory_caches(vcpu);
5255 spin_lock(&vcpu->kvm->mmu_lock);
5257 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5259 ++vcpu->kvm->stat.mmu_pte_write;
5260 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5262 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5263 if (detect_write_misaligned(sp, gpa, bytes) ||
5264 detect_write_flooding(sp)) {
5265 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5266 ++vcpu->kvm->stat.mmu_flooded;
5270 spte = get_written_sptes(sp, gpa, &npte);
5276 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5279 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5281 !((sp->role.word ^ base_role)
5282 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5283 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5284 if (need_remote_flush(entry, *spte))
5285 remote_flush = true;
5289 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5290 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5291 spin_unlock(&vcpu->kvm->mmu_lock);
5294 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5299 if (vcpu->arch.mmu->direct_map)
5302 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5304 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5308 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5310 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5312 LIST_HEAD(invalid_list);
5314 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5317 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5318 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5321 ++vcpu->kvm->stat.mmu_recycled;
5323 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5325 if (!kvm_mmu_available_pages(vcpu->kvm))
5330 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5331 void *insn, int insn_len)
5333 int r, emulation_type = 0;
5334 enum emulation_result er;
5335 bool direct = vcpu->arch.mmu->direct_map;
5337 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5338 if (vcpu->arch.mmu->direct_map) {
5339 vcpu->arch.gpa_available = true;
5340 vcpu->arch.gpa_val = cr2;
5344 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5345 r = handle_mmio_page_fault(vcpu, cr2, direct);
5346 if (r == RET_PF_EMULATE)
5350 if (r == RET_PF_INVALID) {
5351 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5352 lower_32_bits(error_code),
5354 WARN_ON(r == RET_PF_INVALID);
5357 if (r == RET_PF_RETRY)
5363 * Before emulating the instruction, check if the error code
5364 * was due to a RO violation while translating the guest page.
5365 * This can occur when using nested virtualization with nested
5366 * paging in both guests. If true, we simply unprotect the page
5367 * and resume the guest.
5369 if (vcpu->arch.mmu->direct_map &&
5370 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5371 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5376 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5377 * optimistically try to just unprotect the page and let the processor
5378 * re-execute the instruction that caused the page fault. Do not allow
5379 * retrying MMIO emulation, as it's not only pointless but could also
5380 * cause us to enter an infinite loop because the processor will keep
5381 * faulting on the non-existent MMIO address. Retrying an instruction
5382 * from a nested guest is also pointless and dangerous as we are only
5383 * explicitly shadowing L1's page tables, i.e. unprotecting something
5384 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5386 if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5387 emulation_type = EMULTYPE_ALLOW_RETRY;
5390 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5391 * This can happen if a guest gets a page-fault on data access but the HW
5392 * table walker is not able to read the instruction page (e.g instruction
5393 * page is not present in memory). In those cases we simply restart the
5396 if (unlikely(insn && !insn_len))
5399 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
5404 case EMULATE_USER_EXIT:
5405 ++vcpu->stat.mmio_exits;
5413 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5415 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5417 struct kvm_mmu *mmu = vcpu->arch.mmu;
5420 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
5421 if (is_noncanonical_address(gva, vcpu))
5424 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5427 * INVLPG is required to invalidate any global mappings for the VA,
5428 * irrespective of PCID. Since it would take us roughly similar amount
5429 * of work to determine whether any of the prev_root mappings of the VA
5430 * is marked global, or to just sync it blindly, so we might as well
5431 * just always sync it.
5433 * Mappings not reachable via the current cr3 or the prev_roots will be
5434 * synced when switching to that cr3, so nothing needs to be done here
5437 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5438 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5439 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5441 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5442 ++vcpu->stat.invlpg;
5444 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5446 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5448 struct kvm_mmu *mmu = vcpu->arch.mmu;
5449 bool tlb_flush = false;
5452 if (pcid == kvm_get_active_pcid(vcpu)) {
5453 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5457 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5458 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5459 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5460 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5466 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5468 ++vcpu->stat.invlpg;
5471 * Mappings not reachable via the current cr3 or the prev_roots will be
5472 * synced when switching to that cr3, so nothing needs to be done here
5476 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5478 void kvm_enable_tdp(void)
5482 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5484 void kvm_disable_tdp(void)
5486 tdp_enabled = false;
5488 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5491 /* The return value indicates if tlb flush on all vcpus is needed. */
5492 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5494 /* The caller should hold mmu-lock before calling this function. */
5495 static __always_inline bool
5496 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5497 slot_level_handler fn, int start_level, int end_level,
5498 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5500 struct slot_rmap_walk_iterator iterator;
5503 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5504 end_gfn, &iterator) {
5506 flush |= fn(kvm, iterator.rmap);
5508 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5509 if (flush && lock_flush_tlb) {
5510 kvm_flush_remote_tlbs(kvm);
5513 cond_resched_lock(&kvm->mmu_lock);
5517 if (flush && lock_flush_tlb) {
5518 kvm_flush_remote_tlbs(kvm);
5525 static __always_inline bool
5526 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5527 slot_level_handler fn, int start_level, int end_level,
5528 bool lock_flush_tlb)
5530 return slot_handle_level_range(kvm, memslot, fn, start_level,
5531 end_level, memslot->base_gfn,
5532 memslot->base_gfn + memslot->npages - 1,
5536 static __always_inline bool
5537 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5538 slot_level_handler fn, bool lock_flush_tlb)
5540 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5541 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5544 static __always_inline bool
5545 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5546 slot_level_handler fn, bool lock_flush_tlb)
5548 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5549 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5552 static __always_inline bool
5553 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5554 slot_level_handler fn, bool lock_flush_tlb)
5556 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5557 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5560 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5562 free_page((unsigned long)vcpu->arch.mmu->pae_root);
5563 free_page((unsigned long)vcpu->arch.mmu->lm_root);
5566 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5575 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5576 * Therefore we need to allocate shadow page tables in the first
5577 * 4GB of memory, which happens to fit the DMA32 zone.
5579 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5583 vcpu->arch.mmu->pae_root = page_address(page);
5584 for (i = 0; i < 4; ++i)
5585 vcpu->arch.mmu->pae_root[i] = INVALID_PAGE;
5590 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5594 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5595 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5597 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5598 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5599 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5600 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5602 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5603 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5604 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5605 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5607 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5608 return alloc_mmu_pages(vcpu);
5611 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5612 struct kvm_memory_slot *slot,
5613 struct kvm_page_track_notifier_node *node)
5615 kvm_mmu_invalidate_zap_all_pages(kvm);
5618 void kvm_mmu_init_vm(struct kvm *kvm)
5620 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5622 node->track_write = kvm_mmu_pte_write;
5623 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5624 kvm_page_track_register_notifier(kvm, node);
5627 void kvm_mmu_uninit_vm(struct kvm *kvm)
5629 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5631 kvm_page_track_unregister_notifier(kvm, node);
5634 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5636 struct kvm_memslots *slots;
5637 struct kvm_memory_slot *memslot;
5638 bool flush_tlb = true;
5642 if (kvm_available_flush_tlb_with_range())
5645 spin_lock(&kvm->mmu_lock);
5646 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5647 slots = __kvm_memslots(kvm, i);
5648 kvm_for_each_memslot(memslot, slots) {
5651 start = max(gfn_start, memslot->base_gfn);
5652 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5656 flush |= slot_handle_level_range(kvm, memslot,
5657 kvm_zap_rmapp, PT_PAGE_TABLE_LEVEL,
5658 PT_MAX_HUGEPAGE_LEVEL, start,
5659 end - 1, flush_tlb);
5664 kvm_flush_remote_tlbs_with_address(kvm, gfn_start,
5665 gfn_end - gfn_start + 1);
5667 spin_unlock(&kvm->mmu_lock);
5670 static bool slot_rmap_write_protect(struct kvm *kvm,
5671 struct kvm_rmap_head *rmap_head)
5673 return __rmap_write_protect(kvm, rmap_head, false);
5676 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5677 struct kvm_memory_slot *memslot)
5681 spin_lock(&kvm->mmu_lock);
5682 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5684 spin_unlock(&kvm->mmu_lock);
5687 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5688 * which do tlb flush out of mmu-lock should be serialized by
5689 * kvm->slots_lock otherwise tlb flush would be missed.
5691 lockdep_assert_held(&kvm->slots_lock);
5694 * We can flush all the TLBs out of the mmu lock without TLB
5695 * corruption since we just change the spte from writable to
5696 * readonly so that we only need to care the case of changing
5697 * spte from present to present (changing the spte from present
5698 * to nonpresent will flush all the TLBs immediately), in other
5699 * words, the only case we care is mmu_spte_update() where we
5700 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5701 * instead of PT_WRITABLE_MASK, that means it does not depend
5702 * on PT_WRITABLE_MASK anymore.
5705 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5709 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5710 struct kvm_rmap_head *rmap_head)
5713 struct rmap_iterator iter;
5714 int need_tlb_flush = 0;
5716 struct kvm_mmu_page *sp;
5719 for_each_rmap_spte(rmap_head, &iter, sptep) {
5720 sp = page_header(__pa(sptep));
5721 pfn = spte_to_pfn(*sptep);
5724 * We cannot do huge page mapping for indirect shadow pages,
5725 * which are found on the last rmap (level = 1) when not using
5726 * tdp; such shadow pages are synced with the page table in
5727 * the guest, and the guest page table is using 4K page size
5728 * mapping if the indirect sp has level = 1.
5730 if (sp->role.direct &&
5731 !kvm_is_reserved_pfn(pfn) &&
5732 PageTransCompoundMap(pfn_to_page(pfn))) {
5733 pte_list_remove(rmap_head, sptep);
5735 if (kvm_available_flush_tlb_with_range())
5736 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5737 KVM_PAGES_PER_HPAGE(sp->role.level));
5745 return need_tlb_flush;
5748 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5749 const struct kvm_memory_slot *memslot)
5751 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5752 spin_lock(&kvm->mmu_lock);
5753 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5754 kvm_mmu_zap_collapsible_spte, true);
5755 spin_unlock(&kvm->mmu_lock);
5758 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5759 struct kvm_memory_slot *memslot)
5763 spin_lock(&kvm->mmu_lock);
5764 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5765 spin_unlock(&kvm->mmu_lock);
5767 lockdep_assert_held(&kvm->slots_lock);
5770 * It's also safe to flush TLBs out of mmu lock here as currently this
5771 * function is only used for dirty logging, in which case flushing TLB
5772 * out of mmu lock also guarantees no dirty pages will be lost in
5776 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5779 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5781 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5782 struct kvm_memory_slot *memslot)
5786 spin_lock(&kvm->mmu_lock);
5787 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5789 spin_unlock(&kvm->mmu_lock);
5791 /* see kvm_mmu_slot_remove_write_access */
5792 lockdep_assert_held(&kvm->slots_lock);
5795 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5798 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5800 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5801 struct kvm_memory_slot *memslot)
5805 spin_lock(&kvm->mmu_lock);
5806 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5807 spin_unlock(&kvm->mmu_lock);
5809 lockdep_assert_held(&kvm->slots_lock);
5811 /* see kvm_mmu_slot_leaf_clear_dirty */
5813 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5816 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5818 #define BATCH_ZAP_PAGES 10
5819 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5821 struct kvm_mmu_page *sp, *node;
5825 list_for_each_entry_safe_reverse(sp, node,
5826 &kvm->arch.active_mmu_pages, link) {
5830 * No obsolete page exists before new created page since
5831 * active_mmu_pages is the FIFO list.
5833 if (!is_obsolete_sp(kvm, sp))
5837 * Since we are reversely walking the list and the invalid
5838 * list will be moved to the head, skip the invalid page
5839 * can help us to avoid the infinity list walking.
5841 if (sp->role.invalid)
5845 * Need not flush tlb since we only zap the sp with invalid
5846 * generation number.
5848 if (batch >= BATCH_ZAP_PAGES &&
5849 cond_resched_lock(&kvm->mmu_lock)) {
5854 ret = kvm_mmu_prepare_zap_page(kvm, sp,
5855 &kvm->arch.zapped_obsolete_pages);
5863 * Should flush tlb before free page tables since lockless-walking
5864 * may use the pages.
5866 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5870 * Fast invalidate all shadow pages and use lock-break technique
5871 * to zap obsolete pages.
5873 * It's required when memslot is being deleted or VM is being
5874 * destroyed, in these cases, we should ensure that KVM MMU does
5875 * not use any resource of the being-deleted slot or all slots
5876 * after calling the function.
5878 void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
5880 spin_lock(&kvm->mmu_lock);
5881 trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5882 kvm->arch.mmu_valid_gen++;
5885 * Notify all vcpus to reload its shadow page table
5886 * and flush TLB. Then all vcpus will switch to new
5887 * shadow page table with the new mmu_valid_gen.
5889 * Note: we should do this under the protection of
5890 * mmu-lock, otherwise, vcpu would purge shadow page
5891 * but miss tlb flush.
5893 kvm_reload_remote_mmus(kvm);
5895 kvm_zap_obsolete_pages(kvm);
5896 spin_unlock(&kvm->mmu_lock);
5899 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5901 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5904 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5906 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
5908 gen &= MMIO_SPTE_GEN_MASK;
5911 * Generation numbers are incremented in multiples of the number of
5912 * address spaces in order to provide unique generations across all
5913 * address spaces. Strip what is effectively the address space
5914 * modifier prior to checking for a wrap of the MMIO generation so
5915 * that a wrap in any address space is detected.
5917 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5920 * The very rare case: if the MMIO generation number has wrapped,
5921 * zap all shadow pages.
5923 if (unlikely(gen == 0)) {
5924 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5925 kvm_mmu_invalidate_zap_all_pages(kvm);
5929 static unsigned long
5930 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5933 int nr_to_scan = sc->nr_to_scan;
5934 unsigned long freed = 0;
5936 spin_lock(&kvm_lock);
5938 list_for_each_entry(kvm, &vm_list, vm_list) {
5940 LIST_HEAD(invalid_list);
5943 * Never scan more than sc->nr_to_scan VM instances.
5944 * Will not hit this condition practically since we do not try
5945 * to shrink more than one VM and it is very unlikely to see
5946 * !n_used_mmu_pages so many times.
5951 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5952 * here. We may skip a VM instance errorneosly, but we do not
5953 * want to shrink a VM that only started to populate its MMU
5956 if (!kvm->arch.n_used_mmu_pages &&
5957 !kvm_has_zapped_obsolete_pages(kvm))
5960 idx = srcu_read_lock(&kvm->srcu);
5961 spin_lock(&kvm->mmu_lock);
5963 if (kvm_has_zapped_obsolete_pages(kvm)) {
5964 kvm_mmu_commit_zap_page(kvm,
5965 &kvm->arch.zapped_obsolete_pages);
5969 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
5971 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5974 spin_unlock(&kvm->mmu_lock);
5975 srcu_read_unlock(&kvm->srcu, idx);
5978 * unfair on small ones
5979 * per-vm shrinkers cry out
5980 * sadness comes quickly
5982 list_move_tail(&kvm->vm_list, &vm_list);
5986 spin_unlock(&kvm_lock);
5990 static unsigned long
5991 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5993 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5996 static struct shrinker mmu_shrinker = {
5997 .count_objects = mmu_shrink_count,
5998 .scan_objects = mmu_shrink_scan,
5999 .seeks = DEFAULT_SEEKS * 10,
6002 static void mmu_destroy_caches(void)
6004 kmem_cache_destroy(pte_list_desc_cache);
6005 kmem_cache_destroy(mmu_page_header_cache);
6008 int kvm_mmu_module_init(void)
6013 * MMU roles use union aliasing which is, generally speaking, an
6014 * undefined behavior. However, we supposedly know how compilers behave
6015 * and the current status quo is unlikely to change. Guardians below are
6016 * supposed to let us know if the assumption becomes false.
6018 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6019 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6020 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6022 kvm_mmu_reset_all_pte_masks();
6024 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6025 sizeof(struct pte_list_desc),
6026 0, SLAB_ACCOUNT, NULL);
6027 if (!pte_list_desc_cache)
6030 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6031 sizeof(struct kvm_mmu_page),
6032 0, SLAB_ACCOUNT, NULL);
6033 if (!mmu_page_header_cache)
6036 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6039 ret = register_shrinker(&mmu_shrinker);
6046 mmu_destroy_caches();
6051 * Calculate mmu pages needed for kvm.
6053 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
6055 unsigned int nr_mmu_pages;
6056 unsigned int nr_pages = 0;
6057 struct kvm_memslots *slots;
6058 struct kvm_memory_slot *memslot;
6061 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6062 slots = __kvm_memslots(kvm, i);
6064 kvm_for_each_memslot(memslot, slots)
6065 nr_pages += memslot->npages;
6068 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6069 nr_mmu_pages = max(nr_mmu_pages,
6070 (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
6072 return nr_mmu_pages;
6075 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6077 kvm_mmu_unload(vcpu);
6078 free_mmu_pages(vcpu);
6079 mmu_free_memory_caches(vcpu);
6082 void kvm_mmu_module_exit(void)
6084 mmu_destroy_caches();
6085 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6086 unregister_shrinker(&mmu_shrinker);
6087 mmu_audit_disable();