xref: /linux/arch/x86/kvm/mmu/paging_tmpl.h (revision 56070f00d07e30caa9a66c3660045f5f2956a629)
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 /*
19  * The MMU needs to be able to access/walk 32-bit and 64-bit guest page tables,
20  * as well as guest EPT tables, so the code in this file is compiled thrice,
21  * once per guest PTE type.  The per-type defines are #undef'd at the end.
22  */
23 
24 #if PTTYPE == 64
25 	#define pt_element_t u64
26 	#define guest_walker guest_walker64
27 	#define FNAME(name) paging##64_##name
28 	#define PT_LEVEL_BITS 9
29 	#define PT_GUEST_DIRTY_SHIFT PT_DIRTY_SHIFT
30 	#define PT_GUEST_ACCESSED_SHIFT PT_ACCESSED_SHIFT
31 	#define PT_HAVE_ACCESSED_DIRTY(mmu) true
32 	#ifdef CONFIG_X86_64
33 	#define PT_MAX_FULL_LEVELS PT64_ROOT_MAX_LEVEL
34 	#else
35 	#define PT_MAX_FULL_LEVELS 2
36 	#endif
37 #elif PTTYPE == 32
38 	#define pt_element_t u32
39 	#define guest_walker guest_walker32
40 	#define FNAME(name) paging##32_##name
41 	#define PT_LEVEL_BITS 10
42 	#define PT_MAX_FULL_LEVELS 2
43 	#define PT_GUEST_DIRTY_SHIFT PT_DIRTY_SHIFT
44 	#define PT_GUEST_ACCESSED_SHIFT PT_ACCESSED_SHIFT
45 	#define PT_HAVE_ACCESSED_DIRTY(mmu) true
46 
47 	#define PT32_DIR_PSE36_SIZE 4
48 	#define PT32_DIR_PSE36_SHIFT 13
49 	#define PT32_DIR_PSE36_MASK \
50 		(((1ULL << PT32_DIR_PSE36_SIZE) - 1) << PT32_DIR_PSE36_SHIFT)
51 #elif PTTYPE == PTTYPE_EPT
52 	#define pt_element_t u64
53 	#define guest_walker guest_walkerEPT
54 	#define FNAME(name) ept_##name
55 	#define PT_LEVEL_BITS 9
56 	#define PT_GUEST_DIRTY_SHIFT 9
57 	#define PT_GUEST_ACCESSED_SHIFT 8
58 	#define PT_HAVE_ACCESSED_DIRTY(w) (!(w)->cpu_role.base.ad_disabled)
59 	#define PT_MAX_FULL_LEVELS PT64_ROOT_MAX_LEVEL
60 #else
61 	#error Invalid PTTYPE value
62 #endif
63 
64 /* Common logic, but per-type values.  These also need to be undefined. */
65 #define PT_BASE_ADDR_MASK	((pt_element_t)__PT_BASE_ADDR_MASK)
66 #define PT_LVL_ADDR_MASK(lvl)	__PT_LVL_ADDR_MASK(PT_BASE_ADDR_MASK, lvl, PT_LEVEL_BITS)
67 #define PT_LVL_OFFSET_MASK(lvl)	__PT_LVL_OFFSET_MASK(PT_BASE_ADDR_MASK, lvl, PT_LEVEL_BITS)
68 #define PT_INDEX(addr, lvl)	__PT_INDEX(addr, lvl, PT_LEVEL_BITS)
69 
70 #define PT_GUEST_DIRTY_MASK    (1 << PT_GUEST_DIRTY_SHIFT)
71 #define PT_GUEST_ACCESSED_MASK (1 << PT_GUEST_ACCESSED_SHIFT)
72 
73 #define gpte_to_gfn_lvl FNAME(gpte_to_gfn_lvl)
74 #define gpte_to_gfn(pte) gpte_to_gfn_lvl((pte), PG_LEVEL_4K)
75 
76 /*
77  * The guest_walker structure emulates the behavior of the hardware page
78  * table walker.
79  */
80 struct guest_walker {
81 	int level;
82 	unsigned max_level;
83 	gfn_t table_gfn[PT_MAX_FULL_LEVELS];
84 	pt_element_t ptes[PT_MAX_FULL_LEVELS];
85 	pt_element_t prefetch_ptes[PTE_PREFETCH_NUM];
86 	gpa_t pte_gpa[PT_MAX_FULL_LEVELS];
87 	pt_element_t __user *ptep_user[PT_MAX_FULL_LEVELS];
88 	bool pte_writable[PT_MAX_FULL_LEVELS];
89 	unsigned int pt_access[PT_MAX_FULL_LEVELS];
90 	unsigned int pte_access;
91 	gfn_t gfn;
92 	struct x86_exception fault;
93 };
94 
95 #if PTTYPE == 32
96 static inline gfn_t pse36_gfn_delta(u32 gpte)
97 {
98 	int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
99 
100 	return (gpte & PT32_DIR_PSE36_MASK) << shift;
101 }
102 #endif
103 
104 static gfn_t gpte_to_gfn_lvl(pt_element_t gpte, int lvl)
105 {
106 	return (gpte & PT_LVL_ADDR_MASK(lvl)) >> PAGE_SHIFT;
107 }
108 
109 static inline void FNAME(protect_clean_gpte)(struct kvm_pagewalk *w, unsigned *access,
110 					     unsigned gpte)
111 {
112 	unsigned mask;
113 
114 	/* dirty bit is not supported, so no need to track it */
115 	if (!PT_HAVE_ACCESSED_DIRTY(w))
116 		return;
117 
118 	BUILD_BUG_ON(PT_WRITABLE_MASK != ACC_WRITE_MASK);
119 
120 	mask = (unsigned)~ACC_WRITE_MASK;
121 	/* Allow write access to dirty gptes */
122 	mask |= (gpte >> (PT_GUEST_DIRTY_SHIFT - PT_WRITABLE_SHIFT)) &
123 		PT_WRITABLE_MASK;
124 	*access &= mask;
125 }
126 
127 static inline int FNAME(is_present_gpte)(struct kvm_pagewalk *w,
128 					 unsigned long pte)
129 {
130 #if PTTYPE != PTTYPE_EPT
131 	return pte & PT_PRESENT_MASK;
132 #else
133 	/*
134 	 * For EPT, an entry is present if any of bits 2:0 are set.
135 	 * With mode-based execute control, bit 10 also indicates presence.
136 	 */
137 	return pte & (7 | (is_cr4_smep(w) ? VMX_EPT_USER_EXECUTABLE_MASK : 0));
138 #endif
139 }
140 
141 static bool FNAME(is_bad_mt_xwr)(struct kvm_page_format *fmt, u64 gpte)
142 {
143 #if PTTYPE != PTTYPE_EPT
144 	return false;
145 #else
146 	return __is_bad_mt_xwr(fmt, gpte);
147 #endif
148 }
149 
150 static bool FNAME(is_rsvd_bits_set)(struct kvm_page_format *fmt, u64 gpte, int level)
151 {
152 	return __is_rsvd_bits_set(fmt, gpte, level) ||
153 	       FNAME(is_bad_mt_xwr)(fmt, gpte);
154 }
155 
156 static bool FNAME(prefetch_invalid_gpte)(struct kvm_vcpu *vcpu,
157 				  struct kvm_mmu_page *sp, u64 *spte,
158 				  u64 gpte)
159 {
160 	struct kvm_pagewalk *w = vcpu->arch.mmu->w;
161 
162 	if (!FNAME(is_present_gpte)(w, gpte))
163 		goto no_present;
164 
165 	/* Prefetch only accessed entries (unless A/D bits are disabled). */
166 	if (PT_HAVE_ACCESSED_DIRTY(w) &&
167 	    !(gpte & PT_GUEST_ACCESSED_MASK))
168 		goto no_present;
169 
170 	if (FNAME(is_rsvd_bits_set)(&w->fmt, gpte, PG_LEVEL_4K))
171 		goto no_present;
172 
173 	return false;
174 
175 no_present:
176 	drop_spte(vcpu->kvm, spte);
177 	return true;
178 }
179 
180 static inline unsigned FNAME(gpte_access)(u64 gpte)
181 {
182 	unsigned access;
183 	/*
184 	 * Set bits in ACC_*_MASK even if they might not be used in the
185 	 * actual checks.  For example, if EFER.NX is clear permission_fault()
186 	 * will ignore ACC_EXEC_MASK, and if MBEC is disabled it will
187 	 * ignore ACC_USER_EXEC_MASK.
188 	 */
189 #if PTTYPE == PTTYPE_EPT
190 	access = ((gpte & VMX_EPT_WRITABLE_MASK) ? ACC_WRITE_MASK : 0) |
191 		((gpte & VMX_EPT_EXECUTABLE_MASK) ? ACC_EXEC_MASK : 0) |
192 		((gpte & VMX_EPT_READABLE_MASK) ? ACC_READ_MASK : 0) |
193 		((gpte & VMX_EPT_USER_EXECUTABLE_MASK) ? ACC_USER_EXEC_MASK : 0);
194 #else
195 	/*
196 	 * P is set here, so the page is always readable and W/U/!NX represent
197 	 * allowed accesses.
198 	 */
199 	BUILD_BUG_ON(ACC_READ_MASK != PT_PRESENT_MASK);
200 	BUILD_BUG_ON(ACC_WRITE_MASK != PT_WRITABLE_MASK);
201 	BUILD_BUG_ON(ACC_USER_MASK != PT_USER_MASK);
202 	BUILD_BUG_ON(ACC_EXEC_MASK & (PT_WRITABLE_MASK | PT_USER_MASK | PT_PRESENT_MASK));
203 	access = gpte & (PT_WRITABLE_MASK | PT_USER_MASK | PT_PRESENT_MASK);
204 	access |= gpte & PT64_NX_MASK ? 0 : ACC_EXEC_MASK;
205 #endif
206 
207 	return access;
208 }
209 
210 static int FNAME(update_accessed_dirty_bits)(struct kvm_vcpu *vcpu,
211 					     struct kvm_pagewalk *w,
212 					     struct guest_walker *walker,
213 					     gpa_t addr, int write_fault)
214 {
215 	unsigned level, index;
216 	pt_element_t pte, orig_pte;
217 	pt_element_t __user *ptep_user;
218 	gfn_t table_gfn;
219 	int ret;
220 
221 	/* dirty/accessed bits are not supported, so no need to update them */
222 	if (!PT_HAVE_ACCESSED_DIRTY(w))
223 		return 0;
224 
225 	for (level = walker->max_level; level >= walker->level; --level) {
226 		pte = orig_pte = walker->ptes[level - 1];
227 		table_gfn = walker->table_gfn[level - 1];
228 		ptep_user = walker->ptep_user[level - 1];
229 		index = offset_in_page(ptep_user) / sizeof(pt_element_t);
230 		if (!(pte & PT_GUEST_ACCESSED_MASK)) {
231 			trace_kvm_mmu_set_accessed_bit(table_gfn, index, sizeof(pte));
232 			pte |= PT_GUEST_ACCESSED_MASK;
233 		}
234 		if (level == walker->level && write_fault &&
235 				!(pte & PT_GUEST_DIRTY_MASK)) {
236 			trace_kvm_mmu_set_dirty_bit(table_gfn, index, sizeof(pte));
237 #if PTTYPE == PTTYPE_EPT
238 			if (kvm_nested_call(write_log_dirty)(vcpu, addr))
239 				return -EINVAL;
240 #endif
241 			pte |= PT_GUEST_DIRTY_MASK;
242 		}
243 		if (pte == orig_pte)
244 			continue;
245 
246 		/*
247 		 * If the slot is read-only, simply do not process the accessed
248 		 * and dirty bits.  This is the correct thing to do if the slot
249 		 * is ROM, and page tables in read-as-ROM/write-as-MMIO slots
250 		 * are only supported if the accessed and dirty bits are already
251 		 * set in the ROM (so that MMIO writes are never needed).
252 		 *
253 		 * Note that NPT does not allow this at all and faults, since
254 		 * it always wants nested page table entries for the guest
255 		 * page tables to be writable.  And EPT works but will simply
256 		 * overwrite the read-only memory to set the accessed and dirty
257 		 * bits.
258 		 */
259 		if (unlikely(!walker->pte_writable[level - 1]))
260 			continue;
261 
262 		ret = __try_cmpxchg_user(ptep_user, &orig_pte, pte, fault);
263 		if (ret)
264 			return ret;
265 
266 		kvm_vcpu_mark_page_dirty(vcpu, table_gfn);
267 		walker->ptes[level - 1] = pte;
268 	}
269 	return 0;
270 }
271 
272 static inline unsigned FNAME(gpte_pkeys)(struct kvm_vcpu *vcpu, u64 gpte)
273 {
274 	unsigned pkeys = 0;
275 #if PTTYPE == 64
276 	pte_t pte = {.pte = gpte};
277 
278 	pkeys = pte_flags_pkey(pte_flags(pte));
279 #endif
280 	return pkeys;
281 }
282 
283 static inline bool FNAME(is_last_gpte)(struct kvm_pagewalk *w,
284 				       unsigned int level, unsigned int gpte)
285 {
286 	/*
287 	 * For EPT and PAE paging (both variants), bit 7 is either reserved at
288 	 * all level or indicates a huge page (ignoring CR3/EPTP).  In either
289 	 * case, bit 7 being set terminates the walk.
290 	 */
291 #if PTTYPE == 32
292 	/*
293 	 * 32-bit paging requires special handling because bit 7 is ignored if
294 	 * CR4.PSE=0, not reserved.  Clear bit 7 in the gpte if the level is
295 	 * greater than the last level for which bit 7 is the PAGE_SIZE bit.
296 	 *
297 	 * The RHS has bit 7 set iff level < (2 + PSE).  If it is clear, bit 7
298 	 * is not reserved and does not indicate a large page at this level,
299 	 * so clear PT_PAGE_SIZE_MASK in gpte if that is the case.
300 	 */
301 	gpte &= level - (PT32_ROOT_LEVEL + w->cpu_role.ext.cr4_pse);
302 #endif
303 	/*
304 	 * PG_LEVEL_4K always terminates.  The RHS has bit 7 set
305 	 * iff level <= PG_LEVEL_4K, which for our purpose means
306 	 * level == PG_LEVEL_4K; set PT_PAGE_SIZE_MASK in gpte then.
307 	 */
308 	gpte |= level - PG_LEVEL_4K - 1;
309 
310 	return gpte & PT_PAGE_SIZE_MASK;
311 }
312 /*
313  * Fetch a guest pte for a guest virtual address, or for an L2's GPA.
314  */
315 static int FNAME(walk_addr_generic)(struct guest_walker *walker,
316 				    struct kvm_vcpu *vcpu, struct kvm_pagewalk *w,
317 				    gpa_t addr, u64 access)
318 {
319 	int ret;
320 	pt_element_t pte;
321 	pt_element_t __user *ptep_user;
322 	gfn_t table_gfn;
323 	u64 pt_access, pte_access;
324 	unsigned index, accessed_dirty, pte_pkey;
325 	u64 nested_access;
326 	gpa_t pte_gpa;
327 	bool have_ad;
328 	int offset;
329 	u64 walk_nx_mask = 0;
330 	const int write_fault = access & PFERR_WRITE_MASK;
331 	const int fetch_fault = access & PFERR_FETCH_MASK;
332 	/*
333 	 * Note! Track the error_code that's common to legacy shadow paging
334 	 * and NPT shadow paging as a u16 to guard against unintentionally
335 	 * setting any of bits 63:16.  Architecturally, the #PF error code is
336 	 * 32 bits, and Intel CPUs don't support settings bits 31:16.
337 	 */
338 	u16 errcode = 0;
339 	gpa_t real_gpa;
340 	gfn_t gfn;
341 
342 	trace_kvm_mmu_pagetable_walk(addr, access);
343 retry_walk:
344 	walker->level = w->cpu_role.base.level;
345 	pte           = kvm_mmu_get_guest_pgd(vcpu, w);
346 	have_ad       = PT_HAVE_ACCESSED_DIRTY(w);
347 
348 #if PTTYPE == 64
349 	walk_nx_mask = 1ULL << PT64_NX_SHIFT;
350 	if (walker->level == PT32E_ROOT_LEVEL) {
351 		pte = w->get_pdptr(vcpu, (addr >> 30) & 3);
352 		trace_kvm_mmu_paging_element(pte, walker->level);
353 		if (!FNAME(is_present_gpte)(w, pte))
354 			goto error;
355 		--walker->level;
356 	}
357 #endif
358 	walker->max_level = walker->level;
359 
360 	/*
361 	 * FIXME: on Intel processors, loads of the PDPTE registers for PAE paging
362 	 * by the MOV to CR instruction are treated as reads and do not cause the
363 	 * processor to set the dirty flag in any EPT paging-structure entry.
364 	 */
365 	nested_access = (have_ad ? PFERR_WRITE_MASK : 0) | PFERR_USER_MASK;
366 
367 	pte_access = ~0;
368 
369 	/*
370 	 * Queue a page fault for injection if any of the below assertions fail,
371 	 * as callers assume that walker.fault contains sane info on a walk
372 	 * failure.  I.e. avoid making the situation worse by inducing even
373 	 * worse badness between when the assertion fails and when KVM kicks
374 	 * the vCPU out to userspace (because the VM is bugged).
375 	 */
376 	if (KVM_BUG_ON(is_long_mode(vcpu) && !is_pae(vcpu), vcpu->kvm) ||
377 	    KVM_BUG_ON(walker->max_level > PT_MAX_FULL_LEVELS, vcpu->kvm))
378 		goto error;
379 
380 	++walker->level;
381 
382 	do {
383 		struct kvm_memory_slot *slot;
384 		unsigned long host_addr;
385 
386 		pt_access = pte_access;
387 		--walker->level;
388 
389 		index = PT_INDEX(addr, walker->level);
390 		table_gfn = gpte_to_gfn(pte);
391 		offset    = index * sizeof(pt_element_t);
392 		pte_gpa   = gfn_to_gpa(table_gfn) + offset;
393 
394 		if (KVM_BUG_ON(walker->level < 1, vcpu->kvm))
395 			goto error;
396 
397 		walker->table_gfn[walker->level - 1] = table_gfn;
398 		walker->pte_gpa[walker->level - 1] = pte_gpa;
399 
400 		real_gpa = kvm_translate_gpa(vcpu, w, gfn_to_gpa(table_gfn),
401 					     nested_access | PFERR_GUEST_PAGE_MASK,
402 					     &walker->fault, 0);
403 
404 		if (unlikely(real_gpa == INVALID_GPA))
405 			return 0;
406 
407 		slot = kvm_vcpu_gfn_to_memslot(vcpu, gpa_to_gfn(real_gpa));
408 		if (!kvm_is_visible_memslot(slot))
409 			goto error;
410 
411 		host_addr = gfn_to_hva_memslot_prot(slot, gpa_to_gfn(real_gpa),
412 					    &walker->pte_writable[walker->level - 1]);
413 		if (unlikely(kvm_is_error_hva(host_addr)))
414 			goto error;
415 
416 		ptep_user = (pt_element_t __user *)((void *)host_addr + offset);
417 		if (unlikely(get_user(pte, ptep_user)))
418 			goto error;
419 		walker->ptep_user[walker->level - 1] = ptep_user;
420 
421 		trace_kvm_mmu_paging_element(pte, walker->level);
422 
423 		/*
424 		 * Inverting the NX it lets us AND it like other
425 		 * permission bits.
426 		 */
427 		pte_access = pt_access & (pte ^ walk_nx_mask);
428 
429 		if (unlikely(!FNAME(is_present_gpte)(w, pte)))
430 			goto error;
431 
432 		if (unlikely(FNAME(is_rsvd_bits_set)(&w->fmt, pte, walker->level))) {
433 			errcode = PFERR_RSVD_MASK | PFERR_PRESENT_MASK;
434 			goto error;
435 		}
436 
437 		walker->ptes[walker->level - 1] = pte;
438 
439 		/* Convert to ACC_*_MASK flags for struct guest_walker.  */
440 		walker->pt_access[walker->level - 1] = FNAME(gpte_access)(pt_access ^ walk_nx_mask);
441 	} while (!FNAME(is_last_gpte)(w, walker->level, pte));
442 
443 	pte_pkey = FNAME(gpte_pkeys)(vcpu, pte);
444 	accessed_dirty = have_ad ? pte_access & PT_GUEST_ACCESSED_MASK : 0;
445 
446 	/* Convert to ACC_*_MASK flags for struct guest_walker.  */
447 	walker->pte_access = FNAME(gpte_access)(pte_access ^ walk_nx_mask);
448 	errcode = permission_fault(vcpu, w, walker->pte_access, pte_pkey, access);
449 	if (unlikely(errcode))
450 		goto error;
451 
452 	gfn = gpte_to_gfn_lvl(pte, walker->level);
453 	gfn += (addr & PT_LVL_OFFSET_MASK(walker->level)) >> PAGE_SHIFT;
454 
455 #if PTTYPE == 32
456 	if (walker->level > PG_LEVEL_4K && is_cpuid_PSE36())
457 		gfn += pse36_gfn_delta(pte);
458 #endif
459 
460 	real_gpa = kvm_translate_gpa(vcpu, w, gfn_to_gpa(gfn),
461 				     access | PFERR_GUEST_FINAL_MASK,
462 				     &walker->fault, walker->pte_access);
463 	if (real_gpa == INVALID_GPA)
464 		return 0;
465 
466 	walker->gfn = real_gpa >> PAGE_SHIFT;
467 
468 	if (!write_fault)
469 		FNAME(protect_clean_gpte)(w, &walker->pte_access, pte);
470 	else
471 		/*
472 		 * On a write fault, fold the dirty bit into accessed_dirty.
473 		 * For modes without A/D bits support accessed_dirty will be
474 		 * always clear.
475 		 */
476 		accessed_dirty &= pte >>
477 			(PT_GUEST_DIRTY_SHIFT - PT_GUEST_ACCESSED_SHIFT);
478 
479 	if (unlikely(!accessed_dirty)) {
480 		ret = FNAME(update_accessed_dirty_bits)(vcpu, w, walker,
481 							addr, write_fault);
482 		if (unlikely(ret < 0))
483 			goto error;
484 		else if (ret)
485 			goto retry_walk;
486 	}
487 
488 	return 1;
489 
490 error:
491 	errcode |= access & (PFERR_WRITE_MASK | PFERR_USER_MASK | PFERR_SS_MASK);
492 	if (fetch_fault && has_pferr_fetch(w))
493 		errcode |= PFERR_FETCH_MASK;
494 
495 	walker->fault.vector = PF_VECTOR;
496 	walker->fault.error_code_valid = true;
497 	walker->fault.error_code = errcode;
498 
499 #if PTTYPE == PTTYPE_EPT
500 	/*
501 	 * Use PFERR_RSVD_MASK in error_code to tell if EPT
502 	 * misconfiguration requires to be injected. The detection is
503 	 * done by is_rsvd_bits_set() above.
504 	 *
505 	 * We set up the value of exit_qualification to inject:
506 	 * [2:0] - Derive from the access bits. The exit_qualification might be
507 	 *         out of date if it is serving an EPT misconfiguration.
508 	 * [5:3] - Calculated by the page walk of the guest EPT page tables
509 	 * [7:8] - Derived from "fault stage" access bits
510 	 * [9:11] - Derived from [9:11] of real exit_qualification
511 	 *
512 	 * The other bits are set to 0.
513 	 */
514 	if (!(errcode & PFERR_RSVD_MASK)) {
515 		walker->fault.exit_qualification = 0;
516 
517 		if (write_fault)
518 			walker->fault.exit_qualification |= EPT_VIOLATION_ACC_WRITE;
519 		else if (fetch_fault)
520 			walker->fault.exit_qualification |= EPT_VIOLATION_ACC_INSTR;
521 		else
522 			walker->fault.exit_qualification |= EPT_VIOLATION_ACC_READ;
523 
524 		/*
525 		 * KVM doesn't emulate features that access GPAs directly, e.g.
526 		 * Intel Processor Trace.  Assume the GVA is always valid; when
527 		 * propagating faults from hardware, KVM will discard this info
528 		 * and use the EXIT_QUALIFICATION bits from the VMCS.
529 		 */
530 		walker->fault.exit_qualification |= EPT_VIOLATION_GVA_IS_VALID;
531 
532 		/*
533 		 * Accesses to guest paging structures are either "reads" or
534 		 * "read+write" accesses, so consider them the latter if write_fault
535 		 * is true.
536 		 */
537 		if (access & PFERR_GUEST_PAGE_MASK)
538 			walker->fault.exit_qualification |= EPT_VIOLATION_ACC_READ;
539 		else
540 			walker->fault.exit_qualification |= EPT_VIOLATION_GVA_TRANSLATED;
541 
542 		/*
543 		 * Note, pte_access holds the raw RWX bits from the EPTE, not
544 		 * ACC_*_MASK flags!
545 		 */
546 		walker->fault.exit_qualification |= EPT_VIOLATION_RWX_TO_PROT(pte_access);
547 		if (is_cr4_smep(w))
548 			walker->fault.exit_qualification |=
549 				EPT_VIOLATION_USER_EXEC_TO_PROT(pte_access);
550 	}
551 #endif
552 	walker->fault.address = addr;
553 	walker->fault.nested_page_fault = w != &vcpu->arch.gva_walk;
554 	walker->fault.async_page_fault = false;
555 
556 #if PTTYPE != PTTYPE_EPT
557 	if (walker->fault.nested_page_fault)
558 		walker->fault.error_code |= access & PFERR_GUEST_FAULT_STAGE_MASK;
559 #endif
560 
561 	trace_kvm_mmu_walker_error(walker->fault.error_code);
562 	return 0;
563 }
564 
565 static int FNAME(walk_addr)(struct guest_walker *walker,
566 			    struct kvm_vcpu *vcpu, gpa_t addr, u64 access)
567 {
568 	return FNAME(walk_addr_generic)(walker, vcpu, vcpu->arch.mmu->w, addr,
569 					access);
570 }
571 
572 static bool
573 FNAME(prefetch_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
574 		     u64 *spte, pt_element_t gpte)
575 {
576 	unsigned pte_access;
577 	gfn_t gfn;
578 
579 	if (FNAME(prefetch_invalid_gpte)(vcpu, sp, spte, gpte))
580 		return false;
581 
582 	gfn = gpte_to_gfn(gpte);
583 	pte_access = sp->role.access & FNAME(gpte_access)(gpte);
584 	FNAME(protect_clean_gpte)(vcpu->arch.mmu->w, &pte_access, gpte);
585 
586 	return kvm_mmu_prefetch_sptes(vcpu, gfn, spte, 1, pte_access);
587 }
588 
589 static bool FNAME(gpte_changed)(struct kvm_vcpu *vcpu,
590 				struct guest_walker *gw, int level)
591 {
592 	pt_element_t curr_pte;
593 	gpa_t base_gpa, pte_gpa = gw->pte_gpa[level - 1];
594 	u64 mask;
595 	int r, index;
596 
597 	if (level == PG_LEVEL_4K) {
598 		mask = PTE_PREFETCH_NUM * sizeof(pt_element_t) - 1;
599 		base_gpa = pte_gpa & ~mask;
600 		index = (pte_gpa - base_gpa) / sizeof(pt_element_t);
601 
602 		r = kvm_vcpu_read_guest_atomic(vcpu, base_gpa,
603 				gw->prefetch_ptes, sizeof(gw->prefetch_ptes));
604 		curr_pte = gw->prefetch_ptes[index];
605 	} else
606 		r = kvm_vcpu_read_guest_atomic(vcpu, pte_gpa,
607 				  &curr_pte, sizeof(curr_pte));
608 
609 	return r || curr_pte != gw->ptes[level - 1];
610 }
611 
612 static void FNAME(pte_prefetch)(struct kvm_vcpu *vcpu, struct guest_walker *gw,
613 				u64 *sptep)
614 {
615 	struct kvm_mmu_page *sp;
616 	pt_element_t *gptep = gw->prefetch_ptes;
617 	u64 *spte;
618 	int i;
619 
620 	sp = sptep_to_sp(sptep);
621 
622 	if (sp->role.level > PG_LEVEL_4K)
623 		return;
624 
625 	/*
626 	 * If addresses are being invalidated, skip prefetching to avoid
627 	 * accidentally prefetching those addresses.
628 	 */
629 	if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
630 		return;
631 
632 	if (sp->role.direct)
633 		return __direct_pte_prefetch(vcpu, sp, sptep);
634 
635 	i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
636 	spte = sp->spt + i;
637 
638 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
639 		if (spte == sptep)
640 			continue;
641 
642 		if (is_shadow_present_pte(*spte))
643 			continue;
644 
645 		if (!FNAME(prefetch_gpte)(vcpu, sp, spte, gptep[i]))
646 			break;
647 	}
648 }
649 
650 /*
651  * Fetch a shadow pte for a specific level in the paging hierarchy.
652  * If the guest tries to write a write-protected page, we need to
653  * emulate this operation, return 1 to indicate this case.
654  */
655 static int FNAME(fetch)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
656 			 struct guest_walker *gw)
657 {
658 	struct kvm_mmu_page *sp = NULL;
659 	struct kvm_shadow_walk_iterator it;
660 	unsigned int direct_access, access;
661 	int top_level, ret;
662 	gfn_t base_gfn = fault->gfn;
663 
664 	WARN_ON_ONCE(gw->gfn != base_gfn);
665 	direct_access = gw->pte_access;
666 
667 	top_level = vcpu->arch.mmu->w->cpu_role.base.level;
668 	if (top_level == PT32E_ROOT_LEVEL)
669 		top_level = PT32_ROOT_LEVEL;
670 	/*
671 	 * Verify that the top-level gpte is still there.  Since the page
672 	 * is a root page, it is either write protected (and cannot be
673 	 * changed from now on) or it is invalid (in which case, we don't
674 	 * really care if it changes underneath us after this point).
675 	 */
676 	if (FNAME(gpte_changed)(vcpu, gw, top_level))
677 		return RET_PF_RETRY;
678 
679 	if (WARN_ON_ONCE(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
680 		return RET_PF_RETRY;
681 
682 	/*
683 	 * Load a new root and retry the faulting instruction in the extremely
684 	 * unlikely scenario that the guest root gfn became visible between
685 	 * loading a dummy root and handling the resulting page fault, e.g. if
686 	 * userspace create a memslot in the interim.
687 	 */
688 	if (unlikely(kvm_mmu_is_dummy_root(vcpu->arch.mmu->root.hpa))) {
689 		kvm_make_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu);
690 		return RET_PF_RETRY;
691 	}
692 
693 	for_each_shadow_entry(vcpu, fault->addr, it) {
694 		gfn_t table_gfn;
695 
696 		clear_sp_write_flooding_count(it.sptep);
697 		if (it.level == gw->level)
698 			break;
699 
700 		table_gfn = gw->table_gfn[it.level - 2];
701 		access = gw->pt_access[it.level - 2];
702 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, table_gfn,
703 					  false, access);
704 
705 		/*
706 		 * Synchronize the new page before linking it, as the CPU (KVM)
707 		 * is architecturally disallowed from inserting non-present
708 		 * entries into the TLB, i.e. the guest isn't required to flush
709 		 * the TLB when changing the gPTE from non-present to present.
710 		 *
711 		 * For PG_LEVEL_4K, kvm_mmu_find_shadow_page() has already
712 		 * synchronized the page via kvm_sync_page().
713 		 *
714 		 * For higher level pages, which cannot be unsync themselves
715 		 * but can have unsync children, synchronize via the slower
716 		 * mmu_sync_children().  If KVM needs to drop mmu_lock due to
717 		 * contention or to reschedule, instruct the caller to retry
718 		 * the #PF (mmu_sync_children() ensures forward progress will
719 		 * be made).
720 		 */
721 		if (sp != ERR_PTR(-EEXIST) && sp->unsync_children &&
722 		    mmu_sync_children(vcpu, sp, false))
723 			return RET_PF_RETRY;
724 
725 		/*
726 		 * Verify that the gpte in the page, which is now either
727 		 * write-protected or unsync, wasn't modified between the fault
728 		 * and acquiring mmu_lock.  This needs to be done even when
729 		 * reusing an existing shadow page to ensure the information
730 		 * gathered by the walker matches the information stored in the
731 		 * shadow page (which could have been modified by a different
732 		 * vCPU even if the page was already linked).  Holding mmu_lock
733 		 * prevents the shadow page from changing after this point.
734 		 */
735 		if (FNAME(gpte_changed)(vcpu, gw, it.level - 1))
736 			return RET_PF_RETRY;
737 
738 		if (sp != ERR_PTR(-EEXIST))
739 			link_shadow_page(vcpu, it.sptep, sp);
740 
741 		if (fault->write && table_gfn == fault->gfn)
742 			fault->write_fault_to_shadow_pgtable = true;
743 	}
744 
745 	/*
746 	 * Adjust the hugepage size _after_ resolving indirect shadow pages.
747 	 * KVM doesn't support mapping hugepages into the guest for gfns that
748 	 * are being shadowed by KVM, i.e. allocating a new shadow page may
749 	 * affect the allowed hugepage size.
750 	 */
751 	kvm_mmu_hugepage_adjust(vcpu, fault);
752 
753 	trace_kvm_mmu_spte_requested(fault, gw->pte_access);
754 
755 	for (; shadow_walk_okay(&it); shadow_walk_next(&it)) {
756 		/*
757 		 * We cannot overwrite existing page tables with an NX
758 		 * large page, as the leaf could be executable.
759 		 */
760 		if (fault->nx_huge_page_workaround_enabled)
761 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
762 
763 		base_gfn = gfn_round_for_level(fault->gfn, it.level);
764 		if (it.level == fault->goal_level)
765 			break;
766 
767 		validate_direct_spte(vcpu, it.sptep, direct_access);
768 
769 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn,
770 					  true, direct_access);
771 		if (sp == ERR_PTR(-EEXIST))
772 			continue;
773 
774 		link_shadow_page(vcpu, it.sptep, sp);
775 		if (fault->huge_page_disallowed)
776 			account_nx_huge_page(vcpu->kvm, sp,
777 					     fault->req_level >= it.level);
778 	}
779 
780 	if (KVM_BUG_ON(it.level != fault->goal_level, vcpu->kvm))
781 		return -EIO;
782 
783 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, gw->pte_access,
784 			   base_gfn, fault->pfn, fault);
785 	if (ret == RET_PF_SPURIOUS)
786 		return ret;
787 
788 	FNAME(pte_prefetch)(vcpu, gw, it.sptep);
789 	return ret;
790 }
791 
792 /*
793  * Page fault handler.  There are several causes for a page fault:
794  *   - there is no shadow pte for the guest pte
795  *   - write access through a shadow pte marked read only so that we can set
796  *     the dirty bit
797  *   - write access to a shadow pte marked read only so we can update the page
798  *     dirty bitmap, when userspace requests it
799  *   - mmio access; in this case we will never install a present shadow pte
800  *   - normal guest page fault due to the guest pte marked not present, not
801  *     writable, or not executable
802  *
803  *  Returns: 1 if we need to emulate the instruction, 0 otherwise, or
804  *           a negative value on error.
805  */
806 static int FNAME(page_fault)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
807 {
808 	struct guest_walker walker;
809 	int r;
810 
811 	WARN_ON_ONCE(fault->is_tdp);
812 
813 	/*
814 	 * Look up the guest pte for the faulting address.
815 	 * If PFEC.RSVD is set, this is a shadow page fault.
816 	 * The bit needs to be cleared before walking guest page tables.
817 	 */
818 	r = FNAME(walk_addr)(&walker, vcpu, fault->addr,
819 			     fault->error_code & ~PFERR_RSVD_MASK);
820 
821 	/*
822 	 * The page is not mapped by the guest.  Let the guest handle it.
823 	 */
824 	if (!r) {
825 		if (!fault->prefetch)
826 			__kvm_inject_emulated_page_fault(vcpu, &walker.fault, true);
827 
828 		return RET_PF_RETRY;
829 	}
830 
831 	fault->gfn = walker.gfn;
832 	fault->max_level = walker.level;
833 	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
834 
835 	if (page_fault_handle_page_track(vcpu, fault)) {
836 		shadow_page_table_clear_flood(vcpu, fault->addr);
837 		return RET_PF_WRITE_PROTECTED;
838 	}
839 
840 	r = mmu_topup_memory_caches(vcpu, true);
841 	if (r)
842 		return r;
843 
844 	r = kvm_mmu_faultin_pfn(vcpu, fault, walker.pte_access);
845 	if (r != RET_PF_CONTINUE)
846 		return r;
847 
848 #if PTTYPE != PTTYPE_EPT
849 	/*
850 	 * Treat the guest PTE protections as writable, supervisor-only if this
851 	 * is a supervisor write fault and CR0.WP=0 (supervisor accesses ignore
852 	 * PTE.W if CR0.WP=0).  Don't change the access type for emulated MMIO,
853 	 * otherwise KVM will cache incorrect access information in the SPTE.
854 	 */
855 	if (fault->write && !(walker.pte_access & ACC_WRITE_MASK) &&
856 	    !is_cr0_wp(vcpu->arch.mmu->w) && !fault->user && fault->slot) {
857 		walker.pte_access |= ACC_WRITE_MASK;
858 		walker.pte_access &= ~ACC_USER_MASK;
859 
860 		/*
861 		 * If we converted a user page to a kernel page,
862 		 * so that the kernel can write to it when cr0.wp=0,
863 		 * then we should prevent the kernel from executing it
864 		 * if SMEP is enabled.
865 		 */
866 		if (is_cr4_smep(vcpu->arch.mmu->w))
867 			walker.pte_access &= ~ACC_EXEC_MASK;
868 	}
869 #endif
870 
871 	write_lock(&vcpu->kvm->mmu_lock);
872 
873 	r = make_mmu_pages_available(vcpu);
874 	if (r)
875 		goto out_unlock;
876 
877 	if (is_page_fault_stale(vcpu, fault)) {
878 		r = RET_PF_RETRY;
879 		goto out_unlock;
880 	}
881 
882 	r = FNAME(fetch)(vcpu, fault, &walker);
883 
884 out_unlock:
885 	kvm_mmu_finish_page_fault(vcpu, fault, r);
886 	write_unlock(&vcpu->kvm->mmu_lock);
887 	return r;
888 }
889 
890 static gpa_t FNAME(get_level1_sp_gpa)(struct kvm_mmu_page *sp)
891 {
892 	int offset = 0;
893 
894 	WARN_ON_ONCE(sp->role.level != PG_LEVEL_4K);
895 
896 	if (PTTYPE == 32)
897 		offset = sp->role.quadrant << SPTE_LEVEL_BITS;
898 
899 	return gfn_to_gpa(sp->gfn) + offset * sizeof(pt_element_t);
900 }
901 
902 /* Note, @addr is a GPA when gva_to_gpa() translates an L2 GPA to an L1 GPA. */
903 static gpa_t FNAME(gva_to_gpa)(struct kvm_vcpu *vcpu, struct kvm_pagewalk *w,
904 			       gpa_t addr, u64 access,
905 			       struct x86_exception *exception)
906 {
907 	struct guest_walker walker;
908 	gpa_t gpa = INVALID_GPA;
909 	int r;
910 
911 #ifndef CONFIG_X86_64
912 	/* A 64-bit GVA should be impossible on 32-bit KVM. */
913 	WARN_ON_ONCE((addr >> 32) && w == &vcpu->arch.gva_walk);
914 #endif
915 
916 	r = FNAME(walk_addr_generic)(&walker, vcpu, w, addr, access);
917 
918 	if (r) {
919 		gpa = gfn_to_gpa(walker.gfn);
920 		gpa |= addr & ~PAGE_MASK;
921 	} else if (exception)
922 		*exception = walker.fault;
923 
924 	return gpa;
925 }
926 
927 /*
928  * Using the information in sp->shadowed_translation (kvm_mmu_page_get_gfn()) is
929  * safe because SPTEs are protected by mmu_notifiers and memslot generations, so
930  * the pfn for a given gfn can't change unless all SPTEs pointing to the gfn are
931  * nuked first.
932  *
933  * Returns
934  * < 0: failed to sync spte
935  *   0: the spte is synced and no tlb flushing is required
936  * > 0: the spte is synced and tlb flushing is required
937  */
938 static int FNAME(sync_spte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
939 {
940 	bool host_writable;
941 	gpa_t first_pte_gpa;
942 	u64 *sptep, spte;
943 	struct kvm_memory_slot *slot;
944 	unsigned pte_access;
945 	pt_element_t gpte;
946 	gpa_t pte_gpa;
947 	gfn_t gfn;
948 
949 	if (WARN_ON_ONCE(sp->spt[i] == SHADOW_NONPRESENT_VALUE ||
950 			 !sp->shadowed_translation))
951 		return 0;
952 
953 	first_pte_gpa = FNAME(get_level1_sp_gpa)(sp);
954 	pte_gpa = first_pte_gpa + i * sizeof(pt_element_t);
955 
956 	if (kvm_vcpu_read_guest_atomic(vcpu, pte_gpa, &gpte,
957 				       sizeof(pt_element_t)))
958 		return -1;
959 
960 	if (FNAME(prefetch_invalid_gpte)(vcpu, sp, &sp->spt[i], gpte))
961 		return 1;
962 
963 	gfn = gpte_to_gfn(gpte);
964 	pte_access = sp->role.access;
965 	pte_access &= FNAME(gpte_access)(gpte);
966 	FNAME(protect_clean_gpte)(vcpu->arch.mmu->w, &pte_access, gpte);
967 
968 	if (sync_mmio_spte(vcpu, &sp->spt[i], gfn, pte_access))
969 		return 0;
970 
971 	/*
972 	 * Drop the SPTE if the new protections result in no effective
973 	 * "present" bit or if the gfn is changing.  The former case
974 	 * only affects EPT with execute-only support with pte_access==0;
975 	 * all other paging modes will create a read-only SPTE if
976 	 * pte_access is zero.
977 	 */
978 	if ((pte_access | shadow_present_mask) == SHADOW_NONPRESENT_VALUE ||
979 	    gfn != kvm_mmu_page_get_gfn(sp, i)) {
980 		drop_spte(vcpu->kvm, &sp->spt[i]);
981 		return 1;
982 	}
983 	/*
984 	 * Do nothing if the permissions are unchanged.  The existing SPTE is
985 	 * still, and prefetch_invalid_gpte() has verified that the A/D bits
986 	 * are set in the "new" gPTE, i.e. there is no danger of missing an A/D
987 	 * update due to A/D bits being set in the SPTE but not the gPTE.
988 	 */
989 	if (kvm_mmu_page_get_access(sp, i) == pte_access)
990 		return 0;
991 
992 	/* Update the shadowed access bits in case they changed. */
993 	kvm_mmu_page_set_access(sp, i, pte_access);
994 
995 	sptep = &sp->spt[i];
996 	spte = *sptep;
997 	host_writable = spte & shadow_host_writable_mask;
998 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
999 	make_spte(vcpu, sp, slot, pte_access, gfn,
1000 		  spte_to_pfn(spte), spte, true, true,
1001 		  host_writable, &spte);
1002 
1003 	/*
1004 	 * There is no need to mark the pfn dirty, as the new protections must
1005 	 * be a subset of the old protections, i.e. synchronizing a SPTE cannot
1006 	 * change the SPTE from read-only to writable.
1007 	 */
1008 	return mmu_spte_update(sptep, spte);
1009 }
1010 
1011 #undef pt_element_t
1012 #undef guest_walker
1013 #undef FNAME
1014 #undef PT_BASE_ADDR_MASK
1015 #undef PT_INDEX
1016 #undef PT_LVL_ADDR_MASK
1017 #undef PT_LVL_OFFSET_MASK
1018 #undef PT_LEVEL_BITS
1019 #undef PT_MAX_FULL_LEVELS
1020 #undef gpte_to_gfn
1021 #undef gpte_to_gfn_lvl
1022 #undef PT_GUEST_ACCESSED_MASK
1023 #undef PT_GUEST_DIRTY_MASK
1024 #undef PT_GUEST_DIRTY_SHIFT
1025 #undef PT_GUEST_ACCESSED_SHIFT
1026 #undef PT_HAVE_ACCESSED_DIRTY
1027