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