• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * MMU support
8  *
9  * Copyright (C) 2006 Qumranet, Inc.
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  *
12  * Authors:
13  *   Yaniv Kamay  <yaniv@qumranet.com>
14  *   Avi Kivity   <avi@qumranet.com>
15  *
16  * This work is licensed under the terms of the GNU GPL, version 2.  See
17  * the COPYING file in the top-level directory.
18  *
19  */
20 
21 #include "irq.h"
22 #include "mmu.h"
23 #include "x86.h"
24 #include "kvm_cache_regs.h"
25 #include "cpuid.h"
26 
27 #include <linux/kvm_host.h>
28 #include <linux/types.h>
29 #include <linux/string.h>
30 #include <linux/mm.h>
31 #include <linux/highmem.h>
32 #include <linux/moduleparam.h>
33 #include <linux/export.h>
34 #include <linux/swap.h>
35 #include <linux/hugetlb.h>
36 #include <linux/compiler.h>
37 #include <linux/srcu.h>
38 #include <linux/slab.h>
39 #include <linux/sched/signal.h>
40 #include <linux/uaccess.h>
41 #include <linux/hash.h>
42 #include <linux/kern_levels.h>
43 #include <linux/kthread.h>
44 
45 #include <asm/page.h>
46 #include <asm/pat.h>
47 #include <asm/cmpxchg.h>
48 #include <asm/io.h>
49 #include <asm/vmx.h>
50 #include <asm/kvm_page_track.h>
51 #include "trace.h"
52 
53 extern bool itlb_multihit_kvm_mitigation;
54 
55 static int __read_mostly nx_huge_pages = -1;
56 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
57 
58 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
59 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp);
60 
61 static struct kernel_param_ops nx_huge_pages_ops = {
62 	.set = set_nx_huge_pages,
63 	.get = param_get_bool,
64 };
65 
66 static struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
67 	.set = set_nx_huge_pages_recovery_ratio,
68 	.get = param_get_uint,
69 };
70 
71 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
72 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
73 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
74 		&nx_huge_pages_recovery_ratio, 0644);
75 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
76 
77 /*
78  * When setting this variable to true it enables Two-Dimensional-Paging
79  * where the hardware walks 2 page tables:
80  * 1. the guest-virtual to guest-physical
81  * 2. while doing 1. it walks guest-physical to host-physical
82  * If the hardware supports that we don't need to do shadow paging.
83  */
84 bool tdp_enabled = false;
85 
86 enum {
87 	AUDIT_PRE_PAGE_FAULT,
88 	AUDIT_POST_PAGE_FAULT,
89 	AUDIT_PRE_PTE_WRITE,
90 	AUDIT_POST_PTE_WRITE,
91 	AUDIT_PRE_SYNC,
92 	AUDIT_POST_SYNC
93 };
94 
95 #undef MMU_DEBUG
96 
97 #ifdef MMU_DEBUG
98 static bool dbg = 0;
99 module_param(dbg, bool, 0644);
100 
101 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
102 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
103 #define MMU_WARN_ON(x) WARN_ON(x)
104 #else
105 #define pgprintk(x...) do { } while (0)
106 #define rmap_printk(x...) do { } while (0)
107 #define MMU_WARN_ON(x) do { } while (0)
108 #endif
109 
110 #define PTE_PREFETCH_NUM		8
111 
112 #define PT_FIRST_AVAIL_BITS_SHIFT 10
113 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
114 
115 #define PT64_LEVEL_BITS 9
116 
117 #define PT64_LEVEL_SHIFT(level) \
118 		(PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
119 
120 #define PT64_INDEX(address, level)\
121 	(((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
122 
123 
124 #define PT32_LEVEL_BITS 10
125 
126 #define PT32_LEVEL_SHIFT(level) \
127 		(PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
128 
129 #define PT32_LVL_OFFSET_MASK(level) \
130 	(PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
131 						* PT32_LEVEL_BITS))) - 1))
132 
133 #define PT32_INDEX(address, level)\
134 	(((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
135 
136 
137 #define PT64_BASE_ADDR_MASK __sme_clr((((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)))
138 #define PT64_DIR_BASE_ADDR_MASK \
139 	(PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
140 #define PT64_LVL_ADDR_MASK(level) \
141 	(PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
142 						* PT64_LEVEL_BITS))) - 1))
143 #define PT64_LVL_OFFSET_MASK(level) \
144 	(PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
145 						* PT64_LEVEL_BITS))) - 1))
146 
147 #define PT32_BASE_ADDR_MASK PAGE_MASK
148 #define PT32_DIR_BASE_ADDR_MASK \
149 	(PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
150 #define PT32_LVL_ADDR_MASK(level) \
151 	(PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
152 					    * PT32_LEVEL_BITS))) - 1))
153 
154 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
155 			| shadow_x_mask | shadow_nx_mask | shadow_me_mask)
156 
157 #define ACC_EXEC_MASK    1
158 #define ACC_WRITE_MASK   PT_WRITABLE_MASK
159 #define ACC_USER_MASK    PT_USER_MASK
160 #define ACC_ALL          (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
161 
162 /* The mask for the R/X bits in EPT PTEs */
163 #define PT64_EPT_READABLE_MASK			0x1ull
164 #define PT64_EPT_EXECUTABLE_MASK		0x4ull
165 
166 #include <trace/events/kvm.h>
167 
168 #define SPTE_HOST_WRITEABLE	(1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
169 #define SPTE_MMU_WRITEABLE	(1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
170 
171 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
172 
173 /* make pte_list_desc fit well in cache line */
174 #define PTE_LIST_EXT 3
175 
176 /*
177  * Return values of handle_mmio_page_fault and mmu.page_fault:
178  * RET_PF_RETRY: let CPU fault again on the address.
179  * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
180  *
181  * For handle_mmio_page_fault only:
182  * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
183  */
184 enum {
185 	RET_PF_RETRY = 0,
186 	RET_PF_EMULATE = 1,
187 	RET_PF_INVALID = 2,
188 };
189 
190 struct pte_list_desc {
191 	u64 *sptes[PTE_LIST_EXT];
192 	struct pte_list_desc *more;
193 };
194 
195 struct kvm_shadow_walk_iterator {
196 	u64 addr;
197 	hpa_t shadow_addr;
198 	u64 *sptep;
199 	int level;
200 	unsigned index;
201 };
202 
203 static const union kvm_mmu_page_role mmu_base_role_mask = {
204 	.cr0_wp = 1,
205 	.cr4_pae = 1,
206 	.nxe = 1,
207 	.smep_andnot_wp = 1,
208 	.smap_andnot_wp = 1,
209 	.smm = 1,
210 	.guest_mode = 1,
211 	.ad_disabled = 1,
212 };
213 
214 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
215 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
216 					 (_root), (_addr));                \
217 	     shadow_walk_okay(&(_walker));			           \
218 	     shadow_walk_next(&(_walker)))
219 
220 #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
221 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
222 	     shadow_walk_okay(&(_walker));			\
223 	     shadow_walk_next(&(_walker)))
224 
225 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
226 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
227 	     shadow_walk_okay(&(_walker)) &&				\
228 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
229 	     __shadow_walk_next(&(_walker), spte))
230 
231 static struct kmem_cache *pte_list_desc_cache;
232 static struct kmem_cache *mmu_page_header_cache;
233 static struct percpu_counter kvm_total_used_mmu_pages;
234 
235 static u64 __read_mostly shadow_nx_mask;
236 static u64 __read_mostly shadow_x_mask;	/* mutual exclusive with nx_mask */
237 static u64 __read_mostly shadow_user_mask;
238 static u64 __read_mostly shadow_accessed_mask;
239 static u64 __read_mostly shadow_dirty_mask;
240 static u64 __read_mostly shadow_mmio_mask;
241 static u64 __read_mostly shadow_mmio_value;
242 static u64 __read_mostly shadow_present_mask;
243 static u64 __read_mostly shadow_me_mask;
244 
245 /*
246  * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
247  * Non-present SPTEs with shadow_acc_track_value set are in place for access
248  * tracking.
249  */
250 static u64 __read_mostly shadow_acc_track_mask;
251 static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
252 
253 /*
254  * The mask/shift to use for saving the original R/X bits when marking the PTE
255  * as not-present for access tracking purposes. We do not save the W bit as the
256  * PTEs being access tracked also need to be dirty tracked, so the W bit will be
257  * restored only when a write is attempted to the page.
258  */
259 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
260 						    PT64_EPT_EXECUTABLE_MASK;
261 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
262 
263 /*
264  * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
265  * to guard against L1TF attacks.
266  */
267 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
268 
269 /*
270  * The number of high-order 1 bits to use in the mask above.
271  */
272 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
273 
274 /*
275  * In some cases, we need to preserve the GFN of a non-present or reserved
276  * SPTE when we usurp the upper five bits of the physical address space to
277  * defend against L1TF, e.g. for MMIO SPTEs.  To preserve the GFN, we'll
278  * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
279  * left into the reserved bits, i.e. the GFN in the SPTE will be split into
280  * high and low parts.  This mask covers the lower bits of the GFN.
281  */
282 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
283 
284 /*
285  * The number of non-reserved physical address bits irrespective of features
286  * that repurpose legal bits, e.g. MKTME.
287  */
288 static u8 __read_mostly shadow_phys_bits;
289 
290 static void mmu_spte_set(u64 *sptep, u64 spte);
291 static bool is_executable_pte(u64 spte);
292 static union kvm_mmu_page_role
293 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
294 
295 #define CREATE_TRACE_POINTS
296 #include "mmutrace.h"
297 
298 
kvm_mmu_set_mmio_spte_mask(u64 mmio_mask,u64 mmio_value)299 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
300 {
301 	BUG_ON((mmio_mask & mmio_value) != mmio_value);
302 	WARN_ON(mmio_value & (shadow_nonpresent_or_rsvd_mask << shadow_nonpresent_or_rsvd_mask_len));
303 	WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);
304 	shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
305 	shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
306 }
307 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
308 
is_mmio_spte(u64 spte)309 static bool is_mmio_spte(u64 spte)
310 {
311 	return (spte & shadow_mmio_mask) == shadow_mmio_value;
312 }
313 
sp_ad_disabled(struct kvm_mmu_page * sp)314 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
315 {
316 	return sp->role.ad_disabled;
317 }
318 
spte_ad_enabled(u64 spte)319 static inline bool spte_ad_enabled(u64 spte)
320 {
321 	MMU_WARN_ON(is_mmio_spte(spte));
322 	return !(spte & shadow_acc_track_value);
323 }
324 
is_nx_huge_page_enabled(void)325 static bool is_nx_huge_page_enabled(void)
326 {
327 	return READ_ONCE(nx_huge_pages);
328 }
329 
spte_shadow_accessed_mask(u64 spte)330 static inline u64 spte_shadow_accessed_mask(u64 spte)
331 {
332 	MMU_WARN_ON(is_mmio_spte(spte));
333 	return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
334 }
335 
spte_shadow_dirty_mask(u64 spte)336 static inline u64 spte_shadow_dirty_mask(u64 spte)
337 {
338 	MMU_WARN_ON(is_mmio_spte(spte));
339 	return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
340 }
341 
is_access_track_spte(u64 spte)342 static inline bool is_access_track_spte(u64 spte)
343 {
344 	return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
345 }
346 
347 /*
348  * the low bit of the generation number is always presumed to be zero.
349  * This disables mmio caching during memslot updates.  The concept is
350  * similar to a seqcount but instead of retrying the access we just punt
351  * and ignore the cache.
352  *
353  * spte bits 3-11 are used as bits 1-9 of the generation number,
354  * the bits 52-61 are used as bits 10-19 of the generation number.
355  */
356 #define MMIO_SPTE_GEN_LOW_SHIFT		2
357 #define MMIO_SPTE_GEN_HIGH_SHIFT	52
358 
359 #define MMIO_GEN_SHIFT			20
360 #define MMIO_GEN_LOW_SHIFT		10
361 #define MMIO_GEN_LOW_MASK		((1 << MMIO_GEN_LOW_SHIFT) - 2)
362 #define MMIO_GEN_MASK			((1 << MMIO_GEN_SHIFT) - 1)
363 
generation_mmio_spte_mask(unsigned int gen)364 static u64 generation_mmio_spte_mask(unsigned int gen)
365 {
366 	u64 mask;
367 
368 	WARN_ON(gen & ~MMIO_GEN_MASK);
369 
370 	mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
371 	mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
372 	return mask;
373 }
374 
get_mmio_spte_generation(u64 spte)375 static unsigned int get_mmio_spte_generation(u64 spte)
376 {
377 	unsigned int gen;
378 
379 	spte &= ~shadow_mmio_mask;
380 
381 	gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
382 	gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
383 	return gen;
384 }
385 
kvm_current_mmio_generation(struct kvm_vcpu * vcpu)386 static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
387 {
388 	return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
389 }
390 
mark_mmio_spte(struct kvm_vcpu * vcpu,u64 * sptep,u64 gfn,unsigned access)391 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
392 			   unsigned access)
393 {
394 	unsigned int gen = kvm_current_mmio_generation(vcpu);
395 	u64 mask = generation_mmio_spte_mask(gen);
396 	u64 gpa = gfn << PAGE_SHIFT;
397 
398 	access &= ACC_WRITE_MASK | ACC_USER_MASK;
399 	mask |= shadow_mmio_value | access;
400 	mask |= gpa | shadow_nonpresent_or_rsvd_mask;
401 	mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
402 		<< shadow_nonpresent_or_rsvd_mask_len;
403 
404 	trace_mark_mmio_spte(sptep, gfn, access, gen);
405 	mmu_spte_set(sptep, mask);
406 }
407 
get_mmio_spte_gfn(u64 spte)408 static gfn_t get_mmio_spte_gfn(u64 spte)
409 {
410 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
411 
412 	gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
413 	       & shadow_nonpresent_or_rsvd_mask;
414 
415 	return gpa >> PAGE_SHIFT;
416 }
417 
get_mmio_spte_access(u64 spte)418 static unsigned get_mmio_spte_access(u64 spte)
419 {
420 	u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
421 	return (spte & ~mask) & ~PAGE_MASK;
422 }
423 
set_mmio_spte(struct kvm_vcpu * vcpu,u64 * sptep,gfn_t gfn,kvm_pfn_t pfn,unsigned access)424 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
425 			  kvm_pfn_t pfn, unsigned access)
426 {
427 	if (unlikely(is_noslot_pfn(pfn))) {
428 		mark_mmio_spte(vcpu, sptep, gfn, access);
429 		return true;
430 	}
431 
432 	return false;
433 }
434 
check_mmio_spte(struct kvm_vcpu * vcpu,u64 spte)435 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
436 {
437 	unsigned int kvm_gen, spte_gen;
438 
439 	kvm_gen = kvm_current_mmio_generation(vcpu);
440 	spte_gen = get_mmio_spte_generation(spte);
441 
442 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
443 	return likely(kvm_gen == spte_gen);
444 }
445 
446 /*
447  * Sets the shadow PTE masks used by the MMU.
448  *
449  * Assumptions:
450  *  - Setting either @accessed_mask or @dirty_mask requires setting both
451  *  - At least one of @accessed_mask or @acc_track_mask must be set
452  */
kvm_mmu_set_mask_ptes(u64 user_mask,u64 accessed_mask,u64 dirty_mask,u64 nx_mask,u64 x_mask,u64 p_mask,u64 acc_track_mask,u64 me_mask)453 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
454 		u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
455 		u64 acc_track_mask, u64 me_mask)
456 {
457 	BUG_ON(!dirty_mask != !accessed_mask);
458 	BUG_ON(!accessed_mask && !acc_track_mask);
459 	BUG_ON(acc_track_mask & shadow_acc_track_value);
460 
461 	shadow_user_mask = user_mask;
462 	shadow_accessed_mask = accessed_mask;
463 	shadow_dirty_mask = dirty_mask;
464 	shadow_nx_mask = nx_mask;
465 	shadow_x_mask = x_mask;
466 	shadow_present_mask = p_mask;
467 	shadow_acc_track_mask = acc_track_mask;
468 	shadow_me_mask = me_mask;
469 }
470 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
471 
kvm_get_shadow_phys_bits(void)472 static u8 kvm_get_shadow_phys_bits(void)
473 {
474 	/*
475 	 * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
476 	 * in CPU detection code, but MKTME treats those reduced bits as
477 	 * 'keyID' thus they are not reserved bits. Therefore for MKTME
478 	 * we should still return physical address bits reported by CPUID.
479 	 */
480 	if (!boot_cpu_has(X86_FEATURE_TME) ||
481 	    WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
482 		return boot_cpu_data.x86_phys_bits;
483 
484 	return cpuid_eax(0x80000008) & 0xff;
485 }
486 
kvm_mmu_reset_all_pte_masks(void)487 static void kvm_mmu_reset_all_pte_masks(void)
488 {
489 	u8 low_phys_bits;
490 
491 	shadow_user_mask = 0;
492 	shadow_accessed_mask = 0;
493 	shadow_dirty_mask = 0;
494 	shadow_nx_mask = 0;
495 	shadow_x_mask = 0;
496 	shadow_mmio_mask = 0;
497 	shadow_present_mask = 0;
498 	shadow_acc_track_mask = 0;
499 
500 	shadow_phys_bits = kvm_get_shadow_phys_bits();
501 
502 	/*
503 	 * If the CPU has 46 or less physical address bits, then set an
504 	 * appropriate mask to guard against L1TF attacks. Otherwise, it is
505 	 * assumed that the CPU is not vulnerable to L1TF.
506 	 *
507 	 * Some Intel CPUs address the L1 cache using more PA bits than are
508 	 * reported by CPUID. Use the PA width of the L1 cache when possible
509 	 * to achieve more effective mitigation, e.g. if system RAM overlaps
510 	 * the most significant bits of legal physical address space.
511 	 */
512 	shadow_nonpresent_or_rsvd_mask = 0;
513 	low_phys_bits = boot_cpu_data.x86_phys_bits;
514 	if (boot_cpu_has_bug(X86_BUG_L1TF) &&
515 	    !WARN_ON_ONCE(boot_cpu_data.x86_cache_bits >=
516 			  52 - shadow_nonpresent_or_rsvd_mask_len)) {
517 		low_phys_bits = boot_cpu_data.x86_cache_bits
518 			- shadow_nonpresent_or_rsvd_mask_len;
519 		shadow_nonpresent_or_rsvd_mask =
520 			rsvd_bits(low_phys_bits, boot_cpu_data.x86_cache_bits - 1);
521 	}
522 
523 	shadow_nonpresent_or_rsvd_lower_gfn_mask =
524 		GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
525 }
526 
is_cpuid_PSE36(void)527 static int is_cpuid_PSE36(void)
528 {
529 	return 1;
530 }
531 
is_nx(struct kvm_vcpu * vcpu)532 static int is_nx(struct kvm_vcpu *vcpu)
533 {
534 	return vcpu->arch.efer & EFER_NX;
535 }
536 
is_shadow_present_pte(u64 pte)537 static int is_shadow_present_pte(u64 pte)
538 {
539 	return (pte != 0) && !is_mmio_spte(pte);
540 }
541 
is_large_pte(u64 pte)542 static int is_large_pte(u64 pte)
543 {
544 	return pte & PT_PAGE_SIZE_MASK;
545 }
546 
is_last_spte(u64 pte,int level)547 static int is_last_spte(u64 pte, int level)
548 {
549 	if (level == PT_PAGE_TABLE_LEVEL)
550 		return 1;
551 	if (is_large_pte(pte))
552 		return 1;
553 	return 0;
554 }
555 
is_executable_pte(u64 spte)556 static bool is_executable_pte(u64 spte)
557 {
558 	return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
559 }
560 
spte_to_pfn(u64 pte)561 static kvm_pfn_t spte_to_pfn(u64 pte)
562 {
563 	return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
564 }
565 
pse36_gfn_delta(u32 gpte)566 static gfn_t pse36_gfn_delta(u32 gpte)
567 {
568 	int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
569 
570 	return (gpte & PT32_DIR_PSE36_MASK) << shift;
571 }
572 
573 #ifdef CONFIG_X86_64
__set_spte(u64 * sptep,u64 spte)574 static void __set_spte(u64 *sptep, u64 spte)
575 {
576 	WRITE_ONCE(*sptep, spte);
577 }
578 
__update_clear_spte_fast(u64 * sptep,u64 spte)579 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
580 {
581 	WRITE_ONCE(*sptep, spte);
582 }
583 
__update_clear_spte_slow(u64 * sptep,u64 spte)584 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
585 {
586 	return xchg(sptep, spte);
587 }
588 
__get_spte_lockless(u64 * sptep)589 static u64 __get_spte_lockless(u64 *sptep)
590 {
591 	return READ_ONCE(*sptep);
592 }
593 #else
594 union split_spte {
595 	struct {
596 		u32 spte_low;
597 		u32 spte_high;
598 	};
599 	u64 spte;
600 };
601 
count_spte_clear(u64 * sptep,u64 spte)602 static void count_spte_clear(u64 *sptep, u64 spte)
603 {
604 	struct kvm_mmu_page *sp =  page_header(__pa(sptep));
605 
606 	if (is_shadow_present_pte(spte))
607 		return;
608 
609 	/* Ensure the spte is completely set before we increase the count */
610 	smp_wmb();
611 	sp->clear_spte_count++;
612 }
613 
__set_spte(u64 * sptep,u64 spte)614 static void __set_spte(u64 *sptep, u64 spte)
615 {
616 	union split_spte *ssptep, sspte;
617 
618 	ssptep = (union split_spte *)sptep;
619 	sspte = (union split_spte)spte;
620 
621 	ssptep->spte_high = sspte.spte_high;
622 
623 	/*
624 	 * If we map the spte from nonpresent to present, We should store
625 	 * the high bits firstly, then set present bit, so cpu can not
626 	 * fetch this spte while we are setting the spte.
627 	 */
628 	smp_wmb();
629 
630 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
631 }
632 
__update_clear_spte_fast(u64 * sptep,u64 spte)633 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
634 {
635 	union split_spte *ssptep, sspte;
636 
637 	ssptep = (union split_spte *)sptep;
638 	sspte = (union split_spte)spte;
639 
640 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
641 
642 	/*
643 	 * If we map the spte from present to nonpresent, we should clear
644 	 * present bit firstly to avoid vcpu fetch the old high bits.
645 	 */
646 	smp_wmb();
647 
648 	ssptep->spte_high = sspte.spte_high;
649 	count_spte_clear(sptep, spte);
650 }
651 
__update_clear_spte_slow(u64 * sptep,u64 spte)652 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
653 {
654 	union split_spte *ssptep, sspte, orig;
655 
656 	ssptep = (union split_spte *)sptep;
657 	sspte = (union split_spte)spte;
658 
659 	/* xchg acts as a barrier before the setting of the high bits */
660 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
661 	orig.spte_high = ssptep->spte_high;
662 	ssptep->spte_high = sspte.spte_high;
663 	count_spte_clear(sptep, spte);
664 
665 	return orig.spte;
666 }
667 
668 /*
669  * The idea using the light way get the spte on x86_32 guest is from
670  * gup_get_pte(arch/x86/mm/gup.c).
671  *
672  * An spte tlb flush may be pending, because kvm_set_pte_rmapp
673  * coalesces them and we are running out of the MMU lock.  Therefore
674  * we need to protect against in-progress updates of the spte.
675  *
676  * Reading the spte while an update is in progress may get the old value
677  * for the high part of the spte.  The race is fine for a present->non-present
678  * change (because the high part of the spte is ignored for non-present spte),
679  * but for a present->present change we must reread the spte.
680  *
681  * All such changes are done in two steps (present->non-present and
682  * non-present->present), hence it is enough to count the number of
683  * present->non-present updates: if it changed while reading the spte,
684  * we might have hit the race.  This is done using clear_spte_count.
685  */
__get_spte_lockless(u64 * sptep)686 static u64 __get_spte_lockless(u64 *sptep)
687 {
688 	struct kvm_mmu_page *sp =  page_header(__pa(sptep));
689 	union split_spte spte, *orig = (union split_spte *)sptep;
690 	int count;
691 
692 retry:
693 	count = sp->clear_spte_count;
694 	smp_rmb();
695 
696 	spte.spte_low = orig->spte_low;
697 	smp_rmb();
698 
699 	spte.spte_high = orig->spte_high;
700 	smp_rmb();
701 
702 	if (unlikely(spte.spte_low != orig->spte_low ||
703 	      count != sp->clear_spte_count))
704 		goto retry;
705 
706 	return spte.spte;
707 }
708 #endif
709 
spte_can_locklessly_be_made_writable(u64 spte)710 static bool spte_can_locklessly_be_made_writable(u64 spte)
711 {
712 	return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
713 		(SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
714 }
715 
spte_has_volatile_bits(u64 spte)716 static bool spte_has_volatile_bits(u64 spte)
717 {
718 	if (!is_shadow_present_pte(spte))
719 		return false;
720 
721 	/*
722 	 * Always atomically update spte if it can be updated
723 	 * out of mmu-lock, it can ensure dirty bit is not lost,
724 	 * also, it can help us to get a stable is_writable_pte()
725 	 * to ensure tlb flush is not missed.
726 	 */
727 	if (spte_can_locklessly_be_made_writable(spte) ||
728 	    is_access_track_spte(spte))
729 		return true;
730 
731 	if (spte_ad_enabled(spte)) {
732 		if ((spte & shadow_accessed_mask) == 0 ||
733 	    	    (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
734 			return true;
735 	}
736 
737 	return false;
738 }
739 
is_accessed_spte(u64 spte)740 static bool is_accessed_spte(u64 spte)
741 {
742 	u64 accessed_mask = spte_shadow_accessed_mask(spte);
743 
744 	return accessed_mask ? spte & accessed_mask
745 			     : !is_access_track_spte(spte);
746 }
747 
is_dirty_spte(u64 spte)748 static bool is_dirty_spte(u64 spte)
749 {
750 	u64 dirty_mask = spte_shadow_dirty_mask(spte);
751 
752 	return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
753 }
754 
755 /* Rules for using mmu_spte_set:
756  * Set the sptep from nonpresent to present.
757  * Note: the sptep being assigned *must* be either not present
758  * or in a state where the hardware will not attempt to update
759  * the spte.
760  */
mmu_spte_set(u64 * sptep,u64 new_spte)761 static void mmu_spte_set(u64 *sptep, u64 new_spte)
762 {
763 	WARN_ON(is_shadow_present_pte(*sptep));
764 	__set_spte(sptep, new_spte);
765 }
766 
767 /*
768  * Update the SPTE (excluding the PFN), but do not track changes in its
769  * accessed/dirty status.
770  */
mmu_spte_update_no_track(u64 * sptep,u64 new_spte)771 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
772 {
773 	u64 old_spte = *sptep;
774 
775 	WARN_ON(!is_shadow_present_pte(new_spte));
776 
777 	if (!is_shadow_present_pte(old_spte)) {
778 		mmu_spte_set(sptep, new_spte);
779 		return old_spte;
780 	}
781 
782 	if (!spte_has_volatile_bits(old_spte))
783 		__update_clear_spte_fast(sptep, new_spte);
784 	else
785 		old_spte = __update_clear_spte_slow(sptep, new_spte);
786 
787 	WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
788 
789 	return old_spte;
790 }
791 
792 /* Rules for using mmu_spte_update:
793  * Update the state bits, it means the mapped pfn is not changed.
794  *
795  * Whenever we overwrite a writable spte with a read-only one we
796  * should flush remote TLBs. Otherwise rmap_write_protect
797  * will find a read-only spte, even though the writable spte
798  * might be cached on a CPU's TLB, the return value indicates this
799  * case.
800  *
801  * Returns true if the TLB needs to be flushed
802  */
mmu_spte_update(u64 * sptep,u64 new_spte)803 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
804 {
805 	bool flush = false;
806 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
807 
808 	if (!is_shadow_present_pte(old_spte))
809 		return false;
810 
811 	/*
812 	 * For the spte updated out of mmu-lock is safe, since
813 	 * we always atomically update it, see the comments in
814 	 * spte_has_volatile_bits().
815 	 */
816 	if (spte_can_locklessly_be_made_writable(old_spte) &&
817 	      !is_writable_pte(new_spte))
818 		flush = true;
819 
820 	/*
821 	 * Flush TLB when accessed/dirty states are changed in the page tables,
822 	 * to guarantee consistency between TLB and page tables.
823 	 */
824 
825 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
826 		flush = true;
827 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
828 	}
829 
830 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
831 		flush = true;
832 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
833 	}
834 
835 	return flush;
836 }
837 
838 /*
839  * Rules for using mmu_spte_clear_track_bits:
840  * It sets the sptep from present to nonpresent, and track the
841  * state bits, it is used to clear the last level sptep.
842  * Returns non-zero if the PTE was previously valid.
843  */
mmu_spte_clear_track_bits(u64 * sptep)844 static int mmu_spte_clear_track_bits(u64 *sptep)
845 {
846 	kvm_pfn_t pfn;
847 	u64 old_spte = *sptep;
848 
849 	if (!spte_has_volatile_bits(old_spte))
850 		__update_clear_spte_fast(sptep, 0ull);
851 	else
852 		old_spte = __update_clear_spte_slow(sptep, 0ull);
853 
854 	if (!is_shadow_present_pte(old_spte))
855 		return 0;
856 
857 	pfn = spte_to_pfn(old_spte);
858 
859 	/*
860 	 * KVM does not hold the refcount of the page used by
861 	 * kvm mmu, before reclaiming the page, we should
862 	 * unmap it from mmu first.
863 	 */
864 	WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
865 
866 	if (is_accessed_spte(old_spte))
867 		kvm_set_pfn_accessed(pfn);
868 
869 	if (is_dirty_spte(old_spte))
870 		kvm_set_pfn_dirty(pfn);
871 
872 	return 1;
873 }
874 
875 /*
876  * Rules for using mmu_spte_clear_no_track:
877  * Directly clear spte without caring the state bits of sptep,
878  * it is used to set the upper level spte.
879  */
mmu_spte_clear_no_track(u64 * sptep)880 static void mmu_spte_clear_no_track(u64 *sptep)
881 {
882 	__update_clear_spte_fast(sptep, 0ull);
883 }
884 
mmu_spte_get_lockless(u64 * sptep)885 static u64 mmu_spte_get_lockless(u64 *sptep)
886 {
887 	return __get_spte_lockless(sptep);
888 }
889 
mark_spte_for_access_track(u64 spte)890 static u64 mark_spte_for_access_track(u64 spte)
891 {
892 	if (spte_ad_enabled(spte))
893 		return spte & ~shadow_accessed_mask;
894 
895 	if (is_access_track_spte(spte))
896 		return spte;
897 
898 	/*
899 	 * Making an Access Tracking PTE will result in removal of write access
900 	 * from the PTE. So, verify that we will be able to restore the write
901 	 * access in the fast page fault path later on.
902 	 */
903 	WARN_ONCE((spte & PT_WRITABLE_MASK) &&
904 		  !spte_can_locklessly_be_made_writable(spte),
905 		  "kvm: Writable SPTE is not locklessly dirty-trackable\n");
906 
907 	WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
908 			  shadow_acc_track_saved_bits_shift),
909 		  "kvm: Access Tracking saved bit locations are not zero\n");
910 
911 	spte |= (spte & shadow_acc_track_saved_bits_mask) <<
912 		shadow_acc_track_saved_bits_shift;
913 	spte &= ~shadow_acc_track_mask;
914 
915 	return spte;
916 }
917 
918 /* Restore an acc-track PTE back to a regular PTE */
restore_acc_track_spte(u64 spte)919 static u64 restore_acc_track_spte(u64 spte)
920 {
921 	u64 new_spte = spte;
922 	u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
923 			 & shadow_acc_track_saved_bits_mask;
924 
925 	WARN_ON_ONCE(spte_ad_enabled(spte));
926 	WARN_ON_ONCE(!is_access_track_spte(spte));
927 
928 	new_spte &= ~shadow_acc_track_mask;
929 	new_spte &= ~(shadow_acc_track_saved_bits_mask <<
930 		      shadow_acc_track_saved_bits_shift);
931 	new_spte |= saved_bits;
932 
933 	return new_spte;
934 }
935 
936 /* Returns the Accessed status of the PTE and resets it at the same time. */
mmu_spte_age(u64 * sptep)937 static bool mmu_spte_age(u64 *sptep)
938 {
939 	u64 spte = mmu_spte_get_lockless(sptep);
940 
941 	if (!is_accessed_spte(spte))
942 		return false;
943 
944 	if (spte_ad_enabled(spte)) {
945 		clear_bit((ffs(shadow_accessed_mask) - 1),
946 			  (unsigned long *)sptep);
947 	} else {
948 		/*
949 		 * Capture the dirty status of the page, so that it doesn't get
950 		 * lost when the SPTE is marked for access tracking.
951 		 */
952 		if (is_writable_pte(spte))
953 			kvm_set_pfn_dirty(spte_to_pfn(spte));
954 
955 		spte = mark_spte_for_access_track(spte);
956 		mmu_spte_update_no_track(sptep, spte);
957 	}
958 
959 	return true;
960 }
961 
walk_shadow_page_lockless_begin(struct kvm_vcpu * vcpu)962 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
963 {
964 	/*
965 	 * Prevent page table teardown by making any free-er wait during
966 	 * kvm_flush_remote_tlbs() IPI to all active vcpus.
967 	 */
968 	local_irq_disable();
969 
970 	/*
971 	 * Make sure a following spte read is not reordered ahead of the write
972 	 * to vcpu->mode.
973 	 */
974 	smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
975 }
976 
walk_shadow_page_lockless_end(struct kvm_vcpu * vcpu)977 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
978 {
979 	/*
980 	 * Make sure the write to vcpu->mode is not reordered in front of
981 	 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
982 	 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
983 	 */
984 	smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
985 	local_irq_enable();
986 }
987 
mmu_topup_memory_cache(struct kvm_mmu_memory_cache * cache,struct kmem_cache * base_cache,int min)988 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
989 				  struct kmem_cache *base_cache, int min)
990 {
991 	void *obj;
992 
993 	if (cache->nobjs >= min)
994 		return 0;
995 	while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
996 		obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
997 		if (!obj)
998 			return -ENOMEM;
999 		cache->objects[cache->nobjs++] = obj;
1000 	}
1001 	return 0;
1002 }
1003 
mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache * cache)1004 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
1005 {
1006 	return cache->nobjs;
1007 }
1008 
mmu_free_memory_cache(struct kvm_mmu_memory_cache * mc,struct kmem_cache * cache)1009 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
1010 				  struct kmem_cache *cache)
1011 {
1012 	while (mc->nobjs)
1013 		kmem_cache_free(cache, mc->objects[--mc->nobjs]);
1014 }
1015 
mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache * cache,int min)1016 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1017 				       int min)
1018 {
1019 	void *page;
1020 
1021 	if (cache->nobjs >= min)
1022 		return 0;
1023 	while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1024 		page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1025 		if (!page)
1026 			return -ENOMEM;
1027 		cache->objects[cache->nobjs++] = page;
1028 	}
1029 	return 0;
1030 }
1031 
mmu_free_memory_cache_page(struct kvm_mmu_memory_cache * mc)1032 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1033 {
1034 	while (mc->nobjs)
1035 		free_page((unsigned long)mc->objects[--mc->nobjs]);
1036 }
1037 
mmu_topup_memory_caches(struct kvm_vcpu * vcpu)1038 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1039 {
1040 	int r;
1041 
1042 	r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1043 				   pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1044 	if (r)
1045 		goto out;
1046 	r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1047 	if (r)
1048 		goto out;
1049 	r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1050 				   mmu_page_header_cache, 4);
1051 out:
1052 	return r;
1053 }
1054 
mmu_free_memory_caches(struct kvm_vcpu * vcpu)1055 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1056 {
1057 	mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1058 				pte_list_desc_cache);
1059 	mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1060 	mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1061 				mmu_page_header_cache);
1062 }
1063 
mmu_memory_cache_alloc(struct kvm_mmu_memory_cache * mc)1064 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1065 {
1066 	void *p;
1067 
1068 	BUG_ON(!mc->nobjs);
1069 	p = mc->objects[--mc->nobjs];
1070 	return p;
1071 }
1072 
mmu_alloc_pte_list_desc(struct kvm_vcpu * vcpu)1073 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1074 {
1075 	return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1076 }
1077 
mmu_free_pte_list_desc(struct pte_list_desc * pte_list_desc)1078 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1079 {
1080 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1081 }
1082 
kvm_mmu_page_get_gfn(struct kvm_mmu_page * sp,int index)1083 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1084 {
1085 	if (!sp->role.direct)
1086 		return sp->gfns[index];
1087 
1088 	return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1089 }
1090 
kvm_mmu_page_set_gfn(struct kvm_mmu_page * sp,int index,gfn_t gfn)1091 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1092 {
1093 	if (!sp->role.direct) {
1094 		sp->gfns[index] = gfn;
1095 		return;
1096 	}
1097 
1098 	if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1099 		pr_err_ratelimited("gfn mismatch under direct page %llx "
1100 				   "(expected %llx, got %llx)\n",
1101 				   sp->gfn,
1102 				   kvm_mmu_page_get_gfn(sp, index), gfn);
1103 }
1104 
1105 /*
1106  * Return the pointer to the large page information for a given gfn,
1107  * handling slots that are not large page aligned.
1108  */
lpage_info_slot(gfn_t gfn,struct kvm_memory_slot * slot,int level)1109 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1110 					      struct kvm_memory_slot *slot,
1111 					      int level)
1112 {
1113 	unsigned long idx;
1114 
1115 	idx = gfn_to_index(gfn, slot->base_gfn, level);
1116 	return &slot->arch.lpage_info[level - 2][idx];
1117 }
1118 
update_gfn_disallow_lpage_count(struct kvm_memory_slot * slot,gfn_t gfn,int count)1119 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1120 					    gfn_t gfn, int count)
1121 {
1122 	struct kvm_lpage_info *linfo;
1123 	int i;
1124 
1125 	for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1126 		linfo = lpage_info_slot(gfn, slot, i);
1127 		linfo->disallow_lpage += count;
1128 		WARN_ON(linfo->disallow_lpage < 0);
1129 	}
1130 }
1131 
kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot * slot,gfn_t gfn)1132 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1133 {
1134 	update_gfn_disallow_lpage_count(slot, gfn, 1);
1135 }
1136 
kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot * slot,gfn_t gfn)1137 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1138 {
1139 	update_gfn_disallow_lpage_count(slot, gfn, -1);
1140 }
1141 
account_shadowed(struct kvm * kvm,struct kvm_mmu_page * sp)1142 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1143 {
1144 	struct kvm_memslots *slots;
1145 	struct kvm_memory_slot *slot;
1146 	gfn_t gfn;
1147 
1148 	kvm->arch.indirect_shadow_pages++;
1149 	gfn = sp->gfn;
1150 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1151 	slot = __gfn_to_memslot(slots, gfn);
1152 
1153 	/* the non-leaf shadow pages are keeping readonly. */
1154 	if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1155 		return kvm_slot_page_track_add_page(kvm, slot, gfn,
1156 						    KVM_PAGE_TRACK_WRITE);
1157 
1158 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
1159 }
1160 
account_huge_nx_page(struct kvm * kvm,struct kvm_mmu_page * sp)1161 static void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1162 {
1163 	if (sp->lpage_disallowed)
1164 		return;
1165 
1166 	++kvm->stat.nx_lpage_splits;
1167 	list_add_tail(&sp->lpage_disallowed_link,
1168 		      &kvm->arch.lpage_disallowed_mmu_pages);
1169 	sp->lpage_disallowed = true;
1170 }
1171 
unaccount_shadowed(struct kvm * kvm,struct kvm_mmu_page * sp)1172 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1173 {
1174 	struct kvm_memslots *slots;
1175 	struct kvm_memory_slot *slot;
1176 	gfn_t gfn;
1177 
1178 	kvm->arch.indirect_shadow_pages--;
1179 	gfn = sp->gfn;
1180 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1181 	slot = __gfn_to_memslot(slots, gfn);
1182 	if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1183 		return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1184 						       KVM_PAGE_TRACK_WRITE);
1185 
1186 	kvm_mmu_gfn_allow_lpage(slot, gfn);
1187 }
1188 
unaccount_huge_nx_page(struct kvm * kvm,struct kvm_mmu_page * sp)1189 static void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1190 {
1191 	--kvm->stat.nx_lpage_splits;
1192 	sp->lpage_disallowed = false;
1193 	list_del(&sp->lpage_disallowed_link);
1194 }
1195 
__mmu_gfn_lpage_is_disallowed(gfn_t gfn,int level,struct kvm_memory_slot * slot)1196 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1197 					  struct kvm_memory_slot *slot)
1198 {
1199 	struct kvm_lpage_info *linfo;
1200 
1201 	if (slot) {
1202 		linfo = lpage_info_slot(gfn, slot, level);
1203 		return !!linfo->disallow_lpage;
1204 	}
1205 
1206 	return true;
1207 }
1208 
mmu_gfn_lpage_is_disallowed(struct kvm_vcpu * vcpu,gfn_t gfn,int level)1209 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1210 					int level)
1211 {
1212 	struct kvm_memory_slot *slot;
1213 
1214 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1215 	return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1216 }
1217 
host_mapping_level(struct kvm_vcpu * vcpu,gfn_t gfn)1218 static int host_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn)
1219 {
1220 	unsigned long page_size;
1221 	int i, ret = 0;
1222 
1223 	page_size = kvm_host_page_size(vcpu, gfn);
1224 
1225 	for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1226 		if (page_size >= KVM_HPAGE_SIZE(i))
1227 			ret = i;
1228 		else
1229 			break;
1230 	}
1231 
1232 	return ret;
1233 }
1234 
memslot_valid_for_gpte(struct kvm_memory_slot * slot,bool no_dirty_log)1235 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1236 					  bool no_dirty_log)
1237 {
1238 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1239 		return false;
1240 	if (no_dirty_log && slot->dirty_bitmap)
1241 		return false;
1242 
1243 	return true;
1244 }
1245 
1246 static struct kvm_memory_slot *
gfn_to_memslot_dirty_bitmap(struct kvm_vcpu * vcpu,gfn_t gfn,bool no_dirty_log)1247 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1248 			    bool no_dirty_log)
1249 {
1250 	struct kvm_memory_slot *slot;
1251 
1252 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1253 	if (!memslot_valid_for_gpte(slot, no_dirty_log))
1254 		slot = NULL;
1255 
1256 	return slot;
1257 }
1258 
mapping_level(struct kvm_vcpu * vcpu,gfn_t large_gfn,bool * force_pt_level)1259 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1260 			 bool *force_pt_level)
1261 {
1262 	int host_level, level, max_level;
1263 	struct kvm_memory_slot *slot;
1264 
1265 	if (unlikely(*force_pt_level))
1266 		return PT_PAGE_TABLE_LEVEL;
1267 
1268 	slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1269 	*force_pt_level = !memslot_valid_for_gpte(slot, true);
1270 	if (unlikely(*force_pt_level))
1271 		return PT_PAGE_TABLE_LEVEL;
1272 
1273 	host_level = host_mapping_level(vcpu, large_gfn);
1274 
1275 	if (host_level == PT_PAGE_TABLE_LEVEL)
1276 		return host_level;
1277 
1278 	max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1279 
1280 	for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1281 		if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1282 			break;
1283 
1284 	return level - 1;
1285 }
1286 
1287 /*
1288  * About rmap_head encoding:
1289  *
1290  * If the bit zero of rmap_head->val is clear, then it points to the only spte
1291  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1292  * pte_list_desc containing more mappings.
1293  */
1294 
1295 /*
1296  * Returns the number of pointers in the rmap chain, not counting the new one.
1297  */
pte_list_add(struct kvm_vcpu * vcpu,u64 * spte,struct kvm_rmap_head * rmap_head)1298 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1299 			struct kvm_rmap_head *rmap_head)
1300 {
1301 	struct pte_list_desc *desc;
1302 	int i, count = 0;
1303 
1304 	if (!rmap_head->val) {
1305 		rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1306 		rmap_head->val = (unsigned long)spte;
1307 	} else if (!(rmap_head->val & 1)) {
1308 		rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1309 		desc = mmu_alloc_pte_list_desc(vcpu);
1310 		desc->sptes[0] = (u64 *)rmap_head->val;
1311 		desc->sptes[1] = spte;
1312 		rmap_head->val = (unsigned long)desc | 1;
1313 		++count;
1314 	} else {
1315 		rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1316 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1317 		while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1318 			desc = desc->more;
1319 			count += PTE_LIST_EXT;
1320 		}
1321 		if (desc->sptes[PTE_LIST_EXT-1]) {
1322 			desc->more = mmu_alloc_pte_list_desc(vcpu);
1323 			desc = desc->more;
1324 		}
1325 		for (i = 0; desc->sptes[i]; ++i)
1326 			++count;
1327 		desc->sptes[i] = spte;
1328 	}
1329 	return count;
1330 }
1331 
1332 static void
pte_list_desc_remove_entry(struct kvm_rmap_head * rmap_head,struct pte_list_desc * desc,int i,struct pte_list_desc * prev_desc)1333 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1334 			   struct pte_list_desc *desc, int i,
1335 			   struct pte_list_desc *prev_desc)
1336 {
1337 	int j;
1338 
1339 	for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1340 		;
1341 	desc->sptes[i] = desc->sptes[j];
1342 	desc->sptes[j] = NULL;
1343 	if (j != 0)
1344 		return;
1345 	if (!prev_desc && !desc->more)
1346 		rmap_head->val = (unsigned long)desc->sptes[0];
1347 	else
1348 		if (prev_desc)
1349 			prev_desc->more = desc->more;
1350 		else
1351 			rmap_head->val = (unsigned long)desc->more | 1;
1352 	mmu_free_pte_list_desc(desc);
1353 }
1354 
pte_list_remove(u64 * spte,struct kvm_rmap_head * rmap_head)1355 static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1356 {
1357 	struct pte_list_desc *desc;
1358 	struct pte_list_desc *prev_desc;
1359 	int i;
1360 
1361 	if (!rmap_head->val) {
1362 		printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
1363 		BUG();
1364 	} else if (!(rmap_head->val & 1)) {
1365 		rmap_printk("pte_list_remove:  %p 1->0\n", spte);
1366 		if ((u64 *)rmap_head->val != spte) {
1367 			printk(KERN_ERR "pte_list_remove:  %p 1->BUG\n", spte);
1368 			BUG();
1369 		}
1370 		rmap_head->val = 0;
1371 	} else {
1372 		rmap_printk("pte_list_remove:  %p many->many\n", spte);
1373 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1374 		prev_desc = NULL;
1375 		while (desc) {
1376 			for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1377 				if (desc->sptes[i] == spte) {
1378 					pte_list_desc_remove_entry(rmap_head,
1379 							desc, i, prev_desc);
1380 					return;
1381 				}
1382 			}
1383 			prev_desc = desc;
1384 			desc = desc->more;
1385 		}
1386 		pr_err("pte_list_remove: %p many->many\n", spte);
1387 		BUG();
1388 	}
1389 }
1390 
__gfn_to_rmap(gfn_t gfn,int level,struct kvm_memory_slot * slot)1391 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1392 					   struct kvm_memory_slot *slot)
1393 {
1394 	unsigned long idx;
1395 
1396 	idx = gfn_to_index(gfn, slot->base_gfn, level);
1397 	return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1398 }
1399 
gfn_to_rmap(struct kvm * kvm,gfn_t gfn,struct kvm_mmu_page * sp)1400 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1401 					 struct kvm_mmu_page *sp)
1402 {
1403 	struct kvm_memslots *slots;
1404 	struct kvm_memory_slot *slot;
1405 
1406 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1407 	slot = __gfn_to_memslot(slots, gfn);
1408 	return __gfn_to_rmap(gfn, sp->role.level, slot);
1409 }
1410 
rmap_can_add(struct kvm_vcpu * vcpu)1411 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1412 {
1413 	struct kvm_mmu_memory_cache *cache;
1414 
1415 	cache = &vcpu->arch.mmu_pte_list_desc_cache;
1416 	return mmu_memory_cache_free_objects(cache);
1417 }
1418 
rmap_add(struct kvm_vcpu * vcpu,u64 * spte,gfn_t gfn)1419 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1420 {
1421 	struct kvm_mmu_page *sp;
1422 	struct kvm_rmap_head *rmap_head;
1423 
1424 	sp = page_header(__pa(spte));
1425 	kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1426 	rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1427 	return pte_list_add(vcpu, spte, rmap_head);
1428 }
1429 
rmap_remove(struct kvm * kvm,u64 * spte)1430 static void rmap_remove(struct kvm *kvm, u64 *spte)
1431 {
1432 	struct kvm_mmu_page *sp;
1433 	gfn_t gfn;
1434 	struct kvm_rmap_head *rmap_head;
1435 
1436 	sp = page_header(__pa(spte));
1437 	gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1438 	rmap_head = gfn_to_rmap(kvm, gfn, sp);
1439 	pte_list_remove(spte, rmap_head);
1440 }
1441 
1442 /*
1443  * Used by the following functions to iterate through the sptes linked by a
1444  * rmap.  All fields are private and not assumed to be used outside.
1445  */
1446 struct rmap_iterator {
1447 	/* private fields */
1448 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1449 	int pos;			/* index of the sptep */
1450 };
1451 
1452 /*
1453  * Iteration must be started by this function.  This should also be used after
1454  * removing/dropping sptes from the rmap link because in such cases the
1455  * information in the itererator may not be valid.
1456  *
1457  * Returns sptep if found, NULL otherwise.
1458  */
rmap_get_first(struct kvm_rmap_head * rmap_head,struct rmap_iterator * iter)1459 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1460 			   struct rmap_iterator *iter)
1461 {
1462 	u64 *sptep;
1463 
1464 	if (!rmap_head->val)
1465 		return NULL;
1466 
1467 	if (!(rmap_head->val & 1)) {
1468 		iter->desc = NULL;
1469 		sptep = (u64 *)rmap_head->val;
1470 		goto out;
1471 	}
1472 
1473 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1474 	iter->pos = 0;
1475 	sptep = iter->desc->sptes[iter->pos];
1476 out:
1477 	BUG_ON(!is_shadow_present_pte(*sptep));
1478 	return sptep;
1479 }
1480 
1481 /*
1482  * Must be used with a valid iterator: e.g. after rmap_get_first().
1483  *
1484  * Returns sptep if found, NULL otherwise.
1485  */
rmap_get_next(struct rmap_iterator * iter)1486 static u64 *rmap_get_next(struct rmap_iterator *iter)
1487 {
1488 	u64 *sptep;
1489 
1490 	if (iter->desc) {
1491 		if (iter->pos < PTE_LIST_EXT - 1) {
1492 			++iter->pos;
1493 			sptep = iter->desc->sptes[iter->pos];
1494 			if (sptep)
1495 				goto out;
1496 		}
1497 
1498 		iter->desc = iter->desc->more;
1499 
1500 		if (iter->desc) {
1501 			iter->pos = 0;
1502 			/* desc->sptes[0] cannot be NULL */
1503 			sptep = iter->desc->sptes[iter->pos];
1504 			goto out;
1505 		}
1506 	}
1507 
1508 	return NULL;
1509 out:
1510 	BUG_ON(!is_shadow_present_pte(*sptep));
1511 	return sptep;
1512 }
1513 
1514 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1515 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1516 	     _spte_; _spte_ = rmap_get_next(_iter_))
1517 
drop_spte(struct kvm * kvm,u64 * sptep)1518 static void drop_spte(struct kvm *kvm, u64 *sptep)
1519 {
1520 	if (mmu_spte_clear_track_bits(sptep))
1521 		rmap_remove(kvm, sptep);
1522 }
1523 
1524 
__drop_large_spte(struct kvm * kvm,u64 * sptep)1525 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1526 {
1527 	if (is_large_pte(*sptep)) {
1528 		WARN_ON(page_header(__pa(sptep))->role.level ==
1529 			PT_PAGE_TABLE_LEVEL);
1530 		drop_spte(kvm, sptep);
1531 		--kvm->stat.lpages;
1532 		return true;
1533 	}
1534 
1535 	return false;
1536 }
1537 
drop_large_spte(struct kvm_vcpu * vcpu,u64 * sptep)1538 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1539 {
1540 	if (__drop_large_spte(vcpu->kvm, sptep))
1541 		kvm_flush_remote_tlbs(vcpu->kvm);
1542 }
1543 
1544 /*
1545  * Write-protect on the specified @sptep, @pt_protect indicates whether
1546  * spte write-protection is caused by protecting shadow page table.
1547  *
1548  * Note: write protection is difference between dirty logging and spte
1549  * protection:
1550  * - for dirty logging, the spte can be set to writable at anytime if
1551  *   its dirty bitmap is properly set.
1552  * - for spte protection, the spte can be writable only after unsync-ing
1553  *   shadow page.
1554  *
1555  * Return true if tlb need be flushed.
1556  */
spte_write_protect(u64 * sptep,bool pt_protect)1557 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1558 {
1559 	u64 spte = *sptep;
1560 
1561 	if (!is_writable_pte(spte) &&
1562 	      !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1563 		return false;
1564 
1565 	rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1566 
1567 	if (pt_protect)
1568 		spte &= ~SPTE_MMU_WRITEABLE;
1569 	spte = spte & ~PT_WRITABLE_MASK;
1570 
1571 	return mmu_spte_update(sptep, spte);
1572 }
1573 
__rmap_write_protect(struct kvm * kvm,struct kvm_rmap_head * rmap_head,bool pt_protect)1574 static bool __rmap_write_protect(struct kvm *kvm,
1575 				 struct kvm_rmap_head *rmap_head,
1576 				 bool pt_protect)
1577 {
1578 	u64 *sptep;
1579 	struct rmap_iterator iter;
1580 	bool flush = false;
1581 
1582 	for_each_rmap_spte(rmap_head, &iter, sptep)
1583 		flush |= spte_write_protect(sptep, pt_protect);
1584 
1585 	return flush;
1586 }
1587 
spte_clear_dirty(u64 * sptep)1588 static bool spte_clear_dirty(u64 *sptep)
1589 {
1590 	u64 spte = *sptep;
1591 
1592 	rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1593 
1594 	spte &= ~shadow_dirty_mask;
1595 
1596 	return mmu_spte_update(sptep, spte);
1597 }
1598 
wrprot_ad_disabled_spte(u64 * sptep)1599 static bool wrprot_ad_disabled_spte(u64 *sptep)
1600 {
1601 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1602 					       (unsigned long *)sptep);
1603 	if (was_writable)
1604 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1605 
1606 	return was_writable;
1607 }
1608 
1609 /*
1610  * Gets the GFN ready for another round of dirty logging by clearing the
1611  *	- D bit on ad-enabled SPTEs, and
1612  *	- W bit on ad-disabled SPTEs.
1613  * Returns true iff any D or W bits were cleared.
1614  */
__rmap_clear_dirty(struct kvm * kvm,struct kvm_rmap_head * rmap_head)1615 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1616 {
1617 	u64 *sptep;
1618 	struct rmap_iterator iter;
1619 	bool flush = false;
1620 
1621 	for_each_rmap_spte(rmap_head, &iter, sptep)
1622 		if (spte_ad_enabled(*sptep))
1623 			flush |= spte_clear_dirty(sptep);
1624 		else
1625 			flush |= wrprot_ad_disabled_spte(sptep);
1626 
1627 	return flush;
1628 }
1629 
spte_set_dirty(u64 * sptep)1630 static bool spte_set_dirty(u64 *sptep)
1631 {
1632 	u64 spte = *sptep;
1633 
1634 	rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1635 
1636 	spte |= shadow_dirty_mask;
1637 
1638 	return mmu_spte_update(sptep, spte);
1639 }
1640 
__rmap_set_dirty(struct kvm * kvm,struct kvm_rmap_head * rmap_head)1641 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1642 {
1643 	u64 *sptep;
1644 	struct rmap_iterator iter;
1645 	bool flush = false;
1646 
1647 	for_each_rmap_spte(rmap_head, &iter, sptep)
1648 		if (spte_ad_enabled(*sptep))
1649 			flush |= spte_set_dirty(sptep);
1650 
1651 	return flush;
1652 }
1653 
1654 /**
1655  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1656  * @kvm: kvm instance
1657  * @slot: slot to protect
1658  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1659  * @mask: indicates which pages we should protect
1660  *
1661  * Used when we do not need to care about huge page mappings: e.g. during dirty
1662  * logging we do not have any such mappings.
1663  */
kvm_mmu_write_protect_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)1664 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1665 				     struct kvm_memory_slot *slot,
1666 				     gfn_t gfn_offset, unsigned long mask)
1667 {
1668 	struct kvm_rmap_head *rmap_head;
1669 
1670 	while (mask) {
1671 		rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1672 					  PT_PAGE_TABLE_LEVEL, slot);
1673 		__rmap_write_protect(kvm, rmap_head, false);
1674 
1675 		/* clear the first set bit */
1676 		mask &= mask - 1;
1677 	}
1678 }
1679 
1680 /**
1681  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1682  * protect the page if the D-bit isn't supported.
1683  * @kvm: kvm instance
1684  * @slot: slot to clear D-bit
1685  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1686  * @mask: indicates which pages we should clear D-bit
1687  *
1688  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1689  */
kvm_mmu_clear_dirty_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)1690 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1691 				     struct kvm_memory_slot *slot,
1692 				     gfn_t gfn_offset, unsigned long mask)
1693 {
1694 	struct kvm_rmap_head *rmap_head;
1695 
1696 	while (mask) {
1697 		rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1698 					  PT_PAGE_TABLE_LEVEL, slot);
1699 		__rmap_clear_dirty(kvm, rmap_head);
1700 
1701 		/* clear the first set bit */
1702 		mask &= mask - 1;
1703 	}
1704 }
1705 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1706 
1707 /**
1708  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1709  * PT level pages.
1710  *
1711  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1712  * enable dirty logging for them.
1713  *
1714  * Used when we do not need to care about huge page mappings: e.g. during dirty
1715  * logging we do not have any such mappings.
1716  */
kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)1717 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1718 				struct kvm_memory_slot *slot,
1719 				gfn_t gfn_offset, unsigned long mask)
1720 {
1721 	if (kvm_x86_ops->enable_log_dirty_pt_masked)
1722 		kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1723 				mask);
1724 	else
1725 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1726 }
1727 
1728 /**
1729  * kvm_arch_write_log_dirty - emulate dirty page logging
1730  * @vcpu: Guest mode vcpu
1731  *
1732  * Emulate arch specific page modification logging for the
1733  * nested hypervisor
1734  */
kvm_arch_write_log_dirty(struct kvm_vcpu * vcpu,gpa_t l2_gpa)1735 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu, gpa_t l2_gpa)
1736 {
1737 	if (kvm_x86_ops->write_log_dirty)
1738 		return kvm_x86_ops->write_log_dirty(vcpu, l2_gpa);
1739 
1740 	return 0;
1741 }
1742 
kvm_mmu_slot_gfn_write_protect(struct kvm * kvm,struct kvm_memory_slot * slot,u64 gfn)1743 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1744 				    struct kvm_memory_slot *slot, u64 gfn)
1745 {
1746 	struct kvm_rmap_head *rmap_head;
1747 	int i;
1748 	bool write_protected = false;
1749 
1750 	for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1751 		rmap_head = __gfn_to_rmap(gfn, i, slot);
1752 		write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1753 	}
1754 
1755 	return write_protected;
1756 }
1757 
rmap_write_protect(struct kvm_vcpu * vcpu,u64 gfn)1758 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1759 {
1760 	struct kvm_memory_slot *slot;
1761 
1762 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1763 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1764 }
1765 
kvm_zap_rmapp(struct kvm * kvm,struct kvm_rmap_head * rmap_head)1766 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1767 {
1768 	u64 *sptep;
1769 	struct rmap_iterator iter;
1770 	bool flush = false;
1771 
1772 	while ((sptep = rmap_get_first(rmap_head, &iter))) {
1773 		rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1774 
1775 		drop_spte(kvm, sptep);
1776 		flush = true;
1777 	}
1778 
1779 	return flush;
1780 }
1781 
kvm_unmap_rmapp(struct kvm * kvm,struct kvm_rmap_head * rmap_head,struct kvm_memory_slot * slot,gfn_t gfn,int level,unsigned long data)1782 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1783 			   struct kvm_memory_slot *slot, gfn_t gfn, int level,
1784 			   unsigned long data)
1785 {
1786 	return kvm_zap_rmapp(kvm, rmap_head);
1787 }
1788 
kvm_set_pte_rmapp(struct kvm * kvm,struct kvm_rmap_head * rmap_head,struct kvm_memory_slot * slot,gfn_t gfn,int level,unsigned long data)1789 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1790 			     struct kvm_memory_slot *slot, gfn_t gfn, int level,
1791 			     unsigned long data)
1792 {
1793 	u64 *sptep;
1794 	struct rmap_iterator iter;
1795 	int need_flush = 0;
1796 	u64 new_spte;
1797 	pte_t *ptep = (pte_t *)data;
1798 	kvm_pfn_t new_pfn;
1799 
1800 	WARN_ON(pte_huge(*ptep));
1801 	new_pfn = pte_pfn(*ptep);
1802 
1803 restart:
1804 	for_each_rmap_spte(rmap_head, &iter, sptep) {
1805 		rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1806 			    sptep, *sptep, gfn, level);
1807 
1808 		need_flush = 1;
1809 
1810 		if (pte_write(*ptep)) {
1811 			drop_spte(kvm, sptep);
1812 			goto restart;
1813 		} else {
1814 			new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1815 			new_spte |= (u64)new_pfn << PAGE_SHIFT;
1816 
1817 			new_spte &= ~PT_WRITABLE_MASK;
1818 			new_spte &= ~SPTE_HOST_WRITEABLE;
1819 
1820 			new_spte = mark_spte_for_access_track(new_spte);
1821 
1822 			mmu_spte_clear_track_bits(sptep);
1823 			mmu_spte_set(sptep, new_spte);
1824 		}
1825 	}
1826 
1827 	if (need_flush)
1828 		kvm_flush_remote_tlbs(kvm);
1829 
1830 	return 0;
1831 }
1832 
1833 struct slot_rmap_walk_iterator {
1834 	/* input fields. */
1835 	struct kvm_memory_slot *slot;
1836 	gfn_t start_gfn;
1837 	gfn_t end_gfn;
1838 	int start_level;
1839 	int end_level;
1840 
1841 	/* output fields. */
1842 	gfn_t gfn;
1843 	struct kvm_rmap_head *rmap;
1844 	int level;
1845 
1846 	/* private field. */
1847 	struct kvm_rmap_head *end_rmap;
1848 };
1849 
1850 static void
rmap_walk_init_level(struct slot_rmap_walk_iterator * iterator,int level)1851 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1852 {
1853 	iterator->level = level;
1854 	iterator->gfn = iterator->start_gfn;
1855 	iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1856 	iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1857 					   iterator->slot);
1858 }
1859 
1860 static void
slot_rmap_walk_init(struct slot_rmap_walk_iterator * iterator,struct kvm_memory_slot * slot,int start_level,int end_level,gfn_t start_gfn,gfn_t end_gfn)1861 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1862 		    struct kvm_memory_slot *slot, int start_level,
1863 		    int end_level, gfn_t start_gfn, gfn_t end_gfn)
1864 {
1865 	iterator->slot = slot;
1866 	iterator->start_level = start_level;
1867 	iterator->end_level = end_level;
1868 	iterator->start_gfn = start_gfn;
1869 	iterator->end_gfn = end_gfn;
1870 
1871 	rmap_walk_init_level(iterator, iterator->start_level);
1872 }
1873 
slot_rmap_walk_okay(struct slot_rmap_walk_iterator * iterator)1874 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1875 {
1876 	return !!iterator->rmap;
1877 }
1878 
slot_rmap_walk_next(struct slot_rmap_walk_iterator * iterator)1879 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1880 {
1881 	if (++iterator->rmap <= iterator->end_rmap) {
1882 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1883 		return;
1884 	}
1885 
1886 	if (++iterator->level > iterator->end_level) {
1887 		iterator->rmap = NULL;
1888 		return;
1889 	}
1890 
1891 	rmap_walk_init_level(iterator, iterator->level);
1892 }
1893 
1894 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1895 	   _start_gfn, _end_gfn, _iter_)				\
1896 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1897 				 _end_level_, _start_gfn, _end_gfn);	\
1898 	     slot_rmap_walk_okay(_iter_);				\
1899 	     slot_rmap_walk_next(_iter_))
1900 
kvm_handle_hva_range(struct kvm * kvm,unsigned long start,unsigned long end,unsigned long data,int (* handler)(struct kvm * kvm,struct kvm_rmap_head * rmap_head,struct kvm_memory_slot * slot,gfn_t gfn,int level,unsigned long data))1901 static int kvm_handle_hva_range(struct kvm *kvm,
1902 				unsigned long start,
1903 				unsigned long end,
1904 				unsigned long data,
1905 				int (*handler)(struct kvm *kvm,
1906 					       struct kvm_rmap_head *rmap_head,
1907 					       struct kvm_memory_slot *slot,
1908 					       gfn_t gfn,
1909 					       int level,
1910 					       unsigned long data))
1911 {
1912 	struct kvm_memslots *slots;
1913 	struct kvm_memory_slot *memslot;
1914 	struct slot_rmap_walk_iterator iterator;
1915 	int ret = 0;
1916 	int i;
1917 
1918 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1919 		slots = __kvm_memslots(kvm, i);
1920 		kvm_for_each_memslot(memslot, slots) {
1921 			unsigned long hva_start, hva_end;
1922 			gfn_t gfn_start, gfn_end;
1923 
1924 			hva_start = max(start, memslot->userspace_addr);
1925 			hva_end = min(end, memslot->userspace_addr +
1926 				      (memslot->npages << PAGE_SHIFT));
1927 			if (hva_start >= hva_end)
1928 				continue;
1929 			/*
1930 			 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1931 			 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1932 			 */
1933 			gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1934 			gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1935 
1936 			for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1937 						 PT_MAX_HUGEPAGE_LEVEL,
1938 						 gfn_start, gfn_end - 1,
1939 						 &iterator)
1940 				ret |= handler(kvm, iterator.rmap, memslot,
1941 					       iterator.gfn, iterator.level, data);
1942 		}
1943 	}
1944 
1945 	return ret;
1946 }
1947 
kvm_handle_hva(struct kvm * kvm,unsigned long hva,unsigned long data,int (* handler)(struct kvm * kvm,struct kvm_rmap_head * rmap_head,struct kvm_memory_slot * slot,gfn_t gfn,int level,unsigned long data))1948 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1949 			  unsigned long data,
1950 			  int (*handler)(struct kvm *kvm,
1951 					 struct kvm_rmap_head *rmap_head,
1952 					 struct kvm_memory_slot *slot,
1953 					 gfn_t gfn, int level,
1954 					 unsigned long data))
1955 {
1956 	return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1957 }
1958 
kvm_unmap_hva_range(struct kvm * kvm,unsigned long start,unsigned long end,bool blockable)1959 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end,
1960 			bool blockable)
1961 {
1962 	return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1963 }
1964 
kvm_set_spte_hva(struct kvm * kvm,unsigned long hva,pte_t pte)1965 void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1966 {
1967 	kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1968 }
1969 
kvm_age_rmapp(struct kvm * kvm,struct kvm_rmap_head * rmap_head,struct kvm_memory_slot * slot,gfn_t gfn,int level,unsigned long data)1970 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1971 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1972 			 unsigned long data)
1973 {
1974 	u64 *sptep;
1975 	struct rmap_iterator uninitialized_var(iter);
1976 	int young = 0;
1977 
1978 	for_each_rmap_spte(rmap_head, &iter, sptep)
1979 		young |= mmu_spte_age(sptep);
1980 
1981 	trace_kvm_age_page(gfn, level, slot, young);
1982 	return young;
1983 }
1984 
kvm_test_age_rmapp(struct kvm * kvm,struct kvm_rmap_head * rmap_head,struct kvm_memory_slot * slot,gfn_t gfn,int level,unsigned long data)1985 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1986 			      struct kvm_memory_slot *slot, gfn_t gfn,
1987 			      int level, unsigned long data)
1988 {
1989 	u64 *sptep;
1990 	struct rmap_iterator iter;
1991 
1992 	for_each_rmap_spte(rmap_head, &iter, sptep)
1993 		if (is_accessed_spte(*sptep))
1994 			return 1;
1995 	return 0;
1996 }
1997 
1998 #define RMAP_RECYCLE_THRESHOLD 1000
1999 
rmap_recycle(struct kvm_vcpu * vcpu,u64 * spte,gfn_t gfn)2000 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2001 {
2002 	struct kvm_rmap_head *rmap_head;
2003 	struct kvm_mmu_page *sp;
2004 
2005 	sp = page_header(__pa(spte));
2006 
2007 	rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2008 
2009 	kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2010 	kvm_flush_remote_tlbs(vcpu->kvm);
2011 }
2012 
kvm_age_hva(struct kvm * kvm,unsigned long start,unsigned long end)2013 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2014 {
2015 	return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2016 }
2017 
kvm_test_age_hva(struct kvm * kvm,unsigned long hva)2018 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2019 {
2020 	return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2021 }
2022 
2023 #ifdef MMU_DEBUG
is_empty_shadow_page(u64 * spt)2024 static int is_empty_shadow_page(u64 *spt)
2025 {
2026 	u64 *pos;
2027 	u64 *end;
2028 
2029 	for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2030 		if (is_shadow_present_pte(*pos)) {
2031 			printk(KERN_ERR "%s: %p %llx\n", __func__,
2032 			       pos, *pos);
2033 			return 0;
2034 		}
2035 	return 1;
2036 }
2037 #endif
2038 
2039 /*
2040  * This value is the sum of all of the kvm instances's
2041  * kvm->arch.n_used_mmu_pages values.  We need a global,
2042  * aggregate version in order to make the slab shrinker
2043  * faster
2044  */
kvm_mod_used_mmu_pages(struct kvm * kvm,unsigned long nr)2045 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2046 {
2047 	kvm->arch.n_used_mmu_pages += nr;
2048 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2049 }
2050 
kvm_mmu_free_page(struct kvm_mmu_page * sp)2051 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2052 {
2053 	MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2054 	hlist_del(&sp->hash_link);
2055 	list_del(&sp->link);
2056 	free_page((unsigned long)sp->spt);
2057 	if (!sp->role.direct)
2058 		free_page((unsigned long)sp->gfns);
2059 	kmem_cache_free(mmu_page_header_cache, sp);
2060 }
2061 
kvm_page_table_hashfn(gfn_t gfn)2062 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2063 {
2064 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2065 }
2066 
mmu_page_add_parent_pte(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * parent_pte)2067 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2068 				    struct kvm_mmu_page *sp, u64 *parent_pte)
2069 {
2070 	if (!parent_pte)
2071 		return;
2072 
2073 	pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2074 }
2075 
mmu_page_remove_parent_pte(struct kvm_mmu_page * sp,u64 * parent_pte)2076 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2077 				       u64 *parent_pte)
2078 {
2079 	pte_list_remove(parent_pte, &sp->parent_ptes);
2080 }
2081 
drop_parent_pte(struct kvm_mmu_page * sp,u64 * parent_pte)2082 static void drop_parent_pte(struct kvm_mmu_page *sp,
2083 			    u64 *parent_pte)
2084 {
2085 	mmu_page_remove_parent_pte(sp, parent_pte);
2086 	mmu_spte_clear_no_track(parent_pte);
2087 }
2088 
kvm_mmu_alloc_page(struct kvm_vcpu * vcpu,int direct)2089 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2090 {
2091 	struct kvm_mmu_page *sp;
2092 
2093 	sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2094 	sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2095 	if (!direct)
2096 		sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2097 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2098 
2099 	/*
2100 	 * The active_mmu_pages list is the FIFO list, do not move the
2101 	 * page until it is zapped. kvm_zap_obsolete_pages depends on
2102 	 * this feature. See the comments in kvm_zap_obsolete_pages().
2103 	 */
2104 	list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2105 	kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2106 	return sp;
2107 }
2108 
2109 static void mark_unsync(u64 *spte);
kvm_mmu_mark_parents_unsync(struct kvm_mmu_page * sp)2110 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2111 {
2112 	u64 *sptep;
2113 	struct rmap_iterator iter;
2114 
2115 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2116 		mark_unsync(sptep);
2117 	}
2118 }
2119 
mark_unsync(u64 * spte)2120 static void mark_unsync(u64 *spte)
2121 {
2122 	struct kvm_mmu_page *sp;
2123 	unsigned int index;
2124 
2125 	sp = page_header(__pa(spte));
2126 	index = spte - sp->spt;
2127 	if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2128 		return;
2129 	if (sp->unsync_children++)
2130 		return;
2131 	kvm_mmu_mark_parents_unsync(sp);
2132 }
2133 
nonpaging_sync_page(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp)2134 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2135 			       struct kvm_mmu_page *sp)
2136 {
2137 	return 0;
2138 }
2139 
nonpaging_invlpg(struct kvm_vcpu * vcpu,gva_t gva,hpa_t root)2140 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2141 {
2142 }
2143 
nonpaging_update_pte(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * spte,const void * pte)2144 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2145 				 struct kvm_mmu_page *sp, u64 *spte,
2146 				 const void *pte)
2147 {
2148 	WARN_ON(1);
2149 }
2150 
2151 #define KVM_PAGE_ARRAY_NR 16
2152 
2153 struct kvm_mmu_pages {
2154 	struct mmu_page_and_offset {
2155 		struct kvm_mmu_page *sp;
2156 		unsigned int idx;
2157 	} page[KVM_PAGE_ARRAY_NR];
2158 	unsigned int nr;
2159 };
2160 
mmu_pages_add(struct kvm_mmu_pages * pvec,struct kvm_mmu_page * sp,int idx)2161 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2162 			 int idx)
2163 {
2164 	int i;
2165 
2166 	if (sp->unsync)
2167 		for (i=0; i < pvec->nr; i++)
2168 			if (pvec->page[i].sp == sp)
2169 				return 0;
2170 
2171 	pvec->page[pvec->nr].sp = sp;
2172 	pvec->page[pvec->nr].idx = idx;
2173 	pvec->nr++;
2174 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
2175 }
2176 
clear_unsync_child_bit(struct kvm_mmu_page * sp,int idx)2177 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2178 {
2179 	--sp->unsync_children;
2180 	WARN_ON((int)sp->unsync_children < 0);
2181 	__clear_bit(idx, sp->unsync_child_bitmap);
2182 }
2183 
__mmu_unsync_walk(struct kvm_mmu_page * sp,struct kvm_mmu_pages * pvec)2184 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2185 			   struct kvm_mmu_pages *pvec)
2186 {
2187 	int i, ret, nr_unsync_leaf = 0;
2188 
2189 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2190 		struct kvm_mmu_page *child;
2191 		u64 ent = sp->spt[i];
2192 
2193 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2194 			clear_unsync_child_bit(sp, i);
2195 			continue;
2196 		}
2197 
2198 		child = page_header(ent & PT64_BASE_ADDR_MASK);
2199 
2200 		if (child->unsync_children) {
2201 			if (mmu_pages_add(pvec, child, i))
2202 				return -ENOSPC;
2203 
2204 			ret = __mmu_unsync_walk(child, pvec);
2205 			if (!ret) {
2206 				clear_unsync_child_bit(sp, i);
2207 				continue;
2208 			} else if (ret > 0) {
2209 				nr_unsync_leaf += ret;
2210 			} else
2211 				return ret;
2212 		} else if (child->unsync) {
2213 			nr_unsync_leaf++;
2214 			if (mmu_pages_add(pvec, child, i))
2215 				return -ENOSPC;
2216 		} else
2217 			clear_unsync_child_bit(sp, i);
2218 	}
2219 
2220 	return nr_unsync_leaf;
2221 }
2222 
2223 #define INVALID_INDEX (-1)
2224 
mmu_unsync_walk(struct kvm_mmu_page * sp,struct kvm_mmu_pages * pvec)2225 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2226 			   struct kvm_mmu_pages *pvec)
2227 {
2228 	pvec->nr = 0;
2229 	if (!sp->unsync_children)
2230 		return 0;
2231 
2232 	mmu_pages_add(pvec, sp, INVALID_INDEX);
2233 	return __mmu_unsync_walk(sp, pvec);
2234 }
2235 
kvm_unlink_unsync_page(struct kvm * kvm,struct kvm_mmu_page * sp)2236 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2237 {
2238 	WARN_ON(!sp->unsync);
2239 	trace_kvm_mmu_sync_page(sp);
2240 	sp->unsync = 0;
2241 	--kvm->stat.mmu_unsync;
2242 }
2243 
2244 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2245 				    struct list_head *invalid_list);
2246 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2247 				    struct list_head *invalid_list);
2248 
2249 /*
2250  * NOTE: we should pay more attention on the zapped-obsolete page
2251  * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
2252  * since it has been deleted from active_mmu_pages but still can be found
2253  * at hast list.
2254  *
2255  * for_each_valid_sp() has skipped that kind of pages.
2256  */
2257 #define for_each_valid_sp(_kvm, _sp, _gfn)				\
2258 	hlist_for_each_entry(_sp,					\
2259 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2260 		if (is_obsolete_sp((_kvm), (_sp)) || (_sp)->role.invalid) {    \
2261 		} else
2262 
2263 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn)			\
2264 	for_each_valid_sp(_kvm, _sp, _gfn)				\
2265 		if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2266 
2267 /* @sp->gfn should be write-protected at the call site */
__kvm_sync_page(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,struct list_head * invalid_list)2268 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2269 			    struct list_head *invalid_list)
2270 {
2271 	if (sp->role.cr4_pae != !!is_pae(vcpu)
2272 	    || vcpu->arch.mmu.sync_page(vcpu, sp) == 0) {
2273 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2274 		return false;
2275 	}
2276 
2277 	return true;
2278 }
2279 
kvm_mmu_flush_or_zap(struct kvm_vcpu * vcpu,struct list_head * invalid_list,bool remote_flush,bool local_flush)2280 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2281 				 struct list_head *invalid_list,
2282 				 bool remote_flush, bool local_flush)
2283 {
2284 	if (!list_empty(invalid_list)) {
2285 		kvm_mmu_commit_zap_page(vcpu->kvm, invalid_list);
2286 		return;
2287 	}
2288 
2289 	if (remote_flush)
2290 		kvm_flush_remote_tlbs(vcpu->kvm);
2291 	else if (local_flush)
2292 		kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2293 }
2294 
2295 #ifdef CONFIG_KVM_MMU_AUDIT
2296 #include "mmu_audit.c"
2297 #else
kvm_mmu_audit(struct kvm_vcpu * vcpu,int point)2298 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
mmu_audit_disable(void)2299 static void mmu_audit_disable(void) { }
2300 #endif
2301 
is_obsolete_sp(struct kvm * kvm,struct kvm_mmu_page * sp)2302 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2303 {
2304 	return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2305 }
2306 
kvm_sync_page(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,struct list_head * invalid_list)2307 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2308 			 struct list_head *invalid_list)
2309 {
2310 	kvm_unlink_unsync_page(vcpu->kvm, sp);
2311 	return __kvm_sync_page(vcpu, sp, invalid_list);
2312 }
2313 
2314 /* @gfn should be write-protected at the call site */
kvm_sync_pages(struct kvm_vcpu * vcpu,gfn_t gfn,struct list_head * invalid_list)2315 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2316 			   struct list_head *invalid_list)
2317 {
2318 	struct kvm_mmu_page *s;
2319 	bool ret = false;
2320 
2321 	for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2322 		if (!s->unsync)
2323 			continue;
2324 
2325 		WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2326 		ret |= kvm_sync_page(vcpu, s, invalid_list);
2327 	}
2328 
2329 	return ret;
2330 }
2331 
2332 struct mmu_page_path {
2333 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2334 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
2335 };
2336 
2337 #define for_each_sp(pvec, sp, parents, i)			\
2338 		for (i = mmu_pages_first(&pvec, &parents);	\
2339 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
2340 			i = mmu_pages_next(&pvec, &parents, i))
2341 
mmu_pages_next(struct kvm_mmu_pages * pvec,struct mmu_page_path * parents,int i)2342 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2343 			  struct mmu_page_path *parents,
2344 			  int i)
2345 {
2346 	int n;
2347 
2348 	for (n = i+1; n < pvec->nr; n++) {
2349 		struct kvm_mmu_page *sp = pvec->page[n].sp;
2350 		unsigned idx = pvec->page[n].idx;
2351 		int level = sp->role.level;
2352 
2353 		parents->idx[level-1] = idx;
2354 		if (level == PT_PAGE_TABLE_LEVEL)
2355 			break;
2356 
2357 		parents->parent[level-2] = sp;
2358 	}
2359 
2360 	return n;
2361 }
2362 
mmu_pages_first(struct kvm_mmu_pages * pvec,struct mmu_page_path * parents)2363 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2364 			   struct mmu_page_path *parents)
2365 {
2366 	struct kvm_mmu_page *sp;
2367 	int level;
2368 
2369 	if (pvec->nr == 0)
2370 		return 0;
2371 
2372 	WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2373 
2374 	sp = pvec->page[0].sp;
2375 	level = sp->role.level;
2376 	WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2377 
2378 	parents->parent[level-2] = sp;
2379 
2380 	/* Also set up a sentinel.  Further entries in pvec are all
2381 	 * children of sp, so this element is never overwritten.
2382 	 */
2383 	parents->parent[level-1] = NULL;
2384 	return mmu_pages_next(pvec, parents, 0);
2385 }
2386 
mmu_pages_clear_parents(struct mmu_page_path * parents)2387 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2388 {
2389 	struct kvm_mmu_page *sp;
2390 	unsigned int level = 0;
2391 
2392 	do {
2393 		unsigned int idx = parents->idx[level];
2394 		sp = parents->parent[level];
2395 		if (!sp)
2396 			return;
2397 
2398 		WARN_ON(idx == INVALID_INDEX);
2399 		clear_unsync_child_bit(sp, idx);
2400 		level++;
2401 	} while (!sp->unsync_children);
2402 }
2403 
mmu_sync_children(struct kvm_vcpu * vcpu,struct kvm_mmu_page * parent)2404 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2405 			      struct kvm_mmu_page *parent)
2406 {
2407 	int i;
2408 	struct kvm_mmu_page *sp;
2409 	struct mmu_page_path parents;
2410 	struct kvm_mmu_pages pages;
2411 	LIST_HEAD(invalid_list);
2412 	bool flush = false;
2413 
2414 	while (mmu_unsync_walk(parent, &pages)) {
2415 		bool protected = false;
2416 
2417 		for_each_sp(pages, sp, parents, i)
2418 			protected |= rmap_write_protect(vcpu, sp->gfn);
2419 
2420 		if (protected) {
2421 			kvm_flush_remote_tlbs(vcpu->kvm);
2422 			flush = false;
2423 		}
2424 
2425 		for_each_sp(pages, sp, parents, i) {
2426 			flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2427 			mmu_pages_clear_parents(&parents);
2428 		}
2429 		if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2430 			kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2431 			cond_resched_lock(&vcpu->kvm->mmu_lock);
2432 			flush = false;
2433 		}
2434 	}
2435 
2436 	kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2437 }
2438 
__clear_sp_write_flooding_count(struct kvm_mmu_page * sp)2439 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2440 {
2441 	atomic_set(&sp->write_flooding_count,  0);
2442 }
2443 
clear_sp_write_flooding_count(u64 * spte)2444 static void clear_sp_write_flooding_count(u64 *spte)
2445 {
2446 	struct kvm_mmu_page *sp =  page_header(__pa(spte));
2447 
2448 	__clear_sp_write_flooding_count(sp);
2449 }
2450 
kvm_mmu_get_page(struct kvm_vcpu * vcpu,gfn_t gfn,gva_t gaddr,unsigned level,int direct,unsigned access)2451 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2452 					     gfn_t gfn,
2453 					     gva_t gaddr,
2454 					     unsigned level,
2455 					     int direct,
2456 					     unsigned access)
2457 {
2458 	union kvm_mmu_page_role role;
2459 	unsigned quadrant;
2460 	struct kvm_mmu_page *sp;
2461 	bool need_sync = false;
2462 	bool flush = false;
2463 	int collisions = 0;
2464 	LIST_HEAD(invalid_list);
2465 
2466 	role = vcpu->arch.mmu.base_role;
2467 	role.level = level;
2468 	role.direct = direct;
2469 	if (role.direct)
2470 		role.cr4_pae = 0;
2471 	role.access = access;
2472 	if (!vcpu->arch.mmu.direct_map
2473 	    && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
2474 		quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2475 		quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2476 		role.quadrant = quadrant;
2477 	}
2478 	for_each_valid_sp(vcpu->kvm, sp, gfn) {
2479 		if (sp->gfn != gfn) {
2480 			collisions++;
2481 			continue;
2482 		}
2483 
2484 		if (!need_sync && sp->unsync)
2485 			need_sync = true;
2486 
2487 		if (sp->role.word != role.word)
2488 			continue;
2489 
2490 		if (sp->unsync) {
2491 			/* The page is good, but __kvm_sync_page might still end
2492 			 * up zapping it.  If so, break in order to rebuild it.
2493 			 */
2494 			if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2495 				break;
2496 
2497 			WARN_ON(!list_empty(&invalid_list));
2498 			kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2499 		}
2500 
2501 		if (sp->unsync_children)
2502 			kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2503 
2504 		__clear_sp_write_flooding_count(sp);
2505 		trace_kvm_mmu_get_page(sp, false);
2506 		goto out;
2507 	}
2508 
2509 	++vcpu->kvm->stat.mmu_cache_miss;
2510 
2511 	sp = kvm_mmu_alloc_page(vcpu, direct);
2512 
2513 	sp->gfn = gfn;
2514 	sp->role = role;
2515 	hlist_add_head(&sp->hash_link,
2516 		&vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2517 	if (!direct) {
2518 		/*
2519 		 * we should do write protection before syncing pages
2520 		 * otherwise the content of the synced shadow page may
2521 		 * be inconsistent with guest page table.
2522 		 */
2523 		account_shadowed(vcpu->kvm, sp);
2524 		if (level == PT_PAGE_TABLE_LEVEL &&
2525 		      rmap_write_protect(vcpu, gfn))
2526 			kvm_flush_remote_tlbs(vcpu->kvm);
2527 
2528 		if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2529 			flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2530 	}
2531 	sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2532 	clear_page(sp->spt);
2533 	trace_kvm_mmu_get_page(sp, true);
2534 
2535 	kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2536 out:
2537 	if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2538 		vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2539 	return sp;
2540 }
2541 
shadow_walk_init_using_root(struct kvm_shadow_walk_iterator * iterator,struct kvm_vcpu * vcpu,hpa_t root,u64 addr)2542 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2543 					struct kvm_vcpu *vcpu, hpa_t root,
2544 					u64 addr)
2545 {
2546 	iterator->addr = addr;
2547 	iterator->shadow_addr = root;
2548 	iterator->level = vcpu->arch.mmu.shadow_root_level;
2549 
2550 	if (iterator->level == PT64_ROOT_4LEVEL &&
2551 	    vcpu->arch.mmu.root_level < PT64_ROOT_4LEVEL &&
2552 	    !vcpu->arch.mmu.direct_map)
2553 		--iterator->level;
2554 
2555 	if (iterator->level == PT32E_ROOT_LEVEL) {
2556 		/*
2557 		 * prev_root is currently only used for 64-bit hosts. So only
2558 		 * the active root_hpa is valid here.
2559 		 */
2560 		BUG_ON(root != vcpu->arch.mmu.root_hpa);
2561 
2562 		iterator->shadow_addr
2563 			= vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
2564 		iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2565 		--iterator->level;
2566 		if (!iterator->shadow_addr)
2567 			iterator->level = 0;
2568 	}
2569 }
2570 
shadow_walk_init(struct kvm_shadow_walk_iterator * iterator,struct kvm_vcpu * vcpu,u64 addr)2571 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2572 			     struct kvm_vcpu *vcpu, u64 addr)
2573 {
2574 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu.root_hpa,
2575 				    addr);
2576 }
2577 
shadow_walk_okay(struct kvm_shadow_walk_iterator * iterator)2578 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2579 {
2580 	if (iterator->level < PT_PAGE_TABLE_LEVEL)
2581 		return false;
2582 
2583 	iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2584 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2585 	return true;
2586 }
2587 
__shadow_walk_next(struct kvm_shadow_walk_iterator * iterator,u64 spte)2588 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2589 			       u64 spte)
2590 {
2591 	if (is_last_spte(spte, iterator->level)) {
2592 		iterator->level = 0;
2593 		return;
2594 	}
2595 
2596 	iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2597 	--iterator->level;
2598 }
2599 
shadow_walk_next(struct kvm_shadow_walk_iterator * iterator)2600 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2601 {
2602 	__shadow_walk_next(iterator, *iterator->sptep);
2603 }
2604 
link_shadow_page(struct kvm_vcpu * vcpu,u64 * sptep,struct kvm_mmu_page * sp)2605 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2606 			     struct kvm_mmu_page *sp)
2607 {
2608 	u64 spte;
2609 
2610 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2611 
2612 	spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2613 	       shadow_user_mask | shadow_x_mask | shadow_me_mask;
2614 
2615 	if (sp_ad_disabled(sp))
2616 		spte |= shadow_acc_track_value;
2617 	else
2618 		spte |= shadow_accessed_mask;
2619 
2620 	mmu_spte_set(sptep, spte);
2621 
2622 	mmu_page_add_parent_pte(vcpu, sp, sptep);
2623 
2624 	if (sp->unsync_children || sp->unsync)
2625 		mark_unsync(sptep);
2626 }
2627 
validate_direct_spte(struct kvm_vcpu * vcpu,u64 * sptep,unsigned direct_access)2628 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2629 				   unsigned direct_access)
2630 {
2631 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2632 		struct kvm_mmu_page *child;
2633 
2634 		/*
2635 		 * For the direct sp, if the guest pte's dirty bit
2636 		 * changed form clean to dirty, it will corrupt the
2637 		 * sp's access: allow writable in the read-only sp,
2638 		 * so we should update the spte at this point to get
2639 		 * a new sp with the correct access.
2640 		 */
2641 		child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2642 		if (child->role.access == direct_access)
2643 			return;
2644 
2645 		drop_parent_pte(child, sptep);
2646 		kvm_flush_remote_tlbs(vcpu->kvm);
2647 	}
2648 }
2649 
mmu_page_zap_pte(struct kvm * kvm,struct kvm_mmu_page * sp,u64 * spte)2650 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2651 			     u64 *spte)
2652 {
2653 	u64 pte;
2654 	struct kvm_mmu_page *child;
2655 
2656 	pte = *spte;
2657 	if (is_shadow_present_pte(pte)) {
2658 		if (is_last_spte(pte, sp->role.level)) {
2659 			drop_spte(kvm, spte);
2660 			if (is_large_pte(pte))
2661 				--kvm->stat.lpages;
2662 		} else {
2663 			child = page_header(pte & PT64_BASE_ADDR_MASK);
2664 			drop_parent_pte(child, spte);
2665 		}
2666 		return true;
2667 	}
2668 
2669 	if (is_mmio_spte(pte))
2670 		mmu_spte_clear_no_track(spte);
2671 
2672 	return false;
2673 }
2674 
kvm_mmu_page_unlink_children(struct kvm * kvm,struct kvm_mmu_page * sp)2675 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2676 					 struct kvm_mmu_page *sp)
2677 {
2678 	unsigned i;
2679 
2680 	for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2681 		mmu_page_zap_pte(kvm, sp, sp->spt + i);
2682 }
2683 
kvm_mmu_unlink_parents(struct kvm * kvm,struct kvm_mmu_page * sp)2684 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2685 {
2686 	u64 *sptep;
2687 	struct rmap_iterator iter;
2688 
2689 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2690 		drop_parent_pte(sp, sptep);
2691 }
2692 
mmu_zap_unsync_children(struct kvm * kvm,struct kvm_mmu_page * parent,struct list_head * invalid_list)2693 static int mmu_zap_unsync_children(struct kvm *kvm,
2694 				   struct kvm_mmu_page *parent,
2695 				   struct list_head *invalid_list)
2696 {
2697 	int i, zapped = 0;
2698 	struct mmu_page_path parents;
2699 	struct kvm_mmu_pages pages;
2700 
2701 	if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2702 		return 0;
2703 
2704 	while (mmu_unsync_walk(parent, &pages)) {
2705 		struct kvm_mmu_page *sp;
2706 
2707 		for_each_sp(pages, sp, parents, i) {
2708 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2709 			mmu_pages_clear_parents(&parents);
2710 			zapped++;
2711 		}
2712 	}
2713 
2714 	return zapped;
2715 }
2716 
kvm_mmu_prepare_zap_page(struct kvm * kvm,struct kvm_mmu_page * sp,struct list_head * invalid_list)2717 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2718 				    struct list_head *invalid_list)
2719 {
2720 	int ret;
2721 
2722 	trace_kvm_mmu_prepare_zap_page(sp);
2723 	++kvm->stat.mmu_shadow_zapped;
2724 	ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
2725 	kvm_mmu_page_unlink_children(kvm, sp);
2726 	kvm_mmu_unlink_parents(kvm, sp);
2727 
2728 	if (!sp->role.invalid && !sp->role.direct)
2729 		unaccount_shadowed(kvm, sp);
2730 
2731 	if (sp->unsync)
2732 		kvm_unlink_unsync_page(kvm, sp);
2733 	if (!sp->root_count) {
2734 		/* Count self */
2735 		ret++;
2736 		list_move(&sp->link, invalid_list);
2737 		kvm_mod_used_mmu_pages(kvm, -1);
2738 	} else {
2739 		list_move(&sp->link, &kvm->arch.active_mmu_pages);
2740 
2741 		/*
2742 		 * The obsolete pages can not be used on any vcpus.
2743 		 * See the comments in kvm_mmu_invalidate_zap_all_pages().
2744 		 */
2745 		if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
2746 			kvm_reload_remote_mmus(kvm);
2747 	}
2748 
2749 	if (sp->lpage_disallowed)
2750 		unaccount_huge_nx_page(kvm, sp);
2751 
2752 	sp->role.invalid = 1;
2753 	return ret;
2754 }
2755 
kvm_mmu_commit_zap_page(struct kvm * kvm,struct list_head * invalid_list)2756 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2757 				    struct list_head *invalid_list)
2758 {
2759 	struct kvm_mmu_page *sp, *nsp;
2760 
2761 	if (list_empty(invalid_list))
2762 		return;
2763 
2764 	/*
2765 	 * We need to make sure everyone sees our modifications to
2766 	 * the page tables and see changes to vcpu->mode here. The barrier
2767 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2768 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2769 	 *
2770 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2771 	 * guest mode and/or lockless shadow page table walks.
2772 	 */
2773 	kvm_flush_remote_tlbs(kvm);
2774 
2775 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2776 		WARN_ON(!sp->role.invalid || sp->root_count);
2777 		kvm_mmu_free_page(sp);
2778 	}
2779 }
2780 
prepare_zap_oldest_mmu_page(struct kvm * kvm,struct list_head * invalid_list)2781 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2782 					struct list_head *invalid_list)
2783 {
2784 	struct kvm_mmu_page *sp;
2785 
2786 	if (list_empty(&kvm->arch.active_mmu_pages))
2787 		return false;
2788 
2789 	sp = list_last_entry(&kvm->arch.active_mmu_pages,
2790 			     struct kvm_mmu_page, link);
2791 	return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2792 }
2793 
2794 /*
2795  * Changing the number of mmu pages allocated to the vm
2796  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2797  */
kvm_mmu_change_mmu_pages(struct kvm * kvm,unsigned long goal_nr_mmu_pages)2798 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2799 {
2800 	LIST_HEAD(invalid_list);
2801 
2802 	spin_lock(&kvm->mmu_lock);
2803 
2804 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2805 		/* Need to free some mmu pages to achieve the goal. */
2806 		while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2807 			if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2808 				break;
2809 
2810 		kvm_mmu_commit_zap_page(kvm, &invalid_list);
2811 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2812 	}
2813 
2814 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2815 
2816 	spin_unlock(&kvm->mmu_lock);
2817 }
2818 
kvm_mmu_unprotect_page(struct kvm * kvm,gfn_t gfn)2819 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2820 {
2821 	struct kvm_mmu_page *sp;
2822 	LIST_HEAD(invalid_list);
2823 	int r;
2824 
2825 	pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2826 	r = 0;
2827 	spin_lock(&kvm->mmu_lock);
2828 	for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2829 		pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2830 			 sp->role.word);
2831 		r = 1;
2832 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2833 	}
2834 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2835 	spin_unlock(&kvm->mmu_lock);
2836 
2837 	return r;
2838 }
2839 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2840 
kvm_unsync_page(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp)2841 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2842 {
2843 	trace_kvm_mmu_unsync_page(sp);
2844 	++vcpu->kvm->stat.mmu_unsync;
2845 	sp->unsync = 1;
2846 
2847 	kvm_mmu_mark_parents_unsync(sp);
2848 }
2849 
mmu_need_write_protect(struct kvm_vcpu * vcpu,gfn_t gfn,bool can_unsync)2850 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2851 				   bool can_unsync)
2852 {
2853 	struct kvm_mmu_page *sp;
2854 
2855 	if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2856 		return true;
2857 
2858 	for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2859 		if (!can_unsync)
2860 			return true;
2861 
2862 		if (sp->unsync)
2863 			continue;
2864 
2865 		WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2866 		kvm_unsync_page(vcpu, sp);
2867 	}
2868 
2869 	/*
2870 	 * We need to ensure that the marking of unsync pages is visible
2871 	 * before the SPTE is updated to allow writes because
2872 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2873 	 * the MMU lock and so can race with this. If the SPTE was updated
2874 	 * before the page had been marked as unsync-ed, something like the
2875 	 * following could happen:
2876 	 *
2877 	 * CPU 1                    CPU 2
2878 	 * ---------------------------------------------------------------------
2879 	 * 1.2 Host updates SPTE
2880 	 *     to be writable
2881 	 *                      2.1 Guest writes a GPTE for GVA X.
2882 	 *                          (GPTE being in the guest page table shadowed
2883 	 *                           by the SP from CPU 1.)
2884 	 *                          This reads SPTE during the page table walk.
2885 	 *                          Since SPTE.W is read as 1, there is no
2886 	 *                          fault.
2887 	 *
2888 	 *                      2.2 Guest issues TLB flush.
2889 	 *                          That causes a VM Exit.
2890 	 *
2891 	 *                      2.3 kvm_mmu_sync_pages() reads sp->unsync.
2892 	 *                          Since it is false, so it just returns.
2893 	 *
2894 	 *                      2.4 Guest accesses GVA X.
2895 	 *                          Since the mapping in the SP was not updated,
2896 	 *                          so the old mapping for GVA X incorrectly
2897 	 *                          gets used.
2898 	 * 1.1 Host marks SP
2899 	 *     as unsync
2900 	 *     (sp->unsync = true)
2901 	 *
2902 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2903 	 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2904 	 * pairs with this write barrier.
2905 	 */
2906 	smp_wmb();
2907 
2908 	return false;
2909 }
2910 
kvm_is_mmio_pfn(kvm_pfn_t pfn)2911 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2912 {
2913 	if (pfn_valid(pfn))
2914 		return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2915 			/*
2916 			 * Some reserved pages, such as those from NVDIMM
2917 			 * DAX devices, are not for MMIO, and can be mapped
2918 			 * with cached memory type for better performance.
2919 			 * However, the above check misconceives those pages
2920 			 * as MMIO, and results in KVM mapping them with UC
2921 			 * memory type, which would hurt the performance.
2922 			 * Therefore, we check the host memory type in addition
2923 			 * and only treat UC/UC-/WC pages as MMIO.
2924 			 */
2925 			(!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2926 
2927 	return true;
2928 }
2929 
2930 /* Bits which may be returned by set_spte() */
2931 #define SET_SPTE_WRITE_PROTECTED_PT	BIT(0)
2932 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH	BIT(1)
2933 
set_spte(struct kvm_vcpu * vcpu,u64 * sptep,unsigned pte_access,int level,gfn_t gfn,kvm_pfn_t pfn,bool speculative,bool can_unsync,bool host_writable)2934 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2935 		    unsigned pte_access, int level,
2936 		    gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2937 		    bool can_unsync, bool host_writable)
2938 {
2939 	u64 spte = 0;
2940 	int ret = 0;
2941 	struct kvm_mmu_page *sp;
2942 
2943 	if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2944 		return 0;
2945 
2946 	sp = page_header(__pa(sptep));
2947 	if (sp_ad_disabled(sp))
2948 		spte |= shadow_acc_track_value;
2949 
2950 	/*
2951 	 * For the EPT case, shadow_present_mask is 0 if hardware
2952 	 * supports exec-only page table entries.  In that case,
2953 	 * ACC_USER_MASK and shadow_user_mask are used to represent
2954 	 * read access.  See FNAME(gpte_access) in paging_tmpl.h.
2955 	 */
2956 	spte |= shadow_present_mask;
2957 	if (!speculative)
2958 		spte |= spte_shadow_accessed_mask(spte);
2959 
2960 	if (level > PT_PAGE_TABLE_LEVEL && (pte_access & ACC_EXEC_MASK) &&
2961 	    is_nx_huge_page_enabled()) {
2962 		pte_access &= ~ACC_EXEC_MASK;
2963 	}
2964 
2965 	if (pte_access & ACC_EXEC_MASK)
2966 		spte |= shadow_x_mask;
2967 	else
2968 		spte |= shadow_nx_mask;
2969 
2970 	if (pte_access & ACC_USER_MASK)
2971 		spte |= shadow_user_mask;
2972 
2973 	if (level > PT_PAGE_TABLE_LEVEL)
2974 		spte |= PT_PAGE_SIZE_MASK;
2975 	if (tdp_enabled)
2976 		spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2977 			kvm_is_mmio_pfn(pfn));
2978 
2979 	if (host_writable)
2980 		spte |= SPTE_HOST_WRITEABLE;
2981 	else
2982 		pte_access &= ~ACC_WRITE_MASK;
2983 
2984 	if (!kvm_is_mmio_pfn(pfn))
2985 		spte |= shadow_me_mask;
2986 
2987 	spte |= (u64)pfn << PAGE_SHIFT;
2988 
2989 	if (pte_access & ACC_WRITE_MASK) {
2990 
2991 		/*
2992 		 * Other vcpu creates new sp in the window between
2993 		 * mapping_level() and acquiring mmu-lock. We can
2994 		 * allow guest to retry the access, the mapping can
2995 		 * be fixed if guest refault.
2996 		 */
2997 		if (level > PT_PAGE_TABLE_LEVEL &&
2998 		    mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
2999 			goto done;
3000 
3001 		spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3002 
3003 		/*
3004 		 * Optimization: for pte sync, if spte was writable the hash
3005 		 * lookup is unnecessary (and expensive). Write protection
3006 		 * is responsibility of mmu_get_page / kvm_sync_page.
3007 		 * Same reasoning can be applied to dirty page accounting.
3008 		 */
3009 		if (!can_unsync && is_writable_pte(*sptep))
3010 			goto set_pte;
3011 
3012 		if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3013 			pgprintk("%s: found shadow page for %llx, marking ro\n",
3014 				 __func__, gfn);
3015 			ret |= SET_SPTE_WRITE_PROTECTED_PT;
3016 			pte_access &= ~ACC_WRITE_MASK;
3017 			spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3018 		}
3019 	}
3020 
3021 	if (pte_access & ACC_WRITE_MASK) {
3022 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
3023 		spte |= spte_shadow_dirty_mask(spte);
3024 	}
3025 
3026 	if (speculative)
3027 		spte = mark_spte_for_access_track(spte);
3028 
3029 set_pte:
3030 	if (mmu_spte_update(sptep, spte))
3031 		ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3032 done:
3033 	return ret;
3034 }
3035 
mmu_set_spte(struct kvm_vcpu * vcpu,u64 * sptep,unsigned pte_access,int write_fault,int level,gfn_t gfn,kvm_pfn_t pfn,bool speculative,bool host_writable)3036 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3037 			int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3038 		       	bool speculative, bool host_writable)
3039 {
3040 	int was_rmapped = 0;
3041 	int rmap_count;
3042 	int set_spte_ret;
3043 	int ret = RET_PF_RETRY;
3044 	bool flush = false;
3045 
3046 	pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3047 		 *sptep, write_fault, gfn);
3048 
3049 	if (is_shadow_present_pte(*sptep)) {
3050 		/*
3051 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3052 		 * the parent of the now unreachable PTE.
3053 		 */
3054 		if (level > PT_PAGE_TABLE_LEVEL &&
3055 		    !is_large_pte(*sptep)) {
3056 			struct kvm_mmu_page *child;
3057 			u64 pte = *sptep;
3058 
3059 			child = page_header(pte & PT64_BASE_ADDR_MASK);
3060 			drop_parent_pte(child, sptep);
3061 			flush = true;
3062 		} else if (pfn != spte_to_pfn(*sptep)) {
3063 			pgprintk("hfn old %llx new %llx\n",
3064 				 spte_to_pfn(*sptep), pfn);
3065 			drop_spte(vcpu->kvm, sptep);
3066 			flush = true;
3067 		} else
3068 			was_rmapped = 1;
3069 	}
3070 
3071 	set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3072 				speculative, true, host_writable);
3073 	if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3074 		if (write_fault)
3075 			ret = RET_PF_EMULATE;
3076 		kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3077 	}
3078 	if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3079 		kvm_flush_remote_tlbs(vcpu->kvm);
3080 
3081 	if (unlikely(is_mmio_spte(*sptep)))
3082 		ret = RET_PF_EMULATE;
3083 
3084 	pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3085 	trace_kvm_mmu_set_spte(level, gfn, sptep);
3086 	if (!was_rmapped && is_large_pte(*sptep))
3087 		++vcpu->kvm->stat.lpages;
3088 
3089 	if (is_shadow_present_pte(*sptep)) {
3090 		if (!was_rmapped) {
3091 			rmap_count = rmap_add(vcpu, sptep, gfn);
3092 			if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3093 				rmap_recycle(vcpu, sptep, gfn);
3094 		}
3095 	}
3096 
3097 	return ret;
3098 }
3099 
pte_prefetch_gfn_to_pfn(struct kvm_vcpu * vcpu,gfn_t gfn,bool no_dirty_log)3100 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3101 				     bool no_dirty_log)
3102 {
3103 	struct kvm_memory_slot *slot;
3104 
3105 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3106 	if (!slot)
3107 		return KVM_PFN_ERR_FAULT;
3108 
3109 	return gfn_to_pfn_memslot_atomic(slot, gfn);
3110 }
3111 
direct_pte_prefetch_many(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * start,u64 * end)3112 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3113 				    struct kvm_mmu_page *sp,
3114 				    u64 *start, u64 *end)
3115 {
3116 	struct page *pages[PTE_PREFETCH_NUM];
3117 	struct kvm_memory_slot *slot;
3118 	unsigned access = sp->role.access;
3119 	int i, ret;
3120 	gfn_t gfn;
3121 
3122 	gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3123 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3124 	if (!slot)
3125 		return -1;
3126 
3127 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3128 	if (ret <= 0)
3129 		return -1;
3130 
3131 	for (i = 0; i < ret; i++, gfn++, start++) {
3132 		mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3133 			     page_to_pfn(pages[i]), true, true);
3134 		put_page(pages[i]);
3135 	}
3136 
3137 	return 0;
3138 }
3139 
__direct_pte_prefetch(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * sptep)3140 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3141 				  struct kvm_mmu_page *sp, u64 *sptep)
3142 {
3143 	u64 *spte, *start = NULL;
3144 	int i;
3145 
3146 	WARN_ON(!sp->role.direct);
3147 
3148 	i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3149 	spte = sp->spt + i;
3150 
3151 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3152 		if (is_shadow_present_pte(*spte) || spte == sptep) {
3153 			if (!start)
3154 				continue;
3155 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3156 				break;
3157 			start = NULL;
3158 		} else if (!start)
3159 			start = spte;
3160 	}
3161 }
3162 
direct_pte_prefetch(struct kvm_vcpu * vcpu,u64 * sptep)3163 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3164 {
3165 	struct kvm_mmu_page *sp;
3166 
3167 	sp = page_header(__pa(sptep));
3168 
3169 	/*
3170 	 * Without accessed bits, there's no way to distinguish between
3171 	 * actually accessed translations and prefetched, so disable pte
3172 	 * prefetch if accessed bits aren't available.
3173 	 */
3174 	if (sp_ad_disabled(sp))
3175 		return;
3176 
3177 	if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3178 		return;
3179 
3180 	__direct_pte_prefetch(vcpu, sp, sptep);
3181 }
3182 
disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,gfn_t gfn,kvm_pfn_t * pfnp,int * levelp)3183 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3184 				       gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3185 {
3186 	int level = *levelp;
3187 	u64 spte = *it.sptep;
3188 
3189 	if (it.level == level && level > PT_PAGE_TABLE_LEVEL &&
3190 	    is_nx_huge_page_enabled() &&
3191 	    is_shadow_present_pte(spte) &&
3192 	    !is_large_pte(spte)) {
3193 		/*
3194 		 * A small SPTE exists for this pfn, but FNAME(fetch)
3195 		 * and __direct_map would like to create a large PTE
3196 		 * instead: just force them to go down another level,
3197 		 * patching back for them into pfn the next 9 bits of
3198 		 * the address.
3199 		 */
3200 		u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3201 		*pfnp |= gfn & page_mask;
3202 		(*levelp)--;
3203 	}
3204 }
3205 
__direct_map(struct kvm_vcpu * vcpu,gpa_t gpa,int write,int map_writable,int level,kvm_pfn_t pfn,bool prefault,bool lpage_disallowed)3206 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3207 			int map_writable, int level, kvm_pfn_t pfn,
3208 			bool prefault, bool lpage_disallowed)
3209 {
3210 	struct kvm_shadow_walk_iterator it;
3211 	struct kvm_mmu_page *sp;
3212 	int ret;
3213 	gfn_t gfn = gpa >> PAGE_SHIFT;
3214 	gfn_t base_gfn = gfn;
3215 
3216 	if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3217 		return RET_PF_RETRY;
3218 
3219 	trace_kvm_mmu_spte_requested(gpa, level, pfn);
3220 	for_each_shadow_entry(vcpu, gpa, it) {
3221 		/*
3222 		 * We cannot overwrite existing page tables with an NX
3223 		 * large page, as the leaf could be executable.
3224 		 */
3225 		disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3226 
3227 		base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3228 		if (it.level == level)
3229 			break;
3230 
3231 		drop_large_spte(vcpu, it.sptep);
3232 		if (!is_shadow_present_pte(*it.sptep)) {
3233 			sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3234 					      it.level - 1, true, ACC_ALL);
3235 
3236 			link_shadow_page(vcpu, it.sptep, sp);
3237 			if (lpage_disallowed)
3238 				account_huge_nx_page(vcpu->kvm, sp);
3239 		}
3240 	}
3241 
3242 	ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3243 			   write, level, base_gfn, pfn, prefault,
3244 			   map_writable);
3245 	direct_pte_prefetch(vcpu, it.sptep);
3246 	++vcpu->stat.pf_fixed;
3247 	return ret;
3248 }
3249 
kvm_send_hwpoison_signal(unsigned long address,struct task_struct * tsk)3250 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3251 {
3252 	siginfo_t info;
3253 
3254 	clear_siginfo(&info);
3255 	info.si_signo	= SIGBUS;
3256 	info.si_errno	= 0;
3257 	info.si_code	= BUS_MCEERR_AR;
3258 	info.si_addr	= (void __user *)address;
3259 	info.si_addr_lsb = PAGE_SHIFT;
3260 
3261 	send_sig_info(SIGBUS, &info, tsk);
3262 }
3263 
kvm_handle_bad_page(struct kvm_vcpu * vcpu,gfn_t gfn,kvm_pfn_t pfn)3264 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3265 {
3266 	/*
3267 	 * Do not cache the mmio info caused by writing the readonly gfn
3268 	 * into the spte otherwise read access on readonly gfn also can
3269 	 * caused mmio page fault and treat it as mmio access.
3270 	 */
3271 	if (pfn == KVM_PFN_ERR_RO_FAULT)
3272 		return RET_PF_EMULATE;
3273 
3274 	if (pfn == KVM_PFN_ERR_HWPOISON) {
3275 		kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3276 		return RET_PF_RETRY;
3277 	}
3278 
3279 	return -EFAULT;
3280 }
3281 
transparent_hugepage_adjust(struct kvm_vcpu * vcpu,gfn_t gfn,kvm_pfn_t * pfnp,int * levelp)3282 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3283 					gfn_t gfn, kvm_pfn_t *pfnp,
3284 					int *levelp)
3285 {
3286 	kvm_pfn_t pfn = *pfnp;
3287 	int level = *levelp;
3288 
3289 	/*
3290 	 * Check if it's a transparent hugepage. If this would be an
3291 	 * hugetlbfs page, level wouldn't be set to
3292 	 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3293 	 * here.
3294 	 */
3295 	if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3296 	    !kvm_is_zone_device_pfn(pfn) && level == PT_PAGE_TABLE_LEVEL &&
3297 	    PageTransCompoundMap(pfn_to_page(pfn)) &&
3298 	    !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3299 		unsigned long mask;
3300 		/*
3301 		 * mmu_notifier_retry was successful and we hold the
3302 		 * mmu_lock here, so the pmd can't become splitting
3303 		 * from under us, and in turn
3304 		 * __split_huge_page_refcount() can't run from under
3305 		 * us and we can safely transfer the refcount from
3306 		 * PG_tail to PG_head as we switch the pfn to tail to
3307 		 * head.
3308 		 */
3309 		*levelp = level = PT_DIRECTORY_LEVEL;
3310 		mask = KVM_PAGES_PER_HPAGE(level) - 1;
3311 		VM_BUG_ON((gfn & mask) != (pfn & mask));
3312 		if (pfn & mask) {
3313 			kvm_release_pfn_clean(pfn);
3314 			pfn &= ~mask;
3315 			kvm_get_pfn(pfn);
3316 			*pfnp = pfn;
3317 		}
3318 	}
3319 }
3320 
handle_abnormal_pfn(struct kvm_vcpu * vcpu,gva_t gva,gfn_t gfn,kvm_pfn_t pfn,unsigned access,int * ret_val)3321 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3322 				kvm_pfn_t pfn, unsigned access, int *ret_val)
3323 {
3324 	/* The pfn is invalid, report the error! */
3325 	if (unlikely(is_error_pfn(pfn))) {
3326 		*ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3327 		return true;
3328 	}
3329 
3330 	if (unlikely(is_noslot_pfn(pfn)))
3331 		vcpu_cache_mmio_info(vcpu, gva, gfn, access);
3332 
3333 	return false;
3334 }
3335 
page_fault_can_be_fast(u32 error_code)3336 static bool page_fault_can_be_fast(u32 error_code)
3337 {
3338 	/*
3339 	 * Do not fix the mmio spte with invalid generation number which
3340 	 * need to be updated by slow page fault path.
3341 	 */
3342 	if (unlikely(error_code & PFERR_RSVD_MASK))
3343 		return false;
3344 
3345 	/* See if the page fault is due to an NX violation */
3346 	if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3347 		      == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3348 		return false;
3349 
3350 	/*
3351 	 * #PF can be fast if:
3352 	 * 1. The shadow page table entry is not present, which could mean that
3353 	 *    the fault is potentially caused by access tracking (if enabled).
3354 	 * 2. The shadow page table entry is present and the fault
3355 	 *    is caused by write-protect, that means we just need change the W
3356 	 *    bit of the spte which can be done out of mmu-lock.
3357 	 *
3358 	 * However, if access tracking is disabled we know that a non-present
3359 	 * page must be a genuine page fault where we have to create a new SPTE.
3360 	 * So, if access tracking is disabled, we return true only for write
3361 	 * accesses to a present page.
3362 	 */
3363 
3364 	return shadow_acc_track_mask != 0 ||
3365 	       ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3366 		== (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3367 }
3368 
3369 /*
3370  * Returns true if the SPTE was fixed successfully. Otherwise,
3371  * someone else modified the SPTE from its original value.
3372  */
3373 static bool
fast_pf_fix_direct_spte(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * sptep,u64 old_spte,u64 new_spte)3374 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3375 			u64 *sptep, u64 old_spte, u64 new_spte)
3376 {
3377 	gfn_t gfn;
3378 
3379 	WARN_ON(!sp->role.direct);
3380 
3381 	/*
3382 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3383 	 * order to eliminate unnecessary PML logging. See comments in
3384 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3385 	 * enabled, so we do not do this. This might result in the same GPA
3386 	 * to be logged in PML buffer again when the write really happens, and
3387 	 * eventually to be called by mark_page_dirty twice. But it's also no
3388 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3389 	 * so non-PML cases won't be impacted.
3390 	 *
3391 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3392 	 */
3393 	if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3394 		return false;
3395 
3396 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3397 		/*
3398 		 * The gfn of direct spte is stable since it is
3399 		 * calculated by sp->gfn.
3400 		 */
3401 		gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3402 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
3403 	}
3404 
3405 	return true;
3406 }
3407 
is_access_allowed(u32 fault_err_code,u64 spte)3408 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3409 {
3410 	if (fault_err_code & PFERR_FETCH_MASK)
3411 		return is_executable_pte(spte);
3412 
3413 	if (fault_err_code & PFERR_WRITE_MASK)
3414 		return is_writable_pte(spte);
3415 
3416 	/* Fault was on Read access */
3417 	return spte & PT_PRESENT_MASK;
3418 }
3419 
3420 /*
3421  * Return value:
3422  * - true: let the vcpu to access on the same address again.
3423  * - false: let the real page fault path to fix it.
3424  */
fast_page_fault(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int level,u32 error_code)3425 static bool fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, int level,
3426 			    u32 error_code)
3427 {
3428 	struct kvm_shadow_walk_iterator iterator;
3429 	struct kvm_mmu_page *sp;
3430 	bool fault_handled = false;
3431 	u64 spte = 0ull;
3432 	uint retry_count = 0;
3433 
3434 	if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3435 		return false;
3436 
3437 	if (!page_fault_can_be_fast(error_code))
3438 		return false;
3439 
3440 	walk_shadow_page_lockless_begin(vcpu);
3441 
3442 	do {
3443 		u64 new_spte;
3444 
3445 		for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
3446 			if (!is_shadow_present_pte(spte) ||
3447 			    iterator.level < level)
3448 				break;
3449 
3450 		sp = page_header(__pa(iterator.sptep));
3451 		if (!is_last_spte(spte, sp->role.level))
3452 			break;
3453 
3454 		/*
3455 		 * Check whether the memory access that caused the fault would
3456 		 * still cause it if it were to be performed right now. If not,
3457 		 * then this is a spurious fault caused by TLB lazily flushed,
3458 		 * or some other CPU has already fixed the PTE after the
3459 		 * current CPU took the fault.
3460 		 *
3461 		 * Need not check the access of upper level table entries since
3462 		 * they are always ACC_ALL.
3463 		 */
3464 		if (is_access_allowed(error_code, spte)) {
3465 			fault_handled = true;
3466 			break;
3467 		}
3468 
3469 		new_spte = spte;
3470 
3471 		if (is_access_track_spte(spte))
3472 			new_spte = restore_acc_track_spte(new_spte);
3473 
3474 		/*
3475 		 * Currently, to simplify the code, write-protection can
3476 		 * be removed in the fast path only if the SPTE was
3477 		 * write-protected for dirty-logging or access tracking.
3478 		 */
3479 		if ((error_code & PFERR_WRITE_MASK) &&
3480 		    spte_can_locklessly_be_made_writable(spte))
3481 		{
3482 			new_spte |= PT_WRITABLE_MASK;
3483 
3484 			/*
3485 			 * Do not fix write-permission on the large spte.  Since
3486 			 * we only dirty the first page into the dirty-bitmap in
3487 			 * fast_pf_fix_direct_spte(), other pages are missed
3488 			 * if its slot has dirty logging enabled.
3489 			 *
3490 			 * Instead, we let the slow page fault path create a
3491 			 * normal spte to fix the access.
3492 			 *
3493 			 * See the comments in kvm_arch_commit_memory_region().
3494 			 */
3495 			if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3496 				break;
3497 		}
3498 
3499 		/* Verify that the fault can be handled in the fast path */
3500 		if (new_spte == spte ||
3501 		    !is_access_allowed(error_code, new_spte))
3502 			break;
3503 
3504 		/*
3505 		 * Currently, fast page fault only works for direct mapping
3506 		 * since the gfn is not stable for indirect shadow page. See
3507 		 * Documentation/virtual/kvm/locking.txt to get more detail.
3508 		 */
3509 		fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3510 							iterator.sptep, spte,
3511 							new_spte);
3512 		if (fault_handled)
3513 			break;
3514 
3515 		if (++retry_count > 4) {
3516 			printk_once(KERN_WARNING
3517 				"kvm: Fast #PF retrying more than 4 times.\n");
3518 			break;
3519 		}
3520 
3521 	} while (true);
3522 
3523 	trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
3524 			      spte, fault_handled);
3525 	walk_shadow_page_lockless_end(vcpu);
3526 
3527 	return fault_handled;
3528 }
3529 
3530 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3531 			 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
3532 			 bool *writable);
3533 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3534 
nonpaging_map(struct kvm_vcpu * vcpu,gpa_t gpa,u32 error_code,gfn_t gfn,bool prefault)3535 static int nonpaging_map(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
3536 			 gfn_t gfn, bool prefault)
3537 {
3538 	int r;
3539 	int level;
3540 	bool force_pt_level;
3541 	kvm_pfn_t pfn;
3542 	unsigned long mmu_seq;
3543 	bool map_writable, write = error_code & PFERR_WRITE_MASK;
3544 	bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
3545 				is_nx_huge_page_enabled();
3546 
3547 	force_pt_level = lpage_disallowed;
3548 	level = mapping_level(vcpu, gfn, &force_pt_level);
3549 	if (likely(!force_pt_level)) {
3550 		/*
3551 		 * This path builds a PAE pagetable - so we can map
3552 		 * 2mb pages at maximum. Therefore check if the level
3553 		 * is larger than that.
3554 		 */
3555 		if (level > PT_DIRECTORY_LEVEL)
3556 			level = PT_DIRECTORY_LEVEL;
3557 
3558 		gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3559 	}
3560 
3561 	if (fast_page_fault(vcpu, gpa, level, error_code))
3562 		return RET_PF_RETRY;
3563 
3564 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
3565 	smp_rmb();
3566 
3567 	if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
3568 		return RET_PF_RETRY;
3569 
3570 	if (handle_abnormal_pfn(vcpu, gpa, gfn, pfn, ACC_ALL, &r))
3571 		return r;
3572 
3573 	r = RET_PF_RETRY;
3574 	spin_lock(&vcpu->kvm->mmu_lock);
3575 	if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3576 		goto out_unlock;
3577 	if (make_mmu_pages_available(vcpu) < 0)
3578 		goto out_unlock;
3579 	if (likely(!force_pt_level))
3580 		transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3581 	r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
3582 			 prefault, false);
3583 out_unlock:
3584 	spin_unlock(&vcpu->kvm->mmu_lock);
3585 	kvm_release_pfn_clean(pfn);
3586 	return r;
3587 }
3588 
mmu_free_root_page(struct kvm * kvm,hpa_t * root_hpa,struct list_head * invalid_list)3589 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3590 			       struct list_head *invalid_list)
3591 {
3592 	struct kvm_mmu_page *sp;
3593 
3594 	if (!VALID_PAGE(*root_hpa))
3595 		return;
3596 
3597 	sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3598 	--sp->root_count;
3599 	if (!sp->root_count && sp->role.invalid)
3600 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3601 
3602 	*root_hpa = INVALID_PAGE;
3603 }
3604 
3605 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
kvm_mmu_free_roots(struct kvm_vcpu * vcpu,ulong roots_to_free)3606 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, ulong roots_to_free)
3607 {
3608 	int i;
3609 	LIST_HEAD(invalid_list);
3610 	struct kvm_mmu *mmu = &vcpu->arch.mmu;
3611 	bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3612 
3613 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3614 
3615 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3616 	if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3617 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3618 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3619 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3620 				break;
3621 
3622 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3623 			return;
3624 	}
3625 
3626 	spin_lock(&vcpu->kvm->mmu_lock);
3627 
3628 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3629 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3630 			mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3631 					   &invalid_list);
3632 
3633 	if (free_active_root) {
3634 		if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3635 		    (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3636 			mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3637 					   &invalid_list);
3638 		} else {
3639 			for (i = 0; i < 4; ++i)
3640 				if (mmu->pae_root[i] != 0)
3641 					mmu_free_root_page(vcpu->kvm,
3642 							   &mmu->pae_root[i],
3643 							   &invalid_list);
3644 			mmu->root_hpa = INVALID_PAGE;
3645 		}
3646 	}
3647 
3648 	kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3649 	spin_unlock(&vcpu->kvm->mmu_lock);
3650 }
3651 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3652 
mmu_check_root(struct kvm_vcpu * vcpu,gfn_t root_gfn)3653 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3654 {
3655 	int ret = 0;
3656 
3657 	if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3658 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3659 		ret = 1;
3660 	}
3661 
3662 	return ret;
3663 }
3664 
mmu_alloc_direct_roots(struct kvm_vcpu * vcpu)3665 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3666 {
3667 	struct kvm_mmu_page *sp;
3668 	unsigned i;
3669 
3670 	if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL) {
3671 		spin_lock(&vcpu->kvm->mmu_lock);
3672 		if(make_mmu_pages_available(vcpu) < 0) {
3673 			spin_unlock(&vcpu->kvm->mmu_lock);
3674 			return -ENOSPC;
3675 		}
3676 		sp = kvm_mmu_get_page(vcpu, 0, 0,
3677 				vcpu->arch.mmu.shadow_root_level, 1, ACC_ALL);
3678 		++sp->root_count;
3679 		spin_unlock(&vcpu->kvm->mmu_lock);
3680 		vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3681 	} else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3682 		for (i = 0; i < 4; ++i) {
3683 			hpa_t root = vcpu->arch.mmu.pae_root[i];
3684 
3685 			MMU_WARN_ON(VALID_PAGE(root));
3686 			spin_lock(&vcpu->kvm->mmu_lock);
3687 			if (make_mmu_pages_available(vcpu) < 0) {
3688 				spin_unlock(&vcpu->kvm->mmu_lock);
3689 				return -ENOSPC;
3690 			}
3691 			sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3692 					i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3693 			root = __pa(sp->spt);
3694 			++sp->root_count;
3695 			spin_unlock(&vcpu->kvm->mmu_lock);
3696 			vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
3697 		}
3698 		vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3699 	} else
3700 		BUG();
3701 
3702 	return 0;
3703 }
3704 
mmu_alloc_shadow_roots(struct kvm_vcpu * vcpu)3705 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3706 {
3707 	struct kvm_mmu_page *sp;
3708 	u64 pdptr, pm_mask;
3709 	gfn_t root_gfn;
3710 	int i;
3711 
3712 	root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
3713 
3714 	if (mmu_check_root(vcpu, root_gfn))
3715 		return 1;
3716 
3717 	/*
3718 	 * Do we shadow a long mode page table? If so we need to
3719 	 * write-protect the guests page table root.
3720 	 */
3721 	if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3722 		hpa_t root = vcpu->arch.mmu.root_hpa;
3723 
3724 		MMU_WARN_ON(VALID_PAGE(root));
3725 
3726 		spin_lock(&vcpu->kvm->mmu_lock);
3727 		if (make_mmu_pages_available(vcpu) < 0) {
3728 			spin_unlock(&vcpu->kvm->mmu_lock);
3729 			return -ENOSPC;
3730 		}
3731 		sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3732 				vcpu->arch.mmu.shadow_root_level, 0, ACC_ALL);
3733 		root = __pa(sp->spt);
3734 		++sp->root_count;
3735 		spin_unlock(&vcpu->kvm->mmu_lock);
3736 		vcpu->arch.mmu.root_hpa = root;
3737 		return 0;
3738 	}
3739 
3740 	/*
3741 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3742 	 * or a PAE 3-level page table. In either case we need to be aware that
3743 	 * the shadow page table may be a PAE or a long mode page table.
3744 	 */
3745 	pm_mask = PT_PRESENT_MASK;
3746 	if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL)
3747 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3748 
3749 	for (i = 0; i < 4; ++i) {
3750 		hpa_t root = vcpu->arch.mmu.pae_root[i];
3751 
3752 		MMU_WARN_ON(VALID_PAGE(root));
3753 		if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
3754 			pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
3755 			if (!(pdptr & PT_PRESENT_MASK)) {
3756 				vcpu->arch.mmu.pae_root[i] = 0;
3757 				continue;
3758 			}
3759 			root_gfn = pdptr >> PAGE_SHIFT;
3760 			if (mmu_check_root(vcpu, root_gfn))
3761 				return 1;
3762 		}
3763 		spin_lock(&vcpu->kvm->mmu_lock);
3764 		if (make_mmu_pages_available(vcpu) < 0) {
3765 			spin_unlock(&vcpu->kvm->mmu_lock);
3766 			return -ENOSPC;
3767 		}
3768 		sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3769 				      0, ACC_ALL);
3770 		root = __pa(sp->spt);
3771 		++sp->root_count;
3772 		spin_unlock(&vcpu->kvm->mmu_lock);
3773 
3774 		vcpu->arch.mmu.pae_root[i] = root | pm_mask;
3775 	}
3776 	vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3777 
3778 	/*
3779 	 * If we shadow a 32 bit page table with a long mode page
3780 	 * table we enter this path.
3781 	 */
3782 	if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL) {
3783 		if (vcpu->arch.mmu.lm_root == NULL) {
3784 			/*
3785 			 * The additional page necessary for this is only
3786 			 * allocated on demand.
3787 			 */
3788 
3789 			u64 *lm_root;
3790 
3791 			lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3792 			if (lm_root == NULL)
3793 				return 1;
3794 
3795 			lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3796 
3797 			vcpu->arch.mmu.lm_root = lm_root;
3798 		}
3799 
3800 		vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3801 	}
3802 
3803 	return 0;
3804 }
3805 
mmu_alloc_roots(struct kvm_vcpu * vcpu)3806 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3807 {
3808 	if (vcpu->arch.mmu.direct_map)
3809 		return mmu_alloc_direct_roots(vcpu);
3810 	else
3811 		return mmu_alloc_shadow_roots(vcpu);
3812 }
3813 
kvm_mmu_sync_roots(struct kvm_vcpu * vcpu)3814 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3815 {
3816 	int i;
3817 	struct kvm_mmu_page *sp;
3818 
3819 	if (vcpu->arch.mmu.direct_map)
3820 		return;
3821 
3822 	if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3823 		return;
3824 
3825 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3826 
3827 	if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3828 		hpa_t root = vcpu->arch.mmu.root_hpa;
3829 
3830 		sp = page_header(root);
3831 
3832 		/*
3833 		 * Even if another CPU was marking the SP as unsync-ed
3834 		 * simultaneously, any guest page table changes are not
3835 		 * guaranteed to be visible anyway until this VCPU issues a TLB
3836 		 * flush strictly after those changes are made. We only need to
3837 		 * ensure that the other CPU sets these flags before any actual
3838 		 * changes to the page tables are made. The comments in
3839 		 * mmu_need_write_protect() describe what could go wrong if this
3840 		 * requirement isn't satisfied.
3841 		 */
3842 		if (!smp_load_acquire(&sp->unsync) &&
3843 		    !smp_load_acquire(&sp->unsync_children))
3844 			return;
3845 
3846 		spin_lock(&vcpu->kvm->mmu_lock);
3847 		kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3848 
3849 		mmu_sync_children(vcpu, sp);
3850 
3851 		kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3852 		spin_unlock(&vcpu->kvm->mmu_lock);
3853 		return;
3854 	}
3855 
3856 	spin_lock(&vcpu->kvm->mmu_lock);
3857 	kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3858 
3859 	for (i = 0; i < 4; ++i) {
3860 		hpa_t root = vcpu->arch.mmu.pae_root[i];
3861 
3862 		if (root && VALID_PAGE(root)) {
3863 			root &= PT64_BASE_ADDR_MASK;
3864 			sp = page_header(root);
3865 			mmu_sync_children(vcpu, sp);
3866 		}
3867 	}
3868 
3869 	kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3870 	spin_unlock(&vcpu->kvm->mmu_lock);
3871 }
3872 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3873 
nonpaging_gva_to_gpa(struct kvm_vcpu * vcpu,gpa_t vaddr,u32 access,struct x86_exception * exception)3874 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3875 				  u32 access, struct x86_exception *exception)
3876 {
3877 	if (exception)
3878 		exception->error_code = 0;
3879 	return vaddr;
3880 }
3881 
nonpaging_gva_to_gpa_nested(struct kvm_vcpu * vcpu,gpa_t vaddr,u32 access,struct x86_exception * exception)3882 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3883 					 u32 access,
3884 					 struct x86_exception *exception)
3885 {
3886 	if (exception)
3887 		exception->error_code = 0;
3888 	return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3889 }
3890 
3891 static bool
__is_rsvd_bits_set(struct rsvd_bits_validate * rsvd_check,u64 pte,int level)3892 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3893 {
3894 	int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3895 
3896 	return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3897 		((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3898 }
3899 
is_rsvd_bits_set(struct kvm_mmu * mmu,u64 gpte,int level)3900 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3901 {
3902 	return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3903 }
3904 
is_shadow_zero_bits_set(struct kvm_mmu * mmu,u64 spte,int level)3905 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3906 {
3907 	return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3908 }
3909 
mmio_info_in_cache(struct kvm_vcpu * vcpu,u64 addr,bool direct)3910 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3911 {
3912 	/*
3913 	 * A nested guest cannot use the MMIO cache if it is using nested
3914 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3915 	 */
3916 	if (mmu_is_nested(vcpu))
3917 		return false;
3918 
3919 	if (direct)
3920 		return vcpu_match_mmio_gpa(vcpu, addr);
3921 
3922 	return vcpu_match_mmio_gva(vcpu, addr);
3923 }
3924 
3925 /* return true if reserved bit is detected on spte. */
3926 static bool
walk_shadow_page_get_mmio_spte(struct kvm_vcpu * vcpu,u64 addr,u64 * sptep)3927 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3928 {
3929 	struct kvm_shadow_walk_iterator iterator;
3930 	u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3931 	int root, leaf;
3932 	bool reserved = false;
3933 
3934 	if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3935 		goto exit;
3936 
3937 	walk_shadow_page_lockless_begin(vcpu);
3938 
3939 	for (shadow_walk_init(&iterator, vcpu, addr),
3940 		 leaf = root = iterator.level;
3941 	     shadow_walk_okay(&iterator);
3942 	     __shadow_walk_next(&iterator, spte)) {
3943 		spte = mmu_spte_get_lockless(iterator.sptep);
3944 
3945 		sptes[leaf - 1] = spte;
3946 		leaf--;
3947 
3948 		if (!is_shadow_present_pte(spte))
3949 			break;
3950 
3951 		reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
3952 						    iterator.level);
3953 	}
3954 
3955 	walk_shadow_page_lockless_end(vcpu);
3956 
3957 	if (reserved) {
3958 		pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3959 		       __func__, addr);
3960 		while (root > leaf) {
3961 			pr_err("------ spte 0x%llx level %d.\n",
3962 			       sptes[root - 1], root);
3963 			root--;
3964 		}
3965 	}
3966 exit:
3967 	*sptep = spte;
3968 	return reserved;
3969 }
3970 
handle_mmio_page_fault(struct kvm_vcpu * vcpu,u64 addr,bool direct)3971 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3972 {
3973 	u64 spte;
3974 	bool reserved;
3975 
3976 	if (mmio_info_in_cache(vcpu, addr, direct))
3977 		return RET_PF_EMULATE;
3978 
3979 	reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3980 	if (WARN_ON(reserved))
3981 		return -EINVAL;
3982 
3983 	if (is_mmio_spte(spte)) {
3984 		gfn_t gfn = get_mmio_spte_gfn(spte);
3985 		unsigned access = get_mmio_spte_access(spte);
3986 
3987 		if (!check_mmio_spte(vcpu, spte))
3988 			return RET_PF_INVALID;
3989 
3990 		if (direct)
3991 			addr = 0;
3992 
3993 		trace_handle_mmio_page_fault(addr, gfn, access);
3994 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3995 		return RET_PF_EMULATE;
3996 	}
3997 
3998 	/*
3999 	 * If the page table is zapped by other cpus, let CPU fault again on
4000 	 * the address.
4001 	 */
4002 	return RET_PF_RETRY;
4003 }
4004 
page_fault_handle_page_track(struct kvm_vcpu * vcpu,u32 error_code,gfn_t gfn)4005 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4006 					 u32 error_code, gfn_t gfn)
4007 {
4008 	if (unlikely(error_code & PFERR_RSVD_MASK))
4009 		return false;
4010 
4011 	if (!(error_code & PFERR_PRESENT_MASK) ||
4012 	      !(error_code & PFERR_WRITE_MASK))
4013 		return false;
4014 
4015 	/*
4016 	 * guest is writing the page which is write tracked which can
4017 	 * not be fixed by page fault handler.
4018 	 */
4019 	if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4020 		return true;
4021 
4022 	return false;
4023 }
4024 
shadow_page_table_clear_flood(struct kvm_vcpu * vcpu,gva_t addr)4025 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4026 {
4027 	struct kvm_shadow_walk_iterator iterator;
4028 	u64 spte;
4029 
4030 	if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4031 		return;
4032 
4033 	walk_shadow_page_lockless_begin(vcpu);
4034 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4035 		clear_sp_write_flooding_count(iterator.sptep);
4036 		if (!is_shadow_present_pte(spte))
4037 			break;
4038 	}
4039 	walk_shadow_page_lockless_end(vcpu);
4040 }
4041 
nonpaging_page_fault(struct kvm_vcpu * vcpu,gpa_t gpa,u32 error_code,bool prefault)4042 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
4043 				u32 error_code, bool prefault)
4044 {
4045 	gfn_t gfn = gpa >> PAGE_SHIFT;
4046 	int r;
4047 
4048 	/* Note, paging is disabled, ergo gva == gpa. */
4049 	pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
4050 
4051 	if (page_fault_handle_page_track(vcpu, error_code, gfn))
4052 		return RET_PF_EMULATE;
4053 
4054 	r = mmu_topup_memory_caches(vcpu);
4055 	if (r)
4056 		return r;
4057 
4058 	MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
4059 
4060 
4061 	return nonpaging_map(vcpu, gpa & PAGE_MASK,
4062 			     error_code, gfn, prefault);
4063 }
4064 
kvm_arch_setup_async_pf(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,gfn_t gfn)4065 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4066 				   gfn_t gfn)
4067 {
4068 	struct kvm_arch_async_pf arch;
4069 
4070 	arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4071 	arch.gfn = gfn;
4072 	arch.direct_map = vcpu->arch.mmu.direct_map;
4073 	arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
4074 
4075 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4076 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4077 }
4078 
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)4079 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
4080 {
4081 	if (unlikely(!lapic_in_kernel(vcpu) ||
4082 		     kvm_event_needs_reinjection(vcpu) ||
4083 		     vcpu->arch.exception.pending))
4084 		return false;
4085 
4086 	if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
4087 		return false;
4088 
4089 	return kvm_x86_ops->interrupt_allowed(vcpu);
4090 }
4091 
try_async_pf(struct kvm_vcpu * vcpu,bool prefault,gfn_t gfn,gpa_t cr2_or_gpa,kvm_pfn_t * pfn,bool write,bool * writable)4092 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4093 			 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
4094 			 bool *writable)
4095 {
4096 	struct kvm_memory_slot *slot;
4097 	bool async;
4098 
4099 	/*
4100 	 * Don't expose private memslots to L2.
4101 	 */
4102 	if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4103 		*pfn = KVM_PFN_NOSLOT;
4104 		return false;
4105 	}
4106 
4107 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4108 	async = false;
4109 	*pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4110 	if (!async)
4111 		return false; /* *pfn has correct page already */
4112 
4113 	if (!prefault && kvm_can_do_async_pf(vcpu)) {
4114 		trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
4115 		if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4116 			trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
4117 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4118 			return true;
4119 		} else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
4120 			return true;
4121 	}
4122 
4123 	*pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4124 	return false;
4125 }
4126 
kvm_handle_page_fault(struct kvm_vcpu * vcpu,u64 error_code,u64 fault_address,char * insn,int insn_len)4127 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4128 				u64 fault_address, char *insn, int insn_len)
4129 {
4130 	int r = 1;
4131 
4132 #ifndef CONFIG_X86_64
4133 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4134 	if (WARN_ON_ONCE(fault_address >> 32))
4135 		return -EFAULT;
4136 #endif
4137 
4138 	vcpu->arch.l1tf_flush_l1d = true;
4139 	switch (vcpu->arch.apf.host_apf_reason) {
4140 	default:
4141 		trace_kvm_page_fault(fault_address, error_code);
4142 
4143 		if (kvm_event_needs_reinjection(vcpu))
4144 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4145 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4146 				insn_len);
4147 		break;
4148 	case KVM_PV_REASON_PAGE_NOT_PRESENT:
4149 		vcpu->arch.apf.host_apf_reason = 0;
4150 		local_irq_disable();
4151 		kvm_async_pf_task_wait(fault_address, 0);
4152 		local_irq_enable();
4153 		break;
4154 	case KVM_PV_REASON_PAGE_READY:
4155 		vcpu->arch.apf.host_apf_reason = 0;
4156 		local_irq_disable();
4157 		kvm_async_pf_task_wake(fault_address);
4158 		local_irq_enable();
4159 		break;
4160 	}
4161 	return r;
4162 }
4163 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4164 
4165 static bool
check_hugepage_cache_consistency(struct kvm_vcpu * vcpu,gfn_t gfn,int level)4166 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4167 {
4168 	int page_num = KVM_PAGES_PER_HPAGE(level);
4169 
4170 	gfn &= ~(page_num - 1);
4171 
4172 	return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4173 }
4174 
tdp_page_fault(struct kvm_vcpu * vcpu,gpa_t gpa,u32 error_code,bool prefault)4175 static int tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4176 			  bool prefault)
4177 {
4178 	kvm_pfn_t pfn;
4179 	int r;
4180 	int level;
4181 	bool force_pt_level;
4182 	gfn_t gfn = gpa >> PAGE_SHIFT;
4183 	unsigned long mmu_seq;
4184 	int write = error_code & PFERR_WRITE_MASK;
4185 	bool map_writable;
4186 	bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
4187 				is_nx_huge_page_enabled();
4188 
4189 	MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
4190 
4191 	if (page_fault_handle_page_track(vcpu, error_code, gfn))
4192 		return RET_PF_EMULATE;
4193 
4194 	r = mmu_topup_memory_caches(vcpu);
4195 	if (r)
4196 		return r;
4197 
4198 	force_pt_level =
4199 		lpage_disallowed ||
4200 		!check_hugepage_cache_consistency(vcpu, gfn, PT_DIRECTORY_LEVEL);
4201 	level = mapping_level(vcpu, gfn, &force_pt_level);
4202 	if (likely(!force_pt_level)) {
4203 		if (level > PT_DIRECTORY_LEVEL &&
4204 		    !check_hugepage_cache_consistency(vcpu, gfn, level))
4205 			level = PT_DIRECTORY_LEVEL;
4206 		gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4207 	}
4208 
4209 	if (fast_page_fault(vcpu, gpa, level, error_code))
4210 		return RET_PF_RETRY;
4211 
4212 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
4213 	smp_rmb();
4214 
4215 	if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4216 		return RET_PF_RETRY;
4217 
4218 	if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4219 		return r;
4220 
4221 	r = RET_PF_RETRY;
4222 	spin_lock(&vcpu->kvm->mmu_lock);
4223 	if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4224 		goto out_unlock;
4225 	if (make_mmu_pages_available(vcpu) < 0)
4226 		goto out_unlock;
4227 	if (likely(!force_pt_level))
4228 		transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4229 	r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
4230 			 prefault, lpage_disallowed);
4231 out_unlock:
4232 	spin_unlock(&vcpu->kvm->mmu_lock);
4233 	kvm_release_pfn_clean(pfn);
4234 	return r;
4235 }
4236 
nonpaging_init_context(struct kvm_vcpu * vcpu,struct kvm_mmu * context)4237 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4238 				   struct kvm_mmu *context)
4239 {
4240 	context->page_fault = nonpaging_page_fault;
4241 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4242 	context->sync_page = nonpaging_sync_page;
4243 	context->invlpg = nonpaging_invlpg;
4244 	context->update_pte = nonpaging_update_pte;
4245 	context->root_level = 0;
4246 	context->shadow_root_level = PT32E_ROOT_LEVEL;
4247 	context->direct_map = true;
4248 	context->nx = false;
4249 }
4250 
4251 /*
4252  * Find out if a previously cached root matching the new CR3/role is available.
4253  * The current root is also inserted into the cache.
4254  * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4255  * returned.
4256  * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4257  * false is returned. This root should now be freed by the caller.
4258  */
cached_root_available(struct kvm_vcpu * vcpu,gpa_t new_cr3,union kvm_mmu_page_role new_role)4259 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4260 				  union kvm_mmu_page_role new_role)
4261 {
4262 	uint i;
4263 	struct kvm_mmu_root_info root;
4264 	struct kvm_mmu *mmu = &vcpu->arch.mmu;
4265 
4266 	root.cr3 = mmu->get_cr3(vcpu);
4267 	root.hpa = mmu->root_hpa;
4268 
4269 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4270 		swap(root, mmu->prev_roots[i]);
4271 
4272 		if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4273 		    page_header(root.hpa) != NULL &&
4274 		    new_role.word == page_header(root.hpa)->role.word)
4275 			break;
4276 	}
4277 
4278 	mmu->root_hpa = root.hpa;
4279 
4280 	return i < KVM_MMU_NUM_PREV_ROOTS;
4281 }
4282 
fast_cr3_switch(struct kvm_vcpu * vcpu,gpa_t new_cr3,union kvm_mmu_page_role new_role,bool skip_tlb_flush)4283 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4284 			    union kvm_mmu_page_role new_role,
4285 			    bool skip_tlb_flush)
4286 {
4287 	struct kvm_mmu *mmu = &vcpu->arch.mmu;
4288 
4289 	/*
4290 	 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4291 	 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4292 	 * later if necessary.
4293 	 */
4294 	if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4295 	    mmu->root_level >= PT64_ROOT_4LEVEL) {
4296 		if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4297 			return false;
4298 
4299 		if (cached_root_available(vcpu, new_cr3, new_role)) {
4300 			/*
4301 			 * It is possible that the cached previous root page is
4302 			 * obsolete because of a change in the MMU
4303 			 * generation number. However, that is accompanied by
4304 			 * KVM_REQ_MMU_RELOAD, which will free the root that we
4305 			 * have set here and allocate a new one.
4306 			 */
4307 
4308 			kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4309 			if (!skip_tlb_flush) {
4310 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4311 				kvm_x86_ops->tlb_flush(vcpu, true);
4312 			}
4313 
4314 			/*
4315 			 * The last MMIO access's GVA and GPA are cached in the
4316 			 * VCPU. When switching to a new CR3, that GVA->GPA
4317 			 * mapping may no longer be valid. So clear any cached
4318 			 * MMIO info even when we don't need to sync the shadow
4319 			 * page tables.
4320 			 */
4321 			vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4322 
4323 			__clear_sp_write_flooding_count(
4324 				page_header(mmu->root_hpa));
4325 
4326 			return true;
4327 		}
4328 	}
4329 
4330 	return false;
4331 }
4332 
__kvm_mmu_new_cr3(struct kvm_vcpu * vcpu,gpa_t new_cr3,union kvm_mmu_page_role new_role,bool skip_tlb_flush)4333 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4334 			      union kvm_mmu_page_role new_role,
4335 			      bool skip_tlb_flush)
4336 {
4337 	if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4338 		kvm_mmu_free_roots(vcpu, KVM_MMU_ROOT_CURRENT);
4339 }
4340 
kvm_mmu_new_cr3(struct kvm_vcpu * vcpu,gpa_t new_cr3,bool skip_tlb_flush)4341 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4342 {
4343 	__kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4344 			  skip_tlb_flush);
4345 }
4346 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4347 
get_cr3(struct kvm_vcpu * vcpu)4348 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4349 {
4350 	return kvm_read_cr3(vcpu);
4351 }
4352 
inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)4353 static void inject_page_fault(struct kvm_vcpu *vcpu,
4354 			      struct x86_exception *fault)
4355 {
4356 	vcpu->arch.mmu.inject_page_fault(vcpu, fault);
4357 }
4358 
sync_mmio_spte(struct kvm_vcpu * vcpu,u64 * sptep,gfn_t gfn,unsigned access,int * nr_present)4359 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4360 			   unsigned access, int *nr_present)
4361 {
4362 	if (unlikely(is_mmio_spte(*sptep))) {
4363 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4364 			mmu_spte_clear_no_track(sptep);
4365 			return true;
4366 		}
4367 
4368 		(*nr_present)++;
4369 		mark_mmio_spte(vcpu, sptep, gfn, access);
4370 		return true;
4371 	}
4372 
4373 	return false;
4374 }
4375 
is_last_gpte(struct kvm_mmu * mmu,unsigned level,unsigned gpte)4376 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4377 				unsigned level, unsigned gpte)
4378 {
4379 	/*
4380 	 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4381 	 * If it is clear, there are no large pages at this level, so clear
4382 	 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4383 	 */
4384 	gpte &= level - mmu->last_nonleaf_level;
4385 
4386 	/*
4387 	 * PT_PAGE_TABLE_LEVEL always terminates.  The RHS has bit 7 set
4388 	 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4389 	 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4390 	 */
4391 	gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4392 
4393 	return gpte & PT_PAGE_SIZE_MASK;
4394 }
4395 
4396 #define PTTYPE_EPT 18 /* arbitrary */
4397 #define PTTYPE PTTYPE_EPT
4398 #include "paging_tmpl.h"
4399 #undef PTTYPE
4400 
4401 #define PTTYPE 64
4402 #include "paging_tmpl.h"
4403 #undef PTTYPE
4404 
4405 #define PTTYPE 32
4406 #include "paging_tmpl.h"
4407 #undef PTTYPE
4408 
4409 static void
__reset_rsvds_bits_mask(struct kvm_vcpu * vcpu,struct rsvd_bits_validate * rsvd_check,int maxphyaddr,int level,bool nx,bool gbpages,bool pse,bool amd)4410 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4411 			struct rsvd_bits_validate *rsvd_check,
4412 			int maxphyaddr, int level, bool nx, bool gbpages,
4413 			bool pse, bool amd)
4414 {
4415 	u64 exb_bit_rsvd = 0;
4416 	u64 gbpages_bit_rsvd = 0;
4417 	u64 nonleaf_bit8_rsvd = 0;
4418 
4419 	rsvd_check->bad_mt_xwr = 0;
4420 
4421 	if (!nx)
4422 		exb_bit_rsvd = rsvd_bits(63, 63);
4423 	if (!gbpages)
4424 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4425 
4426 	/*
4427 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4428 	 * leaf entries) on AMD CPUs only.
4429 	 */
4430 	if (amd)
4431 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4432 
4433 	switch (level) {
4434 	case PT32_ROOT_LEVEL:
4435 		/* no rsvd bits for 2 level 4K page table entries */
4436 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4437 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4438 		rsvd_check->rsvd_bits_mask[1][0] =
4439 			rsvd_check->rsvd_bits_mask[0][0];
4440 
4441 		if (!pse) {
4442 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4443 			break;
4444 		}
4445 
4446 		if (is_cpuid_PSE36())
4447 			/* 36bits PSE 4MB page */
4448 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4449 		else
4450 			/* 32 bits PSE 4MB page */
4451 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4452 		break;
4453 	case PT32E_ROOT_LEVEL:
4454 		rsvd_check->rsvd_bits_mask[0][2] =
4455 			rsvd_bits(maxphyaddr, 63) |
4456 			rsvd_bits(5, 8) | rsvd_bits(1, 2);	/* PDPTE */
4457 		rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4458 			rsvd_bits(maxphyaddr, 62);	/* PDE */
4459 		rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4460 			rsvd_bits(maxphyaddr, 62); 	/* PTE */
4461 		rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4462 			rsvd_bits(maxphyaddr, 62) |
4463 			rsvd_bits(13, 20);		/* large page */
4464 		rsvd_check->rsvd_bits_mask[1][0] =
4465 			rsvd_check->rsvd_bits_mask[0][0];
4466 		break;
4467 	case PT64_ROOT_5LEVEL:
4468 		rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4469 			nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4470 			rsvd_bits(maxphyaddr, 51);
4471 		rsvd_check->rsvd_bits_mask[1][4] =
4472 			rsvd_check->rsvd_bits_mask[0][4];
4473 	case PT64_ROOT_4LEVEL:
4474 		rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4475 			nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4476 			rsvd_bits(maxphyaddr, 51);
4477 		rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4478 			gbpages_bit_rsvd |
4479 			rsvd_bits(maxphyaddr, 51);
4480 		rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4481 			rsvd_bits(maxphyaddr, 51);
4482 		rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4483 			rsvd_bits(maxphyaddr, 51);
4484 		rsvd_check->rsvd_bits_mask[1][3] =
4485 			rsvd_check->rsvd_bits_mask[0][3];
4486 		rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4487 			gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4488 			rsvd_bits(13, 29);
4489 		rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4490 			rsvd_bits(maxphyaddr, 51) |
4491 			rsvd_bits(13, 20);		/* large page */
4492 		rsvd_check->rsvd_bits_mask[1][0] =
4493 			rsvd_check->rsvd_bits_mask[0][0];
4494 		break;
4495 	}
4496 }
4497 
reset_rsvds_bits_mask(struct kvm_vcpu * vcpu,struct kvm_mmu * context)4498 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4499 				  struct kvm_mmu *context)
4500 {
4501 	__reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4502 				cpuid_maxphyaddr(vcpu), context->root_level,
4503 				context->nx,
4504 				guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4505 				is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4506 }
4507 
4508 static void
__reset_rsvds_bits_mask_ept(struct rsvd_bits_validate * rsvd_check,int maxphyaddr,bool execonly)4509 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4510 			    int maxphyaddr, bool execonly)
4511 {
4512 	u64 bad_mt_xwr;
4513 
4514 	rsvd_check->rsvd_bits_mask[0][4] =
4515 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4516 	rsvd_check->rsvd_bits_mask[0][3] =
4517 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4518 	rsvd_check->rsvd_bits_mask[0][2] =
4519 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4520 	rsvd_check->rsvd_bits_mask[0][1] =
4521 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4522 	rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4523 
4524 	/* large page */
4525 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4526 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4527 	rsvd_check->rsvd_bits_mask[1][2] =
4528 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4529 	rsvd_check->rsvd_bits_mask[1][1] =
4530 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4531 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4532 
4533 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4534 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4535 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4536 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4537 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4538 	if (!execonly) {
4539 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4540 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4541 	}
4542 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4543 }
4544 
reset_rsvds_bits_mask_ept(struct kvm_vcpu * vcpu,struct kvm_mmu * context,bool execonly)4545 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4546 		struct kvm_mmu *context, bool execonly)
4547 {
4548 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4549 				    cpuid_maxphyaddr(vcpu), execonly);
4550 }
4551 
4552 /*
4553  * the page table on host is the shadow page table for the page
4554  * table in guest or amd nested guest, its mmu features completely
4555  * follow the features in guest.
4556  */
4557 void
reset_shadow_zero_bits_mask(struct kvm_vcpu * vcpu,struct kvm_mmu * context)4558 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4559 {
4560 	bool uses_nx = context->nx || context->base_role.smep_andnot_wp;
4561 	struct rsvd_bits_validate *shadow_zero_check;
4562 	int i;
4563 
4564 	/*
4565 	 * Passing "true" to the last argument is okay; it adds a check
4566 	 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4567 	 */
4568 	shadow_zero_check = &context->shadow_zero_check;
4569 	__reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4570 				shadow_phys_bits,
4571 				context->shadow_root_level, uses_nx,
4572 				guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4573 				is_pse(vcpu), true);
4574 
4575 	if (!shadow_me_mask)
4576 		return;
4577 
4578 	for (i = context->shadow_root_level; --i >= 0;) {
4579 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4580 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4581 	}
4582 
4583 }
4584 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4585 
boot_cpu_is_amd(void)4586 static inline bool boot_cpu_is_amd(void)
4587 {
4588 	WARN_ON_ONCE(!tdp_enabled);
4589 	return shadow_x_mask == 0;
4590 }
4591 
4592 /*
4593  * the direct page table on host, use as much mmu features as
4594  * possible, however, kvm currently does not do execution-protection.
4595  */
4596 static void
reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu * vcpu,struct kvm_mmu * context)4597 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4598 				struct kvm_mmu *context)
4599 {
4600 	struct rsvd_bits_validate *shadow_zero_check;
4601 	int i;
4602 
4603 	shadow_zero_check = &context->shadow_zero_check;
4604 
4605 	if (boot_cpu_is_amd())
4606 		__reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4607 					shadow_phys_bits,
4608 					context->shadow_root_level, false,
4609 					boot_cpu_has(X86_FEATURE_GBPAGES),
4610 					true, true);
4611 	else
4612 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
4613 					    shadow_phys_bits,
4614 					    false);
4615 
4616 	if (!shadow_me_mask)
4617 		return;
4618 
4619 	for (i = context->shadow_root_level; --i >= 0;) {
4620 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4621 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4622 	}
4623 }
4624 
4625 /*
4626  * as the comments in reset_shadow_zero_bits_mask() except it
4627  * is the shadow page table for intel nested guest.
4628  */
4629 static void
reset_ept_shadow_zero_bits_mask(struct kvm_vcpu * vcpu,struct kvm_mmu * context,bool execonly)4630 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4631 				struct kvm_mmu *context, bool execonly)
4632 {
4633 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4634 				    shadow_phys_bits, execonly);
4635 }
4636 
4637 #define BYTE_MASK(access) \
4638 	((1 & (access) ? 2 : 0) | \
4639 	 (2 & (access) ? 4 : 0) | \
4640 	 (3 & (access) ? 8 : 0) | \
4641 	 (4 & (access) ? 16 : 0) | \
4642 	 (5 & (access) ? 32 : 0) | \
4643 	 (6 & (access) ? 64 : 0) | \
4644 	 (7 & (access) ? 128 : 0))
4645 
4646 
update_permission_bitmask(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu,bool ept)4647 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4648 				      struct kvm_mmu *mmu, bool ept)
4649 {
4650 	unsigned byte;
4651 
4652 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4653 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4654 	const u8 u = BYTE_MASK(ACC_USER_MASK);
4655 
4656 	bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4657 	bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4658 	bool cr0_wp = is_write_protection(vcpu);
4659 
4660 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4661 		unsigned pfec = byte << 1;
4662 
4663 		/*
4664 		 * Each "*f" variable has a 1 bit for each UWX value
4665 		 * that causes a fault with the given PFEC.
4666 		 */
4667 
4668 		/* Faults from writes to non-writable pages */
4669 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4670 		/* Faults from user mode accesses to supervisor pages */
4671 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4672 		/* Faults from fetches of non-executable pages*/
4673 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4674 		/* Faults from kernel mode fetches of user pages */
4675 		u8 smepf = 0;
4676 		/* Faults from kernel mode accesses of user pages */
4677 		u8 smapf = 0;
4678 
4679 		if (!ept) {
4680 			/* Faults from kernel mode accesses to user pages */
4681 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4682 
4683 			/* Not really needed: !nx will cause pte.nx to fault */
4684 			if (!mmu->nx)
4685 				ff = 0;
4686 
4687 			/* Allow supervisor writes if !cr0.wp */
4688 			if (!cr0_wp)
4689 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4690 
4691 			/* Disallow supervisor fetches of user code if cr4.smep */
4692 			if (cr4_smep)
4693 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4694 
4695 			/*
4696 			 * SMAP:kernel-mode data accesses from user-mode
4697 			 * mappings should fault. A fault is considered
4698 			 * as a SMAP violation if all of the following
4699 			 * conditions are ture:
4700 			 *   - X86_CR4_SMAP is set in CR4
4701 			 *   - A user page is accessed
4702 			 *   - The access is not a fetch
4703 			 *   - Page fault in kernel mode
4704 			 *   - if CPL = 3 or X86_EFLAGS_AC is clear
4705 			 *
4706 			 * Here, we cover the first three conditions.
4707 			 * The fourth is computed dynamically in permission_fault();
4708 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4709 			 * *not* subject to SMAP restrictions.
4710 			 */
4711 			if (cr4_smap)
4712 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4713 		}
4714 
4715 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4716 	}
4717 }
4718 
4719 /*
4720 * PKU is an additional mechanism by which the paging controls access to
4721 * user-mode addresses based on the value in the PKRU register.  Protection
4722 * key violations are reported through a bit in the page fault error code.
4723 * Unlike other bits of the error code, the PK bit is not known at the
4724 * call site of e.g. gva_to_gpa; it must be computed directly in
4725 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4726 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4727 *
4728 * In particular the following conditions come from the error code, the
4729 * page tables and the machine state:
4730 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4731 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4732 * - PK is always zero if U=0 in the page tables
4733 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4734 *
4735 * The PKRU bitmask caches the result of these four conditions.  The error
4736 * code (minus the P bit) and the page table's U bit form an index into the
4737 * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4738 * with the two bits of the PKRU register corresponding to the protection key.
4739 * For the first three conditions above the bits will be 00, thus masking
4740 * away both AD and WD.  For all reads or if the last condition holds, WD
4741 * only will be masked away.
4742 */
update_pkru_bitmask(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu,bool ept)4743 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4744 				bool ept)
4745 {
4746 	unsigned bit;
4747 	bool wp;
4748 
4749 	if (ept) {
4750 		mmu->pkru_mask = 0;
4751 		return;
4752 	}
4753 
4754 	/* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4755 	if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4756 		mmu->pkru_mask = 0;
4757 		return;
4758 	}
4759 
4760 	wp = is_write_protection(vcpu);
4761 
4762 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4763 		unsigned pfec, pkey_bits;
4764 		bool check_pkey, check_write, ff, uf, wf, pte_user;
4765 
4766 		pfec = bit << 1;
4767 		ff = pfec & PFERR_FETCH_MASK;
4768 		uf = pfec & PFERR_USER_MASK;
4769 		wf = pfec & PFERR_WRITE_MASK;
4770 
4771 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
4772 		pte_user = pfec & PFERR_RSVD_MASK;
4773 
4774 		/*
4775 		 * Only need to check the access which is not an
4776 		 * instruction fetch and is to a user page.
4777 		 */
4778 		check_pkey = (!ff && pte_user);
4779 		/*
4780 		 * write access is controlled by PKRU if it is a
4781 		 * user access or CR0.WP = 1.
4782 		 */
4783 		check_write = check_pkey && wf && (uf || wp);
4784 
4785 		/* PKRU.AD stops both read and write access. */
4786 		pkey_bits = !!check_pkey;
4787 		/* PKRU.WD stops write access. */
4788 		pkey_bits |= (!!check_write) << 1;
4789 
4790 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4791 	}
4792 }
4793 
update_last_nonleaf_level(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu)4794 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4795 {
4796 	unsigned root_level = mmu->root_level;
4797 
4798 	mmu->last_nonleaf_level = root_level;
4799 	if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4800 		mmu->last_nonleaf_level++;
4801 }
4802 
paging64_init_context_common(struct kvm_vcpu * vcpu,struct kvm_mmu * context,int level)4803 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4804 					 struct kvm_mmu *context,
4805 					 int level)
4806 {
4807 	context->nx = is_nx(vcpu);
4808 	context->root_level = level;
4809 
4810 	reset_rsvds_bits_mask(vcpu, context);
4811 	update_permission_bitmask(vcpu, context, false);
4812 	update_pkru_bitmask(vcpu, context, false);
4813 	update_last_nonleaf_level(vcpu, context);
4814 
4815 	MMU_WARN_ON(!is_pae(vcpu));
4816 	context->page_fault = paging64_page_fault;
4817 	context->gva_to_gpa = paging64_gva_to_gpa;
4818 	context->sync_page = paging64_sync_page;
4819 	context->invlpg = paging64_invlpg;
4820 	context->update_pte = paging64_update_pte;
4821 	context->shadow_root_level = level;
4822 	context->direct_map = false;
4823 }
4824 
paging64_init_context(struct kvm_vcpu * vcpu,struct kvm_mmu * context)4825 static void paging64_init_context(struct kvm_vcpu *vcpu,
4826 				  struct kvm_mmu *context)
4827 {
4828 	int root_level = is_la57_mode(vcpu) ?
4829 			 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4830 
4831 	paging64_init_context_common(vcpu, context, root_level);
4832 }
4833 
paging32_init_context(struct kvm_vcpu * vcpu,struct kvm_mmu * context)4834 static void paging32_init_context(struct kvm_vcpu *vcpu,
4835 				  struct kvm_mmu *context)
4836 {
4837 	context->nx = false;
4838 	context->root_level = PT32_ROOT_LEVEL;
4839 
4840 	reset_rsvds_bits_mask(vcpu, context);
4841 	update_permission_bitmask(vcpu, context, false);
4842 	update_pkru_bitmask(vcpu, context, false);
4843 	update_last_nonleaf_level(vcpu, context);
4844 
4845 	context->page_fault = paging32_page_fault;
4846 	context->gva_to_gpa = paging32_gva_to_gpa;
4847 	context->sync_page = paging32_sync_page;
4848 	context->invlpg = paging32_invlpg;
4849 	context->update_pte = paging32_update_pte;
4850 	context->shadow_root_level = PT32E_ROOT_LEVEL;
4851 	context->direct_map = false;
4852 }
4853 
paging32E_init_context(struct kvm_vcpu * vcpu,struct kvm_mmu * context)4854 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4855 				   struct kvm_mmu *context)
4856 {
4857 	paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4858 }
4859 
4860 static union kvm_mmu_page_role
kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu * vcpu)4861 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu)
4862 {
4863 	union kvm_mmu_page_role role = {0};
4864 
4865 	role.guest_mode = is_guest_mode(vcpu);
4866 	role.smm = is_smm(vcpu);
4867 	role.ad_disabled = (shadow_accessed_mask == 0);
4868 	role.level = kvm_x86_ops->get_tdp_level(vcpu);
4869 	role.direct = true;
4870 	role.access = ACC_ALL;
4871 
4872 	return role;
4873 }
4874 
init_kvm_tdp_mmu(struct kvm_vcpu * vcpu)4875 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4876 {
4877 	struct kvm_mmu *context = &vcpu->arch.mmu;
4878 
4879 	context->base_role.word = mmu_base_role_mask.word &
4880 				  kvm_calc_tdp_mmu_root_page_role(vcpu).word;
4881 	context->page_fault = tdp_page_fault;
4882 	context->sync_page = nonpaging_sync_page;
4883 	context->invlpg = nonpaging_invlpg;
4884 	context->update_pte = nonpaging_update_pte;
4885 	context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4886 	context->direct_map = true;
4887 	context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4888 	context->get_cr3 = get_cr3;
4889 	context->get_pdptr = kvm_pdptr_read;
4890 	context->inject_page_fault = kvm_inject_page_fault;
4891 
4892 	if (!is_paging(vcpu)) {
4893 		context->nx = false;
4894 		context->gva_to_gpa = nonpaging_gva_to_gpa;
4895 		context->root_level = 0;
4896 	} else if (is_long_mode(vcpu)) {
4897 		context->nx = is_nx(vcpu);
4898 		context->root_level = is_la57_mode(vcpu) ?
4899 				PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4900 		reset_rsvds_bits_mask(vcpu, context);
4901 		context->gva_to_gpa = paging64_gva_to_gpa;
4902 	} else if (is_pae(vcpu)) {
4903 		context->nx = is_nx(vcpu);
4904 		context->root_level = PT32E_ROOT_LEVEL;
4905 		reset_rsvds_bits_mask(vcpu, context);
4906 		context->gva_to_gpa = paging64_gva_to_gpa;
4907 	} else {
4908 		context->nx = false;
4909 		context->root_level = PT32_ROOT_LEVEL;
4910 		reset_rsvds_bits_mask(vcpu, context);
4911 		context->gva_to_gpa = paging32_gva_to_gpa;
4912 	}
4913 
4914 	update_permission_bitmask(vcpu, context, false);
4915 	update_pkru_bitmask(vcpu, context, false);
4916 	update_last_nonleaf_level(vcpu, context);
4917 	reset_tdp_shadow_zero_bits_mask(vcpu, context);
4918 }
4919 
4920 static union kvm_mmu_page_role
kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu * vcpu)4921 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu)
4922 {
4923 	union kvm_mmu_page_role role = {0};
4924 	bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4925 	bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4926 
4927 	role.nxe = is_nx(vcpu);
4928 	role.cr4_pae = !!is_pae(vcpu);
4929 	role.cr0_wp  = is_write_protection(vcpu);
4930 	role.smep_andnot_wp = smep && !is_write_protection(vcpu);
4931 	role.smap_andnot_wp = smap && !is_write_protection(vcpu);
4932 	role.guest_mode = is_guest_mode(vcpu);
4933 	role.smm = is_smm(vcpu);
4934 	role.direct = !is_paging(vcpu);
4935 	role.access = ACC_ALL;
4936 
4937 	if (!is_long_mode(vcpu))
4938 		role.level = PT32E_ROOT_LEVEL;
4939 	else if (is_la57_mode(vcpu))
4940 		role.level = PT64_ROOT_5LEVEL;
4941 	else
4942 		role.level = PT64_ROOT_4LEVEL;
4943 
4944 	return role;
4945 }
4946 
kvm_init_shadow_mmu(struct kvm_vcpu * vcpu)4947 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4948 {
4949 	struct kvm_mmu *context = &vcpu->arch.mmu;
4950 
4951 	if (!is_paging(vcpu))
4952 		nonpaging_init_context(vcpu, context);
4953 	else if (is_long_mode(vcpu))
4954 		paging64_init_context(vcpu, context);
4955 	else if (is_pae(vcpu))
4956 		paging32E_init_context(vcpu, context);
4957 	else
4958 		paging32_init_context(vcpu, context);
4959 
4960 	context->base_role.word = mmu_base_role_mask.word &
4961 				  kvm_calc_shadow_mmu_root_page_role(vcpu).word;
4962 	reset_shadow_zero_bits_mask(vcpu, context);
4963 }
4964 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4965 
4966 static union kvm_mmu_page_role
kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu * vcpu,bool accessed_dirty)4967 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty)
4968 {
4969 	union kvm_mmu_page_role role = vcpu->arch.mmu.base_role;
4970 
4971 	role.level = PT64_ROOT_4LEVEL;
4972 	role.direct = false;
4973 	role.ad_disabled = !accessed_dirty;
4974 	role.guest_mode = true;
4975 	role.access = ACC_ALL;
4976 
4977 	return role;
4978 }
4979 
kvm_init_shadow_ept_mmu(struct kvm_vcpu * vcpu,bool execonly,bool accessed_dirty,gpa_t new_eptp)4980 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4981 			     bool accessed_dirty, gpa_t new_eptp)
4982 {
4983 	struct kvm_mmu *context = &vcpu->arch.mmu;
4984 	union kvm_mmu_page_role root_page_role =
4985 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty);
4986 
4987 	__kvm_mmu_new_cr3(vcpu, new_eptp, root_page_role, false);
4988 	context->shadow_root_level = PT64_ROOT_4LEVEL;
4989 
4990 	context->nx = true;
4991 	context->ept_ad = accessed_dirty;
4992 	context->page_fault = ept_page_fault;
4993 	context->gva_to_gpa = ept_gva_to_gpa;
4994 	context->sync_page = ept_sync_page;
4995 	context->invlpg = ept_invlpg;
4996 	context->update_pte = ept_update_pte;
4997 	context->root_level = PT64_ROOT_4LEVEL;
4998 	context->direct_map = false;
4999 	context->base_role.word = root_page_role.word & mmu_base_role_mask.word;
5000 	update_permission_bitmask(vcpu, context, true);
5001 	update_pkru_bitmask(vcpu, context, true);
5002 	update_last_nonleaf_level(vcpu, context);
5003 	reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5004 	reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5005 }
5006 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5007 
init_kvm_softmmu(struct kvm_vcpu * vcpu)5008 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5009 {
5010 	struct kvm_mmu *context = &vcpu->arch.mmu;
5011 
5012 	kvm_init_shadow_mmu(vcpu);
5013 	context->set_cr3           = kvm_x86_ops->set_cr3;
5014 	context->get_cr3           = get_cr3;
5015 	context->get_pdptr         = kvm_pdptr_read;
5016 	context->inject_page_fault = kvm_inject_page_fault;
5017 }
5018 
init_kvm_nested_mmu(struct kvm_vcpu * vcpu)5019 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5020 {
5021 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5022 
5023 	g_context->get_cr3           = get_cr3;
5024 	g_context->get_pdptr         = kvm_pdptr_read;
5025 	g_context->inject_page_fault = kvm_inject_page_fault;
5026 
5027 	/*
5028 	 * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
5029 	 * L1's nested page tables (e.g. EPT12). The nested translation
5030 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5031 	 * L2's page tables as the first level of translation and L1's
5032 	 * nested page tables as the second level of translation. Basically
5033 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5034 	 */
5035 	if (!is_paging(vcpu)) {
5036 		g_context->nx = false;
5037 		g_context->root_level = 0;
5038 		g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5039 	} else if (is_long_mode(vcpu)) {
5040 		g_context->nx = is_nx(vcpu);
5041 		g_context->root_level = is_la57_mode(vcpu) ?
5042 					PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5043 		reset_rsvds_bits_mask(vcpu, g_context);
5044 		g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5045 	} else if (is_pae(vcpu)) {
5046 		g_context->nx = is_nx(vcpu);
5047 		g_context->root_level = PT32E_ROOT_LEVEL;
5048 		reset_rsvds_bits_mask(vcpu, g_context);
5049 		g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5050 	} else {
5051 		g_context->nx = false;
5052 		g_context->root_level = PT32_ROOT_LEVEL;
5053 		reset_rsvds_bits_mask(vcpu, g_context);
5054 		g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5055 	}
5056 
5057 	update_permission_bitmask(vcpu, g_context, false);
5058 	update_pkru_bitmask(vcpu, g_context, false);
5059 	update_last_nonleaf_level(vcpu, g_context);
5060 }
5061 
kvm_init_mmu(struct kvm_vcpu * vcpu,bool reset_roots)5062 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5063 {
5064 	if (reset_roots) {
5065 		uint i;
5066 
5067 		vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5068 
5069 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5070 			vcpu->arch.mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5071 	}
5072 
5073 	if (mmu_is_nested(vcpu))
5074 		init_kvm_nested_mmu(vcpu);
5075 	else if (tdp_enabled)
5076 		init_kvm_tdp_mmu(vcpu);
5077 	else
5078 		init_kvm_softmmu(vcpu);
5079 }
5080 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5081 
5082 static union kvm_mmu_page_role
kvm_mmu_calc_root_page_role(struct kvm_vcpu * vcpu)5083 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5084 {
5085 	if (tdp_enabled)
5086 		return kvm_calc_tdp_mmu_root_page_role(vcpu);
5087 	else
5088 		return kvm_calc_shadow_mmu_root_page_role(vcpu);
5089 }
5090 
kvm_mmu_reset_context(struct kvm_vcpu * vcpu)5091 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5092 {
5093 	kvm_mmu_unload(vcpu);
5094 	kvm_init_mmu(vcpu, true);
5095 }
5096 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5097 
kvm_mmu_load(struct kvm_vcpu * vcpu)5098 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5099 {
5100 	int r;
5101 
5102 	r = mmu_topup_memory_caches(vcpu);
5103 	if (r)
5104 		goto out;
5105 	r = mmu_alloc_roots(vcpu);
5106 	kvm_mmu_sync_roots(vcpu);
5107 	if (r)
5108 		goto out;
5109 	kvm_mmu_load_cr3(vcpu);
5110 	kvm_x86_ops->tlb_flush(vcpu, true);
5111 out:
5112 	return r;
5113 }
5114 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5115 
kvm_mmu_unload(struct kvm_vcpu * vcpu)5116 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5117 {
5118 	kvm_mmu_free_roots(vcpu, KVM_MMU_ROOTS_ALL);
5119 	WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
5120 }
5121 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5122 
mmu_pte_write_new_pte(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * spte,const void * new)5123 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5124 				  struct kvm_mmu_page *sp, u64 *spte,
5125 				  const void *new)
5126 {
5127 	if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5128 		++vcpu->kvm->stat.mmu_pde_zapped;
5129 		return;
5130         }
5131 
5132 	++vcpu->kvm->stat.mmu_pte_updated;
5133 	vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
5134 }
5135 
need_remote_flush(u64 old,u64 new)5136 static bool need_remote_flush(u64 old, u64 new)
5137 {
5138 	if (!is_shadow_present_pte(old))
5139 		return false;
5140 	if (!is_shadow_present_pte(new))
5141 		return true;
5142 	if ((old ^ new) & PT64_BASE_ADDR_MASK)
5143 		return true;
5144 	old ^= shadow_nx_mask;
5145 	new ^= shadow_nx_mask;
5146 	return (old & ~new & PT64_PERM_MASK) != 0;
5147 }
5148 
mmu_pte_write_fetch_gpte(struct kvm_vcpu * vcpu,gpa_t * gpa,int * bytes)5149 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5150 				    int *bytes)
5151 {
5152 	u64 gentry = 0;
5153 	int r;
5154 
5155 	/*
5156 	 * Assume that the pte write on a page table of the same type
5157 	 * as the current vcpu paging mode since we update the sptes only
5158 	 * when they have the same mode.
5159 	 */
5160 	if (is_pae(vcpu) && *bytes == 4) {
5161 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5162 		*gpa &= ~(gpa_t)7;
5163 		*bytes = 8;
5164 	}
5165 
5166 	if (*bytes == 4 || *bytes == 8) {
5167 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5168 		if (r)
5169 			gentry = 0;
5170 	}
5171 
5172 	return gentry;
5173 }
5174 
5175 /*
5176  * If we're seeing too many writes to a page, it may no longer be a page table,
5177  * or we may be forking, in which case it is better to unmap the page.
5178  */
detect_write_flooding(struct kvm_mmu_page * sp)5179 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5180 {
5181 	/*
5182 	 * Skip write-flooding detected for the sp whose level is 1, because
5183 	 * it can become unsync, then the guest page is not write-protected.
5184 	 */
5185 	if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5186 		return false;
5187 
5188 	atomic_inc(&sp->write_flooding_count);
5189 	return atomic_read(&sp->write_flooding_count) >= 3;
5190 }
5191 
5192 /*
5193  * Misaligned accesses are too much trouble to fix up; also, they usually
5194  * indicate a page is not used as a page table.
5195  */
detect_write_misaligned(struct kvm_mmu_page * sp,gpa_t gpa,int bytes)5196 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5197 				    int bytes)
5198 {
5199 	unsigned offset, pte_size, misaligned;
5200 
5201 	pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5202 		 gpa, bytes, sp->role.word);
5203 
5204 	offset = offset_in_page(gpa);
5205 	pte_size = sp->role.cr4_pae ? 8 : 4;
5206 
5207 	/*
5208 	 * Sometimes, the OS only writes the last one bytes to update status
5209 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5210 	 */
5211 	if (!(offset & (pte_size - 1)) && bytes == 1)
5212 		return false;
5213 
5214 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5215 	misaligned |= bytes < 4;
5216 
5217 	return misaligned;
5218 }
5219 
get_written_sptes(struct kvm_mmu_page * sp,gpa_t gpa,int * nspte)5220 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5221 {
5222 	unsigned page_offset, quadrant;
5223 	u64 *spte;
5224 	int level;
5225 
5226 	page_offset = offset_in_page(gpa);
5227 	level = sp->role.level;
5228 	*nspte = 1;
5229 	if (!sp->role.cr4_pae) {
5230 		page_offset <<= 1;	/* 32->64 */
5231 		/*
5232 		 * A 32-bit pde maps 4MB while the shadow pdes map
5233 		 * only 2MB.  So we need to double the offset again
5234 		 * and zap two pdes instead of one.
5235 		 */
5236 		if (level == PT32_ROOT_LEVEL) {
5237 			page_offset &= ~7; /* kill rounding error */
5238 			page_offset <<= 1;
5239 			*nspte = 2;
5240 		}
5241 		quadrant = page_offset >> PAGE_SHIFT;
5242 		page_offset &= ~PAGE_MASK;
5243 		if (quadrant != sp->role.quadrant)
5244 			return NULL;
5245 	}
5246 
5247 	spte = &sp->spt[page_offset / sizeof(*spte)];
5248 	return spte;
5249 }
5250 
kvm_mmu_pte_write(struct kvm_vcpu * vcpu,gpa_t gpa,const u8 * new,int bytes,struct kvm_page_track_notifier_node * node)5251 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5252 			      const u8 *new, int bytes,
5253 			      struct kvm_page_track_notifier_node *node)
5254 {
5255 	gfn_t gfn = gpa >> PAGE_SHIFT;
5256 	struct kvm_mmu_page *sp;
5257 	LIST_HEAD(invalid_list);
5258 	u64 entry, gentry, *spte;
5259 	int npte;
5260 	bool remote_flush, local_flush;
5261 
5262 	/*
5263 	 * If we don't have indirect shadow pages, it means no page is
5264 	 * write-protected, so we can exit simply.
5265 	 */
5266 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5267 		return;
5268 
5269 	remote_flush = local_flush = false;
5270 
5271 	pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5272 
5273 	/*
5274 	 * No need to care whether allocation memory is successful
5275 	 * or not since pte prefetch is skiped if it does not have
5276 	 * enough objects in the cache.
5277 	 */
5278 	mmu_topup_memory_caches(vcpu);
5279 
5280 	spin_lock(&vcpu->kvm->mmu_lock);
5281 
5282 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5283 
5284 	++vcpu->kvm->stat.mmu_pte_write;
5285 	kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5286 
5287 	for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5288 		if (detect_write_misaligned(sp, gpa, bytes) ||
5289 		      detect_write_flooding(sp)) {
5290 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5291 			++vcpu->kvm->stat.mmu_flooded;
5292 			continue;
5293 		}
5294 
5295 		spte = get_written_sptes(sp, gpa, &npte);
5296 		if (!spte)
5297 			continue;
5298 
5299 		local_flush = true;
5300 		while (npte--) {
5301 			entry = *spte;
5302 			mmu_page_zap_pte(vcpu->kvm, sp, spte);
5303 			if (gentry &&
5304 			      !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
5305 			      & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5306 				mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5307 			if (need_remote_flush(entry, *spte))
5308 				remote_flush = true;
5309 			++spte;
5310 		}
5311 	}
5312 	kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5313 	kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5314 	spin_unlock(&vcpu->kvm->mmu_lock);
5315 }
5316 
kvm_mmu_unprotect_page_virt(struct kvm_vcpu * vcpu,gva_t gva)5317 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5318 {
5319 	gpa_t gpa;
5320 	int r;
5321 
5322 	if (vcpu->arch.mmu.direct_map)
5323 		return 0;
5324 
5325 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5326 
5327 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5328 
5329 	return r;
5330 }
5331 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5332 
make_mmu_pages_available(struct kvm_vcpu * vcpu)5333 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5334 {
5335 	LIST_HEAD(invalid_list);
5336 
5337 	if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5338 		return 0;
5339 
5340 	while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5341 		if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5342 			break;
5343 
5344 		++vcpu->kvm->stat.mmu_recycled;
5345 	}
5346 	kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5347 
5348 	if (!kvm_mmu_available_pages(vcpu->kvm))
5349 		return -ENOSPC;
5350 	return 0;
5351 }
5352 
kvm_mmu_page_fault(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,u64 error_code,void * insn,int insn_len)5353 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5354 		       void *insn, int insn_len)
5355 {
5356 	int r, emulation_type = 0;
5357 	enum emulation_result er;
5358 	bool direct = vcpu->arch.mmu.direct_map;
5359 
5360 	/* With shadow page tables, fault_address contains a GVA or nGPA.  */
5361 	if (vcpu->arch.mmu.direct_map) {
5362 		vcpu->arch.gpa_available = true;
5363 		vcpu->arch.gpa_val = cr2_or_gpa;
5364 	}
5365 
5366 	r = RET_PF_INVALID;
5367 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5368 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5369 		if (r == RET_PF_EMULATE)
5370 			goto emulate;
5371 	}
5372 
5373 	if (r == RET_PF_INVALID) {
5374 		r = vcpu->arch.mmu.page_fault(vcpu, cr2_or_gpa,
5375 					       lower_32_bits(error_code),
5376 					       false);
5377 		WARN_ON(r == RET_PF_INVALID);
5378 	}
5379 
5380 	if (r == RET_PF_RETRY)
5381 		return 1;
5382 	if (r < 0)
5383 		return r;
5384 
5385 	/*
5386 	 * Before emulating the instruction, check if the error code
5387 	 * was due to a RO violation while translating the guest page.
5388 	 * This can occur when using nested virtualization with nested
5389 	 * paging in both guests. If true, we simply unprotect the page
5390 	 * and resume the guest.
5391 	 */
5392 	if (vcpu->arch.mmu.direct_map &&
5393 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5394 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5395 		return 1;
5396 	}
5397 
5398 	/*
5399 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5400 	 * optimistically try to just unprotect the page and let the processor
5401 	 * re-execute the instruction that caused the page fault.  Do not allow
5402 	 * retrying MMIO emulation, as it's not only pointless but could also
5403 	 * cause us to enter an infinite loop because the processor will keep
5404 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5405 	 * from a nested guest is also pointless and dangerous as we are only
5406 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5407 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5408 	 */
5409 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5410 		emulation_type = EMULTYPE_ALLOW_RETRY;
5411 emulate:
5412 	/*
5413 	 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5414 	 * This can happen if a guest gets a page-fault on data access but the HW
5415 	 * table walker is not able to read the instruction page (e.g instruction
5416 	 * page is not present in memory). In those cases we simply restart the
5417 	 * guest.
5418 	 */
5419 	if (unlikely(insn && !insn_len))
5420 		return 1;
5421 
5422 	er = x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn, insn_len);
5423 
5424 	switch (er) {
5425 	case EMULATE_DONE:
5426 		return 1;
5427 	case EMULATE_USER_EXIT:
5428 		++vcpu->stat.mmio_exits;
5429 		/* fall through */
5430 	case EMULATE_FAIL:
5431 		return 0;
5432 	default:
5433 		BUG();
5434 	}
5435 }
5436 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5437 
kvm_mmu_invlpg(struct kvm_vcpu * vcpu,gva_t gva)5438 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5439 {
5440 	struct kvm_mmu *mmu = &vcpu->arch.mmu;
5441 	int i;
5442 
5443 	/* INVLPG on a * non-canonical address is a NOP according to the SDM.  */
5444 	if (is_noncanonical_address(gva, vcpu))
5445 		return;
5446 
5447 	mmu->invlpg(vcpu, gva, mmu->root_hpa);
5448 
5449 	/*
5450 	 * INVLPG is required to invalidate any global mappings for the VA,
5451 	 * irrespective of PCID. Since it would take us roughly similar amount
5452 	 * of work to determine whether any of the prev_root mappings of the VA
5453 	 * is marked global, or to just sync it blindly, so we might as well
5454 	 * just always sync it.
5455 	 *
5456 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5457 	 * synced when switching to that cr3, so nothing needs to be done here
5458 	 * for them.
5459 	 */
5460 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5461 		if (VALID_PAGE(mmu->prev_roots[i].hpa))
5462 			mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5463 
5464 	kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5465 	++vcpu->stat.invlpg;
5466 }
5467 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5468 
kvm_mmu_invpcid_gva(struct kvm_vcpu * vcpu,gva_t gva,unsigned long pcid)5469 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5470 {
5471 	struct kvm_mmu *mmu = &vcpu->arch.mmu;
5472 	bool tlb_flush = false;
5473 	uint i;
5474 
5475 	if (pcid == kvm_get_active_pcid(vcpu)) {
5476 		mmu->invlpg(vcpu, gva, mmu->root_hpa);
5477 		tlb_flush = true;
5478 	}
5479 
5480 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5481 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5482 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5483 			mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5484 			tlb_flush = true;
5485 		}
5486 	}
5487 
5488 	if (tlb_flush)
5489 		kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5490 
5491 	++vcpu->stat.invlpg;
5492 
5493 	/*
5494 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5495 	 * synced when switching to that cr3, so nothing needs to be done here
5496 	 * for them.
5497 	 */
5498 }
5499 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5500 
kvm_enable_tdp(void)5501 void kvm_enable_tdp(void)
5502 {
5503 	tdp_enabled = true;
5504 }
5505 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5506 
kvm_disable_tdp(void)5507 void kvm_disable_tdp(void)
5508 {
5509 	tdp_enabled = false;
5510 }
5511 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5512 
free_mmu_pages(struct kvm_vcpu * vcpu)5513 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5514 {
5515 	free_page((unsigned long)vcpu->arch.mmu.pae_root);
5516 	free_page((unsigned long)vcpu->arch.mmu.lm_root);
5517 }
5518 
alloc_mmu_pages(struct kvm_vcpu * vcpu)5519 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5520 {
5521 	struct page *page;
5522 	int i;
5523 
5524 	/*
5525 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5526 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
5527 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5528 	 * x86_64.  Therefore we need to allocate the PDP table in the first
5529 	 * 4GB of memory, which happens to fit the DMA32 zone.  Except for
5530 	 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5531 	 * skip allocating the PDP table.
5532 	 */
5533 	if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5534 		return 0;
5535 
5536 	/*
5537 	 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5538 	 * Therefore we need to allocate shadow page tables in the first
5539 	 * 4GB of memory, which happens to fit the DMA32 zone.
5540 	 */
5541 	page = alloc_page(GFP_KERNEL | __GFP_DMA32);
5542 	if (!page)
5543 		return -ENOMEM;
5544 
5545 	vcpu->arch.mmu.pae_root = page_address(page);
5546 	for (i = 0; i < 4; ++i)
5547 		vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
5548 
5549 	return 0;
5550 }
5551 
kvm_mmu_create(struct kvm_vcpu * vcpu)5552 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5553 {
5554 	uint i;
5555 
5556 	vcpu->arch.walk_mmu = &vcpu->arch.mmu;
5557 	vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5558 	vcpu->arch.mmu.translate_gpa = translate_gpa;
5559 	vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5560 
5561 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5562 		vcpu->arch.mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5563 
5564 	return alloc_mmu_pages(vcpu);
5565 }
5566 
kvm_mmu_setup(struct kvm_vcpu * vcpu)5567 void kvm_mmu_setup(struct kvm_vcpu *vcpu)
5568 {
5569 	MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
5570 
5571 	/*
5572 	 * kvm_mmu_setup() is called only on vCPU initialization.
5573 	 * Therefore, no need to reset mmu roots as they are not yet
5574 	 * initialized.
5575 	 */
5576 	kvm_init_mmu(vcpu, false);
5577 }
5578 
kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm * kvm,struct kvm_memory_slot * slot,struct kvm_page_track_notifier_node * node)5579 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5580 			struct kvm_memory_slot *slot,
5581 			struct kvm_page_track_notifier_node *node)
5582 {
5583 	kvm_mmu_invalidate_zap_all_pages(kvm);
5584 }
5585 
kvm_mmu_init_vm(struct kvm * kvm)5586 void kvm_mmu_init_vm(struct kvm *kvm)
5587 {
5588 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5589 
5590 	node->track_write = kvm_mmu_pte_write;
5591 	node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5592 	kvm_page_track_register_notifier(kvm, node);
5593 }
5594 
kvm_mmu_uninit_vm(struct kvm * kvm)5595 void kvm_mmu_uninit_vm(struct kvm *kvm)
5596 {
5597 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5598 
5599 	kvm_page_track_unregister_notifier(kvm, node);
5600 }
5601 
5602 /* The return value indicates if tlb flush on all vcpus is needed. */
5603 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5604 
5605 /* The caller should hold mmu-lock before calling this function. */
5606 static __always_inline bool
slot_handle_level_range(struct kvm * kvm,struct kvm_memory_slot * memslot,slot_level_handler fn,int start_level,int end_level,gfn_t start_gfn,gfn_t end_gfn,bool lock_flush_tlb)5607 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5608 			slot_level_handler fn, int start_level, int end_level,
5609 			gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5610 {
5611 	struct slot_rmap_walk_iterator iterator;
5612 	bool flush = false;
5613 
5614 	for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5615 			end_gfn, &iterator) {
5616 		if (iterator.rmap)
5617 			flush |= fn(kvm, iterator.rmap);
5618 
5619 		if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5620 			if (flush && lock_flush_tlb) {
5621 				kvm_flush_remote_tlbs(kvm);
5622 				flush = false;
5623 			}
5624 			cond_resched_lock(&kvm->mmu_lock);
5625 		}
5626 	}
5627 
5628 	if (flush && lock_flush_tlb) {
5629 		kvm_flush_remote_tlbs(kvm);
5630 		flush = false;
5631 	}
5632 
5633 	return flush;
5634 }
5635 
5636 static __always_inline bool
slot_handle_level(struct kvm * kvm,struct kvm_memory_slot * memslot,slot_level_handler fn,int start_level,int end_level,bool lock_flush_tlb)5637 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5638 		  slot_level_handler fn, int start_level, int end_level,
5639 		  bool lock_flush_tlb)
5640 {
5641 	return slot_handle_level_range(kvm, memslot, fn, start_level,
5642 			end_level, memslot->base_gfn,
5643 			memslot->base_gfn + memslot->npages - 1,
5644 			lock_flush_tlb);
5645 }
5646 
5647 static __always_inline bool
slot_handle_all_level(struct kvm * kvm,struct kvm_memory_slot * memslot,slot_level_handler fn,bool lock_flush_tlb)5648 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5649 		      slot_level_handler fn, bool lock_flush_tlb)
5650 {
5651 	return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5652 				 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5653 }
5654 
5655 static __always_inline bool
slot_handle_large_level(struct kvm * kvm,struct kvm_memory_slot * memslot,slot_level_handler fn,bool lock_flush_tlb)5656 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5657 			slot_level_handler fn, bool lock_flush_tlb)
5658 {
5659 	return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5660 				 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5661 }
5662 
5663 static __always_inline bool
slot_handle_leaf(struct kvm * kvm,struct kvm_memory_slot * memslot,slot_level_handler fn,bool lock_flush_tlb)5664 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5665 		 slot_level_handler fn, bool lock_flush_tlb)
5666 {
5667 	return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5668 				 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5669 }
5670 
kvm_zap_gfn_range(struct kvm * kvm,gfn_t gfn_start,gfn_t gfn_end)5671 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5672 {
5673 	struct kvm_memslots *slots;
5674 	struct kvm_memory_slot *memslot;
5675 	int i;
5676 
5677 	spin_lock(&kvm->mmu_lock);
5678 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5679 		slots = __kvm_memslots(kvm, i);
5680 		kvm_for_each_memslot(memslot, slots) {
5681 			gfn_t start, end;
5682 
5683 			start = max(gfn_start, memslot->base_gfn);
5684 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
5685 			if (start >= end)
5686 				continue;
5687 
5688 			slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5689 						PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5690 						start, end - 1, true);
5691 		}
5692 	}
5693 
5694 	spin_unlock(&kvm->mmu_lock);
5695 }
5696 
slot_rmap_write_protect(struct kvm * kvm,struct kvm_rmap_head * rmap_head)5697 static bool slot_rmap_write_protect(struct kvm *kvm,
5698 				    struct kvm_rmap_head *rmap_head)
5699 {
5700 	return __rmap_write_protect(kvm, rmap_head, false);
5701 }
5702 
kvm_mmu_slot_remove_write_access(struct kvm * kvm,struct kvm_memory_slot * memslot)5703 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5704 				      struct kvm_memory_slot *memslot)
5705 {
5706 	bool flush;
5707 
5708 	spin_lock(&kvm->mmu_lock);
5709 	flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5710 				      false);
5711 	spin_unlock(&kvm->mmu_lock);
5712 
5713 	/*
5714 	 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5715 	 * which do tlb flush out of mmu-lock should be serialized by
5716 	 * kvm->slots_lock otherwise tlb flush would be missed.
5717 	 */
5718 	lockdep_assert_held(&kvm->slots_lock);
5719 
5720 	/*
5721 	 * We can flush all the TLBs out of the mmu lock without TLB
5722 	 * corruption since we just change the spte from writable to
5723 	 * readonly so that we only need to care the case of changing
5724 	 * spte from present to present (changing the spte from present
5725 	 * to nonpresent will flush all the TLBs immediately), in other
5726 	 * words, the only case we care is mmu_spte_update() where we
5727 	 * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5728 	 * instead of PT_WRITABLE_MASK, that means it does not depend
5729 	 * on PT_WRITABLE_MASK anymore.
5730 	 */
5731 	if (flush)
5732 		kvm_flush_remote_tlbs(kvm);
5733 }
5734 
kvm_mmu_zap_collapsible_spte(struct kvm * kvm,struct kvm_rmap_head * rmap_head)5735 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5736 					 struct kvm_rmap_head *rmap_head)
5737 {
5738 	u64 *sptep;
5739 	struct rmap_iterator iter;
5740 	int need_tlb_flush = 0;
5741 	kvm_pfn_t pfn;
5742 	struct kvm_mmu_page *sp;
5743 
5744 restart:
5745 	for_each_rmap_spte(rmap_head, &iter, sptep) {
5746 		sp = page_header(__pa(sptep));
5747 		pfn = spte_to_pfn(*sptep);
5748 
5749 		/*
5750 		 * We cannot do huge page mapping for indirect shadow pages,
5751 		 * which are found on the last rmap (level = 1) when not using
5752 		 * tdp; such shadow pages are synced with the page table in
5753 		 * the guest, and the guest page table is using 4K page size
5754 		 * mapping if the indirect sp has level = 1.
5755 		 */
5756 		if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5757 		    !kvm_is_zone_device_pfn(pfn) &&
5758 		    PageTransCompoundMap(pfn_to_page(pfn))) {
5759 			drop_spte(kvm, sptep);
5760 			need_tlb_flush = 1;
5761 			goto restart;
5762 		}
5763 	}
5764 
5765 	return need_tlb_flush;
5766 }
5767 
kvm_mmu_zap_collapsible_sptes(struct kvm * kvm,const struct kvm_memory_slot * memslot)5768 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5769 				   const struct kvm_memory_slot *memslot)
5770 {
5771 	/* FIXME: const-ify all uses of struct kvm_memory_slot.  */
5772 	spin_lock(&kvm->mmu_lock);
5773 	slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5774 			 kvm_mmu_zap_collapsible_spte, true);
5775 	spin_unlock(&kvm->mmu_lock);
5776 }
5777 
kvm_mmu_slot_leaf_clear_dirty(struct kvm * kvm,struct kvm_memory_slot * memslot)5778 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5779 				   struct kvm_memory_slot *memslot)
5780 {
5781 	bool flush;
5782 
5783 	spin_lock(&kvm->mmu_lock);
5784 	flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5785 	spin_unlock(&kvm->mmu_lock);
5786 
5787 	lockdep_assert_held(&kvm->slots_lock);
5788 
5789 	/*
5790 	 * It's also safe to flush TLBs out of mmu lock here as currently this
5791 	 * function is only used for dirty logging, in which case flushing TLB
5792 	 * out of mmu lock also guarantees no dirty pages will be lost in
5793 	 * dirty_bitmap.
5794 	 */
5795 	if (flush)
5796 		kvm_flush_remote_tlbs(kvm);
5797 }
5798 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5799 
kvm_mmu_slot_largepage_remove_write_access(struct kvm * kvm,struct kvm_memory_slot * memslot)5800 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5801 					struct kvm_memory_slot *memslot)
5802 {
5803 	bool flush;
5804 
5805 	spin_lock(&kvm->mmu_lock);
5806 	flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5807 					false);
5808 	spin_unlock(&kvm->mmu_lock);
5809 
5810 	/* see kvm_mmu_slot_remove_write_access */
5811 	lockdep_assert_held(&kvm->slots_lock);
5812 
5813 	if (flush)
5814 		kvm_flush_remote_tlbs(kvm);
5815 }
5816 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5817 
kvm_mmu_slot_set_dirty(struct kvm * kvm,struct kvm_memory_slot * memslot)5818 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5819 			    struct kvm_memory_slot *memslot)
5820 {
5821 	bool flush;
5822 
5823 	spin_lock(&kvm->mmu_lock);
5824 	flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5825 	spin_unlock(&kvm->mmu_lock);
5826 
5827 	lockdep_assert_held(&kvm->slots_lock);
5828 
5829 	/* see kvm_mmu_slot_leaf_clear_dirty */
5830 	if (flush)
5831 		kvm_flush_remote_tlbs(kvm);
5832 }
5833 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5834 
5835 #define BATCH_ZAP_PAGES	10
kvm_zap_obsolete_pages(struct kvm * kvm)5836 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5837 {
5838 	struct kvm_mmu_page *sp, *node;
5839 	int batch = 0;
5840 
5841 restart:
5842 	list_for_each_entry_safe_reverse(sp, node,
5843 	      &kvm->arch.active_mmu_pages, link) {
5844 		int ret;
5845 
5846 		/*
5847 		 * No obsolete page exists before new created page since
5848 		 * active_mmu_pages is the FIFO list.
5849 		 */
5850 		if (!is_obsolete_sp(kvm, sp))
5851 			break;
5852 
5853 		/*
5854 		 * Since we are reversely walking the list and the invalid
5855 		 * list will be moved to the head, skip the invalid page
5856 		 * can help us to avoid the infinity list walking.
5857 		 */
5858 		if (sp->role.invalid)
5859 			continue;
5860 
5861 		/*
5862 		 * Need not flush tlb since we only zap the sp with invalid
5863 		 * generation number.
5864 		 */
5865 		if (batch >= BATCH_ZAP_PAGES &&
5866 		      cond_resched_lock(&kvm->mmu_lock)) {
5867 			batch = 0;
5868 			goto restart;
5869 		}
5870 
5871 		ret = kvm_mmu_prepare_zap_page(kvm, sp,
5872 				&kvm->arch.zapped_obsolete_pages);
5873 		batch += ret;
5874 
5875 		if (ret)
5876 			goto restart;
5877 	}
5878 
5879 	/*
5880 	 * Should flush tlb before free page tables since lockless-walking
5881 	 * may use the pages.
5882 	 */
5883 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5884 }
5885 
5886 /*
5887  * Fast invalidate all shadow pages and use lock-break technique
5888  * to zap obsolete pages.
5889  *
5890  * It's required when memslot is being deleted or VM is being
5891  * destroyed, in these cases, we should ensure that KVM MMU does
5892  * not use any resource of the being-deleted slot or all slots
5893  * after calling the function.
5894  */
kvm_mmu_invalidate_zap_all_pages(struct kvm * kvm)5895 void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
5896 {
5897 	spin_lock(&kvm->mmu_lock);
5898 	trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5899 	kvm->arch.mmu_valid_gen++;
5900 
5901 	/*
5902 	 * Notify all vcpus to reload its shadow page table
5903 	 * and flush TLB. Then all vcpus will switch to new
5904 	 * shadow page table with the new mmu_valid_gen.
5905 	 *
5906 	 * Note: we should do this under the protection of
5907 	 * mmu-lock, otherwise, vcpu would purge shadow page
5908 	 * but miss tlb flush.
5909 	 */
5910 	kvm_reload_remote_mmus(kvm);
5911 
5912 	kvm_zap_obsolete_pages(kvm);
5913 	spin_unlock(&kvm->mmu_lock);
5914 }
5915 
kvm_has_zapped_obsolete_pages(struct kvm * kvm)5916 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5917 {
5918 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5919 }
5920 
kvm_mmu_invalidate_mmio_sptes(struct kvm * kvm,u64 gen)5921 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5922 {
5923 	gen &= MMIO_GEN_MASK;
5924 
5925 	/*
5926 	 * Shift to eliminate the "update in-progress" flag, which isn't
5927 	 * included in the spte's generation number.
5928 	 */
5929 	gen >>= 1;
5930 
5931 	/*
5932 	 * Generation numbers are incremented in multiples of the number of
5933 	 * address spaces in order to provide unique generations across all
5934 	 * address spaces.  Strip what is effectively the address space
5935 	 * modifier prior to checking for a wrap of the MMIO generation so
5936 	 * that a wrap in any address space is detected.
5937 	 */
5938 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5939 
5940 	/*
5941 	 * The very rare case: if the MMIO generation number has wrapped,
5942 	 * zap all shadow pages.
5943 	 */
5944 	if (unlikely(gen == 0)) {
5945 		kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5946 		kvm_mmu_invalidate_zap_all_pages(kvm);
5947 	}
5948 }
5949 
5950 static unsigned long
mmu_shrink_scan(struct shrinker * shrink,struct shrink_control * sc)5951 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5952 {
5953 	struct kvm *kvm;
5954 	int nr_to_scan = sc->nr_to_scan;
5955 	unsigned long freed = 0;
5956 
5957 	mutex_lock(&kvm_lock);
5958 
5959 	list_for_each_entry(kvm, &vm_list, vm_list) {
5960 		int idx;
5961 		LIST_HEAD(invalid_list);
5962 
5963 		/*
5964 		 * Never scan more than sc->nr_to_scan VM instances.
5965 		 * Will not hit this condition practically since we do not try
5966 		 * to shrink more than one VM and it is very unlikely to see
5967 		 * !n_used_mmu_pages so many times.
5968 		 */
5969 		if (!nr_to_scan--)
5970 			break;
5971 		/*
5972 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5973 		 * here. We may skip a VM instance errorneosly, but we do not
5974 		 * want to shrink a VM that only started to populate its MMU
5975 		 * anyway.
5976 		 */
5977 		if (!kvm->arch.n_used_mmu_pages &&
5978 		      !kvm_has_zapped_obsolete_pages(kvm))
5979 			continue;
5980 
5981 		idx = srcu_read_lock(&kvm->srcu);
5982 		spin_lock(&kvm->mmu_lock);
5983 
5984 		if (kvm_has_zapped_obsolete_pages(kvm)) {
5985 			kvm_mmu_commit_zap_page(kvm,
5986 			      &kvm->arch.zapped_obsolete_pages);
5987 			goto unlock;
5988 		}
5989 
5990 		if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
5991 			freed++;
5992 		kvm_mmu_commit_zap_page(kvm, &invalid_list);
5993 
5994 unlock:
5995 		spin_unlock(&kvm->mmu_lock);
5996 		srcu_read_unlock(&kvm->srcu, idx);
5997 
5998 		/*
5999 		 * unfair on small ones
6000 		 * per-vm shrinkers cry out
6001 		 * sadness comes quickly
6002 		 */
6003 		list_move_tail(&kvm->vm_list, &vm_list);
6004 		break;
6005 	}
6006 
6007 	mutex_unlock(&kvm_lock);
6008 	return freed;
6009 }
6010 
6011 static unsigned long
mmu_shrink_count(struct shrinker * shrink,struct shrink_control * sc)6012 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6013 {
6014 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6015 }
6016 
6017 static struct shrinker mmu_shrinker = {
6018 	.count_objects = mmu_shrink_count,
6019 	.scan_objects = mmu_shrink_scan,
6020 	.seeks = DEFAULT_SEEKS * 10,
6021 };
6022 
mmu_destroy_caches(void)6023 static void mmu_destroy_caches(void)
6024 {
6025 	kmem_cache_destroy(pte_list_desc_cache);
6026 	kmem_cache_destroy(mmu_page_header_cache);
6027 }
6028 
get_nx_auto_mode(void)6029 static bool get_nx_auto_mode(void)
6030 {
6031 	/* Return true when CPU has the bug, and mitigations are ON */
6032 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6033 }
6034 
__set_nx_huge_pages(bool val)6035 static void __set_nx_huge_pages(bool val)
6036 {
6037 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6038 }
6039 
set_nx_huge_pages(const char * val,const struct kernel_param * kp)6040 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6041 {
6042 	bool old_val = nx_huge_pages;
6043 	bool new_val;
6044 
6045 	/* In "auto" mode deploy workaround only if CPU has the bug. */
6046 	if (sysfs_streq(val, "off"))
6047 		new_val = 0;
6048 	else if (sysfs_streq(val, "force"))
6049 		new_val = 1;
6050 	else if (sysfs_streq(val, "auto"))
6051 		new_val = get_nx_auto_mode();
6052 	else if (strtobool(val, &new_val) < 0)
6053 		return -EINVAL;
6054 
6055 	__set_nx_huge_pages(new_val);
6056 
6057 	if (new_val != old_val) {
6058 		struct kvm *kvm;
6059 		int idx;
6060 
6061 		mutex_lock(&kvm_lock);
6062 
6063 		list_for_each_entry(kvm, &vm_list, vm_list) {
6064 			idx = srcu_read_lock(&kvm->srcu);
6065 			kvm_mmu_invalidate_zap_all_pages(kvm);
6066 			srcu_read_unlock(&kvm->srcu, idx);
6067 
6068 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6069 		}
6070 		mutex_unlock(&kvm_lock);
6071 	}
6072 
6073 	return 0;
6074 }
6075 
kvm_set_mmio_spte_mask(void)6076 static void kvm_set_mmio_spte_mask(void)
6077 {
6078 	u64 mask;
6079 
6080 	/*
6081 	 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
6082 	 * PFEC.RSVD=1 on MMIO accesses.  64-bit PTEs (PAE, x86-64, and EPT
6083 	 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
6084 	 * 52-bit physical addresses then there are no reserved PA bits in the
6085 	 * PTEs and so the reserved PA approach must be disabled.
6086 	 */
6087 	if (shadow_phys_bits < 52)
6088 		mask = BIT_ULL(51) | PT_PRESENT_MASK;
6089 	else
6090 		mask = 0;
6091 
6092 	kvm_mmu_set_mmio_spte_mask(mask, mask);
6093 }
6094 
kvm_mmu_module_init(void)6095 int kvm_mmu_module_init(void)
6096 {
6097 	int ret = -ENOMEM;
6098 
6099 	if (nx_huge_pages == -1)
6100 		__set_nx_huge_pages(get_nx_auto_mode());
6101 
6102 	kvm_mmu_reset_all_pte_masks();
6103 
6104 	kvm_set_mmio_spte_mask();
6105 
6106 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6107 					    sizeof(struct pte_list_desc),
6108 					    0, SLAB_ACCOUNT, NULL);
6109 	if (!pte_list_desc_cache)
6110 		goto out;
6111 
6112 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6113 						  sizeof(struct kvm_mmu_page),
6114 						  0, SLAB_ACCOUNT, NULL);
6115 	if (!mmu_page_header_cache)
6116 		goto out;
6117 
6118 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6119 		goto out;
6120 
6121 	ret = register_shrinker(&mmu_shrinker);
6122 	if (ret)
6123 		goto out;
6124 
6125 	return 0;
6126 
6127 out:
6128 	mmu_destroy_caches();
6129 	return ret;
6130 }
6131 
6132 /*
6133  * Caculate mmu pages needed for kvm.
6134  */
kvm_mmu_calculate_mmu_pages(struct kvm * kvm)6135 unsigned long kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
6136 {
6137 	unsigned long nr_mmu_pages;
6138 	unsigned long nr_pages = 0;
6139 	struct kvm_memslots *slots;
6140 	struct kvm_memory_slot *memslot;
6141 	int i;
6142 
6143 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6144 		slots = __kvm_memslots(kvm, i);
6145 
6146 		kvm_for_each_memslot(memslot, slots)
6147 			nr_pages += memslot->npages;
6148 	}
6149 
6150 	nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6151 	nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6152 
6153 	return nr_mmu_pages;
6154 }
6155 
kvm_mmu_destroy(struct kvm_vcpu * vcpu)6156 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6157 {
6158 	kvm_mmu_unload(vcpu);
6159 	free_mmu_pages(vcpu);
6160 	mmu_free_memory_caches(vcpu);
6161 }
6162 
kvm_mmu_module_exit(void)6163 void kvm_mmu_module_exit(void)
6164 {
6165 	mmu_destroy_caches();
6166 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6167 	unregister_shrinker(&mmu_shrinker);
6168 	mmu_audit_disable();
6169 }
6170 
set_nx_huge_pages_recovery_ratio(const char * val,const struct kernel_param * kp)6171 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6172 {
6173 	unsigned int old_val;
6174 	int err;
6175 
6176 	old_val = nx_huge_pages_recovery_ratio;
6177 	err = param_set_uint(val, kp);
6178 	if (err)
6179 		return err;
6180 
6181 	if (READ_ONCE(nx_huge_pages) &&
6182 	    !old_val && nx_huge_pages_recovery_ratio) {
6183 		struct kvm *kvm;
6184 
6185 		mutex_lock(&kvm_lock);
6186 
6187 		list_for_each_entry(kvm, &vm_list, vm_list)
6188 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6189 
6190 		mutex_unlock(&kvm_lock);
6191 	}
6192 
6193 	return err;
6194 }
6195 
kvm_recover_nx_lpages(struct kvm * kvm)6196 static void kvm_recover_nx_lpages(struct kvm *kvm)
6197 {
6198 	int rcu_idx;
6199 	struct kvm_mmu_page *sp;
6200 	unsigned int ratio;
6201 	LIST_HEAD(invalid_list);
6202 	ulong to_zap;
6203 
6204 	rcu_idx = srcu_read_lock(&kvm->srcu);
6205 	spin_lock(&kvm->mmu_lock);
6206 
6207 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6208 	to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
6209 	while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
6210 		/*
6211 		 * We use a separate list instead of just using active_mmu_pages
6212 		 * because the number of lpage_disallowed pages is expected to
6213 		 * be relatively small compared to the total.
6214 		 */
6215 		sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6216 				      struct kvm_mmu_page,
6217 				      lpage_disallowed_link);
6218 		WARN_ON_ONCE(!sp->lpage_disallowed);
6219 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6220 		WARN_ON_ONCE(sp->lpage_disallowed);
6221 
6222 		if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
6223 			kvm_mmu_commit_zap_page(kvm, &invalid_list);
6224 			if (to_zap)
6225 				cond_resched_lock(&kvm->mmu_lock);
6226 		}
6227 	}
6228 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6229 
6230 	spin_unlock(&kvm->mmu_lock);
6231 	srcu_read_unlock(&kvm->srcu, rcu_idx);
6232 }
6233 
get_nx_lpage_recovery_timeout(u64 start_time)6234 static long get_nx_lpage_recovery_timeout(u64 start_time)
6235 {
6236 	return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6237 		? start_time + 60 * HZ - get_jiffies_64()
6238 		: MAX_SCHEDULE_TIMEOUT;
6239 }
6240 
kvm_nx_lpage_recovery_worker(struct kvm * kvm,uintptr_t data)6241 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6242 {
6243 	u64 start_time;
6244 	long remaining_time;
6245 
6246 	while (true) {
6247 		start_time = get_jiffies_64();
6248 		remaining_time = get_nx_lpage_recovery_timeout(start_time);
6249 
6250 		set_current_state(TASK_INTERRUPTIBLE);
6251 		while (!kthread_should_stop() && remaining_time > 0) {
6252 			schedule_timeout(remaining_time);
6253 			remaining_time = get_nx_lpage_recovery_timeout(start_time);
6254 			set_current_state(TASK_INTERRUPTIBLE);
6255 		}
6256 
6257 		set_current_state(TASK_RUNNING);
6258 
6259 		if (kthread_should_stop())
6260 			return 0;
6261 
6262 		kvm_recover_nx_lpages(kvm);
6263 	}
6264 }
6265 
kvm_mmu_post_init_vm(struct kvm * kvm)6266 int kvm_mmu_post_init_vm(struct kvm *kvm)
6267 {
6268 	int err;
6269 
6270 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6271 					  "kvm-nx-lpage-recovery",
6272 					  &kvm->arch.nx_lpage_recovery_thread);
6273 	if (!err)
6274 		kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6275 
6276 	return err;
6277 }
6278 
kvm_mmu_pre_destroy_vm(struct kvm * kvm)6279 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6280 {
6281 	if (kvm->arch.nx_lpage_recovery_thread)
6282 		kthread_stop(kvm->arch.nx_lpage_recovery_thread);
6283 }
6284