xref: /openbmc/linux/arch/x86/kvm/mmu/paging_tmpl.h (revision fbb6b31a)
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  * We need the mmu code to access both 32-bit and 64-bit guest ptes,
20  * so the code in this file is compiled twice, once per pte size.
21  */
22 
23 #if PTTYPE == 64
24 	#define pt_element_t u64
25 	#define guest_walker guest_walker64
26 	#define FNAME(name) paging##64_##name
27 	#define PT_BASE_ADDR_MASK GUEST_PT64_BASE_ADDR_MASK
28 	#define PT_LVL_ADDR_MASK(lvl) PT64_LVL_ADDR_MASK(lvl)
29 	#define PT_LVL_OFFSET_MASK(lvl) PT64_LVL_OFFSET_MASK(lvl)
30 	#define PT_INDEX(addr, level) PT64_INDEX(addr, level)
31 	#define PT_LEVEL_BITS PT64_LEVEL_BITS
32 	#define PT_GUEST_DIRTY_SHIFT PT_DIRTY_SHIFT
33 	#define PT_GUEST_ACCESSED_SHIFT PT_ACCESSED_SHIFT
34 	#define PT_HAVE_ACCESSED_DIRTY(mmu) true
35 	#ifdef CONFIG_X86_64
36 	#define PT_MAX_FULL_LEVELS PT64_ROOT_MAX_LEVEL
37 	#define CMPXCHG "cmpxchgq"
38 	#else
39 	#define PT_MAX_FULL_LEVELS 2
40 	#endif
41 #elif PTTYPE == 32
42 	#define pt_element_t u32
43 	#define guest_walker guest_walker32
44 	#define FNAME(name) paging##32_##name
45 	#define PT_BASE_ADDR_MASK PT32_BASE_ADDR_MASK
46 	#define PT_LVL_ADDR_MASK(lvl) PT32_LVL_ADDR_MASK(lvl)
47 	#define PT_LVL_OFFSET_MASK(lvl) PT32_LVL_OFFSET_MASK(lvl)
48 	#define PT_INDEX(addr, level) PT32_INDEX(addr, level)
49 	#define PT_LEVEL_BITS PT32_LEVEL_BITS
50 	#define PT_MAX_FULL_LEVELS 2
51 	#define PT_GUEST_DIRTY_SHIFT PT_DIRTY_SHIFT
52 	#define PT_GUEST_ACCESSED_SHIFT PT_ACCESSED_SHIFT
53 	#define PT_HAVE_ACCESSED_DIRTY(mmu) true
54 	#define CMPXCHG "cmpxchgl"
55 #elif PTTYPE == PTTYPE_EPT
56 	#define pt_element_t u64
57 	#define guest_walker guest_walkerEPT
58 	#define FNAME(name) ept_##name
59 	#define PT_BASE_ADDR_MASK GUEST_PT64_BASE_ADDR_MASK
60 	#define PT_LVL_ADDR_MASK(lvl) PT64_LVL_ADDR_MASK(lvl)
61 	#define PT_LVL_OFFSET_MASK(lvl) PT64_LVL_OFFSET_MASK(lvl)
62 	#define PT_INDEX(addr, level) PT64_INDEX(addr, level)
63 	#define PT_LEVEL_BITS PT64_LEVEL_BITS
64 	#define PT_GUEST_DIRTY_SHIFT 9
65 	#define PT_GUEST_ACCESSED_SHIFT 8
66 	#define PT_HAVE_ACCESSED_DIRTY(mmu) ((mmu)->ept_ad)
67 	#ifdef CONFIG_X86_64
68 	#define CMPXCHG "cmpxchgq"
69 	#endif
70 	#define PT_MAX_FULL_LEVELS PT64_ROOT_MAX_LEVEL
71 #else
72 	#error Invalid PTTYPE value
73 #endif
74 
75 #define PT_GUEST_DIRTY_MASK    (1 << PT_GUEST_DIRTY_SHIFT)
76 #define PT_GUEST_ACCESSED_MASK (1 << PT_GUEST_ACCESSED_SHIFT)
77 
78 #define gpte_to_gfn_lvl FNAME(gpte_to_gfn_lvl)
79 #define gpte_to_gfn(pte) gpte_to_gfn_lvl((pte), PG_LEVEL_4K)
80 
81 /*
82  * The guest_walker structure emulates the behavior of the hardware page
83  * table walker.
84  */
85 struct guest_walker {
86 	int level;
87 	unsigned max_level;
88 	gfn_t table_gfn[PT_MAX_FULL_LEVELS];
89 	pt_element_t ptes[PT_MAX_FULL_LEVELS];
90 	pt_element_t prefetch_ptes[PTE_PREFETCH_NUM];
91 	gpa_t pte_gpa[PT_MAX_FULL_LEVELS];
92 	pt_element_t __user *ptep_user[PT_MAX_FULL_LEVELS];
93 	bool pte_writable[PT_MAX_FULL_LEVELS];
94 	unsigned int pt_access[PT_MAX_FULL_LEVELS];
95 	unsigned int pte_access;
96 	gfn_t gfn;
97 	struct x86_exception fault;
98 };
99 
100 static gfn_t gpte_to_gfn_lvl(pt_element_t gpte, int lvl)
101 {
102 	return (gpte & PT_LVL_ADDR_MASK(lvl)) >> PAGE_SHIFT;
103 }
104 
105 static inline void FNAME(protect_clean_gpte)(struct kvm_mmu *mmu, unsigned *access,
106 					     unsigned gpte)
107 {
108 	unsigned mask;
109 
110 	/* dirty bit is not supported, so no need to track it */
111 	if (!PT_HAVE_ACCESSED_DIRTY(mmu))
112 		return;
113 
114 	BUILD_BUG_ON(PT_WRITABLE_MASK != ACC_WRITE_MASK);
115 
116 	mask = (unsigned)~ACC_WRITE_MASK;
117 	/* Allow write access to dirty gptes */
118 	mask |= (gpte >> (PT_GUEST_DIRTY_SHIFT - PT_WRITABLE_SHIFT)) &
119 		PT_WRITABLE_MASK;
120 	*access &= mask;
121 }
122 
123 static inline int FNAME(is_present_gpte)(unsigned long pte)
124 {
125 #if PTTYPE != PTTYPE_EPT
126 	return pte & PT_PRESENT_MASK;
127 #else
128 	return pte & 7;
129 #endif
130 }
131 
132 static bool FNAME(is_bad_mt_xwr)(struct rsvd_bits_validate *rsvd_check, u64 gpte)
133 {
134 #if PTTYPE != PTTYPE_EPT
135 	return false;
136 #else
137 	return __is_bad_mt_xwr(rsvd_check, gpte);
138 #endif
139 }
140 
141 static bool FNAME(is_rsvd_bits_set)(struct kvm_mmu *mmu, u64 gpte, int level)
142 {
143 	return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level) ||
144 	       FNAME(is_bad_mt_xwr)(&mmu->guest_rsvd_check, gpte);
145 }
146 
147 static int FNAME(cmpxchg_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
148 			       pt_element_t __user *ptep_user, unsigned index,
149 			       pt_element_t orig_pte, pt_element_t new_pte)
150 {
151 	signed char r;
152 
153 	if (!user_access_begin(ptep_user, sizeof(pt_element_t)))
154 		return -EFAULT;
155 
156 #ifdef CMPXCHG
157 	asm volatile("1:" LOCK_PREFIX CMPXCHG " %[new], %[ptr]\n"
158 		     "setnz %b[r]\n"
159 		     "2:"
160 		     _ASM_EXTABLE_TYPE_REG(1b, 2b, EX_TYPE_EFAULT_REG, %k[r])
161 		     : [ptr] "+m" (*ptep_user),
162 		       [old] "+a" (orig_pte),
163 		       [r] "=q" (r)
164 		     : [new] "r" (new_pte)
165 		     : "memory");
166 #else
167 	asm volatile("1:" LOCK_PREFIX "cmpxchg8b %[ptr]\n"
168 		     "setnz %b[r]\n"
169 		     "2:"
170 		     _ASM_EXTABLE_TYPE_REG(1b, 2b, EX_TYPE_EFAULT_REG, %k[r])
171 		     : [ptr] "+m" (*ptep_user),
172 		       [old] "+A" (orig_pte),
173 		       [r] "=q" (r)
174 		     : [new_lo] "b" ((u32)new_pte),
175 		       [new_hi] "c" ((u32)(new_pte >> 32))
176 		     : "memory");
177 #endif
178 
179 	user_access_end();
180 	return r;
181 }
182 
183 static bool FNAME(prefetch_invalid_gpte)(struct kvm_vcpu *vcpu,
184 				  struct kvm_mmu_page *sp, u64 *spte,
185 				  u64 gpte)
186 {
187 	if (!FNAME(is_present_gpte)(gpte))
188 		goto no_present;
189 
190 	/* if accessed bit is not supported prefetch non accessed gpte */
191 	if (PT_HAVE_ACCESSED_DIRTY(vcpu->arch.mmu) &&
192 	    !(gpte & PT_GUEST_ACCESSED_MASK))
193 		goto no_present;
194 
195 	if (FNAME(is_rsvd_bits_set)(vcpu->arch.mmu, gpte, PG_LEVEL_4K))
196 		goto no_present;
197 
198 	return false;
199 
200 no_present:
201 	drop_spte(vcpu->kvm, spte);
202 	return true;
203 }
204 
205 /*
206  * For PTTYPE_EPT, a page table can be executable but not readable
207  * on supported processors. Therefore, set_spte does not automatically
208  * set bit 0 if execute only is supported. Here, we repurpose ACC_USER_MASK
209  * to signify readability since it isn't used in the EPT case
210  */
211 static inline unsigned FNAME(gpte_access)(u64 gpte)
212 {
213 	unsigned access;
214 #if PTTYPE == PTTYPE_EPT
215 	access = ((gpte & VMX_EPT_WRITABLE_MASK) ? ACC_WRITE_MASK : 0) |
216 		((gpte & VMX_EPT_EXECUTABLE_MASK) ? ACC_EXEC_MASK : 0) |
217 		((gpte & VMX_EPT_READABLE_MASK) ? ACC_USER_MASK : 0);
218 #else
219 	BUILD_BUG_ON(ACC_EXEC_MASK != PT_PRESENT_MASK);
220 	BUILD_BUG_ON(ACC_EXEC_MASK != 1);
221 	access = gpte & (PT_WRITABLE_MASK | PT_USER_MASK | PT_PRESENT_MASK);
222 	/* Combine NX with P (which is set here) to get ACC_EXEC_MASK.  */
223 	access ^= (gpte >> PT64_NX_SHIFT);
224 #endif
225 
226 	return access;
227 }
228 
229 static int FNAME(update_accessed_dirty_bits)(struct kvm_vcpu *vcpu,
230 					     struct kvm_mmu *mmu,
231 					     struct guest_walker *walker,
232 					     gpa_t addr, int write_fault)
233 {
234 	unsigned level, index;
235 	pt_element_t pte, orig_pte;
236 	pt_element_t __user *ptep_user;
237 	gfn_t table_gfn;
238 	int ret;
239 
240 	/* dirty/accessed bits are not supported, so no need to update them */
241 	if (!PT_HAVE_ACCESSED_DIRTY(mmu))
242 		return 0;
243 
244 	for (level = walker->max_level; level >= walker->level; --level) {
245 		pte = orig_pte = walker->ptes[level - 1];
246 		table_gfn = walker->table_gfn[level - 1];
247 		ptep_user = walker->ptep_user[level - 1];
248 		index = offset_in_page(ptep_user) / sizeof(pt_element_t);
249 		if (!(pte & PT_GUEST_ACCESSED_MASK)) {
250 			trace_kvm_mmu_set_accessed_bit(table_gfn, index, sizeof(pte));
251 			pte |= PT_GUEST_ACCESSED_MASK;
252 		}
253 		if (level == walker->level && write_fault &&
254 				!(pte & PT_GUEST_DIRTY_MASK)) {
255 			trace_kvm_mmu_set_dirty_bit(table_gfn, index, sizeof(pte));
256 #if PTTYPE == PTTYPE_EPT
257 			if (kvm_x86_ops.nested_ops->write_log_dirty(vcpu, addr))
258 				return -EINVAL;
259 #endif
260 			pte |= PT_GUEST_DIRTY_MASK;
261 		}
262 		if (pte == orig_pte)
263 			continue;
264 
265 		/*
266 		 * If the slot is read-only, simply do not process the accessed
267 		 * and dirty bits.  This is the correct thing to do if the slot
268 		 * is ROM, and page tables in read-as-ROM/write-as-MMIO slots
269 		 * are only supported if the accessed and dirty bits are already
270 		 * set in the ROM (so that MMIO writes are never needed).
271 		 *
272 		 * Note that NPT does not allow this at all and faults, since
273 		 * it always wants nested page table entries for the guest
274 		 * page tables to be writable.  And EPT works but will simply
275 		 * overwrite the read-only memory to set the accessed and dirty
276 		 * bits.
277 		 */
278 		if (unlikely(!walker->pte_writable[level - 1]))
279 			continue;
280 
281 		ret = FNAME(cmpxchg_gpte)(vcpu, mmu, ptep_user, index, orig_pte, pte);
282 		if (ret)
283 			return ret;
284 
285 		kvm_vcpu_mark_page_dirty(vcpu, table_gfn);
286 		walker->ptes[level - 1] = pte;
287 	}
288 	return 0;
289 }
290 
291 static inline unsigned FNAME(gpte_pkeys)(struct kvm_vcpu *vcpu, u64 gpte)
292 {
293 	unsigned pkeys = 0;
294 #if PTTYPE == 64
295 	pte_t pte = {.pte = gpte};
296 
297 	pkeys = pte_flags_pkey(pte_flags(pte));
298 #endif
299 	return pkeys;
300 }
301 
302 static inline bool FNAME(is_last_gpte)(struct kvm_mmu *mmu,
303 				       unsigned int level, unsigned int gpte)
304 {
305 	/*
306 	 * For EPT and PAE paging (both variants), bit 7 is either reserved at
307 	 * all level or indicates a huge page (ignoring CR3/EPTP).  In either
308 	 * case, bit 7 being set terminates the walk.
309 	 */
310 #if PTTYPE == 32
311 	/*
312 	 * 32-bit paging requires special handling because bit 7 is ignored if
313 	 * CR4.PSE=0, not reserved.  Clear bit 7 in the gpte if the level is
314 	 * greater than the last level for which bit 7 is the PAGE_SIZE bit.
315 	 *
316 	 * The RHS has bit 7 set iff level < (2 + PSE).  If it is clear, bit 7
317 	 * is not reserved and does not indicate a large page at this level,
318 	 * so clear PT_PAGE_SIZE_MASK in gpte if that is the case.
319 	 */
320 	gpte &= level - (PT32_ROOT_LEVEL + mmu->mmu_role.ext.cr4_pse);
321 #endif
322 	/*
323 	 * PG_LEVEL_4K always terminates.  The RHS has bit 7 set
324 	 * iff level <= PG_LEVEL_4K, which for our purpose means
325 	 * level == PG_LEVEL_4K; set PT_PAGE_SIZE_MASK in gpte then.
326 	 */
327 	gpte |= level - PG_LEVEL_4K - 1;
328 
329 	return gpte & PT_PAGE_SIZE_MASK;
330 }
331 /*
332  * Fetch a guest pte for a guest virtual address, or for an L2's GPA.
333  */
334 static int FNAME(walk_addr_generic)(struct guest_walker *walker,
335 				    struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
336 				    gpa_t addr, u64 access)
337 {
338 	int ret;
339 	pt_element_t pte;
340 	pt_element_t __user *ptep_user;
341 	gfn_t table_gfn;
342 	u64 pt_access, pte_access;
343 	unsigned index, accessed_dirty, pte_pkey;
344 	u64 nested_access;
345 	gpa_t pte_gpa;
346 	bool have_ad;
347 	int offset;
348 	u64 walk_nx_mask = 0;
349 	const int write_fault = access & PFERR_WRITE_MASK;
350 	const int user_fault  = access & PFERR_USER_MASK;
351 	const int fetch_fault = access & PFERR_FETCH_MASK;
352 	u16 errcode = 0;
353 	gpa_t real_gpa;
354 	gfn_t gfn;
355 
356 	trace_kvm_mmu_pagetable_walk(addr, access);
357 retry_walk:
358 	walker->level = mmu->root_level;
359 	pte           = mmu->get_guest_pgd(vcpu);
360 	have_ad       = PT_HAVE_ACCESSED_DIRTY(mmu);
361 
362 #if PTTYPE == 64
363 	walk_nx_mask = 1ULL << PT64_NX_SHIFT;
364 	if (walker->level == PT32E_ROOT_LEVEL) {
365 		pte = mmu->get_pdptr(vcpu, (addr >> 30) & 3);
366 		trace_kvm_mmu_paging_element(pte, walker->level);
367 		if (!FNAME(is_present_gpte)(pte))
368 			goto error;
369 		--walker->level;
370 	}
371 #endif
372 	walker->max_level = walker->level;
373 	ASSERT(!(is_long_mode(vcpu) && !is_pae(vcpu)));
374 
375 	/*
376 	 * FIXME: on Intel processors, loads of the PDPTE registers for PAE paging
377 	 * by the MOV to CR instruction are treated as reads and do not cause the
378 	 * processor to set the dirty flag in any EPT paging-structure entry.
379 	 */
380 	nested_access = (have_ad ? PFERR_WRITE_MASK : 0) | PFERR_USER_MASK;
381 
382 	pte_access = ~0;
383 	++walker->level;
384 
385 	do {
386 		unsigned long host_addr;
387 
388 		pt_access = pte_access;
389 		--walker->level;
390 
391 		index = PT_INDEX(addr, walker->level);
392 		table_gfn = gpte_to_gfn(pte);
393 		offset    = index * sizeof(pt_element_t);
394 		pte_gpa   = gfn_to_gpa(table_gfn) + offset;
395 
396 		BUG_ON(walker->level < 1);
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, mmu, gfn_to_gpa(table_gfn),
401 					     nested_access, &walker->fault);
402 
403 		/*
404 		 * FIXME: This can happen if emulation (for of an INS/OUTS
405 		 * instruction) triggers a nested page fault.  The exit
406 		 * qualification / exit info field will incorrectly have
407 		 * "guest page access" as the nested page fault's cause,
408 		 * instead of "guest page structure access".  To fix this,
409 		 * the x86_exception struct should be augmented with enough
410 		 * information to fix the exit_qualification or exit_info_1
411 		 * fields.
412 		 */
413 		if (unlikely(real_gpa == UNMAPPED_GVA))
414 			return 0;
415 
416 		host_addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gpa_to_gfn(real_gpa),
417 					    &walker->pte_writable[walker->level - 1]);
418 		if (unlikely(kvm_is_error_hva(host_addr)))
419 			goto error;
420 
421 		ptep_user = (pt_element_t __user *)((void *)host_addr + offset);
422 		if (unlikely(__get_user(pte, ptep_user)))
423 			goto error;
424 		walker->ptep_user[walker->level - 1] = ptep_user;
425 
426 		trace_kvm_mmu_paging_element(pte, walker->level);
427 
428 		/*
429 		 * Inverting the NX it lets us AND it like other
430 		 * permission bits.
431 		 */
432 		pte_access = pt_access & (pte ^ walk_nx_mask);
433 
434 		if (unlikely(!FNAME(is_present_gpte)(pte)))
435 			goto error;
436 
437 		if (unlikely(FNAME(is_rsvd_bits_set)(mmu, pte, walker->level))) {
438 			errcode = PFERR_RSVD_MASK | PFERR_PRESENT_MASK;
439 			goto error;
440 		}
441 
442 		walker->ptes[walker->level - 1] = pte;
443 
444 		/* Convert to ACC_*_MASK flags for struct guest_walker.  */
445 		walker->pt_access[walker->level - 1] = FNAME(gpte_access)(pt_access ^ walk_nx_mask);
446 	} while (!FNAME(is_last_gpte)(mmu, walker->level, pte));
447 
448 	pte_pkey = FNAME(gpte_pkeys)(vcpu, pte);
449 	accessed_dirty = have_ad ? pte_access & PT_GUEST_ACCESSED_MASK : 0;
450 
451 	/* Convert to ACC_*_MASK flags for struct guest_walker.  */
452 	walker->pte_access = FNAME(gpte_access)(pte_access ^ walk_nx_mask);
453 	errcode = permission_fault(vcpu, mmu, walker->pte_access, pte_pkey, access);
454 	if (unlikely(errcode))
455 		goto error;
456 
457 	gfn = gpte_to_gfn_lvl(pte, walker->level);
458 	gfn += (addr & PT_LVL_OFFSET_MASK(walker->level)) >> PAGE_SHIFT;
459 
460 	if (PTTYPE == 32 && walker->level > PG_LEVEL_4K && is_cpuid_PSE36())
461 		gfn += pse36_gfn_delta(pte);
462 
463 	real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(gfn), access, &walker->fault);
464 	if (real_gpa == UNMAPPED_GVA)
465 		return 0;
466 
467 	walker->gfn = real_gpa >> PAGE_SHIFT;
468 
469 	if (!write_fault)
470 		FNAME(protect_clean_gpte)(mmu, &walker->pte_access, pte);
471 	else
472 		/*
473 		 * On a write fault, fold the dirty bit into accessed_dirty.
474 		 * For modes without A/D bits support accessed_dirty will be
475 		 * always clear.
476 		 */
477 		accessed_dirty &= pte >>
478 			(PT_GUEST_DIRTY_SHIFT - PT_GUEST_ACCESSED_SHIFT);
479 
480 	if (unlikely(!accessed_dirty)) {
481 		ret = FNAME(update_accessed_dirty_bits)(vcpu, mmu, walker,
482 							addr, write_fault);
483 		if (unlikely(ret < 0))
484 			goto error;
485 		else if (ret)
486 			goto retry_walk;
487 	}
488 
489 	pgprintk("%s: pte %llx pte_access %x pt_access %x\n",
490 		 __func__, (u64)pte, walker->pte_access,
491 		 walker->pt_access[walker->level - 1]);
492 	return 1;
493 
494 error:
495 	errcode |= write_fault | user_fault;
496 	if (fetch_fault && (is_efer_nx(mmu) || is_cr4_smep(mmu)))
497 		errcode |= PFERR_FETCH_MASK;
498 
499 	walker->fault.vector = PF_VECTOR;
500 	walker->fault.error_code_valid = true;
501 	walker->fault.error_code = errcode;
502 
503 #if PTTYPE == PTTYPE_EPT
504 	/*
505 	 * Use PFERR_RSVD_MASK in error_code to to tell if EPT
506 	 * misconfiguration requires to be injected. The detection is
507 	 * done by is_rsvd_bits_set() above.
508 	 *
509 	 * We set up the value of exit_qualification to inject:
510 	 * [2:0] - Derive from the access bits. The exit_qualification might be
511 	 *         out of date if it is serving an EPT misconfiguration.
512 	 * [5:3] - Calculated by the page walk of the guest EPT page tables
513 	 * [7:8] - Derived from [7:8] of real exit_qualification
514 	 *
515 	 * The other bits are set to 0.
516 	 */
517 	if (!(errcode & PFERR_RSVD_MASK)) {
518 		vcpu->arch.exit_qualification &= 0x180;
519 		if (write_fault)
520 			vcpu->arch.exit_qualification |= EPT_VIOLATION_ACC_WRITE;
521 		if (user_fault)
522 			vcpu->arch.exit_qualification |= EPT_VIOLATION_ACC_READ;
523 		if (fetch_fault)
524 			vcpu->arch.exit_qualification |= EPT_VIOLATION_ACC_INSTR;
525 		vcpu->arch.exit_qualification |= (pte_access & 0x7) << 3;
526 	}
527 #endif
528 	walker->fault.address = addr;
529 	walker->fault.nested_page_fault = mmu != vcpu->arch.walk_mmu;
530 	walker->fault.async_page_fault = false;
531 
532 	trace_kvm_mmu_walker_error(walker->fault.error_code);
533 	return 0;
534 }
535 
536 static int FNAME(walk_addr)(struct guest_walker *walker,
537 			    struct kvm_vcpu *vcpu, gpa_t addr, u64 access)
538 {
539 	return FNAME(walk_addr_generic)(walker, vcpu, vcpu->arch.mmu, addr,
540 					access);
541 }
542 
543 static bool
544 FNAME(prefetch_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
545 		     u64 *spte, pt_element_t gpte, bool no_dirty_log)
546 {
547 	struct kvm_memory_slot *slot;
548 	unsigned pte_access;
549 	gfn_t gfn;
550 	kvm_pfn_t pfn;
551 
552 	if (FNAME(prefetch_invalid_gpte)(vcpu, sp, spte, gpte))
553 		return false;
554 
555 	pgprintk("%s: gpte %llx spte %p\n", __func__, (u64)gpte, spte);
556 
557 	gfn = gpte_to_gfn(gpte);
558 	pte_access = sp->role.access & FNAME(gpte_access)(gpte);
559 	FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);
560 
561 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn,
562 			no_dirty_log && (pte_access & ACC_WRITE_MASK));
563 	if (!slot)
564 		return false;
565 
566 	pfn = gfn_to_pfn_memslot_atomic(slot, gfn);
567 	if (is_error_pfn(pfn))
568 		return false;
569 
570 	mmu_set_spte(vcpu, slot, spte, pte_access, gfn, pfn, NULL);
571 	kvm_release_pfn_clean(pfn);
572 	return true;
573 }
574 
575 static bool FNAME(gpte_changed)(struct kvm_vcpu *vcpu,
576 				struct guest_walker *gw, int level)
577 {
578 	pt_element_t curr_pte;
579 	gpa_t base_gpa, pte_gpa = gw->pte_gpa[level - 1];
580 	u64 mask;
581 	int r, index;
582 
583 	if (level == PG_LEVEL_4K) {
584 		mask = PTE_PREFETCH_NUM * sizeof(pt_element_t) - 1;
585 		base_gpa = pte_gpa & ~mask;
586 		index = (pte_gpa - base_gpa) / sizeof(pt_element_t);
587 
588 		r = kvm_vcpu_read_guest_atomic(vcpu, base_gpa,
589 				gw->prefetch_ptes, sizeof(gw->prefetch_ptes));
590 		curr_pte = gw->prefetch_ptes[index];
591 	} else
592 		r = kvm_vcpu_read_guest_atomic(vcpu, pte_gpa,
593 				  &curr_pte, sizeof(curr_pte));
594 
595 	return r || curr_pte != gw->ptes[level - 1];
596 }
597 
598 static void FNAME(pte_prefetch)(struct kvm_vcpu *vcpu, struct guest_walker *gw,
599 				u64 *sptep)
600 {
601 	struct kvm_mmu_page *sp;
602 	pt_element_t *gptep = gw->prefetch_ptes;
603 	u64 *spte;
604 	int i;
605 
606 	sp = sptep_to_sp(sptep);
607 
608 	if (sp->role.level > PG_LEVEL_4K)
609 		return;
610 
611 	/*
612 	 * If addresses are being invalidated, skip prefetching to avoid
613 	 * accidentally prefetching those addresses.
614 	 */
615 	if (unlikely(vcpu->kvm->mmu_notifier_count))
616 		return;
617 
618 	if (sp->role.direct)
619 		return __direct_pte_prefetch(vcpu, sp, sptep);
620 
621 	i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
622 	spte = sp->spt + i;
623 
624 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
625 		if (spte == sptep)
626 			continue;
627 
628 		if (is_shadow_present_pte(*spte))
629 			continue;
630 
631 		if (!FNAME(prefetch_gpte)(vcpu, sp, spte, gptep[i], true))
632 			break;
633 	}
634 }
635 
636 /*
637  * Fetch a shadow pte for a specific level in the paging hierarchy.
638  * If the guest tries to write a write-protected page, we need to
639  * emulate this operation, return 1 to indicate this case.
640  */
641 static int FNAME(fetch)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
642 			 struct guest_walker *gw)
643 {
644 	struct kvm_mmu_page *sp = NULL;
645 	struct kvm_shadow_walk_iterator it;
646 	unsigned int direct_access, access;
647 	int top_level, ret;
648 	gfn_t base_gfn = fault->gfn;
649 
650 	WARN_ON_ONCE(gw->gfn != base_gfn);
651 	direct_access = gw->pte_access;
652 
653 	top_level = vcpu->arch.mmu->root_level;
654 	if (top_level == PT32E_ROOT_LEVEL)
655 		top_level = PT32_ROOT_LEVEL;
656 	/*
657 	 * Verify that the top-level gpte is still there.  Since the page
658 	 * is a root page, it is either write protected (and cannot be
659 	 * changed from now on) or it is invalid (in which case, we don't
660 	 * really care if it changes underneath us after this point).
661 	 */
662 	if (FNAME(gpte_changed)(vcpu, gw, top_level))
663 		goto out_gpte_changed;
664 
665 	if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
666 		goto out_gpte_changed;
667 
668 	for (shadow_walk_init(&it, vcpu, fault->addr);
669 	     shadow_walk_okay(&it) && it.level > gw->level;
670 	     shadow_walk_next(&it)) {
671 		gfn_t table_gfn;
672 
673 		clear_sp_write_flooding_count(it.sptep);
674 		drop_large_spte(vcpu, it.sptep);
675 
676 		sp = NULL;
677 		if (!is_shadow_present_pte(*it.sptep)) {
678 			table_gfn = gw->table_gfn[it.level - 2];
679 			access = gw->pt_access[it.level - 2];
680 			sp = kvm_mmu_get_page(vcpu, table_gfn, fault->addr,
681 					      it.level-1, false, access);
682 			/*
683 			 * We must synchronize the pagetable before linking it
684 			 * because the guest doesn't need to flush tlb when
685 			 * the gpte is changed from non-present to present.
686 			 * Otherwise, the guest may use the wrong mapping.
687 			 *
688 			 * For PG_LEVEL_4K, kvm_mmu_get_page() has already
689 			 * synchronized it transiently via kvm_sync_page().
690 			 *
691 			 * For higher level pagetable, we synchronize it via
692 			 * the slower mmu_sync_children().  If it needs to
693 			 * break, some progress has been made; return
694 			 * RET_PF_RETRY and retry on the next #PF.
695 			 * KVM_REQ_MMU_SYNC is not necessary but it
696 			 * expedites the process.
697 			 */
698 			if (sp->unsync_children &&
699 			    mmu_sync_children(vcpu, sp, false))
700 				return RET_PF_RETRY;
701 		}
702 
703 		/*
704 		 * Verify that the gpte in the page we've just write
705 		 * protected is still there.
706 		 */
707 		if (FNAME(gpte_changed)(vcpu, gw, it.level - 1))
708 			goto out_gpte_changed;
709 
710 		if (sp)
711 			link_shadow_page(vcpu, it.sptep, sp);
712 	}
713 
714 	kvm_mmu_hugepage_adjust(vcpu, fault);
715 
716 	trace_kvm_mmu_spte_requested(fault);
717 
718 	for (; shadow_walk_okay(&it); shadow_walk_next(&it)) {
719 		clear_sp_write_flooding_count(it.sptep);
720 
721 		/*
722 		 * We cannot overwrite existing page tables with an NX
723 		 * large page, as the leaf could be executable.
724 		 */
725 		if (fault->nx_huge_page_workaround_enabled)
726 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
727 
728 		base_gfn = fault->gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
729 		if (it.level == fault->goal_level)
730 			break;
731 
732 		validate_direct_spte(vcpu, it.sptep, direct_access);
733 
734 		drop_large_spte(vcpu, it.sptep);
735 
736 		if (!is_shadow_present_pte(*it.sptep)) {
737 			sp = kvm_mmu_get_page(vcpu, base_gfn, fault->addr,
738 					      it.level - 1, true, direct_access);
739 			link_shadow_page(vcpu, it.sptep, sp);
740 			if (fault->huge_page_disallowed &&
741 			    fault->req_level >= it.level)
742 				account_huge_nx_page(vcpu->kvm, sp);
743 		}
744 	}
745 
746 	if (WARN_ON_ONCE(it.level != fault->goal_level))
747 		return -EFAULT;
748 
749 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, gw->pte_access,
750 			   base_gfn, fault->pfn, fault);
751 	if (ret == RET_PF_SPURIOUS)
752 		return ret;
753 
754 	FNAME(pte_prefetch)(vcpu, gw, it.sptep);
755 	++vcpu->stat.pf_fixed;
756 	return ret;
757 
758 out_gpte_changed:
759 	return RET_PF_RETRY;
760 }
761 
762  /*
763  * To see whether the mapped gfn can write its page table in the current
764  * mapping.
765  *
766  * It is the helper function of FNAME(page_fault). When guest uses large page
767  * size to map the writable gfn which is used as current page table, we should
768  * force kvm to use small page size to map it because new shadow page will be
769  * created when kvm establishes shadow page table that stop kvm using large
770  * page size. Do it early can avoid unnecessary #PF and emulation.
771  *
772  * @write_fault_to_shadow_pgtable will return true if the fault gfn is
773  * currently used as its page table.
774  *
775  * Note: the PDPT page table is not checked for PAE-32 bit guest. It is ok
776  * since the PDPT is always shadowed, that means, we can not use large page
777  * size to map the gfn which is used as PDPT.
778  */
779 static bool
780 FNAME(is_self_change_mapping)(struct kvm_vcpu *vcpu,
781 			      struct guest_walker *walker, bool user_fault,
782 			      bool *write_fault_to_shadow_pgtable)
783 {
784 	int level;
785 	gfn_t mask = ~(KVM_PAGES_PER_HPAGE(walker->level) - 1);
786 	bool self_changed = false;
787 
788 	if (!(walker->pte_access & ACC_WRITE_MASK ||
789 	    (!is_cr0_wp(vcpu->arch.mmu) && !user_fault)))
790 		return false;
791 
792 	for (level = walker->level; level <= walker->max_level; level++) {
793 		gfn_t gfn = walker->gfn ^ walker->table_gfn[level - 1];
794 
795 		self_changed |= !(gfn & mask);
796 		*write_fault_to_shadow_pgtable |= !gfn;
797 	}
798 
799 	return self_changed;
800 }
801 
802 /*
803  * Page fault handler.  There are several causes for a page fault:
804  *   - there is no shadow pte for the guest pte
805  *   - write access through a shadow pte marked read only so that we can set
806  *     the dirty bit
807  *   - write access to a shadow pte marked read only so we can update the page
808  *     dirty bitmap, when userspace requests it
809  *   - mmio access; in this case we will never install a present shadow pte
810  *   - normal guest page fault due to the guest pte marked not present, not
811  *     writable, or not executable
812  *
813  *  Returns: 1 if we need to emulate the instruction, 0 otherwise, or
814  *           a negative value on error.
815  */
816 static int FNAME(page_fault)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
817 {
818 	struct guest_walker walker;
819 	int r;
820 	unsigned long mmu_seq;
821 	bool is_self_change_mapping;
822 
823 	pgprintk("%s: addr %lx err %x\n", __func__, fault->addr, fault->error_code);
824 	WARN_ON_ONCE(fault->is_tdp);
825 
826 	/*
827 	 * Look up the guest pte for the faulting address.
828 	 * If PFEC.RSVD is set, this is a shadow page fault.
829 	 * The bit needs to be cleared before walking guest page tables.
830 	 */
831 	r = FNAME(walk_addr)(&walker, vcpu, fault->addr,
832 			     fault->error_code & ~PFERR_RSVD_MASK);
833 
834 	/*
835 	 * The page is not mapped by the guest.  Let the guest handle it.
836 	 */
837 	if (!r) {
838 		pgprintk("%s: guest page fault\n", __func__);
839 		if (!fault->prefetch)
840 			kvm_inject_emulated_page_fault(vcpu, &walker.fault);
841 
842 		return RET_PF_RETRY;
843 	}
844 
845 	fault->gfn = walker.gfn;
846 	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
847 
848 	if (page_fault_handle_page_track(vcpu, fault)) {
849 		shadow_page_table_clear_flood(vcpu, fault->addr);
850 		return RET_PF_EMULATE;
851 	}
852 
853 	r = mmu_topup_memory_caches(vcpu, true);
854 	if (r)
855 		return r;
856 
857 	vcpu->arch.write_fault_to_shadow_pgtable = false;
858 
859 	is_self_change_mapping = FNAME(is_self_change_mapping)(vcpu,
860 	      &walker, fault->user, &vcpu->arch.write_fault_to_shadow_pgtable);
861 
862 	if (is_self_change_mapping)
863 		fault->max_level = PG_LEVEL_4K;
864 	else
865 		fault->max_level = walker.level;
866 
867 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
868 	smp_rmb();
869 
870 	if (kvm_faultin_pfn(vcpu, fault, &r))
871 		return r;
872 
873 	if (handle_abnormal_pfn(vcpu, fault, walker.pte_access, &r))
874 		return r;
875 
876 	/*
877 	 * Do not change pte_access if the pfn is a mmio page, otherwise
878 	 * we will cache the incorrect access into mmio spte.
879 	 */
880 	if (fault->write && !(walker.pte_access & ACC_WRITE_MASK) &&
881 	    !is_cr0_wp(vcpu->arch.mmu) && !fault->user && fault->slot) {
882 		walker.pte_access |= ACC_WRITE_MASK;
883 		walker.pte_access &= ~ACC_USER_MASK;
884 
885 		/*
886 		 * If we converted a user page to a kernel page,
887 		 * so that the kernel can write to it when cr0.wp=0,
888 		 * then we should prevent the kernel from executing it
889 		 * if SMEP is enabled.
890 		 */
891 		if (is_cr4_smep(vcpu->arch.mmu))
892 			walker.pte_access &= ~ACC_EXEC_MASK;
893 	}
894 
895 	r = RET_PF_RETRY;
896 	write_lock(&vcpu->kvm->mmu_lock);
897 
898 	if (is_page_fault_stale(vcpu, fault, mmu_seq))
899 		goto out_unlock;
900 
901 	r = make_mmu_pages_available(vcpu);
902 	if (r)
903 		goto out_unlock;
904 	r = FNAME(fetch)(vcpu, fault, &walker);
905 
906 out_unlock:
907 	write_unlock(&vcpu->kvm->mmu_lock);
908 	kvm_release_pfn_clean(fault->pfn);
909 	return r;
910 }
911 
912 static gpa_t FNAME(get_level1_sp_gpa)(struct kvm_mmu_page *sp)
913 {
914 	int offset = 0;
915 
916 	WARN_ON(sp->role.level != PG_LEVEL_4K);
917 
918 	if (PTTYPE == 32)
919 		offset = sp->role.quadrant << PT64_LEVEL_BITS;
920 
921 	return gfn_to_gpa(sp->gfn) + offset * sizeof(pt_element_t);
922 }
923 
924 static void FNAME(invlpg)(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root_hpa)
925 {
926 	struct kvm_shadow_walk_iterator iterator;
927 	struct kvm_mmu_page *sp;
928 	u64 old_spte;
929 	int level;
930 	u64 *sptep;
931 
932 	vcpu_clear_mmio_info(vcpu, gva);
933 
934 	/*
935 	 * No need to check return value here, rmap_can_add() can
936 	 * help us to skip pte prefetch later.
937 	 */
938 	mmu_topup_memory_caches(vcpu, true);
939 
940 	if (!VALID_PAGE(root_hpa)) {
941 		WARN_ON(1);
942 		return;
943 	}
944 
945 	write_lock(&vcpu->kvm->mmu_lock);
946 	for_each_shadow_entry_using_root(vcpu, root_hpa, gva, iterator) {
947 		level = iterator.level;
948 		sptep = iterator.sptep;
949 
950 		sp = sptep_to_sp(sptep);
951 		old_spte = *sptep;
952 		if (is_last_spte(old_spte, level)) {
953 			pt_element_t gpte;
954 			gpa_t pte_gpa;
955 
956 			if (!sp->unsync)
957 				break;
958 
959 			pte_gpa = FNAME(get_level1_sp_gpa)(sp);
960 			pte_gpa += (sptep - sp->spt) * sizeof(pt_element_t);
961 
962 			mmu_page_zap_pte(vcpu->kvm, sp, sptep, NULL);
963 			if (is_shadow_present_pte(old_spte))
964 				kvm_flush_remote_tlbs_with_address(vcpu->kvm,
965 					sp->gfn, KVM_PAGES_PER_HPAGE(sp->role.level));
966 
967 			if (!rmap_can_add(vcpu))
968 				break;
969 
970 			if (kvm_vcpu_read_guest_atomic(vcpu, pte_gpa, &gpte,
971 						       sizeof(pt_element_t)))
972 				break;
973 
974 			FNAME(prefetch_gpte)(vcpu, sp, sptep, gpte, false);
975 		}
976 
977 		if (!sp->unsync_children)
978 			break;
979 	}
980 	write_unlock(&vcpu->kvm->mmu_lock);
981 }
982 
983 /* Note, @addr is a GPA when gva_to_gpa() translates an L2 GPA to an L1 GPA. */
984 static gpa_t FNAME(gva_to_gpa)(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
985 			       gpa_t addr, u64 access,
986 			       struct x86_exception *exception)
987 {
988 	struct guest_walker walker;
989 	gpa_t gpa = UNMAPPED_GVA;
990 	int r;
991 
992 #ifndef CONFIG_X86_64
993 	/* A 64-bit GVA should be impossible on 32-bit KVM. */
994 	WARN_ON_ONCE((addr >> 32) && mmu == vcpu->arch.walk_mmu);
995 #endif
996 
997 	r = FNAME(walk_addr_generic)(&walker, vcpu, mmu, addr, access);
998 
999 	if (r) {
1000 		gpa = gfn_to_gpa(walker.gfn);
1001 		gpa |= addr & ~PAGE_MASK;
1002 	} else if (exception)
1003 		*exception = walker.fault;
1004 
1005 	return gpa;
1006 }
1007 
1008 /*
1009  * Using the cached information from sp->gfns is safe because:
1010  * - The spte has a reference to the struct page, so the pfn for a given gfn
1011  *   can't change unless all sptes pointing to it are nuked first.
1012  *
1013  * Returns
1014  * < 0: the sp should be zapped
1015  *   0: the sp is synced and no tlb flushing is required
1016  * > 0: the sp is synced and tlb flushing is required
1017  */
1018 static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1019 {
1020 	union kvm_mmu_page_role mmu_role = vcpu->arch.mmu->mmu_role.base;
1021 	int i;
1022 	bool host_writable;
1023 	gpa_t first_pte_gpa;
1024 	bool flush = false;
1025 
1026 	/*
1027 	 * Ignore various flags when verifying that it's safe to sync a shadow
1028 	 * page using the current MMU context.
1029 	 *
1030 	 *  - level: not part of the overall MMU role and will never match as the MMU's
1031 	 *           level tracks the root level
1032 	 *  - access: updated based on the new guest PTE
1033 	 *  - quadrant: not part of the overall MMU role (similar to level)
1034 	 */
1035 	const union kvm_mmu_page_role sync_role_ign = {
1036 		.level = 0xf,
1037 		.access = 0x7,
1038 		.quadrant = 0x3,
1039 	};
1040 
1041 	/*
1042 	 * Direct pages can never be unsync, and KVM should never attempt to
1043 	 * sync a shadow page for a different MMU context, e.g. if the role
1044 	 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
1045 	 * reserved bits checks will be wrong, etc...
1046 	 */
1047 	if (WARN_ON_ONCE(sp->role.direct ||
1048 			 (sp->role.word ^ mmu_role.word) & ~sync_role_ign.word))
1049 		return -1;
1050 
1051 	first_pte_gpa = FNAME(get_level1_sp_gpa)(sp);
1052 
1053 	for (i = 0; i < PT64_ENT_PER_PAGE; i++) {
1054 		u64 *sptep, spte;
1055 		struct kvm_memory_slot *slot;
1056 		unsigned pte_access;
1057 		pt_element_t gpte;
1058 		gpa_t pte_gpa;
1059 		gfn_t gfn;
1060 
1061 		if (!sp->spt[i])
1062 			continue;
1063 
1064 		pte_gpa = first_pte_gpa + i * sizeof(pt_element_t);
1065 
1066 		if (kvm_vcpu_read_guest_atomic(vcpu, pte_gpa, &gpte,
1067 					       sizeof(pt_element_t)))
1068 			return -1;
1069 
1070 		if (FNAME(prefetch_invalid_gpte)(vcpu, sp, &sp->spt[i], gpte)) {
1071 			flush = true;
1072 			continue;
1073 		}
1074 
1075 		gfn = gpte_to_gfn(gpte);
1076 		pte_access = sp->role.access;
1077 		pte_access &= FNAME(gpte_access)(gpte);
1078 		FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);
1079 
1080 		if (sync_mmio_spte(vcpu, &sp->spt[i], gfn, pte_access))
1081 			continue;
1082 
1083 		if (gfn != sp->gfns[i]) {
1084 			drop_spte(vcpu->kvm, &sp->spt[i]);
1085 			flush = true;
1086 			continue;
1087 		}
1088 
1089 		sptep = &sp->spt[i];
1090 		spte = *sptep;
1091 		host_writable = spte & shadow_host_writable_mask;
1092 		slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1093 		make_spte(vcpu, sp, slot, pte_access, gfn,
1094 			  spte_to_pfn(spte), spte, true, false,
1095 			  host_writable, &spte);
1096 
1097 		flush |= mmu_spte_update(sptep, spte);
1098 	}
1099 
1100 	return flush;
1101 }
1102 
1103 #undef pt_element_t
1104 #undef guest_walker
1105 #undef FNAME
1106 #undef PT_BASE_ADDR_MASK
1107 #undef PT_INDEX
1108 #undef PT_LVL_ADDR_MASK
1109 #undef PT_LVL_OFFSET_MASK
1110 #undef PT_LEVEL_BITS
1111 #undef PT_MAX_FULL_LEVELS
1112 #undef gpte_to_gfn
1113 #undef gpte_to_gfn_lvl
1114 #undef CMPXCHG
1115 #undef PT_GUEST_ACCESSED_MASK
1116 #undef PT_GUEST_DIRTY_MASK
1117 #undef PT_GUEST_DIRTY_SHIFT
1118 #undef PT_GUEST_ACCESSED_SHIFT
1119 #undef PT_HAVE_ACCESSED_DIRTY
1120