xref: /linux/arch/x86/kvm/mmu/mmu.c (revision c924c5e9b8c65b3a479a90e5e37d74cc8cd9fe0a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * This module enables machines with Intel VT-x extensions to run virtual
6  * machines without emulation or binary translation.
7  *
8  * MMU support
9  *
10  * Copyright (C) 2006 Qumranet, Inc.
11  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12  *
13  * Authors:
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Avi Kivity   <avi@qumranet.com>
16  */
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18 
19 #include "irq.h"
20 #include "ioapic.h"
21 #include "mmu.h"
22 #include "mmu_internal.h"
23 #include "tdp_mmu.h"
24 #include "x86.h"
25 #include "kvm_cache_regs.h"
26 #include "smm.h"
27 #include "kvm_emulate.h"
28 #include "page_track.h"
29 #include "cpuid.h"
30 #include "spte.h"
31 
32 #include <linux/kvm_host.h>
33 #include <linux/types.h>
34 #include <linux/string.h>
35 #include <linux/mm.h>
36 #include <linux/highmem.h>
37 #include <linux/moduleparam.h>
38 #include <linux/export.h>
39 #include <linux/swap.h>
40 #include <linux/hugetlb.h>
41 #include <linux/compiler.h>
42 #include <linux/srcu.h>
43 #include <linux/slab.h>
44 #include <linux/sched/signal.h>
45 #include <linux/uaccess.h>
46 #include <linux/hash.h>
47 #include <linux/kern_levels.h>
48 #include <linux/kstrtox.h>
49 #include <linux/kthread.h>
50 #include <linux/wordpart.h>
51 
52 #include <asm/page.h>
53 #include <asm/memtype.h>
54 #include <asm/cmpxchg.h>
55 #include <asm/io.h>
56 #include <asm/set_memory.h>
57 #include <asm/spec-ctrl.h>
58 #include <asm/vmx.h>
59 
60 #include "trace.h"
61 
62 static bool nx_hugepage_mitigation_hard_disabled;
63 
64 int __read_mostly nx_huge_pages = -1;
65 static uint __read_mostly nx_huge_pages_recovery_period_ms;
66 #ifdef CONFIG_PREEMPT_RT
67 /* Recovery can cause latency spikes, disable it for PREEMPT_RT.  */
68 static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
69 #else
70 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
71 #endif
72 
73 static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp);
74 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
75 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
76 
77 static const struct kernel_param_ops nx_huge_pages_ops = {
78 	.set = set_nx_huge_pages,
79 	.get = get_nx_huge_pages,
80 };
81 
82 static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
83 	.set = set_nx_huge_pages_recovery_param,
84 	.get = param_get_uint,
85 };
86 
87 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
88 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
89 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
90 		&nx_huge_pages_recovery_ratio, 0644);
91 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
92 module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
93 		&nx_huge_pages_recovery_period_ms, 0644);
94 __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
95 
96 static bool __read_mostly force_flush_and_sync_on_reuse;
97 module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
98 
99 /*
100  * When setting this variable to true it enables Two-Dimensional-Paging
101  * where the hardware walks 2 page tables:
102  * 1. the guest-virtual to guest-physical
103  * 2. while doing 1. it walks guest-physical to host-physical
104  * If the hardware supports that we don't need to do shadow paging.
105  */
106 bool tdp_enabled = false;
107 
108 static bool __ro_after_init tdp_mmu_allowed;
109 
110 #ifdef CONFIG_X86_64
111 bool __read_mostly tdp_mmu_enabled = true;
112 module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
113 #endif
114 
115 static int max_huge_page_level __read_mostly;
116 static int tdp_root_level __read_mostly;
117 static int max_tdp_level __read_mostly;
118 
119 #define PTE_PREFETCH_NUM		8
120 
121 #include <trace/events/kvm.h>
122 
123 /* make pte_list_desc fit well in cache lines */
124 #define PTE_LIST_EXT 14
125 
126 /*
127  * struct pte_list_desc is the core data structure used to implement a custom
128  * list for tracking a set of related SPTEs, e.g. all the SPTEs that map a
129  * given GFN when used in the context of rmaps.  Using a custom list allows KVM
130  * to optimize for the common case where many GFNs will have at most a handful
131  * of SPTEs pointing at them, i.e. allows packing multiple SPTEs into a small
132  * memory footprint, which in turn improves runtime performance by exploiting
133  * cache locality.
134  *
135  * A list is comprised of one or more pte_list_desc objects (descriptors).
136  * Each individual descriptor stores up to PTE_LIST_EXT SPTEs.  If a descriptor
137  * is full and a new SPTEs needs to be added, a new descriptor is allocated and
138  * becomes the head of the list.  This means that by definitions, all tail
139  * descriptors are full.
140  *
141  * Note, the meta data fields are deliberately placed at the start of the
142  * structure to optimize the cacheline layout; accessing the descriptor will
143  * touch only a single cacheline so long as @spte_count<=6 (or if only the
144  * descriptors metadata is accessed).
145  */
146 struct pte_list_desc {
147 	struct pte_list_desc *more;
148 	/* The number of PTEs stored in _this_ descriptor. */
149 	u32 spte_count;
150 	/* The number of PTEs stored in all tails of this descriptor. */
151 	u32 tail_count;
152 	u64 *sptes[PTE_LIST_EXT];
153 };
154 
155 struct kvm_shadow_walk_iterator {
156 	u64 addr;
157 	hpa_t shadow_addr;
158 	u64 *sptep;
159 	int level;
160 	unsigned index;
161 };
162 
163 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
164 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
165 					 (_root), (_addr));                \
166 	     shadow_walk_okay(&(_walker));			           \
167 	     shadow_walk_next(&(_walker)))
168 
169 #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
170 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
171 	     shadow_walk_okay(&(_walker));			\
172 	     shadow_walk_next(&(_walker)))
173 
174 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
175 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
176 	     shadow_walk_okay(&(_walker)) &&				\
177 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
178 	     __shadow_walk_next(&(_walker), spte))
179 
180 static struct kmem_cache *pte_list_desc_cache;
181 struct kmem_cache *mmu_page_header_cache;
182 
183 static void mmu_spte_set(u64 *sptep, u64 spte);
184 
185 struct kvm_mmu_role_regs {
186 	const unsigned long cr0;
187 	const unsigned long cr4;
188 	const u64 efer;
189 };
190 
191 #define CREATE_TRACE_POINTS
192 #include "mmutrace.h"
193 
194 /*
195  * Yes, lot's of underscores.  They're a hint that you probably shouldn't be
196  * reading from the role_regs.  Once the root_role is constructed, it becomes
197  * the single source of truth for the MMU's state.
198  */
199 #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag)			\
200 static inline bool __maybe_unused					\
201 ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs)		\
202 {									\
203 	return !!(regs->reg & flag);					\
204 }
205 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
206 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
207 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
208 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
209 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
210 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
211 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
212 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
213 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
214 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
215 
216 /*
217  * The MMU itself (with a valid role) is the single source of truth for the
218  * MMU.  Do not use the regs used to build the MMU/role, nor the vCPU.  The
219  * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
220  * and the vCPU may be incorrect/irrelevant.
221  */
222 #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name)		\
223 static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu)	\
224 {								\
225 	return !!(mmu->cpu_role. base_or_ext . reg##_##name);	\
226 }
227 BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
228 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pse);
229 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smep);
230 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smap);
231 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pke);
232 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, la57);
233 BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
234 BUILD_MMU_ROLE_ACCESSOR(ext,  efer, lma);
235 
is_cr0_pg(struct kvm_mmu * mmu)236 static inline bool is_cr0_pg(struct kvm_mmu *mmu)
237 {
238         return mmu->cpu_role.base.level > 0;
239 }
240 
is_cr4_pae(struct kvm_mmu * mmu)241 static inline bool is_cr4_pae(struct kvm_mmu *mmu)
242 {
243         return !mmu->cpu_role.base.has_4_byte_gpte;
244 }
245 
vcpu_to_role_regs(struct kvm_vcpu * vcpu)246 static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
247 {
248 	struct kvm_mmu_role_regs regs = {
249 		.cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
250 		.cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
251 		.efer = vcpu->arch.efer,
252 	};
253 
254 	return regs;
255 }
256 
get_guest_cr3(struct kvm_vcpu * vcpu)257 static unsigned long get_guest_cr3(struct kvm_vcpu *vcpu)
258 {
259 	return kvm_read_cr3(vcpu);
260 }
261 
kvm_mmu_get_guest_pgd(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu)262 static inline unsigned long kvm_mmu_get_guest_pgd(struct kvm_vcpu *vcpu,
263 						  struct kvm_mmu *mmu)
264 {
265 	if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) && mmu->get_guest_pgd == get_guest_cr3)
266 		return kvm_read_cr3(vcpu);
267 
268 	return mmu->get_guest_pgd(vcpu);
269 }
270 
kvm_available_flush_remote_tlbs_range(void)271 static inline bool kvm_available_flush_remote_tlbs_range(void)
272 {
273 #if IS_ENABLED(CONFIG_HYPERV)
274 	return kvm_x86_ops.flush_remote_tlbs_range;
275 #else
276 	return false;
277 #endif
278 }
279 
280 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
281 
282 /* Flush the range of guest memory mapped by the given SPTE. */
kvm_flush_remote_tlbs_sptep(struct kvm * kvm,u64 * sptep)283 static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
284 {
285 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
286 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
287 
288 	kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
289 }
290 
mark_mmio_spte(struct kvm_vcpu * vcpu,u64 * sptep,u64 gfn,unsigned int access)291 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
292 			   unsigned int access)
293 {
294 	u64 spte = make_mmio_spte(vcpu, gfn, access);
295 
296 	trace_mark_mmio_spte(sptep, gfn, spte);
297 	mmu_spte_set(sptep, spte);
298 }
299 
get_mmio_spte_gfn(u64 spte)300 static gfn_t get_mmio_spte_gfn(u64 spte)
301 {
302 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
303 
304 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
305 	       & shadow_nonpresent_or_rsvd_mask;
306 
307 	return gpa >> PAGE_SHIFT;
308 }
309 
get_mmio_spte_access(u64 spte)310 static unsigned get_mmio_spte_access(u64 spte)
311 {
312 	return spte & shadow_mmio_access_mask;
313 }
314 
check_mmio_spte(struct kvm_vcpu * vcpu,u64 spte)315 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
316 {
317 	u64 kvm_gen, spte_gen, gen;
318 
319 	gen = kvm_vcpu_memslots(vcpu)->generation;
320 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
321 		return false;
322 
323 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
324 	spte_gen = get_mmio_spte_generation(spte);
325 
326 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
327 	return likely(kvm_gen == spte_gen);
328 }
329 
is_cpuid_PSE36(void)330 static int is_cpuid_PSE36(void)
331 {
332 	return 1;
333 }
334 
335 #ifdef CONFIG_X86_64
__set_spte(u64 * sptep,u64 spte)336 static void __set_spte(u64 *sptep, u64 spte)
337 {
338 	KVM_MMU_WARN_ON(is_ept_ve_possible(spte));
339 	WRITE_ONCE(*sptep, spte);
340 }
341 
__update_clear_spte_fast(u64 * sptep,u64 spte)342 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
343 {
344 	KVM_MMU_WARN_ON(is_ept_ve_possible(spte));
345 	WRITE_ONCE(*sptep, spte);
346 }
347 
__update_clear_spte_slow(u64 * sptep,u64 spte)348 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
349 {
350 	KVM_MMU_WARN_ON(is_ept_ve_possible(spte));
351 	return xchg(sptep, spte);
352 }
353 
__get_spte_lockless(u64 * sptep)354 static u64 __get_spte_lockless(u64 *sptep)
355 {
356 	return READ_ONCE(*sptep);
357 }
358 #else
359 union split_spte {
360 	struct {
361 		u32 spte_low;
362 		u32 spte_high;
363 	};
364 	u64 spte;
365 };
366 
count_spte_clear(u64 * sptep,u64 spte)367 static void count_spte_clear(u64 *sptep, u64 spte)
368 {
369 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
370 
371 	if (is_shadow_present_pte(spte))
372 		return;
373 
374 	/* Ensure the spte is completely set before we increase the count */
375 	smp_wmb();
376 	sp->clear_spte_count++;
377 }
378 
__set_spte(u64 * sptep,u64 spte)379 static void __set_spte(u64 *sptep, u64 spte)
380 {
381 	union split_spte *ssptep, sspte;
382 
383 	ssptep = (union split_spte *)sptep;
384 	sspte = (union split_spte)spte;
385 
386 	ssptep->spte_high = sspte.spte_high;
387 
388 	/*
389 	 * If we map the spte from nonpresent to present, We should store
390 	 * the high bits firstly, then set present bit, so cpu can not
391 	 * fetch this spte while we are setting the spte.
392 	 */
393 	smp_wmb();
394 
395 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
396 }
397 
__update_clear_spte_fast(u64 * sptep,u64 spte)398 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
399 {
400 	union split_spte *ssptep, sspte;
401 
402 	ssptep = (union split_spte *)sptep;
403 	sspte = (union split_spte)spte;
404 
405 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
406 
407 	/*
408 	 * If we map the spte from present to nonpresent, we should clear
409 	 * present bit firstly to avoid vcpu fetch the old high bits.
410 	 */
411 	smp_wmb();
412 
413 	ssptep->spte_high = sspte.spte_high;
414 	count_spte_clear(sptep, spte);
415 }
416 
__update_clear_spte_slow(u64 * sptep,u64 spte)417 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
418 {
419 	union split_spte *ssptep, sspte, orig;
420 
421 	ssptep = (union split_spte *)sptep;
422 	sspte = (union split_spte)spte;
423 
424 	/* xchg acts as a barrier before the setting of the high bits */
425 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
426 	orig.spte_high = ssptep->spte_high;
427 	ssptep->spte_high = sspte.spte_high;
428 	count_spte_clear(sptep, spte);
429 
430 	return orig.spte;
431 }
432 
433 /*
434  * The idea using the light way get the spte on x86_32 guest is from
435  * gup_get_pte (mm/gup.c).
436  *
437  * An spte tlb flush may be pending, because they are coalesced and
438  * we are running out of the MMU lock.  Therefore
439  * we need to protect against in-progress updates of the spte.
440  *
441  * Reading the spte while an update is in progress may get the old value
442  * for the high part of the spte.  The race is fine for a present->non-present
443  * change (because the high part of the spte is ignored for non-present spte),
444  * but for a present->present change we must reread the spte.
445  *
446  * All such changes are done in two steps (present->non-present and
447  * non-present->present), hence it is enough to count the number of
448  * present->non-present updates: if it changed while reading the spte,
449  * we might have hit the race.  This is done using clear_spte_count.
450  */
__get_spte_lockless(u64 * sptep)451 static u64 __get_spte_lockless(u64 *sptep)
452 {
453 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
454 	union split_spte spte, *orig = (union split_spte *)sptep;
455 	int count;
456 
457 retry:
458 	count = sp->clear_spte_count;
459 	smp_rmb();
460 
461 	spte.spte_low = orig->spte_low;
462 	smp_rmb();
463 
464 	spte.spte_high = orig->spte_high;
465 	smp_rmb();
466 
467 	if (unlikely(spte.spte_low != orig->spte_low ||
468 	      count != sp->clear_spte_count))
469 		goto retry;
470 
471 	return spte.spte;
472 }
473 #endif
474 
475 /* Rules for using mmu_spte_set:
476  * Set the sptep from nonpresent to present.
477  * Note: the sptep being assigned *must* be either not present
478  * or in a state where the hardware will not attempt to update
479  * the spte.
480  */
mmu_spte_set(u64 * sptep,u64 new_spte)481 static void mmu_spte_set(u64 *sptep, u64 new_spte)
482 {
483 	WARN_ON_ONCE(is_shadow_present_pte(*sptep));
484 	__set_spte(sptep, new_spte);
485 }
486 
487 /* Rules for using mmu_spte_update:
488  * Update the state bits, it means the mapped pfn is not changed.
489  *
490  * Returns true if the TLB needs to be flushed
491  */
mmu_spte_update(u64 * sptep,u64 new_spte)492 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
493 {
494 	u64 old_spte = *sptep;
495 
496 	WARN_ON_ONCE(!is_shadow_present_pte(new_spte));
497 	check_spte_writable_invariants(new_spte);
498 
499 	if (!is_shadow_present_pte(old_spte)) {
500 		mmu_spte_set(sptep, new_spte);
501 		return false;
502 	}
503 
504 	if (!spte_needs_atomic_update(old_spte))
505 		__update_clear_spte_fast(sptep, new_spte);
506 	else
507 		old_spte = __update_clear_spte_slow(sptep, new_spte);
508 
509 	WARN_ON_ONCE(!is_shadow_present_pte(old_spte) ||
510 		     spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
511 
512 	return leaf_spte_change_needs_tlb_flush(old_spte, new_spte);
513 }
514 
515 /*
516  * Rules for using mmu_spte_clear_track_bits:
517  * It sets the sptep from present to nonpresent, and track the
518  * state bits, it is used to clear the last level sptep.
519  * Returns the old PTE.
520  */
mmu_spte_clear_track_bits(struct kvm * kvm,u64 * sptep)521 static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
522 {
523 	u64 old_spte = *sptep;
524 	int level = sptep_to_sp(sptep)->role.level;
525 
526 	if (!is_shadow_present_pte(old_spte) ||
527 	    !spte_needs_atomic_update(old_spte))
528 		__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
529 	else
530 		old_spte = __update_clear_spte_slow(sptep, SHADOW_NONPRESENT_VALUE);
531 
532 	if (!is_shadow_present_pte(old_spte))
533 		return old_spte;
534 
535 	kvm_update_page_stats(kvm, level, -1);
536 	return old_spte;
537 }
538 
539 /*
540  * Rules for using mmu_spte_clear_no_track:
541  * Directly clear spte without caring the state bits of sptep,
542  * it is used to set the upper level spte.
543  */
mmu_spte_clear_no_track(u64 * sptep)544 static void mmu_spte_clear_no_track(u64 *sptep)
545 {
546 	__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
547 }
548 
mmu_spte_get_lockless(u64 * sptep)549 static u64 mmu_spte_get_lockless(u64 *sptep)
550 {
551 	return __get_spte_lockless(sptep);
552 }
553 
is_tdp_mmu_active(struct kvm_vcpu * vcpu)554 static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
555 {
556 	return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
557 }
558 
walk_shadow_page_lockless_begin(struct kvm_vcpu * vcpu)559 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
560 {
561 	if (is_tdp_mmu_active(vcpu)) {
562 		kvm_tdp_mmu_walk_lockless_begin();
563 	} else {
564 		/*
565 		 * Prevent page table teardown by making any free-er wait during
566 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
567 		 */
568 		local_irq_disable();
569 
570 		/*
571 		 * Make sure a following spte read is not reordered ahead of the write
572 		 * to vcpu->mode.
573 		 */
574 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
575 	}
576 }
577 
walk_shadow_page_lockless_end(struct kvm_vcpu * vcpu)578 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
579 {
580 	if (is_tdp_mmu_active(vcpu)) {
581 		kvm_tdp_mmu_walk_lockless_end();
582 	} else {
583 		/*
584 		 * Make sure the write to vcpu->mode is not reordered in front of
585 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
586 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
587 		 */
588 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
589 		local_irq_enable();
590 	}
591 }
592 
mmu_topup_memory_caches(struct kvm_vcpu * vcpu,bool maybe_indirect)593 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
594 {
595 	int r;
596 
597 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
598 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
599 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
600 	if (r)
601 		return r;
602 	if (kvm_has_mirrored_tdp(vcpu->kvm)) {
603 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_external_spt_cache,
604 					       PT64_ROOT_MAX_LEVEL);
605 		if (r)
606 			return r;
607 	}
608 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
609 				       PT64_ROOT_MAX_LEVEL);
610 	if (r)
611 		return r;
612 	if (maybe_indirect) {
613 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
614 					       PT64_ROOT_MAX_LEVEL);
615 		if (r)
616 			return r;
617 	}
618 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
619 					  PT64_ROOT_MAX_LEVEL);
620 }
621 
mmu_free_memory_caches(struct kvm_vcpu * vcpu)622 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
623 {
624 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
625 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
626 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
627 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_external_spt_cache);
628 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
629 }
630 
mmu_free_pte_list_desc(struct pte_list_desc * pte_list_desc)631 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
632 {
633 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
634 }
635 
636 static bool sp_has_gptes(struct kvm_mmu_page *sp);
637 
kvm_mmu_page_get_gfn(struct kvm_mmu_page * sp,int index)638 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
639 {
640 	if (sp->role.passthrough)
641 		return sp->gfn;
642 
643 	if (sp->shadowed_translation)
644 		return sp->shadowed_translation[index] >> PAGE_SHIFT;
645 
646 	return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
647 }
648 
649 /*
650  * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
651  * that the SPTE itself may have a more constrained access permissions that
652  * what the guest enforces. For example, a guest may create an executable
653  * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
654  */
kvm_mmu_page_get_access(struct kvm_mmu_page * sp,int index)655 static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
656 {
657 	if (sp->shadowed_translation)
658 		return sp->shadowed_translation[index] & ACC_ALL;
659 
660 	/*
661 	 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
662 	 * KVM is not shadowing any guest page tables, so the "guest access
663 	 * permissions" are just ACC_ALL.
664 	 *
665 	 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
666 	 * is shadowing a guest huge page with small pages, the guest access
667 	 * permissions being shadowed are the access permissions of the huge
668 	 * page.
669 	 *
670 	 * In both cases, sp->role.access contains the correct access bits.
671 	 */
672 	return sp->role.access;
673 }
674 
kvm_mmu_page_set_translation(struct kvm_mmu_page * sp,int index,gfn_t gfn,unsigned int access)675 static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
676 					 gfn_t gfn, unsigned int access)
677 {
678 	if (sp->shadowed_translation) {
679 		sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
680 		return;
681 	}
682 
683 	WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
684 	          "access mismatch under %s page %llx (expected %u, got %u)\n",
685 	          sp->role.passthrough ? "passthrough" : "direct",
686 	          sp->gfn, kvm_mmu_page_get_access(sp, index), access);
687 
688 	WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
689 	          "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
690 	          sp->role.passthrough ? "passthrough" : "direct",
691 	          sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
692 }
693 
kvm_mmu_page_set_access(struct kvm_mmu_page * sp,int index,unsigned int access)694 static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
695 				    unsigned int access)
696 {
697 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
698 
699 	kvm_mmu_page_set_translation(sp, index, gfn, access);
700 }
701 
702 /*
703  * Return the pointer to the large page information for a given gfn,
704  * handling slots that are not large page aligned.
705  */
lpage_info_slot(gfn_t gfn,const struct kvm_memory_slot * slot,int level)706 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
707 		const struct kvm_memory_slot *slot, int level)
708 {
709 	unsigned long idx;
710 
711 	idx = gfn_to_index(gfn, slot->base_gfn, level);
712 	return &slot->arch.lpage_info[level - 2][idx];
713 }
714 
715 /*
716  * The most significant bit in disallow_lpage tracks whether or not memory
717  * attributes are mixed, i.e. not identical for all gfns at the current level.
718  * The lower order bits are used to refcount other cases where a hugepage is
719  * disallowed, e.g. if KVM has shadow a page table at the gfn.
720  */
721 #define KVM_LPAGE_MIXED_FLAG	BIT(31)
722 
update_gfn_disallow_lpage_count(const struct kvm_memory_slot * slot,gfn_t gfn,int count)723 static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
724 					    gfn_t gfn, int count)
725 {
726 	struct kvm_lpage_info *linfo;
727 	int old, i;
728 
729 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
730 		linfo = lpage_info_slot(gfn, slot, i);
731 
732 		old = linfo->disallow_lpage;
733 		linfo->disallow_lpage += count;
734 		WARN_ON_ONCE((old ^ linfo->disallow_lpage) & KVM_LPAGE_MIXED_FLAG);
735 	}
736 }
737 
kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot * slot,gfn_t gfn)738 void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
739 {
740 	update_gfn_disallow_lpage_count(slot, gfn, 1);
741 }
742 
kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot * slot,gfn_t gfn)743 void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
744 {
745 	update_gfn_disallow_lpage_count(slot, gfn, -1);
746 }
747 
account_shadowed(struct kvm * kvm,struct kvm_mmu_page * sp)748 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
749 {
750 	struct kvm_memslots *slots;
751 	struct kvm_memory_slot *slot;
752 	gfn_t gfn;
753 
754 	kvm->arch.indirect_shadow_pages++;
755 	/*
756 	 * Ensure indirect_shadow_pages is elevated prior to re-reading guest
757 	 * child PTEs in FNAME(gpte_changed), i.e. guarantee either in-flight
758 	 * emulated writes are visible before re-reading guest PTEs, or that
759 	 * an emulated write will see the elevated count and acquire mmu_lock
760 	 * to update SPTEs.  Pairs with the smp_mb() in kvm_mmu_track_write().
761 	 */
762 	smp_mb();
763 
764 	gfn = sp->gfn;
765 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
766 	slot = __gfn_to_memslot(slots, gfn);
767 
768 	/* the non-leaf shadow pages are keeping readonly. */
769 	if (sp->role.level > PG_LEVEL_4K)
770 		return __kvm_write_track_add_gfn(kvm, slot, gfn);
771 
772 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
773 
774 	if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
775 		kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
776 }
777 
track_possible_nx_huge_page(struct kvm * kvm,struct kvm_mmu_page * sp)778 void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
779 {
780 	/*
781 	 * If it's possible to replace the shadow page with an NX huge page,
782 	 * i.e. if the shadow page is the only thing currently preventing KVM
783 	 * from using a huge page, add the shadow page to the list of "to be
784 	 * zapped for NX recovery" pages.  Note, the shadow page can already be
785 	 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
786 	 * links a shadow page at multiple points.
787 	 */
788 	if (!list_empty(&sp->possible_nx_huge_page_link))
789 		return;
790 
791 	++kvm->stat.nx_lpage_splits;
792 	list_add_tail(&sp->possible_nx_huge_page_link,
793 		      &kvm->arch.possible_nx_huge_pages);
794 }
795 
account_nx_huge_page(struct kvm * kvm,struct kvm_mmu_page * sp,bool nx_huge_page_possible)796 static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
797 				 bool nx_huge_page_possible)
798 {
799 	sp->nx_huge_page_disallowed = true;
800 
801 	if (nx_huge_page_possible)
802 		track_possible_nx_huge_page(kvm, sp);
803 }
804 
unaccount_shadowed(struct kvm * kvm,struct kvm_mmu_page * sp)805 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
806 {
807 	struct kvm_memslots *slots;
808 	struct kvm_memory_slot *slot;
809 	gfn_t gfn;
810 
811 	kvm->arch.indirect_shadow_pages--;
812 	gfn = sp->gfn;
813 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
814 	slot = __gfn_to_memslot(slots, gfn);
815 	if (sp->role.level > PG_LEVEL_4K)
816 		return __kvm_write_track_remove_gfn(kvm, slot, gfn);
817 
818 	kvm_mmu_gfn_allow_lpage(slot, gfn);
819 }
820 
untrack_possible_nx_huge_page(struct kvm * kvm,struct kvm_mmu_page * sp)821 void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
822 {
823 	if (list_empty(&sp->possible_nx_huge_page_link))
824 		return;
825 
826 	--kvm->stat.nx_lpage_splits;
827 	list_del_init(&sp->possible_nx_huge_page_link);
828 }
829 
unaccount_nx_huge_page(struct kvm * kvm,struct kvm_mmu_page * sp)830 static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
831 {
832 	sp->nx_huge_page_disallowed = false;
833 
834 	untrack_possible_nx_huge_page(kvm, sp);
835 }
836 
gfn_to_memslot_dirty_bitmap(struct kvm_vcpu * vcpu,gfn_t gfn,bool no_dirty_log)837 static struct kvm_memory_slot *gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu,
838 							   gfn_t gfn,
839 							   bool no_dirty_log)
840 {
841 	struct kvm_memory_slot *slot;
842 
843 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
844 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
845 		return NULL;
846 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
847 		return NULL;
848 
849 	return slot;
850 }
851 
852 /*
853  * About rmap_head encoding:
854  *
855  * If the bit zero of rmap_head->val is clear, then it points to the only spte
856  * in this rmap chain. Otherwise, (rmap_head->val & ~3) points to a struct
857  * pte_list_desc containing more mappings.
858  */
859 #define KVM_RMAP_MANY	BIT(0)
860 
861 /*
862  * rmaps and PTE lists are mostly protected by mmu_lock (the shadow MMU always
863  * operates with mmu_lock held for write), but rmaps can be walked without
864  * holding mmu_lock so long as the caller can tolerate SPTEs in the rmap chain
865  * being zapped/dropped _while the rmap is locked_.
866  *
867  * Other than the KVM_RMAP_LOCKED flag, modifications to rmap entries must be
868  * done while holding mmu_lock for write.  This allows a task walking rmaps
869  * without holding mmu_lock to concurrently walk the same entries as a task
870  * that is holding mmu_lock but _not_ the rmap lock.  Neither task will modify
871  * the rmaps, thus the walks are stable.
872  *
873  * As alluded to above, SPTEs in rmaps are _not_ protected by KVM_RMAP_LOCKED,
874  * only the rmap chains themselves are protected.  E.g. holding an rmap's lock
875  * ensures all "struct pte_list_desc" fields are stable.
876  */
877 #define KVM_RMAP_LOCKED	BIT(1)
878 
__kvm_rmap_lock(struct kvm_rmap_head * rmap_head)879 static unsigned long __kvm_rmap_lock(struct kvm_rmap_head *rmap_head)
880 {
881 	unsigned long old_val, new_val;
882 
883 	lockdep_assert_preemption_disabled();
884 
885 	/*
886 	 * Elide the lock if the rmap is empty, as lockless walkers (read-only
887 	 * mode) don't need to (and can't) walk an empty rmap, nor can they add
888 	 * entries to the rmap.  I.e. the only paths that process empty rmaps
889 	 * do so while holding mmu_lock for write, and are mutually exclusive.
890 	 */
891 	old_val = atomic_long_read(&rmap_head->val);
892 	if (!old_val)
893 		return 0;
894 
895 	do {
896 		/*
897 		 * If the rmap is locked, wait for it to be unlocked before
898 		 * trying acquire the lock, e.g. to avoid bouncing the cache
899 		 * line.
900 		 */
901 		while (old_val & KVM_RMAP_LOCKED) {
902 			cpu_relax();
903 			old_val = atomic_long_read(&rmap_head->val);
904 		}
905 
906 		/*
907 		 * Recheck for an empty rmap, it may have been purged by the
908 		 * task that held the lock.
909 		 */
910 		if (!old_val)
911 			return 0;
912 
913 		new_val = old_val | KVM_RMAP_LOCKED;
914 	/*
915 	 * Use try_cmpxchg_acquire() to prevent reads and writes to the rmap
916 	 * from being reordered outside of the critical section created by
917 	 * __kvm_rmap_lock().
918 	 *
919 	 * Pairs with the atomic_long_set_release() in kvm_rmap_unlock().
920 	 *
921 	 * For the !old_val case, no ordering is needed, as there is no rmap
922 	 * to walk.
923 	 */
924 	} while (!atomic_long_try_cmpxchg_acquire(&rmap_head->val, &old_val, new_val));
925 
926 	/*
927 	 * Return the old value, i.e. _without_ the LOCKED bit set.  It's
928 	 * impossible for the return value to be 0 (see above), i.e. the read-
929 	 * only unlock flow can't get a false positive and fail to unlock.
930 	 */
931 	return old_val;
932 }
933 
kvm_rmap_lock(struct kvm * kvm,struct kvm_rmap_head * rmap_head)934 static unsigned long kvm_rmap_lock(struct kvm *kvm,
935 				   struct kvm_rmap_head *rmap_head)
936 {
937 	lockdep_assert_held_write(&kvm->mmu_lock);
938 
939 	return __kvm_rmap_lock(rmap_head);
940 }
941 
__kvm_rmap_unlock(struct kvm_rmap_head * rmap_head,unsigned long val)942 static void __kvm_rmap_unlock(struct kvm_rmap_head *rmap_head,
943 			      unsigned long val)
944 {
945 	KVM_MMU_WARN_ON(val & KVM_RMAP_LOCKED);
946 	/*
947 	 * Ensure that all accesses to the rmap have completed before unlocking
948 	 * the rmap.
949 	 *
950 	 * Pairs with the atomic_long_try_cmpxchg_acquire() in __kvm_rmap_lock().
951 	 */
952 	atomic_long_set_release(&rmap_head->val, val);
953 }
954 
kvm_rmap_unlock(struct kvm * kvm,struct kvm_rmap_head * rmap_head,unsigned long new_val)955 static void kvm_rmap_unlock(struct kvm *kvm,
956 			    struct kvm_rmap_head *rmap_head,
957 			    unsigned long new_val)
958 {
959 	lockdep_assert_held_write(&kvm->mmu_lock);
960 
961 	__kvm_rmap_unlock(rmap_head, new_val);
962 }
963 
kvm_rmap_get(struct kvm_rmap_head * rmap_head)964 static unsigned long kvm_rmap_get(struct kvm_rmap_head *rmap_head)
965 {
966 	return atomic_long_read(&rmap_head->val) & ~KVM_RMAP_LOCKED;
967 }
968 
969 /*
970  * If mmu_lock isn't held, rmaps can only be locked in read-only mode.  The
971  * actual locking is the same, but the caller is disallowed from modifying the
972  * rmap, and so the unlock flow is a nop if the rmap is/was empty.
973  */
kvm_rmap_lock_readonly(struct kvm_rmap_head * rmap_head)974 static unsigned long kvm_rmap_lock_readonly(struct kvm_rmap_head *rmap_head)
975 {
976 	unsigned long rmap_val;
977 
978 	preempt_disable();
979 	rmap_val = __kvm_rmap_lock(rmap_head);
980 
981 	if (!rmap_val)
982 		preempt_enable();
983 
984 	return rmap_val;
985 }
986 
kvm_rmap_unlock_readonly(struct kvm_rmap_head * rmap_head,unsigned long old_val)987 static void kvm_rmap_unlock_readonly(struct kvm_rmap_head *rmap_head,
988 				     unsigned long old_val)
989 {
990 	if (!old_val)
991 		return;
992 
993 	KVM_MMU_WARN_ON(old_val != kvm_rmap_get(rmap_head));
994 
995 	__kvm_rmap_unlock(rmap_head, old_val);
996 	preempt_enable();
997 }
998 
999 /*
1000  * Returns the number of pointers in the rmap chain, not counting the new one.
1001  */
pte_list_add(struct kvm * kvm,struct kvm_mmu_memory_cache * cache,u64 * spte,struct kvm_rmap_head * rmap_head)1002 static int pte_list_add(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,
1003 			u64 *spte, struct kvm_rmap_head *rmap_head)
1004 {
1005 	unsigned long old_val, new_val;
1006 	struct pte_list_desc *desc;
1007 	int count = 0;
1008 
1009 	old_val = kvm_rmap_lock(kvm, rmap_head);
1010 
1011 	if (!old_val) {
1012 		new_val = (unsigned long)spte;
1013 	} else if (!(old_val & KVM_RMAP_MANY)) {
1014 		desc = kvm_mmu_memory_cache_alloc(cache);
1015 		desc->sptes[0] = (u64 *)old_val;
1016 		desc->sptes[1] = spte;
1017 		desc->spte_count = 2;
1018 		desc->tail_count = 0;
1019 		new_val = (unsigned long)desc | KVM_RMAP_MANY;
1020 		++count;
1021 	} else {
1022 		desc = (struct pte_list_desc *)(old_val & ~KVM_RMAP_MANY);
1023 		count = desc->tail_count + desc->spte_count;
1024 
1025 		/*
1026 		 * If the previous head is full, allocate a new head descriptor
1027 		 * as tail descriptors are always kept full.
1028 		 */
1029 		if (desc->spte_count == PTE_LIST_EXT) {
1030 			desc = kvm_mmu_memory_cache_alloc(cache);
1031 			desc->more = (struct pte_list_desc *)(old_val & ~KVM_RMAP_MANY);
1032 			desc->spte_count = 0;
1033 			desc->tail_count = count;
1034 			new_val = (unsigned long)desc | KVM_RMAP_MANY;
1035 		} else {
1036 			new_val = old_val;
1037 		}
1038 		desc->sptes[desc->spte_count++] = spte;
1039 	}
1040 
1041 	kvm_rmap_unlock(kvm, rmap_head, new_val);
1042 
1043 	return count;
1044 }
1045 
pte_list_desc_remove_entry(struct kvm * kvm,unsigned long * rmap_val,struct pte_list_desc * desc,int i)1046 static void pte_list_desc_remove_entry(struct kvm *kvm, unsigned long *rmap_val,
1047 				       struct pte_list_desc *desc, int i)
1048 {
1049 	struct pte_list_desc *head_desc = (struct pte_list_desc *)(*rmap_val & ~KVM_RMAP_MANY);
1050 	int j = head_desc->spte_count - 1;
1051 
1052 	/*
1053 	 * The head descriptor should never be empty.  A new head is added only
1054 	 * when adding an entry and the previous head is full, and heads are
1055 	 * removed (this flow) when they become empty.
1056 	 */
1057 	KVM_BUG_ON_DATA_CORRUPTION(j < 0, kvm);
1058 
1059 	/*
1060 	 * Replace the to-be-freed SPTE with the last valid entry from the head
1061 	 * descriptor to ensure that tail descriptors are full at all times.
1062 	 * Note, this also means that tail_count is stable for each descriptor.
1063 	 */
1064 	desc->sptes[i] = head_desc->sptes[j];
1065 	head_desc->sptes[j] = NULL;
1066 	head_desc->spte_count--;
1067 	if (head_desc->spte_count)
1068 		return;
1069 
1070 	/*
1071 	 * The head descriptor is empty.  If there are no tail descriptors,
1072 	 * nullify the rmap head to mark the list as empty, else point the rmap
1073 	 * head at the next descriptor, i.e. the new head.
1074 	 */
1075 	if (!head_desc->more)
1076 		*rmap_val = 0;
1077 	else
1078 		*rmap_val = (unsigned long)head_desc->more | KVM_RMAP_MANY;
1079 	mmu_free_pte_list_desc(head_desc);
1080 }
1081 
pte_list_remove(struct kvm * kvm,u64 * spte,struct kvm_rmap_head * rmap_head)1082 static void pte_list_remove(struct kvm *kvm, u64 *spte,
1083 			    struct kvm_rmap_head *rmap_head)
1084 {
1085 	struct pte_list_desc *desc;
1086 	unsigned long rmap_val;
1087 	int i;
1088 
1089 	rmap_val = kvm_rmap_lock(kvm, rmap_head);
1090 	if (KVM_BUG_ON_DATA_CORRUPTION(!rmap_val, kvm))
1091 		goto out;
1092 
1093 	if (!(rmap_val & KVM_RMAP_MANY)) {
1094 		if (KVM_BUG_ON_DATA_CORRUPTION((u64 *)rmap_val != spte, kvm))
1095 			goto out;
1096 
1097 		rmap_val = 0;
1098 	} else {
1099 		desc = (struct pte_list_desc *)(rmap_val & ~KVM_RMAP_MANY);
1100 		while (desc) {
1101 			for (i = 0; i < desc->spte_count; ++i) {
1102 				if (desc->sptes[i] == spte) {
1103 					pte_list_desc_remove_entry(kvm, &rmap_val,
1104 								   desc, i);
1105 					goto out;
1106 				}
1107 			}
1108 			desc = desc->more;
1109 		}
1110 
1111 		KVM_BUG_ON_DATA_CORRUPTION(true, kvm);
1112 	}
1113 
1114 out:
1115 	kvm_rmap_unlock(kvm, rmap_head, rmap_val);
1116 }
1117 
kvm_zap_one_rmap_spte(struct kvm * kvm,struct kvm_rmap_head * rmap_head,u64 * sptep)1118 static void kvm_zap_one_rmap_spte(struct kvm *kvm,
1119 				  struct kvm_rmap_head *rmap_head, u64 *sptep)
1120 {
1121 	mmu_spte_clear_track_bits(kvm, sptep);
1122 	pte_list_remove(kvm, sptep, rmap_head);
1123 }
1124 
1125 /* Return true if at least one SPTE was zapped, false otherwise */
kvm_zap_all_rmap_sptes(struct kvm * kvm,struct kvm_rmap_head * rmap_head)1126 static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
1127 				   struct kvm_rmap_head *rmap_head)
1128 {
1129 	struct pte_list_desc *desc, *next;
1130 	unsigned long rmap_val;
1131 	int i;
1132 
1133 	rmap_val = kvm_rmap_lock(kvm, rmap_head);
1134 	if (!rmap_val)
1135 		return false;
1136 
1137 	if (!(rmap_val & KVM_RMAP_MANY)) {
1138 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_val);
1139 		goto out;
1140 	}
1141 
1142 	desc = (struct pte_list_desc *)(rmap_val & ~KVM_RMAP_MANY);
1143 
1144 	for (; desc; desc = next) {
1145 		for (i = 0; i < desc->spte_count; i++)
1146 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1147 		next = desc->more;
1148 		mmu_free_pte_list_desc(desc);
1149 	}
1150 out:
1151 	/* rmap_head is meaningless now, remember to reset it */
1152 	kvm_rmap_unlock(kvm, rmap_head, 0);
1153 	return true;
1154 }
1155 
pte_list_count(struct kvm_rmap_head * rmap_head)1156 unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
1157 {
1158 	unsigned long rmap_val = kvm_rmap_get(rmap_head);
1159 	struct pte_list_desc *desc;
1160 
1161 	if (!rmap_val)
1162 		return 0;
1163 	else if (!(rmap_val & KVM_RMAP_MANY))
1164 		return 1;
1165 
1166 	desc = (struct pte_list_desc *)(rmap_val & ~KVM_RMAP_MANY);
1167 	return desc->tail_count + desc->spte_count;
1168 }
1169 
gfn_to_rmap(gfn_t gfn,int level,const struct kvm_memory_slot * slot)1170 static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1171 					 const struct kvm_memory_slot *slot)
1172 {
1173 	unsigned long idx;
1174 
1175 	idx = gfn_to_index(gfn, slot->base_gfn, level);
1176 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1177 }
1178 
rmap_remove(struct kvm * kvm,u64 * spte)1179 static void rmap_remove(struct kvm *kvm, u64 *spte)
1180 {
1181 	struct kvm_memslots *slots;
1182 	struct kvm_memory_slot *slot;
1183 	struct kvm_mmu_page *sp;
1184 	gfn_t gfn;
1185 	struct kvm_rmap_head *rmap_head;
1186 
1187 	sp = sptep_to_sp(spte);
1188 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1189 
1190 	/*
1191 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
1192 	 * so we have to determine which memslots to use based on context
1193 	 * information in sp->role.
1194 	 */
1195 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1196 
1197 	slot = __gfn_to_memslot(slots, gfn);
1198 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1199 
1200 	pte_list_remove(kvm, spte, rmap_head);
1201 }
1202 
1203 /*
1204  * Used by the following functions to iterate through the sptes linked by a
1205  * rmap.  All fields are private and not assumed to be used outside.
1206  */
1207 struct rmap_iterator {
1208 	/* private fields */
1209 	struct rmap_head *head;
1210 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1211 	int pos;			/* index of the sptep */
1212 };
1213 
1214 /*
1215  * Iteration must be started by this function.  This should also be used after
1216  * removing/dropping sptes from the rmap link because in such cases the
1217  * information in the iterator may not be valid.
1218  *
1219  * Returns sptep if found, NULL otherwise.
1220  */
rmap_get_first(struct kvm_rmap_head * rmap_head,struct rmap_iterator * iter)1221 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1222 			   struct rmap_iterator *iter)
1223 {
1224 	unsigned long rmap_val = kvm_rmap_get(rmap_head);
1225 
1226 	if (!rmap_val)
1227 		return NULL;
1228 
1229 	if (!(rmap_val & KVM_RMAP_MANY)) {
1230 		iter->desc = NULL;
1231 		return (u64 *)rmap_val;
1232 	}
1233 
1234 	iter->desc = (struct pte_list_desc *)(rmap_val & ~KVM_RMAP_MANY);
1235 	iter->pos = 0;
1236 	return iter->desc->sptes[iter->pos];
1237 }
1238 
1239 /*
1240  * Must be used with a valid iterator: e.g. after rmap_get_first().
1241  *
1242  * Returns sptep if found, NULL otherwise.
1243  */
rmap_get_next(struct rmap_iterator * iter)1244 static u64 *rmap_get_next(struct rmap_iterator *iter)
1245 {
1246 	if (iter->desc) {
1247 		if (iter->pos < PTE_LIST_EXT - 1) {
1248 			++iter->pos;
1249 			if (iter->desc->sptes[iter->pos])
1250 				return iter->desc->sptes[iter->pos];
1251 		}
1252 
1253 		iter->desc = iter->desc->more;
1254 
1255 		if (iter->desc) {
1256 			iter->pos = 0;
1257 			/* desc->sptes[0] cannot be NULL */
1258 			return iter->desc->sptes[iter->pos];
1259 		}
1260 	}
1261 
1262 	return NULL;
1263 }
1264 
1265 #define __for_each_rmap_spte(_rmap_head_, _iter_, _sptep_)	\
1266 	for (_sptep_ = rmap_get_first(_rmap_head_, _iter_);	\
1267 	     _sptep_; _sptep_ = rmap_get_next(_iter_))
1268 
1269 #define for_each_rmap_spte(_rmap_head_, _iter_, _sptep_)			\
1270 	__for_each_rmap_spte(_rmap_head_, _iter_, _sptep_)			\
1271 		if (!WARN_ON_ONCE(!is_shadow_present_pte(*(_sptep_))))	\
1272 
1273 #define for_each_rmap_spte_lockless(_rmap_head_, _iter_, _sptep_, _spte_)	\
1274 	__for_each_rmap_spte(_rmap_head_, _iter_, _sptep_)			\
1275 		if (is_shadow_present_pte(_spte_ = mmu_spte_get_lockless(sptep)))
1276 
drop_spte(struct kvm * kvm,u64 * sptep)1277 static void drop_spte(struct kvm *kvm, u64 *sptep)
1278 {
1279 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
1280 
1281 	if (is_shadow_present_pte(old_spte))
1282 		rmap_remove(kvm, sptep);
1283 }
1284 
drop_large_spte(struct kvm * kvm,u64 * sptep,bool flush)1285 static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1286 {
1287 	struct kvm_mmu_page *sp;
1288 
1289 	sp = sptep_to_sp(sptep);
1290 	WARN_ON_ONCE(sp->role.level == PG_LEVEL_4K);
1291 
1292 	drop_spte(kvm, sptep);
1293 
1294 	if (flush)
1295 		kvm_flush_remote_tlbs_sptep(kvm, sptep);
1296 }
1297 
1298 /*
1299  * Write-protect on the specified @sptep, @pt_protect indicates whether
1300  * spte write-protection is caused by protecting shadow page table.
1301  *
1302  * Note: write protection is difference between dirty logging and spte
1303  * protection:
1304  * - for dirty logging, the spte can be set to writable at anytime if
1305  *   its dirty bitmap is properly set.
1306  * - for spte protection, the spte can be writable only after unsync-ing
1307  *   shadow page.
1308  *
1309  * Return true if tlb need be flushed.
1310  */
spte_write_protect(u64 * sptep,bool pt_protect)1311 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1312 {
1313 	u64 spte = *sptep;
1314 
1315 	if (!is_writable_pte(spte) &&
1316 	    !(pt_protect && is_mmu_writable_spte(spte)))
1317 		return false;
1318 
1319 	if (pt_protect)
1320 		spte &= ~shadow_mmu_writable_mask;
1321 	spte = spte & ~PT_WRITABLE_MASK;
1322 
1323 	return mmu_spte_update(sptep, spte);
1324 }
1325 
rmap_write_protect(struct kvm_rmap_head * rmap_head,bool pt_protect)1326 static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1327 			       bool pt_protect)
1328 {
1329 	u64 *sptep;
1330 	struct rmap_iterator iter;
1331 	bool flush = false;
1332 
1333 	for_each_rmap_spte(rmap_head, &iter, sptep)
1334 		flush |= spte_write_protect(sptep, pt_protect);
1335 
1336 	return flush;
1337 }
1338 
spte_clear_dirty(u64 * sptep)1339 static bool spte_clear_dirty(u64 *sptep)
1340 {
1341 	u64 spte = *sptep;
1342 
1343 	KVM_MMU_WARN_ON(!spte_ad_enabled(spte));
1344 	spte &= ~shadow_dirty_mask;
1345 	return mmu_spte_update(sptep, spte);
1346 }
1347 
1348 /*
1349  * Gets the GFN ready for another round of dirty logging by clearing the
1350  *	- D bit on ad-enabled SPTEs, and
1351  *	- W bit on ad-disabled SPTEs.
1352  * Returns true iff any D or W bits were cleared.
1353  */
__rmap_clear_dirty(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)1354 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1355 			       const struct kvm_memory_slot *slot)
1356 {
1357 	u64 *sptep;
1358 	struct rmap_iterator iter;
1359 	bool flush = false;
1360 
1361 	for_each_rmap_spte(rmap_head, &iter, sptep) {
1362 		if (spte_ad_need_write_protect(*sptep))
1363 			flush |= test_and_clear_bit(PT_WRITABLE_SHIFT,
1364 						    (unsigned long *)sptep);
1365 		else
1366 			flush |= spte_clear_dirty(sptep);
1367 	}
1368 
1369 	return flush;
1370 }
1371 
kvm_mmu_write_protect_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)1372 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1373 				     struct kvm_memory_slot *slot,
1374 				     gfn_t gfn_offset, unsigned long mask)
1375 {
1376 	struct kvm_rmap_head *rmap_head;
1377 
1378 	if (tdp_mmu_enabled)
1379 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1380 				slot->base_gfn + gfn_offset, mask, true);
1381 
1382 	if (!kvm_memslots_have_rmaps(kvm))
1383 		return;
1384 
1385 	while (mask) {
1386 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1387 					PG_LEVEL_4K, slot);
1388 		rmap_write_protect(rmap_head, false);
1389 
1390 		/* clear the first set bit */
1391 		mask &= mask - 1;
1392 	}
1393 }
1394 
kvm_mmu_clear_dirty_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)1395 static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1396 					 struct kvm_memory_slot *slot,
1397 					 gfn_t gfn_offset, unsigned long mask)
1398 {
1399 	struct kvm_rmap_head *rmap_head;
1400 
1401 	if (tdp_mmu_enabled)
1402 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1403 				slot->base_gfn + gfn_offset, mask, false);
1404 
1405 	if (!kvm_memslots_have_rmaps(kvm))
1406 		return;
1407 
1408 	while (mask) {
1409 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1410 					PG_LEVEL_4K, slot);
1411 		__rmap_clear_dirty(kvm, rmap_head, slot);
1412 
1413 		/* clear the first set bit */
1414 		mask &= mask - 1;
1415 	}
1416 }
1417 
kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)1418 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1419 				struct kvm_memory_slot *slot,
1420 				gfn_t gfn_offset, unsigned long mask)
1421 {
1422 	/*
1423 	 * If the slot was assumed to be "initially all dirty", write-protect
1424 	 * huge pages to ensure they are split to 4KiB on the first write (KVM
1425 	 * dirty logs at 4KiB granularity). If eager page splitting is enabled,
1426 	 * immediately try to split huge pages, e.g. so that vCPUs don't get
1427 	 * saddled with the cost of splitting.
1428 	 *
1429 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
1430 	 * of memslot has no such restriction, so the range can cross two large
1431 	 * pages.
1432 	 */
1433 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1434 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
1435 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
1436 
1437 		if (READ_ONCE(eager_page_split))
1438 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end + 1, PG_LEVEL_4K);
1439 
1440 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
1441 
1442 		/* Cross two large pages? */
1443 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
1444 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
1445 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
1446 						       PG_LEVEL_2M);
1447 	}
1448 
1449 	/*
1450 	 * (Re)Enable dirty logging for all 4KiB SPTEs that map the GFNs in
1451 	 * mask.  If PML is enabled and the GFN doesn't need to be write-
1452 	 * protected for other reasons, e.g. shadow paging, clear the Dirty bit.
1453 	 * Otherwise clear the Writable bit.
1454 	 *
1455 	 * Note that kvm_mmu_clear_dirty_pt_masked() is called whenever PML is
1456 	 * enabled but it chooses between clearing the Dirty bit and Writeable
1457 	 * bit based on the context.
1458 	 */
1459 	if (kvm_x86_ops.cpu_dirty_log_size)
1460 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1461 	else
1462 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1463 }
1464 
kvm_cpu_dirty_log_size(void)1465 int kvm_cpu_dirty_log_size(void)
1466 {
1467 	return kvm_x86_ops.cpu_dirty_log_size;
1468 }
1469 
kvm_mmu_slot_gfn_write_protect(struct kvm * kvm,struct kvm_memory_slot * slot,u64 gfn,int min_level)1470 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1471 				    struct kvm_memory_slot *slot, u64 gfn,
1472 				    int min_level)
1473 {
1474 	struct kvm_rmap_head *rmap_head;
1475 	int i;
1476 	bool write_protected = false;
1477 
1478 	if (kvm_memslots_have_rmaps(kvm)) {
1479 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1480 			rmap_head = gfn_to_rmap(gfn, i, slot);
1481 			write_protected |= rmap_write_protect(rmap_head, true);
1482 		}
1483 	}
1484 
1485 	if (tdp_mmu_enabled)
1486 		write_protected |=
1487 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
1488 
1489 	return write_protected;
1490 }
1491 
kvm_vcpu_write_protect_gfn(struct kvm_vcpu * vcpu,u64 gfn)1492 static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1493 {
1494 	struct kvm_memory_slot *slot;
1495 
1496 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1497 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1498 }
1499 
kvm_zap_rmap(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)1500 static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1501 			 const struct kvm_memory_slot *slot)
1502 {
1503 	return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1504 }
1505 
1506 struct slot_rmap_walk_iterator {
1507 	/* input fields. */
1508 	const struct kvm_memory_slot *slot;
1509 	gfn_t start_gfn;
1510 	gfn_t end_gfn;
1511 	int start_level;
1512 	int end_level;
1513 
1514 	/* output fields. */
1515 	gfn_t gfn;
1516 	struct kvm_rmap_head *rmap;
1517 	int level;
1518 
1519 	/* private field. */
1520 	struct kvm_rmap_head *end_rmap;
1521 };
1522 
rmap_walk_init_level(struct slot_rmap_walk_iterator * iterator,int level)1523 static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
1524 				 int level)
1525 {
1526 	iterator->level = level;
1527 	iterator->gfn = iterator->start_gfn;
1528 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
1529 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1530 }
1531 
slot_rmap_walk_init(struct slot_rmap_walk_iterator * iterator,const struct kvm_memory_slot * slot,int start_level,int end_level,gfn_t start_gfn,gfn_t end_gfn)1532 static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1533 				const struct kvm_memory_slot *slot,
1534 				int start_level, int end_level,
1535 				gfn_t start_gfn, gfn_t end_gfn)
1536 {
1537 	iterator->slot = slot;
1538 	iterator->start_level = start_level;
1539 	iterator->end_level = end_level;
1540 	iterator->start_gfn = start_gfn;
1541 	iterator->end_gfn = end_gfn;
1542 
1543 	rmap_walk_init_level(iterator, iterator->start_level);
1544 }
1545 
slot_rmap_walk_okay(struct slot_rmap_walk_iterator * iterator)1546 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1547 {
1548 	return !!iterator->rmap;
1549 }
1550 
slot_rmap_walk_next(struct slot_rmap_walk_iterator * iterator)1551 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1552 {
1553 	while (++iterator->rmap <= iterator->end_rmap) {
1554 		iterator->gfn += KVM_PAGES_PER_HPAGE(iterator->level);
1555 
1556 		if (atomic_long_read(&iterator->rmap->val))
1557 			return;
1558 	}
1559 
1560 	if (++iterator->level > iterator->end_level) {
1561 		iterator->rmap = NULL;
1562 		return;
1563 	}
1564 
1565 	rmap_walk_init_level(iterator, iterator->level);
1566 }
1567 
1568 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1569 	   _start_gfn, _end_gfn, _iter_)				\
1570 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1571 				 _end_level_, _start_gfn, _end_gfn);	\
1572 	     slot_rmap_walk_okay(_iter_);				\
1573 	     slot_rmap_walk_next(_iter_))
1574 
1575 /* The return value indicates if tlb flush on all vcpus is needed. */
1576 typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
1577 				    struct kvm_rmap_head *rmap_head,
1578 				    const struct kvm_memory_slot *slot);
1579 
__walk_slot_rmaps(struct kvm * kvm,const struct kvm_memory_slot * slot,slot_rmaps_handler fn,int start_level,int end_level,gfn_t start_gfn,gfn_t end_gfn,bool can_yield,bool flush_on_yield,bool flush)1580 static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
1581 					      const struct kvm_memory_slot *slot,
1582 					      slot_rmaps_handler fn,
1583 					      int start_level, int end_level,
1584 					      gfn_t start_gfn, gfn_t end_gfn,
1585 					      bool can_yield, bool flush_on_yield,
1586 					      bool flush)
1587 {
1588 	struct slot_rmap_walk_iterator iterator;
1589 
1590 	lockdep_assert_held_write(&kvm->mmu_lock);
1591 
1592 	for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
1593 			end_gfn, &iterator) {
1594 		if (iterator.rmap)
1595 			flush |= fn(kvm, iterator.rmap, slot);
1596 
1597 		if (!can_yield)
1598 			continue;
1599 
1600 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
1601 			if (flush && flush_on_yield) {
1602 				kvm_flush_remote_tlbs_range(kvm, start_gfn,
1603 							    iterator.gfn - start_gfn + 1);
1604 				flush = false;
1605 			}
1606 			cond_resched_rwlock_write(&kvm->mmu_lock);
1607 		}
1608 	}
1609 
1610 	return flush;
1611 }
1612 
walk_slot_rmaps(struct kvm * kvm,const struct kvm_memory_slot * slot,slot_rmaps_handler fn,int start_level,int end_level,bool flush_on_yield)1613 static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
1614 					    const struct kvm_memory_slot *slot,
1615 					    slot_rmaps_handler fn,
1616 					    int start_level, int end_level,
1617 					    bool flush_on_yield)
1618 {
1619 	return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
1620 				 slot->base_gfn, slot->base_gfn + slot->npages - 1,
1621 				 true, flush_on_yield, false);
1622 }
1623 
walk_slot_rmaps_4k(struct kvm * kvm,const struct kvm_memory_slot * slot,slot_rmaps_handler fn,bool flush_on_yield)1624 static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
1625 					       const struct kvm_memory_slot *slot,
1626 					       slot_rmaps_handler fn,
1627 					       bool flush_on_yield)
1628 {
1629 	return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
1630 }
1631 
__kvm_rmap_zap_gfn_range(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t start,gfn_t end,bool can_yield,bool flush)1632 static bool __kvm_rmap_zap_gfn_range(struct kvm *kvm,
1633 				     const struct kvm_memory_slot *slot,
1634 				     gfn_t start, gfn_t end, bool can_yield,
1635 				     bool flush)
1636 {
1637 	return __walk_slot_rmaps(kvm, slot, kvm_zap_rmap,
1638 				 PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
1639 				 start, end - 1, can_yield, true, flush);
1640 }
1641 
kvm_unmap_gfn_range(struct kvm * kvm,struct kvm_gfn_range * range)1642 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1643 {
1644 	bool flush = false;
1645 
1646 	/*
1647 	 * To prevent races with vCPUs faulting in a gfn using stale data,
1648 	 * zapping a gfn range must be protected by mmu_invalidate_in_progress
1649 	 * (and mmu_invalidate_seq).  The only exception is memslot deletion;
1650 	 * in that case, SRCU synchronization ensures that SPTEs are zapped
1651 	 * after all vCPUs have unlocked SRCU, guaranteeing that vCPUs see the
1652 	 * invalid slot.
1653 	 */
1654 	lockdep_assert_once(kvm->mmu_invalidate_in_progress ||
1655 			    lockdep_is_held(&kvm->slots_lock));
1656 
1657 	if (kvm_memslots_have_rmaps(kvm))
1658 		flush = __kvm_rmap_zap_gfn_range(kvm, range->slot,
1659 						 range->start, range->end,
1660 						 range->may_block, flush);
1661 
1662 	if (tdp_mmu_enabled)
1663 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1664 
1665 	if (kvm_x86_ops.set_apic_access_page_addr &&
1666 	    range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)
1667 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
1668 
1669 	return flush;
1670 }
1671 
1672 #define RMAP_RECYCLE_THRESHOLD 1000
1673 
__rmap_add(struct kvm * kvm,struct kvm_mmu_memory_cache * cache,const struct kvm_memory_slot * slot,u64 * spte,gfn_t gfn,unsigned int access)1674 static void __rmap_add(struct kvm *kvm,
1675 		       struct kvm_mmu_memory_cache *cache,
1676 		       const struct kvm_memory_slot *slot,
1677 		       u64 *spte, gfn_t gfn, unsigned int access)
1678 {
1679 	struct kvm_mmu_page *sp;
1680 	struct kvm_rmap_head *rmap_head;
1681 	int rmap_count;
1682 
1683 	sp = sptep_to_sp(spte);
1684 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
1685 	kvm_update_page_stats(kvm, sp->role.level, 1);
1686 
1687 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1688 	rmap_count = pte_list_add(kvm, cache, spte, rmap_head);
1689 
1690 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
1691 		kvm->stat.max_mmu_rmap_size = rmap_count;
1692 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
1693 		kvm_zap_all_rmap_sptes(kvm, rmap_head);
1694 		kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
1695 	}
1696 }
1697 
rmap_add(struct kvm_vcpu * vcpu,const struct kvm_memory_slot * slot,u64 * spte,gfn_t gfn,unsigned int access)1698 static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
1699 		     u64 *spte, gfn_t gfn, unsigned int access)
1700 {
1701 	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
1702 
1703 	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
1704 }
1705 
kvm_rmap_age_gfn_range(struct kvm * kvm,struct kvm_gfn_range * range,bool test_only)1706 static bool kvm_rmap_age_gfn_range(struct kvm *kvm,
1707 				   struct kvm_gfn_range *range,
1708 				   bool test_only)
1709 {
1710 	struct kvm_rmap_head *rmap_head;
1711 	struct rmap_iterator iter;
1712 	unsigned long rmap_val;
1713 	bool young = false;
1714 	u64 *sptep;
1715 	gfn_t gfn;
1716 	int level;
1717 	u64 spte;
1718 
1719 	for (level = PG_LEVEL_4K; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
1720 		for (gfn = range->start; gfn < range->end;
1721 		     gfn += KVM_PAGES_PER_HPAGE(level)) {
1722 			rmap_head = gfn_to_rmap(gfn, level, range->slot);
1723 			rmap_val = kvm_rmap_lock_readonly(rmap_head);
1724 
1725 			for_each_rmap_spte_lockless(rmap_head, &iter, sptep, spte) {
1726 				if (!is_accessed_spte(spte))
1727 					continue;
1728 
1729 				if (test_only) {
1730 					kvm_rmap_unlock_readonly(rmap_head, rmap_val);
1731 					return true;
1732 				}
1733 
1734 				if (spte_ad_enabled(spte))
1735 					clear_bit((ffs(shadow_accessed_mask) - 1),
1736 						  (unsigned long *)sptep);
1737 				else
1738 					/*
1739 					 * If the following cmpxchg fails, the
1740 					 * spte is being concurrently modified
1741 					 * and should most likely stay young.
1742 					 */
1743 					cmpxchg64(sptep, spte,
1744 					      mark_spte_for_access_track(spte));
1745 				young = true;
1746 			}
1747 
1748 			kvm_rmap_unlock_readonly(rmap_head, rmap_val);
1749 		}
1750 	}
1751 	return young;
1752 }
1753 
kvm_may_have_shadow_mmu_sptes(struct kvm * kvm)1754 static bool kvm_may_have_shadow_mmu_sptes(struct kvm *kvm)
1755 {
1756 	return !tdp_mmu_enabled || READ_ONCE(kvm->arch.indirect_shadow_pages);
1757 }
1758 
kvm_age_gfn(struct kvm * kvm,struct kvm_gfn_range * range)1759 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1760 {
1761 	bool young = false;
1762 
1763 	if (tdp_mmu_enabled)
1764 		young = kvm_tdp_mmu_age_gfn_range(kvm, range);
1765 
1766 	if (kvm_may_have_shadow_mmu_sptes(kvm))
1767 		young |= kvm_rmap_age_gfn_range(kvm, range, false);
1768 
1769 	return young;
1770 }
1771 
kvm_test_age_gfn(struct kvm * kvm,struct kvm_gfn_range * range)1772 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1773 {
1774 	bool young = false;
1775 
1776 	if (tdp_mmu_enabled)
1777 		young = kvm_tdp_mmu_test_age_gfn(kvm, range);
1778 
1779 	if (young)
1780 		return young;
1781 
1782 	if (kvm_may_have_shadow_mmu_sptes(kvm))
1783 		young |= kvm_rmap_age_gfn_range(kvm, range, true);
1784 
1785 	return young;
1786 }
1787 
kvm_mmu_check_sptes_at_free(struct kvm_mmu_page * sp)1788 static void kvm_mmu_check_sptes_at_free(struct kvm_mmu_page *sp)
1789 {
1790 #ifdef CONFIG_KVM_PROVE_MMU
1791 	int i;
1792 
1793 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
1794 		if (KVM_MMU_WARN_ON(is_shadow_present_pte(sp->spt[i])))
1795 			pr_err_ratelimited("SPTE %llx (@ %p) for gfn %llx shadow-present at free",
1796 					   sp->spt[i], &sp->spt[i],
1797 					   kvm_mmu_page_get_gfn(sp, i));
1798 	}
1799 #endif
1800 }
1801 
kvm_account_mmu_page(struct kvm * kvm,struct kvm_mmu_page * sp)1802 static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1803 {
1804 	kvm->arch.n_used_mmu_pages++;
1805 	kvm_account_pgtable_pages((void *)sp->spt, +1);
1806 }
1807 
kvm_unaccount_mmu_page(struct kvm * kvm,struct kvm_mmu_page * sp)1808 static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1809 {
1810 	kvm->arch.n_used_mmu_pages--;
1811 	kvm_account_pgtable_pages((void *)sp->spt, -1);
1812 }
1813 
kvm_mmu_free_shadow_page(struct kvm_mmu_page * sp)1814 static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1815 {
1816 	kvm_mmu_check_sptes_at_free(sp);
1817 
1818 	hlist_del(&sp->hash_link);
1819 	list_del(&sp->link);
1820 	free_page((unsigned long)sp->spt);
1821 	free_page((unsigned long)sp->shadowed_translation);
1822 	kmem_cache_free(mmu_page_header_cache, sp);
1823 }
1824 
kvm_page_table_hashfn(gfn_t gfn)1825 static unsigned kvm_page_table_hashfn(gfn_t gfn)
1826 {
1827 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1828 }
1829 
mmu_page_add_parent_pte(struct kvm * kvm,struct kvm_mmu_memory_cache * cache,struct kvm_mmu_page * sp,u64 * parent_pte)1830 static void mmu_page_add_parent_pte(struct kvm *kvm,
1831 				    struct kvm_mmu_memory_cache *cache,
1832 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1833 {
1834 	if (!parent_pte)
1835 		return;
1836 
1837 	pte_list_add(kvm, cache, parent_pte, &sp->parent_ptes);
1838 }
1839 
mmu_page_remove_parent_pte(struct kvm * kvm,struct kvm_mmu_page * sp,u64 * parent_pte)1840 static void mmu_page_remove_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1841 				       u64 *parent_pte)
1842 {
1843 	pte_list_remove(kvm, parent_pte, &sp->parent_ptes);
1844 }
1845 
drop_parent_pte(struct kvm * kvm,struct kvm_mmu_page * sp,u64 * parent_pte)1846 static void drop_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1847 			    u64 *parent_pte)
1848 {
1849 	mmu_page_remove_parent_pte(kvm, sp, parent_pte);
1850 	mmu_spte_clear_no_track(parent_pte);
1851 }
1852 
1853 static void mark_unsync(u64 *spte);
kvm_mmu_mark_parents_unsync(struct kvm_mmu_page * sp)1854 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1855 {
1856 	u64 *sptep;
1857 	struct rmap_iterator iter;
1858 
1859 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1860 		mark_unsync(sptep);
1861 	}
1862 }
1863 
mark_unsync(u64 * spte)1864 static void mark_unsync(u64 *spte)
1865 {
1866 	struct kvm_mmu_page *sp;
1867 
1868 	sp = sptep_to_sp(spte);
1869 	if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1870 		return;
1871 	if (sp->unsync_children++)
1872 		return;
1873 	kvm_mmu_mark_parents_unsync(sp);
1874 }
1875 
1876 #define KVM_PAGE_ARRAY_NR 16
1877 
1878 struct kvm_mmu_pages {
1879 	struct mmu_page_and_offset {
1880 		struct kvm_mmu_page *sp;
1881 		unsigned int idx;
1882 	} page[KVM_PAGE_ARRAY_NR];
1883 	unsigned int nr;
1884 };
1885 
mmu_pages_add(struct kvm_mmu_pages * pvec,struct kvm_mmu_page * sp,int idx)1886 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1887 			 int idx)
1888 {
1889 	int i;
1890 
1891 	if (sp->unsync)
1892 		for (i=0; i < pvec->nr; i++)
1893 			if (pvec->page[i].sp == sp)
1894 				return 0;
1895 
1896 	pvec->page[pvec->nr].sp = sp;
1897 	pvec->page[pvec->nr].idx = idx;
1898 	pvec->nr++;
1899 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1900 }
1901 
clear_unsync_child_bit(struct kvm_mmu_page * sp,int idx)1902 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1903 {
1904 	--sp->unsync_children;
1905 	WARN_ON_ONCE((int)sp->unsync_children < 0);
1906 	__clear_bit(idx, sp->unsync_child_bitmap);
1907 }
1908 
__mmu_unsync_walk(struct kvm_mmu_page * sp,struct kvm_mmu_pages * pvec)1909 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1910 			   struct kvm_mmu_pages *pvec)
1911 {
1912 	int i, ret, nr_unsync_leaf = 0;
1913 
1914 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1915 		struct kvm_mmu_page *child;
1916 		u64 ent = sp->spt[i];
1917 
1918 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1919 			clear_unsync_child_bit(sp, i);
1920 			continue;
1921 		}
1922 
1923 		child = spte_to_child_sp(ent);
1924 
1925 		if (child->unsync_children) {
1926 			if (mmu_pages_add(pvec, child, i))
1927 				return -ENOSPC;
1928 
1929 			ret = __mmu_unsync_walk(child, pvec);
1930 			if (!ret) {
1931 				clear_unsync_child_bit(sp, i);
1932 				continue;
1933 			} else if (ret > 0) {
1934 				nr_unsync_leaf += ret;
1935 			} else
1936 				return ret;
1937 		} else if (child->unsync) {
1938 			nr_unsync_leaf++;
1939 			if (mmu_pages_add(pvec, child, i))
1940 				return -ENOSPC;
1941 		} else
1942 			clear_unsync_child_bit(sp, i);
1943 	}
1944 
1945 	return nr_unsync_leaf;
1946 }
1947 
1948 #define INVALID_INDEX (-1)
1949 
mmu_unsync_walk(struct kvm_mmu_page * sp,struct kvm_mmu_pages * pvec)1950 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1951 			   struct kvm_mmu_pages *pvec)
1952 {
1953 	pvec->nr = 0;
1954 	if (!sp->unsync_children)
1955 		return 0;
1956 
1957 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1958 	return __mmu_unsync_walk(sp, pvec);
1959 }
1960 
kvm_unlink_unsync_page(struct kvm * kvm,struct kvm_mmu_page * sp)1961 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1962 {
1963 	WARN_ON_ONCE(!sp->unsync);
1964 	trace_kvm_mmu_sync_page(sp);
1965 	sp->unsync = 0;
1966 	--kvm->stat.mmu_unsync;
1967 }
1968 
1969 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1970 				     struct list_head *invalid_list);
1971 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1972 				    struct list_head *invalid_list);
1973 
sp_has_gptes(struct kvm_mmu_page * sp)1974 static bool sp_has_gptes(struct kvm_mmu_page *sp)
1975 {
1976 	if (sp->role.direct)
1977 		return false;
1978 
1979 	if (sp->role.passthrough)
1980 		return false;
1981 
1982 	return true;
1983 }
1984 
1985 #define for_each_valid_sp(_kvm, _sp, _list)				\
1986 	hlist_for_each_entry(_sp, _list, hash_link)			\
1987 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1988 		} else
1989 
1990 #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn)		\
1991 	for_each_valid_sp(_kvm, _sp,					\
1992 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1993 		if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1994 
kvm_sync_page_check(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp)1995 static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1996 {
1997 	union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
1998 
1999 	/*
2000 	 * Ignore various flags when verifying that it's safe to sync a shadow
2001 	 * page using the current MMU context.
2002 	 *
2003 	 *  - level: not part of the overall MMU role and will never match as the MMU's
2004 	 *           level tracks the root level
2005 	 *  - access: updated based on the new guest PTE
2006 	 *  - quadrant: not part of the overall MMU role (similar to level)
2007 	 */
2008 	const union kvm_mmu_page_role sync_role_ign = {
2009 		.level = 0xf,
2010 		.access = 0x7,
2011 		.quadrant = 0x3,
2012 		.passthrough = 0x1,
2013 	};
2014 
2015 	/*
2016 	 * Direct pages can never be unsync, and KVM should never attempt to
2017 	 * sync a shadow page for a different MMU context, e.g. if the role
2018 	 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
2019 	 * reserved bits checks will be wrong, etc...
2020 	 */
2021 	if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
2022 			 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
2023 		return false;
2024 
2025 	return true;
2026 }
2027 
kvm_sync_spte(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,int i)2028 static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
2029 {
2030 	/* sp->spt[i] has initial value of shadow page table allocation */
2031 	if (sp->spt[i] == SHADOW_NONPRESENT_VALUE)
2032 		return 0;
2033 
2034 	return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
2035 }
2036 
__kvm_sync_page(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp)2037 static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2038 {
2039 	int flush = 0;
2040 	int i;
2041 
2042 	if (!kvm_sync_page_check(vcpu, sp))
2043 		return -1;
2044 
2045 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
2046 		int ret = kvm_sync_spte(vcpu, sp, i);
2047 
2048 		if (ret < -1)
2049 			return -1;
2050 		flush |= ret;
2051 	}
2052 
2053 	/*
2054 	 * Note, any flush is purely for KVM's correctness, e.g. when dropping
2055 	 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
2056 	 * unmap or dirty logging event doesn't fail to flush.  The guest is
2057 	 * responsible for flushing the TLB to ensure any changes in protection
2058 	 * bits are recognized, i.e. until the guest flushes or page faults on
2059 	 * a relevant address, KVM is architecturally allowed to let vCPUs use
2060 	 * cached translations with the old protection bits.
2061 	 */
2062 	return flush;
2063 }
2064 
kvm_sync_page(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,struct list_head * invalid_list)2065 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2066 			 struct list_head *invalid_list)
2067 {
2068 	int ret = __kvm_sync_page(vcpu, sp);
2069 
2070 	if (ret < 0)
2071 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2072 	return ret;
2073 }
2074 
kvm_mmu_remote_flush_or_zap(struct kvm * kvm,struct list_head * invalid_list,bool remote_flush)2075 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2076 					struct list_head *invalid_list,
2077 					bool remote_flush)
2078 {
2079 	if (!remote_flush && list_empty(invalid_list))
2080 		return false;
2081 
2082 	if (!list_empty(invalid_list))
2083 		kvm_mmu_commit_zap_page(kvm, invalid_list);
2084 	else
2085 		kvm_flush_remote_tlbs(kvm);
2086 	return true;
2087 }
2088 
is_obsolete_sp(struct kvm * kvm,struct kvm_mmu_page * sp)2089 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2090 {
2091 	if (sp->role.invalid)
2092 		return true;
2093 
2094 	/* TDP MMU pages do not use the MMU generation. */
2095 	return !is_tdp_mmu_page(sp) &&
2096 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2097 }
2098 
2099 struct mmu_page_path {
2100 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2101 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
2102 };
2103 
2104 #define for_each_sp(pvec, sp, parents, i)			\
2105 		for (i = mmu_pages_first(&pvec, &parents);	\
2106 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
2107 			i = mmu_pages_next(&pvec, &parents, i))
2108 
mmu_pages_next(struct kvm_mmu_pages * pvec,struct mmu_page_path * parents,int i)2109 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2110 			  struct mmu_page_path *parents,
2111 			  int i)
2112 {
2113 	int n;
2114 
2115 	for (n = i+1; n < pvec->nr; n++) {
2116 		struct kvm_mmu_page *sp = pvec->page[n].sp;
2117 		unsigned idx = pvec->page[n].idx;
2118 		int level = sp->role.level;
2119 
2120 		parents->idx[level-1] = idx;
2121 		if (level == PG_LEVEL_4K)
2122 			break;
2123 
2124 		parents->parent[level-2] = sp;
2125 	}
2126 
2127 	return n;
2128 }
2129 
mmu_pages_first(struct kvm_mmu_pages * pvec,struct mmu_page_path * parents)2130 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2131 			   struct mmu_page_path *parents)
2132 {
2133 	struct kvm_mmu_page *sp;
2134 	int level;
2135 
2136 	if (pvec->nr == 0)
2137 		return 0;
2138 
2139 	WARN_ON_ONCE(pvec->page[0].idx != INVALID_INDEX);
2140 
2141 	sp = pvec->page[0].sp;
2142 	level = sp->role.level;
2143 	WARN_ON_ONCE(level == PG_LEVEL_4K);
2144 
2145 	parents->parent[level-2] = sp;
2146 
2147 	/* Also set up a sentinel.  Further entries in pvec are all
2148 	 * children of sp, so this element is never overwritten.
2149 	 */
2150 	parents->parent[level-1] = NULL;
2151 	return mmu_pages_next(pvec, parents, 0);
2152 }
2153 
mmu_pages_clear_parents(struct mmu_page_path * parents)2154 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2155 {
2156 	struct kvm_mmu_page *sp;
2157 	unsigned int level = 0;
2158 
2159 	do {
2160 		unsigned int idx = parents->idx[level];
2161 		sp = parents->parent[level];
2162 		if (!sp)
2163 			return;
2164 
2165 		WARN_ON_ONCE(idx == INVALID_INDEX);
2166 		clear_unsync_child_bit(sp, idx);
2167 		level++;
2168 	} while (!sp->unsync_children);
2169 }
2170 
mmu_sync_children(struct kvm_vcpu * vcpu,struct kvm_mmu_page * parent,bool can_yield)2171 static int mmu_sync_children(struct kvm_vcpu *vcpu,
2172 			     struct kvm_mmu_page *parent, bool can_yield)
2173 {
2174 	int i;
2175 	struct kvm_mmu_page *sp;
2176 	struct mmu_page_path parents;
2177 	struct kvm_mmu_pages pages;
2178 	LIST_HEAD(invalid_list);
2179 	bool flush = false;
2180 
2181 	while (mmu_unsync_walk(parent, &pages)) {
2182 		bool protected = false;
2183 
2184 		for_each_sp(pages, sp, parents, i)
2185 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2186 
2187 		if (protected) {
2188 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2189 			flush = false;
2190 		}
2191 
2192 		for_each_sp(pages, sp, parents, i) {
2193 			kvm_unlink_unsync_page(vcpu->kvm, sp);
2194 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2195 			mmu_pages_clear_parents(&parents);
2196 		}
2197 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2198 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2199 			if (!can_yield) {
2200 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2201 				return -EINTR;
2202 			}
2203 
2204 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2205 			flush = false;
2206 		}
2207 	}
2208 
2209 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2210 	return 0;
2211 }
2212 
__clear_sp_write_flooding_count(struct kvm_mmu_page * sp)2213 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2214 {
2215 	atomic_set(&sp->write_flooding_count,  0);
2216 }
2217 
clear_sp_write_flooding_count(u64 * spte)2218 static void clear_sp_write_flooding_count(u64 *spte)
2219 {
2220 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2221 }
2222 
2223 /*
2224  * The vCPU is required when finding indirect shadow pages; the shadow
2225  * page may already exist and syncing it needs the vCPU pointer in
2226  * order to read guest page tables.  Direct shadow pages are never
2227  * unsync, thus @vcpu can be NULL if @role.direct is true.
2228  */
kvm_mmu_find_shadow_page(struct kvm * kvm,struct kvm_vcpu * vcpu,gfn_t gfn,struct hlist_head * sp_list,union kvm_mmu_page_role role)2229 static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
2230 						     struct kvm_vcpu *vcpu,
2231 						     gfn_t gfn,
2232 						     struct hlist_head *sp_list,
2233 						     union kvm_mmu_page_role role)
2234 {
2235 	struct kvm_mmu_page *sp;
2236 	int ret;
2237 	int collisions = 0;
2238 	LIST_HEAD(invalid_list);
2239 
2240 	for_each_valid_sp(kvm, sp, sp_list) {
2241 		if (sp->gfn != gfn) {
2242 			collisions++;
2243 			continue;
2244 		}
2245 
2246 		if (sp->role.word != role.word) {
2247 			/*
2248 			 * If the guest is creating an upper-level page, zap
2249 			 * unsync pages for the same gfn.  While it's possible
2250 			 * the guest is using recursive page tables, in all
2251 			 * likelihood the guest has stopped using the unsync
2252 			 * page and is installing a completely unrelated page.
2253 			 * Unsync pages must not be left as is, because the new
2254 			 * upper-level page will be write-protected.
2255 			 */
2256 			if (role.level > PG_LEVEL_4K && sp->unsync)
2257 				kvm_mmu_prepare_zap_page(kvm, sp,
2258 							 &invalid_list);
2259 			continue;
2260 		}
2261 
2262 		/* unsync and write-flooding only apply to indirect SPs. */
2263 		if (sp->role.direct)
2264 			goto out;
2265 
2266 		if (sp->unsync) {
2267 			if (KVM_BUG_ON(!vcpu, kvm))
2268 				break;
2269 
2270 			/*
2271 			 * The page is good, but is stale.  kvm_sync_page does
2272 			 * get the latest guest state, but (unlike mmu_unsync_children)
2273 			 * it doesn't write-protect the page or mark it synchronized!
2274 			 * This way the validity of the mapping is ensured, but the
2275 			 * overhead of write protection is not incurred until the
2276 			 * guest invalidates the TLB mapping.  This allows multiple
2277 			 * SPs for a single gfn to be unsync.
2278 			 *
2279 			 * If the sync fails, the page is zapped.  If so, break
2280 			 * in order to rebuild it.
2281 			 */
2282 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
2283 			if (ret < 0)
2284 				break;
2285 
2286 			WARN_ON_ONCE(!list_empty(&invalid_list));
2287 			if (ret > 0)
2288 				kvm_flush_remote_tlbs(kvm);
2289 		}
2290 
2291 		__clear_sp_write_flooding_count(sp);
2292 
2293 		goto out;
2294 	}
2295 
2296 	sp = NULL;
2297 	++kvm->stat.mmu_cache_miss;
2298 
2299 out:
2300 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2301 
2302 	if (collisions > kvm->stat.max_mmu_page_hash_collisions)
2303 		kvm->stat.max_mmu_page_hash_collisions = collisions;
2304 	return sp;
2305 }
2306 
2307 /* Caches used when allocating a new shadow page. */
2308 struct shadow_page_caches {
2309 	struct kvm_mmu_memory_cache *page_header_cache;
2310 	struct kvm_mmu_memory_cache *shadow_page_cache;
2311 	struct kvm_mmu_memory_cache *shadowed_info_cache;
2312 };
2313 
kvm_mmu_alloc_shadow_page(struct kvm * kvm,struct shadow_page_caches * caches,gfn_t gfn,struct hlist_head * sp_list,union kvm_mmu_page_role role)2314 static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
2315 						      struct shadow_page_caches *caches,
2316 						      gfn_t gfn,
2317 						      struct hlist_head *sp_list,
2318 						      union kvm_mmu_page_role role)
2319 {
2320 	struct kvm_mmu_page *sp;
2321 
2322 	sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
2323 	sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2324 	if (!role.direct && role.level <= KVM_MAX_HUGEPAGE_LEVEL)
2325 		sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2326 
2327 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2328 
2329 	INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2330 
2331 	/*
2332 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2333 	 * depends on valid pages being added to the head of the list.  See
2334 	 * comments in kvm_zap_obsolete_pages().
2335 	 */
2336 	sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2337 	list_add(&sp->link, &kvm->arch.active_mmu_pages);
2338 	kvm_account_mmu_page(kvm, sp);
2339 
2340 	sp->gfn = gfn;
2341 	sp->role = role;
2342 	hlist_add_head(&sp->hash_link, sp_list);
2343 	if (sp_has_gptes(sp))
2344 		account_shadowed(kvm, sp);
2345 
2346 	return sp;
2347 }
2348 
2349 /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
__kvm_mmu_get_shadow_page(struct kvm * kvm,struct kvm_vcpu * vcpu,struct shadow_page_caches * caches,gfn_t gfn,union kvm_mmu_page_role role)2350 static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
2351 						      struct kvm_vcpu *vcpu,
2352 						      struct shadow_page_caches *caches,
2353 						      gfn_t gfn,
2354 						      union kvm_mmu_page_role role)
2355 {
2356 	struct hlist_head *sp_list;
2357 	struct kvm_mmu_page *sp;
2358 	bool created = false;
2359 
2360 	sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2361 
2362 	sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
2363 	if (!sp) {
2364 		created = true;
2365 		sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
2366 	}
2367 
2368 	trace_kvm_mmu_get_page(sp, created);
2369 	return sp;
2370 }
2371 
kvm_mmu_get_shadow_page(struct kvm_vcpu * vcpu,gfn_t gfn,union kvm_mmu_page_role role)2372 static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
2373 						    gfn_t gfn,
2374 						    union kvm_mmu_page_role role)
2375 {
2376 	struct shadow_page_caches caches = {
2377 		.page_header_cache = &vcpu->arch.mmu_page_header_cache,
2378 		.shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
2379 		.shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
2380 	};
2381 
2382 	return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
2383 }
2384 
kvm_mmu_child_role(u64 * sptep,bool direct,unsigned int access)2385 static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
2386 						  unsigned int access)
2387 {
2388 	struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
2389 	union kvm_mmu_page_role role;
2390 
2391 	role = parent_sp->role;
2392 	role.level--;
2393 	role.access = access;
2394 	role.direct = direct;
2395 	role.passthrough = 0;
2396 
2397 	/*
2398 	 * If the guest has 4-byte PTEs then that means it's using 32-bit,
2399 	 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
2400 	 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
2401 	 * shadow each guest page table with multiple shadow page tables, which
2402 	 * requires extra bookkeeping in the role.
2403 	 *
2404 	 * Specifically, to shadow the guest's page directory (which covers a
2405 	 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
2406 	 * 1GiB of the address space. @role.quadrant encodes which quarter of
2407 	 * the address space each maps.
2408 	 *
2409 	 * To shadow the guest's page tables (which each map a 4MiB region), KVM
2410 	 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
2411 	 * @role.quadrant encodes which half of the region they map.
2412 	 *
2413 	 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
2414 	 * consumes bits 29:21.  To consume bits 31:30, KVM's uses 4 shadow
2415 	 * PDPTEs; those 4 PAE page directories are pre-allocated and their
2416 	 * quadrant is assigned in mmu_alloc_root().   A 4-byte PTE consumes
2417 	 * bits 21:12, while an 8-byte PTE consumes bits 20:12.  To consume
2418 	 * bit 21 in the PTE (the child here), KVM propagates that bit to the
2419 	 * quadrant, i.e. sets quadrant to '0' or '1'.  The parent 8-byte PDE
2420 	 * covers bit 21 (see above), thus the quadrant is calculated from the
2421 	 * _least_ significant bit of the PDE index.
2422 	 */
2423 	if (role.has_4_byte_gpte) {
2424 		WARN_ON_ONCE(role.level != PG_LEVEL_4K);
2425 		role.quadrant = spte_index(sptep) & 1;
2426 	}
2427 
2428 	return role;
2429 }
2430 
kvm_mmu_get_child_sp(struct kvm_vcpu * vcpu,u64 * sptep,gfn_t gfn,bool direct,unsigned int access)2431 static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
2432 						 u64 *sptep, gfn_t gfn,
2433 						 bool direct, unsigned int access)
2434 {
2435 	union kvm_mmu_page_role role;
2436 
2437 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
2438 		return ERR_PTR(-EEXIST);
2439 
2440 	role = kvm_mmu_child_role(sptep, direct, access);
2441 	return kvm_mmu_get_shadow_page(vcpu, gfn, role);
2442 }
2443 
shadow_walk_init_using_root(struct kvm_shadow_walk_iterator * iterator,struct kvm_vcpu * vcpu,hpa_t root,u64 addr)2444 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2445 					struct kvm_vcpu *vcpu, hpa_t root,
2446 					u64 addr)
2447 {
2448 	iterator->addr = addr;
2449 	iterator->shadow_addr = root;
2450 	iterator->level = vcpu->arch.mmu->root_role.level;
2451 
2452 	if (iterator->level >= PT64_ROOT_4LEVEL &&
2453 	    vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2454 	    !vcpu->arch.mmu->root_role.direct)
2455 		iterator->level = PT32E_ROOT_LEVEL;
2456 
2457 	if (iterator->level == PT32E_ROOT_LEVEL) {
2458 		/*
2459 		 * prev_root is currently only used for 64-bit hosts. So only
2460 		 * the active root_hpa is valid here.
2461 		 */
2462 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2463 
2464 		iterator->shadow_addr
2465 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2466 		iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2467 		--iterator->level;
2468 		if (!iterator->shadow_addr)
2469 			iterator->level = 0;
2470 	}
2471 }
2472 
shadow_walk_init(struct kvm_shadow_walk_iterator * iterator,struct kvm_vcpu * vcpu,u64 addr)2473 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2474 			     struct kvm_vcpu *vcpu, u64 addr)
2475 {
2476 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2477 				    addr);
2478 }
2479 
shadow_walk_okay(struct kvm_shadow_walk_iterator * iterator)2480 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2481 {
2482 	if (iterator->level < PG_LEVEL_4K)
2483 		return false;
2484 
2485 	iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2486 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2487 	return true;
2488 }
2489 
__shadow_walk_next(struct kvm_shadow_walk_iterator * iterator,u64 spte)2490 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2491 			       u64 spte)
2492 {
2493 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2494 		iterator->level = 0;
2495 		return;
2496 	}
2497 
2498 	iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2499 	--iterator->level;
2500 }
2501 
shadow_walk_next(struct kvm_shadow_walk_iterator * iterator)2502 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2503 {
2504 	__shadow_walk_next(iterator, *iterator->sptep);
2505 }
2506 
__link_shadow_page(struct kvm * kvm,struct kvm_mmu_memory_cache * cache,u64 * sptep,struct kvm_mmu_page * sp,bool flush)2507 static void __link_shadow_page(struct kvm *kvm,
2508 			       struct kvm_mmu_memory_cache *cache, u64 *sptep,
2509 			       struct kvm_mmu_page *sp, bool flush)
2510 {
2511 	u64 spte;
2512 
2513 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2514 
2515 	/*
2516 	 * If an SPTE is present already, it must be a leaf and therefore
2517 	 * a large one.  Drop it, and flush the TLB if needed, before
2518 	 * installing sp.
2519 	 */
2520 	if (is_shadow_present_pte(*sptep))
2521 		drop_large_spte(kvm, sptep, flush);
2522 
2523 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2524 
2525 	mmu_spte_set(sptep, spte);
2526 
2527 	mmu_page_add_parent_pte(kvm, cache, sp, sptep);
2528 
2529 	/*
2530 	 * The non-direct sub-pagetable must be updated before linking.  For
2531 	 * L1 sp, the pagetable is updated via kvm_sync_page() in
2532 	 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2533 	 * so sp->unsync can be true or false.  For higher level non-direct
2534 	 * sp, the pagetable is updated/synced via mmu_sync_children() in
2535 	 * FNAME(fetch)(), so sp->unsync_children can only be false.
2536 	 * WARN_ON_ONCE() if anything happens unexpectedly.
2537 	 */
2538 	if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2539 		mark_unsync(sptep);
2540 }
2541 
link_shadow_page(struct kvm_vcpu * vcpu,u64 * sptep,struct kvm_mmu_page * sp)2542 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2543 			     struct kvm_mmu_page *sp)
2544 {
2545 	__link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
2546 }
2547 
validate_direct_spte(struct kvm_vcpu * vcpu,u64 * sptep,unsigned direct_access)2548 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2549 				   unsigned direct_access)
2550 {
2551 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2552 		struct kvm_mmu_page *child;
2553 
2554 		/*
2555 		 * For the direct sp, if the guest pte's dirty bit
2556 		 * changed form clean to dirty, it will corrupt the
2557 		 * sp's access: allow writable in the read-only sp,
2558 		 * so we should update the spte at this point to get
2559 		 * a new sp with the correct access.
2560 		 */
2561 		child = spte_to_child_sp(*sptep);
2562 		if (child->role.access == direct_access)
2563 			return;
2564 
2565 		drop_parent_pte(vcpu->kvm, child, sptep);
2566 		kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2567 	}
2568 }
2569 
2570 /* Returns the number of zapped non-leaf child shadow pages. */
mmu_page_zap_pte(struct kvm * kvm,struct kvm_mmu_page * sp,u64 * spte,struct list_head * invalid_list)2571 static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2572 			    u64 *spte, struct list_head *invalid_list)
2573 {
2574 	u64 pte;
2575 	struct kvm_mmu_page *child;
2576 
2577 	pte = *spte;
2578 	if (is_shadow_present_pte(pte)) {
2579 		if (is_last_spte(pte, sp->role.level)) {
2580 			drop_spte(kvm, spte);
2581 		} else {
2582 			child = spte_to_child_sp(pte);
2583 			drop_parent_pte(kvm, child, spte);
2584 
2585 			/*
2586 			 * Recursively zap nested TDP SPs, parentless SPs are
2587 			 * unlikely to be used again in the near future.  This
2588 			 * avoids retaining a large number of stale nested SPs.
2589 			 */
2590 			if (tdp_enabled && invalid_list &&
2591 			    child->role.guest_mode &&
2592 			    !atomic_long_read(&child->parent_ptes.val))
2593 				return kvm_mmu_prepare_zap_page(kvm, child,
2594 								invalid_list);
2595 		}
2596 	} else if (is_mmio_spte(kvm, pte)) {
2597 		mmu_spte_clear_no_track(spte);
2598 	}
2599 	return 0;
2600 }
2601 
kvm_mmu_page_unlink_children(struct kvm * kvm,struct kvm_mmu_page * sp,struct list_head * invalid_list)2602 static int kvm_mmu_page_unlink_children(struct kvm *kvm,
2603 					struct kvm_mmu_page *sp,
2604 					struct list_head *invalid_list)
2605 {
2606 	int zapped = 0;
2607 	unsigned i;
2608 
2609 	for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
2610 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
2611 
2612 	return zapped;
2613 }
2614 
kvm_mmu_unlink_parents(struct kvm * kvm,struct kvm_mmu_page * sp)2615 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2616 {
2617 	u64 *sptep;
2618 	struct rmap_iterator iter;
2619 
2620 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2621 		drop_parent_pte(kvm, sp, sptep);
2622 }
2623 
mmu_zap_unsync_children(struct kvm * kvm,struct kvm_mmu_page * parent,struct list_head * invalid_list)2624 static int mmu_zap_unsync_children(struct kvm *kvm,
2625 				   struct kvm_mmu_page *parent,
2626 				   struct list_head *invalid_list)
2627 {
2628 	int i, zapped = 0;
2629 	struct mmu_page_path parents;
2630 	struct kvm_mmu_pages pages;
2631 
2632 	if (parent->role.level == PG_LEVEL_4K)
2633 		return 0;
2634 
2635 	while (mmu_unsync_walk(parent, &pages)) {
2636 		struct kvm_mmu_page *sp;
2637 
2638 		for_each_sp(pages, sp, parents, i) {
2639 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2640 			mmu_pages_clear_parents(&parents);
2641 			zapped++;
2642 		}
2643 	}
2644 
2645 	return zapped;
2646 }
2647 
__kvm_mmu_prepare_zap_page(struct kvm * kvm,struct kvm_mmu_page * sp,struct list_head * invalid_list,int * nr_zapped)2648 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2649 				       struct kvm_mmu_page *sp,
2650 				       struct list_head *invalid_list,
2651 				       int *nr_zapped)
2652 {
2653 	bool list_unstable, zapped_root = false;
2654 
2655 	lockdep_assert_held_write(&kvm->mmu_lock);
2656 	trace_kvm_mmu_prepare_zap_page(sp);
2657 	++kvm->stat.mmu_shadow_zapped;
2658 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2659 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2660 	kvm_mmu_unlink_parents(kvm, sp);
2661 
2662 	/* Zapping children means active_mmu_pages has become unstable. */
2663 	list_unstable = *nr_zapped;
2664 
2665 	if (!sp->role.invalid && sp_has_gptes(sp))
2666 		unaccount_shadowed(kvm, sp);
2667 
2668 	if (sp->unsync)
2669 		kvm_unlink_unsync_page(kvm, sp);
2670 	if (!sp->root_count) {
2671 		/* Count self */
2672 		(*nr_zapped)++;
2673 
2674 		/*
2675 		 * Already invalid pages (previously active roots) are not on
2676 		 * the active page list.  See list_del() in the "else" case of
2677 		 * !sp->root_count.
2678 		 */
2679 		if (sp->role.invalid)
2680 			list_add(&sp->link, invalid_list);
2681 		else
2682 			list_move(&sp->link, invalid_list);
2683 		kvm_unaccount_mmu_page(kvm, sp);
2684 	} else {
2685 		/*
2686 		 * Remove the active root from the active page list, the root
2687 		 * will be explicitly freed when the root_count hits zero.
2688 		 */
2689 		list_del(&sp->link);
2690 
2691 		/*
2692 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2693 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2694 		 * treats invalid shadow pages as being obsolete.
2695 		 */
2696 		zapped_root = !is_obsolete_sp(kvm, sp);
2697 	}
2698 
2699 	if (sp->nx_huge_page_disallowed)
2700 		unaccount_nx_huge_page(kvm, sp);
2701 
2702 	sp->role.invalid = 1;
2703 
2704 	/*
2705 	 * Make the request to free obsolete roots after marking the root
2706 	 * invalid, otherwise other vCPUs may not see it as invalid.
2707 	 */
2708 	if (zapped_root)
2709 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2710 	return list_unstable;
2711 }
2712 
kvm_mmu_prepare_zap_page(struct kvm * kvm,struct kvm_mmu_page * sp,struct list_head * invalid_list)2713 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2714 				     struct list_head *invalid_list)
2715 {
2716 	int nr_zapped;
2717 
2718 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2719 	return nr_zapped;
2720 }
2721 
kvm_mmu_commit_zap_page(struct kvm * kvm,struct list_head * invalid_list)2722 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2723 				    struct list_head *invalid_list)
2724 {
2725 	struct kvm_mmu_page *sp, *nsp;
2726 
2727 	if (list_empty(invalid_list))
2728 		return;
2729 
2730 	/*
2731 	 * We need to make sure everyone sees our modifications to
2732 	 * the page tables and see changes to vcpu->mode here. The barrier
2733 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2734 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2735 	 *
2736 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2737 	 * guest mode and/or lockless shadow page table walks.
2738 	 */
2739 	kvm_flush_remote_tlbs(kvm);
2740 
2741 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2742 		WARN_ON_ONCE(!sp->role.invalid || sp->root_count);
2743 		kvm_mmu_free_shadow_page(sp);
2744 	}
2745 }
2746 
kvm_mmu_zap_oldest_mmu_pages(struct kvm * kvm,unsigned long nr_to_zap)2747 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2748 						  unsigned long nr_to_zap)
2749 {
2750 	unsigned long total_zapped = 0;
2751 	struct kvm_mmu_page *sp, *tmp;
2752 	LIST_HEAD(invalid_list);
2753 	bool unstable;
2754 	int nr_zapped;
2755 
2756 	if (list_empty(&kvm->arch.active_mmu_pages))
2757 		return 0;
2758 
2759 restart:
2760 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2761 		/*
2762 		 * Don't zap active root pages, the page itself can't be freed
2763 		 * and zapping it will just force vCPUs to realloc and reload.
2764 		 */
2765 		if (sp->root_count)
2766 			continue;
2767 
2768 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2769 						      &nr_zapped);
2770 		total_zapped += nr_zapped;
2771 		if (total_zapped >= nr_to_zap)
2772 			break;
2773 
2774 		if (unstable)
2775 			goto restart;
2776 	}
2777 
2778 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2779 
2780 	kvm->stat.mmu_recycled += total_zapped;
2781 	return total_zapped;
2782 }
2783 
kvm_mmu_available_pages(struct kvm * kvm)2784 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2785 {
2786 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2787 		return kvm->arch.n_max_mmu_pages -
2788 			kvm->arch.n_used_mmu_pages;
2789 
2790 	return 0;
2791 }
2792 
make_mmu_pages_available(struct kvm_vcpu * vcpu)2793 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2794 {
2795 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2796 
2797 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2798 		return 0;
2799 
2800 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2801 
2802 	/*
2803 	 * Note, this check is intentionally soft, it only guarantees that one
2804 	 * page is available, while the caller may end up allocating as many as
2805 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
2806 	 * exceeding the (arbitrary by default) limit will not harm the host,
2807 	 * being too aggressive may unnecessarily kill the guest, and getting an
2808 	 * exact count is far more trouble than it's worth, especially in the
2809 	 * page fault paths.
2810 	 */
2811 	if (!kvm_mmu_available_pages(vcpu->kvm))
2812 		return -ENOSPC;
2813 	return 0;
2814 }
2815 
2816 /*
2817  * Changing the number of mmu pages allocated to the vm
2818  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2819  */
kvm_mmu_change_mmu_pages(struct kvm * kvm,unsigned long goal_nr_mmu_pages)2820 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2821 {
2822 	write_lock(&kvm->mmu_lock);
2823 
2824 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2825 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2826 						  goal_nr_mmu_pages);
2827 
2828 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2829 	}
2830 
2831 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2832 
2833 	write_unlock(&kvm->mmu_lock);
2834 }
2835 
__kvm_mmu_unprotect_gfn_and_retry(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,bool always_retry)2836 bool __kvm_mmu_unprotect_gfn_and_retry(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
2837 				       bool always_retry)
2838 {
2839 	struct kvm *kvm = vcpu->kvm;
2840 	LIST_HEAD(invalid_list);
2841 	struct kvm_mmu_page *sp;
2842 	gpa_t gpa = cr2_or_gpa;
2843 	bool r = false;
2844 
2845 	/*
2846 	 * Bail early if there aren't any write-protected shadow pages to avoid
2847 	 * unnecessarily taking mmu_lock lock, e.g. if the gfn is write-tracked
2848 	 * by a third party.  Reading indirect_shadow_pages without holding
2849 	 * mmu_lock is safe, as this is purely an optimization, i.e. a false
2850 	 * positive is benign, and a false negative will simply result in KVM
2851 	 * skipping the unprotect+retry path, which is also an optimization.
2852 	 */
2853 	if (!READ_ONCE(kvm->arch.indirect_shadow_pages))
2854 		goto out;
2855 
2856 	if (!vcpu->arch.mmu->root_role.direct) {
2857 		gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
2858 		if (gpa == INVALID_GPA)
2859 			goto out;
2860 	}
2861 
2862 	write_lock(&kvm->mmu_lock);
2863 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gpa_to_gfn(gpa))
2864 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2865 
2866 	/*
2867 	 * Snapshot the result before zapping, as zapping will remove all list
2868 	 * entries, i.e. checking the list later would yield a false negative.
2869 	 */
2870 	r = !list_empty(&invalid_list);
2871 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2872 	write_unlock(&kvm->mmu_lock);
2873 
2874 out:
2875 	if (r || always_retry) {
2876 		vcpu->arch.last_retry_eip = kvm_rip_read(vcpu);
2877 		vcpu->arch.last_retry_addr = cr2_or_gpa;
2878 	}
2879 	return r;
2880 }
2881 
kvm_unsync_page(struct kvm * kvm,struct kvm_mmu_page * sp)2882 static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2883 {
2884 	trace_kvm_mmu_unsync_page(sp);
2885 	++kvm->stat.mmu_unsync;
2886 	sp->unsync = 1;
2887 
2888 	kvm_mmu_mark_parents_unsync(sp);
2889 }
2890 
2891 /*
2892  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
2893  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
2894  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
2895  * be write-protected.
2896  */
mmu_try_to_unsync_pages(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t gfn,bool synchronizing,bool prefetch)2897 int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
2898 			    gfn_t gfn, bool synchronizing, bool prefetch)
2899 {
2900 	struct kvm_mmu_page *sp;
2901 	bool locked = false;
2902 
2903 	/*
2904 	 * Force write-protection if the page is being tracked.  Note, the page
2905 	 * track machinery is used to write-protect upper-level shadow pages,
2906 	 * i.e. this guards the role.level == 4K assertion below!
2907 	 */
2908 	if (kvm_gfn_is_write_tracked(kvm, slot, gfn))
2909 		return -EPERM;
2910 
2911 	/*
2912 	 * The page is not write-tracked, mark existing shadow pages unsync
2913 	 * unless KVM is synchronizing an unsync SP.  In that case, KVM must
2914 	 * complete emulation of the guest TLB flush before allowing shadow
2915 	 * pages to become unsync (writable by the guest).
2916 	 */
2917 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2918 		if (synchronizing)
2919 			return -EPERM;
2920 
2921 		if (sp->unsync)
2922 			continue;
2923 
2924 		if (prefetch)
2925 			return -EEXIST;
2926 
2927 		/*
2928 		 * TDP MMU page faults require an additional spinlock as they
2929 		 * run with mmu_lock held for read, not write, and the unsync
2930 		 * logic is not thread safe.  Take the spinklock regardless of
2931 		 * the MMU type to avoid extra conditionals/parameters, there's
2932 		 * no meaningful penalty if mmu_lock is held for write.
2933 		 */
2934 		if (!locked) {
2935 			locked = true;
2936 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2937 
2938 			/*
2939 			 * Recheck after taking the spinlock, a different vCPU
2940 			 * may have since marked the page unsync.  A false
2941 			 * negative on the unprotected check above is not
2942 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2943 			 * for write, i.e. unsync cannot transition from 1->0
2944 			 * while this CPU holds mmu_lock for read (or write).
2945 			 */
2946 			if (READ_ONCE(sp->unsync))
2947 				continue;
2948 		}
2949 
2950 		WARN_ON_ONCE(sp->role.level != PG_LEVEL_4K);
2951 		kvm_unsync_page(kvm, sp);
2952 	}
2953 	if (locked)
2954 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2955 
2956 	/*
2957 	 * We need to ensure that the marking of unsync pages is visible
2958 	 * before the SPTE is updated to allow writes because
2959 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2960 	 * the MMU lock and so can race with this. If the SPTE was updated
2961 	 * before the page had been marked as unsync-ed, something like the
2962 	 * following could happen:
2963 	 *
2964 	 * CPU 1                    CPU 2
2965 	 * ---------------------------------------------------------------------
2966 	 * 1.2 Host updates SPTE
2967 	 *     to be writable
2968 	 *                      2.1 Guest writes a GPTE for GVA X.
2969 	 *                          (GPTE being in the guest page table shadowed
2970 	 *                           by the SP from CPU 1.)
2971 	 *                          This reads SPTE during the page table walk.
2972 	 *                          Since SPTE.W is read as 1, there is no
2973 	 *                          fault.
2974 	 *
2975 	 *                      2.2 Guest issues TLB flush.
2976 	 *                          That causes a VM Exit.
2977 	 *
2978 	 *                      2.3 Walking of unsync pages sees sp->unsync is
2979 	 *                          false and skips the page.
2980 	 *
2981 	 *                      2.4 Guest accesses GVA X.
2982 	 *                          Since the mapping in the SP was not updated,
2983 	 *                          so the old mapping for GVA X incorrectly
2984 	 *                          gets used.
2985 	 * 1.1 Host marks SP
2986 	 *     as unsync
2987 	 *     (sp->unsync = true)
2988 	 *
2989 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2990 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2991 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2992 	 */
2993 	smp_wmb();
2994 
2995 	return 0;
2996 }
2997 
mmu_set_spte(struct kvm_vcpu * vcpu,struct kvm_memory_slot * slot,u64 * sptep,unsigned int pte_access,gfn_t gfn,kvm_pfn_t pfn,struct kvm_page_fault * fault)2998 static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
2999 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
3000 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
3001 {
3002 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
3003 	int level = sp->role.level;
3004 	int was_rmapped = 0;
3005 	int ret = RET_PF_FIXED;
3006 	bool flush = false;
3007 	bool wrprot;
3008 	u64 spte;
3009 
3010 	/* Prefetching always gets a writable pfn.  */
3011 	bool host_writable = !fault || fault->map_writable;
3012 	bool prefetch = !fault || fault->prefetch;
3013 	bool write_fault = fault && fault->write;
3014 
3015 	if (unlikely(is_noslot_pfn(pfn))) {
3016 		vcpu->stat.pf_mmio_spte_created++;
3017 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
3018 		return RET_PF_EMULATE;
3019 	}
3020 
3021 	if (is_shadow_present_pte(*sptep)) {
3022 		if (prefetch)
3023 			return RET_PF_SPURIOUS;
3024 
3025 		/*
3026 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3027 		 * the parent of the now unreachable PTE.
3028 		 */
3029 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
3030 			struct kvm_mmu_page *child;
3031 			u64 pte = *sptep;
3032 
3033 			child = spte_to_child_sp(pte);
3034 			drop_parent_pte(vcpu->kvm, child, sptep);
3035 			flush = true;
3036 		} else if (pfn != spte_to_pfn(*sptep)) {
3037 			drop_spte(vcpu->kvm, sptep);
3038 			flush = true;
3039 		} else
3040 			was_rmapped = 1;
3041 	}
3042 
3043 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
3044 			   false, host_writable, &spte);
3045 
3046 	if (*sptep == spte) {
3047 		ret = RET_PF_SPURIOUS;
3048 	} else {
3049 		flush |= mmu_spte_update(sptep, spte);
3050 		trace_kvm_mmu_set_spte(level, gfn, sptep);
3051 	}
3052 
3053 	if (wrprot && write_fault)
3054 		ret = RET_PF_WRITE_PROTECTED;
3055 
3056 	if (flush)
3057 		kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
3058 
3059 	if (!was_rmapped) {
3060 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
3061 		rmap_add(vcpu, slot, sptep, gfn, pte_access);
3062 	} else {
3063 		/* Already rmapped but the pte_access bits may have changed. */
3064 		kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
3065 	}
3066 
3067 	return ret;
3068 }
3069 
kvm_mmu_prefetch_sptes(struct kvm_vcpu * vcpu,gfn_t gfn,u64 * sptep,int nr_pages,unsigned int access)3070 static bool kvm_mmu_prefetch_sptes(struct kvm_vcpu *vcpu, gfn_t gfn, u64 *sptep,
3071 				   int nr_pages, unsigned int access)
3072 {
3073 	struct page *pages[PTE_PREFETCH_NUM];
3074 	struct kvm_memory_slot *slot;
3075 	int i;
3076 
3077 	if (WARN_ON_ONCE(nr_pages > PTE_PREFETCH_NUM))
3078 		return false;
3079 
3080 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3081 	if (!slot)
3082 		return false;
3083 
3084 	nr_pages = kvm_prefetch_pages(slot, gfn, pages, nr_pages);
3085 	if (nr_pages <= 0)
3086 		return false;
3087 
3088 	for (i = 0; i < nr_pages; i++, gfn++, sptep++) {
3089 		mmu_set_spte(vcpu, slot, sptep, access, gfn,
3090 			     page_to_pfn(pages[i]), NULL);
3091 
3092 		/*
3093 		 * KVM always prefetches writable pages from the primary MMU,
3094 		 * and KVM can make its SPTE writable in the fast page handler,
3095 		 * without notifying the primary MMU.  Mark pages/folios dirty
3096 		 * now to ensure file data is written back if it ends up being
3097 		 * written by the guest.  Because KVM's prefetching GUPs
3098 		 * writable PTEs, the probability of unnecessary writeback is
3099 		 * extremely low.
3100 		 */
3101 		kvm_release_page_dirty(pages[i]);
3102 	}
3103 
3104 	return true;
3105 }
3106 
direct_pte_prefetch_many(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * start,u64 * end)3107 static bool direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3108 				     struct kvm_mmu_page *sp,
3109 				     u64 *start, u64 *end)
3110 {
3111 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
3112 	unsigned int access = sp->role.access;
3113 
3114 	return kvm_mmu_prefetch_sptes(vcpu, gfn, start, end - start, access);
3115 }
3116 
__direct_pte_prefetch(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * sptep)3117 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3118 				  struct kvm_mmu_page *sp, u64 *sptep)
3119 {
3120 	u64 *spte, *start = NULL;
3121 	int i;
3122 
3123 	WARN_ON_ONCE(!sp->role.direct);
3124 
3125 	i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
3126 	spte = sp->spt + i;
3127 
3128 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3129 		if (is_shadow_present_pte(*spte) || spte == sptep) {
3130 			if (!start)
3131 				continue;
3132 			if (!direct_pte_prefetch_many(vcpu, sp, start, spte))
3133 				return;
3134 
3135 			start = NULL;
3136 		} else if (!start)
3137 			start = spte;
3138 	}
3139 	if (start)
3140 		direct_pte_prefetch_many(vcpu, sp, start, spte);
3141 }
3142 
direct_pte_prefetch(struct kvm_vcpu * vcpu,u64 * sptep)3143 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3144 {
3145 	struct kvm_mmu_page *sp;
3146 
3147 	sp = sptep_to_sp(sptep);
3148 
3149 	/*
3150 	 * Without accessed bits, there's no way to distinguish between
3151 	 * actually accessed translations and prefetched, so disable pte
3152 	 * prefetch if accessed bits aren't available.
3153 	 */
3154 	if (sp_ad_disabled(sp))
3155 		return;
3156 
3157 	if (sp->role.level > PG_LEVEL_4K)
3158 		return;
3159 
3160 	/*
3161 	 * If addresses are being invalidated, skip prefetching to avoid
3162 	 * accidentally prefetching those addresses.
3163 	 */
3164 	if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
3165 		return;
3166 
3167 	__direct_pte_prefetch(vcpu, sp, sptep);
3168 }
3169 
3170 /*
3171  * Lookup the mapping level for @gfn in the current mm.
3172  *
3173  * WARNING!  Use of host_pfn_mapping_level() requires the caller and the end
3174  * consumer to be tied into KVM's handlers for MMU notifier events!
3175  *
3176  * There are several ways to safely use this helper:
3177  *
3178  * - Check mmu_invalidate_retry_gfn() after grabbing the mapping level, before
3179  *   consuming it.  In this case, mmu_lock doesn't need to be held during the
3180  *   lookup, but it does need to be held while checking the MMU notifier.
3181  *
3182  * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
3183  *   event for the hva.  This can be done by explicit checking the MMU notifier
3184  *   or by ensuring that KVM already has a valid mapping that covers the hva.
3185  *
3186  * - Do not use the result to install new mappings, e.g. use the host mapping
3187  *   level only to decide whether or not to zap an entry.  In this case, it's
3188  *   not required to hold mmu_lock (though it's highly likely the caller will
3189  *   want to hold mmu_lock anyways, e.g. to modify SPTEs).
3190  *
3191  * Note!  The lookup can still race with modifications to host page tables, but
3192  * the above "rules" ensure KVM will not _consume_ the result of the walk if a
3193  * race with the primary MMU occurs.
3194  */
host_pfn_mapping_level(struct kvm * kvm,gfn_t gfn,const struct kvm_memory_slot * slot)3195 static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
3196 				  const struct kvm_memory_slot *slot)
3197 {
3198 	int level = PG_LEVEL_4K;
3199 	unsigned long hva;
3200 	unsigned long flags;
3201 	pgd_t pgd;
3202 	p4d_t p4d;
3203 	pud_t pud;
3204 	pmd_t pmd;
3205 
3206 	/*
3207 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3208 	 * is not solely for performance, it's also necessary to avoid the
3209 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
3210 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
3211 	 * page fault steps have already verified the guest isn't writing a
3212 	 * read-only memslot.
3213 	 */
3214 	hva = __gfn_to_hva_memslot(slot, gfn);
3215 
3216 	/*
3217 	 * Disable IRQs to prevent concurrent tear down of host page tables,
3218 	 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
3219 	 * the original page table.
3220 	 */
3221 	local_irq_save(flags);
3222 
3223 	/*
3224 	 * Read each entry once.  As above, a non-leaf entry can be promoted to
3225 	 * a huge page _during_ this walk.  Re-reading the entry could send the
3226 	 * walk into the weeks, e.g. p*d_leaf() returns false (sees the old
3227 	 * value) and then p*d_offset() walks into the target huge page instead
3228 	 * of the old page table (sees the new value).
3229 	 */
3230 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
3231 	if (pgd_none(pgd))
3232 		goto out;
3233 
3234 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
3235 	if (p4d_none(p4d) || !p4d_present(p4d))
3236 		goto out;
3237 
3238 	pud = READ_ONCE(*pud_offset(&p4d, hva));
3239 	if (pud_none(pud) || !pud_present(pud))
3240 		goto out;
3241 
3242 	if (pud_leaf(pud)) {
3243 		level = PG_LEVEL_1G;
3244 		goto out;
3245 	}
3246 
3247 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
3248 	if (pmd_none(pmd) || !pmd_present(pmd))
3249 		goto out;
3250 
3251 	if (pmd_leaf(pmd))
3252 		level = PG_LEVEL_2M;
3253 
3254 out:
3255 	local_irq_restore(flags);
3256 	return level;
3257 }
3258 
__kvm_mmu_max_mapping_level(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t gfn,int max_level,bool is_private)3259 static int __kvm_mmu_max_mapping_level(struct kvm *kvm,
3260 				       const struct kvm_memory_slot *slot,
3261 				       gfn_t gfn, int max_level, bool is_private)
3262 {
3263 	struct kvm_lpage_info *linfo;
3264 	int host_level;
3265 
3266 	max_level = min(max_level, max_huge_page_level);
3267 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
3268 		linfo = lpage_info_slot(gfn, slot, max_level);
3269 		if (!linfo->disallow_lpage)
3270 			break;
3271 	}
3272 
3273 	if (is_private)
3274 		return max_level;
3275 
3276 	if (max_level == PG_LEVEL_4K)
3277 		return PG_LEVEL_4K;
3278 
3279 	host_level = host_pfn_mapping_level(kvm, gfn, slot);
3280 	return min(host_level, max_level);
3281 }
3282 
kvm_mmu_max_mapping_level(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t gfn)3283 int kvm_mmu_max_mapping_level(struct kvm *kvm,
3284 			      const struct kvm_memory_slot *slot, gfn_t gfn)
3285 {
3286 	bool is_private = kvm_slot_can_be_private(slot) &&
3287 			  kvm_mem_is_private(kvm, gfn);
3288 
3289 	return __kvm_mmu_max_mapping_level(kvm, slot, gfn, PG_LEVEL_NUM, is_private);
3290 }
3291 
kvm_mmu_hugepage_adjust(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)3292 void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3293 {
3294 	struct kvm_memory_slot *slot = fault->slot;
3295 	kvm_pfn_t mask;
3296 
3297 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
3298 
3299 	if (unlikely(fault->max_level == PG_LEVEL_4K))
3300 		return;
3301 
3302 	if (is_error_noslot_pfn(fault->pfn))
3303 		return;
3304 
3305 	if (kvm_slot_dirty_track_enabled(slot))
3306 		return;
3307 
3308 	/*
3309 	 * Enforce the iTLB multihit workaround after capturing the requested
3310 	 * level, which will be used to do precise, accurate accounting.
3311 	 */
3312 	fault->req_level = __kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3313 						       fault->gfn, fault->max_level,
3314 						       fault->is_private);
3315 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
3316 		return;
3317 
3318 	/*
3319 	 * mmu_invalidate_retry() was successful and mmu_lock is held, so
3320 	 * the pmd can't be split from under us.
3321 	 */
3322 	fault->goal_level = fault->req_level;
3323 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
3324 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
3325 	fault->pfn &= ~mask;
3326 }
3327 
disallowed_hugepage_adjust(struct kvm_page_fault * fault,u64 spte,int cur_level)3328 void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3329 {
3330 	if (cur_level > PG_LEVEL_4K &&
3331 	    cur_level == fault->goal_level &&
3332 	    is_shadow_present_pte(spte) &&
3333 	    !is_large_pte(spte) &&
3334 	    spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3335 		/*
3336 		 * A small SPTE exists for this pfn, but FNAME(fetch),
3337 		 * direct_map(), or kvm_tdp_mmu_map() would like to create a
3338 		 * large PTE instead: just force them to go down another level,
3339 		 * patching back for them into pfn the next 9 bits of the
3340 		 * address.
3341 		 */
3342 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3343 				KVM_PAGES_PER_HPAGE(cur_level - 1);
3344 		fault->pfn |= fault->gfn & page_mask;
3345 		fault->goal_level--;
3346 	}
3347 }
3348 
direct_map(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)3349 static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3350 {
3351 	struct kvm_shadow_walk_iterator it;
3352 	struct kvm_mmu_page *sp;
3353 	int ret;
3354 	gfn_t base_gfn = fault->gfn;
3355 
3356 	kvm_mmu_hugepage_adjust(vcpu, fault);
3357 
3358 	trace_kvm_mmu_spte_requested(fault);
3359 	for_each_shadow_entry(vcpu, fault->addr, it) {
3360 		/*
3361 		 * We cannot overwrite existing page tables with an NX
3362 		 * large page, as the leaf could be executable.
3363 		 */
3364 		if (fault->nx_huge_page_workaround_enabled)
3365 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3366 
3367 		base_gfn = gfn_round_for_level(fault->gfn, it.level);
3368 		if (it.level == fault->goal_level)
3369 			break;
3370 
3371 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
3372 		if (sp == ERR_PTR(-EEXIST))
3373 			continue;
3374 
3375 		link_shadow_page(vcpu, it.sptep, sp);
3376 		if (fault->huge_page_disallowed)
3377 			account_nx_huge_page(vcpu->kvm, sp,
3378 					     fault->req_level >= it.level);
3379 	}
3380 
3381 	if (WARN_ON_ONCE(it.level != fault->goal_level))
3382 		return -EFAULT;
3383 
3384 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3385 			   base_gfn, fault->pfn, fault);
3386 	if (ret == RET_PF_SPURIOUS)
3387 		return ret;
3388 
3389 	direct_pte_prefetch(vcpu, it.sptep);
3390 	return ret;
3391 }
3392 
kvm_send_hwpoison_signal(struct kvm_memory_slot * slot,gfn_t gfn)3393 static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3394 {
3395 	unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3396 
3397 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3398 }
3399 
kvm_handle_error_pfn(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)3400 static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3401 {
3402 	if (is_sigpending_pfn(fault->pfn)) {
3403 		kvm_handle_signal_exit(vcpu);
3404 		return -EINTR;
3405 	}
3406 
3407 	/*
3408 	 * Do not cache the mmio info caused by writing the readonly gfn
3409 	 * into the spte otherwise read access on readonly gfn also can
3410 	 * caused mmio page fault and treat it as mmio access.
3411 	 */
3412 	if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3413 		return RET_PF_EMULATE;
3414 
3415 	if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3416 		kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3417 		return RET_PF_RETRY;
3418 	}
3419 
3420 	return -EFAULT;
3421 }
3422 
kvm_handle_noslot_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault,unsigned int access)3423 static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3424 				   struct kvm_page_fault *fault,
3425 				   unsigned int access)
3426 {
3427 	gva_t gva = fault->is_tdp ? 0 : fault->addr;
3428 
3429 	if (fault->is_private) {
3430 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
3431 		return -EFAULT;
3432 	}
3433 
3434 	vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3435 			     access & shadow_mmio_access_mask);
3436 
3437 	fault->slot = NULL;
3438 	fault->pfn = KVM_PFN_NOSLOT;
3439 	fault->map_writable = false;
3440 
3441 	/*
3442 	 * If MMIO caching is disabled, emulate immediately without
3443 	 * touching the shadow page tables as attempting to install an
3444 	 * MMIO SPTE will just be an expensive nop.
3445 	 */
3446 	if (unlikely(!enable_mmio_caching))
3447 		return RET_PF_EMULATE;
3448 
3449 	/*
3450 	 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3451 	 * any guest that generates such gfns is running nested and is being
3452 	 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3453 	 * only if L1's MAXPHYADDR is inaccurate with respect to the
3454 	 * hardware's).
3455 	 */
3456 	if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3457 		return RET_PF_EMULATE;
3458 
3459 	return RET_PF_CONTINUE;
3460 }
3461 
page_fault_can_be_fast(struct kvm * kvm,struct kvm_page_fault * fault)3462 static bool page_fault_can_be_fast(struct kvm *kvm, struct kvm_page_fault *fault)
3463 {
3464 	/*
3465 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
3466 	 * reach the common page fault handler if the SPTE has an invalid MMIO
3467 	 * generation number.  Refreshing the MMIO generation needs to go down
3468 	 * the slow path.  Note, EPT Misconfigs do NOT set the PRESENT flag!
3469 	 */
3470 	if (fault->rsvd)
3471 		return false;
3472 
3473 	/*
3474 	 * For hardware-protected VMs, certain conditions like attempting to
3475 	 * perform a write to a page which is not in the state that the guest
3476 	 * expects it to be in can result in a nested/extended #PF. In this
3477 	 * case, the below code might misconstrue this situation as being the
3478 	 * result of a write-protected access, and treat it as a spurious case
3479 	 * rather than taking any action to satisfy the real source of the #PF
3480 	 * such as generating a KVM_EXIT_MEMORY_FAULT. This can lead to the
3481 	 * guest spinning on a #PF indefinitely, so don't attempt the fast path
3482 	 * in this case.
3483 	 *
3484 	 * Note that the kvm_mem_is_private() check might race with an
3485 	 * attribute update, but this will either result in the guest spinning
3486 	 * on RET_PF_SPURIOUS until the update completes, or an actual spurious
3487 	 * case might go down the slow path. Either case will resolve itself.
3488 	 */
3489 	if (kvm->arch.has_private_mem &&
3490 	    fault->is_private != kvm_mem_is_private(kvm, fault->gfn))
3491 		return false;
3492 
3493 	/*
3494 	 * #PF can be fast if:
3495 	 *
3496 	 * 1. The shadow page table entry is not present and A/D bits are
3497 	 *    disabled _by KVM_, which could mean that the fault is potentially
3498 	 *    caused by access tracking (if enabled).  If A/D bits are enabled
3499 	 *    by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
3500 	 *    bits for L2 and employ access tracking, but the fast page fault
3501 	 *    mechanism only supports direct MMUs.
3502 	 * 2. The shadow page table entry is present, the access is a write,
3503 	 *    and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
3504 	 *    the fault was caused by a write-protection violation.  If the
3505 	 *    SPTE is MMU-writable (determined later), the fault can be fixed
3506 	 *    by setting the Writable bit, which can be done out of mmu_lock.
3507 	 */
3508 	if (!fault->present)
3509 		return !kvm_ad_enabled;
3510 
3511 	/*
3512 	 * Note, instruction fetches and writes are mutually exclusive, ignore
3513 	 * the "exec" flag.
3514 	 */
3515 	return fault->write;
3516 }
3517 
3518 /*
3519  * Returns true if the SPTE was fixed successfully. Otherwise,
3520  * someone else modified the SPTE from its original value.
3521  */
fast_pf_fix_direct_spte(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault,u64 * sptep,u64 old_spte,u64 new_spte)3522 static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu,
3523 				    struct kvm_page_fault *fault,
3524 				    u64 *sptep, u64 old_spte, u64 new_spte)
3525 {
3526 	/*
3527 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3528 	 * order to eliminate unnecessary PML logging. See comments in
3529 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3530 	 * enabled, so we do not do this. This might result in the same GPA
3531 	 * to be logged in PML buffer again when the write really happens, and
3532 	 * eventually to be called by mark_page_dirty twice. But it's also no
3533 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3534 	 * so non-PML cases won't be impacted.
3535 	 *
3536 	 * Compare with make_spte() where instead shadow_dirty_mask is set.
3537 	 */
3538 	if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3539 		return false;
3540 
3541 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3542 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3543 
3544 	return true;
3545 }
3546 
3547 /*
3548  * Returns the last level spte pointer of the shadow page walk for the given
3549  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
3550  * walk could be performed, returns NULL and *spte does not contain valid data.
3551  *
3552  * Contract:
3553  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
3554  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
3555  */
fast_pf_get_last_sptep(struct kvm_vcpu * vcpu,gpa_t gpa,u64 * spte)3556 static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
3557 {
3558 	struct kvm_shadow_walk_iterator iterator;
3559 	u64 old_spte;
3560 	u64 *sptep = NULL;
3561 
3562 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
3563 		sptep = iterator.sptep;
3564 		*spte = old_spte;
3565 	}
3566 
3567 	return sptep;
3568 }
3569 
3570 /*
3571  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3572  */
fast_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)3573 static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3574 {
3575 	struct kvm_mmu_page *sp;
3576 	int ret = RET_PF_INVALID;
3577 	u64 spte;
3578 	u64 *sptep;
3579 	uint retry_count = 0;
3580 
3581 	if (!page_fault_can_be_fast(vcpu->kvm, fault))
3582 		return ret;
3583 
3584 	walk_shadow_page_lockless_begin(vcpu);
3585 
3586 	do {
3587 		u64 new_spte;
3588 
3589 		if (tdp_mmu_enabled)
3590 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->gfn, &spte);
3591 		else
3592 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3593 
3594 		/*
3595 		 * It's entirely possible for the mapping to have been zapped
3596 		 * by a different task, but the root page should always be
3597 		 * available as the vCPU holds a reference to its root(s).
3598 		 */
3599 		if (WARN_ON_ONCE(!sptep))
3600 			spte = FROZEN_SPTE;
3601 
3602 		if (!is_shadow_present_pte(spte))
3603 			break;
3604 
3605 		sp = sptep_to_sp(sptep);
3606 		if (!is_last_spte(spte, sp->role.level))
3607 			break;
3608 
3609 		/*
3610 		 * Check whether the memory access that caused the fault would
3611 		 * still cause it if it were to be performed right now. If not,
3612 		 * then this is a spurious fault caused by TLB lazily flushed,
3613 		 * or some other CPU has already fixed the PTE after the
3614 		 * current CPU took the fault.
3615 		 *
3616 		 * Need not check the access of upper level table entries since
3617 		 * they are always ACC_ALL.
3618 		 */
3619 		if (is_access_allowed(fault, spte)) {
3620 			ret = RET_PF_SPURIOUS;
3621 			break;
3622 		}
3623 
3624 		new_spte = spte;
3625 
3626 		/*
3627 		 * KVM only supports fixing page faults outside of MMU lock for
3628 		 * direct MMUs, nested MMUs are always indirect, and KVM always
3629 		 * uses A/D bits for non-nested MMUs.  Thus, if A/D bits are
3630 		 * enabled, the SPTE can't be an access-tracked SPTE.
3631 		 */
3632 		if (unlikely(!kvm_ad_enabled) && is_access_track_spte(spte))
3633 			new_spte = restore_acc_track_spte(new_spte) |
3634 				   shadow_accessed_mask;
3635 
3636 		/*
3637 		 * To keep things simple, only SPTEs that are MMU-writable can
3638 		 * be made fully writable outside of mmu_lock, e.g. only SPTEs
3639 		 * that were write-protected for dirty-logging or access
3640 		 * tracking are handled here.  Don't bother checking if the
3641 		 * SPTE is writable to prioritize running with A/D bits enabled.
3642 		 * The is_access_allowed() check above handles the common case
3643 		 * of the fault being spurious, and the SPTE is known to be
3644 		 * shadow-present, i.e. except for access tracking restoration
3645 		 * making the new SPTE writable, the check is wasteful.
3646 		 */
3647 		if (fault->write && is_mmu_writable_spte(spte)) {
3648 			new_spte |= PT_WRITABLE_MASK;
3649 
3650 			/*
3651 			 * Do not fix write-permission on the large spte when
3652 			 * dirty logging is enabled. Since we only dirty the
3653 			 * first page into the dirty-bitmap in
3654 			 * fast_pf_fix_direct_spte(), other pages are missed
3655 			 * if its slot has dirty logging enabled.
3656 			 *
3657 			 * Instead, we let the slow page fault path create a
3658 			 * normal spte to fix the access.
3659 			 */
3660 			if (sp->role.level > PG_LEVEL_4K &&
3661 			    kvm_slot_dirty_track_enabled(fault->slot))
3662 				break;
3663 		}
3664 
3665 		/* Verify that the fault can be handled in the fast path */
3666 		if (new_spte == spte ||
3667 		    !is_access_allowed(fault, new_spte))
3668 			break;
3669 
3670 		/*
3671 		 * Currently, fast page fault only works for direct mapping
3672 		 * since the gfn is not stable for indirect shadow page. See
3673 		 * Documentation/virt/kvm/locking.rst to get more detail.
3674 		 */
3675 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3676 			ret = RET_PF_FIXED;
3677 			break;
3678 		}
3679 
3680 		if (++retry_count > 4) {
3681 			pr_warn_once("Fast #PF retrying more than 4 times.\n");
3682 			break;
3683 		}
3684 
3685 	} while (true);
3686 
3687 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3688 	walk_shadow_page_lockless_end(vcpu);
3689 
3690 	if (ret != RET_PF_INVALID)
3691 		vcpu->stat.pf_fast++;
3692 
3693 	return ret;
3694 }
3695 
mmu_free_root_page(struct kvm * kvm,hpa_t * root_hpa,struct list_head * invalid_list)3696 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3697 			       struct list_head *invalid_list)
3698 {
3699 	struct kvm_mmu_page *sp;
3700 
3701 	if (!VALID_PAGE(*root_hpa))
3702 		return;
3703 
3704 	sp = root_to_sp(*root_hpa);
3705 	if (WARN_ON_ONCE(!sp))
3706 		return;
3707 
3708 	if (is_tdp_mmu_page(sp)) {
3709 		lockdep_assert_held_read(&kvm->mmu_lock);
3710 		kvm_tdp_mmu_put_root(kvm, sp);
3711 	} else {
3712 		lockdep_assert_held_write(&kvm->mmu_lock);
3713 		if (!--sp->root_count && sp->role.invalid)
3714 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3715 	}
3716 
3717 	*root_hpa = INVALID_PAGE;
3718 }
3719 
3720 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
kvm_mmu_free_roots(struct kvm * kvm,struct kvm_mmu * mmu,ulong roots_to_free)3721 void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3722 			ulong roots_to_free)
3723 {
3724 	bool is_tdp_mmu = tdp_mmu_enabled && mmu->root_role.direct;
3725 	int i;
3726 	LIST_HEAD(invalid_list);
3727 	bool free_active_root;
3728 
3729 	WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3730 
3731 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3732 
3733 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3734 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3735 		&& VALID_PAGE(mmu->root.hpa);
3736 
3737 	if (!free_active_root) {
3738 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3739 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3740 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3741 				break;
3742 
3743 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3744 			return;
3745 	}
3746 
3747 	if (is_tdp_mmu)
3748 		read_lock(&kvm->mmu_lock);
3749 	else
3750 		write_lock(&kvm->mmu_lock);
3751 
3752 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3753 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3754 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3755 					   &invalid_list);
3756 
3757 	if (free_active_root) {
3758 		if (kvm_mmu_is_dummy_root(mmu->root.hpa)) {
3759 			/* Nothing to cleanup for dummy roots. */
3760 		} else if (root_to_sp(mmu->root.hpa)) {
3761 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
3762 		} else if (mmu->pae_root) {
3763 			for (i = 0; i < 4; ++i) {
3764 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3765 					continue;
3766 
3767 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3768 						   &invalid_list);
3769 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3770 			}
3771 		}
3772 		mmu->root.hpa = INVALID_PAGE;
3773 		mmu->root.pgd = 0;
3774 	}
3775 
3776 	if (is_tdp_mmu) {
3777 		read_unlock(&kvm->mmu_lock);
3778 		WARN_ON_ONCE(!list_empty(&invalid_list));
3779 	} else {
3780 		kvm_mmu_commit_zap_page(kvm, &invalid_list);
3781 		write_unlock(&kvm->mmu_lock);
3782 	}
3783 }
3784 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3785 
kvm_mmu_free_guest_mode_roots(struct kvm * kvm,struct kvm_mmu * mmu)3786 void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
3787 {
3788 	unsigned long roots_to_free = 0;
3789 	struct kvm_mmu_page *sp;
3790 	hpa_t root_hpa;
3791 	int i;
3792 
3793 	/*
3794 	 * This should not be called while L2 is active, L2 can't invalidate
3795 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
3796 	 */
3797 	WARN_ON_ONCE(mmu->root_role.guest_mode);
3798 
3799 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
3800 		root_hpa = mmu->prev_roots[i].hpa;
3801 		if (!VALID_PAGE(root_hpa))
3802 			continue;
3803 
3804 		sp = root_to_sp(root_hpa);
3805 		if (!sp || sp->role.guest_mode)
3806 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
3807 	}
3808 
3809 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
3810 }
3811 EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
3812 
mmu_alloc_root(struct kvm_vcpu * vcpu,gfn_t gfn,int quadrant,u8 level)3813 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
3814 			    u8 level)
3815 {
3816 	union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3817 	struct kvm_mmu_page *sp;
3818 
3819 	role.level = level;
3820 	role.quadrant = quadrant;
3821 
3822 	WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
3823 	WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
3824 
3825 	sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
3826 	++sp->root_count;
3827 
3828 	return __pa(sp->spt);
3829 }
3830 
mmu_alloc_direct_roots(struct kvm_vcpu * vcpu)3831 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3832 {
3833 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3834 	u8 shadow_root_level = mmu->root_role.level;
3835 	hpa_t root;
3836 	unsigned i;
3837 	int r;
3838 
3839 	if (tdp_mmu_enabled) {
3840 		if (kvm_has_mirrored_tdp(vcpu->kvm) &&
3841 		    !VALID_PAGE(mmu->mirror_root_hpa))
3842 			kvm_tdp_mmu_alloc_root(vcpu, true);
3843 		kvm_tdp_mmu_alloc_root(vcpu, false);
3844 		return 0;
3845 	}
3846 
3847 	write_lock(&vcpu->kvm->mmu_lock);
3848 	r = make_mmu_pages_available(vcpu);
3849 	if (r < 0)
3850 		goto out_unlock;
3851 
3852 	if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3853 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3854 		mmu->root.hpa = root;
3855 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3856 		if (WARN_ON_ONCE(!mmu->pae_root)) {
3857 			r = -EIO;
3858 			goto out_unlock;
3859 		}
3860 
3861 		for (i = 0; i < 4; ++i) {
3862 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3863 
3864 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
3865 					      PT32_ROOT_LEVEL);
3866 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
3867 					   shadow_me_value;
3868 		}
3869 		mmu->root.hpa = __pa(mmu->pae_root);
3870 	} else {
3871 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
3872 		r = -EIO;
3873 		goto out_unlock;
3874 	}
3875 
3876 	/* root.pgd is ignored for direct MMUs. */
3877 	mmu->root.pgd = 0;
3878 out_unlock:
3879 	write_unlock(&vcpu->kvm->mmu_lock);
3880 	return r;
3881 }
3882 
mmu_first_shadow_root_alloc(struct kvm * kvm)3883 static int mmu_first_shadow_root_alloc(struct kvm *kvm)
3884 {
3885 	struct kvm_memslots *slots;
3886 	struct kvm_memory_slot *slot;
3887 	int r = 0, i, bkt;
3888 
3889 	/*
3890 	 * Check if this is the first shadow root being allocated before
3891 	 * taking the lock.
3892 	 */
3893 	if (kvm_shadow_root_allocated(kvm))
3894 		return 0;
3895 
3896 	mutex_lock(&kvm->slots_arch_lock);
3897 
3898 	/* Recheck, under the lock, whether this is the first shadow root. */
3899 	if (kvm_shadow_root_allocated(kvm))
3900 		goto out_unlock;
3901 
3902 	/*
3903 	 * Check if anything actually needs to be allocated, e.g. all metadata
3904 	 * will be allocated upfront if TDP is disabled.
3905 	 */
3906 	if (kvm_memslots_have_rmaps(kvm) &&
3907 	    kvm_page_track_write_tracking_enabled(kvm))
3908 		goto out_success;
3909 
3910 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
3911 		slots = __kvm_memslots(kvm, i);
3912 		kvm_for_each_memslot(slot, bkt, slots) {
3913 			/*
3914 			 * Both of these functions are no-ops if the target is
3915 			 * already allocated, so unconditionally calling both
3916 			 * is safe.  Intentionally do NOT free allocations on
3917 			 * failure to avoid having to track which allocations
3918 			 * were made now versus when the memslot was created.
3919 			 * The metadata is guaranteed to be freed when the slot
3920 			 * is freed, and will be kept/used if userspace retries
3921 			 * KVM_RUN instead of killing the VM.
3922 			 */
3923 			r = memslot_rmap_alloc(slot, slot->npages);
3924 			if (r)
3925 				goto out_unlock;
3926 			r = kvm_page_track_write_tracking_alloc(slot);
3927 			if (r)
3928 				goto out_unlock;
3929 		}
3930 	}
3931 
3932 	/*
3933 	 * Ensure that shadow_root_allocated becomes true strictly after
3934 	 * all the related pointers are set.
3935 	 */
3936 out_success:
3937 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
3938 
3939 out_unlock:
3940 	mutex_unlock(&kvm->slots_arch_lock);
3941 	return r;
3942 }
3943 
mmu_alloc_shadow_roots(struct kvm_vcpu * vcpu)3944 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3945 {
3946 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3947 	u64 pdptrs[4], pm_mask;
3948 	gfn_t root_gfn, root_pgd;
3949 	int quadrant, i, r;
3950 	hpa_t root;
3951 
3952 	root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
3953 	root_gfn = (root_pgd & __PT_BASE_ADDR_MASK) >> PAGE_SHIFT;
3954 
3955 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3956 		mmu->root.hpa = kvm_mmu_get_dummy_root();
3957 		return 0;
3958 	}
3959 
3960 	/*
3961 	 * On SVM, reading PDPTRs might access guest memory, which might fault
3962 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
3963 	 */
3964 	if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3965 		for (i = 0; i < 4; ++i) {
3966 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
3967 			if (!(pdptrs[i] & PT_PRESENT_MASK))
3968 				continue;
3969 
3970 			if (!kvm_vcpu_is_visible_gfn(vcpu, pdptrs[i] >> PAGE_SHIFT))
3971 				pdptrs[i] = 0;
3972 		}
3973 	}
3974 
3975 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3976 	if (r)
3977 		return r;
3978 
3979 	write_lock(&vcpu->kvm->mmu_lock);
3980 	r = make_mmu_pages_available(vcpu);
3981 	if (r < 0)
3982 		goto out_unlock;
3983 
3984 	/*
3985 	 * Do we shadow a long mode page table? If so we need to
3986 	 * write-protect the guests page table root.
3987 	 */
3988 	if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3989 		root = mmu_alloc_root(vcpu, root_gfn, 0,
3990 				      mmu->root_role.level);
3991 		mmu->root.hpa = root;
3992 		goto set_root_pgd;
3993 	}
3994 
3995 	if (WARN_ON_ONCE(!mmu->pae_root)) {
3996 		r = -EIO;
3997 		goto out_unlock;
3998 	}
3999 
4000 	/*
4001 	 * We shadow a 32 bit page table. This may be a legacy 2-level
4002 	 * or a PAE 3-level page table. In either case we need to be aware that
4003 	 * the shadow page table may be a PAE or a long mode page table.
4004 	 */
4005 	pm_mask = PT_PRESENT_MASK | shadow_me_value;
4006 	if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
4007 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
4008 
4009 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
4010 			r = -EIO;
4011 			goto out_unlock;
4012 		}
4013 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
4014 
4015 		if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
4016 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
4017 				r = -EIO;
4018 				goto out_unlock;
4019 			}
4020 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
4021 		}
4022 	}
4023 
4024 	for (i = 0; i < 4; ++i) {
4025 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
4026 
4027 		if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
4028 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
4029 				mmu->pae_root[i] = INVALID_PAE_ROOT;
4030 				continue;
4031 			}
4032 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
4033 		}
4034 
4035 		/*
4036 		 * If shadowing 32-bit non-PAE page tables, each PAE page
4037 		 * directory maps one quarter of the guest's non-PAE page
4038 		 * directory. Othwerise each PAE page direct shadows one guest
4039 		 * PAE page directory so that quadrant should be 0.
4040 		 */
4041 		quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
4042 
4043 		root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
4044 		mmu->pae_root[i] = root | pm_mask;
4045 	}
4046 
4047 	if (mmu->root_role.level == PT64_ROOT_5LEVEL)
4048 		mmu->root.hpa = __pa(mmu->pml5_root);
4049 	else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
4050 		mmu->root.hpa = __pa(mmu->pml4_root);
4051 	else
4052 		mmu->root.hpa = __pa(mmu->pae_root);
4053 
4054 set_root_pgd:
4055 	mmu->root.pgd = root_pgd;
4056 out_unlock:
4057 	write_unlock(&vcpu->kvm->mmu_lock);
4058 
4059 	return r;
4060 }
4061 
mmu_alloc_special_roots(struct kvm_vcpu * vcpu)4062 static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
4063 {
4064 	struct kvm_mmu *mmu = vcpu->arch.mmu;
4065 	bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
4066 	u64 *pml5_root = NULL;
4067 	u64 *pml4_root = NULL;
4068 	u64 *pae_root;
4069 
4070 	/*
4071 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
4072 	 * tables are allocated and initialized at root creation as there is no
4073 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
4074 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
4075 	 */
4076 	if (mmu->root_role.direct ||
4077 	    mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
4078 	    mmu->root_role.level < PT64_ROOT_4LEVEL)
4079 		return 0;
4080 
4081 	/*
4082 	 * NPT, the only paging mode that uses this horror, uses a fixed number
4083 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
4084 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
4085 	 * is allocated if the other roots are valid and pml5 is needed, as any
4086 	 * prior MMU would also have required pml5.
4087 	 */
4088 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
4089 		return 0;
4090 
4091 	/*
4092 	 * The special roots should always be allocated in concert.  Yell and
4093 	 * bail if KVM ends up in a state where only one of the roots is valid.
4094 	 */
4095 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
4096 			 (need_pml5 && mmu->pml5_root)))
4097 		return -EIO;
4098 
4099 	/*
4100 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
4101 	 * doesn't need to be decrypted.
4102 	 */
4103 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
4104 	if (!pae_root)
4105 		return -ENOMEM;
4106 
4107 #ifdef CONFIG_X86_64
4108 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
4109 	if (!pml4_root)
4110 		goto err_pml4;
4111 
4112 	if (need_pml5) {
4113 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
4114 		if (!pml5_root)
4115 			goto err_pml5;
4116 	}
4117 #endif
4118 
4119 	mmu->pae_root = pae_root;
4120 	mmu->pml4_root = pml4_root;
4121 	mmu->pml5_root = pml5_root;
4122 
4123 	return 0;
4124 
4125 #ifdef CONFIG_X86_64
4126 err_pml5:
4127 	free_page((unsigned long)pml4_root);
4128 err_pml4:
4129 	free_page((unsigned long)pae_root);
4130 	return -ENOMEM;
4131 #endif
4132 }
4133 
is_unsync_root(hpa_t root)4134 static bool is_unsync_root(hpa_t root)
4135 {
4136 	struct kvm_mmu_page *sp;
4137 
4138 	if (!VALID_PAGE(root) || kvm_mmu_is_dummy_root(root))
4139 		return false;
4140 
4141 	/*
4142 	 * The read barrier orders the CPU's read of SPTE.W during the page table
4143 	 * walk before the reads of sp->unsync/sp->unsync_children here.
4144 	 *
4145 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
4146 	 * any guest page table changes are not guaranteed to be visible anyway
4147 	 * until this VCPU issues a TLB flush strictly after those changes are
4148 	 * made.  We only need to ensure that the other CPU sets these flags
4149 	 * before any actual changes to the page tables are made.  The comments
4150 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
4151 	 * requirement isn't satisfied.
4152 	 */
4153 	smp_rmb();
4154 	sp = root_to_sp(root);
4155 
4156 	/*
4157 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
4158 	 * PDPTEs for a given PAE root need to be synchronized individually.
4159 	 */
4160 	if (WARN_ON_ONCE(!sp))
4161 		return false;
4162 
4163 	if (sp->unsync || sp->unsync_children)
4164 		return true;
4165 
4166 	return false;
4167 }
4168 
kvm_mmu_sync_roots(struct kvm_vcpu * vcpu)4169 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
4170 {
4171 	int i;
4172 	struct kvm_mmu_page *sp;
4173 
4174 	if (vcpu->arch.mmu->root_role.direct)
4175 		return;
4176 
4177 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
4178 		return;
4179 
4180 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4181 
4182 	if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
4183 		hpa_t root = vcpu->arch.mmu->root.hpa;
4184 
4185 		if (!is_unsync_root(root))
4186 			return;
4187 
4188 		sp = root_to_sp(root);
4189 
4190 		write_lock(&vcpu->kvm->mmu_lock);
4191 		mmu_sync_children(vcpu, sp, true);
4192 		write_unlock(&vcpu->kvm->mmu_lock);
4193 		return;
4194 	}
4195 
4196 	write_lock(&vcpu->kvm->mmu_lock);
4197 
4198 	for (i = 0; i < 4; ++i) {
4199 		hpa_t root = vcpu->arch.mmu->pae_root[i];
4200 
4201 		if (IS_VALID_PAE_ROOT(root)) {
4202 			sp = spte_to_child_sp(root);
4203 			mmu_sync_children(vcpu, sp, true);
4204 		}
4205 	}
4206 
4207 	write_unlock(&vcpu->kvm->mmu_lock);
4208 }
4209 
kvm_mmu_sync_prev_roots(struct kvm_vcpu * vcpu)4210 void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
4211 {
4212 	unsigned long roots_to_free = 0;
4213 	int i;
4214 
4215 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4216 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
4217 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
4218 
4219 	/* sync prev_roots by simply freeing them */
4220 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
4221 }
4222 
nonpaging_gva_to_gpa(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu,gpa_t vaddr,u64 access,struct x86_exception * exception)4223 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4224 				  gpa_t vaddr, u64 access,
4225 				  struct x86_exception *exception)
4226 {
4227 	if (exception)
4228 		exception->error_code = 0;
4229 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4230 }
4231 
mmio_info_in_cache(struct kvm_vcpu * vcpu,u64 addr,bool direct)4232 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4233 {
4234 	/*
4235 	 * A nested guest cannot use the MMIO cache if it is using nested
4236 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4237 	 */
4238 	if (mmu_is_nested(vcpu))
4239 		return false;
4240 
4241 	if (direct)
4242 		return vcpu_match_mmio_gpa(vcpu, addr);
4243 
4244 	return vcpu_match_mmio_gva(vcpu, addr);
4245 }
4246 
4247 /*
4248  * Return the level of the lowest level SPTE added to sptes.
4249  * That SPTE may be non-present.
4250  *
4251  * Must be called between walk_shadow_page_lockless_{begin,end}.
4252  */
get_walk(struct kvm_vcpu * vcpu,u64 addr,u64 * sptes,int * root_level)4253 static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4254 {
4255 	struct kvm_shadow_walk_iterator iterator;
4256 	int leaf = -1;
4257 	u64 spte;
4258 
4259 	for (shadow_walk_init(&iterator, vcpu, addr),
4260 	     *root_level = iterator.level;
4261 	     shadow_walk_okay(&iterator);
4262 	     __shadow_walk_next(&iterator, spte)) {
4263 		leaf = iterator.level;
4264 		spte = mmu_spte_get_lockless(iterator.sptep);
4265 
4266 		sptes[leaf] = spte;
4267 	}
4268 
4269 	return leaf;
4270 }
4271 
get_sptes_lockless(struct kvm_vcpu * vcpu,u64 addr,u64 * sptes,int * root_level)4272 static int get_sptes_lockless(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes,
4273 			      int *root_level)
4274 {
4275 	int leaf;
4276 
4277 	walk_shadow_page_lockless_begin(vcpu);
4278 
4279 	if (is_tdp_mmu_active(vcpu))
4280 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, root_level);
4281 	else
4282 		leaf = get_walk(vcpu, addr, sptes, root_level);
4283 
4284 	walk_shadow_page_lockless_end(vcpu);
4285 	return leaf;
4286 }
4287 
4288 /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
get_mmio_spte(struct kvm_vcpu * vcpu,u64 addr,u64 * sptep)4289 static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
4290 {
4291 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
4292 	struct rsvd_bits_validate *rsvd_check;
4293 	int root, leaf, level;
4294 	bool reserved = false;
4295 
4296 	leaf = get_sptes_lockless(vcpu, addr, sptes, &root);
4297 	if (unlikely(leaf < 0)) {
4298 		*sptep = 0ull;
4299 		return reserved;
4300 	}
4301 
4302 	*sptep = sptes[leaf];
4303 
4304 	/*
4305 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
4306 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
4307 	 * design, always have reserved bits set.  The purpose of the checks is
4308 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
4309 	 */
4310 	if (!is_shadow_present_pte(sptes[leaf]))
4311 		leaf++;
4312 
4313 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
4314 
4315 	for (level = root; level >= leaf; level--)
4316 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4317 
4318 	if (reserved) {
4319 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4320 		       __func__, addr);
4321 		for (level = root; level >= leaf; level--)
4322 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4323 			       sptes[level], level,
4324 			       get_rsvd_bits(rsvd_check, sptes[level], level));
4325 	}
4326 
4327 	return reserved;
4328 }
4329 
handle_mmio_page_fault(struct kvm_vcpu * vcpu,u64 addr,bool direct)4330 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4331 {
4332 	u64 spte;
4333 	bool reserved;
4334 
4335 	if (mmio_info_in_cache(vcpu, addr, direct))
4336 		return RET_PF_EMULATE;
4337 
4338 	reserved = get_mmio_spte(vcpu, addr, &spte);
4339 	if (WARN_ON_ONCE(reserved))
4340 		return -EINVAL;
4341 
4342 	if (is_mmio_spte(vcpu->kvm, spte)) {
4343 		gfn_t gfn = get_mmio_spte_gfn(spte);
4344 		unsigned int access = get_mmio_spte_access(spte);
4345 
4346 		if (!check_mmio_spte(vcpu, spte))
4347 			return RET_PF_INVALID;
4348 
4349 		if (direct)
4350 			addr = 0;
4351 
4352 		trace_handle_mmio_page_fault(addr, gfn, access);
4353 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4354 		return RET_PF_EMULATE;
4355 	}
4356 
4357 	/*
4358 	 * If the page table is zapped by other cpus, let CPU fault again on
4359 	 * the address.
4360 	 */
4361 	return RET_PF_RETRY;
4362 }
4363 
page_fault_handle_page_track(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4364 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4365 					 struct kvm_page_fault *fault)
4366 {
4367 	if (unlikely(fault->rsvd))
4368 		return false;
4369 
4370 	if (!fault->present || !fault->write)
4371 		return false;
4372 
4373 	/*
4374 	 * guest is writing the page which is write tracked which can
4375 	 * not be fixed by page fault handler.
4376 	 */
4377 	if (kvm_gfn_is_write_tracked(vcpu->kvm, fault->slot, fault->gfn))
4378 		return true;
4379 
4380 	return false;
4381 }
4382 
shadow_page_table_clear_flood(struct kvm_vcpu * vcpu,gva_t addr)4383 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4384 {
4385 	struct kvm_shadow_walk_iterator iterator;
4386 	u64 spte;
4387 
4388 	walk_shadow_page_lockless_begin(vcpu);
4389 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4390 		clear_sp_write_flooding_count(iterator.sptep);
4391 	walk_shadow_page_lockless_end(vcpu);
4392 }
4393 
alloc_apf_token(struct kvm_vcpu * vcpu)4394 static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
4395 {
4396 	/* make sure the token value is not 0 */
4397 	u32 id = vcpu->arch.apf.id;
4398 
4399 	if (id << 12 == 0)
4400 		vcpu->arch.apf.id = 1;
4401 
4402 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4403 }
4404 
kvm_arch_setup_async_pf(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4405 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu,
4406 				    struct kvm_page_fault *fault)
4407 {
4408 	struct kvm_arch_async_pf arch;
4409 
4410 	arch.token = alloc_apf_token(vcpu);
4411 	arch.gfn = fault->gfn;
4412 	arch.error_code = fault->error_code;
4413 	arch.direct_map = vcpu->arch.mmu->root_role.direct;
4414 	arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
4415 
4416 	return kvm_setup_async_pf(vcpu, fault->addr,
4417 				  kvm_vcpu_gfn_to_hva(vcpu, fault->gfn), &arch);
4418 }
4419 
kvm_arch_async_page_ready(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)4420 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
4421 {
4422 	int r;
4423 
4424 	if (WARN_ON_ONCE(work->arch.error_code & PFERR_PRIVATE_ACCESS))
4425 		return;
4426 
4427 	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
4428 	      work->wakeup_all)
4429 		return;
4430 
4431 	r = kvm_mmu_reload(vcpu);
4432 	if (unlikely(r))
4433 		return;
4434 
4435 	if (!vcpu->arch.mmu->root_role.direct &&
4436 	      work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
4437 		return;
4438 
4439 	r = kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, work->arch.error_code,
4440 				  true, NULL, NULL);
4441 
4442 	/*
4443 	 * Account fixed page faults, otherwise they'll never be counted, but
4444 	 * ignore stats for all other return times.  Page-ready "faults" aren't
4445 	 * truly spurious and never trigger emulation
4446 	 */
4447 	if (r == RET_PF_FIXED)
4448 		vcpu->stat.pf_fixed++;
4449 }
4450 
kvm_max_level_for_order(int order)4451 static inline u8 kvm_max_level_for_order(int order)
4452 {
4453 	BUILD_BUG_ON(KVM_MAX_HUGEPAGE_LEVEL > PG_LEVEL_1G);
4454 
4455 	KVM_MMU_WARN_ON(order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G) &&
4456 			order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M) &&
4457 			order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_4K));
4458 
4459 	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G))
4460 		return PG_LEVEL_1G;
4461 
4462 	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
4463 		return PG_LEVEL_2M;
4464 
4465 	return PG_LEVEL_4K;
4466 }
4467 
kvm_max_private_mapping_level(struct kvm * kvm,kvm_pfn_t pfn,u8 max_level,int gmem_order)4468 static u8 kvm_max_private_mapping_level(struct kvm *kvm, kvm_pfn_t pfn,
4469 					u8 max_level, int gmem_order)
4470 {
4471 	u8 req_max_level;
4472 
4473 	if (max_level == PG_LEVEL_4K)
4474 		return PG_LEVEL_4K;
4475 
4476 	max_level = min(kvm_max_level_for_order(gmem_order), max_level);
4477 	if (max_level == PG_LEVEL_4K)
4478 		return PG_LEVEL_4K;
4479 
4480 	req_max_level = kvm_x86_call(private_max_mapping_level)(kvm, pfn);
4481 	if (req_max_level)
4482 		max_level = min(max_level, req_max_level);
4483 
4484 	return max_level;
4485 }
4486 
kvm_mmu_finish_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault,int r)4487 static void kvm_mmu_finish_page_fault(struct kvm_vcpu *vcpu,
4488 				      struct kvm_page_fault *fault, int r)
4489 {
4490 	kvm_release_faultin_page(vcpu->kvm, fault->refcounted_page,
4491 				 r == RET_PF_RETRY, fault->map_writable);
4492 }
4493 
kvm_mmu_faultin_pfn_private(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4494 static int kvm_mmu_faultin_pfn_private(struct kvm_vcpu *vcpu,
4495 				       struct kvm_page_fault *fault)
4496 {
4497 	int max_order, r;
4498 
4499 	if (!kvm_slot_can_be_private(fault->slot)) {
4500 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4501 		return -EFAULT;
4502 	}
4503 
4504 	r = kvm_gmem_get_pfn(vcpu->kvm, fault->slot, fault->gfn, &fault->pfn,
4505 			     &fault->refcounted_page, &max_order);
4506 	if (r) {
4507 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4508 		return r;
4509 	}
4510 
4511 	fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY);
4512 	fault->max_level = kvm_max_private_mapping_level(vcpu->kvm, fault->pfn,
4513 							 fault->max_level, max_order);
4514 
4515 	return RET_PF_CONTINUE;
4516 }
4517 
__kvm_mmu_faultin_pfn(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4518 static int __kvm_mmu_faultin_pfn(struct kvm_vcpu *vcpu,
4519 				 struct kvm_page_fault *fault)
4520 {
4521 	unsigned int foll = fault->write ? FOLL_WRITE : 0;
4522 
4523 	if (fault->is_private)
4524 		return kvm_mmu_faultin_pfn_private(vcpu, fault);
4525 
4526 	foll |= FOLL_NOWAIT;
4527 	fault->pfn = __kvm_faultin_pfn(fault->slot, fault->gfn, foll,
4528 				       &fault->map_writable, &fault->refcounted_page);
4529 
4530 	/*
4531 	 * If resolving the page failed because I/O is needed to fault-in the
4532 	 * page, then either set up an asynchronous #PF to do the I/O, or if
4533 	 * doing an async #PF isn't possible, retry with I/O allowed.  All
4534 	 * other failures are terminal, i.e. retrying won't help.
4535 	 */
4536 	if (fault->pfn != KVM_PFN_ERR_NEEDS_IO)
4537 		return RET_PF_CONTINUE;
4538 
4539 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
4540 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
4541 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
4542 			trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4543 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4544 			return RET_PF_RETRY;
4545 		} else if (kvm_arch_setup_async_pf(vcpu, fault)) {
4546 			return RET_PF_RETRY;
4547 		}
4548 	}
4549 
4550 	/*
4551 	 * Allow gup to bail on pending non-fatal signals when it's also allowed
4552 	 * to wait for IO.  Note, gup always bails if it is unable to quickly
4553 	 * get a page and a fatal signal, i.e. SIGKILL, is pending.
4554 	 */
4555 	foll |= FOLL_INTERRUPTIBLE;
4556 	foll &= ~FOLL_NOWAIT;
4557 	fault->pfn = __kvm_faultin_pfn(fault->slot, fault->gfn, foll,
4558 				       &fault->map_writable, &fault->refcounted_page);
4559 
4560 	return RET_PF_CONTINUE;
4561 }
4562 
kvm_mmu_faultin_pfn(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault,unsigned int access)4563 static int kvm_mmu_faultin_pfn(struct kvm_vcpu *vcpu,
4564 			       struct kvm_page_fault *fault, unsigned int access)
4565 {
4566 	struct kvm_memory_slot *slot = fault->slot;
4567 	struct kvm *kvm = vcpu->kvm;
4568 	int ret;
4569 
4570 	if (KVM_BUG_ON(kvm_is_gfn_alias(kvm, fault->gfn), kvm))
4571 		return -EFAULT;
4572 
4573 	/*
4574 	 * Note that the mmu_invalidate_seq also serves to detect a concurrent
4575 	 * change in attributes.  is_page_fault_stale() will detect an
4576 	 * invalidation relate to fault->fn and resume the guest without
4577 	 * installing a mapping in the page tables.
4578 	 */
4579 	fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4580 	smp_rmb();
4581 
4582 	/*
4583 	 * Now that we have a snapshot of mmu_invalidate_seq we can check for a
4584 	 * private vs. shared mismatch.
4585 	 */
4586 	if (fault->is_private != kvm_mem_is_private(kvm, fault->gfn)) {
4587 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4588 		return -EFAULT;
4589 	}
4590 
4591 	if (unlikely(!slot))
4592 		return kvm_handle_noslot_fault(vcpu, fault, access);
4593 
4594 	/*
4595 	 * Retry the page fault if the gfn hit a memslot that is being deleted
4596 	 * or moved.  This ensures any existing SPTEs for the old memslot will
4597 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4598 	 */
4599 	if (slot->flags & KVM_MEMSLOT_INVALID)
4600 		return RET_PF_RETRY;
4601 
4602 	if (slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT) {
4603 		/*
4604 		 * Don't map L1's APIC access page into L2, KVM doesn't support
4605 		 * using APICv/AVIC to accelerate L2 accesses to L1's APIC,
4606 		 * i.e. the access needs to be emulated.  Emulating access to
4607 		 * L1's APIC is also correct if L1 is accelerating L2's own
4608 		 * virtual APIC, but for some reason L1 also maps _L1's_ APIC
4609 		 * into L2.  Note, vcpu_is_mmio_gpa() always treats access to
4610 		 * the APIC as MMIO.  Allow an MMIO SPTE to be created, as KVM
4611 		 * uses different roots for L1 vs. L2, i.e. there is no danger
4612 		 * of breaking APICv/AVIC for L1.
4613 		 */
4614 		if (is_guest_mode(vcpu))
4615 			return kvm_handle_noslot_fault(vcpu, fault, access);
4616 
4617 		/*
4618 		 * If the APIC access page exists but is disabled, go directly
4619 		 * to emulation without caching the MMIO access or creating a
4620 		 * MMIO SPTE.  That way the cache doesn't need to be purged
4621 		 * when the AVIC is re-enabled.
4622 		 */
4623 		if (!kvm_apicv_activated(vcpu->kvm))
4624 			return RET_PF_EMULATE;
4625 	}
4626 
4627 	/*
4628 	 * Check for a relevant mmu_notifier invalidation event before getting
4629 	 * the pfn from the primary MMU, and before acquiring mmu_lock.
4630 	 *
4631 	 * For mmu_lock, if there is an in-progress invalidation and the kernel
4632 	 * allows preemption, the invalidation task may drop mmu_lock and yield
4633 	 * in response to mmu_lock being contended, which is *very* counter-
4634 	 * productive as this vCPU can't actually make forward progress until
4635 	 * the invalidation completes.
4636 	 *
4637 	 * Retrying now can also avoid unnessary lock contention in the primary
4638 	 * MMU, as the primary MMU doesn't necessarily hold a single lock for
4639 	 * the duration of the invalidation, i.e. faulting in a conflicting pfn
4640 	 * can cause the invalidation to take longer by holding locks that are
4641 	 * needed to complete the invalidation.
4642 	 *
4643 	 * Do the pre-check even for non-preemtible kernels, i.e. even if KVM
4644 	 * will never yield mmu_lock in response to contention, as this vCPU is
4645 	 * *guaranteed* to need to retry, i.e. waiting until mmu_lock is held
4646 	 * to detect retry guarantees the worst case latency for the vCPU.
4647 	 */
4648 	if (mmu_invalidate_retry_gfn_unsafe(kvm, fault->mmu_seq, fault->gfn))
4649 		return RET_PF_RETRY;
4650 
4651 	ret = __kvm_mmu_faultin_pfn(vcpu, fault);
4652 	if (ret != RET_PF_CONTINUE)
4653 		return ret;
4654 
4655 	if (unlikely(is_error_pfn(fault->pfn)))
4656 		return kvm_handle_error_pfn(vcpu, fault);
4657 
4658 	if (WARN_ON_ONCE(!fault->slot || is_noslot_pfn(fault->pfn)))
4659 		return kvm_handle_noslot_fault(vcpu, fault, access);
4660 
4661 	/*
4662 	 * Check again for a relevant mmu_notifier invalidation event purely to
4663 	 * avoid contending mmu_lock.  Most invalidations will be detected by
4664 	 * the previous check, but checking is extremely cheap relative to the
4665 	 * overall cost of failing to detect the invalidation until after
4666 	 * mmu_lock is acquired.
4667 	 */
4668 	if (mmu_invalidate_retry_gfn_unsafe(kvm, fault->mmu_seq, fault->gfn)) {
4669 		kvm_mmu_finish_page_fault(vcpu, fault, RET_PF_RETRY);
4670 		return RET_PF_RETRY;
4671 	}
4672 
4673 	return RET_PF_CONTINUE;
4674 }
4675 
4676 /*
4677  * Returns true if the page fault is stale and needs to be retried, i.e. if the
4678  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4679  */
is_page_fault_stale(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4680 static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4681 				struct kvm_page_fault *fault)
4682 {
4683 	struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
4684 
4685 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
4686 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
4687 		return true;
4688 
4689 	/*
4690 	 * Roots without an associated shadow page are considered invalid if
4691 	 * there is a pending request to free obsolete roots.  The request is
4692 	 * only a hint that the current root _may_ be obsolete and needs to be
4693 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
4694 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
4695 	 * to reload even if no vCPU is actively using the root.
4696 	 */
4697 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4698 		return true;
4699 
4700 	/*
4701 	 * Check for a relevant mmu_notifier invalidation event one last time
4702 	 * now that mmu_lock is held, as the "unsafe" checks performed without
4703 	 * holding mmu_lock can get false negatives.
4704 	 */
4705 	return fault->slot &&
4706 	       mmu_invalidate_retry_gfn(vcpu->kvm, fault->mmu_seq, fault->gfn);
4707 }
4708 
direct_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4709 static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4710 {
4711 	int r;
4712 
4713 	/* Dummy roots are used only for shadowing bad guest roots. */
4714 	if (WARN_ON_ONCE(kvm_mmu_is_dummy_root(vcpu->arch.mmu->root.hpa)))
4715 		return RET_PF_RETRY;
4716 
4717 	if (page_fault_handle_page_track(vcpu, fault))
4718 		return RET_PF_WRITE_PROTECTED;
4719 
4720 	r = fast_page_fault(vcpu, fault);
4721 	if (r != RET_PF_INVALID)
4722 		return r;
4723 
4724 	r = mmu_topup_memory_caches(vcpu, false);
4725 	if (r)
4726 		return r;
4727 
4728 	r = kvm_mmu_faultin_pfn(vcpu, fault, ACC_ALL);
4729 	if (r != RET_PF_CONTINUE)
4730 		return r;
4731 
4732 	r = RET_PF_RETRY;
4733 	write_lock(&vcpu->kvm->mmu_lock);
4734 
4735 	if (is_page_fault_stale(vcpu, fault))
4736 		goto out_unlock;
4737 
4738 	r = make_mmu_pages_available(vcpu);
4739 	if (r)
4740 		goto out_unlock;
4741 
4742 	r = direct_map(vcpu, fault);
4743 
4744 out_unlock:
4745 	kvm_mmu_finish_page_fault(vcpu, fault, r);
4746 	write_unlock(&vcpu->kvm->mmu_lock);
4747 	return r;
4748 }
4749 
nonpaging_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4750 static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4751 				struct kvm_page_fault *fault)
4752 {
4753 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4754 	fault->max_level = PG_LEVEL_2M;
4755 	return direct_page_fault(vcpu, fault);
4756 }
4757 
kvm_handle_page_fault(struct kvm_vcpu * vcpu,u64 error_code,u64 fault_address,char * insn,int insn_len)4758 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4759 				u64 fault_address, char *insn, int insn_len)
4760 {
4761 	int r = 1;
4762 	u32 flags = vcpu->arch.apf.host_apf_flags;
4763 
4764 #ifndef CONFIG_X86_64
4765 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4766 	if (WARN_ON_ONCE(fault_address >> 32))
4767 		return -EFAULT;
4768 #endif
4769 	/*
4770 	 * Legacy #PF exception only have a 32-bit error code.  Simply drop the
4771 	 * upper bits as KVM doesn't use them for #PF (because they are never
4772 	 * set), and to ensure there are no collisions with KVM-defined bits.
4773 	 */
4774 	if (WARN_ON_ONCE(error_code >> 32))
4775 		error_code = lower_32_bits(error_code);
4776 
4777 	/*
4778 	 * Restrict KVM-defined flags to bits 63:32 so that it's impossible for
4779 	 * them to conflict with #PF error codes, which are limited to 32 bits.
4780 	 */
4781 	BUILD_BUG_ON(lower_32_bits(PFERR_SYNTHETIC_MASK));
4782 
4783 	vcpu->arch.l1tf_flush_l1d = true;
4784 	if (!flags) {
4785 		trace_kvm_page_fault(vcpu, fault_address, error_code);
4786 
4787 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4788 				insn_len);
4789 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
4790 		vcpu->arch.apf.host_apf_flags = 0;
4791 		local_irq_disable();
4792 		kvm_async_pf_task_wait_schedule(fault_address);
4793 		local_irq_enable();
4794 	} else {
4795 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4796 	}
4797 
4798 	return r;
4799 }
4800 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4801 
4802 #ifdef CONFIG_X86_64
kvm_tdp_mmu_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4803 static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
4804 				  struct kvm_page_fault *fault)
4805 {
4806 	int r;
4807 
4808 	if (page_fault_handle_page_track(vcpu, fault))
4809 		return RET_PF_WRITE_PROTECTED;
4810 
4811 	r = fast_page_fault(vcpu, fault);
4812 	if (r != RET_PF_INVALID)
4813 		return r;
4814 
4815 	r = mmu_topup_memory_caches(vcpu, false);
4816 	if (r)
4817 		return r;
4818 
4819 	r = kvm_mmu_faultin_pfn(vcpu, fault, ACC_ALL);
4820 	if (r != RET_PF_CONTINUE)
4821 		return r;
4822 
4823 	r = RET_PF_RETRY;
4824 	read_lock(&vcpu->kvm->mmu_lock);
4825 
4826 	if (is_page_fault_stale(vcpu, fault))
4827 		goto out_unlock;
4828 
4829 	r = kvm_tdp_mmu_map(vcpu, fault);
4830 
4831 out_unlock:
4832 	kvm_mmu_finish_page_fault(vcpu, fault, r);
4833 	read_unlock(&vcpu->kvm->mmu_lock);
4834 	return r;
4835 }
4836 #endif
4837 
kvm_mmu_may_ignore_guest_pat(void)4838 bool kvm_mmu_may_ignore_guest_pat(void)
4839 {
4840 	/*
4841 	 * When EPT is enabled (shadow_memtype_mask is non-zero), and the VM
4842 	 * has non-coherent DMA (DMA doesn't snoop CPU caches), KVM's ABI is to
4843 	 * honor the memtype from the guest's PAT so that guest accesses to
4844 	 * memory that is DMA'd aren't cached against the guest's wishes.  As a
4845 	 * result, KVM _may_ ignore guest PAT, whereas without non-coherent DMA,
4846 	 * KVM _always_ ignores guest PAT (when EPT is enabled).
4847 	 */
4848 	return shadow_memtype_mask;
4849 }
4850 
kvm_tdp_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4851 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4852 {
4853 #ifdef CONFIG_X86_64
4854 	if (tdp_mmu_enabled)
4855 		return kvm_tdp_mmu_page_fault(vcpu, fault);
4856 #endif
4857 
4858 	return direct_page_fault(vcpu, fault);
4859 }
4860 
kvm_tdp_map_page(struct kvm_vcpu * vcpu,gpa_t gpa,u64 error_code,u8 * level)4861 static int kvm_tdp_map_page(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code,
4862 			    u8 *level)
4863 {
4864 	int r;
4865 
4866 	/*
4867 	 * Restrict to TDP page fault, since that's the only case where the MMU
4868 	 * is indexed by GPA.
4869 	 */
4870 	if (vcpu->arch.mmu->page_fault != kvm_tdp_page_fault)
4871 		return -EOPNOTSUPP;
4872 
4873 	do {
4874 		if (signal_pending(current))
4875 			return -EINTR;
4876 		cond_resched();
4877 		r = kvm_mmu_do_page_fault(vcpu, gpa, error_code, true, NULL, level);
4878 	} while (r == RET_PF_RETRY);
4879 
4880 	if (r < 0)
4881 		return r;
4882 
4883 	switch (r) {
4884 	case RET_PF_FIXED:
4885 	case RET_PF_SPURIOUS:
4886 	case RET_PF_WRITE_PROTECTED:
4887 		return 0;
4888 
4889 	case RET_PF_EMULATE:
4890 		return -ENOENT;
4891 
4892 	case RET_PF_RETRY:
4893 	case RET_PF_CONTINUE:
4894 	case RET_PF_INVALID:
4895 	default:
4896 		WARN_ONCE(1, "could not fix page fault during prefault");
4897 		return -EIO;
4898 	}
4899 }
4900 
kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu * vcpu,struct kvm_pre_fault_memory * range)4901 long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
4902 				    struct kvm_pre_fault_memory *range)
4903 {
4904 	u64 error_code = PFERR_GUEST_FINAL_MASK;
4905 	u8 level = PG_LEVEL_4K;
4906 	u64 end;
4907 	int r;
4908 
4909 	if (!vcpu->kvm->arch.pre_fault_allowed)
4910 		return -EOPNOTSUPP;
4911 
4912 	/*
4913 	 * reload is efficient when called repeatedly, so we can do it on
4914 	 * every iteration.
4915 	 */
4916 	r = kvm_mmu_reload(vcpu);
4917 	if (r)
4918 		return r;
4919 
4920 	if (kvm_arch_has_private_mem(vcpu->kvm) &&
4921 	    kvm_mem_is_private(vcpu->kvm, gpa_to_gfn(range->gpa)))
4922 		error_code |= PFERR_PRIVATE_ACCESS;
4923 
4924 	/*
4925 	 * Shadow paging uses GVA for kvm page fault, so restrict to
4926 	 * two-dimensional paging.
4927 	 */
4928 	r = kvm_tdp_map_page(vcpu, range->gpa, error_code, &level);
4929 	if (r < 0)
4930 		return r;
4931 
4932 	/*
4933 	 * If the mapping that covers range->gpa can use a huge page, it
4934 	 * may start below it or end after range->gpa + range->size.
4935 	 */
4936 	end = (range->gpa & KVM_HPAGE_MASK(level)) + KVM_HPAGE_SIZE(level);
4937 	return min(range->size, end - range->gpa);
4938 }
4939 
nonpaging_init_context(struct kvm_mmu * context)4940 static void nonpaging_init_context(struct kvm_mmu *context)
4941 {
4942 	context->page_fault = nonpaging_page_fault;
4943 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4944 	context->sync_spte = NULL;
4945 }
4946 
is_root_usable(struct kvm_mmu_root_info * root,gpa_t pgd,union kvm_mmu_page_role role)4947 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
4948 				  union kvm_mmu_page_role role)
4949 {
4950 	struct kvm_mmu_page *sp;
4951 
4952 	if (!VALID_PAGE(root->hpa))
4953 		return false;
4954 
4955 	if (!role.direct && pgd != root->pgd)
4956 		return false;
4957 
4958 	sp = root_to_sp(root->hpa);
4959 	if (WARN_ON_ONCE(!sp))
4960 		return false;
4961 
4962 	return role.word == sp->role.word;
4963 }
4964 
4965 /*
4966  * Find out if a previously cached root matching the new pgd/role is available,
4967  * and insert the current root as the MRU in the cache.
4968  * If a matching root is found, it is assigned to kvm_mmu->root and
4969  * true is returned.
4970  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
4971  * evicted to make room for the current root, and false is returned.
4972  */
cached_root_find_and_keep_current(struct kvm * kvm,struct kvm_mmu * mmu,gpa_t new_pgd,union kvm_mmu_page_role new_role)4973 static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
4974 					      gpa_t new_pgd,
4975 					      union kvm_mmu_page_role new_role)
4976 {
4977 	uint i;
4978 
4979 	if (is_root_usable(&mmu->root, new_pgd, new_role))
4980 		return true;
4981 
4982 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4983 		/*
4984 		 * The swaps end up rotating the cache like this:
4985 		 *   C   0 1 2 3   (on entry to the function)
4986 		 *   0   C 1 2 3
4987 		 *   1   C 0 2 3
4988 		 *   2   C 0 1 3
4989 		 *   3   C 0 1 2   (on exit from the loop)
4990 		 */
4991 		swap(mmu->root, mmu->prev_roots[i]);
4992 		if (is_root_usable(&mmu->root, new_pgd, new_role))
4993 			return true;
4994 	}
4995 
4996 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4997 	return false;
4998 }
4999 
5000 /*
5001  * Find out if a previously cached root matching the new pgd/role is available.
5002  * On entry, mmu->root is invalid.
5003  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
5004  * of the cache becomes invalid, and true is returned.
5005  * If no match is found, kvm_mmu->root is left invalid and false is returned.
5006  */
cached_root_find_without_current(struct kvm * kvm,struct kvm_mmu * mmu,gpa_t new_pgd,union kvm_mmu_page_role new_role)5007 static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
5008 					     gpa_t new_pgd,
5009 					     union kvm_mmu_page_role new_role)
5010 {
5011 	uint i;
5012 
5013 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5014 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
5015 			goto hit;
5016 
5017 	return false;
5018 
5019 hit:
5020 	swap(mmu->root, mmu->prev_roots[i]);
5021 	/* Bubble up the remaining roots.  */
5022 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
5023 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
5024 	mmu->prev_roots[i].hpa = INVALID_PAGE;
5025 	return true;
5026 }
5027 
fast_pgd_switch(struct kvm * kvm,struct kvm_mmu * mmu,gpa_t new_pgd,union kvm_mmu_page_role new_role)5028 static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
5029 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
5030 {
5031 	/*
5032 	 * Limit reuse to 64-bit hosts+VMs without "special" roots in order to
5033 	 * avoid having to deal with PDPTEs and other complexities.
5034 	 */
5035 	if (VALID_PAGE(mmu->root.hpa) && !root_to_sp(mmu->root.hpa))
5036 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
5037 
5038 	if (VALID_PAGE(mmu->root.hpa))
5039 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
5040 	else
5041 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
5042 }
5043 
kvm_mmu_new_pgd(struct kvm_vcpu * vcpu,gpa_t new_pgd)5044 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
5045 {
5046 	struct kvm_mmu *mmu = vcpu->arch.mmu;
5047 	union kvm_mmu_page_role new_role = mmu->root_role;
5048 
5049 	/*
5050 	 * Return immediately if no usable root was found, kvm_mmu_reload()
5051 	 * will establish a valid root prior to the next VM-Enter.
5052 	 */
5053 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
5054 		return;
5055 
5056 	/*
5057 	 * It's possible that the cached previous root page is obsolete because
5058 	 * of a change in the MMU generation number. However, changing the
5059 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
5060 	 * which will free the root set here and allocate a new one.
5061 	 */
5062 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
5063 
5064 	if (force_flush_and_sync_on_reuse) {
5065 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
5066 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
5067 	}
5068 
5069 	/*
5070 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
5071 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
5072 	 * valid. So clear any cached MMIO info even when we don't need to sync
5073 	 * the shadow page tables.
5074 	 */
5075 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5076 
5077 	/*
5078 	 * If this is a direct root page, it doesn't have a write flooding
5079 	 * count. Otherwise, clear the write flooding count.
5080 	 */
5081 	if (!new_role.direct) {
5082 		struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
5083 
5084 		if (!WARN_ON_ONCE(!sp))
5085 			__clear_sp_write_flooding_count(sp);
5086 	}
5087 }
5088 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
5089 
sync_mmio_spte(struct kvm_vcpu * vcpu,u64 * sptep,gfn_t gfn,unsigned int access)5090 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
5091 			   unsigned int access)
5092 {
5093 	if (unlikely(is_mmio_spte(vcpu->kvm, *sptep))) {
5094 		if (gfn != get_mmio_spte_gfn(*sptep)) {
5095 			mmu_spte_clear_no_track(sptep);
5096 			return true;
5097 		}
5098 
5099 		mark_mmio_spte(vcpu, sptep, gfn, access);
5100 		return true;
5101 	}
5102 
5103 	return false;
5104 }
5105 
5106 #define PTTYPE_EPT 18 /* arbitrary */
5107 #define PTTYPE PTTYPE_EPT
5108 #include "paging_tmpl.h"
5109 #undef PTTYPE
5110 
5111 #define PTTYPE 64
5112 #include "paging_tmpl.h"
5113 #undef PTTYPE
5114 
5115 #define PTTYPE 32
5116 #include "paging_tmpl.h"
5117 #undef PTTYPE
5118 
__reset_rsvds_bits_mask(struct rsvd_bits_validate * rsvd_check,u64 pa_bits_rsvd,int level,bool nx,bool gbpages,bool pse,bool amd)5119 static void __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
5120 				    u64 pa_bits_rsvd, int level, bool nx,
5121 				    bool gbpages, bool pse, bool amd)
5122 {
5123 	u64 gbpages_bit_rsvd = 0;
5124 	u64 nonleaf_bit8_rsvd = 0;
5125 	u64 high_bits_rsvd;
5126 
5127 	rsvd_check->bad_mt_xwr = 0;
5128 
5129 	if (!gbpages)
5130 		gbpages_bit_rsvd = rsvd_bits(7, 7);
5131 
5132 	if (level == PT32E_ROOT_LEVEL)
5133 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
5134 	else
5135 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
5136 
5137 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
5138 	if (!nx)
5139 		high_bits_rsvd |= rsvd_bits(63, 63);
5140 
5141 	/*
5142 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
5143 	 * leaf entries) on AMD CPUs only.
5144 	 */
5145 	if (amd)
5146 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
5147 
5148 	switch (level) {
5149 	case PT32_ROOT_LEVEL:
5150 		/* no rsvd bits for 2 level 4K page table entries */
5151 		rsvd_check->rsvd_bits_mask[0][1] = 0;
5152 		rsvd_check->rsvd_bits_mask[0][0] = 0;
5153 		rsvd_check->rsvd_bits_mask[1][0] =
5154 			rsvd_check->rsvd_bits_mask[0][0];
5155 
5156 		if (!pse) {
5157 			rsvd_check->rsvd_bits_mask[1][1] = 0;
5158 			break;
5159 		}
5160 
5161 		if (is_cpuid_PSE36())
5162 			/* 36bits PSE 4MB page */
5163 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
5164 		else
5165 			/* 32 bits PSE 4MB page */
5166 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
5167 		break;
5168 	case PT32E_ROOT_LEVEL:
5169 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
5170 						   high_bits_rsvd |
5171 						   rsvd_bits(5, 8) |
5172 						   rsvd_bits(1, 2);	/* PDPTE */
5173 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
5174 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
5175 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
5176 						   rsvd_bits(13, 20);	/* large page */
5177 		rsvd_check->rsvd_bits_mask[1][0] =
5178 			rsvd_check->rsvd_bits_mask[0][0];
5179 		break;
5180 	case PT64_ROOT_5LEVEL:
5181 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
5182 						   nonleaf_bit8_rsvd |
5183 						   rsvd_bits(7, 7);
5184 		rsvd_check->rsvd_bits_mask[1][4] =
5185 			rsvd_check->rsvd_bits_mask[0][4];
5186 		fallthrough;
5187 	case PT64_ROOT_4LEVEL:
5188 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
5189 						   nonleaf_bit8_rsvd |
5190 						   rsvd_bits(7, 7);
5191 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
5192 						   gbpages_bit_rsvd;
5193 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
5194 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
5195 		rsvd_check->rsvd_bits_mask[1][3] =
5196 			rsvd_check->rsvd_bits_mask[0][3];
5197 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
5198 						   gbpages_bit_rsvd |
5199 						   rsvd_bits(13, 29);
5200 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
5201 						   rsvd_bits(13, 20); /* large page */
5202 		rsvd_check->rsvd_bits_mask[1][0] =
5203 			rsvd_check->rsvd_bits_mask[0][0];
5204 		break;
5205 	}
5206 }
5207 
reset_guest_rsvds_bits_mask(struct kvm_vcpu * vcpu,struct kvm_mmu * context)5208 static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
5209 					struct kvm_mmu *context)
5210 {
5211 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
5212 				vcpu->arch.reserved_gpa_bits,
5213 				context->cpu_role.base.level, is_efer_nx(context),
5214 				guest_cpu_cap_has(vcpu, X86_FEATURE_GBPAGES),
5215 				is_cr4_pse(context),
5216 				guest_cpuid_is_amd_compatible(vcpu));
5217 }
5218 
__reset_rsvds_bits_mask_ept(struct rsvd_bits_validate * rsvd_check,u64 pa_bits_rsvd,bool execonly,int huge_page_level)5219 static void __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
5220 					u64 pa_bits_rsvd, bool execonly,
5221 					int huge_page_level)
5222 {
5223 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
5224 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
5225 	u64 bad_mt_xwr;
5226 
5227 	if (huge_page_level < PG_LEVEL_1G)
5228 		large_1g_rsvd = rsvd_bits(7, 7);
5229 	if (huge_page_level < PG_LEVEL_2M)
5230 		large_2m_rsvd = rsvd_bits(7, 7);
5231 
5232 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
5233 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
5234 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
5235 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
5236 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
5237 
5238 	/* large page */
5239 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
5240 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
5241 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
5242 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
5243 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
5244 
5245 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
5246 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
5247 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
5248 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
5249 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
5250 	if (!execonly) {
5251 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
5252 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
5253 	}
5254 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
5255 }
5256 
reset_rsvds_bits_mask_ept(struct kvm_vcpu * vcpu,struct kvm_mmu * context,bool execonly,int huge_page_level)5257 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
5258 		struct kvm_mmu *context, bool execonly, int huge_page_level)
5259 {
5260 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
5261 				    vcpu->arch.reserved_gpa_bits, execonly,
5262 				    huge_page_level);
5263 }
5264 
reserved_hpa_bits(void)5265 static inline u64 reserved_hpa_bits(void)
5266 {
5267 	return rsvd_bits(kvm_host.maxphyaddr, 63);
5268 }
5269 
5270 /*
5271  * the page table on host is the shadow page table for the page
5272  * table in guest or amd nested guest, its mmu features completely
5273  * follow the features in guest.
5274  */
reset_shadow_zero_bits_mask(struct kvm_vcpu * vcpu,struct kvm_mmu * context)5275 static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
5276 					struct kvm_mmu *context)
5277 {
5278 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
5279 	bool is_amd = true;
5280 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
5281 	bool is_pse = false;
5282 	struct rsvd_bits_validate *shadow_zero_check;
5283 	int i;
5284 
5285 	WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
5286 
5287 	shadow_zero_check = &context->shadow_zero_check;
5288 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
5289 				context->root_role.level,
5290 				context->root_role.efer_nx,
5291 				guest_cpu_cap_has(vcpu, X86_FEATURE_GBPAGES),
5292 				is_pse, is_amd);
5293 
5294 	if (!shadow_me_mask)
5295 		return;
5296 
5297 	for (i = context->root_role.level; --i >= 0;) {
5298 		/*
5299 		 * So far shadow_me_value is a constant during KVM's life
5300 		 * time.  Bits in shadow_me_value are allowed to be set.
5301 		 * Bits in shadow_me_mask but not in shadow_me_value are
5302 		 * not allowed to be set.
5303 		 */
5304 		shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
5305 		shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
5306 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
5307 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
5308 	}
5309 
5310 }
5311 
boot_cpu_is_amd(void)5312 static inline bool boot_cpu_is_amd(void)
5313 {
5314 	WARN_ON_ONCE(!tdp_enabled);
5315 	return shadow_x_mask == 0;
5316 }
5317 
5318 /*
5319  * the direct page table on host, use as much mmu features as
5320  * possible, however, kvm currently does not do execution-protection.
5321  */
reset_tdp_shadow_zero_bits_mask(struct kvm_mmu * context)5322 static void reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
5323 {
5324 	struct rsvd_bits_validate *shadow_zero_check;
5325 	int i;
5326 
5327 	shadow_zero_check = &context->shadow_zero_check;
5328 
5329 	if (boot_cpu_is_amd())
5330 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
5331 					context->root_role.level, true,
5332 					boot_cpu_has(X86_FEATURE_GBPAGES),
5333 					false, true);
5334 	else
5335 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
5336 					    reserved_hpa_bits(), false,
5337 					    max_huge_page_level);
5338 
5339 	if (!shadow_me_mask)
5340 		return;
5341 
5342 	for (i = context->root_role.level; --i >= 0;) {
5343 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
5344 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
5345 	}
5346 }
5347 
5348 /*
5349  * as the comments in reset_shadow_zero_bits_mask() except it
5350  * is the shadow page table for intel nested guest.
5351  */
5352 static void
reset_ept_shadow_zero_bits_mask(struct kvm_mmu * context,bool execonly)5353 reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
5354 {
5355 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
5356 				    reserved_hpa_bits(), execonly,
5357 				    max_huge_page_level);
5358 }
5359 
5360 #define BYTE_MASK(access) \
5361 	((1 & (access) ? 2 : 0) | \
5362 	 (2 & (access) ? 4 : 0) | \
5363 	 (3 & (access) ? 8 : 0) | \
5364 	 (4 & (access) ? 16 : 0) | \
5365 	 (5 & (access) ? 32 : 0) | \
5366 	 (6 & (access) ? 64 : 0) | \
5367 	 (7 & (access) ? 128 : 0))
5368 
5369 
update_permission_bitmask(struct kvm_mmu * mmu,bool ept)5370 static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
5371 {
5372 	unsigned byte;
5373 
5374 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
5375 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
5376 	const u8 u = BYTE_MASK(ACC_USER_MASK);
5377 
5378 	bool cr4_smep = is_cr4_smep(mmu);
5379 	bool cr4_smap = is_cr4_smap(mmu);
5380 	bool cr0_wp = is_cr0_wp(mmu);
5381 	bool efer_nx = is_efer_nx(mmu);
5382 
5383 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
5384 		unsigned pfec = byte << 1;
5385 
5386 		/*
5387 		 * Each "*f" variable has a 1 bit for each UWX value
5388 		 * that causes a fault with the given PFEC.
5389 		 */
5390 
5391 		/* Faults from writes to non-writable pages */
5392 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
5393 		/* Faults from user mode accesses to supervisor pages */
5394 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
5395 		/* Faults from fetches of non-executable pages*/
5396 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
5397 		/* Faults from kernel mode fetches of user pages */
5398 		u8 smepf = 0;
5399 		/* Faults from kernel mode accesses of user pages */
5400 		u8 smapf = 0;
5401 
5402 		if (!ept) {
5403 			/* Faults from kernel mode accesses to user pages */
5404 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
5405 
5406 			/* Not really needed: !nx will cause pte.nx to fault */
5407 			if (!efer_nx)
5408 				ff = 0;
5409 
5410 			/* Allow supervisor writes if !cr0.wp */
5411 			if (!cr0_wp)
5412 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
5413 
5414 			/* Disallow supervisor fetches of user code if cr4.smep */
5415 			if (cr4_smep)
5416 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
5417 
5418 			/*
5419 			 * SMAP:kernel-mode data accesses from user-mode
5420 			 * mappings should fault. A fault is considered
5421 			 * as a SMAP violation if all of the following
5422 			 * conditions are true:
5423 			 *   - X86_CR4_SMAP is set in CR4
5424 			 *   - A user page is accessed
5425 			 *   - The access is not a fetch
5426 			 *   - The access is supervisor mode
5427 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
5428 			 *
5429 			 * Here, we cover the first four conditions.
5430 			 * The fifth is computed dynamically in permission_fault();
5431 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5432 			 * *not* subject to SMAP restrictions.
5433 			 */
5434 			if (cr4_smap)
5435 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5436 		}
5437 
5438 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5439 	}
5440 }
5441 
5442 /*
5443 * PKU is an additional mechanism by which the paging controls access to
5444 * user-mode addresses based on the value in the PKRU register.  Protection
5445 * key violations are reported through a bit in the page fault error code.
5446 * Unlike other bits of the error code, the PK bit is not known at the
5447 * call site of e.g. gva_to_gpa; it must be computed directly in
5448 * permission_fault based on two bits of PKRU, on some machine state (CR4,
5449 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5450 *
5451 * In particular the following conditions come from the error code, the
5452 * page tables and the machine state:
5453 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5454 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5455 * - PK is always zero if U=0 in the page tables
5456 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5457 *
5458 * The PKRU bitmask caches the result of these four conditions.  The error
5459 * code (minus the P bit) and the page table's U bit form an index into the
5460 * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
5461 * with the two bits of the PKRU register corresponding to the protection key.
5462 * For the first three conditions above the bits will be 00, thus masking
5463 * away both AD and WD.  For all reads or if the last condition holds, WD
5464 * only will be masked away.
5465 */
update_pkru_bitmask(struct kvm_mmu * mmu)5466 static void update_pkru_bitmask(struct kvm_mmu *mmu)
5467 {
5468 	unsigned bit;
5469 	bool wp;
5470 
5471 	mmu->pkru_mask = 0;
5472 
5473 	if (!is_cr4_pke(mmu))
5474 		return;
5475 
5476 	wp = is_cr0_wp(mmu);
5477 
5478 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5479 		unsigned pfec, pkey_bits;
5480 		bool check_pkey, check_write, ff, uf, wf, pte_user;
5481 
5482 		pfec = bit << 1;
5483 		ff = pfec & PFERR_FETCH_MASK;
5484 		uf = pfec & PFERR_USER_MASK;
5485 		wf = pfec & PFERR_WRITE_MASK;
5486 
5487 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
5488 		pte_user = pfec & PFERR_RSVD_MASK;
5489 
5490 		/*
5491 		 * Only need to check the access which is not an
5492 		 * instruction fetch and is to a user page.
5493 		 */
5494 		check_pkey = (!ff && pte_user);
5495 		/*
5496 		 * write access is controlled by PKRU if it is a
5497 		 * user access or CR0.WP = 1.
5498 		 */
5499 		check_write = check_pkey && wf && (uf || wp);
5500 
5501 		/* PKRU.AD stops both read and write access. */
5502 		pkey_bits = !!check_pkey;
5503 		/* PKRU.WD stops write access. */
5504 		pkey_bits |= (!!check_write) << 1;
5505 
5506 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5507 	}
5508 }
5509 
reset_guest_paging_metadata(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu)5510 static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5511 					struct kvm_mmu *mmu)
5512 {
5513 	if (!is_cr0_pg(mmu))
5514 		return;
5515 
5516 	reset_guest_rsvds_bits_mask(vcpu, mmu);
5517 	update_permission_bitmask(mmu, false);
5518 	update_pkru_bitmask(mmu);
5519 }
5520 
paging64_init_context(struct kvm_mmu * context)5521 static void paging64_init_context(struct kvm_mmu *context)
5522 {
5523 	context->page_fault = paging64_page_fault;
5524 	context->gva_to_gpa = paging64_gva_to_gpa;
5525 	context->sync_spte = paging64_sync_spte;
5526 }
5527 
paging32_init_context(struct kvm_mmu * context)5528 static void paging32_init_context(struct kvm_mmu *context)
5529 {
5530 	context->page_fault = paging32_page_fault;
5531 	context->gva_to_gpa = paging32_gva_to_gpa;
5532 	context->sync_spte = paging32_sync_spte;
5533 }
5534 
kvm_calc_cpu_role(struct kvm_vcpu * vcpu,const struct kvm_mmu_role_regs * regs)5535 static union kvm_cpu_role kvm_calc_cpu_role(struct kvm_vcpu *vcpu,
5536 					    const struct kvm_mmu_role_regs *regs)
5537 {
5538 	union kvm_cpu_role role = {0};
5539 
5540 	role.base.access = ACC_ALL;
5541 	role.base.smm = is_smm(vcpu);
5542 	role.base.guest_mode = is_guest_mode(vcpu);
5543 	role.ext.valid = 1;
5544 
5545 	if (!____is_cr0_pg(regs)) {
5546 		role.base.direct = 1;
5547 		return role;
5548 	}
5549 
5550 	role.base.efer_nx = ____is_efer_nx(regs);
5551 	role.base.cr0_wp = ____is_cr0_wp(regs);
5552 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5553 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5554 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
5555 
5556 	if (____is_efer_lma(regs))
5557 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
5558 							: PT64_ROOT_4LEVEL;
5559 	else if (____is_cr4_pae(regs))
5560 		role.base.level = PT32E_ROOT_LEVEL;
5561 	else
5562 		role.base.level = PT32_ROOT_LEVEL;
5563 
5564 	role.ext.cr4_smep = ____is_cr4_smep(regs);
5565 	role.ext.cr4_smap = ____is_cr4_smap(regs);
5566 	role.ext.cr4_pse = ____is_cr4_pse(regs);
5567 
5568 	/* PKEY and LA57 are active iff long mode is active. */
5569 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5570 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5571 	role.ext.efer_lma = ____is_efer_lma(regs);
5572 	return role;
5573 }
5574 
__kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu)5575 void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
5576 					struct kvm_mmu *mmu)
5577 {
5578 	const bool cr0_wp = kvm_is_cr0_bit_set(vcpu, X86_CR0_WP);
5579 
5580 	BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
5581 	BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
5582 
5583 	if (is_cr0_wp(mmu) == cr0_wp)
5584 		return;
5585 
5586 	mmu->cpu_role.base.cr0_wp = cr0_wp;
5587 	reset_guest_paging_metadata(vcpu, mmu);
5588 }
5589 
kvm_mmu_get_tdp_level(struct kvm_vcpu * vcpu)5590 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5591 {
5592 	/* tdp_root_level is architecture forced level, use it if nonzero */
5593 	if (tdp_root_level)
5594 		return tdp_root_level;
5595 
5596 	/* Use 5-level TDP if and only if it's useful/necessary. */
5597 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5598 		return 4;
5599 
5600 	return max_tdp_level;
5601 }
5602 
kvm_mmu_get_max_tdp_level(void)5603 u8 kvm_mmu_get_max_tdp_level(void)
5604 {
5605 	return tdp_root_level ? tdp_root_level : max_tdp_level;
5606 }
5607 
5608 static union kvm_mmu_page_role
kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu * vcpu,union kvm_cpu_role cpu_role)5609 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
5610 				union kvm_cpu_role cpu_role)
5611 {
5612 	union kvm_mmu_page_role role = {0};
5613 
5614 	role.access = ACC_ALL;
5615 	role.cr0_wp = true;
5616 	role.efer_nx = true;
5617 	role.smm = cpu_role.base.smm;
5618 	role.guest_mode = cpu_role.base.guest_mode;
5619 	role.ad_disabled = !kvm_ad_enabled;
5620 	role.level = kvm_mmu_get_tdp_level(vcpu);
5621 	role.direct = true;
5622 	role.has_4_byte_gpte = false;
5623 
5624 	return role;
5625 }
5626 
init_kvm_tdp_mmu(struct kvm_vcpu * vcpu,union kvm_cpu_role cpu_role)5627 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5628 			     union kvm_cpu_role cpu_role)
5629 {
5630 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5631 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5632 
5633 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5634 	    root_role.word == context->root_role.word)
5635 		return;
5636 
5637 	context->cpu_role.as_u64 = cpu_role.as_u64;
5638 	context->root_role.word = root_role.word;
5639 	context->page_fault = kvm_tdp_page_fault;
5640 	context->sync_spte = NULL;
5641 	context->get_guest_pgd = get_guest_cr3;
5642 	context->get_pdptr = kvm_pdptr_read;
5643 	context->inject_page_fault = kvm_inject_page_fault;
5644 
5645 	if (!is_cr0_pg(context))
5646 		context->gva_to_gpa = nonpaging_gva_to_gpa;
5647 	else if (is_cr4_pae(context))
5648 		context->gva_to_gpa = paging64_gva_to_gpa;
5649 	else
5650 		context->gva_to_gpa = paging32_gva_to_gpa;
5651 
5652 	reset_guest_paging_metadata(vcpu, context);
5653 	reset_tdp_shadow_zero_bits_mask(context);
5654 }
5655 
shadow_mmu_init_context(struct kvm_vcpu * vcpu,struct kvm_mmu * context,union kvm_cpu_role cpu_role,union kvm_mmu_page_role root_role)5656 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
5657 				    union kvm_cpu_role cpu_role,
5658 				    union kvm_mmu_page_role root_role)
5659 {
5660 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5661 	    root_role.word == context->root_role.word)
5662 		return;
5663 
5664 	context->cpu_role.as_u64 = cpu_role.as_u64;
5665 	context->root_role.word = root_role.word;
5666 
5667 	if (!is_cr0_pg(context))
5668 		nonpaging_init_context(context);
5669 	else if (is_cr4_pae(context))
5670 		paging64_init_context(context);
5671 	else
5672 		paging32_init_context(context);
5673 
5674 	reset_guest_paging_metadata(vcpu, context);
5675 	reset_shadow_zero_bits_mask(vcpu, context);
5676 }
5677 
kvm_init_shadow_mmu(struct kvm_vcpu * vcpu,union kvm_cpu_role cpu_role)5678 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5679 				union kvm_cpu_role cpu_role)
5680 {
5681 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5682 	union kvm_mmu_page_role root_role;
5683 
5684 	root_role = cpu_role.base;
5685 
5686 	/* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
5687 	root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
5688 
5689 	/*
5690 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
5691 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
5692 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
5693 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
5694 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
5695 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
5696 	 * MMU contexts.
5697 	 */
5698 	root_role.efer_nx = true;
5699 
5700 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5701 }
5702 
kvm_init_shadow_npt_mmu(struct kvm_vcpu * vcpu,unsigned long cr0,unsigned long cr4,u64 efer,gpa_t nested_cr3)5703 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5704 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
5705 {
5706 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5707 	struct kvm_mmu_role_regs regs = {
5708 		.cr0 = cr0,
5709 		.cr4 = cr4 & ~X86_CR4_PKE,
5710 		.efer = efer,
5711 	};
5712 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
5713 	union kvm_mmu_page_role root_role;
5714 
5715 	/* NPT requires CR0.PG=1. */
5716 	WARN_ON_ONCE(cpu_role.base.direct || !cpu_role.base.guest_mode);
5717 
5718 	root_role = cpu_role.base;
5719 	root_role.level = kvm_mmu_get_tdp_level(vcpu);
5720 	if (root_role.level == PT64_ROOT_5LEVEL &&
5721 	    cpu_role.base.level == PT64_ROOT_4LEVEL)
5722 		root_role.passthrough = 1;
5723 
5724 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5725 	kvm_mmu_new_pgd(vcpu, nested_cr3);
5726 }
5727 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5728 
5729 static union kvm_cpu_role
kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu * vcpu,bool accessed_dirty,bool execonly,u8 level)5730 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5731 				   bool execonly, u8 level)
5732 {
5733 	union kvm_cpu_role role = {0};
5734 
5735 	/*
5736 	 * KVM does not support SMM transfer monitors, and consequently does not
5737 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
5738 	 */
5739 	WARN_ON_ONCE(is_smm(vcpu));
5740 	role.base.level = level;
5741 	role.base.has_4_byte_gpte = false;
5742 	role.base.direct = false;
5743 	role.base.ad_disabled = !accessed_dirty;
5744 	role.base.guest_mode = true;
5745 	role.base.access = ACC_ALL;
5746 
5747 	role.ext.word = 0;
5748 	role.ext.execonly = execonly;
5749 	role.ext.valid = 1;
5750 
5751 	return role;
5752 }
5753 
kvm_init_shadow_ept_mmu(struct kvm_vcpu * vcpu,bool execonly,int huge_page_level,bool accessed_dirty,gpa_t new_eptp)5754 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5755 			     int huge_page_level, bool accessed_dirty,
5756 			     gpa_t new_eptp)
5757 {
5758 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5759 	u8 level = vmx_eptp_page_walk_level(new_eptp);
5760 	union kvm_cpu_role new_mode =
5761 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5762 						   execonly, level);
5763 
5764 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
5765 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5766 		context->cpu_role.as_u64 = new_mode.as_u64;
5767 		context->root_role.word = new_mode.base.word;
5768 
5769 		context->page_fault = ept_page_fault;
5770 		context->gva_to_gpa = ept_gva_to_gpa;
5771 		context->sync_spte = ept_sync_spte;
5772 
5773 		update_permission_bitmask(context, true);
5774 		context->pkru_mask = 0;
5775 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5776 		reset_ept_shadow_zero_bits_mask(context, execonly);
5777 	}
5778 
5779 	kvm_mmu_new_pgd(vcpu, new_eptp);
5780 }
5781 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5782 
init_kvm_softmmu(struct kvm_vcpu * vcpu,union kvm_cpu_role cpu_role)5783 static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5784 			     union kvm_cpu_role cpu_role)
5785 {
5786 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5787 
5788 	kvm_init_shadow_mmu(vcpu, cpu_role);
5789 
5790 	context->get_guest_pgd     = get_guest_cr3;
5791 	context->get_pdptr         = kvm_pdptr_read;
5792 	context->inject_page_fault = kvm_inject_page_fault;
5793 }
5794 
init_kvm_nested_mmu(struct kvm_vcpu * vcpu,union kvm_cpu_role new_mode)5795 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5796 				union kvm_cpu_role new_mode)
5797 {
5798 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5799 
5800 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5801 		return;
5802 
5803 	g_context->cpu_role.as_u64   = new_mode.as_u64;
5804 	g_context->get_guest_pgd     = get_guest_cr3;
5805 	g_context->get_pdptr         = kvm_pdptr_read;
5806 	g_context->inject_page_fault = kvm_inject_page_fault;
5807 
5808 	/*
5809 	 * L2 page tables are never shadowed, so there is no need to sync
5810 	 * SPTEs.
5811 	 */
5812 	g_context->sync_spte         = NULL;
5813 
5814 	/*
5815 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5816 	 * L1's nested page tables (e.g. EPT12). The nested translation
5817 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5818 	 * L2's page tables as the first level of translation and L1's
5819 	 * nested page tables as the second level of translation. Basically
5820 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5821 	 */
5822 	if (!is_paging(vcpu))
5823 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5824 	else if (is_long_mode(vcpu))
5825 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5826 	else if (is_pae(vcpu))
5827 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5828 	else
5829 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5830 
5831 	reset_guest_paging_metadata(vcpu, g_context);
5832 }
5833 
kvm_init_mmu(struct kvm_vcpu * vcpu)5834 void kvm_init_mmu(struct kvm_vcpu *vcpu)
5835 {
5836 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5837 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
5838 
5839 	if (mmu_is_nested(vcpu))
5840 		init_kvm_nested_mmu(vcpu, cpu_role);
5841 	else if (tdp_enabled)
5842 		init_kvm_tdp_mmu(vcpu, cpu_role);
5843 	else
5844 		init_kvm_softmmu(vcpu, cpu_role);
5845 }
5846 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5847 
kvm_mmu_after_set_cpuid(struct kvm_vcpu * vcpu)5848 void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
5849 {
5850 	/*
5851 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
5852 	 * information is factored into reserved bit calculations.
5853 	 *
5854 	 * Correctly handling multiple vCPU models with respect to paging and
5855 	 * physical address properties) in a single VM would require tracking
5856 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5857 	 * undesirable as it would increase the memory requirements for
5858 	 * gfn_write_track (see struct kvm_mmu_page_role comments).  For now
5859 	 * that problem is swept under the rug; KVM's CPUID API is horrific and
5860 	 * it's all but impossible to solve it without introducing a new API.
5861 	 */
5862 	vcpu->arch.root_mmu.root_role.invalid = 1;
5863 	vcpu->arch.guest_mmu.root_role.invalid = 1;
5864 	vcpu->arch.nested_mmu.root_role.invalid = 1;
5865 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5866 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5867 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
5868 	kvm_mmu_reset_context(vcpu);
5869 
5870 	/*
5871 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5872 	 * kvm_arch_vcpu_ioctl().
5873 	 */
5874 	KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm);
5875 }
5876 
kvm_mmu_reset_context(struct kvm_vcpu * vcpu)5877 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5878 {
5879 	kvm_mmu_unload(vcpu);
5880 	kvm_init_mmu(vcpu);
5881 }
5882 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5883 
kvm_mmu_load(struct kvm_vcpu * vcpu)5884 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5885 {
5886 	int r;
5887 
5888 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5889 	if (r)
5890 		goto out;
5891 	r = mmu_alloc_special_roots(vcpu);
5892 	if (r)
5893 		goto out;
5894 	if (vcpu->arch.mmu->root_role.direct)
5895 		r = mmu_alloc_direct_roots(vcpu);
5896 	else
5897 		r = mmu_alloc_shadow_roots(vcpu);
5898 	if (r)
5899 		goto out;
5900 
5901 	kvm_mmu_sync_roots(vcpu);
5902 
5903 	kvm_mmu_load_pgd(vcpu);
5904 
5905 	/*
5906 	 * Flush any TLB entries for the new root, the provenance of the root
5907 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5908 	 * for a freed root, in theory another hypervisor could have left
5909 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5910 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5911 	 */
5912 	kvm_x86_call(flush_tlb_current)(vcpu);
5913 out:
5914 	return r;
5915 }
5916 
kvm_mmu_unload(struct kvm_vcpu * vcpu)5917 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5918 {
5919 	struct kvm *kvm = vcpu->kvm;
5920 
5921 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5922 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
5923 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5924 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
5925 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5926 }
5927 
is_obsolete_root(struct kvm * kvm,hpa_t root_hpa)5928 static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5929 {
5930 	struct kvm_mmu_page *sp;
5931 
5932 	if (!VALID_PAGE(root_hpa))
5933 		return false;
5934 
5935 	/*
5936 	 * When freeing obsolete roots, treat roots as obsolete if they don't
5937 	 * have an associated shadow page, as it's impossible to determine if
5938 	 * such roots are fresh or stale.  This does mean KVM will get false
5939 	 * positives and free roots that don't strictly need to be freed, but
5940 	 * such false positives are relatively rare:
5941 	 *
5942 	 *  (a) only PAE paging and nested NPT have roots without shadow pages
5943 	 *      (or any shadow paging flavor with a dummy root, see note below)
5944 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5945 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5946 	 *      is unlikely to zap an in-use PGD.
5947 	 *
5948 	 * Note!  Dummy roots are unique in that they are obsoleted by memslot
5949 	 * _creation_!  See also FNAME(fetch).
5950 	 */
5951 	sp = root_to_sp(root_hpa);
5952 	return !sp || is_obsolete_sp(kvm, sp);
5953 }
5954 
__kvm_mmu_free_obsolete_roots(struct kvm * kvm,struct kvm_mmu * mmu)5955 static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5956 {
5957 	unsigned long roots_to_free = 0;
5958 	int i;
5959 
5960 	if (is_obsolete_root(kvm, mmu->root.hpa))
5961 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5962 
5963 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5964 		if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5965 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5966 	}
5967 
5968 	if (roots_to_free)
5969 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5970 }
5971 
kvm_mmu_free_obsolete_roots(struct kvm_vcpu * vcpu)5972 void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5973 {
5974 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5975 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5976 }
5977 
mmu_pte_write_fetch_gpte(struct kvm_vcpu * vcpu,gpa_t * gpa,int * bytes)5978 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5979 				    int *bytes)
5980 {
5981 	u64 gentry = 0;
5982 	int r;
5983 
5984 	/*
5985 	 * Assume that the pte write on a page table of the same type
5986 	 * as the current vcpu paging mode since we update the sptes only
5987 	 * when they have the same mode.
5988 	 */
5989 	if (is_pae(vcpu) && *bytes == 4) {
5990 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5991 		*gpa &= ~(gpa_t)7;
5992 		*bytes = 8;
5993 	}
5994 
5995 	if (*bytes == 4 || *bytes == 8) {
5996 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5997 		if (r)
5998 			gentry = 0;
5999 	}
6000 
6001 	return gentry;
6002 }
6003 
6004 /*
6005  * If we're seeing too many writes to a page, it may no longer be a page table,
6006  * or we may be forking, in which case it is better to unmap the page.
6007  */
detect_write_flooding(struct kvm_mmu_page * sp)6008 static bool detect_write_flooding(struct kvm_mmu_page *sp)
6009 {
6010 	/*
6011 	 * Skip write-flooding detected for the sp whose level is 1, because
6012 	 * it can become unsync, then the guest page is not write-protected.
6013 	 */
6014 	if (sp->role.level == PG_LEVEL_4K)
6015 		return false;
6016 
6017 	atomic_inc(&sp->write_flooding_count);
6018 	return atomic_read(&sp->write_flooding_count) >= 3;
6019 }
6020 
6021 /*
6022  * Misaligned accesses are too much trouble to fix up; also, they usually
6023  * indicate a page is not used as a page table.
6024  */
detect_write_misaligned(struct kvm_mmu_page * sp,gpa_t gpa,int bytes)6025 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
6026 				    int bytes)
6027 {
6028 	unsigned offset, pte_size, misaligned;
6029 
6030 	offset = offset_in_page(gpa);
6031 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
6032 
6033 	/*
6034 	 * Sometimes, the OS only writes the last one bytes to update status
6035 	 * bits, for example, in linux, andb instruction is used in clear_bit().
6036 	 */
6037 	if (!(offset & (pte_size - 1)) && bytes == 1)
6038 		return false;
6039 
6040 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
6041 	misaligned |= bytes < 4;
6042 
6043 	return misaligned;
6044 }
6045 
get_written_sptes(struct kvm_mmu_page * sp,gpa_t gpa,int * nspte)6046 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
6047 {
6048 	unsigned page_offset, quadrant;
6049 	u64 *spte;
6050 	int level;
6051 
6052 	page_offset = offset_in_page(gpa);
6053 	level = sp->role.level;
6054 	*nspte = 1;
6055 	if (sp->role.has_4_byte_gpte) {
6056 		page_offset <<= 1;	/* 32->64 */
6057 		/*
6058 		 * A 32-bit pde maps 4MB while the shadow pdes map
6059 		 * only 2MB.  So we need to double the offset again
6060 		 * and zap two pdes instead of one.
6061 		 */
6062 		if (level == PT32_ROOT_LEVEL) {
6063 			page_offset &= ~7; /* kill rounding error */
6064 			page_offset <<= 1;
6065 			*nspte = 2;
6066 		}
6067 		quadrant = page_offset >> PAGE_SHIFT;
6068 		page_offset &= ~PAGE_MASK;
6069 		if (quadrant != sp->role.quadrant)
6070 			return NULL;
6071 	}
6072 
6073 	spte = &sp->spt[page_offset / sizeof(*spte)];
6074 	return spte;
6075 }
6076 
kvm_mmu_track_write(struct kvm_vcpu * vcpu,gpa_t gpa,const u8 * new,int bytes)6077 void kvm_mmu_track_write(struct kvm_vcpu *vcpu, gpa_t gpa, const u8 *new,
6078 			 int bytes)
6079 {
6080 	gfn_t gfn = gpa >> PAGE_SHIFT;
6081 	struct kvm_mmu_page *sp;
6082 	LIST_HEAD(invalid_list);
6083 	u64 entry, gentry, *spte;
6084 	int npte;
6085 	bool flush = false;
6086 
6087 	/*
6088 	 * When emulating guest writes, ensure the written value is visible to
6089 	 * any task that is handling page faults before checking whether or not
6090 	 * KVM is shadowing a guest PTE.  This ensures either KVM will create
6091 	 * the correct SPTE in the page fault handler, or this task will see
6092 	 * a non-zero indirect_shadow_pages.  Pairs with the smp_mb() in
6093 	 * account_shadowed().
6094 	 */
6095 	smp_mb();
6096 	if (!vcpu->kvm->arch.indirect_shadow_pages)
6097 		return;
6098 
6099 	write_lock(&vcpu->kvm->mmu_lock);
6100 
6101 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
6102 
6103 	++vcpu->kvm->stat.mmu_pte_write;
6104 
6105 	for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
6106 		if (detect_write_misaligned(sp, gpa, bytes) ||
6107 		      detect_write_flooding(sp)) {
6108 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
6109 			++vcpu->kvm->stat.mmu_flooded;
6110 			continue;
6111 		}
6112 
6113 		spte = get_written_sptes(sp, gpa, &npte);
6114 		if (!spte)
6115 			continue;
6116 
6117 		while (npte--) {
6118 			entry = *spte;
6119 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
6120 			if (gentry && sp->role.level != PG_LEVEL_4K)
6121 				++vcpu->kvm->stat.mmu_pde_zapped;
6122 			if (is_shadow_present_pte(entry))
6123 				flush = true;
6124 			++spte;
6125 		}
6126 	}
6127 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
6128 	write_unlock(&vcpu->kvm->mmu_lock);
6129 }
6130 
is_write_to_guest_page_table(u64 error_code)6131 static bool is_write_to_guest_page_table(u64 error_code)
6132 {
6133 	const u64 mask = PFERR_GUEST_PAGE_MASK | PFERR_WRITE_MASK | PFERR_PRESENT_MASK;
6134 
6135 	return (error_code & mask) == mask;
6136 }
6137 
kvm_mmu_write_protect_fault(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,u64 error_code,int * emulation_type)6138 static int kvm_mmu_write_protect_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6139 				       u64 error_code, int *emulation_type)
6140 {
6141 	bool direct = vcpu->arch.mmu->root_role.direct;
6142 
6143 	/*
6144 	 * Do not try to unprotect and retry if the vCPU re-faulted on the same
6145 	 * RIP with the same address that was previously unprotected, as doing
6146 	 * so will likely put the vCPU into an infinite.  E.g. if the vCPU uses
6147 	 * a non-page-table modifying instruction on the PDE that points to the
6148 	 * instruction, then unprotecting the gfn will unmap the instruction's
6149 	 * code, i.e. make it impossible for the instruction to ever complete.
6150 	 */
6151 	if (vcpu->arch.last_retry_eip == kvm_rip_read(vcpu) &&
6152 	    vcpu->arch.last_retry_addr == cr2_or_gpa)
6153 		return RET_PF_EMULATE;
6154 
6155 	/*
6156 	 * Reset the unprotect+retry values that guard against infinite loops.
6157 	 * The values will be refreshed if KVM explicitly unprotects a gfn and
6158 	 * retries, in all other cases it's safe to retry in the future even if
6159 	 * the next page fault happens on the same RIP+address.
6160 	 */
6161 	vcpu->arch.last_retry_eip = 0;
6162 	vcpu->arch.last_retry_addr = 0;
6163 
6164 	/*
6165 	 * It should be impossible to reach this point with an MMIO cache hit,
6166 	 * as RET_PF_WRITE_PROTECTED is returned if and only if there's a valid,
6167 	 * writable memslot, and creating a memslot should invalidate the MMIO
6168 	 * cache by way of changing the memslot generation.  WARN and disallow
6169 	 * retry if MMIO is detected, as retrying MMIO emulation is pointless
6170 	 * and could put the vCPU into an infinite loop because the processor
6171 	 * will keep faulting on the non-existent MMIO address.
6172 	 */
6173 	if (WARN_ON_ONCE(mmio_info_in_cache(vcpu, cr2_or_gpa, direct)))
6174 		return RET_PF_EMULATE;
6175 
6176 	/*
6177 	 * Before emulating the instruction, check to see if the access was due
6178 	 * to a read-only violation while the CPU was walking non-nested NPT
6179 	 * page tables, i.e. for a direct MMU, for _guest_ page tables in L1.
6180 	 * If L1 is sharing (a subset of) its page tables with L2, e.g. by
6181 	 * having nCR3 share lower level page tables with hCR3, then when KVM
6182 	 * (L0) write-protects the nested NPTs, i.e. npt12 entries, KVM is also
6183 	 * unknowingly write-protecting L1's guest page tables, which KVM isn't
6184 	 * shadowing.
6185 	 *
6186 	 * Because the CPU (by default) walks NPT page tables using a write
6187 	 * access (to ensure the CPU can do A/D updates), page walks in L1 can
6188 	 * trigger write faults for the above case even when L1 isn't modifying
6189 	 * PTEs.  As a result, KVM will unnecessarily emulate (or at least, try
6190 	 * to emulate) an excessive number of L1 instructions; because L1's MMU
6191 	 * isn't shadowed by KVM, there is no need to write-protect L1's gPTEs
6192 	 * and thus no need to emulate in order to guarantee forward progress.
6193 	 *
6194 	 * Try to unprotect the gfn, i.e. zap any shadow pages, so that L1 can
6195 	 * proceed without triggering emulation.  If one or more shadow pages
6196 	 * was zapped, skip emulation and resume L1 to let it natively execute
6197 	 * the instruction.  If no shadow pages were zapped, then the write-
6198 	 * fault is due to something else entirely, i.e. KVM needs to emulate,
6199 	 * as resuming the guest will put it into an infinite loop.
6200 	 *
6201 	 * Note, this code also applies to Intel CPUs, even though it is *very*
6202 	 * unlikely that an L1 will share its page tables (IA32/PAE/paging64
6203 	 * format) with L2's page tables (EPT format).
6204 	 *
6205 	 * For indirect MMUs, i.e. if KVM is shadowing the current MMU, try to
6206 	 * unprotect the gfn and retry if an event is awaiting reinjection.  If
6207 	 * KVM emulates multiple instructions before completing event injection,
6208 	 * the event could be delayed beyond what is architecturally allowed,
6209 	 * e.g. KVM could inject an IRQ after the TPR has been raised.
6210 	 */
6211 	if (((direct && is_write_to_guest_page_table(error_code)) ||
6212 	     (!direct && kvm_event_needs_reinjection(vcpu))) &&
6213 	    kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
6214 		return RET_PF_RETRY;
6215 
6216 	/*
6217 	 * The gfn is write-protected, but if KVM detects its emulating an
6218 	 * instruction that is unlikely to be used to modify page tables, or if
6219 	 * emulation fails, KVM can try to unprotect the gfn and let the CPU
6220 	 * re-execute the instruction that caused the page fault.  Do not allow
6221 	 * retrying an instruction from a nested guest as KVM is only explicitly
6222 	 * shadowing L1's page tables, i.e. unprotecting something for L1 isn't
6223 	 * going to magically fix whatever issue caused L2 to fail.
6224 	 */
6225 	if (!is_guest_mode(vcpu))
6226 		*emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
6227 
6228 	return RET_PF_EMULATE;
6229 }
6230 
kvm_mmu_page_fault(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,u64 error_code,void * insn,int insn_len)6231 int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
6232 		       void *insn, int insn_len)
6233 {
6234 	int r, emulation_type = EMULTYPE_PF;
6235 	bool direct = vcpu->arch.mmu->root_role.direct;
6236 
6237 	if (WARN_ON_ONCE(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
6238 		return RET_PF_RETRY;
6239 
6240 	/*
6241 	 * Except for reserved faults (emulated MMIO is shared-only), set the
6242 	 * PFERR_PRIVATE_ACCESS flag for software-protected VMs based on the gfn's
6243 	 * current attributes, which are the source of truth for such VMs.  Note,
6244 	 * this wrong for nested MMUs as the GPA is an L2 GPA, but KVM doesn't
6245 	 * currently supported nested virtualization (among many other things)
6246 	 * for software-protected VMs.
6247 	 */
6248 	if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) &&
6249 	    !(error_code & PFERR_RSVD_MASK) &&
6250 	    vcpu->kvm->arch.vm_type == KVM_X86_SW_PROTECTED_VM &&
6251 	    kvm_mem_is_private(vcpu->kvm, gpa_to_gfn(cr2_or_gpa)))
6252 		error_code |= PFERR_PRIVATE_ACCESS;
6253 
6254 	r = RET_PF_INVALID;
6255 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
6256 		if (WARN_ON_ONCE(error_code & PFERR_PRIVATE_ACCESS))
6257 			return -EFAULT;
6258 
6259 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
6260 		if (r == RET_PF_EMULATE)
6261 			goto emulate;
6262 	}
6263 
6264 	if (r == RET_PF_INVALID) {
6265 		vcpu->stat.pf_taken++;
6266 
6267 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa, error_code, false,
6268 					  &emulation_type, NULL);
6269 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
6270 			return -EIO;
6271 	}
6272 
6273 	if (r < 0)
6274 		return r;
6275 
6276 	if (r == RET_PF_WRITE_PROTECTED)
6277 		r = kvm_mmu_write_protect_fault(vcpu, cr2_or_gpa, error_code,
6278 						&emulation_type);
6279 
6280 	if (r == RET_PF_FIXED)
6281 		vcpu->stat.pf_fixed++;
6282 	else if (r == RET_PF_EMULATE)
6283 		vcpu->stat.pf_emulate++;
6284 	else if (r == RET_PF_SPURIOUS)
6285 		vcpu->stat.pf_spurious++;
6286 
6287 	/*
6288 	 * None of handle_mmio_page_fault(), kvm_mmu_do_page_fault(), or
6289 	 * kvm_mmu_write_protect_fault() return RET_PF_CONTINUE.
6290 	 * kvm_mmu_do_page_fault() only uses RET_PF_CONTINUE internally to
6291 	 * indicate continuing the page fault handling until to the final
6292 	 * page table mapping phase.
6293 	 */
6294 	WARN_ON_ONCE(r == RET_PF_CONTINUE);
6295 	if (r != RET_PF_EMULATE)
6296 		return r;
6297 
6298 emulate:
6299 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
6300 				       insn_len);
6301 }
6302 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
6303 
kvm_mmu_print_sptes(struct kvm_vcpu * vcpu,gpa_t gpa,const char * msg)6304 void kvm_mmu_print_sptes(struct kvm_vcpu *vcpu, gpa_t gpa, const char *msg)
6305 {
6306 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
6307 	int root_level, leaf, level;
6308 
6309 	leaf = get_sptes_lockless(vcpu, gpa, sptes, &root_level);
6310 	if (unlikely(leaf < 0))
6311 		return;
6312 
6313 	pr_err("%s %llx", msg, gpa);
6314 	for (level = root_level; level >= leaf; level--)
6315 		pr_cont(", spte[%d] = 0x%llx", level, sptes[level]);
6316 	pr_cont("\n");
6317 }
6318 EXPORT_SYMBOL_GPL(kvm_mmu_print_sptes);
6319 
__kvm_mmu_invalidate_addr(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu,u64 addr,hpa_t root_hpa)6320 static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
6321 				      u64 addr, hpa_t root_hpa)
6322 {
6323 	struct kvm_shadow_walk_iterator iterator;
6324 
6325 	vcpu_clear_mmio_info(vcpu, addr);
6326 
6327 	/*
6328 	 * Walking and synchronizing SPTEs both assume they are operating in
6329 	 * the context of the current MMU, and would need to be reworked if
6330 	 * this is ever used to sync the guest_mmu, e.g. to emulate INVEPT.
6331 	 */
6332 	if (WARN_ON_ONCE(mmu != vcpu->arch.mmu))
6333 		return;
6334 
6335 	if (!VALID_PAGE(root_hpa))
6336 		return;
6337 
6338 	write_lock(&vcpu->kvm->mmu_lock);
6339 	for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
6340 		struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
6341 
6342 		if (sp->unsync) {
6343 			int ret = kvm_sync_spte(vcpu, sp, iterator.index);
6344 
6345 			if (ret < 0)
6346 				mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
6347 			if (ret)
6348 				kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
6349 		}
6350 
6351 		if (!sp->unsync_children)
6352 			break;
6353 	}
6354 	write_unlock(&vcpu->kvm->mmu_lock);
6355 }
6356 
kvm_mmu_invalidate_addr(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu,u64 addr,unsigned long roots)6357 void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
6358 			     u64 addr, unsigned long roots)
6359 {
6360 	int i;
6361 
6362 	WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
6363 
6364 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
6365 	if (mmu != &vcpu->arch.guest_mmu) {
6366 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
6367 		if (is_noncanonical_invlpg_address(addr, vcpu))
6368 			return;
6369 
6370 		kvm_x86_call(flush_tlb_gva)(vcpu, addr);
6371 	}
6372 
6373 	if (!mmu->sync_spte)
6374 		return;
6375 
6376 	if (roots & KVM_MMU_ROOT_CURRENT)
6377 		__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
6378 
6379 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
6380 		if (roots & KVM_MMU_ROOT_PREVIOUS(i))
6381 			__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
6382 	}
6383 }
6384 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
6385 
kvm_mmu_invlpg(struct kvm_vcpu * vcpu,gva_t gva)6386 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
6387 {
6388 	/*
6389 	 * INVLPG is required to invalidate any global mappings for the VA,
6390 	 * irrespective of PCID.  Blindly sync all roots as it would take
6391 	 * roughly the same amount of work/time to determine whether any of the
6392 	 * previous roots have a global mapping.
6393 	 *
6394 	 * Mappings not reachable via the current or previous cached roots will
6395 	 * be synced when switching to that new cr3, so nothing needs to be
6396 	 * done here for them.
6397 	 */
6398 	kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
6399 	++vcpu->stat.invlpg;
6400 }
6401 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
6402 
6403 
kvm_mmu_invpcid_gva(struct kvm_vcpu * vcpu,gva_t gva,unsigned long pcid)6404 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
6405 {
6406 	struct kvm_mmu *mmu = vcpu->arch.mmu;
6407 	unsigned long roots = 0;
6408 	uint i;
6409 
6410 	if (pcid == kvm_get_active_pcid(vcpu))
6411 		roots |= KVM_MMU_ROOT_CURRENT;
6412 
6413 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
6414 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
6415 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
6416 			roots |= KVM_MMU_ROOT_PREVIOUS(i);
6417 	}
6418 
6419 	if (roots)
6420 		kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
6421 	++vcpu->stat.invlpg;
6422 
6423 	/*
6424 	 * Mappings not reachable via the current cr3 or the prev_roots will be
6425 	 * synced when switching to that cr3, so nothing needs to be done here
6426 	 * for them.
6427 	 */
6428 }
6429 
kvm_configure_mmu(bool enable_tdp,int tdp_forced_root_level,int tdp_max_root_level,int tdp_huge_page_level)6430 void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
6431 		       int tdp_max_root_level, int tdp_huge_page_level)
6432 {
6433 	tdp_enabled = enable_tdp;
6434 	tdp_root_level = tdp_forced_root_level;
6435 	max_tdp_level = tdp_max_root_level;
6436 
6437 #ifdef CONFIG_X86_64
6438 	tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
6439 #endif
6440 	/*
6441 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
6442 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
6443 	 * the kernel is not.  But, KVM never creates a page size greater than
6444 	 * what is used by the kernel for any given HVA, i.e. the kernel's
6445 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
6446 	 */
6447 	if (tdp_enabled)
6448 		max_huge_page_level = tdp_huge_page_level;
6449 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
6450 		max_huge_page_level = PG_LEVEL_1G;
6451 	else
6452 		max_huge_page_level = PG_LEVEL_2M;
6453 }
6454 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
6455 
free_mmu_pages(struct kvm_mmu * mmu)6456 static void free_mmu_pages(struct kvm_mmu *mmu)
6457 {
6458 	if (!tdp_enabled && mmu->pae_root)
6459 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
6460 	free_page((unsigned long)mmu->pae_root);
6461 	free_page((unsigned long)mmu->pml4_root);
6462 	free_page((unsigned long)mmu->pml5_root);
6463 }
6464 
__kvm_mmu_create(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu)6465 static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6466 {
6467 	struct page *page;
6468 	int i;
6469 
6470 	mmu->root.hpa = INVALID_PAGE;
6471 	mmu->root.pgd = 0;
6472 	mmu->mirror_root_hpa = INVALID_PAGE;
6473 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
6474 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
6475 
6476 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
6477 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
6478 		return 0;
6479 
6480 	/*
6481 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
6482 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
6483 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
6484 	 * x86_64.  Therefore we need to allocate the PDP table in the first
6485 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
6486 	 * generally doesn't use PAE paging and can skip allocating the PDP
6487 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
6488 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
6489 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
6490 	 */
6491 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
6492 		return 0;
6493 
6494 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
6495 	if (!page)
6496 		return -ENOMEM;
6497 
6498 	mmu->pae_root = page_address(page);
6499 
6500 	/*
6501 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
6502 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
6503 	 * that KVM's writes and the CPU's reads get along.  Note, this is
6504 	 * only necessary when using shadow paging, as 64-bit NPT can get at
6505 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
6506 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
6507 	 */
6508 	if (!tdp_enabled)
6509 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
6510 	else
6511 		WARN_ON_ONCE(shadow_me_value);
6512 
6513 	for (i = 0; i < 4; ++i)
6514 		mmu->pae_root[i] = INVALID_PAE_ROOT;
6515 
6516 	return 0;
6517 }
6518 
kvm_mmu_create(struct kvm_vcpu * vcpu)6519 int kvm_mmu_create(struct kvm_vcpu *vcpu)
6520 {
6521 	int ret;
6522 
6523 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
6524 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
6525 
6526 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
6527 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
6528 
6529 	vcpu->arch.mmu_shadow_page_cache.init_value =
6530 		SHADOW_NONPRESENT_VALUE;
6531 	if (!vcpu->arch.mmu_shadow_page_cache.init_value)
6532 		vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
6533 
6534 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
6535 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6536 
6537 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6538 	if (ret)
6539 		return ret;
6540 
6541 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6542 	if (ret)
6543 		goto fail_allocate_root;
6544 
6545 	return ret;
6546  fail_allocate_root:
6547 	free_mmu_pages(&vcpu->arch.guest_mmu);
6548 	return ret;
6549 }
6550 
6551 #define BATCH_ZAP_PAGES	10
kvm_zap_obsolete_pages(struct kvm * kvm)6552 static void kvm_zap_obsolete_pages(struct kvm *kvm)
6553 {
6554 	struct kvm_mmu_page *sp, *node;
6555 	int nr_zapped, batch = 0;
6556 	LIST_HEAD(invalid_list);
6557 	bool unstable;
6558 
6559 	lockdep_assert_held(&kvm->slots_lock);
6560 
6561 restart:
6562 	list_for_each_entry_safe_reverse(sp, node,
6563 	      &kvm->arch.active_mmu_pages, link) {
6564 		/*
6565 		 * No obsolete valid page exists before a newly created page
6566 		 * since active_mmu_pages is a FIFO list.
6567 		 */
6568 		if (!is_obsolete_sp(kvm, sp))
6569 			break;
6570 
6571 		/*
6572 		 * Invalid pages should never land back on the list of active
6573 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
6574 		 * infinite loop if the page gets put back on the list (again).
6575 		 */
6576 		if (WARN_ON_ONCE(sp->role.invalid))
6577 			continue;
6578 
6579 		/*
6580 		 * No need to flush the TLB since we're only zapping shadow
6581 		 * pages with an obsolete generation number and all vCPUS have
6582 		 * loaded a new root, i.e. the shadow pages being zapped cannot
6583 		 * be in active use by the guest.
6584 		 */
6585 		if (batch >= BATCH_ZAP_PAGES &&
6586 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
6587 			batch = 0;
6588 			goto restart;
6589 		}
6590 
6591 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6592 				&invalid_list, &nr_zapped);
6593 		batch += nr_zapped;
6594 
6595 		if (unstable)
6596 			goto restart;
6597 	}
6598 
6599 	/*
6600 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
6601 	 * to ensure KVM is not in the middle of a lockless shadow page table
6602 	 * walk, which may reference the pages.  The remote TLB flush itself is
6603 	 * not required and is simply a convenient way to kick vCPUs as needed.
6604 	 * KVM performs a local TLB flush when allocating a new root (see
6605 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
6606 	 * running with an obsolete MMU.
6607 	 */
6608 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6609 }
6610 
6611 /*
6612  * Fast invalidate all shadow pages and use lock-break technique
6613  * to zap obsolete pages.
6614  *
6615  * It's required when memslot is being deleted or VM is being
6616  * destroyed, in these cases, we should ensure that KVM MMU does
6617  * not use any resource of the being-deleted slot or all slots
6618  * after calling the function.
6619  */
kvm_mmu_zap_all_fast(struct kvm * kvm)6620 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6621 {
6622 	lockdep_assert_held(&kvm->slots_lock);
6623 
6624 	write_lock(&kvm->mmu_lock);
6625 	trace_kvm_mmu_zap_all_fast(kvm);
6626 
6627 	/*
6628 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
6629 	 * held for the entire duration of zapping obsolete pages, it's
6630 	 * impossible for there to be multiple invalid generations associated
6631 	 * with *valid* shadow pages at any given time, i.e. there is exactly
6632 	 * one valid generation and (at most) one invalid generation.
6633 	 */
6634 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6635 
6636 	/*
6637 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
6638 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
6639 	 * write and in the same critical section as making the reload request,
6640 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6641 	 */
6642 	if (tdp_mmu_enabled) {
6643 		/*
6644 		 * External page tables don't support fast zapping, therefore
6645 		 * their mirrors must be invalidated separately by the caller.
6646 		 */
6647 		kvm_tdp_mmu_invalidate_roots(kvm, KVM_DIRECT_ROOTS);
6648 	}
6649 
6650 	/*
6651 	 * Notify all vcpus to reload its shadow page table and flush TLB.
6652 	 * Then all vcpus will switch to new shadow page table with the new
6653 	 * mmu_valid_gen.
6654 	 *
6655 	 * Note: we need to do this under the protection of mmu_lock,
6656 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
6657 	 */
6658 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6659 
6660 	kvm_zap_obsolete_pages(kvm);
6661 
6662 	write_unlock(&kvm->mmu_lock);
6663 
6664 	/*
6665 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6666 	 * returning to the caller, e.g. if the zap is in response to a memslot
6667 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6668 	 * associated with the deleted memslot once the update completes, and
6669 	 * Deferring the zap until the final reference to the root is put would
6670 	 * lead to use-after-free.
6671 	 */
6672 	if (tdp_mmu_enabled)
6673 		kvm_tdp_mmu_zap_invalidated_roots(kvm, true);
6674 }
6675 
kvm_mmu_init_vm(struct kvm * kvm)6676 void kvm_mmu_init_vm(struct kvm *kvm)
6677 {
6678 	kvm->arch.shadow_mmio_value = shadow_mmio_value;
6679 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6680 	INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6681 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6682 
6683 	if (tdp_mmu_enabled)
6684 		kvm_mmu_init_tdp_mmu(kvm);
6685 
6686 	kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6687 	kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6688 
6689 	kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6690 
6691 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6692 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6693 }
6694 
mmu_free_vm_memory_caches(struct kvm * kvm)6695 static void mmu_free_vm_memory_caches(struct kvm *kvm)
6696 {
6697 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6698 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6699 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6700 }
6701 
kvm_mmu_uninit_vm(struct kvm * kvm)6702 void kvm_mmu_uninit_vm(struct kvm *kvm)
6703 {
6704 	if (tdp_mmu_enabled)
6705 		kvm_mmu_uninit_tdp_mmu(kvm);
6706 
6707 	mmu_free_vm_memory_caches(kvm);
6708 }
6709 
kvm_rmap_zap_gfn_range(struct kvm * kvm,gfn_t gfn_start,gfn_t gfn_end)6710 static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6711 {
6712 	const struct kvm_memory_slot *memslot;
6713 	struct kvm_memslots *slots;
6714 	struct kvm_memslot_iter iter;
6715 	bool flush = false;
6716 	gfn_t start, end;
6717 	int i;
6718 
6719 	if (!kvm_memslots_have_rmaps(kvm))
6720 		return flush;
6721 
6722 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
6723 		slots = __kvm_memslots(kvm, i);
6724 
6725 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6726 			memslot = iter.slot;
6727 			start = max(gfn_start, memslot->base_gfn);
6728 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
6729 			if (WARN_ON_ONCE(start >= end))
6730 				continue;
6731 
6732 			flush = __kvm_rmap_zap_gfn_range(kvm, memslot, start,
6733 							 end, true, flush);
6734 		}
6735 	}
6736 
6737 	return flush;
6738 }
6739 
6740 /*
6741  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
6742  * (not including it)
6743  */
kvm_zap_gfn_range(struct kvm * kvm,gfn_t gfn_start,gfn_t gfn_end)6744 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6745 {
6746 	bool flush;
6747 
6748 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
6749 		return;
6750 
6751 	write_lock(&kvm->mmu_lock);
6752 
6753 	kvm_mmu_invalidate_begin(kvm);
6754 
6755 	kvm_mmu_invalidate_range_add(kvm, gfn_start, gfn_end);
6756 
6757 	flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
6758 
6759 	if (tdp_mmu_enabled)
6760 		flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
6761 
6762 	if (flush)
6763 		kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
6764 
6765 	kvm_mmu_invalidate_end(kvm);
6766 
6767 	write_unlock(&kvm->mmu_lock);
6768 }
6769 
slot_rmap_write_protect(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)6770 static bool slot_rmap_write_protect(struct kvm *kvm,
6771 				    struct kvm_rmap_head *rmap_head,
6772 				    const struct kvm_memory_slot *slot)
6773 {
6774 	return rmap_write_protect(rmap_head, false);
6775 }
6776 
kvm_mmu_slot_remove_write_access(struct kvm * kvm,const struct kvm_memory_slot * memslot,int start_level)6777 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6778 				      const struct kvm_memory_slot *memslot,
6779 				      int start_level)
6780 {
6781 	if (kvm_memslots_have_rmaps(kvm)) {
6782 		write_lock(&kvm->mmu_lock);
6783 		walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6784 				start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6785 		write_unlock(&kvm->mmu_lock);
6786 	}
6787 
6788 	if (tdp_mmu_enabled) {
6789 		read_lock(&kvm->mmu_lock);
6790 		kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
6791 		read_unlock(&kvm->mmu_lock);
6792 	}
6793 }
6794 
need_topup(struct kvm_mmu_memory_cache * cache,int min)6795 static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6796 {
6797 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6798 }
6799 
need_topup_split_caches_or_resched(struct kvm * kvm)6800 static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6801 {
6802 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6803 		return true;
6804 
6805 	/*
6806 	 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6807 	 * to split a single huge page. Calculating how many are actually needed
6808 	 * is possible but not worth the complexity.
6809 	 */
6810 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6811 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
6812 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
6813 }
6814 
topup_split_caches(struct kvm * kvm)6815 static int topup_split_caches(struct kvm *kvm)
6816 {
6817 	/*
6818 	 * Allocating rmap list entries when splitting huge pages for nested
6819 	 * MMUs is uncommon as KVM needs to use a list if and only if there is
6820 	 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6821 	 * aliased by multiple L2 gfns and/or from multiple nested roots with
6822 	 * different roles.  Aliasing gfns when using TDP is atypical for VMMs;
6823 	 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6824 	 * but aliasing rarely occurs post-boot or for many gfns.  If there is
6825 	 * only one rmap entry, rmap->val points directly at that one entry and
6826 	 * doesn't need to allocate a list.  Buffer the cache by the default
6827 	 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6828 	 * encounters an aliased gfn or two.
6829 	 */
6830 	const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6831 			     KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6832 	int r;
6833 
6834 	lockdep_assert_held(&kvm->slots_lock);
6835 
6836 	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6837 					 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6838 	if (r)
6839 		return r;
6840 
6841 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6842 	if (r)
6843 		return r;
6844 
6845 	return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6846 }
6847 
shadow_mmu_get_sp_for_split(struct kvm * kvm,u64 * huge_sptep)6848 static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6849 {
6850 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6851 	struct shadow_page_caches caches = {};
6852 	union kvm_mmu_page_role role;
6853 	unsigned int access;
6854 	gfn_t gfn;
6855 
6856 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6857 	access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6858 
6859 	/*
6860 	 * Note, huge page splitting always uses direct shadow pages, regardless
6861 	 * of whether the huge page itself is mapped by a direct or indirect
6862 	 * shadow page, since the huge page region itself is being directly
6863 	 * mapped with smaller pages.
6864 	 */
6865 	role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6866 
6867 	/* Direct SPs do not require a shadowed_info_cache. */
6868 	caches.page_header_cache = &kvm->arch.split_page_header_cache;
6869 	caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6870 
6871 	/* Safe to pass NULL for vCPU since requesting a direct SP. */
6872 	return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6873 }
6874 
shadow_mmu_split_huge_page(struct kvm * kvm,const struct kvm_memory_slot * slot,u64 * huge_sptep)6875 static void shadow_mmu_split_huge_page(struct kvm *kvm,
6876 				       const struct kvm_memory_slot *slot,
6877 				       u64 *huge_sptep)
6878 
6879 {
6880 	struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6881 	u64 huge_spte = READ_ONCE(*huge_sptep);
6882 	struct kvm_mmu_page *sp;
6883 	bool flush = false;
6884 	u64 *sptep, spte;
6885 	gfn_t gfn;
6886 	int index;
6887 
6888 	sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6889 
6890 	for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6891 		sptep = &sp->spt[index];
6892 		gfn = kvm_mmu_page_get_gfn(sp, index);
6893 
6894 		/*
6895 		 * The SP may already have populated SPTEs, e.g. if this huge
6896 		 * page is aliased by multiple sptes with the same access
6897 		 * permissions. These entries are guaranteed to map the same
6898 		 * gfn-to-pfn translation since the SP is direct, so no need to
6899 		 * modify them.
6900 		 *
6901 		 * However, if a given SPTE points to a lower level page table,
6902 		 * that lower level page table may only be partially populated.
6903 		 * Installing such SPTEs would effectively unmap a potion of the
6904 		 * huge page. Unmapping guest memory always requires a TLB flush
6905 		 * since a subsequent operation on the unmapped regions would
6906 		 * fail to detect the need to flush.
6907 		 */
6908 		if (is_shadow_present_pte(*sptep)) {
6909 			flush |= !is_last_spte(*sptep, sp->role.level);
6910 			continue;
6911 		}
6912 
6913 		spte = make_small_spte(kvm, huge_spte, sp->role, index);
6914 		mmu_spte_set(sptep, spte);
6915 		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6916 	}
6917 
6918 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6919 }
6920 
shadow_mmu_try_split_huge_page(struct kvm * kvm,const struct kvm_memory_slot * slot,u64 * huge_sptep)6921 static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6922 					  const struct kvm_memory_slot *slot,
6923 					  u64 *huge_sptep)
6924 {
6925 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6926 	int level, r = 0;
6927 	gfn_t gfn;
6928 	u64 spte;
6929 
6930 	/* Grab information for the tracepoint before dropping the MMU lock. */
6931 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6932 	level = huge_sp->role.level;
6933 	spte = *huge_sptep;
6934 
6935 	if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6936 		r = -ENOSPC;
6937 		goto out;
6938 	}
6939 
6940 	if (need_topup_split_caches_or_resched(kvm)) {
6941 		write_unlock(&kvm->mmu_lock);
6942 		cond_resched();
6943 		/*
6944 		 * If the topup succeeds, return -EAGAIN to indicate that the
6945 		 * rmap iterator should be restarted because the MMU lock was
6946 		 * dropped.
6947 		 */
6948 		r = topup_split_caches(kvm) ?: -EAGAIN;
6949 		write_lock(&kvm->mmu_lock);
6950 		goto out;
6951 	}
6952 
6953 	shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6954 
6955 out:
6956 	trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6957 	return r;
6958 }
6959 
shadow_mmu_try_split_huge_pages(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)6960 static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6961 					    struct kvm_rmap_head *rmap_head,
6962 					    const struct kvm_memory_slot *slot)
6963 {
6964 	struct rmap_iterator iter;
6965 	struct kvm_mmu_page *sp;
6966 	u64 *huge_sptep;
6967 	int r;
6968 
6969 restart:
6970 	for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6971 		sp = sptep_to_sp(huge_sptep);
6972 
6973 		/* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6974 		if (WARN_ON_ONCE(!sp->role.guest_mode))
6975 			continue;
6976 
6977 		/* The rmaps should never contain non-leaf SPTEs. */
6978 		if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6979 			continue;
6980 
6981 		/* SPs with level >PG_LEVEL_4K should never by unsync. */
6982 		if (WARN_ON_ONCE(sp->unsync))
6983 			continue;
6984 
6985 		/* Don't bother splitting huge pages on invalid SPs. */
6986 		if (sp->role.invalid)
6987 			continue;
6988 
6989 		r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6990 
6991 		/*
6992 		 * The split succeeded or needs to be retried because the MMU
6993 		 * lock was dropped. Either way, restart the iterator to get it
6994 		 * back into a consistent state.
6995 		 */
6996 		if (!r || r == -EAGAIN)
6997 			goto restart;
6998 
6999 		/* The split failed and shouldn't be retried (e.g. -ENOMEM). */
7000 		break;
7001 	}
7002 
7003 	return false;
7004 }
7005 
kvm_shadow_mmu_try_split_huge_pages(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t start,gfn_t end,int target_level)7006 static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
7007 						const struct kvm_memory_slot *slot,
7008 						gfn_t start, gfn_t end,
7009 						int target_level)
7010 {
7011 	int level;
7012 
7013 	/*
7014 	 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
7015 	 * down to the target level. This ensures pages are recursively split
7016 	 * all the way to the target level. There's no need to split pages
7017 	 * already at the target level.
7018 	 */
7019 	for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
7020 		__walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
7021 				  level, level, start, end - 1, true, true, false);
7022 }
7023 
7024 /* Must be called with the mmu_lock held in write-mode. */
kvm_mmu_try_split_huge_pages(struct kvm * kvm,const struct kvm_memory_slot * memslot,u64 start,u64 end,int target_level)7025 void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
7026 				   const struct kvm_memory_slot *memslot,
7027 				   u64 start, u64 end,
7028 				   int target_level)
7029 {
7030 	if (!tdp_mmu_enabled)
7031 		return;
7032 
7033 	if (kvm_memslots_have_rmaps(kvm))
7034 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
7035 
7036 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
7037 
7038 	/*
7039 	 * A TLB flush is unnecessary at this point for the same reasons as in
7040 	 * kvm_mmu_slot_try_split_huge_pages().
7041 	 */
7042 }
7043 
kvm_mmu_slot_try_split_huge_pages(struct kvm * kvm,const struct kvm_memory_slot * memslot,int target_level)7044 void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
7045 					const struct kvm_memory_slot *memslot,
7046 					int target_level)
7047 {
7048 	u64 start = memslot->base_gfn;
7049 	u64 end = start + memslot->npages;
7050 
7051 	if (!tdp_mmu_enabled)
7052 		return;
7053 
7054 	if (kvm_memslots_have_rmaps(kvm)) {
7055 		write_lock(&kvm->mmu_lock);
7056 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
7057 		write_unlock(&kvm->mmu_lock);
7058 	}
7059 
7060 	read_lock(&kvm->mmu_lock);
7061 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
7062 	read_unlock(&kvm->mmu_lock);
7063 
7064 	/*
7065 	 * No TLB flush is necessary here. KVM will flush TLBs after
7066 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
7067 	 * ensure that guest writes are reflected in the dirty log before the
7068 	 * ioctl to enable dirty logging on this memslot completes. Since the
7069 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
7070 	 * safe for KVM to decide if a TLB flush is necessary based on the split
7071 	 * SPTEs.
7072 	 */
7073 }
7074 
kvm_mmu_zap_collapsible_spte(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)7075 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
7076 					 struct kvm_rmap_head *rmap_head,
7077 					 const struct kvm_memory_slot *slot)
7078 {
7079 	u64 *sptep;
7080 	struct rmap_iterator iter;
7081 	int need_tlb_flush = 0;
7082 	struct kvm_mmu_page *sp;
7083 
7084 restart:
7085 	for_each_rmap_spte(rmap_head, &iter, sptep) {
7086 		sp = sptep_to_sp(sptep);
7087 
7088 		/*
7089 		 * We cannot do huge page mapping for indirect shadow pages,
7090 		 * which are found on the last rmap (level = 1) when not using
7091 		 * tdp; such shadow pages are synced with the page table in
7092 		 * the guest, and the guest page table is using 4K page size
7093 		 * mapping if the indirect sp has level = 1.
7094 		 */
7095 		if (sp->role.direct &&
7096 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn)) {
7097 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
7098 
7099 			if (kvm_available_flush_remote_tlbs_range())
7100 				kvm_flush_remote_tlbs_sptep(kvm, sptep);
7101 			else
7102 				need_tlb_flush = 1;
7103 
7104 			goto restart;
7105 		}
7106 	}
7107 
7108 	return need_tlb_flush;
7109 }
7110 EXPORT_SYMBOL_GPL(kvm_zap_gfn_range);
7111 
kvm_rmap_zap_collapsible_sptes(struct kvm * kvm,const struct kvm_memory_slot * slot)7112 static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
7113 					   const struct kvm_memory_slot *slot)
7114 {
7115 	/*
7116 	 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
7117 	 * pages that are already mapped at the maximum hugepage level.
7118 	 */
7119 	if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
7120 			    PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
7121 		kvm_flush_remote_tlbs_memslot(kvm, slot);
7122 }
7123 
kvm_mmu_recover_huge_pages(struct kvm * kvm,const struct kvm_memory_slot * slot)7124 void kvm_mmu_recover_huge_pages(struct kvm *kvm,
7125 				const struct kvm_memory_slot *slot)
7126 {
7127 	if (kvm_memslots_have_rmaps(kvm)) {
7128 		write_lock(&kvm->mmu_lock);
7129 		kvm_rmap_zap_collapsible_sptes(kvm, slot);
7130 		write_unlock(&kvm->mmu_lock);
7131 	}
7132 
7133 	if (tdp_mmu_enabled) {
7134 		read_lock(&kvm->mmu_lock);
7135 		kvm_tdp_mmu_recover_huge_pages(kvm, slot);
7136 		read_unlock(&kvm->mmu_lock);
7137 	}
7138 }
7139 
kvm_mmu_slot_leaf_clear_dirty(struct kvm * kvm,const struct kvm_memory_slot * memslot)7140 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
7141 				   const struct kvm_memory_slot *memslot)
7142 {
7143 	if (kvm_memslots_have_rmaps(kvm)) {
7144 		write_lock(&kvm->mmu_lock);
7145 		/*
7146 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
7147 		 * support dirty logging at a 4k granularity.
7148 		 */
7149 		walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
7150 		write_unlock(&kvm->mmu_lock);
7151 	}
7152 
7153 	if (tdp_mmu_enabled) {
7154 		read_lock(&kvm->mmu_lock);
7155 		kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
7156 		read_unlock(&kvm->mmu_lock);
7157 	}
7158 
7159 	/*
7160 	 * The caller will flush the TLBs after this function returns.
7161 	 *
7162 	 * It's also safe to flush TLBs out of mmu lock here as currently this
7163 	 * function is only used for dirty logging, in which case flushing TLB
7164 	 * out of mmu lock also guarantees no dirty pages will be lost in
7165 	 * dirty_bitmap.
7166 	 */
7167 }
7168 
kvm_mmu_zap_all(struct kvm * kvm)7169 static void kvm_mmu_zap_all(struct kvm *kvm)
7170 {
7171 	struct kvm_mmu_page *sp, *node;
7172 	LIST_HEAD(invalid_list);
7173 	int ign;
7174 
7175 	write_lock(&kvm->mmu_lock);
7176 restart:
7177 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
7178 		if (WARN_ON_ONCE(sp->role.invalid))
7179 			continue;
7180 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
7181 			goto restart;
7182 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
7183 			goto restart;
7184 	}
7185 
7186 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
7187 
7188 	if (tdp_mmu_enabled)
7189 		kvm_tdp_mmu_zap_all(kvm);
7190 
7191 	write_unlock(&kvm->mmu_lock);
7192 }
7193 
kvm_arch_flush_shadow_all(struct kvm * kvm)7194 void kvm_arch_flush_shadow_all(struct kvm *kvm)
7195 {
7196 	kvm_mmu_zap_all(kvm);
7197 }
7198 
kvm_mmu_zap_memslot_pages_and_flush(struct kvm * kvm,struct kvm_memory_slot * slot,bool flush)7199 static void kvm_mmu_zap_memslot_pages_and_flush(struct kvm *kvm,
7200 						struct kvm_memory_slot *slot,
7201 						bool flush)
7202 {
7203 	LIST_HEAD(invalid_list);
7204 	unsigned long i;
7205 
7206 	if (list_empty(&kvm->arch.active_mmu_pages))
7207 		goto out_flush;
7208 
7209 	/*
7210 	 * Since accounting information is stored in struct kvm_arch_memory_slot,
7211 	 * all MMU pages that are shadowing guest PTEs must be zapped before the
7212 	 * memslot is deleted, as freeing such pages after the memslot is freed
7213 	 * will result in use-after-free, e.g. in unaccount_shadowed().
7214 	 */
7215 	for (i = 0; i < slot->npages; i++) {
7216 		struct kvm_mmu_page *sp;
7217 		gfn_t gfn = slot->base_gfn + i;
7218 
7219 		for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn)
7220 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7221 
7222 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7223 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7224 			flush = false;
7225 			cond_resched_rwlock_write(&kvm->mmu_lock);
7226 		}
7227 	}
7228 
7229 out_flush:
7230 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7231 }
7232 
kvm_mmu_zap_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)7233 static void kvm_mmu_zap_memslot(struct kvm *kvm,
7234 				struct kvm_memory_slot *slot)
7235 {
7236 	struct kvm_gfn_range range = {
7237 		.slot = slot,
7238 		.start = slot->base_gfn,
7239 		.end = slot->base_gfn + slot->npages,
7240 		.may_block = true,
7241 	};
7242 	bool flush;
7243 
7244 	write_lock(&kvm->mmu_lock);
7245 	flush = kvm_unmap_gfn_range(kvm, &range);
7246 	kvm_mmu_zap_memslot_pages_and_flush(kvm, slot, flush);
7247 	write_unlock(&kvm->mmu_lock);
7248 }
7249 
kvm_memslot_flush_zap_all(struct kvm * kvm)7250 static inline bool kvm_memslot_flush_zap_all(struct kvm *kvm)
7251 {
7252 	return kvm->arch.vm_type == KVM_X86_DEFAULT_VM &&
7253 	       kvm_check_has_quirk(kvm, KVM_X86_QUIRK_SLOT_ZAP_ALL);
7254 }
7255 
kvm_arch_flush_shadow_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)7256 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
7257 				   struct kvm_memory_slot *slot)
7258 {
7259 	if (kvm_memslot_flush_zap_all(kvm))
7260 		kvm_mmu_zap_all_fast(kvm);
7261 	else
7262 		kvm_mmu_zap_memslot(kvm, slot);
7263 }
7264 
kvm_mmu_invalidate_mmio_sptes(struct kvm * kvm,u64 gen)7265 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
7266 {
7267 	WARN_ON_ONCE(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
7268 
7269 	gen &= MMIO_SPTE_GEN_MASK;
7270 
7271 	/*
7272 	 * Generation numbers are incremented in multiples of the number of
7273 	 * address spaces in order to provide unique generations across all
7274 	 * address spaces.  Strip what is effectively the address space
7275 	 * modifier prior to checking for a wrap of the MMIO generation so
7276 	 * that a wrap in any address space is detected.
7277 	 */
7278 	gen &= ~((u64)kvm_arch_nr_memslot_as_ids(kvm) - 1);
7279 
7280 	/*
7281 	 * The very rare case: if the MMIO generation number has wrapped,
7282 	 * zap all shadow pages.
7283 	 */
7284 	if (unlikely(gen == 0)) {
7285 		kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
7286 		kvm_mmu_zap_all_fast(kvm);
7287 	}
7288 }
7289 
mmu_destroy_caches(void)7290 static void mmu_destroy_caches(void)
7291 {
7292 	kmem_cache_destroy(pte_list_desc_cache);
7293 	kmem_cache_destroy(mmu_page_header_cache);
7294 }
7295 
kvm_wake_nx_recovery_thread(struct kvm * kvm)7296 static void kvm_wake_nx_recovery_thread(struct kvm *kvm)
7297 {
7298 	/*
7299 	 * The NX recovery thread is spawned on-demand at the first KVM_RUN and
7300 	 * may not be valid even though the VM is globally visible.  Do nothing,
7301 	 * as such a VM can't have any possible NX huge pages.
7302 	 */
7303 	struct vhost_task *nx_thread = READ_ONCE(kvm->arch.nx_huge_page_recovery_thread);
7304 
7305 	if (nx_thread)
7306 		vhost_task_wake(nx_thread);
7307 }
7308 
get_nx_huge_pages(char * buffer,const struct kernel_param * kp)7309 static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp)
7310 {
7311 	if (nx_hugepage_mitigation_hard_disabled)
7312 		return sysfs_emit(buffer, "never\n");
7313 
7314 	return param_get_bool(buffer, kp);
7315 }
7316 
get_nx_auto_mode(void)7317 static bool get_nx_auto_mode(void)
7318 {
7319 	/* Return true when CPU has the bug, and mitigations are ON */
7320 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
7321 }
7322 
__set_nx_huge_pages(bool val)7323 static void __set_nx_huge_pages(bool val)
7324 {
7325 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
7326 }
7327 
set_nx_huge_pages(const char * val,const struct kernel_param * kp)7328 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
7329 {
7330 	bool old_val = nx_huge_pages;
7331 	bool new_val;
7332 
7333 	if (nx_hugepage_mitigation_hard_disabled)
7334 		return -EPERM;
7335 
7336 	/* In "auto" mode deploy workaround only if CPU has the bug. */
7337 	if (sysfs_streq(val, "off")) {
7338 		new_val = 0;
7339 	} else if (sysfs_streq(val, "force")) {
7340 		new_val = 1;
7341 	} else if (sysfs_streq(val, "auto")) {
7342 		new_val = get_nx_auto_mode();
7343 	} else if (sysfs_streq(val, "never")) {
7344 		new_val = 0;
7345 
7346 		mutex_lock(&kvm_lock);
7347 		if (!list_empty(&vm_list)) {
7348 			mutex_unlock(&kvm_lock);
7349 			return -EBUSY;
7350 		}
7351 		nx_hugepage_mitigation_hard_disabled = true;
7352 		mutex_unlock(&kvm_lock);
7353 	} else if (kstrtobool(val, &new_val) < 0) {
7354 		return -EINVAL;
7355 	}
7356 
7357 	__set_nx_huge_pages(new_val);
7358 
7359 	if (new_val != old_val) {
7360 		struct kvm *kvm;
7361 
7362 		mutex_lock(&kvm_lock);
7363 
7364 		list_for_each_entry(kvm, &vm_list, vm_list) {
7365 			mutex_lock(&kvm->slots_lock);
7366 			kvm_mmu_zap_all_fast(kvm);
7367 			mutex_unlock(&kvm->slots_lock);
7368 
7369 			kvm_wake_nx_recovery_thread(kvm);
7370 		}
7371 		mutex_unlock(&kvm_lock);
7372 	}
7373 
7374 	return 0;
7375 }
7376 
7377 /*
7378  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
7379  * its default value of -1 is technically undefined behavior for a boolean.
7380  * Forward the module init call to SPTE code so that it too can handle module
7381  * params that need to be resolved/snapshot.
7382  */
kvm_mmu_x86_module_init(void)7383 void __init kvm_mmu_x86_module_init(void)
7384 {
7385 	if (nx_huge_pages == -1)
7386 		__set_nx_huge_pages(get_nx_auto_mode());
7387 
7388 	/*
7389 	 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
7390 	 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
7391 	 * when the vendor module is loaded.
7392 	 */
7393 	tdp_mmu_allowed = tdp_mmu_enabled;
7394 
7395 	kvm_mmu_spte_module_init();
7396 }
7397 
7398 /*
7399  * The bulk of the MMU initialization is deferred until the vendor module is
7400  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
7401  * to be reset when a potentially different vendor module is loaded.
7402  */
kvm_mmu_vendor_module_init(void)7403 int kvm_mmu_vendor_module_init(void)
7404 {
7405 	int ret = -ENOMEM;
7406 
7407 	/*
7408 	 * MMU roles use union aliasing which is, generally speaking, an
7409 	 * undefined behavior. However, we supposedly know how compilers behave
7410 	 * and the current status quo is unlikely to change. Guardians below are
7411 	 * supposed to let us know if the assumption becomes false.
7412 	 */
7413 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
7414 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
7415 	BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
7416 
7417 	kvm_mmu_reset_all_pte_masks();
7418 
7419 	pte_list_desc_cache = KMEM_CACHE(pte_list_desc, SLAB_ACCOUNT);
7420 	if (!pte_list_desc_cache)
7421 		goto out;
7422 
7423 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
7424 						  sizeof(struct kvm_mmu_page),
7425 						  0, SLAB_ACCOUNT, NULL);
7426 	if (!mmu_page_header_cache)
7427 		goto out;
7428 
7429 	return 0;
7430 
7431 out:
7432 	mmu_destroy_caches();
7433 	return ret;
7434 }
7435 
kvm_mmu_destroy(struct kvm_vcpu * vcpu)7436 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
7437 {
7438 	kvm_mmu_unload(vcpu);
7439 	if (tdp_mmu_enabled) {
7440 		read_lock(&vcpu->kvm->mmu_lock);
7441 		mmu_free_root_page(vcpu->kvm, &vcpu->arch.mmu->mirror_root_hpa,
7442 				   NULL);
7443 		read_unlock(&vcpu->kvm->mmu_lock);
7444 	}
7445 	free_mmu_pages(&vcpu->arch.root_mmu);
7446 	free_mmu_pages(&vcpu->arch.guest_mmu);
7447 	mmu_free_memory_caches(vcpu);
7448 }
7449 
kvm_mmu_vendor_module_exit(void)7450 void kvm_mmu_vendor_module_exit(void)
7451 {
7452 	mmu_destroy_caches();
7453 }
7454 
7455 /*
7456  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
7457  * select a halving time of 1 hour".  Returns true if recovery is enabled.
7458  */
calc_nx_huge_pages_recovery_period(uint * period)7459 static bool calc_nx_huge_pages_recovery_period(uint *period)
7460 {
7461 	/*
7462 	 * Use READ_ONCE to get the params, this may be called outside of the
7463 	 * param setters, e.g. by the kthread to compute its next timeout.
7464 	 */
7465 	bool enabled = READ_ONCE(nx_huge_pages);
7466 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7467 
7468 	if (!enabled || !ratio)
7469 		return false;
7470 
7471 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
7472 	if (!*period) {
7473 		/* Make sure the period is not less than one second.  */
7474 		ratio = min(ratio, 3600u);
7475 		*period = 60 * 60 * 1000 / ratio;
7476 	}
7477 	return true;
7478 }
7479 
set_nx_huge_pages_recovery_param(const char * val,const struct kernel_param * kp)7480 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
7481 {
7482 	bool was_recovery_enabled, is_recovery_enabled;
7483 	uint old_period, new_period;
7484 	int err;
7485 
7486 	if (nx_hugepage_mitigation_hard_disabled)
7487 		return -EPERM;
7488 
7489 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
7490 
7491 	err = param_set_uint(val, kp);
7492 	if (err)
7493 		return err;
7494 
7495 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
7496 
7497 	if (is_recovery_enabled &&
7498 	    (!was_recovery_enabled || old_period > new_period)) {
7499 		struct kvm *kvm;
7500 
7501 		mutex_lock(&kvm_lock);
7502 
7503 		list_for_each_entry(kvm, &vm_list, vm_list)
7504 			kvm_wake_nx_recovery_thread(kvm);
7505 
7506 		mutex_unlock(&kvm_lock);
7507 	}
7508 
7509 	return err;
7510 }
7511 
kvm_recover_nx_huge_pages(struct kvm * kvm)7512 static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7513 {
7514 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7515 	struct kvm_memory_slot *slot;
7516 	int rcu_idx;
7517 	struct kvm_mmu_page *sp;
7518 	unsigned int ratio;
7519 	LIST_HEAD(invalid_list);
7520 	bool flush = false;
7521 	ulong to_zap;
7522 
7523 	rcu_idx = srcu_read_lock(&kvm->srcu);
7524 	write_lock(&kvm->mmu_lock);
7525 
7526 	/*
7527 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7528 	 * be done under RCU protection, because the pages are freed via RCU
7529 	 * callback.
7530 	 */
7531 	rcu_read_lock();
7532 
7533 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7534 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
7535 	for ( ; to_zap; --to_zap) {
7536 		if (list_empty(&kvm->arch.possible_nx_huge_pages))
7537 			break;
7538 
7539 		/*
7540 		 * We use a separate list instead of just using active_mmu_pages
7541 		 * because the number of shadow pages that be replaced with an
7542 		 * NX huge page is expected to be relatively small compared to
7543 		 * the total number of shadow pages.  And because the TDP MMU
7544 		 * doesn't use active_mmu_pages.
7545 		 */
7546 		sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7547 				      struct kvm_mmu_page,
7548 				      possible_nx_huge_page_link);
7549 		WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7550 		WARN_ON_ONCE(!sp->role.direct);
7551 
7552 		/*
7553 		 * Unaccount and do not attempt to recover any NX Huge Pages
7554 		 * that are being dirty tracked, as they would just be faulted
7555 		 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7556 		 * recovered, along with all the other huge pages in the slot,
7557 		 * when dirty logging is disabled.
7558 		 *
7559 		 * Since gfn_to_memslot() is relatively expensive, it helps to
7560 		 * skip it if it the test cannot possibly return true.  On the
7561 		 * other hand, if any memslot has logging enabled, chances are
7562 		 * good that all of them do, in which case unaccount_nx_huge_page()
7563 		 * is much cheaper than zapping the page.
7564 		 *
7565 		 * If a memslot update is in progress, reading an incorrect value
7566 		 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
7567 		 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
7568 		 * it is becoming nonzero, the page will be zapped unnecessarily.
7569 		 * Either way, this only affects efficiency in racy situations,
7570 		 * and not correctness.
7571 		 */
7572 		slot = NULL;
7573 		if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7574 			struct kvm_memslots *slots;
7575 
7576 			slots = kvm_memslots_for_spte_role(kvm, sp->role);
7577 			slot = __gfn_to_memslot(slots, sp->gfn);
7578 			WARN_ON_ONCE(!slot);
7579 		}
7580 
7581 		if (slot && kvm_slot_dirty_track_enabled(slot))
7582 			unaccount_nx_huge_page(kvm, sp);
7583 		else if (is_tdp_mmu_page(sp))
7584 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
7585 		else
7586 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7587 		WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7588 
7589 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7590 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7591 			rcu_read_unlock();
7592 
7593 			cond_resched_rwlock_write(&kvm->mmu_lock);
7594 			flush = false;
7595 
7596 			rcu_read_lock();
7597 		}
7598 	}
7599 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7600 
7601 	rcu_read_unlock();
7602 
7603 	write_unlock(&kvm->mmu_lock);
7604 	srcu_read_unlock(&kvm->srcu, rcu_idx);
7605 }
7606 
kvm_nx_huge_page_recovery_worker_kill(void * data)7607 static void kvm_nx_huge_page_recovery_worker_kill(void *data)
7608 {
7609 }
7610 
kvm_nx_huge_page_recovery_worker(void * data)7611 static bool kvm_nx_huge_page_recovery_worker(void *data)
7612 {
7613 	struct kvm *kvm = data;
7614 	bool enabled;
7615 	uint period;
7616 	long remaining_time;
7617 
7618 	enabled = calc_nx_huge_pages_recovery_period(&period);
7619 	if (!enabled)
7620 		return false;
7621 
7622 	remaining_time = kvm->arch.nx_huge_page_last + msecs_to_jiffies(period)
7623 		- get_jiffies_64();
7624 	if (remaining_time > 0) {
7625 		schedule_timeout(remaining_time);
7626 		/* check for signals and come back */
7627 		return true;
7628 	}
7629 
7630 	__set_current_state(TASK_RUNNING);
7631 	kvm_recover_nx_huge_pages(kvm);
7632 	kvm->arch.nx_huge_page_last = get_jiffies_64();
7633 	return true;
7634 }
7635 
kvm_mmu_start_lpage_recovery(struct once * once)7636 static int kvm_mmu_start_lpage_recovery(struct once *once)
7637 {
7638 	struct kvm_arch *ka = container_of(once, struct kvm_arch, nx_once);
7639 	struct kvm *kvm = container_of(ka, struct kvm, arch);
7640 	struct vhost_task *nx_thread;
7641 
7642 	kvm->arch.nx_huge_page_last = get_jiffies_64();
7643 	nx_thread = vhost_task_create(kvm_nx_huge_page_recovery_worker,
7644 				      kvm_nx_huge_page_recovery_worker_kill,
7645 				      kvm, "kvm-nx-lpage-recovery");
7646 
7647 	if (IS_ERR(nx_thread))
7648 		return PTR_ERR(nx_thread);
7649 
7650 	vhost_task_start(nx_thread);
7651 
7652 	/* Make the task visible only once it is fully started. */
7653 	WRITE_ONCE(kvm->arch.nx_huge_page_recovery_thread, nx_thread);
7654 	return 0;
7655 }
7656 
kvm_mmu_post_init_vm(struct kvm * kvm)7657 int kvm_mmu_post_init_vm(struct kvm *kvm)
7658 {
7659 	if (nx_hugepage_mitigation_hard_disabled)
7660 		return 0;
7661 
7662 	return call_once(&kvm->arch.nx_once, kvm_mmu_start_lpage_recovery);
7663 }
7664 
kvm_mmu_pre_destroy_vm(struct kvm * kvm)7665 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7666 {
7667 	if (kvm->arch.nx_huge_page_recovery_thread)
7668 		vhost_task_stop(kvm->arch.nx_huge_page_recovery_thread);
7669 }
7670 
7671 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
kvm_arch_pre_set_memory_attributes(struct kvm * kvm,struct kvm_gfn_range * range)7672 bool kvm_arch_pre_set_memory_attributes(struct kvm *kvm,
7673 					struct kvm_gfn_range *range)
7674 {
7675 	/*
7676 	 * Zap SPTEs even if the slot can't be mapped PRIVATE.  KVM x86 only
7677 	 * supports KVM_MEMORY_ATTRIBUTE_PRIVATE, and so it *seems* like KVM
7678 	 * can simply ignore such slots.  But if userspace is making memory
7679 	 * PRIVATE, then KVM must prevent the guest from accessing the memory
7680 	 * as shared.  And if userspace is making memory SHARED and this point
7681 	 * is reached, then at least one page within the range was previously
7682 	 * PRIVATE, i.e. the slot's possible hugepage ranges are changing.
7683 	 * Zapping SPTEs in this case ensures KVM will reassess whether or not
7684 	 * a hugepage can be used for affected ranges.
7685 	 */
7686 	if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
7687 		return false;
7688 
7689 	/* Unmap the old attribute page. */
7690 	if (range->arg.attributes & KVM_MEMORY_ATTRIBUTE_PRIVATE)
7691 		range->attr_filter = KVM_FILTER_SHARED;
7692 	else
7693 		range->attr_filter = KVM_FILTER_PRIVATE;
7694 
7695 	return kvm_unmap_gfn_range(kvm, range);
7696 }
7697 
hugepage_test_mixed(struct kvm_memory_slot * slot,gfn_t gfn,int level)7698 static bool hugepage_test_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
7699 				int level)
7700 {
7701 	return lpage_info_slot(gfn, slot, level)->disallow_lpage & KVM_LPAGE_MIXED_FLAG;
7702 }
7703 
hugepage_clear_mixed(struct kvm_memory_slot * slot,gfn_t gfn,int level)7704 static void hugepage_clear_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
7705 				 int level)
7706 {
7707 	lpage_info_slot(gfn, slot, level)->disallow_lpage &= ~KVM_LPAGE_MIXED_FLAG;
7708 }
7709 
hugepage_set_mixed(struct kvm_memory_slot * slot,gfn_t gfn,int level)7710 static void hugepage_set_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
7711 			       int level)
7712 {
7713 	lpage_info_slot(gfn, slot, level)->disallow_lpage |= KVM_LPAGE_MIXED_FLAG;
7714 }
7715 
hugepage_has_attrs(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn,int level,unsigned long attrs)7716 static bool hugepage_has_attrs(struct kvm *kvm, struct kvm_memory_slot *slot,
7717 			       gfn_t gfn, int level, unsigned long attrs)
7718 {
7719 	const unsigned long start = gfn;
7720 	const unsigned long end = start + KVM_PAGES_PER_HPAGE(level);
7721 
7722 	if (level == PG_LEVEL_2M)
7723 		return kvm_range_has_memory_attributes(kvm, start, end, ~0, attrs);
7724 
7725 	for (gfn = start; gfn < end; gfn += KVM_PAGES_PER_HPAGE(level - 1)) {
7726 		if (hugepage_test_mixed(slot, gfn, level - 1) ||
7727 		    attrs != kvm_get_memory_attributes(kvm, gfn))
7728 			return false;
7729 	}
7730 	return true;
7731 }
7732 
kvm_arch_post_set_memory_attributes(struct kvm * kvm,struct kvm_gfn_range * range)7733 bool kvm_arch_post_set_memory_attributes(struct kvm *kvm,
7734 					 struct kvm_gfn_range *range)
7735 {
7736 	unsigned long attrs = range->arg.attributes;
7737 	struct kvm_memory_slot *slot = range->slot;
7738 	int level;
7739 
7740 	lockdep_assert_held_write(&kvm->mmu_lock);
7741 	lockdep_assert_held(&kvm->slots_lock);
7742 
7743 	/*
7744 	 * Calculate which ranges can be mapped with hugepages even if the slot
7745 	 * can't map memory PRIVATE.  KVM mustn't create a SHARED hugepage over
7746 	 * a range that has PRIVATE GFNs, and conversely converting a range to
7747 	 * SHARED may now allow hugepages.
7748 	 */
7749 	if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
7750 		return false;
7751 
7752 	/*
7753 	 * The sequence matters here: upper levels consume the result of lower
7754 	 * level's scanning.
7755 	 */
7756 	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
7757 		gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
7758 		gfn_t gfn = gfn_round_for_level(range->start, level);
7759 
7760 		/* Process the head page if it straddles the range. */
7761 		if (gfn != range->start || gfn + nr_pages > range->end) {
7762 			/*
7763 			 * Skip mixed tracking if the aligned gfn isn't covered
7764 			 * by the memslot, KVM can't use a hugepage due to the
7765 			 * misaligned address regardless of memory attributes.
7766 			 */
7767 			if (gfn >= slot->base_gfn &&
7768 			    gfn + nr_pages <= slot->base_gfn + slot->npages) {
7769 				if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
7770 					hugepage_clear_mixed(slot, gfn, level);
7771 				else
7772 					hugepage_set_mixed(slot, gfn, level);
7773 			}
7774 			gfn += nr_pages;
7775 		}
7776 
7777 		/*
7778 		 * Pages entirely covered by the range are guaranteed to have
7779 		 * only the attributes which were just set.
7780 		 */
7781 		for ( ; gfn + nr_pages <= range->end; gfn += nr_pages)
7782 			hugepage_clear_mixed(slot, gfn, level);
7783 
7784 		/*
7785 		 * Process the last tail page if it straddles the range and is
7786 		 * contained by the memslot.  Like the head page, KVM can't
7787 		 * create a hugepage if the slot size is misaligned.
7788 		 */
7789 		if (gfn < range->end &&
7790 		    (gfn + nr_pages) <= (slot->base_gfn + slot->npages)) {
7791 			if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
7792 				hugepage_clear_mixed(slot, gfn, level);
7793 			else
7794 				hugepage_set_mixed(slot, gfn, level);
7795 		}
7796 	}
7797 	return false;
7798 }
7799 
kvm_mmu_init_memslot_memory_attributes(struct kvm * kvm,struct kvm_memory_slot * slot)7800 void kvm_mmu_init_memslot_memory_attributes(struct kvm *kvm,
7801 					    struct kvm_memory_slot *slot)
7802 {
7803 	int level;
7804 
7805 	if (!kvm_arch_has_private_mem(kvm))
7806 		return;
7807 
7808 	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
7809 		/*
7810 		 * Don't bother tracking mixed attributes for pages that can't
7811 		 * be huge due to alignment, i.e. process only pages that are
7812 		 * entirely contained by the memslot.
7813 		 */
7814 		gfn_t end = gfn_round_for_level(slot->base_gfn + slot->npages, level);
7815 		gfn_t start = gfn_round_for_level(slot->base_gfn, level);
7816 		gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
7817 		gfn_t gfn;
7818 
7819 		if (start < slot->base_gfn)
7820 			start += nr_pages;
7821 
7822 		/*
7823 		 * Unlike setting attributes, every potential hugepage needs to
7824 		 * be manually checked as the attributes may already be mixed.
7825 		 */
7826 		for (gfn = start; gfn < end; gfn += nr_pages) {
7827 			unsigned long attrs = kvm_get_memory_attributes(kvm, gfn);
7828 
7829 			if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
7830 				hugepage_clear_mixed(slot, gfn, level);
7831 			else
7832 				hugepage_set_mixed(slot, gfn, level);
7833 		}
7834 	}
7835 }
7836 #endif
7837