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