1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
10 * Copyright (C) 2006 Qumranet, Inc.
11 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Avi Kivity <avi@qumranet.com>
21 #include "mmu_internal.h"
23 #include "kvm_cache_regs.h"
24 #include "kvm_emulate.h"
28 #include <linux/kvm_host.h>
29 #include <linux/types.h>
30 #include <linux/string.h>
32 #include <linux/highmem.h>
33 #include <linux/moduleparam.h>
34 #include <linux/export.h>
35 #include <linux/swap.h>
36 #include <linux/hugetlb.h>
37 #include <linux/compiler.h>
38 #include <linux/srcu.h>
39 #include <linux/slab.h>
40 #include <linux/sched/signal.h>
41 #include <linux/uaccess.h>
42 #include <linux/hash.h>
43 #include <linux/kern_levels.h>
44 #include <linux/kthread.h>
47 #include <asm/memtype.h>
48 #include <asm/cmpxchg.h>
51 #include <asm/kvm_page_track.h>
54 extern bool itlb_multihit_kvm_mitigation
;
56 static int __read_mostly nx_huge_pages
= -1;
57 #ifdef CONFIG_PREEMPT_RT
58 /* Recovery can cause latency spikes, disable it for PREEMPT_RT. */
59 static uint __read_mostly nx_huge_pages_recovery_ratio
= 0;
61 static uint __read_mostly nx_huge_pages_recovery_ratio
= 60;
64 static int set_nx_huge_pages(const char *val
, const struct kernel_param
*kp
);
65 static int set_nx_huge_pages_recovery_ratio(const char *val
, const struct kernel_param
*kp
);
67 static const struct kernel_param_ops nx_huge_pages_ops
= {
68 .set
= set_nx_huge_pages
,
69 .get
= param_get_bool
,
72 static const struct kernel_param_ops nx_huge_pages_recovery_ratio_ops
= {
73 .set
= set_nx_huge_pages_recovery_ratio
,
74 .get
= param_get_uint
,
77 module_param_cb(nx_huge_pages
, &nx_huge_pages_ops
, &nx_huge_pages
, 0644);
78 __MODULE_PARM_TYPE(nx_huge_pages
, "bool");
79 module_param_cb(nx_huge_pages_recovery_ratio
, &nx_huge_pages_recovery_ratio_ops
,
80 &nx_huge_pages_recovery_ratio
, 0644);
81 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio
, "uint");
83 static bool __read_mostly force_flush_and_sync_on_reuse
;
84 module_param_named(flush_on_reuse
, force_flush_and_sync_on_reuse
, bool, 0644);
87 * When setting this variable to true it enables Two-Dimensional-Paging
88 * where the hardware walks 2 page tables:
89 * 1. the guest-virtual to guest-physical
90 * 2. while doing 1. it walks guest-physical to host-physical
91 * If the hardware supports that we don't need to do shadow paging.
93 bool tdp_enabled
= false;
95 static int max_huge_page_level __read_mostly
;
96 static int max_tdp_level __read_mostly
;
100 AUDIT_POST_PAGE_FAULT
,
102 AUDIT_POST_PTE_WRITE
,
109 module_param(dbg
, bool, 0644);
112 #define PTE_PREFETCH_NUM 8
114 #define PT32_LEVEL_BITS 10
116 #define PT32_LEVEL_SHIFT(level) \
117 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
119 #define PT32_LVL_OFFSET_MASK(level) \
120 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
121 * PT32_LEVEL_BITS))) - 1))
123 #define PT32_INDEX(address, level)\
124 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
127 #define PT32_BASE_ADDR_MASK PAGE_MASK
128 #define PT32_DIR_BASE_ADDR_MASK \
129 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
130 #define PT32_LVL_ADDR_MASK(level) \
131 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
132 * PT32_LEVEL_BITS))) - 1))
134 #include <trace/events/kvm.h>
136 /* make pte_list_desc fit well in cache line */
137 #define PTE_LIST_EXT 3
140 * Return values of handle_mmio_page_fault, mmu.page_fault, and fast_page_fault().
142 * RET_PF_RETRY: let CPU fault again on the address.
143 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
144 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
145 * RET_PF_FIXED: The faulting entry has been fixed.
146 * RET_PF_SPURIOUS: The faulting entry was already fixed, e.g. by another vCPU.
156 struct pte_list_desc
{
157 u64
*sptes
[PTE_LIST_EXT
];
158 struct pte_list_desc
*more
;
161 struct kvm_shadow_walk_iterator
{
169 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
170 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
172 shadow_walk_okay(&(_walker)); \
173 shadow_walk_next(&(_walker)))
175 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
176 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
177 shadow_walk_okay(&(_walker)); \
178 shadow_walk_next(&(_walker)))
180 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
181 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
182 shadow_walk_okay(&(_walker)) && \
183 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
184 __shadow_walk_next(&(_walker), spte))
186 static struct kmem_cache
*pte_list_desc_cache
;
187 static struct kmem_cache
*mmu_page_header_cache
;
188 static struct percpu_counter kvm_total_used_mmu_pages
;
190 static void mmu_spte_set(u64
*sptep
, u64 spte
);
191 static union kvm_mmu_page_role
192 kvm_mmu_calc_root_page_role(struct kvm_vcpu
*vcpu
);
194 #define CREATE_TRACE_POINTS
195 #include "mmutrace.h"
198 static inline bool kvm_available_flush_tlb_with_range(void)
200 return kvm_x86_ops
.tlb_remote_flush_with_range
;
203 static void kvm_flush_remote_tlbs_with_range(struct kvm
*kvm
,
204 struct kvm_tlb_range
*range
)
208 if (range
&& kvm_x86_ops
.tlb_remote_flush_with_range
)
209 ret
= kvm_x86_ops
.tlb_remote_flush_with_range(kvm
, range
);
212 kvm_flush_remote_tlbs(kvm
);
215 static void kvm_flush_remote_tlbs_with_address(struct kvm
*kvm
,
216 u64 start_gfn
, u64 pages
)
218 struct kvm_tlb_range range
;
220 range
.start_gfn
= start_gfn
;
223 kvm_flush_remote_tlbs_with_range(kvm
, &range
);
226 bool is_nx_huge_page_enabled(void)
228 return READ_ONCE(nx_huge_pages
);
231 static void mark_mmio_spte(struct kvm_vcpu
*vcpu
, u64
*sptep
, u64 gfn
,
234 u64 mask
= make_mmio_spte(vcpu
, gfn
, access
);
235 unsigned int gen
= get_mmio_spte_generation(mask
);
237 access
= mask
& ACC_ALL
;
239 trace_mark_mmio_spte(sptep
, gfn
, access
, gen
);
240 mmu_spte_set(sptep
, mask
);
243 static gfn_t
get_mmio_spte_gfn(u64 spte
)
245 u64 gpa
= spte
& shadow_nonpresent_or_rsvd_lower_gfn_mask
;
247 gpa
|= (spte
>> shadow_nonpresent_or_rsvd_mask_len
)
248 & shadow_nonpresent_or_rsvd_mask
;
250 return gpa
>> PAGE_SHIFT
;
253 static unsigned get_mmio_spte_access(u64 spte
)
255 return spte
& shadow_mmio_access_mask
;
258 static bool set_mmio_spte(struct kvm_vcpu
*vcpu
, u64
*sptep
, gfn_t gfn
,
259 kvm_pfn_t pfn
, unsigned int access
)
261 if (unlikely(is_noslot_pfn(pfn
))) {
262 mark_mmio_spte(vcpu
, sptep
, gfn
, access
);
269 static bool check_mmio_spte(struct kvm_vcpu
*vcpu
, u64 spte
)
271 u64 kvm_gen
, spte_gen
, gen
;
273 gen
= kvm_vcpu_memslots(vcpu
)->generation
;
274 if (unlikely(gen
& KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS
))
277 kvm_gen
= gen
& MMIO_SPTE_GEN_MASK
;
278 spte_gen
= get_mmio_spte_generation(spte
);
280 trace_check_mmio_spte(spte
, kvm_gen
, spte_gen
);
281 return likely(kvm_gen
== spte_gen
);
284 static gpa_t
translate_gpa(struct kvm_vcpu
*vcpu
, gpa_t gpa
, u32 access
,
285 struct x86_exception
*exception
)
287 /* Check if guest physical address doesn't exceed guest maximum */
288 if (kvm_vcpu_is_illegal_gpa(vcpu
, gpa
)) {
289 exception
->error_code
|= PFERR_RSVD_MASK
;
296 static int is_cpuid_PSE36(void)
301 static int is_nx(struct kvm_vcpu
*vcpu
)
303 return vcpu
->arch
.efer
& EFER_NX
;
306 static gfn_t
pse36_gfn_delta(u32 gpte
)
308 int shift
= 32 - PT32_DIR_PSE36_SHIFT
- PAGE_SHIFT
;
310 return (gpte
& PT32_DIR_PSE36_MASK
) << shift
;
314 static void __set_spte(u64
*sptep
, u64 spte
)
316 WRITE_ONCE(*sptep
, spte
);
319 static void __update_clear_spte_fast(u64
*sptep
, u64 spte
)
321 WRITE_ONCE(*sptep
, spte
);
324 static u64
__update_clear_spte_slow(u64
*sptep
, u64 spte
)
326 return xchg(sptep
, spte
);
329 static u64
__get_spte_lockless(u64
*sptep
)
331 return READ_ONCE(*sptep
);
342 static void count_spte_clear(u64
*sptep
, u64 spte
)
344 struct kvm_mmu_page
*sp
= sptep_to_sp(sptep
);
346 if (is_shadow_present_pte(spte
))
349 /* Ensure the spte is completely set before we increase the count */
351 sp
->clear_spte_count
++;
354 static void __set_spte(u64
*sptep
, u64 spte
)
356 union split_spte
*ssptep
, sspte
;
358 ssptep
= (union split_spte
*)sptep
;
359 sspte
= (union split_spte
)spte
;
361 ssptep
->spte_high
= sspte
.spte_high
;
364 * If we map the spte from nonpresent to present, We should store
365 * the high bits firstly, then set present bit, so cpu can not
366 * fetch this spte while we are setting the spte.
370 WRITE_ONCE(ssptep
->spte_low
, sspte
.spte_low
);
373 static void __update_clear_spte_fast(u64
*sptep
, u64 spte
)
375 union split_spte
*ssptep
, sspte
;
377 ssptep
= (union split_spte
*)sptep
;
378 sspte
= (union split_spte
)spte
;
380 WRITE_ONCE(ssptep
->spte_low
, sspte
.spte_low
);
383 * If we map the spte from present to nonpresent, we should clear
384 * present bit firstly to avoid vcpu fetch the old high bits.
388 ssptep
->spte_high
= sspte
.spte_high
;
389 count_spte_clear(sptep
, spte
);
392 static u64
__update_clear_spte_slow(u64
*sptep
, u64 spte
)
394 union split_spte
*ssptep
, sspte
, orig
;
396 ssptep
= (union split_spte
*)sptep
;
397 sspte
= (union split_spte
)spte
;
399 /* xchg acts as a barrier before the setting of the high bits */
400 orig
.spte_low
= xchg(&ssptep
->spte_low
, sspte
.spte_low
);
401 orig
.spte_high
= ssptep
->spte_high
;
402 ssptep
->spte_high
= sspte
.spte_high
;
403 count_spte_clear(sptep
, spte
);
409 * The idea using the light way get the spte on x86_32 guest is from
410 * gup_get_pte (mm/gup.c).
412 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
413 * coalesces them and we are running out of the MMU lock. Therefore
414 * we need to protect against in-progress updates of the spte.
416 * Reading the spte while an update is in progress may get the old value
417 * for the high part of the spte. The race is fine for a present->non-present
418 * change (because the high part of the spte is ignored for non-present spte),
419 * but for a present->present change we must reread the spte.
421 * All such changes are done in two steps (present->non-present and
422 * non-present->present), hence it is enough to count the number of
423 * present->non-present updates: if it changed while reading the spte,
424 * we might have hit the race. This is done using clear_spte_count.
426 static u64
__get_spte_lockless(u64
*sptep
)
428 struct kvm_mmu_page
*sp
= sptep_to_sp(sptep
);
429 union split_spte spte
, *orig
= (union split_spte
*)sptep
;
433 count
= sp
->clear_spte_count
;
436 spte
.spte_low
= orig
->spte_low
;
439 spte
.spte_high
= orig
->spte_high
;
442 if (unlikely(spte
.spte_low
!= orig
->spte_low
||
443 count
!= sp
->clear_spte_count
))
450 static bool spte_has_volatile_bits(u64 spte
)
452 if (!is_shadow_present_pte(spte
))
456 * Always atomically update spte if it can be updated
457 * out of mmu-lock, it can ensure dirty bit is not lost,
458 * also, it can help us to get a stable is_writable_pte()
459 * to ensure tlb flush is not missed.
461 if (spte_can_locklessly_be_made_writable(spte
) ||
462 is_access_track_spte(spte
))
465 if (spte_ad_enabled(spte
)) {
466 if ((spte
& shadow_accessed_mask
) == 0 ||
467 (is_writable_pte(spte
) && (spte
& shadow_dirty_mask
) == 0))
474 /* Rules for using mmu_spte_set:
475 * Set the sptep from nonpresent to present.
476 * Note: the sptep being assigned *must* be either not present
477 * or in a state where the hardware will not attempt to update
480 static void mmu_spte_set(u64
*sptep
, u64 new_spte
)
482 WARN_ON(is_shadow_present_pte(*sptep
));
483 __set_spte(sptep
, new_spte
);
487 * Update the SPTE (excluding the PFN), but do not track changes in its
488 * accessed/dirty status.
490 static u64
mmu_spte_update_no_track(u64
*sptep
, u64 new_spte
)
492 u64 old_spte
= *sptep
;
494 WARN_ON(!is_shadow_present_pte(new_spte
));
496 if (!is_shadow_present_pte(old_spte
)) {
497 mmu_spte_set(sptep
, new_spte
);
501 if (!spte_has_volatile_bits(old_spte
))
502 __update_clear_spte_fast(sptep
, new_spte
);
504 old_spte
= __update_clear_spte_slow(sptep
, new_spte
);
506 WARN_ON(spte_to_pfn(old_spte
) != spte_to_pfn(new_spte
));
511 /* Rules for using mmu_spte_update:
512 * Update the state bits, it means the mapped pfn is not changed.
514 * Whenever we overwrite a writable spte with a read-only one we
515 * should flush remote TLBs. Otherwise rmap_write_protect
516 * will find a read-only spte, even though the writable spte
517 * might be cached on a CPU's TLB, the return value indicates this
520 * Returns true if the TLB needs to be flushed
522 static bool mmu_spte_update(u64
*sptep
, u64 new_spte
)
525 u64 old_spte
= mmu_spte_update_no_track(sptep
, new_spte
);
527 if (!is_shadow_present_pte(old_spte
))
531 * For the spte updated out of mmu-lock is safe, since
532 * we always atomically update it, see the comments in
533 * spte_has_volatile_bits().
535 if (spte_can_locklessly_be_made_writable(old_spte
) &&
536 !is_writable_pte(new_spte
))
540 * Flush TLB when accessed/dirty states are changed in the page tables,
541 * to guarantee consistency between TLB and page tables.
544 if (is_accessed_spte(old_spte
) && !is_accessed_spte(new_spte
)) {
546 kvm_set_pfn_accessed(spte_to_pfn(old_spte
));
549 if (is_dirty_spte(old_spte
) && !is_dirty_spte(new_spte
)) {
551 kvm_set_pfn_dirty(spte_to_pfn(old_spte
));
558 * Rules for using mmu_spte_clear_track_bits:
559 * It sets the sptep from present to nonpresent, and track the
560 * state bits, it is used to clear the last level sptep.
561 * Returns non-zero if the PTE was previously valid.
563 static int mmu_spte_clear_track_bits(u64
*sptep
)
566 u64 old_spte
= *sptep
;
568 if (!spte_has_volatile_bits(old_spte
))
569 __update_clear_spte_fast(sptep
, 0ull);
571 old_spte
= __update_clear_spte_slow(sptep
, 0ull);
573 if (!is_shadow_present_pte(old_spte
))
576 pfn
= spte_to_pfn(old_spte
);
579 * KVM does not hold the refcount of the page used by
580 * kvm mmu, before reclaiming the page, we should
581 * unmap it from mmu first.
583 WARN_ON(!kvm_is_reserved_pfn(pfn
) && !page_count(pfn_to_page(pfn
)));
585 if (is_accessed_spte(old_spte
))
586 kvm_set_pfn_accessed(pfn
);
588 if (is_dirty_spte(old_spte
))
589 kvm_set_pfn_dirty(pfn
);
595 * Rules for using mmu_spte_clear_no_track:
596 * Directly clear spte without caring the state bits of sptep,
597 * it is used to set the upper level spte.
599 static void mmu_spte_clear_no_track(u64
*sptep
)
601 __update_clear_spte_fast(sptep
, 0ull);
604 static u64
mmu_spte_get_lockless(u64
*sptep
)
606 return __get_spte_lockless(sptep
);
609 /* Restore an acc-track PTE back to a regular PTE */
610 static u64
restore_acc_track_spte(u64 spte
)
613 u64 saved_bits
= (spte
>> shadow_acc_track_saved_bits_shift
)
614 & shadow_acc_track_saved_bits_mask
;
616 WARN_ON_ONCE(spte_ad_enabled(spte
));
617 WARN_ON_ONCE(!is_access_track_spte(spte
));
619 new_spte
&= ~shadow_acc_track_mask
;
620 new_spte
&= ~(shadow_acc_track_saved_bits_mask
<<
621 shadow_acc_track_saved_bits_shift
);
622 new_spte
|= saved_bits
;
627 /* Returns the Accessed status of the PTE and resets it at the same time. */
628 static bool mmu_spte_age(u64
*sptep
)
630 u64 spte
= mmu_spte_get_lockless(sptep
);
632 if (!is_accessed_spte(spte
))
635 if (spte_ad_enabled(spte
)) {
636 clear_bit((ffs(shadow_accessed_mask
) - 1),
637 (unsigned long *)sptep
);
640 * Capture the dirty status of the page, so that it doesn't get
641 * lost when the SPTE is marked for access tracking.
643 if (is_writable_pte(spte
))
644 kvm_set_pfn_dirty(spte_to_pfn(spte
));
646 spte
= mark_spte_for_access_track(spte
);
647 mmu_spte_update_no_track(sptep
, spte
);
653 static void walk_shadow_page_lockless_begin(struct kvm_vcpu
*vcpu
)
656 * Prevent page table teardown by making any free-er wait during
657 * kvm_flush_remote_tlbs() IPI to all active vcpus.
662 * Make sure a following spte read is not reordered ahead of the write
665 smp_store_mb(vcpu
->mode
, READING_SHADOW_PAGE_TABLES
);
668 static void walk_shadow_page_lockless_end(struct kvm_vcpu
*vcpu
)
671 * Make sure the write to vcpu->mode is not reordered in front of
672 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
673 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
675 smp_store_release(&vcpu
->mode
, OUTSIDE_GUEST_MODE
);
679 static int mmu_topup_memory_caches(struct kvm_vcpu
*vcpu
, bool maybe_indirect
)
683 /* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
684 r
= kvm_mmu_topup_memory_cache(&vcpu
->arch
.mmu_pte_list_desc_cache
,
685 1 + PT64_ROOT_MAX_LEVEL
+ PTE_PREFETCH_NUM
);
688 r
= kvm_mmu_topup_memory_cache(&vcpu
->arch
.mmu_shadow_page_cache
,
689 PT64_ROOT_MAX_LEVEL
);
692 if (maybe_indirect
) {
693 r
= kvm_mmu_topup_memory_cache(&vcpu
->arch
.mmu_gfn_array_cache
,
694 PT64_ROOT_MAX_LEVEL
);
698 return kvm_mmu_topup_memory_cache(&vcpu
->arch
.mmu_page_header_cache
,
699 PT64_ROOT_MAX_LEVEL
);
702 static void mmu_free_memory_caches(struct kvm_vcpu
*vcpu
)
704 kvm_mmu_free_memory_cache(&vcpu
->arch
.mmu_pte_list_desc_cache
);
705 kvm_mmu_free_memory_cache(&vcpu
->arch
.mmu_shadow_page_cache
);
706 kvm_mmu_free_memory_cache(&vcpu
->arch
.mmu_gfn_array_cache
);
707 kvm_mmu_free_memory_cache(&vcpu
->arch
.mmu_page_header_cache
);
710 static struct pte_list_desc
*mmu_alloc_pte_list_desc(struct kvm_vcpu
*vcpu
)
712 return kvm_mmu_memory_cache_alloc(&vcpu
->arch
.mmu_pte_list_desc_cache
);
715 static void mmu_free_pte_list_desc(struct pte_list_desc
*pte_list_desc
)
717 kmem_cache_free(pte_list_desc_cache
, pte_list_desc
);
720 static gfn_t
kvm_mmu_page_get_gfn(struct kvm_mmu_page
*sp
, int index
)
722 if (!sp
->role
.direct
)
723 return sp
->gfns
[index
];
725 return sp
->gfn
+ (index
<< ((sp
->role
.level
- 1) * PT64_LEVEL_BITS
));
728 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page
*sp
, int index
, gfn_t gfn
)
730 if (!sp
->role
.direct
) {
731 sp
->gfns
[index
] = gfn
;
735 if (WARN_ON(gfn
!= kvm_mmu_page_get_gfn(sp
, index
)))
736 pr_err_ratelimited("gfn mismatch under direct page %llx "
737 "(expected %llx, got %llx)\n",
739 kvm_mmu_page_get_gfn(sp
, index
), gfn
);
743 * Return the pointer to the large page information for a given gfn,
744 * handling slots that are not large page aligned.
746 static struct kvm_lpage_info
*lpage_info_slot(gfn_t gfn
,
747 struct kvm_memory_slot
*slot
,
752 idx
= gfn_to_index(gfn
, slot
->base_gfn
, level
);
753 return &slot
->arch
.lpage_info
[level
- 2][idx
];
756 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot
*slot
,
757 gfn_t gfn
, int count
)
759 struct kvm_lpage_info
*linfo
;
762 for (i
= PG_LEVEL_2M
; i
<= KVM_MAX_HUGEPAGE_LEVEL
; ++i
) {
763 linfo
= lpage_info_slot(gfn
, slot
, i
);
764 linfo
->disallow_lpage
+= count
;
765 WARN_ON(linfo
->disallow_lpage
< 0);
769 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot
*slot
, gfn_t gfn
)
771 update_gfn_disallow_lpage_count(slot
, gfn
, 1);
774 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot
*slot
, gfn_t gfn
)
776 update_gfn_disallow_lpage_count(slot
, gfn
, -1);
779 static void account_shadowed(struct kvm
*kvm
, struct kvm_mmu_page
*sp
)
781 struct kvm_memslots
*slots
;
782 struct kvm_memory_slot
*slot
;
785 kvm
->arch
.indirect_shadow_pages
++;
787 slots
= kvm_memslots_for_spte_role(kvm
, sp
->role
);
788 slot
= __gfn_to_memslot(slots
, gfn
);
790 /* the non-leaf shadow pages are keeping readonly. */
791 if (sp
->role
.level
> PG_LEVEL_4K
)
792 return kvm_slot_page_track_add_page(kvm
, slot
, gfn
,
793 KVM_PAGE_TRACK_WRITE
);
795 kvm_mmu_gfn_disallow_lpage(slot
, gfn
);
798 static void account_huge_nx_page(struct kvm
*kvm
, struct kvm_mmu_page
*sp
)
800 if (sp
->lpage_disallowed
)
803 ++kvm
->stat
.nx_lpage_splits
;
804 list_add_tail(&sp
->lpage_disallowed_link
,
805 &kvm
->arch
.lpage_disallowed_mmu_pages
);
806 sp
->lpage_disallowed
= true;
809 static void unaccount_shadowed(struct kvm
*kvm
, struct kvm_mmu_page
*sp
)
811 struct kvm_memslots
*slots
;
812 struct kvm_memory_slot
*slot
;
815 kvm
->arch
.indirect_shadow_pages
--;
817 slots
= kvm_memslots_for_spte_role(kvm
, sp
->role
);
818 slot
= __gfn_to_memslot(slots
, gfn
);
819 if (sp
->role
.level
> PG_LEVEL_4K
)
820 return kvm_slot_page_track_remove_page(kvm
, slot
, gfn
,
821 KVM_PAGE_TRACK_WRITE
);
823 kvm_mmu_gfn_allow_lpage(slot
, gfn
);
826 static void unaccount_huge_nx_page(struct kvm
*kvm
, struct kvm_mmu_page
*sp
)
828 --kvm
->stat
.nx_lpage_splits
;
829 sp
->lpage_disallowed
= false;
830 list_del(&sp
->lpage_disallowed_link
);
833 static struct kvm_memory_slot
*
834 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu
*vcpu
, gfn_t gfn
,
837 struct kvm_memory_slot
*slot
;
839 slot
= kvm_vcpu_gfn_to_memslot(vcpu
, gfn
);
840 if (!slot
|| slot
->flags
& KVM_MEMSLOT_INVALID
)
842 if (no_dirty_log
&& slot
->dirty_bitmap
)
849 * About rmap_head encoding:
851 * If the bit zero of rmap_head->val is clear, then it points to the only spte
852 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
853 * pte_list_desc containing more mappings.
857 * Returns the number of pointers in the rmap chain, not counting the new one.
859 static int pte_list_add(struct kvm_vcpu
*vcpu
, u64
*spte
,
860 struct kvm_rmap_head
*rmap_head
)
862 struct pte_list_desc
*desc
;
865 if (!rmap_head
->val
) {
866 rmap_printk("pte_list_add: %p %llx 0->1\n", spte
, *spte
);
867 rmap_head
->val
= (unsigned long)spte
;
868 } else if (!(rmap_head
->val
& 1)) {
869 rmap_printk("pte_list_add: %p %llx 1->many\n", spte
, *spte
);
870 desc
= mmu_alloc_pte_list_desc(vcpu
);
871 desc
->sptes
[0] = (u64
*)rmap_head
->val
;
872 desc
->sptes
[1] = spte
;
873 rmap_head
->val
= (unsigned long)desc
| 1;
876 rmap_printk("pte_list_add: %p %llx many->many\n", spte
, *spte
);
877 desc
= (struct pte_list_desc
*)(rmap_head
->val
& ~1ul);
878 while (desc
->sptes
[PTE_LIST_EXT
-1] && desc
->more
) {
880 count
+= PTE_LIST_EXT
;
882 if (desc
->sptes
[PTE_LIST_EXT
-1]) {
883 desc
->more
= mmu_alloc_pte_list_desc(vcpu
);
886 for (i
= 0; desc
->sptes
[i
]; ++i
)
888 desc
->sptes
[i
] = spte
;
894 pte_list_desc_remove_entry(struct kvm_rmap_head
*rmap_head
,
895 struct pte_list_desc
*desc
, int i
,
896 struct pte_list_desc
*prev_desc
)
900 for (j
= PTE_LIST_EXT
- 1; !desc
->sptes
[j
] && j
> i
; --j
)
902 desc
->sptes
[i
] = desc
->sptes
[j
];
903 desc
->sptes
[j
] = NULL
;
906 if (!prev_desc
&& !desc
->more
)
910 prev_desc
->more
= desc
->more
;
912 rmap_head
->val
= (unsigned long)desc
->more
| 1;
913 mmu_free_pte_list_desc(desc
);
916 static void __pte_list_remove(u64
*spte
, struct kvm_rmap_head
*rmap_head
)
918 struct pte_list_desc
*desc
;
919 struct pte_list_desc
*prev_desc
;
922 if (!rmap_head
->val
) {
923 pr_err("%s: %p 0->BUG\n", __func__
, spte
);
925 } else if (!(rmap_head
->val
& 1)) {
926 rmap_printk("%s: %p 1->0\n", __func__
, spte
);
927 if ((u64
*)rmap_head
->val
!= spte
) {
928 pr_err("%s: %p 1->BUG\n", __func__
, spte
);
933 rmap_printk("%s: %p many->many\n", __func__
, spte
);
934 desc
= (struct pte_list_desc
*)(rmap_head
->val
& ~1ul);
937 for (i
= 0; i
< PTE_LIST_EXT
&& desc
->sptes
[i
]; ++i
) {
938 if (desc
->sptes
[i
] == spte
) {
939 pte_list_desc_remove_entry(rmap_head
,
947 pr_err("%s: %p many->many\n", __func__
, spte
);
952 static void pte_list_remove(struct kvm_rmap_head
*rmap_head
, u64
*sptep
)
954 mmu_spte_clear_track_bits(sptep
);
955 __pte_list_remove(sptep
, rmap_head
);
958 static struct kvm_rmap_head
*__gfn_to_rmap(gfn_t gfn
, int level
,
959 struct kvm_memory_slot
*slot
)
963 idx
= gfn_to_index(gfn
, slot
->base_gfn
, level
);
964 return &slot
->arch
.rmap
[level
- PG_LEVEL_4K
][idx
];
967 static struct kvm_rmap_head
*gfn_to_rmap(struct kvm
*kvm
, gfn_t gfn
,
968 struct kvm_mmu_page
*sp
)
970 struct kvm_memslots
*slots
;
971 struct kvm_memory_slot
*slot
;
973 slots
= kvm_memslots_for_spte_role(kvm
, sp
->role
);
974 slot
= __gfn_to_memslot(slots
, gfn
);
975 return __gfn_to_rmap(gfn
, sp
->role
.level
, slot
);
978 static bool rmap_can_add(struct kvm_vcpu
*vcpu
)
980 struct kvm_mmu_memory_cache
*mc
;
982 mc
= &vcpu
->arch
.mmu_pte_list_desc_cache
;
983 return kvm_mmu_memory_cache_nr_free_objects(mc
);
986 static int rmap_add(struct kvm_vcpu
*vcpu
, u64
*spte
, gfn_t gfn
)
988 struct kvm_mmu_page
*sp
;
989 struct kvm_rmap_head
*rmap_head
;
991 sp
= sptep_to_sp(spte
);
992 kvm_mmu_page_set_gfn(sp
, spte
- sp
->spt
, gfn
);
993 rmap_head
= gfn_to_rmap(vcpu
->kvm
, gfn
, sp
);
994 return pte_list_add(vcpu
, spte
, rmap_head
);
997 static void rmap_remove(struct kvm
*kvm
, u64
*spte
)
999 struct kvm_mmu_page
*sp
;
1001 struct kvm_rmap_head
*rmap_head
;
1003 sp
= sptep_to_sp(spte
);
1004 gfn
= kvm_mmu_page_get_gfn(sp
, spte
- sp
->spt
);
1005 rmap_head
= gfn_to_rmap(kvm
, gfn
, sp
);
1006 __pte_list_remove(spte
, rmap_head
);
1010 * Used by the following functions to iterate through the sptes linked by a
1011 * rmap. All fields are private and not assumed to be used outside.
1013 struct rmap_iterator
{
1014 /* private fields */
1015 struct pte_list_desc
*desc
; /* holds the sptep if not NULL */
1016 int pos
; /* index of the sptep */
1020 * Iteration must be started by this function. This should also be used after
1021 * removing/dropping sptes from the rmap link because in such cases the
1022 * information in the iterator may not be valid.
1024 * Returns sptep if found, NULL otherwise.
1026 static u64
*rmap_get_first(struct kvm_rmap_head
*rmap_head
,
1027 struct rmap_iterator
*iter
)
1031 if (!rmap_head
->val
)
1034 if (!(rmap_head
->val
& 1)) {
1036 sptep
= (u64
*)rmap_head
->val
;
1040 iter
->desc
= (struct pte_list_desc
*)(rmap_head
->val
& ~1ul);
1042 sptep
= iter
->desc
->sptes
[iter
->pos
];
1044 BUG_ON(!is_shadow_present_pte(*sptep
));
1049 * Must be used with a valid iterator: e.g. after rmap_get_first().
1051 * Returns sptep if found, NULL otherwise.
1053 static u64
*rmap_get_next(struct rmap_iterator
*iter
)
1058 if (iter
->pos
< PTE_LIST_EXT
- 1) {
1060 sptep
= iter
->desc
->sptes
[iter
->pos
];
1065 iter
->desc
= iter
->desc
->more
;
1069 /* desc->sptes[0] cannot be NULL */
1070 sptep
= iter
->desc
->sptes
[iter
->pos
];
1077 BUG_ON(!is_shadow_present_pte(*sptep
));
1081 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1082 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1083 _spte_; _spte_ = rmap_get_next(_iter_))
1085 static void drop_spte(struct kvm
*kvm
, u64
*sptep
)
1087 if (mmu_spte_clear_track_bits(sptep
))
1088 rmap_remove(kvm
, sptep
);
1092 static bool __drop_large_spte(struct kvm
*kvm
, u64
*sptep
)
1094 if (is_large_pte(*sptep
)) {
1095 WARN_ON(sptep_to_sp(sptep
)->role
.level
== PG_LEVEL_4K
);
1096 drop_spte(kvm
, sptep
);
1104 static void drop_large_spte(struct kvm_vcpu
*vcpu
, u64
*sptep
)
1106 if (__drop_large_spte(vcpu
->kvm
, sptep
)) {
1107 struct kvm_mmu_page
*sp
= sptep_to_sp(sptep
);
1109 kvm_flush_remote_tlbs_with_address(vcpu
->kvm
, sp
->gfn
,
1110 KVM_PAGES_PER_HPAGE(sp
->role
.level
));
1115 * Write-protect on the specified @sptep, @pt_protect indicates whether
1116 * spte write-protection is caused by protecting shadow page table.
1118 * Note: write protection is difference between dirty logging and spte
1120 * - for dirty logging, the spte can be set to writable at anytime if
1121 * its dirty bitmap is properly set.
1122 * - for spte protection, the spte can be writable only after unsync-ing
1125 * Return true if tlb need be flushed.
1127 static bool spte_write_protect(u64
*sptep
, bool pt_protect
)
1131 if (!is_writable_pte(spte
) &&
1132 !(pt_protect
&& spte_can_locklessly_be_made_writable(spte
)))
1135 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep
, *sptep
);
1138 spte
&= ~SPTE_MMU_WRITEABLE
;
1139 spte
= spte
& ~PT_WRITABLE_MASK
;
1141 return mmu_spte_update(sptep
, spte
);
1144 static bool __rmap_write_protect(struct kvm
*kvm
,
1145 struct kvm_rmap_head
*rmap_head
,
1149 struct rmap_iterator iter
;
1152 for_each_rmap_spte(rmap_head
, &iter
, sptep
)
1153 flush
|= spte_write_protect(sptep
, pt_protect
);
1158 static bool spte_clear_dirty(u64
*sptep
)
1162 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep
, *sptep
);
1164 MMU_WARN_ON(!spte_ad_enabled(spte
));
1165 spte
&= ~shadow_dirty_mask
;
1166 return mmu_spte_update(sptep
, spte
);
1169 static bool spte_wrprot_for_clear_dirty(u64
*sptep
)
1171 bool was_writable
= test_and_clear_bit(PT_WRITABLE_SHIFT
,
1172 (unsigned long *)sptep
);
1173 if (was_writable
&& !spte_ad_enabled(*sptep
))
1174 kvm_set_pfn_dirty(spte_to_pfn(*sptep
));
1176 return was_writable
;
1180 * Gets the GFN ready for another round of dirty logging by clearing the
1181 * - D bit on ad-enabled SPTEs, and
1182 * - W bit on ad-disabled SPTEs.
1183 * Returns true iff any D or W bits were cleared.
1185 static bool __rmap_clear_dirty(struct kvm
*kvm
, struct kvm_rmap_head
*rmap_head
)
1188 struct rmap_iterator iter
;
1191 for_each_rmap_spte(rmap_head
, &iter
, sptep
)
1192 if (spte_ad_need_write_protect(*sptep
))
1193 flush
|= spte_wrprot_for_clear_dirty(sptep
);
1195 flush
|= spte_clear_dirty(sptep
);
1200 static bool spte_set_dirty(u64
*sptep
)
1204 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep
, *sptep
);
1207 * Similar to the !kvm_x86_ops.slot_disable_log_dirty case,
1208 * do not bother adding back write access to pages marked
1209 * SPTE_AD_WRPROT_ONLY_MASK.
1211 spte
|= shadow_dirty_mask
;
1213 return mmu_spte_update(sptep
, spte
);
1216 static bool __rmap_set_dirty(struct kvm
*kvm
, struct kvm_rmap_head
*rmap_head
)
1219 struct rmap_iterator iter
;
1222 for_each_rmap_spte(rmap_head
, &iter
, sptep
)
1223 if (spte_ad_enabled(*sptep
))
1224 flush
|= spte_set_dirty(sptep
);
1230 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1231 * @kvm: kvm instance
1232 * @slot: slot to protect
1233 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1234 * @mask: indicates which pages we should protect
1236 * Used when we do not need to care about huge page mappings: e.g. during dirty
1237 * logging we do not have any such mappings.
1239 static void kvm_mmu_write_protect_pt_masked(struct kvm
*kvm
,
1240 struct kvm_memory_slot
*slot
,
1241 gfn_t gfn_offset
, unsigned long mask
)
1243 struct kvm_rmap_head
*rmap_head
;
1246 rmap_head
= __gfn_to_rmap(slot
->base_gfn
+ gfn_offset
+ __ffs(mask
),
1248 __rmap_write_protect(kvm
, rmap_head
, false);
1250 /* clear the first set bit */
1256 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1257 * protect the page if the D-bit isn't supported.
1258 * @kvm: kvm instance
1259 * @slot: slot to clear D-bit
1260 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1261 * @mask: indicates which pages we should clear D-bit
1263 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1265 void kvm_mmu_clear_dirty_pt_masked(struct kvm
*kvm
,
1266 struct kvm_memory_slot
*slot
,
1267 gfn_t gfn_offset
, unsigned long mask
)
1269 struct kvm_rmap_head
*rmap_head
;
1272 rmap_head
= __gfn_to_rmap(slot
->base_gfn
+ gfn_offset
+ __ffs(mask
),
1274 __rmap_clear_dirty(kvm
, rmap_head
);
1276 /* clear the first set bit */
1280 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked
);
1283 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1286 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1287 * enable dirty logging for them.
1289 * Used when we do not need to care about huge page mappings: e.g. during dirty
1290 * logging we do not have any such mappings.
1292 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm
*kvm
,
1293 struct kvm_memory_slot
*slot
,
1294 gfn_t gfn_offset
, unsigned long mask
)
1296 if (kvm_x86_ops
.enable_log_dirty_pt_masked
)
1297 kvm_x86_ops
.enable_log_dirty_pt_masked(kvm
, slot
, gfn_offset
,
1300 kvm_mmu_write_protect_pt_masked(kvm
, slot
, gfn_offset
, mask
);
1303 bool kvm_mmu_slot_gfn_write_protect(struct kvm
*kvm
,
1304 struct kvm_memory_slot
*slot
, u64 gfn
)
1306 struct kvm_rmap_head
*rmap_head
;
1308 bool write_protected
= false;
1310 for (i
= PG_LEVEL_4K
; i
<= KVM_MAX_HUGEPAGE_LEVEL
; ++i
) {
1311 rmap_head
= __gfn_to_rmap(gfn
, i
, slot
);
1312 write_protected
|= __rmap_write_protect(kvm
, rmap_head
, true);
1315 return write_protected
;
1318 static bool rmap_write_protect(struct kvm_vcpu
*vcpu
, u64 gfn
)
1320 struct kvm_memory_slot
*slot
;
1322 slot
= kvm_vcpu_gfn_to_memslot(vcpu
, gfn
);
1323 return kvm_mmu_slot_gfn_write_protect(vcpu
->kvm
, slot
, gfn
);
1326 static bool kvm_zap_rmapp(struct kvm
*kvm
, struct kvm_rmap_head
*rmap_head
)
1329 struct rmap_iterator iter
;
1332 while ((sptep
= rmap_get_first(rmap_head
, &iter
))) {
1333 rmap_printk("%s: spte %p %llx.\n", __func__
, sptep
, *sptep
);
1335 pte_list_remove(rmap_head
, sptep
);
1342 static int kvm_unmap_rmapp(struct kvm
*kvm
, struct kvm_rmap_head
*rmap_head
,
1343 struct kvm_memory_slot
*slot
, gfn_t gfn
, int level
,
1346 return kvm_zap_rmapp(kvm
, rmap_head
);
1349 static int kvm_set_pte_rmapp(struct kvm
*kvm
, struct kvm_rmap_head
*rmap_head
,
1350 struct kvm_memory_slot
*slot
, gfn_t gfn
, int level
,
1354 struct rmap_iterator iter
;
1357 pte_t
*ptep
= (pte_t
*)data
;
1360 WARN_ON(pte_huge(*ptep
));
1361 new_pfn
= pte_pfn(*ptep
);
1364 for_each_rmap_spte(rmap_head
, &iter
, sptep
) {
1365 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1366 sptep
, *sptep
, gfn
, level
);
1370 if (pte_write(*ptep
)) {
1371 pte_list_remove(rmap_head
, sptep
);
1374 new_spte
= kvm_mmu_changed_pte_notifier_make_spte(
1377 mmu_spte_clear_track_bits(sptep
);
1378 mmu_spte_set(sptep
, new_spte
);
1382 if (need_flush
&& kvm_available_flush_tlb_with_range()) {
1383 kvm_flush_remote_tlbs_with_address(kvm
, gfn
, 1);
1390 struct slot_rmap_walk_iterator
{
1392 struct kvm_memory_slot
*slot
;
1398 /* output fields. */
1400 struct kvm_rmap_head
*rmap
;
1403 /* private field. */
1404 struct kvm_rmap_head
*end_rmap
;
1408 rmap_walk_init_level(struct slot_rmap_walk_iterator
*iterator
, int level
)
1410 iterator
->level
= level
;
1411 iterator
->gfn
= iterator
->start_gfn
;
1412 iterator
->rmap
= __gfn_to_rmap(iterator
->gfn
, level
, iterator
->slot
);
1413 iterator
->end_rmap
= __gfn_to_rmap(iterator
->end_gfn
, level
,
1418 slot_rmap_walk_init(struct slot_rmap_walk_iterator
*iterator
,
1419 struct kvm_memory_slot
*slot
, int start_level
,
1420 int end_level
, gfn_t start_gfn
, gfn_t end_gfn
)
1422 iterator
->slot
= slot
;
1423 iterator
->start_level
= start_level
;
1424 iterator
->end_level
= end_level
;
1425 iterator
->start_gfn
= start_gfn
;
1426 iterator
->end_gfn
= end_gfn
;
1428 rmap_walk_init_level(iterator
, iterator
->start_level
);
1431 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator
*iterator
)
1433 return !!iterator
->rmap
;
1436 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator
*iterator
)
1438 if (++iterator
->rmap
<= iterator
->end_rmap
) {
1439 iterator
->gfn
+= (1UL << KVM_HPAGE_GFN_SHIFT(iterator
->level
));
1443 if (++iterator
->level
> iterator
->end_level
) {
1444 iterator
->rmap
= NULL
;
1448 rmap_walk_init_level(iterator
, iterator
->level
);
1451 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1452 _start_gfn, _end_gfn, _iter_) \
1453 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1454 _end_level_, _start_gfn, _end_gfn); \
1455 slot_rmap_walk_okay(_iter_); \
1456 slot_rmap_walk_next(_iter_))
1458 static int kvm_handle_hva_range(struct kvm
*kvm
,
1459 unsigned long start
,
1462 int (*handler
)(struct kvm
*kvm
,
1463 struct kvm_rmap_head
*rmap_head
,
1464 struct kvm_memory_slot
*slot
,
1467 unsigned long data
))
1469 struct kvm_memslots
*slots
;
1470 struct kvm_memory_slot
*memslot
;
1471 struct slot_rmap_walk_iterator iterator
;
1475 for (i
= 0; i
< KVM_ADDRESS_SPACE_NUM
; i
++) {
1476 slots
= __kvm_memslots(kvm
, i
);
1477 kvm_for_each_memslot(memslot
, slots
) {
1478 unsigned long hva_start
, hva_end
;
1479 gfn_t gfn_start
, gfn_end
;
1481 hva_start
= max(start
, memslot
->userspace_addr
);
1482 hva_end
= min(end
, memslot
->userspace_addr
+
1483 (memslot
->npages
<< PAGE_SHIFT
));
1484 if (hva_start
>= hva_end
)
1487 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1488 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1490 gfn_start
= hva_to_gfn_memslot(hva_start
, memslot
);
1491 gfn_end
= hva_to_gfn_memslot(hva_end
+ PAGE_SIZE
- 1, memslot
);
1493 for_each_slot_rmap_range(memslot
, PG_LEVEL_4K
,
1494 KVM_MAX_HUGEPAGE_LEVEL
,
1495 gfn_start
, gfn_end
- 1,
1497 ret
|= handler(kvm
, iterator
.rmap
, memslot
,
1498 iterator
.gfn
, iterator
.level
, data
);
1505 static int kvm_handle_hva(struct kvm
*kvm
, unsigned long hva
,
1507 int (*handler
)(struct kvm
*kvm
,
1508 struct kvm_rmap_head
*rmap_head
,
1509 struct kvm_memory_slot
*slot
,
1510 gfn_t gfn
, int level
,
1511 unsigned long data
))
1513 return kvm_handle_hva_range(kvm
, hva
, hva
+ 1, data
, handler
);
1516 int kvm_unmap_hva_range(struct kvm
*kvm
, unsigned long start
, unsigned long end
,
1519 return kvm_handle_hva_range(kvm
, start
, end
, 0, kvm_unmap_rmapp
);
1522 int kvm_set_spte_hva(struct kvm
*kvm
, unsigned long hva
, pte_t pte
)
1524 return kvm_handle_hva(kvm
, hva
, (unsigned long)&pte
, kvm_set_pte_rmapp
);
1527 static int kvm_age_rmapp(struct kvm
*kvm
, struct kvm_rmap_head
*rmap_head
,
1528 struct kvm_memory_slot
*slot
, gfn_t gfn
, int level
,
1532 struct rmap_iterator iter
;
1535 for_each_rmap_spte(rmap_head
, &iter
, sptep
)
1536 young
|= mmu_spte_age(sptep
);
1538 trace_kvm_age_page(gfn
, level
, slot
, young
);
1542 static int kvm_test_age_rmapp(struct kvm
*kvm
, struct kvm_rmap_head
*rmap_head
,
1543 struct kvm_memory_slot
*slot
, gfn_t gfn
,
1544 int level
, unsigned long data
)
1547 struct rmap_iterator iter
;
1549 for_each_rmap_spte(rmap_head
, &iter
, sptep
)
1550 if (is_accessed_spte(*sptep
))
1555 #define RMAP_RECYCLE_THRESHOLD 1000
1557 static void rmap_recycle(struct kvm_vcpu
*vcpu
, u64
*spte
, gfn_t gfn
)
1559 struct kvm_rmap_head
*rmap_head
;
1560 struct kvm_mmu_page
*sp
;
1562 sp
= sptep_to_sp(spte
);
1564 rmap_head
= gfn_to_rmap(vcpu
->kvm
, gfn
, sp
);
1566 kvm_unmap_rmapp(vcpu
->kvm
, rmap_head
, NULL
, gfn
, sp
->role
.level
, 0);
1567 kvm_flush_remote_tlbs_with_address(vcpu
->kvm
, sp
->gfn
,
1568 KVM_PAGES_PER_HPAGE(sp
->role
.level
));
1571 int kvm_age_hva(struct kvm
*kvm
, unsigned long start
, unsigned long end
)
1573 return kvm_handle_hva_range(kvm
, start
, end
, 0, kvm_age_rmapp
);
1576 int kvm_test_age_hva(struct kvm
*kvm
, unsigned long hva
)
1578 return kvm_handle_hva(kvm
, hva
, 0, kvm_test_age_rmapp
);
1582 static int is_empty_shadow_page(u64
*spt
)
1587 for (pos
= spt
, end
= pos
+ PAGE_SIZE
/ sizeof(u64
); pos
!= end
; pos
++)
1588 if (is_shadow_present_pte(*pos
)) {
1589 printk(KERN_ERR
"%s: %p %llx\n", __func__
,
1598 * This value is the sum of all of the kvm instances's
1599 * kvm->arch.n_used_mmu_pages values. We need a global,
1600 * aggregate version in order to make the slab shrinker
1603 static inline void kvm_mod_used_mmu_pages(struct kvm
*kvm
, unsigned long nr
)
1605 kvm
->arch
.n_used_mmu_pages
+= nr
;
1606 percpu_counter_add(&kvm_total_used_mmu_pages
, nr
);
1609 static void kvm_mmu_free_page(struct kvm_mmu_page
*sp
)
1611 MMU_WARN_ON(!is_empty_shadow_page(sp
->spt
));
1612 hlist_del(&sp
->hash_link
);
1613 list_del(&sp
->link
);
1614 free_page((unsigned long)sp
->spt
);
1615 if (!sp
->role
.direct
)
1616 free_page((unsigned long)sp
->gfns
);
1617 kmem_cache_free(mmu_page_header_cache
, sp
);
1620 static unsigned kvm_page_table_hashfn(gfn_t gfn
)
1622 return hash_64(gfn
, KVM_MMU_HASH_SHIFT
);
1625 static void mmu_page_add_parent_pte(struct kvm_vcpu
*vcpu
,
1626 struct kvm_mmu_page
*sp
, u64
*parent_pte
)
1631 pte_list_add(vcpu
, parent_pte
, &sp
->parent_ptes
);
1634 static void mmu_page_remove_parent_pte(struct kvm_mmu_page
*sp
,
1637 __pte_list_remove(parent_pte
, &sp
->parent_ptes
);
1640 static void drop_parent_pte(struct kvm_mmu_page
*sp
,
1643 mmu_page_remove_parent_pte(sp
, parent_pte
);
1644 mmu_spte_clear_no_track(parent_pte
);
1647 static struct kvm_mmu_page
*kvm_mmu_alloc_page(struct kvm_vcpu
*vcpu
, int direct
)
1649 struct kvm_mmu_page
*sp
;
1651 sp
= kvm_mmu_memory_cache_alloc(&vcpu
->arch
.mmu_page_header_cache
);
1652 sp
->spt
= kvm_mmu_memory_cache_alloc(&vcpu
->arch
.mmu_shadow_page_cache
);
1654 sp
->gfns
= kvm_mmu_memory_cache_alloc(&vcpu
->arch
.mmu_gfn_array_cache
);
1655 set_page_private(virt_to_page(sp
->spt
), (unsigned long)sp
);
1658 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
1659 * depends on valid pages being added to the head of the list. See
1660 * comments in kvm_zap_obsolete_pages().
1662 sp
->mmu_valid_gen
= vcpu
->kvm
->arch
.mmu_valid_gen
;
1663 list_add(&sp
->link
, &vcpu
->kvm
->arch
.active_mmu_pages
);
1664 kvm_mod_used_mmu_pages(vcpu
->kvm
, +1);
1668 static void mark_unsync(u64
*spte
);
1669 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page
*sp
)
1672 struct rmap_iterator iter
;
1674 for_each_rmap_spte(&sp
->parent_ptes
, &iter
, sptep
) {
1679 static void mark_unsync(u64
*spte
)
1681 struct kvm_mmu_page
*sp
;
1684 sp
= sptep_to_sp(spte
);
1685 index
= spte
- sp
->spt
;
1686 if (__test_and_set_bit(index
, sp
->unsync_child_bitmap
))
1688 if (sp
->unsync_children
++)
1690 kvm_mmu_mark_parents_unsync(sp
);
1693 static int nonpaging_sync_page(struct kvm_vcpu
*vcpu
,
1694 struct kvm_mmu_page
*sp
)
1699 static void nonpaging_update_pte(struct kvm_vcpu
*vcpu
,
1700 struct kvm_mmu_page
*sp
, u64
*spte
,
1706 #define KVM_PAGE_ARRAY_NR 16
1708 struct kvm_mmu_pages
{
1709 struct mmu_page_and_offset
{
1710 struct kvm_mmu_page
*sp
;
1712 } page
[KVM_PAGE_ARRAY_NR
];
1716 static int mmu_pages_add(struct kvm_mmu_pages
*pvec
, struct kvm_mmu_page
*sp
,
1722 for (i
=0; i
< pvec
->nr
; i
++)
1723 if (pvec
->page
[i
].sp
== sp
)
1726 pvec
->page
[pvec
->nr
].sp
= sp
;
1727 pvec
->page
[pvec
->nr
].idx
= idx
;
1729 return (pvec
->nr
== KVM_PAGE_ARRAY_NR
);
1732 static inline void clear_unsync_child_bit(struct kvm_mmu_page
*sp
, int idx
)
1734 --sp
->unsync_children
;
1735 WARN_ON((int)sp
->unsync_children
< 0);
1736 __clear_bit(idx
, sp
->unsync_child_bitmap
);
1739 static int __mmu_unsync_walk(struct kvm_mmu_page
*sp
,
1740 struct kvm_mmu_pages
*pvec
)
1742 int i
, ret
, nr_unsync_leaf
= 0;
1744 for_each_set_bit(i
, sp
->unsync_child_bitmap
, 512) {
1745 struct kvm_mmu_page
*child
;
1746 u64 ent
= sp
->spt
[i
];
1748 if (!is_shadow_present_pte(ent
) || is_large_pte(ent
)) {
1749 clear_unsync_child_bit(sp
, i
);
1753 child
= to_shadow_page(ent
& PT64_BASE_ADDR_MASK
);
1755 if (child
->unsync_children
) {
1756 if (mmu_pages_add(pvec
, child
, i
))
1759 ret
= __mmu_unsync_walk(child
, pvec
);
1761 clear_unsync_child_bit(sp
, i
);
1763 } else if (ret
> 0) {
1764 nr_unsync_leaf
+= ret
;
1767 } else if (child
->unsync
) {
1769 if (mmu_pages_add(pvec
, child
, i
))
1772 clear_unsync_child_bit(sp
, i
);
1775 return nr_unsync_leaf
;
1778 #define INVALID_INDEX (-1)
1780 static int mmu_unsync_walk(struct kvm_mmu_page
*sp
,
1781 struct kvm_mmu_pages
*pvec
)
1784 if (!sp
->unsync_children
)
1787 mmu_pages_add(pvec
, sp
, INVALID_INDEX
);
1788 return __mmu_unsync_walk(sp
, pvec
);
1791 static void kvm_unlink_unsync_page(struct kvm
*kvm
, struct kvm_mmu_page
*sp
)
1793 WARN_ON(!sp
->unsync
);
1794 trace_kvm_mmu_sync_page(sp
);
1796 --kvm
->stat
.mmu_unsync
;
1799 static bool kvm_mmu_prepare_zap_page(struct kvm
*kvm
, struct kvm_mmu_page
*sp
,
1800 struct list_head
*invalid_list
);
1801 static void kvm_mmu_commit_zap_page(struct kvm
*kvm
,
1802 struct list_head
*invalid_list
);
1804 #define for_each_valid_sp(_kvm, _sp, _list) \
1805 hlist_for_each_entry(_sp, _list, hash_link) \
1806 if (is_obsolete_sp((_kvm), (_sp))) { \
1809 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
1810 for_each_valid_sp(_kvm, _sp, \
1811 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
1812 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
1814 static inline bool is_ept_sp(struct kvm_mmu_page
*sp
)
1816 return sp
->role
.cr0_wp
&& sp
->role
.smap_andnot_wp
;
1819 /* @sp->gfn should be write-protected at the call site */
1820 static bool __kvm_sync_page(struct kvm_vcpu
*vcpu
, struct kvm_mmu_page
*sp
,
1821 struct list_head
*invalid_list
)
1823 if ((!is_ept_sp(sp
) && sp
->role
.gpte_is_8_bytes
!= !!is_pae(vcpu
)) ||
1824 vcpu
->arch
.mmu
->sync_page(vcpu
, sp
) == 0) {
1825 kvm_mmu_prepare_zap_page(vcpu
->kvm
, sp
, invalid_list
);
1832 static bool kvm_mmu_remote_flush_or_zap(struct kvm
*kvm
,
1833 struct list_head
*invalid_list
,
1836 if (!remote_flush
&& list_empty(invalid_list
))
1839 if (!list_empty(invalid_list
))
1840 kvm_mmu_commit_zap_page(kvm
, invalid_list
);
1842 kvm_flush_remote_tlbs(kvm
);
1846 static void kvm_mmu_flush_or_zap(struct kvm_vcpu
*vcpu
,
1847 struct list_head
*invalid_list
,
1848 bool remote_flush
, bool local_flush
)
1850 if (kvm_mmu_remote_flush_or_zap(vcpu
->kvm
, invalid_list
, remote_flush
))
1854 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT
, vcpu
);
1857 #ifdef CONFIG_KVM_MMU_AUDIT
1858 #include "mmu_audit.c"
1860 static void kvm_mmu_audit(struct kvm_vcpu
*vcpu
, int point
) { }
1861 static void mmu_audit_disable(void) { }
1864 static bool is_obsolete_sp(struct kvm
*kvm
, struct kvm_mmu_page
*sp
)
1866 return sp
->role
.invalid
||
1867 unlikely(sp
->mmu_valid_gen
!= kvm
->arch
.mmu_valid_gen
);
1870 static bool kvm_sync_page(struct kvm_vcpu
*vcpu
, struct kvm_mmu_page
*sp
,
1871 struct list_head
*invalid_list
)
1873 kvm_unlink_unsync_page(vcpu
->kvm
, sp
);
1874 return __kvm_sync_page(vcpu
, sp
, invalid_list
);
1877 /* @gfn should be write-protected at the call site */
1878 static bool kvm_sync_pages(struct kvm_vcpu
*vcpu
, gfn_t gfn
,
1879 struct list_head
*invalid_list
)
1881 struct kvm_mmu_page
*s
;
1884 for_each_gfn_indirect_valid_sp(vcpu
->kvm
, s
, gfn
) {
1888 WARN_ON(s
->role
.level
!= PG_LEVEL_4K
);
1889 ret
|= kvm_sync_page(vcpu
, s
, invalid_list
);
1895 struct mmu_page_path
{
1896 struct kvm_mmu_page
*parent
[PT64_ROOT_MAX_LEVEL
];
1897 unsigned int idx
[PT64_ROOT_MAX_LEVEL
];
1900 #define for_each_sp(pvec, sp, parents, i) \
1901 for (i = mmu_pages_first(&pvec, &parents); \
1902 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
1903 i = mmu_pages_next(&pvec, &parents, i))
1905 static int mmu_pages_next(struct kvm_mmu_pages
*pvec
,
1906 struct mmu_page_path
*parents
,
1911 for (n
= i
+1; n
< pvec
->nr
; n
++) {
1912 struct kvm_mmu_page
*sp
= pvec
->page
[n
].sp
;
1913 unsigned idx
= pvec
->page
[n
].idx
;
1914 int level
= sp
->role
.level
;
1916 parents
->idx
[level
-1] = idx
;
1917 if (level
== PG_LEVEL_4K
)
1920 parents
->parent
[level
-2] = sp
;
1926 static int mmu_pages_first(struct kvm_mmu_pages
*pvec
,
1927 struct mmu_page_path
*parents
)
1929 struct kvm_mmu_page
*sp
;
1935 WARN_ON(pvec
->page
[0].idx
!= INVALID_INDEX
);
1937 sp
= pvec
->page
[0].sp
;
1938 level
= sp
->role
.level
;
1939 WARN_ON(level
== PG_LEVEL_4K
);
1941 parents
->parent
[level
-2] = sp
;
1943 /* Also set up a sentinel. Further entries in pvec are all
1944 * children of sp, so this element is never overwritten.
1946 parents
->parent
[level
-1] = NULL
;
1947 return mmu_pages_next(pvec
, parents
, 0);
1950 static void mmu_pages_clear_parents(struct mmu_page_path
*parents
)
1952 struct kvm_mmu_page
*sp
;
1953 unsigned int level
= 0;
1956 unsigned int idx
= parents
->idx
[level
];
1957 sp
= parents
->parent
[level
];
1961 WARN_ON(idx
== INVALID_INDEX
);
1962 clear_unsync_child_bit(sp
, idx
);
1964 } while (!sp
->unsync_children
);
1967 static void mmu_sync_children(struct kvm_vcpu
*vcpu
,
1968 struct kvm_mmu_page
*parent
)
1971 struct kvm_mmu_page
*sp
;
1972 struct mmu_page_path parents
;
1973 struct kvm_mmu_pages pages
;
1974 LIST_HEAD(invalid_list
);
1977 while (mmu_unsync_walk(parent
, &pages
)) {
1978 bool protected = false;
1980 for_each_sp(pages
, sp
, parents
, i
)
1981 protected |= rmap_write_protect(vcpu
, sp
->gfn
);
1984 kvm_flush_remote_tlbs(vcpu
->kvm
);
1988 for_each_sp(pages
, sp
, parents
, i
) {
1989 flush
|= kvm_sync_page(vcpu
, sp
, &invalid_list
);
1990 mmu_pages_clear_parents(&parents
);
1992 if (need_resched() || spin_needbreak(&vcpu
->kvm
->mmu_lock
)) {
1993 kvm_mmu_flush_or_zap(vcpu
, &invalid_list
, false, flush
);
1994 cond_resched_lock(&vcpu
->kvm
->mmu_lock
);
1999 kvm_mmu_flush_or_zap(vcpu
, &invalid_list
, false, flush
);
2002 static void __clear_sp_write_flooding_count(struct kvm_mmu_page
*sp
)
2004 atomic_set(&sp
->write_flooding_count
, 0);
2007 static void clear_sp_write_flooding_count(u64
*spte
)
2009 __clear_sp_write_flooding_count(sptep_to_sp(spte
));
2012 static struct kvm_mmu_page
*kvm_mmu_get_page(struct kvm_vcpu
*vcpu
,
2017 unsigned int access
)
2019 bool direct_mmu
= vcpu
->arch
.mmu
->direct_map
;
2020 union kvm_mmu_page_role role
;
2021 struct hlist_head
*sp_list
;
2023 struct kvm_mmu_page
*sp
;
2024 bool need_sync
= false;
2027 LIST_HEAD(invalid_list
);
2029 role
= vcpu
->arch
.mmu
->mmu_role
.base
;
2031 role
.direct
= direct
;
2033 role
.gpte_is_8_bytes
= true;
2034 role
.access
= access
;
2035 if (!direct_mmu
&& vcpu
->arch
.mmu
->root_level
<= PT32_ROOT_LEVEL
) {
2036 quadrant
= gaddr
>> (PAGE_SHIFT
+ (PT64_PT_BITS
* level
));
2037 quadrant
&= (1 << ((PT32_PT_BITS
- PT64_PT_BITS
) * level
)) - 1;
2038 role
.quadrant
= quadrant
;
2041 sp_list
= &vcpu
->kvm
->arch
.mmu_page_hash
[kvm_page_table_hashfn(gfn
)];
2042 for_each_valid_sp(vcpu
->kvm
, sp
, sp_list
) {
2043 if (sp
->gfn
!= gfn
) {
2048 if (!need_sync
&& sp
->unsync
)
2051 if (sp
->role
.word
!= role
.word
)
2055 goto trace_get_page
;
2058 /* The page is good, but __kvm_sync_page might still end
2059 * up zapping it. If so, break in order to rebuild it.
2061 if (!__kvm_sync_page(vcpu
, sp
, &invalid_list
))
2064 WARN_ON(!list_empty(&invalid_list
));
2065 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT
, vcpu
);
2068 if (sp
->unsync_children
)
2069 kvm_make_request(KVM_REQ_MMU_SYNC
, vcpu
);
2071 __clear_sp_write_flooding_count(sp
);
2074 trace_kvm_mmu_get_page(sp
, false);
2078 ++vcpu
->kvm
->stat
.mmu_cache_miss
;
2080 sp
= kvm_mmu_alloc_page(vcpu
, direct
);
2084 hlist_add_head(&sp
->hash_link
, sp_list
);
2087 * we should do write protection before syncing pages
2088 * otherwise the content of the synced shadow page may
2089 * be inconsistent with guest page table.
2091 account_shadowed(vcpu
->kvm
, sp
);
2092 if (level
== PG_LEVEL_4K
&& rmap_write_protect(vcpu
, gfn
))
2093 kvm_flush_remote_tlbs_with_address(vcpu
->kvm
, gfn
, 1);
2095 if (level
> PG_LEVEL_4K
&& need_sync
)
2096 flush
|= kvm_sync_pages(vcpu
, gfn
, &invalid_list
);
2098 trace_kvm_mmu_get_page(sp
, true);
2100 kvm_mmu_flush_or_zap(vcpu
, &invalid_list
, false, flush
);
2102 if (collisions
> vcpu
->kvm
->stat
.max_mmu_page_hash_collisions
)
2103 vcpu
->kvm
->stat
.max_mmu_page_hash_collisions
= collisions
;
2107 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator
*iterator
,
2108 struct kvm_vcpu
*vcpu
, hpa_t root
,
2111 iterator
->addr
= addr
;
2112 iterator
->shadow_addr
= root
;
2113 iterator
->level
= vcpu
->arch
.mmu
->shadow_root_level
;
2115 if (iterator
->level
== PT64_ROOT_4LEVEL
&&
2116 vcpu
->arch
.mmu
->root_level
< PT64_ROOT_4LEVEL
&&
2117 !vcpu
->arch
.mmu
->direct_map
)
2120 if (iterator
->level
== PT32E_ROOT_LEVEL
) {
2122 * prev_root is currently only used for 64-bit hosts. So only
2123 * the active root_hpa is valid here.
2125 BUG_ON(root
!= vcpu
->arch
.mmu
->root_hpa
);
2127 iterator
->shadow_addr
2128 = vcpu
->arch
.mmu
->pae_root
[(addr
>> 30) & 3];
2129 iterator
->shadow_addr
&= PT64_BASE_ADDR_MASK
;
2131 if (!iterator
->shadow_addr
)
2132 iterator
->level
= 0;
2136 static void shadow_walk_init(struct kvm_shadow_walk_iterator
*iterator
,
2137 struct kvm_vcpu
*vcpu
, u64 addr
)
2139 shadow_walk_init_using_root(iterator
, vcpu
, vcpu
->arch
.mmu
->root_hpa
,
2143 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator
*iterator
)
2145 if (iterator
->level
< PG_LEVEL_4K
)
2148 iterator
->index
= SHADOW_PT_INDEX(iterator
->addr
, iterator
->level
);
2149 iterator
->sptep
= ((u64
*)__va(iterator
->shadow_addr
)) + iterator
->index
;
2153 static void __shadow_walk_next(struct kvm_shadow_walk_iterator
*iterator
,
2156 if (is_last_spte(spte
, iterator
->level
)) {
2157 iterator
->level
= 0;
2161 iterator
->shadow_addr
= spte
& PT64_BASE_ADDR_MASK
;
2165 static void shadow_walk_next(struct kvm_shadow_walk_iterator
*iterator
)
2167 __shadow_walk_next(iterator
, *iterator
->sptep
);
2170 static void link_shadow_page(struct kvm_vcpu
*vcpu
, u64
*sptep
,
2171 struct kvm_mmu_page
*sp
)
2175 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK
!= PT_WRITABLE_MASK
);
2177 spte
= make_nonleaf_spte(sp
->spt
, sp_ad_disabled(sp
));
2179 mmu_spte_set(sptep
, spte
);
2181 mmu_page_add_parent_pte(vcpu
, sp
, sptep
);
2183 if (sp
->unsync_children
|| sp
->unsync
)
2187 static void validate_direct_spte(struct kvm_vcpu
*vcpu
, u64
*sptep
,
2188 unsigned direct_access
)
2190 if (is_shadow_present_pte(*sptep
) && !is_large_pte(*sptep
)) {
2191 struct kvm_mmu_page
*child
;
2194 * For the direct sp, if the guest pte's dirty bit
2195 * changed form clean to dirty, it will corrupt the
2196 * sp's access: allow writable in the read-only sp,
2197 * so we should update the spte at this point to get
2198 * a new sp with the correct access.
2200 child
= to_shadow_page(*sptep
& PT64_BASE_ADDR_MASK
);
2201 if (child
->role
.access
== direct_access
)
2204 drop_parent_pte(child
, sptep
);
2205 kvm_flush_remote_tlbs_with_address(vcpu
->kvm
, child
->gfn
, 1);
2209 /* Returns the number of zapped non-leaf child shadow pages. */
2210 static int mmu_page_zap_pte(struct kvm
*kvm
, struct kvm_mmu_page
*sp
,
2211 u64
*spte
, struct list_head
*invalid_list
)
2214 struct kvm_mmu_page
*child
;
2217 if (is_shadow_present_pte(pte
)) {
2218 if (is_last_spte(pte
, sp
->role
.level
)) {
2219 drop_spte(kvm
, spte
);
2220 if (is_large_pte(pte
))
2223 child
= to_shadow_page(pte
& PT64_BASE_ADDR_MASK
);
2224 drop_parent_pte(child
, spte
);
2227 * Recursively zap nested TDP SPs, parentless SPs are
2228 * unlikely to be used again in the near future. This
2229 * avoids retaining a large number of stale nested SPs.
2231 if (tdp_enabled
&& invalid_list
&&
2232 child
->role
.guest_mode
&& !child
->parent_ptes
.val
)
2233 return kvm_mmu_prepare_zap_page(kvm
, child
,
2236 } else if (is_mmio_spte(pte
)) {
2237 mmu_spte_clear_no_track(spte
);
2242 static int kvm_mmu_page_unlink_children(struct kvm
*kvm
,
2243 struct kvm_mmu_page
*sp
,
2244 struct list_head
*invalid_list
)
2249 for (i
= 0; i
< PT64_ENT_PER_PAGE
; ++i
)
2250 zapped
+= mmu_page_zap_pte(kvm
, sp
, sp
->spt
+ i
, invalid_list
);
2255 static void kvm_mmu_unlink_parents(struct kvm
*kvm
, struct kvm_mmu_page
*sp
)
2258 struct rmap_iterator iter
;
2260 while ((sptep
= rmap_get_first(&sp
->parent_ptes
, &iter
)))
2261 drop_parent_pte(sp
, sptep
);
2264 static int mmu_zap_unsync_children(struct kvm
*kvm
,
2265 struct kvm_mmu_page
*parent
,
2266 struct list_head
*invalid_list
)
2269 struct mmu_page_path parents
;
2270 struct kvm_mmu_pages pages
;
2272 if (parent
->role
.level
== PG_LEVEL_4K
)
2275 while (mmu_unsync_walk(parent
, &pages
)) {
2276 struct kvm_mmu_page
*sp
;
2278 for_each_sp(pages
, sp
, parents
, i
) {
2279 kvm_mmu_prepare_zap_page(kvm
, sp
, invalid_list
);
2280 mmu_pages_clear_parents(&parents
);
2288 static bool __kvm_mmu_prepare_zap_page(struct kvm
*kvm
,
2289 struct kvm_mmu_page
*sp
,
2290 struct list_head
*invalid_list
,
2295 trace_kvm_mmu_prepare_zap_page(sp
);
2296 ++kvm
->stat
.mmu_shadow_zapped
;
2297 *nr_zapped
= mmu_zap_unsync_children(kvm
, sp
, invalid_list
);
2298 *nr_zapped
+= kvm_mmu_page_unlink_children(kvm
, sp
, invalid_list
);
2299 kvm_mmu_unlink_parents(kvm
, sp
);
2301 /* Zapping children means active_mmu_pages has become unstable. */
2302 list_unstable
= *nr_zapped
;
2304 if (!sp
->role
.invalid
&& !sp
->role
.direct
)
2305 unaccount_shadowed(kvm
, sp
);
2308 kvm_unlink_unsync_page(kvm
, sp
);
2309 if (!sp
->root_count
) {
2314 * Already invalid pages (previously active roots) are not on
2315 * the active page list. See list_del() in the "else" case of
2318 if (sp
->role
.invalid
)
2319 list_add(&sp
->link
, invalid_list
);
2321 list_move(&sp
->link
, invalid_list
);
2322 kvm_mod_used_mmu_pages(kvm
, -1);
2325 * Remove the active root from the active page list, the root
2326 * will be explicitly freed when the root_count hits zero.
2328 list_del(&sp
->link
);
2331 * Obsolete pages cannot be used on any vCPUs, see the comment
2332 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2333 * treats invalid shadow pages as being obsolete.
2335 if (!is_obsolete_sp(kvm
, sp
))
2336 kvm_reload_remote_mmus(kvm
);
2339 if (sp
->lpage_disallowed
)
2340 unaccount_huge_nx_page(kvm
, sp
);
2342 sp
->role
.invalid
= 1;
2343 return list_unstable
;
2346 static bool kvm_mmu_prepare_zap_page(struct kvm
*kvm
, struct kvm_mmu_page
*sp
,
2347 struct list_head
*invalid_list
)
2351 __kvm_mmu_prepare_zap_page(kvm
, sp
, invalid_list
, &nr_zapped
);
2355 static void kvm_mmu_commit_zap_page(struct kvm
*kvm
,
2356 struct list_head
*invalid_list
)
2358 struct kvm_mmu_page
*sp
, *nsp
;
2360 if (list_empty(invalid_list
))
2364 * We need to make sure everyone sees our modifications to
2365 * the page tables and see changes to vcpu->mode here. The barrier
2366 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2367 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2369 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2370 * guest mode and/or lockless shadow page table walks.
2372 kvm_flush_remote_tlbs(kvm
);
2374 list_for_each_entry_safe(sp
, nsp
, invalid_list
, link
) {
2375 WARN_ON(!sp
->role
.invalid
|| sp
->root_count
);
2376 kvm_mmu_free_page(sp
);
2380 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm
*kvm
,
2381 unsigned long nr_to_zap
)
2383 unsigned long total_zapped
= 0;
2384 struct kvm_mmu_page
*sp
, *tmp
;
2385 LIST_HEAD(invalid_list
);
2389 if (list_empty(&kvm
->arch
.active_mmu_pages
))
2393 list_for_each_entry_safe(sp
, tmp
, &kvm
->arch
.active_mmu_pages
, link
) {
2395 * Don't zap active root pages, the page itself can't be freed
2396 * and zapping it will just force vCPUs to realloc and reload.
2401 unstable
= __kvm_mmu_prepare_zap_page(kvm
, sp
, &invalid_list
,
2403 total_zapped
+= nr_zapped
;
2404 if (total_zapped
>= nr_to_zap
)
2411 kvm_mmu_commit_zap_page(kvm
, &invalid_list
);
2413 kvm
->stat
.mmu_recycled
+= total_zapped
;
2414 return total_zapped
;
2417 static inline unsigned long kvm_mmu_available_pages(struct kvm
*kvm
)
2419 if (kvm
->arch
.n_max_mmu_pages
> kvm
->arch
.n_used_mmu_pages
)
2420 return kvm
->arch
.n_max_mmu_pages
-
2421 kvm
->arch
.n_used_mmu_pages
;
2426 static int make_mmu_pages_available(struct kvm_vcpu
*vcpu
)
2428 unsigned long avail
= kvm_mmu_available_pages(vcpu
->kvm
);
2430 if (likely(avail
>= KVM_MIN_FREE_MMU_PAGES
))
2433 kvm_mmu_zap_oldest_mmu_pages(vcpu
->kvm
, KVM_REFILL_PAGES
- avail
);
2435 if (!kvm_mmu_available_pages(vcpu
->kvm
))
2441 * Changing the number of mmu pages allocated to the vm
2442 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2444 void kvm_mmu_change_mmu_pages(struct kvm
*kvm
, unsigned long goal_nr_mmu_pages
)
2446 spin_lock(&kvm
->mmu_lock
);
2448 if (kvm
->arch
.n_used_mmu_pages
> goal_nr_mmu_pages
) {
2449 kvm_mmu_zap_oldest_mmu_pages(kvm
, kvm
->arch
.n_used_mmu_pages
-
2452 goal_nr_mmu_pages
= kvm
->arch
.n_used_mmu_pages
;
2455 kvm
->arch
.n_max_mmu_pages
= goal_nr_mmu_pages
;
2457 spin_unlock(&kvm
->mmu_lock
);
2460 int kvm_mmu_unprotect_page(struct kvm
*kvm
, gfn_t gfn
)
2462 struct kvm_mmu_page
*sp
;
2463 LIST_HEAD(invalid_list
);
2466 pgprintk("%s: looking for gfn %llx\n", __func__
, gfn
);
2468 spin_lock(&kvm
->mmu_lock
);
2469 for_each_gfn_indirect_valid_sp(kvm
, sp
, gfn
) {
2470 pgprintk("%s: gfn %llx role %x\n", __func__
, gfn
,
2473 kvm_mmu_prepare_zap_page(kvm
, sp
, &invalid_list
);
2475 kvm_mmu_commit_zap_page(kvm
, &invalid_list
);
2476 spin_unlock(&kvm
->mmu_lock
);
2480 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page
);
2482 static void kvm_unsync_page(struct kvm_vcpu
*vcpu
, struct kvm_mmu_page
*sp
)
2484 trace_kvm_mmu_unsync_page(sp
);
2485 ++vcpu
->kvm
->stat
.mmu_unsync
;
2488 kvm_mmu_mark_parents_unsync(sp
);
2491 bool mmu_need_write_protect(struct kvm_vcpu
*vcpu
, gfn_t gfn
,
2494 struct kvm_mmu_page
*sp
;
2496 if (kvm_page_track_is_active(vcpu
, gfn
, KVM_PAGE_TRACK_WRITE
))
2499 for_each_gfn_indirect_valid_sp(vcpu
->kvm
, sp
, gfn
) {
2506 WARN_ON(sp
->role
.level
!= PG_LEVEL_4K
);
2507 kvm_unsync_page(vcpu
, sp
);
2511 * We need to ensure that the marking of unsync pages is visible
2512 * before the SPTE is updated to allow writes because
2513 * kvm_mmu_sync_roots() checks the unsync flags without holding
2514 * the MMU lock and so can race with this. If the SPTE was updated
2515 * before the page had been marked as unsync-ed, something like the
2516 * following could happen:
2519 * ---------------------------------------------------------------------
2520 * 1.2 Host updates SPTE
2522 * 2.1 Guest writes a GPTE for GVA X.
2523 * (GPTE being in the guest page table shadowed
2524 * by the SP from CPU 1.)
2525 * This reads SPTE during the page table walk.
2526 * Since SPTE.W is read as 1, there is no
2529 * 2.2 Guest issues TLB flush.
2530 * That causes a VM Exit.
2532 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2533 * Since it is false, so it just returns.
2535 * 2.4 Guest accesses GVA X.
2536 * Since the mapping in the SP was not updated,
2537 * so the old mapping for GVA X incorrectly
2541 * (sp->unsync = true)
2543 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2544 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2545 * pairs with this write barrier.
2552 static int set_spte(struct kvm_vcpu
*vcpu
, u64
*sptep
,
2553 unsigned int pte_access
, int level
,
2554 gfn_t gfn
, kvm_pfn_t pfn
, bool speculative
,
2555 bool can_unsync
, bool host_writable
)
2558 struct kvm_mmu_page
*sp
;
2561 if (set_mmio_spte(vcpu
, sptep
, gfn
, pfn
, pte_access
))
2564 sp
= sptep_to_sp(sptep
);
2566 ret
= make_spte(vcpu
, pte_access
, level
, gfn
, pfn
, *sptep
, speculative
,
2567 can_unsync
, host_writable
, sp_ad_disabled(sp
), &spte
);
2569 if (spte
& PT_WRITABLE_MASK
)
2570 kvm_vcpu_mark_page_dirty(vcpu
, gfn
);
2573 ret
|= SET_SPTE_SPURIOUS
;
2574 else if (mmu_spte_update(sptep
, spte
))
2575 ret
|= SET_SPTE_NEED_REMOTE_TLB_FLUSH
;
2579 static int mmu_set_spte(struct kvm_vcpu
*vcpu
, u64
*sptep
,
2580 unsigned int pte_access
, bool write_fault
, int level
,
2581 gfn_t gfn
, kvm_pfn_t pfn
, bool speculative
,
2584 int was_rmapped
= 0;
2587 int ret
= RET_PF_FIXED
;
2590 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__
,
2591 *sptep
, write_fault
, gfn
);
2593 if (is_shadow_present_pte(*sptep
)) {
2595 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2596 * the parent of the now unreachable PTE.
2598 if (level
> PG_LEVEL_4K
&& !is_large_pte(*sptep
)) {
2599 struct kvm_mmu_page
*child
;
2602 child
= to_shadow_page(pte
& PT64_BASE_ADDR_MASK
);
2603 drop_parent_pte(child
, sptep
);
2605 } else if (pfn
!= spte_to_pfn(*sptep
)) {
2606 pgprintk("hfn old %llx new %llx\n",
2607 spte_to_pfn(*sptep
), pfn
);
2608 drop_spte(vcpu
->kvm
, sptep
);
2614 set_spte_ret
= set_spte(vcpu
, sptep
, pte_access
, level
, gfn
, pfn
,
2615 speculative
, true, host_writable
);
2616 if (set_spte_ret
& SET_SPTE_WRITE_PROTECTED_PT
) {
2618 ret
= RET_PF_EMULATE
;
2619 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT
, vcpu
);
2622 if (set_spte_ret
& SET_SPTE_NEED_REMOTE_TLB_FLUSH
|| flush
)
2623 kvm_flush_remote_tlbs_with_address(vcpu
->kvm
, gfn
,
2624 KVM_PAGES_PER_HPAGE(level
));
2626 if (unlikely(is_mmio_spte(*sptep
)))
2627 ret
= RET_PF_EMULATE
;
2630 * The fault is fully spurious if and only if the new SPTE and old SPTE
2631 * are identical, and emulation is not required.
2633 if ((set_spte_ret
& SET_SPTE_SPURIOUS
) && ret
== RET_PF_FIXED
) {
2634 WARN_ON_ONCE(!was_rmapped
);
2635 return RET_PF_SPURIOUS
;
2638 pgprintk("%s: setting spte %llx\n", __func__
, *sptep
);
2639 trace_kvm_mmu_set_spte(level
, gfn
, sptep
);
2640 if (!was_rmapped
&& is_large_pte(*sptep
))
2641 ++vcpu
->kvm
->stat
.lpages
;
2643 if (is_shadow_present_pte(*sptep
)) {
2645 rmap_count
= rmap_add(vcpu
, sptep
, gfn
);
2646 if (rmap_count
> RMAP_RECYCLE_THRESHOLD
)
2647 rmap_recycle(vcpu
, sptep
, gfn
);
2654 static kvm_pfn_t
pte_prefetch_gfn_to_pfn(struct kvm_vcpu
*vcpu
, gfn_t gfn
,
2657 struct kvm_memory_slot
*slot
;
2659 slot
= gfn_to_memslot_dirty_bitmap(vcpu
, gfn
, no_dirty_log
);
2661 return KVM_PFN_ERR_FAULT
;
2663 return gfn_to_pfn_memslot_atomic(slot
, gfn
);
2666 static int direct_pte_prefetch_many(struct kvm_vcpu
*vcpu
,
2667 struct kvm_mmu_page
*sp
,
2668 u64
*start
, u64
*end
)
2670 struct page
*pages
[PTE_PREFETCH_NUM
];
2671 struct kvm_memory_slot
*slot
;
2672 unsigned int access
= sp
->role
.access
;
2676 gfn
= kvm_mmu_page_get_gfn(sp
, start
- sp
->spt
);
2677 slot
= gfn_to_memslot_dirty_bitmap(vcpu
, gfn
, access
& ACC_WRITE_MASK
);
2681 ret
= gfn_to_page_many_atomic(slot
, gfn
, pages
, end
- start
);
2685 for (i
= 0; i
< ret
; i
++, gfn
++, start
++) {
2686 mmu_set_spte(vcpu
, start
, access
, false, sp
->role
.level
, gfn
,
2687 page_to_pfn(pages
[i
]), true, true);
2694 static void __direct_pte_prefetch(struct kvm_vcpu
*vcpu
,
2695 struct kvm_mmu_page
*sp
, u64
*sptep
)
2697 u64
*spte
, *start
= NULL
;
2700 WARN_ON(!sp
->role
.direct
);
2702 i
= (sptep
- sp
->spt
) & ~(PTE_PREFETCH_NUM
- 1);
2705 for (i
= 0; i
< PTE_PREFETCH_NUM
; i
++, spte
++) {
2706 if (is_shadow_present_pte(*spte
) || spte
== sptep
) {
2709 if (direct_pte_prefetch_many(vcpu
, sp
, start
, spte
) < 0)
2717 static void direct_pte_prefetch(struct kvm_vcpu
*vcpu
, u64
*sptep
)
2719 struct kvm_mmu_page
*sp
;
2721 sp
= sptep_to_sp(sptep
);
2724 * Without accessed bits, there's no way to distinguish between
2725 * actually accessed translations and prefetched, so disable pte
2726 * prefetch if accessed bits aren't available.
2728 if (sp_ad_disabled(sp
))
2731 if (sp
->role
.level
> PG_LEVEL_4K
)
2734 __direct_pte_prefetch(vcpu
, sp
, sptep
);
2737 static int host_pfn_mapping_level(struct kvm_vcpu
*vcpu
, gfn_t gfn
,
2738 kvm_pfn_t pfn
, struct kvm_memory_slot
*slot
)
2744 if (!PageCompound(pfn_to_page(pfn
)) && !kvm_is_zone_device_pfn(pfn
))
2748 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
2749 * is not solely for performance, it's also necessary to avoid the
2750 * "writable" check in __gfn_to_hva_many(), which will always fail on
2751 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
2752 * page fault steps have already verified the guest isn't writing a
2753 * read-only memslot.
2755 hva
= __gfn_to_hva_memslot(slot
, gfn
);
2757 pte
= lookup_address_in_mm(vcpu
->kvm
->mm
, hva
, &level
);
2764 static int kvm_mmu_hugepage_adjust(struct kvm_vcpu
*vcpu
, gfn_t gfn
,
2765 int max_level
, kvm_pfn_t
*pfnp
,
2766 bool huge_page_disallowed
, int *req_level
)
2768 struct kvm_memory_slot
*slot
;
2769 struct kvm_lpage_info
*linfo
;
2770 kvm_pfn_t pfn
= *pfnp
;
2774 *req_level
= PG_LEVEL_4K
;
2776 if (unlikely(max_level
== PG_LEVEL_4K
))
2779 if (is_error_noslot_pfn(pfn
) || kvm_is_reserved_pfn(pfn
))
2782 slot
= gfn_to_memslot_dirty_bitmap(vcpu
, gfn
, true);
2786 max_level
= min(max_level
, max_huge_page_level
);
2787 for ( ; max_level
> PG_LEVEL_4K
; max_level
--) {
2788 linfo
= lpage_info_slot(gfn
, slot
, max_level
);
2789 if (!linfo
->disallow_lpage
)
2793 if (max_level
== PG_LEVEL_4K
)
2796 level
= host_pfn_mapping_level(vcpu
, gfn
, pfn
, slot
);
2797 if (level
== PG_LEVEL_4K
)
2800 *req_level
= level
= min(level
, max_level
);
2803 * Enforce the iTLB multihit workaround after capturing the requested
2804 * level, which will be used to do precise, accurate accounting.
2806 if (huge_page_disallowed
)
2810 * mmu_notifier_retry() was successful and mmu_lock is held, so
2811 * the pmd can't be split from under us.
2813 mask
= KVM_PAGES_PER_HPAGE(level
) - 1;
2814 VM_BUG_ON((gfn
& mask
) != (pfn
& mask
));
2815 *pfnp
= pfn
& ~mask
;
2820 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it
,
2821 gfn_t gfn
, kvm_pfn_t
*pfnp
, int *levelp
)
2823 int level
= *levelp
;
2824 u64 spte
= *it
.sptep
;
2826 if (it
.level
== level
&& level
> PG_LEVEL_4K
&&
2827 is_shadow_present_pte(spte
) &&
2828 !is_large_pte(spte
)) {
2830 * A small SPTE exists for this pfn, but FNAME(fetch)
2831 * and __direct_map would like to create a large PTE
2832 * instead: just force them to go down another level,
2833 * patching back for them into pfn the next 9 bits of
2836 u64 page_mask
= KVM_PAGES_PER_HPAGE(level
) - KVM_PAGES_PER_HPAGE(level
- 1);
2837 *pfnp
|= gfn
& page_mask
;
2842 static int __direct_map(struct kvm_vcpu
*vcpu
, gpa_t gpa
, u32 error_code
,
2843 int map_writable
, int max_level
, kvm_pfn_t pfn
,
2844 bool prefault
, bool is_tdp
)
2846 bool nx_huge_page_workaround_enabled
= is_nx_huge_page_enabled();
2847 bool write
= error_code
& PFERR_WRITE_MASK
;
2848 bool exec
= error_code
& PFERR_FETCH_MASK
;
2849 bool huge_page_disallowed
= exec
&& nx_huge_page_workaround_enabled
;
2850 struct kvm_shadow_walk_iterator it
;
2851 struct kvm_mmu_page
*sp
;
2852 int level
, req_level
, ret
;
2853 gfn_t gfn
= gpa
>> PAGE_SHIFT
;
2854 gfn_t base_gfn
= gfn
;
2856 if (WARN_ON(!VALID_PAGE(vcpu
->arch
.mmu
->root_hpa
)))
2857 return RET_PF_RETRY
;
2859 level
= kvm_mmu_hugepage_adjust(vcpu
, gfn
, max_level
, &pfn
,
2860 huge_page_disallowed
, &req_level
);
2862 trace_kvm_mmu_spte_requested(gpa
, level
, pfn
);
2863 for_each_shadow_entry(vcpu
, gpa
, it
) {
2865 * We cannot overwrite existing page tables with an NX
2866 * large page, as the leaf could be executable.
2868 if (nx_huge_page_workaround_enabled
)
2869 disallowed_hugepage_adjust(it
, gfn
, &pfn
, &level
);
2871 base_gfn
= gfn
& ~(KVM_PAGES_PER_HPAGE(it
.level
) - 1);
2872 if (it
.level
== level
)
2875 drop_large_spte(vcpu
, it
.sptep
);
2876 if (!is_shadow_present_pte(*it
.sptep
)) {
2877 sp
= kvm_mmu_get_page(vcpu
, base_gfn
, it
.addr
,
2878 it
.level
- 1, true, ACC_ALL
);
2880 link_shadow_page(vcpu
, it
.sptep
, sp
);
2881 if (is_tdp
&& huge_page_disallowed
&&
2882 req_level
>= it
.level
)
2883 account_huge_nx_page(vcpu
->kvm
, sp
);
2887 ret
= mmu_set_spte(vcpu
, it
.sptep
, ACC_ALL
,
2888 write
, level
, base_gfn
, pfn
, prefault
,
2890 if (ret
== RET_PF_SPURIOUS
)
2893 direct_pte_prefetch(vcpu
, it
.sptep
);
2894 ++vcpu
->stat
.pf_fixed
;
2898 static void kvm_send_hwpoison_signal(unsigned long address
, struct task_struct
*tsk
)
2900 send_sig_mceerr(BUS_MCEERR_AR
, (void __user
*)address
, PAGE_SHIFT
, tsk
);
2903 static int kvm_handle_bad_page(struct kvm_vcpu
*vcpu
, gfn_t gfn
, kvm_pfn_t pfn
)
2906 * Do not cache the mmio info caused by writing the readonly gfn
2907 * into the spte otherwise read access on readonly gfn also can
2908 * caused mmio page fault and treat it as mmio access.
2910 if (pfn
== KVM_PFN_ERR_RO_FAULT
)
2911 return RET_PF_EMULATE
;
2913 if (pfn
== KVM_PFN_ERR_HWPOISON
) {
2914 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu
, gfn
), current
);
2915 return RET_PF_RETRY
;
2921 static bool handle_abnormal_pfn(struct kvm_vcpu
*vcpu
, gva_t gva
, gfn_t gfn
,
2922 kvm_pfn_t pfn
, unsigned int access
,
2925 /* The pfn is invalid, report the error! */
2926 if (unlikely(is_error_pfn(pfn
))) {
2927 *ret_val
= kvm_handle_bad_page(vcpu
, gfn
, pfn
);
2931 if (unlikely(is_noslot_pfn(pfn
)))
2932 vcpu_cache_mmio_info(vcpu
, gva
, gfn
,
2933 access
& shadow_mmio_access_mask
);
2938 static bool page_fault_can_be_fast(u32 error_code
)
2941 * Do not fix the mmio spte with invalid generation number which
2942 * need to be updated by slow page fault path.
2944 if (unlikely(error_code
& PFERR_RSVD_MASK
))
2947 /* See if the page fault is due to an NX violation */
2948 if (unlikely(((error_code
& (PFERR_FETCH_MASK
| PFERR_PRESENT_MASK
))
2949 == (PFERR_FETCH_MASK
| PFERR_PRESENT_MASK
))))
2953 * #PF can be fast if:
2954 * 1. The shadow page table entry is not present, which could mean that
2955 * the fault is potentially caused by access tracking (if enabled).
2956 * 2. The shadow page table entry is present and the fault
2957 * is caused by write-protect, that means we just need change the W
2958 * bit of the spte which can be done out of mmu-lock.
2960 * However, if access tracking is disabled we know that a non-present
2961 * page must be a genuine page fault where we have to create a new SPTE.
2962 * So, if access tracking is disabled, we return true only for write
2963 * accesses to a present page.
2966 return shadow_acc_track_mask
!= 0 ||
2967 ((error_code
& (PFERR_WRITE_MASK
| PFERR_PRESENT_MASK
))
2968 == (PFERR_WRITE_MASK
| PFERR_PRESENT_MASK
));
2972 * Returns true if the SPTE was fixed successfully. Otherwise,
2973 * someone else modified the SPTE from its original value.
2976 fast_pf_fix_direct_spte(struct kvm_vcpu
*vcpu
, struct kvm_mmu_page
*sp
,
2977 u64
*sptep
, u64 old_spte
, u64 new_spte
)
2981 WARN_ON(!sp
->role
.direct
);
2984 * Theoretically we could also set dirty bit (and flush TLB) here in
2985 * order to eliminate unnecessary PML logging. See comments in
2986 * set_spte. But fast_page_fault is very unlikely to happen with PML
2987 * enabled, so we do not do this. This might result in the same GPA
2988 * to be logged in PML buffer again when the write really happens, and
2989 * eventually to be called by mark_page_dirty twice. But it's also no
2990 * harm. This also avoids the TLB flush needed after setting dirty bit
2991 * so non-PML cases won't be impacted.
2993 * Compare with set_spte where instead shadow_dirty_mask is set.
2995 if (cmpxchg64(sptep
, old_spte
, new_spte
) != old_spte
)
2998 if (is_writable_pte(new_spte
) && !is_writable_pte(old_spte
)) {
3000 * The gfn of direct spte is stable since it is
3001 * calculated by sp->gfn.
3003 gfn
= kvm_mmu_page_get_gfn(sp
, sptep
- sp
->spt
);
3004 kvm_vcpu_mark_page_dirty(vcpu
, gfn
);
3010 static bool is_access_allowed(u32 fault_err_code
, u64 spte
)
3012 if (fault_err_code
& PFERR_FETCH_MASK
)
3013 return is_executable_pte(spte
);
3015 if (fault_err_code
& PFERR_WRITE_MASK
)
3016 return is_writable_pte(spte
);
3018 /* Fault was on Read access */
3019 return spte
& PT_PRESENT_MASK
;
3023 * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3025 static int fast_page_fault(struct kvm_vcpu
*vcpu
, gpa_t cr2_or_gpa
,
3028 struct kvm_shadow_walk_iterator iterator
;
3029 struct kvm_mmu_page
*sp
;
3030 int ret
= RET_PF_INVALID
;
3032 uint retry_count
= 0;
3034 if (!page_fault_can_be_fast(error_code
))
3037 walk_shadow_page_lockless_begin(vcpu
);
3042 for_each_shadow_entry_lockless(vcpu
, cr2_or_gpa
, iterator
, spte
)
3043 if (!is_shadow_present_pte(spte
))
3046 sp
= sptep_to_sp(iterator
.sptep
);
3047 if (!is_last_spte(spte
, sp
->role
.level
))
3051 * Check whether the memory access that caused the fault would
3052 * still cause it if it were to be performed right now. If not,
3053 * then this is a spurious fault caused by TLB lazily flushed,
3054 * or some other CPU has already fixed the PTE after the
3055 * current CPU took the fault.
3057 * Need not check the access of upper level table entries since
3058 * they are always ACC_ALL.
3060 if (is_access_allowed(error_code
, spte
)) {
3061 ret
= RET_PF_SPURIOUS
;
3067 if (is_access_track_spte(spte
))
3068 new_spte
= restore_acc_track_spte(new_spte
);
3071 * Currently, to simplify the code, write-protection can
3072 * be removed in the fast path only if the SPTE was
3073 * write-protected for dirty-logging or access tracking.
3075 if ((error_code
& PFERR_WRITE_MASK
) &&
3076 spte_can_locklessly_be_made_writable(spte
)) {
3077 new_spte
|= PT_WRITABLE_MASK
;
3080 * Do not fix write-permission on the large spte. Since
3081 * we only dirty the first page into the dirty-bitmap in
3082 * fast_pf_fix_direct_spte(), other pages are missed
3083 * if its slot has dirty logging enabled.
3085 * Instead, we let the slow page fault path create a
3086 * normal spte to fix the access.
3088 * See the comments in kvm_arch_commit_memory_region().
3090 if (sp
->role
.level
> PG_LEVEL_4K
)
3094 /* Verify that the fault can be handled in the fast path */
3095 if (new_spte
== spte
||
3096 !is_access_allowed(error_code
, new_spte
))
3100 * Currently, fast page fault only works for direct mapping
3101 * since the gfn is not stable for indirect shadow page. See
3102 * Documentation/virt/kvm/locking.rst to get more detail.
3104 if (fast_pf_fix_direct_spte(vcpu
, sp
, iterator
.sptep
, spte
,
3110 if (++retry_count
> 4) {
3111 printk_once(KERN_WARNING
3112 "kvm: Fast #PF retrying more than 4 times.\n");
3118 trace_fast_page_fault(vcpu
, cr2_or_gpa
, error_code
, iterator
.sptep
,
3120 walk_shadow_page_lockless_end(vcpu
);
3125 static void mmu_free_root_page(struct kvm
*kvm
, hpa_t
*root_hpa
,
3126 struct list_head
*invalid_list
)
3128 struct kvm_mmu_page
*sp
;
3130 if (!VALID_PAGE(*root_hpa
))
3133 sp
= to_shadow_page(*root_hpa
& PT64_BASE_ADDR_MASK
);
3135 if (!sp
->root_count
&& sp
->role
.invalid
)
3136 kvm_mmu_prepare_zap_page(kvm
, sp
, invalid_list
);
3138 *root_hpa
= INVALID_PAGE
;
3141 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3142 void kvm_mmu_free_roots(struct kvm_vcpu
*vcpu
, struct kvm_mmu
*mmu
,
3143 ulong roots_to_free
)
3145 struct kvm
*kvm
= vcpu
->kvm
;
3147 LIST_HEAD(invalid_list
);
3148 bool free_active_root
= roots_to_free
& KVM_MMU_ROOT_CURRENT
;
3150 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS
>= BITS_PER_LONG
);
3152 /* Before acquiring the MMU lock, see if we need to do any real work. */
3153 if (!(free_active_root
&& VALID_PAGE(mmu
->root_hpa
))) {
3154 for (i
= 0; i
< KVM_MMU_NUM_PREV_ROOTS
; i
++)
3155 if ((roots_to_free
& KVM_MMU_ROOT_PREVIOUS(i
)) &&
3156 VALID_PAGE(mmu
->prev_roots
[i
].hpa
))
3159 if (i
== KVM_MMU_NUM_PREV_ROOTS
)
3163 spin_lock(&kvm
->mmu_lock
);
3165 for (i
= 0; i
< KVM_MMU_NUM_PREV_ROOTS
; i
++)
3166 if (roots_to_free
& KVM_MMU_ROOT_PREVIOUS(i
))
3167 mmu_free_root_page(kvm
, &mmu
->prev_roots
[i
].hpa
,
3170 if (free_active_root
) {
3171 if (mmu
->shadow_root_level
>= PT64_ROOT_4LEVEL
&&
3172 (mmu
->root_level
>= PT64_ROOT_4LEVEL
|| mmu
->direct_map
)) {
3173 mmu_free_root_page(kvm
, &mmu
->root_hpa
, &invalid_list
);
3175 for (i
= 0; i
< 4; ++i
)
3176 if (mmu
->pae_root
[i
] != 0)
3177 mmu_free_root_page(kvm
,
3180 mmu
->root_hpa
= INVALID_PAGE
;
3185 kvm_mmu_commit_zap_page(kvm
, &invalid_list
);
3186 spin_unlock(&kvm
->mmu_lock
);
3188 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots
);
3190 static int mmu_check_root(struct kvm_vcpu
*vcpu
, gfn_t root_gfn
)
3194 if (!kvm_vcpu_is_visible_gfn(vcpu
, root_gfn
)) {
3195 kvm_make_request(KVM_REQ_TRIPLE_FAULT
, vcpu
);
3202 static hpa_t
mmu_alloc_root(struct kvm_vcpu
*vcpu
, gfn_t gfn
, gva_t gva
,
3203 u8 level
, bool direct
)
3205 struct kvm_mmu_page
*sp
;
3207 spin_lock(&vcpu
->kvm
->mmu_lock
);
3209 if (make_mmu_pages_available(vcpu
)) {
3210 spin_unlock(&vcpu
->kvm
->mmu_lock
);
3211 return INVALID_PAGE
;
3213 sp
= kvm_mmu_get_page(vcpu
, gfn
, gva
, level
, direct
, ACC_ALL
);
3216 spin_unlock(&vcpu
->kvm
->mmu_lock
);
3217 return __pa(sp
->spt
);
3220 static int mmu_alloc_direct_roots(struct kvm_vcpu
*vcpu
)
3222 u8 shadow_root_level
= vcpu
->arch
.mmu
->shadow_root_level
;
3226 if (shadow_root_level
>= PT64_ROOT_4LEVEL
) {
3227 root
= mmu_alloc_root(vcpu
, 0, 0, shadow_root_level
, true);
3228 if (!VALID_PAGE(root
))
3230 vcpu
->arch
.mmu
->root_hpa
= root
;
3231 } else if (shadow_root_level
== PT32E_ROOT_LEVEL
) {
3232 for (i
= 0; i
< 4; ++i
) {
3233 MMU_WARN_ON(VALID_PAGE(vcpu
->arch
.mmu
->pae_root
[i
]));
3235 root
= mmu_alloc_root(vcpu
, i
<< (30 - PAGE_SHIFT
),
3236 i
<< 30, PT32_ROOT_LEVEL
, true);
3237 if (!VALID_PAGE(root
))
3239 vcpu
->arch
.mmu
->pae_root
[i
] = root
| PT_PRESENT_MASK
;
3241 vcpu
->arch
.mmu
->root_hpa
= __pa(vcpu
->arch
.mmu
->pae_root
);
3245 /* root_pgd is ignored for direct MMUs. */
3246 vcpu
->arch
.mmu
->root_pgd
= 0;
3251 static int mmu_alloc_shadow_roots(struct kvm_vcpu
*vcpu
)
3254 gfn_t root_gfn
, root_pgd
;
3258 root_pgd
= vcpu
->arch
.mmu
->get_guest_pgd(vcpu
);
3259 root_gfn
= root_pgd
>> PAGE_SHIFT
;
3261 if (mmu_check_root(vcpu
, root_gfn
))
3265 * Do we shadow a long mode page table? If so we need to
3266 * write-protect the guests page table root.
3268 if (vcpu
->arch
.mmu
->root_level
>= PT64_ROOT_4LEVEL
) {
3269 MMU_WARN_ON(VALID_PAGE(vcpu
->arch
.mmu
->root_hpa
));
3271 root
= mmu_alloc_root(vcpu
, root_gfn
, 0,
3272 vcpu
->arch
.mmu
->shadow_root_level
, false);
3273 if (!VALID_PAGE(root
))
3275 vcpu
->arch
.mmu
->root_hpa
= root
;
3280 * We shadow a 32 bit page table. This may be a legacy 2-level
3281 * or a PAE 3-level page table. In either case we need to be aware that
3282 * the shadow page table may be a PAE or a long mode page table.
3284 pm_mask
= PT_PRESENT_MASK
;
3285 if (vcpu
->arch
.mmu
->shadow_root_level
== PT64_ROOT_4LEVEL
)
3286 pm_mask
|= PT_ACCESSED_MASK
| PT_WRITABLE_MASK
| PT_USER_MASK
;
3288 for (i
= 0; i
< 4; ++i
) {
3289 MMU_WARN_ON(VALID_PAGE(vcpu
->arch
.mmu
->pae_root
[i
]));
3290 if (vcpu
->arch
.mmu
->root_level
== PT32E_ROOT_LEVEL
) {
3291 pdptr
= vcpu
->arch
.mmu
->get_pdptr(vcpu
, i
);
3292 if (!(pdptr
& PT_PRESENT_MASK
)) {
3293 vcpu
->arch
.mmu
->pae_root
[i
] = 0;
3296 root_gfn
= pdptr
>> PAGE_SHIFT
;
3297 if (mmu_check_root(vcpu
, root_gfn
))
3301 root
= mmu_alloc_root(vcpu
, root_gfn
, i
<< 30,
3302 PT32_ROOT_LEVEL
, false);
3303 if (!VALID_PAGE(root
))
3305 vcpu
->arch
.mmu
->pae_root
[i
] = root
| pm_mask
;
3307 vcpu
->arch
.mmu
->root_hpa
= __pa(vcpu
->arch
.mmu
->pae_root
);
3310 * If we shadow a 32 bit page table with a long mode page
3311 * table we enter this path.
3313 if (vcpu
->arch
.mmu
->shadow_root_level
== PT64_ROOT_4LEVEL
) {
3314 if (vcpu
->arch
.mmu
->lm_root
== NULL
) {
3316 * The additional page necessary for this is only
3317 * allocated on demand.
3322 lm_root
= (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT
);
3323 if (lm_root
== NULL
)
3326 lm_root
[0] = __pa(vcpu
->arch
.mmu
->pae_root
) | pm_mask
;
3328 vcpu
->arch
.mmu
->lm_root
= lm_root
;
3331 vcpu
->arch
.mmu
->root_hpa
= __pa(vcpu
->arch
.mmu
->lm_root
);
3335 vcpu
->arch
.mmu
->root_pgd
= root_pgd
;
3340 static int mmu_alloc_roots(struct kvm_vcpu
*vcpu
)
3342 if (vcpu
->arch
.mmu
->direct_map
)
3343 return mmu_alloc_direct_roots(vcpu
);
3345 return mmu_alloc_shadow_roots(vcpu
);
3348 void kvm_mmu_sync_roots(struct kvm_vcpu
*vcpu
)
3351 struct kvm_mmu_page
*sp
;
3353 if (vcpu
->arch
.mmu
->direct_map
)
3356 if (!VALID_PAGE(vcpu
->arch
.mmu
->root_hpa
))
3359 vcpu_clear_mmio_info(vcpu
, MMIO_GVA_ANY
);
3361 if (vcpu
->arch
.mmu
->root_level
>= PT64_ROOT_4LEVEL
) {
3362 hpa_t root
= vcpu
->arch
.mmu
->root_hpa
;
3363 sp
= to_shadow_page(root
);
3366 * Even if another CPU was marking the SP as unsync-ed
3367 * simultaneously, any guest page table changes are not
3368 * guaranteed to be visible anyway until this VCPU issues a TLB
3369 * flush strictly after those changes are made. We only need to
3370 * ensure that the other CPU sets these flags before any actual
3371 * changes to the page tables are made. The comments in
3372 * mmu_need_write_protect() describe what could go wrong if this
3373 * requirement isn't satisfied.
3375 if (!smp_load_acquire(&sp
->unsync
) &&
3376 !smp_load_acquire(&sp
->unsync_children
))
3379 spin_lock(&vcpu
->kvm
->mmu_lock
);
3380 kvm_mmu_audit(vcpu
, AUDIT_PRE_SYNC
);
3382 mmu_sync_children(vcpu
, sp
);
3384 kvm_mmu_audit(vcpu
, AUDIT_POST_SYNC
);
3385 spin_unlock(&vcpu
->kvm
->mmu_lock
);
3389 spin_lock(&vcpu
->kvm
->mmu_lock
);
3390 kvm_mmu_audit(vcpu
, AUDIT_PRE_SYNC
);
3392 for (i
= 0; i
< 4; ++i
) {
3393 hpa_t root
= vcpu
->arch
.mmu
->pae_root
[i
];
3395 if (root
&& VALID_PAGE(root
)) {
3396 root
&= PT64_BASE_ADDR_MASK
;
3397 sp
= to_shadow_page(root
);
3398 mmu_sync_children(vcpu
, sp
);
3402 kvm_mmu_audit(vcpu
, AUDIT_POST_SYNC
);
3403 spin_unlock(&vcpu
->kvm
->mmu_lock
);
3405 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots
);
3407 static gpa_t
nonpaging_gva_to_gpa(struct kvm_vcpu
*vcpu
, gpa_t vaddr
,
3408 u32 access
, struct x86_exception
*exception
)
3411 exception
->error_code
= 0;
3415 static gpa_t
nonpaging_gva_to_gpa_nested(struct kvm_vcpu
*vcpu
, gpa_t vaddr
,
3417 struct x86_exception
*exception
)
3420 exception
->error_code
= 0;
3421 return vcpu
->arch
.nested_mmu
.translate_gpa(vcpu
, vaddr
, access
, exception
);
3425 __is_rsvd_bits_set(struct rsvd_bits_validate
*rsvd_check
, u64 pte
, int level
)
3427 int bit7
= (pte
>> 7) & 1;
3429 return pte
& rsvd_check
->rsvd_bits_mask
[bit7
][level
-1];
3432 static bool __is_bad_mt_xwr(struct rsvd_bits_validate
*rsvd_check
, u64 pte
)
3434 return rsvd_check
->bad_mt_xwr
& BIT_ULL(pte
& 0x3f);
3437 static bool mmio_info_in_cache(struct kvm_vcpu
*vcpu
, u64 addr
, bool direct
)
3440 * A nested guest cannot use the MMIO cache if it is using nested
3441 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3443 if (mmu_is_nested(vcpu
))
3447 return vcpu_match_mmio_gpa(vcpu
, addr
);
3449 return vcpu_match_mmio_gva(vcpu
, addr
);
3452 /* return true if reserved bit is detected on spte. */
3454 walk_shadow_page_get_mmio_spte(struct kvm_vcpu
*vcpu
, u64 addr
, u64
*sptep
)
3456 struct kvm_shadow_walk_iterator iterator
;
3457 u64 sptes
[PT64_ROOT_MAX_LEVEL
], spte
= 0ull;
3458 struct rsvd_bits_validate
*rsvd_check
;
3460 bool reserved
= false;
3462 rsvd_check
= &vcpu
->arch
.mmu
->shadow_zero_check
;
3464 walk_shadow_page_lockless_begin(vcpu
);
3466 for (shadow_walk_init(&iterator
, vcpu
, addr
),
3467 leaf
= root
= iterator
.level
;
3468 shadow_walk_okay(&iterator
);
3469 __shadow_walk_next(&iterator
, spte
)) {
3470 spte
= mmu_spte_get_lockless(iterator
.sptep
);
3472 sptes
[leaf
- 1] = spte
;
3475 if (!is_shadow_present_pte(spte
))
3479 * Use a bitwise-OR instead of a logical-OR to aggregate the
3480 * reserved bit and EPT's invalid memtype/XWR checks to avoid
3481 * adding a Jcc in the loop.
3483 reserved
|= __is_bad_mt_xwr(rsvd_check
, spte
) |
3484 __is_rsvd_bits_set(rsvd_check
, spte
, iterator
.level
);
3487 walk_shadow_page_lockless_end(vcpu
);
3490 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3492 while (root
> leaf
) {
3493 pr_err("------ spte 0x%llx level %d.\n",
3494 sptes
[root
- 1], root
);
3503 static int handle_mmio_page_fault(struct kvm_vcpu
*vcpu
, u64 addr
, bool direct
)
3508 if (mmio_info_in_cache(vcpu
, addr
, direct
))
3509 return RET_PF_EMULATE
;
3511 reserved
= walk_shadow_page_get_mmio_spte(vcpu
, addr
, &spte
);
3512 if (WARN_ON(reserved
))
3515 if (is_mmio_spte(spte
)) {
3516 gfn_t gfn
= get_mmio_spte_gfn(spte
);
3517 unsigned int access
= get_mmio_spte_access(spte
);
3519 if (!check_mmio_spte(vcpu
, spte
))
3520 return RET_PF_INVALID
;
3525 trace_handle_mmio_page_fault(addr
, gfn
, access
);
3526 vcpu_cache_mmio_info(vcpu
, addr
, gfn
, access
);
3527 return RET_PF_EMULATE
;
3531 * If the page table is zapped by other cpus, let CPU fault again on
3534 return RET_PF_RETRY
;
3537 static bool page_fault_handle_page_track(struct kvm_vcpu
*vcpu
,
3538 u32 error_code
, gfn_t gfn
)
3540 if (unlikely(error_code
& PFERR_RSVD_MASK
))
3543 if (!(error_code
& PFERR_PRESENT_MASK
) ||
3544 !(error_code
& PFERR_WRITE_MASK
))
3548 * guest is writing the page which is write tracked which can
3549 * not be fixed by page fault handler.
3551 if (kvm_page_track_is_active(vcpu
, gfn
, KVM_PAGE_TRACK_WRITE
))
3557 static void shadow_page_table_clear_flood(struct kvm_vcpu
*vcpu
, gva_t addr
)
3559 struct kvm_shadow_walk_iterator iterator
;
3562 walk_shadow_page_lockless_begin(vcpu
);
3563 for_each_shadow_entry_lockless(vcpu
, addr
, iterator
, spte
) {
3564 clear_sp_write_flooding_count(iterator
.sptep
);
3565 if (!is_shadow_present_pte(spte
))
3568 walk_shadow_page_lockless_end(vcpu
);
3571 static bool kvm_arch_setup_async_pf(struct kvm_vcpu
*vcpu
, gpa_t cr2_or_gpa
,
3574 struct kvm_arch_async_pf arch
;
3576 arch
.token
= (vcpu
->arch
.apf
.id
++ << 12) | vcpu
->vcpu_id
;
3578 arch
.direct_map
= vcpu
->arch
.mmu
->direct_map
;
3579 arch
.cr3
= vcpu
->arch
.mmu
->get_guest_pgd(vcpu
);
3581 return kvm_setup_async_pf(vcpu
, cr2_or_gpa
,
3582 kvm_vcpu_gfn_to_hva(vcpu
, gfn
), &arch
);
3585 static bool try_async_pf(struct kvm_vcpu
*vcpu
, bool prefault
, gfn_t gfn
,
3586 gpa_t cr2_or_gpa
, kvm_pfn_t
*pfn
, bool write
,
3589 struct kvm_memory_slot
*slot
= kvm_vcpu_gfn_to_memslot(vcpu
, gfn
);
3592 /* Don't expose private memslots to L2. */
3593 if (is_guest_mode(vcpu
) && !kvm_is_visible_memslot(slot
)) {
3594 *pfn
= KVM_PFN_NOSLOT
;
3600 *pfn
= __gfn_to_pfn_memslot(slot
, gfn
, false, &async
, write
, writable
);
3602 return false; /* *pfn has correct page already */
3604 if (!prefault
&& kvm_can_do_async_pf(vcpu
)) {
3605 trace_kvm_try_async_get_page(cr2_or_gpa
, gfn
);
3606 if (kvm_find_async_pf_gfn(vcpu
, gfn
)) {
3607 trace_kvm_async_pf_doublefault(cr2_or_gpa
, gfn
);
3608 kvm_make_request(KVM_REQ_APF_HALT
, vcpu
);
3610 } else if (kvm_arch_setup_async_pf(vcpu
, cr2_or_gpa
, gfn
))
3614 *pfn
= __gfn_to_pfn_memslot(slot
, gfn
, false, NULL
, write
, writable
);
3618 static int direct_page_fault(struct kvm_vcpu
*vcpu
, gpa_t gpa
, u32 error_code
,
3619 bool prefault
, int max_level
, bool is_tdp
)
3621 bool write
= error_code
& PFERR_WRITE_MASK
;
3624 gfn_t gfn
= gpa
>> PAGE_SHIFT
;
3625 unsigned long mmu_seq
;
3629 if (page_fault_handle_page_track(vcpu
, error_code
, gfn
))
3630 return RET_PF_EMULATE
;
3632 r
= fast_page_fault(vcpu
, gpa
, error_code
);
3633 if (r
!= RET_PF_INVALID
)
3636 r
= mmu_topup_memory_caches(vcpu
, false);
3640 mmu_seq
= vcpu
->kvm
->mmu_notifier_seq
;
3643 if (try_async_pf(vcpu
, prefault
, gfn
, gpa
, &pfn
, write
, &map_writable
))
3644 return RET_PF_RETRY
;
3646 if (handle_abnormal_pfn(vcpu
, is_tdp
? 0 : gpa
, gfn
, pfn
, ACC_ALL
, &r
))
3650 spin_lock(&vcpu
->kvm
->mmu_lock
);
3651 if (mmu_notifier_retry(vcpu
->kvm
, mmu_seq
))
3653 r
= make_mmu_pages_available(vcpu
);
3656 r
= __direct_map(vcpu
, gpa
, error_code
, map_writable
, max_level
, pfn
,
3660 spin_unlock(&vcpu
->kvm
->mmu_lock
);
3661 kvm_release_pfn_clean(pfn
);
3665 static int nonpaging_page_fault(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
3666 u32 error_code
, bool prefault
)
3668 pgprintk("%s: gva %lx error %x\n", __func__
, gpa
, error_code
);
3670 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
3671 return direct_page_fault(vcpu
, gpa
& PAGE_MASK
, error_code
, prefault
,
3672 PG_LEVEL_2M
, false);
3675 int kvm_handle_page_fault(struct kvm_vcpu
*vcpu
, u64 error_code
,
3676 u64 fault_address
, char *insn
, int insn_len
)
3679 u32 flags
= vcpu
->arch
.apf
.host_apf_flags
;
3681 #ifndef CONFIG_X86_64
3682 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
3683 if (WARN_ON_ONCE(fault_address
>> 32))
3687 vcpu
->arch
.l1tf_flush_l1d
= true;
3689 trace_kvm_page_fault(fault_address
, error_code
);
3691 if (kvm_event_needs_reinjection(vcpu
))
3692 kvm_mmu_unprotect_page_virt(vcpu
, fault_address
);
3693 r
= kvm_mmu_page_fault(vcpu
, fault_address
, error_code
, insn
,
3695 } else if (flags
& KVM_PV_REASON_PAGE_NOT_PRESENT
) {
3696 vcpu
->arch
.apf
.host_apf_flags
= 0;
3697 local_irq_disable();
3698 kvm_async_pf_task_wait_schedule(fault_address
);
3701 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags
);
3706 EXPORT_SYMBOL_GPL(kvm_handle_page_fault
);
3708 int kvm_tdp_page_fault(struct kvm_vcpu
*vcpu
, gpa_t gpa
, u32 error_code
,
3713 for (max_level
= KVM_MAX_HUGEPAGE_LEVEL
;
3714 max_level
> PG_LEVEL_4K
;
3716 int page_num
= KVM_PAGES_PER_HPAGE(max_level
);
3717 gfn_t base
= (gpa
>> PAGE_SHIFT
) & ~(page_num
- 1);
3719 if (kvm_mtrr_check_gfn_range_consistency(vcpu
, base
, page_num
))
3723 return direct_page_fault(vcpu
, gpa
, error_code
, prefault
,
3727 static void nonpaging_init_context(struct kvm_vcpu
*vcpu
,
3728 struct kvm_mmu
*context
)
3730 context
->page_fault
= nonpaging_page_fault
;
3731 context
->gva_to_gpa
= nonpaging_gva_to_gpa
;
3732 context
->sync_page
= nonpaging_sync_page
;
3733 context
->invlpg
= NULL
;
3734 context
->update_pte
= nonpaging_update_pte
;
3735 context
->root_level
= 0;
3736 context
->shadow_root_level
= PT32E_ROOT_LEVEL
;
3737 context
->direct_map
= true;
3738 context
->nx
= false;
3741 static inline bool is_root_usable(struct kvm_mmu_root_info
*root
, gpa_t pgd
,
3742 union kvm_mmu_page_role role
)
3744 return (role
.direct
|| pgd
== root
->pgd
) &&
3745 VALID_PAGE(root
->hpa
) && to_shadow_page(root
->hpa
) &&
3746 role
.word
== to_shadow_page(root
->hpa
)->role
.word
;
3750 * Find out if a previously cached root matching the new pgd/role is available.
3751 * The current root is also inserted into the cache.
3752 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
3754 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
3755 * false is returned. This root should now be freed by the caller.
3757 static bool cached_root_available(struct kvm_vcpu
*vcpu
, gpa_t new_pgd
,
3758 union kvm_mmu_page_role new_role
)
3761 struct kvm_mmu_root_info root
;
3762 struct kvm_mmu
*mmu
= vcpu
->arch
.mmu
;
3764 root
.pgd
= mmu
->root_pgd
;
3765 root
.hpa
= mmu
->root_hpa
;
3767 if (is_root_usable(&root
, new_pgd
, new_role
))
3770 for (i
= 0; i
< KVM_MMU_NUM_PREV_ROOTS
; i
++) {
3771 swap(root
, mmu
->prev_roots
[i
]);
3773 if (is_root_usable(&root
, new_pgd
, new_role
))
3777 mmu
->root_hpa
= root
.hpa
;
3778 mmu
->root_pgd
= root
.pgd
;
3780 return i
< KVM_MMU_NUM_PREV_ROOTS
;
3783 static bool fast_pgd_switch(struct kvm_vcpu
*vcpu
, gpa_t new_pgd
,
3784 union kvm_mmu_page_role new_role
)
3786 struct kvm_mmu
*mmu
= vcpu
->arch
.mmu
;
3789 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
3790 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
3791 * later if necessary.
3793 if (mmu
->shadow_root_level
>= PT64_ROOT_4LEVEL
&&
3794 mmu
->root_level
>= PT64_ROOT_4LEVEL
)
3795 return cached_root_available(vcpu
, new_pgd
, new_role
);
3800 static void __kvm_mmu_new_pgd(struct kvm_vcpu
*vcpu
, gpa_t new_pgd
,
3801 union kvm_mmu_page_role new_role
,
3802 bool skip_tlb_flush
, bool skip_mmu_sync
)
3804 if (!fast_pgd_switch(vcpu
, new_pgd
, new_role
)) {
3805 kvm_mmu_free_roots(vcpu
, vcpu
->arch
.mmu
, KVM_MMU_ROOT_CURRENT
);
3810 * It's possible that the cached previous root page is obsolete because
3811 * of a change in the MMU generation number. However, changing the
3812 * generation number is accompanied by KVM_REQ_MMU_RELOAD, which will
3813 * free the root set here and allocate a new one.
3815 kvm_make_request(KVM_REQ_LOAD_MMU_PGD
, vcpu
);
3817 if (!skip_mmu_sync
|| force_flush_and_sync_on_reuse
)
3818 kvm_make_request(KVM_REQ_MMU_SYNC
, vcpu
);
3819 if (!skip_tlb_flush
|| force_flush_and_sync_on_reuse
)
3820 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT
, vcpu
);
3823 * The last MMIO access's GVA and GPA are cached in the VCPU. When
3824 * switching to a new CR3, that GVA->GPA mapping may no longer be
3825 * valid. So clear any cached MMIO info even when we don't need to sync
3826 * the shadow page tables.
3828 vcpu_clear_mmio_info(vcpu
, MMIO_GVA_ANY
);
3830 __clear_sp_write_flooding_count(to_shadow_page(vcpu
->arch
.mmu
->root_hpa
));
3833 void kvm_mmu_new_pgd(struct kvm_vcpu
*vcpu
, gpa_t new_pgd
, bool skip_tlb_flush
,
3836 __kvm_mmu_new_pgd(vcpu
, new_pgd
, kvm_mmu_calc_root_page_role(vcpu
),
3837 skip_tlb_flush
, skip_mmu_sync
);
3839 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd
);
3841 static unsigned long get_cr3(struct kvm_vcpu
*vcpu
)
3843 return kvm_read_cr3(vcpu
);
3846 static bool sync_mmio_spte(struct kvm_vcpu
*vcpu
, u64
*sptep
, gfn_t gfn
,
3847 unsigned int access
, int *nr_present
)
3849 if (unlikely(is_mmio_spte(*sptep
))) {
3850 if (gfn
!= get_mmio_spte_gfn(*sptep
)) {
3851 mmu_spte_clear_no_track(sptep
);
3856 mark_mmio_spte(vcpu
, sptep
, gfn
, access
);
3863 static inline bool is_last_gpte(struct kvm_mmu
*mmu
,
3864 unsigned level
, unsigned gpte
)
3867 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
3868 * If it is clear, there are no large pages at this level, so clear
3869 * PT_PAGE_SIZE_MASK in gpte if that is the case.
3871 gpte
&= level
- mmu
->last_nonleaf_level
;
3874 * PG_LEVEL_4K always terminates. The RHS has bit 7 set
3875 * iff level <= PG_LEVEL_4K, which for our purpose means
3876 * level == PG_LEVEL_4K; set PT_PAGE_SIZE_MASK in gpte then.
3878 gpte
|= level
- PG_LEVEL_4K
- 1;
3880 return gpte
& PT_PAGE_SIZE_MASK
;
3883 #define PTTYPE_EPT 18 /* arbitrary */
3884 #define PTTYPE PTTYPE_EPT
3885 #include "paging_tmpl.h"
3889 #include "paging_tmpl.h"
3893 #include "paging_tmpl.h"
3897 __reset_rsvds_bits_mask(struct kvm_vcpu
*vcpu
,
3898 struct rsvd_bits_validate
*rsvd_check
,
3899 int maxphyaddr
, int level
, bool nx
, bool gbpages
,
3902 u64 exb_bit_rsvd
= 0;
3903 u64 gbpages_bit_rsvd
= 0;
3904 u64 nonleaf_bit8_rsvd
= 0;
3906 rsvd_check
->bad_mt_xwr
= 0;
3909 exb_bit_rsvd
= rsvd_bits(63, 63);
3911 gbpages_bit_rsvd
= rsvd_bits(7, 7);
3914 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
3915 * leaf entries) on AMD CPUs only.
3918 nonleaf_bit8_rsvd
= rsvd_bits(8, 8);
3921 case PT32_ROOT_LEVEL
:
3922 /* no rsvd bits for 2 level 4K page table entries */
3923 rsvd_check
->rsvd_bits_mask
[0][1] = 0;
3924 rsvd_check
->rsvd_bits_mask
[0][0] = 0;
3925 rsvd_check
->rsvd_bits_mask
[1][0] =
3926 rsvd_check
->rsvd_bits_mask
[0][0];
3929 rsvd_check
->rsvd_bits_mask
[1][1] = 0;
3933 if (is_cpuid_PSE36())
3934 /* 36bits PSE 4MB page */
3935 rsvd_check
->rsvd_bits_mask
[1][1] = rsvd_bits(17, 21);
3937 /* 32 bits PSE 4MB page */
3938 rsvd_check
->rsvd_bits_mask
[1][1] = rsvd_bits(13, 21);
3940 case PT32E_ROOT_LEVEL
:
3941 rsvd_check
->rsvd_bits_mask
[0][2] =
3942 rsvd_bits(maxphyaddr
, 63) |
3943 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
3944 rsvd_check
->rsvd_bits_mask
[0][1] = exb_bit_rsvd
|
3945 rsvd_bits(maxphyaddr
, 62); /* PDE */
3946 rsvd_check
->rsvd_bits_mask
[0][0] = exb_bit_rsvd
|
3947 rsvd_bits(maxphyaddr
, 62); /* PTE */
3948 rsvd_check
->rsvd_bits_mask
[1][1] = exb_bit_rsvd
|
3949 rsvd_bits(maxphyaddr
, 62) |
3950 rsvd_bits(13, 20); /* large page */
3951 rsvd_check
->rsvd_bits_mask
[1][0] =
3952 rsvd_check
->rsvd_bits_mask
[0][0];
3954 case PT64_ROOT_5LEVEL
:
3955 rsvd_check
->rsvd_bits_mask
[0][4] = exb_bit_rsvd
|
3956 nonleaf_bit8_rsvd
| rsvd_bits(7, 7) |
3957 rsvd_bits(maxphyaddr
, 51);
3958 rsvd_check
->rsvd_bits_mask
[1][4] =
3959 rsvd_check
->rsvd_bits_mask
[0][4];
3961 case PT64_ROOT_4LEVEL
:
3962 rsvd_check
->rsvd_bits_mask
[0][3] = exb_bit_rsvd
|
3963 nonleaf_bit8_rsvd
| rsvd_bits(7, 7) |
3964 rsvd_bits(maxphyaddr
, 51);
3965 rsvd_check
->rsvd_bits_mask
[0][2] = exb_bit_rsvd
|
3967 rsvd_bits(maxphyaddr
, 51);
3968 rsvd_check
->rsvd_bits_mask
[0][1] = exb_bit_rsvd
|
3969 rsvd_bits(maxphyaddr
, 51);
3970 rsvd_check
->rsvd_bits_mask
[0][0] = exb_bit_rsvd
|
3971 rsvd_bits(maxphyaddr
, 51);
3972 rsvd_check
->rsvd_bits_mask
[1][3] =
3973 rsvd_check
->rsvd_bits_mask
[0][3];
3974 rsvd_check
->rsvd_bits_mask
[1][2] = exb_bit_rsvd
|
3975 gbpages_bit_rsvd
| rsvd_bits(maxphyaddr
, 51) |
3977 rsvd_check
->rsvd_bits_mask
[1][1] = exb_bit_rsvd
|
3978 rsvd_bits(maxphyaddr
, 51) |
3979 rsvd_bits(13, 20); /* large page */
3980 rsvd_check
->rsvd_bits_mask
[1][0] =
3981 rsvd_check
->rsvd_bits_mask
[0][0];
3986 static void reset_rsvds_bits_mask(struct kvm_vcpu
*vcpu
,
3987 struct kvm_mmu
*context
)
3989 __reset_rsvds_bits_mask(vcpu
, &context
->guest_rsvd_check
,
3990 cpuid_maxphyaddr(vcpu
), context
->root_level
,
3992 guest_cpuid_has(vcpu
, X86_FEATURE_GBPAGES
),
3994 guest_cpuid_is_amd_or_hygon(vcpu
));
3998 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate
*rsvd_check
,
3999 int maxphyaddr
, bool execonly
)
4003 rsvd_check
->rsvd_bits_mask
[0][4] =
4004 rsvd_bits(maxphyaddr
, 51) | rsvd_bits(3, 7);
4005 rsvd_check
->rsvd_bits_mask
[0][3] =
4006 rsvd_bits(maxphyaddr
, 51) | rsvd_bits(3, 7);
4007 rsvd_check
->rsvd_bits_mask
[0][2] =
4008 rsvd_bits(maxphyaddr
, 51) | rsvd_bits(3, 6);
4009 rsvd_check
->rsvd_bits_mask
[0][1] =
4010 rsvd_bits(maxphyaddr
, 51) | rsvd_bits(3, 6);
4011 rsvd_check
->rsvd_bits_mask
[0][0] = rsvd_bits(maxphyaddr
, 51);
4014 rsvd_check
->rsvd_bits_mask
[1][4] = rsvd_check
->rsvd_bits_mask
[0][4];
4015 rsvd_check
->rsvd_bits_mask
[1][3] = rsvd_check
->rsvd_bits_mask
[0][3];
4016 rsvd_check
->rsvd_bits_mask
[1][2] =
4017 rsvd_bits(maxphyaddr
, 51) | rsvd_bits(12, 29);
4018 rsvd_check
->rsvd_bits_mask
[1][1] =
4019 rsvd_bits(maxphyaddr
, 51) | rsvd_bits(12, 20);
4020 rsvd_check
->rsvd_bits_mask
[1][0] = rsvd_check
->rsvd_bits_mask
[0][0];
4022 bad_mt_xwr
= 0xFFull
<< (2 * 8); /* bits 3..5 must not be 2 */
4023 bad_mt_xwr
|= 0xFFull
<< (3 * 8); /* bits 3..5 must not be 3 */
4024 bad_mt_xwr
|= 0xFFull
<< (7 * 8); /* bits 3..5 must not be 7 */
4025 bad_mt_xwr
|= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4026 bad_mt_xwr
|= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4028 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4029 bad_mt_xwr
|= REPEAT_BYTE(1ull << 4);
4031 rsvd_check
->bad_mt_xwr
= bad_mt_xwr
;
4034 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu
*vcpu
,
4035 struct kvm_mmu
*context
, bool execonly
)
4037 __reset_rsvds_bits_mask_ept(&context
->guest_rsvd_check
,
4038 cpuid_maxphyaddr(vcpu
), execonly
);
4042 * the page table on host is the shadow page table for the page
4043 * table in guest or amd nested guest, its mmu features completely
4044 * follow the features in guest.
4047 reset_shadow_zero_bits_mask(struct kvm_vcpu
*vcpu
, struct kvm_mmu
*context
)
4049 bool uses_nx
= context
->nx
||
4050 context
->mmu_role
.base
.smep_andnot_wp
;
4051 struct rsvd_bits_validate
*shadow_zero_check
;
4055 * Passing "true" to the last argument is okay; it adds a check
4056 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4058 shadow_zero_check
= &context
->shadow_zero_check
;
4059 __reset_rsvds_bits_mask(vcpu
, shadow_zero_check
,
4061 context
->shadow_root_level
, uses_nx
,
4062 guest_cpuid_has(vcpu
, X86_FEATURE_GBPAGES
),
4063 is_pse(vcpu
), true);
4065 if (!shadow_me_mask
)
4068 for (i
= context
->shadow_root_level
; --i
>= 0;) {
4069 shadow_zero_check
->rsvd_bits_mask
[0][i
] &= ~shadow_me_mask
;
4070 shadow_zero_check
->rsvd_bits_mask
[1][i
] &= ~shadow_me_mask
;
4074 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask
);
4076 static inline bool boot_cpu_is_amd(void)
4078 WARN_ON_ONCE(!tdp_enabled
);
4079 return shadow_x_mask
== 0;
4083 * the direct page table on host, use as much mmu features as
4084 * possible, however, kvm currently does not do execution-protection.
4087 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu
*vcpu
,
4088 struct kvm_mmu
*context
)
4090 struct rsvd_bits_validate
*shadow_zero_check
;
4093 shadow_zero_check
= &context
->shadow_zero_check
;
4095 if (boot_cpu_is_amd())
4096 __reset_rsvds_bits_mask(vcpu
, shadow_zero_check
,
4098 context
->shadow_root_level
, false,
4099 boot_cpu_has(X86_FEATURE_GBPAGES
),
4102 __reset_rsvds_bits_mask_ept(shadow_zero_check
,
4106 if (!shadow_me_mask
)
4109 for (i
= context
->shadow_root_level
; --i
>= 0;) {
4110 shadow_zero_check
->rsvd_bits_mask
[0][i
] &= ~shadow_me_mask
;
4111 shadow_zero_check
->rsvd_bits_mask
[1][i
] &= ~shadow_me_mask
;
4116 * as the comments in reset_shadow_zero_bits_mask() except it
4117 * is the shadow page table for intel nested guest.
4120 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu
*vcpu
,
4121 struct kvm_mmu
*context
, bool execonly
)
4123 __reset_rsvds_bits_mask_ept(&context
->shadow_zero_check
,
4124 shadow_phys_bits
, execonly
);
4127 #define BYTE_MASK(access) \
4128 ((1 & (access) ? 2 : 0) | \
4129 (2 & (access) ? 4 : 0) | \
4130 (3 & (access) ? 8 : 0) | \
4131 (4 & (access) ? 16 : 0) | \
4132 (5 & (access) ? 32 : 0) | \
4133 (6 & (access) ? 64 : 0) | \
4134 (7 & (access) ? 128 : 0))
4137 static void update_permission_bitmask(struct kvm_vcpu
*vcpu
,
4138 struct kvm_mmu
*mmu
, bool ept
)
4142 const u8 x
= BYTE_MASK(ACC_EXEC_MASK
);
4143 const u8 w
= BYTE_MASK(ACC_WRITE_MASK
);
4144 const u8 u
= BYTE_MASK(ACC_USER_MASK
);
4146 bool cr4_smep
= kvm_read_cr4_bits(vcpu
, X86_CR4_SMEP
) != 0;
4147 bool cr4_smap
= kvm_read_cr4_bits(vcpu
, X86_CR4_SMAP
) != 0;
4148 bool cr0_wp
= is_write_protection(vcpu
);
4150 for (byte
= 0; byte
< ARRAY_SIZE(mmu
->permissions
); ++byte
) {
4151 unsigned pfec
= byte
<< 1;
4154 * Each "*f" variable has a 1 bit for each UWX value
4155 * that causes a fault with the given PFEC.
4158 /* Faults from writes to non-writable pages */
4159 u8 wf
= (pfec
& PFERR_WRITE_MASK
) ? (u8
)~w
: 0;
4160 /* Faults from user mode accesses to supervisor pages */
4161 u8 uf
= (pfec
& PFERR_USER_MASK
) ? (u8
)~u
: 0;
4162 /* Faults from fetches of non-executable pages*/
4163 u8 ff
= (pfec
& PFERR_FETCH_MASK
) ? (u8
)~x
: 0;
4164 /* Faults from kernel mode fetches of user pages */
4166 /* Faults from kernel mode accesses of user pages */
4170 /* Faults from kernel mode accesses to user pages */
4171 u8 kf
= (pfec
& PFERR_USER_MASK
) ? 0 : u
;
4173 /* Not really needed: !nx will cause pte.nx to fault */
4177 /* Allow supervisor writes if !cr0.wp */
4179 wf
= (pfec
& PFERR_USER_MASK
) ? wf
: 0;
4181 /* Disallow supervisor fetches of user code if cr4.smep */
4183 smepf
= (pfec
& PFERR_FETCH_MASK
) ? kf
: 0;
4186 * SMAP:kernel-mode data accesses from user-mode
4187 * mappings should fault. A fault is considered
4188 * as a SMAP violation if all of the following
4189 * conditions are true:
4190 * - X86_CR4_SMAP is set in CR4
4191 * - A user page is accessed
4192 * - The access is not a fetch
4193 * - Page fault in kernel mode
4194 * - if CPL = 3 or X86_EFLAGS_AC is clear
4196 * Here, we cover the first three conditions.
4197 * The fourth is computed dynamically in permission_fault();
4198 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4199 * *not* subject to SMAP restrictions.
4202 smapf
= (pfec
& (PFERR_RSVD_MASK
|PFERR_FETCH_MASK
)) ? 0 : kf
;
4205 mmu
->permissions
[byte
] = ff
| uf
| wf
| smepf
| smapf
;
4210 * PKU is an additional mechanism by which the paging controls access to
4211 * user-mode addresses based on the value in the PKRU register. Protection
4212 * key violations are reported through a bit in the page fault error code.
4213 * Unlike other bits of the error code, the PK bit is not known at the
4214 * call site of e.g. gva_to_gpa; it must be computed directly in
4215 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4216 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4218 * In particular the following conditions come from the error code, the
4219 * page tables and the machine state:
4220 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4221 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4222 * - PK is always zero if U=0 in the page tables
4223 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4225 * The PKRU bitmask caches the result of these four conditions. The error
4226 * code (minus the P bit) and the page table's U bit form an index into the
4227 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4228 * with the two bits of the PKRU register corresponding to the protection key.
4229 * For the first three conditions above the bits will be 00, thus masking
4230 * away both AD and WD. For all reads or if the last condition holds, WD
4231 * only will be masked away.
4233 static void update_pkru_bitmask(struct kvm_vcpu
*vcpu
, struct kvm_mmu
*mmu
,
4244 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4245 if (!kvm_read_cr4_bits(vcpu
, X86_CR4_PKE
) || !is_long_mode(vcpu
)) {
4250 wp
= is_write_protection(vcpu
);
4252 for (bit
= 0; bit
< ARRAY_SIZE(mmu
->permissions
); ++bit
) {
4253 unsigned pfec
, pkey_bits
;
4254 bool check_pkey
, check_write
, ff
, uf
, wf
, pte_user
;
4257 ff
= pfec
& PFERR_FETCH_MASK
;
4258 uf
= pfec
& PFERR_USER_MASK
;
4259 wf
= pfec
& PFERR_WRITE_MASK
;
4261 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4262 pte_user
= pfec
& PFERR_RSVD_MASK
;
4265 * Only need to check the access which is not an
4266 * instruction fetch and is to a user page.
4268 check_pkey
= (!ff
&& pte_user
);
4270 * write access is controlled by PKRU if it is a
4271 * user access or CR0.WP = 1.
4273 check_write
= check_pkey
&& wf
&& (uf
|| wp
);
4275 /* PKRU.AD stops both read and write access. */
4276 pkey_bits
= !!check_pkey
;
4277 /* PKRU.WD stops write access. */
4278 pkey_bits
|= (!!check_write
) << 1;
4280 mmu
->pkru_mask
|= (pkey_bits
& 3) << pfec
;
4284 static void update_last_nonleaf_level(struct kvm_vcpu
*vcpu
, struct kvm_mmu
*mmu
)
4286 unsigned root_level
= mmu
->root_level
;
4288 mmu
->last_nonleaf_level
= root_level
;
4289 if (root_level
== PT32_ROOT_LEVEL
&& is_pse(vcpu
))
4290 mmu
->last_nonleaf_level
++;
4293 static void paging64_init_context_common(struct kvm_vcpu
*vcpu
,
4294 struct kvm_mmu
*context
,
4297 context
->nx
= is_nx(vcpu
);
4298 context
->root_level
= level
;
4300 reset_rsvds_bits_mask(vcpu
, context
);
4301 update_permission_bitmask(vcpu
, context
, false);
4302 update_pkru_bitmask(vcpu
, context
, false);
4303 update_last_nonleaf_level(vcpu
, context
);
4305 MMU_WARN_ON(!is_pae(vcpu
));
4306 context
->page_fault
= paging64_page_fault
;
4307 context
->gva_to_gpa
= paging64_gva_to_gpa
;
4308 context
->sync_page
= paging64_sync_page
;
4309 context
->invlpg
= paging64_invlpg
;
4310 context
->update_pte
= paging64_update_pte
;
4311 context
->shadow_root_level
= level
;
4312 context
->direct_map
= false;
4315 static void paging64_init_context(struct kvm_vcpu
*vcpu
,
4316 struct kvm_mmu
*context
)
4318 int root_level
= is_la57_mode(vcpu
) ?
4319 PT64_ROOT_5LEVEL
: PT64_ROOT_4LEVEL
;
4321 paging64_init_context_common(vcpu
, context
, root_level
);
4324 static void paging32_init_context(struct kvm_vcpu
*vcpu
,
4325 struct kvm_mmu
*context
)
4327 context
->nx
= false;
4328 context
->root_level
= PT32_ROOT_LEVEL
;
4330 reset_rsvds_bits_mask(vcpu
, context
);
4331 update_permission_bitmask(vcpu
, context
, false);
4332 update_pkru_bitmask(vcpu
, context
, false);
4333 update_last_nonleaf_level(vcpu
, context
);
4335 context
->page_fault
= paging32_page_fault
;
4336 context
->gva_to_gpa
= paging32_gva_to_gpa
;
4337 context
->sync_page
= paging32_sync_page
;
4338 context
->invlpg
= paging32_invlpg
;
4339 context
->update_pte
= paging32_update_pte
;
4340 context
->shadow_root_level
= PT32E_ROOT_LEVEL
;
4341 context
->direct_map
= false;
4344 static void paging32E_init_context(struct kvm_vcpu
*vcpu
,
4345 struct kvm_mmu
*context
)
4347 paging64_init_context_common(vcpu
, context
, PT32E_ROOT_LEVEL
);
4350 static union kvm_mmu_extended_role
kvm_calc_mmu_role_ext(struct kvm_vcpu
*vcpu
)
4352 union kvm_mmu_extended_role ext
= {0};
4354 ext
.cr0_pg
= !!is_paging(vcpu
);
4355 ext
.cr4_pae
= !!is_pae(vcpu
);
4356 ext
.cr4_smep
= !!kvm_read_cr4_bits(vcpu
, X86_CR4_SMEP
);
4357 ext
.cr4_smap
= !!kvm_read_cr4_bits(vcpu
, X86_CR4_SMAP
);
4358 ext
.cr4_pse
= !!is_pse(vcpu
);
4359 ext
.cr4_pke
= !!kvm_read_cr4_bits(vcpu
, X86_CR4_PKE
);
4360 ext
.maxphyaddr
= cpuid_maxphyaddr(vcpu
);
4367 static union kvm_mmu_role
kvm_calc_mmu_role_common(struct kvm_vcpu
*vcpu
,
4370 union kvm_mmu_role role
= {0};
4372 role
.base
.access
= ACC_ALL
;
4373 role
.base
.nxe
= !!is_nx(vcpu
);
4374 role
.base
.cr0_wp
= is_write_protection(vcpu
);
4375 role
.base
.smm
= is_smm(vcpu
);
4376 role
.base
.guest_mode
= is_guest_mode(vcpu
);
4381 role
.ext
= kvm_calc_mmu_role_ext(vcpu
);
4386 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu
*vcpu
)
4388 /* Use 5-level TDP if and only if it's useful/necessary. */
4389 if (max_tdp_level
== 5 && cpuid_maxphyaddr(vcpu
) <= 48)
4392 return max_tdp_level
;
4395 static union kvm_mmu_role
4396 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu
*vcpu
, bool base_only
)
4398 union kvm_mmu_role role
= kvm_calc_mmu_role_common(vcpu
, base_only
);
4400 role
.base
.ad_disabled
= (shadow_accessed_mask
== 0);
4401 role
.base
.level
= kvm_mmu_get_tdp_level(vcpu
);
4402 role
.base
.direct
= true;
4403 role
.base
.gpte_is_8_bytes
= true;
4408 static void init_kvm_tdp_mmu(struct kvm_vcpu
*vcpu
)
4410 struct kvm_mmu
*context
= &vcpu
->arch
.root_mmu
;
4411 union kvm_mmu_role new_role
=
4412 kvm_calc_tdp_mmu_root_page_role(vcpu
, false);
4414 if (new_role
.as_u64
== context
->mmu_role
.as_u64
)
4417 context
->mmu_role
.as_u64
= new_role
.as_u64
;
4418 context
->page_fault
= kvm_tdp_page_fault
;
4419 context
->sync_page
= nonpaging_sync_page
;
4420 context
->invlpg
= NULL
;
4421 context
->update_pte
= nonpaging_update_pte
;
4422 context
->shadow_root_level
= kvm_mmu_get_tdp_level(vcpu
);
4423 context
->direct_map
= true;
4424 context
->get_guest_pgd
= get_cr3
;
4425 context
->get_pdptr
= kvm_pdptr_read
;
4426 context
->inject_page_fault
= kvm_inject_page_fault
;
4428 if (!is_paging(vcpu
)) {
4429 context
->nx
= false;
4430 context
->gva_to_gpa
= nonpaging_gva_to_gpa
;
4431 context
->root_level
= 0;
4432 } else if (is_long_mode(vcpu
)) {
4433 context
->nx
= is_nx(vcpu
);
4434 context
->root_level
= is_la57_mode(vcpu
) ?
4435 PT64_ROOT_5LEVEL
: PT64_ROOT_4LEVEL
;
4436 reset_rsvds_bits_mask(vcpu
, context
);
4437 context
->gva_to_gpa
= paging64_gva_to_gpa
;
4438 } else if (is_pae(vcpu
)) {
4439 context
->nx
= is_nx(vcpu
);
4440 context
->root_level
= PT32E_ROOT_LEVEL
;
4441 reset_rsvds_bits_mask(vcpu
, context
);
4442 context
->gva_to_gpa
= paging64_gva_to_gpa
;
4444 context
->nx
= false;
4445 context
->root_level
= PT32_ROOT_LEVEL
;
4446 reset_rsvds_bits_mask(vcpu
, context
);
4447 context
->gva_to_gpa
= paging32_gva_to_gpa
;
4450 update_permission_bitmask(vcpu
, context
, false);
4451 update_pkru_bitmask(vcpu
, context
, false);
4452 update_last_nonleaf_level(vcpu
, context
);
4453 reset_tdp_shadow_zero_bits_mask(vcpu
, context
);
4456 static union kvm_mmu_role
4457 kvm_calc_shadow_root_page_role_common(struct kvm_vcpu
*vcpu
, bool base_only
)
4459 union kvm_mmu_role role
= kvm_calc_mmu_role_common(vcpu
, base_only
);
4461 role
.base
.smep_andnot_wp
= role
.ext
.cr4_smep
&&
4462 !is_write_protection(vcpu
);
4463 role
.base
.smap_andnot_wp
= role
.ext
.cr4_smap
&&
4464 !is_write_protection(vcpu
);
4465 role
.base
.gpte_is_8_bytes
= !!is_pae(vcpu
);
4470 static union kvm_mmu_role
4471 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu
*vcpu
, bool base_only
)
4473 union kvm_mmu_role role
=
4474 kvm_calc_shadow_root_page_role_common(vcpu
, base_only
);
4476 role
.base
.direct
= !is_paging(vcpu
);
4478 if (!is_long_mode(vcpu
))
4479 role
.base
.level
= PT32E_ROOT_LEVEL
;
4480 else if (is_la57_mode(vcpu
))
4481 role
.base
.level
= PT64_ROOT_5LEVEL
;
4483 role
.base
.level
= PT64_ROOT_4LEVEL
;
4488 static void shadow_mmu_init_context(struct kvm_vcpu
*vcpu
, struct kvm_mmu
*context
,
4489 u32 cr0
, u32 cr4
, u32 efer
,
4490 union kvm_mmu_role new_role
)
4492 if (!(cr0
& X86_CR0_PG
))
4493 nonpaging_init_context(vcpu
, context
);
4494 else if (efer
& EFER_LMA
)
4495 paging64_init_context(vcpu
, context
);
4496 else if (cr4
& X86_CR4_PAE
)
4497 paging32E_init_context(vcpu
, context
);
4499 paging32_init_context(vcpu
, context
);
4501 context
->mmu_role
.as_u64
= new_role
.as_u64
;
4502 reset_shadow_zero_bits_mask(vcpu
, context
);
4505 static void kvm_init_shadow_mmu(struct kvm_vcpu
*vcpu
, u32 cr0
, u32 cr4
, u32 efer
)
4507 struct kvm_mmu
*context
= &vcpu
->arch
.root_mmu
;
4508 union kvm_mmu_role new_role
=
4509 kvm_calc_shadow_mmu_root_page_role(vcpu
, false);
4511 if (new_role
.as_u64
!= context
->mmu_role
.as_u64
)
4512 shadow_mmu_init_context(vcpu
, context
, cr0
, cr4
, efer
, new_role
);
4515 static union kvm_mmu_role
4516 kvm_calc_shadow_npt_root_page_role(struct kvm_vcpu
*vcpu
)
4518 union kvm_mmu_role role
=
4519 kvm_calc_shadow_root_page_role_common(vcpu
, false);
4521 role
.base
.direct
= false;
4522 role
.base
.level
= kvm_mmu_get_tdp_level(vcpu
);
4527 void kvm_init_shadow_npt_mmu(struct kvm_vcpu
*vcpu
, u32 cr0
, u32 cr4
, u32 efer
,
4530 struct kvm_mmu
*context
= &vcpu
->arch
.guest_mmu
;
4531 union kvm_mmu_role new_role
= kvm_calc_shadow_npt_root_page_role(vcpu
);
4533 context
->shadow_root_level
= new_role
.base
.level
;
4535 __kvm_mmu_new_pgd(vcpu
, nested_cr3
, new_role
.base
, false, false);
4537 if (new_role
.as_u64
!= context
->mmu_role
.as_u64
)
4538 shadow_mmu_init_context(vcpu
, context
, cr0
, cr4
, efer
, new_role
);
4540 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu
);
4542 static union kvm_mmu_role
4543 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu
*vcpu
, bool accessed_dirty
,
4544 bool execonly
, u8 level
)
4546 union kvm_mmu_role role
= {0};
4548 /* SMM flag is inherited from root_mmu */
4549 role
.base
.smm
= vcpu
->arch
.root_mmu
.mmu_role
.base
.smm
;
4551 role
.base
.level
= level
;
4552 role
.base
.gpte_is_8_bytes
= true;
4553 role
.base
.direct
= false;
4554 role
.base
.ad_disabled
= !accessed_dirty
;
4555 role
.base
.guest_mode
= true;
4556 role
.base
.access
= ACC_ALL
;
4559 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
4560 * SMAP variation to denote shadow EPT entries.
4562 role
.base
.cr0_wp
= true;
4563 role
.base
.smap_andnot_wp
= true;
4565 role
.ext
= kvm_calc_mmu_role_ext(vcpu
);
4566 role
.ext
.execonly
= execonly
;
4571 void kvm_init_shadow_ept_mmu(struct kvm_vcpu
*vcpu
, bool execonly
,
4572 bool accessed_dirty
, gpa_t new_eptp
)
4574 struct kvm_mmu
*context
= &vcpu
->arch
.guest_mmu
;
4575 u8 level
= vmx_eptp_page_walk_level(new_eptp
);
4576 union kvm_mmu_role new_role
=
4577 kvm_calc_shadow_ept_root_page_role(vcpu
, accessed_dirty
,
4580 __kvm_mmu_new_pgd(vcpu
, new_eptp
, new_role
.base
, true, true);
4582 if (new_role
.as_u64
== context
->mmu_role
.as_u64
)
4585 context
->shadow_root_level
= level
;
4588 context
->ept_ad
= accessed_dirty
;
4589 context
->page_fault
= ept_page_fault
;
4590 context
->gva_to_gpa
= ept_gva_to_gpa
;
4591 context
->sync_page
= ept_sync_page
;
4592 context
->invlpg
= ept_invlpg
;
4593 context
->update_pte
= ept_update_pte
;
4594 context
->root_level
= level
;
4595 context
->direct_map
= false;
4596 context
->mmu_role
.as_u64
= new_role
.as_u64
;
4598 update_permission_bitmask(vcpu
, context
, true);
4599 update_pkru_bitmask(vcpu
, context
, true);
4600 update_last_nonleaf_level(vcpu
, context
);
4601 reset_rsvds_bits_mask_ept(vcpu
, context
, execonly
);
4602 reset_ept_shadow_zero_bits_mask(vcpu
, context
, execonly
);
4604 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu
);
4606 static void init_kvm_softmmu(struct kvm_vcpu
*vcpu
)
4608 struct kvm_mmu
*context
= &vcpu
->arch
.root_mmu
;
4610 kvm_init_shadow_mmu(vcpu
,
4611 kvm_read_cr0_bits(vcpu
, X86_CR0_PG
),
4612 kvm_read_cr4_bits(vcpu
, X86_CR4_PAE
),
4615 context
->get_guest_pgd
= get_cr3
;
4616 context
->get_pdptr
= kvm_pdptr_read
;
4617 context
->inject_page_fault
= kvm_inject_page_fault
;
4620 static void init_kvm_nested_mmu(struct kvm_vcpu
*vcpu
)
4622 union kvm_mmu_role new_role
= kvm_calc_mmu_role_common(vcpu
, false);
4623 struct kvm_mmu
*g_context
= &vcpu
->arch
.nested_mmu
;
4625 if (new_role
.as_u64
== g_context
->mmu_role
.as_u64
)
4628 g_context
->mmu_role
.as_u64
= new_role
.as_u64
;
4629 g_context
->get_guest_pgd
= get_cr3
;
4630 g_context
->get_pdptr
= kvm_pdptr_read
;
4631 g_context
->inject_page_fault
= kvm_inject_page_fault
;
4634 * L2 page tables are never shadowed, so there is no need to sync
4637 g_context
->invlpg
= NULL
;
4640 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
4641 * L1's nested page tables (e.g. EPT12). The nested translation
4642 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4643 * L2's page tables as the first level of translation and L1's
4644 * nested page tables as the second level of translation. Basically
4645 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
4647 if (!is_paging(vcpu
)) {
4648 g_context
->nx
= false;
4649 g_context
->root_level
= 0;
4650 g_context
->gva_to_gpa
= nonpaging_gva_to_gpa_nested
;
4651 } else if (is_long_mode(vcpu
)) {
4652 g_context
->nx
= is_nx(vcpu
);
4653 g_context
->root_level
= is_la57_mode(vcpu
) ?
4654 PT64_ROOT_5LEVEL
: PT64_ROOT_4LEVEL
;
4655 reset_rsvds_bits_mask(vcpu
, g_context
);
4656 g_context
->gva_to_gpa
= paging64_gva_to_gpa_nested
;
4657 } else if (is_pae(vcpu
)) {
4658 g_context
->nx
= is_nx(vcpu
);
4659 g_context
->root_level
= PT32E_ROOT_LEVEL
;
4660 reset_rsvds_bits_mask(vcpu
, g_context
);
4661 g_context
->gva_to_gpa
= paging64_gva_to_gpa_nested
;
4663 g_context
->nx
= false;
4664 g_context
->root_level
= PT32_ROOT_LEVEL
;
4665 reset_rsvds_bits_mask(vcpu
, g_context
);
4666 g_context
->gva_to_gpa
= paging32_gva_to_gpa_nested
;
4669 update_permission_bitmask(vcpu
, g_context
, false);
4670 update_pkru_bitmask(vcpu
, g_context
, false);
4671 update_last_nonleaf_level(vcpu
, g_context
);
4674 void kvm_init_mmu(struct kvm_vcpu
*vcpu
, bool reset_roots
)
4679 vcpu
->arch
.mmu
->root_hpa
= INVALID_PAGE
;
4681 for (i
= 0; i
< KVM_MMU_NUM_PREV_ROOTS
; i
++)
4682 vcpu
->arch
.mmu
->prev_roots
[i
] = KVM_MMU_ROOT_INFO_INVALID
;
4685 if (mmu_is_nested(vcpu
))
4686 init_kvm_nested_mmu(vcpu
);
4687 else if (tdp_enabled
)
4688 init_kvm_tdp_mmu(vcpu
);
4690 init_kvm_softmmu(vcpu
);
4692 EXPORT_SYMBOL_GPL(kvm_init_mmu
);
4694 static union kvm_mmu_page_role
4695 kvm_mmu_calc_root_page_role(struct kvm_vcpu
*vcpu
)
4697 union kvm_mmu_role role
;
4700 role
= kvm_calc_tdp_mmu_root_page_role(vcpu
, true);
4702 role
= kvm_calc_shadow_mmu_root_page_role(vcpu
, true);
4707 void kvm_mmu_reset_context(struct kvm_vcpu
*vcpu
)
4709 kvm_mmu_unload(vcpu
);
4710 kvm_init_mmu(vcpu
, true);
4712 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context
);
4714 int kvm_mmu_load(struct kvm_vcpu
*vcpu
)
4718 r
= mmu_topup_memory_caches(vcpu
, !vcpu
->arch
.mmu
->direct_map
);
4721 r
= mmu_alloc_roots(vcpu
);
4722 kvm_mmu_sync_roots(vcpu
);
4725 kvm_mmu_load_pgd(vcpu
);
4726 kvm_x86_ops
.tlb_flush_current(vcpu
);
4730 EXPORT_SYMBOL_GPL(kvm_mmu_load
);
4732 void kvm_mmu_unload(struct kvm_vcpu
*vcpu
)
4734 kvm_mmu_free_roots(vcpu
, &vcpu
->arch
.root_mmu
, KVM_MMU_ROOTS_ALL
);
4735 WARN_ON(VALID_PAGE(vcpu
->arch
.root_mmu
.root_hpa
));
4736 kvm_mmu_free_roots(vcpu
, &vcpu
->arch
.guest_mmu
, KVM_MMU_ROOTS_ALL
);
4737 WARN_ON(VALID_PAGE(vcpu
->arch
.guest_mmu
.root_hpa
));
4739 EXPORT_SYMBOL_GPL(kvm_mmu_unload
);
4741 static void mmu_pte_write_new_pte(struct kvm_vcpu
*vcpu
,
4742 struct kvm_mmu_page
*sp
, u64
*spte
,
4745 if (sp
->role
.level
!= PG_LEVEL_4K
) {
4746 ++vcpu
->kvm
->stat
.mmu_pde_zapped
;
4750 ++vcpu
->kvm
->stat
.mmu_pte_updated
;
4751 vcpu
->arch
.mmu
->update_pte(vcpu
, sp
, spte
, new);
4754 static bool need_remote_flush(u64 old
, u64
new)
4756 if (!is_shadow_present_pte(old
))
4758 if (!is_shadow_present_pte(new))
4760 if ((old
^ new) & PT64_BASE_ADDR_MASK
)
4762 old
^= shadow_nx_mask
;
4763 new ^= shadow_nx_mask
;
4764 return (old
& ~new & PT64_PERM_MASK
) != 0;
4767 static u64
mmu_pte_write_fetch_gpte(struct kvm_vcpu
*vcpu
, gpa_t
*gpa
,
4774 * Assume that the pte write on a page table of the same type
4775 * as the current vcpu paging mode since we update the sptes only
4776 * when they have the same mode.
4778 if (is_pae(vcpu
) && *bytes
== 4) {
4779 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
4784 if (*bytes
== 4 || *bytes
== 8) {
4785 r
= kvm_vcpu_read_guest_atomic(vcpu
, *gpa
, &gentry
, *bytes
);
4794 * If we're seeing too many writes to a page, it may no longer be a page table,
4795 * or we may be forking, in which case it is better to unmap the page.
4797 static bool detect_write_flooding(struct kvm_mmu_page
*sp
)
4800 * Skip write-flooding detected for the sp whose level is 1, because
4801 * it can become unsync, then the guest page is not write-protected.
4803 if (sp
->role
.level
== PG_LEVEL_4K
)
4806 atomic_inc(&sp
->write_flooding_count
);
4807 return atomic_read(&sp
->write_flooding_count
) >= 3;
4811 * Misaligned accesses are too much trouble to fix up; also, they usually
4812 * indicate a page is not used as a page table.
4814 static bool detect_write_misaligned(struct kvm_mmu_page
*sp
, gpa_t gpa
,
4817 unsigned offset
, pte_size
, misaligned
;
4819 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
4820 gpa
, bytes
, sp
->role
.word
);
4822 offset
= offset_in_page(gpa
);
4823 pte_size
= sp
->role
.gpte_is_8_bytes
? 8 : 4;
4826 * Sometimes, the OS only writes the last one bytes to update status
4827 * bits, for example, in linux, andb instruction is used in clear_bit().
4829 if (!(offset
& (pte_size
- 1)) && bytes
== 1)
4832 misaligned
= (offset
^ (offset
+ bytes
- 1)) & ~(pte_size
- 1);
4833 misaligned
|= bytes
< 4;
4838 static u64
*get_written_sptes(struct kvm_mmu_page
*sp
, gpa_t gpa
, int *nspte
)
4840 unsigned page_offset
, quadrant
;
4844 page_offset
= offset_in_page(gpa
);
4845 level
= sp
->role
.level
;
4847 if (!sp
->role
.gpte_is_8_bytes
) {
4848 page_offset
<<= 1; /* 32->64 */
4850 * A 32-bit pde maps 4MB while the shadow pdes map
4851 * only 2MB. So we need to double the offset again
4852 * and zap two pdes instead of one.
4854 if (level
== PT32_ROOT_LEVEL
) {
4855 page_offset
&= ~7; /* kill rounding error */
4859 quadrant
= page_offset
>> PAGE_SHIFT
;
4860 page_offset
&= ~PAGE_MASK
;
4861 if (quadrant
!= sp
->role
.quadrant
)
4865 spte
= &sp
->spt
[page_offset
/ sizeof(*spte
)];
4870 * Ignore various flags when determining if a SPTE can be immediately
4871 * overwritten for the current MMU.
4872 * - level: explicitly checked in mmu_pte_write_new_pte(), and will never
4873 * match the current MMU role, as MMU's level tracks the root level.
4874 * - access: updated based on the new guest PTE
4875 * - quadrant: handled by get_written_sptes()
4876 * - invalid: always false (loop only walks valid shadow pages)
4878 static const union kvm_mmu_page_role role_ign
= {
4885 static void kvm_mmu_pte_write(struct kvm_vcpu
*vcpu
, gpa_t gpa
,
4886 const u8
*new, int bytes
,
4887 struct kvm_page_track_notifier_node
*node
)
4889 gfn_t gfn
= gpa
>> PAGE_SHIFT
;
4890 struct kvm_mmu_page
*sp
;
4891 LIST_HEAD(invalid_list
);
4892 u64 entry
, gentry
, *spte
;
4894 bool remote_flush
, local_flush
;
4897 * If we don't have indirect shadow pages, it means no page is
4898 * write-protected, so we can exit simply.
4900 if (!READ_ONCE(vcpu
->kvm
->arch
.indirect_shadow_pages
))
4903 remote_flush
= local_flush
= false;
4905 pgprintk("%s: gpa %llx bytes %d\n", __func__
, gpa
, bytes
);
4908 * No need to care whether allocation memory is successful
4909 * or not since pte prefetch is skiped if it does not have
4910 * enough objects in the cache.
4912 mmu_topup_memory_caches(vcpu
, true);
4914 spin_lock(&vcpu
->kvm
->mmu_lock
);
4916 gentry
= mmu_pte_write_fetch_gpte(vcpu
, &gpa
, &bytes
);
4918 ++vcpu
->kvm
->stat
.mmu_pte_write
;
4919 kvm_mmu_audit(vcpu
, AUDIT_PRE_PTE_WRITE
);
4921 for_each_gfn_indirect_valid_sp(vcpu
->kvm
, sp
, gfn
) {
4922 if (detect_write_misaligned(sp
, gpa
, bytes
) ||
4923 detect_write_flooding(sp
)) {
4924 kvm_mmu_prepare_zap_page(vcpu
->kvm
, sp
, &invalid_list
);
4925 ++vcpu
->kvm
->stat
.mmu_flooded
;
4929 spte
= get_written_sptes(sp
, gpa
, &npte
);
4935 u32 base_role
= vcpu
->arch
.mmu
->mmu_role
.base
.word
;
4938 mmu_page_zap_pte(vcpu
->kvm
, sp
, spte
, NULL
);
4940 !((sp
->role
.word
^ base_role
) & ~role_ign
.word
) &&
4942 mmu_pte_write_new_pte(vcpu
, sp
, spte
, &gentry
);
4943 if (need_remote_flush(entry
, *spte
))
4944 remote_flush
= true;
4948 kvm_mmu_flush_or_zap(vcpu
, &invalid_list
, remote_flush
, local_flush
);
4949 kvm_mmu_audit(vcpu
, AUDIT_POST_PTE_WRITE
);
4950 spin_unlock(&vcpu
->kvm
->mmu_lock
);
4953 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu
*vcpu
, gva_t gva
)
4958 if (vcpu
->arch
.mmu
->direct_map
)
4961 gpa
= kvm_mmu_gva_to_gpa_read(vcpu
, gva
, NULL
);
4963 r
= kvm_mmu_unprotect_page(vcpu
->kvm
, gpa
>> PAGE_SHIFT
);
4967 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt
);
4969 int kvm_mmu_page_fault(struct kvm_vcpu
*vcpu
, gpa_t cr2_or_gpa
, u64 error_code
,
4970 void *insn
, int insn_len
)
4972 int r
, emulation_type
= EMULTYPE_PF
;
4973 bool direct
= vcpu
->arch
.mmu
->direct_map
;
4975 if (WARN_ON(!VALID_PAGE(vcpu
->arch
.mmu
->root_hpa
)))
4976 return RET_PF_RETRY
;
4979 if (unlikely(error_code
& PFERR_RSVD_MASK
)) {
4980 r
= handle_mmio_page_fault(vcpu
, cr2_or_gpa
, direct
);
4981 if (r
== RET_PF_EMULATE
)
4985 if (r
== RET_PF_INVALID
) {
4986 r
= kvm_mmu_do_page_fault(vcpu
, cr2_or_gpa
,
4987 lower_32_bits(error_code
), false);
4988 if (WARN_ON_ONCE(r
== RET_PF_INVALID
))
4994 if (r
!= RET_PF_EMULATE
)
4998 * Before emulating the instruction, check if the error code
4999 * was due to a RO violation while translating the guest page.
5000 * This can occur when using nested virtualization with nested
5001 * paging in both guests. If true, we simply unprotect the page
5002 * and resume the guest.
5004 if (vcpu
->arch
.mmu
->direct_map
&&
5005 (error_code
& PFERR_NESTED_GUEST_PAGE
) == PFERR_NESTED_GUEST_PAGE
) {
5006 kvm_mmu_unprotect_page(vcpu
->kvm
, gpa_to_gfn(cr2_or_gpa
));
5011 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5012 * optimistically try to just unprotect the page and let the processor
5013 * re-execute the instruction that caused the page fault. Do not allow
5014 * retrying MMIO emulation, as it's not only pointless but could also
5015 * cause us to enter an infinite loop because the processor will keep
5016 * faulting on the non-existent MMIO address. Retrying an instruction
5017 * from a nested guest is also pointless and dangerous as we are only
5018 * explicitly shadowing L1's page tables, i.e. unprotecting something
5019 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5021 if (!mmio_info_in_cache(vcpu
, cr2_or_gpa
, direct
) && !is_guest_mode(vcpu
))
5022 emulation_type
|= EMULTYPE_ALLOW_RETRY_PF
;
5024 return x86_emulate_instruction(vcpu
, cr2_or_gpa
, emulation_type
, insn
,
5027 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault
);
5029 void kvm_mmu_invalidate_gva(struct kvm_vcpu
*vcpu
, struct kvm_mmu
*mmu
,
5030 gva_t gva
, hpa_t root_hpa
)
5034 /* It's actually a GPA for vcpu->arch.guest_mmu. */
5035 if (mmu
!= &vcpu
->arch
.guest_mmu
) {
5036 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
5037 if (is_noncanonical_address(gva
, vcpu
))
5040 kvm_x86_ops
.tlb_flush_gva(vcpu
, gva
);
5046 if (root_hpa
== INVALID_PAGE
) {
5047 mmu
->invlpg(vcpu
, gva
, mmu
->root_hpa
);
5050 * INVLPG is required to invalidate any global mappings for the VA,
5051 * irrespective of PCID. Since it would take us roughly similar amount
5052 * of work to determine whether any of the prev_root mappings of the VA
5053 * is marked global, or to just sync it blindly, so we might as well
5054 * just always sync it.
5056 * Mappings not reachable via the current cr3 or the prev_roots will be
5057 * synced when switching to that cr3, so nothing needs to be done here
5060 for (i
= 0; i
< KVM_MMU_NUM_PREV_ROOTS
; i
++)
5061 if (VALID_PAGE(mmu
->prev_roots
[i
].hpa
))
5062 mmu
->invlpg(vcpu
, gva
, mmu
->prev_roots
[i
].hpa
);
5064 mmu
->invlpg(vcpu
, gva
, root_hpa
);
5067 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_gva
);
5069 void kvm_mmu_invlpg(struct kvm_vcpu
*vcpu
, gva_t gva
)
5071 kvm_mmu_invalidate_gva(vcpu
, vcpu
->arch
.mmu
, gva
, INVALID_PAGE
);
5072 ++vcpu
->stat
.invlpg
;
5074 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg
);
5077 void kvm_mmu_invpcid_gva(struct kvm_vcpu
*vcpu
, gva_t gva
, unsigned long pcid
)
5079 struct kvm_mmu
*mmu
= vcpu
->arch
.mmu
;
5080 bool tlb_flush
= false;
5083 if (pcid
== kvm_get_active_pcid(vcpu
)) {
5084 mmu
->invlpg(vcpu
, gva
, mmu
->root_hpa
);
5088 for (i
= 0; i
< KVM_MMU_NUM_PREV_ROOTS
; i
++) {
5089 if (VALID_PAGE(mmu
->prev_roots
[i
].hpa
) &&
5090 pcid
== kvm_get_pcid(vcpu
, mmu
->prev_roots
[i
].pgd
)) {
5091 mmu
->invlpg(vcpu
, gva
, mmu
->prev_roots
[i
].hpa
);
5097 kvm_x86_ops
.tlb_flush_gva(vcpu
, gva
);
5099 ++vcpu
->stat
.invlpg
;
5102 * Mappings not reachable via the current cr3 or the prev_roots will be
5103 * synced when switching to that cr3, so nothing needs to be done here
5107 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva
);
5109 void kvm_configure_mmu(bool enable_tdp
, int tdp_max_root_level
,
5110 int tdp_huge_page_level
)
5112 tdp_enabled
= enable_tdp
;
5113 max_tdp_level
= tdp_max_root_level
;
5116 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5117 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5118 * the kernel is not. But, KVM never creates a page size greater than
5119 * what is used by the kernel for any given HVA, i.e. the kernel's
5120 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5123 max_huge_page_level
= tdp_huge_page_level
;
5124 else if (boot_cpu_has(X86_FEATURE_GBPAGES
))
5125 max_huge_page_level
= PG_LEVEL_1G
;
5127 max_huge_page_level
= PG_LEVEL_2M
;
5129 EXPORT_SYMBOL_GPL(kvm_configure_mmu
);
5131 /* The return value indicates if tlb flush on all vcpus is needed. */
5132 typedef bool (*slot_level_handler
) (struct kvm
*kvm
, struct kvm_rmap_head
*rmap_head
);
5134 /* The caller should hold mmu-lock before calling this function. */
5135 static __always_inline
bool
5136 slot_handle_level_range(struct kvm
*kvm
, struct kvm_memory_slot
*memslot
,
5137 slot_level_handler fn
, int start_level
, int end_level
,
5138 gfn_t start_gfn
, gfn_t end_gfn
, bool lock_flush_tlb
)
5140 struct slot_rmap_walk_iterator iterator
;
5143 for_each_slot_rmap_range(memslot
, start_level
, end_level
, start_gfn
,
5144 end_gfn
, &iterator
) {
5146 flush
|= fn(kvm
, iterator
.rmap
);
5148 if (need_resched() || spin_needbreak(&kvm
->mmu_lock
)) {
5149 if (flush
&& lock_flush_tlb
) {
5150 kvm_flush_remote_tlbs_with_address(kvm
,
5152 iterator
.gfn
- start_gfn
+ 1);
5155 cond_resched_lock(&kvm
->mmu_lock
);
5159 if (flush
&& lock_flush_tlb
) {
5160 kvm_flush_remote_tlbs_with_address(kvm
, start_gfn
,
5161 end_gfn
- start_gfn
+ 1);
5168 static __always_inline
bool
5169 slot_handle_level(struct kvm
*kvm
, struct kvm_memory_slot
*memslot
,
5170 slot_level_handler fn
, int start_level
, int end_level
,
5171 bool lock_flush_tlb
)
5173 return slot_handle_level_range(kvm
, memslot
, fn
, start_level
,
5174 end_level
, memslot
->base_gfn
,
5175 memslot
->base_gfn
+ memslot
->npages
- 1,
5179 static __always_inline
bool
5180 slot_handle_all_level(struct kvm
*kvm
, struct kvm_memory_slot
*memslot
,
5181 slot_level_handler fn
, bool lock_flush_tlb
)
5183 return slot_handle_level(kvm
, memslot
, fn
, PG_LEVEL_4K
,
5184 KVM_MAX_HUGEPAGE_LEVEL
, lock_flush_tlb
);
5187 static __always_inline
bool
5188 slot_handle_large_level(struct kvm
*kvm
, struct kvm_memory_slot
*memslot
,
5189 slot_level_handler fn
, bool lock_flush_tlb
)
5191 return slot_handle_level(kvm
, memslot
, fn
, PG_LEVEL_4K
+ 1,
5192 KVM_MAX_HUGEPAGE_LEVEL
, lock_flush_tlb
);
5195 static __always_inline
bool
5196 slot_handle_leaf(struct kvm
*kvm
, struct kvm_memory_slot
*memslot
,
5197 slot_level_handler fn
, bool lock_flush_tlb
)
5199 return slot_handle_level(kvm
, memslot
, fn
, PG_LEVEL_4K
,
5200 PG_LEVEL_4K
, lock_flush_tlb
);
5203 static void free_mmu_pages(struct kvm_mmu
*mmu
)
5205 free_page((unsigned long)mmu
->pae_root
);
5206 free_page((unsigned long)mmu
->lm_root
);
5209 static int __kvm_mmu_create(struct kvm_vcpu
*vcpu
, struct kvm_mmu
*mmu
)
5214 mmu
->root_hpa
= INVALID_PAGE
;
5216 mmu
->translate_gpa
= translate_gpa
;
5217 for (i
= 0; i
< KVM_MMU_NUM_PREV_ROOTS
; i
++)
5218 mmu
->prev_roots
[i
] = KVM_MMU_ROOT_INFO_INVALID
;
5221 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5222 * while the PDP table is a per-vCPU construct that's allocated at MMU
5223 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5224 * x86_64. Therefore we need to allocate the PDP table in the first
5225 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5226 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5227 * skip allocating the PDP table.
5229 if (tdp_enabled
&& kvm_mmu_get_tdp_level(vcpu
) > PT32E_ROOT_LEVEL
)
5232 page
= alloc_page(GFP_KERNEL_ACCOUNT
| __GFP_DMA32
);
5236 mmu
->pae_root
= page_address(page
);
5237 for (i
= 0; i
< 4; ++i
)
5238 mmu
->pae_root
[i
] = INVALID_PAGE
;
5243 int kvm_mmu_create(struct kvm_vcpu
*vcpu
)
5247 vcpu
->arch
.mmu_pte_list_desc_cache
.kmem_cache
= pte_list_desc_cache
;
5248 vcpu
->arch
.mmu_pte_list_desc_cache
.gfp_zero
= __GFP_ZERO
;
5250 vcpu
->arch
.mmu_page_header_cache
.kmem_cache
= mmu_page_header_cache
;
5251 vcpu
->arch
.mmu_page_header_cache
.gfp_zero
= __GFP_ZERO
;
5253 vcpu
->arch
.mmu_shadow_page_cache
.gfp_zero
= __GFP_ZERO
;
5255 vcpu
->arch
.mmu
= &vcpu
->arch
.root_mmu
;
5256 vcpu
->arch
.walk_mmu
= &vcpu
->arch
.root_mmu
;
5258 vcpu
->arch
.nested_mmu
.translate_gpa
= translate_nested_gpa
;
5260 ret
= __kvm_mmu_create(vcpu
, &vcpu
->arch
.guest_mmu
);
5264 ret
= __kvm_mmu_create(vcpu
, &vcpu
->arch
.root_mmu
);
5266 goto fail_allocate_root
;
5270 free_mmu_pages(&vcpu
->arch
.guest_mmu
);
5274 #define BATCH_ZAP_PAGES 10
5275 static void kvm_zap_obsolete_pages(struct kvm
*kvm
)
5277 struct kvm_mmu_page
*sp
, *node
;
5278 int nr_zapped
, batch
= 0;
5281 list_for_each_entry_safe_reverse(sp
, node
,
5282 &kvm
->arch
.active_mmu_pages
, link
) {
5284 * No obsolete valid page exists before a newly created page
5285 * since active_mmu_pages is a FIFO list.
5287 if (!is_obsolete_sp(kvm
, sp
))
5291 * Invalid pages should never land back on the list of active
5292 * pages. Skip the bogus page, otherwise we'll get stuck in an
5293 * infinite loop if the page gets put back on the list (again).
5295 if (WARN_ON(sp
->role
.invalid
))
5299 * No need to flush the TLB since we're only zapping shadow
5300 * pages with an obsolete generation number and all vCPUS have
5301 * loaded a new root, i.e. the shadow pages being zapped cannot
5302 * be in active use by the guest.
5304 if (batch
>= BATCH_ZAP_PAGES
&&
5305 cond_resched_lock(&kvm
->mmu_lock
)) {
5310 if (__kvm_mmu_prepare_zap_page(kvm
, sp
,
5311 &kvm
->arch
.zapped_obsolete_pages
, &nr_zapped
)) {
5318 * Trigger a remote TLB flush before freeing the page tables to ensure
5319 * KVM is not in the middle of a lockless shadow page table walk, which
5320 * may reference the pages.
5322 kvm_mmu_commit_zap_page(kvm
, &kvm
->arch
.zapped_obsolete_pages
);
5326 * Fast invalidate all shadow pages and use lock-break technique
5327 * to zap obsolete pages.
5329 * It's required when memslot is being deleted or VM is being
5330 * destroyed, in these cases, we should ensure that KVM MMU does
5331 * not use any resource of the being-deleted slot or all slots
5332 * after calling the function.
5334 static void kvm_mmu_zap_all_fast(struct kvm
*kvm
)
5336 lockdep_assert_held(&kvm
->slots_lock
);
5338 spin_lock(&kvm
->mmu_lock
);
5339 trace_kvm_mmu_zap_all_fast(kvm
);
5342 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5343 * held for the entire duration of zapping obsolete pages, it's
5344 * impossible for there to be multiple invalid generations associated
5345 * with *valid* shadow pages at any given time, i.e. there is exactly
5346 * one valid generation and (at most) one invalid generation.
5348 kvm
->arch
.mmu_valid_gen
= kvm
->arch
.mmu_valid_gen
? 0 : 1;
5351 * Notify all vcpus to reload its shadow page table and flush TLB.
5352 * Then all vcpus will switch to new shadow page table with the new
5355 * Note: we need to do this under the protection of mmu_lock,
5356 * otherwise, vcpu would purge shadow page but miss tlb flush.
5358 kvm_reload_remote_mmus(kvm
);
5360 kvm_zap_obsolete_pages(kvm
);
5361 spin_unlock(&kvm
->mmu_lock
);
5364 static bool kvm_has_zapped_obsolete_pages(struct kvm
*kvm
)
5366 return unlikely(!list_empty_careful(&kvm
->arch
.zapped_obsolete_pages
));
5369 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm
*kvm
,
5370 struct kvm_memory_slot
*slot
,
5371 struct kvm_page_track_notifier_node
*node
)
5373 kvm_mmu_zap_all_fast(kvm
);
5376 void kvm_mmu_init_vm(struct kvm
*kvm
)
5378 struct kvm_page_track_notifier_node
*node
= &kvm
->arch
.mmu_sp_tracker
;
5380 node
->track_write
= kvm_mmu_pte_write
;
5381 node
->track_flush_slot
= kvm_mmu_invalidate_zap_pages_in_memslot
;
5382 kvm_page_track_register_notifier(kvm
, node
);
5385 void kvm_mmu_uninit_vm(struct kvm
*kvm
)
5387 struct kvm_page_track_notifier_node
*node
= &kvm
->arch
.mmu_sp_tracker
;
5389 kvm_page_track_unregister_notifier(kvm
, node
);
5392 void kvm_zap_gfn_range(struct kvm
*kvm
, gfn_t gfn_start
, gfn_t gfn_end
)
5394 struct kvm_memslots
*slots
;
5395 struct kvm_memory_slot
*memslot
;
5398 spin_lock(&kvm
->mmu_lock
);
5399 for (i
= 0; i
< KVM_ADDRESS_SPACE_NUM
; i
++) {
5400 slots
= __kvm_memslots(kvm
, i
);
5401 kvm_for_each_memslot(memslot
, slots
) {
5404 start
= max(gfn_start
, memslot
->base_gfn
);
5405 end
= min(gfn_end
, memslot
->base_gfn
+ memslot
->npages
);
5409 slot_handle_level_range(kvm
, memslot
, kvm_zap_rmapp
,
5411 KVM_MAX_HUGEPAGE_LEVEL
,
5412 start
, end
- 1, true);
5416 spin_unlock(&kvm
->mmu_lock
);
5419 static bool slot_rmap_write_protect(struct kvm
*kvm
,
5420 struct kvm_rmap_head
*rmap_head
)
5422 return __rmap_write_protect(kvm
, rmap_head
, false);
5425 void kvm_mmu_slot_remove_write_access(struct kvm
*kvm
,
5426 struct kvm_memory_slot
*memslot
,
5431 spin_lock(&kvm
->mmu_lock
);
5432 flush
= slot_handle_level(kvm
, memslot
, slot_rmap_write_protect
,
5433 start_level
, KVM_MAX_HUGEPAGE_LEVEL
, false);
5434 spin_unlock(&kvm
->mmu_lock
);
5437 * We can flush all the TLBs out of the mmu lock without TLB
5438 * corruption since we just change the spte from writable to
5439 * readonly so that we only need to care the case of changing
5440 * spte from present to present (changing the spte from present
5441 * to nonpresent will flush all the TLBs immediately), in other
5442 * words, the only case we care is mmu_spte_update() where we
5443 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5444 * instead of PT_WRITABLE_MASK, that means it does not depend
5445 * on PT_WRITABLE_MASK anymore.
5448 kvm_arch_flush_remote_tlbs_memslot(kvm
, memslot
);
5451 static bool kvm_mmu_zap_collapsible_spte(struct kvm
*kvm
,
5452 struct kvm_rmap_head
*rmap_head
)
5455 struct rmap_iterator iter
;
5456 int need_tlb_flush
= 0;
5458 struct kvm_mmu_page
*sp
;
5461 for_each_rmap_spte(rmap_head
, &iter
, sptep
) {
5462 sp
= sptep_to_sp(sptep
);
5463 pfn
= spte_to_pfn(*sptep
);
5466 * We cannot do huge page mapping for indirect shadow pages,
5467 * which are found on the last rmap (level = 1) when not using
5468 * tdp; such shadow pages are synced with the page table in
5469 * the guest, and the guest page table is using 4K page size
5470 * mapping if the indirect sp has level = 1.
5472 if (sp
->role
.direct
&& !kvm_is_reserved_pfn(pfn
) &&
5473 (kvm_is_zone_device_pfn(pfn
) ||
5474 PageCompound(pfn_to_page(pfn
)))) {
5475 pte_list_remove(rmap_head
, sptep
);
5477 if (kvm_available_flush_tlb_with_range())
5478 kvm_flush_remote_tlbs_with_address(kvm
, sp
->gfn
,
5479 KVM_PAGES_PER_HPAGE(sp
->role
.level
));
5487 return need_tlb_flush
;
5490 void kvm_mmu_zap_collapsible_sptes(struct kvm
*kvm
,
5491 const struct kvm_memory_slot
*memslot
)
5493 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5494 spin_lock(&kvm
->mmu_lock
);
5495 slot_handle_leaf(kvm
, (struct kvm_memory_slot
*)memslot
,
5496 kvm_mmu_zap_collapsible_spte
, true);
5497 spin_unlock(&kvm
->mmu_lock
);
5500 void kvm_arch_flush_remote_tlbs_memslot(struct kvm
*kvm
,
5501 struct kvm_memory_slot
*memslot
)
5504 * All current use cases for flushing the TLBs for a specific memslot
5505 * are related to dirty logging, and do the TLB flush out of mmu_lock.
5506 * The interaction between the various operations on memslot must be
5507 * serialized by slots_locks to ensure the TLB flush from one operation
5508 * is observed by any other operation on the same memslot.
5510 lockdep_assert_held(&kvm
->slots_lock
);
5511 kvm_flush_remote_tlbs_with_address(kvm
, memslot
->base_gfn
,
5515 void kvm_mmu_slot_leaf_clear_dirty(struct kvm
*kvm
,
5516 struct kvm_memory_slot
*memslot
)
5520 spin_lock(&kvm
->mmu_lock
);
5521 flush
= slot_handle_leaf(kvm
, memslot
, __rmap_clear_dirty
, false);
5522 spin_unlock(&kvm
->mmu_lock
);
5525 * It's also safe to flush TLBs out of mmu lock here as currently this
5526 * function is only used for dirty logging, in which case flushing TLB
5527 * out of mmu lock also guarantees no dirty pages will be lost in
5531 kvm_arch_flush_remote_tlbs_memslot(kvm
, memslot
);
5533 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty
);
5535 void kvm_mmu_slot_largepage_remove_write_access(struct kvm
*kvm
,
5536 struct kvm_memory_slot
*memslot
)
5540 spin_lock(&kvm
->mmu_lock
);
5541 flush
= slot_handle_large_level(kvm
, memslot
, slot_rmap_write_protect
,
5543 spin_unlock(&kvm
->mmu_lock
);
5546 kvm_arch_flush_remote_tlbs_memslot(kvm
, memslot
);
5548 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access
);
5550 void kvm_mmu_slot_set_dirty(struct kvm
*kvm
,
5551 struct kvm_memory_slot
*memslot
)
5555 spin_lock(&kvm
->mmu_lock
);
5556 flush
= slot_handle_all_level(kvm
, memslot
, __rmap_set_dirty
, false);
5557 spin_unlock(&kvm
->mmu_lock
);
5560 kvm_arch_flush_remote_tlbs_memslot(kvm
, memslot
);
5562 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty
);
5564 void kvm_mmu_zap_all(struct kvm
*kvm
)
5566 struct kvm_mmu_page
*sp
, *node
;
5567 LIST_HEAD(invalid_list
);
5570 spin_lock(&kvm
->mmu_lock
);
5572 list_for_each_entry_safe(sp
, node
, &kvm
->arch
.active_mmu_pages
, link
) {
5573 if (WARN_ON(sp
->role
.invalid
))
5575 if (__kvm_mmu_prepare_zap_page(kvm
, sp
, &invalid_list
, &ign
))
5577 if (cond_resched_lock(&kvm
->mmu_lock
))
5581 kvm_mmu_commit_zap_page(kvm
, &invalid_list
);
5582 spin_unlock(&kvm
->mmu_lock
);
5585 void kvm_mmu_invalidate_mmio_sptes(struct kvm
*kvm
, u64 gen
)
5587 WARN_ON(gen
& KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS
);
5589 gen
&= MMIO_SPTE_GEN_MASK
;
5592 * Generation numbers are incremented in multiples of the number of
5593 * address spaces in order to provide unique generations across all
5594 * address spaces. Strip what is effectively the address space
5595 * modifier prior to checking for a wrap of the MMIO generation so
5596 * that a wrap in any address space is detected.
5598 gen
&= ~((u64
)KVM_ADDRESS_SPACE_NUM
- 1);
5601 * The very rare case: if the MMIO generation number has wrapped,
5602 * zap all shadow pages.
5604 if (unlikely(gen
== 0)) {
5605 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5606 kvm_mmu_zap_all_fast(kvm
);
5610 static unsigned long
5611 mmu_shrink_scan(struct shrinker
*shrink
, struct shrink_control
*sc
)
5614 int nr_to_scan
= sc
->nr_to_scan
;
5615 unsigned long freed
= 0;
5617 mutex_lock(&kvm_lock
);
5619 list_for_each_entry(kvm
, &vm_list
, vm_list
) {
5621 LIST_HEAD(invalid_list
);
5624 * Never scan more than sc->nr_to_scan VM instances.
5625 * Will not hit this condition practically since we do not try
5626 * to shrink more than one VM and it is very unlikely to see
5627 * !n_used_mmu_pages so many times.
5632 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5633 * here. We may skip a VM instance errorneosly, but we do not
5634 * want to shrink a VM that only started to populate its MMU
5637 if (!kvm
->arch
.n_used_mmu_pages
&&
5638 !kvm_has_zapped_obsolete_pages(kvm
))
5641 idx
= srcu_read_lock(&kvm
->srcu
);
5642 spin_lock(&kvm
->mmu_lock
);
5644 if (kvm_has_zapped_obsolete_pages(kvm
)) {
5645 kvm_mmu_commit_zap_page(kvm
,
5646 &kvm
->arch
.zapped_obsolete_pages
);
5650 freed
= kvm_mmu_zap_oldest_mmu_pages(kvm
, sc
->nr_to_scan
);
5653 spin_unlock(&kvm
->mmu_lock
);
5654 srcu_read_unlock(&kvm
->srcu
, idx
);
5657 * unfair on small ones
5658 * per-vm shrinkers cry out
5659 * sadness comes quickly
5661 list_move_tail(&kvm
->vm_list
, &vm_list
);
5665 mutex_unlock(&kvm_lock
);
5669 static unsigned long
5670 mmu_shrink_count(struct shrinker
*shrink
, struct shrink_control
*sc
)
5672 return percpu_counter_read_positive(&kvm_total_used_mmu_pages
);
5675 static struct shrinker mmu_shrinker
= {
5676 .count_objects
= mmu_shrink_count
,
5677 .scan_objects
= mmu_shrink_scan
,
5678 .seeks
= DEFAULT_SEEKS
* 10,
5681 static void mmu_destroy_caches(void)
5683 kmem_cache_destroy(pte_list_desc_cache
);
5684 kmem_cache_destroy(mmu_page_header_cache
);
5687 static void kvm_set_mmio_spte_mask(void)
5692 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
5693 * PFEC.RSVD=1 on MMIO accesses. 64-bit PTEs (PAE, x86-64, and EPT
5694 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
5695 * 52-bit physical addresses then there are no reserved PA bits in the
5696 * PTEs and so the reserved PA approach must be disabled.
5698 if (shadow_phys_bits
< 52)
5699 mask
= BIT_ULL(51) | PT_PRESENT_MASK
;
5703 kvm_mmu_set_mmio_spte_mask(mask
, ACC_WRITE_MASK
| ACC_USER_MASK
);
5706 static bool get_nx_auto_mode(void)
5708 /* Return true when CPU has the bug, and mitigations are ON */
5709 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT
) && !cpu_mitigations_off();
5712 static void __set_nx_huge_pages(bool val
)
5714 nx_huge_pages
= itlb_multihit_kvm_mitigation
= val
;
5717 static int set_nx_huge_pages(const char *val
, const struct kernel_param
*kp
)
5719 bool old_val
= nx_huge_pages
;
5722 /* In "auto" mode deploy workaround only if CPU has the bug. */
5723 if (sysfs_streq(val
, "off"))
5725 else if (sysfs_streq(val
, "force"))
5727 else if (sysfs_streq(val
, "auto"))
5728 new_val
= get_nx_auto_mode();
5729 else if (strtobool(val
, &new_val
) < 0)
5732 __set_nx_huge_pages(new_val
);
5734 if (new_val
!= old_val
) {
5737 mutex_lock(&kvm_lock
);
5739 list_for_each_entry(kvm
, &vm_list
, vm_list
) {
5740 mutex_lock(&kvm
->slots_lock
);
5741 kvm_mmu_zap_all_fast(kvm
);
5742 mutex_unlock(&kvm
->slots_lock
);
5744 wake_up_process(kvm
->arch
.nx_lpage_recovery_thread
);
5746 mutex_unlock(&kvm_lock
);
5752 int kvm_mmu_module_init(void)
5756 if (nx_huge_pages
== -1)
5757 __set_nx_huge_pages(get_nx_auto_mode());
5760 * MMU roles use union aliasing which is, generally speaking, an
5761 * undefined behavior. However, we supposedly know how compilers behave
5762 * and the current status quo is unlikely to change. Guardians below are
5763 * supposed to let us know if the assumption becomes false.
5765 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role
) != sizeof(u32
));
5766 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role
) != sizeof(u32
));
5767 BUILD_BUG_ON(sizeof(union kvm_mmu_role
) != sizeof(u64
));
5769 kvm_mmu_reset_all_pte_masks();
5771 kvm_set_mmio_spte_mask();
5773 pte_list_desc_cache
= kmem_cache_create("pte_list_desc",
5774 sizeof(struct pte_list_desc
),
5775 0, SLAB_ACCOUNT
, NULL
);
5776 if (!pte_list_desc_cache
)
5779 mmu_page_header_cache
= kmem_cache_create("kvm_mmu_page_header",
5780 sizeof(struct kvm_mmu_page
),
5781 0, SLAB_ACCOUNT
, NULL
);
5782 if (!mmu_page_header_cache
)
5785 if (percpu_counter_init(&kvm_total_used_mmu_pages
, 0, GFP_KERNEL
))
5788 ret
= register_shrinker(&mmu_shrinker
);
5795 mmu_destroy_caches();
5800 * Calculate mmu pages needed for kvm.
5802 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm
*kvm
)
5804 unsigned long nr_mmu_pages
;
5805 unsigned long nr_pages
= 0;
5806 struct kvm_memslots
*slots
;
5807 struct kvm_memory_slot
*memslot
;
5810 for (i
= 0; i
< KVM_ADDRESS_SPACE_NUM
; i
++) {
5811 slots
= __kvm_memslots(kvm
, i
);
5813 kvm_for_each_memslot(memslot
, slots
)
5814 nr_pages
+= memslot
->npages
;
5817 nr_mmu_pages
= nr_pages
* KVM_PERMILLE_MMU_PAGES
/ 1000;
5818 nr_mmu_pages
= max(nr_mmu_pages
, KVM_MIN_ALLOC_MMU_PAGES
);
5820 return nr_mmu_pages
;
5823 void kvm_mmu_destroy(struct kvm_vcpu
*vcpu
)
5825 kvm_mmu_unload(vcpu
);
5826 free_mmu_pages(&vcpu
->arch
.root_mmu
);
5827 free_mmu_pages(&vcpu
->arch
.guest_mmu
);
5828 mmu_free_memory_caches(vcpu
);
5831 void kvm_mmu_module_exit(void)
5833 mmu_destroy_caches();
5834 percpu_counter_destroy(&kvm_total_used_mmu_pages
);
5835 unregister_shrinker(&mmu_shrinker
);
5836 mmu_audit_disable();
5839 static int set_nx_huge_pages_recovery_ratio(const char *val
, const struct kernel_param
*kp
)
5841 unsigned int old_val
;
5844 old_val
= nx_huge_pages_recovery_ratio
;
5845 err
= param_set_uint(val
, kp
);
5849 if (READ_ONCE(nx_huge_pages
) &&
5850 !old_val
&& nx_huge_pages_recovery_ratio
) {
5853 mutex_lock(&kvm_lock
);
5855 list_for_each_entry(kvm
, &vm_list
, vm_list
)
5856 wake_up_process(kvm
->arch
.nx_lpage_recovery_thread
);
5858 mutex_unlock(&kvm_lock
);
5864 static void kvm_recover_nx_lpages(struct kvm
*kvm
)
5867 struct kvm_mmu_page
*sp
;
5869 LIST_HEAD(invalid_list
);
5872 rcu_idx
= srcu_read_lock(&kvm
->srcu
);
5873 spin_lock(&kvm
->mmu_lock
);
5875 ratio
= READ_ONCE(nx_huge_pages_recovery_ratio
);
5876 to_zap
= ratio
? DIV_ROUND_UP(kvm
->stat
.nx_lpage_splits
, ratio
) : 0;
5877 for ( ; to_zap
; --to_zap
) {
5878 if (list_empty(&kvm
->arch
.lpage_disallowed_mmu_pages
))
5882 * We use a separate list instead of just using active_mmu_pages
5883 * because the number of lpage_disallowed pages is expected to
5884 * be relatively small compared to the total.
5886 sp
= list_first_entry(&kvm
->arch
.lpage_disallowed_mmu_pages
,
5887 struct kvm_mmu_page
,
5888 lpage_disallowed_link
);
5889 WARN_ON_ONCE(!sp
->lpage_disallowed
);
5890 kvm_mmu_prepare_zap_page(kvm
, sp
, &invalid_list
);
5891 WARN_ON_ONCE(sp
->lpage_disallowed
);
5893 if (need_resched() || spin_needbreak(&kvm
->mmu_lock
)) {
5894 kvm_mmu_commit_zap_page(kvm
, &invalid_list
);
5895 cond_resched_lock(&kvm
->mmu_lock
);
5898 kvm_mmu_commit_zap_page(kvm
, &invalid_list
);
5900 spin_unlock(&kvm
->mmu_lock
);
5901 srcu_read_unlock(&kvm
->srcu
, rcu_idx
);
5904 static long get_nx_lpage_recovery_timeout(u64 start_time
)
5906 return READ_ONCE(nx_huge_pages
) && READ_ONCE(nx_huge_pages_recovery_ratio
)
5907 ? start_time
+ 60 * HZ
- get_jiffies_64()
5908 : MAX_SCHEDULE_TIMEOUT
;
5911 static int kvm_nx_lpage_recovery_worker(struct kvm
*kvm
, uintptr_t data
)
5914 long remaining_time
;
5917 start_time
= get_jiffies_64();
5918 remaining_time
= get_nx_lpage_recovery_timeout(start_time
);
5920 set_current_state(TASK_INTERRUPTIBLE
);
5921 while (!kthread_should_stop() && remaining_time
> 0) {
5922 schedule_timeout(remaining_time
);
5923 remaining_time
= get_nx_lpage_recovery_timeout(start_time
);
5924 set_current_state(TASK_INTERRUPTIBLE
);
5927 set_current_state(TASK_RUNNING
);
5929 if (kthread_should_stop())
5932 kvm_recover_nx_lpages(kvm
);
5936 int kvm_mmu_post_init_vm(struct kvm
*kvm
)
5940 err
= kvm_vm_create_worker_thread(kvm
, kvm_nx_lpage_recovery_worker
, 0,
5941 "kvm-nx-lpage-recovery",
5942 &kvm
->arch
.nx_lpage_recovery_thread
);
5944 kthread_unpark(kvm
->arch
.nx_lpage_recovery_thread
);
5949 void kvm_mmu_pre_destroy_vm(struct kvm
*kvm
)
5951 if (kvm
->arch
.nx_lpage_recovery_thread
)
5952 kthread_stop(kvm
->arch
.nx_lpage_recovery_thread
);