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