xref: /linux/arch/x86/kvm/vmx/nested.c (revision 26ba30221c03364d6ed9910be8da4c1fd871b07b)
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 "mmu.h"
15 #include "nested.h"
16 #include "pmu.h"
17 #include "posted_intr.h"
18 #include "sgx.h"
19 #include "trace.h"
20 #include "vmx.h"
21 #include "smm.h"
22 #include "x86_ops.h"
23 
24 static bool __read_mostly enable_shadow_vmcs = 1;
25 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
26 
27 static bool __ro_after_init warn_on_missed_cc;
28 module_param(warn_on_missed_cc, bool, 0444);
29 
30 #define CC KVM_NESTED_VMENTER_CONSISTENCY_CHECK
31 
32 /*
33  * Hyper-V requires all of these, so mark them as supported even though
34  * they are just treated the same as all-context.
35  */
36 #define VMX_VPID_EXTENT_SUPPORTED_MASK		\
37 	(VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT |	\
38 	VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |	\
39 	VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT |	\
40 	VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
41 
42 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
43 
44 enum {
45 	VMX_VMREAD_BITMAP,
46 	VMX_VMWRITE_BITMAP,
47 	VMX_BITMAP_NR
48 };
49 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
50 
51 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
52 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
53 
54 struct shadow_vmcs_field {
55 	u16	encoding;
56 	u16	offset;
57 };
58 static struct shadow_vmcs_field shadow_read_only_fields[] = {
59 #define SHADOW_FIELD_RO(x, y) { x, offsetof(struct vmcs12, y) },
60 #include "vmcs_shadow_fields.h"
61 };
62 static int max_shadow_read_only_fields =
63 	ARRAY_SIZE(shadow_read_only_fields);
64 
65 static struct shadow_vmcs_field shadow_read_write_fields[] = {
66 #define SHADOW_FIELD_RW(x, y) { x, offsetof(struct vmcs12, y) },
67 #include "vmcs_shadow_fields.h"
68 };
69 static int max_shadow_read_write_fields =
70 	ARRAY_SIZE(shadow_read_write_fields);
71 
72 static void init_vmcs_shadow_fields(void)
73 {
74 	int i, j;
75 
76 	memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
77 	memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
78 
79 	for (i = j = 0; i < max_shadow_read_only_fields; i++) {
80 		struct shadow_vmcs_field entry = shadow_read_only_fields[i];
81 		u16 field = entry.encoding;
82 
83 		if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
84 		    (i + 1 == max_shadow_read_only_fields ||
85 		     shadow_read_only_fields[i + 1].encoding != field + 1))
86 			pr_err("Missing field from shadow_read_only_field %x\n",
87 			       field + 1);
88 
89 		if (get_vmcs12_field_offset(field) < 0)
90 			continue;
91 
92 		clear_bit(field, vmx_vmread_bitmap);
93 		if (field & 1)
94 #ifdef CONFIG_X86_64
95 			continue;
96 #else
97 			entry.offset += sizeof(u32);
98 #endif
99 		shadow_read_only_fields[j++] = entry;
100 	}
101 	max_shadow_read_only_fields = j;
102 
103 	for (i = j = 0; i < max_shadow_read_write_fields; i++) {
104 		struct shadow_vmcs_field entry = shadow_read_write_fields[i];
105 		u16 field = entry.encoding;
106 
107 		if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
108 		    (i + 1 == max_shadow_read_write_fields ||
109 		     shadow_read_write_fields[i + 1].encoding != field + 1))
110 			pr_err("Missing field from shadow_read_write_field %x\n",
111 			       field + 1);
112 
113 		WARN_ONCE(field >= GUEST_ES_AR_BYTES &&
114 			  field <= GUEST_TR_AR_BYTES,
115 			  "Update vmcs12_write_any() to drop reserved bits from AR_BYTES");
116 
117 		if (get_vmcs12_field_offset(field) < 0)
118 			continue;
119 
120 		/*
121 		 * KVM emulates PML and the VMX preemption timer irrespective
122 		 * of hardware support, but shadowing their related VMCS fields
123 		 * requires hardware support as the CPU will reject VMWRITEs to
124 		 * fields that don't exist.
125 		 */
126 		switch (field) {
127 		case GUEST_PML_INDEX:
128 			if (!cpu_has_vmx_pml())
129 				continue;
130 			break;
131 		case VMX_PREEMPTION_TIMER_VALUE:
132 			if (!cpu_has_vmx_preemption_timer())
133 				continue;
134 			break;
135 		default:
136 			break;
137 		}
138 
139 		clear_bit(field, vmx_vmwrite_bitmap);
140 		clear_bit(field, vmx_vmread_bitmap);
141 		if (field & 1)
142 #ifdef CONFIG_X86_64
143 			continue;
144 #else
145 			entry.offset += sizeof(u32);
146 #endif
147 		shadow_read_write_fields[j++] = entry;
148 	}
149 	max_shadow_read_write_fields = j;
150 }
151 
152 /*
153  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
154  * set the success or error code of an emulated VMX instruction (as specified
155  * by Vol 2B, VMX Instruction Reference, "Conventions"), and skip the emulated
156  * instruction.
157  */
158 static int nested_vmx_succeed(struct kvm_vcpu *vcpu)
159 {
160 	vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
161 			& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
162 			    X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
163 	return kvm_skip_emulated_instruction(vcpu);
164 }
165 
166 static int nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
167 {
168 	vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
169 			& ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
170 			    X86_EFLAGS_SF | X86_EFLAGS_OF))
171 			| X86_EFLAGS_CF);
172 	return kvm_skip_emulated_instruction(vcpu);
173 }
174 
175 static int nested_vmx_failValid(struct kvm_vcpu *vcpu,
176 				u32 vm_instruction_error)
177 {
178 	vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
179 			& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
180 			    X86_EFLAGS_SF | X86_EFLAGS_OF))
181 			| X86_EFLAGS_ZF);
182 	get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
183 	/*
184 	 * We don't need to force sync to shadow VMCS because
185 	 * VM_INSTRUCTION_ERROR is not shadowed. Enlightened VMCS 'shadows' all
186 	 * fields and thus must be synced.
187 	 */
188 	if (nested_vmx_is_evmptr12_set(to_vmx(vcpu)))
189 		to_vmx(vcpu)->nested.need_vmcs12_to_shadow_sync = true;
190 
191 	return kvm_skip_emulated_instruction(vcpu);
192 }
193 
194 static int nested_vmx_fail(struct kvm_vcpu *vcpu, u32 vm_instruction_error)
195 {
196 	struct vcpu_vmx *vmx = to_vmx(vcpu);
197 
198 	/*
199 	 * failValid writes the error number to the current VMCS, which
200 	 * can't be done if there isn't a current VMCS.
201 	 */
202 	if (vmx->nested.current_vmptr == INVALID_GPA &&
203 	    !nested_vmx_is_evmptr12_valid(vmx))
204 		return nested_vmx_failInvalid(vcpu);
205 
206 	return nested_vmx_failValid(vcpu, vm_instruction_error);
207 }
208 
209 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
210 {
211 	/* TODO: not to reset guest simply here. */
212 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
213 	pr_debug_ratelimited("nested vmx abort, indicator %d\n", indicator);
214 }
215 
216 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
217 {
218 	return fixed_bits_valid(control, low, high);
219 }
220 
221 static inline u64 vmx_control_msr(u32 low, u32 high)
222 {
223 	return low | ((u64)high << 32);
224 }
225 
226 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
227 {
228 	secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_SHADOW_VMCS);
229 	vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA);
230 	vmx->nested.need_vmcs12_to_shadow_sync = false;
231 }
232 
233 static inline void nested_release_evmcs(struct kvm_vcpu *vcpu)
234 {
235 #ifdef CONFIG_KVM_HYPERV
236 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
237 	struct vcpu_vmx *vmx = to_vmx(vcpu);
238 
239 	kvm_vcpu_unmap(vcpu, &vmx->nested.hv_evmcs_map);
240 	vmx->nested.hv_evmcs = NULL;
241 	vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
242 
243 	if (hv_vcpu) {
244 		hv_vcpu->nested.pa_page_gpa = INVALID_GPA;
245 		hv_vcpu->nested.vm_id = 0;
246 		hv_vcpu->nested.vp_id = 0;
247 	}
248 #endif
249 }
250 
251 static bool nested_evmcs_handle_vmclear(struct kvm_vcpu *vcpu, gpa_t vmptr)
252 {
253 #ifdef CONFIG_KVM_HYPERV
254 	struct vcpu_vmx *vmx = to_vmx(vcpu);
255 	/*
256 	 * When Enlightened VMEntry is enabled on the calling CPU we treat
257 	 * memory area pointer by vmptr as Enlightened VMCS (as there's no good
258 	 * way to distinguish it from VMCS12) and we must not corrupt it by
259 	 * writing to the non-existent 'launch_state' field. The area doesn't
260 	 * have to be the currently active EVMCS on the calling CPU and there's
261 	 * nothing KVM has to do to transition it from 'active' to 'non-active'
262 	 * state. It is possible that the area will stay mapped as
263 	 * vmx->nested.hv_evmcs but this shouldn't be a problem.
264 	 */
265 	if (!guest_cpu_cap_has_evmcs(vcpu) ||
266 	    !evmptr_is_valid(nested_get_evmptr(vcpu)))
267 		return false;
268 
269 	if (nested_vmx_evmcs(vmx) && vmptr == vmx->nested.hv_evmcs_vmptr)
270 		nested_release_evmcs(vcpu);
271 
272 	return true;
273 #else
274 	return false;
275 #endif
276 }
277 
278 static void vmx_sync_vmcs_host_state(struct vcpu_vmx *vmx,
279 				     struct loaded_vmcs *prev)
280 {
281 	struct vmcs_host_state *dest, *src;
282 
283 	if (unlikely(!vmx->vt.guest_state_loaded))
284 		return;
285 
286 	src = &prev->host_state;
287 	dest = &vmx->loaded_vmcs->host_state;
288 
289 	vmx_set_host_fs_gs(dest, src->fs_sel, src->gs_sel, src->fs_base, src->gs_base);
290 	dest->ldt_sel = src->ldt_sel;
291 #ifdef CONFIG_X86_64
292 	dest->ds_sel = src->ds_sel;
293 	dest->es_sel = src->es_sel;
294 #endif
295 }
296 
297 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
298 {
299 	struct vcpu_vmx *vmx = to_vmx(vcpu);
300 	struct loaded_vmcs *prev;
301 	int cpu;
302 
303 	if (WARN_ON_ONCE(vmx->loaded_vmcs == vmcs))
304 		return;
305 
306 	cpu = get_cpu();
307 	prev = vmx->loaded_vmcs;
308 	vmx->loaded_vmcs = vmcs;
309 	vmx_vcpu_load_vmcs(vcpu, cpu);
310 	vmx_sync_vmcs_host_state(vmx, prev);
311 	put_cpu();
312 
313 	kvm_clear_available_registers(vcpu, VMX_REGS_LAZY_LOAD_SET);
314 
315 	/*
316 	 * All lazily updated registers will be reloaded from VMCS12 on both
317 	 * vmentry and vmexit.
318 	 */
319 	kvm_reset_dirty_registers(vcpu);
320 }
321 
322 static void nested_put_vmcs12_pages(struct kvm_vcpu *vcpu)
323 {
324 	struct vcpu_vmx *vmx = to_vmx(vcpu);
325 
326 	kvm_vcpu_unmap(vcpu, &vmx->nested.apic_access_page_map);
327 	kvm_vcpu_unmap(vcpu, &vmx->nested.virtual_apic_map);
328 	kvm_vcpu_unmap(vcpu, &vmx->nested.pi_desc_map);
329 	vmx->nested.pi_desc = NULL;
330 }
331 
332 /*
333  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
334  * just stops using VMX.
335  */
336 static void free_nested(struct kvm_vcpu *vcpu)
337 {
338 	struct vcpu_vmx *vmx = to_vmx(vcpu);
339 	struct vmcs *shadow_vmcs;
340 
341 	if (WARN_ON_ONCE(vmx->loaded_vmcs != &vmx->vmcs01))
342 		vmx_switch_vmcs(vcpu, &vmx->vmcs01);
343 
344 	if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
345 		return;
346 
347 	kvm_clear_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
348 
349 	vmx->nested.vmxon = false;
350 	vmx->nested.smm.vmxon = false;
351 	vmx->nested.vmxon_ptr = INVALID_GPA;
352 	free_vpid(vmx->nested.vpid02);
353 	vmx->nested.posted_intr_nv = -1;
354 	vmx->nested.current_vmptr = INVALID_GPA;
355 	if (enable_shadow_vmcs) {
356 		vmx_disable_shadow_vmcs(vmx);
357 
358 		/*
359 		 * Keep the pointer visible until after VMCLEAR, so migration
360 		 * can clear an active shadow VMCS on the old CPU.
361 		 */
362 		shadow_vmcs = vmx->vmcs01.shadow_vmcs;
363 		vmcs_clear(shadow_vmcs);
364 		vmx->vmcs01.shadow_vmcs = NULL;
365 		free_vmcs(shadow_vmcs);
366 	}
367 	kfree(vmx->nested.cached_vmcs12);
368 	vmx->nested.cached_vmcs12 = NULL;
369 	kfree(vmx->nested.cached_shadow_vmcs12);
370 	vmx->nested.cached_shadow_vmcs12 = NULL;
371 
372 	nested_put_vmcs12_pages(vcpu);
373 
374 	kvm_mmu_free_roots(vcpu->kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
375 
376 	nested_release_evmcs(vcpu);
377 
378 	free_loaded_vmcs(&vmx->nested.vmcs02);
379 }
380 
381 /*
382  * Ensure that the current vmcs of the logical processor is the
383  * vmcs01 of the vcpu before calling free_nested().
384  */
385 void nested_vmx_free_vcpu(struct kvm_vcpu *vcpu)
386 {
387 	vcpu_load(vcpu);
388 	vmx_leave_nested(vcpu);
389 	vcpu_put(vcpu);
390 }
391 
392 #define EPTP_PA_MASK   GENMASK_ULL(51, 12)
393 
394 static bool nested_ept_root_matches(hpa_t root_hpa, u64 root_eptp, u64 eptp)
395 {
396 	return VALID_PAGE(root_hpa) &&
397 	       ((root_eptp & EPTP_PA_MASK) == (eptp & EPTP_PA_MASK));
398 }
399 
400 static void nested_ept_invalidate_addr(struct kvm_vcpu *vcpu, gpa_t eptp,
401 				       gpa_t addr)
402 {
403 	unsigned long roots = 0;
404 	uint i;
405 	struct kvm_mmu_root_info *cached_root;
406 
407 	WARN_ON_ONCE(!mmu_is_nested(vcpu));
408 
409 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
410 		cached_root = &vcpu->arch.mmu->prev_roots[i];
411 
412 		if (nested_ept_root_matches(cached_root->hpa, cached_root->pgd,
413 					    eptp))
414 			roots |= KVM_MMU_ROOT_PREVIOUS(i);
415 	}
416 	if (roots)
417 		kvm_mmu_invalidate_addr(vcpu, vcpu->arch.mmu, addr, roots);
418 }
419 
420 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
421 					 struct x86_exception *fault,
422 					 bool from_hardware)
423 {
424 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
425 	struct vcpu_vmx *vmx = to_vmx(vcpu);
426 	unsigned long exit_qualification;
427 	u32 vm_exit_reason;
428 
429 	if (vmx->nested.pml_full) {
430 		vm_exit_reason = EXIT_REASON_PML_FULL;
431 		vmx->nested.pml_full = false;
432 
433 		/*
434 		 * It should be impossible to trigger a nested PML Full VM-Exit
435 		 * for anything other than an EPT Violation from L2.  KVM *can*
436 		 * trigger nEPT page fault injection in response to an EPT
437 		 * Misconfig, e.g. if the MMIO SPTE was stale and L1's EPT
438 		 * tables also changed, but KVM should not treat EPT Misconfig
439 		 * VM-Exits as writes.
440 		 */
441 		WARN_ON_ONCE(vmx->vt.exit_reason.basic != EXIT_REASON_EPT_VIOLATION);
442 
443 		/*
444 		 * PML Full and EPT Violation VM-Exits both use bit 12 to report
445 		 * "NMI unblocking due to IRET", i.e. the bit can be propagated
446 		 * as-is from the original EXIT_QUALIFICATION.
447 		 */
448 		exit_qualification = vmx_get_exit_qual(vcpu) & INTR_INFO_UNBLOCK_NMI;
449 	} else {
450 		if (fault->error_code & PFERR_RSVD_MASK) {
451 			vm_exit_reason = EXIT_REASON_EPT_MISCONFIG;
452 			exit_qualification = 0;
453 		} else {
454 			u64 mask = EPT_VIOLATION_GVA_IS_VALID |
455 				   EPT_VIOLATION_GVA_TRANSLATED;
456 
457 			if (vmx->nested.msrs.ept_caps & VMX_EPT_ADVANCED_VMEXIT_INFO_BIT)
458 				mask |= EPT_VIOLATION_GVA_USER |
459 					EPT_VIOLATION_GVA_WRITABLE |
460 					EPT_VIOLATION_GVA_NX;
461 
462 			exit_qualification = fault->exit_qualification & ~mask;
463 
464 			/*
465 			 * Use the EXIT_QUALIFICATION from the VMCS if and only
466 			 * if the hardware VM-Exit from L2 was an EPT Violation.
467 			 * If the fault is synthesized, then EXIT_QUALIFICATION
468 			 * is stale and/or holds entirely different data.  And
469 			 * conversely, KVM _must_ rely on EXIT_QUALIFICATION if
470 			 * the fault came from hardware, because KVM only sees
471 			 * and walks the faulting GPA.
472 			 */
473 			if (from_hardware)
474 				exit_qualification |= vmx_get_exit_qual(vcpu) & mask;
475 			else
476 				exit_qualification |= fault->exit_qualification & mask;
477 
478 			vm_exit_reason = EXIT_REASON_EPT_VIOLATION;
479 		}
480 
481 		/*
482 		 * Although the caller (kvm_inject_emulated_page_fault) would
483 		 * have already synced the faulting address in the shadow EPT
484 		 * tables for the current EPTP12, we also need to sync it for
485 		 * any other cached EPTP02s based on the same EP4TA, since the
486 		 * TLB associates mappings to the EP4TA rather than the full EPTP.
487 		 */
488 		nested_ept_invalidate_addr(vcpu, vmcs12->ept_pointer,
489 					   fault->address);
490 	}
491 
492 	nested_vmx_vmexit(vcpu, vm_exit_reason, 0, exit_qualification);
493 	vmcs12->guest_physical_address = fault->address;
494 }
495 
496 static inline bool nested_ept_mbec_enabled(struct kvm_vcpu *vcpu)
497 {
498 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
499 
500 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_MODE_BASED_EPT_EXEC);
501 }
502 
503 static void nested_ept_new_eptp(struct kvm_vcpu *vcpu)
504 {
505 	struct vcpu_vmx *vmx = to_vmx(vcpu);
506 	bool execonly = vmx->nested.msrs.ept_caps & VMX_EPT_EXECUTE_ONLY_BIT;
507 	int ept_lpage_level = ept_caps_to_lpage_level(vmx->nested.msrs.ept_caps);
508 
509 	kvm_init_shadow_ept_mmu(vcpu, execonly, ept_lpage_level,
510 				nested_ept_ad_enabled(vcpu),
511 				nested_ept_mbec_enabled(vcpu),
512 				nested_ept_get_eptp(vcpu));
513 }
514 
515 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
516 {
517 	WARN_ON(mmu_is_nested(vcpu));
518 
519 	vcpu->arch.mmu = &vcpu->arch.guest_mmu;
520 	nested_ept_new_eptp(vcpu);
521 	vcpu->arch.mmu->get_guest_pgd     = nested_ept_get_eptp;
522 	vcpu->arch.mmu->inject_page_fault = nested_ept_inject_page_fault;
523 	vcpu->arch.mmu->get_pdptr         = kvm_pdptr_read;
524 
525 	vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
526 }
527 
528 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
529 {
530 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
531 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
532 }
533 
534 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
535 					    u16 error_code)
536 {
537 	bool inequality, bit;
538 
539 	bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
540 	inequality =
541 		(error_code & vmcs12->page_fault_error_code_mask) !=
542 		 vmcs12->page_fault_error_code_match;
543 	return inequality ^ bit;
544 }
545 
546 static bool nested_vmx_is_exception_vmexit(struct kvm_vcpu *vcpu, u8 vector,
547 					   u32 error_code)
548 {
549 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
550 
551 	/*
552 	 * Drop bits 31:16 of the error code when performing the #PF mask+match
553 	 * check.  All VMCS fields involved are 32 bits, but Intel CPUs never
554 	 * set bits 31:16 and VMX disallows setting bits 31:16 in the injected
555 	 * error code.  Including the to-be-dropped bits in the check might
556 	 * result in an "impossible" or missed exit from L1's perspective.
557 	 */
558 	if (vector == PF_VECTOR)
559 		return nested_vmx_is_page_fault_vmexit(vmcs12, (u16)error_code);
560 
561 	return (vmcs12->exception_bitmap & (1u << vector));
562 }
563 
564 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
565 					       struct vmcs12 *vmcs12)
566 {
567 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
568 		return 0;
569 
570 	if (CC(!page_address_valid(vcpu, vmcs12->io_bitmap_a)) ||
571 	    CC(!page_address_valid(vcpu, vmcs12->io_bitmap_b)))
572 		return -EINVAL;
573 
574 	return 0;
575 }
576 
577 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
578 						struct vmcs12 *vmcs12)
579 {
580 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
581 		return 0;
582 
583 	if (CC(!page_address_valid(vcpu, vmcs12->msr_bitmap)))
584 		return -EINVAL;
585 
586 	return 0;
587 }
588 
589 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
590 						struct vmcs12 *vmcs12)
591 {
592 	gpa_t vtpr_gpa = vmcs12->virtual_apic_page_addr + APIC_TASKPRI;
593 	u32 vtpr;
594 
595 	if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
596 		return 0;
597 
598 	if (CC(!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr)))
599 		return -EINVAL;
600 
601 	if (CC(!nested_cpu_has_vid(vmcs12) && vmcs12->tpr_threshold >> 4))
602 		return -EINVAL;
603 
604 	/*
605 	 * Do the illegal vTPR vs. TPR Threshold consistency check if and only
606 	 * if KVM is configured to WARN on missed consistency checks, otherwise
607 	 * it's a waste of time.  KVM needs to rely on hardware to fully detect
608 	 * an illegal combination due to the vTPR being writable by L1 at all
609 	 * times (it's an in-memory value, not a VMCS field).  I.e. even if the
610 	 * check passes now, it might fail at the actual VM-Enter.
611 	 *
612 	 * If reading guest memory fails, skip the check as KVM's de facto ABI
613 	 * for VMX instruction accesses to non-existent memory is to provide
614 	 * PCI Bus Error semantics (reads return 0xFFs), in which case the vTPR
615 	 * is guaranteed to greater than or equal to the threshold.
616 	 *
617 	 * Note!  Deliberately use the VM-scoped API when reading guest memory,
618 	 * to ensure the read doesn't hit SMRAM when restoring L2 state on RSM,
619 	 * and only perform the check when in KVM_RUN, to avoid a false failure
620 	 * if userspace hasn't yet configured memslots during state restore.
621 	 */
622 	if (warn_on_missed_cc && vcpu->wants_to_run &&
623 	    nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW) &&
624 	    !nested_cpu_has_vid(vmcs12) &&
625 	    !nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
626 	    !kvm_read_guest(vcpu->kvm, vtpr_gpa, &vtpr, sizeof(vtpr)) &&
627 	    CC((vmcs12->tpr_threshold & GENMASK(3, 0)) > ((vtpr >> 4) & GENMASK(3, 0))))
628 		return -EINVAL;
629 
630 	return 0;
631 }
632 
633 /*
634  * For x2APIC MSRs, ignore the vmcs01 bitmap.  L1 can enable x2APIC without L1
635  * itself utilizing x2APIC.  All MSRs were previously set to be intercepted,
636  * only the "disable intercept" case needs to be handled.
637  */
638 static void nested_vmx_disable_intercept_for_x2apic_msr(unsigned long *msr_bitmap_l1,
639 							unsigned long *msr_bitmap_l0,
640 							u32 msr, int type)
641 {
642 	if (type & MSR_TYPE_R && !vmx_test_msr_bitmap_read(msr_bitmap_l1, msr))
643 		vmx_clear_msr_bitmap_read(msr_bitmap_l0, msr);
644 
645 	if (type & MSR_TYPE_W && !vmx_test_msr_bitmap_write(msr_bitmap_l1, msr))
646 		vmx_clear_msr_bitmap_write(msr_bitmap_l0, msr);
647 }
648 
649 static inline void enable_x2apic_msr_intercepts(unsigned long *msr_bitmap)
650 {
651 	int msr;
652 
653 	for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
654 		unsigned word = msr / BITS_PER_LONG;
655 
656 		msr_bitmap[word] = ~0;
657 		msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
658 	}
659 }
660 
661 #define BUILD_NVMX_MSR_INTERCEPT_HELPER(rw)					\
662 static inline									\
663 void nested_vmx_set_msr_##rw##_intercept(struct vcpu_vmx *vmx,			\
664 					 unsigned long *msr_bitmap_l1,		\
665 					 unsigned long *msr_bitmap_l0, u32 msr)	\
666 {										\
667 	if (vmx_test_msr_bitmap_##rw(vmx->vmcs01.msr_bitmap, msr) ||		\
668 	    vmx_test_msr_bitmap_##rw(msr_bitmap_l1, msr))			\
669 		vmx_set_msr_bitmap_##rw(msr_bitmap_l0, msr);			\
670 	else									\
671 		vmx_clear_msr_bitmap_##rw(msr_bitmap_l0, msr);			\
672 }
673 BUILD_NVMX_MSR_INTERCEPT_HELPER(read)
674 BUILD_NVMX_MSR_INTERCEPT_HELPER(write)
675 
676 static inline void nested_vmx_set_intercept_for_msr(struct vcpu_vmx *vmx,
677 						    unsigned long *msr_bitmap_l1,
678 						    unsigned long *msr_bitmap_l0,
679 						    u32 msr, int types)
680 {
681 	if (types & MSR_TYPE_R)
682 		nested_vmx_set_msr_read_intercept(vmx, msr_bitmap_l1,
683 						  msr_bitmap_l0, msr);
684 	if (types & MSR_TYPE_W)
685 		nested_vmx_set_msr_write_intercept(vmx, msr_bitmap_l1,
686 						   msr_bitmap_l0, msr);
687 }
688 
689 #define nested_vmx_merge_msr_bitmaps(msr, type)	\
690 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1,	\
691 					 msr_bitmap_l0, msr, type)
692 
693 #define nested_vmx_merge_msr_bitmaps_read(msr) \
694 	nested_vmx_merge_msr_bitmaps(msr, MSR_TYPE_R)
695 
696 #define nested_vmx_merge_msr_bitmaps_write(msr) \
697 	nested_vmx_merge_msr_bitmaps(msr, MSR_TYPE_W)
698 
699 #define nested_vmx_merge_msr_bitmaps_rw(msr) \
700 	nested_vmx_merge_msr_bitmaps(msr, MSR_TYPE_RW)
701 
702 static void nested_vmx_merge_pmu_msr_bitmaps(struct kvm_vcpu *vcpu,
703 					     unsigned long *msr_bitmap_l1,
704 					     unsigned long *msr_bitmap_l0)
705 {
706 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
707 	struct vcpu_vmx *vmx = to_vmx(vcpu);
708 	int i;
709 
710 	/*
711 	 * Skip the merges if the vCPU doesn't have a mediated PMU MSR, i.e. if
712 	 * none of the MSRs can possibly be passed through to L1.
713 	 */
714 	if (!kvm_vcpu_has_mediated_pmu(vcpu))
715 		return;
716 
717 	for (i = 0; i < pmu->nr_arch_gp_counters; i++) {
718 		nested_vmx_merge_msr_bitmaps_rw(MSR_IA32_PERFCTR0 + i);
719 		nested_vmx_merge_msr_bitmaps_rw(MSR_IA32_PMC0 + i);
720 	}
721 
722 	for (i = 0; i < pmu->nr_arch_fixed_counters; i++)
723 		nested_vmx_merge_msr_bitmaps_rw(MSR_CORE_PERF_FIXED_CTR0 + i);
724 
725 	nested_vmx_merge_msr_bitmaps_rw(MSR_CORE_PERF_GLOBAL_CTRL);
726 	nested_vmx_merge_msr_bitmaps_read(MSR_CORE_PERF_GLOBAL_STATUS);
727 	nested_vmx_merge_msr_bitmaps_write(MSR_CORE_PERF_GLOBAL_OVF_CTRL);
728 }
729 
730 /*
731  * Merge L0's and L1's MSR bitmap, return false to indicate that
732  * we do not use the hardware.
733  */
734 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
735 						 struct vmcs12 *vmcs12)
736 {
737 	struct vcpu_vmx *vmx = to_vmx(vcpu);
738 	int msr;
739 	unsigned long *msr_bitmap_l1;
740 	unsigned long *msr_bitmap_l0 = vmx->nested.vmcs02.msr_bitmap;
741 	struct kvm_host_map map;
742 
743 	/* Nothing to do if the MSR bitmap is not in use.  */
744 	if (!cpu_has_vmx_msr_bitmap() ||
745 	    !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
746 		return false;
747 
748 	/*
749 	 * MSR bitmap update can be skipped when:
750 	 * - MSR bitmap for L1 hasn't changed.
751 	 * - Nested hypervisor (L1) is attempting to launch the same L2 as
752 	 *   before.
753 	 * - Nested hypervisor (L1) has enabled 'Enlightened MSR Bitmap' feature
754 	 *   and tells KVM (L0) there were no changes in MSR bitmap for L2.
755 	 */
756 	if (!vmx->nested.force_msr_bitmap_recalc) {
757 		struct hv_enlightened_vmcs *evmcs = nested_vmx_evmcs(vmx);
758 
759 		if (evmcs && evmcs->hv_enlightenments_control.msr_bitmap &&
760 		    evmcs->hv_clean_fields & HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP)
761 			return true;
762 	}
763 
764 	if (kvm_vcpu_map_readonly(vcpu, gpa_to_gfn(vmcs12->msr_bitmap), &map))
765 		return false;
766 
767 	msr_bitmap_l1 = (unsigned long *)map.hva;
768 
769 	/*
770 	 * To keep the control flow simple, pay eight 8-byte writes (sixteen
771 	 * 4-byte writes on 32-bit systems) up front to enable intercepts for
772 	 * the x2APIC MSR range and selectively toggle those relevant to L2.
773 	 */
774 	enable_x2apic_msr_intercepts(msr_bitmap_l0);
775 
776 	if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
777 		if (nested_cpu_has_apic_reg_virt(vmcs12)) {
778 			/*
779 			 * L0 need not intercept reads for MSRs between 0x800
780 			 * and 0x8ff, it just lets the processor take the value
781 			 * from the virtual-APIC page; take those 256 bits
782 			 * directly from the L1 bitmap.
783 			 */
784 			for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
785 				unsigned word = msr / BITS_PER_LONG;
786 
787 				msr_bitmap_l0[word] = msr_bitmap_l1[word];
788 			}
789 		}
790 
791 		nested_vmx_disable_intercept_for_x2apic_msr(
792 			msr_bitmap_l1, msr_bitmap_l0,
793 			X2APIC_MSR(APIC_TASKPRI),
794 			MSR_TYPE_R | MSR_TYPE_W);
795 
796 		if (nested_cpu_has_vid(vmcs12)) {
797 			nested_vmx_disable_intercept_for_x2apic_msr(
798 				msr_bitmap_l1, msr_bitmap_l0,
799 				X2APIC_MSR(APIC_EOI),
800 				MSR_TYPE_W);
801 			nested_vmx_disable_intercept_for_x2apic_msr(
802 				msr_bitmap_l1, msr_bitmap_l0,
803 				X2APIC_MSR(APIC_SELF_IPI),
804 				MSR_TYPE_W);
805 		}
806 	}
807 
808 	/*
809 	 * Always check vmcs01's bitmap to honor userspace MSR filters and any
810 	 * other runtime changes to vmcs01's bitmap, e.g. dynamic pass-through.
811 	 */
812 #ifdef CONFIG_X86_64
813 	nested_vmx_merge_msr_bitmaps_rw(MSR_FS_BASE);
814 	nested_vmx_merge_msr_bitmaps_rw(MSR_GS_BASE);
815 	nested_vmx_merge_msr_bitmaps_rw(MSR_KERNEL_GS_BASE);
816 #endif
817 	nested_vmx_merge_msr_bitmaps_rw(MSR_IA32_SPEC_CTRL);
818 	nested_vmx_merge_msr_bitmaps_write(MSR_IA32_PRED_CMD);
819 	nested_vmx_merge_msr_bitmaps_write(MSR_IA32_FLUSH_CMD);
820 
821 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
822 					 MSR_IA32_APERF, MSR_TYPE_R);
823 
824 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
825 					 MSR_IA32_MPERF, MSR_TYPE_R);
826 
827 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
828 					 MSR_IA32_U_CET, MSR_TYPE_RW);
829 
830 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
831 					 MSR_IA32_S_CET, MSR_TYPE_RW);
832 
833 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
834 					 MSR_IA32_PL0_SSP, MSR_TYPE_RW);
835 
836 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
837 					 MSR_IA32_PL1_SSP, MSR_TYPE_RW);
838 
839 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
840 					 MSR_IA32_PL2_SSP, MSR_TYPE_RW);
841 
842 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
843 					 MSR_IA32_PL3_SSP, MSR_TYPE_RW);
844 
845 	nested_vmx_merge_pmu_msr_bitmaps(vcpu, msr_bitmap_l1, msr_bitmap_l0);
846 
847 	kvm_vcpu_unmap(vcpu, &map);
848 
849 	vmx->nested.force_msr_bitmap_recalc = false;
850 
851 	return true;
852 }
853 
854 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
855 				       struct vmcs12 *vmcs12)
856 {
857 	struct vcpu_vmx *vmx = to_vmx(vcpu);
858 	struct gfn_to_hva_cache *ghc = &vmx->nested.shadow_vmcs12_cache;
859 
860 	if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
861 	    vmcs12->vmcs_link_pointer == INVALID_GPA)
862 		return;
863 
864 	if (ghc->gpa != vmcs12->vmcs_link_pointer &&
865 	    kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc,
866 				      vmcs12->vmcs_link_pointer, VMCS12_SIZE))
867 		return;
868 
869 	kvm_read_guest_cached(vcpu->kvm, ghc, get_shadow_vmcs12(vcpu),
870 			      VMCS12_SIZE);
871 }
872 
873 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
874 					      struct vmcs12 *vmcs12)
875 {
876 	struct vcpu_vmx *vmx = to_vmx(vcpu);
877 	struct gfn_to_hva_cache *ghc = &vmx->nested.shadow_vmcs12_cache;
878 
879 	if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
880 	    vmcs12->vmcs_link_pointer == INVALID_GPA)
881 		return;
882 
883 	if (ghc->gpa != vmcs12->vmcs_link_pointer &&
884 	    kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc,
885 				      vmcs12->vmcs_link_pointer, VMCS12_SIZE))
886 		return;
887 
888 	kvm_write_guest_cached(vcpu->kvm, ghc, get_shadow_vmcs12(vcpu),
889 			       VMCS12_SIZE);
890 }
891 
892 /*
893  * In nested virtualization, check if L1 has set
894  * VM_EXIT_ACK_INTR_ON_EXIT
895  */
896 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
897 {
898 	return get_vmcs12(vcpu)->vm_exit_controls &
899 		VM_EXIT_ACK_INTR_ON_EXIT;
900 }
901 
902 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
903 					  struct vmcs12 *vmcs12)
904 {
905 	if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
906 	    CC(!page_address_valid(vcpu, vmcs12->apic_access_addr)))
907 		return -EINVAL;
908 	else
909 		return 0;
910 }
911 
912 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
913 					   struct vmcs12 *vmcs12)
914 {
915 	if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
916 	    !nested_cpu_has_apic_reg_virt(vmcs12) &&
917 	    !nested_cpu_has_vid(vmcs12) &&
918 	    !nested_cpu_has_posted_intr(vmcs12))
919 		return 0;
920 
921 	/*
922 	 * If virtualize x2apic mode is enabled,
923 	 * virtualize apic access must be disabled.
924 	 */
925 	if (CC(nested_cpu_has_virt_x2apic_mode(vmcs12) &&
926 	       nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)))
927 		return -EINVAL;
928 
929 	/*
930 	 * If virtual interrupt delivery is enabled,
931 	 * we must exit on external interrupts.
932 	 */
933 	if (CC(nested_cpu_has_vid(vmcs12) && !nested_exit_on_intr(vcpu)))
934 		return -EINVAL;
935 
936 	/*
937 	 * bits 15:8 should be zero in posted_intr_nv,
938 	 * the descriptor address has been already checked
939 	 * in nested_get_vmcs12_pages.
940 	 *
941 	 * bits 5:0 of posted_intr_desc_addr should be zero.
942 	 */
943 	if (nested_cpu_has_posted_intr(vmcs12) &&
944 	   (CC(!nested_cpu_has_vid(vmcs12)) ||
945 	    CC(!nested_exit_intr_ack_set(vcpu)) ||
946 	    CC((vmcs12->posted_intr_nv & 0xff00)) ||
947 	    CC(!kvm_vcpu_is_legal_aligned_gpa(vcpu, vmcs12->posted_intr_desc_addr, 64))))
948 		return -EINVAL;
949 
950 	/* tpr shadow is needed by all apicv features. */
951 	if (CC(!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)))
952 		return -EINVAL;
953 
954 	return 0;
955 }
956 
957 static u32 nested_vmx_max_atomic_switch_msrs(struct kvm_vcpu *vcpu)
958 {
959 	struct vcpu_vmx *vmx = to_vmx(vcpu);
960 	u64 vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
961 				       vmx->nested.msrs.misc_high);
962 
963 	return (vmx_misc_max_msr(vmx_misc) + 1) * VMX_MISC_MSR_LIST_MULTIPLIER;
964 }
965 
966 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
967 				       u32 count, u64 addr)
968 {
969 	if (count == 0)
970 		return 0;
971 
972 	/*
973 	 * Exceeding the limit results in architecturally _undefined_ behavior,
974 	 * i.e. KVM is allowed to do literally anything in response to a bad
975 	 * limit.  Immediately generate a consistency check so that code that
976 	 * consumes the count doesn't need to worry about extreme edge cases.
977 	 */
978 	if (count > nested_vmx_max_atomic_switch_msrs(vcpu))
979 		return -EINVAL;
980 
981 	if (!kvm_vcpu_is_legal_aligned_gpa(vcpu, addr, 16) ||
982 	    !kvm_vcpu_is_legal_gpa(vcpu, (addr + count * sizeof(struct vmx_msr_entry) - 1)))
983 		return -EINVAL;
984 
985 	return 0;
986 }
987 
988 static int nested_vmx_check_exit_msr_switch_controls(struct kvm_vcpu *vcpu,
989 						     struct vmcs12 *vmcs12)
990 {
991 	if (CC(nested_vmx_check_msr_switch(vcpu,
992 					   vmcs12->vm_exit_msr_load_count,
993 					   vmcs12->vm_exit_msr_load_addr)) ||
994 	    CC(nested_vmx_check_msr_switch(vcpu,
995 					   vmcs12->vm_exit_msr_store_count,
996 					   vmcs12->vm_exit_msr_store_addr)))
997 		return -EINVAL;
998 
999 	return 0;
1000 }
1001 
1002 static int nested_vmx_check_entry_msr_switch_controls(struct kvm_vcpu *vcpu,
1003                                                       struct vmcs12 *vmcs12)
1004 {
1005 	if (CC(nested_vmx_check_msr_switch(vcpu,
1006 					   vmcs12->vm_entry_msr_load_count,
1007 					   vmcs12->vm_entry_msr_load_addr)))
1008                 return -EINVAL;
1009 
1010 	return 0;
1011 }
1012 
1013 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
1014 					 struct vmcs12 *vmcs12)
1015 {
1016 	if (!nested_cpu_has_pml(vmcs12))
1017 		return 0;
1018 
1019 	if (CC(!nested_cpu_has_ept(vmcs12)) ||
1020 	    CC(!page_address_valid(vcpu, vmcs12->pml_address)))
1021 		return -EINVAL;
1022 
1023 	return 0;
1024 }
1025 
1026 static int nested_vmx_check_unrestricted_guest_controls(struct kvm_vcpu *vcpu,
1027 							struct vmcs12 *vmcs12)
1028 {
1029 	if (CC(nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST) &&
1030 	       !nested_cpu_has_ept(vmcs12)))
1031 		return -EINVAL;
1032 	return 0;
1033 }
1034 
1035 static int nested_vmx_check_mode_based_ept_exec_controls(struct kvm_vcpu *vcpu,
1036 							 struct vmcs12 *vmcs12)
1037 {
1038 	if (CC(nested_cpu_has2(vmcs12, SECONDARY_EXEC_MODE_BASED_EPT_EXEC) &&
1039 	       !nested_cpu_has_ept(vmcs12)))
1040 		return -EINVAL;
1041 	return 0;
1042 }
1043 
1044 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
1045 						 struct vmcs12 *vmcs12)
1046 {
1047 	if (!nested_cpu_has_shadow_vmcs(vmcs12))
1048 		return 0;
1049 
1050 	if (CC(!page_address_valid(vcpu, vmcs12->vmread_bitmap)) ||
1051 	    CC(!page_address_valid(vcpu, vmcs12->vmwrite_bitmap)))
1052 		return -EINVAL;
1053 
1054 	return 0;
1055 }
1056 
1057 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
1058 				       struct vmx_msr_entry *e)
1059 {
1060 	/* x2APIC MSR accesses are not allowed */
1061 	if (CC(vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8))
1062 		return -EINVAL;
1063 	if (CC(e->index == MSR_IA32_UCODE_WRITE) || /* SDM Table 35-2 */
1064 	    CC(e->index == MSR_IA32_UCODE_REV))
1065 		return -EINVAL;
1066 	if (CC(e->reserved != 0))
1067 		return -EINVAL;
1068 	return 0;
1069 }
1070 
1071 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
1072 				     struct vmx_msr_entry *e)
1073 {
1074 	if (CC(e->index == MSR_FS_BASE) ||
1075 	    CC(e->index == MSR_GS_BASE) ||
1076 	    CC(e->index == MSR_IA32_SMM_MONITOR_CTL) || /* SMM is not supported */
1077 	    nested_vmx_msr_check_common(vcpu, e))
1078 		return -EINVAL;
1079 	return 0;
1080 }
1081 
1082 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
1083 				      struct vmx_msr_entry *e)
1084 {
1085 	if (CC(e->index == MSR_IA32_SMBASE) || /* SMM is not supported */
1086 	    nested_vmx_msr_check_common(vcpu, e))
1087 		return -EINVAL;
1088 	return 0;
1089 }
1090 
1091 /*
1092  * Load guest's/host's msr at nested entry/exit.
1093  * return 0 for success, entry index for failure.
1094  *
1095  * One of the failure modes for MSR load/store is when a list exceeds the
1096  * virtual hardware's capacity. To maintain compatibility with hardware inasmuch
1097  * as possible, process all valid entries before failing rather than precheck
1098  * for a capacity violation.
1099  */
1100 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
1101 {
1102 	u32 i;
1103 	struct vmx_msr_entry e;
1104 	u32 max_msr_list_size = nested_vmx_max_atomic_switch_msrs(vcpu);
1105 
1106 	for (i = 0; i < count; i++) {
1107 		if (WARN_ON_ONCE(i >= max_msr_list_size))
1108 			goto fail;
1109 
1110 		if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
1111 					&e, sizeof(e))) {
1112 			pr_debug_ratelimited(
1113 				"%s cannot read MSR entry (%u, 0x%08llx)\n",
1114 				__func__, i, gpa + i * sizeof(e));
1115 			goto fail;
1116 		}
1117 		if (nested_vmx_load_msr_check(vcpu, &e)) {
1118 			pr_debug_ratelimited(
1119 				"%s check failed (%u, 0x%x, 0x%x)\n",
1120 				__func__, i, e.index, e.reserved);
1121 			goto fail;
1122 		}
1123 		if (kvm_emulate_msr_write(vcpu, e.index, e.value)) {
1124 			pr_debug_ratelimited(
1125 				"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
1126 				__func__, i, e.index, e.value);
1127 			goto fail;
1128 		}
1129 	}
1130 	return 0;
1131 fail:
1132 	/* Note, max_msr_list_size is at most 4096, i.e. this can't wrap. */
1133 	return i + 1;
1134 }
1135 
1136 static bool nested_vmx_get_vmexit_msr_value(struct kvm_vcpu *vcpu,
1137 					    u32 msr_index,
1138 					    u64 *data)
1139 {
1140 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1141 
1142 	/*
1143 	 * If the L0 hypervisor stored a more accurate value for the TSC that
1144 	 * does not include the time taken for emulation of the L2->L1
1145 	 * VM-exit in L0, use the more accurate value.
1146 	 */
1147 	if (msr_index == MSR_IA32_TSC && vmx->nested.tsc_autostore_slot >= 0) {
1148 		int slot = vmx->nested.tsc_autostore_slot;
1149 		u64 host_tsc = vmx->msr_autostore.val[slot].value;
1150 
1151 		*data = kvm_read_l1_tsc(vcpu, host_tsc);
1152 		return true;
1153 	}
1154 
1155 	if (kvm_emulate_msr_read(vcpu, msr_index, data)) {
1156 		pr_debug_ratelimited("%s cannot read MSR (0x%x)\n", __func__,
1157 			msr_index);
1158 		return false;
1159 	}
1160 	return true;
1161 }
1162 
1163 static bool read_and_check_msr_entry(struct kvm_vcpu *vcpu, u64 gpa, int i,
1164 				     struct vmx_msr_entry *e)
1165 {
1166 	if (kvm_vcpu_read_guest(vcpu,
1167 				gpa + i * sizeof(*e),
1168 				e, 2 * sizeof(u32))) {
1169 		pr_debug_ratelimited(
1170 			"%s cannot read MSR entry (%u, 0x%08llx)\n",
1171 			__func__, i, gpa + i * sizeof(*e));
1172 		return false;
1173 	}
1174 	if (nested_vmx_store_msr_check(vcpu, e)) {
1175 		pr_debug_ratelimited(
1176 			"%s check failed (%u, 0x%x, 0x%x)\n",
1177 			__func__, i, e->index, e->reserved);
1178 		return false;
1179 	}
1180 	return true;
1181 }
1182 
1183 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
1184 {
1185 	u64 data;
1186 	u32 i;
1187 	struct vmx_msr_entry e;
1188 	u32 max_msr_list_size = nested_vmx_max_atomic_switch_msrs(vcpu);
1189 
1190 	for (i = 0; i < count; i++) {
1191 		if (WARN_ON_ONCE(i >= max_msr_list_size))
1192 			return -EINVAL;
1193 
1194 		if (!read_and_check_msr_entry(vcpu, gpa, i, &e))
1195 			return -EINVAL;
1196 
1197 		if (!nested_vmx_get_vmexit_msr_value(vcpu, e.index, &data))
1198 			return -EINVAL;
1199 
1200 		if (kvm_vcpu_write_guest(vcpu,
1201 					 gpa + i * sizeof(e) +
1202 					     offsetof(struct vmx_msr_entry, value),
1203 					 &data, sizeof(data))) {
1204 			pr_debug_ratelimited(
1205 				"%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
1206 				__func__, i, e.index, data);
1207 			return -EINVAL;
1208 		}
1209 	}
1210 	return 0;
1211 }
1212 
1213 static bool nested_msr_store_list_has_msr(struct kvm_vcpu *vcpu, u32 msr_index)
1214 {
1215 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1216 	u32 count = vmcs12->vm_exit_msr_store_count;
1217 	u64 gpa = vmcs12->vm_exit_msr_store_addr;
1218 	struct vmx_msr_entry e;
1219 	u32 i;
1220 
1221 	for (i = 0; i < count; i++) {
1222 		if (!read_and_check_msr_entry(vcpu, gpa, i, &e))
1223 			return false;
1224 
1225 		if (e.index == msr_index)
1226 			return true;
1227 	}
1228 	return false;
1229 }
1230 
1231 /*
1232  * Load guest's/host's cr3 at nested entry/exit.  @nested_ept is true if we are
1233  * emulating VM-Entry into a guest with EPT enabled.  On failure, the expected
1234  * Exit Qualification (for a VM-Entry consistency check VM-Exit) is assigned to
1235  * @entry_failure_code.
1236  */
1237 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3,
1238 			       bool nested_ept, bool reload_pdptrs,
1239 			       enum vm_entry_failure_code *entry_failure_code)
1240 {
1241 	if (CC(!kvm_vcpu_is_legal_cr3(vcpu, cr3))) {
1242 		*entry_failure_code = ENTRY_FAIL_DEFAULT;
1243 		return -EINVAL;
1244 	}
1245 
1246 	/*
1247 	 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
1248 	 * must not be dereferenced.
1249 	 */
1250 	if (reload_pdptrs && !nested_ept && is_pae_paging(vcpu) &&
1251 	    CC(!load_pdptrs(vcpu, cr3))) {
1252 		*entry_failure_code = ENTRY_FAIL_PDPTE;
1253 		return -EINVAL;
1254 	}
1255 
1256 	vcpu->arch.cr3 = cr3;
1257 	kvm_register_mark_dirty(vcpu, VCPU_REG_CR3);
1258 
1259 	/* Re-initialize the MMU, e.g. to pick up CR4 MMU role changes. */
1260 	kvm_init_mmu(vcpu);
1261 
1262 	if (!nested_ept)
1263 		kvm_mmu_new_pgd(vcpu, cr3);
1264 
1265 	return 0;
1266 }
1267 
1268 /*
1269  * Returns if KVM is able to config CPU to tag TLB entries
1270  * populated by L2 differently than TLB entries populated
1271  * by L1.
1272  *
1273  * If L0 uses EPT, L1 and L2 run with different EPTP because
1274  * guest_mode is part of kvm_mmu_page_role. Thus, TLB entries
1275  * are tagged with different EPTP.
1276  *
1277  * If L1 uses VPID and we allocated a vpid02, TLB entries are tagged
1278  * with different VPID (L1 entries are tagged with vmx->vpid
1279  * while L2 entries are tagged with vmx->nested.vpid02).
1280  */
1281 static bool nested_has_guest_tlb_tag(struct kvm_vcpu *vcpu)
1282 {
1283 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1284 
1285 	return enable_ept ||
1286 	       (nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02);
1287 }
1288 
1289 static void nested_vmx_transition_tlb_flush(struct kvm_vcpu *vcpu,
1290 					    struct vmcs12 *vmcs12,
1291 					    bool is_vmenter)
1292 {
1293 	struct vcpu_vmx *vmx = to_vmx(vcpu);
1294 
1295 	/* Handle pending Hyper-V TLB flush requests */
1296 	kvm_hv_nested_transtion_tlb_flush(vcpu, enable_ept);
1297 
1298 	/*
1299 	 * If VPID is disabled, then guest TLB accesses use VPID=0, i.e. the
1300 	 * same VPID as the host, and so architecturally, linear and combined
1301 	 * mappings for VPID=0 must be flushed at VM-Enter and VM-Exit.  KVM
1302 	 * emulates L2 sharing L1's VPID=0 by using vpid01 while running L2,
1303 	 * and so KVM must also emulate TLB flush of VPID=0, i.e. vpid01.  This
1304 	 * is required if VPID is disabled in KVM, as a TLB flush (there are no
1305 	 * VPIDs) still occurs from L1's perspective, and KVM may need to
1306 	 * synchronize the MMU in response to the guest TLB flush.
1307 	 *
1308 	 * Note, using TLB_FLUSH_GUEST is correct even if nested EPT is in use.
1309 	 * EPT is a special snowflake, as guest-physical mappings aren't
1310 	 * flushed on VPID invalidations, including VM-Enter or VM-Exit with
1311 	 * VPID disabled.  As a result, KVM _never_ needs to sync nEPT
1312 	 * entries on VM-Enter because L1 can't rely on VM-Enter to flush
1313 	 * those mappings.
1314 	 */
1315 	if (!nested_cpu_has_vpid(vmcs12)) {
1316 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1317 		return;
1318 	}
1319 
1320 	/* L2 should never have a VPID if VPID is disabled. */
1321 	WARN_ON(!enable_vpid);
1322 
1323 	/*
1324 	 * VPID is enabled and in use by vmcs12.  If vpid12 is changing, then
1325 	 * emulate a guest TLB flush as KVM does not track vpid12 history nor
1326 	 * is the VPID incorporated into the MMU context.  I.e. KVM must assume
1327 	 * that the new vpid12 has never been used and thus represents a new
1328 	 * guest ASID that cannot have entries in the TLB.
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 			vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3469 			vcpu->run->internal.suberror =
3470 				KVM_INTERNAL_ERROR_EMULATION;
3471 			vcpu->run->internal.ndata = 0;
3472 			return false;
3473 		}
3474 	}
3475 
3476 	if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
3477 		map = &vmx->nested.virtual_apic_map;
3478 
3479 		if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->virtual_apic_page_addr), map)) {
3480 			vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, pfn_to_hpa(map->pfn));
3481 		} else if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING) &&
3482 		           nested_cpu_has(vmcs12, CPU_BASED_CR8_STORE_EXITING) &&
3483 			   !nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
3484 			/*
3485 			 * The processor will never use the TPR shadow, simply
3486 			 * clear the bit from the execution control.  Such a
3487 			 * configuration is useless, but it happens in tests.
3488 			 * For any other configuration, failing the vm entry is
3489 			 * _not_ what the processor does but it's basically the
3490 			 * only possibility we have.
3491 			 */
3492 			exec_controls_clearbit(vmx, CPU_BASED_TPR_SHADOW);
3493 		} else {
3494 			/*
3495 			 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR to
3496 			 * force VM-Entry to fail.
3497 			 */
3498 			vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, INVALID_GPA);
3499 		}
3500 	}
3501 
3502 	if (nested_cpu_has_posted_intr(vmcs12)) {
3503 		map = &vmx->nested.pi_desc_map;
3504 
3505 		if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->posted_intr_desc_addr), map)) {
3506 			vmx->nested.pi_desc =
3507 				(struct pi_desc *)(((void *)map->hva) +
3508 				offset_in_page(vmcs12->posted_intr_desc_addr));
3509 			vmcs_write64(POSTED_INTR_DESC_ADDR,
3510 				     pfn_to_hpa(map->pfn) + offset_in_page(vmcs12->posted_intr_desc_addr));
3511 		} else {
3512 			/*
3513 			 * Defer the KVM_INTERNAL_EXIT until KVM tries to
3514 			 * access the contents of the VMCS12 posted interrupt
3515 			 * descriptor. (Note that KVM may do this when it
3516 			 * should not, per the architectural specification.)
3517 			 */
3518 			vmx->nested.pi_desc = NULL;
3519 			pin_controls_clearbit(vmx, PIN_BASED_POSTED_INTR);
3520 		}
3521 	}
3522 	if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
3523 		exec_controls_setbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3524 	else
3525 		exec_controls_clearbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3526 
3527 	return true;
3528 }
3529 
3530 static bool vmx_get_nested_state_pages(struct kvm_vcpu *vcpu)
3531 {
3532 #ifdef CONFIG_KVM_HYPERV
3533 	/*
3534 	 * Note: nested_get_evmcs_page() also updates 'vp_assist_page' copy
3535 	 * in 'struct kvm_vcpu_hv' in case eVMCS is in use, this is mandatory
3536 	 * to make nested_evmcs_l2_tlb_flush_enabled() work correctly post
3537 	 * migration.
3538 	 */
3539 	if (!nested_get_evmcs_page(vcpu)) {
3540 		pr_debug_ratelimited("%s: enlightened vmptrld failed\n",
3541 				     __func__);
3542 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3543 		vcpu->run->internal.suberror =
3544 			KVM_INTERNAL_ERROR_EMULATION;
3545 		vcpu->run->internal.ndata = 0;
3546 
3547 		return false;
3548 	}
3549 #endif
3550 
3551 	if (is_guest_mode(vcpu) && !nested_get_vmcs12_pages(vcpu))
3552 		return false;
3553 
3554 	return true;
3555 }
3556 
3557 static int nested_vmx_write_pml_buffer(struct kvm_vcpu *vcpu, gpa_t gpa)
3558 {
3559 	struct vmcs12 *vmcs12;
3560 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3561 	gpa_t dst;
3562 
3563 	if (WARN_ON_ONCE(!is_guest_mode(vcpu)))
3564 		return 0;
3565 
3566 	if (WARN_ON_ONCE(vmx->nested.pml_full))
3567 		return 1;
3568 
3569 	/*
3570 	 * Check if PML is enabled for the nested guest. Whether eptp bit 6 is
3571 	 * set is already checked as part of A/D emulation.
3572 	 */
3573 	vmcs12 = get_vmcs12(vcpu);
3574 	if (!nested_cpu_has_pml(vmcs12))
3575 		return 0;
3576 
3577 	if (vmcs12->guest_pml_index >= PML_LOG_NR_ENTRIES) {
3578 		vmx->nested.pml_full = true;
3579 		return 1;
3580 	}
3581 
3582 	gpa &= ~0xFFFull;
3583 	dst = vmcs12->pml_address + sizeof(u64) * vmcs12->guest_pml_index;
3584 
3585 	if (kvm_write_guest_page(vcpu->kvm, gpa_to_gfn(dst), &gpa,
3586 				 offset_in_page(dst), sizeof(gpa)))
3587 		return 0;
3588 
3589 	vmcs12->guest_pml_index--;
3590 
3591 	return 0;
3592 }
3593 
3594 /*
3595  * Intel's VMX Instruction Reference specifies a common set of prerequisites
3596  * for running VMX instructions (except VMXON, whose prerequisites are
3597  * slightly different). It also specifies what exception to inject otherwise.
3598  * Note that many of these exceptions have priority over VM exits, so they
3599  * don't have to be checked again here.
3600  */
3601 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
3602 {
3603 	if (!to_vmx(vcpu)->nested.vmxon) {
3604 		kvm_queue_exception(vcpu, UD_VECTOR);
3605 		return 0;
3606 	}
3607 
3608 	if (vmx_get_cpl(vcpu)) {
3609 		kvm_inject_gp(vcpu, 0);
3610 		return 0;
3611 	}
3612 
3613 	return 1;
3614 }
3615 
3616 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
3617 				   struct vmcs12 *vmcs12);
3618 
3619 /*
3620  * If from_vmentry is false, this is being called from state restore (either RSM
3621  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
3622  *
3623  * Returns:
3624  *	NVMX_VMENTRY_SUCCESS: Entered VMX non-root mode
3625  *	NVMX_VMENTRY_VMFAIL:  Consistency check VMFail
3626  *	NVMX_VMENTRY_VMEXIT:  Consistency check VMExit
3627  *	NVMX_VMENTRY_KVM_INTERNAL_ERROR: KVM internal error
3628  */
3629 enum nvmx_vmentry_status nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
3630 							bool from_vmentry)
3631 {
3632 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3633 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3634 	enum vm_entry_failure_code entry_failure_code;
3635 	union vmx_exit_reason exit_reason = {
3636 		.basic = EXIT_REASON_INVALID_STATE,
3637 		.failed_vmentry = 1,
3638 	};
3639 	u32 failed_index;
3640 
3641 	trace_kvm_nested_vmenter(kvm_rip_read(vcpu),
3642 				 vmx->nested.current_vmptr,
3643 				 vmcs12->guest_rip,
3644 				 vmcs12->guest_intr_status,
3645 				 vmcs12->vm_entry_intr_info_field,
3646 				 vmcs12->secondary_vm_exec_control & SECONDARY_EXEC_ENABLE_EPT,
3647 				 vmcs12->ept_pointer,
3648 				 vmcs12->guest_cr3,
3649 				 KVM_ISA_VMX);
3650 
3651 	kvm_service_local_tlb_flush_requests(vcpu);
3652 
3653 	if (!vcpu->arch.nested_run_pending ||
3654 	    !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
3655 		vmx->nested.pre_vmenter_debugctl = vmx_guest_debugctl_read();
3656 	if (kvm_mpx_supported() &&
3657 	    (!vcpu->arch.nested_run_pending ||
3658 	     !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)))
3659 		vmx->nested.pre_vmenter_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
3660 
3661 	if (!vcpu->arch.nested_run_pending ||
3662 	    !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_CET_STATE))
3663 		vmcs_read_cet_state(vcpu, &vmx->nested.pre_vmenter_s_cet,
3664 				    &vmx->nested.pre_vmenter_ssp,
3665 				    &vmx->nested.pre_vmenter_ssp_tbl);
3666 
3667 	/*
3668 	 * Stash L1's CR3, so that in the event of a "late" VM-Fail, i.e. a
3669 	 * VM-Fail detected by hardware but not KVM, KVM can unwind its
3670 	 * software model to the pre-VM-Entry host state.  When EPT is
3671 	 * disabled, GUEST_CR3 holds KVM's shadow CR3, not L1's "real" CR3,
3672 	 * and so simply restoring from vmcs01.GUEST_CR3 would corrupt
3673 	 * vcpu->arch.cr3.
3674 	 */
3675 	vmx->nested.pre_vmenter_cr3 = kvm_read_cr3(vcpu);
3676 
3677 	vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
3678 
3679 	prepare_vmcs02_early(vmx, &vmx->vmcs01, vmcs12);
3680 
3681 	if (from_vmentry) {
3682 		if (unlikely(!nested_get_vmcs12_pages(vcpu))) {
3683 			vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3684 			return NVMX_VMENTRY_KVM_INTERNAL_ERROR;
3685 		}
3686 
3687 		if (nested_vmx_check_guest_state(vcpu, vmcs12,
3688 						 &entry_failure_code)) {
3689 			exit_reason.basic = EXIT_REASON_INVALID_STATE;
3690 			vmcs12->exit_qualification = entry_failure_code;
3691 			goto vmentry_fail_vmexit;
3692 		}
3693 	}
3694 
3695 	enter_guest_mode(vcpu);
3696 
3697 	if (prepare_vmcs02(vcpu, vmcs12, from_vmentry, &entry_failure_code)) {
3698 		exit_reason.basic = EXIT_REASON_INVALID_STATE;
3699 		vmcs12->exit_qualification = entry_failure_code;
3700 		goto vmentry_fail_vmexit_guest_mode;
3701 	}
3702 
3703 	if (from_vmentry) {
3704 		failed_index = nested_vmx_load_msr(vcpu,
3705 						   vmcs12->vm_entry_msr_load_addr,
3706 						   vmcs12->vm_entry_msr_load_count);
3707 		if (failed_index) {
3708 			exit_reason.basic = EXIT_REASON_MSR_LOAD_FAIL;
3709 			vmcs12->exit_qualification = failed_index;
3710 			goto vmentry_fail_vmexit_guest_mode;
3711 		}
3712 	} else {
3713 		/*
3714 		 * The MMU is not initialized to point at the right entities yet and
3715 		 * "get pages" would need to read data from the guest (i.e. we will
3716 		 * need to perform gpa to hpa translation). Request a call
3717 		 * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
3718 		 * have already been set at vmentry time and should not be reset.
3719 		 */
3720 		kvm_make_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
3721 	}
3722 
3723 	/*
3724 	 * Re-evaluate pending events if L1 had a pending IRQ/NMI/INIT/SIPI
3725 	 * when it executed VMLAUNCH/VMRESUME, as entering non-root mode can
3726 	 * effectively unblock various events, e.g. INIT/SIPI cause VM-Exit
3727 	 * unconditionally.  Take care to pull data from vmcs01 as appropriate,
3728 	 * e.g. when checking for interrupt windows, as vmcs02 is now loaded.
3729 	 */
3730 	if ((__exec_controls_get(&vmx->vmcs01) & (CPU_BASED_INTR_WINDOW_EXITING |
3731 						  CPU_BASED_NMI_WINDOW_EXITING)) ||
3732 	    kvm_apic_has_pending_init_or_sipi(vcpu) ||
3733 	    kvm_apic_has_interrupt(vcpu))
3734 		kvm_make_request(KVM_REQ_EVENT, vcpu);
3735 
3736 	/*
3737 	 * Do not start the preemption timer hrtimer until after we know
3738 	 * we are successful, so that only nested_vmx_vmexit needs to cancel
3739 	 * the timer.
3740 	 */
3741 	vmx->nested.preemption_timer_expired = false;
3742 	if (nested_cpu_has_preemption_timer(vmcs12)) {
3743 		u64 timer_value = vmx_calc_preemption_timer_value(vcpu);
3744 		vmx_start_preemption_timer(vcpu, timer_value);
3745 	}
3746 
3747 	/*
3748 	 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
3749 	 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
3750 	 * returned as far as L1 is concerned. It will only return (and set
3751 	 * the success flag) when L2 exits (see nested_vmx_vmexit()).
3752 	 */
3753 	return NVMX_VMENTRY_SUCCESS;
3754 
3755 	/*
3756 	 * A failed consistency check that leads to a VMExit during L1's
3757 	 * VMEnter to L2 is a variation of a normal VMexit, as explained in
3758 	 * 26.7 "VM-entry failures during or after loading guest state".
3759 	 */
3760 vmentry_fail_vmexit_guest_mode:
3761 	if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
3762 		vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
3763 	leave_guest_mode(vcpu);
3764 
3765 vmentry_fail_vmexit:
3766 	vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3767 
3768 	if (!from_vmentry)
3769 		return NVMX_VMENTRY_VMEXIT;
3770 
3771 	nested_put_vmcs12_pages(vcpu);
3772 
3773 	load_vmcs12_host_state(vcpu, vmcs12);
3774 	vmcs12->vm_exit_reason = exit_reason.full;
3775 	if (enable_shadow_vmcs || nested_vmx_is_evmptr12_valid(vmx))
3776 		vmx->nested.need_vmcs12_to_shadow_sync = true;
3777 	return NVMX_VMENTRY_VMEXIT;
3778 }
3779 
3780 /*
3781  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
3782  * for running an L2 nested guest.
3783  */
3784 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
3785 {
3786 	struct vmcs12 *vmcs12;
3787 	enum nvmx_vmentry_status status;
3788 	struct vcpu_vmx *vmx = to_vmx(vcpu);
3789 	u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
3790 	enum nested_evmptrld_status evmptrld_status;
3791 
3792 	if (!nested_vmx_check_permission(vcpu))
3793 		return 1;
3794 
3795 	evmptrld_status = nested_vmx_handle_enlightened_vmptrld(vcpu, launch);
3796 	if (evmptrld_status == EVMPTRLD_ERROR) {
3797 		kvm_queue_exception(vcpu, UD_VECTOR);
3798 		return 1;
3799 	}
3800 
3801 	kvm_pmu_branch_retired(vcpu);
3802 
3803 	if (CC(evmptrld_status == EVMPTRLD_VMFAIL))
3804 		return nested_vmx_failInvalid(vcpu);
3805 
3806 	if (CC(!nested_vmx_is_evmptr12_valid(vmx) &&
3807 	       vmx->nested.current_vmptr == INVALID_GPA))
3808 		return nested_vmx_failInvalid(vcpu);
3809 
3810 	vmcs12 = get_vmcs12(vcpu);
3811 
3812 	/*
3813 	 * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
3814 	 * that there *is* a valid VMCS pointer, RFLAGS.CF is set
3815 	 * rather than RFLAGS.ZF, and no error number is stored to the
3816 	 * VM-instruction error field.
3817 	 */
3818 	if (CC(vmcs12->hdr.shadow_vmcs))
3819 		return nested_vmx_failInvalid(vcpu);
3820 
3821 	if (nested_vmx_is_evmptr12_valid(vmx)) {
3822 		struct hv_enlightened_vmcs *evmcs = nested_vmx_evmcs(vmx);
3823 
3824 		copy_enlightened_to_vmcs12(vmx, evmcs->hv_clean_fields);
3825 		/* Enlightened VMCS doesn't have launch state */
3826 		vmcs12->launch_state = !launch;
3827 	} else if (enable_shadow_vmcs) {
3828 		copy_shadow_to_vmcs12(vmx);
3829 	}
3830 
3831 	/*
3832 	 * The nested entry process starts with enforcing various prerequisites
3833 	 * on vmcs12 as required by the Intel SDM, and act appropriately when
3834 	 * they fail: As the SDM explains, some conditions should cause the
3835 	 * instruction to fail, while others will cause the instruction to seem
3836 	 * to succeed, but return an EXIT_REASON_INVALID_STATE.
3837 	 * To speed up the normal (success) code path, we should avoid checking
3838 	 * for misconfigurations which will anyway be caught by the processor
3839 	 * when using the merged vmcs02.
3840 	 */
3841 	if (CC(interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS))
3842 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
3843 
3844 	if (CC(vmcs12->launch_state == launch))
3845 		return nested_vmx_fail(vcpu,
3846 			launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
3847 			       : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
3848 
3849 	if (nested_vmx_check_controls(vcpu, vmcs12))
3850 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3851 
3852 	if (nested_vmx_check_address_space_size(vcpu, vmcs12))
3853 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
3854 
3855 	if (nested_vmx_check_host_state(vcpu, vmcs12))
3856 		return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
3857 
3858 	/*
3859 	 * We're finally done with prerequisite checking, and can start with
3860 	 * the nested entry.
3861 	 */
3862 	vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING;
3863 	vmx->nested.has_preemption_timer_deadline = false;
3864 	status = nested_vmx_enter_non_root_mode(vcpu, true);
3865 	if (unlikely(status != NVMX_VMENTRY_SUCCESS))
3866 		goto vmentry_failed;
3867 
3868 	/* Hide L1D cache contents from the nested guest.  */
3869 	kvm_request_l1tf_flush_l1d();
3870 
3871 	/*
3872 	 * Must happen outside of nested_vmx_enter_non_root_mode() as it will
3873 	 * also be used as part of restoring nVMX state for
3874 	 * snapshot restore (migration).
3875 	 *
3876 	 * In this flow, it is assumed that vmcs12 cache was
3877 	 * transferred as part of captured nVMX state and should
3878 	 * therefore not be read from guest memory (which may not
3879 	 * exist on destination host yet).
3880 	 */
3881 	nested_cache_shadow_vmcs12(vcpu, vmcs12);
3882 
3883 	switch (vmcs12->guest_activity_state) {
3884 	case GUEST_ACTIVITY_HLT:
3885 		/*
3886 		 * If we're entering a halted L2 vcpu and the L2 vcpu won't be
3887 		 * awakened by event injection or by an NMI-window VM-exit or
3888 		 * by an interrupt-window VM-exit, halt the vcpu.
3889 		 */
3890 		if (!(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) &&
3891 		    !nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING) &&
3892 		    !(nested_cpu_has(vmcs12, CPU_BASED_INTR_WINDOW_EXITING) &&
3893 		      (vmcs12->guest_rflags & X86_EFLAGS_IF))) {
3894 			vcpu->arch.nested_run_pending = 0;
3895 			return kvm_emulate_halt_noskip(vcpu);
3896 		}
3897 		break;
3898 	case GUEST_ACTIVITY_WAIT_SIPI:
3899 		vcpu->arch.nested_run_pending = 0;
3900 		kvm_set_mp_state(vcpu, KVM_MP_STATE_INIT_RECEIVED);
3901 		break;
3902 	default:
3903 		break;
3904 	}
3905 
3906 	return 1;
3907 
3908 vmentry_failed:
3909 	vcpu->arch.nested_run_pending = 0;
3910 	if (status == NVMX_VMENTRY_KVM_INTERNAL_ERROR)
3911 		return 0;
3912 	if (status == NVMX_VMENTRY_VMEXIT)
3913 		return 1;
3914 	WARN_ON_ONCE(status != NVMX_VMENTRY_VMFAIL);
3915 	return nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3916 }
3917 
3918 /*
3919  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
3920  * because L2 may have changed some cr0 bits directly (CR0_GUEST_HOST_MASK).
3921  * This function returns the new value we should put in vmcs12.guest_cr0.
3922  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
3923  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
3924  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
3925  *     didn't trap the bit, because if L1 did, so would L0).
3926  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
3927  *     been modified by L2, and L1 knows it. So just leave the old value of
3928  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
3929  *     isn't relevant, because if L0 traps this bit it can set it to anything.
3930  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
3931  *     changed these bits, and therefore they need to be updated, but L0
3932  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
3933  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
3934  */
3935 static inline unsigned long
3936 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3937 {
3938 	return
3939 	/*1*/	(vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
3940 	/*2*/	(vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
3941 	/*3*/	(vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
3942 			vcpu->arch.cr0_guest_owned_bits));
3943 }
3944 
3945 static inline unsigned long
3946 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3947 {
3948 	return
3949 	/*1*/	(vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
3950 	/*2*/	(vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
3951 	/*3*/	(vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
3952 			vcpu->arch.cr4_guest_owned_bits));
3953 }
3954 
3955 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
3956 				      struct vmcs12 *vmcs12,
3957 				      u32 vm_exit_reason, u32 exit_intr_info)
3958 {
3959 	u32 idt_vectoring;
3960 	unsigned int nr;
3961 
3962 	/*
3963 	 * Per the SDM, VM-Exits due to double and triple faults are never
3964 	 * considered to occur during event delivery, even if the double/triple
3965 	 * fault is the result of an escalating vectoring issue.
3966 	 *
3967 	 * Note, the SDM qualifies the double fault behavior with "The original
3968 	 * event results in a double-fault exception".  It's unclear why the
3969 	 * qualification exists since exits due to double fault can occur only
3970 	 * while vectoring a different exception (injected events are never
3971 	 * subject to interception), i.e. there's _always_ an original event.
3972 	 *
3973 	 * The SDM also uses NMI as a confusing example for the "original event
3974 	 * causes the VM exit directly" clause.  NMI isn't special in any way,
3975 	 * the same rule applies to all events that cause an exit directly.
3976 	 * NMI is an odd choice for the example because NMIs can only occur on
3977 	 * instruction boundaries, i.e. they _can't_ occur during vectoring.
3978 	 */
3979 	if ((u16)vm_exit_reason == EXIT_REASON_TRIPLE_FAULT ||
3980 	    ((u16)vm_exit_reason == EXIT_REASON_EXCEPTION_NMI &&
3981 	     is_double_fault(exit_intr_info))) {
3982 		vmcs12->idt_vectoring_info_field = 0;
3983 	} else if (vcpu->arch.exception.injected) {
3984 		nr = vcpu->arch.exception.vector;
3985 		idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
3986 
3987 		if (kvm_exception_is_soft(nr)) {
3988 			vmcs12->vm_exit_instruction_len =
3989 				vcpu->arch.event_exit_inst_len;
3990 			idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
3991 		} else
3992 			idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
3993 
3994 		if (vcpu->arch.exception.has_error_code) {
3995 			idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
3996 			vmcs12->idt_vectoring_error_code =
3997 				vcpu->arch.exception.error_code;
3998 		}
3999 
4000 		vmcs12->idt_vectoring_info_field = idt_vectoring;
4001 	} else if (vcpu->arch.nmi_injected) {
4002 		vmcs12->idt_vectoring_info_field =
4003 			INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
4004 	} else if (vcpu->arch.interrupt.injected) {
4005 		nr = vcpu->arch.interrupt.nr;
4006 		idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
4007 
4008 		if (vcpu->arch.interrupt.soft) {
4009 			idt_vectoring |= INTR_TYPE_SOFT_INTR;
4010 			vmcs12->vm_entry_instruction_len =
4011 				vcpu->arch.event_exit_inst_len;
4012 		} else
4013 			idt_vectoring |= INTR_TYPE_EXT_INTR;
4014 
4015 		vmcs12->idt_vectoring_info_field = idt_vectoring;
4016 	} else {
4017 		vmcs12->idt_vectoring_info_field = 0;
4018 	}
4019 }
4020 
4021 static int vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
4022 {
4023 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4024 	int max_irr;
4025 	void *vapic_page;
4026 	u16 status;
4027 
4028 	if (!vmx->nested.pi_pending)
4029 		return 0;
4030 
4031 	if (!vmx->nested.pi_desc)
4032 		goto mmio_needed;
4033 
4034 	vmx->nested.pi_pending = false;
4035 
4036 	if (!pi_test_and_clear_on(vmx->nested.pi_desc))
4037 		return 0;
4038 
4039 	max_irr = pi_find_highest_vector(vmx->nested.pi_desc);
4040 	if (max_irr > 0) {
4041 		vapic_page = vmx->nested.virtual_apic_map.hva;
4042 		if (!vapic_page)
4043 			goto mmio_needed;
4044 
4045 		__kvm_apic_update_irr(vmx->nested.pi_desc->pir,
4046 			vapic_page, &max_irr);
4047 		status = vmcs_read16(GUEST_INTR_STATUS);
4048 		if ((u8)max_irr > ((u8)status & 0xff)) {
4049 			status &= ~0xff;
4050 			status |= (u8)max_irr;
4051 			vmcs_write16(GUEST_INTR_STATUS, status);
4052 		}
4053 	}
4054 
4055 	kvm_vcpu_map_mark_dirty(vcpu, &vmx->nested.virtual_apic_map);
4056 	kvm_vcpu_map_mark_dirty(vcpu, &vmx->nested.pi_desc_map);
4057 	return 0;
4058 
4059 mmio_needed:
4060 	kvm_handle_memory_failure(vcpu, X86EMUL_IO_NEEDED, NULL);
4061 	return -ENXIO;
4062 }
4063 
4064 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu)
4065 {
4066 	struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
4067 	u32 intr_info = ex->vector | INTR_INFO_VALID_MASK;
4068 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4069 	unsigned long exit_qual;
4070 
4071 	if (ex->has_payload) {
4072 		exit_qual = ex->payload;
4073 	} else if (ex->vector == PF_VECTOR) {
4074 		exit_qual = vcpu->arch.cr2;
4075 	} else if (ex->vector == DB_VECTOR) {
4076 		exit_qual = vcpu->arch.dr6;
4077 		exit_qual &= ~DR6_BT;
4078 		exit_qual ^= DR6_ACTIVE_LOW;
4079 	} else {
4080 		exit_qual = 0;
4081 	}
4082 
4083 	/*
4084 	 * Unlike AMD's Paged Real Mode, which reports an error code on #PF
4085 	 * VM-Exits even if the CPU is in Real Mode, Intel VMX never sets the
4086 	 * "has error code" flags on VM-Exit if the CPU is in Real Mode.
4087 	 */
4088 	if (ex->has_error_code && is_protmode(vcpu)) {
4089 		/*
4090 		 * Intel CPUs do not generate error codes with bits 31:16 set,
4091 		 * and more importantly VMX disallows setting bits 31:16 in the
4092 		 * injected error code for VM-Entry.  Drop the bits to mimic
4093 		 * hardware and avoid inducing failure on nested VM-Entry if L1
4094 		 * chooses to inject the exception back to L2.  AMD CPUs _do_
4095 		 * generate "full" 32-bit error codes, so KVM allows userspace
4096 		 * to inject exception error codes with bits 31:16 set.
4097 		 */
4098 		vmcs12->vm_exit_intr_error_code = (u16)ex->error_code;
4099 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
4100 	}
4101 
4102 	if (kvm_exception_is_soft(ex->vector))
4103 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
4104 	else
4105 		intr_info |= INTR_TYPE_HARD_EXCEPTION;
4106 
4107 	if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
4108 	    vmx_get_nmi_mask(vcpu))
4109 		intr_info |= INTR_INFO_UNBLOCK_NMI;
4110 
4111 	nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
4112 }
4113 
4114 /*
4115  * Returns true if a debug trap is (likely) pending delivery.  Infer the class
4116  * of a #DB (trap-like vs. fault-like) from the exception payload (to-be-DR6).
4117  * Using the payload is flawed because code breakpoints (fault-like) and data
4118  * breakpoints (trap-like) set the same bits in DR6 (breakpoint detected), i.e.
4119  * this will return false positives if a to-be-injected code breakpoint #DB is
4120  * pending (from KVM's perspective, but not "pending" across an instruction
4121  * boundary).  ICEBP, a.k.a. INT1, is also not reflected here even though it
4122  * too is trap-like.
4123  *
4124  * KVM "works" despite these flaws as ICEBP isn't currently supported by the
4125  * emulator, Monitor Trap Flag is not marked pending on intercepted #DBs (the
4126  * #DB has already happened), and MTF isn't marked pending on code breakpoints
4127  * from the emulator (because such #DBs are fault-like and thus don't trigger
4128  * actions that fire on instruction retire).
4129  */
4130 static unsigned long vmx_get_pending_dbg_trap(struct kvm_queued_exception *ex)
4131 {
4132 	if (!ex->pending || ex->vector != DB_VECTOR)
4133 		return 0;
4134 
4135 	/* General Detect #DBs are always fault-like. */
4136 	return ex->payload & ~DR6_BD;
4137 }
4138 
4139 /*
4140  * Returns true if there's a pending #DB exception that is lower priority than
4141  * a pending Monitor Trap Flag VM-Exit.  TSS T-flag #DBs are not emulated by
4142  * KVM, but could theoretically be injected by userspace.  Note, this code is
4143  * imperfect, see above.
4144  */
4145 static bool vmx_is_low_priority_db_trap(struct kvm_queued_exception *ex)
4146 {
4147 	return vmx_get_pending_dbg_trap(ex) & ~DR6_BT;
4148 }
4149 
4150 /*
4151  * Certain VM-exits set the 'pending debug exceptions' field to indicate a
4152  * recognized #DB (data or single-step) that has yet to be delivered. Since KVM
4153  * represents these debug traps with a payload that is said to be compatible
4154  * with the 'pending debug exceptions' field, write the payload to the VMCS
4155  * field if a VM-exit is delivered before the debug trap.
4156  */
4157 static void nested_vmx_update_pending_dbg(struct kvm_vcpu *vcpu)
4158 {
4159 	unsigned long pending_dbg;
4160 
4161 	pending_dbg = vmx_get_pending_dbg_trap(&vcpu->arch.exception);
4162 	if (pending_dbg)
4163 		vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, pending_dbg);
4164 }
4165 
4166 static bool nested_vmx_preemption_timer_pending(struct kvm_vcpu *vcpu)
4167 {
4168 	return nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
4169 	       to_vmx(vcpu)->nested.preemption_timer_expired;
4170 }
4171 
4172 static bool vmx_has_nested_events(struct kvm_vcpu *vcpu, bool for_injection)
4173 {
4174 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4175 	void *vapic = vmx->nested.virtual_apic_map.hva;
4176 	int max_irr, vppr;
4177 
4178 	if (nested_vmx_preemption_timer_pending(vcpu) ||
4179 	    vmx->nested.mtf_pending)
4180 		return true;
4181 
4182 	/*
4183 	 * Virtual Interrupt Delivery doesn't require manual injection.  Either
4184 	 * the interrupt is already in GUEST_RVI and will be recognized by CPU
4185 	 * at VM-Entry, or there is a KVM_REQ_EVENT pending and KVM will move
4186 	 * the interrupt from the PIR to RVI prior to entering the guest.
4187 	 */
4188 	if (for_injection)
4189 		return false;
4190 
4191 	if (!nested_cpu_has_vid(get_vmcs12(vcpu)) ||
4192 	    __vmx_interrupt_blocked(vcpu))
4193 		return false;
4194 
4195 	if (!vapic)
4196 		return false;
4197 
4198 	vppr = *((u32 *)(vapic + APIC_PROCPRI));
4199 
4200 	max_irr = vmx_get_rvi();
4201 	if ((max_irr & 0xf0) > (vppr & 0xf0))
4202 		return true;
4203 
4204 	if (vmx->nested.pi_pending && vmx->nested.pi_desc &&
4205 	    pi_test_on(vmx->nested.pi_desc)) {
4206 		max_irr = pi_find_highest_vector(vmx->nested.pi_desc);
4207 		if (max_irr > 0 && (max_irr & 0xf0) > (vppr & 0xf0))
4208 			return true;
4209 	}
4210 
4211 	return false;
4212 }
4213 
4214 /*
4215  * Per the Intel SDM's table "Priority Among Concurrent Events", with minor
4216  * edits to fill in missing examples, e.g. #DB due to split-lock accesses,
4217  * and less minor edits to splice in the priority of VMX Non-Root specific
4218  * events, e.g. MTF and NMI/INTR-window exiting.
4219  *
4220  * 1 Hardware Reset and Machine Checks
4221  *	- RESET
4222  *	- Machine Check
4223  *
4224  * 2 Trap on Task Switch
4225  *	- T flag in TSS is set (on task switch)
4226  *
4227  * 3 External Hardware Interventions
4228  *	- FLUSH
4229  *	- STOPCLK
4230  *	- SMI
4231  *	- INIT
4232  *
4233  * 3.5 Monitor Trap Flag (MTF) VM-exit[1]
4234  *
4235  * 4 Traps on Previous Instruction
4236  *	- Breakpoints
4237  *	- Trap-class Debug Exceptions (#DB due to TF flag set, data/I-O
4238  *	  breakpoint, or #DB due to a split-lock access)
4239  *
4240  * 4.3	VMX-preemption timer expired VM-exit
4241  *
4242  * 4.6	NMI-window exiting VM-exit[2]
4243  *
4244  * 5 Nonmaskable Interrupts (NMI)
4245  *
4246  * 5.5 Interrupt-window exiting VM-exit and Virtual-interrupt delivery
4247  *
4248  * 6 Maskable Hardware Interrupts
4249  *
4250  * 7 Code Breakpoint Fault
4251  *
4252  * 8 Faults from Fetching Next Instruction
4253  *	- Code-Segment Limit Violation
4254  *	- Code Page Fault
4255  *	- Control protection exception (missing ENDBRANCH at target of indirect
4256  *					call or jump)
4257  *
4258  * 9 Faults from Decoding Next Instruction
4259  *	- Instruction length > 15 bytes
4260  *	- Invalid Opcode
4261  *	- Coprocessor Not Available
4262  *
4263  *10 Faults on Executing Instruction
4264  *	- Overflow
4265  *	- Bound error
4266  *	- Invalid TSS
4267  *	- Segment Not Present
4268  *	- Stack fault
4269  *	- General Protection
4270  *	- Data Page Fault
4271  *	- Alignment Check
4272  *	- x86 FPU Floating-point exception
4273  *	- SIMD floating-point exception
4274  *	- Virtualization exception
4275  *	- Control protection exception
4276  *
4277  * [1] Per the "Monitor Trap Flag" section: System-management interrupts (SMIs),
4278  *     INIT signals, and higher priority events take priority over MTF VM exits.
4279  *     MTF VM exits take priority over debug-trap exceptions and lower priority
4280  *     events.
4281  *
4282  * [2] Debug-trap exceptions and higher priority events take priority over VM exits
4283  *     caused by the VMX-preemption timer.  VM exits caused by the VMX-preemption
4284  *     timer take priority over VM exits caused by the "NMI-window exiting"
4285  *     VM-execution control and lower priority events.
4286  *
4287  * [3] Debug-trap exceptions and higher priority events take priority over VM exits
4288  *     caused by "NMI-window exiting".  VM exits caused by this control take
4289  *     priority over non-maskable interrupts (NMIs) and lower priority events.
4290  *
4291  * [4] Virtual-interrupt delivery has the same priority as that of VM exits due to
4292  *     the 1-setting of the "interrupt-window exiting" VM-execution control.  Thus,
4293  *     non-maskable interrupts (NMIs) and higher priority events take priority over
4294  *     delivery of a virtual interrupt; delivery of a virtual interrupt takes
4295  *     priority over external interrupts and lower priority events.
4296  */
4297 static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
4298 {
4299 	struct kvm_lapic *apic = vcpu->arch.apic;
4300 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4301 	/*
4302 	 * Only a pending nested run blocks a pending exception.  If there is a
4303 	 * previously injected event, the pending exception occurred while said
4304 	 * event was being delivered and thus needs to be handled.
4305 	 */
4306 	bool block_nested_exceptions = vcpu->arch.nested_run_pending;
4307 	/*
4308 	 * Events that don't require injection, i.e. that are virtualized by
4309 	 * hardware, aren't blocked by a pending VM-Enter as KVM doesn't need
4310 	 * to regain control in order to deliver the event, and hardware will
4311 	 * handle event ordering, e.g. with respect to injected exceptions.
4312 	 *
4313 	 * But, new events (not exceptions) are only recognized at instruction
4314 	 * boundaries.  If an event needs reinjection, then KVM is handling a
4315 	 * VM-Exit that occurred _during_ instruction execution; new events,
4316 	 * irrespective of whether or not they're injected, are blocked until
4317 	 * the instruction completes.
4318 	 */
4319 	bool block_non_injected_events = kvm_event_needs_reinjection(vcpu);
4320 	/*
4321 	 * Inject events are blocked by nested VM-Enter, as KVM is responsible
4322 	 * for managing priority between concurrent events, i.e. KVM needs to
4323 	 * wait until after VM-Enter completes to deliver injected events.
4324 	 */
4325 	bool block_nested_events = block_nested_exceptions ||
4326 				   block_non_injected_events;
4327 
4328 	if (lapic_in_kernel(vcpu) &&
4329 		test_bit(KVM_APIC_INIT, &apic->pending_events)) {
4330 		if (block_nested_events)
4331 			return -EBUSY;
4332 		nested_vmx_update_pending_dbg(vcpu);
4333 		clear_bit(KVM_APIC_INIT, &apic->pending_events);
4334 		if (vcpu->arch.mp_state != KVM_MP_STATE_INIT_RECEIVED)
4335 			nested_vmx_vmexit(vcpu, EXIT_REASON_INIT_SIGNAL, 0, 0);
4336 
4337 		/* MTF is discarded if the vCPU is in WFS. */
4338 		vmx->nested.mtf_pending = false;
4339 		return 0;
4340 	}
4341 
4342 	if (lapic_in_kernel(vcpu) &&
4343 	    test_bit(KVM_APIC_SIPI, &apic->pending_events)) {
4344 		if (block_nested_events)
4345 			return -EBUSY;
4346 
4347 		clear_bit(KVM_APIC_SIPI, &apic->pending_events);
4348 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
4349 			nested_vmx_vmexit(vcpu, EXIT_REASON_SIPI_SIGNAL, 0,
4350 						apic->sipi_vector & 0xFFUL);
4351 			return 0;
4352 		}
4353 		/* Fallthrough, the SIPI is completely ignored. */
4354 	}
4355 
4356 	/*
4357 	 * Process exceptions that are higher priority than Monitor Trap Flag:
4358 	 * fault-like exceptions, TSS T flag #DB (not emulated by KVM, but
4359 	 * could theoretically come in from userspace), and ICEBP (INT1).
4360 	 *
4361 	 * TODO: SMIs have higher priority than MTF and trap-like #DBs (except
4362 	 * for TSS T flag #DBs).  KVM also doesn't save/restore pending MTF
4363 	 * across SMI/RSM as it should; that needs to be addressed in order to
4364 	 * prioritize SMI over MTF and trap-like #DBs.
4365 	 */
4366 	if (vcpu->arch.exception_vmexit.pending &&
4367 	    !vmx_is_low_priority_db_trap(&vcpu->arch.exception_vmexit)) {
4368 		if (block_nested_exceptions)
4369 			return -EBUSY;
4370 
4371 		nested_vmx_inject_exception_vmexit(vcpu);
4372 		return 0;
4373 	}
4374 
4375 	if (vcpu->arch.exception.pending &&
4376 	    !vmx_is_low_priority_db_trap(&vcpu->arch.exception)) {
4377 		if (block_nested_exceptions)
4378 			return -EBUSY;
4379 		goto no_vmexit;
4380 	}
4381 
4382 	if (vmx->nested.mtf_pending) {
4383 		if (block_nested_events)
4384 			return -EBUSY;
4385 		nested_vmx_update_pending_dbg(vcpu);
4386 		nested_vmx_vmexit(vcpu, EXIT_REASON_MONITOR_TRAP_FLAG, 0, 0);
4387 		return 0;
4388 	}
4389 
4390 	if (vcpu->arch.exception_vmexit.pending) {
4391 		if (block_nested_exceptions)
4392 			return -EBUSY;
4393 
4394 		nested_vmx_inject_exception_vmexit(vcpu);
4395 		return 0;
4396 	}
4397 
4398 	if (vcpu->arch.exception.pending) {
4399 		if (block_nested_exceptions)
4400 			return -EBUSY;
4401 		goto no_vmexit;
4402 	}
4403 
4404 	if (nested_vmx_preemption_timer_pending(vcpu)) {
4405 		if (block_nested_events)
4406 			return -EBUSY;
4407 		nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
4408 		return 0;
4409 	}
4410 
4411 	if (vcpu->arch.smi_pending && !is_smm(vcpu)) {
4412 		if (block_nested_events)
4413 			return -EBUSY;
4414 		goto no_vmexit;
4415 	}
4416 
4417 	if (vcpu->arch.nmi_pending && !vmx_nmi_blocked(vcpu)) {
4418 		if (block_nested_events)
4419 			return -EBUSY;
4420 		if (!nested_exit_on_nmi(vcpu))
4421 			goto no_vmexit;
4422 
4423 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
4424 				  NMI_VECTOR | INTR_TYPE_NMI_INTR |
4425 				  INTR_INFO_VALID_MASK, 0);
4426 		/*
4427 		 * The NMI-triggered VM exit counts as injection:
4428 		 * clear this one and block further NMIs.
4429 		 */
4430 		vcpu->arch.nmi_pending = 0;
4431 		vmx_set_nmi_mask(vcpu, true);
4432 		return 0;
4433 	}
4434 
4435 	if (kvm_cpu_has_interrupt(vcpu) && !vmx_interrupt_blocked(vcpu)) {
4436 		int irq;
4437 
4438 		if (!nested_exit_on_intr(vcpu)) {
4439 			if (block_nested_events)
4440 				return -EBUSY;
4441 
4442 			goto no_vmexit;
4443 		}
4444 
4445 		if (!nested_exit_intr_ack_set(vcpu)) {
4446 			if (block_nested_events)
4447 				return -EBUSY;
4448 
4449 			nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
4450 			return 0;
4451 		}
4452 
4453 		irq = kvm_cpu_get_extint(vcpu);
4454 		if (irq != -1) {
4455 			if (block_nested_events)
4456 				return -EBUSY;
4457 
4458 			nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT,
4459 					  INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR | irq, 0);
4460 			return 0;
4461 		}
4462 
4463 		irq = kvm_apic_has_interrupt(vcpu);
4464 		if (WARN_ON_ONCE(irq < 0))
4465 			goto no_vmexit;
4466 
4467 		/*
4468 		 * If the IRQ is L2's PI notification vector, process posted
4469 		 * interrupts for L2 instead of injecting VM-Exit, as the
4470 		 * detection/morphing architecturally occurs when the IRQ is
4471 		 * delivered to the CPU.  Note, only interrupts that are routed
4472 		 * through the local APIC trigger posted interrupt processing,
4473 		 * and enabling posted interrupts requires ACK-on-exit.
4474 		 */
4475 		if (irq == vmx->nested.posted_intr_nv) {
4476 			/*
4477 			 * Nested posted interrupts are delivered via RVI, i.e.
4478 			 * aren't injected by KVM, and so can be queued even if
4479 			 * manual event injection is disallowed.
4480 			 */
4481 			if (block_non_injected_events)
4482 				return -EBUSY;
4483 
4484 			vmx->nested.pi_pending = true;
4485 			kvm_apic_clear_irr(vcpu, irq);
4486 			goto no_vmexit;
4487 		}
4488 
4489 		if (block_nested_events)
4490 			return -EBUSY;
4491 
4492 		nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT,
4493 				  INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR | irq, 0);
4494 
4495 		/*
4496 		 * ACK the interrupt _after_ emulating VM-Exit, as the IRQ must
4497 		 * be marked as in-service in vmcs01.GUEST_INTERRUPT_STATUS.SVI
4498 		 * if APICv is active.
4499 		 */
4500 		kvm_apic_ack_interrupt(vcpu, irq);
4501 		return 0;
4502 	}
4503 
4504 no_vmexit:
4505 	return vmx_complete_nested_posted_interrupt(vcpu);
4506 }
4507 
4508 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
4509 {
4510 	ktime_t remaining =
4511 		hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
4512 	u64 value;
4513 
4514 	if (ktime_to_ns(remaining) <= 0)
4515 		return 0;
4516 
4517 	value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
4518 	do_div(value, 1000000);
4519 	return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
4520 }
4521 
4522 static bool is_vmcs12_ext_field(unsigned long field)
4523 {
4524 	switch (field) {
4525 	case GUEST_ES_SELECTOR:
4526 	case GUEST_CS_SELECTOR:
4527 	case GUEST_SS_SELECTOR:
4528 	case GUEST_DS_SELECTOR:
4529 	case GUEST_FS_SELECTOR:
4530 	case GUEST_GS_SELECTOR:
4531 	case GUEST_LDTR_SELECTOR:
4532 	case GUEST_TR_SELECTOR:
4533 	case GUEST_ES_LIMIT:
4534 	case GUEST_CS_LIMIT:
4535 	case GUEST_SS_LIMIT:
4536 	case GUEST_DS_LIMIT:
4537 	case GUEST_FS_LIMIT:
4538 	case GUEST_GS_LIMIT:
4539 	case GUEST_LDTR_LIMIT:
4540 	case GUEST_TR_LIMIT:
4541 	case GUEST_GDTR_LIMIT:
4542 	case GUEST_IDTR_LIMIT:
4543 	case GUEST_ES_AR_BYTES:
4544 	case GUEST_DS_AR_BYTES:
4545 	case GUEST_FS_AR_BYTES:
4546 	case GUEST_GS_AR_BYTES:
4547 	case GUEST_LDTR_AR_BYTES:
4548 	case GUEST_TR_AR_BYTES:
4549 	case GUEST_ES_BASE:
4550 	case GUEST_CS_BASE:
4551 	case GUEST_SS_BASE:
4552 	case GUEST_DS_BASE:
4553 	case GUEST_FS_BASE:
4554 	case GUEST_GS_BASE:
4555 	case GUEST_LDTR_BASE:
4556 	case GUEST_TR_BASE:
4557 	case GUEST_GDTR_BASE:
4558 	case GUEST_IDTR_BASE:
4559 	case GUEST_PENDING_DBG_EXCEPTIONS:
4560 	case GUEST_BNDCFGS:
4561 		return true;
4562 	default:
4563 		break;
4564 	}
4565 
4566 	return false;
4567 }
4568 
4569 static void sync_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
4570 				       struct vmcs12 *vmcs12)
4571 {
4572 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4573 
4574 	vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
4575 	vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
4576 	vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
4577 	vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
4578 	vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
4579 	vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
4580 	vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
4581 	vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
4582 	vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
4583 	vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
4584 	vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
4585 	vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
4586 	vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
4587 	vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
4588 	vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
4589 	vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
4590 	vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
4591 	vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
4592 	vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
4593 	vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
4594 	vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
4595 	vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
4596 	vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
4597 	vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
4598 	vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
4599 	vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
4600 	vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
4601 	vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
4602 	vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
4603 	vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
4604 	vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
4605 	vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
4606 	vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
4607 	vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
4608 	vmcs12->guest_pending_dbg_exceptions =
4609 		vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
4610 
4611 	vmx->nested.need_sync_vmcs02_to_vmcs12_rare = false;
4612 }
4613 
4614 static void copy_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
4615 				       struct vmcs12 *vmcs12)
4616 {
4617 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4618 	int cpu;
4619 
4620 	if (!vmx->nested.need_sync_vmcs02_to_vmcs12_rare)
4621 		return;
4622 
4623 
4624 	WARN_ON_ONCE(vmx->loaded_vmcs != &vmx->vmcs01);
4625 
4626 	cpu = get_cpu();
4627 	vmx->loaded_vmcs = &vmx->nested.vmcs02;
4628 	vmx_vcpu_load_vmcs(vcpu, cpu);
4629 
4630 	sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
4631 
4632 	vmx->loaded_vmcs = &vmx->vmcs01;
4633 	vmx_vcpu_load_vmcs(vcpu, cpu);
4634 	put_cpu();
4635 }
4636 
4637 /*
4638  * Update the guest state fields of vmcs12 to reflect changes that
4639  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
4640  * VM-entry controls is also updated, since this is really a guest
4641  * state bit.)
4642  */
4643 static void sync_vmcs02_to_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
4644 {
4645 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4646 
4647 	if (nested_vmx_is_evmptr12_valid(vmx))
4648 		sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
4649 
4650 	vmx->nested.need_sync_vmcs02_to_vmcs12_rare =
4651 		!nested_vmx_is_evmptr12_valid(vmx);
4652 
4653 	vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
4654 	vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
4655 
4656 	vmcs12->guest_rsp = kvm_rsp_read(vcpu);
4657 	vmcs12->guest_rip = kvm_rip_read(vcpu);
4658 	vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
4659 
4660 	vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
4661 	vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
4662 
4663 	vmcs12->guest_interruptibility_info =
4664 		vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
4665 
4666 	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
4667 		vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
4668 	else if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4669 		vmcs12->guest_activity_state = GUEST_ACTIVITY_WAIT_SIPI;
4670 	else
4671 		vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
4672 
4673 	if (nested_cpu_has_preemption_timer(vmcs12) &&
4674 	    vmcs12->vm_exit_controls & VM_EXIT_SAVE_VMX_PREEMPTION_TIMER &&
4675 	    !vcpu->arch.nested_run_pending)
4676 		vmcs12->vmx_preemption_timer_value =
4677 			vmx_get_preemption_timer_value(vcpu);
4678 
4679 	/*
4680 	 * In some cases (usually, nested EPT), L2 is allowed to change its
4681 	 * own CR3 without exiting. If it has changed it, we must keep it.
4682 	 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
4683 	 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
4684 	 *
4685 	 * Additionally, restore L2's PDPTR to vmcs12.
4686 	 */
4687 	if (enable_ept) {
4688 		vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
4689 		if (nested_cpu_has_ept(vmcs12) && is_pae_paging(vcpu)) {
4690 			vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
4691 			vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
4692 			vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
4693 			vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
4694 		}
4695 	}
4696 
4697 	vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
4698 
4699 	if (nested_cpu_has_vid(vmcs12))
4700 		vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
4701 
4702 	vmcs12->vm_entry_controls =
4703 		(vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
4704 		(vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
4705 
4706 	/*
4707 	 * Note!  Save DR7, but intentionally don't grab DEBUGCTL from vmcs02.
4708 	 * Writes to DEBUGCTL that aren't intercepted by L1 are immediately
4709 	 * propagated to vmcs12 (see vmx_set_msr()), as the value loaded into
4710 	 * vmcs02 doesn't strictly track vmcs12.
4711 	 */
4712 	if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS)
4713 		vmcs12->guest_dr7 = vcpu->arch.dr7;
4714 
4715 	if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
4716 		vmcs12->guest_ia32_efer = vcpu->arch.efer;
4717 
4718 	vmcs_read_cet_state(&vmx->vcpu, &vmcs12->guest_s_cet,
4719 			    &vmcs12->guest_ssp,
4720 			    &vmcs12->guest_ssp_tbl);
4721 }
4722 
4723 /*
4724  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
4725  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
4726  * and this function updates it to reflect the changes to the guest state while
4727  * L2 was running (and perhaps made some exits which were handled directly by L0
4728  * without going back to L1), and to reflect the exit reason.
4729  * Note that we do not have to copy here all VMCS fields, just those that
4730  * could have changed by the L2 guest or the exit - i.e., the guest-state and
4731  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
4732  * which already writes to vmcs12 directly.
4733  */
4734 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
4735 			   u32 vm_exit_reason, u32 exit_intr_info,
4736 			   unsigned long exit_qualification, u32 exit_insn_len)
4737 {
4738 	/* update exit information fields: */
4739 	vmcs12->vm_exit_reason = vm_exit_reason;
4740 	if (vmx_get_exit_reason(vcpu).enclave_mode)
4741 		vmcs12->vm_exit_reason |= VMX_EXIT_REASONS_SGX_ENCLAVE_MODE;
4742 	vmcs12->exit_qualification = exit_qualification;
4743 
4744 	/*
4745 	 * On VM-Exit due to a failed VM-Entry, the VMCS isn't marked launched
4746 	 * and only EXIT_REASON and EXIT_QUALIFICATION are updated, all other
4747 	 * exit info fields are unmodified.
4748 	 */
4749 	if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
4750 		vmcs12->launch_state = 1;
4751 
4752 		/* vm_entry_intr_info_field is cleared on exit. Emulate this
4753 		 * instead of reading the real value. */
4754 		vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
4755 
4756 		/*
4757 		 * Transfer the event that L0 or L1 may wanted to inject into
4758 		 * L2 to IDT_VECTORING_INFO_FIELD.
4759 		 */
4760 		vmcs12_save_pending_event(vcpu, vmcs12,
4761 					  vm_exit_reason, exit_intr_info);
4762 
4763 		vmcs12->vm_exit_intr_info = exit_intr_info;
4764 		vmcs12->vm_exit_instruction_len = exit_insn_len;
4765 		vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4766 
4767 		/*
4768 		 * According to spec, there's no need to store the guest's
4769 		 * MSRs if the exit is due to a VM-entry failure that occurs
4770 		 * during or after loading the guest state. Since this exit
4771 		 * does not fall in that category, we need to save the MSRs.
4772 		 */
4773 		if (nested_vmx_store_msr(vcpu,
4774 					 vmcs12->vm_exit_msr_store_addr,
4775 					 vmcs12->vm_exit_msr_store_count))
4776 			nested_vmx_abort(vcpu,
4777 					 VMX_ABORT_SAVE_GUEST_MSR_FAIL);
4778 	}
4779 }
4780 
4781 /*
4782  * A part of what we need to when the nested L2 guest exits and we want to
4783  * run its L1 parent, is to reset L1's guest state to the host state specified
4784  * in vmcs12.
4785  * This function is to be called not only on normal nested exit, but also on
4786  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
4787  * Failures During or After Loading Guest State").
4788  * This function should be called when the active VMCS is L1's (vmcs01).
4789  */
4790 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
4791 				   struct vmcs12 *vmcs12)
4792 {
4793 	enum vm_entry_failure_code ignored;
4794 	struct kvm_segment seg;
4795 
4796 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
4797 		vcpu->arch.efer = vmcs12->host_ia32_efer;
4798 	else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4799 		vcpu->arch.efer |= (EFER_LMA | EFER_LME);
4800 	else
4801 		vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
4802 	vmx_set_efer(vcpu, vcpu->arch.efer);
4803 
4804 	kvm_rsp_write(vcpu, vmcs12->host_rsp);
4805 	kvm_rip_write(vcpu, vmcs12->host_rip);
4806 	vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
4807 	vmx_set_interrupt_shadow(vcpu, 0);
4808 
4809 	/*
4810 	 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
4811 	 * actually changed, because vmx_set_cr0 refers to efer set above.
4812 	 *
4813 	 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
4814 	 * (KVM doesn't change it);
4815 	 */
4816 	vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
4817 	vmx_set_cr0(vcpu, vmcs12->host_cr0);
4818 
4819 	/* Same as above - no reason to call set_cr4_guest_host_mask().  */
4820 	vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4821 	vmx_set_cr4(vcpu, vmcs12->host_cr4);
4822 
4823 	nested_ept_uninit_mmu_context(vcpu);
4824 
4825 	/*
4826 	 * Only PDPTE load can fail as the value of cr3 was checked on entry and
4827 	 * couldn't have changed.
4828 	 */
4829 	if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, true, &ignored))
4830 		nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
4831 
4832 	nested_vmx_transition_tlb_flush(vcpu, vmcs12, false);
4833 
4834 	vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
4835 	vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
4836 	vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
4837 	vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
4838 	vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
4839 	vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
4840 	vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
4841 
4842 	/* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
4843 	if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
4844 		vmcs_write64(GUEST_BNDCFGS, 0);
4845 
4846 	/*
4847 	 * Load CET state from host state if VM_EXIT_LOAD_CET_STATE is set.
4848 	 * otherwise CET state should be retained across VM-exit, i.e.,
4849 	 * guest values should be propagated from vmcs12 to vmcs01.
4850 	 */
4851 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_CET_STATE)
4852 		vmcs_write_cet_state(vcpu, vmcs12->host_s_cet, vmcs12->host_ssp,
4853 				     vmcs12->host_ssp_tbl);
4854 	else
4855 		vmcs_write_cet_state(vcpu, vmcs12->guest_s_cet, vmcs12->guest_ssp,
4856 				     vmcs12->guest_ssp_tbl);
4857 
4858 	if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
4859 		vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
4860 		vcpu->arch.pat = vmcs12->host_ia32_pat;
4861 	}
4862 	if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) &&
4863 	    kvm_pmu_has_perf_global_ctrl(vcpu_to_pmu(vcpu)))
4864 		WARN_ON_ONCE(__kvm_emulate_msr_write(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
4865 						     vmcs12->host_ia32_perf_global_ctrl));
4866 
4867 	/* Set L1 segment info according to Intel SDM
4868 	    27.5.2 Loading Host Segment and Descriptor-Table Registers */
4869 	seg = (struct kvm_segment) {
4870 		.base = 0,
4871 		.limit = 0xFFFFFFFF,
4872 		.selector = vmcs12->host_cs_selector,
4873 		.type = 11,
4874 		.present = 1,
4875 		.s = 1,
4876 		.g = 1
4877 	};
4878 	if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4879 		seg.l = 1;
4880 	else
4881 		seg.db = 1;
4882 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
4883 	seg = (struct kvm_segment) {
4884 		.base = 0,
4885 		.limit = 0xFFFFFFFF,
4886 		.type = 3,
4887 		.present = 1,
4888 		.s = 1,
4889 		.db = 1,
4890 		.g = 1
4891 	};
4892 	seg.selector = vmcs12->host_ds_selector;
4893 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
4894 	seg.selector = vmcs12->host_es_selector;
4895 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
4896 	seg.selector = vmcs12->host_ss_selector;
4897 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
4898 	seg.selector = vmcs12->host_fs_selector;
4899 	seg.base = vmcs12->host_fs_base;
4900 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
4901 	seg.selector = vmcs12->host_gs_selector;
4902 	seg.base = vmcs12->host_gs_base;
4903 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
4904 	seg = (struct kvm_segment) {
4905 		.base = vmcs12->host_tr_base,
4906 		.limit = 0x67,
4907 		.selector = vmcs12->host_tr_selector,
4908 		.type = 11,
4909 		.present = 1
4910 	};
4911 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
4912 
4913 	memset(&seg, 0, sizeof(seg));
4914 	seg.unusable = 1;
4915 	__vmx_set_segment(vcpu, &seg, VCPU_SREG_LDTR);
4916 
4917 	kvm_set_dr(vcpu, 7, 0x400);
4918 	vmx_guest_debugctl_write(vcpu, 0);
4919 
4920 	if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
4921 				vmcs12->vm_exit_msr_load_count))
4922 		nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
4923 
4924 	to_vt(vcpu)->emulation_required = vmx_emulation_required(vcpu);
4925 }
4926 
4927 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
4928 {
4929 	struct vmx_uret_msr *efer_msr;
4930 	unsigned int i;
4931 
4932 	if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
4933 		return vmcs_read64(GUEST_IA32_EFER);
4934 
4935 	if (cpu_has_load_ia32_efer())
4936 		return kvm_host.efer;
4937 
4938 	for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
4939 		if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
4940 			return vmx->msr_autoload.guest.val[i].value;
4941 	}
4942 
4943 	efer_msr = vmx_find_uret_msr(vmx, MSR_EFER);
4944 	if (efer_msr)
4945 		return efer_msr->data;
4946 
4947 	return kvm_host.efer;
4948 }
4949 
4950 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
4951 {
4952 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4953 	struct vcpu_vmx *vmx = to_vmx(vcpu);
4954 	struct vmx_msr_entry g, h;
4955 	gpa_t gpa;
4956 	u32 i, j;
4957 
4958 	vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
4959 
4960 	if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
4961 		/*
4962 		 * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
4963 		 * as vmcs01.GUEST_DR7 contains a userspace defined value
4964 		 * and vcpu->arch.dr7 is not squirreled away before the
4965 		 * nested VMENTER (not worth adding a variable in nested_vmx).
4966 		 */
4967 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
4968 			kvm_set_dr(vcpu, 7, DR7_FIXED_1);
4969 		else
4970 			WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
4971 	}
4972 
4973 	/* Reload DEBUGCTL to ensure vmcs01 has a fresh FREEZE_IN_SMM value. */
4974 	vmx_reload_guest_debugctl(vcpu);
4975 
4976 	/*
4977 	 * Note that calling vmx_set_{efer,cr0,cr4} is important as they
4978 	 * handle a variety of side effects to KVM's software model.
4979 	 */
4980 	vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
4981 
4982 	vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
4983 	vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
4984 
4985 	vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4986 	vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
4987 
4988 	nested_ept_uninit_mmu_context(vcpu);
4989 	vcpu->arch.cr3 = vmx->nested.pre_vmenter_cr3;
4990 	kvm_register_mark_available(vcpu, VCPU_REG_CR3);
4991 
4992 	/*
4993 	 * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
4994 	 * from vmcs01 (if necessary).  The PDPTRs are not loaded on
4995 	 * VMFail, like everything else we just need to ensure our
4996 	 * software model is up-to-date.
4997 	 */
4998 	if (enable_ept && is_pae_paging(vcpu))
4999 		ept_save_pdptrs(vcpu);
5000 
5001 	kvm_mmu_reset_context(vcpu);
5002 
5003 	/*
5004 	 * This nasty bit of open coding is a compromise between blindly
5005 	 * loading L1's MSRs using the exit load lists (incorrect emulation
5006 	 * of VMFail), leaving the nested VM's MSRs in the software model
5007 	 * (incorrect behavior) and snapshotting the modified MSRs (too
5008 	 * expensive since the lists are unbound by hardware).  For each
5009 	 * MSR that was (prematurely) loaded from the nested VMEntry load
5010 	 * list, reload it from the exit load list if it exists and differs
5011 	 * from the guest value.  The intent is to stuff host state as
5012 	 * silently as possible, not to fully process the exit load list.
5013 	 */
5014 	for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
5015 		gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
5016 		if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
5017 			pr_debug_ratelimited(
5018 				"%s read MSR index failed (%u, 0x%08llx)\n",
5019 				__func__, i, gpa);
5020 			goto vmabort;
5021 		}
5022 
5023 		for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
5024 			gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
5025 			if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
5026 				pr_debug_ratelimited(
5027 					"%s read MSR failed (%u, 0x%08llx)\n",
5028 					__func__, j, gpa);
5029 				goto vmabort;
5030 			}
5031 			if (h.index != g.index)
5032 				continue;
5033 			if (h.value == g.value)
5034 				break;
5035 
5036 			if (nested_vmx_load_msr_check(vcpu, &h)) {
5037 				pr_debug_ratelimited(
5038 					"%s check failed (%u, 0x%x, 0x%x)\n",
5039 					__func__, j, h.index, h.reserved);
5040 				goto vmabort;
5041 			}
5042 
5043 			if (kvm_emulate_msr_write(vcpu, h.index, h.value)) {
5044 				pr_debug_ratelimited(
5045 					"%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
5046 					__func__, j, h.index, h.value);
5047 				goto vmabort;
5048 			}
5049 		}
5050 	}
5051 
5052 	return;
5053 
5054 vmabort:
5055 	nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
5056 }
5057 
5058 /*
5059  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
5060  * and modify vmcs12 to make it see what it would expect to see there if
5061  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
5062  */
5063 void __nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
5064 			 u32 exit_intr_info, unsigned long exit_qualification,
5065 			 u32 exit_insn_len)
5066 {
5067 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5068 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5069 
5070 	/* Pending MTF traps are discarded on VM-Exit. */
5071 	vmx->nested.mtf_pending = false;
5072 
5073 	/* trying to cancel vmlaunch/vmresume is a bug */
5074 	kvm_warn_on_nested_run_pending(vcpu);
5075 
5076 #ifdef CONFIG_KVM_HYPERV
5077 	if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
5078 		/*
5079 		 * KVM_REQ_GET_NESTED_STATE_PAGES is also used to map
5080 		 * Enlightened VMCS after migration and we still need to
5081 		 * do that when something is forcing L2->L1 exit prior to
5082 		 * the first L2 run.
5083 		 */
5084 		(void)nested_get_evmcs_page(vcpu);
5085 	}
5086 #endif
5087 
5088 	/* Service pending TLB flush requests for L2 before switching to L1. */
5089 	kvm_service_local_tlb_flush_requests(vcpu);
5090 
5091 	/*
5092 	 * VCPU_REG_PDPTR will be clobbered in arch/x86/kvm/vmx/vmx.h between
5093 	 * now and the new vmentry.  Ensure that the VMCS02 PDPTR fields are
5094 	 * up-to-date before switching to L1.
5095 	 */
5096 	if (enable_ept && is_pae_paging(vcpu))
5097 		vmx_ept_load_pdptrs(vcpu);
5098 
5099 	leave_guest_mode(vcpu);
5100 
5101 	if (nested_cpu_has_preemption_timer(vmcs12))
5102 		hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
5103 
5104 	if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING)) {
5105 		vcpu->arch.tsc_offset = vcpu->arch.l1_tsc_offset;
5106 		if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
5107 			vcpu->arch.tsc_scaling_ratio = vcpu->arch.l1_tsc_scaling_ratio;
5108 	}
5109 
5110 	if (likely(!vmx->fail)) {
5111 		sync_vmcs02_to_vmcs12(vcpu, vmcs12);
5112 
5113 		if (vm_exit_reason != -1)
5114 			prepare_vmcs12(vcpu, vmcs12, vm_exit_reason,
5115 				       exit_intr_info, exit_qualification,
5116 				       exit_insn_len);
5117 
5118 		/*
5119 		 * Must happen outside of sync_vmcs02_to_vmcs12() as it will
5120 		 * also be used to capture vmcs12 cache as part of
5121 		 * capturing nVMX state for snapshot (migration).
5122 		 *
5123 		 * Otherwise, this flush will dirty guest memory at a
5124 		 * point it is already assumed by user-space to be
5125 		 * immutable.
5126 		 */
5127 		nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
5128 	} else {
5129 		/*
5130 		 * The only expected VM-instruction error is "VM entry with
5131 		 * invalid control field(s)." Anything else indicates a
5132 		 * problem with L0.
5133 		 */
5134 		WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
5135 			     VMXERR_ENTRY_INVALID_CONTROL_FIELD);
5136 
5137 		/* VM-Fail at VM-Entry means KVM missed a consistency check. */
5138 		WARN_ON_ONCE(warn_on_missed_cc);
5139 	}
5140 
5141 	/*
5142 	 * Drop events/exceptions that were queued for re-injection to L2
5143 	 * (picked up via vmx_complete_interrupts()), as well as exceptions
5144 	 * that were pending for L2.  Note, this must NOT be hoisted above
5145 	 * prepare_vmcs12(), events/exceptions queued for re-injection need to
5146 	 * be captured in vmcs12 (see vmcs12_save_pending_event()).
5147 	 */
5148 	vcpu->arch.nmi_injected = false;
5149 	kvm_clear_exception_queue(vcpu);
5150 	kvm_clear_interrupt_queue(vcpu);
5151 
5152 	vmx_switch_vmcs(vcpu, &vmx->vmcs01);
5153 
5154 	kvm_nested_vmexit_handle_ibrs(vcpu);
5155 
5156 	/*
5157 	 * Update any VMCS fields that might have changed while vmcs02 was the
5158 	 * active VMCS.  The tracking is per-vCPU, not per-VMCS.
5159 	 */
5160 	vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vmx->msr_autostore.nr);
5161 	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
5162 	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
5163 	vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
5164 	if (kvm_caps.has_tsc_control)
5165 		vmcs_write64(TSC_MULTIPLIER, vcpu->arch.tsc_scaling_ratio);
5166 
5167 	nested_put_vmcs12_pages(vcpu);
5168 
5169 	if ((vm_exit_reason != -1) &&
5170 	    (enable_shadow_vmcs || nested_vmx_is_evmptr12_valid(vmx)))
5171 		vmx->nested.need_vmcs12_to_shadow_sync = true;
5172 
5173 	/* in case we halted in L2 */
5174 	kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
5175 
5176 	if (likely(!vmx->fail)) {
5177 		if (vm_exit_reason != -1)
5178 			trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
5179 						       vmcs12->exit_qualification,
5180 						       vmcs12->idt_vectoring_info_field,
5181 						       vmcs12->vm_exit_intr_info,
5182 						       vmcs12->vm_exit_intr_error_code,
5183 						       KVM_ISA_VMX);
5184 
5185 		load_vmcs12_host_state(vcpu, vmcs12);
5186 
5187 		/*
5188 		 * Process events if an injectable IRQ or NMI is pending, even
5189 		 * if the event is blocked (RFLAGS.IF is cleared on VM-Exit).
5190 		 * If an event became pending while L2 was active, KVM needs to
5191 		 * either inject the event or request an IRQ/NMI window.  SMIs
5192 		 * don't need to be processed as SMM is mutually exclusive with
5193 		 * non-root mode.  INIT/SIPI don't need to be checked as INIT
5194 		 * is blocked post-VMXON, and SIPIs are ignored.
5195 		 */
5196 		if (kvm_cpu_has_injectable_intr(vcpu) || vcpu->arch.nmi_pending)
5197 			kvm_make_request(KVM_REQ_EVENT, vcpu);
5198 		return;
5199 	}
5200 
5201 	/*
5202 	 * After an early L2 VM-entry failure, we're now back
5203 	 * in L1 which thinks it just finished a VMLAUNCH or
5204 	 * VMRESUME instruction, so we need to set the failure
5205 	 * flag and the VM-instruction error field of the VMCS
5206 	 * accordingly, and skip the emulated instruction.
5207 	 */
5208 	(void)nested_vmx_fail(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
5209 
5210 	/*
5211 	 * Restore L1's host state to KVM's software model.  We're here
5212 	 * because a consistency check was caught by hardware, which
5213 	 * means some amount of guest state has been propagated to KVM's
5214 	 * model and needs to be unwound to the host's state.
5215 	 */
5216 	nested_vmx_restore_host_state(vcpu);
5217 
5218 	vmx->fail = 0;
5219 }
5220 
5221 static void nested_vmx_triple_fault(struct kvm_vcpu *vcpu)
5222 {
5223 	kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5224 	nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
5225 }
5226 
5227 /*
5228  * Decode the memory-address operand of a vmx instruction, as recorded on an
5229  * exit caused by such an instruction (run by a guest hypervisor).
5230  * On success, returns 0. When the operand is invalid, returns 1 and throws
5231  * #UD, #GP, or #SS.
5232  */
5233 int get_vmx_mem_address(struct kvm_vcpu *vcpu, unsigned long exit_qualification,
5234 			u32 vmx_instruction_info, bool wr, int len, gva_t *ret)
5235 {
5236 	gva_t off;
5237 	bool exn;
5238 	struct kvm_segment s;
5239 
5240 	/*
5241 	 * According to Vol. 3B, "Information for VM Exits Due to Instruction
5242 	 * Execution", on an exit, vmx_instruction_info holds most of the
5243 	 * addressing components of the operand. Only the displacement part
5244 	 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
5245 	 * For how an actual address is calculated from all these components,
5246 	 * refer to Vol. 1, "Operand Addressing".
5247 	 */
5248 	int  scaling = vmx_instruction_info & 3;
5249 	int  addr_size = (vmx_instruction_info >> 7) & 7;
5250 	bool is_reg = vmx_instruction_info & (1u << 10);
5251 	int  seg_reg = (vmx_instruction_info >> 15) & 7;
5252 	int  index_reg = (vmx_instruction_info >> 18) & 0xf;
5253 	bool index_is_valid = !(vmx_instruction_info & (1u << 22));
5254 	int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
5255 	bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
5256 
5257 	if (is_reg) {
5258 		kvm_queue_exception(vcpu, UD_VECTOR);
5259 		return 1;
5260 	}
5261 
5262 	/* Addr = segment_base + offset */
5263 	/* offset = base + [index * scale] + displacement */
5264 	off = exit_qualification; /* holds the displacement */
5265 	if (addr_size == 1)
5266 		off = (gva_t)sign_extend64(off, 31);
5267 	else if (addr_size == 0)
5268 		off = (gva_t)sign_extend64(off, 15);
5269 	if (base_is_valid)
5270 		off += kvm_register_read(vcpu, base_reg);
5271 	if (index_is_valid)
5272 		off += kvm_register_read(vcpu, index_reg) << scaling;
5273 	vmx_get_segment(vcpu, &s, seg_reg);
5274 
5275 	/*
5276 	 * The effective address, i.e. @off, of a memory operand is truncated
5277 	 * based on the address size of the instruction.  Note that this is
5278 	 * the *effective address*, i.e. the address prior to accounting for
5279 	 * the segment's base.
5280 	 */
5281 	if (addr_size == 1) /* 32 bit */
5282 		off &= 0xffffffff;
5283 	else if (addr_size == 0) /* 16 bit */
5284 		off &= 0xffff;
5285 
5286 	/* Checks for #GP/#SS exceptions. */
5287 	exn = false;
5288 	if (is_long_mode(vcpu)) {
5289 		/*
5290 		 * The virtual/linear address is never truncated in 64-bit
5291 		 * mode, e.g. a 32-bit address size can yield a 64-bit virtual
5292 		 * address when using FS/GS with a non-zero base.
5293 		 */
5294 		if (seg_reg == VCPU_SREG_FS || seg_reg == VCPU_SREG_GS)
5295 			*ret = s.base + off;
5296 		else
5297 			*ret = off;
5298 
5299 		*ret = vmx_get_untagged_addr(vcpu, *ret, 0);
5300 		/* Long mode: #GP(0)/#SS(0) if the memory address is in a
5301 		 * non-canonical form. This is the only check on the memory
5302 		 * destination for long mode!
5303 		 */
5304 		exn = is_noncanonical_address(*ret, vcpu, 0);
5305 	} else {
5306 		/*
5307 		 * When not in long mode, the virtual/linear address is
5308 		 * unconditionally truncated to 32 bits regardless of the
5309 		 * address size.
5310 		 */
5311 		*ret = (s.base + off) & 0xffffffff;
5312 
5313 		/* Protected mode: apply checks for segment validity in the
5314 		 * following order:
5315 		 * - segment type check (#GP(0) may be thrown)
5316 		 * - usability check (#GP(0)/#SS(0))
5317 		 * - limit check (#GP(0)/#SS(0))
5318 		 */
5319 		if (wr)
5320 			/* #GP(0) if the destination operand is located in a
5321 			 * read-only data segment or any code segment.
5322 			 */
5323 			exn = ((s.type & 0xa) == 0 || (s.type & 8));
5324 		else
5325 			/* #GP(0) if the source operand is located in an
5326 			 * execute-only code segment
5327 			 */
5328 			exn = ((s.type & 0xa) == 8);
5329 		if (exn) {
5330 			kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
5331 			return 1;
5332 		}
5333 		/* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
5334 		 */
5335 		exn = (s.unusable != 0);
5336 
5337 		/*
5338 		 * Protected mode: #GP(0)/#SS(0) if the memory operand is
5339 		 * outside the segment limit.  All CPUs that support VMX ignore
5340 		 * limit checks for flat segments, i.e. segments with base==0,
5341 		 * limit==0xffffffff and of type expand-up data or code.
5342 		 */
5343 		if (!(s.base == 0 && s.limit == 0xffffffff &&
5344 		     ((s.type & 8) || !(s.type & 4))))
5345 			exn = exn || ((u64)off + len - 1 > s.limit);
5346 	}
5347 	if (exn) {
5348 		kvm_queue_exception_e(vcpu,
5349 				      seg_reg == VCPU_SREG_SS ?
5350 						SS_VECTOR : GP_VECTOR,
5351 				      0);
5352 		return 1;
5353 	}
5354 
5355 	return 0;
5356 }
5357 
5358 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer,
5359 				int *ret)
5360 {
5361 	gva_t gva;
5362 	struct x86_exception e;
5363 	int r;
5364 
5365 	if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5366 				vmcs_read32(VMX_INSTRUCTION_INFO), false,
5367 				sizeof(*vmpointer), &gva)) {
5368 		*ret = 1;
5369 		return -EINVAL;
5370 	}
5371 
5372 	r = kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e);
5373 	if (r != X86EMUL_CONTINUE) {
5374 		*ret = kvm_handle_memory_failure(vcpu, r, &e);
5375 		return -EINVAL;
5376 	}
5377 
5378 	return 0;
5379 }
5380 
5381 /*
5382  * Allocate a shadow VMCS and associate it with the currently loaded
5383  * VMCS, unless such a shadow VMCS already exists. The newly allocated
5384  * VMCS is also VMCLEARed, so that it is ready for use.
5385  */
5386 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
5387 {
5388 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5389 	struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
5390 
5391 	/*
5392 	 * KVM allocates a shadow VMCS only when L1 executes VMXON and frees it
5393 	 * when L1 executes VMXOFF or the vCPU is forced out of nested
5394 	 * operation.  VMXON faults if the CPU is already post-VMXON, so it
5395 	 * should be impossible to already have an allocated shadow VMCS.  KVM
5396 	 * doesn't support virtualization of VMCS shadowing, so vmcs01 should
5397 	 * always be the loaded VMCS.
5398 	 */
5399 	if (WARN_ON(loaded_vmcs != &vmx->vmcs01 || loaded_vmcs->shadow_vmcs))
5400 		return loaded_vmcs->shadow_vmcs;
5401 
5402 	loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
5403 	if (loaded_vmcs->shadow_vmcs)
5404 		vmcs_clear(loaded_vmcs->shadow_vmcs);
5405 
5406 	return loaded_vmcs->shadow_vmcs;
5407 }
5408 
5409 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
5410 {
5411 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5412 	int r;
5413 
5414 	r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
5415 	if (r < 0)
5416 		goto out_vmcs02;
5417 
5418 	vmx->nested.cached_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
5419 	if (!vmx->nested.cached_vmcs12)
5420 		goto out_cached_vmcs12;
5421 
5422 	vmx->nested.shadow_vmcs12_cache.gpa = INVALID_GPA;
5423 	vmx->nested.cached_shadow_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
5424 	if (!vmx->nested.cached_shadow_vmcs12)
5425 		goto out_cached_shadow_vmcs12;
5426 
5427 	if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
5428 		goto out_shadow_vmcs;
5429 
5430 	hrtimer_setup(&vmx->nested.preemption_timer, vmx_preemption_timer_fn, CLOCK_MONOTONIC,
5431 		      HRTIMER_MODE_ABS_PINNED);
5432 
5433 	vmx->nested.vpid02 = allocate_vpid();
5434 
5435 	vmx->nested.vmcs02_initialized = false;
5436 	vmx->nested.vmxon = true;
5437 
5438 	if (vmx_pt_mode_is_host_guest()) {
5439 		vmx->pt_desc.guest.ctl = 0;
5440 		pt_update_intercept_for_msr(vcpu);
5441 	}
5442 
5443 	return 0;
5444 
5445 out_shadow_vmcs:
5446 	kfree(vmx->nested.cached_shadow_vmcs12);
5447 
5448 out_cached_shadow_vmcs12:
5449 	kfree(vmx->nested.cached_vmcs12);
5450 
5451 out_cached_vmcs12:
5452 	free_loaded_vmcs(&vmx->nested.vmcs02);
5453 
5454 out_vmcs02:
5455 	return -ENOMEM;
5456 }
5457 
5458 /* Emulate the VMXON instruction. */
5459 static int handle_vmxon(struct kvm_vcpu *vcpu)
5460 {
5461 	int ret;
5462 	gpa_t vmptr;
5463 	uint32_t revision;
5464 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5465 	const u64 VMXON_NEEDED_FEATURES = FEAT_CTL_LOCKED
5466 		| FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
5467 
5468 	/*
5469 	 * Manually check CR4.VMXE checks, KVM must force CR4.VMXE=1 to enter
5470 	 * the guest and so cannot rely on hardware to perform the check,
5471 	 * which has higher priority than VM-Exit (see Intel SDM's pseudocode
5472 	 * for VMXON).
5473 	 *
5474 	 * Rely on hardware for the other pre-VM-Exit checks, CR0.PE=1, !VM86
5475 	 * and !COMPATIBILITY modes.  For an unrestricted guest, KVM doesn't
5476 	 * force any of the relevant guest state.  For a restricted guest, KVM
5477 	 * does force CR0.PE=1, but only to also force VM86 in order to emulate
5478 	 * Real Mode, and so there's no need to check CR0.PE manually.
5479 	 */
5480 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_VMXE)) {
5481 		kvm_queue_exception(vcpu, UD_VECTOR);
5482 		return 1;
5483 	}
5484 
5485 	/*
5486 	 * The CPL is checked for "not in VMX operation" and for "in VMX root",
5487 	 * and has higher priority than the VM-Fail due to being post-VMXON,
5488 	 * i.e. VMXON #GPs outside of VMX non-root if CPL!=0.  In VMX non-root,
5489 	 * VMXON causes VM-Exit and KVM unconditionally forwards VMXON VM-Exits
5490 	 * from L2 to L1, i.e. there's no need to check for the vCPU being in
5491 	 * VMX non-root.
5492 	 *
5493 	 * Forwarding the VM-Exit unconditionally, i.e. without performing the
5494 	 * #UD checks (see above), is functionally ok because KVM doesn't allow
5495 	 * L1 to run L2 without CR4.VMXE=0, and because KVM never modifies L2's
5496 	 * CR0 or CR4, i.e. it's L2's responsibility to emulate #UDs that are
5497 	 * missed by hardware due to shadowing CR0 and/or CR4.
5498 	 */
5499 	if (vmx_get_cpl(vcpu)) {
5500 		kvm_inject_gp(vcpu, 0);
5501 		return 1;
5502 	}
5503 
5504 	if (vmx->nested.vmxon)
5505 		return nested_vmx_fail(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
5506 
5507 	/*
5508 	 * Invalid CR0/CR4 generates #GP.  These checks are performed if and
5509 	 * only if the vCPU isn't already in VMX operation, i.e. effectively
5510 	 * have lower priority than the VM-Fail above.
5511 	 */
5512 	if (!nested_host_cr0_valid(vcpu, kvm_read_cr0(vcpu)) ||
5513 	    !nested_host_cr4_valid(vcpu, kvm_read_cr4(vcpu))) {
5514 		kvm_inject_gp(vcpu, 0);
5515 		return 1;
5516 	}
5517 
5518 	if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
5519 			!= VMXON_NEEDED_FEATURES) {
5520 		kvm_inject_gp(vcpu, 0);
5521 		return 1;
5522 	}
5523 
5524 	if (nested_vmx_get_vmptr(vcpu, &vmptr, &ret))
5525 		return ret;
5526 
5527 	/*
5528 	 * SDM 3: 24.11.5
5529 	 * The first 4 bytes of VMXON region contain the supported
5530 	 * VMCS revision identifier
5531 	 *
5532 	 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
5533 	 * which replaces physical address width with 32
5534 	 */
5535 	if (!page_address_valid(vcpu, vmptr))
5536 		return nested_vmx_failInvalid(vcpu);
5537 
5538 	if (kvm_read_guest(vcpu->kvm, vmptr, &revision, sizeof(revision)) ||
5539 	    revision != VMCS12_REVISION)
5540 		return nested_vmx_failInvalid(vcpu);
5541 
5542 	vmx->nested.vmxon_ptr = vmptr;
5543 	ret = enter_vmx_operation(vcpu);
5544 	if (ret)
5545 		return ret;
5546 
5547 	return nested_vmx_succeed(vcpu);
5548 }
5549 
5550 static inline void nested_release_vmcs12(struct kvm_vcpu *vcpu)
5551 {
5552 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5553 
5554 	if (vmx->nested.current_vmptr == INVALID_GPA)
5555 		return;
5556 
5557 	copy_vmcs02_to_vmcs12_rare(vcpu, get_vmcs12(vcpu));
5558 
5559 	if (enable_shadow_vmcs) {
5560 		/* copy to memory all shadowed fields in case
5561 		   they were modified */
5562 		copy_shadow_to_vmcs12(vmx);
5563 		vmx_disable_shadow_vmcs(vmx);
5564 	}
5565 	vmx->nested.posted_intr_nv = -1;
5566 
5567 	/* Flush VMCS12 to guest memory */
5568 	kvm_vcpu_write_guest_page(vcpu,
5569 				  vmx->nested.current_vmptr >> PAGE_SHIFT,
5570 				  vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
5571 
5572 	kvm_mmu_free_roots(vcpu->kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5573 
5574 	vmx->nested.current_vmptr = INVALID_GPA;
5575 }
5576 
5577 /* Emulate the VMXOFF instruction */
5578 static int handle_vmxoff(struct kvm_vcpu *vcpu)
5579 {
5580 	if (!nested_vmx_check_permission(vcpu))
5581 		return 1;
5582 
5583 	free_nested(vcpu);
5584 
5585 	if (kvm_apic_has_pending_init_or_sipi(vcpu))
5586 		kvm_make_request(KVM_REQ_EVENT, vcpu);
5587 
5588 	return nested_vmx_succeed(vcpu);
5589 }
5590 
5591 /* Emulate the VMCLEAR instruction */
5592 static int handle_vmclear(struct kvm_vcpu *vcpu)
5593 {
5594 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5595 	u32 zero = 0;
5596 	gpa_t vmptr;
5597 	int r;
5598 
5599 	if (!nested_vmx_check_permission(vcpu))
5600 		return 1;
5601 
5602 	if (nested_vmx_get_vmptr(vcpu, &vmptr, &r))
5603 		return r;
5604 
5605 	if (!page_address_valid(vcpu, vmptr))
5606 		return nested_vmx_fail(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
5607 
5608 	if (vmptr == vmx->nested.vmxon_ptr)
5609 		return nested_vmx_fail(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
5610 
5611 	if (likely(!nested_evmcs_handle_vmclear(vcpu, vmptr))) {
5612 		if (vmptr == vmx->nested.current_vmptr)
5613 			nested_release_vmcs12(vcpu);
5614 
5615 		/*
5616 		 * Silently ignore memory errors on VMCLEAR, Intel's pseudocode
5617 		 * for VMCLEAR includes a "ensure that data for VMCS referenced
5618 		 * by the operand is in memory" clause that guards writes to
5619 		 * memory, i.e. doing nothing for I/O is architecturally valid.
5620 		 *
5621 		 * FIXME: Suppress failures if and only if no memslot is found,
5622 		 * i.e. exit to userspace if __copy_to_user() fails.
5623 		 */
5624 		(void)kvm_vcpu_write_guest(vcpu,
5625 					   vmptr + offsetof(struct vmcs12,
5626 							    launch_state),
5627 					   &zero, sizeof(zero));
5628 	}
5629 
5630 	return nested_vmx_succeed(vcpu);
5631 }
5632 
5633 /* Emulate the VMLAUNCH instruction */
5634 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
5635 {
5636 	return nested_vmx_run(vcpu, true);
5637 }
5638 
5639 /* Emulate the VMRESUME instruction */
5640 static int handle_vmresume(struct kvm_vcpu *vcpu)
5641 {
5642 
5643 	return nested_vmx_run(vcpu, false);
5644 }
5645 
5646 static int handle_vmread(struct kvm_vcpu *vcpu)
5647 {
5648 	struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
5649 						    : get_vmcs12(vcpu);
5650 	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5651 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5652 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5653 	struct x86_exception e;
5654 	unsigned long field;
5655 	u64 value;
5656 	gva_t gva = 0;
5657 	short offset;
5658 	int len, r;
5659 
5660 	if (!nested_vmx_check_permission(vcpu))
5661 		return 1;
5662 
5663 	/* Decode instruction info and find the field to read */
5664 	field = kvm_register_read(vcpu, (((instr_info) >> 28) & 0xf));
5665 
5666 	if (!nested_vmx_is_evmptr12_valid(vmx)) {
5667 		/*
5668 		 * In VMX non-root operation, when the VMCS-link pointer is INVALID_GPA,
5669 		 * any VMREAD sets the ALU flags for VMfailInvalid.
5670 		 */
5671 		if (vmx->nested.current_vmptr == INVALID_GPA ||
5672 		    (is_guest_mode(vcpu) &&
5673 		     get_vmcs12(vcpu)->vmcs_link_pointer == INVALID_GPA))
5674 			return nested_vmx_failInvalid(vcpu);
5675 
5676 		offset = get_vmcs12_field_offset(field);
5677 		if (offset < 0)
5678 			return nested_vmx_fail(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5679 
5680 		if (!is_guest_mode(vcpu) && is_vmcs12_ext_field(field))
5681 			copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
5682 
5683 		/* Read the field, zero-extended to a u64 value */
5684 		value = vmcs12_read_any(vmcs12, field, offset);
5685 	} else {
5686 		/*
5687 		 * Hyper-V TLFS (as of 6.0b) explicitly states, that while an
5688 		 * enlightened VMCS is active VMREAD/VMWRITE instructions are
5689 		 * unsupported. Unfortunately, certain versions of Windows 11
5690 		 * don't comply with this requirement which is not enforced in
5691 		 * genuine Hyper-V. Allow VMREAD from an enlightened VMCS as a
5692 		 * workaround, as misbehaving guests will panic on VM-Fail.
5693 		 * Note, enlightened VMCS is incompatible with shadow VMCS so
5694 		 * all VMREADs from L2 should go to L1.
5695 		 */
5696 		if (WARN_ON_ONCE(is_guest_mode(vcpu)))
5697 			return nested_vmx_failInvalid(vcpu);
5698 
5699 		offset = evmcs_field_offset(field, NULL);
5700 		if (offset < 0)
5701 			return nested_vmx_fail(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5702 
5703 		/* Read the field, zero-extended to a u64 value */
5704 		value = evmcs_read_any(nested_vmx_evmcs(vmx), field, offset);
5705 	}
5706 
5707 	/*
5708 	 * Now copy part of this value to register or memory, as requested.
5709 	 * Note that the number of bits actually copied is 32 or 64 depending
5710 	 * on the guest's mode (32 or 64 bit), not on the given field's length.
5711 	 */
5712 	if (instr_info & BIT(10)) {
5713 		kvm_register_write(vcpu, (((instr_info) >> 3) & 0xf), value);
5714 	} else {
5715 		len = is_64_bit_mode(vcpu) ? 8 : 4;
5716 		if (get_vmx_mem_address(vcpu, exit_qualification,
5717 					instr_info, true, len, &gva))
5718 			return 1;
5719 		/* _system ok, nested_vmx_check_permission has verified cpl=0 */
5720 		r = kvm_write_guest_virt_system(vcpu, gva, &value, len, &e);
5721 		if (r != X86EMUL_CONTINUE)
5722 			return kvm_handle_memory_failure(vcpu, r, &e);
5723 	}
5724 
5725 	return nested_vmx_succeed(vcpu);
5726 }
5727 
5728 static bool is_shadow_field_rw(unsigned long field)
5729 {
5730 	switch (field) {
5731 #define SHADOW_FIELD_RW(x, y) case x:
5732 #include "vmcs_shadow_fields.h"
5733 		return true;
5734 	default:
5735 		break;
5736 	}
5737 	return false;
5738 }
5739 
5740 static bool is_shadow_field_ro(unsigned long field)
5741 {
5742 	switch (field) {
5743 #define SHADOW_FIELD_RO(x, y) case x:
5744 #include "vmcs_shadow_fields.h"
5745 		return true;
5746 	default:
5747 		break;
5748 	}
5749 	return false;
5750 }
5751 
5752 static int handle_vmwrite(struct kvm_vcpu *vcpu)
5753 {
5754 	struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
5755 						    : get_vmcs12(vcpu);
5756 	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5757 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5758 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5759 	struct x86_exception e;
5760 	unsigned long field;
5761 	short offset;
5762 	gva_t gva;
5763 	int len, r;
5764 
5765 	/*
5766 	 * The value to write might be 32 or 64 bits, depending on L1's long
5767 	 * mode, and eventually we need to write that into a field of several
5768 	 * possible lengths. The code below first zero-extends the value to 64
5769 	 * bit (value), and then copies only the appropriate number of
5770 	 * bits into the vmcs12 field.
5771 	 */
5772 	u64 value = 0;
5773 
5774 	if (!nested_vmx_check_permission(vcpu))
5775 		return 1;
5776 
5777 	/*
5778 	 * In VMX non-root operation, when the VMCS-link pointer is INVALID_GPA,
5779 	 * any VMWRITE sets the ALU flags for VMfailInvalid.
5780 	 */
5781 	if (vmx->nested.current_vmptr == INVALID_GPA ||
5782 	    (is_guest_mode(vcpu) &&
5783 	     get_vmcs12(vcpu)->vmcs_link_pointer == INVALID_GPA))
5784 		return nested_vmx_failInvalid(vcpu);
5785 
5786 	if (instr_info & BIT(10))
5787 		value = kvm_register_read(vcpu, (((instr_info) >> 3) & 0xf));
5788 	else {
5789 		len = is_64_bit_mode(vcpu) ? 8 : 4;
5790 		if (get_vmx_mem_address(vcpu, exit_qualification,
5791 					instr_info, false, len, &gva))
5792 			return 1;
5793 		r = kvm_read_guest_virt(vcpu, gva, &value, len, &e);
5794 		if (r != X86EMUL_CONTINUE)
5795 			return kvm_handle_memory_failure(vcpu, r, &e);
5796 	}
5797 
5798 	field = kvm_register_read(vcpu, (((instr_info) >> 28) & 0xf));
5799 
5800 	offset = get_vmcs12_field_offset(field);
5801 	if (offset < 0)
5802 		return nested_vmx_fail(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5803 
5804 	/*
5805 	 * If the vCPU supports "VMWRITE to any supported field in the
5806 	 * VMCS," then the "read-only" fields are actually read/write.
5807 	 */
5808 	if (vmcs_field_readonly(field) &&
5809 	    !nested_cpu_has_vmwrite_any_field(vcpu))
5810 		return nested_vmx_fail(vcpu, VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
5811 
5812 	/*
5813 	 * Ensure vmcs12 is up-to-date before any VMWRITE that dirties
5814 	 * vmcs12, else we may crush a field or consume a stale value.
5815 	 */
5816 	if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field))
5817 		copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
5818 
5819 	/*
5820 	 * Some Intel CPUs intentionally drop the reserved bits of the AR byte
5821 	 * fields on VMWRITE.  Emulate this behavior to ensure consistent KVM
5822 	 * behavior regardless of the underlying hardware, e.g. if an AR_BYTE
5823 	 * field is intercepted for VMWRITE but not VMREAD (in L1), then VMREAD
5824 	 * from L1 will return a different value than VMREAD from L2 (L1 sees
5825 	 * the stripped down value, L2 sees the full value as stored by KVM).
5826 	 */
5827 	if (field >= GUEST_ES_AR_BYTES && field <= GUEST_TR_AR_BYTES)
5828 		value &= 0x1f0ff;
5829 
5830 	vmcs12_write_any(vmcs12, field, offset, value);
5831 
5832 	/*
5833 	 * Do not track vmcs12 dirty-state if in guest-mode as we actually
5834 	 * dirty shadow vmcs12 instead of vmcs12.  Fields that can be updated
5835 	 * by L1 without a vmexit are always updated in the vmcs02, i.e. don't
5836 	 * "dirty" vmcs12, all others go down the prepare_vmcs02() slow path.
5837 	 */
5838 	if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field)) {
5839 		/*
5840 		 * L1 can read these fields without exiting, ensure the
5841 		 * shadow VMCS is up-to-date.
5842 		 */
5843 		if (enable_shadow_vmcs && is_shadow_field_ro(field)) {
5844 			preempt_disable();
5845 			vmcs_load(vmx->vmcs01.shadow_vmcs);
5846 
5847 			__vmcs_writel(field, value);
5848 
5849 			vmcs_clear(vmx->vmcs01.shadow_vmcs);
5850 			vmcs_load(vmx->loaded_vmcs->vmcs);
5851 			preempt_enable();
5852 		}
5853 		vmx->nested.dirty_vmcs12 = true;
5854 	}
5855 
5856 	return nested_vmx_succeed(vcpu);
5857 }
5858 
5859 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
5860 {
5861 	vmx->nested.current_vmptr = vmptr;
5862 	if (enable_shadow_vmcs) {
5863 		secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_SHADOW_VMCS);
5864 		vmcs_write64(VMCS_LINK_POINTER,
5865 			     __pa(vmx->vmcs01.shadow_vmcs));
5866 		vmx->nested.need_vmcs12_to_shadow_sync = true;
5867 	}
5868 	vmx->nested.dirty_vmcs12 = true;
5869 	vmx->nested.force_msr_bitmap_recalc = true;
5870 }
5871 
5872 /* Emulate the VMPTRLD instruction */
5873 static int handle_vmptrld(struct kvm_vcpu *vcpu)
5874 {
5875 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5876 	gpa_t vmptr;
5877 	int r;
5878 
5879 	if (!nested_vmx_check_permission(vcpu))
5880 		return 1;
5881 
5882 	if (nested_vmx_get_vmptr(vcpu, &vmptr, &r))
5883 		return r;
5884 
5885 	if (!page_address_valid(vcpu, vmptr))
5886 		return nested_vmx_fail(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
5887 
5888 	if (vmptr == vmx->nested.vmxon_ptr)
5889 		return nested_vmx_fail(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
5890 
5891 	/* Forbid normal VMPTRLD if Enlightened version was used */
5892 	if (nested_vmx_is_evmptr12_valid(vmx))
5893 		return 1;
5894 
5895 	if (vmx->nested.current_vmptr != vmptr) {
5896 		struct gfn_to_hva_cache *ghc = &vmx->nested.vmcs12_cache;
5897 		struct vmcs_hdr hdr;
5898 
5899 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, vmptr, VMCS12_SIZE)) {
5900 			/*
5901 			 * Reads from an unbacked page return all 1s,
5902 			 * which means that the 32 bits located at the
5903 			 * given physical address won't match the required
5904 			 * VMCS12_REVISION identifier.
5905 			 */
5906 			return nested_vmx_fail(vcpu,
5907 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5908 		}
5909 
5910 		if (kvm_read_guest_offset_cached(vcpu->kvm, ghc, &hdr,
5911 						 offsetof(struct vmcs12, hdr),
5912 						 sizeof(hdr))) {
5913 			return nested_vmx_fail(vcpu,
5914 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5915 		}
5916 
5917 		if (hdr.revision_id != VMCS12_REVISION ||
5918 		    (hdr.shadow_vmcs &&
5919 		     !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
5920 			return nested_vmx_fail(vcpu,
5921 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5922 		}
5923 
5924 		nested_release_vmcs12(vcpu);
5925 
5926 		/*
5927 		 * Load VMCS12 from guest memory since it is not already
5928 		 * cached.
5929 		 */
5930 		if (kvm_read_guest_cached(vcpu->kvm, ghc, vmx->nested.cached_vmcs12,
5931 					  VMCS12_SIZE)) {
5932 			return nested_vmx_fail(vcpu,
5933 				VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5934 		}
5935 
5936 		set_current_vmptr(vmx, vmptr);
5937 	}
5938 
5939 	return nested_vmx_succeed(vcpu);
5940 }
5941 
5942 /* Emulate the VMPTRST instruction */
5943 static int handle_vmptrst(struct kvm_vcpu *vcpu)
5944 {
5945 	unsigned long exit_qual = vmx_get_exit_qual(vcpu);
5946 	u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5947 	gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
5948 	struct x86_exception e;
5949 	gva_t gva;
5950 	int r;
5951 
5952 	if (!nested_vmx_check_permission(vcpu))
5953 		return 1;
5954 
5955 	if (unlikely(nested_vmx_is_evmptr12_valid(to_vmx(vcpu))))
5956 		return 1;
5957 
5958 	if (get_vmx_mem_address(vcpu, exit_qual, instr_info,
5959 				true, sizeof(gpa_t), &gva))
5960 		return 1;
5961 	/* *_system ok, nested_vmx_check_permission has verified cpl=0 */
5962 	r = kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
5963 					sizeof(gpa_t), &e);
5964 	if (r != X86EMUL_CONTINUE)
5965 		return kvm_handle_memory_failure(vcpu, r, &e);
5966 
5967 	return nested_vmx_succeed(vcpu);
5968 }
5969 
5970 /* Emulate the INVEPT instruction */
5971 static int handle_invept(struct kvm_vcpu *vcpu)
5972 {
5973 	struct vcpu_vmx *vmx = to_vmx(vcpu);
5974 	u32 vmx_instruction_info, types;
5975 	unsigned long type, roots_to_free;
5976 	struct kvm_mmu *mmu;
5977 	gva_t gva;
5978 	struct x86_exception e;
5979 	struct {
5980 		u64 eptp, gpa;
5981 	} operand;
5982 	int i, r, gpr_index;
5983 
5984 	if (!(vmx->nested.msrs.secondary_ctls_high &
5985 	      SECONDARY_EXEC_ENABLE_EPT) ||
5986 	    !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
5987 		kvm_queue_exception(vcpu, UD_VECTOR);
5988 		return 1;
5989 	}
5990 
5991 	if (!nested_vmx_check_permission(vcpu))
5992 		return 1;
5993 
5994 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5995 	gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
5996 	type = kvm_register_read(vcpu, gpr_index);
5997 
5998 	types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
5999 
6000 	if (type >= 32 || !(types & (1 << type)))
6001 		return nested_vmx_fail(vcpu, VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6002 
6003 	/* According to the Intel VMX instruction reference, the memory
6004 	 * operand is read even if it isn't needed (e.g., for type==global)
6005 	 */
6006 	if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
6007 			vmx_instruction_info, false, sizeof(operand), &gva))
6008 		return 1;
6009 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
6010 	if (r != X86EMUL_CONTINUE)
6011 		return kvm_handle_memory_failure(vcpu, r, &e);
6012 
6013 	/*
6014 	 * Nested EPT roots are always held through guest_mmu,
6015 	 * not root_mmu.
6016 	 */
6017 	mmu = &vcpu->arch.guest_mmu;
6018 
6019 	switch (type) {
6020 	case VMX_EPT_EXTENT_CONTEXT:
6021 		if (!nested_vmx_check_eptp(vcpu, operand.eptp))
6022 			return nested_vmx_fail(vcpu,
6023 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6024 
6025 		roots_to_free = 0;
6026 		if (nested_ept_root_matches(mmu->root.hpa, mmu->root.pgd,
6027 					    operand.eptp))
6028 			roots_to_free |= KVM_MMU_ROOT_CURRENT;
6029 
6030 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
6031 			if (nested_ept_root_matches(mmu->prev_roots[i].hpa,
6032 						    mmu->prev_roots[i].pgd,
6033 						    operand.eptp))
6034 				roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
6035 		}
6036 		break;
6037 	case VMX_EPT_EXTENT_GLOBAL:
6038 		roots_to_free = KVM_MMU_ROOTS_ALL;
6039 		break;
6040 	default:
6041 		BUG();
6042 		break;
6043 	}
6044 
6045 	if (roots_to_free)
6046 		kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
6047 
6048 	return nested_vmx_succeed(vcpu);
6049 }
6050 
6051 static int handle_invvpid(struct kvm_vcpu *vcpu)
6052 {
6053 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6054 	u32 vmx_instruction_info;
6055 	unsigned long type, types;
6056 	gva_t gva;
6057 	struct x86_exception e;
6058 	struct {
6059 		u64 vpid;
6060 		u64 gla;
6061 	} operand;
6062 	u16 vpid02;
6063 	int r, gpr_index;
6064 
6065 	if (!(vmx->nested.msrs.secondary_ctls_high &
6066 	      SECONDARY_EXEC_ENABLE_VPID) ||
6067 			!(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
6068 		kvm_queue_exception(vcpu, UD_VECTOR);
6069 		return 1;
6070 	}
6071 
6072 	if (!nested_vmx_check_permission(vcpu))
6073 		return 1;
6074 
6075 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6076 	gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
6077 	type = kvm_register_read(vcpu, gpr_index);
6078 
6079 	types = (vmx->nested.msrs.vpid_caps &
6080 			VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
6081 
6082 	if (type >= 32 || !(types & (1 << type)))
6083 		return nested_vmx_fail(vcpu,
6084 			VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6085 
6086 	/* according to the intel vmx instruction reference, the memory
6087 	 * operand is read even if it isn't needed (e.g., for type==global)
6088 	 */
6089 	if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
6090 			vmx_instruction_info, false, sizeof(operand), &gva))
6091 		return 1;
6092 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
6093 	if (r != X86EMUL_CONTINUE)
6094 		return kvm_handle_memory_failure(vcpu, r, &e);
6095 
6096 	if (operand.vpid >> 16)
6097 		return nested_vmx_fail(vcpu,
6098 			VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6099 
6100 	/*
6101 	 * Always flush the effective vpid02, i.e. never flush the current VPID
6102 	 * and never explicitly flush vpid01.  INVVPID targets a VPID, not a
6103 	 * VMCS, and so whether or not the current vmcs12 has VPID enabled is
6104 	 * irrelevant (and there may not be a loaded vmcs12).
6105 	 */
6106 	vpid02 = nested_get_vpid02(vcpu);
6107 	switch (type) {
6108 	case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
6109 		/*
6110 		 * LAM doesn't apply to addresses that are inputs to TLB
6111 		 * invalidation.
6112 		 */
6113 		if (!operand.vpid ||
6114 		    is_noncanonical_invlpg_address(operand.gla, vcpu))
6115 			return nested_vmx_fail(vcpu,
6116 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6117 		vpid_sync_vcpu_addr(vpid02, operand.gla);
6118 		break;
6119 	case VMX_VPID_EXTENT_SINGLE_CONTEXT:
6120 	case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
6121 		if (!operand.vpid)
6122 			return nested_vmx_fail(vcpu,
6123 				VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6124 		vpid_sync_context(vpid02);
6125 		break;
6126 	case VMX_VPID_EXTENT_ALL_CONTEXT:
6127 		vpid_sync_context(vpid02);
6128 		break;
6129 	default:
6130 		WARN_ON_ONCE(1);
6131 		return kvm_skip_emulated_instruction(vcpu);
6132 	}
6133 
6134 	/*
6135 	 * Sync the shadow page tables if EPT is disabled, L1 is invalidating
6136 	 * linear mappings for L2 (tagged with L2's VPID).  Free all guest
6137 	 * roots as VPIDs are not tracked in the MMU role.
6138 	 *
6139 	 * Note, this operates on root_mmu, not guest_mmu, as L1 and L2 share
6140 	 * an MMU when EPT is disabled.
6141 	 *
6142 	 * TODO: sync only the affected SPTEs for INVDIVIDUAL_ADDR.
6143 	 */
6144 	if (!enable_ept)
6145 		kvm_mmu_free_guest_mode_roots(vcpu->kvm, &vcpu->arch.root_mmu);
6146 
6147 	return nested_vmx_succeed(vcpu);
6148 }
6149 
6150 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
6151 				     struct vmcs12 *vmcs12)
6152 {
6153 	u32 index = kvm_ecx_read(vcpu);
6154 	u64 new_eptp;
6155 
6156 	if (WARN_ON_ONCE(!nested_cpu_has_ept(vmcs12)))
6157 		return 1;
6158 	if (index >= VMFUNC_EPTP_ENTRIES)
6159 		return 1;
6160 
6161 	if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
6162 				     &new_eptp, index * 8, 8))
6163 		return 1;
6164 
6165 	/*
6166 	 * If the (L2) guest does a vmfunc to the currently
6167 	 * active ept pointer, we don't have to do anything else
6168 	 */
6169 	if (vmcs12->ept_pointer != new_eptp) {
6170 		if (!nested_vmx_check_eptp(vcpu, new_eptp))
6171 			return 1;
6172 
6173 		vmcs12->ept_pointer = new_eptp;
6174 		nested_ept_new_eptp(vcpu);
6175 
6176 		if (!nested_cpu_has_vpid(vmcs12))
6177 			kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
6178 	}
6179 
6180 	return 0;
6181 }
6182 
6183 static int handle_vmfunc(struct kvm_vcpu *vcpu)
6184 {
6185 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6186 	struct vmcs12 *vmcs12;
6187 	u32 function = kvm_eax_read(vcpu);
6188 
6189 	/*
6190 	 * VMFUNC should never execute cleanly while L1 is active; KVM supports
6191 	 * VMFUNC for nested VMs, but not for L1.
6192 	 */
6193 	if (WARN_ON_ONCE(!is_guest_mode(vcpu))) {
6194 		kvm_queue_exception(vcpu, UD_VECTOR);
6195 		return 1;
6196 	}
6197 
6198 	vmcs12 = get_vmcs12(vcpu);
6199 
6200 	/*
6201 	 * #UD on out-of-bounds function has priority over VM-Exit, and VMFUNC
6202 	 * is enabled in vmcs02 if and only if it's enabled in vmcs12.
6203 	 */
6204 	if (WARN_ON_ONCE((function > 63) || !nested_cpu_has_vmfunc(vmcs12))) {
6205 		kvm_queue_exception(vcpu, UD_VECTOR);
6206 		return 1;
6207 	}
6208 
6209 	if (!(vmcs12->vm_function_control & BIT_ULL(function)))
6210 		goto fail;
6211 
6212 	switch (function) {
6213 	case 0:
6214 		if (nested_vmx_eptp_switching(vcpu, vmcs12))
6215 			goto fail;
6216 		break;
6217 	default:
6218 		goto fail;
6219 	}
6220 	return kvm_skip_emulated_instruction(vcpu);
6221 
6222 fail:
6223 	/*
6224 	 * This is effectively a reflected VM-Exit, as opposed to a synthesized
6225 	 * nested VM-Exit.  Pass the original exit reason, i.e. don't hardcode
6226 	 * EXIT_REASON_VMFUNC as the exit reason.
6227 	 */
6228 	nested_vmx_vmexit(vcpu, vmx->vt.exit_reason.full,
6229 			  vmx_get_intr_info(vcpu),
6230 			  vmx_get_exit_qual(vcpu));
6231 	return 1;
6232 }
6233 
6234 /*
6235  * Return true if an IO instruction with the specified port and size should cause
6236  * a VM-exit into L1.
6237  */
6238 bool nested_vmx_check_io_bitmaps(struct kvm_vcpu *vcpu, unsigned int port,
6239 				 int size)
6240 {
6241 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6242 	gpa_t bitmap, last_bitmap;
6243 	u8 b;
6244 
6245 	last_bitmap = INVALID_GPA;
6246 	b = -1;
6247 
6248 	while (size > 0) {
6249 		if (port < 0x8000)
6250 			bitmap = vmcs12->io_bitmap_a;
6251 		else if (port < 0x10000)
6252 			bitmap = vmcs12->io_bitmap_b;
6253 		else
6254 			return true;
6255 		bitmap += (port & 0x7fff) / 8;
6256 
6257 		if (last_bitmap != bitmap)
6258 			if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
6259 				return true;
6260 		if (b & (1 << (port & 7)))
6261 			return true;
6262 
6263 		port++;
6264 		size--;
6265 		last_bitmap = bitmap;
6266 	}
6267 
6268 	return false;
6269 }
6270 
6271 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
6272 				       struct vmcs12 *vmcs12)
6273 {
6274 	unsigned long exit_qualification;
6275 	unsigned short port;
6276 	int size;
6277 
6278 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
6279 		return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
6280 
6281 	exit_qualification = vmx_get_exit_qual(vcpu);
6282 
6283 	port = exit_qualification >> 16;
6284 	size = (exit_qualification & 7) + 1;
6285 
6286 	return nested_vmx_check_io_bitmaps(vcpu, port, size);
6287 }
6288 
6289 /*
6290  * Return 1 if we should exit from L2 to L1 to handle an MSR access,
6291  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
6292  * disinterest in the current event (read or write a specific MSR) by using an
6293  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
6294  */
6295 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
6296 					struct vmcs12 *vmcs12,
6297 					union vmx_exit_reason exit_reason)
6298 {
6299 	u32 msr_index;
6300 	gpa_t bitmap;
6301 
6302 	if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
6303 		return true;
6304 
6305 	if (exit_reason.basic == EXIT_REASON_MSR_READ_IMM ||
6306 	    exit_reason.basic == EXIT_REASON_MSR_WRITE_IMM)
6307 		msr_index = vmx_get_exit_qual(vcpu);
6308 	else
6309 		msr_index = kvm_ecx_read(vcpu);
6310 
6311 	/*
6312 	 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
6313 	 * for the four combinations of read/write and low/high MSR numbers.
6314 	 * First we need to figure out which of the four to use:
6315 	 */
6316 	bitmap = vmcs12->msr_bitmap;
6317 	if (exit_reason.basic == EXIT_REASON_MSR_WRITE ||
6318 	    exit_reason.basic == EXIT_REASON_MSR_WRITE_IMM)
6319 		bitmap += 2048;
6320 	if (msr_index >= 0xc0000000) {
6321 		msr_index -= 0xc0000000;
6322 		bitmap += 1024;
6323 	}
6324 
6325 	/* Then read the msr_index'th bit from this bitmap: */
6326 	if (msr_index < 1024*8) {
6327 		unsigned char b;
6328 		if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
6329 			return true;
6330 		return 1 & (b >> (msr_index & 7));
6331 	} else
6332 		return true; /* let L1 handle the wrong parameter */
6333 }
6334 
6335 /*
6336  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
6337  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
6338  * intercept (via guest_host_mask etc.) the current event.
6339  */
6340 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
6341 	struct vmcs12 *vmcs12)
6342 {
6343 	unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
6344 	int cr = exit_qualification & 15;
6345 	int reg;
6346 	unsigned long val;
6347 
6348 	switch ((exit_qualification >> 4) & 3) {
6349 	case 0: /* mov to cr */
6350 		reg = (exit_qualification >> 8) & 15;
6351 		val = kvm_register_read(vcpu, reg);
6352 		switch (cr) {
6353 		case 0:
6354 			if (vmcs12->cr0_guest_host_mask &
6355 			    (val ^ vmcs12->cr0_read_shadow))
6356 				return true;
6357 			break;
6358 		case 3:
6359 			if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
6360 				return true;
6361 			break;
6362 		case 4:
6363 			if (vmcs12->cr4_guest_host_mask &
6364 			    (vmcs12->cr4_read_shadow ^ val))
6365 				return true;
6366 			break;
6367 		case 8:
6368 			if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
6369 				return true;
6370 			break;
6371 		}
6372 		break;
6373 	case 2: /* clts */
6374 		if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
6375 		    (vmcs12->cr0_read_shadow & X86_CR0_TS))
6376 			return true;
6377 		break;
6378 	case 1: /* mov from cr */
6379 		switch (cr) {
6380 		case 3:
6381 			if (vmcs12->cpu_based_vm_exec_control &
6382 			    CPU_BASED_CR3_STORE_EXITING)
6383 				return true;
6384 			break;
6385 		case 8:
6386 			if (vmcs12->cpu_based_vm_exec_control &
6387 			    CPU_BASED_CR8_STORE_EXITING)
6388 				return true;
6389 			break;
6390 		}
6391 		break;
6392 	case 3: /* lmsw */
6393 		/*
6394 		 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
6395 		 * cr0. Other attempted changes are ignored, with no exit.
6396 		 */
6397 		val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6398 		if (vmcs12->cr0_guest_host_mask & 0xe &
6399 		    (val ^ vmcs12->cr0_read_shadow))
6400 			return true;
6401 		if ((vmcs12->cr0_guest_host_mask & 0x1) &&
6402 		    !(vmcs12->cr0_read_shadow & 0x1) &&
6403 		    (val & 0x1))
6404 			return true;
6405 		break;
6406 	}
6407 	return false;
6408 }
6409 
6410 static bool nested_vmx_exit_handled_encls(struct kvm_vcpu *vcpu,
6411 					  struct vmcs12 *vmcs12)
6412 {
6413 	u32 encls_leaf;
6414 
6415 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SGX) ||
6416 	    !nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENCLS_EXITING))
6417 		return false;
6418 
6419 	encls_leaf = kvm_eax_read(vcpu);
6420 	if (encls_leaf > 62)
6421 		encls_leaf = 63;
6422 	return vmcs12->encls_exiting_bitmap & BIT_ULL(encls_leaf);
6423 }
6424 
6425 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
6426 	struct vmcs12 *vmcs12, gpa_t bitmap)
6427 {
6428 	u32 vmx_instruction_info;
6429 	unsigned long field;
6430 	u8 b;
6431 
6432 	if (!nested_cpu_has_shadow_vmcs(vmcs12))
6433 		return true;
6434 
6435 	/* Decode instruction info and find the field to access */
6436 	vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6437 	field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
6438 
6439 	/* Out-of-range fields always cause a VM exit from L2 to L1 */
6440 	if (field >> 15)
6441 		return true;
6442 
6443 	if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
6444 		return true;
6445 
6446 	return 1 & (b >> (field & 7));
6447 }
6448 
6449 static bool nested_vmx_exit_handled_mtf(struct vmcs12 *vmcs12)
6450 {
6451 	u32 entry_intr_info = vmcs12->vm_entry_intr_info_field;
6452 
6453 	if (nested_cpu_has_mtf(vmcs12))
6454 		return true;
6455 
6456 	/*
6457 	 * An MTF VM-exit may be injected into the guest by setting the
6458 	 * interruption-type to 7 (other event) and the vector field to 0. Such
6459 	 * is the case regardless of the 'monitor trap flag' VM-execution
6460 	 * control.
6461 	 */
6462 	return entry_intr_info == (INTR_INFO_VALID_MASK
6463 				   | INTR_TYPE_OTHER_EVENT);
6464 }
6465 
6466 /*
6467  * Return true if L0 wants to handle an exit from L2 regardless of whether or not
6468  * L1 wants the exit.  Only call this when in is_guest_mode (L2).
6469  */
6470 static bool nested_vmx_l0_wants_exit(struct kvm_vcpu *vcpu,
6471 				     union vmx_exit_reason exit_reason)
6472 {
6473 	u32 intr_info;
6474 
6475 	switch ((u16)exit_reason.basic) {
6476 	case EXIT_REASON_EXCEPTION_NMI:
6477 		intr_info = vmx_get_intr_info(vcpu);
6478 		if (is_nmi(intr_info))
6479 			return true;
6480 		else if (is_page_fault(intr_info))
6481 			return vcpu->arch.apf.host_apf_flags ||
6482 			       vmx_need_pf_intercept(vcpu);
6483 		else if (is_debug(intr_info) &&
6484 			 vcpu->guest_debug &
6485 			 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6486 			return true;
6487 		else if (is_breakpoint(intr_info) &&
6488 			 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6489 			return true;
6490 		else if (is_alignment_check(intr_info) &&
6491 			 !vmx_guest_inject_ac(vcpu))
6492 			return true;
6493 		else if (is_ve_fault(intr_info))
6494 			return true;
6495 		return false;
6496 	case EXIT_REASON_EXTERNAL_INTERRUPT:
6497 		return true;
6498 	case EXIT_REASON_MCE_DURING_VMENTRY:
6499 		return true;
6500 	case EXIT_REASON_EPT_VIOLATION:
6501 		/*
6502 		 * L0 always deals with the EPT violation. If nested EPT is
6503 		 * used, and the nested mmu code discovers that the address is
6504 		 * missing in the guest EPT table (EPT12), the EPT violation
6505 		 * will be injected with nested_ept_inject_page_fault()
6506 		 */
6507 		return true;
6508 	case EXIT_REASON_EPT_MISCONFIG:
6509 		/*
6510 		 * L2 never uses directly L1's EPT, but rather L0's own EPT
6511 		 * table (shadow on EPT) or a merged EPT table that L0 built
6512 		 * (EPT on EPT). So any problems with the structure of the
6513 		 * table is L0's fault.
6514 		 */
6515 		return true;
6516 	case EXIT_REASON_PREEMPTION_TIMER:
6517 		return true;
6518 	case EXIT_REASON_PML_FULL:
6519 		/*
6520 		 * PML is emulated for an L1 VMM and should never be enabled in
6521 		 * vmcs02, always "handle" PML_FULL by exiting to userspace.
6522 		 */
6523 		return true;
6524 	case EXIT_REASON_VMFUNC:
6525 		/* VM functions are emulated through L2->L0 vmexits. */
6526 		return true;
6527 	case EXIT_REASON_BUS_LOCK:
6528 		/*
6529 		 * At present, bus lock VM exit is never exposed to L1.
6530 		 * Handle L2's bus locks in L0 directly.
6531 		 */
6532 		return true;
6533 #ifdef CONFIG_KVM_HYPERV
6534 	case EXIT_REASON_VMCALL:
6535 		/* Hyper-V L2 TLB flush hypercall is handled by L0 */
6536 		return guest_hv_cpuid_has_l2_tlb_flush(vcpu) &&
6537 			nested_evmcs_l2_tlb_flush_enabled(vcpu) &&
6538 			kvm_hv_is_tlb_flush_hcall(vcpu);
6539 #endif
6540 	case EXIT_REASON_CPUID:
6541 		return !kvm_is_cpuid_allowed(vcpu);
6542 	default:
6543 		break;
6544 	}
6545 	return false;
6546 }
6547 
6548 /*
6549  * Return 1 if L1 wants to intercept an exit from L2.  Only call this when in
6550  * is_guest_mode (L2).
6551  */
6552 static bool nested_vmx_l1_wants_exit(struct kvm_vcpu *vcpu,
6553 				     union vmx_exit_reason exit_reason)
6554 {
6555 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6556 	u32 intr_info;
6557 
6558 	switch ((u16)exit_reason.basic) {
6559 	case EXIT_REASON_EXCEPTION_NMI:
6560 		intr_info = vmx_get_intr_info(vcpu);
6561 		if (is_nmi(intr_info))
6562 			return true;
6563 		else if (is_page_fault(intr_info))
6564 			return true;
6565 		return vmcs12->exception_bitmap &
6566 				(1u << (intr_info & INTR_INFO_VECTOR_MASK));
6567 	case EXIT_REASON_EXTERNAL_INTERRUPT:
6568 		return nested_exit_on_intr(vcpu);
6569 	case EXIT_REASON_TRIPLE_FAULT:
6570 		return true;
6571 	case EXIT_REASON_INTERRUPT_WINDOW:
6572 		return nested_cpu_has(vmcs12, CPU_BASED_INTR_WINDOW_EXITING);
6573 	case EXIT_REASON_NMI_WINDOW:
6574 		return nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING);
6575 	case EXIT_REASON_TASK_SWITCH:
6576 		return true;
6577 	case EXIT_REASON_CPUID:
6578 		return true;
6579 	case EXIT_REASON_HLT:
6580 		return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
6581 	case EXIT_REASON_INVD:
6582 		return true;
6583 	case EXIT_REASON_INVLPG:
6584 		return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
6585 	case EXIT_REASON_RDPMC:
6586 		return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
6587 	case EXIT_REASON_RDRAND:
6588 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
6589 	case EXIT_REASON_RDSEED:
6590 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
6591 	case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
6592 		return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
6593 	case EXIT_REASON_VMREAD:
6594 		return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
6595 			vmcs12->vmread_bitmap);
6596 	case EXIT_REASON_VMWRITE:
6597 		return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
6598 			vmcs12->vmwrite_bitmap);
6599 	case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
6600 	case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
6601 	case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
6602 	case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
6603 	case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
6604 		/*
6605 		 * VMX instructions trap unconditionally. This allows L1 to
6606 		 * emulate them for its L2 guest, i.e., allows 3-level nesting!
6607 		 */
6608 		return true;
6609 	case EXIT_REASON_CR_ACCESS:
6610 		return nested_vmx_exit_handled_cr(vcpu, vmcs12);
6611 	case EXIT_REASON_DR_ACCESS:
6612 		return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
6613 	case EXIT_REASON_IO_INSTRUCTION:
6614 		return nested_vmx_exit_handled_io(vcpu, vmcs12);
6615 	case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
6616 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
6617 	case EXIT_REASON_MSR_READ:
6618 	case EXIT_REASON_MSR_WRITE:
6619 	case EXIT_REASON_MSR_READ_IMM:
6620 	case EXIT_REASON_MSR_WRITE_IMM:
6621 		return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
6622 	case EXIT_REASON_INVALID_STATE:
6623 		return true;
6624 	case EXIT_REASON_MWAIT_INSTRUCTION:
6625 		return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
6626 	case EXIT_REASON_MONITOR_TRAP_FLAG:
6627 		return nested_vmx_exit_handled_mtf(vmcs12);
6628 	case EXIT_REASON_MONITOR_INSTRUCTION:
6629 		return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
6630 	case EXIT_REASON_PAUSE_INSTRUCTION:
6631 		return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
6632 			nested_cpu_has2(vmcs12,
6633 				SECONDARY_EXEC_PAUSE_LOOP_EXITING);
6634 	case EXIT_REASON_MCE_DURING_VMENTRY:
6635 		return true;
6636 	case EXIT_REASON_TPR_BELOW_THRESHOLD:
6637 		return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
6638 	case EXIT_REASON_APIC_ACCESS:
6639 	case EXIT_REASON_APIC_WRITE:
6640 	case EXIT_REASON_EOI_INDUCED:
6641 		/*
6642 		 * The controls for "virtualize APIC accesses," "APIC-
6643 		 * register virtualization," and "virtual-interrupt
6644 		 * delivery" only come from vmcs12.
6645 		 */
6646 		return true;
6647 	case EXIT_REASON_INVPCID:
6648 		return
6649 			nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
6650 			nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
6651 	case EXIT_REASON_WBINVD:
6652 		return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
6653 	case EXIT_REASON_XSETBV:
6654 		return true;
6655 	case EXIT_REASON_XSAVES:
6656 	case EXIT_REASON_XRSTORS:
6657 		/*
6658 		 * Always forward XSAVES/XRSTORS to L1 as KVM doesn't utilize
6659 		 * XSS-bitmap, and always loads vmcs02 with vmcs12's XSS-bitmap
6660 		 * verbatim, i.e. any exit is due to L1's bitmap.  WARN if
6661 		 * XSAVES isn't enabled, as the CPU is supposed to inject #UD
6662 		 * in that case, before consulting the XSS-bitmap.
6663 		 */
6664 		WARN_ON_ONCE(!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_XSAVES));
6665 		return true;
6666 	case EXIT_REASON_UMWAIT:
6667 	case EXIT_REASON_TPAUSE:
6668 		return nested_cpu_has2(vmcs12,
6669 			SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE);
6670 	case EXIT_REASON_ENCLS:
6671 		return nested_vmx_exit_handled_encls(vcpu, vmcs12);
6672 	case EXIT_REASON_NOTIFY:
6673 		/* Notify VM exit is not exposed to L1 */
6674 		return false;
6675 	case EXIT_REASON_SEAMCALL:
6676 	case EXIT_REASON_TDCALL:
6677 		/*
6678 		 * SEAMCALL and TDCALL unconditionally VM-Exit, but aren't
6679 		 * virtualized by KVM for L1 hypervisors, i.e. L1 should
6680 		 * never want or expect such an exit.
6681 		 */
6682 		return false;
6683 	default:
6684 		return true;
6685 	}
6686 }
6687 
6688 /*
6689  * Conditionally reflect a VM-Exit into L1.  Returns %true if the VM-Exit was
6690  * reflected into L1.
6691  */
6692 bool nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu)
6693 {
6694 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6695 	union vmx_exit_reason exit_reason = vmx->vt.exit_reason;
6696 	unsigned long exit_qual;
6697 	u32 exit_intr_info;
6698 
6699 	kvm_warn_on_nested_run_pending(vcpu);
6700 
6701 	/*
6702 	 * Late nested VM-Fail shares the same flow as nested VM-Exit since KVM
6703 	 * has already loaded L2's state.
6704 	 */
6705 	if (unlikely(vmx->fail)) {
6706 		trace_kvm_nested_vmenter_failed(
6707 			"hardware VM-instruction error: ",
6708 			vmcs_read32(VM_INSTRUCTION_ERROR));
6709 		exit_intr_info = 0;
6710 		exit_qual = 0;
6711 		goto reflect_vmexit;
6712 	}
6713 
6714 	trace_kvm_nested_vmexit(vcpu, KVM_ISA_VMX);
6715 
6716 	/* If L0 (KVM) wants the exit, it trumps L1's desires. */
6717 	if (nested_vmx_l0_wants_exit(vcpu, exit_reason))
6718 		return false;
6719 
6720 	/* If L1 doesn't want the exit, handle it in L0. */
6721 	if (!nested_vmx_l1_wants_exit(vcpu, exit_reason))
6722 		return false;
6723 
6724 	/*
6725 	 * vmcs.VM_EXIT_INTR_INFO is only valid for EXCEPTION_NMI exits.  For
6726 	 * EXTERNAL_INTERRUPT, the value for vmcs12->vm_exit_intr_info would
6727 	 * need to be synthesized by querying the in-kernel LAPIC, but external
6728 	 * interrupts are never reflected to L1 so it's a non-issue.
6729 	 */
6730 	exit_intr_info = vmx_get_intr_info(vcpu);
6731 	if (is_exception_with_error_code(exit_intr_info)) {
6732 		struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6733 
6734 		vmcs12->vm_exit_intr_error_code =
6735 			vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6736 	}
6737 	exit_qual = vmx_get_exit_qual(vcpu);
6738 
6739 reflect_vmexit:
6740 	nested_vmx_vmexit(vcpu, exit_reason.full, exit_intr_info, exit_qual);
6741 	return true;
6742 }
6743 
6744 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
6745 				struct kvm_nested_state __user *user_kvm_nested_state,
6746 				u32 user_data_size)
6747 {
6748 	struct vcpu_vmx *vmx;
6749 	struct vmcs12 *vmcs12;
6750 	struct kvm_nested_state kvm_state = {
6751 		.flags = 0,
6752 		.format = KVM_STATE_NESTED_FORMAT_VMX,
6753 		.size = sizeof(kvm_state),
6754 		.hdr.vmx.flags = 0,
6755 		.hdr.vmx.vmxon_pa = INVALID_GPA,
6756 		.hdr.vmx.vmcs12_pa = INVALID_GPA,
6757 		.hdr.vmx.preemption_timer_deadline = 0,
6758 	};
6759 	struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
6760 		&user_kvm_nested_state->data.vmx[0];
6761 
6762 	if (!vcpu)
6763 		return kvm_state.size + sizeof(*user_vmx_nested_state);
6764 
6765 	vmx = to_vmx(vcpu);
6766 	vmcs12 = get_vmcs12(vcpu);
6767 
6768 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_VMX) &&
6769 	    (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
6770 		kvm_state.hdr.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
6771 		kvm_state.hdr.vmx.vmcs12_pa = vmx->nested.current_vmptr;
6772 
6773 		if (vmx_has_valid_vmcs12(vcpu)) {
6774 			kvm_state.size += sizeof(user_vmx_nested_state->vmcs12);
6775 
6776 			/* 'hv_evmcs_vmptr' can also be EVMPTR_MAP_PENDING here */
6777 			if (nested_vmx_is_evmptr12_set(vmx))
6778 				kvm_state.flags |= KVM_STATE_NESTED_EVMCS;
6779 
6780 			if (is_guest_mode(vcpu) &&
6781 			    nested_cpu_has_shadow_vmcs(vmcs12) &&
6782 			    vmcs12->vmcs_link_pointer != INVALID_GPA)
6783 				kvm_state.size += sizeof(user_vmx_nested_state->shadow_vmcs12);
6784 		}
6785 
6786 		if (vmx->nested.smm.vmxon)
6787 			kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
6788 
6789 		if (vmx->nested.smm.guest_mode)
6790 			kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
6791 
6792 		if (is_guest_mode(vcpu)) {
6793 			kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
6794 
6795 			if (vcpu->arch.nested_run_pending)
6796 				kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
6797 
6798 			if (vmx->nested.mtf_pending)
6799 				kvm_state.flags |= KVM_STATE_NESTED_MTF_PENDING;
6800 
6801 			if (nested_cpu_has_preemption_timer(vmcs12) &&
6802 			    vmx->nested.has_preemption_timer_deadline) {
6803 				kvm_state.hdr.vmx.flags |=
6804 					KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE;
6805 				kvm_state.hdr.vmx.preemption_timer_deadline =
6806 					vmx->nested.preemption_timer_deadline;
6807 			}
6808 		}
6809 	}
6810 
6811 	if (user_data_size < kvm_state.size)
6812 		goto out;
6813 
6814 	if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
6815 		return -EFAULT;
6816 
6817 	if (!vmx_has_valid_vmcs12(vcpu))
6818 		goto out;
6819 
6820 	/*
6821 	 * When running L2, the authoritative vmcs12 state is in the
6822 	 * vmcs02. When running L1, the authoritative vmcs12 state is
6823 	 * in the shadow or enlightened vmcs linked to vmcs01, unless
6824 	 * need_vmcs12_to_shadow_sync is set, in which case, the authoritative
6825 	 * vmcs12 state is in the vmcs12 already.
6826 	 */
6827 	if (is_guest_mode(vcpu)) {
6828 		sync_vmcs02_to_vmcs12(vcpu, vmcs12);
6829 		sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
6830 	} else  {
6831 		copy_vmcs02_to_vmcs12_rare(vcpu, get_vmcs12(vcpu));
6832 		if (!vmx->nested.need_vmcs12_to_shadow_sync) {
6833 			if (nested_vmx_is_evmptr12_valid(vmx))
6834 				/*
6835 				 * L1 hypervisor is not obliged to keep eVMCS
6836 				 * clean fields data always up-to-date while
6837 				 * not in guest mode, 'hv_clean_fields' is only
6838 				 * supposed to be actual upon vmentry so we need
6839 				 * to ignore it here and do full copy.
6840 				 */
6841 				copy_enlightened_to_vmcs12(vmx, 0);
6842 			else if (enable_shadow_vmcs)
6843 				copy_shadow_to_vmcs12(vmx);
6844 		}
6845 	}
6846 
6847 	BUILD_BUG_ON(sizeof(user_vmx_nested_state->vmcs12) < VMCS12_SIZE);
6848 	BUILD_BUG_ON(sizeof(user_vmx_nested_state->shadow_vmcs12) < VMCS12_SIZE);
6849 
6850 	/*
6851 	 * Copy over the full allocated size of vmcs12 rather than just the size
6852 	 * of the struct.
6853 	 */
6854 	if (copy_to_user(user_vmx_nested_state->vmcs12, vmcs12, VMCS12_SIZE))
6855 		return -EFAULT;
6856 
6857 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
6858 	    vmcs12->vmcs_link_pointer != INVALID_GPA) {
6859 		if (copy_to_user(user_vmx_nested_state->shadow_vmcs12,
6860 				 get_shadow_vmcs12(vcpu), VMCS12_SIZE))
6861 			return -EFAULT;
6862 	}
6863 out:
6864 	return kvm_state.size;
6865 }
6866 
6867 void vmx_leave_nested(struct kvm_vcpu *vcpu)
6868 {
6869 	if (is_guest_mode(vcpu)) {
6870 		vcpu->arch.nested_run_pending = 0;
6871 		nested_vmx_vmexit(vcpu, -1, 0, 0);
6872 	}
6873 	free_nested(vcpu);
6874 }
6875 
6876 int nested_vmx_check_restored_vmcs12(struct kvm_vcpu *vcpu)
6877 {
6878 	enum vm_entry_failure_code ignored;
6879 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6880 
6881 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
6882 	    vmcs12->vmcs_link_pointer != INVALID_GPA) {
6883 		struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
6884 
6885 		if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
6886 		    !shadow_vmcs12->hdr.shadow_vmcs)
6887 			return -EINVAL;
6888 	}
6889 
6890 	if (nested_vmx_check_controls(vcpu, vmcs12) ||
6891 	    nested_vmx_check_host_state(vcpu, vmcs12) ||
6892 	    nested_vmx_check_guest_state(vcpu, vmcs12, &ignored))
6893 		return -EINVAL;
6894 
6895 	return 0;
6896 }
6897 
6898 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
6899 				struct kvm_nested_state __user *user_kvm_nested_state,
6900 				struct kvm_nested_state *kvm_state)
6901 {
6902 	struct vcpu_vmx *vmx = to_vmx(vcpu);
6903 	struct vmcs12 *vmcs12;
6904 	struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
6905 		&user_kvm_nested_state->data.vmx[0];
6906 	int ret;
6907 
6908 	if (kvm_state->format != KVM_STATE_NESTED_FORMAT_VMX)
6909 		return -EINVAL;
6910 
6911 	if (kvm_state->hdr.vmx.vmxon_pa == INVALID_GPA) {
6912 		if (kvm_state->hdr.vmx.smm.flags)
6913 			return -EINVAL;
6914 
6915 		if (kvm_state->hdr.vmx.vmcs12_pa != INVALID_GPA)
6916 			return -EINVAL;
6917 
6918 		/*
6919 		 * KVM_STATE_NESTED_EVMCS used to signal that KVM should
6920 		 * enable eVMCS capability on vCPU. However, since then
6921 		 * code was changed such that flag signals vmcs12 should
6922 		 * be copied into eVMCS in guest memory.
6923 		 *
6924 		 * To preserve backwards compatibility, allow user
6925 		 * to set this flag even when there is no VMXON region.
6926 		 */
6927 		if (kvm_state->flags & ~KVM_STATE_NESTED_EVMCS)
6928 			return -EINVAL;
6929 	} else {
6930 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_VMX))
6931 			return -EINVAL;
6932 
6933 		if (!page_address_valid(vcpu, kvm_state->hdr.vmx.vmxon_pa))
6934 			return -EINVAL;
6935 	}
6936 
6937 	if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6938 	    (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
6939 		return -EINVAL;
6940 
6941 	if (kvm_state->hdr.vmx.smm.flags &
6942 	    ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
6943 		return -EINVAL;
6944 
6945 	if (kvm_state->hdr.vmx.flags & ~KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE)
6946 		return -EINVAL;
6947 
6948 	/*
6949 	 * SMM temporarily disables VMX, so we cannot be in guest mode,
6950 	 * nor can VMLAUNCH/VMRESUME be pending.  Outside SMM, SMM flags
6951 	 * must be zero.
6952 	 */
6953 	if (is_smm(vcpu) ?
6954 		(kvm_state->flags &
6955 		 (KVM_STATE_NESTED_GUEST_MODE | KVM_STATE_NESTED_RUN_PENDING))
6956 		: kvm_state->hdr.vmx.smm.flags)
6957 		return -EINVAL;
6958 
6959 	if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6960 	    !(kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
6961 		return -EINVAL;
6962 
6963 	if ((kvm_state->flags & KVM_STATE_NESTED_EVMCS) &&
6964 	    (!guest_cpu_cap_has(vcpu, X86_FEATURE_VMX) ||
6965 	     !vmx->nested.enlightened_vmcs_enabled))
6966 			return -EINVAL;
6967 
6968 	vmx_leave_nested(vcpu);
6969 
6970 	if (kvm_state->hdr.vmx.vmxon_pa == INVALID_GPA)
6971 		return 0;
6972 
6973 	vmx->nested.vmxon_ptr = kvm_state->hdr.vmx.vmxon_pa;
6974 	ret = enter_vmx_operation(vcpu);
6975 	if (ret)
6976 		return ret;
6977 
6978 	/* Empty 'VMXON' state is permitted if no VMCS loaded */
6979 	if (kvm_state->size < sizeof(*kvm_state) + sizeof(*vmcs12)) {
6980 		/* See vmx_has_valid_vmcs12.  */
6981 		if ((kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE) ||
6982 		    (kvm_state->flags & KVM_STATE_NESTED_EVMCS) ||
6983 		    (kvm_state->hdr.vmx.vmcs12_pa != INVALID_GPA))
6984 			return -EINVAL;
6985 		else
6986 			return 0;
6987 	}
6988 
6989 	if (kvm_state->hdr.vmx.vmcs12_pa != INVALID_GPA) {
6990 		if (kvm_state->hdr.vmx.vmcs12_pa == kvm_state->hdr.vmx.vmxon_pa ||
6991 		    !page_address_valid(vcpu, kvm_state->hdr.vmx.vmcs12_pa))
6992 			return -EINVAL;
6993 
6994 		set_current_vmptr(vmx, kvm_state->hdr.vmx.vmcs12_pa);
6995 #ifdef CONFIG_KVM_HYPERV
6996 	} else if (kvm_state->flags & KVM_STATE_NESTED_EVMCS) {
6997 		/*
6998 		 * nested_vmx_handle_enlightened_vmptrld() cannot be called
6999 		 * directly from here as HV_X64_MSR_VP_ASSIST_PAGE may not be
7000 		 * restored yet. EVMCS will be mapped from
7001 		 * nested_get_vmcs12_pages().
7002 		 */
7003 		vmx->nested.hv_evmcs_vmptr = EVMPTR_MAP_PENDING;
7004 		kvm_make_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
7005 #endif
7006 	} else {
7007 		return -EINVAL;
7008 	}
7009 
7010 	if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
7011 		vmx->nested.smm.vmxon = true;
7012 		vmx->nested.vmxon = false;
7013 
7014 		if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
7015 			vmx->nested.smm.guest_mode = true;
7016 	}
7017 
7018 	vmcs12 = get_vmcs12(vcpu);
7019 	if (copy_from_user(vmcs12, user_vmx_nested_state->vmcs12, sizeof(*vmcs12)))
7020 		return -EFAULT;
7021 
7022 	if (vmcs12->hdr.revision_id != VMCS12_REVISION)
7023 		return -EINVAL;
7024 
7025 	if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
7026 		return 0;
7027 
7028 	if (kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING)
7029 		vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING_UNTRUSTED;
7030 	else
7031 		vcpu->arch.nested_run_pending = 0;
7032 
7033 	vmx->nested.mtf_pending =
7034 		!!(kvm_state->flags & KVM_STATE_NESTED_MTF_PENDING);
7035 
7036 	if (nested_cpu_has_shadow_vmcs(vmcs12) &&
7037 	    vmcs12->vmcs_link_pointer != INVALID_GPA) {
7038 		struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
7039 
7040 		ret = -EINVAL;
7041 		if (kvm_state->size <
7042 		    sizeof(*kvm_state) +
7043 		    sizeof(user_vmx_nested_state->vmcs12) + sizeof(*shadow_vmcs12))
7044 			goto error_guest_mode;
7045 
7046 		ret = -EFAULT;
7047 		if (copy_from_user(shadow_vmcs12,
7048 				   user_vmx_nested_state->shadow_vmcs12,
7049 				   sizeof(*shadow_vmcs12)))
7050 			goto error_guest_mode;
7051 	}
7052 
7053 	vmx->nested.has_preemption_timer_deadline = false;
7054 	if (kvm_state->hdr.vmx.flags & KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE) {
7055 		vmx->nested.has_preemption_timer_deadline = true;
7056 		vmx->nested.preemption_timer_deadline =
7057 			kvm_state->hdr.vmx.preemption_timer_deadline;
7058 	}
7059 
7060 	ret = nested_vmx_check_restored_vmcs12(vcpu);
7061 	if (ret < 0)
7062 		goto error_guest_mode;
7063 
7064 	vmx->nested.dirty_vmcs12 = true;
7065 	vmx->nested.force_msr_bitmap_recalc = true;
7066 	ret = nested_vmx_enter_non_root_mode(vcpu, false);
7067 	if (ret)
7068 		goto error_guest_mode;
7069 
7070 	if (vmx->nested.mtf_pending)
7071 		kvm_make_request(KVM_REQ_EVENT, vcpu);
7072 
7073 	return 0;
7074 
7075 error_guest_mode:
7076 	vcpu->arch.nested_run_pending = 0;
7077 	return ret;
7078 }
7079 
7080 void nested_vmx_set_vmcs_shadowing_bitmap(void)
7081 {
7082 	if (enable_shadow_vmcs) {
7083 		vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
7084 		vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
7085 	}
7086 }
7087 
7088 static u64 nested_vmx_calc_vmcs_enum_msr(void)
7089 {
7090 	/*
7091 	 * Note these are the so called "index" of the VMCS field encoding, not
7092 	 * the index into vmcs12.
7093 	 */
7094 	unsigned int max_idx, idx;
7095 	int i;
7096 
7097 	/*
7098 	 * For better or worse, KVM allows VMREAD/VMWRITE to all fields in
7099 	 * vmcs12, regardless of whether or not the associated feature is
7100 	 * exposed to L1.  Simply find the field with the highest index.
7101 	 */
7102 	max_idx = 0;
7103 	for (i = 0; i < nr_vmcs12_fields; i++) {
7104 		/* The vmcs12 table is very, very sparsely populated. */
7105 		if (!vmcs12_field_offsets[i])
7106 			continue;
7107 
7108 		idx = vmcs_field_index(VMCS12_IDX_TO_ENC(i));
7109 		if (idx > max_idx)
7110 			max_idx = idx;
7111 	}
7112 
7113 	return (u64)max_idx << VMCS_FIELD_INDEX_SHIFT;
7114 }
7115 
7116 static void nested_vmx_setup_pinbased_ctls(struct vmcs_config *vmcs_conf,
7117 					   struct nested_vmx_msrs *msrs)
7118 {
7119 	msrs->pinbased_ctls_low =
7120 		PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
7121 
7122 	msrs->pinbased_ctls_high = vmcs_conf->pin_based_exec_ctrl;
7123 	msrs->pinbased_ctls_high &=
7124 		PIN_BASED_EXT_INTR_MASK |
7125 		PIN_BASED_NMI_EXITING |
7126 		PIN_BASED_VIRTUAL_NMIS |
7127 		(enable_apicv ? PIN_BASED_POSTED_INTR : 0);
7128 	msrs->pinbased_ctls_high |=
7129 		PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
7130 		PIN_BASED_VMX_PREEMPTION_TIMER;
7131 }
7132 
7133 static void nested_vmx_setup_exit_ctls(struct vmcs_config *vmcs_conf,
7134 				       struct nested_vmx_msrs *msrs)
7135 {
7136 	msrs->exit_ctls_low =
7137 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
7138 
7139 	msrs->exit_ctls_high = vmcs_conf->vmexit_ctrl;
7140 	msrs->exit_ctls_high &=
7141 #ifdef CONFIG_X86_64
7142 		VM_EXIT_HOST_ADDR_SPACE_SIZE |
7143 #endif
7144 		VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT |
7145 		VM_EXIT_CLEAR_BNDCFGS | VM_EXIT_LOAD_CET_STATE;
7146 	msrs->exit_ctls_high |=
7147 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
7148 		VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
7149 		VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT |
7150 		VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
7151 
7152 	if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
7153 	    !kvm_cpu_cap_has(X86_FEATURE_IBT))
7154 		msrs->exit_ctls_high &= ~VM_EXIT_LOAD_CET_STATE;
7155 
7156 	/* We support free control of debug control saving. */
7157 	msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
7158 }
7159 
7160 static void nested_vmx_setup_entry_ctls(struct vmcs_config *vmcs_conf,
7161 					struct nested_vmx_msrs *msrs)
7162 {
7163 	msrs->entry_ctls_low =
7164 		VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
7165 
7166 	msrs->entry_ctls_high = vmcs_conf->vmentry_ctrl;
7167 	msrs->entry_ctls_high &=
7168 #ifdef CONFIG_X86_64
7169 		VM_ENTRY_IA32E_MODE |
7170 #endif
7171 		VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS |
7172 		VM_ENTRY_LOAD_CET_STATE;
7173 	msrs->entry_ctls_high |=
7174 		(VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER |
7175 		 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL);
7176 
7177 	if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
7178 	    !kvm_cpu_cap_has(X86_FEATURE_IBT))
7179 		msrs->entry_ctls_high &= ~VM_ENTRY_LOAD_CET_STATE;
7180 
7181 	/* We support free control of debug control loading. */
7182 	msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
7183 }
7184 
7185 static void nested_vmx_setup_cpubased_ctls(struct vmcs_config *vmcs_conf,
7186 					   struct nested_vmx_msrs *msrs)
7187 {
7188 	msrs->procbased_ctls_low =
7189 		CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
7190 
7191 	msrs->procbased_ctls_high = vmcs_conf->cpu_based_exec_ctrl;
7192 	msrs->procbased_ctls_high &=
7193 		CPU_BASED_INTR_WINDOW_EXITING |
7194 		CPU_BASED_NMI_WINDOW_EXITING | CPU_BASED_USE_TSC_OFFSETTING |
7195 		CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
7196 		CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
7197 		CPU_BASED_CR3_STORE_EXITING |
7198 #ifdef CONFIG_X86_64
7199 		CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
7200 #endif
7201 		CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
7202 		CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
7203 		CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
7204 		CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
7205 		CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
7206 	/*
7207 	 * We can allow some features even when not supported by the
7208 	 * hardware. For example, L1 can specify an MSR bitmap - and we
7209 	 * can use it to avoid exits to L1 - even when L0 runs L2
7210 	 * without MSR bitmaps.
7211 	 */
7212 	msrs->procbased_ctls_high |=
7213 		CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
7214 		CPU_BASED_USE_MSR_BITMAPS;
7215 
7216 	/* We support free control of CR3 access interception. */
7217 	msrs->procbased_ctls_low &=
7218 		~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
7219 }
7220 
7221 static void nested_vmx_setup_secondary_ctls(u32 ept_caps,
7222 					    struct vmcs_config *vmcs_conf,
7223 					    struct nested_vmx_msrs *msrs)
7224 {
7225 	msrs->secondary_ctls_low = 0;
7226 
7227 	msrs->secondary_ctls_high = vmcs_conf->cpu_based_2nd_exec_ctrl;
7228 	msrs->secondary_ctls_high &=
7229 		SECONDARY_EXEC_DESC |
7230 		SECONDARY_EXEC_ENABLE_RDTSCP |
7231 		SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7232 		SECONDARY_EXEC_WBINVD_EXITING |
7233 		SECONDARY_EXEC_APIC_REGISTER_VIRT |
7234 		SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
7235 		SECONDARY_EXEC_RDRAND_EXITING |
7236 		SECONDARY_EXEC_ENABLE_INVPCID |
7237 		SECONDARY_EXEC_ENABLE_VMFUNC |
7238 		SECONDARY_EXEC_RDSEED_EXITING |
7239 		SECONDARY_EXEC_ENABLE_XSAVES |
7240 		SECONDARY_EXEC_TSC_SCALING |
7241 		SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
7242 
7243 	/*
7244 	 * We can emulate "VMCS shadowing," even if the hardware
7245 	 * doesn't support it.
7246 	 */
7247 	msrs->secondary_ctls_high |=
7248 		SECONDARY_EXEC_SHADOW_VMCS;
7249 
7250 	if (enable_ept) {
7251 		/* nested EPT: emulate EPT also to L1 */
7252 		msrs->secondary_ctls_high |=
7253 			SECONDARY_EXEC_ENABLE_EPT;
7254 		msrs->ept_caps =
7255 			VMX_EPT_PAGE_WALK_4_BIT |
7256 			VMX_EPT_PAGE_WALK_5_BIT |
7257 			VMX_EPTP_WB_BIT |
7258 			VMX_EPT_INVEPT_BIT |
7259 			VMX_EPT_EXECUTE_ONLY_BIT |
7260 			VMX_EPT_ADVANCED_VMEXIT_INFO_BIT;
7261 
7262 		msrs->ept_caps &= ept_caps;
7263 		msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
7264 			VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
7265 			VMX_EPT_1GB_PAGE_BIT;
7266 		if (enable_ept_ad_bits) {
7267 			msrs->secondary_ctls_high |=
7268 				SECONDARY_EXEC_ENABLE_PML;
7269 			msrs->ept_caps |= VMX_EPT_AD_BIT;
7270 		}
7271 
7272 		if (enable_mbec)
7273 			msrs->secondary_ctls_high |=
7274 				SECONDARY_EXEC_MODE_BASED_EPT_EXEC;
7275 		/*
7276 		 * Advertise EPTP switching irrespective of hardware support,
7277 		 * KVM emulates it in software so long as VMFUNC is supported.
7278 		 */
7279 		if (cpu_has_vmx_vmfunc())
7280 			msrs->vmfunc_controls = VMX_VMFUNC_EPTP_SWITCHING;
7281 	}
7282 
7283 	/*
7284 	 * Old versions of KVM use the single-context version without
7285 	 * checking for support, so declare that it is supported even
7286 	 * though it is treated as global context.  The alternative is
7287 	 * not failing the single-context invvpid, and it is worse.
7288 	 */
7289 	if (enable_vpid) {
7290 		msrs->secondary_ctls_high |=
7291 			SECONDARY_EXEC_ENABLE_VPID;
7292 		msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
7293 			VMX_VPID_EXTENT_SUPPORTED_MASK;
7294 	}
7295 
7296 	if (enable_unrestricted_guest)
7297 		msrs->secondary_ctls_high |=
7298 			SECONDARY_EXEC_UNRESTRICTED_GUEST;
7299 
7300 	if (flexpriority_enabled)
7301 		msrs->secondary_ctls_high |=
7302 			SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7303 
7304 	if (enable_sgx)
7305 		msrs->secondary_ctls_high |= SECONDARY_EXEC_ENCLS_EXITING;
7306 }
7307 
7308 static void nested_vmx_setup_misc_data(struct vmcs_config *vmcs_conf,
7309 				       struct nested_vmx_msrs *msrs)
7310 {
7311 	msrs->misc_low = (u32)vmcs_conf->misc & VMX_MISC_SAVE_EFER_LMA;
7312 	msrs->misc_low |=
7313 		VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
7314 		VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
7315 		VMX_MISC_ACTIVITY_HLT |
7316 		VMX_MISC_ACTIVITY_WAIT_SIPI;
7317 	msrs->misc_high = 0;
7318 }
7319 
7320 static void nested_vmx_setup_basic(struct nested_vmx_msrs *msrs)
7321 {
7322 	/*
7323 	 * This MSR reports some information about VMX support. We
7324 	 * should return information about the VMX we emulate for the
7325 	 * guest, and the VMCS structure we give it - not about the
7326 	 * VMX support of the underlying hardware.
7327 	 */
7328 	msrs->basic = vmx_basic_encode_vmcs_info(VMCS12_REVISION, VMCS12_SIZE,
7329 						 X86_MEMTYPE_WB);
7330 
7331 	msrs->basic |= VMX_BASIC_TRUE_CTLS;
7332 	if (cpu_has_vmx_basic_inout())
7333 		msrs->basic |= VMX_BASIC_INOUT;
7334 	if (cpu_has_vmx_basic_no_hw_errcode_cc())
7335 		msrs->basic |= VMX_BASIC_NO_HW_ERROR_CODE_CC;
7336 }
7337 
7338 static void nested_vmx_setup_cr_fixed(struct nested_vmx_msrs *msrs)
7339 {
7340 	/*
7341 	 * These MSRs specify bits which the guest must keep fixed on
7342 	 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
7343 	 * We picked the standard core2 setting.
7344 	 */
7345 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
7346 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
7347 	msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
7348 	msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
7349 
7350 	/* These MSRs specify bits which the guest must keep fixed off. */
7351 	rdmsrq(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
7352 	rdmsrq(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
7353 
7354 	if (vmx_umip_emulated())
7355 		msrs->cr4_fixed1 |= X86_CR4_UMIP;
7356 }
7357 
7358 /*
7359  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
7360  * returned for the various VMX controls MSRs when nested VMX is enabled.
7361  * The same values should also be used to verify that vmcs12 control fields are
7362  * valid during nested entry from L1 to L2.
7363  * Each of these control msrs has a low and high 32-bit half: A low bit is on
7364  * if the corresponding bit in the (32-bit) control field *must* be on, and a
7365  * bit in the high half is on if the corresponding bit in the control field
7366  * may be on. See also vmx_control_verify().
7367  */
7368 void nested_vmx_setup_ctls_msrs(struct vmcs_config *vmcs_conf, u32 ept_caps)
7369 {
7370 	struct nested_vmx_msrs *msrs = &vmcs_conf->nested;
7371 
7372 	/*
7373 	 * Note that as a general rule, the high half of the MSRs (bits in
7374 	 * the control fields which may be 1) should be initialized by the
7375 	 * intersection of the underlying hardware's MSR (i.e., features which
7376 	 * can be supported) and the list of features we want to expose -
7377 	 * because they are known to be properly supported in our code.
7378 	 * Also, usually, the low half of the MSRs (bits which must be 1) can
7379 	 * be set to 0, meaning that L1 may turn off any of these bits. The
7380 	 * reason is that if one of these bits is necessary, it will appear
7381 	 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
7382 	 * fields of vmcs01 and vmcs02, will turn these bits off - and
7383 	 * nested_vmx_l1_wants_exit() will not pass related exits to L1.
7384 	 * These rules have exceptions below.
7385 	 */
7386 	nested_vmx_setup_pinbased_ctls(vmcs_conf, msrs);
7387 
7388 	nested_vmx_setup_exit_ctls(vmcs_conf, msrs);
7389 
7390 	nested_vmx_setup_entry_ctls(vmcs_conf, msrs);
7391 
7392 	nested_vmx_setup_cpubased_ctls(vmcs_conf, msrs);
7393 
7394 	nested_vmx_setup_secondary_ctls(ept_caps, vmcs_conf, msrs);
7395 
7396 	nested_vmx_setup_misc_data(vmcs_conf, msrs);
7397 
7398 	nested_vmx_setup_basic(msrs);
7399 
7400 	nested_vmx_setup_cr_fixed(msrs);
7401 
7402 	msrs->vmcs_enum = nested_vmx_calc_vmcs_enum_msr();
7403 }
7404 
7405 void nested_vmx_hardware_unsetup(void)
7406 {
7407 	int i;
7408 
7409 	if (enable_shadow_vmcs) {
7410 		for (i = 0; i < VMX_BITMAP_NR; i++)
7411 			free_page((unsigned long)vmx_bitmap[i]);
7412 	}
7413 }
7414 
7415 __init int nested_vmx_hardware_setup(int (*exit_handlers[])(struct kvm_vcpu *))
7416 {
7417 	int i;
7418 
7419 	/*
7420 	 * Note!  The set of supported vmcs12 fields is consumed by both VMX
7421 	 * MSR and shadow VMCS setup.
7422 	 */
7423 	nested_vmx_setup_vmcs12_fields();
7424 
7425 	nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
7426 
7427 	if (!cpu_has_vmx_shadow_vmcs())
7428 		enable_shadow_vmcs = 0;
7429 	if (enable_shadow_vmcs) {
7430 		for (i = 0; i < VMX_BITMAP_NR; i++) {
7431 			/*
7432 			 * The vmx_bitmap is not tied to a VM and so should
7433 			 * not be charged to a memcg.
7434 			 */
7435 			vmx_bitmap[i] = (unsigned long *)
7436 				__get_free_page(GFP_KERNEL);
7437 			if (!vmx_bitmap[i]) {
7438 				nested_vmx_hardware_unsetup();
7439 				return -ENOMEM;
7440 			}
7441 		}
7442 
7443 		init_vmcs_shadow_fields();
7444 	}
7445 
7446 	exit_handlers[EXIT_REASON_VMCLEAR]	= handle_vmclear;
7447 	exit_handlers[EXIT_REASON_VMLAUNCH]	= handle_vmlaunch;
7448 	exit_handlers[EXIT_REASON_VMPTRLD]	= handle_vmptrld;
7449 	exit_handlers[EXIT_REASON_VMPTRST]	= handle_vmptrst;
7450 	exit_handlers[EXIT_REASON_VMREAD]	= handle_vmread;
7451 	exit_handlers[EXIT_REASON_VMRESUME]	= handle_vmresume;
7452 	exit_handlers[EXIT_REASON_VMWRITE]	= handle_vmwrite;
7453 	exit_handlers[EXIT_REASON_VMOFF]	= handle_vmxoff;
7454 	exit_handlers[EXIT_REASON_VMON]		= handle_vmxon;
7455 	exit_handlers[EXIT_REASON_INVEPT]	= handle_invept;
7456 	exit_handlers[EXIT_REASON_INVVPID]	= handle_invvpid;
7457 	exit_handlers[EXIT_REASON_VMFUNC]	= handle_vmfunc;
7458 
7459 	return 0;
7460 }
7461 
7462 static gpa_t vmx_translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa,
7463 				      u64 access,
7464 				      struct x86_exception *exception,
7465 				      u64 pte_access)
7466 {
7467 	struct kvm_mmu *mmu = vcpu->arch.mmu;
7468 
7469 	if (WARN_ON_ONCE(!mmu_is_nested(vcpu)))
7470 		return gpa;
7471 
7472 	/*
7473 	 * MBEC differentiates based on the effective U/S bit of
7474 	 * the guest page tables; not the processor CPL.
7475 	 */
7476 	access &= ~PFERR_USER_MASK;
7477 	if ((pte_access & ACC_USER_MASK) && (access & PFERR_GUEST_FINAL_MASK))
7478 		access |= PFERR_USER_MASK;
7479 
7480 	return mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7481 }
7482 
7483 struct kvm_x86_nested_ops vmx_nested_ops = {
7484 	.leave_nested = vmx_leave_nested,
7485 	.translate_nested_gpa = vmx_translate_nested_gpa,
7486 	.is_exception_vmexit = nested_vmx_is_exception_vmexit,
7487 	.check_events = vmx_check_nested_events,
7488 	.has_events = vmx_has_nested_events,
7489 	.triple_fault = nested_vmx_triple_fault,
7490 	.get_state = vmx_get_nested_state,
7491 	.set_state = vmx_set_nested_state,
7492 	.get_nested_state_pages = vmx_get_nested_state_pages,
7493 	.write_log_dirty = nested_vmx_write_pml_buffer,
7494 #ifdef CONFIG_KVM_HYPERV
7495 	.enable_evmcs = nested_enable_evmcs,
7496 	.get_evmcs_version = nested_get_evmcs_version,
7497 	.hv_inject_synthetic_vmexit_post_tlb_flush = vmx_hv_inject_synthetic_vmexit_post_tlb_flush,
7498 #endif
7499 };
7500