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