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