xref: /linux/arch/x86/kvm/vmx/nested.c (revision 7e170da2edec9fb0717543571cc14b0aabee2b46)
1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3 
4 #include <linux/objtool.h>
5 #include <linux/percpu.h>
6 
7 #include <asm/debugreg.h>
8 #include <asm/mmu_context.h>
9 #include <asm/msr.h>
10 
11 #include "x86.h"
12 #include "cpuid.h"
13 #include "hyperv.h"
14 #include "irq.h"
15 #include "mmu.h"
16 #include "nested.h"
17 #include "pmu.h"
18 #include "posted_intr.h"
19 #include "sgx.h"
20 #include "trace.h"
21 #include "vmx.h"
22 #include "smm.h"
23 #include "x86_ops.h"
24 
25 static bool __read_mostly enable_shadow_vmcs = 1;
26 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
27 
28 static bool __ro_after_init warn_on_missed_cc;
29 module_param(warn_on_missed_cc, bool, 0444);
30 
31 #define CC KVM_NESTED_VMENTER_CONSISTENCY_CHECK
32 
33 /*
34  * Hyper-V requires all of these, so mark them as supported even though
35  * they are just treated the same as all-context.
36  */
37 #define VMX_VPID_EXTENT_SUPPORTED_MASK		\
38 	(VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT |	\
39 	VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |	\
40 	VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT |	\
41 	VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
42 
43 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
44 
45 enum {
46 	VMX_VMREAD_BITMAP,
47 	VMX_VMWRITE_BITMAP,
48 	VMX_BITMAP_NR
49 };
50 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
51 
52 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
53 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
54 
55 struct shadow_vmcs_field {
56 	u16	encoding;
57 	u16	offset;
58 };
59 static struct shadow_vmcs_field shadow_read_only_fields[] = {
60 #define SHADOW_FIELD_RO(x, y) { x, offsetof(struct vmcs12, y) },
61 #include "vmcs_shadow_fields.h"
62 };
63 static int max_shadow_read_only_fields =
64 	ARRAY_SIZE(shadow_read_only_fields);
65 
66 static struct shadow_vmcs_field shadow_read_write_fields[] = {
67 #define SHADOW_FIELD_RW(x, y) { x, offsetof(struct vmcs12, y) },
68 #include "vmcs_shadow_fields.h"
69 };
70 static int max_shadow_read_write_fields =
71 	ARRAY_SIZE(shadow_read_write_fields);
72 
73 static void init_vmcs_shadow_fields(void)
74 {
75 	int i, j;
76 
77 	memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
78 	memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
79 
80 	for (i = j = 0; i < max_shadow_read_only_fields; i++) {
81 		struct shadow_vmcs_field entry = shadow_read_only_fields[i];
82 		u16 field = entry.encoding;
83 
84 		if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
85 		    (i + 1 == max_shadow_read_only_fields ||
86 		     shadow_read_only_fields[i + 1].encoding != field + 1))
87 			pr_err("Missing field from shadow_read_only_field %x\n",
88 			       field + 1);
89 
90 		if (get_vmcs12_field_offset(field) < 0)
91 			continue;
92 
93 		clear_bit(field, vmx_vmread_bitmap);
94 		if (field & 1)
95 #ifdef CONFIG_X86_64
96 			continue;
97 #else
98 			entry.offset += sizeof(u32);
99 #endif
100 		shadow_read_only_fields[j++] = entry;
101 	}
102 	max_shadow_read_only_fields = j;
103 
104 	for (i = j = 0; i < max_shadow_read_write_fields; i++) {
105 		struct shadow_vmcs_field entry = shadow_read_write_fields[i];
106 		u16 field = entry.encoding;
107 
108 		if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
109 		    (i + 1 == max_shadow_read_write_fields ||
110 		     shadow_read_write_fields[i + 1].encoding != field + 1))
111 			pr_err("Missing field from shadow_read_write_field %x\n",
112 			       field + 1);
113 
114 		WARN_ONCE(field >= GUEST_ES_AR_BYTES &&
115 			  field <= GUEST_TR_AR_BYTES,
116 			  "Update vmcs12_write_any() to drop reserved bits from AR_BYTES");
117 
118 		if (get_vmcs12_field_offset(field) < 0)
119 			continue;
120 
121 		/*
122 		 * KVM emulates PML and the VMX preemption timer irrespective
123 		 * of hardware support, but shadowing their related VMCS fields
124 		 * requires hardware support as the CPU will reject VMWRITEs to
125 		 * fields that don't exist.
126 		 */
127 		switch (field) {
128 		case GUEST_PML_INDEX:
129 			if (!cpu_has_vmx_pml())
130 				continue;
131 			break;
132 		case VMX_PREEMPTION_TIMER_VALUE:
133 			if (!cpu_has_vmx_preemption_timer())
134 				continue;
135 			break;
136 		default:
137 			break;
138 		}
139 
140 		clear_bit(field, vmx_vmwrite_bitmap);
141 		clear_bit(field, vmx_vmread_bitmap);
142 		if (field & 1)
143 #ifdef CONFIG_X86_64
144 			continue;
145 #else
146 			entry.offset += sizeof(u32);
147 #endif
148 		shadow_read_write_fields[j++] = entry;
149 	}
150 	max_shadow_read_write_fields = j;
151 }
152 
153 /*
154  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
155  * set the success or error code of an emulated VMX instruction (as specified
156  * by Vol 2B, VMX Instruction Reference, "Conventions"), and skip the emulated
157  * instruction.
158  */
159 static int nested_vmx_succeed(struct kvm_vcpu *vcpu)
160 {
161 	vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
162 			& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
163 			    X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
164 	return kvm_skip_emulated_instruction(vcpu);
165 }
166 
167 static int nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
168 {
169 	vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
170 			& ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
171 			    X86_EFLAGS_SF | X86_EFLAGS_OF))
172 			| X86_EFLAGS_CF);
173 	return kvm_skip_emulated_instruction(vcpu);
174 }
175 
176 static int nested_vmx_failValid(struct kvm_vcpu *vcpu,
177 				u32 vm_instruction_error)
178 {
179 	vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
180 			& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
181 			    X86_EFLAGS_SF | X86_EFLAGS_OF))
182 			| X86_EFLAGS_ZF);
183 	get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
184 	/*
185 	 * We don't need to force sync to shadow VMCS because
186 	 * VM_INSTRUCTION_ERROR is not shadowed. Enlightened VMCS 'shadows' all
187 	 * fields and thus must be synced.
188 	 */
189 	if (nested_vmx_is_evmptr12_set(to_vmx(vcpu)))
190 		to_vmx(vcpu)->nested.need_vmcs12_to_shadow_sync = true;
191 
192 	return kvm_skip_emulated_instruction(vcpu);
193 }
194 
195 static int nested_vmx_fail(struct kvm_vcpu *vcpu, u32 vm_instruction_error)
196 {
197 	struct vcpu_vmx *vmx = to_vmx(vcpu);
198 
199 	/*
200 	 * failValid writes the error number to the current VMCS, which
201 	 * can't be done if there isn't a current VMCS.
202 	 */
203 	if (vmx->nested.current_vmptr == INVALID_GPA &&
204 	    !nested_vmx_is_evmptr12_valid(vmx))
205 		return nested_vmx_failInvalid(vcpu);
206 
207 	return nested_vmx_failValid(vcpu, vm_instruction_error);
208 }
209 
210 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
211 {
212 	/* TODO: not to reset guest simply here. */
213 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
214 	pr_debug_ratelimited("nested vmx abort, indicator %d\n", indicator);
215 }
216 
217 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
218 {
219 	return fixed_bits_valid(control, low, high);
220 }
221 
222 static inline u64 vmx_control_msr(u32 low, u32 high)
223 {
224 	return low | ((u64)high << 32);
225 }
226 
227 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
228 {
229 	secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_SHADOW_VMCS);
230 	vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA);
231 	vmx->nested.need_vmcs12_to_shadow_sync = false;
232 }
233 
234 static inline void nested_release_evmcs(struct kvm_vcpu *vcpu)
235 {
236 #ifdef CONFIG_KVM_HYPERV
237 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
238 	struct vcpu_vmx *vmx = to_vmx(vcpu);
239 
240 	kvm_vcpu_unmap(vcpu, &vmx->nested.hv_evmcs_map);
241 	vmx->nested.hv_evmcs = NULL;
242 	vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
243 
244 	if (hv_vcpu) {
245 		hv_vcpu->nested.pa_page_gpa = INVALID_GPA;
246 		hv_vcpu->nested.vm_id = 0;
247 		hv_vcpu->nested.vp_id = 0;
248 	}
249 #endif
250 }
251 
252 static bool nested_evmcs_handle_vmclear(struct kvm_vcpu *vcpu, gpa_t vmptr)
253 {
254 #ifdef CONFIG_KVM_HYPERV
255 	struct vcpu_vmx *vmx = to_vmx(vcpu);
256 	/*
257 	 * When Enlightened VMEntry is enabled on the calling CPU we treat
258 	 * memory area pointer by vmptr as Enlightened VMCS (as there's no good
259 	 * way to distinguish it from VMCS12) and we must not corrupt it by
260 	 * writing to the non-existent 'launch_state' field. The area doesn't
261 	 * have to be the currently active EVMCS on the calling CPU and there's
262 	 * nothing KVM has to do to transition it from 'active' to 'non-active'
263 	 * state. It is possible that the area will stay mapped as
264 	 * vmx->nested.hv_evmcs but this shouldn't be a problem.
265 	 */
266 	if (!guest_cpu_cap_has_evmcs(vcpu) ||
267 	    !evmptr_is_valid(nested_get_evmptr(vcpu)))
268 		return false;
269 
270 	if (nested_vmx_evmcs(vmx) && vmptr == vmx->nested.hv_evmcs_vmptr)
271 		nested_release_evmcs(vcpu);
272 
273 	return true;
274 #else
275 	return false;
276 #endif
277 }
278 
279 static void vmx_sync_vmcs_host_state(struct vcpu_vmx *vmx,
280 				     struct loaded_vmcs *prev)
281 {
282 	struct vmcs_host_state *dest, *src;
283 
284 	if (unlikely(!vmx->vt.guest_state_loaded))
285 		return;
286 
287 	src = &prev->host_state;
288 	dest = &vmx->loaded_vmcs->host_state;
289 
290 	vmx_set_host_fs_gs(dest, src->fs_sel, src->gs_sel, src->fs_base, src->gs_base);
291 	dest->ldt_sel = src->ldt_sel;
292 #ifdef CONFIG_X86_64
293 	dest->ds_sel = src->ds_sel;
294 	dest->es_sel = src->es_sel;
295 #endif
296 }
297 
298 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
299 {
300 	struct vcpu_vmx *vmx = to_vmx(vcpu);
301 	struct loaded_vmcs *prev;
302 	int cpu;
303 
304 	if (WARN_ON_ONCE(vmx->loaded_vmcs == vmcs))
305 		return;
306 
307 	cpu = get_cpu();
308 	prev = vmx->loaded_vmcs;
309 	vmx->loaded_vmcs = vmcs;
310 	vmx_vcpu_load_vmcs(vcpu, cpu);
311 	vmx_sync_vmcs_host_state(vmx, prev);
312 	put_cpu();
313 
314 	kvm_clear_available_registers(vcpu, VMX_REGS_LAZY_LOAD_SET);
315 
316 	/*
317 	 * All lazily updated registers will be reloaded from VMCS12 on both
318 	 * vmentry and vmexit.
319 	 */
320 	kvm_reset_dirty_registers(vcpu);
321 }
322 
323 static void nested_put_vmcs12_pages(struct kvm_vcpu *vcpu)
324 {
325 	struct vcpu_vmx *vmx = to_vmx(vcpu);
326 
327 	kvm_vcpu_unmap(vcpu, &vmx->nested.apic_access_page_map);
328 	kvm_vcpu_unmap(vcpu, &vmx->nested.virtual_apic_map);
329 	kvm_vcpu_unmap(vcpu, &vmx->nested.pi_desc_map);
330 	vmx->nested.pi_desc = NULL;
331 }
332 
333 /*
334  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
335  * just stops using VMX.
336  */
337 static void free_nested(struct kvm_vcpu *vcpu)
338 {
339 	struct vcpu_vmx *vmx = to_vmx(vcpu);
340 	struct vmcs *shadow_vmcs;
341 
342 	if (WARN_ON_ONCE(vmx->loaded_vmcs != &vmx->vmcs01))
343 		vmx_switch_vmcs(vcpu, &vmx->vmcs01);
344 
345 	if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
346 		return;
347 
348 	kvm_clear_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
349 
350 	vmx->nested.vmxon = false;
351 	vmx->nested.smm.vmxon = false;
352 	vmx->nested.vmxon_ptr = INVALID_GPA;
353 	free_vpid(vmx->nested.vpid02);
354 	vmx->nested.posted_intr_nv = -1;
355 	vmx->nested.current_vmptr = INVALID_GPA;
356 	if (enable_shadow_vmcs) {
357 		vmx_disable_shadow_vmcs(vmx);
358 
359 		/*
360 		 * Keep the pointer visible until after VMCLEAR, so migration
361 		 * can clear an active shadow VMCS on the old CPU.
362 		 */
363 		shadow_vmcs = vmx->vmcs01.shadow_vmcs;
364 		vmcs_clear(shadow_vmcs);
365 		vmx->vmcs01.shadow_vmcs = NULL;
366 		free_vmcs(shadow_vmcs);
367 	}
368 	kfree(vmx->nested.cached_vmcs12);
369 	vmx->nested.cached_vmcs12 = NULL;
370 	kfree(vmx->nested.cached_shadow_vmcs12);
371 	vmx->nested.cached_shadow_vmcs12 = NULL;
372 
373 	nested_put_vmcs12_pages(vcpu);
374 
375 	kvm_mmu_free_roots(vcpu->kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
376 
377 	nested_release_evmcs(vcpu);
378 
379 	free_loaded_vmcs(&vmx->nested.vmcs02);
380 }
381 
382 /*
383  * Ensure that the current vmcs of the logical processor is the
384  * vmcs01 of the vcpu before calling free_nested().
385  */
386 void nested_vmx_free_vcpu(struct kvm_vcpu *vcpu)
387 {
388 	vcpu_load(vcpu);
389 	vmx_leave_nested(vcpu);
390 	vcpu_put(vcpu);
391 }
392 
393 #define EPTP_PA_MASK   GENMASK_ULL(51, 12)
394 
395 static bool nested_ept_root_matches(hpa_t root_hpa, u64 root_eptp, u64 eptp)
396 {
397 	return VALID_PAGE(root_hpa) &&
398 	       ((root_eptp & EPTP_PA_MASK) == (eptp & EPTP_PA_MASK));
399 }
400 
401 static void nested_ept_invalidate_addr(struct kvm_vcpu *vcpu, gpa_t eptp,
402 				       gpa_t addr)
403 {
404 	unsigned long roots = 0;
405 	uint i;
406 	struct kvm_mmu_root_info *cached_root;
407 
408 	WARN_ON_ONCE(!mmu_is_nested(vcpu));
409 
410 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
411 		cached_root = &vcpu->arch.mmu->prev_roots[i];
412 
413 		if (nested_ept_root_matches(cached_root->hpa, cached_root->pgd,
414 					    eptp))
415 			roots |= KVM_MMU_ROOT_PREVIOUS(i);
416 	}
417 	if (roots)
418 		kvm_mmu_invalidate_addr(vcpu, &vcpu->arch.ngpa_walk, addr, roots);
419 }
420 
421 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
422 					 struct x86_exception *fault,
423 					 bool from_hardware)
424 {
425 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
426 	struct vcpu_vmx *vmx = to_vmx(vcpu);
427 	unsigned long exit_qualification;
428 	u32 vm_exit_reason;
429 
430 	if (vmx->nested.pml_full) {
431 		vm_exit_reason = EXIT_REASON_PML_FULL;
432 		vmx->nested.pml_full = false;
433 
434 		/*
435 		 * It should be impossible to trigger a nested PML Full VM-Exit
436 		 * for anything other than an EPT Violation from L2.  KVM *can*
437 		 * trigger nEPT page fault injection in response to an EPT
438 		 * Misconfig, e.g. if the MMIO SPTE was stale and L1's EPT
439 		 * tables also changed, but KVM should not treat EPT Misconfig
440 		 * VM-Exits as writes.
441 		 */
442 		WARN_ON_ONCE(vmx->vt.exit_reason.basic != EXIT_REASON_EPT_VIOLATION);
443 
444 		/*
445 		 * PML Full and EPT Violation VM-Exits both use bit 12 to report
446 		 * "NMI unblocking due to IRET", i.e. the bit can be propagated
447 		 * as-is from the original EXIT_QUALIFICATION.
448 		 */
449 		exit_qualification = vmx_get_exit_qual(vcpu) & INTR_INFO_UNBLOCK_NMI;
450 	} else {
451 		if (fault->error_code & PFERR_RSVD_MASK) {
452 			vm_exit_reason = EXIT_REASON_EPT_MISCONFIG;
453 			exit_qualification = 0;
454 		} else {
455 			u64 mask = EPT_VIOLATION_GVA_IS_VALID |
456 				   EPT_VIOLATION_GVA_TRANSLATED;
457 
458 			if (vmx->nested.msrs.ept_caps & VMX_EPT_ADVANCED_VMEXIT_INFO_BIT)
459 				mask |= EPT_VIOLATION_GVA_USER |
460 					EPT_VIOLATION_GVA_WRITABLE |
461 					EPT_VIOLATION_GVA_NX;
462 
463 			exit_qualification = fault->exit_qualification & ~mask;
464 
465 			/*
466 			 * Use the EXIT_QUALIFICATION from the VMCS if and only
467 			 * if the hardware VM-Exit from L2 was an EPT Violation.
468 			 * If the fault is synthesized, then EXIT_QUALIFICATION
469 			 * is stale and/or holds entirely different data.  And
470 			 * conversely, KVM _must_ rely on EXIT_QUALIFICATION if
471 			 * the fault came from hardware, because KVM only sees
472 			 * and walks the faulting GPA.
473 			 */
474 			if (from_hardware)
475 				exit_qualification |= vmx_get_exit_qual(vcpu) & mask;
476 			else
477 				exit_qualification |= fault->exit_qualification & mask;
478 
479 			vm_exit_reason = EXIT_REASON_EPT_VIOLATION;
480 		}
481 
482 		/*
483 		 * Although the caller (kvm_inject_emulated_page_fault) would
484 		 * have already synced the faulting address in the shadow EPT
485 		 * tables for the current EPTP12, we also need to sync it for
486 		 * any other cached EPTP02s based on the same EP4TA, since the
487 		 * TLB associates mappings to the EP4TA rather than the full EPTP.
488 		 */
489 		nested_ept_invalidate_addr(vcpu, vmcs12->ept_pointer,
490 					   fault->address);
491 	}
492 
493 	nested_vmx_vmexit(vcpu, vm_exit_reason, 0, exit_qualification);
494 	vmcs12->guest_physical_address = fault->address;
495 }
496 
497 static inline bool nested_ept_mbec_enabled(struct kvm_vcpu *vcpu)
498 {
499 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
500 
501 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_MODE_BASED_EPT_EXEC);
502 }
503 
504 static void nested_ept_new_eptp(struct kvm_vcpu *vcpu)
505 {
506 	struct vcpu_vmx *vmx = to_vmx(vcpu);
507 	bool execonly = vmx->nested.msrs.ept_caps & VMX_EPT_EXECUTE_ONLY_BIT;
508 	int ept_lpage_level = ept_caps_to_lpage_level(vmx->nested.msrs.ept_caps);
509 
510 	kvm_init_shadow_ept_mmu(vcpu, execonly, ept_lpage_level,
511 				nested_ept_ad_enabled(vcpu),
512 				nested_ept_mbec_enabled(vcpu),
513 				nested_ept_get_eptp(vcpu));
514 }
515 
516 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
517 {
518 	WARN_ON(mmu_is_nested(vcpu));
519 
520 	vcpu->arch.mmu = &vcpu->arch.guest_mmu;
521 	nested_ept_new_eptp(vcpu);
522 	vcpu->arch.ngpa_walk.get_guest_pgd     = nested_ept_get_eptp;
523 	vcpu->arch.ngpa_walk.get_pdptr       = kvm_pdptr_read;
524 
525 	vcpu->arch.ngpa_walk.inject_page_fault = nested_ept_inject_page_fault;
526 }
527 
528 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
529 {
530 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
531 }
532 
533 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
534 					    u16 error_code)
535 {
536 	bool inequality, bit;
537 
538 	bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
539 	inequality =
540 		(error_code & vmcs12->page_fault_error_code_mask) !=
541 		 vmcs12->page_fault_error_code_match;
542 	return inequality ^ bit;
543 }
544 
545 static bool nested_vmx_is_exception_vmexit(struct kvm_vcpu *vcpu, u8 vector,
546 					   u32 error_code)
547 {
548 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
549 
550 	/*
551 	 * Drop bits 31:16 of the error code when performing the #PF mask+match
552 	 * check.  All VMCS fields involved are 32 bits, but Intel CPUs never
553 	 * set bits 31:16 and VMX disallows setting bits 31:16 in the injected
554 	 * error code.  Including the to-be-dropped bits in the check might
555 	 * result in an "impossible" or missed exit from L1's perspective.
556 	 */
557 	if (vector == PF_VECTOR)
558 		return nested_vmx_is_page_fault_vmexit(vmcs12, (u16)error_code);
559 
560 	return (vmcs12->exception_bitmap & (1u << vector));
561 }
562 
563 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
564 					       struct vmcs12 *vmcs12)
565 {
566 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
567 		return 0;
568 
569 	if (CC(!page_address_valid(vcpu, vmcs12->io_bitmap_a)) ||
570 	    CC(!page_address_valid(vcpu, vmcs12->io_bitmap_b)))
571 		return -EINVAL;
572 
573 	return 0;
574 }
575 
576 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
577 						struct vmcs12 *vmcs12)
578 {
579 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
580 		return 0;
581 
582 	if (CC(!page_address_valid(vcpu, vmcs12->msr_bitmap)))
583 		return -EINVAL;
584 
585 	return 0;
586 }
587 
588 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
589 						struct vmcs12 *vmcs12)
590 {
591 	gpa_t vtpr_gpa = vmcs12->virtual_apic_page_addr + APIC_TASKPRI;
592 	u32 vtpr;
593 
594 	if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
595 		return 0;
596 
597 	if (CC(!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr)))
598 		return -EINVAL;
599 
600 	if (CC(!nested_cpu_has_vid(vmcs12) && vmcs12->tpr_threshold >> 4))
601 		return -EINVAL;
602 
603 	/*
604 	 * Do the illegal vTPR vs. TPR Threshold consistency check if and only
605 	 * if KVM is configured to WARN on missed consistency checks, otherwise
606 	 * it's a waste of time.  KVM needs to rely on hardware to fully detect
607 	 * an illegal combination due to the vTPR being writable by L1 at all
608 	 * times (it's an in-memory value, not a VMCS field).  I.e. even if the
609 	 * check passes now, it might fail at the actual VM-Enter.
610 	 *
611 	 * If reading guest memory fails, skip the check as KVM's de facto ABI
612 	 * for VMX instruction accesses to non-existent memory is to provide
613 	 * PCI Bus Error semantics (reads return 0xFFs), in which case the vTPR
614 	 * is guaranteed to greater than or equal to the threshold.
615 	 *
616 	 * Note!  Deliberately use the VM-scoped API when reading guest memory,
617 	 * to ensure the read doesn't hit SMRAM when restoring L2 state on RSM,
618 	 * and only perform the check when in KVM_RUN, to avoid a false failure
619 	 * if userspace hasn't yet configured memslots during state restore.
620 	 */
621 	if (warn_on_missed_cc && vcpu->wants_to_run &&
622 	    nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW) &&
623 	    !nested_cpu_has_vid(vmcs12) &&
624 	    !nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
625 	    !kvm_read_guest(vcpu->kvm, vtpr_gpa, &vtpr, sizeof(vtpr)) &&
626 	    CC((vmcs12->tpr_threshold & GENMASK(3, 0)) > ((vtpr >> 4) & GENMASK(3, 0))))
627 		return -EINVAL;
628 
629 	return 0;
630 }
631 
632 /*
633  * For x2APIC MSRs, ignore the vmcs01 bitmap.  L1 can enable x2APIC without L1
634  * itself utilizing x2APIC.  All MSRs were previously set to be intercepted,
635  * only the "disable intercept" case needs to be handled.
636  */
637 static void nested_vmx_disable_intercept_for_x2apic_msr(unsigned long *msr_bitmap_l1,
638 							unsigned long *msr_bitmap_l0,
639 							u32 msr, int type)
640 {
641 	if (type & MSR_TYPE_R && !vmx_test_msr_bitmap_read(msr_bitmap_l1, msr))
642 		vmx_clear_msr_bitmap_read(msr_bitmap_l0, msr);
643 
644 	if (type & MSR_TYPE_W && !vmx_test_msr_bitmap_write(msr_bitmap_l1, msr))
645 		vmx_clear_msr_bitmap_write(msr_bitmap_l0, msr);
646 }
647 
648 static inline void enable_x2apic_msr_intercepts(unsigned long *msr_bitmap)
649 {
650 	int msr;
651 
652 	for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
653 		unsigned word = msr / BITS_PER_LONG;
654 
655 		msr_bitmap[word] = ~0;
656 		msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
657 	}
658 }
659 
660 #define BUILD_NVMX_MSR_INTERCEPT_HELPER(rw)					\
661 static inline									\
662 void nested_vmx_set_msr_##rw##_intercept(struct vcpu_vmx *vmx,			\
663 					 unsigned long *msr_bitmap_l1,		\
664 					 unsigned long *msr_bitmap_l0, u32 msr)	\
665 {										\
666 	if (vmx_test_msr_bitmap_##rw(vmx->vmcs01.msr_bitmap, msr) ||		\
667 	    vmx_test_msr_bitmap_##rw(msr_bitmap_l1, msr))			\
668 		vmx_set_msr_bitmap_##rw(msr_bitmap_l0, msr);			\
669 	else									\
670 		vmx_clear_msr_bitmap_##rw(msr_bitmap_l0, msr);			\
671 }
672 BUILD_NVMX_MSR_INTERCEPT_HELPER(read)
673 BUILD_NVMX_MSR_INTERCEPT_HELPER(write)
674 
675 static inline void nested_vmx_set_intercept_for_msr(struct vcpu_vmx *vmx,
676 						    unsigned long *msr_bitmap_l1,
677 						    unsigned long *msr_bitmap_l0,
678 						    u32 msr, int types)
679 {
680 	if (types & MSR_TYPE_R)
681 		nested_vmx_set_msr_read_intercept(vmx, msr_bitmap_l1,
682 						  msr_bitmap_l0, msr);
683 	if (types & MSR_TYPE_W)
684 		nested_vmx_set_msr_write_intercept(vmx, msr_bitmap_l1,
685 						   msr_bitmap_l0, msr);
686 }
687 
688 #define nested_vmx_merge_msr_bitmaps(msr, type)	\
689 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1,	\
690 					 msr_bitmap_l0, msr, type)
691 
692 #define nested_vmx_merge_msr_bitmaps_read(msr) \
693 	nested_vmx_merge_msr_bitmaps(msr, MSR_TYPE_R)
694 
695 #define nested_vmx_merge_msr_bitmaps_write(msr) \
696 	nested_vmx_merge_msr_bitmaps(msr, MSR_TYPE_W)
697 
698 #define nested_vmx_merge_msr_bitmaps_rw(msr) \
699 	nested_vmx_merge_msr_bitmaps(msr, MSR_TYPE_RW)
700 
701 static void nested_vmx_merge_pmu_msr_bitmaps(struct kvm_vcpu *vcpu,
702 					     unsigned long *msr_bitmap_l1,
703 					     unsigned long *msr_bitmap_l0)
704 {
705 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
706 	struct vcpu_vmx *vmx = to_vmx(vcpu);
707 	int i;
708 
709 	/*
710 	 * Skip the merges if the vCPU doesn't have a mediated PMU MSR, i.e. if
711 	 * none of the MSRs can possibly be passed through to L1.
712 	 */
713 	if (!kvm_vcpu_has_mediated_pmu(vcpu))
714 		return;
715 
716 	for (i = 0; i < pmu->nr_arch_gp_counters; i++) {
717 		nested_vmx_merge_msr_bitmaps_rw(MSR_IA32_PERFCTR0 + i);
718 		nested_vmx_merge_msr_bitmaps_rw(MSR_IA32_PMC0 + i);
719 	}
720 
721 	for (i = 0; i < pmu->nr_arch_fixed_counters; i++)
722 		nested_vmx_merge_msr_bitmaps_rw(MSR_CORE_PERF_FIXED_CTR0 + i);
723 
724 	nested_vmx_merge_msr_bitmaps_rw(MSR_CORE_PERF_GLOBAL_CTRL);
725 	nested_vmx_merge_msr_bitmaps_read(MSR_CORE_PERF_GLOBAL_STATUS);
726 	nested_vmx_merge_msr_bitmaps_write(MSR_CORE_PERF_GLOBAL_OVF_CTRL);
727 }
728 
729 /*
730  * Merge L0's and L1's MSR bitmap, return false to indicate that
731  * we do not use the hardware.
732  */
733 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
734 						 struct vmcs12 *vmcs12)
735 {
736 	struct vcpu_vmx *vmx = to_vmx(vcpu);
737 	int msr;
738 	unsigned long *msr_bitmap_l1;
739 	unsigned long *msr_bitmap_l0 = vmx->nested.vmcs02.msr_bitmap;
740 
741 	/* Nothing to do if the MSR bitmap is not in use.  */
742 	if (!cpu_has_vmx_msr_bitmap() ||
743 	    !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
744 		return false;
745 
746 	/*
747 	 * MSR bitmap update can be skipped when:
748 	 * - MSR bitmap for L1 hasn't changed.
749 	 * - Nested hypervisor (L1) is attempting to launch the same L2 as
750 	 *   before.
751 	 * - Nested hypervisor (L1) has enabled 'Enlightened MSR Bitmap' feature
752 	 *   and tells KVM (L0) there were no changes in MSR bitmap for L2.
753 	 */
754 	if (!vmx->nested.force_msr_bitmap_recalc) {
755 		struct hv_enlightened_vmcs *evmcs = nested_vmx_evmcs(vmx);
756 
757 		if (evmcs && evmcs->hv_enlightenments_control.msr_bitmap &&
758 		    evmcs->hv_clean_fields & HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP)
759 			return true;
760 	}
761 
762 	CLASS(kvm_vcpu_map_local_readonly, m)(vcpu, gpa_to_gfn(vmcs12->msr_bitmap));
763 	if (m.ret)
764 		return false;
765 
766 	msr_bitmap_l1 = (unsigned long *)m.map.hva;
767 
768 	/*
769 	 * To keep the control flow simple, pay eight 8-byte writes (sixteen
770 	 * 4-byte writes on 32-bit systems) up front to enable intercepts for
771 	 * the x2APIC MSR range and selectively toggle those relevant to L2.
772 	 */
773 	enable_x2apic_msr_intercepts(msr_bitmap_l0);
774 
775 	if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
776 		if (nested_cpu_has_apic_reg_virt(vmcs12)) {
777 			/*
778 			 * L0 need not intercept reads for MSRs between 0x800
779 			 * and 0x8ff, it just lets the processor take the value
780 			 * from the virtual-APIC page; take those 256 bits
781 			 * directly from the L1 bitmap.
782 			 */
783 			for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
784 				unsigned word = msr / BITS_PER_LONG;
785 
786 				msr_bitmap_l0[word] = msr_bitmap_l1[word];
787 			}
788 		}
789 
790 		nested_vmx_disable_intercept_for_x2apic_msr(
791 			msr_bitmap_l1, msr_bitmap_l0,
792 			X2APIC_MSR(APIC_TASKPRI),
793 			MSR_TYPE_R | MSR_TYPE_W);
794 
795 		if (nested_cpu_has_vid(vmcs12)) {
796 			nested_vmx_disable_intercept_for_x2apic_msr(
797 				msr_bitmap_l1, msr_bitmap_l0,
798 				X2APIC_MSR(APIC_EOI),
799 				MSR_TYPE_W);
800 			nested_vmx_disable_intercept_for_x2apic_msr(
801 				msr_bitmap_l1, msr_bitmap_l0,
802 				X2APIC_MSR(APIC_SELF_IPI),
803 				MSR_TYPE_W);
804 		}
805 	}
806 
807 	/*
808 	 * Always check vmcs01's bitmap to honor userspace MSR filters and any
809 	 * other runtime changes to vmcs01's bitmap, e.g. dynamic pass-through.
810 	 */
811 #ifdef CONFIG_X86_64
812 	nested_vmx_merge_msr_bitmaps_rw(MSR_FS_BASE);
813 	nested_vmx_merge_msr_bitmaps_rw(MSR_GS_BASE);
814 	nested_vmx_merge_msr_bitmaps_rw(MSR_KERNEL_GS_BASE);
815 #endif
816 	nested_vmx_merge_msr_bitmaps_rw(MSR_IA32_SPEC_CTRL);
817 	nested_vmx_merge_msr_bitmaps_write(MSR_IA32_PRED_CMD);
818 	nested_vmx_merge_msr_bitmaps_write(MSR_IA32_FLUSH_CMD);
819 
820 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
821 					 MSR_IA32_APERF, MSR_TYPE_R);
822 
823 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
824 					 MSR_IA32_MPERF, MSR_TYPE_R);
825 
826 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
827 					 MSR_IA32_U_CET, MSR_TYPE_RW);
828 
829 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
830 					 MSR_IA32_S_CET, MSR_TYPE_RW);
831 
832 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
833 					 MSR_IA32_PL0_SSP, MSR_TYPE_RW);
834 
835 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
836 					 MSR_IA32_PL1_SSP, MSR_TYPE_RW);
837 
838 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
839 					 MSR_IA32_PL2_SSP, MSR_TYPE_RW);
840 
841 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
842 					 MSR_IA32_PL3_SSP, MSR_TYPE_RW);
843 
844 	nested_vmx_merge_pmu_msr_bitmaps(vcpu, msr_bitmap_l1, msr_bitmap_l0);
845 
846 	vmx->nested.force_msr_bitmap_recalc = false;
847 
848 	return true;
849 }
850 
851 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
852 				       struct vmcs12 *vmcs12)
853 {
854 	struct vcpu_vmx *vmx = to_vmx(vcpu);
855 	struct gfn_to_hva_cache *ghc = &vmx->nested.shadow_vmcs12_cache;
856 
857 	if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
858 	    vmcs12->vmcs_link_pointer == INVALID_GPA)
859 		return;
860 
861 	if (ghc->gpa != vmcs12->vmcs_link_pointer &&
862 	    kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc,
863 				      vmcs12->vmcs_link_pointer, VMCS12_SIZE))
864 		return;
865 
866 	kvm_read_guest_cached(vcpu->kvm, ghc, get_shadow_vmcs12(vcpu),
867 			      VMCS12_SIZE);
868 }
869 
870 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
871 					      struct vmcs12 *vmcs12)
872 {
873 	struct vcpu_vmx *vmx = to_vmx(vcpu);
874 	struct gfn_to_hva_cache *ghc = &vmx->nested.shadow_vmcs12_cache;
875 
876 	if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
877 	    vmcs12->vmcs_link_pointer == INVALID_GPA)
878 		return;
879 
880 	if (ghc->gpa != vmcs12->vmcs_link_pointer &&
881 	    kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc,
882 				      vmcs12->vmcs_link_pointer, VMCS12_SIZE))
883 		return;
884 
885 	kvm_write_guest_cached(vcpu->kvm, ghc, get_shadow_vmcs12(vcpu),
886 			       VMCS12_SIZE);
887 }
888 
889 /*
890  * In nested virtualization, check if L1 has set
891  * VM_EXIT_ACK_INTR_ON_EXIT
892  */
893 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
894 {
895 	return get_vmcs12(vcpu)->vm_exit_controls &
896 		VM_EXIT_ACK_INTR_ON_EXIT;
897 }
898 
899 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
900 					  struct vmcs12 *vmcs12)
901 {
902 	if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
903 	    CC(!page_address_valid(vcpu, vmcs12->apic_access_addr)))
904 		return -EINVAL;
905 	else
906 		return 0;
907 }
908 
909 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
910 					   struct vmcs12 *vmcs12)
911 {
912 	if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
913 	    !nested_cpu_has_apic_reg_virt(vmcs12) &&
914 	    !nested_cpu_has_vid(vmcs12) &&
915 	    !nested_cpu_has_posted_intr(vmcs12))
916 		return 0;
917 
918 	/*
919 	 * If virtualize x2apic mode is enabled,
920 	 * virtualize apic access must be disabled.
921 	 */
922 	if (CC(nested_cpu_has_virt_x2apic_mode(vmcs12) &&
923 	       nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)))
924 		return -EINVAL;
925 
926 	/*
927 	 * If virtual interrupt delivery is enabled,
928 	 * we must exit on external interrupts.
929 	 */
930 	if (CC(nested_cpu_has_vid(vmcs12) && !nested_exit_on_intr(vcpu)))
931 		return -EINVAL;
932 
933 	/*
934 	 * bits 15:8 should be zero in posted_intr_nv,
935 	 * the descriptor address has been already checked
936 	 * in nested_get_vmcs12_pages.
937 	 *
938 	 * bits 5:0 of posted_intr_desc_addr should be zero.
939 	 */
940 	if (nested_cpu_has_posted_intr(vmcs12) &&
941 	   (CC(!nested_cpu_has_vid(vmcs12)) ||
942 	    CC(!nested_exit_intr_ack_set(vcpu)) ||
943 	    CC((vmcs12->posted_intr_nv & 0xff00)) ||
944 	    CC(!kvm_vcpu_is_legal_aligned_gpa(vcpu, vmcs12->posted_intr_desc_addr, 64))))
945 		return -EINVAL;
946 
947 	/* tpr shadow is needed by all apicv features. */
948 	if (CC(!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)))
949 		return -EINVAL;
950 
951 	return 0;
952 }
953 
954 static u32 nested_vmx_max_atomic_switch_msrs(struct kvm_vcpu *vcpu)
955 {
956 	struct vcpu_vmx *vmx = to_vmx(vcpu);
957 	u64 vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
958 				       vmx->nested.msrs.misc_high);
959 
960 	return (vmx_misc_max_msr(vmx_misc) + 1) * VMX_MISC_MSR_LIST_MULTIPLIER;
961 }
962 
963 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
964 				       u32 count, u64 addr)
965 {
966 	if (count == 0)
967 		return 0;
968 
969 	/*
970 	 * Exceeding the limit results in architecturally _undefined_ behavior,
971 	 * i.e. KVM is allowed to do literally anything in response to a bad
972 	 * limit.  Immediately generate a consistency check so that code that
973 	 * consumes the count doesn't need to worry about extreme edge cases.
974 	 */
975 	if (count > nested_vmx_max_atomic_switch_msrs(vcpu))
976 		return -EINVAL;
977 
978 	if (!kvm_vcpu_is_legal_aligned_gpa(vcpu, addr, 16) ||
979 	    !kvm_vcpu_is_legal_gpa(vcpu, (addr + count * sizeof(struct vmx_msr_entry) - 1)))
980 		return -EINVAL;
981 
982 	return 0;
983 }
984 
985 static int nested_vmx_check_exit_msr_switch_controls(struct kvm_vcpu *vcpu,
986 						     struct vmcs12 *vmcs12)
987 {
988 	if (CC(nested_vmx_check_msr_switch(vcpu,
989 					   vmcs12->vm_exit_msr_load_count,
990 					   vmcs12->vm_exit_msr_load_addr)) ||
991 	    CC(nested_vmx_check_msr_switch(vcpu,
992 					   vmcs12->vm_exit_msr_store_count,
993 					   vmcs12->vm_exit_msr_store_addr)))
994 		return -EINVAL;
995 
996 	return 0;
997 }
998 
999 static int nested_vmx_check_entry_msr_switch_controls(struct kvm_vcpu *vcpu,
1000                                                       struct vmcs12 *vmcs12)
1001 {
1002 	if (CC(nested_vmx_check_msr_switch(vcpu,
1003 					   vmcs12->vm_entry_msr_load_count,
1004 					   vmcs12->vm_entry_msr_load_addr)))
1005                 return -EINVAL;
1006 
1007 	return 0;
1008 }
1009 
1010 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
1011 					 struct vmcs12 *vmcs12)
1012 {
1013 	if (!nested_cpu_has_pml(vmcs12))
1014 		return 0;
1015 
1016 	if (CC(!nested_cpu_has_ept(vmcs12)) ||
1017 	    CC(!page_address_valid(vcpu, vmcs12->pml_address)))
1018 		return -EINVAL;
1019 
1020 	return 0;
1021 }
1022 
1023 static int nested_vmx_check_unrestricted_guest_controls(struct kvm_vcpu *vcpu,
1024 							struct vmcs12 *vmcs12)
1025 {
1026 	if (CC(nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST) &&
1027 	       !nested_cpu_has_ept(vmcs12)))
1028 		return -EINVAL;
1029 	return 0;
1030 }
1031 
1032 static int nested_vmx_check_mode_based_ept_exec_controls(struct kvm_vcpu *vcpu,
1033 							 struct vmcs12 *vmcs12)
1034 {
1035 	if (CC(nested_cpu_has2(vmcs12, SECONDARY_EXEC_MODE_BASED_EPT_EXEC) &&
1036 	       !nested_cpu_has_ept(vmcs12)))
1037 		return -EINVAL;
1038 	return 0;
1039 }
1040 
1041 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
1042 						 struct vmcs12 *vmcs12)
1043 {
1044 	if (!nested_cpu_has_shadow_vmcs(vmcs12))
1045 		return 0;
1046 
1047 	if (CC(!page_address_valid(vcpu, vmcs12->vmread_bitmap)) ||
1048 	    CC(!page_address_valid(vcpu, vmcs12->vmwrite_bitmap)))
1049 		return -EINVAL;
1050 
1051 	return 0;
1052 }
1053 
1054 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
1055 				       struct vmx_msr_entry *e)
1056 {
1057 	/* x2APIC MSR accesses are not allowed */
1058 	if (CC(vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8))
1059 		return -EINVAL;
1060 	if (CC(e->index == MSR_IA32_UCODE_WRITE) || /* SDM Table 35-2 */
1061 	    CC(e->index == MSR_IA32_UCODE_REV))
1062 		return -EINVAL;
1063 	if (CC(e->reserved != 0))
1064 		return -EINVAL;
1065 	return 0;
1066 }
1067 
1068 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
1069 				     struct vmx_msr_entry *e)
1070 {
1071 	if (CC(e->index == MSR_FS_BASE) ||
1072 	    CC(e->index == MSR_GS_BASE) ||
1073 	    CC(e->index == MSR_IA32_SMM_MONITOR_CTL) || /* SMM is not supported */
1074 	    nested_vmx_msr_check_common(vcpu, e))
1075 		return -EINVAL;
1076 	return 0;
1077 }
1078 
1079 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
1080 				      struct vmx_msr_entry *e)
1081 {
1082 	if (CC(e->index == MSR_IA32_SMBASE) || /* SMM is not supported */
1083 	    nested_vmx_msr_check_common(vcpu, e))
1084 		return -EINVAL;
1085 	return 0;
1086 }
1087 
1088 /*
1089  * Load guest's/host's msr at nested entry/exit.
1090  * return 0 for success, entry index for failure.
1091  *
1092  * One of the failure modes for MSR load/store is when a list exceeds the
1093  * virtual hardware's capacity. To maintain compatibility with hardware inasmuch
1094  * as possible, process all valid entries before failing rather than precheck
1095  * for a capacity violation.
1096  */
1097 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
1098 {
1099 	u32 i;
1100 	struct vmx_msr_entry e;
1101 	u32 max_msr_list_size = nested_vmx_max_atomic_switch_msrs(vcpu);
1102 
1103 	for (i = 0; i < count; i++) {
1104 		if (WARN_ON_ONCE(i >= max_msr_list_size))
1105 			goto fail;
1106 
1107 		if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
1108 					&e, sizeof(e))) {
1109 			pr_debug_ratelimited(
1110 				"%s cannot read MSR entry (%u, 0x%08llx)\n",
1111 				__func__, i, gpa + i * sizeof(e));
1112 			goto fail;
1113 		}
1114 		if (nested_vmx_load_msr_check(vcpu, &e)) {
1115 			pr_debug_ratelimited(
1116 				"%s check failed (%u, 0x%x, 0x%x)\n",
1117 				__func__, i, e.index, e.reserved);
1118 			goto fail;
1119 		}
1120 		if (kvm_emulate_msr_write(vcpu, e.index, e.value)) {
1121 			pr_debug_ratelimited(
1122 				"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
1123 				__func__, i, e.index, e.value);
1124 			goto fail;
1125 		}
1126 	}
1127 	return 0;
1128 fail:
1129 	/* Note, max_msr_list_size is at most 4096, i.e. this can't wrap. */
1130 	return i + 1;
1131 }
1132 
1133 static bool nested_vmx_get_vmexit_msr_value(struct kvm_vcpu *vcpu,
1134 					    u32 msr_index,
1135 					    u64 *data)
1136 {
1137 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1138 
1139 	/*
1140 	 * If the L0 hypervisor stored a more accurate value for the TSC that
1141 	 * does not include the time taken for emulation of the L2->L1
1142 	 * VM-exit in L0, use the more accurate value.
1143 	 */
1144 	if (msr_index == MSR_IA32_TSC && vmx->nested.tsc_autostore_slot >= 0) {
1145 		int slot = vmx->nested.tsc_autostore_slot;
1146 		u64 host_tsc = vmx->msr_autostore.val[slot].value;
1147 
1148 		*data = kvm_read_l1_tsc(vcpu, host_tsc);
1149 		return true;
1150 	}
1151 
1152 	if (kvm_emulate_msr_read(vcpu, msr_index, data)) {
1153 		pr_debug_ratelimited("%s cannot read MSR (0x%x)\n", __func__,
1154 			msr_index);
1155 		return false;
1156 	}
1157 	return true;
1158 }
1159 
1160 static bool read_and_check_msr_entry(struct kvm_vcpu *vcpu, u64 gpa, int i,
1161 				     struct vmx_msr_entry *e)
1162 {
1163 	if (kvm_vcpu_read_guest(vcpu,
1164 				gpa + i * sizeof(*e),
1165 				e, 2 * sizeof(u32))) {
1166 		pr_debug_ratelimited(
1167 			"%s cannot read MSR entry (%u, 0x%08llx)\n",
1168 			__func__, i, gpa + i * sizeof(*e));
1169 		return false;
1170 	}
1171 	if (nested_vmx_store_msr_check(vcpu, e)) {
1172 		pr_debug_ratelimited(
1173 			"%s check failed (%u, 0x%x, 0x%x)\n",
1174 			__func__, i, e->index, e->reserved);
1175 		return false;
1176 	}
1177 	return true;
1178 }
1179 
1180 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
1181 {
1182 	u64 data;
1183 	u32 i;
1184 	struct vmx_msr_entry e;
1185 	u32 max_msr_list_size = nested_vmx_max_atomic_switch_msrs(vcpu);
1186 
1187 	for (i = 0; i < count; i++) {
1188 		if (WARN_ON_ONCE(i >= max_msr_list_size))
1189 			return -EINVAL;
1190 
1191 		if (!read_and_check_msr_entry(vcpu, gpa, i, &e))
1192 			return -EINVAL;
1193 
1194 		if (!nested_vmx_get_vmexit_msr_value(vcpu, e.index, &data))
1195 			return -EINVAL;
1196 
1197 		if (kvm_vcpu_write_guest(vcpu,
1198 					 gpa + i * sizeof(e) +
1199 					     offsetof(struct vmx_msr_entry, value),
1200 					 &data, sizeof(data))) {
1201 			pr_debug_ratelimited(
1202 				"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
1203 				__func__, i, e.index, data);
1204 			return -EINVAL;
1205 		}
1206 	}
1207 	return 0;
1208 }
1209 
1210 static bool nested_msr_store_list_has_msr(struct kvm_vcpu *vcpu, u32 msr_index)
1211 {
1212 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1213 	u32 count = vmcs12->vm_exit_msr_store_count;
1214 	u64 gpa = vmcs12->vm_exit_msr_store_addr;
1215 	struct vmx_msr_entry e;
1216 	u32 i;
1217 
1218 	for (i = 0; i < count; i++) {
1219 		if (!read_and_check_msr_entry(vcpu, gpa, i, &e))
1220 			return false;
1221 
1222 		if (e.index == msr_index)
1223 			return true;
1224 	}
1225 	return false;
1226 }
1227 
1228 /*
1229  * Load guest's/host's cr3 at nested entry/exit.  @nested_ept is true if we are
1230  * emulating VM-Entry into a guest with EPT enabled.  On failure, the expected
1231  * Exit Qualification (for a VM-Entry consistency check VM-Exit) is assigned to
1232  * @entry_failure_code.
1233  */
1234 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3,
1235 			       bool nested_ept, bool reload_pdptrs,
1236 			       enum vm_entry_failure_code *entry_failure_code)
1237 {
1238 	if (CC(!kvm_vcpu_is_legal_cr3(vcpu, cr3))) {
1239 		*entry_failure_code = ENTRY_FAIL_DEFAULT;
1240 		return -EINVAL;
1241 	}
1242 
1243 	/*
1244 	 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
1245 	 * must not be dereferenced.
1246 	 */
1247 	if (reload_pdptrs && !nested_ept && is_pae_paging(vcpu) &&
1248 	    CC(!load_pdptrs(vcpu, cr3))) {
1249 		*entry_failure_code = ENTRY_FAIL_PDPTE;
1250 		return -EINVAL;
1251 	}
1252 
1253 	vcpu->arch.cr3 = cr3;
1254 	kvm_register_mark_dirty(vcpu, VCPU_REG_CR3);
1255 
1256 	/* Re-initialize the MMU, e.g. to pick up CR4 MMU role changes. */
1257 	kvm_init_mmu(vcpu);
1258 
1259 	if (!nested_ept)
1260 		kvm_mmu_new_pgd(vcpu, cr3);
1261 
1262 	return 0;
1263 }
1264 
1265 /*
1266  * Returns if KVM is able to config CPU to tag TLB entries
1267  * populated by L2 differently than TLB entries populated
1268  * by L1.
1269  *
1270  * If L0 uses EPT, L1 and L2 run with different EPTP because
1271  * guest_mode is part of kvm_mmu_page_role. Thus, TLB entries
1272  * are tagged with different EPTP.
1273  *
1274  * If L1 uses VPID and we allocated a vpid02, TLB entries are tagged
1275  * with different VPID (L1 entries are tagged with vmx->vpid
1276  * while L2 entries are tagged with vmx->nested.vpid02).
1277  */
1278 static bool nested_has_guest_tlb_tag(struct kvm_vcpu *vcpu)
1279 {
1280 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1281 
1282 	return enable_ept ||
1283 	       (nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02);
1284 }
1285 
1286 static void nested_vmx_transition_tlb_flush(struct kvm_vcpu *vcpu,
1287 					    struct vmcs12 *vmcs12,
1288 					    bool is_vmenter)
1289 {
1290 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1291 
1292 	/* Handle pending Hyper-V TLB flush requests */
1293 	kvm_hv_nested_transtion_tlb_flush(vcpu, enable_ept);
1294 
1295 	/*
1296 	 * If VPID is disabled, then guest TLB accesses use VPID=0, i.e. the
1297 	 * same VPID as the host, and so architecturally, linear and combined
1298 	 * mappings for VPID=0 must be flushed at VM-Enter and VM-Exit.  KVM
1299 	 * emulates L2 sharing L1's VPID=0 by using vpid01 while running L2,
1300 	 * and so KVM must also emulate TLB flush of VPID=0, i.e. vpid01.  This
1301 	 * is required if VPID is disabled in KVM, as a TLB flush (there are no
1302 	 * VPIDs) still occurs from L1's perspective, and KVM may need to
1303 	 * synchronize the MMU in response to the guest TLB flush.
1304 	 *
1305 	 * Note, using TLB_FLUSH_GUEST is correct even if nested EPT is in use.
1306 	 * EPT is a special snowflake, as guest-physical mappings aren't
1307 	 * flushed on VPID invalidations, including VM-Enter or VM-Exit with
1308 	 * VPID disabled.  As a result, KVM _never_ needs to sync nEPT
1309 	 * entries on VM-Enter because L1 can't rely on VM-Enter to flush
1310 	 * those mappings.
1311 	 */
1312 	if (!nested_cpu_has_vpid(vmcs12)) {
1313 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1314 		return;
1315 	}
1316 
1317 	/* L2 should never have a VPID if VPID is disabled. */
1318 	WARN_ON(!enable_vpid);
1319 
1320 	/*
1321 	 * VPID is enabled and in use by vmcs12.  If vpid12 is changing, then
1322 	 * emulate a guest TLB flush as KVM does not track vpid12 history nor
1323 	 * is the VPID incorporated into the MMU context.  I.e. KVM must assume
1324 	 * that the new vpid12 has never been used and thus represents a new
1325 	 * guest ASID that cannot have entries in the TLB.
1326 	 *
1327 	 * Note, last_vpid is initialized as 0, so the first nested VM-Enter
1328 	 * after VMXON will always flush the TLB to avoid using stale entries.
1329 	 */
1330 	if (is_vmenter && vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
1331 		vmx->nested.last_vpid = vmcs12->virtual_processor_id;
1332 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1333 		return;
1334 	}
1335 
1336 	/*
1337 	 * If VPID is enabled, used by vmc12, and vpid12 is not changing but
1338 	 * does not have a unique TLB tag (ASID), i.e. EPT is disabled and
1339 	 * KVM was unable to allocate a VPID for L2, flush the current context
1340 	 * as the effective ASID is common to both L1 and L2.
1341 	 */
1342 	if (!nested_has_guest_tlb_tag(vcpu))
1343 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1344 }
1345 
1346 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
1347 {
1348 	superset &= mask;
1349 	subset &= mask;
1350 
1351 	return (superset | subset) == superset;
1352 }
1353 
1354 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
1355 {
1356 	const u64 feature_bits = VMX_BASIC_DUAL_MONITOR_TREATMENT |
1357 				 VMX_BASIC_INOUT |
1358 				 VMX_BASIC_TRUE_CTLS |
1359 				 VMX_BASIC_NO_HW_ERROR_CODE_CC;
1360 
1361 	const u64 reserved_bits = GENMASK_ULL(63, 57) |
1362 				  GENMASK_ULL(47, 45) |
1363 				  BIT_ULL(31);
1364 
1365 	u64 vmx_basic = vmcs_config.nested.basic;
1366 
1367 	BUILD_BUG_ON(feature_bits & reserved_bits);
1368 
1369 	/*
1370 	 * Except for 32BIT_PHYS_ADDR_ONLY, which is an anti-feature bit (has
1371 	 * inverted polarity), the incoming value must not set feature bits or
1372 	 * reserved bits that aren't allowed/supported by KVM.  Fields, i.e.
1373 	 * multi-bit values, are explicitly checked below.
1374 	 */
1375 	if (!is_bitwise_subset(vmx_basic, data, feature_bits | reserved_bits))
1376 		return -EINVAL;
1377 
1378 	/*
1379 	 * KVM does not emulate a version of VMX that constrains physical
1380 	 * addresses of VMX structures (e.g. VMCS) to 32-bits.
1381 	 */
1382 	if (data & VMX_BASIC_32BIT_PHYS_ADDR_ONLY)
1383 		return -EINVAL;
1384 
1385 	if (vmx_basic_vmcs_revision_id(vmx_basic) !=
1386 	    vmx_basic_vmcs_revision_id(data))
1387 		return -EINVAL;
1388 
1389 	if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
1390 		return -EINVAL;
1391 
1392 	vmx->nested.msrs.basic = data;
1393 	return 0;
1394 }
1395 
1396 static void vmx_get_control_msr(struct nested_vmx_msrs *msrs, u32 msr_index,
1397 				u32 **low, u32 **high)
1398 {
1399 	switch (msr_index) {
1400 	case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
1401 		*low = &msrs->pinbased_ctls_low;
1402 		*high = &msrs->pinbased_ctls_high;
1403 		break;
1404 	case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
1405 		*low = &msrs->procbased_ctls_low;
1406 		*high = &msrs->procbased_ctls_high;
1407 		break;
1408 	case MSR_IA32_VMX_TRUE_EXIT_CTLS:
1409 		*low = &msrs->exit_ctls_low;
1410 		*high = &msrs->exit_ctls_high;
1411 		break;
1412 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
1413 		*low = &msrs->entry_ctls_low;
1414 		*high = &msrs->entry_ctls_high;
1415 		break;
1416 	case MSR_IA32_VMX_PROCBASED_CTLS2:
1417 		*low = &msrs->secondary_ctls_low;
1418 		*high = &msrs->secondary_ctls_high;
1419 		break;
1420 	default:
1421 		BUG();
1422 	}
1423 }
1424 
1425 static int
1426 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
1427 {
1428 	u32 *lowp, *highp;
1429 	u64 supported;
1430 
1431 	vmx_get_control_msr(&vmcs_config.nested, msr_index, &lowp, &highp);
1432 
1433 	supported = vmx_control_msr(*lowp, *highp);
1434 
1435 	/* Check must-be-1 bits are still 1. */
1436 	if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
1437 		return -EINVAL;
1438 
1439 	/* Check must-be-0 bits are still 0. */
1440 	if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
1441 		return -EINVAL;
1442 
1443 	vmx_get_control_msr(&vmx->nested.msrs, msr_index, &lowp, &highp);
1444 	*lowp = data;
1445 	*highp = data >> 32;
1446 	return 0;
1447 }
1448 
1449 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
1450 {
1451 	const u64 feature_bits = VMX_MISC_SAVE_EFER_LMA |
1452 				 VMX_MISC_ACTIVITY_HLT |
1453 				 VMX_MISC_ACTIVITY_SHUTDOWN |
1454 				 VMX_MISC_ACTIVITY_WAIT_SIPI |
1455 				 VMX_MISC_INTEL_PT |
1456 				 VMX_MISC_RDMSR_IN_SMM |
1457 				 VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
1458 				 VMX_MISC_VMXOFF_BLOCK_SMI |
1459 				 VMX_MISC_ZERO_LEN_INS;
1460 
1461 	const u64 reserved_bits = BIT_ULL(31) | GENMASK_ULL(13, 9);
1462 
1463 	u64 vmx_misc = vmx_control_msr(vmcs_config.nested.misc_low,
1464 				       vmcs_config.nested.misc_high);
1465 
1466 	BUILD_BUG_ON(feature_bits & reserved_bits);
1467 
1468 	/*
1469 	 * The incoming value must not set feature bits or reserved bits that
1470 	 * aren't allowed/supported by KVM.  Fields, i.e. multi-bit values, are
1471 	 * explicitly checked below.
1472 	 */
1473 	if (!is_bitwise_subset(vmx_misc, data, feature_bits | reserved_bits))
1474 		return -EINVAL;
1475 
1476 	if ((vmx->nested.msrs.pinbased_ctls_high &
1477 	     PIN_BASED_VMX_PREEMPTION_TIMER) &&
1478 	    vmx_misc_preemption_timer_rate(data) !=
1479 	    vmx_misc_preemption_timer_rate(vmx_misc))
1480 		return -EINVAL;
1481 
1482 	if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
1483 		return -EINVAL;
1484 
1485 	if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
1486 		return -EINVAL;
1487 
1488 	if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
1489 		return -EINVAL;
1490 
1491 	vmx->nested.msrs.misc_low = data;
1492 	vmx->nested.msrs.misc_high = data >> 32;
1493 
1494 	return 0;
1495 }
1496 
1497 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
1498 {
1499 	u64 vmx_ept_vpid_cap = vmx_control_msr(vmcs_config.nested.ept_caps,
1500 					       vmcs_config.nested.vpid_caps);
1501 
1502 	/* Every bit is either reserved or a feature bit. */
1503 	if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
1504 		return -EINVAL;
1505 
1506 	vmx->nested.msrs.ept_caps = data;
1507 	vmx->nested.msrs.vpid_caps = data >> 32;
1508 	return 0;
1509 }
1510 
1511 static u64 *vmx_get_fixed0_msr(struct nested_vmx_msrs *msrs, u32 msr_index)
1512 {
1513 	switch (msr_index) {
1514 	case MSR_IA32_VMX_CR0_FIXED0:
1515 		return &msrs->cr0_fixed0;
1516 	case MSR_IA32_VMX_CR4_FIXED0:
1517 		return &msrs->cr4_fixed0;
1518 	default:
1519 		BUG();
1520 	}
1521 }
1522 
1523 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
1524 {
1525 	const u64 *msr = vmx_get_fixed0_msr(&vmcs_config.nested, msr_index);
1526 
1527 	/*
1528 	 * 1 bits (which indicates bits which "must-be-1" during VMX operation)
1529 	 * must be 1 in the restored value.
1530 	 */
1531 	if (!is_bitwise_subset(data, *msr, -1ULL))
1532 		return -EINVAL;
1533 
1534 	*vmx_get_fixed0_msr(&vmx->nested.msrs, msr_index) = data;
1535 	return 0;
1536 }
1537 
1538 /*
1539  * Called when userspace is restoring VMX MSRs.
1540  *
1541  * Returns 0 on success, non-0 otherwise.
1542  */
1543 int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
1544 {
1545 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1546 
1547 	/*
1548 	 * Don't allow changes to the VMX capability MSRs while the vCPU
1549 	 * is in VMX operation.
1550 	 */
1551 	if (vmx->nested.vmxon)
1552 		return -EBUSY;
1553 
1554 	switch (msr_index) {
1555 	case MSR_IA32_VMX_BASIC:
1556 		return vmx_restore_vmx_basic(vmx, data);
1557 	case MSR_IA32_VMX_PINBASED_CTLS:
1558 	case MSR_IA32_VMX_PROCBASED_CTLS:
1559 	case MSR_IA32_VMX_EXIT_CTLS:
1560 	case MSR_IA32_VMX_ENTRY_CTLS:
1561 		/*
1562 		 * The "non-true" VMX capability MSRs are generated from the
1563 		 * "true" MSRs, so we do not support restoring them directly.
1564 		 *
1565 		 * If userspace wants to emulate VMX_BASIC[55]=0, userspace
1566 		 * should restore the "true" MSRs with the must-be-1 bits
1567 		 * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
1568 		 * DEFAULT SETTINGS".
1569 		 */
1570 		return -EINVAL;
1571 	case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
1572 	case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
1573 	case MSR_IA32_VMX_TRUE_EXIT_CTLS:
1574 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
1575 	case MSR_IA32_VMX_PROCBASED_CTLS2:
1576 		return vmx_restore_control_msr(vmx, msr_index, data);
1577 	case MSR_IA32_VMX_MISC:
1578 		return vmx_restore_vmx_misc(vmx, data);
1579 	case MSR_IA32_VMX_CR0_FIXED0:
1580 	case MSR_IA32_VMX_CR4_FIXED0:
1581 		return vmx_restore_fixed0_msr(vmx, msr_index, data);
1582 	case MSR_IA32_VMX_CR0_FIXED1:
1583 	case MSR_IA32_VMX_CR4_FIXED1:
1584 		/*
1585 		 * These MSRs are generated based on the vCPU's CPUID, so we
1586 		 * do not support restoring them directly.
1587 		 */
1588 		return -EINVAL;
1589 	case MSR_IA32_VMX_EPT_VPID_CAP:
1590 		return vmx_restore_vmx_ept_vpid_cap(vmx, data);
1591 	case MSR_IA32_VMX_VMCS_ENUM:
1592 		vmx->nested.msrs.vmcs_enum = data;
1593 		return 0;
1594 	case MSR_IA32_VMX_VMFUNC:
1595 		if (data & ~vmcs_config.nested.vmfunc_controls)
1596 			return -EINVAL;
1597 		vmx->nested.msrs.vmfunc_controls = data;
1598 		return 0;
1599 	default:
1600 		/*
1601 		 * The rest of the VMX capability MSRs do not support restore.
1602 		 */
1603 		return -EINVAL;
1604 	}
1605 }
1606 
1607 /* Returns 0 on success, non-0 otherwise. */
1608 int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
1609 {
1610 	switch (msr_index) {
1611 	case MSR_IA32_VMX_BASIC:
1612 		*pdata = msrs->basic;
1613 		break;
1614 	case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
1615 	case MSR_IA32_VMX_PINBASED_CTLS:
1616 		*pdata = vmx_control_msr(
1617 			msrs->pinbased_ctls_low,
1618 			msrs->pinbased_ctls_high);
1619 		if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
1620 			*pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
1621 		break;
1622 	case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
1623 	case MSR_IA32_VMX_PROCBASED_CTLS:
1624 		*pdata = vmx_control_msr(
1625 			msrs->procbased_ctls_low,
1626 			msrs->procbased_ctls_high);
1627 		if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
1628 			*pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
1629 		break;
1630 	case MSR_IA32_VMX_TRUE_EXIT_CTLS:
1631 	case MSR_IA32_VMX_EXIT_CTLS:
1632 		*pdata = vmx_control_msr(
1633 			msrs->exit_ctls_low,
1634 			msrs->exit_ctls_high);
1635 		if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
1636 			*pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
1637 		break;
1638 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
1639 	case MSR_IA32_VMX_ENTRY_CTLS:
1640 		*pdata = vmx_control_msr(
1641 			msrs->entry_ctls_low,
1642 			msrs->entry_ctls_high);
1643 		if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
1644 			*pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
1645 		break;
1646 	case MSR_IA32_VMX_MISC:
1647 		*pdata = vmx_control_msr(
1648 			msrs->misc_low,
1649 			msrs->misc_high);
1650 		break;
1651 	case MSR_IA32_VMX_CR0_FIXED0:
1652 		*pdata = msrs->cr0_fixed0;
1653 		break;
1654 	case MSR_IA32_VMX_CR0_FIXED1:
1655 		*pdata = msrs->cr0_fixed1;
1656 		break;
1657 	case MSR_IA32_VMX_CR4_FIXED0:
1658 		*pdata = msrs->cr4_fixed0;
1659 		break;
1660 	case MSR_IA32_VMX_CR4_FIXED1:
1661 		*pdata = msrs->cr4_fixed1;
1662 		break;
1663 	case MSR_IA32_VMX_VMCS_ENUM:
1664 		*pdata = msrs->vmcs_enum;
1665 		break;
1666 	case MSR_IA32_VMX_PROCBASED_CTLS2:
1667 		*pdata = vmx_control_msr(
1668 			msrs->secondary_ctls_low,
1669 			msrs->secondary_ctls_high);
1670 		break;
1671 	case MSR_IA32_VMX_EPT_VPID_CAP:
1672 		*pdata = msrs->ept_caps |
1673 			((u64)msrs->vpid_caps << 32);
1674 		break;
1675 	case MSR_IA32_VMX_VMFUNC:
1676 		*pdata = msrs->vmfunc_controls;
1677 		break;
1678 	default:
1679 		return 1;
1680 	}
1681 
1682 	return 0;
1683 }
1684 
1685 /*
1686  * Copy the writable VMCS shadow fields back to the VMCS12, in case they have
1687  * been modified by the L1 guest.  Note, "writable" in this context means
1688  * "writable by the guest", i.e. tagged SHADOW_FIELD_RW; the set of
1689  * fields tagged SHADOW_FIELD_RO may or may not align with the "read-only"
1690  * VM-exit information fields (which are actually writable if the vCPU is
1691  * configured to support "VMWRITE to any supported field in the VMCS").
1692  */
1693 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
1694 {
1695 	struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
1696 	struct vmcs12 *vmcs12 = get_vmcs12(&vmx->vcpu);
1697 	struct shadow_vmcs_field field;
1698 	unsigned long val;
1699 	int i;
1700 
1701 	if (WARN_ON(!shadow_vmcs))
1702 		return;
1703 
1704 	preempt_disable();
1705 
1706 	vmcs_load(shadow_vmcs);
1707 
1708 	for (i = 0; i < max_shadow_read_write_fields; i++) {
1709 		field = shadow_read_write_fields[i];
1710 		val = __vmcs_readl(field.encoding);
1711 		vmcs12_write_any(vmcs12, field.encoding, field.offset, val);
1712 	}
1713 
1714 	vmcs_clear(shadow_vmcs);
1715 	vmcs_load(vmx->loaded_vmcs->vmcs);
1716 
1717 	preempt_enable();
1718 }
1719 
1720 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
1721 {
1722 	const struct shadow_vmcs_field *fields[] = {
1723 		shadow_read_write_fields,
1724 		shadow_read_only_fields
1725 	};
1726 	const int max_fields[] = {
1727 		max_shadow_read_write_fields,
1728 		max_shadow_read_only_fields
1729 	};
1730 	struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
1731 	struct vmcs12 *vmcs12 = get_vmcs12(&vmx->vcpu);
1732 	struct shadow_vmcs_field field;
1733 	unsigned long val;
1734 	int i, q;
1735 
1736 	if (WARN_ON(!shadow_vmcs))
1737 		return;
1738 
1739 	vmcs_load(shadow_vmcs);
1740 
1741 	for (q = 0; q < ARRAY_SIZE(fields); q++) {
1742 		for (i = 0; i < max_fields[q]; i++) {
1743 			field = fields[q][i];
1744 			val = vmcs12_read_any(vmcs12, field.encoding,
1745 					      field.offset);
1746 			__vmcs_writel(field.encoding, val);
1747 		}
1748 	}
1749 
1750 	vmcs_clear(shadow_vmcs);
1751 	vmcs_load(vmx->loaded_vmcs->vmcs);
1752 }
1753 
1754 static void copy_enlightened_to_vmcs12(struct vcpu_vmx *vmx, u32 hv_clean_fields)
1755 {
1756 #ifdef CONFIG_KVM_HYPERV
1757 	struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
1758 	struct hv_enlightened_vmcs *evmcs = nested_vmx_evmcs(vmx);
1759 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(&vmx->vcpu);
1760 
1761 	/* HV_VMX_ENLIGHTENED_CLEAN_FIELD_NONE */
1762 	vmcs12->tpr_threshold = evmcs->tpr_threshold;
1763 	vmcs12->guest_rip = evmcs->guest_rip;
1764 
1765 	if (unlikely(!(hv_clean_fields &
1766 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_ENLIGHTENMENTSCONTROL))) {
1767 		hv_vcpu->nested.pa_page_gpa = evmcs->partition_assist_page;
1768 		hv_vcpu->nested.vm_id = evmcs->hv_vm_id;
1769 		hv_vcpu->nested.vp_id = evmcs->hv_vp_id;
1770 	}
1771 
1772 	if (unlikely(!(hv_clean_fields &
1773 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_BASIC))) {
1774 		vmcs12->guest_rsp = evmcs->guest_rsp;
1775 		vmcs12->guest_rflags = evmcs->guest_rflags;
1776 		vmcs12->guest_interruptibility_info =
1777 			evmcs->guest_interruptibility_info;
1778 		/*
1779 		 * Not present in struct vmcs12:
1780 		 * vmcs12->guest_ssp = evmcs->guest_ssp;
1781 		 */
1782 	}
1783 
1784 	if (unlikely(!(hv_clean_fields &
1785 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
1786 		vmcs12->cpu_based_vm_exec_control =
1787 			evmcs->cpu_based_vm_exec_control;
1788 	}
1789 
1790 	if (unlikely(!(hv_clean_fields &
1791 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EXCPN))) {
1792 		vmcs12->exception_bitmap = evmcs->exception_bitmap;
1793 	}
1794 
1795 	if (unlikely(!(hv_clean_fields &
1796 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_ENTRY))) {
1797 		vmcs12->vm_entry_controls = evmcs->vm_entry_controls;
1798 	}
1799 
1800 	if (unlikely(!(hv_clean_fields &
1801 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EVENT))) {
1802 		vmcs12->vm_entry_intr_info_field =
1803 			evmcs->vm_entry_intr_info_field;
1804 		vmcs12->vm_entry_exception_error_code =
1805 			evmcs->vm_entry_exception_error_code;
1806 		vmcs12->vm_entry_instruction_len =
1807 			evmcs->vm_entry_instruction_len;
1808 	}
1809 
1810 	if (unlikely(!(hv_clean_fields &
1811 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
1812 		vmcs12->host_ia32_pat = evmcs->host_ia32_pat;
1813 		vmcs12->host_ia32_efer = evmcs->host_ia32_efer;
1814 		vmcs12->host_cr0 = evmcs->host_cr0;
1815 		vmcs12->host_cr3 = evmcs->host_cr3;
1816 		vmcs12->host_cr4 = evmcs->host_cr4;
1817 		vmcs12->host_ia32_sysenter_esp = evmcs->host_ia32_sysenter_esp;
1818 		vmcs12->host_ia32_sysenter_eip = evmcs->host_ia32_sysenter_eip;
1819 		vmcs12->host_rip = evmcs->host_rip;
1820 		vmcs12->host_ia32_sysenter_cs = evmcs->host_ia32_sysenter_cs;
1821 		vmcs12->host_es_selector = evmcs->host_es_selector;
1822 		vmcs12->host_cs_selector = evmcs->host_cs_selector;
1823 		vmcs12->host_ss_selector = evmcs->host_ss_selector;
1824 		vmcs12->host_ds_selector = evmcs->host_ds_selector;
1825 		vmcs12->host_fs_selector = evmcs->host_fs_selector;
1826 		vmcs12->host_gs_selector = evmcs->host_gs_selector;
1827 		vmcs12->host_tr_selector = evmcs->host_tr_selector;
1828 		vmcs12->host_ia32_perf_global_ctrl = evmcs->host_ia32_perf_global_ctrl;
1829 		/*
1830 		 * Not present in struct vmcs12:
1831 		 * vmcs12->host_ia32_s_cet = evmcs->host_ia32_s_cet;
1832 		 * vmcs12->host_ssp = evmcs->host_ssp;
1833 		 * vmcs12->host_ia32_int_ssp_table_addr = evmcs->host_ia32_int_ssp_table_addr;
1834 		 */
1835 	}
1836 
1837 	if (unlikely(!(hv_clean_fields &
1838 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP1))) {
1839 		vmcs12->pin_based_vm_exec_control =
1840 			evmcs->pin_based_vm_exec_control;
1841 		vmcs12->vm_exit_controls = evmcs->vm_exit_controls;
1842 		vmcs12->secondary_vm_exec_control =
1843 			evmcs->secondary_vm_exec_control;
1844 	}
1845 
1846 	if (unlikely(!(hv_clean_fields &
1847 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_IO_BITMAP))) {
1848 		vmcs12->io_bitmap_a = evmcs->io_bitmap_a;
1849 		vmcs12->io_bitmap_b = evmcs->io_bitmap_b;
1850 	}
1851 
1852 	if (unlikely(!(hv_clean_fields &
1853 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP))) {
1854 		vmcs12->msr_bitmap = evmcs->msr_bitmap;
1855 	}
1856 
1857 	if (unlikely(!(hv_clean_fields &
1858 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2))) {
1859 		vmcs12->guest_es_base = evmcs->guest_es_base;
1860 		vmcs12->guest_cs_base = evmcs->guest_cs_base;
1861 		vmcs12->guest_ss_base = evmcs->guest_ss_base;
1862 		vmcs12->guest_ds_base = evmcs->guest_ds_base;
1863 		vmcs12->guest_fs_base = evmcs->guest_fs_base;
1864 		vmcs12->guest_gs_base = evmcs->guest_gs_base;
1865 		vmcs12->guest_ldtr_base = evmcs->guest_ldtr_base;
1866 		vmcs12->guest_tr_base = evmcs->guest_tr_base;
1867 		vmcs12->guest_gdtr_base = evmcs->guest_gdtr_base;
1868 		vmcs12->guest_idtr_base = evmcs->guest_idtr_base;
1869 		vmcs12->guest_es_limit = evmcs->guest_es_limit;
1870 		vmcs12->guest_cs_limit = evmcs->guest_cs_limit;
1871 		vmcs12->guest_ss_limit = evmcs->guest_ss_limit;
1872 		vmcs12->guest_ds_limit = evmcs->guest_ds_limit;
1873 		vmcs12->guest_fs_limit = evmcs->guest_fs_limit;
1874 		vmcs12->guest_gs_limit = evmcs->guest_gs_limit;
1875 		vmcs12->guest_ldtr_limit = evmcs->guest_ldtr_limit;
1876 		vmcs12->guest_tr_limit = evmcs->guest_tr_limit;
1877 		vmcs12->guest_gdtr_limit = evmcs->guest_gdtr_limit;
1878 		vmcs12->guest_idtr_limit = evmcs->guest_idtr_limit;
1879 		vmcs12->guest_es_ar_bytes = evmcs->guest_es_ar_bytes;
1880 		vmcs12->guest_cs_ar_bytes = evmcs->guest_cs_ar_bytes;
1881 		vmcs12->guest_ss_ar_bytes = evmcs->guest_ss_ar_bytes;
1882 		vmcs12->guest_ds_ar_bytes = evmcs->guest_ds_ar_bytes;
1883 		vmcs12->guest_fs_ar_bytes = evmcs->guest_fs_ar_bytes;
1884 		vmcs12->guest_gs_ar_bytes = evmcs->guest_gs_ar_bytes;
1885 		vmcs12->guest_ldtr_ar_bytes = evmcs->guest_ldtr_ar_bytes;
1886 		vmcs12->guest_tr_ar_bytes = evmcs->guest_tr_ar_bytes;
1887 		vmcs12->guest_es_selector = evmcs->guest_es_selector;
1888 		vmcs12->guest_cs_selector = evmcs->guest_cs_selector;
1889 		vmcs12->guest_ss_selector = evmcs->guest_ss_selector;
1890 		vmcs12->guest_ds_selector = evmcs->guest_ds_selector;
1891 		vmcs12->guest_fs_selector = evmcs->guest_fs_selector;
1892 		vmcs12->guest_gs_selector = evmcs->guest_gs_selector;
1893 		vmcs12->guest_ldtr_selector = evmcs->guest_ldtr_selector;
1894 		vmcs12->guest_tr_selector = evmcs->guest_tr_selector;
1895 	}
1896 
1897 	if (unlikely(!(hv_clean_fields &
1898 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP2))) {
1899 		vmcs12->tsc_offset = evmcs->tsc_offset;
1900 		vmcs12->virtual_apic_page_addr = evmcs->virtual_apic_page_addr;
1901 		vmcs12->xss_exit_bitmap = evmcs->xss_exit_bitmap;
1902 		vmcs12->encls_exiting_bitmap = evmcs->encls_exiting_bitmap;
1903 		vmcs12->tsc_multiplier = evmcs->tsc_multiplier;
1904 	}
1905 
1906 	if (unlikely(!(hv_clean_fields &
1907 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CRDR))) {
1908 		vmcs12->cr0_guest_host_mask = evmcs->cr0_guest_host_mask;
1909 		vmcs12->cr4_guest_host_mask = evmcs->cr4_guest_host_mask;
1910 		vmcs12->cr0_read_shadow = evmcs->cr0_read_shadow;
1911 		vmcs12->cr4_read_shadow = evmcs->cr4_read_shadow;
1912 		vmcs12->guest_cr0 = evmcs->guest_cr0;
1913 		vmcs12->guest_cr3 = evmcs->guest_cr3;
1914 		vmcs12->guest_cr4 = evmcs->guest_cr4;
1915 		vmcs12->guest_dr7 = evmcs->guest_dr7;
1916 	}
1917 
1918 	if (unlikely(!(hv_clean_fields &
1919 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_POINTER))) {
1920 		vmcs12->host_fs_base = evmcs->host_fs_base;
1921 		vmcs12->host_gs_base = evmcs->host_gs_base;
1922 		vmcs12->host_tr_base = evmcs->host_tr_base;
1923 		vmcs12->host_gdtr_base = evmcs->host_gdtr_base;
1924 		vmcs12->host_idtr_base = evmcs->host_idtr_base;
1925 		vmcs12->host_rsp = evmcs->host_rsp;
1926 	}
1927 
1928 	if (unlikely(!(hv_clean_fields &
1929 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_XLAT))) {
1930 		vmcs12->ept_pointer = evmcs->ept_pointer;
1931 		vmcs12->virtual_processor_id = evmcs->virtual_processor_id;
1932 	}
1933 
1934 	if (unlikely(!(hv_clean_fields &
1935 		       HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1))) {
1936 		vmcs12->vmcs_link_pointer = evmcs->vmcs_link_pointer;
1937 		vmcs12->guest_ia32_debugctl = evmcs->guest_ia32_debugctl;
1938 		vmcs12->guest_ia32_pat = evmcs->guest_ia32_pat;
1939 		vmcs12->guest_ia32_efer = evmcs->guest_ia32_efer;
1940 		vmcs12->guest_pdptr0 = evmcs->guest_pdptr0;
1941 		vmcs12->guest_pdptr1 = evmcs->guest_pdptr1;
1942 		vmcs12->guest_pdptr2 = evmcs->guest_pdptr2;
1943 		vmcs12->guest_pdptr3 = evmcs->guest_pdptr3;
1944 		vmcs12->guest_pending_dbg_exceptions =
1945 			evmcs->guest_pending_dbg_exceptions;
1946 		vmcs12->guest_sysenter_esp = evmcs->guest_sysenter_esp;
1947 		vmcs12->guest_sysenter_eip = evmcs->guest_sysenter_eip;
1948 		vmcs12->guest_bndcfgs = evmcs->guest_bndcfgs;
1949 		vmcs12->guest_activity_state = evmcs->guest_activity_state;
1950 		vmcs12->guest_sysenter_cs = evmcs->guest_sysenter_cs;
1951 		vmcs12->guest_ia32_perf_global_ctrl = evmcs->guest_ia32_perf_global_ctrl;
1952 		/*
1953 		 * Not present in struct vmcs12:
1954 		 * vmcs12->guest_ia32_s_cet = evmcs->guest_ia32_s_cet;
1955 		 * vmcs12->guest_ia32_lbr_ctl = evmcs->guest_ia32_lbr_ctl;
1956 		 * vmcs12->guest_ia32_int_ssp_table_addr = evmcs->guest_ia32_int_ssp_table_addr;
1957 		 */
1958 	}
1959 
1960 	/*
1961 	 * Not used?
1962 	 * vmcs12->vm_exit_msr_store_addr = evmcs->vm_exit_msr_store_addr;
1963 	 * vmcs12->vm_exit_msr_load_addr = evmcs->vm_exit_msr_load_addr;
1964 	 * vmcs12->vm_entry_msr_load_addr = evmcs->vm_entry_msr_load_addr;
1965 	 * vmcs12->page_fault_error_code_mask =
1966 	 *		evmcs->page_fault_error_code_mask;
1967 	 * vmcs12->page_fault_error_code_match =
1968 	 *		evmcs->page_fault_error_code_match;
1969 	 * vmcs12->cr3_target_count = evmcs->cr3_target_count;
1970 	 * vmcs12->vm_exit_msr_store_count = evmcs->vm_exit_msr_store_count;
1971 	 * vmcs12->vm_exit_msr_load_count = evmcs->vm_exit_msr_load_count;
1972 	 * vmcs12->vm_entry_msr_load_count = evmcs->vm_entry_msr_load_count;
1973 	 */
1974 
1975 	/*
1976 	 * Read only fields:
1977 	 * vmcs12->guest_physical_address = evmcs->guest_physical_address;
1978 	 * vmcs12->vm_instruction_error = evmcs->vm_instruction_error;
1979 	 * vmcs12->vm_exit_reason = evmcs->vm_exit_reason;
1980 	 * vmcs12->vm_exit_intr_info = evmcs->vm_exit_intr_info;
1981 	 * vmcs12->vm_exit_intr_error_code = evmcs->vm_exit_intr_error_code;
1982 	 * vmcs12->idt_vectoring_info_field = evmcs->idt_vectoring_info_field;
1983 	 * vmcs12->idt_vectoring_error_code = evmcs->idt_vectoring_error_code;
1984 	 * vmcs12->vm_exit_instruction_len = evmcs->vm_exit_instruction_len;
1985 	 * vmcs12->vmx_instruction_info = evmcs->vmx_instruction_info;
1986 	 * vmcs12->exit_qualification = evmcs->exit_qualification;
1987 	 * vmcs12->guest_linear_address = evmcs->guest_linear_address;
1988 	 *
1989 	 * Not present in struct vmcs12:
1990 	 * vmcs12->exit_io_instruction_ecx = evmcs->exit_io_instruction_ecx;
1991 	 * vmcs12->exit_io_instruction_esi = evmcs->exit_io_instruction_esi;
1992 	 * vmcs12->exit_io_instruction_edi = evmcs->exit_io_instruction_edi;
1993 	 * vmcs12->exit_io_instruction_eip = evmcs->exit_io_instruction_eip;
1994 	 */
1995 
1996 	return;
1997 #else /* CONFIG_KVM_HYPERV */
1998 	KVM_BUG_ON(1, vmx->vcpu.kvm);
1999 #endif /* CONFIG_KVM_HYPERV */
2000 }
2001 
2002 static void copy_vmcs12_to_enlightened(struct vcpu_vmx *vmx)
2003 {
2004 #ifdef CONFIG_KVM_HYPERV
2005 	struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
2006 	struct hv_enlightened_vmcs *evmcs = nested_vmx_evmcs(vmx);
2007 
2008 	/*
2009 	 * Should not be changed by KVM:
2010 	 *
2011 	 * evmcs->host_es_selector = vmcs12->host_es_selector;
2012 	 * evmcs->host_cs_selector = vmcs12->host_cs_selector;
2013 	 * evmcs->host_ss_selector = vmcs12->host_ss_selector;
2014 	 * evmcs->host_ds_selector = vmcs12->host_ds_selector;
2015 	 * evmcs->host_fs_selector = vmcs12->host_fs_selector;
2016 	 * evmcs->host_gs_selector = vmcs12->host_gs_selector;
2017 	 * evmcs->host_tr_selector = vmcs12->host_tr_selector;
2018 	 * evmcs->host_ia32_pat = vmcs12->host_ia32_pat;
2019 	 * evmcs->host_ia32_efer = vmcs12->host_ia32_efer;
2020 	 * evmcs->host_cr0 = vmcs12->host_cr0;
2021 	 * evmcs->host_cr3 = vmcs12->host_cr3;
2022 	 * evmcs->host_cr4 = vmcs12->host_cr4;
2023 	 * evmcs->host_ia32_sysenter_esp = vmcs12->host_ia32_sysenter_esp;
2024 	 * evmcs->host_ia32_sysenter_eip = vmcs12->host_ia32_sysenter_eip;
2025 	 * evmcs->host_rip = vmcs12->host_rip;
2026 	 * evmcs->host_ia32_sysenter_cs = vmcs12->host_ia32_sysenter_cs;
2027 	 * evmcs->host_fs_base = vmcs12->host_fs_base;
2028 	 * evmcs->host_gs_base = vmcs12->host_gs_base;
2029 	 * evmcs->host_tr_base = vmcs12->host_tr_base;
2030 	 * evmcs->host_gdtr_base = vmcs12->host_gdtr_base;
2031 	 * evmcs->host_idtr_base = vmcs12->host_idtr_base;
2032 	 * evmcs->host_rsp = vmcs12->host_rsp;
2033 	 * sync_vmcs02_to_vmcs12() doesn't read these:
2034 	 * evmcs->io_bitmap_a = vmcs12->io_bitmap_a;
2035 	 * evmcs->io_bitmap_b = vmcs12->io_bitmap_b;
2036 	 * evmcs->msr_bitmap = vmcs12->msr_bitmap;
2037 	 * evmcs->ept_pointer = vmcs12->ept_pointer;
2038 	 * evmcs->xss_exit_bitmap = vmcs12->xss_exit_bitmap;
2039 	 * evmcs->vm_exit_msr_store_addr = vmcs12->vm_exit_msr_store_addr;
2040 	 * evmcs->vm_exit_msr_load_addr = vmcs12->vm_exit_msr_load_addr;
2041 	 * evmcs->vm_entry_msr_load_addr = vmcs12->vm_entry_msr_load_addr;
2042 	 * evmcs->tpr_threshold = vmcs12->tpr_threshold;
2043 	 * evmcs->virtual_processor_id = vmcs12->virtual_processor_id;
2044 	 * evmcs->exception_bitmap = vmcs12->exception_bitmap;
2045 	 * evmcs->vmcs_link_pointer = vmcs12->vmcs_link_pointer;
2046 	 * evmcs->pin_based_vm_exec_control = vmcs12->pin_based_vm_exec_control;
2047 	 * evmcs->vm_exit_controls = vmcs12->vm_exit_controls;
2048 	 * evmcs->secondary_vm_exec_control = vmcs12->secondary_vm_exec_control;
2049 	 * evmcs->page_fault_error_code_mask =
2050 	 *		vmcs12->page_fault_error_code_mask;
2051 	 * evmcs->page_fault_error_code_match =
2052 	 *		vmcs12->page_fault_error_code_match;
2053 	 * evmcs->cr3_target_count = vmcs12->cr3_target_count;
2054 	 * evmcs->virtual_apic_page_addr = vmcs12->virtual_apic_page_addr;
2055 	 * evmcs->tsc_offset = vmcs12->tsc_offset;
2056 	 * evmcs->guest_ia32_debugctl = vmcs12->guest_ia32_debugctl;
2057 	 * evmcs->cr0_guest_host_mask = vmcs12->cr0_guest_host_mask;
2058 	 * evmcs->cr4_guest_host_mask = vmcs12->cr4_guest_host_mask;
2059 	 * evmcs->cr0_read_shadow = vmcs12->cr0_read_shadow;
2060 	 * evmcs->cr4_read_shadow = vmcs12->cr4_read_shadow;
2061 	 * evmcs->vm_exit_msr_store_count = vmcs12->vm_exit_msr_store_count;
2062 	 * evmcs->vm_exit_msr_load_count = vmcs12->vm_exit_msr_load_count;
2063 	 * evmcs->vm_entry_msr_load_count = vmcs12->vm_entry_msr_load_count;
2064 	 * evmcs->guest_ia32_perf_global_ctrl = vmcs12->guest_ia32_perf_global_ctrl;
2065 	 * evmcs->host_ia32_perf_global_ctrl = vmcs12->host_ia32_perf_global_ctrl;
2066 	 * evmcs->encls_exiting_bitmap = vmcs12->encls_exiting_bitmap;
2067 	 * evmcs->tsc_multiplier = vmcs12->tsc_multiplier;
2068 	 *
2069 	 * Not present in struct vmcs12:
2070 	 * evmcs->exit_io_instruction_ecx = vmcs12->exit_io_instruction_ecx;
2071 	 * evmcs->exit_io_instruction_esi = vmcs12->exit_io_instruction_esi;
2072 	 * evmcs->exit_io_instruction_edi = vmcs12->exit_io_instruction_edi;
2073 	 * evmcs->exit_io_instruction_eip = vmcs12->exit_io_instruction_eip;
2074 	 * evmcs->host_ia32_s_cet = vmcs12->host_ia32_s_cet;
2075 	 * evmcs->host_ssp = vmcs12->host_ssp;
2076 	 * evmcs->host_ia32_int_ssp_table_addr = vmcs12->host_ia32_int_ssp_table_addr;
2077 	 * evmcs->guest_ia32_s_cet = vmcs12->guest_ia32_s_cet;
2078 	 * evmcs->guest_ia32_lbr_ctl = vmcs12->guest_ia32_lbr_ctl;
2079 	 * evmcs->guest_ia32_int_ssp_table_addr = vmcs12->guest_ia32_int_ssp_table_addr;
2080 	 * evmcs->guest_ssp = vmcs12->guest_ssp;
2081 	 */
2082 
2083 	evmcs->guest_es_selector = vmcs12->guest_es_selector;
2084 	evmcs->guest_cs_selector = vmcs12->guest_cs_selector;
2085 	evmcs->guest_ss_selector = vmcs12->guest_ss_selector;
2086 	evmcs->guest_ds_selector = vmcs12->guest_ds_selector;
2087 	evmcs->guest_fs_selector = vmcs12->guest_fs_selector;
2088 	evmcs->guest_gs_selector = vmcs12->guest_gs_selector;
2089 	evmcs->guest_ldtr_selector = vmcs12->guest_ldtr_selector;
2090 	evmcs->guest_tr_selector = vmcs12->guest_tr_selector;
2091 
2092 	evmcs->guest_es_limit = vmcs12->guest_es_limit;
2093 	evmcs->guest_cs_limit = vmcs12->guest_cs_limit;
2094 	evmcs->guest_ss_limit = vmcs12->guest_ss_limit;
2095 	evmcs->guest_ds_limit = vmcs12->guest_ds_limit;
2096 	evmcs->guest_fs_limit = vmcs12->guest_fs_limit;
2097 	evmcs->guest_gs_limit = vmcs12->guest_gs_limit;
2098 	evmcs->guest_ldtr_limit = vmcs12->guest_ldtr_limit;
2099 	evmcs->guest_tr_limit = vmcs12->guest_tr_limit;
2100 	evmcs->guest_gdtr_limit = vmcs12->guest_gdtr_limit;
2101 	evmcs->guest_idtr_limit = vmcs12->guest_idtr_limit;
2102 
2103 	evmcs->guest_es_ar_bytes = vmcs12->guest_es_ar_bytes;
2104 	evmcs->guest_cs_ar_bytes = vmcs12->guest_cs_ar_bytes;
2105 	evmcs->guest_ss_ar_bytes = vmcs12->guest_ss_ar_bytes;
2106 	evmcs->guest_ds_ar_bytes = vmcs12->guest_ds_ar_bytes;
2107 	evmcs->guest_fs_ar_bytes = vmcs12->guest_fs_ar_bytes;
2108 	evmcs->guest_gs_ar_bytes = vmcs12->guest_gs_ar_bytes;
2109 	evmcs->guest_ldtr_ar_bytes = vmcs12->guest_ldtr_ar_bytes;
2110 	evmcs->guest_tr_ar_bytes = vmcs12->guest_tr_ar_bytes;
2111 
2112 	evmcs->guest_es_base = vmcs12->guest_es_base;
2113 	evmcs->guest_cs_base = vmcs12->guest_cs_base;
2114 	evmcs->guest_ss_base = vmcs12->guest_ss_base;
2115 	evmcs->guest_ds_base = vmcs12->guest_ds_base;
2116 	evmcs->guest_fs_base = vmcs12->guest_fs_base;
2117 	evmcs->guest_gs_base = vmcs12->guest_gs_base;
2118 	evmcs->guest_ldtr_base = vmcs12->guest_ldtr_base;
2119 	evmcs->guest_tr_base = vmcs12->guest_tr_base;
2120 	evmcs->guest_gdtr_base = vmcs12->guest_gdtr_base;
2121 	evmcs->guest_idtr_base = vmcs12->guest_idtr_base;
2122 
2123 	evmcs->guest_ia32_pat = vmcs12->guest_ia32_pat;
2124 	evmcs->guest_ia32_efer = vmcs12->guest_ia32_efer;
2125 
2126 	evmcs->guest_pdptr0 = vmcs12->guest_pdptr0;
2127 	evmcs->guest_pdptr1 = vmcs12->guest_pdptr1;
2128 	evmcs->guest_pdptr2 = vmcs12->guest_pdptr2;
2129 	evmcs->guest_pdptr3 = vmcs12->guest_pdptr3;
2130 
2131 	evmcs->guest_pending_dbg_exceptions =
2132 		vmcs12->guest_pending_dbg_exceptions;
2133 	evmcs->guest_sysenter_esp = vmcs12->guest_sysenter_esp;
2134 	evmcs->guest_sysenter_eip = vmcs12->guest_sysenter_eip;
2135 
2136 	evmcs->guest_activity_state = vmcs12->guest_activity_state;
2137 	evmcs->guest_sysenter_cs = vmcs12->guest_sysenter_cs;
2138 
2139 	evmcs->guest_cr0 = vmcs12->guest_cr0;
2140 	evmcs->guest_cr3 = vmcs12->guest_cr3;
2141 	evmcs->guest_cr4 = vmcs12->guest_cr4;
2142 	evmcs->guest_dr7 = vmcs12->guest_dr7;
2143 
2144 	evmcs->guest_physical_address = vmcs12->guest_physical_address;
2145 
2146 	evmcs->vm_instruction_error = vmcs12->vm_instruction_error;
2147 	evmcs->vm_exit_reason = vmcs12->vm_exit_reason;
2148 	evmcs->vm_exit_intr_info = vmcs12->vm_exit_intr_info;
2149 	evmcs->vm_exit_intr_error_code = vmcs12->vm_exit_intr_error_code;
2150 	evmcs->idt_vectoring_info_field = vmcs12->idt_vectoring_info_field;
2151 	evmcs->idt_vectoring_error_code = vmcs12->idt_vectoring_error_code;
2152 	evmcs->vm_exit_instruction_len = vmcs12->vm_exit_instruction_len;
2153 	evmcs->vmx_instruction_info = vmcs12->vmx_instruction_info;
2154 
2155 	evmcs->exit_qualification = vmcs12->exit_qualification;
2156 
2157 	evmcs->guest_linear_address = vmcs12->guest_linear_address;
2158 	evmcs->guest_rsp = vmcs12->guest_rsp;
2159 	evmcs->guest_rflags = vmcs12->guest_rflags;
2160 
2161 	evmcs->guest_interruptibility_info =
2162 		vmcs12->guest_interruptibility_info;
2163 	evmcs->cpu_based_vm_exec_control = vmcs12->cpu_based_vm_exec_control;
2164 	evmcs->vm_entry_controls = vmcs12->vm_entry_controls;
2165 	evmcs->vm_entry_intr_info_field = vmcs12->vm_entry_intr_info_field;
2166 	evmcs->vm_entry_exception_error_code =
2167 		vmcs12->vm_entry_exception_error_code;
2168 	evmcs->vm_entry_instruction_len = vmcs12->vm_entry_instruction_len;
2169 
2170 	evmcs->guest_rip = vmcs12->guest_rip;
2171 
2172 	evmcs->guest_bndcfgs = vmcs12->guest_bndcfgs;
2173 
2174 	return;
2175 #else /* CONFIG_KVM_HYPERV */
2176 	KVM_BUG_ON(1, vmx->vcpu.kvm);
2177 #endif /* CONFIG_KVM_HYPERV */
2178 }
2179 
2180 /*
2181  * This is an equivalent of the nested hypervisor executing the vmptrld
2182  * instruction.
2183  */
2184 static enum nested_evmptrld_status nested_vmx_handle_enlightened_vmptrld(
2185 	struct kvm_vcpu *vcpu, bool from_launch)
2186 {
2187 #ifdef CONFIG_KVM_HYPERV
2188 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2189 	bool evmcs_gpa_changed = false;
2190 	u64 evmcs_gpa;
2191 
2192 	if (likely(!guest_cpu_cap_has_evmcs(vcpu)))
2193 		return EVMPTRLD_DISABLED;
2194 
2195 	evmcs_gpa = nested_get_evmptr(vcpu);
2196 	if (!evmptr_is_valid(evmcs_gpa)) {
2197 		nested_release_evmcs(vcpu);
2198 		return EVMPTRLD_DISABLED;
2199 	}
2200 
2201 	if (unlikely(evmcs_gpa != vmx->nested.hv_evmcs_vmptr)) {
2202 		vmx->nested.current_vmptr = INVALID_GPA;
2203 
2204 		nested_release_evmcs(vcpu);
2205 
2206 		if (kvm_vcpu_map(vcpu, gpa_to_gfn(evmcs_gpa),
2207 				 &vmx->nested.hv_evmcs_map))
2208 			return EVMPTRLD_ERROR;
2209 
2210 		vmx->nested.hv_evmcs = vmx->nested.hv_evmcs_map.hva;
2211 
2212 		/*
2213 		 * Currently, KVM only supports eVMCS version 1
2214 		 * (== KVM_EVMCS_VERSION) and thus we expect guest to set this
2215 		 * value to first u32 field of eVMCS which should specify eVMCS
2216 		 * VersionNumber.
2217 		 *
2218 		 * Guest should be aware of supported eVMCS versions by host by
2219 		 * examining CPUID.0x4000000A.EAX[0:15]. Host userspace VMM is
2220 		 * expected to set this CPUID leaf according to the value
2221 		 * returned in vmcs_version from nested_enable_evmcs().
2222 		 *
2223 		 * However, it turns out that Microsoft Hyper-V fails to comply
2224 		 * to their own invented interface: When Hyper-V use eVMCS, it
2225 		 * just sets first u32 field of eVMCS to revision_id specified
2226 		 * in MSR_IA32_VMX_BASIC. Instead of used eVMCS version number
2227 		 * which is one of the supported versions specified in
2228 		 * CPUID.0x4000000A.EAX[0:15].
2229 		 *
2230 		 * To overcome Hyper-V bug, we accept here either a supported
2231 		 * eVMCS version or VMCS12 revision_id as valid values for first
2232 		 * u32 field of eVMCS.
2233 		 */
2234 		if ((vmx->nested.hv_evmcs->revision_id != KVM_EVMCS_VERSION) &&
2235 		    (vmx->nested.hv_evmcs->revision_id != VMCS12_REVISION)) {
2236 			nested_release_evmcs(vcpu);
2237 			return EVMPTRLD_VMFAIL;
2238 		}
2239 
2240 		vmx->nested.hv_evmcs_vmptr = evmcs_gpa;
2241 
2242 		evmcs_gpa_changed = true;
2243 		/*
2244 		 * Unlike normal vmcs12, enlightened vmcs12 is not fully
2245 		 * reloaded from guest's memory (read only fields, fields not
2246 		 * present in struct hv_enlightened_vmcs, ...). Make sure there
2247 		 * are no leftovers.
2248 		 */
2249 		if (from_launch) {
2250 			struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2251 			memset(vmcs12, 0, sizeof(*vmcs12));
2252 			vmcs12->hdr.revision_id = VMCS12_REVISION;
2253 		}
2254 
2255 	}
2256 
2257 	/*
2258 	 * Clean fields data can't be used on VMLAUNCH and when we switch
2259 	 * between different L2 guests as KVM keeps a single VMCS12 per L1.
2260 	 */
2261 	if (from_launch || evmcs_gpa_changed) {
2262 		vmx->nested.hv_evmcs->hv_clean_fields &=
2263 			~HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
2264 
2265 		vmx->nested.force_msr_bitmap_recalc = true;
2266 	}
2267 
2268 	return EVMPTRLD_SUCCEEDED;
2269 #else
2270 	return EVMPTRLD_DISABLED;
2271 #endif
2272 }
2273 
2274 void nested_sync_vmcs12_to_shadow(struct kvm_vcpu *vcpu)
2275 {
2276 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2277 
2278 	if (nested_vmx_is_evmptr12_valid(vmx))
2279 		copy_vmcs12_to_enlightened(vmx);
2280 	else
2281 		copy_vmcs12_to_shadow(vmx);
2282 
2283 	vmx->nested.need_vmcs12_to_shadow_sync = false;
2284 }
2285 
2286 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
2287 {
2288 	struct vcpu_vmx *vmx =
2289 		container_of(timer, struct vcpu_vmx, nested.preemption_timer);
2290 
2291 	vmx->nested.preemption_timer_expired = true;
2292 	kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
2293 	kvm_vcpu_kick(&vmx->vcpu);
2294 
2295 	return HRTIMER_NORESTART;
2296 }
2297 
2298 static u64 vmx_calc_preemption_timer_value(struct kvm_vcpu *vcpu)
2299 {
2300 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2301 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2302 
2303 	u64 l1_scaled_tsc = kvm_read_l1_tsc(vcpu, rdtsc()) >>
2304 			    VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
2305 
2306 	if (!vmx->nested.has_preemption_timer_deadline) {
2307 		vmx->nested.preemption_timer_deadline =
2308 			vmcs12->vmx_preemption_timer_value + l1_scaled_tsc;
2309 		vmx->nested.has_preemption_timer_deadline = true;
2310 	}
2311 	return vmx->nested.preemption_timer_deadline - l1_scaled_tsc;
2312 }
2313 
2314 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu,
2315 					u64 preemption_timeout)
2316 {
2317 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2318 
2319 	/*
2320 	 * A timer value of zero is architecturally guaranteed to cause
2321 	 * a VMExit prior to executing any instructions in the guest.
2322 	 */
2323 	if (preemption_timeout == 0) {
2324 		vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
2325 		return;
2326 	}
2327 
2328 	if (vcpu->arch.virtual_tsc_khz == 0)
2329 		return;
2330 
2331 	preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
2332 	preemption_timeout *= 1000000;
2333 	do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
2334 	hrtimer_start(&vmx->nested.preemption_timer,
2335 		      ktime_add_ns(ktime_get(), preemption_timeout),
2336 		      HRTIMER_MODE_ABS_PINNED);
2337 }
2338 
2339 static u64 nested_vmx_calc_efer(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2340 {
2341 	if (vmx->vcpu.arch.nested_run_pending &&
2342 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
2343 		return vmcs12->guest_ia32_efer;
2344 	else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
2345 		return vmx->vcpu.arch.efer | (EFER_LMA | EFER_LME);
2346 	else
2347 		return vmx->vcpu.arch.efer & ~(EFER_LMA | EFER_LME);
2348 }
2349 
2350 static void prepare_vmcs02_constant_state(struct vcpu_vmx *vmx)
2351 {
2352 	struct kvm *kvm = vmx->vcpu.kvm;
2353 
2354 	/*
2355 	 * If vmcs02 hasn't been initialized, set the constant vmcs02 state
2356 	 * according to L0's settings (vmcs12 is irrelevant here).  Host
2357 	 * fields that come from L0 and are not constant, e.g. HOST_CR3,
2358 	 * will be set as needed prior to VMLAUNCH/VMRESUME.
2359 	 */
2360 	if (vmx->nested.vmcs02_initialized)
2361 		return;
2362 	vmx->nested.vmcs02_initialized = true;
2363 
2364 	if (vmx->ve_info)
2365 		vmcs_write64(VE_INFORMATION_ADDRESS, __pa(vmx->ve_info));
2366 
2367 	/* All VMFUNCs are currently emulated through L0 vmexits.  */
2368 	if (cpu_has_vmx_vmfunc())
2369 		vmcs_write64(VM_FUNCTION_CONTROL, 0);
2370 
2371 	if (cpu_has_vmx_posted_intr())
2372 		vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
2373 
2374 	if (cpu_has_vmx_msr_bitmap())
2375 		vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
2376 
2377 	/*
2378 	 * PML is emulated for L2, but never enabled in hardware as the MMU
2379 	 * handles A/D emulation.  Disabling PML for L2 also avoids having to
2380 	 * deal with filtering out L2 GPAs from the buffer.
2381 	 */
2382 	if (enable_pml) {
2383 		vmcs_write64(PML_ADDRESS, 0);
2384 		vmcs_write16(GUEST_PML_INDEX, -1);
2385 	}
2386 
2387 	if (cpu_has_vmx_encls_vmexit())
2388 		vmcs_write64(ENCLS_EXITING_BITMAP, INVALID_GPA);
2389 
2390 	if (kvm_notify_vmexit_enabled(kvm))
2391 		vmcs_write32(NOTIFY_WINDOW, kvm->arch.notify_window);
2392 
2393 	/*
2394 	 * Set the MSR load/store lists to match L0's settings.  Only the
2395 	 * addresses are constant (for vmcs02), the counts can change based
2396 	 * on L2's behavior, e.g. switching to/from long mode.
2397 	 */
2398 	vmcs_write64(VM_EXIT_MSR_STORE_ADDR, __pa(vmx->msr_autostore.val));
2399 	vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
2400 	vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
2401 
2402 	vmx_set_constant_host_state(vmx);
2403 }
2404 
2405 static void prepare_vmcs02_early_rare(struct vcpu_vmx *vmx,
2406 				      struct vmcs12 *vmcs12)
2407 {
2408 	prepare_vmcs02_constant_state(vmx);
2409 
2410 	vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA);
2411 
2412 	/*
2413 	 * If VPID is disabled, then guest TLB accesses use VPID=0, i.e. the
2414 	 * same VPID as the host.  Emulate this behavior by using vpid01 for L2
2415 	 * if VPID is disabled in vmcs12.  Note, if VPID is disabled, VM-Enter
2416 	 * and VM-Exit are architecturally required to flush VPID=0, but *only*
2417 	 * VPID=0.  I.e. using vpid02 would be ok (so long as KVM emulates the
2418 	 * required flushes), but doing so would cause KVM to over-flush.  E.g.
2419 	 * if L1 runs L2 X with VPID12=1, then runs L2 Y with VPID12 disabled,
2420 	 * and then runs L2 X again, then KVM can and should retain TLB entries
2421 	 * for VPID12=1.
2422 	 */
2423 	if (enable_vpid) {
2424 		if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
2425 			vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
2426 		else
2427 			vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
2428 	}
2429 }
2430 
2431 static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct loaded_vmcs *vmcs01,
2432 				 struct vmcs12 *vmcs12)
2433 {
2434 	u32 exec_control;
2435 	u64 guest_efer = nested_vmx_calc_efer(vmx, vmcs12);
2436 
2437 	if (vmx->nested.dirty_vmcs12 || nested_vmx_is_evmptr12_valid(vmx))
2438 		prepare_vmcs02_early_rare(vmx, vmcs12);
2439 
2440 	/*
2441 	 * PIN CONTROLS
2442 	 */
2443 	exec_control = __pin_controls_get(vmcs01);
2444 	exec_control |= (vmcs12->pin_based_vm_exec_control &
2445 			 ~PIN_BASED_VMX_PREEMPTION_TIMER);
2446 
2447 	/* Posted interrupts setting is only taken from vmcs12.  */
2448 	vmx->nested.pi_pending = false;
2449 	if (nested_cpu_has_posted_intr(vmcs12)) {
2450 		vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
2451 	} else {
2452 		vmx->nested.posted_intr_nv = -1;
2453 		exec_control &= ~PIN_BASED_POSTED_INTR;
2454 	}
2455 	pin_controls_set(vmx, exec_control);
2456 
2457 	/*
2458 	 * EXEC CONTROLS
2459 	 */
2460 	exec_control = __exec_controls_get(vmcs01); /* L0's desires */
2461 	exec_control &= ~CPU_BASED_INTR_WINDOW_EXITING;
2462 	exec_control &= ~CPU_BASED_NMI_WINDOW_EXITING;
2463 	exec_control &= ~CPU_BASED_TPR_SHADOW;
2464 	exec_control |= vmcs12->cpu_based_vm_exec_control;
2465 
2466 	if (exec_control & CPU_BASED_TPR_SHADOW)
2467 		vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
2468 #ifdef CONFIG_X86_64
2469 	else
2470 		exec_control |= CPU_BASED_CR8_LOAD_EXITING |
2471 				CPU_BASED_CR8_STORE_EXITING;
2472 #endif
2473 
2474 	/*
2475 	 * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
2476 	 * for I/O port accesses.
2477 	 */
2478 	exec_control |= CPU_BASED_UNCOND_IO_EXITING;
2479 	exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
2480 
2481 	/*
2482 	 * This bit will be computed in nested_get_vmcs12_pages, because
2483 	 * we do not have access to L1's MSR bitmap yet.  For now, keep
2484 	 * the same bit as before, hoping to avoid multiple VMWRITEs that
2485 	 * only set/clear this bit.
2486 	 */
2487 	exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
2488 	exec_control |= exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS;
2489 
2490 	exec_controls_set(vmx, exec_control);
2491 
2492 	/*
2493 	 * SECONDARY EXEC CONTROLS
2494 	 */
2495 	if (cpu_has_secondary_exec_ctrls()) {
2496 		exec_control = __secondary_exec_controls_get(vmcs01);
2497 
2498 		/* Take the following fields only from vmcs12 */
2499 		exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2500 				  SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2501 				  SECONDARY_EXEC_ENABLE_INVPCID |
2502 				  SECONDARY_EXEC_ENABLE_RDTSCP |
2503 				  SECONDARY_EXEC_ENABLE_XSAVES |
2504 				  SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2505 				  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2506 				  SECONDARY_EXEC_APIC_REGISTER_VIRT |
2507 				  SECONDARY_EXEC_ENABLE_VMFUNC |
2508 				  SECONDARY_EXEC_MODE_BASED_EPT_EXEC |
2509 				  SECONDARY_EXEC_DESC);
2510 
2511 		if (nested_cpu_has(vmcs12,
2512 				   CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
2513 			exec_control |= vmcs12->secondary_vm_exec_control;
2514 
2515 		/* PML is emulated and never enabled in hardware for L2. */
2516 		exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
2517 
2518 		/* VMCS shadowing for L2 is emulated for now */
2519 		exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
2520 
2521 		/*
2522 		 * Preset *DT exiting when emulating UMIP, so that vmx_set_cr4()
2523 		 * will not have to rewrite the controls just for this bit.
2524 		 */
2525 		if (vmx_umip_emulated() && (vmcs12->guest_cr4 & X86_CR4_UMIP))
2526 			exec_control |= SECONDARY_EXEC_DESC;
2527 
2528 		if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
2529 			vmcs_write16(GUEST_INTR_STATUS,
2530 				vmcs12->guest_intr_status);
2531 
2532 		if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
2533 		    exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
2534 
2535 		if (exec_control & SECONDARY_EXEC_ENCLS_EXITING)
2536 			vmx_write_encls_bitmap(&vmx->vcpu, vmcs12);
2537 
2538 		secondary_exec_controls_set(vmx, exec_control);
2539 	}
2540 
2541 	/*
2542 	 * ENTRY CONTROLS
2543 	 *
2544 	 * vmcs12's VM_{ENTRY,EXIT}_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE
2545 	 * are emulated by vmx_set_efer() in prepare_vmcs02(), but speculate
2546 	 * on the related bits (if supported by the CPU) in the hope that
2547 	 * we can avoid VMWrites during vmx_set_efer().
2548 	 *
2549 	 * Similarly, take vmcs01's PERF_GLOBAL_CTRL in the hope that if KVM is
2550 	 * loading PERF_GLOBAL_CTRL via the VMCS for L1, then KVM will want to
2551 	 * do the same for L2.
2552 	 */
2553 	exec_control = __vm_entry_controls_get(vmcs01);
2554 	exec_control |= (vmcs12->vm_entry_controls &
2555 			 ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL);
2556 	exec_control &= ~(VM_ENTRY_IA32E_MODE | VM_ENTRY_LOAD_IA32_EFER);
2557 	if (cpu_has_load_ia32_efer()) {
2558 		if (guest_efer & EFER_LMA)
2559 			exec_control |= VM_ENTRY_IA32E_MODE;
2560 		if (guest_efer != kvm_host.efer)
2561 			exec_control |= VM_ENTRY_LOAD_IA32_EFER;
2562 	}
2563 	vm_entry_controls_set(vmx, exec_control);
2564 
2565 	/*
2566 	 * EXIT CONTROLS
2567 	 *
2568 	 * L2->L1 exit controls are emulated - the hardware exit is to L0 so
2569 	 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
2570 	 * bits may be modified by vmx_set_efer() in prepare_vmcs02().
2571 	 */
2572 	exec_control = __vm_exit_controls_get(vmcs01);
2573 	if (cpu_has_load_ia32_efer() && guest_efer != kvm_host.efer)
2574 		exec_control |= VM_EXIT_LOAD_IA32_EFER;
2575 	else
2576 		exec_control &= ~VM_EXIT_LOAD_IA32_EFER;
2577 	vm_exit_controls_set(vmx, exec_control);
2578 
2579 	/*
2580 	 * Interrupt/Exception Fields
2581 	 */
2582 	if (vmx->vcpu.arch.nested_run_pending) {
2583 		vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2584 			     vmcs12->vm_entry_intr_info_field);
2585 		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
2586 			     vmcs12->vm_entry_exception_error_code);
2587 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2588 			     vmcs12->vm_entry_instruction_len);
2589 		vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
2590 			     vmcs12->guest_interruptibility_info);
2591 		vmx->loaded_vmcs->nmi_known_unmasked =
2592 			!(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
2593 	} else {
2594 		vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
2595 	}
2596 }
2597 
2598 static void vmcs_read_cet_state(struct kvm_vcpu *vcpu, u64 *s_cet,
2599 				u64 *ssp, u64 *ssp_tbl)
2600 {
2601 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_IBT) ||
2602 	    guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
2603 		*s_cet = vmcs_readl(GUEST_S_CET);
2604 
2605 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK)) {
2606 		*ssp = vmcs_readl(GUEST_SSP);
2607 		*ssp_tbl = vmcs_readl(GUEST_INTR_SSP_TABLE);
2608 	}
2609 }
2610 
2611 static void vmcs_write_cet_state(struct kvm_vcpu *vcpu, u64 s_cet,
2612 				 u64 ssp, u64 ssp_tbl)
2613 {
2614 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_IBT) ||
2615 	    guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
2616 		vmcs_writel(GUEST_S_CET, s_cet);
2617 
2618 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK)) {
2619 		vmcs_writel(GUEST_SSP, ssp);
2620 		vmcs_writel(GUEST_INTR_SSP_TABLE, ssp_tbl);
2621 	}
2622 }
2623 
2624 static void prepare_vmcs02_rare(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2625 {
2626 	struct hv_enlightened_vmcs *hv_evmcs = nested_vmx_evmcs(vmx);
2627 
2628 	if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
2629 			   HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
2630 
2631 		vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
2632 		vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
2633 		vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
2634 		vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
2635 		vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
2636 		vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
2637 		vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
2638 		vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
2639 		vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
2640 		vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
2641 		vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
2642 		vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
2643 		vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
2644 		vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
2645 		vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
2646 		vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
2647 		vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
2648 		vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
2649 		vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
2650 		vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
2651 		vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
2652 		vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
2653 		vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
2654 		vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
2655 		vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
2656 		vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
2657 		vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
2658 		vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
2659 		vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
2660 		vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
2661 		vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
2662 		vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
2663 		vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
2664 		vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
2665 		vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
2666 		vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
2667 
2668 		vmx_segment_cache_clear(vmx);
2669 	}
2670 
2671 	if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
2672 			   HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1)) {
2673 		vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
2674 		vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
2675 			    vmcs12->guest_pending_dbg_exceptions);
2676 		vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
2677 		vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
2678 
2679 		if (kvm_mpx_supported() && vmx->vcpu.arch.nested_run_pending &&
2680 		    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
2681 			vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
2682 	}
2683 
2684 	if (nested_cpu_has_xsaves(vmcs12))
2685 		vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
2686 
2687 	/*
2688 	 * Whether page-faults are trapped is determined by a combination of
2689 	 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.  If L0
2690 	 * doesn't care about page faults then we should set all of these to
2691 	 * L1's desires. However, if L0 does care about (some) page faults, it
2692 	 * is not easy (if at all possible?) to merge L0 and L1's desires, we
2693 	 * simply ask to exit on each and every L2 page fault. This is done by
2694 	 * setting MASK=MATCH=0 and (see below) EB.PF=1.
2695 	 * Note that below we don't need special code to set EB.PF beyond the
2696 	 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
2697 	 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
2698 	 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
2699 	 */
2700 	if (vmx_need_pf_intercept(&vmx->vcpu)) {
2701 		/*
2702 		 * TODO: if both L0 and L1 need the same MASK and MATCH,
2703 		 * go ahead and use it?
2704 		 */
2705 		vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
2706 		vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
2707 	} else {
2708 		vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, vmcs12->page_fault_error_code_mask);
2709 		vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, vmcs12->page_fault_error_code_match);
2710 	}
2711 
2712 	if (cpu_has_vmx_apicv()) {
2713 		vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
2714 		vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
2715 		vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
2716 		vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
2717 	}
2718 
2719 	/*
2720 	 * If vmcs12 is configured to save TSC on exit via the auto-store list,
2721 	 * append the MSR to vmcs02's auto-store list so that KVM effectively
2722 	 * reads TSC at the time of VM-Exit from L2.  The saved value will be
2723 	 * propagated to vmcs12's list on nested VM-Exit.
2724 	 *
2725 	 * Don't increment the number of MSRs in the vCPU structure, as saving
2726 	 * TSC is specific to this particular incarnation of vmcb02, i.e. must
2727 	 * not bleed into vmcs01.
2728 	 */
2729 	if (nested_msr_store_list_has_msr(&vmx->vcpu, MSR_IA32_TSC) &&
2730 	    !WARN_ON_ONCE(vmx->msr_autostore.nr >= ARRAY_SIZE(vmx->msr_autostore.val))) {
2731 		vmx->nested.tsc_autostore_slot = vmx->msr_autostore.nr;
2732 		vmx->msr_autostore.val[vmx->msr_autostore.nr].index = MSR_IA32_TSC;
2733 
2734 		vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vmx->msr_autostore.nr + 1);
2735 	} else {
2736 		vmx->nested.tsc_autostore_slot = -1;
2737 		vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vmx->msr_autostore.nr);
2738 	}
2739 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
2740 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
2741 
2742 	if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_CET_STATE)
2743 		vmcs_write_cet_state(&vmx->vcpu, vmcs12->guest_s_cet,
2744 				     vmcs12->guest_ssp, vmcs12->guest_ssp_tbl);
2745 
2746 	set_cr4_guest_host_mask(vmx);
2747 }
2748 
2749 /*
2750  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
2751  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
2752  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
2753  * guest in a way that will both be appropriate to L1's requests, and our
2754  * needs. In addition to modifying the active vmcs (which is vmcs02), this
2755  * function also has additional necessary side-effects, like setting various
2756  * vcpu->arch fields.
2757  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
2758  * is assigned to entry_failure_code on failure.
2759  */
2760 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
2761 			  bool from_vmentry,
2762 			  enum vm_entry_failure_code *entry_failure_code)
2763 {
2764 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2765 	struct hv_enlightened_vmcs *evmcs = nested_vmx_evmcs(vmx);
2766 	bool load_guest_pdptrs_vmcs12 = false;
2767 
2768 	if (vmx->nested.dirty_vmcs12 || nested_vmx_is_evmptr12_valid(vmx)) {
2769 		prepare_vmcs02_rare(vmx, vmcs12);
2770 		vmx->nested.dirty_vmcs12 = false;
2771 
2772 		load_guest_pdptrs_vmcs12 = !nested_vmx_is_evmptr12_valid(vmx) ||
2773 			!(evmcs->hv_clean_fields & HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1);
2774 	}
2775 
2776 	if (vcpu->arch.nested_run_pending &&
2777 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
2778 		kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
2779 		vmx_guest_debugctl_write(vcpu, vmcs12->guest_ia32_debugctl &
2780 					       vmx_get_supported_debugctl(vcpu, false));
2781 	} else {
2782 		kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
2783 		vmx_guest_debugctl_write(vcpu, vmx->nested.pre_vmenter_debugctl);
2784 	}
2785 
2786 	if (!vcpu->arch.nested_run_pending ||
2787 	    !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_CET_STATE))
2788 		vmcs_write_cet_state(vcpu, vmx->nested.pre_vmenter_s_cet,
2789 				     vmx->nested.pre_vmenter_ssp,
2790 				     vmx->nested.pre_vmenter_ssp_tbl);
2791 
2792 	if (kvm_mpx_supported() && (!vcpu->arch.nested_run_pending ||
2793 	    !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)))
2794 		vmcs_write64(GUEST_BNDCFGS, vmx->nested.pre_vmenter_bndcfgs);
2795 	vmx_set_rflags(vcpu, vmcs12->guest_rflags);
2796 
2797 	/* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
2798 	 * bitwise-or of what L1 wants to trap for L2, and what we want to
2799 	 * trap. Note that CR0.TS also needs updating - we do this later.
2800 	 */
2801 	vmx_update_exception_bitmap(vcpu);
2802 	vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
2803 	vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2804 
2805 	if (vcpu->arch.nested_run_pending &&
2806 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
2807 		vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
2808 		vcpu->arch.pat = vmcs12->guest_ia32_pat;
2809 	} else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2810 		vmcs_write64(GUEST_IA32_PAT, vcpu->arch.pat);
2811 	}
2812 
2813 	vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2814 			vcpu->arch.l1_tsc_offset,
2815 			vmx_get_l2_tsc_offset(vcpu),
2816 			vmx_get_l2_tsc_multiplier(vcpu));
2817 
2818 	vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2819 			vcpu->arch.l1_tsc_scaling_ratio,
2820 			vmx_get_l2_tsc_multiplier(vcpu));
2821 
2822 	vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
2823 	if (kvm_caps.has_tsc_control)
2824 		vmcs_write64(TSC_MULTIPLIER, vcpu->arch.tsc_scaling_ratio);
2825 
2826 	nested_vmx_transition_tlb_flush(vcpu, vmcs12, true);
2827 
2828 	if (nested_cpu_has_ept(vmcs12))
2829 		nested_ept_init_mmu_context(vcpu);
2830 
2831 	/*
2832 	 * Override the CR0/CR4 read shadows after setting the effective guest
2833 	 * CR0/CR4.  The common helpers also set the shadows, but they don't
2834 	 * account for vmcs12's cr0/4_guest_host_mask.
2835 	 */
2836 	vmx_set_cr0(vcpu, vmcs12->guest_cr0);
2837 	vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
2838 
2839 	vmx_set_cr4(vcpu, vmcs12->guest_cr4);
2840 	vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
2841 
2842 	vcpu->arch.efer = nested_vmx_calc_efer(vmx, vmcs12);
2843 	/* Note: may modify VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
2844 	vmx_set_efer(vcpu, vcpu->arch.efer);
2845 
2846 	/*
2847 	 * Guest state is invalid and unrestricted guest is disabled,
2848 	 * which means L1 attempted VMEntry to L2 with invalid state.
2849 	 * Fail the VMEntry.
2850 	 *
2851 	 * However when force loading the guest state (SMM exit or
2852 	 * loading nested state after migration, it is possible to
2853 	 * have invalid guest state now, which will be later fixed by
2854 	 * restoring L2 register state
2855 	 */
2856 	if (CC(from_vmentry && !vmx_guest_state_valid(vcpu))) {
2857 		*entry_failure_code = ENTRY_FAIL_DEFAULT;
2858 		return -EINVAL;
2859 	}
2860 
2861 	/* Shadow page tables on either EPT or shadow page tables. */
2862 	if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
2863 				from_vmentry, entry_failure_code))
2864 		return -EINVAL;
2865 
2866 	/*
2867 	 * Immediately write vmcs02.GUEST_CR3.  It will be propagated to vmcs12
2868 	 * on nested VM-Exit, which can occur without actually running L2 and
2869 	 * thus without hitting vmx_load_mmu_pgd(), e.g. if L1 is entering L2 with
2870 	 * vmcs12.GUEST_ACTIVITYSTATE=HLT, in which case KVM will intercept the
2871 	 * transition to HLT instead of running L2.
2872 	 */
2873 	if (enable_ept)
2874 		vmcs_writel(GUEST_CR3, vmcs12->guest_cr3);
2875 
2876 	/* Late preparation of GUEST_PDPTRs now that EFER and CRs are set. */
2877 	if (load_guest_pdptrs_vmcs12 && nested_cpu_has_ept(vmcs12) &&
2878 	    is_pae_paging(vcpu)) {
2879 		vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
2880 		vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
2881 		vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
2882 		vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
2883 	}
2884 
2885 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2886 	    kvm_pmu_has_perf_global_ctrl(vcpu_to_pmu(vcpu)) &&
2887 	    WARN_ON_ONCE(__kvm_emulate_msr_write(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
2888 						 vmcs12->guest_ia32_perf_global_ctrl))) {
2889 		*entry_failure_code = ENTRY_FAIL_DEFAULT;
2890 		return -EINVAL;
2891 	}
2892 
2893 	kvm_rsp_write(vcpu, vmcs12->guest_rsp);
2894 	kvm_rip_write(vcpu, vmcs12->guest_rip);
2895 
2896 	/*
2897 	 * It was observed that genuine Hyper-V running in L1 doesn't reset
2898 	 * 'hv_clean_fields' by itself, it only sets the corresponding dirty
2899 	 * bits when it changes a field in eVMCS. Mark all fields as clean
2900 	 * here.
2901 	 */
2902 	if (nested_vmx_is_evmptr12_valid(vmx))
2903 		evmcs->hv_clean_fields |= HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
2904 
2905 	return 0;
2906 }
2907 
2908 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
2909 {
2910 	if (CC(!nested_cpu_has_nmi_exiting(vmcs12) &&
2911 	       nested_cpu_has_virtual_nmis(vmcs12)))
2912 		return -EINVAL;
2913 
2914 	if (CC(!nested_cpu_has_virtual_nmis(vmcs12) &&
2915 	       nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING)))
2916 		return -EINVAL;
2917 
2918 	return 0;
2919 }
2920 
2921 static bool nested_vmx_check_eptp(struct kvm_vcpu *vcpu, u64 new_eptp)
2922 {
2923 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2924 
2925 	/* Check for memory type validity */
2926 	switch (new_eptp & VMX_EPTP_MT_MASK) {
2927 	case VMX_EPTP_MT_UC:
2928 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT)))
2929 			return false;
2930 		break;
2931 	case VMX_EPTP_MT_WB:
2932 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT)))
2933 			return false;
2934 		break;
2935 	default:
2936 		return false;
2937 	}
2938 
2939 	/* Page-walk levels validity. */
2940 	switch (new_eptp & VMX_EPTP_PWL_MASK) {
2941 	case VMX_EPTP_PWL_5:
2942 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_PAGE_WALK_5_BIT)))
2943 			return false;
2944 		break;
2945 	case VMX_EPTP_PWL_4:
2946 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_PAGE_WALK_4_BIT)))
2947 			return false;
2948 		break;
2949 	default:
2950 		return false;
2951 	}
2952 
2953 	/* Reserved bits should not be set */
2954 	if (CC(!kvm_vcpu_is_legal_gpa(vcpu, new_eptp) || ((new_eptp >> 7) & 0x1f)))
2955 		return false;
2956 
2957 	/* AD, if set, should be supported */
2958 	if (new_eptp & VMX_EPTP_AD_ENABLE_BIT) {
2959 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT)))
2960 			return false;
2961 	}
2962 
2963 	return true;
2964 }
2965 
2966 /*
2967  * Checks related to VM-Execution Control Fields
2968  */
2969 static int nested_check_vm_execution_controls(struct kvm_vcpu *vcpu,
2970                                               struct vmcs12 *vmcs12)
2971 {
2972 	struct vcpu_vmx *vmx = to_vmx(vcpu);
2973 
2974 	if (CC(!vmx_control_verify(vmcs12->pin_based_vm_exec_control,
2975 				   vmx->nested.msrs.pinbased_ctls_low,
2976 				   vmx->nested.msrs.pinbased_ctls_high)) ||
2977 	    CC(!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
2978 				   vmx->nested.msrs.procbased_ctls_low,
2979 				   vmx->nested.msrs.procbased_ctls_high)))
2980 		return -EINVAL;
2981 
2982 	if (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
2983 	    CC(!vmx_control_verify(vmcs12->secondary_vm_exec_control,
2984 				   vmx->nested.msrs.secondary_ctls_low,
2985 				   vmx->nested.msrs.secondary_ctls_high)))
2986 		return -EINVAL;
2987 
2988 	if (CC(vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu)) ||
2989 	    nested_vmx_check_io_bitmap_controls(vcpu, vmcs12) ||
2990 	    nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12) ||
2991 	    nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12) ||
2992 	    nested_vmx_check_apic_access_controls(vcpu, vmcs12) ||
2993 	    nested_vmx_check_apicv_controls(vcpu, vmcs12) ||
2994 	    nested_vmx_check_nmi_controls(vmcs12) ||
2995 	    nested_vmx_check_pml_controls(vcpu, vmcs12) ||
2996 	    nested_vmx_check_unrestricted_guest_controls(vcpu, vmcs12) ||
2997 	    nested_vmx_check_mode_based_ept_exec_controls(vcpu, vmcs12) ||
2998 	    nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12) ||
2999 	    CC(nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id))
3000 		return -EINVAL;
3001 
3002 	if (!nested_cpu_has_preemption_timer(vmcs12) &&
3003 	    nested_cpu_has_save_preemption_timer(vmcs12))
3004 		return -EINVAL;
3005 
3006 	if (nested_cpu_has_ept(vmcs12) &&
3007 	    CC(!nested_vmx_check_eptp(vcpu, vmcs12->ept_pointer)))
3008 		return -EINVAL;
3009 
3010 	if (nested_cpu_has_vmfunc(vmcs12)) {
3011 		if (CC(vmcs12->vm_function_control &
3012 		       ~vmx->nested.msrs.vmfunc_controls))
3013 			return -EINVAL;
3014 
3015 		if (nested_cpu_has_eptp_switching(vmcs12)) {
3016 			if (CC(!nested_cpu_has_ept(vmcs12)) ||
3017 			    CC(!page_address_valid(vcpu, vmcs12->eptp_list_address)))
3018 				return -EINVAL;
3019 		}
3020 	}
3021 
3022 	if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING) &&
3023 	    CC(!vmcs12->tsc_multiplier))
3024 		return -EINVAL;
3025 
3026 	return 0;
3027 }
3028 
3029 /*
3030  * Checks related to VM-Exit Control Fields
3031  */
3032 static int nested_check_vm_exit_controls(struct kvm_vcpu *vcpu,
3033                                          struct vmcs12 *vmcs12)
3034 {
3035 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3036 
3037 	if (CC(!vmx_control_verify(vmcs12->vm_exit_controls,
3038 				    vmx->nested.msrs.exit_ctls_low,
3039 				    vmx->nested.msrs.exit_ctls_high)) ||
3040 	    CC(nested_vmx_check_exit_msr_switch_controls(vcpu, vmcs12)))
3041 		return -EINVAL;
3042 
3043 	return 0;
3044 }
3045 
3046 /*
3047  * Checks related to VM-Entry Control Fields
3048  */
3049 static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
3050 					  struct vmcs12 *vmcs12)
3051 {
3052 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3053 
3054 	if (CC(!vmx_control_verify(vmcs12->vm_entry_controls,
3055 				    vmx->nested.msrs.entry_ctls_low,
3056 				    vmx->nested.msrs.entry_ctls_high)))
3057 		return -EINVAL;
3058 
3059 	/*
3060 	 * From the Intel SDM, volume 3:
3061 	 * Fields relevant to VM-entry event injection must be set properly.
3062 	 * These fields are the VM-entry interruption-information field, the
3063 	 * VM-entry exception error code, and the VM-entry instruction length.
3064 	 */
3065 	if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
3066 		u32 intr_info = vmcs12->vm_entry_intr_info_field;
3067 		u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
3068 		u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
3069 		bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
3070 		bool urg = nested_cpu_has2(vmcs12,
3071 					   SECONDARY_EXEC_UNRESTRICTED_GUEST);
3072 		bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
3073 
3074 		/* VM-entry interruption-info field: interruption type */
3075 		if (CC(intr_type == INTR_TYPE_RESERVED) ||
3076 		    CC(intr_type == INTR_TYPE_OTHER_EVENT &&
3077 		       !nested_cpu_supports_monitor_trap_flag(vcpu)))
3078 			return -EINVAL;
3079 
3080 		/* VM-entry interruption-info field: vector */
3081 		if (CC(intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
3082 		    CC(intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
3083 		    CC(intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
3084 			return -EINVAL;
3085 
3086 		/*
3087 		 * Cannot deliver error code in real mode or if the interrupt
3088 		 * type is not hardware exception. For other cases, do the
3089 		 * consistency check only if the vCPU doesn't enumerate
3090 		 * VMX_BASIC_NO_HW_ERROR_CODE_CC.
3091 		 */
3092 		if (!prot_mode || intr_type != INTR_TYPE_HARD_EXCEPTION) {
3093 			if (CC(has_error_code))
3094 				return -EINVAL;
3095 		} else if (!nested_cpu_has_no_hw_errcode_cc(vcpu)) {
3096 			if (CC(has_error_code != x86_exception_has_error_code(vector)))
3097 				return -EINVAL;
3098 		}
3099 
3100 		/* VM-entry exception error code */
3101 		if (CC(has_error_code &&
3102 		       vmcs12->vm_entry_exception_error_code & GENMASK(31, 16)))
3103 			return -EINVAL;
3104 
3105 		/* VM-entry interruption-info field: reserved bits */
3106 		if (CC(intr_info & INTR_INFO_RESVD_BITS_MASK))
3107 			return -EINVAL;
3108 
3109 		/* VM-entry instruction length */
3110 		switch (intr_type) {
3111 		case INTR_TYPE_SOFT_EXCEPTION:
3112 		case INTR_TYPE_SOFT_INTR:
3113 		case INTR_TYPE_PRIV_SW_EXCEPTION:
3114 			if (CC(vmcs12->vm_entry_instruction_len > X86_MAX_INSTRUCTION_LENGTH) ||
3115 			    CC(vmcs12->vm_entry_instruction_len == 0 &&
3116 			    CC(!nested_cpu_has_zero_length_injection(vcpu))))
3117 				return -EINVAL;
3118 		}
3119 	}
3120 
3121 	if (nested_vmx_check_entry_msr_switch_controls(vcpu, vmcs12))
3122 		return -EINVAL;
3123 
3124 	return 0;
3125 }
3126 
3127 static int nested_vmx_check_controls(struct kvm_vcpu *vcpu,
3128 				     struct vmcs12 *vmcs12)
3129 {
3130 	if (nested_check_vm_execution_controls(vcpu, vmcs12) ||
3131 	    nested_check_vm_exit_controls(vcpu, vmcs12) ||
3132 	    nested_check_vm_entry_controls(vcpu, vmcs12))
3133 		return -EINVAL;
3134 
3135 #ifdef CONFIG_KVM_HYPERV
3136 	if (guest_cpu_cap_has_evmcs(vcpu))
3137 		return nested_evmcs_check_controls(vmcs12);
3138 #endif
3139 
3140 	return 0;
3141 }
3142 
3143 static int nested_vmx_check_address_space_size(struct kvm_vcpu *vcpu,
3144 				       struct vmcs12 *vmcs12)
3145 {
3146 #ifdef CONFIG_X86_64
3147 	if (CC(!!(vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) !=
3148 		!!(vcpu->arch.efer & EFER_LMA)))
3149 		return -EINVAL;
3150 #endif
3151 	return 0;
3152 }
3153 
3154 static bool is_l1_noncanonical_address_on_vmexit(u64 la, struct vmcs12 *vmcs12)
3155 {
3156 	/*
3157 	 * Check that the given linear address is canonical after a VM exit
3158 	 * from L2, based on HOST_CR4.LA57 value that will be loaded for L1.
3159 	 */
3160 	u8 l1_address_bits_on_exit = (vmcs12->host_cr4 & X86_CR4_LA57) ? 57 : 48;
3161 
3162 	return !__is_canonical_address(la, l1_address_bits_on_exit);
3163 }
3164 
3165 static int nested_vmx_check_cet_state_common(struct kvm_vcpu *vcpu, u64 s_cet,
3166 					     u64 ssp, u64 ssp_tbl)
3167 {
3168 	if (CC(!kvm_is_valid_u_s_cet(vcpu, s_cet)) || CC(!IS_ALIGNED(ssp, 4)) ||
3169 	    CC(is_noncanonical_msr_address(ssp_tbl, vcpu)))
3170 		return -EINVAL;
3171 
3172 	return 0;
3173 }
3174 
3175 static int nested_vmx_check_host_state(struct kvm_vcpu *vcpu,
3176 				       struct vmcs12 *vmcs12)
3177 {
3178 	bool ia32e = !!(vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE);
3179 
3180 	if (CC(!nested_host_cr0_valid(vcpu, vmcs12->host_cr0)) ||
3181 	    CC(!nested_host_cr4_valid(vcpu, vmcs12->host_cr4)) ||
3182 	    CC(!kvm_vcpu_is_legal_cr3(vcpu, vmcs12->host_cr3)))
3183 		return -EINVAL;
3184 
3185 	if (CC(vmcs12->host_cr4 & X86_CR4_CET && !(vmcs12->host_cr0 & X86_CR0_WP)))
3186 		return -EINVAL;
3187 
3188 	if (CC(is_noncanonical_msr_address(vmcs12->host_ia32_sysenter_esp, vcpu)) ||
3189 	    CC(is_noncanonical_msr_address(vmcs12->host_ia32_sysenter_eip, vcpu)))
3190 		return -EINVAL;
3191 
3192 	if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) &&
3193 	    CC(!kvm_pat_valid(vmcs12->host_ia32_pat)))
3194 		return -EINVAL;
3195 
3196 	if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) &&
3197 	    CC(!kvm_valid_perf_global_ctrl(vcpu_to_pmu(vcpu),
3198 					   vmcs12->host_ia32_perf_global_ctrl)))
3199 		return -EINVAL;
3200 
3201 	if (ia32e) {
3202 		if (CC(!(vmcs12->host_cr4 & X86_CR4_PAE)))
3203 			return -EINVAL;
3204 	} else {
3205 		if (CC(vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) ||
3206 		    CC(vmcs12->host_cr4 & X86_CR4_PCIDE) ||
3207 		    CC((vmcs12->host_rip) >> 32))
3208 			return -EINVAL;
3209 	}
3210 
3211 	if (CC(vmcs12->host_cs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
3212 	    CC(vmcs12->host_ss_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
3213 	    CC(vmcs12->host_ds_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
3214 	    CC(vmcs12->host_es_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
3215 	    CC(vmcs12->host_fs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
3216 	    CC(vmcs12->host_gs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
3217 	    CC(vmcs12->host_tr_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
3218 	    CC(vmcs12->host_cs_selector == 0) ||
3219 	    CC(vmcs12->host_tr_selector == 0) ||
3220 	    CC(vmcs12->host_ss_selector == 0 && !ia32e))
3221 		return -EINVAL;
3222 
3223 	if (CC(is_noncanonical_base_address(vmcs12->host_fs_base, vcpu)) ||
3224 	    CC(is_noncanonical_base_address(vmcs12->host_gs_base, vcpu)) ||
3225 	    CC(is_noncanonical_base_address(vmcs12->host_gdtr_base, vcpu)) ||
3226 	    CC(is_noncanonical_base_address(vmcs12->host_idtr_base, vcpu)) ||
3227 	    CC(is_noncanonical_base_address(vmcs12->host_tr_base, vcpu)) ||
3228 	    CC(is_l1_noncanonical_address_on_vmexit(vmcs12->host_rip, vmcs12)))
3229 		return -EINVAL;
3230 
3231 	/*
3232 	 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
3233 	 * IA32_EFER MSR must be 0 in the field for that register. In addition,
3234 	 * the values of the LMA and LME bits in the field must each be that of
3235 	 * the host address-space size VM-exit control.
3236 	 */
3237 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
3238 		if (CC(!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer)) ||
3239 		    CC(ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA)) ||
3240 		    CC(ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)))
3241 			return -EINVAL;
3242 	}
3243 
3244 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_CET_STATE) {
3245 		if (nested_vmx_check_cet_state_common(vcpu, vmcs12->host_s_cet,
3246 						      vmcs12->host_ssp,
3247 						      vmcs12->host_ssp_tbl))
3248 			return -EINVAL;
3249 
3250 		/*
3251 		 * IA32_S_CET and SSP must be canonical if the host will
3252 		 * enter 64-bit mode after VM-exit; otherwise, higher
3253 		 * 32-bits must be all 0s.
3254 		 */
3255 		if (ia32e) {
3256 			if (CC(is_noncanonical_msr_address(vmcs12->host_s_cet, vcpu)) ||
3257 			    CC(is_noncanonical_msr_address(vmcs12->host_ssp, vcpu)))
3258 				return -EINVAL;
3259 		} else {
3260 			if (CC(vmcs12->host_s_cet >> 32) || CC(vmcs12->host_ssp >> 32))
3261 				return -EINVAL;
3262 		}
3263 	}
3264 
3265 	return 0;
3266 }
3267 
3268 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
3269 					  struct vmcs12 *vmcs12)
3270 {
3271 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3272 	struct gfn_to_hva_cache *ghc = &vmx->nested.shadow_vmcs12_cache;
3273 	struct vmcs_hdr hdr;
3274 
3275 	if (vmcs12->vmcs_link_pointer == INVALID_GPA)
3276 		return 0;
3277 
3278 	if (CC(!page_address_valid(vcpu, vmcs12->vmcs_link_pointer)))
3279 		return -EINVAL;
3280 
3281 	if (ghc->gpa != vmcs12->vmcs_link_pointer &&
3282 	    CC(kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc,
3283 					 vmcs12->vmcs_link_pointer, VMCS12_SIZE)))
3284                 return -EINVAL;
3285 
3286 	if (CC(kvm_read_guest_offset_cached(vcpu->kvm, ghc, &hdr,
3287 					    offsetof(struct vmcs12, hdr),
3288 					    sizeof(hdr))))
3289 		return -EINVAL;
3290 
3291 	if (CC(hdr.revision_id != VMCS12_REVISION) ||
3292 	    CC(hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12)))
3293 		return -EINVAL;
3294 
3295 	return 0;
3296 }
3297 
3298 /*
3299  * Checks related to Guest Non-register State
3300  */
3301 static int nested_check_guest_non_reg_state(struct vmcs12 *vmcs12)
3302 {
3303 	if (CC(vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
3304 	       vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT &&
3305 	       vmcs12->guest_activity_state != GUEST_ACTIVITY_WAIT_SIPI))
3306 		return -EINVAL;
3307 
3308 	return 0;
3309 }
3310 
3311 static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,
3312 					struct vmcs12 *vmcs12,
3313 					enum vm_entry_failure_code *entry_failure_code)
3314 {
3315 	bool ia32e = !!(vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE);
3316 
3317 	*entry_failure_code = ENTRY_FAIL_DEFAULT;
3318 
3319 	if (CC(!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0)) ||
3320 	    CC(!nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4)))
3321 		return -EINVAL;
3322 
3323 	if (CC(vmcs12->guest_cr4 & X86_CR4_CET && !(vmcs12->guest_cr0 & X86_CR0_WP)))
3324 		return -EINVAL;
3325 
3326 	if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
3327 		u64 debugctl = vmcs12->guest_ia32_debugctl;
3328 
3329 		/*
3330 		 * FREEZE_IN_SMM is not virtualized, but allow L1 to set it in
3331 		 * vmcs12's DEBUGCTL under a quirk for backwards compatibility.
3332 		 * Note that the quirk only relaxes the consistency check.  The
3333 		 * vmcc02 bit is still under the control of the host.  In
3334 		 * particular, if a host administrator decides to clear the bit,
3335 		 * then L1 has no say in the matter.
3336 		 */
3337 		if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_VMCS12_ALLOW_FREEZE_IN_SMM))
3338 			debugctl &= ~DEBUGCTLMSR_FREEZE_IN_SMM;
3339 
3340 		if (CC(!kvm_dr7_valid(vmcs12->guest_dr7)) ||
3341 		    CC(!vmx_is_valid_debugctl(vcpu, debugctl, false)))
3342 			return -EINVAL;
3343 	}
3344 
3345 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) &&
3346 	    CC(!kvm_pat_valid(vmcs12->guest_ia32_pat)))
3347 		return -EINVAL;
3348 
3349 	if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
3350 		*entry_failure_code = ENTRY_FAIL_VMCS_LINK_PTR;
3351 		return -EINVAL;
3352 	}
3353 
3354 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) &&
3355 	    CC(!kvm_valid_perf_global_ctrl(vcpu_to_pmu(vcpu),
3356 					   vmcs12->guest_ia32_perf_global_ctrl)))
3357 		return -EINVAL;
3358 
3359 	if (CC((vmcs12->guest_cr0 & (X86_CR0_PG | X86_CR0_PE)) == X86_CR0_PG))
3360 		return -EINVAL;
3361 
3362 	if (CC(ia32e && !(vmcs12->guest_cr4 & X86_CR4_PAE)) ||
3363 	    CC(ia32e && !(vmcs12->guest_cr0 & X86_CR0_PG)))
3364 		return -EINVAL;
3365 
3366 	/*
3367 	 * If the load IA32_EFER VM-entry control is 1, the following checks
3368 	 * are performed on the field for the IA32_EFER MSR:
3369 	 * - Bits reserved in the IA32_EFER MSR must be 0.
3370 	 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
3371 	 *   the IA-32e mode guest VM-exit control. It must also be identical
3372 	 *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
3373 	 *   CR0.PG) is 1.
3374 	 */
3375 	if (vcpu->arch.nested_run_pending &&
3376 	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
3377 		if (CC(!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer)) ||
3378 		    CC(ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA)) ||
3379 		    CC(((vmcs12->guest_cr0 & X86_CR0_PG) &&
3380 		     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))))
3381 			return -EINVAL;
3382 	}
3383 
3384 	if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
3385 	    (CC(is_noncanonical_msr_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu)) ||
3386 	     CC((vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD))))
3387 		return -EINVAL;
3388 
3389 	if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_CET_STATE) {
3390 		if (nested_vmx_check_cet_state_common(vcpu, vmcs12->guest_s_cet,
3391 						      vmcs12->guest_ssp,
3392 						      vmcs12->guest_ssp_tbl))
3393 			return -EINVAL;
3394 
3395 		/*
3396 		 * Guest SSP must have 63:N bits identical, rather than
3397 		 * be canonical (i.e., 63:N-1 bits identical), where N is
3398 		 * the CPU's maximum linear-address width. Similar to
3399 		 * is_noncanonical_msr_address(), use the host's
3400 		 * linear-address width.
3401 		 */
3402 		if (CC(!__is_canonical_address(vmcs12->guest_ssp, max_host_virt_addr_bits() + 1)))
3403 			return -EINVAL;
3404 	}
3405 
3406 	if (nested_check_guest_non_reg_state(vmcs12))
3407 		return -EINVAL;
3408 
3409 	return 0;
3410 }
3411 
3412 #ifdef CONFIG_KVM_HYPERV
3413 static bool nested_get_evmcs_page(struct kvm_vcpu *vcpu)
3414 {
3415 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3416 
3417 	/*
3418 	 * hv_evmcs may end up being not mapped after migration (when
3419 	 * L2 was running), map it here to make sure vmcs12 changes are
3420 	 * properly reflected.
3421 	 */
3422 	if (guest_cpu_cap_has_evmcs(vcpu) &&
3423 	    vmx->nested.hv_evmcs_vmptr == EVMPTR_MAP_PENDING) {
3424 		enum nested_evmptrld_status evmptrld_status =
3425 			nested_vmx_handle_enlightened_vmptrld(vcpu, false);
3426 
3427 		if (evmptrld_status == EVMPTRLD_VMFAIL ||
3428 		    evmptrld_status == EVMPTRLD_ERROR)
3429 			return false;
3430 
3431 		/*
3432 		 * Post migration VMCS12 always provides the most actual
3433 		 * information, copy it to eVMCS upon entry.
3434 		 */
3435 		vmx->nested.need_vmcs12_to_shadow_sync = true;
3436 	}
3437 
3438 	return true;
3439 }
3440 #endif
3441 
3442 static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
3443 {
3444 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3445 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3446 	struct kvm_host_map *map;
3447 
3448 	if (!vcpu->arch.pdptrs_from_userspace &&
3449 	    !nested_cpu_has_ept(vmcs12) && is_pae_paging(vcpu)) {
3450 		/*
3451 		 * Reload the guest's PDPTRs since after a migration
3452 		 * the guest CR3 might be restored prior to setting the nested
3453 		 * state which can lead to a load of wrong PDPTRs.
3454 		 */
3455 		if (CC(!load_pdptrs(vcpu, vcpu->arch.cr3)))
3456 			return false;
3457 	}
3458 
3459 
3460 	if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
3461 		map = &vmx->nested.apic_access_page_map;
3462 
3463 		if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->apic_access_addr), map)) {
3464 			vmcs_write64(APIC_ACCESS_ADDR, pfn_to_hpa(map->pfn));
3465 		} else {
3466 			pr_debug_ratelimited("%s: no backing for APIC-access address in vmcs12\n",
3467 					     __func__);
3468 			return false;
3469 		}
3470 	}
3471 
3472 	if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
3473 		map = &vmx->nested.virtual_apic_map;
3474 
3475 		if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->virtual_apic_page_addr), map)) {
3476 			vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, pfn_to_hpa(map->pfn));
3477 		} else if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING) &&
3478 		           nested_cpu_has(vmcs12, CPU_BASED_CR8_STORE_EXITING) &&
3479 			   !nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
3480 			/*
3481 			 * The processor will never use the TPR shadow, simply
3482 			 * clear the bit from the execution control.  Such a
3483 			 * configuration is useless, but it happens in tests.
3484 			 * For any other configuration, failing the vm entry is
3485 			 * _not_ what the processor does but it's basically the
3486 			 * only possibility we have.
3487 			 */
3488 			exec_controls_clearbit(vmx, CPU_BASED_TPR_SHADOW);
3489 		} else {
3490 			/*
3491 			 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR to
3492 			 * force VM-Entry to fail.
3493 			 */
3494 			vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, INVALID_GPA);
3495 		}
3496 	}
3497 
3498 	if (nested_cpu_has_posted_intr(vmcs12)) {
3499 		map = &vmx->nested.pi_desc_map;
3500 
3501 		if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->posted_intr_desc_addr), map)) {
3502 			vmx->nested.pi_desc =
3503 				(struct pi_desc *)(((void *)map->hva) +
3504 				offset_in_page(vmcs12->posted_intr_desc_addr));
3505 			vmcs_write64(POSTED_INTR_DESC_ADDR,
3506 				     pfn_to_hpa(map->pfn) + offset_in_page(vmcs12->posted_intr_desc_addr));
3507 		} else {
3508 			/*
3509 			 * Defer the KVM_INTERNAL_EXIT until KVM tries to
3510 			 * access the contents of the VMCS12 posted interrupt
3511 			 * descriptor. (Note that KVM may do this when it
3512 			 * should not, per the architectural specification.)
3513 			 */
3514 			vmx->nested.pi_desc = NULL;
3515 			pin_controls_clearbit(vmx, PIN_BASED_POSTED_INTR);
3516 		}
3517 	}
3518 	if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
3519 		exec_controls_setbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3520 	else
3521 		exec_controls_clearbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3522 
3523 	return true;
3524 }
3525 
3526 static bool vmx_get_nested_state_pages(struct kvm_vcpu *vcpu)
3527 {
3528 #ifdef CONFIG_KVM_HYPERV
3529 	/*
3530 	 * Note: nested_get_evmcs_page() also updates 'vp_assist_page' copy
3531 	 * in 'struct kvm_vcpu_hv' in case eVMCS is in use, this is mandatory
3532 	 * to make nested_evmcs_l2_tlb_flush_enabled() work correctly post
3533 	 * migration.
3534 	 */
3535 	if (!nested_get_evmcs_page(vcpu)) {
3536 		pr_debug_ratelimited("%s: enlightened vmptrld failed\n",
3537 				     __func__);
3538 		return false;
3539 	}
3540 #endif
3541 
3542 	if (is_guest_mode(vcpu) && !nested_get_vmcs12_pages(vcpu))
3543 		return false;
3544 
3545 	return true;
3546 }
3547 
3548 static int nested_vmx_write_pml_buffer(struct kvm_vcpu *vcpu, gpa_t gpa)
3549 {
3550 	struct vmcs12 *vmcs12;
3551 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3552 	gpa_t dst;
3553 
3554 	if (WARN_ON_ONCE(!is_guest_mode(vcpu)))
3555 		return 0;
3556 
3557 	if (WARN_ON_ONCE(vmx->nested.pml_full))
3558 		return 1;
3559 
3560 	/*
3561 	 * Check if PML is enabled for the nested guest. Whether eptp bit 6 is
3562 	 * set is already checked as part of A/D emulation.
3563 	 */
3564 	vmcs12 = get_vmcs12(vcpu);
3565 	if (!nested_cpu_has_pml(vmcs12))
3566 		return 0;
3567 
3568 	if (vmcs12->guest_pml_index >= PML_LOG_NR_ENTRIES) {
3569 		vmx->nested.pml_full = true;
3570 		return 1;
3571 	}
3572 
3573 	gpa &= ~0xFFFull;
3574 	dst = vmcs12->pml_address + sizeof(u64) * vmcs12->guest_pml_index;
3575 
3576 	if (kvm_write_guest_page(vcpu->kvm, gpa_to_gfn(dst), &gpa,
3577 				 offset_in_page(dst), sizeof(gpa)))
3578 		return 0;
3579 
3580 	vmcs12->guest_pml_index--;
3581 
3582 	return 0;
3583 }
3584 
3585 /*
3586  * Intel's VMX Instruction Reference specifies a common set of prerequisites
3587  * for running VMX instructions (except VMXON, whose prerequisites are
3588  * slightly different). It also specifies what exception to inject otherwise.
3589  * Note that many of these exceptions have priority over VM exits, so they
3590  * don't have to be checked again here.
3591  */
3592 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
3593 {
3594 	if (!to_vmx(vcpu)->nested.vmxon) {
3595 		kvm_queue_exception(vcpu, UD_VECTOR);
3596 		return 0;
3597 	}
3598 
3599 	if (vmx_get_cpl(vcpu)) {
3600 		kvm_inject_gp(vcpu, 0);
3601 		return 0;
3602 	}
3603 
3604 	return 1;
3605 }
3606 
3607 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
3608 				   struct vmcs12 *vmcs12);
3609 
3610 /*
3611  * If from_vmentry is false, this is being called from state restore (either RSM
3612  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
3613  *
3614  * Returns:
3615  *	NVMX_VMENTRY_SUCCESS: Entered VMX non-root mode
3616  *	NVMX_VMENTRY_VMFAIL:  Consistency check VMFail
3617  *	NVMX_VMENTRY_VMEXIT:  Consistency check VMExit
3618  *	NVMX_VMENTRY_KVM_INTERNAL_ERROR: KVM internal error
3619  */
3620 enum nvmx_vmentry_status nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
3621 							bool from_vmentry)
3622 {
3623 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3624 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3625 	enum vm_entry_failure_code entry_failure_code;
3626 	union vmx_exit_reason exit_reason = {
3627 		.basic = EXIT_REASON_INVALID_STATE,
3628 		.failed_vmentry = 1,
3629 	};
3630 	u32 failed_index;
3631 
3632 	trace_kvm_nested_vmenter(kvm_rip_read(vcpu),
3633 				 vmx->nested.current_vmptr,
3634 				 vmcs12->guest_rip,
3635 				 vmcs12->guest_intr_status,
3636 				 vmcs12->vm_entry_intr_info_field,
3637 				 vmcs12->secondary_vm_exec_control & SECONDARY_EXEC_ENABLE_EPT,
3638 				 vmcs12->ept_pointer,
3639 				 vmcs12->guest_cr3,
3640 				 KVM_ISA_VMX);
3641 
3642 	kvm_service_local_tlb_flush_requests(vcpu);
3643 
3644 	if (!vcpu->arch.nested_run_pending ||
3645 	    !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
3646 		vmx->nested.pre_vmenter_debugctl = vmx_guest_debugctl_read();
3647 	if (kvm_mpx_supported() &&
3648 	    (!vcpu->arch.nested_run_pending ||
3649 	     !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)))
3650 		vmx->nested.pre_vmenter_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
3651 
3652 	if (!vcpu->arch.nested_run_pending ||
3653 	    !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_CET_STATE))
3654 		vmcs_read_cet_state(vcpu, &vmx->nested.pre_vmenter_s_cet,
3655 				    &vmx->nested.pre_vmenter_ssp,
3656 				    &vmx->nested.pre_vmenter_ssp_tbl);
3657 
3658 	/*
3659 	 * Stash L1's CR3, so that in the event of a "late" VM-Fail, i.e. a
3660 	 * VM-Fail detected by hardware but not KVM, KVM can unwind its
3661 	 * software model to the pre-VM-Entry host state.  When EPT is
3662 	 * disabled, GUEST_CR3 holds KVM's shadow CR3, not L1's "real" CR3,
3663 	 * and so simply restoring from vmcs01.GUEST_CR3 would corrupt
3664 	 * vcpu->arch.cr3.
3665 	 */
3666 	vmx->nested.pre_vmenter_cr3 = kvm_read_cr3(vcpu);
3667 
3668 	vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
3669 
3670 	prepare_vmcs02_early(vmx, &vmx->vmcs01, vmcs12);
3671 
3672 	if (from_vmentry) {
3673 		if (unlikely(!nested_get_vmcs12_pages(vcpu))) {
3674 			vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3675 			return NVMX_VMENTRY_KVM_INTERNAL_ERROR;
3676 		}
3677 
3678 		if (nested_vmx_check_guest_state(vcpu, vmcs12,
3679 						 &entry_failure_code)) {
3680 			exit_reason.basic = EXIT_REASON_INVALID_STATE;
3681 			vmcs12->exit_qualification = entry_failure_code;
3682 			goto vmentry_fail_vmexit;
3683 		}
3684 	}
3685 
3686 	enter_guest_mode(vcpu);
3687 
3688 	if (prepare_vmcs02(vcpu, vmcs12, from_vmentry, &entry_failure_code)) {
3689 		exit_reason.basic = EXIT_REASON_INVALID_STATE;
3690 		vmcs12->exit_qualification = entry_failure_code;
3691 		goto vmentry_fail_vmexit_guest_mode;
3692 	}
3693 
3694 	if (from_vmentry) {
3695 		failed_index = nested_vmx_load_msr(vcpu,
3696 						   vmcs12->vm_entry_msr_load_addr,
3697 						   vmcs12->vm_entry_msr_load_count);
3698 		if (failed_index) {
3699 			exit_reason.basic = EXIT_REASON_MSR_LOAD_FAIL;
3700 			vmcs12->exit_qualification = failed_index;
3701 			goto vmentry_fail_vmexit_guest_mode;
3702 		}
3703 	} else {
3704 		/*
3705 		 * The MMU is not initialized to point at the right entities yet and
3706 		 * "get pages" would need to read data from the guest (i.e. we will
3707 		 * need to perform gpa to hpa translation). Request a call
3708 		 * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
3709 		 * have already been set at vmentry time and should not be reset.
3710 		 */
3711 		kvm_make_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
3712 	}
3713 
3714 	/*
3715 	 * Re-evaluate pending events if L1 had a pending IRQ/NMI/INIT/SIPI
3716 	 * when it executed VMLAUNCH/VMRESUME, as entering non-root mode can
3717 	 * effectively unblock various events, e.g. INIT/SIPI cause VM-Exit
3718 	 * unconditionally.  Take care to pull data from vmcs01 as appropriate,
3719 	 * e.g. when checking for interrupt windows, as vmcs02 is now loaded.
3720 	 */
3721 	if ((__exec_controls_get(&vmx->vmcs01) & (CPU_BASED_INTR_WINDOW_EXITING |
3722 						  CPU_BASED_NMI_WINDOW_EXITING)) ||
3723 	    kvm_apic_has_pending_init_or_sipi(vcpu) ||
3724 	    kvm_apic_has_interrupt(vcpu))
3725 		kvm_make_request(KVM_REQ_EVENT, vcpu);
3726 
3727 	/*
3728 	 * Do not start the preemption timer hrtimer until after we know
3729 	 * we are successful, so that only nested_vmx_vmexit needs to cancel
3730 	 * the timer.
3731 	 */
3732 	vmx->nested.preemption_timer_expired = false;
3733 	if (nested_cpu_has_preemption_timer(vmcs12)) {
3734 		u64 timer_value = vmx_calc_preemption_timer_value(vcpu);
3735 		vmx_start_preemption_timer(vcpu, timer_value);
3736 	}
3737 
3738 	/*
3739 	 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
3740 	 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
3741 	 * returned as far as L1 is concerned. It will only return (and set
3742 	 * the success flag) when L2 exits (see nested_vmx_vmexit()).
3743 	 */
3744 	return NVMX_VMENTRY_SUCCESS;
3745 
3746 	/*
3747 	 * A failed consistency check that leads to a VMExit during L1's
3748 	 * VMEnter to L2 is a variation of a normal VMexit, as explained in
3749 	 * 26.7 "VM-entry failures during or after loading guest state".
3750 	 */
3751 vmentry_fail_vmexit_guest_mode:
3752 	if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
3753 		vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
3754 
3755 	/*
3756 	 * Handle any TLB flush requests that were queued for L2 if KVM made it
3757 	 * far enough along to switch to L2 context.  Note, loading host state
3758 	 * will generate any flushes for L1 required by VM-Exit.
3759 	 */
3760 	kvm_service_local_tlb_flush_requests(vcpu);
3761 
3762 	leave_guest_mode(vcpu);
3763 
3764 vmentry_fail_vmexit:
3765 	vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3766 
3767 	if (!from_vmentry)
3768 		return NVMX_VMENTRY_VMEXIT;
3769 
3770 	nested_put_vmcs12_pages(vcpu);
3771 
3772 	load_vmcs12_host_state(vcpu, vmcs12);
3773 	vmcs12->vm_exit_reason = exit_reason.full;
3774 	if (enable_shadow_vmcs || nested_vmx_is_evmptr12_valid(vmx))
3775 		vmx->nested.need_vmcs12_to_shadow_sync = true;
3776 	return NVMX_VMENTRY_VMEXIT;
3777 }
3778 
3779 /*
3780  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
3781  * for running an L2 nested guest.
3782  */
3783 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
3784 {
3785 	struct vmcs12 *vmcs12;
3786 	enum nvmx_vmentry_status status;
3787 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3788 	u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
3789 	enum nested_evmptrld_status evmptrld_status;
3790 
3791 	if (!nested_vmx_check_permission(vcpu))
3792 		return 1;
3793 
3794 	evmptrld_status = nested_vmx_handle_enlightened_vmptrld(vcpu, launch);
3795 	if (evmptrld_status == EVMPTRLD_ERROR) {
3796 		kvm_queue_exception(vcpu, UD_VECTOR);
3797 		return 1;
3798 	}
3799 
3800 	kvm_pmu_branch_retired(vcpu);
3801 
3802 	if (CC(evmptrld_status == EVMPTRLD_VMFAIL))
3803 		return nested_vmx_failInvalid(vcpu);
3804 
3805 	if (CC(!nested_vmx_is_evmptr12_valid(vmx) &&
3806 	       vmx->nested.current_vmptr == INVALID_GPA))
3807 		return nested_vmx_failInvalid(vcpu);
3808 
3809 	vmcs12 = get_vmcs12(vcpu);
3810 
3811 	/*
3812 	 * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
3813 	 * that there *is* a valid VMCS pointer, RFLAGS.CF is set
3814 	 * rather than RFLAGS.ZF, and no error number is stored to the
3815 	 * VM-instruction error field.
3816 	 */
3817 	if (CC(vmcs12->hdr.shadow_vmcs))
3818 		return nested_vmx_failInvalid(vcpu);
3819 
3820 	if (nested_vmx_is_evmptr12_valid(vmx)) {
3821 		struct hv_enlightened_vmcs *evmcs = nested_vmx_evmcs(vmx);
3822 
3823 		copy_enlightened_to_vmcs12(vmx, evmcs->hv_clean_fields);
3824 		/* Enlightened VMCS doesn't have launch state */
3825 		vmcs12->launch_state = !launch;
3826 	} else if (enable_shadow_vmcs) {
3827 		copy_shadow_to_vmcs12(vmx);
3828 	}
3829 
3830 	/*
3831 	 * The nested entry process starts with enforcing various prerequisites
3832 	 * on vmcs12 as required by the Intel SDM, and act appropriately when
3833 	 * they fail: As the SDM explains, some conditions should cause the
3834 	 * instruction to fail, while others will cause the instruction to seem
3835 	 * to succeed, but return an EXIT_REASON_INVALID_STATE.
3836 	 * To speed up the normal (success) code path, we should avoid checking
3837 	 * for misconfigurations which will anyway be caught by the processor
3838 	 * when using the merged vmcs02.
3839 	 */
3840 	if (CC(interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS))
3841 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
3842 
3843 	if (CC(vmcs12->launch_state == launch))
3844 		return nested_vmx_fail(vcpu,
3845 			launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
3846 			       : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
3847 
3848 	if (nested_vmx_check_controls(vcpu, vmcs12))
3849 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3850 
3851 	if (nested_vmx_check_address_space_size(vcpu, vmcs12))
3852 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
3853 
3854 	if (nested_vmx_check_host_state(vcpu, vmcs12))
3855 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
3856 
3857 	/*
3858 	 * We're finally done with prerequisite checking, and can start with
3859 	 * the nested entry.
3860 	 */
3861 	vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING;
3862 	vmx->nested.has_preemption_timer_deadline = false;
3863 	status = nested_vmx_enter_non_root_mode(vcpu, true);
3864 	if (unlikely(status != NVMX_VMENTRY_SUCCESS))
3865 		goto vmentry_failed;
3866 
3867 	/* Hide L1D cache contents from the nested guest.  */
3868 	kvm_request_l1tf_flush_l1d();
3869 
3870 	/*
3871 	 * Must happen outside of nested_vmx_enter_non_root_mode() as it will
3872 	 * also be used as part of restoring nVMX state for
3873 	 * snapshot restore (migration).
3874 	 *
3875 	 * In this flow, it is assumed that vmcs12 cache was
3876 	 * transferred as part of captured nVMX state and should
3877 	 * therefore not be read from guest memory (which may not
3878 	 * exist on destination host yet).
3879 	 */
3880 	nested_cache_shadow_vmcs12(vcpu, vmcs12);
3881 
3882 	switch (vmcs12->guest_activity_state) {
3883 	case GUEST_ACTIVITY_HLT:
3884 		/*
3885 		 * If we're entering a halted L2 vcpu and the L2 vcpu won't be
3886 		 * awakened by event injection or by an NMI-window VM-exit or
3887 		 * by an interrupt-window VM-exit, halt the vcpu.
3888 		 */
3889 		if (!(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) &&
3890 		    !nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING) &&
3891 		    !(nested_cpu_has(vmcs12, CPU_BASED_INTR_WINDOW_EXITING) &&
3892 		      (vmcs12->guest_rflags & X86_EFLAGS_IF))) {
3893 			vcpu->arch.nested_run_pending = 0;
3894 			return kvm_emulate_halt_noskip(vcpu);
3895 		}
3896 		break;
3897 	case GUEST_ACTIVITY_WAIT_SIPI:
3898 		vcpu->arch.nested_run_pending = 0;
3899 		kvm_set_mp_state(vcpu, KVM_MP_STATE_INIT_RECEIVED);
3900 		break;
3901 	default:
3902 		break;
3903 	}
3904 
3905 	return 1;
3906 
3907 vmentry_failed:
3908 	vcpu->arch.nested_run_pending = 0;
3909 	if (status == NVMX_VMENTRY_KVM_INTERNAL_ERROR) {
3910 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3911 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3912 		vcpu->run->internal.ndata = 0;
3913 		return 0;
3914 	}
3915 	if (status == NVMX_VMENTRY_VMEXIT)
3916 		return 1;
3917 	WARN_ON_ONCE(status != NVMX_VMENTRY_VMFAIL);
3918 	return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3919 }
3920 
3921 /*
3922  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
3923  * because L2 may have changed some cr0 bits directly (CR0_GUEST_HOST_MASK).
3924  * This function returns the new value we should put in vmcs12.guest_cr0.
3925  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
3926  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
3927  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
3928  *     didn't trap the bit, because if L1 did, so would L0).
3929  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
3930  *     been modified by L2, and L1 knows it. So just leave the old value of
3931  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
3932  *     isn't relevant, because if L0 traps this bit it can set it to anything.
3933  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
3934  *     changed these bits, and therefore they need to be updated, but L0
3935  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
3936  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
3937  */
3938 static inline unsigned long
3939 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3940 {
3941 	return
3942 	/*1*/	(vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
3943 	/*2*/	(vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
3944 	/*3*/	(vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
3945 			vcpu->arch.cr0_guest_owned_bits));
3946 }
3947 
3948 static inline unsigned long
3949 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3950 {
3951 	return
3952 	/*1*/	(vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
3953 	/*2*/	(vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
3954 	/*3*/	(vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
3955 			vcpu->arch.cr4_guest_owned_bits));
3956 }
3957 
3958 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
3959 				      struct vmcs12 *vmcs12,
3960 				      u32 vm_exit_reason, u32 exit_intr_info)
3961 {
3962 	u32 idt_vectoring;
3963 	unsigned int nr;
3964 
3965 	/*
3966 	 * Per the SDM, VM-Exits due to double and triple faults are never
3967 	 * considered to occur during event delivery, even if the double/triple
3968 	 * fault is the result of an escalating vectoring issue.
3969 	 *
3970 	 * Note, the SDM qualifies the double fault behavior with "The original
3971 	 * event results in a double-fault exception".  It's unclear why the
3972 	 * qualification exists since exits due to double fault can occur only
3973 	 * while vectoring a different exception (injected events are never
3974 	 * subject to interception), i.e. there's _always_ an original event.
3975 	 *
3976 	 * The SDM also uses NMI as a confusing example for the "original event
3977 	 * causes the VM exit directly" clause.  NMI isn't special in any way,
3978 	 * the same rule applies to all events that cause an exit directly.
3979 	 * NMI is an odd choice for the example because NMIs can only occur on
3980 	 * instruction boundaries, i.e. they _can't_ occur during vectoring.
3981 	 */
3982 	if ((u16)vm_exit_reason == EXIT_REASON_TRIPLE_FAULT ||
3983 	    ((u16)vm_exit_reason == EXIT_REASON_EXCEPTION_NMI &&
3984 	     is_double_fault(exit_intr_info))) {
3985 		vmcs12->idt_vectoring_info_field = 0;
3986 	} else if (vcpu->arch.exception.injected) {
3987 		nr = vcpu->arch.exception.vector;
3988 		idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
3989 
3990 		if (kvm_exception_is_soft(nr)) {
3991 			vmcs12->vm_exit_instruction_len =
3992 				vcpu->arch.event_exit_inst_len;
3993 			idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
3994 		} else
3995 			idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
3996 
3997 		if (vcpu->arch.exception.has_error_code) {
3998 			idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
3999 			vmcs12->idt_vectoring_error_code =
4000 				vcpu->arch.exception.error_code;
4001 		}
4002 
4003 		vmcs12->idt_vectoring_info_field = idt_vectoring;
4004 	} else if (vcpu->arch.nmi_injected) {
4005 		vmcs12->idt_vectoring_info_field =
4006 			INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
4007 	} else if (vcpu->arch.interrupt.injected) {
4008 		nr = vcpu->arch.interrupt.nr;
4009 		idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
4010 
4011 		if (vcpu->arch.interrupt.soft) {
4012 			idt_vectoring |= INTR_TYPE_SOFT_INTR;
4013 			vmcs12->vm_entry_instruction_len =
4014 				vcpu->arch.event_exit_inst_len;
4015 		} else
4016 			idt_vectoring |= INTR_TYPE_EXT_INTR;
4017 
4018 		vmcs12->idt_vectoring_info_field = idt_vectoring;
4019 	} else {
4020 		vmcs12->idt_vectoring_info_field = 0;
4021 	}
4022 }
4023 
4024 static int vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
4025 {
4026 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4027 	int max_irr;
4028 	void *vapic_page;
4029 	u16 status;
4030 
4031 	if (!vmx->nested.pi_pending)
4032 		return 0;
4033 
4034 	if (!vmx->nested.pi_desc)
4035 		goto mmio_needed;
4036 
4037 	vmx->nested.pi_pending = false;
4038 
4039 	if (!pi_test_and_clear_on(vmx->nested.pi_desc))
4040 		return 0;
4041 
4042 	max_irr = pi_find_highest_vector(vmx->nested.pi_desc);
4043 	if (max_irr > 0) {
4044 		vapic_page = vmx->nested.virtual_apic_map.hva;
4045 		if (!vapic_page)
4046 			goto mmio_needed;
4047 
4048 		__kvm_apic_update_irr(vmx->nested.pi_desc->pir,
4049 			vapic_page, &max_irr);
4050 		status = vmcs_read16(GUEST_INTR_STATUS);
4051 		if ((u8)max_irr > ((u8)status & 0xff)) {
4052 			status &= ~0xff;
4053 			status |= (u8)max_irr;
4054 			vmcs_write16(GUEST_INTR_STATUS, status);
4055 		}
4056 	}
4057 
4058 	kvm_vcpu_map_mark_dirty(vcpu, &vmx->nested.virtual_apic_map);
4059 	kvm_vcpu_map_mark_dirty(vcpu, &vmx->nested.pi_desc_map);
4060 	return 0;
4061 
4062 mmio_needed:
4063 	kvm_handle_memory_failure(vcpu, X86EMUL_IO_NEEDED, NULL);
4064 	return -ENXIO;
4065 }
4066 
4067 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu)
4068 {
4069 	struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
4070 	u32 intr_info = ex->vector | INTR_INFO_VALID_MASK;
4071 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4072 	unsigned long exit_qual;
4073 
4074 	if (ex->has_payload) {
4075 		exit_qual = ex->payload;
4076 	} else if (ex->vector == PF_VECTOR) {
4077 		exit_qual = vcpu->arch.cr2;
4078 	} else if (ex->vector == DB_VECTOR) {
4079 		exit_qual = vcpu->arch.dr6;
4080 		exit_qual &= ~DR6_BT;
4081 		exit_qual ^= DR6_ACTIVE_LOW;
4082 	} else {
4083 		exit_qual = 0;
4084 	}
4085 
4086 	/*
4087 	 * Unlike AMD's Paged Real Mode, which reports an error code on #PF
4088 	 * VM-Exits even if the CPU is in Real Mode, Intel VMX never sets the
4089 	 * "has error code" flags on VM-Exit if the CPU is in Real Mode.
4090 	 */
4091 	if (ex->has_error_code && is_protmode(vcpu)) {
4092 		/*
4093 		 * Intel CPUs do not generate error codes with bits 31:16 set,
4094 		 * and more importantly VMX disallows setting bits 31:16 in the
4095 		 * injected error code for VM-Entry.  Drop the bits to mimic
4096 		 * hardware and avoid inducing failure on nested VM-Entry if L1
4097 		 * chooses to inject the exception back to L2.  AMD CPUs _do_
4098 		 * generate "full" 32-bit error codes, so KVM allows userspace
4099 		 * to inject exception error codes with bits 31:16 set.
4100 		 */
4101 		vmcs12->vm_exit_intr_error_code = (u16)ex->error_code;
4102 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
4103 	}
4104 
4105 	if (kvm_exception_is_soft(ex->vector))
4106 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
4107 	else
4108 		intr_info |= INTR_TYPE_HARD_EXCEPTION;
4109 
4110 	if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
4111 	    vmx_get_nmi_mask(vcpu))
4112 		intr_info |= INTR_INFO_UNBLOCK_NMI;
4113 
4114 	nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
4115 }
4116 
4117 /*
4118  * Returns true if a debug trap is (likely) pending delivery.  Infer the class
4119  * of a #DB (trap-like vs. fault-like) from the exception payload (to-be-DR6).
4120  * Using the payload is flawed because code breakpoints (fault-like) and data
4121  * breakpoints (trap-like) set the same bits in DR6 (breakpoint detected), i.e.
4122  * this will return false positives if a to-be-injected code breakpoint #DB is
4123  * pending (from KVM's perspective, but not "pending" across an instruction
4124  * boundary).  ICEBP, a.k.a. INT1, is also not reflected here even though it
4125  * too is trap-like.
4126  *
4127  * KVM "works" despite these flaws as ICEBP isn't currently supported by the
4128  * emulator, Monitor Trap Flag is not marked pending on intercepted #DBs (the
4129  * #DB has already happened), and MTF isn't marked pending on code breakpoints
4130  * from the emulator (because such #DBs are fault-like and thus don't trigger
4131  * actions that fire on instruction retire).
4132  */
4133 static unsigned long vmx_get_pending_dbg_trap(struct kvm_queued_exception *ex)
4134 {
4135 	if (!ex->pending || ex->vector != DB_VECTOR)
4136 		return 0;
4137 
4138 	/* General Detect #DBs are always fault-like. */
4139 	return ex->payload & ~DR6_BD;
4140 }
4141 
4142 /*
4143  * Returns true if there's a pending #DB exception that is lower priority than
4144  * a pending Monitor Trap Flag VM-Exit.  TSS T-flag #DBs are not emulated by
4145  * KVM, but could theoretically be injected by userspace.  Note, this code is
4146  * imperfect, see above.
4147  */
4148 static bool vmx_is_low_priority_db_trap(struct kvm_queued_exception *ex)
4149 {
4150 	return vmx_get_pending_dbg_trap(ex) & ~DR6_BT;
4151 }
4152 
4153 /*
4154  * Certain VM-exits set the 'pending debug exceptions' field to indicate a
4155  * recognized #DB (data or single-step) that has yet to be delivered. Since KVM
4156  * represents these debug traps with a payload that is said to be compatible
4157  * with the 'pending debug exceptions' field, write the payload to the VMCS
4158  * field if a VM-exit is delivered before the debug trap.
4159  */
4160 static void nested_vmx_update_pending_dbg(struct kvm_vcpu *vcpu)
4161 {
4162 	unsigned long pending_dbg;
4163 
4164 	pending_dbg = vmx_get_pending_dbg_trap(&vcpu->arch.exception);
4165 	if (pending_dbg)
4166 		vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, pending_dbg);
4167 }
4168 
4169 static bool nested_vmx_preemption_timer_pending(struct kvm_vcpu *vcpu)
4170 {
4171 	return nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
4172 	       to_vmx(vcpu)->nested.preemption_timer_expired;
4173 }
4174 
4175 static bool vmx_has_nested_events(struct kvm_vcpu *vcpu, bool for_injection)
4176 {
4177 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4178 	void *vapic = vmx->nested.virtual_apic_map.hva;
4179 	int max_irr, vppr;
4180 
4181 	if (nested_vmx_preemption_timer_pending(vcpu) ||
4182 	    vmx->nested.mtf_pending)
4183 		return true;
4184 
4185 	/*
4186 	 * Virtual Interrupt Delivery doesn't require manual injection.  Either
4187 	 * the interrupt is already in GUEST_RVI and will be recognized by CPU
4188 	 * at VM-Entry, or there is a KVM_REQ_EVENT pending and KVM will move
4189 	 * the interrupt from the PIR to RVI prior to entering the guest.
4190 	 */
4191 	if (for_injection)
4192 		return false;
4193 
4194 	if (!nested_cpu_has_vid(get_vmcs12(vcpu)) ||
4195 	    __vmx_interrupt_blocked(vcpu))
4196 		return false;
4197 
4198 	if (!vapic)
4199 		return false;
4200 
4201 	vppr = *((u32 *)(vapic + APIC_PROCPRI));
4202 
4203 	max_irr = vmx_get_rvi();
4204 	if ((max_irr & 0xf0) > (vppr & 0xf0))
4205 		return true;
4206 
4207 	if (vmx->nested.pi_pending && vmx->nested.pi_desc &&
4208 	    pi_test_on(vmx->nested.pi_desc)) {
4209 		max_irr = pi_find_highest_vector(vmx->nested.pi_desc);
4210 		if (max_irr > 0 && (max_irr & 0xf0) > (vppr & 0xf0))
4211 			return true;
4212 	}
4213 
4214 	return false;
4215 }
4216 
4217 /*
4218  * Per the Intel SDM's table "Priority Among Concurrent Events", with minor
4219  * edits to fill in missing examples, e.g. #DB due to split-lock accesses,
4220  * and less minor edits to splice in the priority of VMX Non-Root specific
4221  * events, e.g. MTF and NMI/INTR-window exiting.
4222  *
4223  * 1 Hardware Reset and Machine Checks
4224  *	- RESET
4225  *	- Machine Check
4226  *
4227  * 2 Trap on Task Switch
4228  *	- T flag in TSS is set (on task switch)
4229  *
4230  * 3 External Hardware Interventions
4231  *	- FLUSH
4232  *	- STOPCLK
4233  *	- SMI
4234  *	- INIT
4235  *
4236  * 3.5 Monitor Trap Flag (MTF) VM-exit[1]
4237  *
4238  * 4 Traps on Previous Instruction
4239  *	- Breakpoints
4240  *	- Trap-class Debug Exceptions (#DB due to TF flag set, data/I-O
4241  *	  breakpoint, or #DB due to a split-lock access)
4242  *
4243  * 4.3	VMX-preemption timer expired VM-exit
4244  *
4245  * 4.6	NMI-window exiting VM-exit[2]
4246  *
4247  * 5 Nonmaskable Interrupts (NMI)
4248  *
4249  * 5.5 Interrupt-window exiting VM-exit and Virtual-interrupt delivery
4250  *
4251  * 6 Maskable Hardware Interrupts
4252  *
4253  * 7 Code Breakpoint Fault
4254  *
4255  * 8 Faults from Fetching Next Instruction
4256  *	- Code-Segment Limit Violation
4257  *	- Code Page Fault
4258  *	- Control protection exception (missing ENDBRANCH at target of indirect
4259  *					call or jump)
4260  *
4261  * 9 Faults from Decoding Next Instruction
4262  *	- Instruction length > 15 bytes
4263  *	- Invalid Opcode
4264  *	- Coprocessor Not Available
4265  *
4266  *10 Faults on Executing Instruction
4267  *	- Overflow
4268  *	- Bound error
4269  *	- Invalid TSS
4270  *	- Segment Not Present
4271  *	- Stack fault
4272  *	- General Protection
4273  *	- Data Page Fault
4274  *	- Alignment Check
4275  *	- x86 FPU Floating-point exception
4276  *	- SIMD floating-point exception
4277  *	- Virtualization exception
4278  *	- Control protection exception
4279  *
4280  * [1] Per the "Monitor Trap Flag" section: System-management interrupts (SMIs),
4281  *     INIT signals, and higher priority events take priority over MTF VM exits.
4282  *     MTF VM exits take priority over debug-trap exceptions and lower priority
4283  *     events.
4284  *
4285  * [2] Debug-trap exceptions and higher priority events take priority over VM exits
4286  *     caused by the VMX-preemption timer.  VM exits caused by the VMX-preemption
4287  *     timer take priority over VM exits caused by the "NMI-window exiting"
4288  *     VM-execution control and lower priority events.
4289  *
4290  * [3] Debug-trap exceptions and higher priority events take priority over VM exits
4291  *     caused by "NMI-window exiting".  VM exits caused by this control take
4292  *     priority over non-maskable interrupts (NMIs) and lower priority events.
4293  *
4294  * [4] Virtual-interrupt delivery has the same priority as that of VM exits due to
4295  *     the 1-setting of the "interrupt-window exiting" VM-execution control.  Thus,
4296  *     non-maskable interrupts (NMIs) and higher priority events take priority over
4297  *     delivery of a virtual interrupt; delivery of a virtual interrupt takes
4298  *     priority over external interrupts and lower priority events.
4299  */
4300 static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
4301 {
4302 	struct kvm_lapic *apic = vcpu->arch.apic;
4303 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4304 	/*
4305 	 * Only a pending nested run blocks a pending exception.  If there is a
4306 	 * previously injected event, the pending exception occurred while said
4307 	 * event was being delivered and thus needs to be handled.
4308 	 */
4309 	bool block_nested_exceptions = vcpu->arch.nested_run_pending;
4310 	/*
4311 	 * Events that don't require injection, i.e. that are virtualized by
4312 	 * hardware, aren't blocked by a pending VM-Enter as KVM doesn't need
4313 	 * to regain control in order to deliver the event, and hardware will
4314 	 * handle event ordering, e.g. with respect to injected exceptions.
4315 	 *
4316 	 * But, new events (not exceptions) are only recognized at instruction
4317 	 * boundaries.  If an event needs reinjection, then KVM is handling a
4318 	 * VM-Exit that occurred _during_ instruction execution; new events,
4319 	 * irrespective of whether or not they're injected, are blocked until
4320 	 * the instruction completes.
4321 	 */
4322 	bool block_non_injected_events = kvm_event_needs_reinjection(vcpu);
4323 	/*
4324 	 * Inject events are blocked by nested VM-Enter, as KVM is responsible
4325 	 * for managing priority between concurrent events, i.e. KVM needs to
4326 	 * wait until after VM-Enter completes to deliver injected events.
4327 	 */
4328 	bool block_nested_events = block_nested_exceptions ||
4329 				   block_non_injected_events;
4330 
4331 	if (lapic_in_kernel(vcpu) &&
4332 		test_bit(KVM_APIC_INIT, &apic->pending_events)) {
4333 		if (block_nested_events)
4334 			return -EBUSY;
4335 		nested_vmx_update_pending_dbg(vcpu);
4336 		clear_bit(KVM_APIC_INIT, &apic->pending_events);
4337 		if (vcpu->arch.mp_state != KVM_MP_STATE_INIT_RECEIVED)
4338 			nested_vmx_vmexit(vcpu, EXIT_REASON_INIT_SIGNAL, 0, 0);
4339 
4340 		/* MTF is discarded if the vCPU is in WFS. */
4341 		vmx->nested.mtf_pending = false;
4342 		return 0;
4343 	}
4344 
4345 	if (lapic_in_kernel(vcpu) &&
4346 	    test_bit(KVM_APIC_SIPI, &apic->pending_events)) {
4347 		if (block_nested_events)
4348 			return -EBUSY;
4349 
4350 		clear_bit(KVM_APIC_SIPI, &apic->pending_events);
4351 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
4352 			nested_vmx_vmexit(vcpu, EXIT_REASON_SIPI_SIGNAL, 0,
4353 						apic->sipi_vector & 0xFFUL);
4354 			return 0;
4355 		}
4356 		/* Fallthrough, the SIPI is completely ignored. */
4357 	}
4358 
4359 	/*
4360 	 * Process exceptions that are higher priority than Monitor Trap Flag:
4361 	 * fault-like exceptions, TSS T flag #DB (not emulated by KVM, but
4362 	 * could theoretically come in from userspace), and ICEBP (INT1).
4363 	 *
4364 	 * TODO: SMIs have higher priority than MTF and trap-like #DBs (except
4365 	 * for TSS T flag #DBs).  KVM also doesn't save/restore pending MTF
4366 	 * across SMI/RSM as it should; that needs to be addressed in order to
4367 	 * prioritize SMI over MTF and trap-like #DBs.
4368 	 */
4369 	if (vcpu->arch.exception_vmexit.pending &&
4370 	    !vmx_is_low_priority_db_trap(&vcpu->arch.exception_vmexit)) {
4371 		if (block_nested_exceptions)
4372 			return -EBUSY;
4373 
4374 		nested_vmx_inject_exception_vmexit(vcpu);
4375 		return 0;
4376 	}
4377 
4378 	if (vcpu->arch.exception.pending &&
4379 	    !vmx_is_low_priority_db_trap(&vcpu->arch.exception)) {
4380 		if (block_nested_exceptions)
4381 			return -EBUSY;
4382 		goto no_vmexit;
4383 	}
4384 
4385 	if (vmx->nested.mtf_pending) {
4386 		if (block_nested_events)
4387 			return -EBUSY;
4388 		nested_vmx_update_pending_dbg(vcpu);
4389 		nested_vmx_vmexit(vcpu, EXIT_REASON_MONITOR_TRAP_FLAG, 0, 0);
4390 		return 0;
4391 	}
4392 
4393 	if (vcpu->arch.exception_vmexit.pending) {
4394 		if (block_nested_exceptions)
4395 			return -EBUSY;
4396 
4397 		nested_vmx_inject_exception_vmexit(vcpu);
4398 		return 0;
4399 	}
4400 
4401 	if (vcpu->arch.exception.pending) {
4402 		if (block_nested_exceptions)
4403 			return -EBUSY;
4404 		goto no_vmexit;
4405 	}
4406 
4407 	if (nested_vmx_preemption_timer_pending(vcpu)) {
4408 		if (block_nested_events)
4409 			return -EBUSY;
4410 		nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
4411 		return 0;
4412 	}
4413 
4414 	if (vcpu->arch.smi_pending && !is_smm(vcpu)) {
4415 		if (block_nested_events)
4416 			return -EBUSY;
4417 		goto no_vmexit;
4418 	}
4419 
4420 	if (vcpu->arch.nmi_pending && !vmx_nmi_blocked(vcpu)) {
4421 		if (block_nested_events)
4422 			return -EBUSY;
4423 		if (!nested_exit_on_nmi(vcpu))
4424 			goto no_vmexit;
4425 
4426 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
4427 				  NMI_VECTOR | INTR_TYPE_NMI_INTR |
4428 				  INTR_INFO_VALID_MASK, 0);
4429 		/*
4430 		 * The NMI-triggered VM exit counts as injection:
4431 		 * clear this one and block further NMIs.
4432 		 */
4433 		vcpu->arch.nmi_pending = 0;
4434 		vmx_set_nmi_mask(vcpu, true);
4435 		return 0;
4436 	}
4437 
4438 	if (kvm_cpu_has_interrupt(vcpu) && !vmx_interrupt_blocked(vcpu)) {
4439 		int irq;
4440 
4441 		if (!nested_exit_on_intr(vcpu)) {
4442 			if (block_nested_events)
4443 				return -EBUSY;
4444 
4445 			goto no_vmexit;
4446 		}
4447 
4448 		if (!nested_exit_intr_ack_set(vcpu)) {
4449 			if (block_nested_events)
4450 				return -EBUSY;
4451 
4452 			nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
4453 			return 0;
4454 		}
4455 
4456 		irq = kvm_cpu_get_extint(vcpu);
4457 		if (irq != -1) {
4458 			if (block_nested_events)
4459 				return -EBUSY;
4460 
4461 			nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT,
4462 					  INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR | irq, 0);
4463 			return 0;
4464 		}
4465 
4466 		irq = kvm_apic_has_interrupt(vcpu);
4467 		if (unlikely(irq < 0)) {
4468 			kvm_warn_on_lost_irq(vcpu);
4469 			goto no_vmexit;
4470 		}
4471 
4472 		/*
4473 		 * If the IRQ is L2's PI notification vector, process posted
4474 		 * interrupts for L2 instead of injecting VM-Exit, as the
4475 		 * detection/morphing architecturally occurs when the IRQ is
4476 		 * delivered to the CPU.  Note, only interrupts that are routed
4477 		 * through the local APIC trigger posted interrupt processing,
4478 		 * and enabling posted interrupts requires ACK-on-exit.
4479 		 */
4480 		if (irq == vmx->nested.posted_intr_nv) {
4481 			/*
4482 			 * Nested posted interrupts are delivered via RVI, i.e.
4483 			 * aren't injected by KVM, and so can be queued even if
4484 			 * manual event injection is disallowed.
4485 			 */
4486 			if (block_non_injected_events)
4487 				return -EBUSY;
4488 
4489 			vmx->nested.pi_pending = true;
4490 			kvm_apic_clear_irr(vcpu, irq);
4491 			goto no_vmexit;
4492 		}
4493 
4494 		if (block_nested_events)
4495 			return -EBUSY;
4496 
4497 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT,
4498 				  INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR | irq, 0);
4499 
4500 		/*
4501 		 * ACK the interrupt _after_ emulating VM-Exit, as the IRQ must
4502 		 * be marked as in-service in vmcs01.GUEST_INTERRUPT_STATUS.SVI
4503 		 * if APICv is active.
4504 		 */
4505 		kvm_apic_ack_interrupt(vcpu, irq);
4506 		return 0;
4507 	}
4508 
4509 no_vmexit:
4510 	return vmx_complete_nested_posted_interrupt(vcpu);
4511 }
4512 
4513 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
4514 {
4515 	ktime_t remaining =
4516 		hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
4517 	u64 value;
4518 
4519 	if (ktime_to_ns(remaining) <= 0)
4520 		return 0;
4521 
4522 	value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
4523 	do_div(value, 1000000);
4524 	return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
4525 }
4526 
4527 static bool is_vmcs12_ext_field(unsigned long field)
4528 {
4529 	switch (field) {
4530 	case GUEST_ES_SELECTOR:
4531 	case GUEST_CS_SELECTOR:
4532 	case GUEST_SS_SELECTOR:
4533 	case GUEST_DS_SELECTOR:
4534 	case GUEST_FS_SELECTOR:
4535 	case GUEST_GS_SELECTOR:
4536 	case GUEST_LDTR_SELECTOR:
4537 	case GUEST_TR_SELECTOR:
4538 	case GUEST_ES_LIMIT:
4539 	case GUEST_CS_LIMIT:
4540 	case GUEST_SS_LIMIT:
4541 	case GUEST_DS_LIMIT:
4542 	case GUEST_FS_LIMIT:
4543 	case GUEST_GS_LIMIT:
4544 	case GUEST_LDTR_LIMIT:
4545 	case GUEST_TR_LIMIT:
4546 	case GUEST_GDTR_LIMIT:
4547 	case GUEST_IDTR_LIMIT:
4548 	case GUEST_ES_AR_BYTES:
4549 	case GUEST_DS_AR_BYTES:
4550 	case GUEST_FS_AR_BYTES:
4551 	case GUEST_GS_AR_BYTES:
4552 	case GUEST_LDTR_AR_BYTES:
4553 	case GUEST_TR_AR_BYTES:
4554 	case GUEST_ES_BASE:
4555 	case GUEST_CS_BASE:
4556 	case GUEST_SS_BASE:
4557 	case GUEST_DS_BASE:
4558 	case GUEST_FS_BASE:
4559 	case GUEST_GS_BASE:
4560 	case GUEST_LDTR_BASE:
4561 	case GUEST_TR_BASE:
4562 	case GUEST_GDTR_BASE:
4563 	case GUEST_IDTR_BASE:
4564 	case GUEST_PENDING_DBG_EXCEPTIONS:
4565 	case GUEST_BNDCFGS:
4566 		return true;
4567 	default:
4568 		break;
4569 	}
4570 
4571 	return false;
4572 }
4573 
4574 static void sync_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
4575 				       struct vmcs12 *vmcs12)
4576 {
4577 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4578 
4579 	vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
4580 	vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
4581 	vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
4582 	vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
4583 	vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
4584 	vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
4585 	vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
4586 	vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
4587 	vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
4588 	vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
4589 	vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
4590 	vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
4591 	vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
4592 	vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
4593 	vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
4594 	vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
4595 	vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
4596 	vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
4597 	vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
4598 	vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
4599 	vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
4600 	vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
4601 	vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
4602 	vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
4603 	vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
4604 	vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
4605 	vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
4606 	vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
4607 	vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
4608 	vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
4609 	vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
4610 	vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
4611 	vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
4612 	vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
4613 	vmcs12->guest_pending_dbg_exceptions =
4614 		vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
4615 
4616 	vmx->nested.need_sync_vmcs02_to_vmcs12_rare = false;
4617 }
4618 
4619 static void copy_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
4620 				       struct vmcs12 *vmcs12)
4621 {
4622 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4623 	int cpu;
4624 
4625 	if (!vmx->nested.need_sync_vmcs02_to_vmcs12_rare)
4626 		return;
4627 
4628 
4629 	WARN_ON_ONCE(vmx->loaded_vmcs != &vmx->vmcs01);
4630 
4631 	cpu = get_cpu();
4632 	vmx->loaded_vmcs = &vmx->nested.vmcs02;
4633 	vmx_vcpu_load_vmcs(vcpu, cpu);
4634 
4635 	sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
4636 
4637 	vmx->loaded_vmcs = &vmx->vmcs01;
4638 	vmx_vcpu_load_vmcs(vcpu, cpu);
4639 	put_cpu();
4640 }
4641 
4642 /*
4643  * Update the guest state fields of vmcs12 to reflect changes that
4644  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
4645  * VM-entry controls is also updated, since this is really a guest
4646  * state bit.)
4647  */
4648 static void sync_vmcs02_to_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
4649 {
4650 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4651 
4652 	if (nested_vmx_is_evmptr12_valid(vmx))
4653 		sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
4654 
4655 	vmx->nested.need_sync_vmcs02_to_vmcs12_rare =
4656 		!nested_vmx_is_evmptr12_valid(vmx);
4657 
4658 	vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
4659 	vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
4660 
4661 	vmcs12->guest_rsp = kvm_rsp_read(vcpu);
4662 	vmcs12->guest_rip = kvm_rip_read(vcpu);
4663 	vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
4664 
4665 	vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
4666 	vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
4667 
4668 	vmcs12->guest_interruptibility_info =
4669 		vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
4670 
4671 	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
4672 		vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
4673 	else if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4674 		vmcs12->guest_activity_state = GUEST_ACTIVITY_WAIT_SIPI;
4675 	else
4676 		vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
4677 
4678 	if (nested_cpu_has_preemption_timer(vmcs12) &&
4679 	    vmcs12->vm_exit_controls & VM_EXIT_SAVE_VMX_PREEMPTION_TIMER &&
4680 	    !vcpu->arch.nested_run_pending)
4681 		vmcs12->vmx_preemption_timer_value =
4682 			vmx_get_preemption_timer_value(vcpu);
4683 
4684 	/*
4685 	 * In some cases (usually, nested EPT), L2 is allowed to change its
4686 	 * own CR3 without exiting. If it has changed it, we must keep it.
4687 	 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
4688 	 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
4689 	 *
4690 	 * Additionally, restore L2's PDPTR to vmcs12.
4691 	 */
4692 	if (enable_ept) {
4693 		vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
4694 		if (nested_cpu_has_ept(vmcs12) && is_pae_paging(vcpu)) {
4695 			vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
4696 			vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
4697 			vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
4698 			vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
4699 		}
4700 	}
4701 
4702 	vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
4703 
4704 	if (nested_cpu_has_vid(vmcs12))
4705 		vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
4706 
4707 	vmcs12->vm_entry_controls =
4708 		(vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
4709 		(vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
4710 
4711 	/*
4712 	 * Note!  Save DR7, but intentionally don't grab DEBUGCTL from vmcs02.
4713 	 * Writes to DEBUGCTL that aren't intercepted by L1 are immediately
4714 	 * propagated to vmcs12 (see vmx_set_msr()), as the value loaded into
4715 	 * vmcs02 doesn't strictly track vmcs12.
4716 	 */
4717 	if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS)
4718 		vmcs12->guest_dr7 = vcpu->arch.dr7;
4719 
4720 	if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
4721 		vmcs12->guest_ia32_efer = vcpu->arch.efer;
4722 
4723 	vmcs_read_cet_state(&vmx->vcpu, &vmcs12->guest_s_cet,
4724 			    &vmcs12->guest_ssp,
4725 			    &vmcs12->guest_ssp_tbl);
4726 }
4727 
4728 /*
4729  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
4730  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
4731  * and this function updates it to reflect the changes to the guest state while
4732  * L2 was running (and perhaps made some exits which were handled directly by L0
4733  * without going back to L1), and to reflect the exit reason.
4734  * Note that we do not have to copy here all VMCS fields, just those that
4735  * could have changed by the L2 guest or the exit - i.e., the guest-state and
4736  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
4737  * which already writes to vmcs12 directly.
4738  */
4739 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
4740 			   u32 vm_exit_reason, u32 exit_intr_info,
4741 			   unsigned long exit_qualification, u32 exit_insn_len)
4742 {
4743 	/* update exit information fields: */
4744 	vmcs12->vm_exit_reason = vm_exit_reason;
4745 	if (vmx_get_exit_reason(vcpu).enclave_mode)
4746 		vmcs12->vm_exit_reason |= VMX_EXIT_REASONS_SGX_ENCLAVE_MODE;
4747 	vmcs12->exit_qualification = exit_qualification;
4748 
4749 	/*
4750 	 * On VM-Exit due to a failed VM-Entry, the VMCS isn't marked launched
4751 	 * and only EXIT_REASON and EXIT_QUALIFICATION are updated, all other
4752 	 * exit info fields are unmodified.
4753 	 */
4754 	if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
4755 		vmcs12->launch_state = 1;
4756 
4757 		/* vm_entry_intr_info_field is cleared on exit. Emulate this
4758 		 * instead of reading the real value. */
4759 		vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
4760 
4761 		/*
4762 		 * Transfer the event that L0 or L1 may wanted to inject into
4763 		 * L2 to IDT_VECTORING_INFO_FIELD.
4764 		 */
4765 		vmcs12_save_pending_event(vcpu, vmcs12,
4766 					  vm_exit_reason, exit_intr_info);
4767 
4768 		vmcs12->vm_exit_intr_info = exit_intr_info;
4769 		vmcs12->vm_exit_instruction_len = exit_insn_len;
4770 		vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4771 
4772 		/*
4773 		 * According to spec, there's no need to store the guest's
4774 		 * MSRs if the exit is due to a VM-entry failure that occurs
4775 		 * during or after loading the guest state. Since this exit
4776 		 * does not fall in that category, we need to save the MSRs.
4777 		 */
4778 		if (nested_vmx_store_msr(vcpu,
4779 					 vmcs12->vm_exit_msr_store_addr,
4780 					 vmcs12->vm_exit_msr_store_count))
4781 			nested_vmx_abort(vcpu,
4782 					 VMX_ABORT_SAVE_GUEST_MSR_FAIL);
4783 	}
4784 }
4785 
4786 /*
4787  * A part of what we need to when the nested L2 guest exits and we want to
4788  * run its L1 parent, is to reset L1's guest state to the host state specified
4789  * in vmcs12.
4790  * This function is to be called not only on normal nested exit, but also on
4791  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
4792  * Failures During or After Loading Guest State").
4793  * This function should be called when the active VMCS is L1's (vmcs01).
4794  */
4795 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
4796 				   struct vmcs12 *vmcs12)
4797 {
4798 	enum vm_entry_failure_code ignored;
4799 	struct kvm_segment seg;
4800 
4801 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
4802 		vcpu->arch.efer = vmcs12->host_ia32_efer;
4803 	else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4804 		vcpu->arch.efer |= (EFER_LMA | EFER_LME);
4805 	else
4806 		vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
4807 	vmx_set_efer(vcpu, vcpu->arch.efer);
4808 
4809 	kvm_rsp_write(vcpu, vmcs12->host_rsp);
4810 	kvm_rip_write(vcpu, vmcs12->host_rip);
4811 	vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
4812 	vmx_set_interrupt_shadow(vcpu, 0);
4813 
4814 	/*
4815 	 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
4816 	 * actually changed, because vmx_set_cr0 refers to efer set above.
4817 	 *
4818 	 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
4819 	 * (KVM doesn't change it);
4820 	 */
4821 	vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
4822 	vmx_set_cr0(vcpu, vmcs12->host_cr0);
4823 
4824 	/* Same as above - no reason to call set_cr4_guest_host_mask().  */
4825 	vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4826 	vmx_set_cr4(vcpu, vmcs12->host_cr4);
4827 
4828 	nested_ept_uninit_mmu_context(vcpu);
4829 
4830 	/*
4831 	 * Only PDPTE load can fail as the value of cr3 was checked on entry and
4832 	 * couldn't have changed.
4833 	 */
4834 	if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, true, &ignored))
4835 		nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
4836 
4837 	nested_vmx_transition_tlb_flush(vcpu, vmcs12, false);
4838 
4839 	vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
4840 	vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
4841 	vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
4842 	vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
4843 	vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
4844 	vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
4845 	vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
4846 
4847 	/* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
4848 	if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
4849 		vmcs_write64(GUEST_BNDCFGS, 0);
4850 
4851 	/*
4852 	 * Load CET state from host state if VM_EXIT_LOAD_CET_STATE is set.
4853 	 * otherwise CET state should be retained across VM-exit, i.e.,
4854 	 * guest values should be propagated from vmcs12 to vmcs01.
4855 	 */
4856 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_CET_STATE)
4857 		vmcs_write_cet_state(vcpu, vmcs12->host_s_cet, vmcs12->host_ssp,
4858 				     vmcs12->host_ssp_tbl);
4859 	else
4860 		vmcs_write_cet_state(vcpu, vmcs12->guest_s_cet, vmcs12->guest_ssp,
4861 				     vmcs12->guest_ssp_tbl);
4862 
4863 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
4864 		vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
4865 		vcpu->arch.pat = vmcs12->host_ia32_pat;
4866 	}
4867 	if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) &&
4868 	    kvm_pmu_has_perf_global_ctrl(vcpu_to_pmu(vcpu)))
4869 		WARN_ON_ONCE(__kvm_emulate_msr_write(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
4870 						     vmcs12->host_ia32_perf_global_ctrl));
4871 
4872 	/* Set L1 segment info according to Intel SDM
4873 	    27.5.2 Loading Host Segment and Descriptor-Table Registers */
4874 	seg = (struct kvm_segment) {
4875 		.base = 0,
4876 		.limit = 0xFFFFFFFF,
4877 		.selector = vmcs12->host_cs_selector,
4878 		.type = 11,
4879 		.present = 1,
4880 		.s = 1,
4881 		.g = 1
4882 	};
4883 	if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4884 		seg.l = 1;
4885 	else
4886 		seg.db = 1;
4887 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
4888 	seg = (struct kvm_segment) {
4889 		.base = 0,
4890 		.limit = 0xFFFFFFFF,
4891 		.type = 3,
4892 		.present = 1,
4893 		.s = 1,
4894 		.db = 1,
4895 		.g = 1
4896 	};
4897 	seg.selector = vmcs12->host_ds_selector;
4898 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
4899 	seg.selector = vmcs12->host_es_selector;
4900 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
4901 	seg.selector = vmcs12->host_ss_selector;
4902 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
4903 	seg.selector = vmcs12->host_fs_selector;
4904 	seg.base = vmcs12->host_fs_base;
4905 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
4906 	seg.selector = vmcs12->host_gs_selector;
4907 	seg.base = vmcs12->host_gs_base;
4908 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
4909 	seg = (struct kvm_segment) {
4910 		.base = vmcs12->host_tr_base,
4911 		.limit = 0x67,
4912 		.selector = vmcs12->host_tr_selector,
4913 		.type = 11,
4914 		.present = 1
4915 	};
4916 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
4917 
4918 	memset(&seg, 0, sizeof(seg));
4919 	seg.unusable = 1;
4920 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_LDTR);
4921 
4922 	kvm_set_dr(vcpu, 7, 0x400);
4923 	vmx_guest_debugctl_write(vcpu, 0);
4924 
4925 	if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
4926 				vmcs12->vm_exit_msr_load_count))
4927 		nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
4928 
4929 	to_vt(vcpu)->emulation_required = vmx_emulation_required(vcpu);
4930 }
4931 
4932 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
4933 {
4934 	struct vmx_uret_msr *efer_msr;
4935 	unsigned int i;
4936 
4937 	if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
4938 		return vmcs_read64(GUEST_IA32_EFER);
4939 
4940 	if (cpu_has_load_ia32_efer())
4941 		return kvm_host.efer;
4942 
4943 	for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
4944 		if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
4945 			return vmx->msr_autoload.guest.val[i].value;
4946 	}
4947 
4948 	efer_msr = vmx_find_uret_msr(vmx, MSR_EFER);
4949 	if (efer_msr)
4950 		return efer_msr->data;
4951 
4952 	return kvm_host.efer;
4953 }
4954 
4955 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
4956 {
4957 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4958 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4959 	struct vmx_msr_entry g, h;
4960 	gpa_t gpa;
4961 	u32 i, j;
4962 
4963 	vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
4964 
4965 	if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
4966 		/*
4967 		 * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
4968 		 * as vmcs01.GUEST_DR7 contains a userspace defined value
4969 		 * and vcpu->arch.dr7 is not squirreled away before the
4970 		 * nested VMENTER (not worth adding a variable in nested_vmx).
4971 		 */
4972 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
4973 			kvm_set_dr(vcpu, 7, DR7_FIXED_1);
4974 		else
4975 			WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
4976 	}
4977 
4978 	/* Reload DEBUGCTL to ensure vmcs01 has a fresh FREEZE_IN_SMM value. */
4979 	vmx_reload_guest_debugctl(vcpu);
4980 
4981 	/*
4982 	 * Note that calling vmx_set_{efer,cr0,cr4} is important as they
4983 	 * handle a variety of side effects to KVM's software model.
4984 	 */
4985 	vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
4986 
4987 	vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
4988 	vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
4989 
4990 	vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4991 	vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
4992 
4993 	nested_ept_uninit_mmu_context(vcpu);
4994 	vcpu->arch.cr3 = vmx->nested.pre_vmenter_cr3;
4995 	kvm_register_mark_available(vcpu, VCPU_REG_CR3);
4996 
4997 	/*
4998 	 * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
4999 	 * from vmcs01 (if necessary).  The PDPTRs are not loaded on
5000 	 * VMFail, like everything else we just need to ensure our
5001 	 * software model is up-to-date.
5002 	 */
5003 	if (enable_ept && is_pae_paging(vcpu))
5004 		ept_save_pdptrs(vcpu);
5005 
5006 	kvm_mmu_reset_context(vcpu);
5007 
5008 	/*
5009 	 * This nasty bit of open coding is a compromise between blindly
5010 	 * loading L1's MSRs using the exit load lists (incorrect emulation
5011 	 * of VMFail), leaving the nested VM's MSRs in the software model
5012 	 * (incorrect behavior) and snapshotting the modified MSRs (too
5013 	 * expensive since the lists are unbound by hardware).  For each
5014 	 * MSR that was (prematurely) loaded from the nested VMEntry load
5015 	 * list, reload it from the exit load list if it exists and differs
5016 	 * from the guest value.  The intent is to stuff host state as
5017 	 * silently as possible, not to fully process the exit load list.
5018 	 */
5019 	for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
5020 		gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
5021 		if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
5022 			pr_debug_ratelimited(
5023 				"%s read MSR index failed (%u, 0x%08llx)\n",
5024 				__func__, i, gpa);
5025 			goto vmabort;
5026 		}
5027 
5028 		for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
5029 			gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
5030 			if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
5031 				pr_debug_ratelimited(
5032 					"%s read MSR failed (%u, 0x%08llx)\n",
5033 					__func__, j, gpa);
5034 				goto vmabort;
5035 			}
5036 			if (h.index != g.index)
5037 				continue;
5038 			if (h.value == g.value)
5039 				break;
5040 
5041 			if (nested_vmx_load_msr_check(vcpu, &h)) {
5042 				pr_debug_ratelimited(
5043 					"%s check failed (%u, 0x%x, 0x%x)\n",
5044 					__func__, j, h.index, h.reserved);
5045 				goto vmabort;
5046 			}
5047 
5048 			if (kvm_emulate_msr_write(vcpu, h.index, h.value)) {
5049 				pr_debug_ratelimited(
5050 					"%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
5051 					__func__, j, h.index, h.value);
5052 				goto vmabort;
5053 			}
5054 		}
5055 	}
5056 
5057 	return;
5058 
5059 vmabort:
5060 	nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
5061 }
5062 
5063 /*
5064  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
5065  * and modify vmcs12 to make it see what it would expect to see there if
5066  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
5067  */
5068 void __nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
5069 			 u32 exit_intr_info, unsigned long exit_qualification,
5070 			 u32 exit_insn_len)
5071 {
5072 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5073 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5074 
5075 	/* Pending MTF traps are discarded on VM-Exit. */
5076 	vmx->nested.mtf_pending = false;
5077 
5078 	/* trying to cancel vmlaunch/vmresume is a bug */
5079 	kvm_warn_on_nested_run_pending(vcpu);
5080 
5081 	/* Note, "checking" the request also clears the request. */
5082 	if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
5083 #ifdef CONFIG_KVM_HYPERV
5084 		/*
5085 		 * KVM_REQ_GET_NESTED_STATE_PAGES is also used to map
5086 		 * Enlightened VMCS after migration and we still need to
5087 		 * do that when something is forcing L2->L1 exit prior to
5088 		 * the first L2 run.
5089 		 */
5090 		(void)nested_get_evmcs_page(vcpu);
5091 #endif
5092 	}
5093 
5094 	/* Service pending TLB flush requests for L2 before switching to L1. */
5095 	kvm_service_local_tlb_flush_requests(vcpu);
5096 
5097 	/*
5098 	 * VCPU_REG_PDPTR will be clobbered in arch/x86/kvm/vmx/vmx.h between
5099 	 * now and the new vmentry.  Ensure that the VMCS02 PDPTR fields are
5100 	 * up-to-date before switching to L1.
5101 	 */
5102 	if (enable_ept && is_pae_paging(vcpu))
5103 		vmx_ept_load_pdptrs(vcpu);
5104 
5105 	leave_guest_mode(vcpu);
5106 
5107 	if (nested_cpu_has_preemption_timer(vmcs12))
5108 		hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
5109 
5110 	if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING)) {
5111 		vcpu->arch.tsc_offset = vcpu->arch.l1_tsc_offset;
5112 		if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
5113 			vcpu->arch.tsc_scaling_ratio = vcpu->arch.l1_tsc_scaling_ratio;
5114 	}
5115 
5116 	if (likely(!vmx->fail)) {
5117 		sync_vmcs02_to_vmcs12(vcpu, vmcs12);
5118 
5119 		if (vm_exit_reason != -1)
5120 			prepare_vmcs12(vcpu, vmcs12, vm_exit_reason,
5121 				       exit_intr_info, exit_qualification,
5122 				       exit_insn_len);
5123 
5124 		/*
5125 		 * Must happen outside of sync_vmcs02_to_vmcs12() as it will
5126 		 * also be used to capture vmcs12 cache as part of
5127 		 * capturing nVMX state for snapshot (migration).
5128 		 *
5129 		 * Otherwise, this flush will dirty guest memory at a
5130 		 * point it is already assumed by user-space to be
5131 		 * immutable.
5132 		 */
5133 		nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
5134 	} else {
5135 		/*
5136 		 * The only expected VM-instruction error is "VM entry with
5137 		 * invalid control field(s)." Anything else indicates a
5138 		 * problem with L0.
5139 		 */
5140 		WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
5141 			     VMXERR_ENTRY_INVALID_CONTROL_FIELD);
5142 
5143 		/* VM-Fail at VM-Entry means KVM missed a consistency check. */
5144 		WARN_ON_ONCE(warn_on_missed_cc);
5145 	}
5146 
5147 	/*
5148 	 * Drop events/exceptions that were queued for re-injection to L2
5149 	 * (picked up via vmx_complete_interrupts()), as well as exceptions
5150 	 * that were pending for L2.  Note, this must NOT be hoisted above
5151 	 * prepare_vmcs12(), events/exceptions queued for re-injection need to
5152 	 * be captured in vmcs12 (see vmcs12_save_pending_event()).
5153 	 */
5154 	vcpu->arch.nmi_injected = false;
5155 	kvm_clear_exception_queue(vcpu);
5156 	kvm_clear_interrupt_queue(vcpu);
5157 
5158 	vmx_switch_vmcs(vcpu, &vmx->vmcs01);
5159 
5160 	kvm_nested_vmexit_handle_ibrs(vcpu);
5161 
5162 	/*
5163 	 * Update any VMCS fields that might have changed while vmcs02 was the
5164 	 * active VMCS.  The tracking is per-vCPU, not per-VMCS.
5165 	 */
5166 	vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vmx->msr_autostore.nr);
5167 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
5168 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
5169 	vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
5170 	if (kvm_caps.has_tsc_control)
5171 		vmcs_write64(TSC_MULTIPLIER, vcpu->arch.tsc_scaling_ratio);
5172 
5173 	nested_put_vmcs12_pages(vcpu);
5174 
5175 	if ((vm_exit_reason != -1) &&
5176 	    (enable_shadow_vmcs || nested_vmx_is_evmptr12_valid(vmx)))
5177 		vmx->nested.need_vmcs12_to_shadow_sync = true;
5178 
5179 	/* in case we halted in L2 */
5180 	kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
5181 
5182 	if (likely(!vmx->fail)) {
5183 		if (vm_exit_reason != -1)
5184 			trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
5185 						       vmcs12->exit_qualification,
5186 						       vmcs12->idt_vectoring_info_field,
5187 						       vmcs12->vm_exit_intr_info,
5188 						       vmcs12->vm_exit_intr_error_code,
5189 						       KVM_ISA_VMX);
5190 
5191 		load_vmcs12_host_state(vcpu, vmcs12);
5192 
5193 		/*
5194 		 * Process events if an injectable IRQ or NMI is pending, even
5195 		 * if the event is blocked (RFLAGS.IF is cleared on VM-Exit).
5196 		 * If an event became pending while L2 was active, KVM needs to
5197 		 * either inject the event or request an IRQ/NMI window.  SMIs
5198 		 * don't need to be processed as SMM is mutually exclusive with
5199 		 * non-root mode.  INIT/SIPI don't need to be checked as INIT
5200 		 * is blocked post-VMXON, and SIPIs are ignored.
5201 		 */
5202 		if (kvm_cpu_has_injectable_intr(vcpu) || vcpu->arch.nmi_pending)
5203 			kvm_make_request(KVM_REQ_EVENT, vcpu);
5204 		return;
5205 	}
5206 
5207 	/*
5208 	 * After an early L2 VM-entry failure, we're now back
5209 	 * in L1 which thinks it just finished a VMLAUNCH or
5210 	 * VMRESUME instruction, so we need to set the failure
5211 	 * flag and the VM-instruction error field of the VMCS
5212 	 * accordingly, and skip the emulated instruction.
5213 	 */
5214 	(void)nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
5215 
5216 	/*
5217 	 * Restore L1's host state to KVM's software model.  We're here
5218 	 * because a consistency check was caught by hardware, which
5219 	 * means some amount of guest state has been propagated to KVM's
5220 	 * model and needs to be unwound to the host's state.
5221 	 */
5222 	nested_vmx_restore_host_state(vcpu);
5223 
5224 	vmx->fail = 0;
5225 }
5226 
5227 static void nested_vmx_triple_fault(struct kvm_vcpu *vcpu)
5228 {
5229 	kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5230 	nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
5231 }
5232 
5233 /*
5234  * Decode the memory-address operand of a vmx instruction, as recorded on an
5235  * exit caused by such an instruction (run by a guest hypervisor).
5236  * On success, returns 0. When the operand is invalid, returns 1 and throws
5237  * #UD, #GP, or #SS.
5238  */
5239 int get_vmx_mem_address(struct kvm_vcpu *vcpu, unsigned long exit_qualification,
5240 			u32 vmx_instruction_info, bool wr, int len, gva_t *ret)
5241 {
5242 	gva_t off;
5243 	bool exn;
5244 	struct kvm_segment s;
5245 
5246 	/*
5247 	 * According to Vol. 3B, "Information for VM Exits Due to Instruction
5248 	 * Execution", on an exit, vmx_instruction_info holds most of the
5249 	 * addressing components of the operand. Only the displacement part
5250 	 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
5251 	 * For how an actual address is calculated from all these components,
5252 	 * refer to Vol. 1, "Operand Addressing".
5253 	 */
5254 	int  scaling = vmx_instruction_info & 3;
5255 	int  addr_size = (vmx_instruction_info >> 7) & 7;
5256 	bool is_reg = vmx_instruction_info & (1u << 10);
5257 	int  seg_reg = (vmx_instruction_info >> 15) & 7;
5258 	int  index_reg = (vmx_instruction_info >> 18) & 0xf;
5259 	bool index_is_valid = !(vmx_instruction_info & (1u << 22));
5260 	int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
5261 	bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
5262 
5263 	if (is_reg) {
5264 		kvm_queue_exception(vcpu, UD_VECTOR);
5265 		return 1;
5266 	}
5267 
5268 	/* Addr = segment_base + offset */
5269 	/* offset = base + [index * scale] + displacement */
5270 	off = exit_qualification; /* holds the displacement */
5271 	if (addr_size == 1)
5272 		off = (gva_t)sign_extend64(off, 31);
5273 	else if (addr_size == 0)
5274 		off = (gva_t)sign_extend64(off, 15);
5275 	if (base_is_valid)
5276 		off += kvm_register_read(vcpu, base_reg);
5277 	if (index_is_valid)
5278 		off += kvm_register_read(vcpu, index_reg) << scaling;
5279 	vmx_get_segment(vcpu, &s, seg_reg);
5280 
5281 	/*
5282 	 * The effective address, i.e. @off, of a memory operand is truncated
5283 	 * based on the address size of the instruction.  Note that this is
5284 	 * the *effective address*, i.e. the address prior to accounting for
5285 	 * the segment's base.
5286 	 */
5287 	if (addr_size == 1) /* 32 bit */
5288 		off &= 0xffffffff;
5289 	else if (addr_size == 0) /* 16 bit */
5290 		off &= 0xffff;
5291 
5292 	/* Checks for #GP/#SS exceptions. */
5293 	exn = false;
5294 	if (is_long_mode(vcpu)) {
5295 		/*
5296 		 * The virtual/linear address is never truncated in 64-bit
5297 		 * mode, e.g. a 32-bit address size can yield a 64-bit virtual
5298 		 * address when using FS/GS with a non-zero base.
5299 		 */
5300 		if (seg_reg == VCPU_SREG_FS || seg_reg == VCPU_SREG_GS)
5301 			*ret = s.base + off;
5302 		else
5303 			*ret = off;
5304 
5305 		*ret = vmx_get_untagged_addr(vcpu, *ret, 0);
5306 		/* Long mode: #GP(0)/#SS(0) if the memory address is in a
5307 		 * non-canonical form. This is the only check on the memory
5308 		 * destination for long mode!
5309 		 */
5310 		exn = is_noncanonical_address(*ret, vcpu, 0);
5311 	} else {
5312 		/*
5313 		 * When not in long mode, the virtual/linear address is
5314 		 * unconditionally truncated to 32 bits regardless of the
5315 		 * address size.
5316 		 */
5317 		*ret = (s.base + off) & 0xffffffff;
5318 
5319 		/* Protected mode: apply checks for segment validity in the
5320 		 * following order:
5321 		 * - segment type check (#GP(0) may be thrown)
5322 		 * - usability check (#GP(0)/#SS(0))
5323 		 * - limit check (#GP(0)/#SS(0))
5324 		 */
5325 		if (wr)
5326 			/* #GP(0) if the destination operand is located in a
5327 			 * read-only data segment or any code segment.
5328 			 */
5329 			exn = ((s.type & 0xa) == 0 || (s.type & 8));
5330 		else
5331 			/* #GP(0) if the source operand is located in an
5332 			 * execute-only code segment
5333 			 */
5334 			exn = ((s.type & 0xa) == 8);
5335 		if (exn) {
5336 			kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
5337 			return 1;
5338 		}
5339 		/* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
5340 		 */
5341 		exn = (s.unusable != 0);
5342 
5343 		/*
5344 		 * Protected mode: #GP(0)/#SS(0) if the memory operand is
5345 		 * outside the segment limit.  All CPUs that support VMX ignore
5346 		 * limit checks for flat segments, i.e. segments with base==0,
5347 		 * limit==0xffffffff and of type expand-up data or code.
5348 		 */
5349 		if (!(s.base == 0 && s.limit == 0xffffffff &&
5350 		     ((s.type & 8) || !(s.type & 4))))
5351 			exn = exn || ((u64)off + len - 1 > s.limit);
5352 	}
5353 	if (exn) {
5354 		kvm_queue_exception_e(vcpu,
5355 				      seg_reg == VCPU_SREG_SS ?
5356 						SS_VECTOR : GP_VECTOR,
5357 				      0);
5358 		return 1;
5359 	}
5360 
5361 	return 0;
5362 }
5363 
5364 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer,
5365 				int *ret)
5366 {
5367 	gva_t gva;
5368 	struct x86_exception e;
5369 	int r;
5370 
5371 	if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5372 				vmcs_read32(VMX_INSTRUCTION_INFO), false,
5373 				sizeof(*vmpointer), &gva)) {
5374 		*ret = 1;
5375 		return -EINVAL;
5376 	}
5377 
5378 	r = kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e);
5379 	if (r != X86EMUL_CONTINUE) {
5380 		*ret = kvm_handle_memory_failure(vcpu, r, &e);
5381 		return -EINVAL;
5382 	}
5383 
5384 	return 0;
5385 }
5386 
5387 /*
5388  * Allocate a shadow VMCS and associate it with the currently loaded
5389  * VMCS, unless such a shadow VMCS already exists. The newly allocated
5390  * VMCS is also VMCLEARed, so that it is ready for use.
5391  */
5392 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
5393 {
5394 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5395 	struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
5396 
5397 	/*
5398 	 * KVM allocates a shadow VMCS only when L1 executes VMXON and frees it
5399 	 * when L1 executes VMXOFF or the vCPU is forced out of nested
5400 	 * operation.  VMXON faults if the CPU is already post-VMXON, so it
5401 	 * should be impossible to already have an allocated shadow VMCS.  KVM
5402 	 * doesn't support virtualization of VMCS shadowing, so vmcs01 should
5403 	 * always be the loaded VMCS.
5404 	 */
5405 	if (WARN_ON(loaded_vmcs != &vmx->vmcs01 || loaded_vmcs->shadow_vmcs))
5406 		return loaded_vmcs->shadow_vmcs;
5407 
5408 	loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
5409 	if (loaded_vmcs->shadow_vmcs)
5410 		vmcs_clear(loaded_vmcs->shadow_vmcs);
5411 
5412 	return loaded_vmcs->shadow_vmcs;
5413 }
5414 
5415 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
5416 {
5417 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5418 	int r;
5419 
5420 	r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
5421 	if (r < 0)
5422 		goto out_vmcs02;
5423 
5424 	vmx->nested.cached_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
5425 	if (!vmx->nested.cached_vmcs12)
5426 		goto out_cached_vmcs12;
5427 
5428 	vmx->nested.shadow_vmcs12_cache.gpa = INVALID_GPA;
5429 	vmx->nested.cached_shadow_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
5430 	if (!vmx->nested.cached_shadow_vmcs12)
5431 		goto out_cached_shadow_vmcs12;
5432 
5433 	if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
5434 		goto out_shadow_vmcs;
5435 
5436 	hrtimer_setup(&vmx->nested.preemption_timer, vmx_preemption_timer_fn, CLOCK_MONOTONIC,
5437 		      HRTIMER_MODE_ABS_PINNED);
5438 
5439 	vmx->nested.vpid02 = allocate_vpid();
5440 
5441 	/*
5442 	 * Clear last_vpid to ensure that the VPID is flushed on the first
5443 	 * nested VM-Enter. Otherwise, stale TLB entries from a previous life of
5444 	 * the VPID (e.g. different vCPU or even different VM) could be used.
5445 	 */
5446 	vmx->nested.last_vpid = 0;
5447 
5448 	vmx->nested.vmcs02_initialized = false;
5449 	vmx->nested.vmxon = true;
5450 
5451 	if (vmx_pt_mode_is_host_guest()) {
5452 		vmx->pt_desc.guest.ctl = 0;
5453 		pt_update_intercept_for_msr(vcpu);
5454 	}
5455 
5456 	return 0;
5457 
5458 out_shadow_vmcs:
5459 	kfree(vmx->nested.cached_shadow_vmcs12);
5460 
5461 out_cached_shadow_vmcs12:
5462 	kfree(vmx->nested.cached_vmcs12);
5463 
5464 out_cached_vmcs12:
5465 	free_loaded_vmcs(&vmx->nested.vmcs02);
5466 
5467 out_vmcs02:
5468 	return -ENOMEM;
5469 }
5470 
5471 /* Emulate the VMXON instruction. */
5472 static int handle_vmxon(struct kvm_vcpu *vcpu)
5473 {
5474 	int ret;
5475 	gpa_t vmptr;
5476 	uint32_t revision;
5477 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5478 	const u64 VMXON_NEEDED_FEATURES = FEAT_CTL_LOCKED
5479 		| FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
5480 
5481 	/*
5482 	 * Manually check CR4.VMXE checks, KVM must force CR4.VMXE=1 to enter
5483 	 * the guest and so cannot rely on hardware to perform the check,
5484 	 * which has higher priority than VM-Exit (see Intel SDM's pseudocode
5485 	 * for VMXON).
5486 	 *
5487 	 * Rely on hardware for the other pre-VM-Exit checks, CR0.PE=1, !VM86
5488 	 * and !COMPATIBILITY modes.  For an unrestricted guest, KVM doesn't
5489 	 * force any of the relevant guest state.  For a restricted guest, KVM
5490 	 * does force CR0.PE=1, but only to also force VM86 in order to emulate
5491 	 * Real Mode, and so there's no need to check CR0.PE manually.
5492 	 */
5493 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_VMXE)) {
5494 		kvm_queue_exception(vcpu, UD_VECTOR);
5495 		return 1;
5496 	}
5497 
5498 	/*
5499 	 * The CPL is checked for "not in VMX operation" and for "in VMX root",
5500 	 * and has higher priority than the VM-Fail due to being post-VMXON,
5501 	 * i.e. VMXON #GPs outside of VMX non-root if CPL!=0.  In VMX non-root,
5502 	 * VMXON causes VM-Exit and KVM unconditionally forwards VMXON VM-Exits
5503 	 * from L2 to L1, i.e. there's no need to check for the vCPU being in
5504 	 * VMX non-root.
5505 	 *
5506 	 * Forwarding the VM-Exit unconditionally, i.e. without performing the
5507 	 * #UD checks (see above), is functionally ok because KVM doesn't allow
5508 	 * L1 to run L2 without CR4.VMXE=0, and because KVM never modifies L2's
5509 	 * CR0 or CR4, i.e. it's L2's responsibility to emulate #UDs that are
5510 	 * missed by hardware due to shadowing CR0 and/or CR4.
5511 	 */
5512 	if (vmx_get_cpl(vcpu)) {
5513 		kvm_inject_gp(vcpu, 0);
5514 		return 1;
5515 	}
5516 
5517 	if (vmx->nested.vmxon)
5518 		return nested_vmx_fail(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
5519 
5520 	/*
5521 	 * Invalid CR0/CR4 generates #GP.  These checks are performed if and
5522 	 * only if the vCPU isn't already in VMX operation, i.e. effectively
5523 	 * have lower priority than the VM-Fail above.
5524 	 */
5525 	if (!nested_host_cr0_valid(vcpu, kvm_read_cr0(vcpu)) ||
5526 	    !nested_host_cr4_valid(vcpu, kvm_read_cr4(vcpu))) {
5527 		kvm_inject_gp(vcpu, 0);
5528 		return 1;
5529 	}
5530 
5531 	if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
5532 			!= VMXON_NEEDED_FEATURES) {
5533 		kvm_inject_gp(vcpu, 0);
5534 		return 1;
5535 	}
5536 
5537 	if (nested_vmx_get_vmptr(vcpu, &vmptr, &ret))
5538 		return ret;
5539 
5540 	/*
5541 	 * SDM 3: 24.11.5
5542 	 * The first 4 bytes of VMXON region contain the supported
5543 	 * VMCS revision identifier
5544 	 *
5545 	 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
5546 	 * which replaces physical address width with 32
5547 	 */
5548 	if (!page_address_valid(vcpu, vmptr))
5549 		return nested_vmx_failInvalid(vcpu);
5550 
5551 	if (kvm_read_guest(vcpu->kvm, vmptr, &revision, sizeof(revision)) ||
5552 	    revision != VMCS12_REVISION)
5553 		return nested_vmx_failInvalid(vcpu);
5554 
5555 	vmx->nested.vmxon_ptr = vmptr;
5556 	ret = enter_vmx_operation(vcpu);
5557 	if (ret)
5558 		return ret;
5559 
5560 	return nested_vmx_succeed(vcpu);
5561 }
5562 
5563 static inline void nested_release_vmcs12(struct kvm_vcpu *vcpu)
5564 {
5565 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5566 
5567 	if (vmx->nested.current_vmptr == INVALID_GPA)
5568 		return;
5569 
5570 	copy_vmcs02_to_vmcs12_rare(vcpu, get_vmcs12(vcpu));
5571 
5572 	if (enable_shadow_vmcs) {
5573 		/* copy to memory all shadowed fields in case
5574 		   they were modified */
5575 		copy_shadow_to_vmcs12(vmx);
5576 		vmx_disable_shadow_vmcs(vmx);
5577 	}
5578 	vmx->nested.posted_intr_nv = -1;
5579 
5580 	/* Flush VMCS12 to guest memory */
5581 	kvm_vcpu_write_guest_page(vcpu,
5582 				  vmx->nested.current_vmptr >> PAGE_SHIFT,
5583 				  vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
5584 
5585 	kvm_mmu_free_roots(vcpu->kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5586 
5587 	vmx->nested.current_vmptr = INVALID_GPA;
5588 }
5589 
5590 /* Emulate the VMXOFF instruction */
5591 static int handle_vmxoff(struct kvm_vcpu *vcpu)
5592 {
5593 	if (!nested_vmx_check_permission(vcpu))
5594 		return 1;
5595 
5596 	free_nested(vcpu);
5597 
5598 	if (kvm_apic_has_pending_init_or_sipi(vcpu))
5599 		kvm_make_request(KVM_REQ_EVENT, vcpu);
5600 
5601 	return nested_vmx_succeed(vcpu);
5602 }
5603 
5604 /* Emulate the VMCLEAR instruction */
5605 static int handle_vmclear(struct kvm_vcpu *vcpu)
5606 {
5607 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5608 	u32 zero = 0;
5609 	gpa_t vmptr;
5610 	int r;
5611 
5612 	if (!nested_vmx_check_permission(vcpu))
5613 		return 1;
5614 
5615 	if (nested_vmx_get_vmptr(vcpu, &vmptr, &r))
5616 		return r;
5617 
5618 	if (!page_address_valid(vcpu, vmptr))
5619 		return nested_vmx_fail(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
5620 
5621 	if (vmptr == vmx->nested.vmxon_ptr)
5622 		return nested_vmx_fail(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
5623 
5624 	if (likely(!nested_evmcs_handle_vmclear(vcpu, vmptr))) {
5625 		if (vmptr == vmx->nested.current_vmptr)
5626 			nested_release_vmcs12(vcpu);
5627 
5628 		/*
5629 		 * Silently ignore memory errors on VMCLEAR, Intel's pseudocode
5630 		 * for VMCLEAR includes a "ensure that data for VMCS referenced
5631 		 * by the operand is in memory" clause that guards writes to
5632 		 * memory, i.e. doing nothing for I/O is architecturally valid.
5633 		 *
5634 		 * FIXME: Suppress failures if and only if no memslot is found,
5635 		 * i.e. exit to userspace if __copy_to_user() fails.
5636 		 */
5637 		(void)kvm_vcpu_write_guest(vcpu,
5638 					   vmptr + offsetof(struct vmcs12,
5639 							    launch_state),
5640 					   &zero, sizeof(zero));
5641 	}
5642 
5643 	return nested_vmx_succeed(vcpu);
5644 }
5645 
5646 /* Emulate the VMLAUNCH instruction */
5647 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
5648 {
5649 	return nested_vmx_run(vcpu, true);
5650 }
5651 
5652 /* Emulate the VMRESUME instruction */
5653 static int handle_vmresume(struct kvm_vcpu *vcpu)
5654 {
5655 
5656 	return nested_vmx_run(vcpu, false);
5657 }
5658 
5659 static int handle_vmread(struct kvm_vcpu *vcpu)
5660 {
5661 	struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
5662 						    : get_vmcs12(vcpu);
5663 	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5664 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5665 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5666 	struct x86_exception e;
5667 	unsigned long field;
5668 	u64 value;
5669 	gva_t gva = 0;
5670 	short offset;
5671 	int len, r;
5672 
5673 	if (!nested_vmx_check_permission(vcpu))
5674 		return 1;
5675 
5676 	/* Decode instruction info and find the field to read */
5677 	field = kvm_register_read(vcpu, (((instr_info) >> 28) & 0xf));
5678 
5679 	if (!nested_vmx_is_evmptr12_valid(vmx)) {
5680 		/*
5681 		 * In VMX non-root operation, when the VMCS-link pointer is INVALID_GPA,
5682 		 * any VMREAD sets the ALU flags for VMfailInvalid.
5683 		 */
5684 		if (vmx->nested.current_vmptr == INVALID_GPA ||
5685 		    (is_guest_mode(vcpu) &&
5686 		     get_vmcs12(vcpu)->vmcs_link_pointer == INVALID_GPA))
5687 			return nested_vmx_failInvalid(vcpu);
5688 
5689 		offset = get_vmcs12_field_offset(field);
5690 		if (offset < 0)
5691 			return nested_vmx_fail(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5692 
5693 		if (!is_guest_mode(vcpu) && is_vmcs12_ext_field(field))
5694 			copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
5695 
5696 		/* Read the field, zero-extended to a u64 value */
5697 		value = vmcs12_read_any(vmcs12, field, offset);
5698 	} else {
5699 		/*
5700 		 * Hyper-V TLFS (as of 6.0b) explicitly states, that while an
5701 		 * enlightened VMCS is active VMREAD/VMWRITE instructions are
5702 		 * unsupported. Unfortunately, certain versions of Windows 11
5703 		 * don't comply with this requirement which is not enforced in
5704 		 * genuine Hyper-V. Allow VMREAD from an enlightened VMCS as a
5705 		 * workaround, as misbehaving guests will panic on VM-Fail.
5706 		 * Note, enlightened VMCS is incompatible with shadow VMCS so
5707 		 * all VMREADs from L2 should go to L1.
5708 		 */
5709 		if (WARN_ON_ONCE(is_guest_mode(vcpu)))
5710 			return nested_vmx_failInvalid(vcpu);
5711 
5712 		offset = evmcs_field_offset(field, NULL);
5713 		if (offset < 0)
5714 			return nested_vmx_fail(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5715 
5716 		/* Read the field, zero-extended to a u64 value */
5717 		value = evmcs_read_any(nested_vmx_evmcs(vmx), field, offset);
5718 	}
5719 
5720 	/*
5721 	 * Now copy part of this value to register or memory, as requested.
5722 	 * Note that the number of bits actually copied is 32 or 64 depending
5723 	 * on the guest's mode (32 or 64 bit), not on the given field's length.
5724 	 */
5725 	if (instr_info & BIT(10)) {
5726 		kvm_register_write(vcpu, (((instr_info) >> 3) & 0xf), value);
5727 	} else {
5728 		len = is_64_bit_mode(vcpu) ? 8 : 4;
5729 		if (get_vmx_mem_address(vcpu, exit_qualification,
5730 					instr_info, true, len, &gva))
5731 			return 1;
5732 		/* _system ok, nested_vmx_check_permission has verified cpl=0 */
5733 		r = kvm_write_guest_virt_system(vcpu, gva, &value, len, &e);
5734 		if (r != X86EMUL_CONTINUE)
5735 			return kvm_handle_memory_failure(vcpu, r, &e);
5736 	}
5737 
5738 	return nested_vmx_succeed(vcpu);
5739 }
5740 
5741 static bool is_shadow_field_rw(unsigned long field)
5742 {
5743 	switch (field) {
5744 #define SHADOW_FIELD_RW(x, y) case x:
5745 #include "vmcs_shadow_fields.h"
5746 		return true;
5747 	default:
5748 		break;
5749 	}
5750 	return false;
5751 }
5752 
5753 static bool is_shadow_field_ro(unsigned long field)
5754 {
5755 	switch (field) {
5756 #define SHADOW_FIELD_RO(x, y) case x:
5757 #include "vmcs_shadow_fields.h"
5758 		return true;
5759 	default:
5760 		break;
5761 	}
5762 	return false;
5763 }
5764 
5765 static int handle_vmwrite(struct kvm_vcpu *vcpu)
5766 {
5767 	struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
5768 						    : get_vmcs12(vcpu);
5769 	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5770 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5771 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5772 	struct x86_exception e;
5773 	unsigned long field;
5774 	short offset;
5775 	gva_t gva;
5776 	int len, r;
5777 
5778 	/*
5779 	 * The value to write might be 32 or 64 bits, depending on L1's long
5780 	 * mode, and eventually we need to write that into a field of several
5781 	 * possible lengths. The code below first zero-extends the value to 64
5782 	 * bit (value), and then copies only the appropriate number of
5783 	 * bits into the vmcs12 field.
5784 	 */
5785 	u64 value = 0;
5786 
5787 	if (!nested_vmx_check_permission(vcpu))
5788 		return 1;
5789 
5790 	/*
5791 	 * In VMX non-root operation, when the VMCS-link pointer is INVALID_GPA,
5792 	 * any VMWRITE sets the ALU flags for VMfailInvalid.
5793 	 */
5794 	if (vmx->nested.current_vmptr == INVALID_GPA ||
5795 	    (is_guest_mode(vcpu) &&
5796 	     get_vmcs12(vcpu)->vmcs_link_pointer == INVALID_GPA))
5797 		return nested_vmx_failInvalid(vcpu);
5798 
5799 	if (instr_info & BIT(10))
5800 		value = kvm_register_read(vcpu, (((instr_info) >> 3) & 0xf));
5801 	else {
5802 		len = is_64_bit_mode(vcpu) ? 8 : 4;
5803 		if (get_vmx_mem_address(vcpu, exit_qualification,
5804 					instr_info, false, len, &gva))
5805 			return 1;
5806 		r = kvm_read_guest_virt(vcpu, gva, &value, len, &e);
5807 		if (r != X86EMUL_CONTINUE)
5808 			return kvm_handle_memory_failure(vcpu, r, &e);
5809 	}
5810 
5811 	field = kvm_register_read(vcpu, (((instr_info) >> 28) & 0xf));
5812 
5813 	offset = get_vmcs12_field_offset(field);
5814 	if (offset < 0)
5815 		return nested_vmx_fail(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5816 
5817 	/*
5818 	 * If the vCPU supports "VMWRITE to any supported field in the
5819 	 * VMCS," then the "read-only" fields are actually read/write.
5820 	 */
5821 	if (vmcs_field_readonly(field) &&
5822 	    !nested_cpu_has_vmwrite_any_field(vcpu))
5823 		return nested_vmx_fail(vcpu, VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
5824 
5825 	/*
5826 	 * Ensure vmcs12 is up-to-date before any VMWRITE that dirties
5827 	 * vmcs12, else we may crush a field or consume a stale value.
5828 	 */
5829 	if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field))
5830 		copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
5831 
5832 	/*
5833 	 * Some Intel CPUs intentionally drop the reserved bits of the AR byte
5834 	 * fields on VMWRITE.  Emulate this behavior to ensure consistent KVM
5835 	 * behavior regardless of the underlying hardware, e.g. if an AR_BYTE
5836 	 * field is intercepted for VMWRITE but not VMREAD (in L1), then VMREAD
5837 	 * from L1 will return a different value than VMREAD from L2 (L1 sees
5838 	 * the stripped down value, L2 sees the full value as stored by KVM).
5839 	 */
5840 	if (field >= GUEST_ES_AR_BYTES && field <= GUEST_TR_AR_BYTES)
5841 		value &= 0x1f0ff;
5842 
5843 	vmcs12_write_any(vmcs12, field, offset, value);
5844 
5845 	/*
5846 	 * Do not track vmcs12 dirty-state if in guest-mode as we actually
5847 	 * dirty shadow vmcs12 instead of vmcs12.  Fields that can be updated
5848 	 * by L1 without a vmexit are always updated in the vmcs02, i.e. don't
5849 	 * "dirty" vmcs12, all others go down the prepare_vmcs02() slow path.
5850 	 */
5851 	if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field)) {
5852 		/*
5853 		 * L1 can read these fields without exiting, ensure the
5854 		 * shadow VMCS is up-to-date.
5855 		 */
5856 		if (enable_shadow_vmcs && is_shadow_field_ro(field)) {
5857 			preempt_disable();
5858 			vmcs_load(vmx->vmcs01.shadow_vmcs);
5859 
5860 			__vmcs_writel(field, value);
5861 
5862 			vmcs_clear(vmx->vmcs01.shadow_vmcs);
5863 			vmcs_load(vmx->loaded_vmcs->vmcs);
5864 			preempt_enable();
5865 		}
5866 		vmx->nested.dirty_vmcs12 = true;
5867 	}
5868 
5869 	return nested_vmx_succeed(vcpu);
5870 }
5871 
5872 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
5873 {
5874 	vmx->nested.current_vmptr = vmptr;
5875 	if (enable_shadow_vmcs) {
5876 		secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_SHADOW_VMCS);
5877 		vmcs_write64(VMCS_LINK_POINTER,
5878 			     __pa(vmx->vmcs01.shadow_vmcs));
5879 		vmx->nested.need_vmcs12_to_shadow_sync = true;
5880 	}
5881 	vmx->nested.dirty_vmcs12 = true;
5882 	vmx->nested.force_msr_bitmap_recalc = true;
5883 }
5884 
5885 /* Emulate the VMPTRLD instruction */
5886 static int handle_vmptrld(struct kvm_vcpu *vcpu)
5887 {
5888 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5889 	gpa_t vmptr;
5890 	int r;
5891 
5892 	if (!nested_vmx_check_permission(vcpu))
5893 		return 1;
5894 
5895 	if (nested_vmx_get_vmptr(vcpu, &vmptr, &r))
5896 		return r;
5897 
5898 	if (!page_address_valid(vcpu, vmptr))
5899 		return nested_vmx_fail(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
5900 
5901 	if (vmptr == vmx->nested.vmxon_ptr)
5902 		return nested_vmx_fail(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
5903 
5904 	/* Forbid normal VMPTRLD if Enlightened version was used */
5905 	if (nested_vmx_is_evmptr12_valid(vmx))
5906 		return 1;
5907 
5908 	if (vmx->nested.current_vmptr != vmptr) {
5909 		struct gfn_to_hva_cache *ghc = &vmx->nested.vmcs12_cache;
5910 		struct vmcs_hdr hdr;
5911 
5912 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, vmptr, VMCS12_SIZE)) {
5913 			/*
5914 			 * Reads from an unbacked page return all 1s,
5915 			 * which means that the 32 bits located at the
5916 			 * given physical address won't match the required
5917 			 * VMCS12_REVISION identifier.
5918 			 */
5919 			return nested_vmx_fail(vcpu,
5920 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5921 		}
5922 
5923 		if (kvm_read_guest_offset_cached(vcpu->kvm, ghc, &hdr,
5924 						 offsetof(struct vmcs12, hdr),
5925 						 sizeof(hdr))) {
5926 			return nested_vmx_fail(vcpu,
5927 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5928 		}
5929 
5930 		if (hdr.revision_id != VMCS12_REVISION ||
5931 		    (hdr.shadow_vmcs &&
5932 		     !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
5933 			return nested_vmx_fail(vcpu,
5934 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5935 		}
5936 
5937 		nested_release_vmcs12(vcpu);
5938 
5939 		/*
5940 		 * Load VMCS12 from guest memory since it is not already
5941 		 * cached.
5942 		 */
5943 		if (kvm_read_guest_cached(vcpu->kvm, ghc, vmx->nested.cached_vmcs12,
5944 					  VMCS12_SIZE)) {
5945 			return nested_vmx_fail(vcpu,
5946 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5947 		}
5948 
5949 		set_current_vmptr(vmx, vmptr);
5950 	}
5951 
5952 	return nested_vmx_succeed(vcpu);
5953 }
5954 
5955 /* Emulate the VMPTRST instruction */
5956 static int handle_vmptrst(struct kvm_vcpu *vcpu)
5957 {
5958 	unsigned long exit_qual = vmx_get_exit_qual(vcpu);
5959 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5960 	gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
5961 	struct x86_exception e;
5962 	gva_t gva;
5963 	int r;
5964 
5965 	if (!nested_vmx_check_permission(vcpu))
5966 		return 1;
5967 
5968 	if (unlikely(nested_vmx_is_evmptr12_valid(to_vmx(vcpu))))
5969 		return 1;
5970 
5971 	if (get_vmx_mem_address(vcpu, exit_qual, instr_info,
5972 				true, sizeof(gpa_t), &gva))
5973 		return 1;
5974 	/* *_system ok, nested_vmx_check_permission has verified cpl=0 */
5975 	r = kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
5976 					sizeof(gpa_t), &e);
5977 	if (r != X86EMUL_CONTINUE)
5978 		return kvm_handle_memory_failure(vcpu, r, &e);
5979 
5980 	return nested_vmx_succeed(vcpu);
5981 }
5982 
5983 /* Emulate the INVEPT instruction */
5984 static int handle_invept(struct kvm_vcpu *vcpu)
5985 {
5986 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5987 	u32 vmx_instruction_info, types;
5988 	unsigned long type, roots_to_free;
5989 	struct kvm_mmu *mmu;
5990 	gva_t gva;
5991 	struct x86_exception e;
5992 	struct {
5993 		u64 eptp, gpa;
5994 	} operand;
5995 	int i, r, gpr_index;
5996 
5997 	if (!(vmx->nested.msrs.secondary_ctls_high &
5998 	      SECONDARY_EXEC_ENABLE_EPT) ||
5999 	    !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
6000 		kvm_queue_exception(vcpu, UD_VECTOR);
6001 		return 1;
6002 	}
6003 
6004 	if (!nested_vmx_check_permission(vcpu))
6005 		return 1;
6006 
6007 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6008 	gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
6009 	type = kvm_register_read(vcpu, gpr_index);
6010 
6011 	types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
6012 
6013 	if (type >= 32 || !(types & (1 << type)))
6014 		return nested_vmx_fail(vcpu, VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6015 
6016 	/* According to the Intel VMX instruction reference, the memory
6017 	 * operand is read even if it isn't needed (e.g., for type==global)
6018 	 */
6019 	if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
6020 			vmx_instruction_info, false, sizeof(operand), &gva))
6021 		return 1;
6022 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
6023 	if (r != X86EMUL_CONTINUE)
6024 		return kvm_handle_memory_failure(vcpu, r, &e);
6025 
6026 	/*
6027 	 * Nested EPT roots are always held through guest_mmu,
6028 	 * not root_mmu.
6029 	 */
6030 	mmu = &vcpu->arch.guest_mmu;
6031 
6032 	switch (type) {
6033 	case VMX_EPT_EXTENT_CONTEXT:
6034 		if (!nested_vmx_check_eptp(vcpu, operand.eptp))
6035 			return nested_vmx_fail(vcpu,
6036 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6037 
6038 		roots_to_free = 0;
6039 		if (nested_ept_root_matches(mmu->root.hpa, mmu->root.pgd,
6040 					    operand.eptp))
6041 			roots_to_free |= KVM_MMU_ROOT_CURRENT;
6042 
6043 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
6044 			if (nested_ept_root_matches(mmu->prev_roots[i].hpa,
6045 						    mmu->prev_roots[i].pgd,
6046 						    operand.eptp))
6047 				roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
6048 		}
6049 		break;
6050 	case VMX_EPT_EXTENT_GLOBAL:
6051 		roots_to_free = KVM_MMU_ROOTS_ALL;
6052 		break;
6053 	default:
6054 		BUG();
6055 		break;
6056 	}
6057 
6058 	if (roots_to_free)
6059 		kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
6060 
6061 	return nested_vmx_succeed(vcpu);
6062 }
6063 
6064 static int handle_invvpid(struct kvm_vcpu *vcpu)
6065 {
6066 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6067 	u32 vmx_instruction_info;
6068 	unsigned long type, types;
6069 	gva_t gva;
6070 	struct x86_exception e;
6071 	struct {
6072 		u64 vpid;
6073 		u64 gla;
6074 	} operand;
6075 	int r, gpr_index;
6076 	int cpu;
6077 
6078 	if (!(vmx->nested.msrs.secondary_ctls_high &
6079 	      SECONDARY_EXEC_ENABLE_VPID) ||
6080 			!(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
6081 		kvm_queue_exception(vcpu, UD_VECTOR);
6082 		return 1;
6083 	}
6084 
6085 	if (!nested_vmx_check_permission(vcpu))
6086 		return 1;
6087 
6088 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6089 	gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
6090 	type = kvm_register_read(vcpu, gpr_index);
6091 
6092 	types = (vmx->nested.msrs.vpid_caps &
6093 			VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
6094 
6095 	if (type >= 32 || !(types & (1 << type)))
6096 		return nested_vmx_fail(vcpu,
6097 			VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6098 
6099 	/* according to the intel vmx instruction reference, the memory
6100 	 * operand is read even if it isn't needed (e.g., for type==global)
6101 	 */
6102 	if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
6103 			vmx_instruction_info, false, sizeof(operand), &gva))
6104 		return 1;
6105 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
6106 	if (r != X86EMUL_CONTINUE)
6107 		return kvm_handle_memory_failure(vcpu, r, &e);
6108 
6109 	if (operand.vpid >> 16)
6110 		return nested_vmx_fail(vcpu, VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6111 
6112 	if (type != VMX_VPID_EXTENT_ALL_CONTEXT && !operand.vpid)
6113 		return nested_vmx_fail(vcpu, VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6114 
6115 	/* LAM doesn't apply to addresses that are inputs to TLB invalidation. */
6116 	if (type == VMX_VPID_EXTENT_INDIVIDUAL_ADDR &&
6117 	    is_noncanonical_invlpg_address(operand.gla, vcpu))
6118 		return nested_vmx_fail(vcpu, VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6119 
6120 	/*
6121 	 * Always flush the effective vpid02, i.e. never flush the current VPID
6122 	 * and never explicitly flush vpid01.  INVVPID targets a VPID, not a
6123 	 * VMCS, and so whether or not the current vmcs12 has VPID enabled is
6124 	 * irrelevant (and there may not be a loaded vmcs12).
6125 	 *
6126 	 * If vmcs02 was last loaded on a different pCPU, then defer the flush
6127 	 * by invalidating the nested VPID tracking to ensure that KVM performs
6128 	 * the invalidation on the correct pCPU.
6129 	 */
6130 	cpu = get_cpu();
6131 	if (cpu != vmx->nested.vmcs02.cpu)
6132 		vmx->nested.last_vpid = 0;
6133 	else if (type == VMX_VPID_EXTENT_INDIVIDUAL_ADDR)
6134 		vpid_sync_vcpu_addr(nested_get_vpid02(vcpu), operand.gla);
6135 	else
6136 		vpid_sync_context(nested_get_vpid02(vcpu));
6137 	put_cpu();
6138 
6139 	/*
6140 	 * Sync the shadow page tables if EPT is disabled, L1 is invalidating
6141 	 * linear mappings for L2 (tagged with L2's VPID).  Free all guest
6142 	 * roots as VPIDs are not tracked in the MMU role.
6143 	 *
6144 	 * Note, this operates on root_mmu, not guest_mmu, as L1 and L2 share
6145 	 * an MMU when EPT is disabled.
6146 	 *
6147 	 * TODO: sync only the affected SPTEs for INVDIVIDUAL_ADDR.
6148 	 */
6149 	if (!enable_ept)
6150 		kvm_mmu_free_guest_mode_roots(vcpu->kvm, &vcpu->arch.root_mmu);
6151 
6152 	return nested_vmx_succeed(vcpu);
6153 }
6154 
6155 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
6156 				     struct vmcs12 *vmcs12)
6157 {
6158 	u32 index = kvm_ecx_read(vcpu);
6159 	u64 new_eptp;
6160 
6161 	if (WARN_ON_ONCE(!nested_cpu_has_ept(vmcs12)))
6162 		return 1;
6163 	if (index >= VMFUNC_EPTP_ENTRIES)
6164 		return 1;
6165 
6166 	if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
6167 				     &new_eptp, index * 8, 8))
6168 		return 1;
6169 
6170 	/*
6171 	 * If the (L2) guest does a vmfunc to the currently
6172 	 * active ept pointer, we don't have to do anything else
6173 	 */
6174 	if (vmcs12->ept_pointer != new_eptp) {
6175 		if (!nested_vmx_check_eptp(vcpu, new_eptp))
6176 			return 1;
6177 
6178 		vmcs12->ept_pointer = new_eptp;
6179 		nested_ept_new_eptp(vcpu);
6180 
6181 		if (!nested_cpu_has_vpid(vmcs12))
6182 			kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
6183 	}
6184 
6185 	return 0;
6186 }
6187 
6188 static int handle_vmfunc(struct kvm_vcpu *vcpu)
6189 {
6190 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6191 	struct vmcs12 *vmcs12;
6192 	u32 function = kvm_eax_read(vcpu);
6193 
6194 	/*
6195 	 * VMFUNC should never execute cleanly while L1 is active; KVM supports
6196 	 * VMFUNC for nested VMs, but not for L1.
6197 	 */
6198 	if (WARN_ON_ONCE(!is_guest_mode(vcpu))) {
6199 		kvm_queue_exception(vcpu, UD_VECTOR);
6200 		return 1;
6201 	}
6202 
6203 	vmcs12 = get_vmcs12(vcpu);
6204 
6205 	/*
6206 	 * #UD on out-of-bounds function has priority over VM-Exit, and VMFUNC
6207 	 * is enabled in vmcs02 if and only if it's enabled in vmcs12.
6208 	 */
6209 	if (WARN_ON_ONCE((function > 63) || !nested_cpu_has_vmfunc(vmcs12))) {
6210 		kvm_queue_exception(vcpu, UD_VECTOR);
6211 		return 1;
6212 	}
6213 
6214 	if (!(vmcs12->vm_function_control & BIT_ULL(function)))
6215 		goto fail;
6216 
6217 	switch (function) {
6218 	case 0:
6219 		if (nested_vmx_eptp_switching(vcpu, vmcs12))
6220 			goto fail;
6221 		break;
6222 	default:
6223 		goto fail;
6224 	}
6225 	return kvm_skip_emulated_instruction(vcpu);
6226 
6227 fail:
6228 	/*
6229 	 * This is effectively a reflected VM-Exit, as opposed to a synthesized
6230 	 * nested VM-Exit.  Pass the original exit reason, i.e. don't hardcode
6231 	 * EXIT_REASON_VMFUNC as the exit reason.
6232 	 */
6233 	nested_vmx_vmexit(vcpu, vmx->vt.exit_reason.full,
6234 			  vmx_get_intr_info(vcpu),
6235 			  vmx_get_exit_qual(vcpu));
6236 	return 1;
6237 }
6238 
6239 /*
6240  * Return true if an IO instruction with the specified port and size should cause
6241  * a VM-exit into L1.
6242  */
6243 bool nested_vmx_check_io_bitmaps(struct kvm_vcpu *vcpu, unsigned int port,
6244 				 int size)
6245 {
6246 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6247 	gpa_t bitmap, last_bitmap;
6248 	u8 b;
6249 
6250 	last_bitmap = INVALID_GPA;
6251 	b = -1;
6252 
6253 	while (size > 0) {
6254 		if (port < 0x8000)
6255 			bitmap = vmcs12->io_bitmap_a;
6256 		else if (port < 0x10000)
6257 			bitmap = vmcs12->io_bitmap_b;
6258 		else
6259 			return true;
6260 		bitmap += (port & 0x7fff) / 8;
6261 
6262 		if (last_bitmap != bitmap)
6263 			if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
6264 				return true;
6265 		if (b & (1 << (port & 7)))
6266 			return true;
6267 
6268 		port++;
6269 		size--;
6270 		last_bitmap = bitmap;
6271 	}
6272 
6273 	return false;
6274 }
6275 
6276 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
6277 				       struct vmcs12 *vmcs12)
6278 {
6279 	unsigned long exit_qualification;
6280 	unsigned short port;
6281 	int size;
6282 
6283 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
6284 		return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
6285 
6286 	exit_qualification = vmx_get_exit_qual(vcpu);
6287 
6288 	port = exit_qualification >> 16;
6289 	size = (exit_qualification & 7) + 1;
6290 
6291 	return nested_vmx_check_io_bitmaps(vcpu, port, size);
6292 }
6293 
6294 /*
6295  * Return 1 if we should exit from L2 to L1 to handle an MSR access,
6296  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
6297  * disinterest in the current event (read or write a specific MSR) by using an
6298  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
6299  */
6300 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
6301 					struct vmcs12 *vmcs12,
6302 					union vmx_exit_reason exit_reason)
6303 {
6304 	u32 msr_index;
6305 	gpa_t bitmap;
6306 
6307 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
6308 		return true;
6309 
6310 	if (exit_reason.basic == EXIT_REASON_MSR_READ_IMM ||
6311 	    exit_reason.basic == EXIT_REASON_MSR_WRITE_IMM)
6312 		msr_index = vmx_get_exit_qual(vcpu);
6313 	else
6314 		msr_index = kvm_ecx_read(vcpu);
6315 
6316 	/*
6317 	 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
6318 	 * for the four combinations of read/write and low/high MSR numbers.
6319 	 * First we need to figure out which of the four to use:
6320 	 */
6321 	bitmap = vmcs12->msr_bitmap;
6322 	if (exit_reason.basic == EXIT_REASON_MSR_WRITE ||
6323 	    exit_reason.basic == EXIT_REASON_MSR_WRITE_IMM)
6324 		bitmap += 2048;
6325 	if (msr_index >= 0xc0000000) {
6326 		msr_index -= 0xc0000000;
6327 		bitmap += 1024;
6328 	}
6329 
6330 	/* Then read the msr_index'th bit from this bitmap: */
6331 	if (msr_index < 1024*8) {
6332 		unsigned char b;
6333 		if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
6334 			return true;
6335 		return 1 & (b >> (msr_index & 7));
6336 	} else
6337 		return true; /* let L1 handle the wrong parameter */
6338 }
6339 
6340 /*
6341  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
6342  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
6343  * intercept (via guest_host_mask etc.) the current event.
6344  */
6345 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
6346 	struct vmcs12 *vmcs12)
6347 {
6348 	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
6349 	int cr = exit_qualification & 15;
6350 	int reg;
6351 	unsigned long val;
6352 
6353 	switch ((exit_qualification >> 4) & 3) {
6354 	case 0: /* mov to cr */
6355 		reg = (exit_qualification >> 8) & 15;
6356 		val = kvm_register_read(vcpu, reg);
6357 		switch (cr) {
6358 		case 0:
6359 			if (vmcs12->cr0_guest_host_mask &
6360 			    (val ^ vmcs12->cr0_read_shadow))
6361 				return true;
6362 			break;
6363 		case 3:
6364 			if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
6365 				return true;
6366 			break;
6367 		case 4:
6368 			if (vmcs12->cr4_guest_host_mask &
6369 			    (vmcs12->cr4_read_shadow ^ val))
6370 				return true;
6371 			break;
6372 		case 8:
6373 			if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
6374 				return true;
6375 			break;
6376 		}
6377 		break;
6378 	case 2: /* clts */
6379 		if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
6380 		    (vmcs12->cr0_read_shadow & X86_CR0_TS))
6381 			return true;
6382 		break;
6383 	case 1: /* mov from cr */
6384 		switch (cr) {
6385 		case 3:
6386 			if (vmcs12->cpu_based_vm_exec_control &
6387 			    CPU_BASED_CR3_STORE_EXITING)
6388 				return true;
6389 			break;
6390 		case 8:
6391 			if (vmcs12->cpu_based_vm_exec_control &
6392 			    CPU_BASED_CR8_STORE_EXITING)
6393 				return true;
6394 			break;
6395 		}
6396 		break;
6397 	case 3: /* lmsw */
6398 		/*
6399 		 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
6400 		 * cr0. Other attempted changes are ignored, with no exit.
6401 		 */
6402 		val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6403 		if (vmcs12->cr0_guest_host_mask & 0xe &
6404 		    (val ^ vmcs12->cr0_read_shadow))
6405 			return true;
6406 		if ((vmcs12->cr0_guest_host_mask & 0x1) &&
6407 		    !(vmcs12->cr0_read_shadow & 0x1) &&
6408 		    (val & 0x1))
6409 			return true;
6410 		break;
6411 	}
6412 	return false;
6413 }
6414 
6415 static bool nested_vmx_exit_handled_encls(struct kvm_vcpu *vcpu,
6416 					  struct vmcs12 *vmcs12)
6417 {
6418 	u32 encls_leaf;
6419 
6420 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SGX) ||
6421 	    !nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENCLS_EXITING))
6422 		return false;
6423 
6424 	encls_leaf = kvm_eax_read(vcpu);
6425 	if (encls_leaf > 62)
6426 		encls_leaf = 63;
6427 	return vmcs12->encls_exiting_bitmap & BIT_ULL(encls_leaf);
6428 }
6429 
6430 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
6431 	struct vmcs12 *vmcs12, gpa_t bitmap)
6432 {
6433 	u32 vmx_instruction_info;
6434 	unsigned long field;
6435 	u8 b;
6436 
6437 	if (!nested_cpu_has_shadow_vmcs(vmcs12))
6438 		return true;
6439 
6440 	/* Decode instruction info and find the field to access */
6441 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6442 	field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
6443 
6444 	/* Out-of-range fields always cause a VM exit from L2 to L1 */
6445 	if (field >> 15)
6446 		return true;
6447 
6448 	if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
6449 		return true;
6450 
6451 	return 1 & (b >> (field & 7));
6452 }
6453 
6454 static bool nested_vmx_exit_handled_mtf(struct vmcs12 *vmcs12)
6455 {
6456 	u32 entry_intr_info = vmcs12->vm_entry_intr_info_field;
6457 
6458 	if (nested_cpu_has_mtf(vmcs12))
6459 		return true;
6460 
6461 	/*
6462 	 * An MTF VM-exit may be injected into the guest by setting the
6463 	 * interruption-type to 7 (other event) and the vector field to 0. Such
6464 	 * is the case regardless of the 'monitor trap flag' VM-execution
6465 	 * control.
6466 	 */
6467 	return entry_intr_info == (INTR_INFO_VALID_MASK
6468 				   | INTR_TYPE_OTHER_EVENT);
6469 }
6470 
6471 /*
6472  * Return true if L0 wants to handle an exit from L2 regardless of whether or not
6473  * L1 wants the exit.  Only call this when in is_guest_mode (L2).
6474  */
6475 static bool nested_vmx_l0_wants_exit(struct kvm_vcpu *vcpu,
6476 				     union vmx_exit_reason exit_reason)
6477 {
6478 	u32 intr_info;
6479 
6480 	switch ((u16)exit_reason.basic) {
6481 	case EXIT_REASON_EXCEPTION_NMI:
6482 		intr_info = vmx_get_intr_info(vcpu);
6483 		if (is_nmi(intr_info))
6484 			return true;
6485 		else if (is_page_fault(intr_info))
6486 			return vcpu->arch.apf.host_apf_flags ||
6487 			       vmx_need_pf_intercept(vcpu);
6488 		else if (is_debug(intr_info) &&
6489 			 vcpu->guest_debug &
6490 			 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6491 			return true;
6492 		else if (is_breakpoint(intr_info) &&
6493 			 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6494 			return true;
6495 		else if (is_alignment_check(intr_info) &&
6496 			 !vmx_guest_inject_ac(vcpu))
6497 			return true;
6498 		else if (is_ve_fault(intr_info))
6499 			return true;
6500 		return false;
6501 	case EXIT_REASON_EXTERNAL_INTERRUPT:
6502 		return true;
6503 	case EXIT_REASON_MCE_DURING_VMENTRY:
6504 		return true;
6505 	case EXIT_REASON_EPT_VIOLATION:
6506 		/*
6507 		 * L0 always deals with the EPT violation. If nested EPT is
6508 		 * used, and the nested mmu code discovers that the address is
6509 		 * missing in the guest EPT table (EPT12), the EPT violation
6510 		 * will be injected with nested_ept_inject_page_fault()
6511 		 */
6512 		return true;
6513 	case EXIT_REASON_EPT_MISCONFIG:
6514 		/*
6515 		 * L2 never uses directly L1's EPT, but rather L0's own EPT
6516 		 * table (shadow on EPT) or a merged EPT table that L0 built
6517 		 * (EPT on EPT). So any problems with the structure of the
6518 		 * table is L0's fault.
6519 		 */
6520 		return true;
6521 	case EXIT_REASON_PREEMPTION_TIMER:
6522 		return true;
6523 	case EXIT_REASON_PML_FULL:
6524 		/*
6525 		 * PML is emulated for an L1 VMM and should never be enabled in
6526 		 * vmcs02, always "handle" PML_FULL by exiting to userspace.
6527 		 */
6528 		return true;
6529 	case EXIT_REASON_VMFUNC:
6530 		/* VM functions are emulated through L2->L0 vmexits. */
6531 		return true;
6532 	case EXIT_REASON_BUS_LOCK:
6533 		/*
6534 		 * At present, bus lock VM exit is never exposed to L1.
6535 		 * Handle L2's bus locks in L0 directly.
6536 		 */
6537 		return true;
6538 #ifdef CONFIG_KVM_HYPERV
6539 	case EXIT_REASON_VMCALL:
6540 		/* Hyper-V L2 TLB flush hypercall is handled by L0 */
6541 		return guest_hv_cpuid_has_l2_tlb_flush(vcpu) &&
6542 			nested_evmcs_l2_tlb_flush_enabled(vcpu) &&
6543 			kvm_hv_is_tlb_flush_hcall(vcpu);
6544 #endif
6545 	case EXIT_REASON_CPUID:
6546 		return !kvm_is_cpuid_allowed(vcpu);
6547 	default:
6548 		break;
6549 	}
6550 	return false;
6551 }
6552 
6553 /*
6554  * Return 1 if L1 wants to intercept an exit from L2.  Only call this when in
6555  * is_guest_mode (L2).
6556  */
6557 static bool nested_vmx_l1_wants_exit(struct kvm_vcpu *vcpu,
6558 				     union vmx_exit_reason exit_reason)
6559 {
6560 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6561 	u32 intr_info;
6562 
6563 	switch ((u16)exit_reason.basic) {
6564 	case EXIT_REASON_EXCEPTION_NMI:
6565 		intr_info = vmx_get_intr_info(vcpu);
6566 		if (is_nmi(intr_info))
6567 			return true;
6568 		else if (is_page_fault(intr_info))
6569 			return true;
6570 		return vmcs12->exception_bitmap &
6571 				(1u << (intr_info & INTR_INFO_VECTOR_MASK));
6572 	case EXIT_REASON_EXTERNAL_INTERRUPT:
6573 		return nested_exit_on_intr(vcpu);
6574 	case EXIT_REASON_TRIPLE_FAULT:
6575 		return true;
6576 	case EXIT_REASON_INTERRUPT_WINDOW:
6577 		return nested_cpu_has(vmcs12, CPU_BASED_INTR_WINDOW_EXITING);
6578 	case EXIT_REASON_NMI_WINDOW:
6579 		return nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING);
6580 	case EXIT_REASON_TASK_SWITCH:
6581 		return true;
6582 	case EXIT_REASON_CPUID:
6583 		return true;
6584 	case EXIT_REASON_HLT:
6585 		return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
6586 	case EXIT_REASON_INVD:
6587 		return true;
6588 	case EXIT_REASON_INVLPG:
6589 		return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
6590 	case EXIT_REASON_RDPMC:
6591 		return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
6592 	case EXIT_REASON_RDRAND:
6593 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
6594 	case EXIT_REASON_RDSEED:
6595 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
6596 	case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
6597 		return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
6598 	case EXIT_REASON_VMREAD:
6599 		return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
6600 			vmcs12->vmread_bitmap);
6601 	case EXIT_REASON_VMWRITE:
6602 		return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
6603 			vmcs12->vmwrite_bitmap);
6604 	case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
6605 	case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
6606 	case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
6607 	case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
6608 	case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
6609 		/*
6610 		 * VMX instructions trap unconditionally. This allows L1 to
6611 		 * emulate them for its L2 guest, i.e., allows 3-level nesting!
6612 		 */
6613 		return true;
6614 	case EXIT_REASON_CR_ACCESS:
6615 		return nested_vmx_exit_handled_cr(vcpu, vmcs12);
6616 	case EXIT_REASON_DR_ACCESS:
6617 		return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
6618 	case EXIT_REASON_IO_INSTRUCTION:
6619 		return nested_vmx_exit_handled_io(vcpu, vmcs12);
6620 	case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
6621 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
6622 	case EXIT_REASON_MSR_READ:
6623 	case EXIT_REASON_MSR_WRITE:
6624 	case EXIT_REASON_MSR_READ_IMM:
6625 	case EXIT_REASON_MSR_WRITE_IMM:
6626 		return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
6627 	case EXIT_REASON_INVALID_STATE:
6628 		return true;
6629 	case EXIT_REASON_MWAIT_INSTRUCTION:
6630 		return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
6631 	case EXIT_REASON_MONITOR_TRAP_FLAG:
6632 		return nested_vmx_exit_handled_mtf(vmcs12);
6633 	case EXIT_REASON_MONITOR_INSTRUCTION:
6634 		return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
6635 	case EXIT_REASON_PAUSE_INSTRUCTION:
6636 		return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
6637 			nested_cpu_has2(vmcs12,
6638 				SECONDARY_EXEC_PAUSE_LOOP_EXITING);
6639 	case EXIT_REASON_MCE_DURING_VMENTRY:
6640 		return true;
6641 	case EXIT_REASON_TPR_BELOW_THRESHOLD:
6642 		return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
6643 	case EXIT_REASON_APIC_ACCESS:
6644 	case EXIT_REASON_APIC_WRITE:
6645 	case EXIT_REASON_EOI_INDUCED:
6646 		/*
6647 		 * The controls for "virtualize APIC accesses," "APIC-
6648 		 * register virtualization," and "virtual-interrupt
6649 		 * delivery" only come from vmcs12.
6650 		 */
6651 		return true;
6652 	case EXIT_REASON_INVPCID:
6653 		return
6654 			nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
6655 			nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
6656 	case EXIT_REASON_WBINVD:
6657 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
6658 	case EXIT_REASON_XSETBV:
6659 		return true;
6660 	case EXIT_REASON_XSAVES:
6661 	case EXIT_REASON_XRSTORS:
6662 		/*
6663 		 * Always forward XSAVES/XRSTORS to L1 as KVM doesn't utilize
6664 		 * XSS-bitmap, and always loads vmcs02 with vmcs12's XSS-bitmap
6665 		 * verbatim, i.e. any exit is due to L1's bitmap.  WARN if
6666 		 * XSAVES isn't enabled, as the CPU is supposed to inject #UD
6667 		 * in that case, before consulting the XSS-bitmap.
6668 		 */
6669 		WARN_ON_ONCE(!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_XSAVES));
6670 		return true;
6671 	case EXIT_REASON_UMWAIT:
6672 	case EXIT_REASON_TPAUSE:
6673 		return nested_cpu_has2(vmcs12,
6674 			SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE);
6675 	case EXIT_REASON_ENCLS:
6676 		return nested_vmx_exit_handled_encls(vcpu, vmcs12);
6677 	case EXIT_REASON_NOTIFY:
6678 		/* Notify VM exit is not exposed to L1 */
6679 		return false;
6680 	case EXIT_REASON_SEAMCALL:
6681 	case EXIT_REASON_TDCALL:
6682 		/*
6683 		 * SEAMCALL and TDCALL unconditionally VM-Exit, but aren't
6684 		 * virtualized by KVM for L1 hypervisors, i.e. L1 should
6685 		 * never want or expect such an exit.
6686 		 */
6687 		return false;
6688 	default:
6689 		return true;
6690 	}
6691 }
6692 
6693 /*
6694  * Conditionally reflect a VM-Exit into L1.  Returns %true if the VM-Exit was
6695  * reflected into L1.
6696  */
6697 bool nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu)
6698 {
6699 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6700 	union vmx_exit_reason exit_reason = vmx->vt.exit_reason;
6701 	unsigned long exit_qual;
6702 	u32 exit_intr_info;
6703 
6704 	kvm_warn_on_nested_run_pending(vcpu);
6705 
6706 	/*
6707 	 * Late nested VM-Fail shares the same flow as nested VM-Exit since KVM
6708 	 * has already loaded L2's state.
6709 	 */
6710 	if (unlikely(vmx->fail)) {
6711 		trace_kvm_nested_vmenter_failed(
6712 			"hardware VM-instruction error: ",
6713 			vmcs_read32(VM_INSTRUCTION_ERROR));
6714 		exit_intr_info = 0;
6715 		exit_qual = 0;
6716 		goto reflect_vmexit;
6717 	}
6718 
6719 	trace_kvm_nested_vmexit(vcpu, KVM_ISA_VMX);
6720 
6721 	/* If L0 (KVM) wants the exit, it trumps L1's desires. */
6722 	if (nested_vmx_l0_wants_exit(vcpu, exit_reason))
6723 		return false;
6724 
6725 	/* If L1 doesn't want the exit, handle it in L0. */
6726 	if (!nested_vmx_l1_wants_exit(vcpu, exit_reason))
6727 		return false;
6728 
6729 	/*
6730 	 * vmcs.VM_EXIT_INTR_INFO is only valid for EXCEPTION_NMI exits.  For
6731 	 * EXTERNAL_INTERRUPT, the value for vmcs12->vm_exit_intr_info would
6732 	 * need to be synthesized by querying the in-kernel LAPIC, but external
6733 	 * interrupts are never reflected to L1 so it's a non-issue.
6734 	 */
6735 	exit_intr_info = vmx_get_intr_info(vcpu);
6736 	if (is_exception_with_error_code(exit_intr_info)) {
6737 		struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6738 
6739 		vmcs12->vm_exit_intr_error_code =
6740 			vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6741 	}
6742 	exit_qual = vmx_get_exit_qual(vcpu);
6743 
6744 reflect_vmexit:
6745 	nested_vmx_vmexit(vcpu, exit_reason.full, exit_intr_info, exit_qual);
6746 	return true;
6747 }
6748 
6749 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
6750 				struct kvm_nested_state __user *user_kvm_nested_state,
6751 				u32 user_data_size)
6752 {
6753 	struct vcpu_vmx *vmx;
6754 	struct vmcs12 *vmcs12;
6755 	struct kvm_nested_state kvm_state = {
6756 		.flags = 0,
6757 		.format = KVM_STATE_NESTED_FORMAT_VMX,
6758 		.size = sizeof(kvm_state),
6759 		.hdr.vmx.flags = 0,
6760 		.hdr.vmx.vmxon_pa = INVALID_GPA,
6761 		.hdr.vmx.vmcs12_pa = INVALID_GPA,
6762 		.hdr.vmx.preemption_timer_deadline = 0,
6763 	};
6764 	struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
6765 		&user_kvm_nested_state->data.vmx[0];
6766 
6767 	if (!vcpu)
6768 		return kvm_state.size + sizeof(*user_vmx_nested_state);
6769 
6770 	vmx = to_vmx(vcpu);
6771 	vmcs12 = get_vmcs12(vcpu);
6772 
6773 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_VMX) &&
6774 	    (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
6775 		kvm_state.hdr.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
6776 		kvm_state.hdr.vmx.vmcs12_pa = vmx->nested.current_vmptr;
6777 
6778 		if (vmx_has_valid_vmcs12(vcpu)) {
6779 			kvm_state.size += sizeof(user_vmx_nested_state->vmcs12);
6780 
6781 			/* 'hv_evmcs_vmptr' can also be EVMPTR_MAP_PENDING here */
6782 			if (nested_vmx_is_evmptr12_set(vmx))
6783 				kvm_state.flags |= KVM_STATE_NESTED_EVMCS;
6784 
6785 			if (is_guest_mode(vcpu) &&
6786 			    nested_cpu_has_shadow_vmcs(vmcs12) &&
6787 			    vmcs12->vmcs_link_pointer != INVALID_GPA)
6788 				kvm_state.size += sizeof(user_vmx_nested_state->shadow_vmcs12);
6789 		}
6790 
6791 		if (vmx->nested.smm.vmxon)
6792 			kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
6793 
6794 		if (vmx->nested.smm.guest_mode)
6795 			kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
6796 
6797 		if (is_guest_mode(vcpu)) {
6798 			kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
6799 
6800 			if (vcpu->arch.nested_run_pending)
6801 				kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
6802 
6803 			if (vmx->nested.mtf_pending)
6804 				kvm_state.flags |= KVM_STATE_NESTED_MTF_PENDING;
6805 
6806 			if (nested_cpu_has_preemption_timer(vmcs12) &&
6807 			    vmx->nested.has_preemption_timer_deadline) {
6808 				kvm_state.hdr.vmx.flags |=
6809 					KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE;
6810 				kvm_state.hdr.vmx.preemption_timer_deadline =
6811 					vmx->nested.preemption_timer_deadline;
6812 			}
6813 		}
6814 	}
6815 
6816 	if (user_data_size < kvm_state.size)
6817 		goto out;
6818 
6819 	if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
6820 		return -EFAULT;
6821 
6822 	if (!vmx_has_valid_vmcs12(vcpu))
6823 		goto out;
6824 
6825 	/*
6826 	 * When running L2, the authoritative vmcs12 state is in the
6827 	 * vmcs02. When running L1, the authoritative vmcs12 state is
6828 	 * in the shadow or enlightened vmcs linked to vmcs01, unless
6829 	 * need_vmcs12_to_shadow_sync is set, in which case, the authoritative
6830 	 * vmcs12 state is in the vmcs12 already.
6831 	 */
6832 	if (is_guest_mode(vcpu)) {
6833 		sync_vmcs02_to_vmcs12(vcpu, vmcs12);
6834 		sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
6835 	} else  {
6836 		copy_vmcs02_to_vmcs12_rare(vcpu, get_vmcs12(vcpu));
6837 		if (!vmx->nested.need_vmcs12_to_shadow_sync) {
6838 			if (nested_vmx_is_evmptr12_valid(vmx))
6839 				/*
6840 				 * L1 hypervisor is not obliged to keep eVMCS
6841 				 * clean fields data always up-to-date while
6842 				 * not in guest mode, 'hv_clean_fields' is only
6843 				 * supposed to be actual upon vmentry so we need
6844 				 * to ignore it here and do full copy.
6845 				 */
6846 				copy_enlightened_to_vmcs12(vmx, 0);
6847 			else if (enable_shadow_vmcs)
6848 				copy_shadow_to_vmcs12(vmx);
6849 		}
6850 	}
6851 
6852 	BUILD_BUG_ON(sizeof(user_vmx_nested_state->vmcs12) < VMCS12_SIZE);
6853 	BUILD_BUG_ON(sizeof(user_vmx_nested_state->shadow_vmcs12) < VMCS12_SIZE);
6854 
6855 	/*
6856 	 * Copy over the full allocated size of vmcs12 rather than just the size
6857 	 * of the struct.
6858 	 */
6859 	if (copy_to_user(user_vmx_nested_state->vmcs12, vmcs12, VMCS12_SIZE))
6860 		return -EFAULT;
6861 
6862 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
6863 	    vmcs12->vmcs_link_pointer != INVALID_GPA) {
6864 		if (copy_to_user(user_vmx_nested_state->shadow_vmcs12,
6865 				 get_shadow_vmcs12(vcpu), VMCS12_SIZE))
6866 			return -EFAULT;
6867 	}
6868 out:
6869 	return kvm_state.size;
6870 }
6871 
6872 void vmx_leave_nested(struct kvm_vcpu *vcpu)
6873 {
6874 	if (is_guest_mode(vcpu)) {
6875 		vcpu->arch.nested_run_pending = 0;
6876 		nested_vmx_vmexit(vcpu, -1, 0, 0);
6877 	}
6878 	free_nested(vcpu);
6879 }
6880 
6881 int nested_vmx_check_restored_vmcs12(struct kvm_vcpu *vcpu)
6882 {
6883 	enum vm_entry_failure_code ignored;
6884 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6885 
6886 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
6887 	    vmcs12->vmcs_link_pointer != INVALID_GPA) {
6888 		struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
6889 
6890 		if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
6891 		    !shadow_vmcs12->hdr.shadow_vmcs)
6892 			return -EINVAL;
6893 	}
6894 
6895 	if (nested_vmx_check_controls(vcpu, vmcs12) ||
6896 	    nested_vmx_check_host_state(vcpu, vmcs12) ||
6897 	    nested_vmx_check_guest_state(vcpu, vmcs12, &ignored))
6898 		return -EINVAL;
6899 
6900 	return 0;
6901 }
6902 
6903 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
6904 				struct kvm_nested_state __user *user_kvm_nested_state,
6905 				struct kvm_nested_state *kvm_state)
6906 {
6907 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6908 	struct vmcs12 *vmcs12;
6909 	struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
6910 		&user_kvm_nested_state->data.vmx[0];
6911 	int ret;
6912 
6913 	if (kvm_state->format != KVM_STATE_NESTED_FORMAT_VMX)
6914 		return -EINVAL;
6915 
6916 	if (kvm_state->hdr.vmx.vmxon_pa == INVALID_GPA) {
6917 		if (kvm_state->hdr.vmx.smm.flags)
6918 			return -EINVAL;
6919 
6920 		if (kvm_state->hdr.vmx.vmcs12_pa != INVALID_GPA)
6921 			return -EINVAL;
6922 
6923 		/*
6924 		 * KVM_STATE_NESTED_EVMCS used to signal that KVM should
6925 		 * enable eVMCS capability on vCPU. However, since then
6926 		 * code was changed such that flag signals vmcs12 should
6927 		 * be copied into eVMCS in guest memory.
6928 		 *
6929 		 * To preserve backwards compatibility, allow user
6930 		 * to set this flag even when there is no VMXON region.
6931 		 */
6932 		if (kvm_state->flags & ~KVM_STATE_NESTED_EVMCS)
6933 			return -EINVAL;
6934 	} else {
6935 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_VMX))
6936 			return -EINVAL;
6937 
6938 		if (!page_address_valid(vcpu, kvm_state->hdr.vmx.vmxon_pa))
6939 			return -EINVAL;
6940 	}
6941 
6942 	if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6943 	    (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
6944 		return -EINVAL;
6945 
6946 	if (kvm_state->hdr.vmx.smm.flags &
6947 	    ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
6948 		return -EINVAL;
6949 
6950 	if (kvm_state->hdr.vmx.flags & ~KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE)
6951 		return -EINVAL;
6952 
6953 	/*
6954 	 * SMM temporarily disables VMX, so we cannot be in guest mode,
6955 	 * nor can VMLAUNCH/VMRESUME be pending.  Outside SMM, SMM flags
6956 	 * must be zero.
6957 	 */
6958 	if (is_smm(vcpu) ?
6959 		(kvm_state->flags &
6960 		 (KVM_STATE_NESTED_GUEST_MODE | KVM_STATE_NESTED_RUN_PENDING))
6961 		: kvm_state->hdr.vmx.smm.flags)
6962 		return -EINVAL;
6963 
6964 	if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6965 	    !(kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
6966 		return -EINVAL;
6967 
6968 	if ((kvm_state->flags & KVM_STATE_NESTED_EVMCS) &&
6969 	    (!guest_cpu_cap_has(vcpu, X86_FEATURE_VMX) ||
6970 	     !vmx->nested.enlightened_vmcs_enabled))
6971 			return -EINVAL;
6972 
6973 	vmx_leave_nested(vcpu);
6974 
6975 	if (kvm_state->hdr.vmx.vmxon_pa == INVALID_GPA)
6976 		return 0;
6977 
6978 	vmx->nested.vmxon_ptr = kvm_state->hdr.vmx.vmxon_pa;
6979 	ret = enter_vmx_operation(vcpu);
6980 	if (ret)
6981 		return ret;
6982 
6983 	/* Empty 'VMXON' state is permitted if no VMCS loaded */
6984 	if (kvm_state->size < sizeof(*kvm_state) + sizeof(*vmcs12)) {
6985 		/* See vmx_has_valid_vmcs12.  */
6986 		if ((kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE) ||
6987 		    (kvm_state->flags & KVM_STATE_NESTED_EVMCS) ||
6988 		    (kvm_state->hdr.vmx.vmcs12_pa != INVALID_GPA))
6989 			return -EINVAL;
6990 		else
6991 			return 0;
6992 	}
6993 
6994 	if (kvm_state->hdr.vmx.vmcs12_pa != INVALID_GPA) {
6995 		if (kvm_state->hdr.vmx.vmcs12_pa == kvm_state->hdr.vmx.vmxon_pa ||
6996 		    !page_address_valid(vcpu, kvm_state->hdr.vmx.vmcs12_pa))
6997 			return -EINVAL;
6998 
6999 		set_current_vmptr(vmx, kvm_state->hdr.vmx.vmcs12_pa);
7000 #ifdef CONFIG_KVM_HYPERV
7001 	} else if (kvm_state->flags & KVM_STATE_NESTED_EVMCS) {
7002 		/*
7003 		 * nested_vmx_handle_enlightened_vmptrld() cannot be called
7004 		 * directly from here as HV_X64_MSR_VP_ASSIST_PAGE may not be
7005 		 * restored yet. EVMCS will be mapped from
7006 		 * nested_get_vmcs12_pages().
7007 		 */
7008 		vmx->nested.hv_evmcs_vmptr = EVMPTR_MAP_PENDING;
7009 		kvm_make_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
7010 #endif
7011 	} else {
7012 		return -EINVAL;
7013 	}
7014 
7015 	if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
7016 		vmx->nested.smm.vmxon = true;
7017 		vmx->nested.vmxon = false;
7018 
7019 		if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
7020 			vmx->nested.smm.guest_mode = true;
7021 	}
7022 
7023 	vmcs12 = get_vmcs12(vcpu);
7024 	if (copy_from_user(vmcs12, user_vmx_nested_state->vmcs12, sizeof(*vmcs12)))
7025 		return -EFAULT;
7026 
7027 	if (vmcs12->hdr.revision_id != VMCS12_REVISION)
7028 		return -EINVAL;
7029 
7030 	if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
7031 		return 0;
7032 
7033 	if (kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING)
7034 		vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING_UNTRUSTED;
7035 	else
7036 		vcpu->arch.nested_run_pending = 0;
7037 
7038 	vmx->nested.mtf_pending =
7039 		!!(kvm_state->flags & KVM_STATE_NESTED_MTF_PENDING);
7040 
7041 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
7042 	    vmcs12->vmcs_link_pointer != INVALID_GPA) {
7043 		struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
7044 
7045 		ret = -EINVAL;
7046 		if (kvm_state->size <
7047 		    sizeof(*kvm_state) +
7048 		    sizeof(user_vmx_nested_state->vmcs12) + sizeof(*shadow_vmcs12))
7049 			goto error_guest_mode;
7050 
7051 		ret = -EFAULT;
7052 		if (copy_from_user(shadow_vmcs12,
7053 				   user_vmx_nested_state->shadow_vmcs12,
7054 				   sizeof(*shadow_vmcs12)))
7055 			goto error_guest_mode;
7056 	}
7057 
7058 	vmx->nested.has_preemption_timer_deadline = false;
7059 	if (kvm_state->hdr.vmx.flags & KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE) {
7060 		vmx->nested.has_preemption_timer_deadline = true;
7061 		vmx->nested.preemption_timer_deadline =
7062 			kvm_state->hdr.vmx.preemption_timer_deadline;
7063 	}
7064 
7065 	ret = nested_vmx_check_restored_vmcs12(vcpu);
7066 	if (ret < 0)
7067 		goto error_guest_mode;
7068 
7069 	vmx->nested.dirty_vmcs12 = true;
7070 	vmx->nested.force_msr_bitmap_recalc = true;
7071 	ret = nested_vmx_enter_non_root_mode(vcpu, false);
7072 	if (ret)
7073 		goto error_guest_mode;
7074 
7075 	if (vmx->nested.mtf_pending)
7076 		kvm_make_request(KVM_REQ_EVENT, vcpu);
7077 
7078 	return 0;
7079 
7080 error_guest_mode:
7081 	vcpu->arch.nested_run_pending = 0;
7082 	return ret;
7083 }
7084 
7085 void nested_vmx_set_vmcs_shadowing_bitmap(void)
7086 {
7087 	if (enable_shadow_vmcs) {
7088 		vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
7089 		vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
7090 	}
7091 }
7092 
7093 static u64 nested_vmx_calc_vmcs_enum_msr(void)
7094 {
7095 	/*
7096 	 * Note these are the so called "index" of the VMCS field encoding, not
7097 	 * the index into vmcs12.
7098 	 */
7099 	unsigned int max_idx, idx;
7100 	int i;
7101 
7102 	/*
7103 	 * For better or worse, KVM allows VMREAD/VMWRITE to all fields in
7104 	 * vmcs12, regardless of whether or not the associated feature is
7105 	 * exposed to L1.  Simply find the field with the highest index.
7106 	 */
7107 	max_idx = 0;
7108 	for (i = 0; i < nr_vmcs12_fields; i++) {
7109 		/* The vmcs12 table is very, very sparsely populated. */
7110 		if (!vmcs12_field_offsets[i])
7111 			continue;
7112 
7113 		idx = vmcs_field_index(VMCS12_IDX_TO_ENC(i));
7114 		if (idx > max_idx)
7115 			max_idx = idx;
7116 	}
7117 
7118 	return (u64)max_idx << VMCS_FIELD_INDEX_SHIFT;
7119 }
7120 
7121 static void nested_vmx_setup_pinbased_ctls(struct vmcs_config *vmcs_conf,
7122 					   struct nested_vmx_msrs *msrs)
7123 {
7124 	msrs->pinbased_ctls_low =
7125 		PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
7126 
7127 	msrs->pinbased_ctls_high = vmcs_conf->pin_based_exec_ctrl;
7128 	msrs->pinbased_ctls_high &=
7129 		PIN_BASED_EXT_INTR_MASK |
7130 		PIN_BASED_NMI_EXITING |
7131 		PIN_BASED_VIRTUAL_NMIS |
7132 		(enable_apicv ? PIN_BASED_POSTED_INTR : 0);
7133 	msrs->pinbased_ctls_high |=
7134 		PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
7135 		PIN_BASED_VMX_PREEMPTION_TIMER;
7136 }
7137 
7138 static void nested_vmx_setup_exit_ctls(struct vmcs_config *vmcs_conf,
7139 				       struct nested_vmx_msrs *msrs)
7140 {
7141 	msrs->exit_ctls_low =
7142 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
7143 
7144 	msrs->exit_ctls_high = vmcs_conf->vmexit_ctrl;
7145 	msrs->exit_ctls_high &=
7146 #ifdef CONFIG_X86_64
7147 		VM_EXIT_HOST_ADDR_SPACE_SIZE |
7148 #endif
7149 		VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT |
7150 		VM_EXIT_CLEAR_BNDCFGS | VM_EXIT_LOAD_CET_STATE;
7151 	msrs->exit_ctls_high |=
7152 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
7153 		VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
7154 		VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT |
7155 		VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
7156 
7157 	if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
7158 	    !kvm_cpu_cap_has(X86_FEATURE_IBT))
7159 		msrs->exit_ctls_high &= ~VM_EXIT_LOAD_CET_STATE;
7160 
7161 	/* We support free control of debug control saving. */
7162 	msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
7163 }
7164 
7165 static void nested_vmx_setup_entry_ctls(struct vmcs_config *vmcs_conf,
7166 					struct nested_vmx_msrs *msrs)
7167 {
7168 	msrs->entry_ctls_low =
7169 		VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
7170 
7171 	msrs->entry_ctls_high = vmcs_conf->vmentry_ctrl;
7172 	msrs->entry_ctls_high &=
7173 #ifdef CONFIG_X86_64
7174 		VM_ENTRY_IA32E_MODE |
7175 #endif
7176 		VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS |
7177 		VM_ENTRY_LOAD_CET_STATE;
7178 	msrs->entry_ctls_high |=
7179 		(VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER |
7180 		 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL);
7181 
7182 	if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
7183 	    !kvm_cpu_cap_has(X86_FEATURE_IBT))
7184 		msrs->entry_ctls_high &= ~VM_ENTRY_LOAD_CET_STATE;
7185 
7186 	/* We support free control of debug control loading. */
7187 	msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
7188 }
7189 
7190 static void nested_vmx_setup_cpubased_ctls(struct vmcs_config *vmcs_conf,
7191 					   struct nested_vmx_msrs *msrs)
7192 {
7193 	msrs->procbased_ctls_low =
7194 		CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
7195 
7196 	msrs->procbased_ctls_high = vmcs_conf->cpu_based_exec_ctrl;
7197 	msrs->procbased_ctls_high &=
7198 		CPU_BASED_INTR_WINDOW_EXITING |
7199 		CPU_BASED_NMI_WINDOW_EXITING | CPU_BASED_USE_TSC_OFFSETTING |
7200 		CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
7201 		CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
7202 		CPU_BASED_CR3_STORE_EXITING |
7203 #ifdef CONFIG_X86_64
7204 		CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
7205 #endif
7206 		CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
7207 		CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
7208 		CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
7209 		CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
7210 		CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
7211 	/*
7212 	 * We can allow some features even when not supported by the
7213 	 * hardware. For example, L1 can specify an MSR bitmap - and we
7214 	 * can use it to avoid exits to L1 - even when L0 runs L2
7215 	 * without MSR bitmaps.
7216 	 */
7217 	msrs->procbased_ctls_high |=
7218 		CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
7219 		CPU_BASED_USE_MSR_BITMAPS;
7220 
7221 	/* We support free control of CR3 access interception. */
7222 	msrs->procbased_ctls_low &=
7223 		~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
7224 }
7225 
7226 static void nested_vmx_setup_secondary_ctls(u32 ept_caps,
7227 					    struct vmcs_config *vmcs_conf,
7228 					    struct nested_vmx_msrs *msrs)
7229 {
7230 	msrs->secondary_ctls_low = 0;
7231 
7232 	msrs->secondary_ctls_high = vmcs_conf->cpu_based_2nd_exec_ctrl;
7233 	msrs->secondary_ctls_high &=
7234 		SECONDARY_EXEC_DESC |
7235 		SECONDARY_EXEC_ENABLE_RDTSCP |
7236 		SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7237 		SECONDARY_EXEC_WBINVD_EXITING |
7238 		SECONDARY_EXEC_APIC_REGISTER_VIRT |
7239 		SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
7240 		SECONDARY_EXEC_RDRAND_EXITING |
7241 		SECONDARY_EXEC_ENABLE_INVPCID |
7242 		SECONDARY_EXEC_ENABLE_VMFUNC |
7243 		SECONDARY_EXEC_RDSEED_EXITING |
7244 		SECONDARY_EXEC_ENABLE_XSAVES |
7245 		SECONDARY_EXEC_TSC_SCALING |
7246 		SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
7247 
7248 	/*
7249 	 * We can emulate "VMCS shadowing," even if the hardware
7250 	 * doesn't support it.
7251 	 */
7252 	msrs->secondary_ctls_high |=
7253 		SECONDARY_EXEC_SHADOW_VMCS;
7254 
7255 	if (enable_ept) {
7256 		/* nested EPT: emulate EPT also to L1 */
7257 		msrs->secondary_ctls_high |=
7258 			SECONDARY_EXEC_ENABLE_EPT;
7259 		msrs->ept_caps =
7260 			VMX_EPT_PAGE_WALK_4_BIT |
7261 			VMX_EPT_PAGE_WALK_5_BIT |
7262 			VMX_EPTP_WB_BIT |
7263 			VMX_EPT_INVEPT_BIT |
7264 			VMX_EPT_EXECUTE_ONLY_BIT |
7265 			VMX_EPT_ADVANCED_VMEXIT_INFO_BIT;
7266 
7267 		msrs->ept_caps &= ept_caps;
7268 		msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
7269 			VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
7270 			VMX_EPT_1GB_PAGE_BIT;
7271 		if (enable_ept_ad_bits) {
7272 			msrs->secondary_ctls_high |=
7273 				SECONDARY_EXEC_ENABLE_PML;
7274 			msrs->ept_caps |= VMX_EPT_AD_BIT;
7275 		}
7276 
7277 		if (enable_mbec)
7278 			msrs->secondary_ctls_high |=
7279 				SECONDARY_EXEC_MODE_BASED_EPT_EXEC;
7280 		/*
7281 		 * Advertise EPTP switching irrespective of hardware support,
7282 		 * KVM emulates it in software so long as VMFUNC is supported.
7283 		 */
7284 		if (cpu_has_vmx_vmfunc())
7285 			msrs->vmfunc_controls = VMX_VMFUNC_EPTP_SWITCHING;
7286 	}
7287 
7288 	/*
7289 	 * Old versions of KVM use the single-context version without
7290 	 * checking for support, so declare that it is supported even
7291 	 * though it is treated as global context.  The alternative is
7292 	 * not failing the single-context invvpid, and it is worse.
7293 	 */
7294 	if (enable_vpid) {
7295 		msrs->secondary_ctls_high |=
7296 			SECONDARY_EXEC_ENABLE_VPID;
7297 		msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
7298 			VMX_VPID_EXTENT_SUPPORTED_MASK;
7299 	}
7300 
7301 	if (enable_unrestricted_guest)
7302 		msrs->secondary_ctls_high |=
7303 			SECONDARY_EXEC_UNRESTRICTED_GUEST;
7304 
7305 	if (flexpriority_enabled)
7306 		msrs->secondary_ctls_high |=
7307 			SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7308 
7309 	if (enable_sgx)
7310 		msrs->secondary_ctls_high |= SECONDARY_EXEC_ENCLS_EXITING;
7311 }
7312 
7313 static void nested_vmx_setup_misc_data(struct vmcs_config *vmcs_conf,
7314 				       struct nested_vmx_msrs *msrs)
7315 {
7316 	msrs->misc_low = (u32)vmcs_conf->misc & VMX_MISC_SAVE_EFER_LMA;
7317 	msrs->misc_low |=
7318 		VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
7319 		VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
7320 		VMX_MISC_ACTIVITY_HLT |
7321 		VMX_MISC_ACTIVITY_WAIT_SIPI;
7322 	msrs->misc_high = 0;
7323 }
7324 
7325 static void nested_vmx_setup_basic(struct nested_vmx_msrs *msrs)
7326 {
7327 	/*
7328 	 * This MSR reports some information about VMX support. We
7329 	 * should return information about the VMX we emulate for the
7330 	 * guest, and the VMCS structure we give it - not about the
7331 	 * VMX support of the underlying hardware.
7332 	 */
7333 	msrs->basic = vmx_basic_encode_vmcs_info(VMCS12_REVISION, VMCS12_SIZE,
7334 						 X86_MEMTYPE_WB);
7335 
7336 	msrs->basic |= VMX_BASIC_TRUE_CTLS;
7337 	if (cpu_has_vmx_basic_inout())
7338 		msrs->basic |= VMX_BASIC_INOUT;
7339 	if (cpu_has_vmx_basic_no_hw_errcode_cc())
7340 		msrs->basic |= VMX_BASIC_NO_HW_ERROR_CODE_CC;
7341 }
7342 
7343 static void nested_vmx_setup_cr_fixed(struct nested_vmx_msrs *msrs)
7344 {
7345 	/*
7346 	 * These MSRs specify bits which the guest must keep fixed on
7347 	 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
7348 	 * We picked the standard core2 setting.
7349 	 */
7350 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
7351 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
7352 	msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
7353 	msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
7354 
7355 	/* These MSRs specify bits which the guest must keep fixed off. */
7356 	rdmsrq(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
7357 	rdmsrq(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
7358 
7359 	if (vmx_umip_emulated())
7360 		msrs->cr4_fixed1 |= X86_CR4_UMIP;
7361 }
7362 
7363 /*
7364  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
7365  * returned for the various VMX controls MSRs when nested VMX is enabled.
7366  * The same values should also be used to verify that vmcs12 control fields are
7367  * valid during nested entry from L1 to L2.
7368  * Each of these control msrs has a low and high 32-bit half: A low bit is on
7369  * if the corresponding bit in the (32-bit) control field *must* be on, and a
7370  * bit in the high half is on if the corresponding bit in the control field
7371  * may be on. See also vmx_control_verify().
7372  */
7373 void nested_vmx_setup_ctls_msrs(struct vmcs_config *vmcs_conf, u32 ept_caps)
7374 {
7375 	struct nested_vmx_msrs *msrs = &vmcs_conf->nested;
7376 
7377 	/*
7378 	 * Note that as a general rule, the high half of the MSRs (bits in
7379 	 * the control fields which may be 1) should be initialized by the
7380 	 * intersection of the underlying hardware's MSR (i.e., features which
7381 	 * can be supported) and the list of features we want to expose -
7382 	 * because they are known to be properly supported in our code.
7383 	 * Also, usually, the low half of the MSRs (bits which must be 1) can
7384 	 * be set to 0, meaning that L1 may turn off any of these bits. The
7385 	 * reason is that if one of these bits is necessary, it will appear
7386 	 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
7387 	 * fields of vmcs01 and vmcs02, will turn these bits off - and
7388 	 * nested_vmx_l1_wants_exit() will not pass related exits to L1.
7389 	 * These rules have exceptions below.
7390 	 */
7391 	nested_vmx_setup_pinbased_ctls(vmcs_conf, msrs);
7392 
7393 	nested_vmx_setup_exit_ctls(vmcs_conf, msrs);
7394 
7395 	nested_vmx_setup_entry_ctls(vmcs_conf, msrs);
7396 
7397 	nested_vmx_setup_cpubased_ctls(vmcs_conf, msrs);
7398 
7399 	nested_vmx_setup_secondary_ctls(ept_caps, vmcs_conf, msrs);
7400 
7401 	nested_vmx_setup_misc_data(vmcs_conf, msrs);
7402 
7403 	nested_vmx_setup_basic(msrs);
7404 
7405 	nested_vmx_setup_cr_fixed(msrs);
7406 
7407 	msrs->vmcs_enum = nested_vmx_calc_vmcs_enum_msr();
7408 }
7409 
7410 void nested_vmx_hardware_unsetup(void)
7411 {
7412 	int i;
7413 
7414 	if (enable_shadow_vmcs) {
7415 		for (i = 0; i < VMX_BITMAP_NR; i++)
7416 			free_page((unsigned long)vmx_bitmap[i]);
7417 	}
7418 }
7419 
7420 __init int nested_vmx_hardware_setup(int (*exit_handlers[])(struct kvm_vcpu *))
7421 {
7422 	int i;
7423 
7424 	/*
7425 	 * Note!  The set of supported vmcs12 fields is consumed by both VMX
7426 	 * MSR and shadow VMCS setup.
7427 	 */
7428 	nested_vmx_setup_vmcs12_fields();
7429 
7430 	nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
7431 
7432 	if (!cpu_has_vmx_shadow_vmcs())
7433 		enable_shadow_vmcs = 0;
7434 	if (enable_shadow_vmcs) {
7435 		for (i = 0; i < VMX_BITMAP_NR; i++) {
7436 			/*
7437 			 * The vmx_bitmap is not tied to a VM and so should
7438 			 * not be charged to a memcg.
7439 			 */
7440 			vmx_bitmap[i] = (unsigned long *)
7441 				__get_free_page(GFP_KERNEL);
7442 			if (!vmx_bitmap[i]) {
7443 				nested_vmx_hardware_unsetup();
7444 				return -ENOMEM;
7445 			}
7446 		}
7447 
7448 		init_vmcs_shadow_fields();
7449 	}
7450 
7451 	exit_handlers[EXIT_REASON_VMCLEAR]	= handle_vmclear;
7452 	exit_handlers[EXIT_REASON_VMLAUNCH]	= handle_vmlaunch;
7453 	exit_handlers[EXIT_REASON_VMPTRLD]	= handle_vmptrld;
7454 	exit_handlers[EXIT_REASON_VMPTRST]	= handle_vmptrst;
7455 	exit_handlers[EXIT_REASON_VMREAD]	= handle_vmread;
7456 	exit_handlers[EXIT_REASON_VMRESUME]	= handle_vmresume;
7457 	exit_handlers[EXIT_REASON_VMWRITE]	= handle_vmwrite;
7458 	exit_handlers[EXIT_REASON_VMOFF]	= handle_vmxoff;
7459 	exit_handlers[EXIT_REASON_VMON]		= handle_vmxon;
7460 	exit_handlers[EXIT_REASON_INVEPT]	= handle_invept;
7461 	exit_handlers[EXIT_REASON_INVVPID]	= handle_invvpid;
7462 	exit_handlers[EXIT_REASON_VMFUNC]	= handle_vmfunc;
7463 
7464 	return 0;
7465 }
7466 
7467 
7468 static gpa_t vmx_translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa,
7469 				      u64 access,
7470 				      struct x86_exception *exception,
7471 				      u64 pte_access)
7472 {
7473 	struct kvm_pagewalk *w = &vcpu->arch.ngpa_walk;
7474 
7475 	if (WARN_ON_ONCE(!mmu_is_nested(vcpu)))
7476 		return gpa;
7477 
7478 	/*
7479 	 * MBEC differentiates based on the effective U/S bit of
7480 	 * the guest page tables; not the processor CPL.
7481 	 */
7482 	access &= ~PFERR_USER_MASK;
7483 	if ((pte_access & ACC_USER_MASK) && (access & PFERR_GUEST_FINAL_MASK))
7484 		access |= PFERR_USER_MASK;
7485 
7486 	return w->gva_to_gpa(vcpu, w, gpa, access, exception);
7487 }
7488 
7489 struct kvm_x86_nested_ops vmx_nested_ops __initdata = {
7490 	.leave_nested = vmx_leave_nested,
7491 	.translate_nested_gpa = vmx_translate_nested_gpa,
7492 	.is_exception_vmexit = nested_vmx_is_exception_vmexit,
7493 	.check_events = vmx_check_nested_events,
7494 	.has_events = vmx_has_nested_events,
7495 	.triple_fault = nested_vmx_triple_fault,
7496 	.get_state = vmx_get_nested_state,
7497 	.set_state = vmx_set_nested_state,
7498 	.get_nested_state_pages = vmx_get_nested_state_pages,
7499 	.write_log_dirty = nested_vmx_write_pml_buffer,
7500 #ifdef CONFIG_KVM_HYPERV
7501 	.enable_evmcs = nested_enable_evmcs,
7502 	.get_evmcs_version = nested_get_evmcs_version,
7503 	.hv_inject_synthetic_vmexit_post_tlb_flush = vmx_hv_inject_synthetic_vmexit_post_tlb_flush,
7504 #endif
7505 };
7506