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/module.h>
33 #include <linux/swap.h>
34 #include <linux/hugetlb.h>
35 #include <linux/compiler.h>
36 #include <linux/srcu.h>
37 #include <linux/slab.h>
38 #include <linux/uaccess.h>
41 #include <asm/cmpxchg.h>
46 * When setting this variable to true it enables Two-Dimensional-Paging
47 * where the hardware walks 2 page tables:
48 * 1. the guest-virtual to guest-physical
49 * 2. while doing 1. it walks guest-physical to host-physical
50 * If the hardware supports that we don't need to do shadow paging.
52 bool tdp_enabled = false;
56 AUDIT_POST_PAGE_FAULT,
67 module_param(dbg, bool, 0644);
69 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
70 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
71 #define MMU_WARN_ON(x) WARN_ON(x)
73 #define pgprintk(x...) do { } while (0)
74 #define rmap_printk(x...) do { } while (0)
75 #define MMU_WARN_ON(x) do { } while (0)
78 #define PTE_PREFETCH_NUM 8
80 #define PT_FIRST_AVAIL_BITS_SHIFT 10
81 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
83 #define PT64_LEVEL_BITS 9
85 #define PT64_LEVEL_SHIFT(level) \
86 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
88 #define PT64_INDEX(address, level)\
89 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
92 #define PT32_LEVEL_BITS 10
94 #define PT32_LEVEL_SHIFT(level) \
95 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
97 #define PT32_LVL_OFFSET_MASK(level) \
98 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
99 * PT32_LEVEL_BITS))) - 1))
101 #define PT32_INDEX(address, level)\
102 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
105 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
106 #define PT64_DIR_BASE_ADDR_MASK \
107 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
108 #define PT64_LVL_ADDR_MASK(level) \
109 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
110 * PT64_LEVEL_BITS))) - 1))
111 #define PT64_LVL_OFFSET_MASK(level) \
112 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
113 * PT64_LEVEL_BITS))) - 1))
115 #define PT32_BASE_ADDR_MASK PAGE_MASK
116 #define PT32_DIR_BASE_ADDR_MASK \
117 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
118 #define PT32_LVL_ADDR_MASK(level) \
119 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
120 * PT32_LEVEL_BITS))) - 1))
122 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
123 | shadow_x_mask | shadow_nx_mask)
125 #define ACC_EXEC_MASK 1
126 #define ACC_WRITE_MASK PT_WRITABLE_MASK
127 #define ACC_USER_MASK PT_USER_MASK
128 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
130 #include <trace/events/kvm.h>
132 #define CREATE_TRACE_POINTS
133 #include "mmutrace.h"
135 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
136 #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
138 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
140 /* make pte_list_desc fit well in cache line */
141 #define PTE_LIST_EXT 3
143 struct pte_list_desc {
144 u64 *sptes[PTE_LIST_EXT];
145 struct pte_list_desc *more;
148 struct kvm_shadow_walk_iterator {
156 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
157 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
158 shadow_walk_okay(&(_walker)); \
159 shadow_walk_next(&(_walker)))
161 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
162 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
163 shadow_walk_okay(&(_walker)) && \
164 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
165 __shadow_walk_next(&(_walker), spte))
167 static struct kmem_cache *pte_list_desc_cache;
168 static struct kmem_cache *mmu_page_header_cache;
169 static struct percpu_counter kvm_total_used_mmu_pages;
171 static u64 __read_mostly shadow_nx_mask;
172 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
173 static u64 __read_mostly shadow_user_mask;
174 static u64 __read_mostly shadow_accessed_mask;
175 static u64 __read_mostly shadow_dirty_mask;
176 static u64 __read_mostly shadow_mmio_mask;
178 static void mmu_spte_set(u64 *sptep, u64 spte);
179 static void mmu_free_roots(struct kvm_vcpu *vcpu);
181 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask)
183 shadow_mmio_mask = mmio_mask;
185 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
188 * the low bit of the generation number is always presumed to be zero.
189 * This disables mmio caching during memslot updates. The concept is
190 * similar to a seqcount but instead of retrying the access we just punt
191 * and ignore the cache.
193 * spte bits 3-11 are used as bits 1-9 of the generation number,
194 * the bits 52-61 are used as bits 10-19 of the generation number.
196 #define MMIO_SPTE_GEN_LOW_SHIFT 2
197 #define MMIO_SPTE_GEN_HIGH_SHIFT 52
199 #define MMIO_GEN_SHIFT 20
200 #define MMIO_GEN_LOW_SHIFT 10
201 #define MMIO_GEN_LOW_MASK ((1 << MMIO_GEN_LOW_SHIFT) - 2)
202 #define MMIO_GEN_MASK ((1 << MMIO_GEN_SHIFT) - 1)
204 static u64 generation_mmio_spte_mask(unsigned int gen)
208 WARN_ON(gen & ~MMIO_GEN_MASK);
210 mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
211 mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
215 static unsigned int get_mmio_spte_generation(u64 spte)
219 spte &= ~shadow_mmio_mask;
221 gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
222 gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
226 static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
228 return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
231 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
234 unsigned int gen = kvm_current_mmio_generation(vcpu);
235 u64 mask = generation_mmio_spte_mask(gen);
237 access &= ACC_WRITE_MASK | ACC_USER_MASK;
238 mask |= shadow_mmio_mask | access | gfn << PAGE_SHIFT;
240 trace_mark_mmio_spte(sptep, gfn, access, gen);
241 mmu_spte_set(sptep, mask);
244 static bool is_mmio_spte(u64 spte)
246 return (spte & shadow_mmio_mask) == shadow_mmio_mask;
249 static gfn_t get_mmio_spte_gfn(u64 spte)
251 u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
252 return (spte & ~mask) >> PAGE_SHIFT;
255 static unsigned get_mmio_spte_access(u64 spte)
257 u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
258 return (spte & ~mask) & ~PAGE_MASK;
261 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
262 kvm_pfn_t pfn, unsigned access)
264 if (unlikely(is_noslot_pfn(pfn))) {
265 mark_mmio_spte(vcpu, sptep, gfn, access);
272 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
274 unsigned int kvm_gen, spte_gen;
276 kvm_gen = kvm_current_mmio_generation(vcpu);
277 spte_gen = get_mmio_spte_generation(spte);
279 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
280 return likely(kvm_gen == spte_gen);
283 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
284 u64 dirty_mask, u64 nx_mask, u64 x_mask)
286 shadow_user_mask = user_mask;
287 shadow_accessed_mask = accessed_mask;
288 shadow_dirty_mask = dirty_mask;
289 shadow_nx_mask = nx_mask;
290 shadow_x_mask = x_mask;
292 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
294 static int is_cpuid_PSE36(void)
299 static int is_nx(struct kvm_vcpu *vcpu)
301 return vcpu->arch.efer & EFER_NX;
304 static int is_shadow_present_pte(u64 pte)
306 return pte & PT_PRESENT_MASK && !is_mmio_spte(pte);
309 static int is_large_pte(u64 pte)
311 return pte & PT_PAGE_SIZE_MASK;
314 static int is_last_spte(u64 pte, int level)
316 if (level == PT_PAGE_TABLE_LEVEL)
318 if (is_large_pte(pte))
323 static kvm_pfn_t spte_to_pfn(u64 pte)
325 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
328 static gfn_t pse36_gfn_delta(u32 gpte)
330 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
332 return (gpte & PT32_DIR_PSE36_MASK) << shift;
336 static void __set_spte(u64 *sptep, u64 spte)
341 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
346 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
348 return xchg(sptep, spte);
351 static u64 __get_spte_lockless(u64 *sptep)
353 return ACCESS_ONCE(*sptep);
364 static void count_spte_clear(u64 *sptep, u64 spte)
366 struct kvm_mmu_page *sp = page_header(__pa(sptep));
368 if (is_shadow_present_pte(spte))
371 /* Ensure the spte is completely set before we increase the count */
373 sp->clear_spte_count++;
376 static void __set_spte(u64 *sptep, u64 spte)
378 union split_spte *ssptep, sspte;
380 ssptep = (union split_spte *)sptep;
381 sspte = (union split_spte)spte;
383 ssptep->spte_high = sspte.spte_high;
386 * If we map the spte from nonpresent to present, We should store
387 * the high bits firstly, then set present bit, so cpu can not
388 * fetch this spte while we are setting the spte.
392 ssptep->spte_low = sspte.spte_low;
395 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
397 union split_spte *ssptep, sspte;
399 ssptep = (union split_spte *)sptep;
400 sspte = (union split_spte)spte;
402 ssptep->spte_low = sspte.spte_low;
405 * If we map the spte from present to nonpresent, we should clear
406 * present bit firstly to avoid vcpu fetch the old high bits.
410 ssptep->spte_high = sspte.spte_high;
411 count_spte_clear(sptep, spte);
414 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
416 union split_spte *ssptep, sspte, orig;
418 ssptep = (union split_spte *)sptep;
419 sspte = (union split_spte)spte;
421 /* xchg acts as a barrier before the setting of the high bits */
422 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
423 orig.spte_high = ssptep->spte_high;
424 ssptep->spte_high = sspte.spte_high;
425 count_spte_clear(sptep, spte);
431 * The idea using the light way get the spte on x86_32 guest is from
432 * gup_get_pte(arch/x86/mm/gup.c).
434 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
435 * coalesces them and we are running out of the MMU lock. Therefore
436 * we need to protect against in-progress updates of the spte.
438 * Reading the spte while an update is in progress may get the old value
439 * for the high part of the spte. The race is fine for a present->non-present
440 * change (because the high part of the spte is ignored for non-present spte),
441 * but for a present->present change we must reread the spte.
443 * All such changes are done in two steps (present->non-present and
444 * non-present->present), hence it is enough to count the number of
445 * present->non-present updates: if it changed while reading the spte,
446 * we might have hit the race. This is done using clear_spte_count.
448 static u64 __get_spte_lockless(u64 *sptep)
450 struct kvm_mmu_page *sp = page_header(__pa(sptep));
451 union split_spte spte, *orig = (union split_spte *)sptep;
455 count = sp->clear_spte_count;
458 spte.spte_low = orig->spte_low;
461 spte.spte_high = orig->spte_high;
464 if (unlikely(spte.spte_low != orig->spte_low ||
465 count != sp->clear_spte_count))
472 static bool spte_is_locklessly_modifiable(u64 spte)
474 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
475 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
478 static bool spte_has_volatile_bits(u64 spte)
481 * Always atomically update spte if it can be updated
482 * out of mmu-lock, it can ensure dirty bit is not lost,
483 * also, it can help us to get a stable is_writable_pte()
484 * to ensure tlb flush is not missed.
486 if (spte_is_locklessly_modifiable(spte))
489 if (!shadow_accessed_mask)
492 if (!is_shadow_present_pte(spte))
495 if ((spte & shadow_accessed_mask) &&
496 (!is_writable_pte(spte) || (spte & shadow_dirty_mask)))
502 static bool spte_is_bit_cleared(u64 old_spte, u64 new_spte, u64 bit_mask)
504 return (old_spte & bit_mask) && !(new_spte & bit_mask);
507 static bool spte_is_bit_changed(u64 old_spte, u64 new_spte, u64 bit_mask)
509 return (old_spte & bit_mask) != (new_spte & bit_mask);
512 /* Rules for using mmu_spte_set:
513 * Set the sptep from nonpresent to present.
514 * Note: the sptep being assigned *must* be either not present
515 * or in a state where the hardware will not attempt to update
518 static void mmu_spte_set(u64 *sptep, u64 new_spte)
520 WARN_ON(is_shadow_present_pte(*sptep));
521 __set_spte(sptep, new_spte);
524 /* Rules for using mmu_spte_update:
525 * Update the state bits, it means the mapped pfn is not changged.
527 * Whenever we overwrite a writable spte with a read-only one we
528 * should flush remote TLBs. Otherwise rmap_write_protect
529 * will find a read-only spte, even though the writable spte
530 * might be cached on a CPU's TLB, the return value indicates this
533 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
535 u64 old_spte = *sptep;
538 WARN_ON(!is_shadow_present_pte(new_spte));
540 if (!is_shadow_present_pte(old_spte)) {
541 mmu_spte_set(sptep, new_spte);
545 if (!spte_has_volatile_bits(old_spte))
546 __update_clear_spte_fast(sptep, new_spte);
548 old_spte = __update_clear_spte_slow(sptep, new_spte);
551 * For the spte updated out of mmu-lock is safe, since
552 * we always atomically update it, see the comments in
553 * spte_has_volatile_bits().
555 if (spte_is_locklessly_modifiable(old_spte) &&
556 !is_writable_pte(new_spte))
559 if (!shadow_accessed_mask)
563 * Flush TLB when accessed/dirty bits are changed in the page tables,
564 * to guarantee consistency between TLB and page tables.
566 if (spte_is_bit_changed(old_spte, new_spte,
567 shadow_accessed_mask | shadow_dirty_mask))
570 if (spte_is_bit_cleared(old_spte, new_spte, shadow_accessed_mask))
571 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
572 if (spte_is_bit_cleared(old_spte, new_spte, shadow_dirty_mask))
573 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
579 * Rules for using mmu_spte_clear_track_bits:
580 * It sets the sptep from present to nonpresent, and track the
581 * state bits, it is used to clear the last level sptep.
583 static int mmu_spte_clear_track_bits(u64 *sptep)
586 u64 old_spte = *sptep;
588 if (!spte_has_volatile_bits(old_spte))
589 __update_clear_spte_fast(sptep, 0ull);
591 old_spte = __update_clear_spte_slow(sptep, 0ull);
593 if (!is_shadow_present_pte(old_spte))
596 pfn = spte_to_pfn(old_spte);
599 * KVM does not hold the refcount of the page used by
600 * kvm mmu, before reclaiming the page, we should
601 * unmap it from mmu first.
603 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
605 if (!shadow_accessed_mask || old_spte & shadow_accessed_mask)
606 kvm_set_pfn_accessed(pfn);
607 if (!shadow_dirty_mask || (old_spte & shadow_dirty_mask))
608 kvm_set_pfn_dirty(pfn);
613 * Rules for using mmu_spte_clear_no_track:
614 * Directly clear spte without caring the state bits of sptep,
615 * it is used to set the upper level spte.
617 static void mmu_spte_clear_no_track(u64 *sptep)
619 __update_clear_spte_fast(sptep, 0ull);
622 static u64 mmu_spte_get_lockless(u64 *sptep)
624 return __get_spte_lockless(sptep);
627 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
630 * Prevent page table teardown by making any free-er wait during
631 * kvm_flush_remote_tlbs() IPI to all active vcpus.
634 vcpu->mode = READING_SHADOW_PAGE_TABLES;
636 * Make sure a following spte read is not reordered ahead of the write
642 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
645 * Make sure the write to vcpu->mode is not reordered in front of
646 * reads to sptes. If it does, kvm_commit_zap_page() can see us
647 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
650 vcpu->mode = OUTSIDE_GUEST_MODE;
654 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
655 struct kmem_cache *base_cache, int min)
659 if (cache->nobjs >= min)
661 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
662 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
665 cache->objects[cache->nobjs++] = obj;
670 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
675 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
676 struct kmem_cache *cache)
679 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
682 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
687 if (cache->nobjs >= min)
689 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
690 page = (void *)__get_free_page(GFP_KERNEL);
693 cache->objects[cache->nobjs++] = page;
698 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
701 free_page((unsigned long)mc->objects[--mc->nobjs]);
704 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
708 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
709 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
712 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
715 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
716 mmu_page_header_cache, 4);
721 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
723 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
724 pte_list_desc_cache);
725 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
726 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
727 mmu_page_header_cache);
730 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
735 p = mc->objects[--mc->nobjs];
739 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
741 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
744 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
746 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
749 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
751 if (!sp->role.direct)
752 return sp->gfns[index];
754 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
757 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
760 BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index));
762 sp->gfns[index] = gfn;
766 * Return the pointer to the large page information for a given gfn,
767 * handling slots that are not large page aligned.
769 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
770 struct kvm_memory_slot *slot,
775 idx = gfn_to_index(gfn, slot->base_gfn, level);
776 return &slot->arch.lpage_info[level - 2][idx];
779 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
781 struct kvm_memslots *slots;
782 struct kvm_memory_slot *slot;
783 struct kvm_lpage_info *linfo;
788 slots = kvm_memslots_for_spte_role(kvm, sp->role);
789 slot = __gfn_to_memslot(slots, gfn);
790 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
791 linfo = lpage_info_slot(gfn, slot, i);
792 linfo->write_count += 1;
794 kvm->arch.indirect_shadow_pages++;
797 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
799 struct kvm_memslots *slots;
800 struct kvm_memory_slot *slot;
801 struct kvm_lpage_info *linfo;
806 slots = kvm_memslots_for_spte_role(kvm, sp->role);
807 slot = __gfn_to_memslot(slots, gfn);
808 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
809 linfo = lpage_info_slot(gfn, slot, i);
810 linfo->write_count -= 1;
811 WARN_ON(linfo->write_count < 0);
813 kvm->arch.indirect_shadow_pages--;
816 static int __has_wrprotected_page(gfn_t gfn, int level,
817 struct kvm_memory_slot *slot)
819 struct kvm_lpage_info *linfo;
822 linfo = lpage_info_slot(gfn, slot, level);
823 return linfo->write_count;
829 static int has_wrprotected_page(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
831 struct kvm_memory_slot *slot;
833 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
834 return __has_wrprotected_page(gfn, level, slot);
837 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
839 unsigned long page_size;
842 page_size = kvm_host_page_size(kvm, gfn);
844 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
845 if (page_size >= KVM_HPAGE_SIZE(i))
854 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
857 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
859 if (no_dirty_log && slot->dirty_bitmap)
865 static struct kvm_memory_slot *
866 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
869 struct kvm_memory_slot *slot;
871 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
872 if (!memslot_valid_for_gpte(slot, no_dirty_log))
878 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
879 bool *force_pt_level)
881 int host_level, level, max_level;
882 struct kvm_memory_slot *slot;
884 if (unlikely(*force_pt_level))
885 return PT_PAGE_TABLE_LEVEL;
887 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
888 *force_pt_level = !memslot_valid_for_gpte(slot, true);
889 if (unlikely(*force_pt_level))
890 return PT_PAGE_TABLE_LEVEL;
892 host_level = host_mapping_level(vcpu->kvm, large_gfn);
894 if (host_level == PT_PAGE_TABLE_LEVEL)
897 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
899 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
900 if (__has_wrprotected_page(large_gfn, level, slot))
907 * About rmap_head encoding:
909 * If the bit zero of rmap_head->val is clear, then it points to the only spte
910 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
911 * pte_list_desc containing more mappings.
915 * Returns the number of pointers in the rmap chain, not counting the new one.
917 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
918 struct kvm_rmap_head *rmap_head)
920 struct pte_list_desc *desc;
923 if (!rmap_head->val) {
924 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
925 rmap_head->val = (unsigned long)spte;
926 } else if (!(rmap_head->val & 1)) {
927 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
928 desc = mmu_alloc_pte_list_desc(vcpu);
929 desc->sptes[0] = (u64 *)rmap_head->val;
930 desc->sptes[1] = spte;
931 rmap_head->val = (unsigned long)desc | 1;
934 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
935 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
936 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
938 count += PTE_LIST_EXT;
940 if (desc->sptes[PTE_LIST_EXT-1]) {
941 desc->more = mmu_alloc_pte_list_desc(vcpu);
944 for (i = 0; desc->sptes[i]; ++i)
946 desc->sptes[i] = spte;
952 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
953 struct pte_list_desc *desc, int i,
954 struct pte_list_desc *prev_desc)
958 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
960 desc->sptes[i] = desc->sptes[j];
961 desc->sptes[j] = NULL;
964 if (!prev_desc && !desc->more)
965 rmap_head->val = (unsigned long)desc->sptes[0];
968 prev_desc->more = desc->more;
970 rmap_head->val = (unsigned long)desc->more | 1;
971 mmu_free_pte_list_desc(desc);
974 static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
976 struct pte_list_desc *desc;
977 struct pte_list_desc *prev_desc;
980 if (!rmap_head->val) {
981 printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
983 } else if (!(rmap_head->val & 1)) {
984 rmap_printk("pte_list_remove: %p 1->0\n", spte);
985 if ((u64 *)rmap_head->val != spte) {
986 printk(KERN_ERR "pte_list_remove: %p 1->BUG\n", spte);
991 rmap_printk("pte_list_remove: %p many->many\n", spte);
992 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
995 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
996 if (desc->sptes[i] == spte) {
997 pte_list_desc_remove_entry(rmap_head,
1005 pr_err("pte_list_remove: %p many->many\n", spte);
1010 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1011 struct kvm_memory_slot *slot)
1015 idx = gfn_to_index(gfn, slot->base_gfn, level);
1016 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1019 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1020 struct kvm_mmu_page *sp)
1022 struct kvm_memslots *slots;
1023 struct kvm_memory_slot *slot;
1025 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1026 slot = __gfn_to_memslot(slots, gfn);
1027 return __gfn_to_rmap(gfn, sp->role.level, slot);
1030 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1032 struct kvm_mmu_memory_cache *cache;
1034 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1035 return mmu_memory_cache_free_objects(cache);
1038 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1040 struct kvm_mmu_page *sp;
1041 struct kvm_rmap_head *rmap_head;
1043 sp = page_header(__pa(spte));
1044 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1045 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1046 return pte_list_add(vcpu, spte, rmap_head);
1049 static void rmap_remove(struct kvm *kvm, u64 *spte)
1051 struct kvm_mmu_page *sp;
1053 struct kvm_rmap_head *rmap_head;
1055 sp = page_header(__pa(spte));
1056 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1057 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1058 pte_list_remove(spte, rmap_head);
1062 * Used by the following functions to iterate through the sptes linked by a
1063 * rmap. All fields are private and not assumed to be used outside.
1065 struct rmap_iterator {
1066 /* private fields */
1067 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1068 int pos; /* index of the sptep */
1072 * Iteration must be started by this function. This should also be used after
1073 * removing/dropping sptes from the rmap link because in such cases the
1074 * information in the itererator may not be valid.
1076 * Returns sptep if found, NULL otherwise.
1078 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1079 struct rmap_iterator *iter)
1083 if (!rmap_head->val)
1086 if (!(rmap_head->val & 1)) {
1088 sptep = (u64 *)rmap_head->val;
1092 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1094 sptep = iter->desc->sptes[iter->pos];
1096 BUG_ON(!is_shadow_present_pte(*sptep));
1101 * Must be used with a valid iterator: e.g. after rmap_get_first().
1103 * Returns sptep if found, NULL otherwise.
1105 static u64 *rmap_get_next(struct rmap_iterator *iter)
1110 if (iter->pos < PTE_LIST_EXT - 1) {
1112 sptep = iter->desc->sptes[iter->pos];
1117 iter->desc = iter->desc->more;
1121 /* desc->sptes[0] cannot be NULL */
1122 sptep = iter->desc->sptes[iter->pos];
1129 BUG_ON(!is_shadow_present_pte(*sptep));
1133 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1134 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1135 _spte_; _spte_ = rmap_get_next(_iter_))
1137 static void drop_spte(struct kvm *kvm, u64 *sptep)
1139 if (mmu_spte_clear_track_bits(sptep))
1140 rmap_remove(kvm, sptep);
1144 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1146 if (is_large_pte(*sptep)) {
1147 WARN_ON(page_header(__pa(sptep))->role.level ==
1148 PT_PAGE_TABLE_LEVEL);
1149 drop_spte(kvm, sptep);
1157 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1159 if (__drop_large_spte(vcpu->kvm, sptep))
1160 kvm_flush_remote_tlbs(vcpu->kvm);
1164 * Write-protect on the specified @sptep, @pt_protect indicates whether
1165 * spte write-protection is caused by protecting shadow page table.
1167 * Note: write protection is difference between dirty logging and spte
1169 * - for dirty logging, the spte can be set to writable at anytime if
1170 * its dirty bitmap is properly set.
1171 * - for spte protection, the spte can be writable only after unsync-ing
1174 * Return true if tlb need be flushed.
1176 static bool spte_write_protect(struct kvm *kvm, u64 *sptep, bool pt_protect)
1180 if (!is_writable_pte(spte) &&
1181 !(pt_protect && spte_is_locklessly_modifiable(spte)))
1184 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1187 spte &= ~SPTE_MMU_WRITEABLE;
1188 spte = spte & ~PT_WRITABLE_MASK;
1190 return mmu_spte_update(sptep, spte);
1193 static bool __rmap_write_protect(struct kvm *kvm,
1194 struct kvm_rmap_head *rmap_head,
1198 struct rmap_iterator iter;
1201 for_each_rmap_spte(rmap_head, &iter, sptep)
1202 flush |= spte_write_protect(kvm, sptep, pt_protect);
1207 static bool spte_clear_dirty(struct kvm *kvm, u64 *sptep)
1211 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1213 spte &= ~shadow_dirty_mask;
1215 return mmu_spte_update(sptep, spte);
1218 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1221 struct rmap_iterator iter;
1224 for_each_rmap_spte(rmap_head, &iter, sptep)
1225 flush |= spte_clear_dirty(kvm, sptep);
1230 static bool spte_set_dirty(struct kvm *kvm, u64 *sptep)
1234 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1236 spte |= shadow_dirty_mask;
1238 return mmu_spte_update(sptep, spte);
1241 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1244 struct rmap_iterator iter;
1247 for_each_rmap_spte(rmap_head, &iter, sptep)
1248 flush |= spte_set_dirty(kvm, sptep);
1254 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1255 * @kvm: kvm instance
1256 * @slot: slot to protect
1257 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1258 * @mask: indicates which pages we should protect
1260 * Used when we do not need to care about huge page mappings: e.g. during dirty
1261 * logging we do not have any such mappings.
1263 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1264 struct kvm_memory_slot *slot,
1265 gfn_t gfn_offset, unsigned long mask)
1267 struct kvm_rmap_head *rmap_head;
1270 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1271 PT_PAGE_TABLE_LEVEL, slot);
1272 __rmap_write_protect(kvm, rmap_head, false);
1274 /* clear the first set bit */
1280 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages
1281 * @kvm: kvm instance
1282 * @slot: slot to clear D-bit
1283 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1284 * @mask: indicates which pages we should clear D-bit
1286 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1288 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1289 struct kvm_memory_slot *slot,
1290 gfn_t gfn_offset, unsigned long mask)
1292 struct kvm_rmap_head *rmap_head;
1295 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1296 PT_PAGE_TABLE_LEVEL, slot);
1297 __rmap_clear_dirty(kvm, rmap_head);
1299 /* clear the first set bit */
1303 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1306 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1309 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1310 * enable dirty logging for them.
1312 * Used when we do not need to care about huge page mappings: e.g. during dirty
1313 * logging we do not have any such mappings.
1315 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1316 struct kvm_memory_slot *slot,
1317 gfn_t gfn_offset, unsigned long mask)
1319 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1320 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1323 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1326 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1328 struct kvm_memory_slot *slot;
1329 struct kvm_rmap_head *rmap_head;
1331 bool write_protected = false;
1333 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1335 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1336 rmap_head = __gfn_to_rmap(gfn, i, slot);
1337 write_protected |= __rmap_write_protect(vcpu->kvm, rmap_head, true);
1340 return write_protected;
1343 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1346 struct rmap_iterator iter;
1349 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1350 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1352 drop_spte(kvm, sptep);
1359 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1360 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1363 return kvm_zap_rmapp(kvm, rmap_head);
1366 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1367 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1371 struct rmap_iterator iter;
1374 pte_t *ptep = (pte_t *)data;
1377 WARN_ON(pte_huge(*ptep));
1378 new_pfn = pte_pfn(*ptep);
1381 for_each_rmap_spte(rmap_head, &iter, sptep) {
1382 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1383 sptep, *sptep, gfn, level);
1387 if (pte_write(*ptep)) {
1388 drop_spte(kvm, sptep);
1391 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1392 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1394 new_spte &= ~PT_WRITABLE_MASK;
1395 new_spte &= ~SPTE_HOST_WRITEABLE;
1396 new_spte &= ~shadow_accessed_mask;
1398 mmu_spte_clear_track_bits(sptep);
1399 mmu_spte_set(sptep, new_spte);
1404 kvm_flush_remote_tlbs(kvm);
1409 struct slot_rmap_walk_iterator {
1411 struct kvm_memory_slot *slot;
1417 /* output fields. */
1419 struct kvm_rmap_head *rmap;
1422 /* private field. */
1423 struct kvm_rmap_head *end_rmap;
1427 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1429 iterator->level = level;
1430 iterator->gfn = iterator->start_gfn;
1431 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1432 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1437 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1438 struct kvm_memory_slot *slot, int start_level,
1439 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1441 iterator->slot = slot;
1442 iterator->start_level = start_level;
1443 iterator->end_level = end_level;
1444 iterator->start_gfn = start_gfn;
1445 iterator->end_gfn = end_gfn;
1447 rmap_walk_init_level(iterator, iterator->start_level);
1450 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1452 return !!iterator->rmap;
1455 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1457 if (++iterator->rmap <= iterator->end_rmap) {
1458 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1462 if (++iterator->level > iterator->end_level) {
1463 iterator->rmap = NULL;
1467 rmap_walk_init_level(iterator, iterator->level);
1470 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1471 _start_gfn, _end_gfn, _iter_) \
1472 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1473 _end_level_, _start_gfn, _end_gfn); \
1474 slot_rmap_walk_okay(_iter_); \
1475 slot_rmap_walk_next(_iter_))
1477 static int kvm_handle_hva_range(struct kvm *kvm,
1478 unsigned long start,
1481 int (*handler)(struct kvm *kvm,
1482 struct kvm_rmap_head *rmap_head,
1483 struct kvm_memory_slot *slot,
1486 unsigned long data))
1488 struct kvm_memslots *slots;
1489 struct kvm_memory_slot *memslot;
1490 struct slot_rmap_walk_iterator iterator;
1494 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1495 slots = __kvm_memslots(kvm, i);
1496 kvm_for_each_memslot(memslot, slots) {
1497 unsigned long hva_start, hva_end;
1498 gfn_t gfn_start, gfn_end;
1500 hva_start = max(start, memslot->userspace_addr);
1501 hva_end = min(end, memslot->userspace_addr +
1502 (memslot->npages << PAGE_SHIFT));
1503 if (hva_start >= hva_end)
1506 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1507 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1509 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1510 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1512 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1513 PT_MAX_HUGEPAGE_LEVEL,
1514 gfn_start, gfn_end - 1,
1516 ret |= handler(kvm, iterator.rmap, memslot,
1517 iterator.gfn, iterator.level, data);
1524 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1526 int (*handler)(struct kvm *kvm,
1527 struct kvm_rmap_head *rmap_head,
1528 struct kvm_memory_slot *slot,
1529 gfn_t gfn, int level,
1530 unsigned long data))
1532 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1535 int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
1537 return kvm_handle_hva(kvm, hva, 0, kvm_unmap_rmapp);
1540 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1542 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1545 void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1547 kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1550 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1551 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1555 struct rmap_iterator uninitialized_var(iter);
1558 BUG_ON(!shadow_accessed_mask);
1560 for_each_rmap_spte(rmap_head, &iter, sptep) {
1561 if (*sptep & shadow_accessed_mask) {
1563 clear_bit((ffs(shadow_accessed_mask) - 1),
1564 (unsigned long *)sptep);
1568 trace_kvm_age_page(gfn, level, slot, young);
1572 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1573 struct kvm_memory_slot *slot, gfn_t gfn,
1574 int level, unsigned long data)
1577 struct rmap_iterator iter;
1581 * If there's no access bit in the secondary pte set by the
1582 * hardware it's up to gup-fast/gup to set the access bit in
1583 * the primary pte or in the page structure.
1585 if (!shadow_accessed_mask)
1588 for_each_rmap_spte(rmap_head, &iter, sptep) {
1589 if (*sptep & shadow_accessed_mask) {
1598 #define RMAP_RECYCLE_THRESHOLD 1000
1600 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1602 struct kvm_rmap_head *rmap_head;
1603 struct kvm_mmu_page *sp;
1605 sp = page_header(__pa(spte));
1607 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1609 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1610 kvm_flush_remote_tlbs(vcpu->kvm);
1613 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1616 * In case of absence of EPT Access and Dirty Bits supports,
1617 * emulate the accessed bit for EPT, by checking if this page has
1618 * an EPT mapping, and clearing it if it does. On the next access,
1619 * a new EPT mapping will be established.
1620 * This has some overhead, but not as much as the cost of swapping
1621 * out actively used pages or breaking up actively used hugepages.
1623 if (!shadow_accessed_mask) {
1625 * We are holding the kvm->mmu_lock, and we are blowing up
1626 * shadow PTEs. MMU notifier consumers need to be kept at bay.
1627 * This is correct as long as we don't decouple the mmu_lock
1628 * protected regions (like invalidate_range_start|end does).
1630 kvm->mmu_notifier_seq++;
1631 return kvm_handle_hva_range(kvm, start, end, 0,
1635 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
1638 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1640 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1644 static int is_empty_shadow_page(u64 *spt)
1649 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1650 if (is_shadow_present_pte(*pos)) {
1651 printk(KERN_ERR "%s: %p %llx\n", __func__,
1660 * This value is the sum of all of the kvm instances's
1661 * kvm->arch.n_used_mmu_pages values. We need a global,
1662 * aggregate version in order to make the slab shrinker
1665 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
1667 kvm->arch.n_used_mmu_pages += nr;
1668 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1671 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
1673 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1674 hlist_del(&sp->hash_link);
1675 list_del(&sp->link);
1676 free_page((unsigned long)sp->spt);
1677 if (!sp->role.direct)
1678 free_page((unsigned long)sp->gfns);
1679 kmem_cache_free(mmu_page_header_cache, sp);
1682 static unsigned kvm_page_table_hashfn(gfn_t gfn)
1684 return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
1687 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
1688 struct kvm_mmu_page *sp, u64 *parent_pte)
1693 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
1696 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1699 pte_list_remove(parent_pte, &sp->parent_ptes);
1702 static void drop_parent_pte(struct kvm_mmu_page *sp,
1705 mmu_page_remove_parent_pte(sp, parent_pte);
1706 mmu_spte_clear_no_track(parent_pte);
1709 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
1711 struct kvm_mmu_page *sp;
1713 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
1714 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
1716 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
1717 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
1720 * The active_mmu_pages list is the FIFO list, do not move the
1721 * page until it is zapped. kvm_zap_obsolete_pages depends on
1722 * this feature. See the comments in kvm_zap_obsolete_pages().
1724 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
1725 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
1729 static void mark_unsync(u64 *spte);
1730 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1733 struct rmap_iterator iter;
1735 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1740 static void mark_unsync(u64 *spte)
1742 struct kvm_mmu_page *sp;
1745 sp = page_header(__pa(spte));
1746 index = spte - sp->spt;
1747 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
1749 if (sp->unsync_children++)
1751 kvm_mmu_mark_parents_unsync(sp);
1754 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1755 struct kvm_mmu_page *sp)
1760 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
1764 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
1765 struct kvm_mmu_page *sp, u64 *spte,
1771 #define KVM_PAGE_ARRAY_NR 16
1773 struct kvm_mmu_pages {
1774 struct mmu_page_and_offset {
1775 struct kvm_mmu_page *sp;
1777 } page[KVM_PAGE_ARRAY_NR];
1781 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1787 for (i=0; i < pvec->nr; i++)
1788 if (pvec->page[i].sp == sp)
1791 pvec->page[pvec->nr].sp = sp;
1792 pvec->page[pvec->nr].idx = idx;
1794 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1797 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1799 --sp->unsync_children;
1800 WARN_ON((int)sp->unsync_children < 0);
1801 __clear_bit(idx, sp->unsync_child_bitmap);
1804 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1805 struct kvm_mmu_pages *pvec)
1807 int i, ret, nr_unsync_leaf = 0;
1809 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1810 struct kvm_mmu_page *child;
1811 u64 ent = sp->spt[i];
1813 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1814 clear_unsync_child_bit(sp, i);
1818 child = page_header(ent & PT64_BASE_ADDR_MASK);
1820 if (child->unsync_children) {
1821 if (mmu_pages_add(pvec, child, i))
1824 ret = __mmu_unsync_walk(child, pvec);
1826 clear_unsync_child_bit(sp, i);
1828 } else if (ret > 0) {
1829 nr_unsync_leaf += ret;
1832 } else if (child->unsync) {
1834 if (mmu_pages_add(pvec, child, i))
1837 clear_unsync_child_bit(sp, i);
1840 return nr_unsync_leaf;
1843 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1844 struct kvm_mmu_pages *pvec)
1846 if (!sp->unsync_children)
1849 mmu_pages_add(pvec, sp, 0);
1850 return __mmu_unsync_walk(sp, pvec);
1853 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1855 WARN_ON(!sp->unsync);
1856 trace_kvm_mmu_sync_page(sp);
1858 --kvm->stat.mmu_unsync;
1861 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1862 struct list_head *invalid_list);
1863 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1864 struct list_head *invalid_list);
1867 * NOTE: we should pay more attention on the zapped-obsolete page
1868 * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
1869 * since it has been deleted from active_mmu_pages but still can be found
1872 * for_each_gfn_indirect_valid_sp has skipped that kind of page and
1873 * kvm_mmu_get_page(), the only user of for_each_gfn_sp(), has skipped
1874 * all the obsolete pages.
1876 #define for_each_gfn_sp(_kvm, _sp, _gfn) \
1877 hlist_for_each_entry(_sp, \
1878 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
1879 if ((_sp)->gfn != (_gfn)) {} else
1881 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
1882 for_each_gfn_sp(_kvm, _sp, _gfn) \
1883 if ((_sp)->role.direct || (_sp)->role.invalid) {} else
1885 /* @sp->gfn should be write-protected at the call site */
1886 static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1887 struct list_head *invalid_list, bool clear_unsync)
1889 if (sp->role.cr4_pae != !!is_pae(vcpu)) {
1890 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1895 kvm_unlink_unsync_page(vcpu->kvm, sp);
1897 if (vcpu->arch.mmu.sync_page(vcpu, sp)) {
1898 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1902 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1906 static int kvm_sync_page_transient(struct kvm_vcpu *vcpu,
1907 struct kvm_mmu_page *sp)
1909 LIST_HEAD(invalid_list);
1912 ret = __kvm_sync_page(vcpu, sp, &invalid_list, false);
1914 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
1919 #ifdef CONFIG_KVM_MMU_AUDIT
1920 #include "mmu_audit.c"
1922 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
1923 static void mmu_audit_disable(void) { }
1926 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1927 struct list_head *invalid_list)
1929 return __kvm_sync_page(vcpu, sp, invalid_list, true);
1932 /* @gfn should be write-protected at the call site */
1933 static void kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn)
1935 struct kvm_mmu_page *s;
1936 LIST_HEAD(invalid_list);
1939 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
1943 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
1944 kvm_unlink_unsync_page(vcpu->kvm, s);
1945 if ((s->role.cr4_pae != !!is_pae(vcpu)) ||
1946 (vcpu->arch.mmu.sync_page(vcpu, s))) {
1947 kvm_mmu_prepare_zap_page(vcpu->kvm, s, &invalid_list);
1953 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
1955 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1958 struct mmu_page_path {
1959 struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1];
1960 unsigned int idx[PT64_ROOT_LEVEL-1];
1963 #define for_each_sp(pvec, sp, parents, i) \
1964 for (i = mmu_pages_next(&pvec, &parents, -1), \
1965 sp = pvec.page[i].sp; \
1966 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
1967 i = mmu_pages_next(&pvec, &parents, i))
1969 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1970 struct mmu_page_path *parents,
1975 for (n = i+1; n < pvec->nr; n++) {
1976 struct kvm_mmu_page *sp = pvec->page[n].sp;
1978 if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1979 parents->idx[0] = pvec->page[n].idx;
1983 parents->parent[sp->role.level-2] = sp;
1984 parents->idx[sp->role.level-1] = pvec->page[n].idx;
1990 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
1992 struct kvm_mmu_page *sp;
1993 unsigned int level = 0;
1996 unsigned int idx = parents->idx[level];
1998 sp = parents->parent[level];
2002 clear_unsync_child_bit(sp, idx);
2004 } while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children);
2007 static void kvm_mmu_pages_init(struct kvm_mmu_page *parent,
2008 struct mmu_page_path *parents,
2009 struct kvm_mmu_pages *pvec)
2011 parents->parent[parent->role.level-1] = NULL;
2015 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2016 struct kvm_mmu_page *parent)
2019 struct kvm_mmu_page *sp;
2020 struct mmu_page_path parents;
2021 struct kvm_mmu_pages pages;
2022 LIST_HEAD(invalid_list);
2024 kvm_mmu_pages_init(parent, &parents, &pages);
2025 while (mmu_unsync_walk(parent, &pages)) {
2026 bool protected = false;
2028 for_each_sp(pages, sp, parents, i)
2029 protected |= rmap_write_protect(vcpu, sp->gfn);
2032 kvm_flush_remote_tlbs(vcpu->kvm);
2034 for_each_sp(pages, sp, parents, i) {
2035 kvm_sync_page(vcpu, sp, &invalid_list);
2036 mmu_pages_clear_parents(&parents);
2038 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2039 cond_resched_lock(&vcpu->kvm->mmu_lock);
2040 kvm_mmu_pages_init(parent, &parents, &pages);
2044 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2046 sp->write_flooding_count = 0;
2049 static void clear_sp_write_flooding_count(u64 *spte)
2051 struct kvm_mmu_page *sp = page_header(__pa(spte));
2053 __clear_sp_write_flooding_count(sp);
2056 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2058 return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2061 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2068 union kvm_mmu_page_role role;
2070 struct kvm_mmu_page *sp;
2071 bool need_sync = false;
2073 role = vcpu->arch.mmu.base_role;
2075 role.direct = direct;
2078 role.access = access;
2079 if (!vcpu->arch.mmu.direct_map
2080 && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
2081 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2082 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2083 role.quadrant = quadrant;
2085 for_each_gfn_sp(vcpu->kvm, sp, gfn) {
2086 if (is_obsolete_sp(vcpu->kvm, sp))
2089 if (!need_sync && sp->unsync)
2092 if (sp->role.word != role.word)
2095 if (sp->unsync && kvm_sync_page_transient(vcpu, sp))
2098 if (sp->unsync_children)
2099 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2101 __clear_sp_write_flooding_count(sp);
2102 trace_kvm_mmu_get_page(sp, false);
2106 ++vcpu->kvm->stat.mmu_cache_miss;
2108 sp = kvm_mmu_alloc_page(vcpu, direct);
2112 hlist_add_head(&sp->hash_link,
2113 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2115 if (rmap_write_protect(vcpu, gfn))
2116 kvm_flush_remote_tlbs(vcpu->kvm);
2117 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2118 kvm_sync_pages(vcpu, gfn);
2120 account_shadowed(vcpu->kvm, sp);
2122 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2123 clear_page(sp->spt);
2124 trace_kvm_mmu_get_page(sp, true);
2128 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2129 struct kvm_vcpu *vcpu, u64 addr)
2131 iterator->addr = addr;
2132 iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
2133 iterator->level = vcpu->arch.mmu.shadow_root_level;
2135 if (iterator->level == PT64_ROOT_LEVEL &&
2136 vcpu->arch.mmu.root_level < PT64_ROOT_LEVEL &&
2137 !vcpu->arch.mmu.direct_map)
2140 if (iterator->level == PT32E_ROOT_LEVEL) {
2141 iterator->shadow_addr
2142 = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
2143 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2145 if (!iterator->shadow_addr)
2146 iterator->level = 0;
2150 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2152 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2155 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2156 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2160 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2163 if (is_last_spte(spte, iterator->level)) {
2164 iterator->level = 0;
2168 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2172 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2174 return __shadow_walk_next(iterator, *iterator->sptep);
2177 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2178 struct kvm_mmu_page *sp)
2182 BUILD_BUG_ON(VMX_EPT_READABLE_MASK != PT_PRESENT_MASK ||
2183 VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2185 spte = __pa(sp->spt) | PT_PRESENT_MASK | PT_WRITABLE_MASK |
2186 shadow_user_mask | shadow_x_mask | shadow_accessed_mask;
2188 mmu_spte_set(sptep, spte);
2190 mmu_page_add_parent_pte(vcpu, sp, sptep);
2192 if (sp->unsync_children || sp->unsync)
2196 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2197 unsigned direct_access)
2199 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2200 struct kvm_mmu_page *child;
2203 * For the direct sp, if the guest pte's dirty bit
2204 * changed form clean to dirty, it will corrupt the
2205 * sp's access: allow writable in the read-only sp,
2206 * so we should update the spte at this point to get
2207 * a new sp with the correct access.
2209 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2210 if (child->role.access == direct_access)
2213 drop_parent_pte(child, sptep);
2214 kvm_flush_remote_tlbs(vcpu->kvm);
2218 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2222 struct kvm_mmu_page *child;
2225 if (is_shadow_present_pte(pte)) {
2226 if (is_last_spte(pte, sp->role.level)) {
2227 drop_spte(kvm, spte);
2228 if (is_large_pte(pte))
2231 child = page_header(pte & PT64_BASE_ADDR_MASK);
2232 drop_parent_pte(child, spte);
2237 if (is_mmio_spte(pte))
2238 mmu_spte_clear_no_track(spte);
2243 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2244 struct kvm_mmu_page *sp)
2248 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2249 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2252 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2255 struct rmap_iterator iter;
2257 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2258 drop_parent_pte(sp, sptep);
2261 static int mmu_zap_unsync_children(struct kvm *kvm,
2262 struct kvm_mmu_page *parent,
2263 struct list_head *invalid_list)
2266 struct mmu_page_path parents;
2267 struct kvm_mmu_pages pages;
2269 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2272 kvm_mmu_pages_init(parent, &parents, &pages);
2273 while (mmu_unsync_walk(parent, &pages)) {
2274 struct kvm_mmu_page *sp;
2276 for_each_sp(pages, sp, parents, i) {
2277 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2278 mmu_pages_clear_parents(&parents);
2281 kvm_mmu_pages_init(parent, &parents, &pages);
2287 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2288 struct list_head *invalid_list)
2292 trace_kvm_mmu_prepare_zap_page(sp);
2293 ++kvm->stat.mmu_shadow_zapped;
2294 ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
2295 kvm_mmu_page_unlink_children(kvm, sp);
2296 kvm_mmu_unlink_parents(kvm, sp);
2298 if (!sp->role.invalid && !sp->role.direct)
2299 unaccount_shadowed(kvm, sp);
2302 kvm_unlink_unsync_page(kvm, sp);
2303 if (!sp->root_count) {
2306 list_move(&sp->link, invalid_list);
2307 kvm_mod_used_mmu_pages(kvm, -1);
2309 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2312 * The obsolete pages can not be used on any vcpus.
2313 * See the comments in kvm_mmu_invalidate_zap_all_pages().
2315 if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
2316 kvm_reload_remote_mmus(kvm);
2319 sp->role.invalid = 1;
2323 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2324 struct list_head *invalid_list)
2326 struct kvm_mmu_page *sp, *nsp;
2328 if (list_empty(invalid_list))
2332 * wmb: make sure everyone sees our modifications to the page tables
2333 * rmb: make sure we see changes to vcpu->mode
2338 * Wait for all vcpus to exit guest mode and/or lockless shadow
2341 kvm_flush_remote_tlbs(kvm);
2343 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2344 WARN_ON(!sp->role.invalid || sp->root_count);
2345 kvm_mmu_free_page(sp);
2349 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2350 struct list_head *invalid_list)
2352 struct kvm_mmu_page *sp;
2354 if (list_empty(&kvm->arch.active_mmu_pages))
2357 sp = list_entry(kvm->arch.active_mmu_pages.prev,
2358 struct kvm_mmu_page, link);
2359 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2365 * Changing the number of mmu pages allocated to the vm
2366 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2368 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
2370 LIST_HEAD(invalid_list);
2372 spin_lock(&kvm->mmu_lock);
2374 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2375 /* Need to free some mmu pages to achieve the goal. */
2376 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2377 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2380 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2381 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2384 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2386 spin_unlock(&kvm->mmu_lock);
2389 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2391 struct kvm_mmu_page *sp;
2392 LIST_HEAD(invalid_list);
2395 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2397 spin_lock(&kvm->mmu_lock);
2398 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2399 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2402 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2404 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2405 spin_unlock(&kvm->mmu_lock);
2409 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2411 static void __kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2413 trace_kvm_mmu_unsync_page(sp);
2414 ++vcpu->kvm->stat.mmu_unsync;
2417 kvm_mmu_mark_parents_unsync(sp);
2420 static void kvm_unsync_pages(struct kvm_vcpu *vcpu, gfn_t gfn)
2422 struct kvm_mmu_page *s;
2424 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2427 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2428 __kvm_unsync_page(vcpu, s);
2432 static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2435 struct kvm_mmu_page *s;
2436 bool need_unsync = false;
2438 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2442 if (s->role.level != PT_PAGE_TABLE_LEVEL)
2449 kvm_unsync_pages(vcpu, gfn);
2453 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2456 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn));
2461 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2462 unsigned pte_access, int level,
2463 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2464 bool can_unsync, bool host_writable)
2469 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2472 spte = PT_PRESENT_MASK;
2474 spte |= shadow_accessed_mask;
2476 if (pte_access & ACC_EXEC_MASK)
2477 spte |= shadow_x_mask;
2479 spte |= shadow_nx_mask;
2481 if (pte_access & ACC_USER_MASK)
2482 spte |= shadow_user_mask;
2484 if (level > PT_PAGE_TABLE_LEVEL)
2485 spte |= PT_PAGE_SIZE_MASK;
2487 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2488 kvm_is_mmio_pfn(pfn));
2491 spte |= SPTE_HOST_WRITEABLE;
2493 pte_access &= ~ACC_WRITE_MASK;
2495 spte |= (u64)pfn << PAGE_SHIFT;
2497 if (pte_access & ACC_WRITE_MASK) {
2500 * Other vcpu creates new sp in the window between
2501 * mapping_level() and acquiring mmu-lock. We can
2502 * allow guest to retry the access, the mapping can
2503 * be fixed if guest refault.
2505 if (level > PT_PAGE_TABLE_LEVEL &&
2506 has_wrprotected_page(vcpu, gfn, level))
2509 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
2512 * Optimization: for pte sync, if spte was writable the hash
2513 * lookup is unnecessary (and expensive). Write protection
2514 * is responsibility of mmu_get_page / kvm_sync_page.
2515 * Same reasoning can be applied to dirty page accounting.
2517 if (!can_unsync && is_writable_pte(*sptep))
2520 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
2521 pgprintk("%s: found shadow page for %llx, marking ro\n",
2524 pte_access &= ~ACC_WRITE_MASK;
2525 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
2529 if (pte_access & ACC_WRITE_MASK) {
2530 kvm_vcpu_mark_page_dirty(vcpu, gfn);
2531 spte |= shadow_dirty_mask;
2535 if (mmu_spte_update(sptep, spte))
2536 kvm_flush_remote_tlbs(vcpu->kvm);
2541 static bool mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
2542 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
2543 bool speculative, bool host_writable)
2545 int was_rmapped = 0;
2547 bool emulate = false;
2549 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2550 *sptep, write_fault, gfn);
2552 if (is_shadow_present_pte(*sptep)) {
2554 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2555 * the parent of the now unreachable PTE.
2557 if (level > PT_PAGE_TABLE_LEVEL &&
2558 !is_large_pte(*sptep)) {
2559 struct kvm_mmu_page *child;
2562 child = page_header(pte & PT64_BASE_ADDR_MASK);
2563 drop_parent_pte(child, sptep);
2564 kvm_flush_remote_tlbs(vcpu->kvm);
2565 } else if (pfn != spte_to_pfn(*sptep)) {
2566 pgprintk("hfn old %llx new %llx\n",
2567 spte_to_pfn(*sptep), pfn);
2568 drop_spte(vcpu->kvm, sptep);
2569 kvm_flush_remote_tlbs(vcpu->kvm);
2574 if (set_spte(vcpu, sptep, pte_access, level, gfn, pfn, speculative,
2575 true, host_writable)) {
2578 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2581 if (unlikely(is_mmio_spte(*sptep)))
2584 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2585 pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
2586 is_large_pte(*sptep)? "2MB" : "4kB",
2587 *sptep & PT_PRESENT_MASK ?"RW":"R", gfn,
2589 if (!was_rmapped && is_large_pte(*sptep))
2590 ++vcpu->kvm->stat.lpages;
2592 if (is_shadow_present_pte(*sptep)) {
2594 rmap_count = rmap_add(vcpu, sptep, gfn);
2595 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
2596 rmap_recycle(vcpu, sptep, gfn);
2600 kvm_release_pfn_clean(pfn);
2605 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
2608 struct kvm_memory_slot *slot;
2610 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
2612 return KVM_PFN_ERR_FAULT;
2614 return gfn_to_pfn_memslot_atomic(slot, gfn);
2617 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2618 struct kvm_mmu_page *sp,
2619 u64 *start, u64 *end)
2621 struct page *pages[PTE_PREFETCH_NUM];
2622 struct kvm_memory_slot *slot;
2623 unsigned access = sp->role.access;
2627 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
2628 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2632 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2636 for (i = 0; i < ret; i++, gfn++, start++)
2637 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
2638 page_to_pfn(pages[i]), true, true);
2643 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2644 struct kvm_mmu_page *sp, u64 *sptep)
2646 u64 *spte, *start = NULL;
2649 WARN_ON(!sp->role.direct);
2651 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
2654 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2655 if (is_shadow_present_pte(*spte) || spte == sptep) {
2658 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2666 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2668 struct kvm_mmu_page *sp;
2671 * Since it's no accessed bit on EPT, it's no way to
2672 * distinguish between actually accessed translations
2673 * and prefetched, so disable pte prefetch if EPT is
2676 if (!shadow_accessed_mask)
2679 sp = page_header(__pa(sptep));
2680 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
2683 __direct_pte_prefetch(vcpu, sp, sptep);
2686 static int __direct_map(struct kvm_vcpu *vcpu, int write, int map_writable,
2687 int level, gfn_t gfn, kvm_pfn_t pfn, bool prefault)
2689 struct kvm_shadow_walk_iterator iterator;
2690 struct kvm_mmu_page *sp;
2694 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2697 for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
2698 if (iterator.level == level) {
2699 emulate = mmu_set_spte(vcpu, iterator.sptep, ACC_ALL,
2700 write, level, gfn, pfn, prefault,
2702 direct_pte_prefetch(vcpu, iterator.sptep);
2703 ++vcpu->stat.pf_fixed;
2707 drop_large_spte(vcpu, iterator.sptep);
2708 if (!is_shadow_present_pte(*iterator.sptep)) {
2709 u64 base_addr = iterator.addr;
2711 base_addr &= PT64_LVL_ADDR_MASK(iterator.level);
2712 pseudo_gfn = base_addr >> PAGE_SHIFT;
2713 sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
2714 iterator.level - 1, 1, ACC_ALL);
2716 link_shadow_page(vcpu, iterator.sptep, sp);
2722 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
2726 info.si_signo = SIGBUS;
2728 info.si_code = BUS_MCEERR_AR;
2729 info.si_addr = (void __user *)address;
2730 info.si_addr_lsb = PAGE_SHIFT;
2732 send_sig_info(SIGBUS, &info, tsk);
2735 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
2738 * Do not cache the mmio info caused by writing the readonly gfn
2739 * into the spte otherwise read access on readonly gfn also can
2740 * caused mmio page fault and treat it as mmio access.
2741 * Return 1 to tell kvm to emulate it.
2743 if (pfn == KVM_PFN_ERR_RO_FAULT)
2746 if (pfn == KVM_PFN_ERR_HWPOISON) {
2747 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
2754 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
2755 gfn_t *gfnp, kvm_pfn_t *pfnp,
2758 kvm_pfn_t pfn = *pfnp;
2760 int level = *levelp;
2763 * Check if it's a transparent hugepage. If this would be an
2764 * hugetlbfs page, level wouldn't be set to
2765 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
2768 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
2769 level == PT_PAGE_TABLE_LEVEL &&
2770 PageTransCompound(pfn_to_page(pfn)) &&
2771 !has_wrprotected_page(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
2774 * mmu_notifier_retry was successful and we hold the
2775 * mmu_lock here, so the pmd can't become splitting
2776 * from under us, and in turn
2777 * __split_huge_page_refcount() can't run from under
2778 * us and we can safely transfer the refcount from
2779 * PG_tail to PG_head as we switch the pfn to tail to
2782 *levelp = level = PT_DIRECTORY_LEVEL;
2783 mask = KVM_PAGES_PER_HPAGE(level) - 1;
2784 VM_BUG_ON((gfn & mask) != (pfn & mask));
2788 kvm_release_pfn_clean(pfn);
2796 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
2797 kvm_pfn_t pfn, unsigned access, int *ret_val)
2801 /* The pfn is invalid, report the error! */
2802 if (unlikely(is_error_pfn(pfn))) {
2803 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
2807 if (unlikely(is_noslot_pfn(pfn)))
2808 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
2815 static bool page_fault_can_be_fast(u32 error_code)
2818 * Do not fix the mmio spte with invalid generation number which
2819 * need to be updated by slow page fault path.
2821 if (unlikely(error_code & PFERR_RSVD_MASK))
2825 * #PF can be fast only if the shadow page table is present and it
2826 * is caused by write-protect, that means we just need change the
2827 * W bit of the spte which can be done out of mmu-lock.
2829 if (!(error_code & PFERR_PRESENT_MASK) ||
2830 !(error_code & PFERR_WRITE_MASK))
2837 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2838 u64 *sptep, u64 spte)
2842 WARN_ON(!sp->role.direct);
2845 * The gfn of direct spte is stable since it is calculated
2848 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
2851 * Theoretically we could also set dirty bit (and flush TLB) here in
2852 * order to eliminate unnecessary PML logging. See comments in
2853 * set_spte. But fast_page_fault is very unlikely to happen with PML
2854 * enabled, so we do not do this. This might result in the same GPA
2855 * to be logged in PML buffer again when the write really happens, and
2856 * eventually to be called by mark_page_dirty twice. But it's also no
2857 * harm. This also avoids the TLB flush needed after setting dirty bit
2858 * so non-PML cases won't be impacted.
2860 * Compare with set_spte where instead shadow_dirty_mask is set.
2862 if (cmpxchg64(sptep, spte, spte | PT_WRITABLE_MASK) == spte)
2863 kvm_vcpu_mark_page_dirty(vcpu, gfn);
2870 * - true: let the vcpu to access on the same address again.
2871 * - false: let the real page fault path to fix it.
2873 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
2876 struct kvm_shadow_walk_iterator iterator;
2877 struct kvm_mmu_page *sp;
2881 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2884 if (!page_fault_can_be_fast(error_code))
2887 walk_shadow_page_lockless_begin(vcpu);
2888 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
2889 if (!is_shadow_present_pte(spte) || iterator.level < level)
2893 * If the mapping has been changed, let the vcpu fault on the
2894 * same address again.
2896 if (!is_shadow_present_pte(spte)) {
2901 sp = page_header(__pa(iterator.sptep));
2902 if (!is_last_spte(spte, sp->role.level))
2906 * Check if it is a spurious fault caused by TLB lazily flushed.
2908 * Need not check the access of upper level table entries since
2909 * they are always ACC_ALL.
2911 if (is_writable_pte(spte)) {
2917 * Currently, to simplify the code, only the spte write-protected
2918 * by dirty-log can be fast fixed.
2920 if (!spte_is_locklessly_modifiable(spte))
2924 * Do not fix write-permission on the large spte since we only dirty
2925 * the first page into the dirty-bitmap in fast_pf_fix_direct_spte()
2926 * that means other pages are missed if its slot is dirty-logged.
2928 * Instead, we let the slow page fault path create a normal spte to
2931 * See the comments in kvm_arch_commit_memory_region().
2933 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
2937 * Currently, fast page fault only works for direct mapping since
2938 * the gfn is not stable for indirect shadow page.
2939 * See Documentation/virtual/kvm/locking.txt to get more detail.
2941 ret = fast_pf_fix_direct_spte(vcpu, sp, iterator.sptep, spte);
2943 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
2945 walk_shadow_page_lockless_end(vcpu);
2950 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
2951 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
2952 static void make_mmu_pages_available(struct kvm_vcpu *vcpu);
2954 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
2955 gfn_t gfn, bool prefault)
2959 bool force_pt_level = false;
2961 unsigned long mmu_seq;
2962 bool map_writable, write = error_code & PFERR_WRITE_MASK;
2964 level = mapping_level(vcpu, gfn, &force_pt_level);
2965 if (likely(!force_pt_level)) {
2967 * This path builds a PAE pagetable - so we can map
2968 * 2mb pages at maximum. Therefore check if the level
2969 * is larger than that.
2971 if (level > PT_DIRECTORY_LEVEL)
2972 level = PT_DIRECTORY_LEVEL;
2974 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
2977 if (fast_page_fault(vcpu, v, level, error_code))
2980 mmu_seq = vcpu->kvm->mmu_notifier_seq;
2983 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
2986 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
2989 spin_lock(&vcpu->kvm->mmu_lock);
2990 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
2992 make_mmu_pages_available(vcpu);
2993 if (likely(!force_pt_level))
2994 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
2995 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
2996 spin_unlock(&vcpu->kvm->mmu_lock);
3001 spin_unlock(&vcpu->kvm->mmu_lock);
3002 kvm_release_pfn_clean(pfn);
3007 static void mmu_free_roots(struct kvm_vcpu *vcpu)
3010 struct kvm_mmu_page *sp;
3011 LIST_HEAD(invalid_list);
3013 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3016 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL &&
3017 (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL ||
3018 vcpu->arch.mmu.direct_map)) {
3019 hpa_t root = vcpu->arch.mmu.root_hpa;
3021 spin_lock(&vcpu->kvm->mmu_lock);
3022 sp = page_header(root);
3024 if (!sp->root_count && sp->role.invalid) {
3025 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
3026 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3028 spin_unlock(&vcpu->kvm->mmu_lock);
3029 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3033 spin_lock(&vcpu->kvm->mmu_lock);
3034 for (i = 0; i < 4; ++i) {
3035 hpa_t root = vcpu->arch.mmu.pae_root[i];
3038 root &= PT64_BASE_ADDR_MASK;
3039 sp = page_header(root);
3041 if (!sp->root_count && sp->role.invalid)
3042 kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
3045 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
3047 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3048 spin_unlock(&vcpu->kvm->mmu_lock);
3049 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3052 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3056 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3057 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3064 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3066 struct kvm_mmu_page *sp;
3069 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3070 spin_lock(&vcpu->kvm->mmu_lock);
3071 make_mmu_pages_available(vcpu);
3072 sp = kvm_mmu_get_page(vcpu, 0, 0, PT64_ROOT_LEVEL, 1, ACC_ALL);
3074 spin_unlock(&vcpu->kvm->mmu_lock);
3075 vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3076 } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3077 for (i = 0; i < 4; ++i) {
3078 hpa_t root = vcpu->arch.mmu.pae_root[i];
3080 MMU_WARN_ON(VALID_PAGE(root));
3081 spin_lock(&vcpu->kvm->mmu_lock);
3082 make_mmu_pages_available(vcpu);
3083 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3084 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3085 root = __pa(sp->spt);
3087 spin_unlock(&vcpu->kvm->mmu_lock);
3088 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
3090 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3097 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3099 struct kvm_mmu_page *sp;
3104 root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
3106 if (mmu_check_root(vcpu, root_gfn))
3110 * Do we shadow a long mode page table? If so we need to
3111 * write-protect the guests page table root.
3113 if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
3114 hpa_t root = vcpu->arch.mmu.root_hpa;
3116 MMU_WARN_ON(VALID_PAGE(root));
3118 spin_lock(&vcpu->kvm->mmu_lock);
3119 make_mmu_pages_available(vcpu);
3120 sp = kvm_mmu_get_page(vcpu, root_gfn, 0, PT64_ROOT_LEVEL,
3122 root = __pa(sp->spt);
3124 spin_unlock(&vcpu->kvm->mmu_lock);
3125 vcpu->arch.mmu.root_hpa = root;
3130 * We shadow a 32 bit page table. This may be a legacy 2-level
3131 * or a PAE 3-level page table. In either case we need to be aware that
3132 * the shadow page table may be a PAE or a long mode page table.
3134 pm_mask = PT_PRESENT_MASK;
3135 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL)
3136 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3138 for (i = 0; i < 4; ++i) {
3139 hpa_t root = vcpu->arch.mmu.pae_root[i];
3141 MMU_WARN_ON(VALID_PAGE(root));
3142 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
3143 pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
3144 if (!is_present_gpte(pdptr)) {
3145 vcpu->arch.mmu.pae_root[i] = 0;
3148 root_gfn = pdptr >> PAGE_SHIFT;
3149 if (mmu_check_root(vcpu, root_gfn))
3152 spin_lock(&vcpu->kvm->mmu_lock);
3153 make_mmu_pages_available(vcpu);
3154 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3156 root = __pa(sp->spt);
3158 spin_unlock(&vcpu->kvm->mmu_lock);
3160 vcpu->arch.mmu.pae_root[i] = root | pm_mask;
3162 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3165 * If we shadow a 32 bit page table with a long mode page
3166 * table we enter this path.
3168 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3169 if (vcpu->arch.mmu.lm_root == NULL) {
3171 * The additional page necessary for this is only
3172 * allocated on demand.
3177 lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3178 if (lm_root == NULL)
3181 lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3183 vcpu->arch.mmu.lm_root = lm_root;
3186 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3192 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3194 if (vcpu->arch.mmu.direct_map)
3195 return mmu_alloc_direct_roots(vcpu);
3197 return mmu_alloc_shadow_roots(vcpu);
3200 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
3203 struct kvm_mmu_page *sp;
3205 if (vcpu->arch.mmu.direct_map)
3208 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3211 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3212 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3213 if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
3214 hpa_t root = vcpu->arch.mmu.root_hpa;
3215 sp = page_header(root);
3216 mmu_sync_children(vcpu, sp);
3217 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3220 for (i = 0; i < 4; ++i) {
3221 hpa_t root = vcpu->arch.mmu.pae_root[i];
3223 if (root && VALID_PAGE(root)) {
3224 root &= PT64_BASE_ADDR_MASK;
3225 sp = page_header(root);
3226 mmu_sync_children(vcpu, sp);
3229 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3232 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3234 spin_lock(&vcpu->kvm->mmu_lock);
3235 mmu_sync_roots(vcpu);
3236 spin_unlock(&vcpu->kvm->mmu_lock);
3238 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3240 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3241 u32 access, struct x86_exception *exception)
3244 exception->error_code = 0;
3248 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3250 struct x86_exception *exception)
3253 exception->error_code = 0;
3254 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3258 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3260 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3262 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3263 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3266 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3268 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3271 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3273 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3276 static bool quickly_check_mmio_pf(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3279 return vcpu_match_mmio_gpa(vcpu, addr);
3281 return vcpu_match_mmio_gva(vcpu, addr);
3284 /* return true if reserved bit is detected on spte. */
3286 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3288 struct kvm_shadow_walk_iterator iterator;
3289 u64 sptes[PT64_ROOT_LEVEL], spte = 0ull;
3291 bool reserved = false;
3293 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3296 walk_shadow_page_lockless_begin(vcpu);
3298 for (shadow_walk_init(&iterator, vcpu, addr),
3299 leaf = root = iterator.level;
3300 shadow_walk_okay(&iterator);
3301 __shadow_walk_next(&iterator, spte)) {
3302 spte = mmu_spte_get_lockless(iterator.sptep);
3304 sptes[leaf - 1] = spte;
3307 if (!is_shadow_present_pte(spte))
3310 reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
3314 walk_shadow_page_lockless_end(vcpu);
3317 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3319 while (root > leaf) {
3320 pr_err("------ spte 0x%llx level %d.\n",
3321 sptes[root - 1], root);
3330 int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3335 if (quickly_check_mmio_pf(vcpu, addr, direct))
3336 return RET_MMIO_PF_EMULATE;
3338 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3339 if (WARN_ON(reserved))
3340 return RET_MMIO_PF_BUG;
3342 if (is_mmio_spte(spte)) {
3343 gfn_t gfn = get_mmio_spte_gfn(spte);
3344 unsigned access = get_mmio_spte_access(spte);
3346 if (!check_mmio_spte(vcpu, spte))
3347 return RET_MMIO_PF_INVALID;
3352 trace_handle_mmio_page_fault(addr, gfn, access);
3353 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3354 return RET_MMIO_PF_EMULATE;
3358 * If the page table is zapped by other cpus, let CPU fault again on
3361 return RET_MMIO_PF_RETRY;
3363 EXPORT_SYMBOL_GPL(handle_mmio_page_fault);
3365 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
3366 u32 error_code, bool prefault)
3371 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
3373 if (unlikely(error_code & PFERR_RSVD_MASK)) {
3374 r = handle_mmio_page_fault(vcpu, gva, true);
3376 if (likely(r != RET_MMIO_PF_INVALID))
3380 r = mmu_topup_memory_caches(vcpu);
3384 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3386 gfn = gva >> PAGE_SHIFT;
3388 return nonpaging_map(vcpu, gva & PAGE_MASK,
3389 error_code, gfn, prefault);
3392 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
3394 struct kvm_arch_async_pf arch;
3396 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3398 arch.direct_map = vcpu->arch.mmu.direct_map;
3399 arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
3401 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3404 static bool can_do_async_pf(struct kvm_vcpu *vcpu)
3406 if (unlikely(!lapic_in_kernel(vcpu) ||
3407 kvm_event_needs_reinjection(vcpu)))
3410 return kvm_x86_ops->interrupt_allowed(vcpu);
3413 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3414 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
3416 struct kvm_memory_slot *slot;
3419 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3421 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
3423 return false; /* *pfn has correct page already */
3425 if (!prefault && can_do_async_pf(vcpu)) {
3426 trace_kvm_try_async_get_page(gva, gfn);
3427 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
3428 trace_kvm_async_pf_doublefault(gva, gfn);
3429 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3431 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
3435 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
3440 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
3442 int page_num = KVM_PAGES_PER_HPAGE(level);
3444 gfn &= ~(page_num - 1);
3446 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
3449 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
3455 bool force_pt_level;
3456 gfn_t gfn = gpa >> PAGE_SHIFT;
3457 unsigned long mmu_seq;
3458 int write = error_code & PFERR_WRITE_MASK;
3461 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3463 if (unlikely(error_code & PFERR_RSVD_MASK)) {
3464 r = handle_mmio_page_fault(vcpu, gpa, true);
3466 if (likely(r != RET_MMIO_PF_INVALID))
3470 r = mmu_topup_memory_caches(vcpu);
3474 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
3475 PT_DIRECTORY_LEVEL);
3476 level = mapping_level(vcpu, gfn, &force_pt_level);
3477 if (likely(!force_pt_level)) {
3478 if (level > PT_DIRECTORY_LEVEL &&
3479 !check_hugepage_cache_consistency(vcpu, gfn, level))
3480 level = PT_DIRECTORY_LEVEL;
3481 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3484 if (fast_page_fault(vcpu, gpa, level, error_code))
3487 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3490 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
3493 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
3496 spin_lock(&vcpu->kvm->mmu_lock);
3497 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3499 make_mmu_pages_available(vcpu);
3500 if (likely(!force_pt_level))
3501 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
3502 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
3503 spin_unlock(&vcpu->kvm->mmu_lock);
3508 spin_unlock(&vcpu->kvm->mmu_lock);
3509 kvm_release_pfn_clean(pfn);
3513 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
3514 struct kvm_mmu *context)
3516 context->page_fault = nonpaging_page_fault;
3517 context->gva_to_gpa = nonpaging_gva_to_gpa;
3518 context->sync_page = nonpaging_sync_page;
3519 context->invlpg = nonpaging_invlpg;
3520 context->update_pte = nonpaging_update_pte;
3521 context->root_level = 0;
3522 context->shadow_root_level = PT32E_ROOT_LEVEL;
3523 context->root_hpa = INVALID_PAGE;
3524 context->direct_map = true;
3525 context->nx = false;
3528 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu)
3530 mmu_free_roots(vcpu);
3533 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
3535 return kvm_read_cr3(vcpu);
3538 static void inject_page_fault(struct kvm_vcpu *vcpu,
3539 struct x86_exception *fault)
3541 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
3544 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
3545 unsigned access, int *nr_present)
3547 if (unlikely(is_mmio_spte(*sptep))) {
3548 if (gfn != get_mmio_spte_gfn(*sptep)) {
3549 mmu_spte_clear_no_track(sptep);
3554 mark_mmio_spte(vcpu, sptep, gfn, access);
3561 static inline bool is_last_gpte(struct kvm_mmu *mmu, unsigned level, unsigned gpte)
3566 index |= (gpte & PT_PAGE_SIZE_MASK) >> (PT_PAGE_SIZE_SHIFT - 2);
3567 return mmu->last_pte_bitmap & (1 << index);
3570 #define PTTYPE_EPT 18 /* arbitrary */
3571 #define PTTYPE PTTYPE_EPT
3572 #include "paging_tmpl.h"
3576 #include "paging_tmpl.h"
3580 #include "paging_tmpl.h"
3584 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3585 struct rsvd_bits_validate *rsvd_check,
3586 int maxphyaddr, int level, bool nx, bool gbpages,
3589 u64 exb_bit_rsvd = 0;
3590 u64 gbpages_bit_rsvd = 0;
3591 u64 nonleaf_bit8_rsvd = 0;
3593 rsvd_check->bad_mt_xwr = 0;
3596 exb_bit_rsvd = rsvd_bits(63, 63);
3598 gbpages_bit_rsvd = rsvd_bits(7, 7);
3601 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
3602 * leaf entries) on AMD CPUs only.
3605 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
3608 case PT32_ROOT_LEVEL:
3609 /* no rsvd bits for 2 level 4K page table entries */
3610 rsvd_check->rsvd_bits_mask[0][1] = 0;
3611 rsvd_check->rsvd_bits_mask[0][0] = 0;
3612 rsvd_check->rsvd_bits_mask[1][0] =
3613 rsvd_check->rsvd_bits_mask[0][0];
3616 rsvd_check->rsvd_bits_mask[1][1] = 0;
3620 if (is_cpuid_PSE36())
3621 /* 36bits PSE 4MB page */
3622 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
3624 /* 32 bits PSE 4MB page */
3625 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
3627 case PT32E_ROOT_LEVEL:
3628 rsvd_check->rsvd_bits_mask[0][2] =
3629 rsvd_bits(maxphyaddr, 63) |
3630 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
3631 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3632 rsvd_bits(maxphyaddr, 62); /* PDE */
3633 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3634 rsvd_bits(maxphyaddr, 62); /* PTE */
3635 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
3636 rsvd_bits(maxphyaddr, 62) |
3637 rsvd_bits(13, 20); /* large page */
3638 rsvd_check->rsvd_bits_mask[1][0] =
3639 rsvd_check->rsvd_bits_mask[0][0];
3641 case PT64_ROOT_LEVEL:
3642 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
3643 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
3644 rsvd_bits(maxphyaddr, 51);
3645 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
3646 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
3647 rsvd_bits(maxphyaddr, 51);
3648 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3649 rsvd_bits(maxphyaddr, 51);
3650 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3651 rsvd_bits(maxphyaddr, 51);
3652 rsvd_check->rsvd_bits_mask[1][3] =
3653 rsvd_check->rsvd_bits_mask[0][3];
3654 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
3655 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
3657 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
3658 rsvd_bits(maxphyaddr, 51) |
3659 rsvd_bits(13, 20); /* large page */
3660 rsvd_check->rsvd_bits_mask[1][0] =
3661 rsvd_check->rsvd_bits_mask[0][0];
3666 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3667 struct kvm_mmu *context)
3669 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
3670 cpuid_maxphyaddr(vcpu), context->root_level,
3671 context->nx, guest_cpuid_has_gbpages(vcpu),
3672 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
3676 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
3677 int maxphyaddr, bool execonly)
3681 rsvd_check->rsvd_bits_mask[0][3] =
3682 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
3683 rsvd_check->rsvd_bits_mask[0][2] =
3684 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
3685 rsvd_check->rsvd_bits_mask[0][1] =
3686 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
3687 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
3690 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
3691 rsvd_check->rsvd_bits_mask[1][2] =
3692 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
3693 rsvd_check->rsvd_bits_mask[1][1] =
3694 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
3695 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
3697 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
3698 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
3699 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
3700 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
3701 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
3703 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
3704 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
3706 rsvd_check->bad_mt_xwr = bad_mt_xwr;
3709 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
3710 struct kvm_mmu *context, bool execonly)
3712 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
3713 cpuid_maxphyaddr(vcpu), execonly);
3717 * the page table on host is the shadow page table for the page
3718 * table in guest or amd nested guest, its mmu features completely
3719 * follow the features in guest.
3722 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
3724 bool uses_nx = context->nx || context->base_role.smep_andnot_wp;
3727 * Passing "true" to the last argument is okay; it adds a check
3728 * on bit 8 of the SPTEs which KVM doesn't use anyway.
3730 __reset_rsvds_bits_mask(vcpu, &context->shadow_zero_check,
3731 boot_cpu_data.x86_phys_bits,
3732 context->shadow_root_level, uses_nx,
3733 guest_cpuid_has_gbpages(vcpu), is_pse(vcpu),
3736 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
3738 static inline bool boot_cpu_is_amd(void)
3740 WARN_ON_ONCE(!tdp_enabled);
3741 return shadow_x_mask == 0;
3745 * the direct page table on host, use as much mmu features as
3746 * possible, however, kvm currently does not do execution-protection.
3749 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
3750 struct kvm_mmu *context)
3752 if (boot_cpu_is_amd())
3753 __reset_rsvds_bits_mask(vcpu, &context->shadow_zero_check,
3754 boot_cpu_data.x86_phys_bits,
3755 context->shadow_root_level, false,
3756 cpu_has_gbpages, true, true);
3758 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
3759 boot_cpu_data.x86_phys_bits,
3765 * as the comments in reset_shadow_zero_bits_mask() except it
3766 * is the shadow page table for intel nested guest.
3769 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
3770 struct kvm_mmu *context, bool execonly)
3772 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
3773 boot_cpu_data.x86_phys_bits, execonly);
3776 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
3777 struct kvm_mmu *mmu, bool ept)
3779 unsigned bit, byte, pfec;
3781 bool fault, x, w, u, wf, uf, ff, smapf, cr4_smap, cr4_smep, smap = 0;
3783 cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
3784 cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
3785 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
3788 wf = pfec & PFERR_WRITE_MASK;
3789 uf = pfec & PFERR_USER_MASK;
3790 ff = pfec & PFERR_FETCH_MASK;
3792 * PFERR_RSVD_MASK bit is set in PFEC if the access is not
3793 * subject to SMAP restrictions, and cleared otherwise. The
3794 * bit is only meaningful if the SMAP bit is set in CR4.
3796 smapf = !(pfec & PFERR_RSVD_MASK);
3797 for (bit = 0; bit < 8; ++bit) {
3798 x = bit & ACC_EXEC_MASK;
3799 w = bit & ACC_WRITE_MASK;
3800 u = bit & ACC_USER_MASK;
3803 /* Not really needed: !nx will cause pte.nx to fault */
3805 /* Allow supervisor writes if !cr0.wp */
3806 w |= !is_write_protection(vcpu) && !uf;
3807 /* Disallow supervisor fetches of user code if cr4.smep */
3808 x &= !(cr4_smep && u && !uf);
3811 * SMAP:kernel-mode data accesses from user-mode
3812 * mappings should fault. A fault is considered
3813 * as a SMAP violation if all of the following
3814 * conditions are ture:
3815 * - X86_CR4_SMAP is set in CR4
3816 * - An user page is accessed
3817 * - Page fault in kernel mode
3818 * - if CPL = 3 or X86_EFLAGS_AC is clear
3820 * Here, we cover the first three conditions.
3821 * The fourth is computed dynamically in
3822 * permission_fault() and is in smapf.
3824 * Also, SMAP does not affect instruction
3825 * fetches, add the !ff check here to make it
3828 smap = cr4_smap && u && !uf && !ff;
3830 /* Not really needed: no U/S accesses on ept */
3833 fault = (ff && !x) || (uf && !u) || (wf && !w) ||
3835 map |= fault << bit;
3837 mmu->permissions[byte] = map;
3841 static void update_last_pte_bitmap(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
3844 unsigned level, root_level = mmu->root_level;
3845 const unsigned ps_set_index = 1 << 2; /* bit 2 of index: ps */
3847 if (root_level == PT32E_ROOT_LEVEL)
3849 /* PT_PAGE_TABLE_LEVEL always terminates */
3850 map = 1 | (1 << ps_set_index);
3851 for (level = PT_DIRECTORY_LEVEL; level <= root_level; ++level) {
3852 if (level <= PT_PDPE_LEVEL
3853 && (mmu->root_level >= PT32E_ROOT_LEVEL || is_pse(vcpu)))
3854 map |= 1 << (ps_set_index | (level - 1));
3856 mmu->last_pte_bitmap = map;
3859 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
3860 struct kvm_mmu *context,
3863 context->nx = is_nx(vcpu);
3864 context->root_level = level;
3866 reset_rsvds_bits_mask(vcpu, context);
3867 update_permission_bitmask(vcpu, context, false);
3868 update_last_pte_bitmap(vcpu, context);
3870 MMU_WARN_ON(!is_pae(vcpu));
3871 context->page_fault = paging64_page_fault;
3872 context->gva_to_gpa = paging64_gva_to_gpa;
3873 context->sync_page = paging64_sync_page;
3874 context->invlpg = paging64_invlpg;
3875 context->update_pte = paging64_update_pte;
3876 context->shadow_root_level = level;
3877 context->root_hpa = INVALID_PAGE;
3878 context->direct_map = false;
3881 static void paging64_init_context(struct kvm_vcpu *vcpu,
3882 struct kvm_mmu *context)
3884 paging64_init_context_common(vcpu, context, PT64_ROOT_LEVEL);
3887 static void paging32_init_context(struct kvm_vcpu *vcpu,
3888 struct kvm_mmu *context)
3890 context->nx = false;
3891 context->root_level = PT32_ROOT_LEVEL;
3893 reset_rsvds_bits_mask(vcpu, context);
3894 update_permission_bitmask(vcpu, context, false);
3895 update_last_pte_bitmap(vcpu, context);
3897 context->page_fault = paging32_page_fault;
3898 context->gva_to_gpa = paging32_gva_to_gpa;
3899 context->sync_page = paging32_sync_page;
3900 context->invlpg = paging32_invlpg;
3901 context->update_pte = paging32_update_pte;
3902 context->shadow_root_level = PT32E_ROOT_LEVEL;
3903 context->root_hpa = INVALID_PAGE;
3904 context->direct_map = false;
3907 static void paging32E_init_context(struct kvm_vcpu *vcpu,
3908 struct kvm_mmu *context)
3910 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
3913 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
3915 struct kvm_mmu *context = &vcpu->arch.mmu;
3917 context->base_role.word = 0;
3918 context->base_role.smm = is_smm(vcpu);
3919 context->page_fault = tdp_page_fault;
3920 context->sync_page = nonpaging_sync_page;
3921 context->invlpg = nonpaging_invlpg;
3922 context->update_pte = nonpaging_update_pte;
3923 context->shadow_root_level = kvm_x86_ops->get_tdp_level();
3924 context->root_hpa = INVALID_PAGE;
3925 context->direct_map = true;
3926 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
3927 context->get_cr3 = get_cr3;
3928 context->get_pdptr = kvm_pdptr_read;
3929 context->inject_page_fault = kvm_inject_page_fault;
3931 if (!is_paging(vcpu)) {
3932 context->nx = false;
3933 context->gva_to_gpa = nonpaging_gva_to_gpa;
3934 context->root_level = 0;
3935 } else if (is_long_mode(vcpu)) {
3936 context->nx = is_nx(vcpu);
3937 context->root_level = PT64_ROOT_LEVEL;
3938 reset_rsvds_bits_mask(vcpu, context);
3939 context->gva_to_gpa = paging64_gva_to_gpa;
3940 } else if (is_pae(vcpu)) {
3941 context->nx = is_nx(vcpu);
3942 context->root_level = PT32E_ROOT_LEVEL;
3943 reset_rsvds_bits_mask(vcpu, context);
3944 context->gva_to_gpa = paging64_gva_to_gpa;
3946 context->nx = false;
3947 context->root_level = PT32_ROOT_LEVEL;
3948 reset_rsvds_bits_mask(vcpu, context);
3949 context->gva_to_gpa = paging32_gva_to_gpa;
3952 update_permission_bitmask(vcpu, context, false);
3953 update_last_pte_bitmap(vcpu, context);
3954 reset_tdp_shadow_zero_bits_mask(vcpu, context);
3957 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
3959 bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
3960 bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
3961 struct kvm_mmu *context = &vcpu->arch.mmu;
3963 MMU_WARN_ON(VALID_PAGE(context->root_hpa));
3965 if (!is_paging(vcpu))
3966 nonpaging_init_context(vcpu, context);
3967 else if (is_long_mode(vcpu))
3968 paging64_init_context(vcpu, context);
3969 else if (is_pae(vcpu))
3970 paging32E_init_context(vcpu, context);
3972 paging32_init_context(vcpu, context);
3974 context->base_role.nxe = is_nx(vcpu);
3975 context->base_role.cr4_pae = !!is_pae(vcpu);
3976 context->base_role.cr0_wp = is_write_protection(vcpu);
3977 context->base_role.smep_andnot_wp
3978 = smep && !is_write_protection(vcpu);
3979 context->base_role.smap_andnot_wp
3980 = smap && !is_write_protection(vcpu);
3981 context->base_role.smm = is_smm(vcpu);
3982 reset_shadow_zero_bits_mask(vcpu, context);
3984 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
3986 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly)
3988 struct kvm_mmu *context = &vcpu->arch.mmu;
3990 MMU_WARN_ON(VALID_PAGE(context->root_hpa));
3992 context->shadow_root_level = kvm_x86_ops->get_tdp_level();
3995 context->page_fault = ept_page_fault;
3996 context->gva_to_gpa = ept_gva_to_gpa;
3997 context->sync_page = ept_sync_page;
3998 context->invlpg = ept_invlpg;
3999 context->update_pte = ept_update_pte;
4000 context->root_level = context->shadow_root_level;
4001 context->root_hpa = INVALID_PAGE;
4002 context->direct_map = false;
4004 update_permission_bitmask(vcpu, context, true);
4005 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4006 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4008 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4010 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4012 struct kvm_mmu *context = &vcpu->arch.mmu;
4014 kvm_init_shadow_mmu(vcpu);
4015 context->set_cr3 = kvm_x86_ops->set_cr3;
4016 context->get_cr3 = get_cr3;
4017 context->get_pdptr = kvm_pdptr_read;
4018 context->inject_page_fault = kvm_inject_page_fault;
4021 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4023 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4025 g_context->get_cr3 = get_cr3;
4026 g_context->get_pdptr = kvm_pdptr_read;
4027 g_context->inject_page_fault = kvm_inject_page_fault;
4030 * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
4031 * L1's nested page tables (e.g. EPT12). The nested translation
4032 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4033 * L2's page tables as the first level of translation and L1's
4034 * nested page tables as the second level of translation. Basically
4035 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
4037 if (!is_paging(vcpu)) {
4038 g_context->nx = false;
4039 g_context->root_level = 0;
4040 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4041 } else if (is_long_mode(vcpu)) {
4042 g_context->nx = is_nx(vcpu);
4043 g_context->root_level = PT64_ROOT_LEVEL;
4044 reset_rsvds_bits_mask(vcpu, g_context);
4045 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4046 } else if (is_pae(vcpu)) {
4047 g_context->nx = is_nx(vcpu);
4048 g_context->root_level = PT32E_ROOT_LEVEL;
4049 reset_rsvds_bits_mask(vcpu, g_context);
4050 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4052 g_context->nx = false;
4053 g_context->root_level = PT32_ROOT_LEVEL;
4054 reset_rsvds_bits_mask(vcpu, g_context);
4055 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
4058 update_permission_bitmask(vcpu, g_context, false);
4059 update_last_pte_bitmap(vcpu, g_context);
4062 static void init_kvm_mmu(struct kvm_vcpu *vcpu)
4064 if (mmu_is_nested(vcpu))
4065 init_kvm_nested_mmu(vcpu);
4066 else if (tdp_enabled)
4067 init_kvm_tdp_mmu(vcpu);
4069 init_kvm_softmmu(vcpu);
4072 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
4074 kvm_mmu_unload(vcpu);
4077 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
4079 int kvm_mmu_load(struct kvm_vcpu *vcpu)
4083 r = mmu_topup_memory_caches(vcpu);
4086 r = mmu_alloc_roots(vcpu);
4087 kvm_mmu_sync_roots(vcpu);
4090 /* set_cr3() should ensure TLB has been flushed */
4091 vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
4095 EXPORT_SYMBOL_GPL(kvm_mmu_load);
4097 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4099 mmu_free_roots(vcpu);
4100 WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
4102 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
4104 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
4105 struct kvm_mmu_page *sp, u64 *spte,
4108 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
4109 ++vcpu->kvm->stat.mmu_pde_zapped;
4113 ++vcpu->kvm->stat.mmu_pte_updated;
4114 vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
4117 static bool need_remote_flush(u64 old, u64 new)
4119 if (!is_shadow_present_pte(old))
4121 if (!is_shadow_present_pte(new))
4123 if ((old ^ new) & PT64_BASE_ADDR_MASK)
4125 old ^= shadow_nx_mask;
4126 new ^= shadow_nx_mask;
4127 return (old & ~new & PT64_PERM_MASK) != 0;
4130 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, bool zap_page,
4131 bool remote_flush, bool local_flush)
4137 kvm_flush_remote_tlbs(vcpu->kvm);
4138 else if (local_flush)
4139 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4142 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
4143 const u8 *new, int *bytes)
4149 * Assume that the pte write on a page table of the same type
4150 * as the current vcpu paging mode since we update the sptes only
4151 * when they have the same mode.
4153 if (is_pae(vcpu) && *bytes == 4) {
4154 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
4157 r = kvm_vcpu_read_guest(vcpu, *gpa, &gentry, 8);
4160 new = (const u8 *)&gentry;
4165 gentry = *(const u32 *)new;
4168 gentry = *(const u64 *)new;
4179 * If we're seeing too many writes to a page, it may no longer be a page table,
4180 * or we may be forking, in which case it is better to unmap the page.
4182 static bool detect_write_flooding(struct kvm_mmu_page *sp)
4185 * Skip write-flooding detected for the sp whose level is 1, because
4186 * it can become unsync, then the guest page is not write-protected.
4188 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
4191 return ++sp->write_flooding_count >= 3;
4195 * Misaligned accesses are too much trouble to fix up; also, they usually
4196 * indicate a page is not used as a page table.
4198 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
4201 unsigned offset, pte_size, misaligned;
4203 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
4204 gpa, bytes, sp->role.word);
4206 offset = offset_in_page(gpa);
4207 pte_size = sp->role.cr4_pae ? 8 : 4;
4210 * Sometimes, the OS only writes the last one bytes to update status
4211 * bits, for example, in linux, andb instruction is used in clear_bit().
4213 if (!(offset & (pte_size - 1)) && bytes == 1)
4216 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
4217 misaligned |= bytes < 4;
4222 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
4224 unsigned page_offset, quadrant;
4228 page_offset = offset_in_page(gpa);
4229 level = sp->role.level;
4231 if (!sp->role.cr4_pae) {
4232 page_offset <<= 1; /* 32->64 */
4234 * A 32-bit pde maps 4MB while the shadow pdes map
4235 * only 2MB. So we need to double the offset again
4236 * and zap two pdes instead of one.
4238 if (level == PT32_ROOT_LEVEL) {
4239 page_offset &= ~7; /* kill rounding error */
4243 quadrant = page_offset >> PAGE_SHIFT;
4244 page_offset &= ~PAGE_MASK;
4245 if (quadrant != sp->role.quadrant)
4249 spte = &sp->spt[page_offset / sizeof(*spte)];
4253 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
4254 const u8 *new, int bytes)
4256 gfn_t gfn = gpa >> PAGE_SHIFT;
4257 struct kvm_mmu_page *sp;
4258 LIST_HEAD(invalid_list);
4259 u64 entry, gentry, *spte;
4261 bool remote_flush, local_flush, zap_page;
4262 union kvm_mmu_page_role mask = { };
4267 mask.smep_andnot_wp = 1;
4268 mask.smap_andnot_wp = 1;
4272 * If we don't have indirect shadow pages, it means no page is
4273 * write-protected, so we can exit simply.
4275 if (!ACCESS_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
4278 zap_page = remote_flush = local_flush = false;
4280 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
4282 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, new, &bytes);
4285 * No need to care whether allocation memory is successful
4286 * or not since pte prefetch is skiped if it does not have
4287 * enough objects in the cache.
4289 mmu_topup_memory_caches(vcpu);
4291 spin_lock(&vcpu->kvm->mmu_lock);
4292 ++vcpu->kvm->stat.mmu_pte_write;
4293 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
4295 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
4296 if (detect_write_misaligned(sp, gpa, bytes) ||
4297 detect_write_flooding(sp)) {
4298 zap_page |= !!kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
4300 ++vcpu->kvm->stat.mmu_flooded;
4304 spte = get_written_sptes(sp, gpa, &npte);
4311 mmu_page_zap_pte(vcpu->kvm, sp, spte);
4313 !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
4314 & mask.word) && rmap_can_add(vcpu))
4315 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
4316 if (need_remote_flush(entry, *spte))
4317 remote_flush = true;
4321 mmu_pte_write_flush_tlb(vcpu, zap_page, remote_flush, local_flush);
4322 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
4323 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
4324 spin_unlock(&vcpu->kvm->mmu_lock);
4327 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
4332 if (vcpu->arch.mmu.direct_map)
4335 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
4337 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4341 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
4343 static void make_mmu_pages_available(struct kvm_vcpu *vcpu)
4345 LIST_HEAD(invalid_list);
4347 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
4350 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
4351 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
4354 ++vcpu->kvm->stat.mmu_recycled;
4356 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
4359 static bool is_mmio_page_fault(struct kvm_vcpu *vcpu, gva_t addr)
4361 if (vcpu->arch.mmu.direct_map || mmu_is_nested(vcpu))
4362 return vcpu_match_mmio_gpa(vcpu, addr);
4364 return vcpu_match_mmio_gva(vcpu, addr);
4367 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code,
4368 void *insn, int insn_len)
4370 int r, emulation_type = EMULTYPE_RETRY;
4371 enum emulation_result er;
4373 r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false);
4382 if (is_mmio_page_fault(vcpu, cr2))
4385 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
4390 case EMULATE_USER_EXIT:
4391 ++vcpu->stat.mmio_exits;
4401 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
4403 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
4405 vcpu->arch.mmu.invlpg(vcpu, gva);
4406 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4407 ++vcpu->stat.invlpg;
4409 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
4411 void kvm_enable_tdp(void)
4415 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
4417 void kvm_disable_tdp(void)
4419 tdp_enabled = false;
4421 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
4423 static void free_mmu_pages(struct kvm_vcpu *vcpu)
4425 free_page((unsigned long)vcpu->arch.mmu.pae_root);
4426 if (vcpu->arch.mmu.lm_root != NULL)
4427 free_page((unsigned long)vcpu->arch.mmu.lm_root);
4430 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
4436 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
4437 * Therefore we need to allocate shadow page tables in the first
4438 * 4GB of memory, which happens to fit the DMA32 zone.
4440 page = alloc_page(GFP_KERNEL | __GFP_DMA32);
4444 vcpu->arch.mmu.pae_root = page_address(page);
4445 for (i = 0; i < 4; ++i)
4446 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
4451 int kvm_mmu_create(struct kvm_vcpu *vcpu)
4453 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
4454 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4455 vcpu->arch.mmu.translate_gpa = translate_gpa;
4456 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
4458 return alloc_mmu_pages(vcpu);
4461 void kvm_mmu_setup(struct kvm_vcpu *vcpu)
4463 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
4468 /* The return value indicates if tlb flush on all vcpus is needed. */
4469 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
4471 /* The caller should hold mmu-lock before calling this function. */
4473 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
4474 slot_level_handler fn, int start_level, int end_level,
4475 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
4477 struct slot_rmap_walk_iterator iterator;
4480 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
4481 end_gfn, &iterator) {
4483 flush |= fn(kvm, iterator.rmap);
4485 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
4486 if (flush && lock_flush_tlb) {
4487 kvm_flush_remote_tlbs(kvm);
4490 cond_resched_lock(&kvm->mmu_lock);
4494 if (flush && lock_flush_tlb) {
4495 kvm_flush_remote_tlbs(kvm);
4503 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
4504 slot_level_handler fn, int start_level, int end_level,
4505 bool lock_flush_tlb)
4507 return slot_handle_level_range(kvm, memslot, fn, start_level,
4508 end_level, memslot->base_gfn,
4509 memslot->base_gfn + memslot->npages - 1,
4514 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
4515 slot_level_handler fn, bool lock_flush_tlb)
4517 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
4518 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
4522 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
4523 slot_level_handler fn, bool lock_flush_tlb)
4525 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
4526 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
4530 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
4531 slot_level_handler fn, bool lock_flush_tlb)
4533 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
4534 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
4537 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
4539 struct kvm_memslots *slots;
4540 struct kvm_memory_slot *memslot;
4543 spin_lock(&kvm->mmu_lock);
4544 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
4545 slots = __kvm_memslots(kvm, i);
4546 kvm_for_each_memslot(memslot, slots) {
4549 start = max(gfn_start, memslot->base_gfn);
4550 end = min(gfn_end, memslot->base_gfn + memslot->npages);
4554 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
4555 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
4556 start, end - 1, true);
4560 spin_unlock(&kvm->mmu_lock);
4563 static bool slot_rmap_write_protect(struct kvm *kvm,
4564 struct kvm_rmap_head *rmap_head)
4566 return __rmap_write_protect(kvm, rmap_head, false);
4569 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
4570 struct kvm_memory_slot *memslot)
4574 spin_lock(&kvm->mmu_lock);
4575 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
4577 spin_unlock(&kvm->mmu_lock);
4580 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
4581 * which do tlb flush out of mmu-lock should be serialized by
4582 * kvm->slots_lock otherwise tlb flush would be missed.
4584 lockdep_assert_held(&kvm->slots_lock);
4587 * We can flush all the TLBs out of the mmu lock without TLB
4588 * corruption since we just change the spte from writable to
4589 * readonly so that we only need to care the case of changing
4590 * spte from present to present (changing the spte from present
4591 * to nonpresent will flush all the TLBs immediately), in other
4592 * words, the only case we care is mmu_spte_update() where we
4593 * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
4594 * instead of PT_WRITABLE_MASK, that means it does not depend
4595 * on PT_WRITABLE_MASK anymore.
4598 kvm_flush_remote_tlbs(kvm);
4601 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
4602 struct kvm_rmap_head *rmap_head)
4605 struct rmap_iterator iter;
4606 int need_tlb_flush = 0;
4608 struct kvm_mmu_page *sp;
4611 for_each_rmap_spte(rmap_head, &iter, sptep) {
4612 sp = page_header(__pa(sptep));
4613 pfn = spte_to_pfn(*sptep);
4616 * We cannot do huge page mapping for indirect shadow pages,
4617 * which are found on the last rmap (level = 1) when not using
4618 * tdp; such shadow pages are synced with the page table in
4619 * the guest, and the guest page table is using 4K page size
4620 * mapping if the indirect sp has level = 1.
4622 if (sp->role.direct &&
4623 !kvm_is_reserved_pfn(pfn) &&
4624 PageTransCompound(pfn_to_page(pfn))) {
4625 drop_spte(kvm, sptep);
4631 return need_tlb_flush;
4634 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
4635 const struct kvm_memory_slot *memslot)
4637 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
4638 spin_lock(&kvm->mmu_lock);
4639 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
4640 kvm_mmu_zap_collapsible_spte, true);
4641 spin_unlock(&kvm->mmu_lock);
4644 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
4645 struct kvm_memory_slot *memslot)
4649 spin_lock(&kvm->mmu_lock);
4650 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
4651 spin_unlock(&kvm->mmu_lock);
4653 lockdep_assert_held(&kvm->slots_lock);
4656 * It's also safe to flush TLBs out of mmu lock here as currently this
4657 * function is only used for dirty logging, in which case flushing TLB
4658 * out of mmu lock also guarantees no dirty pages will be lost in
4662 kvm_flush_remote_tlbs(kvm);
4664 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
4666 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
4667 struct kvm_memory_slot *memslot)
4671 spin_lock(&kvm->mmu_lock);
4672 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
4674 spin_unlock(&kvm->mmu_lock);
4676 /* see kvm_mmu_slot_remove_write_access */
4677 lockdep_assert_held(&kvm->slots_lock);
4680 kvm_flush_remote_tlbs(kvm);
4682 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
4684 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
4685 struct kvm_memory_slot *memslot)
4689 spin_lock(&kvm->mmu_lock);
4690 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
4691 spin_unlock(&kvm->mmu_lock);
4693 lockdep_assert_held(&kvm->slots_lock);
4695 /* see kvm_mmu_slot_leaf_clear_dirty */
4697 kvm_flush_remote_tlbs(kvm);
4699 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
4701 #define BATCH_ZAP_PAGES 10
4702 static void kvm_zap_obsolete_pages(struct kvm *kvm)
4704 struct kvm_mmu_page *sp, *node;
4708 list_for_each_entry_safe_reverse(sp, node,
4709 &kvm->arch.active_mmu_pages, link) {
4713 * No obsolete page exists before new created page since
4714 * active_mmu_pages is the FIFO list.
4716 if (!is_obsolete_sp(kvm, sp))
4720 * Since we are reversely walking the list and the invalid
4721 * list will be moved to the head, skip the invalid page
4722 * can help us to avoid the infinity list walking.
4724 if (sp->role.invalid)
4728 * Need not flush tlb since we only zap the sp with invalid
4729 * generation number.
4731 if (batch >= BATCH_ZAP_PAGES &&
4732 cond_resched_lock(&kvm->mmu_lock)) {
4737 ret = kvm_mmu_prepare_zap_page(kvm, sp,
4738 &kvm->arch.zapped_obsolete_pages);
4746 * Should flush tlb before free page tables since lockless-walking
4747 * may use the pages.
4749 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
4753 * Fast invalidate all shadow pages and use lock-break technique
4754 * to zap obsolete pages.
4756 * It's required when memslot is being deleted or VM is being
4757 * destroyed, in these cases, we should ensure that KVM MMU does
4758 * not use any resource of the being-deleted slot or all slots
4759 * after calling the function.
4761 void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
4763 spin_lock(&kvm->mmu_lock);
4764 trace_kvm_mmu_invalidate_zap_all_pages(kvm);
4765 kvm->arch.mmu_valid_gen++;
4768 * Notify all vcpus to reload its shadow page table
4769 * and flush TLB. Then all vcpus will switch to new
4770 * shadow page table with the new mmu_valid_gen.
4772 * Note: we should do this under the protection of
4773 * mmu-lock, otherwise, vcpu would purge shadow page
4774 * but miss tlb flush.
4776 kvm_reload_remote_mmus(kvm);
4778 kvm_zap_obsolete_pages(kvm);
4779 spin_unlock(&kvm->mmu_lock);
4782 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
4784 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
4787 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, struct kvm_memslots *slots)
4790 * The very rare case: if the generation-number is round,
4791 * zap all shadow pages.
4793 if (unlikely((slots->generation & MMIO_GEN_MASK) == 0)) {
4794 printk_ratelimited(KERN_DEBUG "kvm: zapping shadow pages for mmio generation wraparound\n");
4795 kvm_mmu_invalidate_zap_all_pages(kvm);
4799 static unsigned long
4800 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
4803 int nr_to_scan = sc->nr_to_scan;
4804 unsigned long freed = 0;
4806 spin_lock(&kvm_lock);
4808 list_for_each_entry(kvm, &vm_list, vm_list) {
4810 LIST_HEAD(invalid_list);
4813 * Never scan more than sc->nr_to_scan VM instances.
4814 * Will not hit this condition practically since we do not try
4815 * to shrink more than one VM and it is very unlikely to see
4816 * !n_used_mmu_pages so many times.
4821 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
4822 * here. We may skip a VM instance errorneosly, but we do not
4823 * want to shrink a VM that only started to populate its MMU
4826 if (!kvm->arch.n_used_mmu_pages &&
4827 !kvm_has_zapped_obsolete_pages(kvm))
4830 idx = srcu_read_lock(&kvm->srcu);
4831 spin_lock(&kvm->mmu_lock);
4833 if (kvm_has_zapped_obsolete_pages(kvm)) {
4834 kvm_mmu_commit_zap_page(kvm,
4835 &kvm->arch.zapped_obsolete_pages);
4839 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
4841 kvm_mmu_commit_zap_page(kvm, &invalid_list);
4844 spin_unlock(&kvm->mmu_lock);
4845 srcu_read_unlock(&kvm->srcu, idx);
4848 * unfair on small ones
4849 * per-vm shrinkers cry out
4850 * sadness comes quickly
4852 list_move_tail(&kvm->vm_list, &vm_list);
4856 spin_unlock(&kvm_lock);
4860 static unsigned long
4861 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
4863 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
4866 static struct shrinker mmu_shrinker = {
4867 .count_objects = mmu_shrink_count,
4868 .scan_objects = mmu_shrink_scan,
4869 .seeks = DEFAULT_SEEKS * 10,
4872 static void mmu_destroy_caches(void)
4874 if (pte_list_desc_cache)
4875 kmem_cache_destroy(pte_list_desc_cache);
4876 if (mmu_page_header_cache)
4877 kmem_cache_destroy(mmu_page_header_cache);
4880 int kvm_mmu_module_init(void)
4882 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
4883 sizeof(struct pte_list_desc),
4885 if (!pte_list_desc_cache)
4888 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
4889 sizeof(struct kvm_mmu_page),
4891 if (!mmu_page_header_cache)
4894 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
4897 register_shrinker(&mmu_shrinker);
4902 mmu_destroy_caches();
4907 * Caculate mmu pages needed for kvm.
4909 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
4911 unsigned int nr_mmu_pages;
4912 unsigned int nr_pages = 0;
4913 struct kvm_memslots *slots;
4914 struct kvm_memory_slot *memslot;
4917 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
4918 slots = __kvm_memslots(kvm, i);
4920 kvm_for_each_memslot(memslot, slots)
4921 nr_pages += memslot->npages;
4924 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
4925 nr_mmu_pages = max(nr_mmu_pages,
4926 (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
4928 return nr_mmu_pages;
4931 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
4933 kvm_mmu_unload(vcpu);
4934 free_mmu_pages(vcpu);
4935 mmu_free_memory_caches(vcpu);
4938 void kvm_mmu_module_exit(void)
4940 mmu_destroy_caches();
4941 percpu_counter_destroy(&kvm_total_used_mmu_pages);
4942 unregister_shrinker(&mmu_shrinker);
4943 mmu_audit_disable();